aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/api.js11
-rw-r--r--src/app.js1350
-rw-r--r--src/ark/manager.js551
-rw-r--r--src/ark/proto.js7
-rw-r--r--src/ark/refresh.js26
-rw-r--r--src/ark/send.js52
-rw-r--r--src/ark/store.js20
-rw-r--r--src/ark/validate.js8
-rw-r--r--src/assets/zap.mp3.base64.txt2
-rw-r--r--src/calls.js464
-rw-r--r--src/concord.js25
-rw-r--r--src/cordn-client.js6
-rw-r--r--src/dm-inbox.js27
-rw-r--r--src/features/ark.js885
-rw-r--r--src/features/gifts-wallet.js4
-rw-r--r--src/features/gifts.js235
-rw-r--r--src/features/hats.js52
-rw-r--r--src/features/messages.js4883
-rw-r--r--src/features/names.js180
-rw-r--r--src/features/nostrlogin.js234
-rw-r--r--src/features/nwc.js93
-rw-r--r--src/features/pos.js30
-rw-r--r--src/features/withdraw-links.js218
-rw-r--r--src/features/zaps.js54
-rw-r--r--src/feed-cache.js2
-rw-r--r--src/hls-player.js20
-rw-r--r--src/i18n.js373
-rw-r--r--src/image-thumbnails.js48
-rw-r--r--src/lang-guess.js10
-rw-r--r--src/live.js101
-rw-r--r--src/lnurl.js10
-rw-r--r--src/locales/ar.json30
-rw-r--r--src/locales/bn.json30
-rw-r--r--src/locales/de.json32
-rw-r--r--src/locales/es.json32
-rw-r--r--src/locales/fr.json32
-rw-r--r--src/locales/hi.json30
-rw-r--r--src/locales/id.json30
-rw-r--r--src/locales/it.json63
-rw-r--r--src/locales/ja.json32
-rw-r--r--src/locales/ko.json32
-rw-r--r--src/locales/mr.json30
-rw-r--r--src/locales/pt.json32
-rw-r--r--src/locales/ru.json32
-rw-r--r--src/locales/sw.json30
-rw-r--r--src/locales/ta.json30
-rw-r--r--src/locales/te.json30
-rw-r--r--src/locales/tr.json32
-rw-r--r--src/locales/ur.json30
-rw-r--r--src/locales/vi.json30
-rw-r--r--src/locales/zh.json32
-rw-r--r--src/marmot-client.js2
-rw-r--r--src/media-servers.js27
-rw-r--r--src/media-timeline.js152
-rw-r--r--src/media-upload.js72
-rw-r--r--src/nip29-client.js361
-rw-r--r--src/nostr-login.js75
-rw-r--r--src/nostr.js202
-rw-r--r--src/notify-text.js79
-rw-r--r--src/nwc-bg.js79
-rw-r--r--src/nwc-lock.js18
-rw-r--r--src/nwc-respond.js438
-rw-r--r--src/passkey.js6
-rw-r--r--src/pay-page.html67
-rw-r--r--src/pay-page.js190
-rw-r--r--src/public-chat.js9
-rw-r--r--src/pull-refresh.js97
-rw-r--r--src/recipient-search.js26
-rw-r--r--src/seed.js53
-rw-r--r--src/style.css487
-rw-r--r--src/sw-nwc.js263
-rw-r--r--src/video-compress.js63
-rw-r--r--src/wallet.js38
73 files changed, 11946 insertions, 1490 deletions
diff --git a/src/api.js b/src/api.js
index c0ecb4b..7f22e78 100644
--- a/src/api.js
+++ b/src/api.js
@@ -232,7 +232,7 @@ export function getBoltzWs() { const p = getBoltzProvider(); return p.ws || deri
const ARK_PRESETS_BY_NET = {
mainnet: [
{ id: 'off', label: 'Off', ark: '', esplora: '' },
- { id: 'coinos', label: 'coinos (ark.coinos.io)', ark: 'https://ark.coinos.io', esplora: 'https://mempool.space/api' },
+ { id: 'coinos', label: 'coinos (ark.coinos.io)', ark: 'https://ark.coinos.io', esplora: 'https://mempool.space/api', honorsExpired: true },
{ id: 'second', label: 'Second (ark.second.tech)', ark: 'https://ark.second.tech', esplora: 'https://mempool.second.tech/api' },
{ id: 'custom', label: 'Custom…', ark: '', esplora: '' },
],
@@ -249,12 +249,12 @@ const ARK_PRESETS_BY_NET = {
],
mutinynet: [
{ id: 'off', label: 'Off', ark: '', esplora: '' },
- { id: 'coinos', label: 'coinos (ark-staging.coinos.io)', ark: 'https://ark-staging.coinos.io', esplora: 'https://staging.coinos.io/esplora' },
+ { id: 'coinos', label: 'coinos (ark-staging.coinos.io)', ark: 'https://ark-staging.coinos.io', esplora: 'https://staging.coinos.io/esplora', honorsExpired: true },
{ id: 'custom', label: 'Custom…', ark: '', esplora: '' },
],
regtest: [
{ id: 'off', label: 'Off', ark: '', esplora: '' },
- { id: 'local', label: 'Local (regtest)', ark: 'http://localhost:3535', esplora: 'http://localhost:30002' },
+ { id: 'local', label: 'Local (regtest)', ark: 'http://localhost:3535', esplora: 'http://localhost:30002', honorsExpired: true },
{ id: 'custom', label: 'Custom…', ark: '', esplora: '' },
],
};
@@ -294,7 +294,10 @@ export function getArkConfig(net = getNetwork()) {
const id = getArkProviderId(net);
if (id === 'off') return null;
const p = arkPresets(net).find((x) => x.id === id);
- const cfg = p.id === 'custom' ? getArkCustom(net) : { ark: p.ark, esplora: p.esplora };
+ // honorsExpired: the coinos servers keep cosigning spends of a coin past
+ // its timelock (captaind allow_expired_arkoor) — the basis of the default
+ // "coinos holds my coins" custody tier. Other servers refuse such a coin.
+ const cfg = p.id === 'custom' ? getArkCustom(net) : { ark: p.ark, esplora: p.esplora, honorsExpired: !!p.honorsExpired };
return cfg.ark && cfg.esplora ? cfg : null;
}
diff --git a/src/app.js b/src/app.js
index f904cc3..fae16e0 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,3 +1,4 @@
+import { customMediaServers, saveMediaServers, resetMediaServers } from './media-servers.js';
// Bitcoin Wallet — UI controller (vanilla DOM, no framework).
//
// State lives in `ui` + the singleton `wallet`. Mutating handlers call render(),
@@ -10,15 +11,17 @@ import './rich-text.js'; // <coinos-text>, the composers' field
import { makeSearcher, resultRows, searchable, punkUrl, warmSearch } from './recipient-search.js';
import { assetUrl } from './asset-url.js';
import { npubOf, seedPubkey, neventOf, parseNostrPubkey } from './nostr.js';
+import { warmSeed, forgetSeeds } from './seed.js';
import { nip98Header } from './nip98.js';
-import { uploadPublicMedia, MediaUploadError } from './media-upload.js';
+import { uploadPublicMedia, uploadStream, mediaUploadSigner, MediaUploadError } from './media-upload.js';
import { NOSTR_MARK } from './features/nostrlogin.js';
import { scanQr } from './scan.js';
-import { dataSources, getSource, setSource, getNetwork, setNetwork, NETWORKS } from './api.js';
+import { dataSources, getSource, setSource, getNetwork, setNetwork, NETWORKS, getArkConfig } from './api.js';
import { STAGING } from './build-flags.js';
import { buildFeatures, loadDeferredFeatures } from './features/index.js';
import { cacheReady, cacheStore } from './cache-store.js';
import { t, LANGS, getLang, setLang, isRTL, loadLocale } from './i18n.js';
+import { initPullRefresh } from './pull-refresh.js';
import { rateNow, rateAt, refreshRates, haveRate, getCurrency, setCurrency, currencies, fmtFiat, fmtFiatBare } from './rates.js';
import {
fmtBtc,
@@ -74,7 +77,7 @@ const ui = {
confirmClear: false, // "Clear all" confirmation shown
editId: null, // account being renamed
editLabel: '',
- createStep: 'gen', // 'gen' | 'confirm'
+ createStep: 'intro', // 'intro' (the heads-up) | 'gen' (the words) | 'confirm' (the one-word check)
draftMnemonic: '',
confirm: [], // [{ index, value }]
confirmPass: '', // re-entered passphrase (confirm field, shown once one is typed)
@@ -364,49 +367,50 @@ function morphKeyed(parent, cur, next) {
}
const root = document.getElementById('app');
+// The footer while setting up: the language, nothing else.
+function setupFooter() {
+ const lang = languagePicker();
+ lang.style.width = 'auto'; // as wide as the language's name, not the page
+ lang.style.flex = '0 0 auto';
+ return h('div', { class: 'footer small muted center' },
+ h('div', { class: 'row gap6', style: 'justify-content:center' }, lang));
+}
+// The footer is the display preferences alone: the language this reads in,
+// and the currency amounts are shown in. Everything else that used to sit
+// here (credits, How it works, support, install, the theme, the commit) is
+// on Settings → About (Adam, 2026-11-15).
function footer() {
- return h(
- 'div',
- { class: 'footer small muted center' },
- h(
- 'div',
- {},
- t('footerMadeBy') + ' ',
- h('a', { href: 'https://adamsoltys.com', target: '_blank', rel: 'noopener' }, 'Adam Soltys'),
- h('span', { class: 'faint' }, ' · '),
- t('footerSourceOn') + ' ',
- h('a', { href: 'https://git.coinos.io/coinosv3.git/', target: '_blank', rel: 'noopener' }, 'git.coinos.io')
- ),
- h(
- 'div',
- { style: 'margin-top:4px' },
- h('button', { class: 'linklike', style: 'font-weight:400', onClick: openHowItWorks }, t('howItWorks')),
- // the hat shop: needs a wallet to pay from, so only once one is open
+ // with a wallet open they're in Settings (Adam, 2026-11-15); a visitor
+ // reading the public feed still gets them here
+ if (activeAccount()) return h('div', { class: 'footer', style: 'display:none' });
+ return h('div', { class: 'footer small muted center' },
+ h('div', { class: 'row gap6', style: 'justify-content:center' }, languagePicker(), currencyPicker()));
+}
+
+function aboutSettingsView() {
+ const row = (label, onClick, attrs = {}) => h('button', { class: 'btn-block', onClick, ...attrs }, label);
+ return h('div', { class: 'col', style: 'gap:16px' },
+ h('div', { class: 'card col about-card', style: 'gap:10px' },
+ h('h3', {}, t('aboutTitle')),
+ h('p', { class: 'small muted', style: 'margin:0' },
+ t('footerMadeBy').replace(/^./, (c) => c.toUpperCase()) + ' ',
+ h('a', { href: 'https://adamsoltys.com', target: '_blank', rel: 'noopener' }, 'Adam Soltys'),
+ '. ' + t('footerSourceOn').replace(/^./, (c) => c.toUpperCase()) + ' ',
+ h('a', { href: 'https://git.coinos.io/coinosv3.git/', target: '_blank', rel: 'noopener' }, 'git.coinos.io'), '.'),
+ row(t('howItWorks'), openHowItWorks),
+ // the hat shop pays from the wallet, so only once one is open
activeAccount() && FEATURES.some((f) => f.openHatShop)
- ? h('span', {}, h('span', { class: 'faint' }, ' · '),
- h('button', { class: 'linklike', style: 'font-weight:400', onClick: () => { clearFeatureNav(); ui.screen = 'wallet'; featureHook('openHatShop'); } }, t('footerSupport')))
- : null,
- // Chrome no longer prompts to install on its own — surface our own link
- // once it reports the app is installable. We render from a persisted flag
- // (not the live event) so the link is present on the first paint after a
- // refresh, avoiding a layout shift when beforeinstallprompt fires late.
- installable()
- ? h('span', {}, h('span', { class: 'faint' }, ' · '),
- h('button', { class: 'linklike', style: 'font-weight:400', onClick: triggerInstall }, t('installApp')))
+ ? row(t('footerSupport'), () => { clearFeatureNav(); ui.screen = 'wallet'; featureHook('openHatShop'); }, { id: 'about-support' })
: null,
- h('span', { class: 'faint' }, ' · '),
- h('button', { class: 'linklike', style: 'font-weight:400', onClick: toggleTheme }, resolvedTheme() === 'dark' ? t('lightMode') : t('darkMode'))
- ),
- // Display preferences live together: the language this reads in, and the
- // money amounts are shown in. (The currency sat under Settings → Network
- // for exactly one day, where nobody found it.)
- h('div', { class: 'row gap6', style: 'margin-top:8px;justify-content:center' }, languagePicker(), currencyPicker()),
- // The commit stamp settles "is my PWA fresh?" AND "what code is this?" in
- // one glance — its own last line, so it never wraps the credits on mobile.
- h('div', { class: 'faint', style: 'margin-top:6px' },
- 'Running git commit ',
- h('a', { class: 'faint', href: 'https://git.coinos.io/coinosv3.git/commit/?id={{COMMIT}}', target: '_blank', rel: 'noopener' }, '{{COMMIT}}'))
- );
+ // Chrome no longer prompts to install by itself: our own button, once
+ // it has said the app is installable (a persisted flag, see installable)
+ installable() ? row(t('installApp'), triggerInstall) : null,
+ row(resolvedTheme() === 'dark' ? t('lightMode') : t('darkMode'), toggleTheme, { id: 'about-theme' }),
+ // "is my PWA fresh?" and "what code is this?" in one line
+ h('div', { class: 'small faint', style: 'margin-top:2px' },
+ 'Running git commit ',
+ h('a', { class: 'faint', href: 'https://git.coinos.io/coinosv3.git/commit/?id={{COMMIT}}', target: '_blank', rel: 'noopener' }, '{{COMMIT}}'))),
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.settingsPage = null; render(); } }, t('back')));
}
const THEME_KEY = 'btc-wallet-theme';
@@ -584,10 +588,27 @@ let _publicChatMode = false;
// welcome screen is the one screen that must never be guessed at. The boot
// shell holds the frame for those few ms instead; see the dispatch below.
let _bootDeciding = true;
+// True until boot's restore has run. The feed is a public page: opened by
+// URL it paints before the wallet restores, and it painted as a visitor's
+// (no post button, chips or nav) until the restore landed a beat later —
+// synchronous work (the vault's scrypt, the wallet's state, every feature's
+// init), ~0.5 s on a laptop and more on a phone (Adam, 2026-10-31). When
+// boot can already tell a wallet is about to open (restorePending), the
+// page paints as that wallet's from its first frame.
+let _restorePending = true;
+// Boot phases for the crash-loop guard (build.js BOOT_GUARD counts page
+// 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.
+function bootPhase(p) { try { localStorage.setItem('coinos-boot-phase', p); } catch {} }
+function bootSettled() { try { localStorage.removeItem('coinos-boot'); } catch {} }
+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
// the welcome screen held back forever. Nothing legitimate is still deciding
// four seconds in — the store wait alone caps at 800ms.
-setTimeout(() => { if (_bootDeciding) { _bootDeciding = false; render(); } }, 4000);
+setTimeout(() => { _restorePending = false; if (_bootDeciding) { _bootDeciding = false; render(); } }, 4000);
// A picture, full screen. Posts show images cropped to a few hundred pixels
// so a feed stays a feed; this is where you actually look at one. Tap
// anywhere (or Escape, or Back) to close — no chrome, nothing to aim at.
@@ -630,12 +651,22 @@ function attachZoom(box, img, { wheel = true } = {}) {
const mx = Math.max(0, (img.offsetWidth * s - window.innerWidth) / 2), my = Math.max(0, (img.offsetHeight * s - window.innerHeight) / 2);
x = Math.min(mx, Math.max(-mx, x)); y = Math.min(my, Math.max(-my, y));
};
+ // Chrome keeps a will-change: transform layer rastered at 1× and scales
+ // the bitmap: zoomed in, the raster's tiles show as a faint grid of
+ // seams across the picture ("very faint grid lines", Adam, 2026-11-02).
+ // The hint is on while a gesture moves the picture (no re-raster per
+ // frame) and off once it settles zoomed, so the picture is drawn again
+ // at its real scale: sharp, and seamless.
+ let settle = 0;
const apply = (animate) => {
+ clearTimeout(settle);
img.style.transition = animate ? 'transform .2s ease' : 'none';
img.style.transform = s === 1 && !x && !y ? '' : `translate(${x}px, ${y}px) scale(${s})`;
img.style.cursor = s > 1 ? 'grab' : '';
// zoomed, the finger pans the picture; at 1× the touch is the page's (a pager's swipe)
img.style.touchAction = s > 1 ? 'none' : '';
+ img.style.willChange = 'transform';
+ settle = setTimeout(() => { img.style.willChange = s > 1 ? 'auto' : ''; }, animate ? 250 : 120);
};
// scale to ns keeping the picture point under (cx, cy) where it is
const zoomAt = (ns, cx, cy) => {
@@ -849,11 +880,24 @@ function renderInner() {
// The bottom nav rides every page of a signed-in wallet and a visitor's
// public pages — never over sign-in, onboarding or the lock prompt.
const navPage = ui.pubProf || (activeAccount() && ['wallet', 'accounts', 'accountSettings'].includes(ui.screen) && !(ui.onb || onbInProgress()));
- const bottomNav = navPage && !lockAsk && !_bootDeciding ? featureHook('bottomNav') : null;
+ // (a wallet about to restore gets its nav with the page, not after)
+ const bottomNav = navPage && !lockAsk && (!_bootDeciding || restorePending()) ? featureHook('bottomNav') : null;
if (bottomNav) bottomNav.prepend(h('div', { class: 'app-nav-wide app-nav-brand' }, brandLogo()));
- // the wallet beside the feed and chats on a wide screen (its own page needs no twin)
- const side = bottomNav && featScreen && WIDE_MQ && WIDE_MQ.matches ? walletSide() : null;
- morphChildren(root, [screen, footer(), ...(bottomNav ? [bottomNav] : []), ...(side ? [side] : []), ...(ui.lightbox ? [imageViewer()] : [])]);
+ // the wallet beside the feed and chats on a wide screen (its own page needs
+ // no twin; a wallet still restoring has no numbers to show yet)
+ const side = bottomNav && featScreen && !restorePending() && WIDE_MQ && WIDE_MQ.matches ? walletSide() : null;
+ // a call, over whatever page is up (the messages feature's)
+ const callOv = activeAccount() ? featureHook('callOverlay') : null;
+ // What a feature floats over its page (the feed's post button and
+ // new-posts pill): fixed-position nodes, so they live beside the page,
+ // not inside it — the page's entrance animation transforms it, and a
+ // transform makes fixed descendants position within the page.
+ const floaters = h('div', { class: 'page-floaters', style: 'display:contents' }, ...featureAll('pageFloaters'));
+ // The front door and every setup step keep only the language picker under
+ // them: no credits, theme toggle, currency or build stamp (Adam,
+ // 2026-11-06). Setup = the unlock screen, or a page the wizard drew (.onb).
+ const setup = ui.screen === 'unlock' || !!(screen && (screen.classList?.contains('onb') || screen.querySelector?.('.onb')));
+ morphChildren(root, [screen, floaters, setup ? setupFooter() : footer(), ...(bottomNav ? [bottomNav] : []), ...(side ? [side] : []), ...(ui.lightbox ? [imageViewer()] : []), ...(callOv ? [callOv] : [])]);
promoteLazySrc(root); // sources on the nodes that actually made it into the page
try { document.documentElement.classList.toggle('no-scroll', !!(ui.lightbox || ui.mediaPager)); } catch {}
if (fpath) {
@@ -909,7 +953,7 @@ wallet.subscribe(scheduleRender);
// lightbox: a full-screen photo is a place too — the phone's Back must close
// it, not pop the screen under it (which once walked a viewer straight back
// to the start page, so the photo's × then looked like a logout).
-const NAV_FIELDS = ['screen', 'tab', 'txDetail', 'arkMoveDetail', 'arkReconDetail', 'arkExitDetail', 'giftDetail', 'bump', 'giftMode', 'claimStep', 'chatOpen', 'msgView', 'feedId', 'pubProf', 'arkCoinsPage', 'arkExitPage', 'msgCommunity', 'msgPeer', 'profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'settingsPage', 'nameEditOpen', 'noteThread', 'userSearch', 'zapSetup', 'hatShop', 'lightbox', 'mediaPager', 'feedEdit', 'settingsView'];
+const NAV_FIELDS = ['screen', 'tab', 'txDetail', 'arkMoveDetail', 'arkReconDetail', 'arkExitDetail', 'giftDetail', 'bump', 'giftMode', 'claimStep', 'chatOpen', 'msgView', 'feedId', 'pubProf', 'arkCoinsPage', 'arkExitPage', 'msgCommunity', 'msgPeer', 'profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'settingsPage', 'nameEditOpen', 'noteThread', 'liveStream', 'goLive', 'userSearch', 'zapSetup', 'hatShop', 'lightbox', 'mediaPager', 'feedEdit', 'settingsView'];
function navSnapshot() {
const s = {};
for (const f of NAV_FIELDS) s[f] = ui[f] ?? null;
@@ -917,6 +961,7 @@ function navSnapshot() {
// results streaming in) snapshot only what IDENTIFIES the screen — a
// keystroke must never mint a history entry.
if (ui.noteThread) s.noteThread = { rootId: ui.noteThread.rootId, focusId: ui.noteThread.focusId, seed: ui.noteThread.seed };
+ if (ui.liveStream) s.liveStream = { a: ui.liveStream.a, seed: ui.liveStream.seed };
if (ui.userSearch) s.userSearch = { q: '', rows: null };
if (ui.feedEdit) s.feedEdit = { ...ui.feedEdit, q: '', rows: null, pq: '', packRows: null, pt: null };
if (ui.zapSetup) s.zapSetup = { pk: ui.zapSetup.pk, npub: ui.zapSetup.npub, eventId: ui.zapSetup.eventId, amount: '21' };
@@ -939,7 +984,7 @@ let restoringHistory = false; // true while applying a popstate (suppresses push
// copy it, send it, reload it — the same paths the deep links already open.
// Every other screen keeps whatever path it had (the till at /pos, the
// plain app at /); only a path we set ourselves is taken back to /.
-const OWN_PATH = /^\/(nevent|note|npub)1[a-z0-9]+\/?$/i;
+const OWN_PATH = /^\/((nevent|note|npub|naddr)1[a-z0-9]+|hats)\/?$/i;
function navUrl(snap) {
try {
const fp = featureHook('navPath', snap); // a feed with a public address
@@ -1104,9 +1149,16 @@ function toast(msg, ms = 1600) {
document.body.append(t);
}
t.textContent = msg;
- requestAnimationFrame(() => t.classList.add('show'));
clearTimeout(toastTimer);
- toastTimer = setTimeout(() => t.classList.remove('show'), ms);
+ // The hide timer starts when the toast shows: a hidden tab pauses
+ // requestAnimationFrame but not setTimeout, so a toast raised in the
+ // background (a zap failing after you switched apps) used to be hidden
+ // first and shown on return, then stay up for good.
+ requestAnimationFrame(() => {
+ t.classList.add('show');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => t.classList.remove('show'), ms);
+ });
}
async function copy(text) {
@@ -1196,31 +1248,48 @@ 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'];
- unit = ring[(ring.indexOf(unit) + 1) % ring.length];
+ setUnit(ring[(ring.indexOf(unit) + 1) % ring.length]);
+ render();
+}
+function setUnit(next) {
+ if (next === unit) return;
+ const was = unit;
+ unit = next;
try {
localStorage.setItem(UNIT_KEY, unit);
} catch {}
- render();
+ // 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);
+ }
}
// 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());
}
@@ -1266,19 +1335,36 @@ function unitTag(cls = '') {
// ================================================================ UNLOCK
// The create/import card on its own — the unlock screen wraps it in the
// classic chrome, the onboarding wizard's "Get started" step shows it bare.
+// The front door's seed pages (first run, or "Sign into another account"):
+// no tabs, and the page's own Back steps through the create flow.
+function seedPages() {
+ return ui.screen === 'unlock' && !!((ui.onb && ui.onb.step === 'seed') || (ui.fromWallet && ui.addFlow));
+}
+// Back within the create flow: the check → the passphrase → the words → the
+// heads-up. False when there's no earlier step (the caller leaves the flow).
+const CREATE_PREV = { gen: 'intro', pass: 'gen', confirm: 'pass' };
+function createStepBack() {
+ if (ui.unlockTab !== 'create' || ui.entropyPage || !CREATE_PREV[ui.createStep]) return false;
+ ui.createStep = CREATE_PREV[ui.createStep];
+ ui.unlockError = '';
+ render();
+ return true;
+}
+
function unlockCard() {
// The entropy page takes the card over entirely — seed words, tabs and
// other controls step aside until Submit or Back.
if (ui.entropyPage) return h('div', { class: 'card col' }, entropyPage());
// Inside the first-run wizard the words are already on screen: no tabs,
// just a line underneath for whoever brought their own seed (and one back).
- const wizard = ui.screen === 'unlock' && ui.onb && ui.onb.step === 'seed';
- const swap = wizard ? h('button', {
+ const wizard = seedPages();
+ // only before the words are up: once they're shown, it was already offered
+ const swap = wizard && (ui.unlockTab === 'import' || ui.createStep === 'intro') ? h('button', {
class: 'linklike small', style: 'align-self:center',
onClick: () => {
clearSeedDrafts(); ui.unlockError = '';
if (ui.unlockTab === 'create') ui.unlockTab = 'import';
- else { ui.unlockTab = 'create'; ui.createStep = 'gen'; ui.draftRandom = ui.draftMnemonic = newMnemonic(); }
+ else { ui.unlockTab = 'create'; ui.createStep = 'intro'; ui.draftRandom = ui.draftMnemonic = newMnemonic(); }
render();
},
}, ui.unlockTab === 'create' ? t('onbHaveSeed') : t('onbCreateInstead')) : null;
@@ -1297,7 +1383,77 @@ function unlockCard() {
);
}
+// "Sign in to another account", laid out as the front door is (Adam,
+// 2026-11-07): two choices, then the sign-in list with the seed phrase
+// first. Everything here adds an account beside the open ones; Back returns
+// to the wallet.
+function addAccountScreen() {
+ const page = (kids) => h('div', { class: 'col onb', style: 'gap:20px' }, ...kids);
+ const title = (txt) => h('h2', { class: 'onb-title' }, txt);
+ const toWallet = () => {
+ ui.fromWallet = false; ui.addFlow = false; ui.addStep = null; ui.nostrLoginOpen = false;
+ ui.screen = 'wallet'; ui.unlockError = ''; ui.nostrLoginError = ''; render();
+ };
+ if (ui.addStep === 'doors') {
+ if (ui.nostrLoginOpen) {
+ return page([
+ h('div', { class: 'onb-mark', html: NOSTR_MARK }),
+ title(t('onbSigninTitle')),
+ featureHook('unlockExtra') || h('div', { class: 'notice err' }, 'nostr login unavailable'),
+ h('button', { class: 'linklike small', onClick: () => { ui.nostrLoginOpen = false; ui.nostrLoginError = ''; render(); } }, t('back')),
+ ]);
+ }
+ return page([
+ h('div', { class: 'onb-hero' }, brandHeader(false)),
+ title(t('onbSigninTitle')),
+ h('div', { class: 'col', style: 'gap:10px' },
+ h('button', { id: 'add-restore', class: 'btn-block', style: 'padding:14px', onClick: () => {
+ clearSeedDrafts();
+ ui.unlockTab = 'import'; ui.unlockError = ''; ui.addStep = null;
+ render();
+ } }, t('onbRestoreDoor')),
+ featureHook('frontDoorSignin', { short: true })),
+ h('button', { class: 'linklike small', onClick: () => { ui.nostrLoginError = ''; ui.addStep = 'welcome'; render(); } }, t('back')),
+ ]);
+ }
+ return page([
+ h('div', { class: 'onb-hero' }, brandHeader(false)),
+ title(t('addAccountTitle')),
+ h('div', { class: 'col', style: 'gap:10px' },
+ h('button', {
+ id: 'add-create',
+ class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: () => {
+ clearSeedDrafts();
+ ui.unlockTab = 'create'; ui.unlockError = ''; ui.createStep = 'intro'; ui.confirm = [];
+ ui.draftRandom = ui.draftMnemonic = newMnemonic();
+ ui.addStep = null;
+ render();
+ },
+ }, t('onbStart')),
+ h('button', {
+ id: 'add-signin',
+ class: 'btn-block', style: 'font-size:17px;padding:14px',
+ onClick: () => { ui.nostrLoginError = ''; ui.addStep = 'doors'; render(); },
+ }, t('onbSignInExisting'))),
+ accounts.length ? h('button', { class: 'linklike small', onClick: toWallet }, t('back')) : null,
+ ]);
+}
+
function unlockScreen() {
+ if (ui.fromWallet && ui.addFlow) {
+ if (ui.addStep && !ui.entropyPage) return addAccountScreen();
+ // a choice made there: the same seed pages as the front door, whose
+ // Back steps back to where it was made
+ return h('div', { class: 'col onb', style: 'gap:20px' },
+ h('h2', { class: 'onb-title' }, t(ui.unlockTab === 'import' ? 'onbRestoreTitle' : 'onbSeedTitle')),
+ unlockCard(),
+ ui.entropyPage ? null : h('button', { class: 'linklike small', onClick: () => {
+ if (createStepBack()) return;
+ const from = ui.unlockTab === 'import' ? 'doors' : 'welcome';
+ clearSeedDrafts(); ui.draftMnemonic = ''; ui.createStep = 'intro'; ui.confirm = []; ui.unlockError = '';
+ ui.addStep = from; render();
+ } }, t('back')));
+ }
return h(
'div',
{ class: 'col', style: 'gap:16px' },
@@ -1404,6 +1560,27 @@ function tabBtn(label, active, onClick) {
}
function createPane() {
+ // A heads-up before the words appear: they are secret, and the screen is
+ // about to show them (Adam, 2026-11-07). No warning icon — a plain note.
+ if (ui.createStep === 'intro' || !ui.createStep) {
+ const n = ui.draftMnemonic ? ui.draftMnemonic.split(' ').length : 12;
+ return h(
+ 'div',
+ { class: 'col seed-intro' },
+ h('p', { style: 'margin:0' }, t('seedIntroBody', { n })),
+ h('p', { class: 'muted', style: 'margin:0' }, t('seedIntroPrivate')),
+ h('button', {
+ id: 'seed-intro-next',
+ class: 'btn-primary btn-block', style: 'padding:14px',
+ onClick: () => {
+ if (!ui.draftMnemonic) ui.draftRandom = ui.draftMnemonic = newMnemonic();
+ ui.unlockError = '';
+ ui.createStep = 'gen';
+ render();
+ },
+ }, t('seedIntroShow')),
+ );
+ }
if (ui.createStep === 'gen') {
// The wizard shows words, never a Generate button: a refresh restores
// the step but not the draft (drafts live in memory only), so draw a
@@ -1431,7 +1608,6 @@ function createPane() {
return h(
'div',
{ class: 'col' },
- h('div', { class: 'warn-box' }, t('writeDownWarn')),
h(
'div',
{ class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) },
@@ -1442,74 +1618,78 @@ function createPane() {
h('button', { class: 'btn-block', style: 'display:flex;align-items:center;justify-content:center;gap:8px', onClick: () => copy(ui.draftMnemonic) },
h('span', { style: 'display:flex', html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>' }),
t('copy')),
- optionsPanel(),
h(
'button',
{
+ id: 'seed-next',
class: 'btn-primary btn-block',
- onClick: () => {
- // catch a mistyped passphrase here, while the field to fix it is
- // still on screen — the verify step only samples the words
- if (ui.passphrase && ui.confirmPass !== ui.passphrase) {
- ui.unlockError = t('passphraseMismatch'); render(); return;
- }
- ui.confirm = pickConfirm(words);
- ui.unlockError = '';
- ui.createStep = 'confirm';
- render();
- },
+ onClick: () => { ui.unlockError = ''; ui.createStep = 'pass'; render(); },
},
- t('verifyBackup')
- ),
- h(
- 'button',
- { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic, { generated: true }) },
- t('skipVerification')
+ t('next')
)
);
}
- // confirm step (optional — reachable via "Verify backup")
+ // The passphrase, on a page of its own (Adam, 2026-11-07): what it is,
+ // that it's optional but recommended, and the field — a small "Add
+ // passphrase" button under the words was easy to miss.
+ if (ui.createStep === 'pass') {
+ const words = ui.draftMnemonic.split(' ');
+ const next = () => {
+ // a typo here IS a different wallet: caught while the fields are up
+ if (ui.passphrase && ui.confirmPass !== ui.passphrase) {
+ ui.unlockError = t('passphraseMismatch'); render(); return;
+ }
+ ui.confirm = pickConfirm(words);
+ ui.unlockError = '';
+ ui.createStep = 'confirm';
+ render();
+ };
+ return h(
+ 'div',
+ { class: 'col' },
+ h('h3', { style: 'margin:0' }, t('passStepTitle')),
+ h('p', { style: 'margin:0' }, t('passStepBody', { n: words.length })),
+ h('p', { class: 'muted', style: 'margin:0' }, t('passStepNote')),
+ ...passFields(),
+ h('button', { id: 'pass-next', class: 'btn-primary btn-block', onClick: next }, t(ui.passphrase ? 'next' : 'passStepNone')),
+ );
+ }
+ // The check: which word is #5? One tap from a few of the phrase's own
+ // words, or Skip (Adam, 2026-11-07) — no typing.
+ const q = ui.confirm;
+ if (!q || !q.options) { ui.createStep = 'pass'; return createPane(); }
return h(
'div',
{ class: 'col' },
- h('p', { class: 'muted' }, t('confirmBackupIntro')),
- ...ui.confirm.map((c, i) =>
- h(
- 'label',
- { class: 'field' },
- h('span', { class: 'lab' }, t('wordN', { n: c.index + 1 })),
- h('input', {
- type: 'text',
- class: 'mono-input',
- autocapitalize: 'none',
- autocomplete: 'off',
- spellcheck: 'false',
- value: c.value,
- onInput: (e) => (ui.confirm[i].value = e.target.value.trim()),
- })
- )
- ),
- h('div', { class: 'row gap6' },
- h('button', { class: 'btn-ghost', onClick: () => { ui.createStep = 'gen'; render(); } }, t('back')),
+ h('p', { style: 'margin:0' }, t('quizPrompt', { n: q.index + 1 })),
+ h('div', { class: 'quiz-opts' }, q.options.map((w) =>
h('button', {
- class: 'btn-primary grow',
+ type: 'button',
+ class: 'quiz-opt' + (q.wrong && q.wrong.includes(w) ? ' wrong' : ''),
onClick: () => {
const words = ui.draftMnemonic.split(' ');
- const ok = ui.confirm.every((c) => c.value.toLowerCase() === words[c.index]);
- if (!ok) { ui.unlockError = t('wordsMismatch'); render(); return; }
- openWallet(ui.draftMnemonic, { generated: true });
+ if (w === words[q.index]) { ui.unlockError = ''; openWallet(ui.draftMnemonic, { generated: true }); return; }
+ (q.wrong ||= []).includes(w) || q.wrong.push(w);
+ render();
},
- }, t('openWallet'))
- ),
- h('button', { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic, { generated: true }) }, t('skipVerification'))
+ }, w))),
+ q.wrong && q.wrong.length ? h('div', { class: 'notice err' }, t('quizWrong')) : null,
+ h('button', { id: 'seed-skip', class: 'btn-ghost btn-block', onClick: () => { ui.unlockError = ''; openWallet(ui.draftMnemonic, { generated: true }); } }, t('skip')),
+ // outside the seed pages (no Back of their own), a way back to the words
+ seedPages() ? null : h('button', { class: 'linklike small', style: 'align-self:center', onClick: () => { ui.createStep = 'pass'; ui.unlockError = ''; render(); } }, t('back')),
);
}
-function pickConfirm(words) {
- const idx = new Set();
- while (idx.size < 3) idx.add(Math.floor(Math.random() * words.length));
- return [...idx].sort((a, b) => a - b).map((index) => ({ index, value: '' }));
+// The 5th word and three others from the same phrase, shuffled: knowing the
+// words isn't enough, you need them in order.
+function pickConfirm(words, index = Math.min(4, words.length - 1)) {
+ const right = words[index];
+ const others = [...new Set(words.filter((w) => w !== right))];
+ for (let i = others.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [others[i], others[j]] = [others[j], others[i]]; }
+ const options = [right, ...others.slice(0, 3)];
+ for (let i = options.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [options[i], options[j]] = [options[j], options[i]]; }
+ return { index, options, wrong: [] };
}
// The BYO-entropy page, shared by Create (re-derives the draft phrase) and
@@ -1559,7 +1739,7 @@ function entropyPage() {
// tabs, backing out of the entropy page, going home. Whatever you come back
// to is empty. (An opened wallet clears these too, in openWallet/lock.)
function clearSeedDrafts() {
- ui.importText = ''; ui._entropyFilled = null;
+ ui.importText = ''; ui._entropyFilled = null; ui.passOpen = false;
ui.entropyEntry = ''; ui.ownEntropy = ''; ui.importEntropy = '';
}
@@ -1597,18 +1777,34 @@ function importPane() {
}
function optionsPanel() {
+ // Most people want no passphrase, and an empty field labelled "Passphrase"
+ // under the seed reads as a required password. It waits behind a button,
+ // and once opened says it's optional (Adam, 2026-11-06). A passphrase
+ // already typed keeps it open.
+ if (!ui.passOpen && !ui.passphrase) {
+ return [h('button', {
+ class: 'btn-block', type: 'button',
+ onClick: (e) => { e.preventDefault(); ui.passOpen = true; render(); },
+ }, t('addPassphrase'))];
+ }
+ return passFields({ label: true });
+}
+
+// The passphrase field (+ its confirmation once something is typed). The
+// create flow's own page explains it above; the import pane labels it here.
+function passFields({ label = false } = {}) {
const pass = h(
'label',
{ class: 'field' },
h('span', { class: 'lab' },
- t('passphrase'),
+ t(label ? 'passphraseOptional' : 'passphrase'),
// People assume a password logs in or encrypts; a BIP39 passphrase does
// neither, and getting that wrong loses money — worth a sentence here.
h('button', {
class: 'linklike small', type: 'button', style: 'margin-left:8px',
onClick: (e) => { e.preventDefault(); ui.passInfoOpen = !ui.passInfoOpen; render(); },
}, t('passWhatsThis'))),
- ui.passInfoOpen ? h('p', { class: 'small muted', style: 'margin:0 0 6px' }, t('passInfo')) : null,
+ ui.passInfoOpen ? h('p', { class: 'small muted', style: 'margin:0 0 6px' }, t('passInfo')) : label ? h('p', { class: 'small muted', style: 'margin:0 0 6px' }, t('passOptionalHint')) : null,
h(
'div',
{ class: 'input-group' },
@@ -1637,7 +1833,7 @@ function optionsPanel() {
class: 'mono-input',
autocomplete: 'off',
value: ui.confirmPass,
- onInput: (e) => (ui.confirmPass = e.target.value),
+ onInput: (e) => { ui.confirmPass = e.target.value; if (ui.unlockError && ui.confirmPass === ui.passphrase) { ui.unlockError = ''; render(); } },
})
)
: null;
@@ -1684,7 +1880,22 @@ async function enterWallet(mnemonic, passphrase, opts = {}) {
// it — Google, a passkey and a nostr key all end up at a seed the user has
// never seen, and which nobody can reissue for them. That is the one case
// worth asking about, so it's recorded once and never guessed at again.
- if (acc.seedSeen === undefined) acc.seedSeen = !opts.nostrPubkey;
+ // A sign-up (Create an account) shows no phrase either: it stays one tap
+ // away in Settings, next to the other ways back in (passkey, Google, nostr).
+ if (acc.seedSeen === undefined) acc.seedSeen = !opts.nostrPubkey && !opts.unseen;
+ if (opts.signup && !acc.signupAt) acc.signupAt = Date.now();
+ // Spending first: an account made by signing up has no Savings side until
+ // its owner adds one (or on-chain money turns up — see savingsEvident). A
+ // recovery sign-in carries the same shape over from the account's backup.
+ if (opts.spendingOnly && !acc.kind && !acc.deriveIndex && !acc.savingsAdded && acc.type === 'full') {
+ acc.kind = 'spending'; acc.savingsLater = true;
+ } else if (opts.signup && acc.kind === 'spending') acc.savingsLater = true;
+ // ...unless balances are one: then a sign-up is simply the account, its
+ // on-chain side there underneath for whenever someone pays on-chain
+ if (acc.kind === 'spending' && acc.savingsLater && !acc.deriveIndex && !separateBalances()) {
+ delete acc.kind; delete acc.savingsLater;
+ if (!acc.spendingSetup) acc.spendingSetup = Date.now();
+ }
await activateAccount(acc, { ...opts, fresh: true });
}
@@ -1848,8 +2059,9 @@ async function activateAccount(acc, opts = {}) {
function signInAnother() {
clearSeedDrafts();
ui.fromWallet = true; ui.unlockError = ''; ui.screen = 'unlock';
- // Starts on Create new (its Generate button), not the seed-import box.
- ui.unlockTab = 'create'; ui.createStep = 'gen'; ui.draftMnemonic = ''; ui.confirm = [];
+ ui.addFlow = true; ui.addStep = 'welcome'; ui.nostrLoginOpen = false; ui.nostrLoginError = '';
+ // Opens on the front door's two choices (addAccountScreen).
+ ui.unlockTab = 'create'; ui.createStep = 'intro'; ui.draftMnemonic = ''; ui.confirm = [];
ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false; ui.chatOpen = false;
render();
}
@@ -1920,7 +2132,7 @@ function identities() {
function clearFeatureNav() {
ui.arkCoinsPage = null; ui.arkExitPage = null;
ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false;
- ui.chatOpen = false; ui.userSearch = null; ui.noteThread = null; ui.zapSetup = null;
+ ui.chatOpen = false; ui.userSearch = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.zapSetup = null;
}
// Sign out of the CURRENT identity only. "Log out" locks every account on
@@ -1993,7 +2205,12 @@ function defaultLabel(type) {
function loadWatchAccounts() {
try {
const dir = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
- return dir.filter((d) => d.xpub).map((d) => ({ id: d.id, label: d.label, type: 'watch', xpub: d.xpub, autoLock: d.autoLock || 0, network: d.network, nostrPk: d.nostrPk }));
+ return dir.filter((d) => d.xpub).map((d) => ({ id: d.id, label: d.label, type: 'watch', xpub: d.xpub, autoLock: d.autoLock || 0, network: d.network, nostrPk: d.nostrPk,
+ // a sign-up's Spending-only shape and its ways back in outlive the session
+ ...(d.spendingOnly ? { kind: 'spending', savingsLater: true } : {}),
+ ...(d.signupAt ? { signupAt: d.signupAt } : {}),
+ ...(d.waysBackPrompted ? { waysBackPrompted: d.waysBackPrompted } : {}),
+ ...(Array.isArray(d.recovery) && d.recovery.length ? { recovery: d.recovery } : {}) }));
} catch { return []; }
}
function saveDirectory() {
@@ -2010,7 +2227,11 @@ function saveDirectory() {
|| (wallet.nostrPubkey && wallet.nostrPubkey()) || a.nostrPk;
} catch {}
}
- return { id: a.id, label: a.label, xpub: a.xpub, autoLock: a.autoLock || 0, network: a.network, nostrPk: a.nostrPk, seedSeen: !!a.seedSeen };
+ return { id: a.id, label: a.label, xpub: a.xpub, autoLock: a.autoLock || 0, network: a.network, nostrPk: a.nostrPk, seedSeen: !!a.seedSeen,
+ ...(a.kind === 'spending' && a.savingsLater ? { spendingOnly: true } : {}),
+ ...(a.signupAt ? { signupAt: a.signupAt } : {}),
+ ...(a.waysBackPrompted ? { waysBackPrompted: a.waysBackPrompted } : {}),
+ ...(a.recovery && a.recovery.length ? { recovery: a.recovery } : {}) };
});
localStorage.setItem(WATCH_KEY, JSON.stringify(dir));
} catch {}
@@ -2096,6 +2317,42 @@ function switchAccount(id) {
// Restore accounts after a refresh (sessionStorage); on a fresh session, prompt
// to unlock the encrypted vault if there is one, else seed from watch-only
// accounts. Returns true if it handled the entry (opened or showed a prompt).
+// Whether restoreAccountsState() is about to open a wallet, read from what
+// it reads but without its work: a session list in this tab, a vault the
+// last unlock opened without a password, or watch-only accounts. The vault
+// alone can't say whether a blank password opens it short of the scrypt
+// that is the cost being avoided, so the last seal or unlock leaves a note.
+const VAULT_BLANK_KEY = 'btc-wallet-vault-blank';
+const noteVaultBlank = (password) => { try { if (password === '') localStorage.setItem(VAULT_BLANK_KEY, '1'); else localStorage.removeItem(VAULT_BLANK_KEY); } catch {} };
+const vaultOpensBlank = () => { try { return localStorage.getItem(VAULT_BLANK_KEY) === '1'; } catch { return false; } };
+function bootWillRestore() {
+ if (!unlockDeadlinePassed()) {
+ try { const s = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null'); if (s && Array.isArray(s.accounts) && s.accounts.length) return true; } catch {}
+ }
+ if (hasVault()) return vaultOpensBlank();
+ return loadWatchAccounts().length > 0;
+}
+const restorePending = () => _restorePending && bootWillRestore();
+
+// The phrases the restore below is about to open, stretched into their seeds
+// natively (seed.js) while the stores open: the restore and the wallet then
+// read them instead of stretching each in JavaScript, once per use.
+async function warmBootSeeds() {
+ let list = [];
+ try {
+ if (!unlockDeadlinePassed()) {
+ const s = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null');
+ if (s && Array.isArray(s.accounts)) list = s.accounts;
+ }
+ } catch {}
+ if (!list.length && vaultOpensBlank()) {
+ try { list = decryptVault(loadVaultBlob(), ''); } catch {}
+ }
+ await Promise.all((Array.isArray(list) ? list : [])
+ .filter((a) => a && a.mnemonic && !a.xprv)
+ .map((a) => warmSeed(a.mnemonic, a.passphrase || '')));
+}
+
function restoreAccountsState() {
let sess = null;
try { sess = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null'); } catch {}
@@ -2147,6 +2404,7 @@ const passkeySecret = (pw) => typeof pw === 'string' && pw.startsWith('passkey:'
const vaultPasskey = () => (loadVaultBlob() || {}).passkey || null;
function sealVault(list, password) {
const b = encryptVault(list, password);
+ noteVaultBlank(password);
if (passkeySecret(password) && vaultPasskeyId) b.passkey = vaultPasskeyId;
return b;
}
@@ -2302,7 +2560,7 @@ function submitPw() {
let list;
try { list = decryptVault(loadVaultBlob(), p.v0 || ''); } catch { p.error = t('pwWrong'); render(); return; }
if (p.v1 !== p.v2) { p.error = t('pwMismatch'); render(); return; }
- try { localStorage.setItem(VAULT_KEY, JSON.stringify(encryptVault(list, p.v1 || ''))); } catch {}
+ try { localStorage.setItem(VAULT_KEY, JSON.stringify(encryptVault(list, p.v1 || ''))); noteVaultBlank(p.v1 || ''); } catch {}
if (vaultPassword != null) vaultPassword = p.v1 || ''; // keep the unlocked session in sync
ui.pw = null;
render();
@@ -2443,6 +2701,7 @@ async function submitPwWithPasskey() {
function attemptVaultUnlock(password) {
let list;
try { list = decryptVault(loadVaultBlob(), password); } catch { return false; }
+ noteVaultBlank(password);
vaultPassword = password;
vaultPasskeyId = passkeySecret(password) ? vaultPasskey() : null;
// Start from the durable directory (watch-only views of every known wallet),
@@ -2660,6 +2919,7 @@ function lock({ offerPassword = false } = {}) {
_featuresInited = false;
for (const f of FEATURES) { try { f.stop && f.stop(); } catch {} }
clearAccounts();
+ forgetSeeds();
vaultPassword = null;
vaultPasskeyId = null;
wallet.load({ mnemonic: '', passphrase: '', netName: getNetwork(), offline: false });
@@ -2683,14 +2943,14 @@ function lock({ offerPassword = false } = {}) {
ui.confirmRemove = null;
ui.editId = null;
ui.editLabel = '';
- ui.createStep = 'gen';
+ ui.createStep = 'intro';
ui.draftMnemonic = '';
ui.importText = '';
ui.entropyPage = null;
ui.entropyEntry = '';
ui.ownEntropy = '';
ui.importEntropy = '';
- ui.passphrase = '';
+ ui.passphrase = ''; ui.passOpen = false;
ui.confirmPass = '';
ui.confirm = [];
ui.revealShown = false;
@@ -2833,17 +3093,36 @@ function lockBtn() {
// Find anyone on nostr from the header — results open their profile.
// Wide screens trade the search icon for a field in the header or sticky
// wallet sidebar. It drives the search page, which drops its own copy.
+// On a profile the field searches that person's posts: their chip sits in
+// it (× or Backspace on an empty field searches everywhere again).
function headerSearch() {
if (!featureHook('userSearchAvailable')) return null;
- return h('input', {
- type: 'text', class: 'header-search', placeholder: t('searchUsers') + '…', 'aria-label': t('searchUsers'),
- value: (ui.userSearch && ui.userSearch.q) || '', autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
- onInput: (e) => { clearFeatureNavKeepSearch(); featureHook('userSearchQuery', e.target.value); },
+ const chip = featureHook('userSearchScopeChip');
+ const input = h('input', {
+ type: 'text', class: chip ? 'header-search-field' : 'header-search',
+ placeholder: chip ? t('searchScopedHint') : t('searchUsers') + '…', 'aria-label': t('searchUsers'),
+ // a profile on screen starts a fresh query; the old one waits behind Back
+ value: (!ui.profilePk && ui.userSearch && ui.userSearch.q) || '', autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
+ onInput: (e) => { featureHook('userSearchHoldScope'); clearFeatureNavKeepSearch(); featureHook('userSearchQuery', e.target.value); },
+ // Enter without picking a suggestion: full-text search over notes
+ onKeydown: (e) => {
+ if (e.key === 'Enter' && !e.isComposing && e.target.value.trim()) { e.preventDefault(); featureHook('userSearchSubmit', e.target.value); e.target.blur(); }
+ else if (e.key === 'Backspace' && !e.target.value && chip) { e.preventDefault(); featureHook('userSearchUnscope'); }
+ },
});
+ return chip ? h('div', { class: 'header-search header-search-scoped' }, chip, input) : input;
}
+// Typing in the header field: whatever page is open steps aside for the
+// results, but the search itself (its query and rows) stays. It used to do
+// nothing once a search existed, so a profile opened from the results kept
+// covering them while a new query was typed (Adam, 2026-11-14).
function clearFeatureNavKeepSearch() {
- if (ui.userSearch) return; // already on the search page: just the query moves
- clearFeatureNav(); ui.screen = 'wallet';
+ const s = ui.userSearch;
+ clearFeatureNav();
+ // a visitor has no wallet screen to land on (it derived addresses from no
+ // seed: "Invalid mnemonic"); their search page draws over the front door
+ if (wallet.loaded) ui.screen = 'wallet';
+ ui.userSearch = s;
}
function searchBtn() {
@@ -2853,8 +3132,9 @@ function searchBtn() {
title: t('searchUsers'),
'aria-label': t('searchUsers'),
onClick: () => {
+ const scope = featureHook('userSearchScopePk'); // from a profile: search inside its person's posts
clearFeatureNav(); ui.screen = 'wallet';
- featureHook('openUserSearch');
+ featureHook('openUserSearch', scope);
render();
setTimeout(() => document.querySelector('.user-search-input')?.focus(), 60);
},
@@ -2970,13 +3250,19 @@ function settingsTab() {
switch (ui.settingsPage) {
// the recovery phrase first: it is the one thing on this page that
// matters if the phone is lost tonight
- case 'wallet': return page(a ? [recoveryCard(a), walletNameCard(a), pubkeyCard(a)] : []);
+ case 'wallet':
+ if (ui.delAcct && a) return deleteAccountView(a);
+ // the phrase is one of the ways back in: its card shows only once
+ // Pen and paper asks for it (accounts without the card keep it always)
+ { const ways = a ? featureHook('waysBackCard') : null;
+ return page(a ? [ways, ways && !ui.revealShown ? null : recoveryCard(a), balanceSettingsCard(a), walletNameCard(a), pubkeyCard(a), historyExportCard(), deleteAccountCard(a)] : []); }
case 'payments': return page(featureAll('settingsCards').reverse());
case 'pos': return page(featureAll('posSettingsCards').reverse()); // the till's own card first, then the terminal's
case 'network': return page([networkCard(), explorerCard()]); // an old bookmark of the tile; the cards live under Advanced now
case 'nostr': return nostrSettingsView();
case 'notifications': return page(featureAll('notifySettingsCards').reverse());
case 'advanced': return advancedSettingsView();
+ case 'about': return aboutSettingsView();
}
const I = (d) => '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">' + d + '</svg>';
const TILE_ICONS = {
@@ -2987,6 +3273,7 @@ function settingsTab() {
// a till receipt: paper with a torn foot and two lines of figures
pos: I('<path d="M6 3h12v18l-2-1.5-2 1.5-2-1.5-2 1.5-2-1.5L6 21z"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="12" y1="16" x2="15" y2="16"/>'),
notifications: I('<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/>'),
+ about: I('<circle cx="12" cy="12" r="9"/><line x1="12" y1="11" x2="12" y2="16.5"/><circle cx="12" cy="7.8" r=".6" fill="currentColor"/>'),
advanced: I('<line x1="4" y1="8" x2="20" y2="8"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="9" cy="8" r="2.2" fill="var(--surface,#fff)"/><circle cx="15" cy="16" r="2.2" fill="var(--surface,#fff)"/>'),
};
const tile = (id, label, desc) =>
@@ -3005,6 +3292,8 @@ function settingsTab() {
h('div', { class: 'row gap6', style: 'align-items:center;margin:2px 0 6px 4px' },
h('span', { style: 'display:flex;color:var(--muted)', html: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>' }),
h('h3', { style: 'margin:0' }, t('tabSettings'))),
+ // display preferences, right at the top: the language and the currency
+ h('div', { class: 'row gap6 settings-prefs', style: 'margin:0 0 4px' }, languagePicker(), currencyPicker()),
grid([
tile('wallet', t('settingsWallet'), t('settingsWalletDesc')),
tile('payments', t('settingsPayments'), t('settingsPaymentsDesc')),
@@ -3012,6 +3301,7 @@ function settingsTab() {
tile('nostr', t('nostrSettings'), t('settingsNostrDesc')),
tile('notifications', t('settingsNotifications'), t('settingsNotifDesc')),
tile('advanced', t('advancedSettings'), t('settingsAdvancedDesc')),
+ tile('about', t('aboutTitle'), t('settingsAboutDesc')),
]),
h('button', { class: 'btn-ghost btn-block', style: 'margin-top:6px', onClick: () => { ui.tab = wallet.offline ? 'settings' : 'history'; render(); } }, t('back'))
);
@@ -3027,11 +3317,33 @@ function registerLinkHandler(scheme) {
toast(t('linkHandlerAsked'));
} catch (e) { toast(t('linkHandlerRefused')); }
}
+function mediaServersCard() {
+ if (ui.mediaServersDraft == null) ui.mediaServersDraft = (customMediaServers() || []).join('\n');
+ const save = (reset = false) => {
+ try {
+ if (reset) { resetMediaServers(); ui.mediaServersDraft = ''; }
+ else ui.mediaServersDraft = saveMediaServers(ui.mediaServersDraft).join('\n');
+ toast(t('mediaServersSaved'));
+ render();
+ } catch (e) { toast(t(e.message === 'invalid' ? 'mediaServersInvalid' : 'mediaServersSaveFailed')); }
+ };
+ return h('div', { class: 'card col', 'data-key': 'media-servers' },
+ h('h3', {}, t('mediaServersTitle')),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('mediaServersHow')),
+ h('textarea', { rows: 3, style: 'font-size:12px', 'aria-label': t('mediaServersTitle'),
+ placeholder: t('mediaServersDefault'), value: ui.mediaServersDraft, spellcheck: 'false',
+ onInput: (e) => { ui.mediaServersDraft = e.target.value; } }),
+ h('div', { class: 'row gap6' },
+ h('button', { class: 'btn-ghost small', onClick: () => save() }, t('syncStorageSave')),
+ h('button', { class: 'btn-ghost small', onClick: () => save(true) }, t('syncStorageReset'))));
+}
+
function nostrSettingsView() {
return h(
'div',
{ class: 'col', style: 'gap:16px' },
...featureAll('nostrSettingsCards'),
+ mediaServersCard(),
// The browser's own "open these links here" registry: njump's "Your
// default web app" is a web+nostr: link, and it opens whichever site
// asked for that scheme last. Needs a tap (the browser asks).
@@ -3220,7 +3532,7 @@ function goHome() {
ui.profilePk = null;
ui.profEdit = null;
ui.userSearch = null;
- ui.noteThread = null;
+ ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
ui.zapSetup = null;
ui.arkExitPage = null;
ui.settingsPage = null;
@@ -3243,7 +3555,7 @@ function goHome() {
ui.sendError = '';
ui.fromWallet = false;
} else if ((ui.onb && ui.onb.step !== 'welcome')
- || ui.draftMnemonic || ui.createStep !== 'gen' || ui.importText) {
+ || ui.draftMnemonic || !['intro', 'gen'].includes(ui.createStep) || ui.importText) {
// Mid-create with no wallet minted yet (wizard step, a generated seed on
// screen, the confirm quiz, a pasted import): the logo backs out to the
// start page this began from — not the vault prompt, which reads as a
@@ -3253,7 +3565,7 @@ function goHome() {
ui.nostrLoginOpen = false;
ui.screen = 'unlock';
ui.unlockTab = 'create';
- ui.createStep = 'gen';
+ ui.createStep = 'intro';
ui.draftMnemonic = '';
clearSeedDrafts();
ui.entropyPage = null;
@@ -3272,7 +3584,7 @@ function goHome() {
} else {
ui.screen = 'unlock';
ui.unlockTab = 'create';
- ui.createStep = 'gen';
+ ui.createStep = 'intro';
ui.draftMnemonic = '';
ui.confirm = [];
ui.unlockError = '';
@@ -3352,8 +3664,8 @@ function accountsScreen() {
if (aw.from === 'new') {
ui.newWalletKind = kind;
ui.addWallet = null;
- ui.draftMnemonic = ''; ui.createStep = 'gen'; ui.confirm = []; ui.passphrase = ''; ui.confirmPass = '';
- ui.showPass = false; ui.screen = 'unlock'; ui.unlockTab = 'create'; ui.fromWallet = true; ui.unlockError = '';
+ ui.draftMnemonic = ''; ui.createStep = 'intro'; ui.confirm = []; ui.passphrase = ''; ui.confirmPass = ''; ui.passOpen = false;
+ ui.showPass = false; ui.screen = 'unlock'; ui.unlockTab = 'create'; ui.fromWallet = true; ui.unlockError = ''; ui.addFlow = false;
render();
} else {
createDerivedWallet(aw.from, kind);
@@ -3403,8 +3715,8 @@ function accountsScreen() {
// has to say which identity.
...groupAccounts().flatMap(({ pk, rows }) => [
identityHeading(pk),
- ...rows.flatMap((a) => viewsOf(a).map((view) => {
- const isActive = a.id === activeId && accountSel() === view;
+ ...rows.flatMap((a) => (a.id === activeId && unifiedOn(a) ? ['all'] : viewsOf(a)).map((view) => {
+ const isActive = a.id === activeId && (view === 'all' || accountSel() === view);
const netTag = a.network && a.network !== 'mainnet' ? ' · ' + a.network : '';
const seedTag = '';
const tag = (a.type === 'watch' ? ' · ' + t('watchOnlyTag') : '') + netTag + seedTag;
@@ -3516,6 +3828,76 @@ function openAccountSettings(id) {
// Per-wallet settings cards, shared by the per-account screen (Accounts → ⚙)
// and the main Settings tab (which inlines them for the active wallet).
+// Delete account: the server forgets this wallet (its name is freed, its
+// records go) and the wallet leaves this device. "someone's asking for a way
+// to delete their v3 account. we allowed that in v2" (Adam, 2026-11-10). The
+// coins are the user's own and no server can delete them: they stay
+// spendable from the recovery phrase, which is why the page says how much is
+// still here before anything happens.
+// The saved copy on this device has to go too, and the vault can only be
+// rewritten with its password in hand: a blank one is tried here, a real one
+// is known once the app has been unlocked with it this session.
+function vaultWritable() {
+ if (vaultPassword != null || !hasVault()) return true;
+ try { const list = decryptVault(loadVaultBlob(), ''); vaultPassword = ''; mergeVaultList(list); return true; } catch { return false; }
+}
+function deleteAccountCard(a) {
+ if (a.type === 'watch' || wallet.watchOnly || !wallet.nostrSign) return null;
+ return h('div', { class: 'card col', 'data-key': 'delete-account' },
+ h('h3', {}, t('delAcctTitle')),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('delAcctBlurb')),
+ h('button', { class: 'btn-danger btn-block', onClick: () => {
+ if (!vaultWritable()) { toast(t('delAcctUnlockFirst')); return; }
+ const d = ui.delAcct = { accId: a.id, info: null, sure: false, busy: false, error: '' };
+ render();
+ Promise.resolve(featureHook('accountDelete', true)).then((info) => { if (ui.delAcct === d) { d.info = info || {}; render(); } })
+ .catch((e) => { if (ui.delAcct === d) { d.info = {}; d.error = e.message; render(); } });
+ } }, t('delAcctTitle')));
+}
+function deleteAccountView(a) {
+ const d = ui.delAcct;
+ const heldSat = (wallet.spendable || 0) + (featureHook('arkHeldSat') || 0);
+ const info = d.info;
+ const names = (info && info.names) || [];
+ const owedSat = info ? (info.pendingSat || 0) + (info.withdrawSat || 0) : 0;
+ const blocked = !!(info && (info.blocked || owedSat > 0 || info.paying));
+ const back = () => { ui.delAcct = null; render(); };
+ const go = async () => {
+ if (d.busy || !d.sure || blocked) return;
+ d.busy = true; d.error = ''; render();
+ try {
+ const r = await featureHook('accountDelete', false);
+ if (r && r.blocked) { d.info = { ...d.info, ...r, blocked: true }; d.sure = false; return; }
+ ui.delAcct = null; ui.settingsPage = null;
+ wipeAccountCache(a);
+ // out of the saved vault first, or the next unlock brings it back
+ if (a.persisted && vaultWritable()) { a.persisted = false; writeVault(); }
+ removeAccount(a.id);
+ toast(t('delAcctDone'));
+ } catch (e) { d.error = e.message; }
+ finally { d.busy = false; render(); }
+ };
+ return h('div', { class: 'col', style: 'gap:16px' },
+ h('div', { class: 'card col', style: 'gap:10px' },
+ h('h3', {}, t('delAcctTitle')),
+ !info ? h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('delAcctChecking'))) : null,
+ h('ul', { class: 'small', style: 'margin:0;padding-left:18px;display:flex;flex-direction:column;gap:6px' },
+ names.length ? h('li', {}, t('delAcctName', { name: names.join(', ') })) : null,
+ h('li', {}, t('delAcctRecords')),
+ h('li', {}, t('delAcctDevice', { name: seedName(a) })),
+ h('li', { class: 'muted' }, t('delAcctStays'))),
+ blocked ? h('div', { class: 'warn-box' }, t('delAcctOwed', { sat: fmtAmount(owedSat) })) : null,
+ heldSat > 0 ? h('div', { class: 'warn-box' }, t('delAcctFunds', { sat: fmtAmount(heldSat) })) : null,
+ d.error ? h('div', { class: 'warn-box' }, d.error) : null,
+ h('label', { class: 'row gap6 small', style: 'align-items:flex-start;cursor:pointer' },
+ h('input', { type: 'checkbox', checked: d.sure, disabled: blocked || d.busy, style: 'margin-top:2px', onChange: (e) => { d.sure = e.target.checked; render(); } }),
+ h('span', {}, t(heldSat > 0 ? 'delAcctSureFunds' : 'delAcctSure'))),
+ h('div', { class: 'row gap6' },
+ h('button', { class: 'btn-ghost grow', disabled: d.busy, onClick: back }, t('back')),
+ h('button', { class: 'btn-danger grow', disabled: !info || !d.sure || blocked || d.busy, onClick: go },
+ d.busy ? h('span', { class: 'spinner sm' }) : t('delAcctGo')))));
+}
+
function recoveryCard(a) {
const isWatch = a.type === 'watch' || (!a.mnemonic && !a.xprv);
const shown = ui.revealShown;
@@ -3538,12 +3920,12 @@ function recoveryCard(a) {
// a warning) before anything readable is over your shoulder. The second
// actually shows them.
if (!shown)
- return h('div', { class: 'card col' },
+ return h('div', { class: 'card col recovery-card' },
h('h3', {}, t('recoveryPhrase')),
h('p', { class: 'small muted', style: 'margin:0' }, t('recoveryDesc')),
h('button', { class: 'btn-block', onClick: () => { ui.revealShown = 'masked'; render(); } }, t('revealRecovery')));
const unmasked = shown === 'words';
- return h('div', { class: 'card col' },
+ return h('div', { class: 'card col recovery-card' },
h('h3', {}, t('recoveryPhrase')),
h('div', { class: 'warn-box' }, t('recoveryWarn')),
h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) }, words.map((w, i) =>
@@ -3571,6 +3953,39 @@ function recoveryCard(a) {
);
}
+// The balance cards' gears, reachable from Settings → Wallet too: "I simply
+// cannot find this option" (Nils, 2026-11-12) about the Spending card's gear.
+function balanceSettingsCard(a) {
+ if (a.id !== activeId) return null;
+ const unified = unifiedOn(a);
+ const views = unified ? ['all'] : a.kind ? [a.kind] : spendingActive() ? ['spending', 'savings'] : ['savings'];
+ // Each balance wears its own mark in a tinted tile — the bolt and the
+ // bitcoin disc the balance card uses — rather than a gear beside one and a
+ // coin beside the other (Adam, 2026-11-15: "Icons and padding need work").
+ const BOLT = '<svg width="21" height="21" viewBox="0 0 24 24" fill="currentColor" style="display:block"><path d="M13.5 2 4 13.5h6.5L9.5 22 20 9.5h-6.6z"/></svg>';
+ const tile = (view) => h('span', { class: 'bs-tile ' + (view === 'savings' ? 'save' : 'spend'), html: view === 'savings' ? BITCOIN_ICON(22) : BOLT });
+ const rowOf = (attrs, view, title, desc, tail) => h('button', { class: 'balance-settings-row', ...attrs },
+ tile(view),
+ h('span', { class: 'col bs-text' },
+ h('span', { class: 'bs-title' }, title),
+ h('span', { class: 'small muted' }, desc)),
+ h('span', { class: 'bs-tail', 'aria-hidden': 'true' }, tail));
+ const row = (view) => rowOf({ 'data-view': view, onClick: () => openWalletSettings(view) }, view,
+ viewLabel(a, view), t(view === 'all' ? 'allSettingsDesc' : view === 'spending' ? 'spendingSettingsDesc' : 'savingsSettingsDesc'), '›');
+ // a sign-up's Spending-only account: Savings is one tap away
+ const addRow = a.kind === 'spending' && a.savingsLater && !a.deriveIndex
+ ? rowOf({ id: 'add-savings', onClick: () => { addSavings(a); toast(t('savingsAddedToast')); } }, 'savings',
+ t('addSavings'), t('addSavingsDesc'), '+')
+ : null;
+ // one balance or two, per device: the same seed and coins either way
+ const apart = !a.kind && a.type === 'full' && spendingActive()
+ ? h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer;padding:6px 2px 0' },
+ h('input', { type: 'checkbox', id: 'separate-balances', checked: separateBalances(),
+ onChange: (e) => { setSeparateBalances(e.target.checked); ui.recvOnchain = false; render(); } }),
+ h('span', { class: 'small' }, t('separateBalances')))
+ : null;
+ return h('div', { class: 'card col', style: 'gap:8px' }, h('h3', {}, t('balanceSettingsTitle')), ...views.map(row), unified ? null : addRow, apart);
+}
function walletNameCard(a) {
const saveName = () => {
const v = (ui.editLabel || '').trim();
@@ -3605,6 +4020,46 @@ function pubkeyCard(a) {
);
}
+// Every payment in both balances as a CSV file, for a spreadsheet or an
+// accountant: Savings' on-chain transactions and Spending's movements (the
+// rows the features list in History, each with its `csv` line), oldest
+// first, priced in the chosen currency at the time each happened.
+function historyCsv() {
+ const cur = getCurrency();
+ const lines = [];
+ for (const tx of wallet.history || []) {
+ const out = tx.net < 0, fee = out ? tx.fee || 0 : 0;
+ lines.push({ ts: tx.confirmed && tx.blockTime ? tx.blockTime * 1000 : Date.now(), account: t('savingLabel'), type: out ? 'send' : 'receive', rail: 'onchain',
+ amount: out ? tx.net + fee : tx.net, fee, net: tx.net, status: tx.confirmed ? 'complete' : 'pending', ref: tx.txid, to: '', invoice: '', note: '' });
+ }
+ for (const [sel, account] of [['savings', t('savingLabel')], ['spending', t('spendingLabel')]])
+ for (const e of featureAll('historyEntries', wallet.history || [], sel)) if (e.csv) lines.push({ ...e.csv, account });
+ lines.sort((a, b) => a.ts - b.ts);
+ const q = (v) => (v == null ? '' : /[",\n\r]/.test(String(v)) ? '"' + String(v).replace(/"/g, '""') + '"' : String(v));
+ const head = ['Date (UTC)', 'Account', 'Type', 'Rail', 'Amount (sats)', 'Fee (sats)', 'Net (sats)', `Net (${cur} at the time)`, 'Status', 'Transaction / payment hash', 'To', 'Invoice', 'Note'];
+ const rows = lines.map((l) => {
+ const { rate, stale } = rateAt(l.ts / 1000);
+ const fiat = rate && !stale ? ((l.net / 1e8) * rate).toFixed(2) : '';
+ return [new Date(l.ts).toISOString().replace('T', ' ').slice(0, 19), l.account, l.type, l.rail, l.amount, l.fee || 0, l.net, fiat, l.status, l.ref, l.to, l.invoice, l.note];
+ });
+ return [head, ...rows].map((r) => r.map(q).join(',')).join('\r\n') + '\r\n';
+}
+function exportHistory() {
+ const name = `coinos-history-${new Date().toISOString().slice(0, 10)}.csv`;
+ const url = URL.createObjectURL(new Blob([historyCsv()], { type: 'text/csv;charset=utf-8' }));
+ const a = h('a', { href: url, download: name, style: 'display:none' });
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 60_000);
+}
+function historyExportCard() {
+ return h('div', { class: 'card col' },
+ h('h3', {}, t('historyExportTitle')),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('historyExportDesc')),
+ h('button', { class: 'btn-block history-export', disabled: !wallet.loaded, onClick: exportHistory }, t('historyExportBtn')));
+}
+
function autolockCard(a) {
return h('div', { class: 'card col' },
h('h3', {}, t('autolockTitle')),
@@ -3660,7 +4115,7 @@ function accountSettingsScreen() {
const a = accounts.find((x) => x.id === ui.settingsId) || activeAccount();
if (!a) { ui.screen = 'accounts'; return accountsScreen(); }
const view = ui.settingsView || accountSel();
- const spending = view === 'spending' && a.id === activeId;
+ const spending = (view === 'spending' || view === 'all') && a.id === activeId;
const leave = () => { ui.editLabel = null; ui.revealShown = false; ui.pubkeyShown = false; ui.loadSeed = null; goBack(() => { ui.screen = 'wallet'; }); };
return h(
'div',
@@ -3829,18 +4284,33 @@ function mediaProgress(stage, fraction) {
}
async function publicMediaUpload(file) {
try {
- // a phone video is shrunk on the device first (see video-compress.js)
+ const signEvent = await mediaUploadSigner(wallet, featureHook);
+ // a phone video is shrunk on the device first (see video-compress.js);
+ // a long one becomes an HLS stream, its master playlist the address
if (/^video\//.test(file?.type || '')) {
mediaProgress('shrink', 0);
- const { compressVideo } = await import('./video-compress.js');
+ const { compressVideo, streamVideo } = await import('./video-compress.js');
+ const stream = await streamVideo(file, (p) => mediaProgress('shrink', p));
+ if (stream) {
+ mediaProgress('upload', 0);
+ const url = await uploadStream(stream, signEvent, { onProgress: (p) => mediaProgress('upload', p) });
+ return { url, m: 'application/vnd.apple.mpegurl', dim: stream.dim, duration: Math.round(stream.seconds) };
+ }
+ mediaProgress('shrink', 0);
file = await compressVideo(file, (p) => mediaProgress('shrink', p));
}
mediaProgress('upload', 0);
- return await uploadPublicMedia(file, (event) => wallet.nostrSign(event), { onProgress: (p) => mediaProgress('upload', p) });
+ return await uploadPublicMedia(file, signEvent, { onProgress: (p) => mediaProgress('upload', p) });
} catch (error) {
+ if (error instanceof MediaUploadError && error.code === 'no-identity') throw new Error(t('msgNoIdentity'));
+ 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;
}
@@ -3849,6 +4319,21 @@ async function publicMediaUpload(file) {
// Whether the wizard can offer Spending at all: an Ark-capable build on a
// network with the names registrar, for a full (signing) account. Elsewhere
// the offer would be a spinner that never resolves.
+// Signing up (Adam, 2026-11-15): "we should just have them claim a name and
+// pick their avatar/cover and they should be in." Where a name can be
+// claimed — an Ark server and the names registrar on this network — Create
+// makes the account straight away: no twelve words to copy or check, no
+// Savings side. The phrase waits in Settings with the other ways back in
+// (passkey, Google, nostr), and a quiet line on the wallet asks for one.
+// Elsewhere (regtest, a build without Ark) there's no name to claim, the
+// wallet IS its seed, and Create keeps the classic phrase flow.
+function quickSignupOk() {
+ if (!['mainnet', 'mutinynet'].includes(getNetwork())) return false;
+ try {
+ if (!FEATURES.some((f) => f.id === 'ark') || !FEATURES.some((f) => f.id === 'names')) return false;
+ return !!getArkConfig();
+ } catch { return false; }
+}
function canOfferSpending() {
const acc = activeAccount();
if (!acc || acc.type !== 'full' || wallet.watchOnly) return false;
@@ -3885,7 +4370,8 @@ function onboardScreen() {
// they lose the Google account and find out it was never a backup.
// Handled further down, where page()/title() exist.
const arrived = activeAccount();
- if (arrived && arrived.mnemonic && !arrived.seedSeen) o.step = 'backup';
+ // (a sign-up was never meant to see it: straight on to the name)
+ if (arrived && arrived.mnemonic && !arrived.seedSeen && !arrived.signupAt) o.step = 'backup';
else if (canOfferSpending()) {
// Before the home screen: one offer to set up Spending (a name and a
// payment address), with Not now a single tap away.
@@ -3893,10 +4379,11 @@ function onboardScreen() {
} else {
ui.onb = null;
try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
- // On-chain first: the wizard's promise is "your keys, your coins", and
- // Spending stays out of sight until the user sets it up.
- ui.account = 'savings';
- try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
+ // On-chain first for a seed wallet: the wizard's promise is "your
+ // keys, your coins". A sign-up is Spending alone.
+ const home = arrived && arrived.kind ? arrived.kind : 'savings';
+ ui.account = home;
+ try { localStorage.setItem(ACCOUNT_KEY, home); } catch {}
ui.tab = 'receive';
return null; // the caller falls through to the wallet itself
}
@@ -3990,17 +4477,35 @@ function onboardScreen() {
}
// Making your own keys: the words are the wallet, so show them at once,
// no Generate to tap.
+ // Create an account: a fresh seed opens at once as a Spending-only
+ // account; the wizard carries on to the name and the look.
+ const startQuick = async () => {
+ if (o.creating) return;
+ o.creating = true; ui.onbError = ''; render();
+ try {
+ clearSeedDrafts();
+ ui.passphrase = ''; ui.confirmPass = ''; ui.draftMnemonic = '';
+ ui.newWalletKind = 'spending';
+ await enterWallet(newMnemonic(), '', { generated: true, unseen: true, signup: true });
+ } catch (e) {
+ ui.onbError = e.message || String(e);
+ } finally {
+ ui.newWalletKind = null;
+ o.creating = false;
+ render();
+ }
+ };
const startCreate = () => {
ui.unlockTab = 'create';
ui.unlockError = '';
- ui.createStep = 'gen';
+ ui.createStep = 'intro';
if (!ui.draftMnemonic) ui.draftRandom = ui.draftMnemonic = newMnemonic();
o.step = 'seed';
render();
};
// All the sign-in doors (Google, passkey, Nostr) — the feature supplies
// them; the single-button fallback keeps builds without it working.
- const signinDoors = () => featureHook('frontDoorSignin')
+ const signinDoors = (opts) => featureHook('frontDoorSignin', opts)
|| h('button', { class: 'btn-block', style: 'padding:14px', onClick: () => {
o.step = 'signin';
ui.nostrLoginOpen = true;
@@ -4009,29 +4514,62 @@ function onboardScreen() {
h('span', { style: 'display:flex;flex-shrink:0', html: NOSTR_MARK }),
t('nlSignIn')));
if (o.step === 'welcome') {
+ // Two ways in, nothing else: a new wallet, or one you already have. The
+ // front page had grown a door per sign-in method (Google, passkey, Nostr,
+ // twelve words, coinos.io) and read as a form; they now wait one step
+ // further in, behind the choice that leads to them.
return page([
h('div', { class: 'onb-hero' }, brandHeader(false)),
title(t('onbWelcomeTitle')),
- // Making your own keys is the path; a sign-in is the alternative,
- // below the line.
- h('button', {
- // a stable hook for tests, so this button survives its own copy
- id: 'onb-create',
- class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: startCreate,
- }, t('onbStart')),
- h('div', { class: 'onb-or' }, h('span', {}, t('onbOrSignIn'))),
- signinDoors(),
- // The move from the original coinos.io used to wait behind the
- // Spending offer, where nobody looking for it found it. Its own door
- // on the front page: it stashes the intent the /migrate link stashes
- // (the move needs a wallet and a payment address first) and explains
- // that before any twelve words appear.
- h('button', { id: 'onb-migrate', class: 'btn-block', style: 'padding:14px', onClick: () => {
- try { localStorage.setItem(MIGRATE_LINK_KEY, String(Date.now())); } catch {}
- ui.onbError = '';
- o.step = 'migrate';
- render();
- } }, t('onbMigrateDoor')),
+ // spaced as the sign-in list is (10px)
+ h('div', { class: 'col', style: 'gap:10px' },
+ quickSignupOk()
+ ? h('button', {
+ // a stable hook for tests, so this button survives its own copy
+ id: 'onb-create', 'data-quick': '1',
+ class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', disabled: !!o.creating, onClick: startQuick,
+ }, o.creating ? h('span', { class: 'spinner sm' }) : t('onbCreateAccount'))
+ : h('button', {
+ id: 'onb-create',
+ class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: startCreate,
+ }, t('onbStart')),
+ h('button', {
+ id: 'onb-signin',
+ class: 'btn-block', style: 'font-size:17px;padding:14px',
+ onClick: () => { ui.onbError = ''; o.step = 'doors'; render(); },
+ }, t('onbSignInExisting'))),
+ ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
+ ]);
+ }
+ if (o.step === 'doors') {
+ return page([
+ h('div', { class: 'onb-hero' }, brandHeader(false)),
+ title(t('onbSigninTitle')),
+ // The seed phrase first: it IS the wallet, and works anywhere. It
+ // used to hide as a line under the freshly minted words behind
+ // "Create a new wallet", where a person signing in on their second
+ // phone found it only by chance (user feedback, 2026-11-02).
+ // one evenly spaced list: seed phrase, passkey, Google, Nostr, coinos.io
+ h('div', { class: 'col', style: 'gap:10px' },
+ h('button', { id: 'onb-restore', class: 'btn-block', style: 'padding:14px', onClick: () => {
+ clearSeedDrafts();
+ ui.unlockTab = 'import';
+ ui.unlockError = '';
+ ui.onbError = '';
+ o.step = 'seed';
+ render();
+ } }, t('onbRestoreDoor')),
+ signinDoors({ short: true }),
+ // The move from the original coinos.io: it stashes the intent the
+ // /migrate link stashes (the move needs a wallet and a payment address
+ // first) and explains that before any twelve words appear.
+ h('button', { id: 'onb-migrate', class: 'btn-block', style: 'padding:14px', onClick: () => {
+ try { localStorage.setItem(MIGRATE_LINK_KEY, String(Date.now())); } catch {}
+ ui.onbError = '';
+ o.step = 'migrate';
+ render();
+ } }, t('onbMigrateDoor'))),
+ h('button', { class: 'linklike small', onClick: () => { ui.onbError = ''; o.step = 'welcome'; render(); } }, t('back')),
ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
]);
}
@@ -4047,8 +4585,8 @@ function onboardScreen() {
class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: startCreate,
}, t('onbMigrateCreate')),
h('div', { class: 'onb-or' }, h('span', {}, t('onbOrSignIn'))),
- signinDoors(),
- h('button', { class: 'linklike small', onClick: () => { endMigrateLink(); ui.onbError = ''; o.step = 'welcome'; render(); } }, t('back')),
+ h('div', { class: 'col', style: 'gap:10px' }, signinDoors()),
+ h('button', { class: 'linklike small', onClick: () => { endMigrateLink(); ui.onbError = ''; o.step = 'doors'; render(); } }, t('back')),
ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
]);
}
@@ -4067,27 +4605,36 @@ function onboardScreen() {
ui.tab = 'receive';
render();
};
+ // Later means later, not never: seedSeen stays false, so the wallet
+ // keeps a quiet reminder until the phrase has actually been seen.
+ // Except on the way to a coinos.io move: the balance about to arrive
+ // must have its twelve words written down first, so Later isn't offered.
+ const later = migrateLinkPending() ? null : h('button', { class: 'btn-ghost btn-block', onClick: () => {
+ if (canOfferSpending()) { o.step = 'spend'; o.enterAddr = undefined; render(); return; }
+ ui.onb = null;
+ try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
+ ui.account = 'savings';
+ try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
+ ui.tab = 'receive';
+ render();
+ } }, t('onbBackupLater'));
+ // a heads-up first: the next screen shows the secret (Adam, 2026-11-07)
+ if (!o.backupShown) {
+ return page([
+ title(t('onbBackupTitle')),
+ h('p', { class: 'muted', style: 'margin:0' }, t('onbBackupBody')),
+ h('p', { class: 'muted', style: 'margin:0' }, t('seedIntroPrivate')),
+ h('button', { id: 'onb-backup-show', class: 'btn-primary btn-block', style: 'padding:14px', onClick: () => { o.backupShown = true; render(); } }, t('onbBackupShow')),
+ later,
+ ]);
+ }
return page([
title(t('onbBackupTitle')),
- h('p', { class: 'muted', style: 'margin:0' }, t('onbBackupBody')),
- h('div', { class: 'warn-box' }, t('writeDownWarn')),
h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) }, words.map((w, i) =>
h('div', { class: 'w' }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, w)))),
h('div', { class: 'row gap6' }, copyBtn(acc.mnemonic, t('copyPhrase'))),
h('button', { class: 'btn-primary btn-block', style: 'padding:14px', onClick: done }, t('onbBackupDone')),
- // Later means later, not never: seedSeen stays false, so the wallet
- // keeps a quiet reminder until the phrase has actually been seen.
- // Except on the way to a coinos.io move: the balance about to arrive
- // must have its twelve words written down first, so Later isn't offered.
- migrateLinkPending() ? null : h('button', { class: 'btn-ghost btn-block', onClick: () => {
- if (canOfferSpending()) { o.step = 'spend'; o.enterAddr = undefined; render(); return; }
- ui.onb = null;
- try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
- ui.account = 'savings';
- try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
- ui.tab = 'receive';
- render();
- } }, t('onbBackupLater')),
+ later,
]);
}
if (o.step === 'seed') {
@@ -4095,10 +4642,10 @@ function onboardScreen() {
// means seeing (or bringing) your seed phrase, not a wallet minted
// behind your back. Opening one ends the wizard into the wallet + tour.
return page([
- title(t('onbSeedTitle')),
+ title(t(ui.unlockTab === 'import' ? 'onbRestoreTitle' : 'onbSeedTitle')),
unlockCard(),
// the entropy page brings its own Back — one is enough
- ui.entropyPage ? null : h('button', { class: 'linklike small', onClick: () => { ui.unlockError = ''; o.step = 'welcome'; render(); } }, t('back')),
+ ui.entropyPage ? null : h('button', { class: 'linklike small', onClick: () => { if (createStepBack()) return; ui.unlockError = ''; o.step = ui.unlockTab === 'import' ? 'doors' : 'welcome'; render(); } }, t('back')),
]);
}
if (o.step === 'signin') {
@@ -4106,21 +4653,27 @@ function onboardScreen() {
h('div', { class: 'onb-mark', html: NOSTR_MARK }),
title(t('onbSigninTitle')),
featureHook('unlockExtra') || h('div', { class: 'notice err' }, 'nostr login unavailable'),
- h('button', { class: 'linklike small', onClick: () => { o.step = 'welcome'; render(); } }, t('back')),
+ h('button', { class: 'linklike small', onClick: () => { o.step = 'doors'; render(); } }, t('back')),
]);
}
if (o.step === 'spend') {
+ // A sign-up's name is the account itself — what people pay, follow and
+ // message — so it's claimed here, not skipped.
+ const signupAcc = activeAccount();
+ const signup = !o.fromGift && !!(signupAcc && signupAcc.signupAt && (signupAcc.kind === 'spending' || !signupAcc.kind));
return page([
- title(t('onbSpendTitle')),
- h('p', { class: 'muted', style: 'margin:0' }, t('onbSpendBody')),
+ title(t(o.fromGift ? 'onbGiftNameTitle' : signup ? 'onbNameTitle' : 'onbSpendTitle')),
+ h('p', { class: 'muted', style: 'margin:0' }, t(o.fromGift ? 'onbGiftNameBody' : signup ? 'onbNameBody' : '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.
- h('button', { class: 'btn-ghost btn-block', onClick: () => {
+ // Savings, the account that exists without any setup (or, after a
+ // gift, the account the gift arrived in).
+ signup ? null : 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')),
@@ -4273,7 +4826,8 @@ function onboardScreen() {
ui.tab = 'receive';
render();
} }, t('onbEnter')),
- h('button', { class: 'btn-ghost btn-block', onClick: () => { o.step = 'avatar'; render(); } }, t('back')),
+ // no Back: the name and the look are done, and both change anytime from
+ // the profile (Adam, 2026-11-15)
]);
}
@@ -4340,6 +4894,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 {}
@@ -4401,6 +4964,7 @@ function walletScreen() {
brandHeader(true),
h('div', { class: 'mt16' }, balanceCard()),
ui.offlineFallback && wallet.offline ? offlineBanner() : null,
+ safeBootNotice(),
backupNotice(),
...featureAll('walletNotices'),
tabsBar(),
@@ -4441,22 +5005,160 @@ wallet.registerCacheExtension({
},
});
+// ---- Savings, later --------------------------------------------------------
+// An account made by signing up is Spending alone (kind 'spending', marked
+// savingsLater): no on-chain face, no carousel, no Move money. Its owner adds
+// Savings from Settings → Wallet whenever they like — the same seed, account
+// 0, so it is the on-chain wallet that was always underneath. A balance must
+// never hide, so on-chain money or history arriving adds it by itself.
+function addSavings(acc, { quiet = false } = {}) {
+ if (!acc || acc.kind !== 'spending' || !acc.savingsLater) return false;
+ delete acc.kind; delete acc.savingsLater;
+ if (!acc.spendingSetup) acc.spendingSetup = Date.now();
+ acc.savingsAdded = Date.now();
+ persistAccounts();
+ if (acc.persisted) writeVault();
+ if (acc.id === activeId) { try { wallet.saveCache(); } catch {} }
+ if (!quiet) render();
+ return true;
+}
+function savingsEvident() {
+ const a = activeAccount();
+ if (!a || a.kind !== 'spending' || !a.savingsLater || !wallet.loaded) return;
+ // one balance: on-chain is part of the account from the start, nothing to add
+ if (!separateBalances()) { addSavings(a, { quiet: true }); return; }
+ if ((wallet.spendable || 0) > 0 || (wallet.pendingIncoming || 0) > 0 || (wallet.txs || []).length) addSavings(a, { quiet: true });
+}
+// The shape rides the synced snapshot, so the phone opens the account the
+// way the laptop has it: Spending-only until Savings is added on either.
+// Commutative: savingsAdded only ever turns on and wins over spendingOnly.
+wallet.registerCacheExtension({
+ mergeAlways: true,
+ save: () => {
+ const a = activeAccount();
+ if (!a) return {};
+ if (a.savingsAdded) return { savingsAdded: a.savingsAdded };
+ return a.kind === 'spending' && a.savingsLater ? { spendingOnly: true } : {};
+ },
+ load: (d) => {
+ const a = activeAccount();
+ if (!d || !a || a.type !== 'full' || a.deriveIndex) return;
+ if (d.savingsAdded) { if (addSavings(a, { quiet: true }) === false && !a.savingsAdded) { a.savingsAdded = d.savingsAdded; persistAccounts(); } return; }
+ if (d.spendingOnly && separateBalances() && !a.kind && !a.savingsAdded && !(wallet.txs || []).length && !(wallet.spendable || 0)) {
+ a.kind = 'spending'; a.savingsLater = true;
+ persistAccounts();
+ }
+ },
+});
+
+// ---- ways back in ----------------------------------------------------------
+// The sign-in methods that can open this account somewhere else, besides its
+// recovery phrase: a passkey, a Google account, a nostr identity — each holds
+// a copy of the seed encrypted to its own key on the relays (see the
+// nostrlogin feature's addRecovery). Listed on the account so Settings can
+// say what's set up; the list rides the synced snapshot, union by key.
+function recoveryMethods(a = activeAccount()) {
+ return (a && Array.isArray(a.recovery)) ? a.recovery : [];
+}
+function sameSeed(a, x) {
+ return x.mnemonic && x.mnemonic === a.mnemonic && (x.passphrase || '') === (a.passphrase || '');
+}
+function mergeRecovery(list) {
+ const a = activeAccount();
+ if (!a || !a.mnemonic || !Array.isArray(list) || !list.length) return false;
+ let changed = false;
+ for (const x of accounts) {
+ if (x !== a && !sameSeed(a, x)) continue;
+ const have = new Map(recoveryMethods(x).map((m) => [m.id, m]));
+ for (const m of list) if (m && m.id && !have.has(m.id)) { have.set(m.id, m); changed = true; }
+ x.recovery = [...have.values()].sort((p, q) => (p.at || 0) - (q.at || 0));
+ }
+ if (changed) { persistAccounts(); if (a.persisted) writeVault(); }
+ return changed;
+}
+function addRecoveryMethod(m) {
+ if (!mergeRecovery([{ ...m, at: m.at || Date.now() }])) return;
+ try { wallet.saveCache(); } catch {}
+ render();
+}
+wallet.registerCacheExtension({
+ mergeAlways: true,
+ save: () => {
+ const a = activeAccount(), r = recoveryMethods();
+ return { ...(r.length ? { recovery: r } : {}), ...(a && a.waysBackPrompted ? { waysBackPrompted: a.waysBackPrompted } : {}) };
+ },
+ load: (d) => {
+ if (!d) return;
+ if (d.recovery) mergeRecovery(d.recovery);
+ // asked on another device: asked (only ever turns on)
+ const a = activeAccount();
+ if (d.waysBackPrompted && a && !a.waysBackPrompted) { a.waysBackPrompted = d.waysBackPrompted; persistAccounts(); }
+ },
+});
+
+// A sign-up is asked for a way back in ONCE, and only when there's something
+// to lose (Adam, 2026-11-15: "only prompt to add a way back in after there's
+// some balance and only if we haven't prompted before"). The ask is recorded
+// the moment it first shows — on the account, the directory and the synced
+// snapshot — and stays up for that visit until Add one or Not now.
+function waysBackPrompt(a) {
+ if (recoveryMethods(a).length) { if (ui.waysBackPromptFor === a.id) ui.waysBackPromptFor = null; return null; }
+ if (ui.waysBackPromptFor !== a.id) {
+ if (a.waysBackPrompted || !wallet.loaded) return null;
+ const bal = (featureHook('spendingSat') || 0) + (wallet.spendable || 0) + (wallet.pendingIncoming || 0);
+ if (bal <= 0) return null;
+ a.waysBackPrompted = Date.now();
+ persistAccounts();
+ try { wallet.saveCache(); } catch {}
+ ui.waysBackPromptFor = a.id;
+ }
+ const done = () => { ui.waysBackPromptFor = null; };
+ return h('div', { class: 'notice info col ways-back-prompt', style: 'margin:12px 0 0;gap:10px' },
+ h('span', {}, t('waysBackPrompt')),
+ h('div', { class: 'row gap6' },
+ h('button', { class: 'btn-sm btn-primary', onClick: () => { done(); ui.tab = 'settings'; ui.settingsPage = 'wallet'; render(); } }, t('waysBackReminderGo')),
+ h('button', { class: 'btn-sm btn-ghost', onClick: () => { done(); render(); } }, t('onbNotNow'))));
+}
+
// A wallet whose recovery phrase has never been on screen keeps one quiet
// line about it. "Later" is a real answer, so this is a row and not a modal —
// but it doesn't dismiss, because the risk doesn't go away on its own. It
// disappears the moment the phrase is actually seen (here or in settings).
function backupNotice() {
+ savingsEvident();
const a = activeAccount();
if (!a || !a.mnemonic || a.seedSeen || wallet.watchOnly) return null;
+ // A sign-up never saw a phrase and wasn't asked to: what it needs is A way
+ // back in, any one — and once it has one, nothing to nag about.
+ const signup = !!a.signupAt;
+ if (signup) return waysBackPrompt(a);
return h('div', { class: 'small muted', style: 'margin:10px 0 0;text-align:center' },
- t('backupReminder'),
+ t(signup ? 'waysBackReminder' : 'backupReminder'),
' ',
h('button', { class: 'linklike small', onClick: () => {
ui.tab = 'settings';
ui.settingsPage = 'wallet';
- ui.revealShown = 'masked';
+ if (!signup) ui.revealShown = 'masked';
render();
- } }, t('backupReminderGo')));
+ } }, t(signup ? 'waysBackReminderGo' : 'backupReminderGo')));
+}
+
+// Safe mode (see BOOT_GUARD in build.js): the app crashed on open twice in a
+// row, so this boot made no automatic connections. Say so, name the phase
+// the last boot reached, and offer the way back.
+function safeBootNotice() {
+ if (!safeBoot()) return null;
+ const phase = (typeof window !== 'undefined' && window.__bootPhase) || '?';
+ const report = () => ['Coinos safe mode', 'build ' + (typeof window._v === 'string' ? window._v : '?'),
+ 'starts without a clean boot: ' + window.__safeBoot, 'last phase: ' + phase, navigator.userAgent].join('\n');
+ return h('div', { class: 'notice info col', style: 'margin:12px 0 0;gap:8px' },
+ h('b', {}, t('safeBootTitle')),
+ h('span', { class: 'small' }, t('safeBootBody', { n: window.__safeBoot - 1, phase })),
+ h('div', { class: 'row', style: 'gap:8px' },
+ h('button', { class: 'btn-sm', onClick: () => { bootSettled(); location.reload(); } }, t('safeBootOpen')),
+ h('button', { class: 'btn-sm', onClick: (e) => {
+ navigator.clipboard?.writeText(report()).then(() => { e.target.textContent = t('safeBootCopied'); }).catch(() => {});
+ } }, t('safeBootCopy'))));
}
function offlineBanner() {
@@ -4473,6 +5175,46 @@ function offlineBanner() {
// Lightning) or Savings (on-chain). The balance card headline, the Receive
// pane, and the gift source all follow it.
const ACCOUNT_KEY = 'btc-wallet-account';
+// One balance (Adam, 2026-11-15: "combine the Ark and savings Bitcoin
+// accounts into a single account … a combined history … the balance would
+// be unified"). A seed with both sides shows ONE account: the total, one
+// timeline (a move between the two is one row, priced at what it cost), and
+// Receive leading with the payment address, an on-chain address a tap away.
+// Money stays where it lands; a payment picks its coins by where it's going
+// (Lightning/Ark from the Ark coins, an on-chain address from on-chain coins
+// first). Settings → Wallet can still show the two apart, per device.
+const SEPARATE_KEY = 'btc-wallet-separate-balances';
+function separateBalances() {
+ try { return localStorage.getItem(SEPARATE_KEY) === '1'; } catch { return false; }
+}
+function setSeparateBalances(on) {
+ try { on ? localStorage.setItem(SEPARATE_KEY, '1') : localStorage.removeItem(SEPARATE_KEY); } catch {}
+}
+// The one balance's breakdown (Ark / On-chain / Gifts) folds away under its
+// total by default (Adam, 2026-11-16); opening it is remembered per device.
+const BREAKDOWN_KEY = 'btc-wallet-balance-breakdown';
+function breakdownOpen() {
+ try { return localStorage.getItem(BREAKDOWN_KEY) === '1'; } catch { return false; }
+}
+function setBreakdownOpen(on) {
+ try { on ? localStorage.setItem(BREAKDOWN_KEY, '1') : localStorage.removeItem(BREAKDOWN_KEY); } catch {}
+}
+function unifiedOn(a = activeAccount()) {
+ return !!a && !a.kind && a.type === 'full' && !separateBalances() && spendingActive();
+}
+// History rows, both rails merged: on-chain transactions plus the features'
+// entries. A feature row can stand in for an on-chain transaction
+// (`replacesTxid` — a board or an offboard to our own address, told once).
+function historyEntriesFor(sel) {
+ const all = sel === 'spending' ? [] : wallet.history || [];
+ const feat = featureAll('historyEntries', all, sel);
+ const replaced = new Set(feat.map((e) => e.replacesTxid).filter(Boolean));
+ const txs = replaced.size ? all.filter((tx) => !replaced.has(tx.txid)) : all;
+ return [
+ ...txs.map((tx) => ({ time: tx.confirmed ? (tx.blockTime || 0) * 1000 : Date.now(), render: () => txHistoryItem(tx) })),
+ ...feat,
+ ].sort((a, b) => b.time - a.time);
+}
// Spending is opt-in: a wallet is born on-chain only, and the second balance
// (with its toggle, swipe, and Move money) appears once the user sets it up —
// or the moment money is already there (a restored wallet, a claimed gift),
@@ -4530,6 +5272,7 @@ function seedName(a) {
}
function viewLabel(a, view) {
if (a && a.viewLabels && a.viewLabels[view]) return a.viewLabels[view];
+ if (view === 'all') return t('balance');
return view === 'spending' ? t('spendingName') : t('savingsName');
}
function switchToView(id, view) {
@@ -4546,6 +5289,9 @@ function switchToView(id, view) {
function accountSel() {
const a = activeAccount();
if (a && a.kind) return a.kind; // single-purpose wallet: no other side
+ // one balance: payments start from the Ark coins; the send flow picks
+ // on-chain coins for an on-chain address itself (ark.js matchSend)
+ if (unifiedOn(a)) return 'spending';
if (!spendingActive()) return 'savings'; // one balance, no choice
if (!ui.account) {
let saved = null;
@@ -4582,12 +5328,9 @@ function walletSide() {
const toWallet = (tab) => { goHome(); ui.tab = tab; render(); };
const spending = featureHook('spendingSat') || 0;
const saving = wallet.spendable || 0;
- const sel = accountSel();
- const txs = sel === 'spending' ? [] : wallet.history || [];
- const entries = wallet.loaded ? [
- ...txs.map((tx) => ({ time: tx.confirmed ? (tx.blockTime || 0) * 1000 : Date.now(), render: () => txHistoryItem(tx) })),
- ...featureAll('historyEntries', txs, sel),
- ].sort((a, b) => b.time - a.time).slice(0, 6) : [];
+ const unified = unifiedOn();
+ const sel = unified ? 'all' : accountSel();
+ const entries = wallet.loaded ? historyEntriesFor(sel).slice(0, 6) : [];
const rows = entries.map((e) => {
const row = e.render();
// a row opens its detail on the wallet page: go there first
@@ -4602,8 +5345,8 @@ function walletSide() {
h('button', { type: 'button', class: 'wallet-side-total', onClick: () => toWallet('history') },
h('span', { class: 'small muted' }, t('balance')),
h('span', { class: 'wallet-side-amount' }, wallet.loaded ? fmtAmount(spending + saving) + ' ' + unitLabel() : '…')),
- spendingActive() ? line(t('spendingLabel'), spending) : null,
- spendingActive() ? line(t('savingLabel'), saving) : null,
+ spendingActive() && (!unified || (spending > 0 && saving > 0 && breakdownOpen())) ? line(unified ? t('balInstant') : t('spendingLabel'), spending) : null,
+ spendingActive() && (!unified || (spending > 0 && saving > 0 && breakdownOpen())) ? line(unified ? t('balOnchain') : t('savingLabel'), saving) : null,
h('div', { class: 'row gap6' },
h('button', { type: 'button', class: 'btn-primary grow', onClick: () => toWallet('receive') }, t('tabReceive')),
h('button', { type: 'button', class: 'btn-primary grow', onClick: () => toWallet('send') }, t('tabSend')))),
@@ -4662,7 +5405,9 @@ function balanceCard() {
})
: null,
h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em' },
- kindLocked ? viewLabel(acc0, view)
+ // a lone balance needs no name: blank unless its owner gave it
+ // one (Adam, 2026-11-15); the two-face carousel keeps its labels
+ kindLocked ? ((acc0.viewLabels && acc0.viewLabels[view]) || '')
: hasSpending ? (viewSpending ? t('spendingLabel') : t('savingLabel')) : t('balance'))),
manageBtn(view)),
h('div', { class: 'amt', style: firstLoad ? 'opacity:.3' : '' },
@@ -4712,7 +5457,7 @@ function balanceCard() {
try { localStorage.setItem(ACCOUNT_KEY, 'spending'); } catch {}
}
ui.arkMoveDir = 'toSpending'; ui.arkMoveOpen = true; render();
- } }, t('topUpFromSavings'))
+ } }, unifiedOn() ? t('topUpInstant') : t('topUpFromSavings'))
: null,
!hasSpending && !kindLocked && featureHook('arkReady') && !wallet.watchOnly && acc0 && acc0.type === 'full'
&& featureHook('namesSettled') !== 'pending' // a restoring name may prove Spending any second — don't flash the setup ask
@@ -4737,6 +5482,42 @@ function balanceCard() {
return w;
})(),
];
+ // One account: one face with everything on it. Where it sits shows only
+ // when it's in both places (instant Ark coins, on-chain coins) — and every
+ // line under the figure (pending, moving, locked in gifts) belongs to it.
+ if (unifiedOn()) {
+ // the breakdown (where it sits, what gifts hold) folds away behind a
+ // toggle; what's on its way (pending, moving) always shows
+ const split = (spending > 0 && saving > 0
+ ? [{ label: t('balInstant'), sat: spending }, { label: t('balOnchain'), sat: saving }] : [])
+ .concat(featLines.filter((l) => l.part));
+ const open = breakdownOpen();
+ const lines = (open ? split : [])
+ .concat(pending > 0 ? [{ label: t('pending'), sat: pending, cls: 'v pending' }] : [])
+ .concat(featLines.filter((l) => !l.part));
+ const toggle = split.length
+ ? h('button', { type: 'button', class: 'linklike small breakdown-toggle', 'aria-expanded': open ? 'true' : 'false',
+ onClick: () => { setBreakdownOpen(!open); render(); } },
+ open ? t('hideBreakdown') + ' ▴' : t('showBreakdown') + ' ▾')
+ : null;
+ _accDir = null;
+ return h('div', { class: 'card balance balance-one' },
+ h('div', { class: 'balance-face' },
+ h('div', { class: 'row between', style: 'align-items:center' },
+ h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em' },
+ (acc0.viewLabels && acc0.viewLabels.all) || ''),
+ manageBtn('all')),
+ h('div', { class: 'amt', style: firstLoad ? 'opacity:.3' : '' },
+ firstLoad ? h('span', { class: 'spinner sm', style: 'margin-right:8px' }) : null,
+ // mid-board money is still this account's: it counts, and its Moving line says where it is
+ animatedAmount('bal:all', spending + (saving || 0) + (featureHook('spendingBoardingSat') || 0)), ' ', unitTag('unit')),
+ lines.length
+ ? h('div', { class: 'split' },
+ ...lines.map((l) => h('div', {}, h('div', { class: 'k' }, l.label), h('div', { class: l.cls || 'v' }, fmtAmount(l.sat), ' ', unitTag()))))
+ : null,
+ toggle),
+ ...cardExtras('spending'));
+ }
const carouselMode = hasSpending && !kindLocked;
if (carouselMode) {
// Two SEPARATE cards side by side — the neighbor card peeks past the
@@ -5030,6 +5811,7 @@ function tabsBar() {
tabBtn(label, ui.tab === id, () => {
ui.tab = ui.tab === id ? 'history' : id;
ui.sendError = ''; // a stale send error never survives a tab change
+ ui.recvOnchain = false; // Receive opens on the payment address again
ui.revealShown = false; // re-mask the recovery phrase whenever tabs change
ui.nostrExportStep = false; // and the exported nostr key
ui.txDetail = null; // back to the history list when leaving/returning
@@ -5095,7 +5877,8 @@ function tabContent() {
if (ui.tab === 'send' && sendFocused) return pane;
return h('div', { class: 'col', style: 'gap:16px' },
pane,
- h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em;margin-top:4px' }, t('tabHistory')),
+ // no heading over nothing: it comes with the first payment
+ hist ? h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em;margin-top:4px' }, t('tabHistory')) : null,
hist);
}
@@ -5123,6 +5906,11 @@ function iconGlyph(ic) {
: h('span', { class: 'sel-ico' }, ic);
}
+// One account's Receive: the door to an on-chain address under the payment one.
+function receiveOnchainBtn() {
+ if (!unifiedOn() || wallet.watchOnly) return null;
+ return h('button', { class: 'btn-block', id: 'recv-onchain', onClick: () => { ui.recvOnchain = true; render(); } }, t('recvOnchain'));
+}
function receiveTab() {
// Feature takeovers: boarding success, Ark receive celebration, etc.
const takeover = featureHook('receiveTakeover');
@@ -5161,6 +5949,17 @@ function receiveTab() {
// (receives Ark and Lightning), Savings shows a fresh on-chain address.
const fresh = wallet.freshReceive();
const nameMode = featureAll('receiveModes').find((m) => m.id === 'name');
+ // One account: the payment address leads, an on-chain address is a tap
+ // away (and is all there is offline). What arrives on-chain stays on-chain.
+ if (unifiedOn() && (ui.recvOnchain || wallet.offline)) {
+ return h('div', { class: 'card col', style: 'align-items:center;gap:14px' },
+ wallet.offline ? h('div', { class: 'notice info', style: 'width:100%' }, t('receiveOfflineOnchain')) : null,
+ h('div', { html: qrSvg(fresh.address) }),
+ h('div', { class: 'addr-box', style: 'width:100%' }, fresh.address),
+ copyBtn(fresh.address, t('copyAddress')),
+ h('div', { class: 'small muted', style: 'text-align:center' }, t('recvOnchainNote')),
+ wallet.offline ? null : h('button', { class: 'btn-block', id: 'recv-payaddr', onClick: () => { ui.recvOnchain = false; render(); } }, t('recvPaymentAddress')));
+ }
if (accountSel() === 'spending') {
// Spending needs the network (registrar + ark); offline, offer the
// on-chain path right here instead of an endless spinner.
@@ -5183,7 +5982,9 @@ function receiveTab() {
{ class: 'card col', style: 'align-items:center;gap:14px' },
h('div', { html: qrSvg(ui.arkRecvAddr) }),
h('div', { class: 'addr-box break', style: 'width:100%' }, ui.arkRecvAddr),
- copyBtn(ui.arkRecvAddr, t('copyAddress'))
+ copyBtn(ui.arkRecvAddr, t('copyAddress')),
+ featureHook('posAvailable') ? h('button', { class: 'btn-block', id: 'recv-amount', onClick: () => featureHook('openAmountRequest') }, t('recvAmount')) : null,
+ receiveOnchainBtn()
);
}
}
@@ -5291,15 +6092,21 @@ function handleScanned(raw) {
if (featureMatchSend(text)) return;
if (/^bitcoin:/i.test(text)) {
- const { address, amount } = parseBip21(text);
+ const { address, sats } = parseBip21(text);
if (!address) {
ui.sendError = t('scanUnrecognized');
render();
return;
}
s.recipients[0].address = address;
- if (amount != null) {
- s.recipients[0].amount = amount;
+ if (sats != null) {
+ // A request's amount is written in BTC, so the form shows it in BTC,
+ // whatever unit was chosen: with dollars selected the BTC figure used
+ // to land in the box as it was and read as that many dollars ("it
+ // should always switch over to BTC as the units if I'm scanning a
+ // BIP21 URL like that", Adam, 2026-11-22).
+ setUnit('btc');
+ s.recipients[0].amount = amountField(sats);
s.max = false;
}
render();
@@ -5324,21 +6131,18 @@ function handleScanned(raw) {
render();
}
-// bitcoin:<address>?amount=<btc>&label=... — amount is in BTC; convert to the
-// current display unit so it lands in the form's amount field correctly.
+// bitcoin:<address>?amount=<btc>&label=... — amount is in BTC; handed back
+// in sats.
function parseBip21(uri) {
const m = /^bitcoin:([^?]*)(?:\?(.*))?$/i.exec(uri.trim());
if (!m) return {};
const address = decodeURIComponent((m[1] || '').trim());
- let amount = null;
+ let sats = null;
if (m[2]) {
const amt = new URLSearchParams(m[2]).get('amount');
- if (amt && isFinite(Number(amt)) && Number(amt) > 0) {
- const sats = Math.round(Number(amt) * SATS);
- amount = unit === 'sats' ? String(sats) : String(Number(amt));
- }
+ if (amt && isFinite(Number(amt)) && Number(amt) > 0) sats = Math.round(Number(amt) * SATS);
}
- return { address, amount };
+ return { address, sats };
}
function broadcastConfirmView() {
@@ -6109,7 +6913,7 @@ function historyTab() {
// ledger (BIP84 txs, silent-payment receipts, gift reservations), Spending
// shows the ark side (receives, sends, boards, LN) — each card of the
// carousel owns its own timeline.
- const histSel = accountSel();
+ const histSel = unifiedOn() ? 'all' : accountSel();
const txs = histSel === 'spending' ? [] : wallet.history; // newest first
const featDetail = featureHook('historyDetail');
if (featDetail) return featDetail;
@@ -6127,15 +6931,11 @@ function historyTab() {
h('span', { class: 'spinner' }),
wallet.historyLoading ? h('p', { class: 'small muted', style: 'margin:0' }, t('loadingHistory')) : null
);
- const featEntries = featureAll('historyEntries', txs, histSel);
- if (!txs.length && !featEntries.length)
- return h('div', { class: 'card' }, h('p', { class: 'muted center', style: 'margin:0' }, t('noTxYet')));
-
// Transactions and feature entries merge into one timeline.
- const entries = [
- ...txs.map((tx) => ({ time: tx.confirmed ? (tx.blockTime || 0) * 1000 : Date.now(), render: () => txHistoryItem(tx) })),
- ...featEntries,
- ].sort((a, b) => b.time - a.time);
+ const entries = historyEntriesFor(histSel);
+ // nothing yet: no card at all, it appears with the first payment
+ // (Adam, 2026-11-15: "let's not show an empty history section")
+ if (!entries.length) return null;
const txPages = Math.ceil(entries.length / PAGE_SIZE);
const txPage = Math.min(ui.txPage, Math.max(0, txPages - 1));
const txSlice = entries.slice(txPage * PAGE_SIZE, txPage * PAGE_SIZE + PAGE_SIZE);
@@ -6336,6 +7136,8 @@ const ctx = {
// support) — lazy so it resolves against the final FEATURES list, and a
// build without the target feature simply gets null back
hook: (name, ...args) => featureHook(name, ...args),
+ // boot is about to open a wallet (a page may paint as that wallet's already)
+ restorePending,
// full sign-out (distinct from the padlock's lock-in-place): clear the
// session and leave — offering a password if none protects the vault yet
logout: () => {
@@ -6361,7 +7163,18 @@ const ctx = {
shownPubkey: () => (featureHook('nostrLoginIdentity') || {}).pubkey
|| (wallet.nostrPubkey && wallet.nostrPubkey()) || (activeAccount() || {}).nostrPk || null,
getAccount: () => accountSel(),
+ unifiedBalance: () => unifiedOn(),
+ receiveOnchainBtn: () => receiveOnchainBtn(),
setAccount: (a, dir) => setAccountSel(a, dir),
+ offerProfileSetup, pickConfirm,
+ // the ways back in (Settings → Wallet): what's set up, and adding one
+ recoveryMethods: () => recoveryMethods(), addRecoveryMethod,
+ spendingOnlyAccount: () => { const a = activeAccount(); return !!(a && a.kind === 'spending' && a.savingsLater); },
+ seedSeen: () => !!(activeAccount() || {}).seedSeen,
+ showRecoveryPhrase: () => {
+ ui.tab = 'settings'; ui.settingsPage = 'wallet'; ui.revealShown = ui.revealShown || 'masked'; render();
+ requestAnimationFrame(() => { try { document.querySelector('.recovery-card')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch {} });
+ },
// 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
@@ -6409,6 +7222,10 @@ const BOOT_POS = (() => {
} catch { return false; }
})();
if (BOOT_POS) ui.posAtBoot = true;
+// v3.coinos.io/hats: the hat shop, a link to hand someone who asks where
+// the hats are. Opened once a wallet is up (the hats feature's init); the
+// bar says /hats while the shop is on screen, so it can be copied from there.
+try { if (/^\/hats\/?$/i.test(location.pathname)) ui.hatsAtBoot = true; } catch {}
// v3.coinos.io/migrate: a link to hand someone who hasn't found the
// coinos.io move in the UI. Stashed (not just flagged) because the page it
// leads to needs an open wallet and a payment address — a fresh device gets
@@ -6612,9 +7429,8 @@ if (INTENT_URI) {
// The feed scrolls like a phone on a desktop. A mouse wheel's notch gives
// it a push that coasts and slows, so a few turns travel a few posts and
// quick turns stack up; a trackpad (which already coasts) is left alone.
-// And a mouse can grab the feed and flick it: drag up or down, let go while
-// moving and it keeps going. A drag that starts sideways is still a text
-// selection, and a drag that moved isn't a click on what it started on.
+// (A mouse drag used to grab the feed and flick it; it selects text again —
+// Adam, 2026-10-18: "i'd rather be able to select text normally".)
(() => {
if (typeof window === 'undefined' || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
// The wheel coasts whenever a feed or a thread is the page being scrolled
@@ -6736,49 +7552,7 @@ if (INTENT_URI) {
// anything else that moves the page takes over from a coast
window.addEventListener('keydown', (e) => { if (/^(Arrow|Page|Home|End| )/.test(e.key)) stop(); });
window.addEventListener('touchstart', stop, { passive: true });
- // ---- grab and flick
- let drag = null;
- document.addEventListener('pointerdown', (e) => {
- if (raf) stop(); // a click catches a coasting page, like a finger does
- if (e.pointerType !== 'mouse' || e.button !== 0 || !inScope(e.target)) return;
- drag = { x: e.clientX, y: e.clientY, ly: e.clientY, on: false, pts: [] };
- });
- document.addEventListener('dragstart', (e) => { if (drag) e.preventDefault(); }, true); // images/links: scroll, don't drag them out
- document.addEventListener('pointermove', (e) => {
- if (!drag) return;
- if (!(e.buttons & 1)) { drag = null; return; }
- if (drag.sel) return;
- if (!drag.on) {
- const dx = Math.abs(e.clientX - drag.x), dy = Math.abs(e.clientY - drag.y);
- if (dx < 6 && dy < 6) return;
- // clearly sideways: selecting text (and still not a click on the post)
- if (dx > 2 * dy) { drag.sel = true; return; }
- drag.on = true;
- document.documentElement.classList.add('grab-scrolling');
- try { getSelection().removeAllRanges(); } catch {}
- }
- window.scrollBy({ top: drag.ly - e.clientY, behavior: 'instant' });
- drag.ly = e.clientY;
- drag.pts.push([e.timeStamp, e.clientY]);
- while (drag.pts.length > 2 && e.timeStamp - drag.pts[0][0] > 100) drag.pts.shift();
- });
- const end = (e) => {
- if (!drag) return;
- const d = drag; drag = null;
- if (!d.on && !d.sel) return;
- if (d.on) {
- document.documentElement.classList.remove('grab-scrolling');
- const p = d.pts, a = p[0], b = p[p.length - 1];
- // released while moving: throw it; held still first: just let go
- if (a && b && b[0] > a[0] && e.timeStamp - b[0] < 60) coast((a[1] - b[1]) / (b[0] - a[0]) * 2.4);
- }
- // the press moved: what it started on isn't opened (Chrome still clicks it)
- const eat = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
- document.addEventListener('click', eat, { capture: true, once: true });
- setTimeout(() => document.removeEventListener('click', eat, { capture: true }), 300);
- };
- document.addEventListener('pointerup', end);
- document.addEventListener('pointercancel', () => { if (drag?.on) document.documentElement.classList.remove('grab-scrolling'); drag = null; });
+ document.addEventListener('pointerdown', () => { if (raf) stop(); }); // a click catches a coasting page, like a finger does
})();
window.addEventListener('load', () => {
@@ -6790,6 +7564,7 @@ window.addEventListener('load', () => {
}, 1000);
});
loadLocale(getLang()).finally(async () => {
+ bootPhase('boot');
applyBootAutoLogout(); // clear an overdue session before we read it for claim targets
// Public read-only community chat: no wallet, no login — the join material
// ships in the bundle, so the page decrypts client-side (src/public-chat.js).
@@ -6815,16 +7590,21 @@ loadLocale(getLang()).finally(async () => {
// and a wallet opening in fiat should open with a number in it.
refreshRates().then(() => { if (unit === 'fiat') render(); }).catch(() => {});
setInterval(() => { refreshRates().then(() => { if (unit === 'fiat') render(); }).catch(() => {}); }, 10 * 60_000);
+ bootPhase('store');
const storeReady = featureHook('arkStoreReady');
// the IndexedDB caches (profiles, reports, …) open alongside: a wallet's
// caches are read as soon as it opens
- await Promise.all([storeReady, cacheReady()].filter(Boolean)).catch(() => {});
+ await Promise.all([storeReady, cacheReady(), warmBootSeeds()].filter(Boolean)).catch(() => {});
// Ask the browser not to evict this site's storage under disk pressure.
// Chrome answers without a prompt (yes for an installed or busy site).
try { navigator.storage?.persist?.().catch(() => {}); } catch {}
_bootDeciding = false; // from here on the screen is a decision, not a guess
const opened = restoreAccountsState();
- if (!opened) render();
+ _restorePending = false;
+ if (!opened || !activeAccount()) render();
+ bootPhase('ui');
+ initPullRefresh(); // the app and the Beta have no browser pull-to-refresh
+ setTimeout(bootSettled, 8000);
if (WAKE_PAYLOAD != null) {
// Nothing opened — a locked vault, or no wallet on this device. There is
// nothing to answer with, so say so now.
diff --git a/src/ark/manager.js b/src/ark/manager.js
index d5ae2b0..8be9d58 100644
--- a/src/ark/manager.js
+++ b/src/ark/manager.js
@@ -41,7 +41,7 @@ import {
} from './board.js';
import {
submitRoundParticipation, roundParticipationStatus, parseTx,
- cosignHarkLeaf, requestForfeitNonces, forfeitBundle, forfeitVtxos,
+ cosignHarkLeaf, requestForfeitNonces, forfeitBundle, forfeitVtxos, checkRoundOutputs,
encodeVtxoFromDecoded,
} from './refresh.js';
import {
@@ -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);
@@ -119,6 +129,24 @@ export function lnFoldedIds(movements) {
}
if (best) out.add(best.id);
}
+ // A Lightning payment the closed app's worker made is told twice once the
+ // app opens: the worker's own ln-send row (merged in from the mirror) and
+ // the "while closed" note the app adds from the worker's spend log. Per
+ // preimage (or payment hash), keep the row that names its inputs — the
+ // manager's — else the earliest.
+ const sends = (movements || []).filter((m) => m.type === 'ln-send' && m.status === 'complete' && (m.preimage || m.paymentHash));
+ const keyOf = new Map(); // payment hash → the preimage key, where a row knows both
+ for (const s of sends) if (s.preimage && s.paymentHash) keyOf.set(s.paymentHash, 'p:' + s.preimage);
+ const byPay = new Map();
+ for (const s of sends) {
+ const k = s.preimage ? 'p:' + s.preimage : (keyOf.get(s.paymentHash) || 'h:' + s.paymentHash);
+ (byPay.get(k) || byPay.set(k, []).get(k)).push(s);
+ }
+ for (const rows of byPay.values()) {
+ if (rows.length < 2) continue;
+ const keep = rows.find((r) => r.inputIds && r.inputIds.length) || rows.reduce((a, b) => ((a.ts || 0) <= (b.ts || 0) ? a : b));
+ for (const r of rows) if (r !== keep) out.add(r.id);
+ }
return out;
}
@@ -177,9 +205,46 @@ export function pruneArkState(state, now = Date.now()) {
// Shared by the app (features/ark.js) and the worker tending a closed wallet.
export const backstopMargin = (network) => (network === 'regtest' ? 6 : 36);
+// Custody tiers — what a coin's timelock means to this wallet:
+// custodial nothing renews. The coinos server keeps honoring a coin past
+// its timelock (it has swept the tree; the coin is its IOU), so
+// the balance works like a v2 one, and no renewal is ever paid.
+// self renew in the last hours before expiry — the free ppm bracket,
+// one base fee per round — so a unilateral exit is always there.
+// exit the same, plus: renew a coin as soon as its history runs
+// `maxDepth` hops deep. A unilateral exit publishes one on-chain
+// transaction per hop, so depth — not age — is what makes an
+// exit expensive; a renewal flattens it to one hop. Early, so
+// the top ppm bracket + base; only for a coin worth it (the fee
+// under a tenth of its value — see maybeAutoRefresh).
+// A policy is { window, margin, grid } in blocks: the app renews a coin with
+// under `window` blocks left; the server-side backstop is registered `margin`
+// blocks before expiry, snapped DOWN to a multiple of `grid` so everyone's
+// orders land in the same round (one round's mining fee shared, not one per
+// coin). The snapped height stays inside the free bracket: 36–83 blocks out.
+export const CUSTODY_TIERS = ['custodial', 'self', 'exit'];
+export const MAX_SEND_INPUTS = 48;
+export function renewPolicy(tier, network) {
+ const rt = network === 'regtest';
+ const self = { window: rt ? 24 : 96, margin: backstopMargin(network), grid: rt ? 1 : 48 };
+ // 'early' was the third tier for a day (2026-10-22): a week-ahead renewal,
+ // which flattens the same history a last-hours one does — mirrors may
+ // still carry the name
+ if (tier === 'exit' || tier === 'early') return { ...self, maxDepth: 4 };
+ if (tier === 'self') return self;
+ return null;
+}
+
export class ArkManager {
- constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint }) {
+ constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint, honorsExpired = false, infoHint = null, lnOldestFirst }) {
this.account = account; // HDKey node; ark keys derived beneath it
+ // The server's last published info, kept by the app: lets the wallet open
+ // when the server can't be reached (see init)
+ this.infoHint = infoHint || null;
+ this.offline = false;
+ // the server cosigns spends of a coin past its timelock (coinos): such a
+ // coin stays money here — spendable, receivable — just not exitable
+ this.honorsExpired = !!honorsExpired;
this.storage = storage; // { load(): obj|null, save(obj): void }
this.arkUrl = arkUrl;
this.esploraUrl = esploraUrl;
@@ -193,6 +258,9 @@ export class ArkManager {
: network === 'mutinynet' ? 'https://names.halwallet.app/lnquote?network=mutinynet'
: null;
this.onUpdate = onUpdate || (() => {});
+ // () => true when this wallet renews its own coins (custody tier self or
+ // exit): a Lightning send then spends the coins nearest expiry first
+ this.lnOldestFirst = lnOldestFirst || (() => false);
this.state = null;
this.info = null;
this._lnDriving = new Set(); // re-entrancy guard: sync poll vs UI fast-poll vs mailbox push
@@ -222,6 +290,14 @@ export class ArkManager {
return (this._mbKey = { privkey: node.privateKey, pubkey: secp256k1.getPublicKey(node.privateKey, true) });
}
_keyForVtxo(v) { return this._key(v.keyIndex); }
+ // Which of this wallet's keys a coin is paid to: 0 is the receive key,
+ // the rest were handed out one per payment, change or refund. -1: not ours.
+ _ownKeyIndex(pubkeyHex) {
+ if (pubkeyHex === hex.encode(this._key(0).pubkey)) return 0;
+ const n = (this.state.nextKeyIndex || 1) + 64;
+ for (let i = 1; i < n; i++) if (hex.encode(this._key(i).pubkey) === pubkeyHex) return i;
+ return -1;
+ }
// ---- lifecycle ----
async init() {
@@ -242,8 +318,23 @@ export class ArkManager {
seen.add(m.vtxoId);
return true;
});
- this.info = await getArkInfo(this.arkUrl);
- const hs = await handshake(this.arkUrl).catch(() => null);
+ // (the handshake goes out beside the info call, not after it: a wake of
+ // the phone's worker pays for every round trip in the zap it answers)
+ const hsP = handshake(this.arkUrl).catch(() => null);
+ try {
+ this.info = await getArkInfo(this.arkUrl);
+ this.offline = false;
+ } catch (e) {
+ // The server is unreachable. With its last published info in hand the
+ // wallet still opens on its own records: coins read, a unilateral exit
+ // can start (that needs the chain, not the server), and anything that
+ // does need the server fails when it asks. Without that info there is
+ // no server key to check anything against — then it really is closed.
+ if (!this.infoHint) throw e;
+ this.info = this.infoHint;
+ this.offline = true;
+ }
+ const hs = await hsP;
this.psa = hs?.psa;
this.serverPub = hex.decode(this.info.serverPubkey);
@@ -307,6 +398,20 @@ export class ArkManager {
return Date.now() - age * 600_000;
}
+ // The tip for a payment about to be built: one asked for moments ago (a
+ // worker warms it while the manager starts) is as good as asking again.
+ warmTip() {
+ const p = this.chain.tipHeight().then((h) => { this._tipH = h; this._tipAt = Date.now(); this._tipNow = Date.now(); return h; });
+ this._tipWarm = p;
+ p.catch(() => {}).finally(() => { if (this._tipWarm === p) this._tipWarm = null; });
+ return p;
+ }
+ async _tipFresh() {
+ if (this._tipNow && Date.now() - this._tipNow < 5000 && this._tipH) return this._tipH;
+ if (this._tipWarm) { try { return await this._tipWarm; } catch { /* ask again */ } }
+ return this.chain.tipHeight();
+ }
+
async _tipMemo() {
if (this._tipAt && Date.now() - this._tipAt < 60_000) return this._tipH;
try {
@@ -417,7 +522,9 @@ export class ArkManager {
// the exception — they have no unilateral exit to protect and the coinos ASP
// keeps honoring them off-chain (mirrors validateVtxo's carve-out).
_expired(v, tip) {
- return !!v.expiryRejected || (!!tip && !!v.expiryHeight && v.amountSat >= 330 && v.expiryHeight <= tip);
+ if (v.expiryRejected) return true; // the server said no to this one
+ if (this.honorsExpired) return false;
+ return !!tip && !!v.expiryHeight && v.amountSat >= 330 && v.expiryHeight <= tip;
}
// The dust exemption is not a promise that every old coin will be
@@ -462,6 +569,34 @@ export class ArkManager {
// free to spend, renew or exit from THIS device
_free(v, busy = this._remoteBusy()) { return !!v && v.state === 'spendable' && !busy.has(v.id) && this._policyType(v) === 'pubkey'; }
+ // A coin's exit depth: one transaction per hop of its history (the round
+ // tree's branch, then every arkoor transfer). Each off-chain payment adds
+ // one to the change and one to what the recipient gets; only a round
+ // flattens it. The server refuses to cosign a spend of a coin at its
+ // `maxVtxoExitDepth` (100 on coinos: a wallet paying hourly from one change
+ // chain gets there in four days), so such a coin is money only a refresh
+ // can free — and it refreshes without the base fee at `deepWaiverDepth`.
+ exitDepth(v) { try { return this._decoded(v).genesis.length; } catch { return 0; } }
+ // a server before 0.9.0 wants the old dust split (see isolateDust)
+ _legacyDust() { return !(this.info && this.info.maxRoundParticipationOutputs); }
+ _capDepth() { return (this.info && this.info.maxVtxoExitDepth) || 0; }
+ _waiverDepth() { return (this.info && this.info.refreshFees && this.info.refreshFees.deepWaiverDepth) || 0; }
+ _capped(v) { const cap = this._capDepth(); return !!cap && this.exitDepth(v) >= cap; }
+ // The free coins a refresh should flatten now: at the server's waiver depth
+ // (no base fee, so always worth it), or within a few hops of the cap on a
+ // server without one (stuck otherwise). Expired coins too: a round is the
+ // one thing an expired coin can always do, and the server honors it.
+ deepCoins() {
+ const waiver = this._waiverDepth(), cap = this._capDepth();
+ if (!waiver && !cap) return [];
+ const busy = this._remoteBusy();
+ return this.state.vtxos.filter((v) => {
+ if (!this._free(v, busy)) return false;
+ const d = this.exitDepth(v);
+ return (waiver && d >= waiver) || (cap && d >= cap - 8);
+ });
+ }
+
balance() {
const tip = this._tipH || 0;
const busy = this._remoteBusy();
@@ -508,6 +643,11 @@ export class ArkManager {
this._lnRescanned = true;
try { if (await this.rescanLnReceives()) await this._save(); } catch (e) { this._lnRescanned = false; }
}
+ if (!this._expiredRescanned) {
+ this._expiredRescanned = true;
+ try { if (await this.rescanRejectedExpired()) this._save(); } catch (e) { this._expiredRescanned = false; }
+ try { if (await this.rescanOwnKeyRejects()) this._save(); } catch (e) { this._ownKeyRescanned = false; }
+ }
const baselining = !!this.state.baselinePending;
// keep the cached tip fresh: balance() and input selection judge coin
// expiry against it synchronously, and a stale tip hides dead coins
@@ -570,6 +710,97 @@ export class ArkManager {
}
}
+ // On a server that honors coins past their timelock, the ones this wallet
+ // wrote off before it knew that are still its money:
+ // - receives an older build refused at pickup ("vtxo expired at …"),
+ // recorded as rejected and left behind the mailbox cursor — the
+ // forwards stranded that way before 2026-08-24 among them;
+ // - coins the server once refused to spend (expiryRejected, from before
+ // allow_expired_arkoor), and expired dust the user gave up (Forget).
+ // Once per wallet: re-read the mailbox from the start and adopt what the
+ // server still reports spendable; clear the old verdicts the same way. The
+ // cursor is left where it is. Returns whether anything changed.
+ // A coin to one of our own keys other than the receive key, refused at
+ // pickup by a build that took only key 0 ("vtxo not paid to one of our
+ // keys") and left behind the mailbox cursor. Re-read the mailbox from the
+ // start, once a session while such a refusal is on record, and adopt what
+ // the server still holds for us.
+ async rescanOwnKeyRejects() {
+ const rejected = (this.state.movements || []).filter((m) => m.type === 'receive' && m.status === 'rejected' && /not paid to one of our keys/i.test(m.detail || ''));
+ if (!rejected.length || this._ownKeyRescanned) return false;
+ this._ownKeyRescanned = true;
+ let changed = false;
+ const adopted = [];
+ let checkpoint = 0;
+ for (let page = 0; page < 50; page++) {
+ const { messages, haveMore } = await readMailbox(this.arkUrl, this._mailboxKey(), checkpoint);
+ for (const m of messages) {
+ checkpoint = Math.max(checkpoint, m.checkpoint || 0);
+ if (m.kind !== 'arkoor') continue;
+ const fresh = [];
+ for (const v of m.vtxos) {
+ if (this._vtxo(v.id)) continue;
+ const idx = this._ownKeyIndex(v.policy.userPubkey);
+ if (idx < 1) continue;
+ let status = 0;
+ try { status = await getVtxoStatus(this.arkUrl, v.point.raw, this._key(idx).privkey); } catch { status = 0; }
+ if (status === VTXO_STATE_SPENDABLE) fresh.push(v);
+ }
+ if (fresh.length && await this._handleMailboxMessage({ ...m, vtxos: fresh })) { changed = true; adopted.push(...fresh.filter((v) => this._vtxo(v.id)).map((v) => v.amountSat)); }
+ }
+ if (!haveMore || !messages.length) break;
+ }
+ // the refusals those coins left in the history
+ for (const amt of adopted) {
+ const i = this.state.movements.findIndex((m) => rejected.includes(m) && m.amountSat === amt);
+ if (i >= 0) this.state.movements.splice(i, 1);
+ }
+ return changed;
+ }
+
+ async rescanRejectedExpired() {
+ if (!this.honorsExpired || this.state.expiredRescanDone) return false;
+ let changed = false;
+ const alive = async (v) => {
+ try {
+ return (await getVtxoStatus(this.arkUrl, this._decoded(v).point.raw, this._keyForVtxo(v).privkey)) === VTXO_STATE_SPENDABLE;
+ } catch { return false; }
+ };
+ for (const v of this.state.vtxos) {
+ if (!(v.expiryRejected || (v.forgotten && v.state === 'spent'))) continue;
+ if (!(await alive(v))) continue;
+ delete v.expiryRejected; delete v.forgotten; v.state = 'spendable';
+ changed = true;
+ }
+ const rejected = (this.state.movements || []).filter((m) => m.type === 'receive' && m.status === 'rejected' && /expired at/i.test(m.detail || ''));
+ if (rejected.length) {
+ const mailbox = this._mailboxKey();
+ let checkpoint = 0;
+ for (let page = 0; page < 50; page++) {
+ const { messages, haveMore } = await readMailbox(this.arkUrl, mailbox, checkpoint);
+ for (const m of messages) {
+ checkpoint = Math.max(checkpoint, m.checkpoint || 0);
+ if (m.kind !== 'arkoor') continue;
+ const fresh = [];
+ for (const v of m.vtxos) {
+ if (this._vtxo(v.id)) continue;
+ // a coin another device of this wallet adopted and spent since
+ // is not money here; only what the server still holds for us is
+ let status = 0;
+ try { status = await getVtxoStatus(this.arkUrl, v.point.raw, this._key(0).privkey); } catch { status = 0; }
+ if (status === VTXO_STATE_SPENDABLE) fresh.push(v);
+ }
+ if (fresh.length && await this._handleMailboxMessage({ ...m, vtxos: fresh })) changed = true;
+ }
+ if (!haveMore || !messages.length) break;
+ }
+ this.state.movements = this.state.movements.filter((m) => !rejected.includes(m));
+ changed = true;
+ }
+ this.state.expiredRescanDone = true;
+ return true;
+ }
+
async _handleMailboxMessage(m) {
let changed = false;
if (m.kind === 'lnSendFinished') {
@@ -616,7 +847,7 @@ export class ArkManager {
return changed;
}
if (m.kind !== 'arkoor') return changed;
- const ourKeys = [hex.encode(this._key(0).pubkey)];
+ const key0 = hex.encode(this._key(0).pubkey);
const tip = await this._tipMemo();
// The mailbox checkpoint IS the delivery timestamp (ms << 20, verified
// to the millisecond against the server's rows) — the one honest date
@@ -639,8 +870,13 @@ export class ArkManager {
}
continue;
}
+ // Receives are paid to key 0, but every key this wallet has handed
+ // out is its own: a failed payment's refund, cosigned by the server
+ // and lost here before it was written down (a reload in that second),
+ // comes back through the mailbox to the key it was made for.
+ const keyIndex = this._ownKeyIndex(v.policy.userPubkey);
try {
- await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: ourKeys });
+ await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: keyIndex > 0 ? [v.policy.userPubkey] : [key0], acceptExpired: this.honorsExpired });
} catch (e) {
if (e instanceof VtxoValidationError) {
this._movement({ type: 'receive', amountSat: v.amountSat, status: 'rejected', detail: e.message });
@@ -652,10 +888,28 @@ export class ArkManager {
// _addVtxo dedupes by id — the poll and the live stream can process the
// 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;
+ if (!this._addVtxo(v, v._raw.bytes, keyIndex)) continue;
+ if (keyIndex >= (this.state.nextKeyIndex || 1)) this.state.nextKeyIndex = keyIndex + 1;
+ // the refund of a payment of ours: that payment failed and its money
+ // is back, which is what the history says, not "received"
+ const pay = keyIndex > 0 && this.state.actions.find((a) => a.type === 'ln-pay' && a.revKeyIndex === keyIndex);
+ if (pay) {
+ if (!['done', 'failed'].includes(pay.step)) {
+ for (const id of pay.htlcVtxoIds || [pay.htlcVtxoId]) { const htlc = this._vtxo(id); if (htlc) htlc.state = 'spent'; }
+ pay.step = 'failed';
+ pay.error = pay.error || 'payment failed';
+ this._movement({ type: 'ln-send', amountSat: pay.amountSat, status: 'failed', detail: 'payment failed, funds returned', invoice: pay.invoice });
+ }
+ changed = true;
+ 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;
}
@@ -733,8 +987,13 @@ export class ArkManager {
v.state = owner.step === 'done' || owner.step === 'failed' ? 'spent' : 'pending';
changed = true;
}
+ // An HTLC coin whose payment no action names any more (done ln-pays are
+ // pruned after a while) is an orphan too: five 22-sat ones sat 'pending'
+ // in a wallet for days, counted as money on its way. The server's answer
+ // settles it — spent is spent; one still open stays pending, since an
+ // HTLC coin is never this wallet's to spend (see below).
const candidates = this.state.vtxos.filter((v) => v.state === 'spendable'
- || (v.state === 'pending' && !held.has(v.id) && v.bytes && this._policyType(v) === 'pubkey'));
+ || (v.state === 'pending' && !held.has(v.id) && v.bytes));
const was = candidates.map((v) => v.state); // what each was when this pass began
// Each status query signs a challenge (schnorr) and may decode the vtxo —
// real secp256k1 work. Building them all in one synchronous map was a
@@ -759,8 +1018,8 @@ export class ArkManager {
// an orphan the server still counts is simply spendable again; one it
// holds as spent is gone, and the pay that took it was recorded (or
// will merge in) elsewhere — no row of its own
- if (states[i] === VTXO_STATE_SPENDABLE) { v.state = 'spendable'; changed = true; }
- else if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; }
+ if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; }
+ else if (states[i] === VTXO_STATE_SPENDABLE && this._policyType(v) === 'pubkey') { v.state = 'spendable'; changed = true; }
return;
}
if (states[i] !== VTXO_STATE_SPENT) return;
@@ -962,30 +1221,91 @@ export class ArkManager {
// that covers it, else largest-first until the sum does. A balance scattered
// by many small receives stays spendable — the package cosign spends all
// the inputs atomically and the recipient just receives several vtxos.
+ // A coin past its timelock spends LAST. The server honors it, and so does
+ // this build at pickup — but a receiver on an older build still refuses
+ // one as expired and strands it. Reaching for such a coin only when
+ // nothing else covers the amount narrows that to almost no payment.
+ _pastExpiry(v, tip) { return !!tip && !!v.expiryHeight && v.expiryHeight <= tip; }
+ _spendOrder(list, tip, cmp) {
+ const live = list.filter((v) => !this._pastExpiry(v, tip)).sort(cmp);
+ const past = list.filter((v) => this._pastExpiry(v, tip)).sort(cmp);
+ return [...live, ...past];
+ }
+ // largest-first (or in `order`) until `need` is covered; the coins inside their
+ // timelock alone if they can carry it, else everything
+ _accumulate(spendable, tip, need, order) {
+ const desc = order || ((a, b) => b.amountSat - a.amountSat);
+ const live = spendable.filter((v) => !this._pastExpiry(v, tip)).sort(desc);
+ for (const pool of [live, [...spendable].sort(desc)]) {
+ const picked = [];
+ let sum = 0;
+ for (const v of pool) {
+ picked.push(v); sum += v.amountSat;
+ if (need(picked, sum)) return picked;
+ }
+ }
+ return null;
+ }
+
_selectInputs(amountSat, tip = this._tipH || 0) {
const busy = this._remoteBusy();
+ // a coin at the server's depth cap can't be an input: the cosign is refused
const spendable = this.state.vtxos
- .filter((v) => this._free(v, busy) && !this._expired(v, tip));
- const single = spendable
- .filter((v) => v.amountSat >= amountSat)
- .sort((a, b) => a.amountSat - b.amountSat)[0];
+ .filter((v) => this._free(v, busy) && !this._expired(v, tip) && !this._capped(v));
+ const single = this._spendOrder(spendable.filter((v) => v.amountSat >= amountSat), tip, (a, b) => a.amountSat - b.amountSat)[0];
if (single) return [single];
- const picked = [];
- let sum = 0;
- for (const v of [...spendable].sort((a, b) => b.amountSat - a.amountSat)) {
- picked.push(v); sum += v.amountSat;
- if (sum >= amountSat) break;
- }
- if (sum < amountSat) throw new Error(this._insufficientMsg(tip));
- if (picked.length > 24) throw new Error('balance is spread over too many coins for one send');
+ const picked = this._accumulate(spendable, tip, (set, sum) => sum >= amountSat);
+ if (!picked) throw new Error(this._insufficientMsg(tip));
+ // The cap is this wallet's, not the server's (which caps offboard and
+ // board inputs only). It used to be 24, with an automatic consolidation
+ // round at 20 coins to stay under it — a round that cost 0.2% + base on
+ // every coin and was 84% of what users paid in fees. Wider, no round.
+ if (picked.length > MAX_SEND_INPUTS) throw new Error('balance is spread over too many coins for one send');
return picked;
}
+ // Inputs for a Lightning send of `amountSat` plus `routing`, and the fee
+ // they come to: { inputs, feeSat }. Throws when the coins can't cover it.
+ _selectLnInputs(spendable, tip, amountSat, routing) {
+ let inputs = null, feeSat = 0;
+ // A wallet that renews its own coins pays for every renewal, so it
+ // spends the coins nearest expiry first (Stacker News, 2026-10-29): the
+ // ASP takes them, so nobody downstream inherits the short timelock, as
+ // an Ark-to-Ark send's recipient would. Otherwise (and on a tie) the
+ // smallest coin that covers it, keeping the balance in few coins.
+ const oldest = !!this.lnOldestFirst();
+ const exp = (v) => v.expiryHeight || Infinity;
+ const bySize = (a, b) => a.amountSat - b.amountSat;
+ const byAge = (a, b) => (exp(a) - exp(b)) || bySize(a, b);
+ for (const v of this._spendOrder(spendable, tip, oldest ? byAge : bySize)) {
+ const fee = lnSendFee(amountSat, this.info.lnSendFees, [v], tip) + routing;
+ if (v.amountSat >= amountSat + fee) { inputs = [v]; feeSat = fee; break; }
+ }
+ if (!inputs) {
+ const need = (set, sum) => {
+ feeSat = lnSendFee(amountSat, this.info.lnSendFees, set, tip) + routing;
+ return sum >= amountSat + feeSat;
+ };
+ let picked = oldest ? this._accumulate(spendable, tip, need, byAge) : null;
+ // too many old crumbs for one payment: fall back to largest-first
+ if (!picked || picked.length > MAX_SEND_INPUTS) picked = this._accumulate(spendable, tip, need);
+ if (picked) inputs = picked;
+ if (!inputs) throw new Error(this._insufficientMsg(tip));
+ if (inputs.length > MAX_SEND_INPUTS) throw new Error('balance is spread over too many coins for one payment');
+ }
+ return { inputs, feeSat };
+ }
+
_insufficientMsg(tip) {
const expiredSat = this.state.vtxos
.filter((v) => v.state === 'spendable' && this._expired(v, tip))
.reduce((n, v) => n + v.amountSat, 0);
if (expiredSat) return `insufficient ark balance (${expiredSat} sat expired and unusable)`;
+ const cappedSat = this.state.vtxos.filter((v) => this._free(v) && this._capped(v)).reduce((n, v) => n + v.amountSat, 0);
+ // under dust a round won't take it either: only new money pays from here
+ if (cappedSat) return cappedSat < 330
+ ? `insufficient ark balance (${cappedSat} sat have a history too long to spend and are too few to renew; receive more to keep paying)`
+ : `insufficient ark balance (${cappedSat} sat have a history too long to spend and are waiting to be renewed)`;
// coins a renewal took stay unspendable until its round confirms on-chain
const renewing = lnShortfall(this.state.vtxos, this.state.actions, Infinity).renewingSat;
return renewing
@@ -1061,7 +1381,7 @@ export class ArkManager {
const decoded = inputRecs.map((r) => this._decoded(r));
const keysList = inputRecs.map((r) => this._keyForVtxo(r));
await registerVtxoTransactions(this.arkUrl, decoded.map((d) => d._raw.bytes));
- const builds = parts.map((p, i) => buildArkoorSend({
+ const builds = parts.map((p, i) => buildArkoorSend({ legacyDust: this._legacyDust(),
input: decoded[i],
outputs: [
{ amountSat: p.destSat, userPubkey: hex.decode(action.destPubkey) },
@@ -1186,10 +1506,17 @@ export class ArkManager {
async awaitLnPay(id, timeoutMs = 90_000) {
const a = this.lnAction(id);
if (!a || a.step !== 'initiated') return this.driveLn(id);
- await Promise.race([
+ const res = await Promise.race([
checkLightningPayment(this.arkUrl, hex.decode(a.paymentHash), true).catch(() => null),
new Promise((r) => setTimeout(r, timeoutMs)),
]);
+ // the held call's own answer settles it: asking once more for the same
+ // preimage was a round trip between the payment and its reply
+ if (res && res.status === 'success' && res.preimage && a.step === 'initiated'
+ && hex.encode(sha256(hex.decode(res.preimage))) === a.paymentHash) {
+ this._settleLnPay(a, res.preimage);
+ return a;
+ }
return this.driveLn(id);
}
@@ -1313,34 +1640,30 @@ 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);
+ const [tip, routing] = await Promise.all([
+ this._tipFresh(),
+ routingFeeSat != null ? routingFeeSat : this.lnRouteFee(invoice, amountSat),
+ ]);
+ // the two awaits above let a second call for the same invoice in
+ const twin = this.state.actions.find((a) =>
+ a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed');
+ if (twin) throw new Error(twin.step === 'done' ? 'this invoice was already paid' : 'a payment for this invoice is already in progress');
// smallest single vtxo that covers amount + routing + its expiry-dependent
// fee — else gather largest-first: each input funds its own HTLC vtxo with
// the same payment hash, and the server sums them into one payment.
const busy = this._remoteBusy();
+ // a coin at the depth cap can't be an input: the ASP refuses the cosign
const spendable = this.state.vtxos
- .filter((v) => this._free(v, busy) && !this._expired(v, tip));
- let inputs = null, feeSat = 0;
- for (const v of [...spendable].sort((a, b) => a.amountSat - b.amountSat)) {
- const fee = lnSendFee(amountSat, this.info.lnSendFees, [v], tip) + routing;
- if (v.amountSat >= amountSat + fee) { inputs = [v]; feeSat = fee; break; }
- }
- if (!inputs) {
- const picked = [];
- let sum = 0;
- for (const v of [...spendable].sort((a, b) => b.amountSat - a.amountSat)) {
- picked.push(v); sum += v.amountSat;
- feeSat = lnSendFee(amountSat, this.info.lnSendFees, picked, tip) + routing;
- if (sum >= amountSat + feeSat) { inputs = picked; break; }
- }
- if (!inputs) throw new Error(this._insufficientMsg(tip));
- if (inputs.length > 24) throw new Error('balance is spread over too many coins for one payment');
- }
+ .filter((v) => this._free(v, busy) && !this._expired(v, tip) && !this._capped(v));
+ const { inputs, feeSat } = this._selectLnInputs(spendable, tip, amountSat, routing);
// per-input HTLC share: first n-1 consumed whole, the last carries change
let remainingLock = amountSat + feeSat;
const parts = inputs.map((v) => {
@@ -1387,7 +1710,7 @@ export class ArkManager {
const htlcKey = this._key(action.htlcKeyIndex);
// every part locks its own HTLC vtxo under the SAME payment hash and
// key — the server sums them into one payment (htlc_vtxo_sum)
- const builds = parts.map((p, i) => buildArkoorSend({
+ const builds = parts.map((p, i) => buildArkoorSend({ legacyDust: this._legacyDust(),
input: decoded[i],
outputs: [
{
@@ -1496,10 +1819,22 @@ export class ArkManager {
});
action.step = 'initiated';
this._save();
+ // Just handed to the server: nothing to learn from asking this
+ // instant (it answered "pending", and the chain tip was fetched to
+ // go with it — two round trips before the caller's held call could
+ // even start). The caller waits on it (awaitLnPay) or polls.
+ return;
} 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();
@@ -1526,7 +1861,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) {
@@ -1560,7 +1910,7 @@ export class ArkManager {
const revKey = this._key(action.revKeyIndex);
const inputs = (action.htlcBytesList || [action.htlcBytes])
.map((b) => decodeVtxo(hex.decode(b)));
- const builds = inputs.map((input) => buildArkoorSend({
+ const builds = inputs.map((input) => buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: revKey.pubkey }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -1623,9 +1973,11 @@ export class ArkManager {
});
} catch (e) {
// "already been paid" for a settled one; "UNIQUE constraint failed:
- // invoices.payment_hash" for one merely issued before — both mean
- // this index is spoken for
- const used = /already been paid|already exists|already in use|duplicate|UNIQUE constraint|payment_hash/i.test(e?.message || '');
+ // invoices.payment_hash" for one merely issued before; "the invoice
+ // for payment hash … was canceled" for one a cancel retired (a
+ // withdraw-link claim died on that, 2026-11-08) — all mean this
+ // index is spoken for
+ const used = /already been paid|already exists|already in use|duplicate|UNIQUE constraint|payment_hash|payment hash [0-9a-f]+ was cancel+ed/i.test(e?.message || '');
if (!used || tries >= 200) throw e;
this._save(); // remember the skipped index even if the next try fails
continue;
@@ -1771,7 +2123,7 @@ export class ArkManager {
if (v.policy.userPubkey !== hex.encode(keys.pubkey)) throw new Error('HTLC vtxo pubkey mismatch');
if (v.policy.htlcExpiry < htlcRecvExpiry) throw new Error('HTLC vtxo expiry lower than requested');
try {
- await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, allowPolicies: ['serverHtlcRecv'] });
+ await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, allowPolicies: ['serverHtlcRecv'], acceptExpired: this.honorsExpired });
} catch (e) {
// a granted vtxo can anchor to a round the chain hasn't confirmed
// yet — park (no preimage revealed, nothing at risk) and retry on
@@ -1820,7 +2172,7 @@ export class ArkManager {
return;
}
}
- const builds = decoded.map((input) => buildArkoorSend({
+ const builds = decoded.map((input) => buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: keys.pubkey }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -1890,7 +2242,7 @@ export class ArkManager {
if (changeSat > 0) outputs.push({ amountSat: changeSat, userPubkey: this._key(refundIndex).pubkey });
await registerVtxoTransactions(this.arkUrl, [decoded._raw.bytes]);
- const build = buildArkoorSend({ input: decoded, outputs, serverPubkey: this.serverPub, vtxoKeys: keys });
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(), input: decoded, outputs, serverPubkey: this.serverPub, vtxoKeys: keys });
const sigs = await cosignWithServer(this.arkUrl, build, {
input: decoded, vtxoKeys: keys, serverPubkey: this.serverPub,
});
@@ -1931,7 +2283,7 @@ export class ArkManager {
? (typeof destPubkey === 'string' ? hex.decode(destPubkey) : destPubkey)
: this._key(outIndex).pubkey;
await registerVtxoTransactions(this.arkUrl, [input._raw.bytes]).catch(() => {});
- const build = buildArkoorSend({
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(),
input, outputs: [{ amountSat: input.amountSat, userPubkey: outPub }],
serverPubkey: this.serverPub, vtxoKeys: keys,
});
@@ -1963,7 +2315,7 @@ export class ArkManager {
const keys = this._key(claimKeyIndex);
if (input.policy.claimPubkey !== hex.encode(keys.pubkey)) throw new Error('htlc not held by this key');
await registerVtxoTransactions(this.arkUrl, [input._raw.bytes]).catch(() => {});
- const build = buildArkoorSend({
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: hex.decode(input.policy.refundPubkey) }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -1987,7 +2339,7 @@ export class ArkManager {
if (v.policy.type !== 'pubkey' || v.policy.userPubkey !== expect) {
throw new Error('refund vtxo is not paid to our refund key');
}
- await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: [expect] });
+ await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: [expect], acceptExpired: this.honorsExpired });
if (this._addVtxo(v, bytes, refundIndex)) total += v.amountSat;
}
if (total) {
@@ -2110,7 +2462,10 @@ export class ArkManager {
const entry = table.filter((e) => e.thresholdBlocks <= blocks).pop();
ppmUnits += v.amountSat * (entry?.ppm ?? 0);
}
- return this.info.refreshFees.baseFeeSat + Math.ceil(ppmUnits / 1_000_000);
+ // the server waives the base fee when every input is at its waiver depth
+ const waiver = this._waiverDepth();
+ const base = waiver && inputs.length && inputs.every((v) => this.exitDepth(v) >= waiver) ? 0 : this.info.refreshFees.baseFeeSat;
+ return base + Math.ceil(ppmUnits / 1_000_000);
}
// manual: the user asked for this one (the coins page) — it earns a
@@ -2250,19 +2605,20 @@ export class ArkManager {
if (action.step === 'created') {
// A set the round would refuse anyway is retired here, not resubmitted
- // every sync: an input past its expiry (only the server's backstop can
- // renew it now), or an output the fee leaves under the 330-sat dust
- // floor (a 21-sat coin with a 150-sat fee sat "in progress" for days).
- // Nothing was spent, so the inputs go back to spendable.
- const tip = this._tipH || (await this.chain.tipHeight().catch(() => 0));
+ // every sync: an output the fee leaves under the 330-sat dust floor (a
+ // 21-sat coin with a 150-sat fee sat "in progress" for days), or an
+ // input no longer held. Nothing was spent, so the inputs go back to
+ // spendable. An input PAST ITS EXPIRY is not a reason: the server's
+ // round-input check has no expiry clause (a coin 3,127 blocks past its
+ // height was renewed on mainnet, 2026-10-14) — renewal is the one
+ // thing an expired coin can always do, and this gate used to retire
+ // the Manage page's own "Renew" of exactly those coins, silently.
const inSat = inputRecs.reduce((n, v) => n + (v ? v.amountSat : 0), 0);
- const expired = inputRecs.some((v) => v && v.expiryHeight && tip && v.expiryHeight <= tip);
- if (expired || inSat - (action.feeSat || 0) < 330 || inputRecs.some((v) => !v)) {
+ if (inSat - (action.feeSat || 0) < 330 || inputRecs.some((v) => !v)) {
for (const v of inputRecs) if (v && v.state === 'pending') v.state = 'spendable';
action.step = 'failed';
action.superseded = true; // no row: the renewal never began
- action.lastError = expired ? 'an input has expired: only the server can renew it now'
- : inputRecs.some((v) => !v) ? 'an input is no longer held' : 'the fee leaves less than the 330-sat minimum';
+ action.lastError = inputRecs.some((v) => !v) ? 'an input is no longer held' : 'the fee leaves less than the 330-sat minimum';
this._save();
return;
}
@@ -2335,6 +2691,18 @@ export class ArkManager {
const fundingTx = parseTx(hex.decode(action.fundingTxHex));
const unlockHash = hex.decode(action.unlockHash);
const newVtxos = action.outputVtxos.map((b) => decodeVtxo(hex.decode(b)));
+ // nothing is signed for coins we couldn't unlock (bark !2803): the
+ // action stays 'issued' with the reason, and no forfeit goes out
+ try {
+ checkRoundOutputs(newVtxos, {
+ unlockHash: action.unlockHash, fundingTxid: fundingTx.txid,
+ ownerPubkey: outKeys.pubkey ? hex.encode(outKeys.pubkey) : null, minTotalSat: action.outAmountSat || 0,
+ });
+ } catch (e) {
+ if (action.lastError !== e.message) { action.lastError = e.message; this._save(); }
+ console.warn('ark: refusing to forfeit for this round —', e.message);
+ return;
+ }
// leaf cosign + forfeit are both idempotent server-side
const leafSigs = [];
for (const v of newVtxos) {
@@ -2437,24 +2805,32 @@ export class ArkManager {
// expiry. Coins arrive, get spent, get renewed — each new one needs its own
// backstop while it still has the lifetime to register one. Caller owns the
// policy (how much margin, how often to ask); this owns the bookkeeping.
- async ensureScheduledRefreshes(marginBlocks, maxCoins = 8) {
+ // grid: the order's height is snapped DOWN to a multiple of it, so orders
+ // from every wallet fall into the same round instead of one round (one
+ // on-chain fee) per coin. The snap only ever moves EARLIER, by under one
+ // grid step — the caller picks a margin+grid that stays in one fee bracket.
+ async ensureScheduledRefreshes(marginBlocks, maxCoins = 8, grid = 1) {
const tip = await this._tipMemo();
if (!tip) return 0;
const covered = new Set((this.state.scheduled || []).flatMap((s) => s.inputIds));
+ const runAt = (v) => {
+ const h = v.expiryHeight - marginBlocks;
+ return grid > 1 ? h - (h % grid) : h;
+ };
// A round output over the server's cap is refused when the round runs —
// long after registration, with nobody there to hear it. Don't register
// an order that is going to die that quietly.
const cap = this.info.maxVtxoAmountSat || Infinity;
const coins = this.state.vtxos
.filter((v) => this._free(v) && v.expiryHeight && !covered.has(v.id)
- && !this._expired(v, tip) && v.expiryHeight - marginBlocks > tip && v.amountSat <= cap)
+ && !this._expired(v, tip) && v.expiryHeight > tip && runAt(v) > tip && v.amountSat <= cap)
.sort((a, b) => b.amountSat - a.amountSat)
.slice(0, maxCoins);
let n = 0;
for (const v of coins) {
// One participation per coin. A shared one dies whole the moment any
// single input is spent, taking the untouched coins' cover with it.
- try { await this.scheduleRefresh([v.id], v.expiryHeight - marginBlocks); n++; }
+ try { await this.scheduleRefresh([v.id], runAt(v)); n++; }
catch (e) {
// priced from a stale schedule: re-read it so the next pass registers
if (/insufficient refresh fee/i.test(e.message || '')) this.info = await getArkInfo(this.arkUrl).catch(() => this.info);
@@ -2464,6 +2840,35 @@ export class ArkManager {
return n;
}
+ // The worker's version of flattening deep coins: it can't sit through a
+ // live round, so each deep coin gets a standing order for two blocks out,
+ // one per coin (an order dies whole when any input is spent — and a coin
+ // that is spent hourly will void it; the next wake registers again, and
+ // the one time the coin rests through the height, the round runs). Only
+ // coins still inside their timelock can be scheduled; an expired deep coin
+ // waits for the app, whose live refresh the server honors.
+ async ensureDeepRefreshes(maxCoins = 2) {
+ const deep = this.deepCoins();
+ if (!deep.length || !maxCoins) return 0;
+ const tip = await this._tipMemo();
+ if (!tip) return 0;
+ const covered = new Set((this.state.scheduled || []).flatMap((s) => s.inputIds));
+ const cap = this.info.maxVtxoAmountSat || Infinity;
+ // a round output under dust (330 sat) is refused, so a coin that small
+ // can't be renewed on its own — asking only spends the wake's budget
+ const coins = deep
+ .filter((v) => !covered.has(v.id) && v.expiryHeight > tip + 2 && v.amountSat <= cap
+ && v.amountSat - this.refreshFee([v], tip + 2) >= 330)
+ .sort((a, b) => this.exitDepth(b) - this.exitDepth(a))
+ .slice(0, maxCoins);
+ let n = 0;
+ for (const v of coins) {
+ try { await this.scheduleRefresh([v.id], tip + 2); n++; }
+ catch (e) { console.warn('ark: no deep refresh order for', v.id, '—', e.message); }
+ }
+ return n;
+ }
+
_dropScheduled(entry) {
this.state.scheduled = (this.state.scheduled || []).filter((s) => s !== entry);
this._save();
diff --git a/src/ark/proto.js b/src/ark/proto.js
index eb89d5e..69218c6 100644
--- a/src/ark/proto.js
+++ b/src/ark/proto.js
@@ -416,6 +416,10 @@ export async function getArkInfo(ark) {
if (field === 13) info.minBoardAmountSat = Number(value);
if (field === 15) info.lnReceiveAntiDosRequired = Number(value) !== 0;
if (field === 16) info.mailboxPubkey = hex.encode(value);
+ if (field === 19) info.maxVtxoExitDepth = Number(value); // past this depth a coin can't be spent until refreshed
+ // server-0.9.0+ (always ≥ 1 there, so always sent): also the sign that its
+ // stricter arkoor dust rules apply (see isolateDust in send.js)
+ if (field === 23) info.maxRoundParticipationOutputs = Number(value);
if (field === 20) info.maxOffboardInputs = Number(value);
if (field === 18) { // FeeSchedule
for (const f of pbFields(value)) {
@@ -445,9 +449,10 @@ export async function getArkInfo(ark) {
info.offboardFees = ob;
}
if (f.field === 3) { // refresh
- const rf = { baseFeeSat: 0, ppmExpiryTable: [] };
+ const rf = { baseFeeSat: 0, ppmExpiryTable: [], deepWaiverDepth: 0 };
for (const g of pbFields(f.value)) {
if (g.field === 1) rf.baseFeeSat = Number(g.value);
+ if (g.field === 3) rf.deepWaiverDepth = Number(g.value); // base fee waived when every input is this deep
if (g.field === 2) {
const e = { thresholdBlocks: 0, ppm: 0 };
for (const h of pbFields(g.value)) {
diff --git a/src/ark/refresh.js b/src/ark/refresh.js
index 6e4453d..44c8321 100644
--- a/src/ark/refresh.js
+++ b/src/ark/refresh.js
@@ -355,6 +355,32 @@ export async function roundParticipationStatus(ark, unlockHash) {
return out;
}
+// The round's new coins, checked before we cosign their leaves and forfeit
+// our inputs. The forfeits hand the server our inputs in exchange for the
+// preimage of OUR unlock hash, so a new coin locked by any other hash could
+// never be unlocked: forfeiting for it gives the money away. Port of bark
+// !2803 (server-0.9.0's client fix, reported by MrHodl: "Bark didn't check
+// that the unlock hash of its forfeits matched the one locking its new
+// VTXOs"), plus what bark's check_round_matches_participation also asks:
+// every coin a hark leaf anchored in this round's transaction and paid to
+// our key, and together at least what we asked for. Throws on the first
+// mismatch; nothing is signed then.
+export function checkRoundOutputs(vtxos, { unlockHash, fundingTxid, ownerPubkey, minTotalSat = 0 }) {
+ if (!vtxos.length) throw new Error('the round returned no coins for this participation');
+ let total = 0;
+ for (const v of vtxos) {
+ const last = v.genesis[v.genesis.length - 1];
+ const t = last && last.transition;
+ if (!t || !['hashLockedCosigned', 'hashLockedCosigned_v0'].includes(t.type)) throw new Error(`new coin ${v.id} is not a hash-locked round leaf`);
+ const lockedBy = t.unlock && (t.unlock.hash ?? (t.unlock.preimage != null ? sha256Hex(t.unlock.preimage) : null));
+ if (lockedBy !== unlockHash) throw new Error(`new coin ${v.id} is locked by unlock hash ${lockedBy}, expected ${unlockHash}`);
+ if (v.anchorPoint.txid !== fundingTxid) throw new Error(`new coin ${v.id} is anchored in ${v.anchorPoint.txid}, not this round's ${fundingTxid}`);
+ if (v.policy.type !== 'pubkey' || v.policy.userPubkey !== ownerPubkey) throw new Error(`new coin ${v.id} is not paid to our key`);
+ total += v.amountSat;
+ }
+ if (total < minTotalSat) throw new Error(`the round's new coins hold ${total} sat, ${minTotalSat} were asked for`);
+}
+
// MuSig2 script-spend cosign of the hash-locked leaf (NO taptweak)
export async function cosignHarkLeaf(ark, vtxo, fundingTx, vtxoKeys, serverPub) {
const last = vtxo.genesis[vtxo.genesis.length - 1];
diff --git a/src/ark/send.js b/src/ark/send.js
index f0e471a..9cf79b4 100644
--- a/src/ark/send.js
+++ b/src/ark/send.js
@@ -272,11 +272,49 @@ function encodeVtxo({ amountSat, expiryHeight, serverPubkey, exitDelta, anchorPo
const DUST_SAT = 330; // P2TR dust threshold
-// Mirror of bark's ArkoorBuilder::new_isolate_dust: the server rejects an
-// arkoor whose outputs mix dust and non-dust, so dust outputs are routed
-// through a combined isolation output (spent by a fanout tx). When the dust
-// alone can't reach the threshold, a non-dust output is split to pad it.
-function isolateDust(outputs) {
+// Mirror of bark's ArkoorBuilder::new_isolate_dust (server-0.9.0). Dust
+// outputs are routed through one combined isolation output on the checkpoint
+// (spent by a fanout tx), so every checkpoint output is standard. Since
+// server-0.9.0 (!2822) the server refuses a cosign whose checkpoint carries
+// a sub-dust output unless the input itself is dust, so this must match
+// upstream case for case:
+// - no dust, or a dust input: nothing isolated
+// - dust summing to ≥ 330: all of it isolated
+// - otherwise pad the dust from the first non-dust output that stays ≥ 330
+// after giving up the deficit; failing that, isolate the smallest non-dust
+// output whole (each is then under 330 + deficit ≤ 660, which isolation
+// allows). Both used to "accept the mix", which 0.9.0 refuses.
+// - every output dust (from an input ≥ 330): all of it isolated, the
+// checkpoint holding only the isolation output.
+//
+// `legacy`: a server before 0.9.0 (it advertises no ArkInfo field 23) refuses
+// the two new shapes instead — "At least one output is required" for an
+// all-isolated checkpoint, checked on regtest 0.8.0 — and takes the old mix,
+// so it gets the old split (isolateDustLegacy) until it upgrades.
+export function isolateDust(outputs, inputSat, { legacy = false } = {}) {
+ if (legacy) return isolateDustLegacy(outputs);
+ const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0);
+ if (outputs.every((o) => o.amountSat >= DUST_SAT)) return { outs: outputs, isolated: [] };
+ if (inputSat < DUST_SAT) return { outs: outputs, isolated: [] };
+ const dust = outputs.filter((o) => o.amountSat < DUST_SAT);
+ const nonDust = outputs.filter((o) => o.amountSat >= DUST_SAT);
+ if (sum(dust) >= DUST_SAT) return { outs: nonDust, isolated: dust };
+ const deficit = DUST_SAT - sum(dust);
+ const idx = nonDust.findIndex((o) => o.amountSat - deficit >= DUST_SAT);
+ if (idx >= 0) {
+ const outs = nonDust.slice();
+ outs[idx] = { amountSat: outs[idx].amountSat - deficit, policy: outs[idx].policy };
+ return { outs, isolated: [{ amountSat: deficit, policy: nonDust[idx].policy }, ...dust] };
+ }
+ let small = -1;
+ nonDust.forEach((o, i) => { if (small < 0 || o.amountSat < nonDust[small].amountSat) small = i; });
+ if (small < 0) return { outs: [], isolated: dust }; // unreachable: dust alone sums to the input ≥ 330
+ const outs = nonDust.filter((_, i) => i !== small);
+ return { outs, isolated: [nonDust[small], ...dust] };
+}
+
+// bark ≤ 0.8's new_isolate_dust, for servers before 0.9.0
+function isolateDustLegacy(outputs) {
const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0);
const dust = outputs.filter((o) => o.amountSat < DUST_SAT);
const nonDust = outputs.filter((o) => o.amountSat >= DUST_SAT);
@@ -298,7 +336,7 @@ function isolateDust(outputs) {
// — destination first, change last. NB an output may come back SPLIT across
// two result vtxos (dust padding), so callers should consume
// buildAllSignedVtxos() and classify by policy rather than by index.
-export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys }) {
+export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys, legacyDust = false }) {
const userPub = vtxoKeys.pubkey;
if (hex.encode(userPub) !== policyOwnerPubkey(input.policy)) throw new Error('input not owned by our key');
@@ -307,7 +345,7 @@ export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys }) {
amountSat: o.amountSat,
policy: o.policy || { type: 'pubkey', userPubkey: hex.encode(o.userPubkey) },
}));
- const { outs, isolated } = isolateDust(normalized);
+ const { outs, isolated } = isolateDust(normalized, input.amountSat, { legacy: legacyDust });
const isolationSat = isolated.reduce((n, o) => n + o.amountSat, 0);
const inputTaproot = policyTaproot(input.policy, serverPubkey, input.exitDelta);
diff --git a/src/ark/store.js b/src/ark/store.js
index b1caa94..24d8f55 100644
--- a/src/ark/store.js
+++ b/src/ark/store.js
@@ -139,6 +139,7 @@ export class ArkStore {
}
}
this.ready = true;
+ this._parsed = null; // peeks now read the opened store
if (migrated.length) {
this.flush().then(() => { for (const k of migrated) { try { ls.removeItem(k); } catch {} } }).catch(() => {});
}
@@ -153,13 +154,32 @@ export class ArkStore {
const v = this.mem.get(key);
return v ? clone(v) : null;
}
+ // The stored object itself, not a copy — for readers that only look (the
+ // render path). get() deep-copies, and a big wallet's state is ~1 MB: on a
+ // Pixel 9 each copy took ~220 ms and the first render asked five to seven
+ // times before the manager connected, 1.4 s of every launch. Never mutate
+ // what this returns. Before the store opens (or on localStorage) the parse
+ // is kept until the key is next written.
+ peek(key) {
+ if (!this.ready || this.lsMode) {
+ const hit = this._parsed && this._parsed.get(key);
+ if (hit !== undefined) return hit;
+ let v = null;
+ try { const raw = this.ls().getItem(key); v = raw ? JSON.parse(raw) : null; } catch { v = null; }
+ (this._parsed ||= new Map()).set(key, v);
+ return v;
+ }
+ return this.mem.get(key) || null;
+ }
set(key, obj) {
+ if (this._parsed) this._parsed.delete(key);
if (!this.ready || this.lsMode) { try { this.ls().setItem(key, JSON.stringify(obj)); } catch {} return; }
this.mem.set(key, obj);
this.dirty.add(key);
this._schedule();
}
remove(key) {
+ if (this._parsed) this._parsed.delete(key);
if (!this.ready || this.lsMode) { try { this.ls().removeItem(key); } catch {} return; }
this.mem.delete(key);
this.dirty.add(key);
diff --git a/src/ark/validate.js b/src/ark/validate.js
index fae3465..9cb1751 100644
--- a/src/ark/validate.js
+++ b/src/ark/validate.js
@@ -24,7 +24,11 @@ const fail = (msg) => { throw new VtxoValidationError(msg); };
// plus getTxStatus(txid) -> {confirmed, block_height} (esplora semantics)
// allowPolicies: acceptable policy types (default plain pubkey only; lightning
// flows pass ['serverHtlcSend'] / ['serverHtlcRecv'] for their HTLC vtxos)
-export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, allowPolicies = ['pubkey'] }) {
+// acceptExpired: the server keeps honoring coins past their timelock (coinos:
+// captaind allow_expired_arkoor) — the coin is then an IOU the server has
+// already swept the tree of, which is exactly what the holder chose when they
+// left custody to coinos; refuse only on servers that would refuse to spend it
+export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, allowPolicies = ['pubkey'], acceptExpired = false }) {
const serverHex = hex.encode(serverPubkey);
// -- structural --
@@ -41,7 +45,7 @@ export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, a
// and the coinos ASP keeps honoring them off-chain after sweeping their
// round — an explicit IOU where the trustless path never existed anyway.
const tip = await chain.tipHeight();
- if (vtxo.expiryHeight <= tip && vtxo.amountSat >= 330) {
+ if (!acceptExpired && vtxo.expiryHeight <= tip && vtxo.amountSat >= 330) {
fail(`vtxo expired at ${vtxo.expiryHeight}, tip ${tip}`);
}
diff --git a/src/assets/zap.mp3.base64.txt b/src/assets/zap.mp3.base64.txt
index 6f056c5..b9b7d5b 100644
--- a/src/assets/zap.mp3.base64.txt
+++ b/src/assets/zap.mp3.base64.txt
@@ -1 +1 @@
-SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2LjEwMAAAAAAAAAAAAAAA//OEwAAAAAAAAAAAAFhpbmcAAAAPAAAAOQAAIuAADxEREhITExYfHyUlLS0yOztGRk5OU1dXWlpeXmNsbHJyd3d7f3+Dg4iIkJWVmZmdnaGlpampra2wtLS5uby8wMTEyMjNzdHV1dnZ3d3h5eXp6ezs7/Ly9PT39/r8/P7+////AAAAAExhdmM1OC4xMwAAAAAAAAAAAAAAACQDgAAAAAAAACLg/oQQbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//O0xAAcwBJlvmBAAQBk3JLbt/wH8DgAAAAw8PDw8AAAAAAw8PDw8AAAAAAw8PDw8AAAAAAw8PDw8AAAAARh4eHjwAAAEAGHh4eHgAAAAAGHh4ePAP/9+Hh4eAAAAAAYeHh4eAAAAAAYeHh4eAADv2Hh4ePAAAAAEYeHh48AAAAD0pyXfgNmWNGgESJEiVESJEiRIhBQoKCgoJBQUFBQoKCgoJBQUFBQoKCgoJBQUFBQoKCgo4FBQV3hQUowAKqQimoPXYSgFJq9unDgTEcFy4h69VVtuUyf5hBBhgBAFcHofCq5ODzmW6vw3DevrVKOSqsjw7Ork+xZv/u//+/Rv/9XIRmP//+k87f///////////zzrjnjnYQH///+PA+hRYY3QbhYbJeY/9uy0fACCPCgMYCRGL4qbIBTNDCEo8jPoDTjMMCCACeEOnDGluTC//NExNAO2EJRuMmCDag2wYt+MhEJcJEIhAU1irk7DNg0GBjoYUSIHgC2H1eBhgCADRIFBEwJGJHwMUAxxMSSxRe80+oYXVUL4GbAiAEsWKO8uZLKMJ/0FFFWScgtRNb6//MUxOcBYBZdQJiAAucWIPEnQ4D9wt/2//MkxOwESBJeQVgAAJ0qsutE781csWpE8K1zEBlQtPZOuSWo95WI9TU9NulrRujt//M0xP0S8zZSNZsQANLPTPxaUvs2jiKYN5IZf///yJ44Ei9Lr///+hxe+lu4/////hUjD8Mvf+f925El4rizG7n/8827XHEd//O0xOxOvCKbH5rSIEf/+PvG35YY/H/923SXrtb/u3qDd28XIaBONwhN+Tu5K0Ab1PIl+nXPyD///swBDF6tPy2jh6Luu29HE7VX///+cwpefPV5dKuSimkVX7iGlTc2aY/3kYCeDACGFISw1UMDgOBD2dT7fR0sT4fjPPCiNjZM/YE0Sebk946hsLDcUx3h7J46xyeNjxGNTcPY1qk81GxhAG6Z4kjraHuSQTGJxcPeO9xoszSeoY084QBMSTXbZeoymXKd+xjH3HTKYx7+7Yz5fERHvk3Pv//Zve/hj7v//2U9NM3fBxjGzfTGMpjGfvfbqqmH7t73/y9N753vZ///Dz75erEm7WppjvJ7m2aUbu7EAEdqqpWEWHWIX/b5gJvUqgGNXkLdkmcsVSpxq81SwU11JJRclA5UBryvw1F5dTxZ3lD1TSkQCbnBwOGr//OExPQu0+avH89YAWNdhTQHOk0nmuwRDrS4StIeoqIkCjU+qL7jOSuRYrtA062nvR/eR1i3kRGWCDZUkNdQmY0QizIeoTAQTaPhxeEzQptL45uZAEJfBq1wogbjs5heFyRI6jIPsjjdE+Jqdw7zGXYrji1lAuXxO1xAJYxzEEfKgsZuLpGqpVnAkkq9VZDMgbyVrm2VFG0HUYvf/9/lJJpkkXVliiuUutFy7MzSzUC0ZTU9+lpf2rieTZlDUGTX//OkxOtDtB6zHsPTjK6BfUE5o0Cjj5GJUYOrGA8q8Nh8qIzChIdQticqiFKBXo1EsniKiJf9/9bAF20Ps1DcBkKq4O0vigE5P86wgx+H4ETijrWHO8tDcgTxwUiY8Ekd7R5N1zZBt1JcwgiaqSV0CMfxvNDogD5KNESoim5BiETCo2aVExVpDuJ5+TdlFFKFLNFzz60LdLNZMmNWr56KO3rNSX1as1jSZJqfcavXLmUZH9auXq7EoYk1dtf//819zsj49v/39ff3H///W29v3HUxX38NiKZLpttXTGOp6NptegERR1V1WVVjTff7+7SVyuJJIJlh5CJHVYZJ1vgFQOYmI1hIRyioFiUyw9mDcw3icMo014SQLk/0LPEn5hHU//OExO8tDALS/09YAXwapB2Mn5pGQwMKkIUmSdn8h7Kl2RJzrTIyIs7EMOgt50GUWE8lSYx4oY2pdSsyw5qBvSsdOPlU0H+oS/oYr2ZQSuCnhQ5meK5MkKI5vUMeKhHv1epFlankcmSKwMLM4qtghdneqZlbFSj1HBcorFBwubYfLFMxX7Jlsh7on3z6BuktlerIbp28tFjws/cBziNKgV8OM63ef7ppqmfrKrhO4kXEu///l7PAs9jx30XUO0d5//OkxO1DTCbC/5h4AX1//5GzcdFszIqHrnPGpjf//zfor0QxTp5C+oXLrzQAKmZoqXh5LbXZ23KezGGU1crMcWzZWsyglN9gTeJgFqw+On+05j+GZzMgCwNsaDCQc2qsMvvTE1MQSIBElxccLDChwUvMmEDHkUIhRGq0VjLKAEgOdUgDDzPRFolb1giZRs1QeHAhItWnKYIZeMrDQhDD4FAyqDgBHWmBSS0hQiXrTXVoLtpIKwF+ihUIgL7omMwTyQwbAqo+604ykGj4wxD5WxTBLRe5ZhKhGpNxZBftGdFNQ1KtS5H9H53E41DKVXDsM1Ug5kkUgu5bCTTOlTJNrPi7kwAxRuz2N+uSu+cwtNyF3xWFrUh9T65HPeaaUDh+//PExPJhvDKS85vIALrWY80NHN95hFqXS4uXL7zoSF+1EkyJEnSierx5otebC7GdlW+86LA3cYeyJrCzqTl66yWr1eMDyxaK71uNhXuprXoae0ze1f+SyJ0FMqLqykI1B4ba2mlA1l6HsvR/H/9qsQKgSzoSvBDgmooOxSPv+kjlGkvZWw6m5/WYrcJQIPpUnkHiQR7kPEOlMl9cnE/Kyas3ltuu5qqs8LM0cbTupGf0vG/Bb9piQY6FriPaPitTJCqFF8RET0FbEMCEPVCS47h9BHy6kBLogTJ0LeVxelACcFhJyqhQga4FApB3JZXOc5jC0AKI9BCAjJyHgwJovCgUB3FyJIPQiFGY5Xmg1IYq4EBTqVheqNM9PplfQxzUrD4DVOi1WqT9XKgQh6olJEfWcle+VbI5MTehr1geKRPrKzH7C/c47pXv6qxie6RqHv2NEPoemlpdKhUqvNmyMxUbJ3jAyK5siO96mjySdsjN7HGcYcd5Fu/vfPiRdSwW//OkxN5FLCq6fZh4AQeUhxtUxNPf6cJI+JH8Cj+2G3d4Pd4/+oFob3tr2DFq6nq9255r/lYVjBar1zdu3C8aWC1uqSqIe2ZWh0/RBylagZA6rAVFFoPwT+USW7cbNV0TmM3s19O4cVHGhECNALuc1rEHj7sfzUl1l1kXkckLJ9RUFVccpKreZ9/ez8/Pz8e1d/XFfVxdJ1XL+NLREt7cOJvRtVYq1f67Vsqhwkpx4i8aYAri+RsKFFj1LeaUZA92m2Z3iF/hK0BoQSFYuxkQwjaFThNSPyXWjFcmVEjKw+oDg8dA8lZJLcadBjjO7NrE8sPOFMwvDuwmQUoLBFR8E0IkUSTM6DnB1DkRtcu2dkbaCkQ9KkfdXLY6p9p/9Ur6//N0xNweugrPFc9AAC0udWNmz/6sqMzkItSKuzrIi6nLQyv+31NyKxlYR6ipWazqEZV3eVllx09RXzxhB9IDY51ljIKhLkKTJENVyLuP55FPDWGnS66ETu2w8oDgGTLZAZyzuWMk+mKW32BGde1E2P6fTPlWFyQ6WbPTbSp2VGqzNDKUxYW20SDTpKoEuXhUu4wKpjNPJ6RA0gUC4MEgqeEtsuR/ytQ3//NkxPwhVBbTFHpEsBY9DSrIiWhot0kiDbmGoYoI0aly6rchVM+Dqo+Qauayk9HWoKD6mmJBrLGWmDLFQR3VpRnBvDYJofEUGIpmRkBtclnIahsuTbdE01223pgtWttm1QqmUm6Bnb0UmRbtGpq383pRUaejzVV2Bsog1/I06EZG3+nqEI7Kd2CMcgMeQ8XV//NUxPkeSfbTFHmFDAhGOHDAdZVmWNfZEiRfKw6wgZqQDkS+yf2iGjvJyHITAuNFIyzw3ctplzIBwP5G6KsizUOSg1Dj7sxDxyJ5/NzI6mtxvv5T/ovtULXV77V9aXn+/pSXcfPx8fPcff1Xf3/o3Pz/HfE8z/3X//NkxOohHBLjHnpE4Vdt9/UdzHM1EWozm6buklJ/49/93aGvrgftfdRtadX3zGSj2QWyfXOIyRLIidsqlAouNKktwm6tBPVqicpgIW8SoQCPej2AALZf9eqw6w0OO2lWo8wRdrS5idXc1Zf9VSlkxEWTvVHWXxSFwC9DQHflq/n864EsaBOwukZXUiUOOXFZ//N0xOgiY/7S/U9AAXyaanInG5Y3kxi7dFflEqr5T0Vpn8dLJ28aKenKaUUNiIV4FvyCtM2qa1GLU7Is41IbERn4blT+VL0nlupurPSypS279z+W5PdjligryuV4x6puxuWfUzp6/3K0/Say1Vl16UTNatOU9e5K888f+7TSuRS2xN2rdFjfu//fwmLNHS2r1Nev0eXzMx93OY7Zu3YrNyt/Kfn/hSc+//OkxPlFZDK+d5jAAG+TUQnstdxu2tUvIp//cnf+h+5GrH//67rG5GcVVlRpVIRmmGRDkiTKCaSLjQZjQgKqdEFCWsRnaYCAcsiYQqUVGlMACLuoQTt4cxdNAa5/wjgLuegRGVgwww6xlIQRMoND2c1EgeCqPhNMKrQMyCcycPVRBLeWxCEeuFyW86FWXtdMandK96/UjZCZGdtTM92eKaavZW9zRLxrWIMOC5zOT5SJtugKZUMrg3u4l8Q1ty2wLETTt5Hhud6RlbDeR3N4q2ueH37Otu1XDqtxfDvBTl3m/Tbm1x3F2yUgXiPMfz6WYTyLAb3OJGh03/FxGhx40k7Pv4v/5WCPN////1Vj+77/COPFfm//+/8zV/a5v9nP//OUxPY+fAbHH5h4AKh61yCmVVVphE7hInIQtdCxWLU6stvrd7m301abWzWgWs9MSrPDOTmdsmeNxuPnXoN2MJIVEo4eWiHml3J0QyiHz2Luac5phpSTY920xzITRdU042qfqYyMYmk481TjVoh7I6qfc3tqfV6vRqOaa//U1EWh/pmWM3zlNM33q//vZ6t18///lQeHvQyYC8RAGFqnVVlZlUqWgVwR8UI0LrLJHhDn9gPV9v5qUJr51W83BrUKupBYgq1UiFrXcItSgwB0qTkOL4M7TMlzUjWkwJZK7Z8qMMurnEq5nb7N2Te7XK0b//N0xN8jNBbXF9g4AHpO3K36Eb6aPv/77vf7M++2Tbf1f/2r////9pHneDcLZYNIeFVPVhlZkCgM1BTEIaAVVunJ+ZEA/xDpjABevFKRzyDFYUqCs5KHEyyssbhV4ZknRMUwBUFVniasjjeeoPSopWdD8zkMwcpVaWU+9G9HcFqiMZyJYsvq0nz//yZMOWqGZ1OdnZGVXQru0quCOsb1m3/iX+MCwQKk//NkxO0chA7bFMDFEQYY2jl3scRB+o+ogO4sDGY6alMF4/UeHiLnbSkbBkKV82lpBXbk/f6671hyICdx9FMMKRBJgxOKJhZanXmrKXC9HUyRNelczItDgR6FNEKtEz9IcgMwwSN0u/slDJQouOd2HrUv2X8zzKNGCY4KGjzPsLj6OQgeIKB2RESj3iU3//Br//NUxP4fQybXFHmE7HB1QNGAYu5nVhlThmjIeOx3LFj19DsiQy4YunsLhCZD2Me6nOBmYM2HJ9VoKWgcvjIGH7CPesrdDW6u7+6qbnrrm7j3u2iKuYmU94FqYqmelMuFv9Nxx+1UNupmkaT6S7/mOEmf///6y8aP//NkxOwhswLSXHjLGKit02pSe09PeomRj3jtbouK0T//7FPqoIp+b5v+4SLJHno9W40fYcYsI5lHJBJ4hhQdhmdVhVaEhldVrtijVkYVSLSAcrukwVMS/A0MFDSvbukOw0wJa1JlK1lRFDlAMaZUtBAWtGLuQj0qVgwFJBL0RRXMCOXFmnIeogM6V20F1tvx//N0xOglvBbWd09AACdzHFizrRiD5LF4TSP04E5PRjCNwBSu5ucizkNleqOvDJnLicql0sxg2ITuUrpMqtqNO5BNeHIftQ7efafgS9F4pRRaBIrQ37Utjd2WXZu67TtQLHJbOvA/s//wqlrVdx6rczrfuMX9Qrkxf/eP15XDEMu9IYJhh37UVkTzUMQz7+qm8pq7clVDNXKv/+ec/KIDjcsh+VxihvVv//OkxOxJFC7LH5jAAP1Y+68MWk0fi11/mdMDaxFV7M1bi0pst7/5/4/r8d40MczoZqX1ZRW/////Dn//KGNdoYlFYZtWFc5DImVoAA4NRlAe1nBMJpjhVNSUT2Z4q5MqY7TG3mB16KPCQYcBHjXiuLlOBJxagq5HYSWr3Ldr5aNGOo1JknZkuW46w9xroV5sUcpKFx9HrputKL8///ij+KS0EhzCosZnhY1xJ1FhqMmUSlG+Zfh5/+r0KX/dFi9VKUzmHXYwcxso1VHlkXljZa4pJEsaeTEsHWHcpWqDvUezyhuUVo5YqtAkFQMdWASCAtXKjmd0mchPGuXEsrTN3c0zwrYj4MvJ7K5n1VyXstViqLM8HldQe+VY7LJHOtrS//N0xNohtArKV88oAZWdmTepv/p5kkypahXQdiO5TurSrf7urN//JvXX659Z0UyzzkJI6sA0JA05JcWqlXNYrteiTgSTUK4oV78Vt52099fDla9EYg+i6aeq+Wf3u5XrEf/s3hun1yQasCZNKT+OGEsFCPZv5GgkJ6Qj60+Znn2yQ0zK7R0mMUHw74eq81qWo5mSwsEUer//2o1KSzXBOo+Kc853qavX//NkxO4gS97a/MGEvf/96bbeqPY98yrOyMVGUjlQjAkUiFHpKRLEUzSOxONLchpL3oMPn2WhNYcjATpMGtwOxWHc7stx9ltvJNxqDc4O6OezWIrCM+LRFdSOdJyMRVELGW+6zra6EejTttO7s9nUshpDIR52uzO1tv6ZM8p5Xey2KQSXMqzqipRH9fp//X////NkxO8hM/re/sDFOW33s8yTIxkMFqJlcfBWefs1rbJEktiWHwHQxrB8Yiki3lYzqai+pMLqPazhhji9gxRixgTEAKFCEFNWGN5h2KEZ+ckqmtcihvN/y3LeS2nV1TZ/redv31lOkf9dvY0Ov929NGzWNI8mtC0Euoqz+v///v///XTfHq1Wg9Dhm/Mv1ZX///NkxO0eO9be/MJEPUmrscbbYgZCEcE5qg3kZHGjTCXiYZ/MUtoSb/m8usQol2/yq4c0TUlBkBs5TQdy5MSiiEV3Rod3Z4K7YRI9SXdwTsp0BTJkzTPV2Q6GaQ82dJqP/TtXNn+8M7mGYEORKv9MnsSp//7fav0y7So8TKNBnqRQbS9kGxXSLazRxpLYnCAG//NUxPcck87eXHjFHdJTZRxdnJrDi7ioiC8NO78xvhxuv7lY5qRZ9ws9uvYWRDHCoOwEensz3UeY3fnVdA0O8ORdc1GWuQLKXOGt3hJcdAZlHzI4XYSeNl8+vwnvp1ck4dz0VLEN6r/ttXv6b7/7Otkolk3S015D//NkxO8edAreXovEHZbrkzVM5GUolbNTRfpJ8sxIk2guKEZxGF6ca3G1bpXF4/IQakxuynKx8z+NTPfx72vTA7yF3u6AmgiwdQ0gJEWuCI5HKdkYtkvsrMx3o1NdNNapVqOq0eiXff71fazoahsttcz///19bgj0z7bbtbLV6Kq65LncwtlG3otdndGi2x4q//NkxPgfZBLWXHjFPIRUZ9vW0lIiCYjKD7QNjAVUUkOappvjsT1tOCM9LTVGYHDSM4atWVLXANbjGU3qWUR9LDlQXg5qTDnkTFgjoMtj28bj8fvmIo42hqDOhyjMQmUTgj1sCmlgYdGRskOMBoreVnP+7tUGA4h6BfXGJW4xtasfHTyHwiBxCEb5zbXSf3Gg//NUxP0eTArS9MMEXWzmVRvLSLBO0HKweSNDuQBG1hLdO05qAalUFYipwxInUGMMeuNZBE6njhKw9BErIKzDkCkdqiOUph9jUdFZFYytNVlZEtSqsowx7863dWbvYy3UrLZLCSd+3//6T5MilIvtT/vfXf10betV//NkxO4e8gLO/npGzMiJVkpUrUeN59bL5tJHE/icYofNbmGldofZlASPo2jIM8gmbKMYbu07GkdyCfLeeq3aa0/KkhTGCOzWEogyxkQpAQlIiCKdqPchZEuqsq2K7L2Z0RUu25KJTe9Vbu2VWbW7vKXEo//0/9ULvUq1a/o+/ps9LN6tt6OxZ1ZxrFoLKGlG//NkxPUevA7OVsJKOZ3VZFRImrdabjANYYgqbuYN3qGxcqOSsi7Xzq8kfDc6xCxZdxYcPWYddOHyN0TAQrVhxhRiw6DljtqSLyQF4dd1gtIJKBSRTdtSgfwiaeU3LO1iiWLsTuer0vY3apHXR0I9s2P////7b5q3TSqbZ8ezrc5B/2FunB3fEwFxMbE5pYZC//NUxP0e4+7KXHsEXWOXNxNSIgxeJFUacU83CXZQV+Mouy2ENIZuHYoNl4cJTy6n3Qvsb2Rfjv/hlYaexdkj0UfV1EHYLHRuXNh6j1ZbRqYqUyIdmSwrM8zERqsr3M53vdhyy7WWJQ5H/7TjgavVdct6b/UxzXQo//NkxOwfo1rC/njFOS7AkWLQMYMmAuG1tVKG30bcdkQZM6Il7VOcGyaxeP8LpyAHqxCqIxNFY9U2IiBu7jnvA9va2m7trnejRjxK4+g7Fo1IweYLKpHYYlbBlSSDkTGiyiJKrRLtFjE701ojNXR6yq8imOiFOSqXUp9f//9FeaqzGel/t/L96N9+iFe5Akcg//NkxPAd4i66/sGKmJKqqxFKZRIOOpiI1q0urbTjkQJD2wGYCP0iko5j81y2KRVm9BgNLUu4k8kR9EnMELG3OTbhLEGrieX8aPt6g/m5Uzk/k2bSBh2NeBJe/JSwG4Y2oddrZ1Cta7ylRabmfI7as0rIj90eYrojGXRBxsyv0//q+61dyqrXZC1/75v8ys63//NkxPsgw/q2/sJKXUm7apZamkq7GdjxiXWVRnBa2rjkcsRTZ9EghpU6zNlulJft94jStNdVqrLr0y8l44IcqG3watgLcJV3cnDCVcDTNN9T/hGj8YCZdV5soP4XO9u0HUQWdEH6GcrPNeWbaV8VlKh/5Xc+ZEdUdbF6M5st////9qsm5vpt+n/Vm1L6Pmsr//NkxPshVAamXnoE+Vms7HpMgMteSjaASddK5Nf7Kfdgdy4ToIdD0LFh/QyztBlG2pieRxyUhUSWJJs1e0ORL4ezRs9Tlr+a5XZnsCbo7DOyfZblb/P/5hsAedmdLs+zKfDtltI+kQVFIqGZiYqvCQ+tHM0UbW/qw4QBn/foHQOQPmB8dxyGL0UERcBEAgGg//NkxPgfXAKi/sGE2drDQncsyRNmxYlVtwXk0kkt/lyMVgVMkxTvaxakXd337sUcslmMZaB5oFhssYQC0Dr8ukd8QoxE6MYSlBjaDo1v4n3Wuv0Hhl4IjtlPUrMBVGMdGRyGaUqro5k2a1WlYx2V2dpqsu1qmZQbQbXUx6m////+qM3v5nKVqde82tNGRWLR//NkxP0hCm6i/nmG3E7EAtEZguZRKziTsCpDgFn/247triIVVYdLG0qhB78hQf+3kakS83OgRs7QFYKUxeuBRtPh1uWVS6MTNid1Jys5tc3GBmf/M73JlcUr3jHZLDFZtqO52ULRs7S6omivsVrMj7JpPsizbq7F2qX///fSRTslTI+7N/QoMl6G20+XZDOA//NkxPshK/qaXsGEvKq+fnFexrdtaro3At9SU5/ZWhWSqVAa04EiFgNujNlpVwgZAMVoVfu40SQIkSJEgh62UGkr8KxqS2eG/ao5CghFAauSR0aCoomXbCpHI5+xjKqSldNkm3s5mOz5FdDGQNHRTGmK5hQUWu12Qox4Z////qio+r0dE0N/dZktppovXXRv//NkxPkf466O3sGEvUXo92dFnJFZNS6BayiSpf/a810YKt+lGTo+tJRly6lariFoIFcgqkS1gaImi9xoZh2qpWQ9U9kdhpF4x4Lo4b2NmBb54O5HIMhBq6/1Iy5GRcPBzL2JboY+9S0sb1U7fDXLQz1FRDcfKmreqj2GXYx1FQwhP1VrfA1rGg2KHrWVVPjl//NkxPwgfAZ+PsJEfcfoY0CGUNVJPQoCrMJigVXEgp7/a4fB0EfkuoW6DJRluAvRXBB3U0kWK53EWma5orwfJNjkfIbnewqPGupiWwdMztTvQ1iP/yX7EeIGab2rPX5vZUyp/WTmGh6BmbPk/Uvk6/sXyVWFF9s+3z35R1IhJyk//XnUKtl6eQNaJtyWeqtJ//NkxP0hql52XsMQbAWhe9cKAOMgAp7gAbyIFI1YIICIUCLn5ZCw61CgSaiilTwqhogtkk7XEBd+MON7DS+uskD2GG3A+ivOaSv4YzgfYhBpZvcd/jJx9b6jvqFE867QlxRvZ2TTz8SzQP4wS6kCgAQyoFW/gATgJwXDMBuB8BXDgi0A7OSUM+M+SdqusHob//NUxPkeekpuXnmHGGuWBuP8MZGtcGIkxpuJzp+eJ4XlQs1K06zVma/yyNMh0iIFjhuezHhl81KHK/zXtMC5H+ZlbhNkw7/pllWHARqGJX9r0VKBIW7l5E122AYXkXzl0RhLVHRypOV7Q3vSxMENSxK3oLWPJm2x//NUxOoXMf5mXsMQcBtSMnWVI26nrXm05t/O/qaIgldS/F9rpexNiKnR6vgwXuhbxJiiAYAEJNLf6rkJVW7TbDipjqz/fEQI3VYrt+YCdnpcErThUQzdzWOTZlfR81IubyyiKW6NOUiSmZO/F79+0wCNmEaGyjJE//NExPgXobpm/oPWHRQroj30Zwiz8jrFajOA3IYnv+ykYSw+mEAxJbB1sd6oHFZ5+5fQv/qzJsNqirW7XIhucq6czvnU0s1ep6cutEU5o3CvqWyG7ua2rQgHIMGslksb//NExOwU6ZJmWMMWeAvKrPV+t3pGWrt2Jq+D3YbLuKsHllUY5xkA0qys/t1tIUdSFvfoyDFe4P8eT5PV5mT2zBprxWcXGUJjimGgNWEclHoS1QqqV6VBuJBFWxVz9NP2//NExOsUEYpe2MLGvb1LA5ohX24EsgdxtxCZHUzD9+Eu3Tq2MqWyLCNuc7x1JFCVKhwtypXMrdddawuelhHAXTFNNhS9Zpd6abBLgXKRWMDIEMvQewUt++AAzUfRXLlb//NExO0UsYpeWMMW6AYxGU6e6uMjv4tRBr5LAaGmJjWpE0m3Yw5oZiWpFkxSgjCTCugEKi1MQU1FMy4xMDBVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//NExO0R6SpeWMPQcVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//M0xPgReSZaeHsHCFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//M0xO0KgMpWWHsQKFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//MUxP0CKDY5QAhEBVVVVVVVVVVVVVVV//MUxPQAAAP8AAAAAFVVVVVVVVVVVVVV \ No newline at end of file
+SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2LjEwMAAAAAAAAAAAAAAA//OEwAAAAAAAAAAAAEluZm8AAAAPAAAAEQAADYAAHBwcHBwqKioqKio4ODg4ODhHR0dHR0dVVVVVVVVjY2NjY2NxcXFxcXGAgICAgICOjo6OjpycnJycnKqqqqqqqri4uLi4uMfHx8fHx9XV1dXV1ePj4+Pj4/Hx8fHx8f//////AAAAAExhdmM1OC4xMwAAAAAAAAAAAAAAACQDMAAAAAAAAA2An17QwwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//OExAAk7CHMAVoYAQMTFBxqHhyqB0JBulRlgi9H0THXW77/y+3nnTxiMRiMRikpOZgAgvQAEEiIiF10RERC/3d3fqbu7+jnp7uLAAAQiIiBAMDA3P/RE///c///////9/4ibgAhEREL/d//67u7uiIhf/7v6I7u/p/EREREd3c9C0RERP3d3/ocAAABELrgAAiIiBAADAwMDAwMWcDi3Ho72l3+P1gYaA5/MCltyYAttOwALBcuvBHVIRctmHBM//OExB8sazYMAZyYAIgeNSIk0T4HMo9EEY4ms4bl08SA0yfFhWzqNDNNSkRZY2iSTHGaMmu5oSaTpoBkcW9MLgximCloPemyOyhOZfPixkAPGj2st6LJ6k1JrZMwLjFxl3ZN0EK9a6mpVoLqrdBRPmykTyi4YKr2st913ehs6lLSouhNEGqWm6aVWicgIWRKi4sCA51j9RWzLxpBo0YzRSwwKFaJDm8z27HWTGAEAT8lkk5lruK4Ql9kAYCA0fzM//OExCAwKwJiX5iQAGMxoOXOukDRAkYh50GkA3MFlCkxOZoRWXxOp4lxfCcx2kMICLMFGEoCE4WFjLDvQJobA7xjhcY7hlxhkoGXCkOaHvj2gNkvHySYsMVigYGImwlRjAxkVTxBEFlA3KpaMDM0IoT0xMymfQMDRPlwpERL5r5TMThuv/Lg7zA8mbpl/0CJl8rk4s6j6RfPIo1pJ//8jCobnEK2TWyb83QLyrDaGYgJQUGOhEIC7Q4w0agUhGAk//OExBIrgnZQAZh4AKqYVKLGKhkuBAcqAFyXBIhDQfq4CNg3DCXLYWgZpPXBTF0JeSkh6EEvGAcg90EjHQlD3ItEq06y9nExqZmPtjV6BSLO2l7gl+iM6rU65c1hkjTzuKjiKym4DxWvIbRPvcPcjf9//MC1qZ1J8Q64gxfNr0+sJ5rtj3b4lf1fHZX0LGKP6bb36H+aFEu8fB41UA8sRKNQA9IADR+cmQCQBIINOPVvwFyKQY/IREMIW/jbigXD//OExBctqwqBlZh4AVVi67Cn1e5apfOLkMmYHilLyqhhhpnI4XBWSK00Y5hj1osbRwM50WPNCVCu3CoAHHmpQLbk1KhVRYLkqFw4zP4JBz7gnOzxlJNlkl8NngvYazC0/OPSFs7Iq5bXy/nxqO4Wfxozj4M07Ir7RGeSJWn+YjPHzu95v/8R8WrSFK+m36trM8syd5nU18U/z/nf/g0mg1//1jX/8O3nibsIST0CARSgBEx3Co4v0j2CwixY2ieQ//OExBMtAs6ArZh4AIi1wjM3dOkEiacgjTEK9LC2ogfQmxYC5kMEDO8/y9tDDCTIhp8HMK6ErIDd+QVnJUhI/VwLIGm5BoroWBKk9UCNQkq0NUOWFQhfIeWxZVStORYWW+IqVe2Kpc6abxlb1fO4TvmuDKv3zmmXyubdQGGs2WtsgeJFhbzjO/psZID/cLEHV//jevrM0bH9sVzN7Y36/ftSn//+v80l0haq3SIBHZl8kBid4i0YXB3GDQGkebzC//OExBIrOmJ8AZh4AJkDgbd0nwAkTIEOQ/QFcnhZCsIUJMDeL65HOLODTbxmuRbRNWQ8SUCADCMQW8UhPGqVySLiW0mw9RAhYSTrRjpwyB9IlhcFhEEtHpMFRGkrmqI5uKvvDaVWztisYW+71hj7g00yQnl4qvmla7S2kup86ta0NlbmyA3yRK/1jyYi5rAbN/ULUS/1jPv9wZYJsgBJsQX4IwGTZxnSkAGae1ADXgsEqHQYRtLhqaK2s9VpVqQQ//OExBgtoxaML5h4ASHJtw46sDsuOS4yS2H8oSxsA+DELiyqY0VpWK5pTZoLDYlE8iEcfqsN9I2cFYhhlrKcblC3RVcxrK+4H9EWzHOuO9V6rdtsCsK9odnkWW0aA4PI2KM72SDJmNmkWA16YoO3LwoMskPcCup4DljcVrmfYhVs9jfzTP3mr/DVFzLeAxv6X+NZt95cZNQtxv661n/Ns3f0f6xr/f//n8RVSgrw1FhYZaRgQk+hxTOj7b0A0qDi//OExBQnOuKAB9h4AENfg0iNk0Ww4c42R+aVTfIoVdiK2J9sJ04J+I2PLFz5hHAnT8aiGsphxEUS3JyRjQczB2woCExXeNLe5Q3l5Iq4ZdqvC4nbaYWKqfWY18YZNyzy33G083LPnPj+2v/XMsXGcX+f/nXl9t/eqWl/j/Hx//8b1/////T/vNwcf/NLRrnjJpZZGVRRCeDNWQhPLA1NxWUkSpKPCqG4rOBCBOFDuiVEExoPSNkSU0moWGU4d0c9//OExConctJ4BsPK/FWuRDmgSFFFG1LqOxGg6LM2k2JWUZ8Utq24EQoEC/MpqTNz0WXNI6MKdEs11DKibHZAfvISHyLtYgP5lBpfZ96wxwHsKKtUZdTyw5+5dhz9XuQJOFlJ4lOlUEEI8c4sUrqb+urU/xV0iSHtjBjwm9qqk5KlBfCzUtBwNswBvouIXPtA0kB3o6I4sVUVkcNMclBIKo0Z5KFgtJNzsZytN5I24Ubp2IizfFlfWEz9Gx221x51//OExD8lojp4BsMNaJFi1EZI/cwBUqOJhwToycrVYXYjsN1hhg9TQfaFiEeVzxtAr1PVkm3gfTE4HYHYY0DjK1LcV/o2IYrxLNN7q3vleEdVyJYtKLeB0SiAIMCYXNEw+xH9wCUF4J42BPTjA2jcCq5oTxPBIAjrxiKK61FV+cbDTsHeRjTmSRpslvFYn6sjsZO4qsUR+iWuQBVEwR2RmmYEZiD/ZUyqVUQ5YTjExITYx3RSTnLU+U+3FwiqOiIa//OExFsm8mZwBsPK/CRX9D8IgpsoKzk5oZXKEuBwukjK/jyLez+kZrtU3cKNus3GgxB8SjHRGI6ucQyo0T/5xJjBVlyDzCIAHg2WkP+hBWCkG4g6DLSF8hJXQAypakRA2nidhKNrqLEOq6hkUDifkJDjzbjlRzZMih5MSGK8ZCEEHQ5VhIT0HFEnDobhfq4mpzCQtZ7mwzrOmM8F2gnRTOx8PFK4sZbVCeNzsULIgrpC5dp13GuVMRNyRUrIj1Bs//OExHInYhJsBsPS3CS8pDGxPHBTiE+fdX5hQxH+/pplLK6agHFQy48GeKEgXNFjCFgJ6qXf/O6VGBM1mRiLfLSQOIQLMftClnYCa/wyp+7iLFAhDCk7ItiJhRRh3LTnEqIFGELgF+GoP0TAkQLYnIYLOiQmLHMbwxk8YZ9qUeNKaSJeTZcoJBDyPMiUWli7k2OYnUM3VMrjq5x0KkTAKIZKPQlJIkkVKCy8yLIp0pqcQtX1SofKemViRp2ZnItc//OExIcm8ipkBMPY2L69BWXP6YI5sDshhEHw2tiHh06VrQKAzVL4JlFkLocYMog0tw4FONFGVNlaGVKa2Uzr67ph9Eu0SIt6T2AZoZOTIXwoYtKVDJVoEqsoxJoWCBiC0qYL1ShUyxUC8P257q1I5bG9FBJTxLqzFtRqOS8yRPFnJrpDGVTpTBYXpCUJWWQ3odENgp04HXlsfIkJAyVp68JBKH/0rPhVNSDVzbr9NbjwdQKOrBNrRG6ulSVnheVo//OExJ4mIhpYBsPM3KAAr1RtRxZiXeWHMhUFQQNA05nNICanSF6MWr3Dasp1QstSeiGrDmqRPQ5XUFFEKOYG0SYuo/T2IUcw9TOyqZxYifBqkErZESPSdUZPKKMVRF4OUEGqkqiKsJxWAkehKHqYyJQjGQCjUQlRWEZVlzn2l329lacmR8u9l2q2szLK3rfjLrLoiLfBoGgKs7hoRZZ55apMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqqq//OExLgmCgo8AsPYnqqqqqqqqqqqqqqqqqqqqqqqqqqqqqoA1JoGdGhKGCgwjkasFDAg6B6LCtIwX1iotgUUFtQqZMhIXFaxUWD34Of/qF+tuLC4qKioqSfs/rFEGhUVJPxRsWFiILCQCigs3WKirv9YoLVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//OExJ0UKFX0FhhGAlVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV \ No newline at end of file
diff --git a/src/calls.js b/src/calls.js
new file mode 100644
index 0000000..8ff32e9
--- /dev/null
+++ b/src/calls.js
@@ -0,0 +1,464 @@
+// 1:1 voice and video calls (NIP-AC, the draft Amethyst, nospeak and Noscall
+// speak): WebRTC between the two devices, its setup carried over nostr.
+//
+// Every setup message (offer, answer, ICE candidate, hang-up, reject,
+// renegotiate) is an event signed by its sender and wrapped for its one
+// recipient in an ephemeral gift wrap (kind 21059: NIP-44 to them, under a
+// throwaway key, no seal). Relays see only who it's for. The sound and
+// picture go device to device, encrypted by WebRTC itself (DTLS-SRTP); the
+// fingerprints that pin that encryption ride in the signed offer and answer,
+// so nobody between can stand in for either side. When the two can't reach
+// each other directly, TURN relays the (still encrypted) packets.
+//
+// No DOM here: the app hands in how to sign, send, fetch ICE servers, open
+// the camera, and who may ring; it gets back the call's state to draw.
+import { finalizeEvent, generateSecretKey, verifyEvent } from 'nostr-tools/pure';
+import * as nip44 from 'nostr-tools/nip44';
+
+export const CALL_WRAP = 21059;
+export const CALL = { OFFER: 25050, ANSWER: 25051, ICE: 25052, HANGUP: 25053, REJECT: 25054, RENEGOTIATE: 25055 };
+const KINDS = new Set(Object.values(CALL));
+const ALT = {
+ [CALL.OFFER]: 'WebRTC call offer', [CALL.ANSWER]: 'WebRTC call answer', [CALL.ICE]: 'WebRTC ICE candidate',
+ [CALL.HANGUP]: 'WebRTC call hangup', [CALL.REJECT]: 'WebRTC call rejection', [CALL.RENEGOTIATE]: 'WebRTC call renegotiation',
+};
+export const STALE_S = 20; // older setup messages are a relay replaying the past
+export const RING_S = 60;
+const RING_MS = RING_S * 1000;
+const ENDED_MS = 2500; // how long "Call ended" stays up
+
+const now = () => Math.floor(Date.now() / 1000);
+const tagOf = (ev, k) => (ev.tags.find((x) => x[0] === k) || [])[1];
+export const callIdOf = (ev) => tagOf(ev, 'call-id');
+export const uuid = () => (globalThis.crypto && crypto.randomUUID ? crypto.randomUUID()
+ : 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => ((Math.random() * 16) | (c === 'x' ? 0 : 8)).toString(16)));
+
+// The unsigned setup message.
+export function callEvent(kind, to, callId, content = '', extra = []) {
+ return { kind, created_at: now(), content, tags: [['p', to], ['call-id', callId], ['alt', ALT[kind]], ...extra] };
+}
+// A signed one, wrapped for one recipient.
+export function wrapCall(signed, receiverPk) {
+ const eph = generateSecretKey();
+ return finalizeEvent({
+ kind: CALL_WRAP, created_at: now(), tags: [['p', receiverPk]],
+ content: nip44.encrypt(JSON.stringify(signed), nip44.getConversationKey(eph, receiverPk)),
+ }, eph);
+}
+// A wrap to us opened: the setup message inside, its signature good, or null
+// (not a call — Concord's presence beats ride the same kind — or not ours).
+// `decryptFrom(peerPk, ciphertext)`: our key's NIP-44 decryption.
+export async function openCall(wrap, decryptFrom) {
+ if (!wrap || wrap.kind !== CALL_WRAP) return null;
+ let inner;
+ try { inner = JSON.parse(await decryptFrom(wrap.pubkey, wrap.content)); } catch { return null; }
+ if (!inner || !KINDS.has(inner.kind) || !callIdOf(inner) || !verifyEvent(inner)) return null;
+ return inner;
+}
+// ICE candidates as the spec writes them: JSON of the three fields.
+export const candidateJson = (c) => JSON.stringify({ candidate: c.candidate, sdpMid: c.sdpMid, sdpMLineIndex: c.sdpMLineIndex });
+
+// The calls of one identity. env:
+// me() our pubkey
+// sign(template) → signed event (our key or signer)
+// send(peerPk, signed) wrap and publish to them (the app picks the relays)
+// iceServers() → RTCIceServer[] (TURN from coinos, STUN at least)
+// media(type, facing) → MediaStream: microphone, and camera for 'video'
+// mayRing(pk) 'ring' (someone followed, or written to), 'quiet' (anyone else:
+// no ring, but the call is told of, as missed), or null (muted: nothing)
+// changed() the call's state moved: draw it
+// ended(record) a call is over: { id, peer, type, dir, reason, connected, seconds, at } for its log
+// trickle() false for a signer that's slow or asks each time (a
+// bunker, Amber): the candidates go inside the offer or
+// answer instead of one signed message each
+// warm(pk) a call with them may be coming: look up what sending to
+// them takes (their relays, TURN) ahead of it
+// RTCPeerConnection (tests may pass their own)
+export function createCalls(env) {
+ const PC = env.RTCPeerConnection || globalThis.RTCPeerConnection;
+ let call = null; // { id, peer, type, dir, state, reason, pc, local, remote, offer, remoteSet, ice: [], at, connectedAt, muted, camOff, facing }
+ const seen = new Set();
+ const early = new Map(); // peer -> candidates that came before their call did
+ let endTimer = null, ringTimer = null;
+ const changed = () => { try { env.changed(); } catch {} };
+
+ async function sendFor(c, kind, to, content = '', extra = []) {
+ const signed = await env.sign(callEvent(kind, to, c.id, content, extra));
+ await env.send(to, signed);
+ }
+
+ function stopMedia(c) {
+ for (const s of [c.local]) if (s) for (const t of s.getTracks()) { try { t.stop(); } catch {} }
+ for (const t of [c.cam, c.screen]) if (t) { try { t.stop(); } catch {} } // the camera set aside while sharing
+ try { c.pc && c.pc.close(); } catch {}
+ }
+ function end(reason, c = call) {
+ if (!c || c !== call || c.state === 'ended') return;
+ clearTimeout(ringTimer);
+ stopMedia(c);
+ c.state = 'ended'; c.reason = reason; c.endedAt = Date.now();
+ changed();
+ try {
+ if (env.ended) env.ended({ id: c.id, peer: c.peer, type: c.type, dir: c.dir, reason, at: c.offerAt || c.at, connected: !!c.connectedAt,
+ seconds: c.connectedAt ? Math.round((c.endedAt - c.connectedAt) / 1000) : 0 });
+ } catch {}
+ clearTimeout(endTimer);
+ endTimer = setTimeout(() => { if (call === c) { call = null; changed(); } }, ENDED_MS);
+ }
+
+ // (iceCandidatePoolSize: the routes — TURN's included, which take a round
+ // trip to allocate — are gathered from the start, not from the answer on)
+ async function connection(c) {
+ const pc = new PC({ iceServers: await env.iceServers(), bundlePolicy: 'max-bundle', iceCandidatePoolSize: 2 });
+ c.pc = pc;
+ c.remote = new MediaStream();
+ pc.ontrack = (e) => {
+ for (const t of (e.streams[0] || { getTracks: () => [e.track] }).getTracks()) if (!c.remote.getTracks().includes(t)) c.remote.addTrack(t);
+ // a picture that stops coming (they stopped sharing, camera and all) mutes
+ e.track.onmute = e.track.onunmute = changed;
+ changed();
+ };
+ c.trickle = env.trickle ? env.trickle() !== false : true;
+ c.sent = [];
+ pc.onicecandidate = (e) => {
+ // the routes found before the offer or answer went ride inside it;
+ // only the late ones go one by one (one signed message each — dozens
+ // of them got the household's IP rate-limited on the relays, and the
+ // answer refused with them)
+ if (!c.trickle || !c.described || !e.candidate || call !== c || c.state === 'ended') return;
+ if (c.described.includes(e.candidate.candidate)) return;
+ c.sent.push(e.candidate);
+ sendFor(c, CALL.ICE, c.peer, candidateJson(e.candidate)).catch(() => {});
+ };
+ pc.onconnectionstatechange = () => {
+ if (call !== c) return;
+ const s = pc.connectionState;
+ if (s === 'connected' && c.state !== 'connected') { c.state = 'connected'; c.connectedAt = Date.now(); clearTimeout(ringTimer); changed(); }
+ else if (s === 'failed') end('failed', c);
+ };
+ if (c.local) for (const t of c.local.getTracks()) pc.addTrack(t, c.local);
+ return pc;
+ }
+ // While a call rings: its connection made and the offer set, the routes
+ // gathering — everything but the microphone and camera, which wait for
+ // Answer. Answering then only adds them and replies (it used to do all of
+ // this after the tap, seconds of "Connecting…").
+ async function prepare(c) {
+ const pc = await connection(c);
+ if (call !== c || c.state === 'ended') { try { pc.close(); } catch {} return null; }
+ await pc.setRemoteDescription({ type: 'offer', sdp: c.offer });
+ c.remoteSet = true;
+ await addCandidates(c);
+ return pc;
+ }
+ // our tracks into the transceivers the offer made
+ function attachLocal(c) {
+ const trs = c.pc.getTransceivers();
+ for (const track of c.local.getTracks()) {
+ const tr = trs.find((x) => !x.sender.track && x.receiver.track && x.receiver.track.kind === track.kind && !x.stopped);
+ if (tr) {
+ tr.sender.replaceTrack(track);
+ tr.direction = 'sendrecv';
+ try { tr.sender.setStreams && tr.sender.setStreams(c.local); } catch {}
+ } else c.pc.addTrack(track, c.local);
+ }
+ }
+ // Without trickle: the description once it holds routes enough — one
+ // through the router (srflx) and one through TURN (relay) — or after a
+ // second and a half. Waiting for gathering to finish took up to 4 s (TURN
+ // over TCP and TLS is slow to give up), all of it after the tap.
+ async function described(c) {
+ const pc = c.pc;
+ const enough = () => pc.iceGatheringState === 'complete'
+ || (/ typ srflx/.test(pc.localDescription.sdp) && / typ relay/.test(pc.localDescription.sdp));
+ if (!enough()) {
+ await new Promise((resolve) => {
+ const check = () => { if (enough()) resolve(); };
+ pc.addEventListener('icegatheringstatechange', check);
+ pc.addEventListener('icecandidate', check);
+ setTimeout(resolve, 1500);
+ });
+ }
+ const sdp = pc.localDescription.sdp;
+ // what it carries isn't sent again; what comes later is (trickle)
+ c.described = sdp;
+ return sdp;
+ }
+ async function addCandidates(c) {
+ const list = [...(early.get(c.peer) || []), ...c.ice];
+ early.delete(c.peer); c.ice = [];
+ for (const cand of list) { try { await c.pc.addIceCandidate(cand); } catch {} }
+ }
+
+ // ---- what the person does
+ async function start(peer, type = 'voice') {
+ if (call && call.state !== 'ended') throw new Error('busy');
+ clearTimeout(endTimer);
+ const c = call = { id: uuid(), peer, type, dir: 'out', state: 'starting', ice: [], at: Date.now(), muted: false, camOff: false, facing: 'user' };
+ changed();
+ try {
+ c.local = await env.media(type, c.facing);
+ if (call !== c) { stopMedia(c); return c; }
+ const pc = await connection(c);
+ await pc.setLocalDescription(await pc.createOffer());
+ c.state = 'offering';
+ changed();
+ await sendFor(c, CALL.OFFER, peer, await described(c), [['call-type', type]]);
+ ringTimer = setTimeout(() => { if (call === c && c.state === 'offering') { sendFor(c, CALL.HANGUP, peer, 'timeout').catch(() => {}); end('no-answer', c); } }, RING_MS);
+ } catch (e) {
+ end(e && e.name === 'NotAllowedError' ? 'no-permission' : 'error', c);
+ }
+ return c;
+ }
+ async function accept() {
+ const c = call;
+ if (!c || c.state !== 'incoming') return;
+ clearTimeout(ringTimer);
+ c.state = 'connecting';
+ changed();
+ try {
+ const [local, ready] = await Promise.all([env.media(c.type, c.facing), (c.prep || Promise.resolve(null)).catch(() => null)]);
+ c.local = local;
+ if (call !== c) { stopMedia(c); return; }
+ let pc = ready;
+ if (pc && pc.signalingState === 'have-remote-offer') attachLocal(c);
+ else { // nothing made while it rang (or it failed): all of it now
+ try { pc && pc.close(); } catch {}
+ pc = await connection(c);
+ await pc.setRemoteDescription({ type: 'offer', sdp: c.offer });
+ c.remoteSet = true;
+ await addCandidates(c);
+ }
+ await pc.setLocalDescription(await pc.createAnswer());
+ const signed = await env.sign(callEvent(CALL.ANSWER, c.peer, c.id, await described(c)));
+ await env.send(c.peer, signed);
+ // our other devices stop ringing: answered here
+ env.send(env.me(), await env.sign(callEvent(CALL.ANSWER, env.me(), c.id, ''))).catch(() => {});
+ } catch (e) {
+ sendFor(c, CALL.HANGUP, c.peer, 'error').catch(() => {});
+ end(e && e.name === 'NotAllowedError' ? 'no-permission' : 'error', c);
+ }
+ }
+ async function reject() {
+ const c = call;
+ if (!c || c.state !== 'incoming') return;
+ sendFor(c, CALL.REJECT, c.peer).catch(() => {});
+ env.sign(callEvent(CALL.REJECT, env.me(), c.id)).then((s) => env.send(env.me(), s)).catch(() => {});
+ end('declined', c);
+ }
+ function hangup() {
+ const c = call;
+ if (!c || c.state === 'ended') return;
+ if (c.state === 'incoming') { reject(); return; }
+ sendFor(c, CALL.HANGUP, c.peer).catch(() => {});
+ end('hung-up', c);
+ }
+ function setMuted(on) {
+ if (!call || !call.local) return;
+ call.muted = on;
+ for (const t of call.local.getAudioTracks()) t.enabled = !on;
+ changed();
+ }
+ function setCamOff(on) {
+ if (!call || !call.local) return;
+ call.camOff = on;
+ for (const t of call.local.getVideoTracks()) t.enabled = !on;
+ changed();
+ }
+ // A voice call turned video: our camera into the call, by a new offer
+ // (NIP-AC's renegotiate). Into the video transceiver their camera already
+ // came by if there is one, else a new one. The other side sees us at once
+ // and gets the same button for theirs.
+ async function addVideo() {
+ const c = call;
+ if (!c || c.state !== 'connected' || !c.pc || !c.local || c.local.getVideoTracks().length) return;
+ try {
+ const fresh = await env.media('video-only', c.facing);
+ const track = fresh.getVideoTracks()[0];
+ if (call !== c || c.state !== 'connected') { track.stop(); return; }
+ // a new stream object, so the preview picks the camera up
+ c.local = new MediaStream([...c.local.getTracks(), track]);
+ const tr = c.pc.getTransceivers().find((x) => !x.stopped && !x.sender.track && x.receiver.track && x.receiver.track.kind === 'video');
+ if (tr) { await tr.sender.replaceTrack(track); tr.direction = 'sendrecv'; try { tr.sender.setStreams && tr.sender.setStreams(c.local); } catch {} }
+ else c.pc.addTrack(track, c.local);
+ c.type = 'video'; c.camOff = false;
+ changed();
+ await renegotiate(c);
+ } catch {}
+ }
+ async function renegotiate(c) {
+ c.renegotiating = true;
+ await c.pc.setLocalDescription(await c.pc.createOffer());
+ await sendFor(c, CALL.RENEGOTIATE, c.peer, c.pc.localDescription.sdp);
+ }
+ // Your screen in the call: in the camera's place if it's on (a swap, no new
+ // offer), else into the video slot by a renegotiation, as addVideo does.
+ // Stopping — here or from the browser's own Stop sharing — brings the
+ // camera back if it was on, else stops sending a picture.
+ async function shareScreen() {
+ const c = call;
+ if (!c || c.state !== 'connected' || !c.pc || c.sharing) return;
+ let track;
+ try { track = (await env.media('screen')).getVideoTracks()[0]; } catch { return; }
+ if (!track) return;
+ if (call !== c || c.state !== 'connected') { track.stop(); return; }
+ try { track.contentHint = 'detail'; } catch {}
+ const cam = c.local.getVideoTracks()[0] || null;
+ Object.assign(c, { sharing: true, screen: track, cam });
+ c.local = new MediaStream([...c.local.getAudioTracks(), track]);
+ let renego = false;
+ const sender = c.pc.getSenders().find((x) => x.track && x.track.kind === 'video');
+ if (sender) await sender.replaceTrack(track);
+ else {
+ const tr = c.pc.getTransceivers().find((x) => !x.stopped && !x.sender.track && x.receiver.track && x.receiver.track.kind === 'video');
+ if (tr) { await tr.sender.replaceTrack(track); if (tr.direction !== 'sendrecv') { tr.direction = 'sendrecv'; renego = true; } }
+ else { c.pc.addTrack(track, c.local); renego = true; }
+ }
+ c.type = 'video';
+ track.onended = () => { if (call === c && c.screen === track) stopShare(); };
+ changed();
+ if (renego) await renegotiate(c).catch(() => {});
+ }
+ async function stopShare() {
+ const c = call;
+ if (!c || !c.sharing) return;
+ const track = c.screen, cam = c.cam;
+ Object.assign(c, { sharing: false, screen: null, cam: null });
+ try { track.stop(); } catch {}
+ if (!c.pc || c.state === 'ended') return;
+ const sender = c.pc.getSenders().find((x) => x.track === track);
+ if (cam && cam.readyState === 'live') {
+ if (sender) await sender.replaceTrack(cam).catch(() => {});
+ c.local = new MediaStream([...c.local.getAudioTracks(), cam]);
+ changed();
+ return;
+ }
+ c.local = new MediaStream(c.local.getAudioTracks());
+ changed();
+ if (sender) {
+ await sender.replaceTrack(null).catch(() => {});
+ const tr = c.pc.getTransceivers().find((x) => x.sender === sender);
+ if (tr && !tr.stopped) { tr.direction = 'recvonly'; await renegotiate(c).catch(() => {}); }
+ }
+ }
+ // the other camera: the sender's track swapped, no new offer needed
+ async function flip() {
+ const c = call;
+ if (!c || !c.local || !c.local.getVideoTracks().length) return;
+ const facing = c.facing === 'user' ? 'environment' : 'user';
+ try {
+ const fresh = await env.media('video-only', facing);
+ const track = fresh.getVideoTracks()[0];
+ const sender = c.pc && c.pc.getSenders().find((s) => s.track && s.track.kind === 'video');
+ if (sender) await sender.replaceTrack(track);
+ for (const old of c.local.getVideoTracks()) { c.local.removeTrack(old); old.stop(); }
+ track.enabled = !c.camOff;
+ c.local.addTrack(track);
+ c.facing = facing;
+ changed();
+ } catch {}
+ }
+
+ // ---- what arrives
+ // `maxAge`: an offer the service worker kept from a push may be older than
+ // a relay's live one (the person had to tap the notification): it still
+ // rings, for what's left of its minute
+ async function handle(ev, { maxAge = STALE_S } = {}) {
+ if (!ev || seen.has(ev.id)) return;
+ if (now() - ev.created_at > maxAge) return;
+ seen.add(ev.id);
+ if (seen.size > 5000) seen.clear();
+ const me = env.me();
+ const id = callIdOf(ev), from = ev.pubkey, self = from === me;
+ const c = call;
+ switch (ev.kind) {
+ case CALL.OFFER: {
+ if (self) return;
+ if (c && c.state !== 'ended') {
+ if (c.id !== id) { const s = await env.sign(callEvent(CALL.REJECT, from, id, 'busy')); env.send(from, s).catch(() => {}); }
+ return;
+ }
+ const may = await env.mayRing(from);
+ if (!may) return;
+ if (may === 'quiet') {
+ // not someone who rings us: no ring, but not nothing either — it's
+ // logged as a call that didn't ring
+ try { if (env.ended) env.ended({ id, peer: from, type: tagOf(ev, 'call-type') === 'video' ? 'video' : 'voice', dir: 'in', reason: 'unrung', connected: false, seconds: 0, at: ev.created_at * 1000 }); } catch {}
+ return;
+ }
+ clearTimeout(endTimer);
+ const type = tagOf(ev, 'call-type') === 'video' ? 'video' : 'voice';
+ const n = call = { id, peer: from, type, dir: 'in', state: 'incoming', offer: ev.content, ice: [], at: Date.now(), offerAt: ev.created_at * 1000, muted: false, camOff: false, facing: 'user' };
+ ringTimer = setTimeout(() => { if (call === n && n.state === 'incoming') end('missed', n); }, Math.max(5000, RING_MS - (Date.now() - ev.created_at * 1000)));
+ changed();
+ try { if (env.warm) env.warm(from); } catch {}
+ n.prep = prepare(n).catch(() => null);
+ return;
+ }
+ case CALL.ANSWER: {
+ if (!c || c.id !== id) return;
+ if (self) { if (c.state === 'incoming') end('answered-elsewhere', c); return; } // another of our devices took it
+ if (from !== c.peer) return;
+ if (c.state === 'offering') {
+ c.state = 'connecting'; changed();
+ try { await c.pc.setRemoteDescription({ type: 'answer', sdp: ev.content }); c.remoteSet = true; await addCandidates(c); }
+ catch { end('error', c); return; }
+ // Our candidates went out while they rang — to an app that may have
+ // been closed then (woken by a push, it heard none of them). Once
+ // more, now that they're listening; a repeat is harmless.
+ if (c.trickle) for (const cand of c.sent || []) sendFor(c, CALL.ICE, c.peer, candidateJson(cand)).catch(() => {});
+ } else if (c.renegotiating) { // their answer to our renegotiation
+ c.renegotiating = false;
+ try { await c.pc.setRemoteDescription({ type: 'answer', sdp: ev.content }); } catch {}
+ }
+ return;
+ }
+ case CALL.ICE: {
+ if (self) return;
+ let cand; try { cand = JSON.parse(ev.content); } catch { return; }
+ if (c && c.id === id && from === c.peer) {
+ if (c.pc && c.remoteSet) { try { await c.pc.addIceCandidate(cand); } catch {} }
+ else c.ice.push(cand);
+ } else {
+ // before the offer that opens its call: kept for when it does
+ const list = early.get(from) || []; list.push(cand); early.set(from, list.slice(-50));
+ }
+ return;
+ }
+ case CALL.HANGUP: {
+ if (self || !c || c.id !== id || from !== c.peer) return;
+ end(c.state === 'incoming' ? 'missed' : 'peer-hung-up', c);
+ return;
+ }
+ case CALL.REJECT: {
+ if (!c || c.id !== id) return;
+ if (self) { if (c.state === 'incoming') end('declined-elsewhere', c); return; }
+ if (from !== c.peer) return;
+ end(ev.content === 'busy' ? 'busy' : 'peer-declined', c);
+ return;
+ }
+ case CALL.RENEGOTIATE: {
+ if (self || !c || c.id !== id || from !== c.peer || !c.pc) return;
+ try {
+ if (c.pc.signalingState === 'have-local-offer') {
+ if (me > from) return; // ours wins (the higher key), theirs is dropped
+ await c.pc.setLocalDescription({ type: 'rollback' });
+ }
+ await c.pc.setRemoteDescription({ type: 'offer', sdp: ev.content });
+ await c.pc.setLocalDescription(await c.pc.createAnswer());
+ await sendFor(c, CALL.ANSWER, c.peer, c.pc.localDescription.sdp);
+ // they turned their camera on: this is a video call now
+ if (c.type !== 'video' && /^m=video [1-9]/m.test(ev.content)) { c.type = 'video'; changed(); }
+ } catch {}
+ return;
+ }
+ }
+ }
+
+ return {
+ get call() { return call; },
+ start, accept, reject, hangup, setMuted, setCamOff, flip, addVideo, shareScreen, stopShare, handle,
+ // a sign-out or account switch: whatever was going on ends here
+ stop() { if (call && call.state !== 'ended') hangup(); call = null; early.clear(); },
+ };
+}
diff --git a/src/concord.js b/src/concord.js
index 63a83b9..521bfc8 100644
--- a/src/concord.js
+++ b/src/concord.js
@@ -187,6 +187,11 @@ export const foldControl = (entries, { ownerHex, cid }) => {
// entries: [{ rumor, author }] — group by (vsk, eid), take highest intact version
let byEntity = new Map();
for (let e of entries) {
+ // Only the owner's editions are honored below, so only they compete for
+ // a head: anyone holding the control stream's key (every member of a
+ // public community) could otherwise sign a higher version and blank the
+ // owner's ban list, name or channels.
+ if (e.author !== ownerHex) continue;
let tag = (k) => e.rumor.tags?.find((t) => t[0] === k)?.[1];
let vsk = tag("vsk"), eid = tag("eid"), ev = +tag("ev");
if (vsk === undefined || !eid || !(ev >= 1)) continue;
@@ -225,6 +230,26 @@ export const foldControl = (entries, { ownerHex, cid }) => {
return state;
};
+// The owner's ban list as it stands: the head edition (its version, and the
+// hash a successor chains to) and the keys on it. Same winner as the fold.
+export const banlistHead = (entries, { ownerHex, cid }) => {
+ let eid = banlistEid(cid), cur = null;
+ for (let e of entries) {
+ if (e.author !== ownerHex || e.rumor.kind !== 3308) continue;
+ let tag = (k) => e.rumor.tags?.find((t) => t[0] === k)?.[1];
+ let ev = +tag("ev");
+ if (tag("vsk") !== "4" || tag("eid") !== eid || !(ev >= 1)) continue;
+ if (!cur || ev > cur.ev || (ev === cur.ev && e.rumor.id < cur.id)) cur = { ev, id: e.rumor.id, ep: tag("ep") || null, content: e.rumor.content };
+ }
+ let list = [];
+ try { let c = cur && JSON.parse(cur.content); if (Array.isArray(c)) list = c.filter((x) => /^[0-9a-f]{64}$/.test(x)); } catch {}
+ return { eid, version: cur ? cur.ev : 0, hash: cur ? editionHash(eid, cur.ev, cur.ep, cur.content) : null, list };
+};
+
+// The next ban-list edition: `list` replaces the one that stands.
+export const makeBanlist = (head, list, nowMs) =>
+ makeEdition({ vsk: 4, eid: head.eid, version: head.version + 1, prev: head.hash || undefined, content: JSON.stringify(list) }, nowMs);
+
// ---- CORD-02 §5 guestbook fold ----
// entries: [{ rumor, author }], returns Map(npub -> { state: 'join'|'leave'|'kick', t })
export const foldGuestbook = (entries, { nowMs, banned = new Set(), ownerHex } = {}) => {
diff --git a/src/cordn-client.js b/src/cordn-client.js
index d09488d..e0be08b 100644
--- a/src/cordn-client.js
+++ b/src/cordn-client.js
@@ -67,14 +67,16 @@ export function cordnClient({ scope, pubkey, identity, on, coordinator = C.DEFAU
// never used unasked.
if (id.signer.interactive && !interactive) return null;
if (!id.signer.decryptFrom) return null;
- return { raw: null, sign: (e) => id.signer.signEvent(e), decrypt: (peer, ct) => id.signer.decryptFrom(peer, ct) };
+ return { raw: null, obj: id.signer, sign: (e) => id.signer.signEvent(e), decrypt: (peer, ct) => id.signer.decryptFrom(peer, ct) };
}
// The transport, once a signer can back it. Rebuilt if the signer changes.
async function transport(opts) {
const s = await signer(opts);
if (!s) return null;
- const key = s.raw ? Array.from(s.raw.slice(0, 8)).join(',') : 'adapter';
+ // a remote signer that reconnected is a new object: the old one is
+ // closed ("not open anymore"), so the transport must follow it
+ const key = s.raw ? Array.from(s.raw.slice(0, 8)).join(',') : s.obj;
if (cvm && cvmSigner === key) return cvm;
if (cvm) cvm.stop();
cvmSigner = key;
diff --git a/src/dm-inbox.js b/src/dm-inbox.js
index b9eec3a..58fc72d 100644
--- a/src/dm-inbox.js
+++ b/src/dm-inbox.js
@@ -15,6 +15,8 @@
// notification instead of a filtered one.
import { unwrapDM } from './dm.js';
+import { openCall, CALL, RING_S } from './calls.js';
+import * as nip44 from 'nostr-tools/nip44';
const DB = 'coinos-dm-inbox';
const STORE = 'inbox';
@@ -115,3 +117,28 @@ export function shouldNotifyDm(verdict) {
if (verdict.followed || verdict.known) return true;
return !verdict.hasList;
}
+
+// A call ringing in (NIP-AC), the wrap a push pointed at: opened with the key
+// it's for, and worth ringing only as a fresh offer from someone this
+// account follows or talks to, and hasn't muted. Returns { offer, name,
+// type } to ring with, or null for anything else (a candidate, a stranger,
+// a stale one, a wrap we hold no key for); `quiet` for a caller who
+// may not ring us (not followed, not written to).
+export async function classifyCall(wrap, inboxes, nowS = Math.floor(Date.now() / 1000)) {
+ for (const rec of inboxes) {
+ if (!rec || !rec.sk) continue;
+ let sk;
+ try { sk = unhex(rec.sk); } catch { continue; }
+ const ev = await openCall(wrap, async (pk, ct) => nip44.decrypt(ct, nip44.getConversationKey(sk, pk)));
+ if (!ev) continue;
+ const from = ev.pubkey;
+ if (ev.kind !== CALL.OFFER || from === rec.pubkey || nowS - ev.created_at > RING_S) return null;
+ if ((rec.muted || []).includes(from)) return null;
+ const type = (ev.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice';
+ // someone not followed nor written to doesn't ring — `quiet`: the app
+ // lists it as a call that didn't ring, next time it opens
+ const quiet = !(rec.follows || []).includes(from) && !(rec.rings || rec.known || []).includes(from);
+ return { offer: ev, name: (rec.names || {})[from] || null, type, quiet };
+ }
+ return null;
+}
diff --git a/src/features/ark.js b/src/features/ark.js
index cbfd1b9..2c1a581 100644
--- a/src/features/ark.js
+++ b/src/features/ark.js
@@ -1,12 +1,14 @@
+import { momentTags, momentToggle, mediaClock } from '../media-timeline.js';
// Ark feature — off-chain payments via an ASP (Second's bark/captaind
// protocol, spoken natively by ../ark). Receive address + boarding, instant
// sends, history entries, refresh/consolidation, server settings.
+import { zapAddrOf } from '../live.js';
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, backstopMargin } 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
@@ -16,6 +18,17 @@ function freeCoins(st) {
const busy = new Set(remoteRenewalsInFlight(st).flatMap((r) => r.inputIds || []));
return (st.vtxos || []).filter((v) => v.state === 'spendable' && !busy.has(v.id));
}
+// The coins a unilateral exit can still take on-chain. Past its timelock a
+// coin's tree is the server's to sweep (and it has): only the server can
+// honor it now, and it does — but no exit transaction will ever confirm.
+function exitableCoins(st, tip) {
+ return freeCoins(st).filter((v) => !(tip && v.expiryHeight && v.expiryHeight <= tip));
+}
+// The crash-loop guard's phase notes (build.js BOOT_GUARD, app.js bootPhase):
+// a boot iOS killed shows the last one it reached, and three in a row open
+// the app in safe mode, where nothing connects on its own.
+const bootPhase = (p) => { try { localStorage.setItem('coinos-boot-phase', p); } catch {} };
+const safeBoot = () => !!(typeof window !== 'undefined' && window.__safeBoot);
import { loadBg, saveBg, buildBg, disarmSiblingRecords } from '../nwc-bg.js';
import { boardFee, p2trAddress } from '../ark/board.js';
import { maybeBolt11, maybeLnInvoice, lnSendFee, lnShortfall } from '../ark/lightning.js';
@@ -30,7 +43,7 @@ import { t } from '../i18n.js';
import { rateNow } from '../rates.js';
import { resolveBip353, parsePaymentName, parseBip21 as parseBip21Uri } from '../bip353.js';
import { parseZapTarget, fetchPayParams, requestInvoice } from '../lnurl.js';
-import { shortAddr, shortTxid, timeAgo, fmtSats, ARK_ICON, ARK_MARK, BITCOIN_ICON } from '../format.js';
+import { shortAddr, shortTxid, timeAgo, fmtSats, fmtBtc, ARK_ICON, ARK_MARK, BITCOIN_ICON } from '../format.js';
// t?ark1… bech32m — an Ark address for this or another ASP.
export function isArkAddress(a) { return /^t?ark1[a-z0-9]{20,}$/i.test((a || '').trim()); }
@@ -64,11 +77,15 @@ if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flushAll(); });
}
+// A read-only look at the stored state (stub wallets in tests have only loadArkState).
+const peekArk = (wallet, url) => (wallet.peekArkState ? wallet.peekArkState(url) : wallet.loadArkState(url));
+
// Wallet storage/key helpers for this feature, installed onto the core
// wallet instance so a build without the feature ships none of it.
export function installArkWallet(wallet) {
if (wallet.loadArkState) return; // already installed
const store = arkStore(); // IndexedDB-backed, memory-fronted; opens now
+ const peekOwnerOk = new WeakSet(); // stored states whose owner check passed
Object.assign(wallet, {
_arkStore: store,
// ---- Ark support -------------------------------------------------------
@@ -120,6 +137,21 @@ export function installArkWallet(wallet) {
return st;
} catch { return null; }
},
+ // loadArkState for readers that only look (see ArkStore.peek): the stored
+ // object, no copy — never mutate it. Misfiled state goes through
+ // loadArkState's repair; each object's owner is decoded once.
+ peekArkState(url) {
+ try {
+ const st = store.peek(this._arkKey(url));
+ if (!st) return null;
+ if (!peekOwnerOk.has(st)) {
+ const owner = this._arkVtxoOwner(st);
+ if (owner && st.serverPubkey && owner !== st.serverPubkey) return this.loadArkState(url);
+ peekOwnerOk.add(st);
+ }
+ return st;
+ } catch { return null; }
+ },
// Offer up pre-namespacing state, but only to the ASP that actually
// cosigned it. Its owner is read from the state's own stamp, or failing
// that decoded straight out of a vtxo — the vtxo wire format carries the
@@ -452,8 +484,58 @@ export function arkFeature(ctx) {
// One manager per open wallet; null when Ark is off in Settings, watch-only,
// or not yet dialed (lazy: fresh wallets connect on first use).
let ark = null;
+ // The same manager the moment its own init is done (server info, tip,
+ // persisted coins) — before the Nostr snapshot restore that `ark` also
+ // waits for, which can take ten seconds on a slow relay/Blossom day. For
+ // READING only: the pages price and label coins from it; anything that
+ // acts (a renewal, an exit) still waits for `ark`.
+ let arkInited = null;
+ const arkView = () => ark || arkInited;
+ // An amount in bitcoin terms whatever the display unit: sats, or BTC when
+ // that is the unit chosen — never fiat. A co-operative exit moves coins,
+ // and the number on its button is the coins' own.
+ const fmtNative = (sat) => (unitLabel() === 'BTC' ? fmtBtc(sat) + ' BTC' : fmtSats(sat) + ' sats');
+ // The last server info and chain tip seen, per server, so the first paint
+ // after a refresh shows the real renewal price and expiries instead of
+ // "free" and "—" for the half second the info call takes.
+ const ARK_INFO_KEY = 'btc-wallet-arkinfo:';
+ function cachedArkInfo(url) {
+ try { return url ? JSON.parse(localStorage.getItem(ARK_INFO_KEY + url) || 'null') : null; } catch { return null; }
+ }
+ function rememberArkInfo(url, info, tip) {
+ try {
+ if (!url || !info) return;
+ // no tip yet (right after init): keep the last one seen, dated as it was
+ const prev = tip ? null : cachedArkInfo(url);
+ localStorage.setItem(ARK_INFO_KEY + url, JSON.stringify(tip ? { info, tip, at: Date.now() } : { info, tip: (prev && prev.tip) || 0, at: (prev && prev.at) || Date.now() }));
+ } catch {}
+ }
+ // Whether Savings can fund a move into Spending at all: the server's board
+ // minimum (1,000 sats on coinos) plus the board transaction's chain fee.
+ // A Savings balance under that — 546 sats, say — must not be offered a
+ // move the board panel then refuses with "Needs at least 1,000 sats"; the
+ // way into Spending for it is a Lightning receive, which lands there
+ // directly. The minimum comes from the live manager or the last copy of
+ // the server's info seen, so the answer is right before connect too.
+ function savingsBoardMin() {
+ const info = (ark && ark.info) || ((cachedArkInfo((getArkConfig() || {}).ark) || {}).info) || null;
+ return info ? (info.minBoardAmountSat || 0) : 1000;
+ }
+ function savingsCanBoard() {
+ if (!arkAvailable()) return false;
+ const min = savingsBoardMin();
+ if (min >= 2_100_000_000_000_000 || wallet.spendable < min) return false; // paused, or short
+ try { return previewBoardFunding(wallet, ark, min).fundingSat >= min; } catch { return false; } // the fee on top
+ }
+ // the tip, live or estimated from the last one seen (a block per ten minutes)
+ function arkTipNow(mgr) {
+ if (mgr && mgr._tipH) return mgr._tipH;
+ const c = cachedArkInfo((getArkConfig() || {}).ark);
+ return c && c.tip ? c.tip + Math.floor((Date.now() - (c.at || Date.now())) / 600_000) : 0;
+ }
let arkTimer = null;
let arkConnectPromise = null;
+ let arkInitPromise = null; // the manager's own init, apart from the snapshot gate
let arkInitGen = 0; // guards against a stale init() resolving after a wallet switch
function stopArk() {
@@ -472,7 +554,9 @@ export function arkFeature(ctx) {
clearTimeout(lnTagT);
lnTagSeen = -1;
ark = null;
+ arkInited = null;
arkConnectPromise = null;
+ arkInitPromise = null;
// The renewal warning describes the coins of the wallet we're leaving.
// Switching accounts used to carry it onto the next one — with the old
// wallet's amount and deadline, over the new wallet's balance — and the
@@ -489,7 +573,7 @@ export function arkFeature(ctx) {
function arkWanted() {
const cfg = getArkConfig();
- const st = cfg && wallet.loadArkState(cfg.ark);
+ const st = cfg && peekArk(wallet, cfg.ark);
return !!(st && ((st.vtxos || []).length || (st.movements || []).length
|| (st.actions || []).some((a) => !['done', 'failed'].includes(a.step))));
}
@@ -504,9 +588,11 @@ export function arkFeature(ctx) {
// holds is on screen the moment it can be.
const store = wallet._arkStore;
if (store && !store.ready) {
+ bootPhase('ark-store');
store.open().then(() => { ctx.forgetAmountAnim && ctx.forgetAmountAnim(); render(); initArk(); }).catch(() => {});
return;
}
+ if (safeBoot()) return; // safe mode: the coins show from the store; nothing dials out unasked
if (arkAvailable() && arkWanted()) { lastAutoInit = Date.now(); connectArk().then(() => rescueOtherServers()).catch(() => {}); }
}
@@ -539,7 +625,7 @@ export function arkFeature(ctx) {
adopt: (serverPubkey) => wallet.adoptArkState(serverPubkey, p.ark),
save: (s) => { wallet.saveArkState(mergeArkStates(s, wallet.loadArkState(p.ark)), p.ark); },
},
- arkUrl: p.ark, esploraUrl: p.esplora, network: getNetwork(),
+ arkUrl: p.ark, esploraUrl: p.esplora, network: getNetwork(), honorsExpired: !!p.honorsExpired,
});
await mgr.init();
const done = () => (mgr.state.movements || []).filter((m) => m.type === 'ln-receive' && m.status === 'complete');
@@ -553,7 +639,7 @@ export function arkFeature(ctx) {
}
}
function maybeInitArk() {
- if (ark || arkConnectPromise) return;
+ if (ark || arkConnectPromise || safeBoot()) return;
if (Date.now() - lastAutoInit < 20000) return;
// A fresh snapshot may be held under its server pubkey, so arkWanted()
// cannot see it until the handshake identifies the server and adopts it.
@@ -596,6 +682,7 @@ export function arkFeature(ctx) {
arkPersistFlushers.add(flushPersist);
const mgr = new ArkManager({
account: wallet.account(),
+ lnOldestFirst: () => getCustody() !== 'custodial',
storage: {
load: () => wallet.loadArkState(cfg.ark),
adopt: (serverPubkey) => wallet.adoptArkState(serverPubkey, cfg.ark),
@@ -621,6 +708,10 @@ export function arkFeature(ctx) {
arkUrl: cfg.ark,
esploraUrl: cfg.esplora,
network: getNetwork(),
+ honorsExpired: !!cfg.honorsExpired,
+ // the server's last published info: the wallet opens on it when the
+ // server is gone, so coins can still be read and exited
+ infoHint: (cachedArkInfo(cfg.ark) || {}).info || null,
// the wallet's own tx table as a second witness for confirmations —
// its data source is user-configurable and often healthier than the
// ark preset's esplora from this device
@@ -634,9 +725,27 @@ export function arkFeature(ctx) {
// Open the server connection while Nostr restores, but do not replay the
// mailbox before the snapshot's history and cursor have arrived.
const restored = Promise.resolve(wallet.nostrRestoreReady || wallet.syncFromNostr?.()).catch(() => false);
- arkConnectPromise = Promise.all([mgr.init(), restored]).then(() => {
+ bootPhase('ark-init');
+ const inited = mgr.init().then(() => {
+ if (gen !== arkInitGen) return;
+ bootPhase('ark-inited');
+ arkInited = mgr; // readable now; `ark` (and the mailbox) wait for the snapshot
+ if (!mgr.offline) rememberArkInfo(cfg.ark, mgr.info, mgr._tipH);
+ render();
+ });
+ arkInitPromise = inited;
+ // The tip: expiries and exit costs are judged against it, and init alone
+ // never asks for it (the first sync does, after the snapshot gate). Ask
+ // now, off the connect path, and remember it for the next refresh.
+ inited.then(() => mgr._tipMemo()).then(() => {
+ if (gen !== arkInitGen || !mgr._tipH) return;
+ rememberArkInfo(cfg.ark, mgr.info, mgr._tipH);
+ render();
+ }).catch(() => {});
+ arkConnectPromise = Promise.all([inited, restored]).then(() => {
if (gen !== arkInitGen) throw new Error('superseded'); // wallet switched mid-connect
ark = mgr;
+ bootPhase('ark-adopt');
// Sync may have arrived while init awaited the server handshake.
adoptArkSnapshot(mgr, wallet.loadArkState(cfg.ark));
// Boards that died before funding (a failed tx build, a closed tab)
@@ -677,12 +786,14 @@ export function arkFeature(ctx) {
// sync() already reconciles on its first pass. Start the live stream
// afterwards, at the caught-up cursor: running both together replayed
// the backlog one message/render at a time alongside the batch read.
+ bootPhase('ark-sync');
tick().finally(() => { if (ark === mgr) mgr.startMailboxStream(); });
mergeBgWorkerState(mgr).catch(() => {}); // absorb what the SW did while we were closed
// Receives arrive in real time over the mailbox stream; the poll is the
// fallback and what drives in-flight boards/refreshes forward.
scheduleLnTag(mgr); // receives that landed while this device was closed
arkTimer = setInterval(() => { if (ark === mgr) tick(); }, getNetwork() === 'regtest' ? 5000 : 30000);
+ bootPhase('ark-ready');
render();
return mgr;
}).catch((e) => {
@@ -705,7 +816,7 @@ export function arkFeature(ctx) {
// (send/exit) still requires the seed and is gated separately.
const cfg = getArkConfig();
if (!cfg) return null;
- return wallet.loadArkState(cfg.ark);
+ return peekArk(wallet, cfg.ark);
}
// Which receives actually arrived over Lightning? A payment to the user's
@@ -855,7 +966,7 @@ export function arkFeature(ctx) {
h('button', { class: 'btn-ghost', onClick: () => { ui.arkSend = null; ui.sendError = ''; render(); } }, t('back')),
ui.busy
? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
- : a.amountSat > (arkBalance()?.spendableSat || 0) && wallet.spendable > 0 && !wallet.watchOnly
+ : a.amountSat > (arkBalance()?.spendableSat || 0) && savingsCanBoard()
? h('button', { class: 'btn-primary grow', onClick: () => {
const need = a.amountSat;
ui.arkSend = null; ui.sendError = '';
@@ -921,22 +1032,62 @@ export function arkFeature(ctx) {
// connections/offer belong to the nwc feature; when it isn't the caller
// (an auto-withdraw setting changed, say) carry forward what's mirrored
// rather than blanking someone's wallet connections.
- async function writeBgMirror(connections, offer, prefs) {
+ // The mirror carries hundreds of pre-derived keys (BG_KEY_LOOKAHEAD) and
+ // is rewritten after every state change: derive each index once per
+ // account, not once per write.
+ const bgKeyMemo = new WeakMap(); // account node -> Map('chain:i' -> hex)
+ function bgKeyFor(account) {
+ let m = bgKeyMemo.get(account);
+ if (!m) { m = new Map(); bgKeyMemo.set(account, m); }
+ const chains = new Map();
+ return (chain, i) => {
+ const k = chain + ':' + i;
+ let v = m.get(k);
+ if (!v) {
+ let node = chains.get(chain);
+ if (!node) { node = account.deriveChild(chain); chains.set(chain, node); }
+ v = hex.encode(node.deriveChild(i).privateKey);
+ m.set(k, v);
+ }
+ return v;
+ };
+ }
+ // The worker can now pay while this app is alive behind another one (a
+ // phone with Coinos in the background: the page is frozen or throttled,
+ // the worker is not). Its change coin and its spent coins then exist only
+ // in the mirror — so the mirror is never written over the worker's hand:
+ // one writer at a time (the lock the worker holds for a whole push), and
+ // whatever the worker did since we last looked is folded in first.
+ let bgAbsorbedAt = 0; // the worker stamp (rec.workerAt) this app has folded in
+ const withBgLock = (fn) => (typeof navigator !== 'undefined' && navigator.locks
+ ? navigator.locks.request('nwc-bg-work', fn) : fn());
+ const bgBusy = (mgr) => !!(mgr && mgr._lnDriving && mgr._lnDriving.size);
+ async function writeBgMirror(connections, offer, prefs) { return withBgLock(() => writeBgMirrorLocked(connections, offer, prefs)); }
+ async function writeBgMirrorLocked(connections, offer, prefs) {
const cfg = getArkConfig();
if (!cfg || !ark || !ark.info || !ark.state) return;
- const prev = await loadBg(wallet._cacheKey());
+ let prev = await loadBg(wallet._cacheKey());
+ if (prev && prev.v >= 3 && prev.mgr && (prev.workerAt || 0) > bgAbsorbedAt) {
+ // a payment of ours in flight holds the very records a merge replaces:
+ // leave the worker's state standing and write at the next call
+ if (bgBusy(ark)) return;
+ await mergeBgWorkerState(ark).catch((e) => console.warn('ark: worker merge failed', e && e.message));
+ if ((prev.workerAt || 0) > bgAbsorbedAt) return; // not folded in: don't write over it
+ prev = await loadBg(wallet._cacheKey());
+ }
if (connections === undefined) connections = (prev && prev.connections) || [];
if (offer === undefined) offer = (prev && prev.offer) || null;
if (prefs === undefined) prefs = (prev && prev.prefs) || undefined;
const rec = buildBg({
- ark: { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), serverPubkey: ark.info.serverPubkey },
+ ark: { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), serverPubkey: ark.info.serverPubkey, honorsExpired: !!cfg.honorsExpired },
mgrState: ark.state,
- keyFor: (chain, i) => hex.encode(ark.account.deriveChild(chain).deriveChild(i).privateKey),
+ custody: getCustody(),
+ keyFor: bgKeyFor(ark.account),
connections,
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; if (prev.workerAt) rec.workerAt = prev.workerAt; } // 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(() => {});
@@ -955,6 +1106,8 @@ export function arkFeature(ctx) {
return;
}
if (!rec.mgr) return;
+ bootPhase('ark-merge');
+ const stamp = rec.workerAt || 0;
const merged = mergeArkStates(mgr.state, rec.mgr);
// the worker's view of OUR vtxos is newer for anything it spent
const workerState = new Map((rec.mgr.vtxos || []).map((v) => [v.id, v.state]));
@@ -964,8 +1117,12 @@ export function arkFeature(ctx) {
merged.nextKeyIndex = Math.max(merged.nextKeyIndex || 1, rec.mgr.nextKeyIndex || 1);
mgr.state = merged;
mgr._save();
+ if (mgr === ark) bgAbsorbedAt = Math.max(bgAbsorbedAt, stamp);
+ bootPhase('ark-merged');
await mgr.reconcile().catch(() => {});
+ bootPhase('ark-reconciled');
await mgr.resumePending().catch(() => {});
+ bootPhase('ark-resumed');
}
// A leftover chain-6 pouch from before whole-balance background spending:
@@ -985,7 +1142,7 @@ export function arkFeature(ctx) {
const pm = await new ArkManager({
account: shim,
storage: { load: () => state, save: (s2) => { state = s2; } },
- arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(),
+ arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired,
}).init();
const dest = mgr.address();
for (let guard = 0; guard < 30; guard++) {
@@ -1359,13 +1516,27 @@ export function arkFeature(ctx) {
: m.type === 'ln-send' && m.invoice ? zapNotes()['inv:' + m.invoice]
: null;
- function arkHistoryItem(m) {
+ // A move inside one account (on-chain ⇄ Ark): no money in or out, only
+ // what moving it cost.
+ function arkInternalMoveItem(m, feeSat, pending) {
+ const label = m.type === 'board' ? (pending ? t('movingInstant') : t('movedInstant')) : t('movedOnchain');
+ return h('div', { class: 'item internal-move', style: m.id ? 'cursor:pointer' : '', onClick: m.id ? () => { ui.arkMoveDetail = m.id; render(); } : undefined },
+ h('div', { class: 'ico' }, '\u21c4'),
+ h('div', { class: 'grow' },
+ h('div', {}, label),
+ h('div', { class: 'small faint' }, (pending ? t('pending') + ' · ' : '') + fmtAmount(m.amountSat || 0) + ' ' + unitLabel() + ' · ' + timeAgo((m.ts || Date.now()) / 1000))),
+ h('div', { style: 'text-align:right' },
+ feeSat > 0 ? h('div', { class: 'amount-neg' }, fmtAmount(feeSat)) : h('div', { class: 'small faint' }, t('arkDepthFree'))));
+ }
+
+ function arkHistoryItem(m, labelAs) {
const failed = m.status === 'failed';
const incoming = !['send', 'offboard', 'exit', 'ln-send', 'refresh'].includes(m.type);
- const label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded')
+ let label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded')
: m.type === 'ln-send' ? t('arkLnPaidHistory') : m.type === 'ln-receive' ? t('arkLnReceivedHistory')
: m.type === 'offboard' ? t('arkOffboarded') : m.type === 'exit' ? t('arkExited')
: m.type === 'refresh' ? t('arkRenewedHistory') : t('sent');
+ if (labelAs) label = labelAs;
// A spent input proves neither a payment amount nor its date: it can
// contain change, an offboard, or a renewal this device has not synced.
// Show the missing history explicitly until its records arrive.
@@ -1420,15 +1591,37 @@ 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)))
);
}
+ // a movement as a line of the history export (Settings → Wallet): what
+ // was paid, the fee beside it, and the change to the balance — a failed
+ // payment moved nothing; a renewal moved nothing but its fee
+ function arkCsvRow(m) {
+ if (m.status === 'failed') return null;
+ const out = ['send', 'offboard', 'exit', 'ln-send', 'refresh', 'reconcile'].includes(m.type);
+ const fee = m.feeSat != null ? m.feeSat : Number(((m.detail || '').match(/fee (\d+) sat/) || [])[1]) || 0;
+ const amount = m.type === 'refresh' ? 0 : m.amountSat || 0;
+ const viaLn = m.type.startsWith('ln-') || m.viaLn;
+ return {
+ ts: m.ts, type: m.type === 'reconcile' ? 'spent-elsewhere' : m.type,
+ rail: viaLn ? 'lightning' : ONCHAIN_ARK.has(m.type) ? 'onchain' : 'ark',
+ amount: out ? -amount : amount, fee: out ? fee : 0, net: out ? -(amount + fee) : amount,
+ status: m.status === 'complete' ? 'complete' : 'pending',
+ ref: m.txid || m.paymentHash || m.vtxoId || '', to: m.to || '', invoice: m.invoice || '',
+ note: m.type === 'reconcile' ? t('arkDetailsNotSynced') : '',
+ };
+ }
+
const exitStartedTs = (a) => Number((a.id || '').split('-')[1]) || Date.now();
// A Lightning payment (a zap, mostly) still settling: the money has left
// the balance, so history shows it now as the Sent row it will become.
@@ -1572,6 +1765,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
@@ -1620,7 +1814,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,
@@ -1711,8 +1905,9 @@ export function arkFeature(ctx) {
// 2. lightning: profile lud16/lud06, via the zap flow
// 3. an on-chain address from the BIP-353 record
const NAMES_REGISTRAR = 'https://names.coinos.io';
- function startNpubPay(pk, npub, eventId = null, autoSat = 0) {
- const z = { npub, pk, eventId, amount: '', comment: '', status: 'lookup', autoSat };
+ function startNpubPay(pk, npub, eventId = null, autoSat = 0, moment = null) {
+ // `moment`: where the clip was — offered in the sheet, tied only when ticked
+ const z = { npub, pk, eventId, momentOffer: moment, moment: null, amount: '', comment: '', status: 'lookup', autoSat };
// A one-tap post zap has no card: it resolves and pays off-screen, so a
// second tap — the same post again, or another — never evicts the one
// already in the air. Everything else takes the send screen's zap slot.
@@ -1794,7 +1989,7 @@ export function arkFeature(ctx) {
z.lnOk = true;
await connectArk().catch(() => {});
if (!live()) return;
- if (ctx.hook('canLnZap')) { if (ui.arkZap === z) ui.arkZap = null; ctx.hook('lnZapNpub', pk, npub, z.eventId, z.autoSat); return; }
+ if (ctx.hook('canLnZap')) { if (ui.arkZap === z) ui.arkZap = null; ctx.hook('lnZapNpub', pk, npub, z.eventId, z.autoSat, z.moment || (z.autoSat ? null : z.momentOffer)); return; }
}
// 3. on-chain fallback (a one-tap zap can't take the send form)
if (onchain && !(z.autoSat && z.eventId)) {
@@ -1830,11 +2025,16 @@ export function arkFeature(ctx) {
}
// The ask itself: switch and continue, move Savings over first, or not.
+ // When Savings can't fund a move either (under the board minimum, as a
+ // 546-sat Savings against coinos's 1,000 is), the door offered is the one
+ // that works: a Lightning receive, which lands in Spending directly.
function arkLnFromSavingsView() {
const p = ui.arkLnFromSavings;
const have = arkBalance()?.spendableSat || 0;
const need = p.amountSat || 0;
const enough = !need || have >= need;
+ const canMove = savingsCanBoard();
+ const close = () => { ui.arkLnFromSavings = null; ui.sendError = ''; ui.send = blankSend(); };
const proceed = () => {
ui.arkLnFromSavings = null;
ctx.setAccount('spending', 'right');
@@ -1842,20 +2042,27 @@ export function arkFeature(ctx) {
if (startArkLnPay(p.invoice, p.meta)) return;
ui.arkLnFromSavingsOk = false;
// Spending can't carry it: the same offer the Spending side makes
- if (need && wallet.spendable > 1000 && ctx.hook('arkOfferBoard', need)) return;
+ if (need && canMove && ctx.hook('arkOfferBoard', need)) return;
ui.sendError = t('arkLnExceedsSpending', { need: fmtAmount(need) + ' ' + unitLabel(), have: fmtAmount(have) + ' ' + unitLabel() });
render();
};
+ const moveFirst = () => { ui.arkLnFromSavings = null; ctx.hook('arkOfferBoard', need || 0); };
+ const receiveInstead = () => { close(); ctx.setAccount('spending', 'right'); render(); };
+ const sats = (n) => fmtAmount(n) + ' ' + unitLabel();
return h('div', { class: 'card col', style: 'gap:12px' },
h('h3', { style: 'margin:0' }, t('arkLnFromSavingsTitle')),
- h('p', { class: 'small muted', style: 'margin:0' }, t('arkLnFromSavingsBody', { have: fmtAmount(have) + ' ' + unitLabel() })),
- need ? h('div', { class: 'row between' }, h('span', { class: 'small muted' }, t('lnPayAmount')), h('span', { class: 'small' }, fmtAmount(need) + ' ' + unitLabel())) : null,
- !enough ? h('div', { class: 'notice info small' }, t('arkLnFromSavingsShort')) : null,
- h('button', { class: 'btn-primary btn-block', onClick: proceed }, enough ? t('arkLnUseSpending') : t('arkLnMoveFirst')),
- enough && wallet.spendable > 1000
- ? h('button', { class: 'btn-block', onClick: () => { ui.arkLnFromSavings = null; ctx.hook('arkOfferBoard', need || 0); } }, t('arkLnMoveFirst'))
+ h('p', { class: 'small muted', style: 'margin:0' }, t('arkLnFromSavingsBody', { have: sats(have) })),
+ need ? h('div', { class: 'row between' }, h('span', { class: 'small muted' }, t('lnPayAmount')), h('span', { class: 'small' }, sats(need))) : null,
+ enough ? null
+ : canMove ? h('div', { class: 'notice info small' }, t('arkLnFromSavingsShort'))
+ : h('div', { class: 'notice info small' }, t('arkLnSavingsTooSmall', { have: sats(wallet.spendable || 0), min: sats(savingsBoardMin()) })),
+ enough ? h('button', { class: 'btn-primary btn-block', onClick: proceed }, t('arkLnUseSpending'))
+ : canMove ? h('button', { class: 'btn-primary btn-block', onClick: moveFirst }, t('arkLnMoveFirst'))
+ : h('button', { class: 'btn-primary btn-block', onClick: receiveInstead }, t('arkLnReceiveInstead')),
+ enough && canMove
+ ? h('button', { class: 'btn-block', onClick: moveFirst }, t('arkLnMoveFirst'))
: null,
- h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkLnFromSavings = null; ui.sendError = ''; ui.send = blankSend(); render(); } }, t('cancel')));
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { close(); render(); } }, t('cancel')));
}
// shared by the ark and lightning zap flows (see zaps.js for the twin)
@@ -1914,7 +2121,7 @@ export function arkFeature(ctx) {
await wallet.nostrPublish({
kind: ARK_ZAP_KIND,
content: (z.comment || '').slice(0, 280),
- tags: [['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []),
+ tags: [...momentTags(z.moment), ['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []), ...(zapAddrOf(z.eventId) ? [['a', zapAddrOf(z.eventId)]] : []),
['amount', String(sats)], ['vtxo', vtxoId], ['network', getNetwork()], ...zapSenderTag()],
}).catch(() => {});
}
@@ -1957,7 +2164,7 @@ export function arkFeature(ctx) {
wallet.nostrPublish({
kind: ARK_ZAP_KIND,
content: (z.comment || '').slice(0, 280),
- tags: [['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []),
+ tags: [...momentTags(z.moment), ['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []), ...(zapAddrOf(z.eventId) ? [['a', zapAddrOf(z.eventId)]] : []),
['amount', String(sats)], ['network', getNetwork()], ['gift', locked.url], ...zapSenderTag()],
}).catch(() => {});
const dmText = t('giftDmText', { amount: fmtAmount(sats) + ' ' + unitLabel(), link: locked.url, code: locked.claimCode });
@@ -2035,6 +2242,8 @@ export function arkFeature(ctx) {
h('div', { style: 'display:flex;align-items:center' }, unitTag())),
h('input', { type: 'text', class: 'mono-input', placeholder: t('arkZapCommentPh'), value: z.comment,
onInput: (e) => { z.comment = e.target.value; } }),
+ z.momentOffer ? h('div', { class: 'row' }, momentToggle(h, z.momentOffer, !!z.moment, (on) => { z.moment = on ? z.momentOffer : null; render(); },
+ t('mediaTieTo', { time: mediaClock(z.momentOffer.seconds) }))) : null,
h('div', { class: 'small faint' }, hint));
return h('div', { class: 'card col', style: 'gap:12px' },
h('h3', {}, '⚡ ' + t('zapTitle')),
@@ -2045,7 +2254,7 @@ export function arkFeature(ctx) {
// Only someone with a Lightning address gets the Lightning door (the
// lookup normally hands such a person straight to the zaps feature).
noAddr && z.lnOk && ctx.hook('canLnZap')
- ? h('button', { class: 'btn-block', disabled: !!ui.busy, onClick: () => { ctx.hook('lnZapNpub', z.pk, z.npub, z.eventId); } }, '⚡ ' + t('lnZapFallback'))
+ ? h('button', { class: 'btn-block', disabled: !!ui.busy, onClick: () => { ctx.hook('lnZapNpub', z.pk, z.npub, z.eventId, 0, z.moment || z.momentOffer); } }, '⚡ ' + t('lnZapFallback'))
: null,
payable && spendable < 330
? h('div', { class: 'notice info' }, t(spendable + renewingSat() >= 330 ? 'spendingRenewingPayment' : 'zapNoBalance'))
@@ -2126,23 +2335,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;
}
@@ -2280,7 +2474,7 @@ export function arkFeature(ctx) {
// page, or a tap before the manager has connected (the first seconds
// after boot) found no coins and closed itself — Manage needed two taps.
// The manager is dialled meanwhile; what needs it live waits for it.
- const mgr = ark;
+ const mgr = arkView();
const st = (mgr && mgr.state) || arkStateNow();
// another device's renewal holds its coins just the same: greyed here too
const elsewhere = st ? remoteRenewalsInFlight(st) : [];
@@ -2292,7 +2486,11 @@ export function arkFeature(ctx) {
const renewing = ((st && st.actions) || []).filter((a) => a.type === 'refresh' && !['done', 'failed'].includes(a.step));
const inRound = new Set([...renewing, ...elsewhere].flatMap((a) => a.inputIds || []));
const pendingCoins = ((st && st.vtxos) || []).filter((v) => (v.state === 'pending' || v.state === 'spendable') && inRound.has(v.id));
- const tip = (mgr && mgr._tipH) || 0;
+ const tip = arkTipNow(mgr);
+ // the coinos servers keep honoring a coin past its timelock: it is held
+ // by coinos, not expired — still money, just not exitable on its own
+ const honors = !!(mgr && mgr.honorsExpired);
+ const exitable = exitableCoins(st, tip);
const back = embedded
? () => { ui.arkCoinsSel = null; ui.arkRenewConfirm = null; ctx.goHome(); }
: () => ctx.goBack(() => { ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkRenewConfirm = null; }); // the page is a history entry now
@@ -2314,7 +2512,7 @@ export function arkFeature(ctx) {
const expiresOf = (v) => {
if (!v.expiryHeight || !tip) return '—';
const blocks = v.expiryHeight - tip;
- if (blocks <= 0) return t('arkCoinsExpired');
+ if (blocks <= 0) return honors ? t('arkCoinsHeld') : t('arkCoinsExpired');
return blocks >= 144 ? Math.round(blocks / 144) + 'd' : Math.max(1, Math.round(blocks / 6)) + 'h';
};
// what pulling THIS coin on-chain alone would cost: every hop's fee
@@ -2332,10 +2530,11 @@ export function arkFeature(ctx) {
// bracket the share is zero, where the wallet renews on its own anyway.
// A flat base fee (the round's on-chain cost, which coinos stopped
// absorbing in October 2026) rides on top of every bracket.
- const table = (((mgr && mgr.info) || {}).refreshFees || {}).ppmExpiryTable || [];
- const baseSat = (((mgr && mgr.info) || {}).refreshFees || {}).baseFeeSat || 0;
+ const infoNow = (mgr && mgr.info) || (cachedArkInfo((getArkConfig() || {}).ark) || {}).info || {};
+ const table = (infoNow.refreshFees || {}).ppmExpiryTable || [];
+ const baseSat = (infoNow.refreshFees || {}).baseFeeSat || 0;
const baseCost = fmtSats(baseSat) + ' sats';
- const roundMins = Math.max(1, Math.round((((mgr && mgr.info) || {}).roundIntervalSecs || 120) / 60));
+ const roundMins = Math.max(1, Math.round((infoNow.roundIntervalSecs || 120) / 60));
const roundEvery = roundMins === 1 ? t('arkCoinsRoundEveryOne') : t('arkCoinsRoundEvery', { n: roundMins });
const ppmFor = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0;
// A coin's SHARE of the renewal fee, fractional: the server totals the
@@ -2373,6 +2572,12 @@ export function arkFeature(ctx) {
for (const id of ui.arkCoinsSel) if (!ids.has(id)) ui.arkCoinsSel.delete(id);
const sel = ui.arkCoinsSel;
const selCoins = spend.filter((v) => sel.has(v.id));
+ // the three actions below the table act on the ticked coins
+ const selExitable = selCoins.filter((v) => exitable.includes(v));
+ const selExitSat = selExitable.reduce((n, v) => n + v.amountSat, 0);
+ let selExitFee = 0; try { if (mgr) selExitFee = estimateExitFeeSat(mgr, selExitable); } catch {}
+ const subset = selCoins.length > 0 && selCoins.length < spend.length;
+ const coopSat = subset ? selCoins.reduce((n, v) => n + v.amountSat, 0) : spendableSat;
let selFee = 0; try { selFee = mgr.refreshFee(selCoins, tip); } catch {}
const renew = () => {
if (!selCoins.length || !mgr) return;
@@ -2383,6 +2588,20 @@ export function arkFeature(ctx) {
ui.arkRenewConfirm = null;
render(); // the page stays: the coins show as renewing
};
+ // What a renewal is and what it costs, told where it is decided: on the
+ // confirmation, not as a card on the page (the page is the coins and
+ // their three buttons; the explainers were a wall under them).
+ const renewExplainer = () => [
+ h('p', { class: 'small muted', style: 'margin:0' }, getCustody() === 'custodial' && honors
+ ? t('arkCoinsRenewDescCustodial', { every: roundEvery, base: baseSat ? baseCost : t('arkDepthFree') })
+ : baseSat
+ ? t('arkCoinsRenewDescBase', { every: roundEvery, base: baseCost })
+ : t('arkCoinsRenewDesc', { every: roundEvery })),
+ schedule.length ? h('div', { class: 'col', style: 'gap:2px;margin:2px 0' },
+ ...schedule.map((r) => h('div', { class: 'row between' },
+ h('span', { class: 'small muted' }, r.label),
+ h('span', { class: 'small' + (r.free ? ' faint' : '') }, r.cost)))) : null,
+ ];
// "Renew" asks once, with the numbers on the table: the coins it takes
// can't be spent until the round's transaction confirms, it can't be
// called back, and by default it takes every coin. (A user renewed their
@@ -2395,6 +2614,7 @@ export function arkFeature(ctx) {
h('div', { class: 'card col', style: 'gap:10px' },
h('h3', { style: 'margin:0' }, t('arkRenewConfirmTitle')),
h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmBody')),
+ ...renewExplainer(),
h('div', { class: 'col', style: 'gap:4px' },
row(t('arkExitConfirmCoins'), String(selCoins.length)),
row(t('arkExitConfirmAmount'), fmtSats(selSat) + ' sats'),
@@ -2402,7 +2622,7 @@ export function arkFeature(ctx) {
row(t('arkRenewConfirmLeft'), fmtSats(leftSat) + ' sats', leftSat ? '' : 'err')),
leftSat ? null : h('div', { class: 'notice err small' }, t('arkRenewConfirmAll')),
h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmWait')),
- h('button', { class: 'btn-primary btn-block ark-renew-go', disabled: !!ui.arkBusy || !mgr, onClick: renew },
+ h('button', { class: 'btn-primary btn-block ark-renew-go', disabled: !!ui.arkBusy || !ark, onClick: renew },
selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))),
h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkRenewConfirm = null; render(); } }, t('cancel')));
}
@@ -2435,22 +2655,23 @@ export function arkFeature(ctx) {
// is published: an exit cannot be called back.
if (ui.arkExitConfirm) {
const savings = wallet.spendable || 0;
- const short = savings < exitFee;
+ const short = savings < selExitFee;
const row = (k, v, cls = '') => h('div', { class: 'row between' }, h('span', { class: 'small muted' }, k), h('span', { class: 'small' + (cls ? ' ' + cls : '') }, v));
return h('div', { class: 'col', style: 'gap:16px' },
h('div', { class: 'card col', style: 'gap:10px' },
h('h3', { style: 'margin:0' }, t('arkExitConfirmTitle')),
h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmBody')),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoinsExitDesc', { fee: fmtSats(selExitFee), after: fmtSats(afterFee) })),
h('div', { class: 'col', style: 'gap:4px' },
- row(t('arkExitConfirmCoins'), String(spend.length)),
- row(t('arkExitConfirmAmount'), fmtSats(totalSat) + ' sats'),
- row(t('arkExitConfirmFee'), fmtSats(exitFee) + ' sats'),
+ row(t('arkExitConfirmCoins'), String(selExitable.length)),
+ row(t('arkExitConfirmAmount'), fmtSats(selExitSat) + ' sats'),
+ row(t('arkExitConfirmFee'), fmtSats(selExitFee) + ' sats'),
row(t('arkExitConfirmSavings'), fmtSats(savings) + ' sats', short ? 'err' : '')),
- short ? h('div', { class: 'notice err small' }, t('arkExitFeeShort', { need: fmtSats(exitFee), have: fmtSats(savings) })) : null,
+ short ? h('div', { class: 'notice err small' }, t('arkExitFeeShort', { need: fmtSats(selExitFee), have: fmtSats(savings) })) : null,
h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmWait')),
- h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || short || !spend.length, onClick: () => {
+ h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || short || !selExitable.length, onClick: () => {
ui.arkExitConfirm = null;
- doArkExit();
+ doArkExit(selExitable.map((v) => v.id));
ui.arkCoinsSel = null;
back();
ui.tab = 'history'; // the exit lives as a pending record there
@@ -2501,7 +2722,8 @@ export function arkFeature(ctx) {
h('tbody', {}, ...spend.map((v) => {
const f = feeNowOf(v);
const xf = exitFeeOf(v);
- const due = !!(v.expiryHeight && tip && v.expiryHeight - tip <= 0) || !!v.expiryRejected;
+ const past = !!(v.expiryHeight && tip && v.expiryHeight - tip <= 0);
+ const due = (past && !honors) || !!v.expiryRejected;
// expired and under the floor: nothing can renew it, so the
// last column offers to give it up
const lost = due && v.amountSat < 330;
@@ -2524,43 +2746,78 @@ export function arkFeature(ctx) {
h('td', { class: 'num' }, fmtSats(v.amountSat), h('span', { class: 'small faint' }, ' sats')),
h('td', { class: 'num' }, expiresOf(v)),
h('td', { class: 'num' }, '—'),
- h('td', { class: 'num' }, h('span', { class: 'tag pending' }, t('arkCoinsRenewing'))))))))),
+ h('td', { class: 'num' }, h('span', { class: 'tag pending' }, t('arkCoinsRenewing')))))))),
+ // What the ticked coins can do, right under them: renew, withdraw
+ // (the co-operative exit, into Savings) or exit on their own. Each
+ // names the ticked total it acts on.
+ // present even while every coin is in a round: disabled, so the page
+ // keeps its shape and says why nothing can be done
+ h('div', { class: 'col ark-coin-actions', style: 'gap:6px;margin-top:4px' },
+ h('button', { class: 'btn-primary btn-block ark-renew-ask', disabled: !!ui.arkBusy || !selCoins.length || !ark, onClick: () => { ui.arkRenewConfirm = true; render(); try { window.scrollTo({ top: 0 }); } catch {} } },
+ !selCoins.length ? t('arkCoinsRenewNone')
+ : selCoins.length < spend.length
+ ? t('arkCoinsRenewSome', { n: selCoins.length, fee: selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree') })
+ : selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn')),
+ h('button', { class: 'btn-ghost btn-block ark-coop-go', disabled: !!ui.arkBusy || !coopSat || !selCoins.length || wallet.watchOnly, onClick: () => {
+ const address = wallet.freshReceive().address;
+ const vtxoIds = subset ? selCoins.map((v) => v.id) : undefined;
+ ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkExitPage = null; ui.arkExitConfirm = null; ui.arkRenewConfirm = null;
+ ui.arkOffboarded = null; ui.arkError = '';
+ ctx.showSend({ fresh: true });
+ ui.arkOffboardSend = { address, amount: String(coopSat), fromCoins: true, vtxoIds };
+ render();
+ } }, t('arkCoinsWithdrawBtn', { amount: fmtNative(coopSat) })),
+ h('button', { class: 'btn-ghost btn-block ark-exit-ask', disabled: !!ui.arkBusy || !selExitable.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } },
+ t('arkCoinsExitBtnAmt', { amount: fmtNative(selExitSat) })))),
renewingCard,
- h('div', { class: 'card col', style: 'gap:8px' },
- h('h4', { style: 'margin:0' }, t('arkCoinsRenewTitle')),
- // the round cadence comes from the server (it has been an hour and
- // is two minutes as of September 2026) — never a number baked in here
- h('p', { class: 'small muted', style: 'margin:0' }, baseSat
- ? t('arkCoinsRenewDescBase', { every: roundEvery, base: baseCost })
- : t('arkCoinsRenewDesc', { every: roundEvery })),
- schedule.length ? h('div', { class: 'col', style: 'gap:2px;margin:2px 0' },
- ...schedule.map((r) => h('div', { class: 'row between' },
- h('span', { class: 'small muted' }, r.label),
- h('span', { class: 'small' + (r.free ? ' faint' : '') }, r.cost)))) : null,
- !spend.length ? null : h('button', { class: 'btn-primary btn-block ark-renew-ask', disabled: !!ui.arkBusy || !selCoins.length || !mgr, onClick: () => { ui.arkRenewConfirm = true; render(); try { window.scrollTo({ top: 0 }); } catch {} } },
- !selCoins.length ? t('arkCoinsRenewNone')
- : selCoins.length < spend.length
- ? t('arkCoinsRenewSome', { n: selCoins.length, fee: selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree') })
- : selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))),
- h('div', { class: 'card col', style: 'gap:8px' },
- h('h4', { style: 'margin:0' }, t('arkCoinsCoopTitle')),
- h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')),
- h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || !spendableSat || wallet.watchOnly, onClick: () => {
- const address = wallet.freshReceive().address;
- ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkExitPage = null; ui.arkExitConfirm = null; ui.arkRenewConfirm = null;
- ui.arkOffboarded = null; ui.arkError = '';
- ctx.showSend({ fresh: true });
- ui.arkOffboardSend = { address, amount: String(spendableSat), fromCoins: true };
- render();
- } }, t('arkOffboardBtn', { n: fmtAmount(spendableSat) + ' ' + unitLabel() }))),
- h('div', { class: 'card col', style: 'gap:8px' },
- h('h4', { style: 'margin:0' }, t('arkCoinsExitTitle')),
- h('p', { class: 'small muted', style: 'margin:0' },
- t('arkCoinsExitDesc', { fee: fmtSats(exitFee), after: fmtSats(afterFee) })),
- h('button', { class: 'btn-ghost btn-block', disabled: !!ui.arkBusy || !spend.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } }, t('arkCoinsExitBtn'))),
+ embedded ? custodyCard() : null,
embedded ? null : h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back')));
}
+ // Who holds the coins once their timelock runs out — the user's call, made
+ // here, with what each option costs in the server's own numbers. The
+ // default is coinos: most people come from v2, where coinos held
+ // everything, and the server honors a coin past its timelock anyway. The
+ // two renewing tiers are the opt-ins, for those who want the exit kept
+ // (self) or kept cheap by flattening deep histories early (exit). Only
+ // shown on a server that honors expired coins; elsewhere renewal is the
+ // only way to keep money.
+ function custodyCard() {
+ if (!arkAvailable() || wallet.watchOnly) return null;
+ const cfg = getArkConfig();
+ const view = arkView();
+ const info = (view && view.info) || (cachedArkInfo(cfg && cfg.ark) || {}).info || null;
+ const honors = !!(cfg && cfg.honorsExpired);
+ 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;
+ const lifeDays = Math.max(1, Math.round(((info && info.vtxoExpiryDelta) || 8640) / 144));
+ const baseCost = !info ? '…' : base ? fmtSats(base) + ' sats' : t('arkDepthFree');
+ // an early renewal pays the bracket a fresh coin sits in (the top one)
+ const earlyPct = pct(ppmAt(((info && info.vtxoExpiryDelta) || 8640) - 1));
+ const hops = (renewPolicy('exit', getNetwork()) || {}).maxDepth || 4;
+ const tiers = [
+ { id: 'custodial', label: t('arkCustodyCustodial'), desc: t('arkCustodyCustodialDesc'), cost: t('arkCustodyCostNone') },
+ { id: 'self', label: t('arkCustodySelf'), desc: t('arkCustodySelfDesc', { days: lifeDays }), cost: t('arkCustodyCostSelf', { base: baseCost }) },
+ { id: 'exit', label: t('arkCustodyExit'), desc: t('arkCustodyExitDesc', { hops }), cost: t('arkCustodyCostExit', { pct: earlyPct, base: baseCost }) },
+ ].filter((x) => honors || x.id !== 'custodial');
+ const chosen = tiers.find((x) => x.id === cur) || tiers[0];
+ // A drop-down, and only the chosen strategy's description under it: three
+ // paragraphs at once read as a wall, and two of them are about choices
+ // the reader has not made.
+ return h('div', { class: 'card col ark-custody', style: 'gap:10px' },
+ h('h4', { style: 'margin:0' }, t('arkCustodyTitle')),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('arkCustodyDesc', { days: lifeDays })),
+ h('select', { id: 'ark-custody-select', disabled: !honors, onChange: (e) => applyCustody(e.target.value) },
+ ...tiers.map((x) => h('option', { value: x.id, selected: x.id === cur }, x.label))),
+ // the price under the choice, not in the option (a long option text
+ // overflows the select on a phone)
+ h('div', { class: 'small ark-custody-cost' }, chosen.cost),
+ h('p', { class: 'small muted ark-custody-desc', style: 'margin:0' }, chosen.desc),
+ honors ? null : h('p', { class: 'small faint', style: 'margin:0' }, t('arkCustodyNotHere')));
+ }
+
// What each server charges and promises, from its own published info —
// laid side by side under the switcher so the choice is an informed one.
const serverInfos = new Map(); // url -> info | null (failed) | undefined (loading)
@@ -2778,9 +3035,9 @@ export function arkFeature(ctx) {
// Fee = size × rate needs none of it. Still memoized on the coin set +
// feerate, since the advisory asks on every wallet render.
let _exitFeeMemo = { key: null, val: 0 };
- function estimateExitFeeSat(mgr) {
+ function estimateExitFeeSat(mgr, only = null) {
const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
- const coins = freeCoins(mgr.state);
+ const coins = only || exitableCoins(mgr.state, mgr._tipH || 0);
const key = feeRate + '|' + coins.map((v) => v.id).join(',');
if (_exitFeeMemo.key === key) return _exitFeeMemo.val;
let total = 0;
@@ -2795,16 +3052,27 @@ export function arkFeature(ctx) {
return total;
}
- async function doArkExit() {
+ // ids: exactly these coins (the Manage page's ticked ones); else every coin
+ async function doArkExit(ids = null) {
ui.arkBusy = 'exit'; ui.arkError = ''; render();
try {
- const mgr = await connectArk();
- const spendables = freeCoins(mgr.state);
- if (!spendables.length) throw new Error(t('arkNotConnected'));
+ // The manager's own init is enough for an exit — the server may be
+ // gone (that is what a unilateral exit is for), and the snapshot gate
+ // the full connect also waits on may never clear without the relays.
+ let mgr = arkView();
+ if (!mgr) {
+ connectArk().catch(() => {});
+ for (let i = 0; i < 50 && !arkInitPromise; i++) await new Promise((r) => setTimeout(r, 100));
+ try { await arkInitPromise; } catch {}
+ mgr = arkView();
+ }
+ if (!mgr) throw new Error(t('arkNotConnected'));
+ const spendables = exitableCoins(mgr.state, mgr._tipH || 0).filter((v) => !ids || ids.includes(v.id));
+ if (!spendables.length) throw new Error(freeCoins(mgr.state).length ? t('arkExitNoneExitable') : t('arkNotConnected'));
// Fees are paid hop by hop from Savings as the exit unrolls — an exit
// that can't fund its hops just stalls at step zero. Refuse to start
// one Savings can't carry, with the number on the table.
- const feeEst = estimateExitFeeSat(mgr);
+ const feeEst = estimateExitFeeSat(mgr, spendables);
if ((wallet.spendable || 0) < feeEst) {
throw new Error(t('arkExitFeeShort', { need: fmtSats(feeEst), have: fmtSats(wallet.spendable || 0) }));
}
@@ -2962,7 +3230,7 @@ export function arkFeature(ctx) {
load: () => { try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch { return null; } },
save: (s) => { try { localStorage.setItem(key, JSON.stringify(s)); } catch {} },
},
- arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(),
+ arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired,
});
await mgr.init();
return mgr;
@@ -3010,7 +3278,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);
@@ -3020,7 +3288,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 };
}
@@ -3054,7 +3322,7 @@ export function arkFeature(ctx) {
async function quoteOffboard(o, address) {
o.quoteFor = address; o.quote = null;
let quote = null;
- try { quote = await (await connectArk()).offboardQuote(addrScript(address)); }
+ try { quote = await (await connectArk()).offboardQuote(addrScript(address), o.vtxoIds); }
catch {} // no quote: the send itself still says what went wrong
if (o.quoteFor !== address) return; // the address changed meanwhile
o.quote = quote; o.quoteDone = true;
@@ -3062,7 +3330,9 @@ export function arkFeature(ctx) {
}
function arkOffboardSendView() {
const o = ui.arkOffboardSend;
- const spendable = arkBalance()?.spendableSat || 0;
+ // chosen coins: the amount is theirs and is not a field
+ const chosen = o.vtxoIds ? freeCoins(arkStateNow()).filter((v) => o.vtxoIds.includes(v.id)) : null;
+ const spendable = chosen ? chosen.reduce((n, v) => n + v.amountSat, 0) : (arkBalance()?.spendableSat || 0);
if (o.quoteFor !== o.address) {
o.quote = null; o.quoteDone = false; o.quoteFor = o.address;
let ok = false; try { addrScript(o.address); ok = true; } catch {}
@@ -3072,6 +3342,7 @@ export function arkFeature(ctx) {
const tooSmall = !!q && spendable < q.minSat;
return h('div', { class: 'card col', style: 'gap:12px' },
h('h3', {}, t(o.fromCoins ? 'arkCoinsCoopTitle' : 'arkExitSendTitle')),
+ o.fromCoins ? h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')) : null,
h('label', { class: 'field' },
h('span', { class: 'lab' }, t('recipient')),
h('input', { type: 'text', class: 'mono-input', value: o.address, spellcheck: 'false', autocomplete: 'off', autocapitalize: 'none',
@@ -3082,10 +3353,11 @@ export function arkFeature(ctx) {
fee: fmtSats(q.totalSat), chain: fmtSats(q.chainSat), service: fmtSats(q.serviceSat), min: fmtSats(q.minSat),
})) : !o.quoteDone ? h('div', { class: 'small faint' }, t('arkOffboardQuoting')) : null,
tooSmall ? h('div', { class: 'notice' }, t('arkOffboardBelowMin', { n: fmtSats(spendable), min: fmtSats(q.minSat) })) : null,
- h('div', { class: 'input-group' },
- h('input', { type: 'number', min: '1', placeholder: String(spendable), value: o.amount,
- onInput: (e) => { o.amount = e.target.value; } }),
- h('button', { type: 'button', onClick: () => { o.amount = String(spendable); render(); } }, t('max'))),
+ chosen ? h('div', { class: 'small ark-coop-chosen' }, chosen.length === 1 ? t('arkCoopSelectedAmtOne', { amount: fmtSats(spendable) + ' sats' }) : t('arkCoopSelectedAmt', { n: chosen.length, amount: fmtSats(spendable) + ' sats' }))
+ : h('div', { class: 'input-group' },
+ h('input', { type: 'number', min: '1', placeholder: String(spendable), value: o.amount,
+ onInput: (e) => { o.amount = e.target.value; } }),
+ h('button', { type: 'button', onClick: () => { o.amount = String(spendable); render(); } }, t('max'))),
ui.arkError ? h('div', { class: 'notice err' }, ui.arkError) : null,
h('div', { class: 'row gap6' },
h('button', { class: 'btn-ghost grow', onClick: () => {
@@ -3095,7 +3367,7 @@ export function arkFeature(ctx) {
ui.arkBusy === 'offboard'
? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner sm' }))
: h('button', { class: 'btn-primary grow', disabled: tooSmall, onClick: () => {
- const amount = String(o.amount ?? '').trim();
+ const amount = chosen ? String(spendable) : String(o.amount ?? '').trim();
const sats = amount ? Number(amount) : spendable;
if (!Number.isSafeInteger(sats) || sats <= 0 || sats > spendable) { ui.arkError = t('enterValidAmtForN', { n: 1 }); render(); return; }
try { addrScript(o.address); } catch { ui.arkError = t('arkOffboardBadAddress'); render(); return; }
@@ -3104,7 +3376,7 @@ export function arkFeature(ctx) {
ui.arkCoopFailed = false;
ui.arkError = t('arkOffboardAmtBelowMin', { min: fmtSats(q.minSat), fee: fmtSats(q.totalSat) }); render(); return;
}
- doArkOffboard(sats >= spendable ? 0 : sats, o.address);
+ doArkOffboard(sats >= spendable ? 0 : sats, o.address, chosen ? o.vtxoIds : undefined);
} }, t('arkSendBtn'))),
// This send IS the cooperative exit. The trustless fallback only
// appears when cooperation actually failed (not when the amount was
@@ -3140,29 +3412,69 @@ export function arkFeature(ctx) {
})());
}
- async function doArkOffboard(amountSat, destAddress = null) {
+ // 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) {
ui.arkBusy = 'offboard'; ui.arkError = ''; ui.arkCoopFailed = false; render();
try {
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);
- let ids; // undefined = all spendable vtxos
- if (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];
- }
+ const total = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0);
+ let ids = vtxoIds; // undefined = all spendable vtxos
+ if (!ids && amountSat && amountSat < total) ids = await carveCoins(mgr, amountSat);
const action = await mgr.startOffboard(spk, address, ids);
ui.arkOffboardAmt = '';
ui.arkMoveOpen = false;
@@ -3178,25 +3490,63 @@ export function arkFeature(ctx) {
ui.arkBusy = null; render();
}
- // VTXO upkeep, invisibly: a send needs a single vtxo covering the amount
- // (fragmentation breaks coin selection) and every vtxo expires at
- // expiryHeight (unrenewed, the ASP can eventually sweep it). Rather than
- // exposing a refresh button, consolidate-and-renew automatically when a
- // vtxo is inside the renewal window or fragmentation builds up. The round
- // fee this spends is the cost of keeping the money spendable at all.
- // The ASP's refresh fee brackets reward renewing LATE — under 96 blocks of
- // remaining life a renewal is free, and this ASP keeps honoring (and freely
- // rescuing) a coin even past its expiry, so aiming inside the free window
- // risks nothing. ~16 hours of margin on mainnet.
- const renewWindow = () => (getNetwork() === 'regtest' ? 24 : 96);
- // How close to expiry the SERVER's own backstop renewal is aimed. The
- // window above only helps a wallet someone opens inside it; this one is a
- // participation registered far in advance that the ASP runs on its own,
- // whether or not anybody is looking. It sits well inside renewWindow so an
- // app that IS open still renews first (and the untouched backstop is
- // dropped), and far enough from expiry — 36 blocks, six hourly rounds — for
- // the round to actually run in time. Both are in the free fee bracket.
- const backstopWindow = () => backstopMargin(getNetwork());
+ // VTXO upkeep, by the user's choice of custody (Settings → Spending):
+ // custodial (the default) — nothing renews. A coin past its timelock is
+ // coinos's IOU: the server sweeps the tree and keeps cosigning spends of
+ // the coin (captaind allow_expired_arkoor), so the balance works as a v2
+ // one did, and no renewal fee is ever paid. The holder trusts coinos.
+ // self — renew in the last hours before expiry, the free ppm bracket, one
+ // base fee per round (~300 sats): a unilateral exit is always possible.
+ // exit — the same, plus a coin is renewed as soon as its history is four
+ // hops deep: an exit pays one on-chain transaction per hop, so this
+ // keeps the exit price of every coin near a fresh coin's. Costs the
+ // top bracket + base each time, so only for coins worth it.
+ // The policy's window is when THIS app renews a coin (blocks of life left);
+ // margin/grid aim the SERVER's own backstop order — a participation the ASP
+ // runs on its own, registered far in advance, snapped to a grid so every
+ // wallet's orders share one round. renewPolicy() in ark/manager.js.
+ //
+ // Consolidation is gone from here: it used to trigger at 20 coins, bill the
+ // top ppm bracket on every fresh coin, and was 84% of all renewal fees paid
+ // in Sep–Oct 2026 — the "money draining" people saw. Multi-input sends take
+ // up to MAX_SEND_INPUTS coins; small change folds into a renewal that is
+ // 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)
+ 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());
+ // Switching: a renewing tier starts covering coins right away (the throttles
+ // are reset so the next sync registers backstops and renews what is due),
+ // and the worker's mirror learns the tier so closed-app renewals follow it.
+ // Orders already registered with the server keep running whatever the tier
+ // (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)) 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(() => {});
+ toast(t('arkCustodySaved'));
+ render();
+ }
let arkAutoRefreshAt = 0;
let arkBackstopAt = 0;
// Set when the balance is too small to renew itself (total minus round fee
@@ -3227,12 +3577,38 @@ export function arkFeature(ctx) {
return true;
}
+ // Whatever the tier, a coin whose history has run very deep is renewed:
+ // the server stops cosigning spends of a coin at its depth cap, so this is
+ // what keeps such a coin spendable, and it waives the base fee for a
+ // refresh of deep coins alone — so they go in a round of their own, never
+ // mixed with coins that would make it pay. A wallet paying hourly from one
+ // change chain (a subscription) is the usual way to get here.
+ async function flattenDeepCoins(mgr, tip) {
+ const deep = mgr.deepCoins ? mgr.deepCoins() : [];
+ if (!deep.length) return false;
+ if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return false;
+ const feeSat = mgr.refreshFee(deep, tip);
+ const totalSat = deep.reduce((n, v) => n + v.amountSat, 0);
+ if (totalSat - feeSat < 330 || feeSat * 10 > totalSat) return false; // dust, or a server charging full price: left alone
+ await mgr.refresh(deep.map((v) => v.id));
+ render();
+ return true;
+ }
+
async function maybeAutoRefresh(mgr) {
if (wallet.watchOnly || !mgr || !mgr.state) return;
if (Date.now() - arkAutoRefreshAt < 30 * 60_000) return;
+ const policy = custodyPolicy();
+ if (mgr.deepCoins && mgr.deepCoins().length) {
+ arkAutoRefreshAt = Date.now();
+ try { if (await flattenDeepCoins(mgr, await mgr.chain.tipHeight())) return; } catch {}
+ }
+ // "coinos holds my coins": nothing renews on its own and nothing warns.
+ // The server honors a coin past its timelock, and the holder chose this.
+ if (!policy) { arkRenewWarn = null; return; }
// NOT filtered by expiryRejected. A coin the server refused as expired
// can still be REFRESHED — that is the one thing an expired vtxo can
- // still do — and excluding it here meant a wallet holding nothing else
+ // always do — and excluding it here meant a wallet holding nothing else
// did nothing at all: no renewal attempt, and no warning either.
const spendables = freeCoins(mgr.state);
if (!spendables.length) { arkRenewWarn = null; return; }
@@ -3244,25 +3620,43 @@ export function arkFeature(ctx) {
// stamped, and this must not then run on every five-second sync.
if (Date.now() - arkBackstopAt > 30 * 60_000) {
arkBackstopAt = Date.now();
- await mgr.ensureScheduledRefreshes(backstopWindow()).catch(() => {});
+ await mgr.ensureScheduledRefreshes(policy.margin, 8, policy.grid).catch(() => {});
}
// never start a round while any other action is still in flight
if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return;
arkAutoRefreshAt = Date.now();
try {
const tip = await mgr.chain.tipHeight();
- const RENEW_BLOCKS = renewWindow();
- const expiringCoins = spendables.filter((v) => v.expiryHeight && v.expiryHeight - tip < RENEW_BLOCKS);
- const expiring = expiringCoins.length > 0;
- // Fragmentation alone is no longer worth paying for: multi-input sends
- // handle up to 24 coins, and consolidating FRESH coins bills the round
- // fee's top ppm bracket (a burst of refund coins after failed payments
- // once cost a user ~1% overnight). Consolidate only when the coin count
- // itself approaches the 24-input send ceiling.
- const fragmented = spendables.length >= 20;
+ const expiringCoins = spendables.filter((v) => v.expiryHeight && v.expiryHeight - tip < policy.window);
+ // The exit tier also renews a coin whose history has grown deep — each
+ // hop is one more on-chain transaction in a unilateral exit — but only
+ // a coin worth it: never more than a tenth of the coin on its renewal
+ // (300 sats to flatten a 21-sat coin's history would be absurd, and
+ // such a coin's exit is uneconomic whatever its depth).
+ const depthOf = (v) => { try { return mgr._decoded(v).genesis.length; } catch { return 0; } };
+ const deepCoins = !policy.maxDepth ? [] : spendables.filter((v) =>
+ !expiringCoins.includes(v) && depthOf(v) >= policy.maxDepth && mgr.refreshFee([v], tip) * 10 <= v.amountSat);
+ if (!expiringCoins.length && !deepCoins.length) { arkRenewWarn = null; return; }
+ // Worth it, or not at all: an automatic renewal never spends more than
+ // a tenth of what it renews. 301 sats to renew a 1,000-sat coin and
+ // four bits of change restored an exit nobody would ever use (the
+ // exit itself would cost more than the coins). Coins left alone stay
+ // spendable — the server keeps honoring them.
+ const worthIt = (set) => mgr.refreshFee(set, tip) * 10 <= set.reduce((n, v) => n + v.amountSat, 0);
+ if (!expiringCoins.length) {
+ // nothing is expiring: this round is for the deep coins alone, and
+ // they pay for it — the floor logic below still applies
+ arkRenewWarn = null;
+ let renewSet = [...deepCoins, ...spendables.filter((v) => !deepCoins.includes(v) && v.amountSat < 1000)];
+ const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip);
+ if (netSat(renewSet) < 330 || !worthIt(renewSet)) return;
+ await mgr.refresh(renewSet.map((v) => v.id));
+ render();
+ return;
+ }
const totalSat = spendables.reduce((n, v) => n + v.amountSat, 0);
const renewable = totalSat - mgr.refreshFee(spendables, tip) >= 330;
- if (expiring && !renewable) {
+ if (!renewable) {
// Can't save these coins ourselves — tell the user while receiving
// any amount (or spending) can still beat the clock.
const minExpiry = Math.min(...spendables.map((v) => v.expiryHeight || Infinity));
@@ -3273,26 +3667,25 @@ export function arkFeature(ctx) {
return;
}
arkRenewWarn = null;
- if (!expiring && !fragmented) return;
// Renew ONLY the coins that need it: dragging far-from-expiry coins
// into the round would bill their (higher) fee bracket for nothing.
- // The rare fragmentation consolidation still sweeps everything.
- //
- // But the subset must clear the server's 330-sat output floor BY
- // ITSELF — the renewable check above prices the whole balance. Two
- // dust coins at expiry (133 sats between them) failed their renewal
- // round silently every 30 minutes forever. Pull in the smallest
- // healthy coins until the renewed output is mintable.
- let renewSet = expiringCoins;
- if (!fragmented) {
- const extras = spendables
- .filter((v) => !expiringCoins.includes(v))
- .sort((a, b) => a.amountSat - b.amountSat);
- const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip);
- while (netSat(renewSet) < 330 && extras.length) renewSet = [...renewSet, extras.shift()];
- if (netSat(renewSet) < 330) return; // whole balance can't clear the floor — the warn above covers it
- }
- await mgr.refresh(fragmented ? undefined : renewSet.map((v) => v.id));
+ // Small change rides along, though: a coin under 1,000 sats costs at
+ // most 2 sats of ppm in this round, and folding it in now spares it a
+ // whole base fee's worth of round of its own when its turn comes.
+ let renewSet = [...expiringCoins, ...deepCoins, ...spendables.filter((v) => !expiringCoins.includes(v) && !deepCoins.includes(v) && v.amountSat < 1000)];
+ // The set must clear the server's 330-sat output floor BY ITSELF — the
+ // renewable check above prices the whole balance. Two dust coins at
+ // expiry (133 sats between them) failed their renewal round silently
+ // every 30 minutes forever. Pull in the smallest healthy coins until the
+ // renewed output is mintable.
+ const extras = spendables
+ .filter((v) => !renewSet.includes(v))
+ .sort((a, b) => a.amountSat - b.amountSat);
+ const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip);
+ while (netSat(renewSet) < 330 && extras.length) renewSet = [...renewSet, extras.shift()];
+ if (netSat(renewSet) < 330) return; // whole balance can't clear the floor — the warn above covers it
+ if (!worthIt(renewSet)) return; // not worth a tenth of itself: left alone, still spendable
+ await mgr.refresh(renewSet.map((v) => v.id));
render();
} catch {} // transient — the next throttled attempt retries
}
@@ -3309,8 +3702,8 @@ export function arkFeature(ctx) {
date: new Date(arkRenewWarn.deadlineMs).toLocaleDateString(),
});
navigator.serviceWorker?.ready
- .then((reg) => reg.showNotification('coinos', { body }))
- .catch(() => { try { new Notification('coinos', { body }); } catch {} });
+ .then((reg) => reg.showNotification(t('arkRenewWarnTitle'), { body }))
+ .catch(() => { try { new Notification(t('arkRenewWarnTitle'), { body }); } catch {} });
} catch {}
}
@@ -3359,7 +3752,7 @@ export function arkFeature(ctx) {
const boardsPaused = () => ((ark && ark.info && ark.info.minBoardAmountSat) || 0) >= 2_100_000_000_000_000;
function boardForm() {
if (boardsPaused()) return h('div', { class: 'notice small' }, t('arkBoardPaused'));
- const minBoard = (ark && ark.info && ark.info.minBoardAmountSat) || 0;
+ const minBoard = savingsBoardMin();
const canBoard = wallet.spendable >= minBoard;
return h('div', { class: 'col', style: 'width:100%;gap:8px' },
h('div', { class: 'input-group' },
@@ -3574,7 +3967,7 @@ export function arkFeature(ctx) {
const b = arkBalance() || { spendableSat: 0, pendingSat: 0 };
const spendable = b.spendableSat;
const total = b.spendableSat + b.pendingSat;
- const nSpend = freeCoins(arkStateNow()).length;
+ const nSpend = exitableCoins(arkStateNow(), (ark && ark._tipH) || 0).length;
const exitingSat = ((arkStateNow() && arkStateNow().actions) || [])
.filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step))
.reduce((n, a) => n + a.amountSat, 0);
@@ -3594,7 +3987,7 @@ export function arkFeature(ctx) {
h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')),
spendable > 0
? h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy, onClick: () => doArkOffboard() },
- ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('arkOffboardBtn', { n: fmtAmount(spendable) + ' ' + unitLabel() }))
+ ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('arkOffboardBtn', { n: fmtNative(spendable) }))
: h('div', { class: 'small faint' }, exitingSat > 0 ? t('arkExitCoopHeld') : t('arkExitNoBalance'))),
// unilateral
h('div', { class: 'card col', style: 'gap:8px' },
@@ -3629,10 +4022,10 @@ export function arkFeature(ctx) {
new Promise((r) => setTimeout(r, 800)),
]);
},
- // the Spending face's settings page leads with its coins
+ // the Spending face's settings page: the custody choice, then its coins
spendingSettings() {
if (wallet.watchOnly) return null; // a locked wallet can't renew or exit
- return arkCoinsPage({ embedded: true });
+ return arkCoinsPage({ embedded: true }); // the custody strategy sits inside, after the coins
},
// the wallet's own pages keep the top nav: these are pages, not takeovers
screenView() {
@@ -3728,6 +4121,7 @@ export function arkFeature(ctx) {
return mgr.fetchBolt12(offerStr, amountSat);
},
lnSpendableSat() { const b = arkBalance(); return b ? b.spendableSat : 0; },
+ arkSavingsCanBoard() { return savingsCanBoard(); },
spendingRenewingSat() { return renewingSat(); },
// Max for any Lightning amount form: spendable minus estimated fees.
lnMaxSendSat() { return lnMaxSat(); },
@@ -3751,7 +4145,7 @@ export function arkFeature(ctx) {
const short = Math.max(0, Math.ceil(needSat * 1.01) + 2 - have);
let gross = short;
try { for (let i = 0; i < 4; i++) gross = short + boardFee(gross, ark.info.boardFees); } catch {}
- const minBoard = (ark && ark.info && ark.info.minBoardAmountSat) || 0;
+ const minBoard = savingsBoardMin(); // remembered info too: the offer can come before connect
ctx.goHome();
ui.arkMoveOpen = true;
ui.arkMoveDir = 'toSpending';
@@ -3772,6 +4166,8 @@ export function arkFeature(ctx) {
return mgr.lnOutcome(paymentHash, timeoutMs);
},
arkSpendableSat() { const b = arkBalance(); return b ? b.spendableSat : 0; },
+ // everything Spending holds, settled or not
+ arkHeldSat() { const b = arkBalance(); return b ? b.spendableSat + b.pendingSat + b.boardingSat : 0; },
arkReady() { return arkAvailable(); },
// A Lightning invoice for another feature to watch (point of sale):
// the action id is the handle, the poller tells it when it settles.
@@ -3810,6 +4206,18 @@ export function arkFeature(ctx) {
// nwc.js calls this (with its connections) whenever the mirror should
// refresh: on enable, on connection changes, after payments, on a timer.
async arkBgWrite(connections, offer, prefs) { return writeBgMirror(connections, offer, prefs); },
+ // Back on screen: what the worker paid while this app sat behind another
+ // one is folded in now, not at the next start. true when there was any.
+ async arkBgAbsorb() {
+ if (!ark || !ark.state) return false;
+ return withBgLock(async () => {
+ const rec = await loadBg(wallet._cacheKey());
+ if (!rec || rec.v < 3 || !rec.mgr || (rec.workerAt || 0) <= bgAbsorbedAt || bgBusy(ark)) return false;
+ await mergeBgWorkerState(ark);
+ render();
+ return true;
+ });
+ },
async arkBgSpendableSat() {
const rec = await loadBg(wallet._cacheKey());
return ((rec && rec.mgr && rec.mgr.vtxos) || [])
@@ -3819,9 +4227,21 @@ export function arkFeature(ctx) {
async arkBgNoteSpends(spends) {
const mgr = await connectArk();
for (const sp of spends) {
+ // The worker's own manager wrote this payment's row into the mirror,
+ // and the merge on connect brings it over: a second row here showed
+ // every closed-app payment twice (PullCap, 2026-10-23). Stamp the
+ // row that exists instead; lnFoldedIds hides a twin that still
+ // forms when the merge lands after this note.
+ const twin = (mgr.state.movements || []).find((m) => m.type === 'ln-send'
+ && ((sp.preimage && m.preimage === sp.preimage) || (sp.paymentHash && m.paymentHash === sp.paymentHash)));
+ if (twin) {
+ if (!/while closed/.test(twin.detail || '')) twin.detail = `while closed · fee ${sp.feeSat || 0} sat`;
+ continue;
+ }
mgr._movement({
type: 'ln-send', amountSat: sp.amountSat, status: 'complete',
detail: `while closed · fee ${sp.feeSat || 0} sat`, invoice: sp.invoice || '', preimage: sp.preimage || '',
+ paymentHash: sp.paymentHash || undefined,
});
}
mgr._save();
@@ -3864,7 +4284,11 @@ export function arkFeature(ctx) {
}
// In a Spending wallet an on-chain address means "exit ark to there":
// the offboard happens right in the send flow, no Move money ceremony.
- if (ctx.getAccount() === 'spending' && wallet.isOnchainAddress(inv) && arkAvailable()) {
+ // One balance: an on-chain address is paid from the on-chain coins
+ // when there are any — one ordinary transaction, nothing to move out
+ // of Ark first. Only without them does the payment leave Ark.
+ const onchainFirst = ctx.unifiedBalance && ctx.unifiedBalance() && (wallet.spendable || 0) > 0;
+ if (ctx.getAccount() === 'spending' && !onchainFirst && wallet.isOnchainAddress(inv) && arkAvailable()) {
const b = arkBalance() || {};
if ((b.spendableSat || 0) > 0) {
ui.arkOffboardSend = { address: inv, amount: '' };
@@ -3890,11 +4314,13 @@ export function arkFeature(ctx) {
// paste. Own it: offer to board the shortfall from Savings when
// there is one, else say plainly what's short.
const need = (maybeLnInvoice(inv) || {}).amountSat || 0;
- if (need && wallet.spendable > 1000 && ctx.hook('arkOfferBoard', need)) return true;
+ if (need && savingsCanBoard() && ctx.hook('arkOfferBoard', need)) return true;
ui.sendError = t('arkLnExceedsSpending', {
need: fmtAmount(need) + ' ' + unitLabel(),
have: fmtAmount(arkBalance()?.spendableSat || 0) + ' ' + unitLabel(),
- });
+ }) + (wallet.spendable > 0 && !savingsCanBoard() // Savings has sats, just too few to move
+ ? ' ' + t('arkLnSavingsTooSmall', { have: fmtAmount(wallet.spendable) + ' ' + unitLabel(), min: fmtAmount(savingsBoardMin()) + ' ' + unitLabel() })
+ : '');
render();
return true;
}
@@ -3909,9 +4335,9 @@ export function arkFeature(ctx) {
// ⚡ button) — through the same resolution ladder as a pasted npub. The
// event id rides into the receipt's e tag; callers fall back to the
// lnZapNpub hook when ark can't serve this build/wallet.
- zapNpub(pk, npub, eventId, autoSat) {
+ zapNpub(pk, npub, eventId, autoSat, moment) {
if (!arkAvailable() || !wallet.nostrFetch) return false;
- startNpubPay(pk, npub, eventId || null, autoSat || 0);
+ startNpubPay(pk, npub, eventId || null, autoSat || 0, moment);
return true;
},
sendFormExtras() {
@@ -3925,10 +4351,11 @@ export function arkFeature(ctx) {
render();
} }, t('arkExitInFlightLink', { n: fmtAmount(acts.reduce((s2, a) => s2 + a.amountSat, 0)) }));
},
- historyEntries(_txs, sel) {
- if (sel && sel !== 'spending') return []; // ark movements are the Spending timeline
+ historyEntries(txs, sel) {
+ if (sel && sel !== 'spending' && sel !== 'all') return []; // ark movements are the Spending timeline
const s = arkStateNow();
if (!s) return [];
+ if (sel === 'all') return this._histOne(s, txs || []);
// Memoized on the state's REVISION, not a timer. This rebuild sorts and
// dedupes every movement, resolves gifts, and touches secp256k1 — ~60ms
// cold. A 1.5s TTL used to re-cool it between unhurried flicks, so every
@@ -3941,6 +4368,35 @@ export function arkFeature(ctx) {
this._histMemo = { key, val };
return val;
},
+ // One balance's timeline: a board, or an offboard to our own on-chain
+ // address, moves money between two halves of the same account. Its
+ // on-chain transaction and its Ark movement were two rows (Sent, then
+ // Boarded); here they're one, worth what the move cost.
+ _histOne(s, txs) {
+ const key = `${s._rev || 0}:${(s.movements || []).length}:${(s.actions || []).length}`;
+ if (!(this._histMemo && this._histMemo.key === key)) this._histMemo = { key, val: this._histBuild(s) };
+ const own = new Map(txs.map((tx) => [tx.txid, tx]));
+ const rows = this._histMemo.val.map((e) => {
+ const m = e.m;
+ // with no Savings to move to, an offboard elsewhere is a payment
+ if (m && m.type === 'offboard' && !(m.txid && own.has(m.txid))) return { ...e, render: () => arkHistoryItem(m, t('sent')) };
+ if (!m || !m.txid || !own.has(m.txid) || (m.type !== 'board' && m.type !== 'offboard')) return e;
+ const tx = own.get(m.txid);
+ const feeSat = m.type === 'board' ? Math.max(0, -(tx.net || 0) - (m.amountSat || 0)) : (m.feeSat || 0);
+ return { ...e, replacesTxid: m.txid, render: () => arkInternalMoveItem(m, feeSat, false) };
+ });
+ // a board still waiting on its funding transaction's confirmations
+ const told = new Set(rows.map((e) => e.replacesTxid).filter(Boolean));
+ for (const a of s.actions || []) {
+ if (a.type !== 'board' || !a.fundingTxid || ['done', 'failed'].includes(a.step) || told.has(a.fundingTxid)) continue;
+ const tx = own.get(a.fundingTxid);
+ if (!tx) continue;
+ const m = { id: null, type: 'board', amountSat: (a.amountSat || 0) - (a.feeSat || 0), ts: exitStartedTs(a), txid: a.fundingTxid };
+ const feeSat = Math.max(0, -(tx.net || 0) - m.amountSat);
+ rows.push({ time: m.ts, replacesTxid: a.fundingTxid, render: () => arkInternalMoveItem(m, feeSat, true) });
+ }
+ return rows;
+ },
_histBuild(s) {
// In-flight exits are payments the user made — they belong in history
// as pending records, not on a monitoring page nobody thinks to visit.
@@ -3955,7 +4411,7 @@ export function arkFeature(ctx) {
const paid = new Set((s.movements || []).filter((m) => m.type === 'ln-send' && m.status === 'complete').map((m) => m.paymentHash));
const lnPending = (s.actions || [])
.filter((a) => a.type === 'ln-pay' && !['done', 'failed'].includes(a.step) && !paid.has(a.paymentHash))
- .map((a) => { const m = lnPendingMove(a); return { time: m.ts, render: () => arkHistoryItem(m) }; });
+ .map((a) => { const m = lnPendingMove(a); return { time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }; });
// Same-payment duplicates (the old settle race, or a snapshot adopted
// whole before the merge learned to dedupe) fold at display time too —
// the earliest telling wins, everywhere, however the state got here.
@@ -3995,7 +4451,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);
@@ -4008,7 +4479,8 @@ export function arkFeature(ctx) {
out.push({ ...m, count: 1, vtxoIds: m.vtxoId ? [m.vtxoId] : [] });
}
}
- return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m) })));
+ this._histFolded = folded; // a folded row's detail shows the whole payment
+ return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, m, render: () => arkHistoryItem(m), csv: arkCsvRow(m) })));
},
historyDetail() {
if (ui.arkExitDetail) {
@@ -4027,7 +4499,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;
@@ -4092,7 +4565,11 @@ export function arkFeature(ctx) {
// and it is one tap away on the Manage page. What it cannot do is be
// spent over Ark or exited unilaterally, so saying nothing is the one
// option that isn't honest.
- if (!wallet.watchOnly && ark && ark.balance) {
+ // On the coinos servers a coin past its timelock is still money (the
+ // server keeps cosigning its spends) — the balance counts it and
+ // there is nothing to warn about; the custody tier the user chose
+ // says what expiry means to them. Elsewhere, the old warning.
+ if (!wallet.watchOnly && ark && ark.balance && !ark.honorsExpired) {
let expiredSat = 0;
try { expiredSat = ark.balance().expiredSat || 0; } catch {}
// Expired dust (under the 330-sat floor) cannot be renewed or exited
@@ -4174,7 +4651,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..9532125 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, from }) {
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 } : {}), ...(from ? { from } : {}) };
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..30b8d5e 100644
--- a/src/features/gifts.js
+++ b/src/features/gifts.js
@@ -8,20 +8,26 @@ import { decryptWithCode, npubOf } from '../nostr.js';
import { installGiftWallet, previewGift, giftOutpoints, giftClaimTxs, isRetiredGift, giftMinimum, lockGift, previewLockedGift } from './gifts-wallet.js';
import { t } from '../i18n.js';
import { qrSvg } from '../qr.js';
+import { withdrawLinks } from './withdraw-links.js';
import { fmtBtc, timeAgo, shortAddr } from '../format.js';
+import { getEventHash, verifyEvent } from 'nostr-tools/pure';
+import { sha256 } from '@noble/hashes/sha256';
+import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
+import { base32nopad } from '@scure/base';
export function giftsFeature(ctx) {
const {
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);
// every call degrades to null in an on-chain-only build.
const hook = ctx.hook || (() => null);
const arkGiftOf = (code) => hook('arkGiftDecode', code);
+ const wl = withdrawLinks(ctx); // prepaid LNURL-withdraw links, the gift link's sibling on Send
// ================================================================ GIFT / CLAIM
// Read a gift link, returning the code (and scrubbing it from the URL so the
@@ -32,6 +38,8 @@ export function giftsFeature(ctx) {
try {
const am = location.pathname.match(/^\/ag\/([A-Za-z0-9]+)\/?$/i); // ark gift
if (am) {
+ ui.claimNote = readNoteFrag();
+ ui.claimFrom = readFromFrag(am[1]);
history.replaceState(null, '', '/');
return arkGiftOf(am[1]) ? am[1] : null;
}
@@ -43,6 +51,7 @@ export function giftsFeature(ctx) {
if (hm) code = hm[1];
}
if (!code) return null;
+ if (pm) { ui.claimNote = readNoteFrag(); ui.claimFrom = readFromFrag(code); }
history.replaceState(null, '', '/');
return previewGift(code) ? code : null;
} catch {
@@ -57,6 +66,8 @@ export function giftsFeature(ctx) {
try {
const m = location.pathname.match(/^\/lg\/([A-Za-z0-9_-]+)\/?$/);
if (!m) return null;
+ ui.claimNote = null;
+ ui.claimFrom = null;
history.replaceState(null, '', '/');
return previewLockedGift(m[1]);
} catch { return null; }
@@ -120,6 +131,77 @@ 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;
+ // Who it's from rides there too (f=…): the sender's nostr key, signed over
+ // the gift's code, so a link can't be passed on as someone else's gift.
+ // 100 bytes in base32: pubkey, created_at, schnorr sig.
+ const giftFrag = (note, from) => {
+ const p = [];
+ if (note) p.push('m=' + encodeURIComponent(note));
+ if (from) p.push('f=' + from);
+ return p.length ? '#' + p.join('&') : '';
+ };
+ 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; }
+ }
+ const GIFT_FROM_KIND = 27121; // ephemeral range: never meant for a relay
+ const giftFromTmpl = (code, created_at) => ({
+ kind: GIFT_FROM_KIND, created_at, content: '',
+ tags: [['x', bytesToHex(sha256(new TextEncoder().encode(String(code).toUpperCase())))]],
+ });
+ // the sender's pubkey, if the link's f= is their signature over this code
+ function readFromFrag(code) {
+ try {
+ const f = [...new URLSearchParams(location.hash.slice(1))].find(([k]) => k.toLowerCase() === 'f')?.[1];
+ const b = f && base32nopad.decode(f.toUpperCase());
+ if (!b || b.length !== 100) return null;
+ const ev = { ...giftFromTmpl(code, new DataView(b.buffer, b.byteOffset).getUint32(32)),
+ pubkey: bytesToHex(b.slice(0, 32)), sig: bytesToHex(b.slice(36)) };
+ ev.id = getEventHash(ev);
+ return verifyEvent(ev) ? ev.pubkey : null;
+ } catch { return null; }
+ }
+ // Sign a new gift as ours (the messages feature holds the identity); null
+ // when there's no identity, the signer refuses, or it takes too long.
+ async function signGiftFrom(code) {
+ try {
+ const ev = await Promise.race([
+ hook('signGiftFrom', giftFromTmpl(code, Math.floor(Date.now() / 1000))),
+ new Promise((r) => setTimeout(() => r(null), 20_000)),
+ ]);
+ if (!ev || !ev.sig) return null;
+ const b = new Uint8Array(100);
+ b.set(hexToBytes(ev.pubkey), 0);
+ new DataView(b.buffer).setUint32(32, ev.created_at);
+ b.set(hexToBytes(ev.sig), 36);
+ return base32nopad.encode(b);
+ } catch { return null; }
+ }
+ const GIFT_ANON_KEY = 'giftAnon';
+ const giftAnon = () => { try { return localStorage.getItem(GIFT_ANON_KEY) === '1'; } catch { return false; } };
+ // who sent it, and that claiming follows them
+ const giftFromView = () => (ui.claimFrom
+ ? h('div', { class: 'col', style: 'align-items:center;gap:4px' },
+ h('div', { class: 'row gap6', style: 'align-items:center;justify-content:center' },
+ h('span', { class: 'small muted' }, t('giftFrom')),
+ hook('profileChip', ui.claimFrom, undefined, () => {})
+ || h('span', { class: 'small mono' }, (npubOf(ui.claimFrom) || '').slice(0, 16) + '…')),
+ h('div', { class: 'small faint' }, t('giftClaimFollows')))
+ : 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 or a sender the link has a # in it: a byte-mode QR (the
+ // bare link is upper-cased into the denser alphanumeric mode)
+ const giftQr = (url, hasFrag) => qrSvg(hasFrag ? url : url.toUpperCase(), { ec: 'L', mode: hasFrag ? 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 +253,8 @@ 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')),
+ giftFromView(),
+ 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'))
@@ -206,53 +290,47 @@ export function giftsFeature(ctx) {
h('h2', { style: 'margin:0' }, claimed ? t('claimedTitle') : t('newWalletTitle')),
h('p', { class: 'muted', style: 'margin:0' }, claimed ? t('claimedBody') : t('newWalletBody'))
),
- h('div', { class: 'card col' },
- h('h3', {}, t('recoveryPhrase')),
- h('div', { class: 'warn-box' }, t('writeDownWarn')),
- h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) },
- words.map((w, i) => h('div', { class: 'w' }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, w)))
- ),
- 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'))
- )
+ // a heads-up before the words, then the words, then one word to
+ // check (Adam, 2026-11-07) — the same three steps as a new wallet
+ !ui.claimShown
+ ? h('div', { class: 'card col' },
+ h('h3', { style: 'margin-top:0' }, t('recoveryPhrase')),
+ h('p', { style: 'margin:0' }, t('seedIntroBody', { n: words.length })),
+ h('p', { class: 'muted', style: 'margin:0' }, t('seedIntroPrivate')),
+ h('button', { id: 'claim-seed-show', class: 'btn-primary btn-block', onClick: () => { ui.claimShown = true; render(); } }, t('seedIntroShow')))
+ : h('div', { class: 'card col' },
+ h('h3', { style: 'margin-top:0' }, t('recoveryPhrase')),
+ h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) },
+ words.map((w, i) => h('div', { class: 'w' }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, w)))
+ ),
+ h('div', { class: 'row gap6' }, copyBtn(wallet.mnemonic, t('copyPhrase'))),
+ h('button', { id: 'claim-seed-next', class: 'btn-primary btn-block', onClick: () => { ui.confirm = pickConfirm(words); ui.claimError = ''; ui.claimStep = 'verify'; render(); } }, t('next')))
);
}
if (ui.claimStep === 'verify') {
- // Same word-confirmation as new-wallet creation: prove the recipient wrote
- // the phrase down before sending them off into their freshly funded wallet.
const words = wallet.mnemonic.split(' ');
+ const q = ui.confirm;
+ if (!q || !q.options) { ui.claimStep = 'backup'; ui.claimShown = true; return claimScreen(); }
return h(
'div',
{ class: 'col', style: 'gap:16px' },
brandHeader(false),
h('div', { class: 'card col' },
h('h3', { style: 'margin-top:0' }, t('recoveryPhrase')),
- h('p', { class: 'muted', style: 'margin:0' }, t('confirmBackupIntro')),
- ...ui.confirm.map((c, i) =>
- h('label', { class: 'field' },
- h('span', { class: 'lab' }, t('wordN', { n: c.index + 1 })),
- h('input', {
- type: 'text', class: 'mono-input', autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
- value: c.value, onInput: (e) => (ui.confirm[i].value = e.target.value.trim()),
- })
- )
- ),
- ui.claimError && h('div', { class: 'notice err' }, ui.claimError),
- h('div', { class: 'row gap6' },
- h('button', { class: 'btn-ghost', onClick: () => { ui.claimStep = 'backup'; ui.claimError = ''; render(); } }, t('back')),
+ h('p', { style: 'margin:0' }, t('quizPrompt', { n: q.index + 1 })),
+ h('div', { class: 'quiz-opts' }, q.options.map((w) =>
h('button', {
- class: 'btn-primary grow',
+ type: 'button',
+ class: 'quiz-opt' + (q.wrong.includes(w) ? ' wrong' : ''),
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();
+ if (w === words[q.index]) { ui.claimError = ''; finishClaim(); return; }
+ if (!q.wrong.includes(w)) q.wrong.push(w);
+ ui.claimError = t('quizWrong'); render();
},
- }, t('openWallet'))
- ),
- h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); render(); } }, t('skipVerification'))
+ }, w))),
+ ui.claimError && h('div', { class: 'notice err' }, ui.claimError),
+ h('button', { id: 'claim-seed-skip', class: 'btn-ghost btn-block', onClick: () => { ui.claimError = ''; finishClaim(); } }, t('skip')),
+ h('button', { class: 'linklike small', style: 'align-self:center', onClick: () => { ui.claimStep = 'backup'; ui.claimShown = true; ui.claimError = ''; render(); } }, t('quizBack')),
)
);
}
@@ -286,7 +364,7 @@ export function giftsFeature(ctx) {
// view the claim on a block explorer, or head back to the home screen.
h('button', { class: 'btn-primary btn-block', onClick: () => {
ui.claimTaken = null; ui.claimedAmount = 0;
- if (activeAccount() && activeAccount().provisional) { ui.claimStep = 'backup'; commitAccount(); }
+ if (activeAccount() && activeAccount().provisional) { ui.claimStep = 'backup'; ui.claimShown = false; commitAccount(); }
else { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); }
render();
} }, activeAccount() && activeAccount().provisional ? t('createWalletAnyway') : t('goToWallet')),
@@ -313,6 +391,8 @@ 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')),
+ giftFromView(),
+ giftNoteView(),
h('div', { class: 'amt', style: 'font-size:30px' },
h('span', { class: 'amount-pos' }, fmtAmount(total)), ' ', unitTag('unit')
),
@@ -324,10 +404,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,12 +470,23 @@ 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);
commitAccount(); // claimed — keep a fresh gift wallet (no-op for an existing one)
+ if (ui.claimFrom) hook('followGiftSender', ui.claimFrom);
if (wasProvisional) {
- ui.claimStep = 'backup'; // fresh wallet — show the new seed to back up
+ ui.claimStep = 'backup'; ui.claimShown = false; // fresh wallet — show the new seed to back up
} else {
ui.screen = 'wallet'; // existing wallet — straight into it, no new seed to back up
ui.claimStep = null;
@@ -526,13 +619,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}${giftFrag(g.note, g.from)}`;
let svg = null;
- try { svg = qrSvg(url.toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }); } catch {}
+ try { svg = giftQr(url, !!(g.note || g.from)); } 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,9 +661,9 @@ 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);
+ await finishGift(g, amt);
} catch (e) {
ui.giftError = e.message;
}
@@ -611,12 +705,21 @@ export function giftsFeature(ctx) {
doCreateGift(amt, rate);
}
- // Finalize a freshly-built gift: a plain bearer link.
- function finishGift(g, fallbackAmt) {
+ // Finalize a freshly-built gift: a plain bearer link, signed as ours
+ // unless the sender would rather stay anonymous. Recorded before the
+ // signer is asked, so a signer that never answers can't lose the gift.
+ async function finishGift(g, fallbackAmt) {
const amount = g.amount || fallbackAmt || 0;
+ const note = giftNoteNow(); // the link says what was typed when it was made
+ const rec = { code: g.code, locked: false, amount, outpoints: g.reserved, note };
+ wallet.recordGift(rec);
+ const from = giftAnon() ? null : await signGiftFrom(g.code);
+ if (from) wallet.recordGift({ ...rec, from });
ui.giftCode = g.code;
- wallet.recordGift({ code: g.code, locked: false, amount, outpoints: g.reserved });
+ ui.giftNoteMade = note;
+ ui.giftFromMade = from;
}
+ const giftNoteNow = () => String(ui.giftNote || '').trim().slice(0, GIFT_NOTE_MAX) || null;
function giftCard() {
const active = wallet.outstandingGifts();
@@ -631,13 +734,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 || ui.giftFromMade)); } 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.giftFromMade = null; ui.giftMax = false; ui.giftIsArk = false; render(); } }, t('giftAnother'))
)
)
: ui.giftSplitOffer
@@ -692,6 +796,15 @@ 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; } }),
+ // the link names its sender (and claiming follows them) unless unticked
+ h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
+ h('input', { type: 'checkbox', checked: !giftAnon(), onChange: (e) => {
+ try { if (e.target.checked) localStorage.removeItem(GIFT_ANON_KEY); else localStorage.setItem(GIFT_ANON_KEY, '1'); } catch {}
+ } }),
+ h('span', { class: 'small' }, t('giftFromMe'))),
ui.giftError && h('div', { class: 'notice err' }, ui.giftError),
ui.busy
? h('button', { class: 'btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
@@ -864,36 +977,40 @@ 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}${giftFrag(ui.giftNoteMade, ui.giftFromMade)}`;
}
function giftRate() {
return (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
}
- function doCreateGift(amt, rate) {
+ async function doCreateGift(amt, rate) {
+ ui.busy = true; render();
try {
- finishGift(wallet.createGift(amt, rate), amt);
+ await finishGift(wallet.createGift(amt, rate), amt);
ui.giftError = '';
ui.giftSplitOffer = null;
} catch (e) {
ui.giftError = e.message;
ui.giftSplitOffer = null;
}
+ ui.busy = false;
render();
}
// Gift the whole spendable balance as a no-change sweep (the recipient receives
// everything minus their claim fee).
- function doCreateGiftAll(rate) {
+ async function doCreateGiftAll(rate) {
+ ui.busy = true; render();
try {
- finishGift(wallet.createGiftAll(rate));
+ await finishGift(wallet.createGiftAll(rate));
ui.giftError = '';
ui.giftMax = false;
ui.giftSplitOffer = null;
} catch (e) {
ui.giftError = e.message;
}
+ ui.busy = false;
render();
}
@@ -906,7 +1023,7 @@ export function giftsFeature(ctx) {
ui.busy = true; ui.giftError = ''; render();
try {
const rate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
- finishGift(await wallet.createGiftFromSplit(amt, rate), amt);
+ await finishGift(await wallet.createGiftFromSplit(amt, rate), amt);
ui.giftSplitOffer = null;
ui.giftError = '';
} catch (e) {
@@ -970,14 +1087,16 @@ export function giftsFeature(ctx) {
return { blob, claimCode, url: `${location.origin}/lg/${blob}` };
},
receiveTakeover() { return claimCelebration(); },
- sendView() { return ui.giftMode ? giftView() : null; },
+ sendView() { return ui.giftMode === 'lnurl' ? wl.view() : ui.giftMode ? giftView() : null; },
sendFormExtras() {
- return h('button', { class: 'linklike small', style: 'align-self:center;margin-top:2px', onClick: () => { ui.giftMode = true; ui.sendError = ''; render(); } }, '🎁 ' + t('giftLink'));
+ return h('div', { class: 'row gap6 wrap', style: 'justify-content:center;column-gap:18px' },
+ h('button', { class: 'linklike small', style: 'margin-top:2px', onClick: () => { ui.giftMode = true; ui.sendError = ''; render(); } }, '🎁 ' + t('giftLink')),
+ wl.entry());
},
balanceLines() {
const locked = wallet.giftLockedValue();
// on-chain reservations: money still in Savings, spoken for
- return locked > 0 ? [{ label: t('lockedInGifts'), sat: locked, side: 'savings' }] : [];
+ return locked > 0 ? [{ label: t('balGifts'), sat: locked, side: 'savings', part: true }] : [];
},
historyEntries(txs, sel) {
// These are ON-CHAIN gift reservations — Savings timeline. Ark gifts show
diff --git a/src/features/hats.js b/src/features/hats.js
index a14fc2b..a00f285 100644
--- a/src/features/hats.js
+++ b/src/features/hats.js
@@ -222,9 +222,52 @@ export function hatsFeature(ctx) {
}
}
+ // ---- the whole list ------------------------------------------------------
+ // Only a couple of dozen heads wear a hat, so the registrar hands over all
+ // of them (/hats/worn) and every avatar is answered from that, even one
+ // seen for the first time; per-head lookups were 400 ms + a round trip
+ // after the page had painted. Public data, so it's kept per device, not per
+ // account. Until it has arrived once, the per-head path above still runs.
+ const ALL_KEY = (net) => 'hat-worn-all:' + net;
+ const allWorn = {}; // net -> { hats: {pk: id}, t }
+ const readAll = (net) => {
+ if (!(net in allWorn)) {
+ try { allWorn[net] = JSON.parse(localStorage.getItem(ALL_KEY(net)) || 'null'); } catch { allWorn[net] = null; }
+ }
+ return allWorn[net];
+ };
+ const allBusy = {}, allFailedAt = {};
+ async function fetchAll(net) {
+ if (allBusy[net] || Date.now() - (allFailedAt[net] || 0) < 60_000) return;
+ allBusy[net] = true;
+ try {
+ const r = await fetch(`${REGISTRAR}/hats/worn?net=${net}`);
+ if (!r.ok) throw new Error('hats list failed');
+ const j = await r.json();
+ const hats = j.hats || {};
+ const prev = readAll(net);
+ allWorn[net] = { hats, t: Date.now() };
+ try { localStorage.setItem(ALL_KEY(net), JSON.stringify(allWorn[net])); } catch {}
+ if (!prev || JSON.stringify(prev.hats) !== JSON.stringify(hats)) render();
+ } catch {
+ allFailedAt[net] = Date.now();
+ } finally {
+ allBusy[net] = false;
+ }
+ }
+ const fromAll = (pk) => {
+ const net = hatNet();
+ const all = readAll(net);
+ if (!all || Date.now() - all.t > REVALIDATE) fetchAll(net);
+ return all ? { hat: all.hats[pk] || null } : null;
+ };
+ setTimeout(() => { try { fromAll(''); } catch {} }, 0); // warm before the first avatar
+
// Stale-while-revalidate: answer from cache immediately, refresh behind.
function hatFor(pk) {
if (!pk || !/^[0-9a-f]{64}$/.test(pk)) return null;
+ const known = fromAll(pk);
+ if (known) return known.hat;
loadStore();
const v = worn.get(hatNet() + ':' + pk);
if (!v || Date.now() - v.t > REVALIDATE) queueFetch(pk);
@@ -438,6 +481,15 @@ export function hatsFeature(ctx) {
node,
h('span', { class: 'ava-hat', style: posStyle(hat), html: hat.art }));
},
+ // A wallet just opened: the /hats link lands in the shop.
+ init() {
+ if (!ui.hatsAtBoot) return;
+ ui.hatsAtBoot = false;
+ ui.screen = 'wallet';
+ openShop();
+ },
+ // ...and the shop's address is /hats for as long as it is on screen
+ navPath(snap) { return snap && snap.screen === 'wallet' && snap.hatShop ? '/hats' : null; },
// The footer's "Show your support" link: straight into the shop.
openHatShop() { openShop(); try { window.scrollTo(0, 0); } catch {} return true; },
// Own-profile editor entry: the door to the shop.
diff --git a/src/features/messages.js b/src/features/messages.js
index 3789f93..2351e2b 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -1,3 +1,5 @@
+import { mediaMoment, momentTags, readMoment, mediaClock, mediaTimeline, markAt, momentToggle } from '../media-timeline.js';
+import { mediaServers } from '../media-servers.js';
// Messages — Concord community chat (CORD-01..05) + NIP-17 private DMs.
//
// Communities are end-to-end private: there is no global discovery in
@@ -13,14 +15,14 @@
// listens for both identities and decrypts with whichever keys are present.
import {
- subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay,
+ subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, queryDepthOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay, wakeRelays,
npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44,
PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread, verifyEventsAsync, setSyncConfig, DEFAULT_SYNC_RELAYS,
} from '../nostr.js';
import { reconcileOn, syncOn, negentropyOff } from '../nostr.js'; // NIP-77: fetch only what we lack
import {
channelKey, channelStream, channelEpoch, channelIsPrivate, controlKey, guestbookKey, openWrap, wrapRumor, rumorWithId,
- foldControl, foldGuestbook, observeAuthor, eventMs, msTags, makeEdition,
+ foldControl, foldGuestbook, observeAuthor, eventMs, msTags, makeEdition, banlistHead, makeBanlist,
communityId, parseInviteLink, makeInviteLink, makeInviteBundleEvent, openInviteBundle,
} from '../concord.js';
import { makeDMRumor, makeDMReaction, unwrapDM, wrapDM } from '../dm.js';
@@ -34,10 +36,10 @@ import { loadMediaIndex, saveMediaIndex, wipeMediaIndex } from '../media-cache.j
import { mergeFeedWindow } from '../feed-window.js';
import { createThreadStore } from '../thread-cache.js';
import { createThreadPrefetch } from '../thread-prefetch.js';
-import { makeImageThumbnails } from '../image-thumbnails.js';
+import { makeImageThumbnails, loopGif } from '../image-thumbnails.js';
import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js';
import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js';
-import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache } from '../recipient-search.js';
+import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache, searchRecipients, searchable, setLocalPeople } from '../recipient-search.js';
import { getNetwork } from '../api.js';
import { decodeBolt11 } from '../ark/lightning.js';
import { hexToBytes, bytesToHex } from '@noble/hashes/utils';
@@ -52,6 +54,8 @@ import { animateZap, warmZapSound } from '../zap-animation.js';
import { SIGNER_SILENT } from '../dm.js';
import { cacheStorage, onCacheReady, cacheIsReady } from '../cache-store.js';
import { dlog } from '../debug.js';
+import { createCalls, openCall, wrapCall, CALL, CALL_WRAP, RING_S } from '../calls.js';
+import { LIVE_KIND, LIVE_CHAT_KIND, LIVE_RELAYS, liveAddr, liveHost, liveTitle, liveSummary, liveImage, liveViewers, liveStarts, liveStream, liveRecording, liveStatus as announcedStatus, isLiveNow as isLiveAnnounced, liveRelays, newestByAddr, zapLine, setZapAddr, liveReactions } from '../live.js';
import { qrSvg } from '../qr.js';
// The coinos community's join material lives in ../community.js — shared
@@ -60,7 +64,15 @@ import { COMMUNITY, EPOCH } from '../community.js';
import COMMUNITY_DIRECTORY from '../community-directory.json';
import { assetUrl } from '../asset-url.js';
import { mergeFeeds } from '../feed-sync.js';
-const DM_RELAYS = ['wss://relay.coinos.io', 'wss://nos.lol'];
+// 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.
+// 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
@@ -69,6 +81,7 @@ const CACHE_MAX = 50; // messages kept per channel / per DM thread in feature st
// kind-31990 handler coordinate, which we haven't published. Deliberately
// absent from anything encrypted (DMs, community wraps) — those are private
// and need no billboard.
+const CALL_LOG = 1405; // a call, logged in its conversation (see logCall)
const CLIENT_TAG = ['client', 'coinos', '31990:72bdbc57bdd6dfc4e62685051de8041d148c3c68fe42bf301f71aa6cf53e52fb:coinos'];
// A view the URL asks to open (a notification tap): read once, then taken
@@ -88,7 +101,7 @@ export function messagesFeature(ctx) {
const gifs = createGifPicker({ h, t, ui, render });
// NIP-92: an attachment described, so clients needn't sniff the URL
const mediaImeta = (m) => ['imeta', 'url ' + m.url, ...(m.m ? ['m ' + m.m] : []), ...(m.dim ? ['dim ' + m.dim] : []),
- ...(m.size ? ['size ' + m.size] : []), ...(m.alt ? ['alt ' + m.alt] : [])];
+ ...(m.size ? ['size ' + m.size] : []), ...(m.duration ? ['duration ' + m.duration] : []), ...(m.alt ? ['alt ' + m.alt] : [])];
// ---- persisted state ----------------------------------------------------
@@ -475,8 +488,9 @@ export function messagesFeature(ctx) {
function roomUnread(room) {
const s = st();
const my = myPubkeys();
+ const banned = room.folded && room.folded.banned;
for (const [id, msgs] of room.byChannel)
- if (newestFrom(msgs.values(), (m) => !my.includes(m.author)) > (s.read[chRead(id)] || 0)) return true;
+ if (newestFrom(msgs.values(), (m) => !my.includes(m.author) && !(banned && banned.has(m.author))) > (s.read[chRead(id)] || 0)) return true;
return false;
}
@@ -574,7 +588,10 @@ export function messagesFeature(ctx) {
let repostBy = null; // set while noteRow draws a repost's note
// A profile shows its articles (NIP-23) among the notes, as Amethyst does.
// Their boosts too, under "<name> reposted", as in a feed.
- const PROFILE_KINDS = [...FEED_KINDS, 30023, REPOST];
+ // ...and their NIP-22 comments (kind 1111): the Replies tab is where
+ // those go, and a comment scoped to a web address (DaddyTube's, on a
+ // film's IMDb page) was never asked for at all
+ const PROFILE_KINDS = [...FEED_KINDS, 30023, REPOST, 1111];
// An edited article is a new event at the same address: keep the newest.
const newestArticles = (evs) => {
const best = new Map();
@@ -744,14 +761,43 @@ export function messagesFeature(ctx) {
let allUnsubs = [];
let dmUnsubs = []; // the DM wrap subscriptions alone, so they can be rebuilt
+ // Is the page under the reader's finger, or still coasting from a flick?
+ // Background work (a repaint for a face that arrived, writing the profile
+ // cache) waits for it to settle: on Adam's Pixel a flick through the feed
+ // spent 1.7 s of 9 on the main thread doing exactly that, and taps queued
+ // behind it (2026-11-07, "flick to scroll … not getting up to speed …
+ // clicking around feels sluggish"). Never longer than `most` ms, though:
+ // a slow, steady read must still see what arrived.
+ let pageMovedAt = 0, fingerDown = false;
+ if (typeof window !== 'undefined') {
+ window.addEventListener('scroll', () => { pageMovedAt = Date.now(); }, { passive: true, capture: true });
+ window.addEventListener('touchstart', () => { fingerDown = true; }, { passive: true, capture: true });
+ for (const n of ['touchend', 'touchcancel']) window.addEventListener(n, (e) => { if (!e.touches || !e.touches.length) fingerDown = false; }, { passive: true, capture: true });
+ }
+ const pageMoving = () => fingerDown || Date.now() - pageMovedAt < 200;
+ const whenSettled = (fn, most = 1500, step = 150) => {
+ const until = Date.now() + most;
+ const go = () => { if (pageMoving() && Date.now() < until) { setTimeout(go, step); return; } fn(); };
+ go();
+ };
+
let repaintTimer = null;
const scheduleRepaint = () => {
if (repaintTimer) return;
- repaintTimer = setTimeout(() => {
+ const since = Date.now();
+ const run = () => {
+ // not under a pager in motion: the page beneath is out of sight, and
+ // its repaint (40–55 ms on Adam's phone) dropped frames from flights
+ // through the pictures (2026-10-17) — it waits for the landing
+ if (pagerMoving()) { repaintTimer = setTimeout(run, 120); return; }
+ // nor mid-flick on the page itself (up to 1.5 s): a whole-page morph
+ // in the middle of a fling is a dropped frame and a late tap
+ if (pageMoving() && Date.now() - since < 1500) { repaintTimer = setTimeout(run, 150); return; }
repaintTimer = null;
// a visitor's public page (a profile, a thread, a feed) repaints too
if (ui.screen === 'wallet' || ui.pubProf) renderThreadStable();
- }, 80);
+ };
+ repaintTimer = setTimeout(run, 80);
};
// Profiles persist across sessions (capped) so known faces paint right
@@ -805,11 +851,14 @@ export function messagesFeature(ctx) {
// memory and is written back once per burst: a batch of thirty profiles
// landing during a scroll used to parse and re-serialize the whole blob
// thirty times over, on the main thread, mid-scroll.
- let profBlob = null, profFlush = null;
+ let profBlob = null, profFlush = null, profFlushSince = 0;
const PROFILE_ROWS = 1500; // a row without a thumbnail is ~430 chars; IndexedDB has room
const profilesDisk = () => (profBlob ||= wallet.loadFeatureState('profiles', {}));
- function flushProfiles() {
- profFlush = null;
+ function flushProfiles(force) {
+ // up to 5 s for the page to settle: stringifying this blob (thumbnails
+ // and all, up to ~2 MB) is a long main-thread task
+ if (!force && pageMoving() && Date.now() - (profFlushSince || 0) < 5000) { profFlush = setTimeout(flushProfiles, 300); return; }
+ profFlush = null; profFlushSince = 0;
const s = profBlob;
if (!s) return;
// Who stays when space runs out: your own faces, the people you follow,
@@ -827,7 +876,10 @@ export function messagesFeature(ctx) {
// Thumbnails are the bulk of this blob, so they live on a budget: the
// least recently seen strangers give theirs up first. The row itself
// stays — that face just paints the way it used to.
- let size = JSON.stringify(s).length;
+ // (an estimate, not a JSON.stringify of the lot just to measure it:
+ // a row is ~430 chars plus its thumbnail)
+ let size = 0;
+ for (const k in s) size += 430 + ((s[k] && s[k].thumb) || '').length;
if (size > THUMB_BUDGET) {
// never our own: the header face is the one that must paint offline
for (const k of evictFirst(Object.keys(s).filter((k) => s[k].thumb && !mine.has(k)))) {
@@ -854,7 +906,7 @@ export function messagesFeature(ctx) {
? { thumb: p.thumb, thumbFor: p.thumbFor, thumbPx: p.thumbPx || 0 } : {}),
...(p.thumbFail ? { thumbFail: p.thumbFail, thumbFailAt: p.thumbFailAt || 0, thumbFails: p.thumbFails || 1,
thumbFailVersion: p.thumbFailVersion || 0 } : {}) };
- if (!profFlush) profFlush = setTimeout(flushProfiles, 500);
+ if (!profFlush) { profFlushSince = Date.now(); profFlush = setTimeout(flushProfiles, 500); }
}
// A punk picture is OUR OWN art. Every coinos user who keeps the default
// publishes https://v3.coinos.io/punks/N.webp as their nostr picture, and
@@ -998,6 +1050,101 @@ export function messagesFeature(ctx) {
}
}
}
+ // ---- a Blossom blob gone from its host, found on another ---------------
+ // A picture named by its sha256 (…/<64 hex>.jpg) is a Blossom blob: any
+ // server holding the same bytes serves them under the same name. When the
+ // host in the URL no longer has it — Karnage's face and banner on
+ // media.21media.to answered "blob not found" (2026-11-02) while
+ // blossom.primal.net, the server he publishes in his kind 10063, still had
+ // both — the picture is looked for on the servers the person published
+ // and then on the public ones we know, and the first that answers stands
+ // in for it: the thumbnail is made from it, the big face and the banner
+ // paint from it. Remembered on the device, so the search runs once.
+ const BLOB_RE = /^(https?:\/\/[^/?#]+)(?:\/[^?#]*)?\/([0-9a-f]{64})(\.[a-z0-9]{2,5})?(?:[?#].*)?$/i;
+ const BLOB_ALT_HOSTS = ['https://blossom.primal.net', 'https://blossom.ditto.pub', 'https://nostr.download',
+ 'https://blossom.nostr.build', 'https://blossom.band', 'https://cdn.satellite.earth'];
+ const BLOB_ALT_KEY = 'btc-wallet-blob-alts';
+ const blobAlts = new Map(); // url -> the copy that answered, or null when none did
+ (() => { try { for (const [k, v] of Object.entries(JSON.parse(localStorage.getItem(BLOB_ALT_KEY) || '{}'))) if (typeof v === 'string') blobAlts.set(k, v); } catch {} })();
+ const saveBlobAlts = () => {
+ try {
+ const found = [...blobAlts].filter(([, v]) => v).slice(-200);
+ localStorage.setItem(BLOB_ALT_KEY, JSON.stringify(Object.fromEntries(found)));
+ } catch {}
+ };
+ const blobProbing = new Map();
+ const blobAltOf = (url) => (url && blobAlts.get(url)) || null;
+ // the servers a person publishes for their files (BUD-03), asked only when
+ // one of their pictures has gone missing
+ const blobServersOf = async (pk) => {
+ try {
+ const evs = await queryOn(PROFILE_RELAYS, { kinds: [10063], authors: [pk], limit: 1 }, 4000);
+ const ev = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
+ return ev ? ev.tags.filter((x) => x[0] === 'server' && /^(https:\/\/|http:\/\/localhost(:\d+)?\/)/i.test(x[1] || ''))
+ .map((x) => x[1].replace(/\/+$/, '')) : [];
+ } catch { return []; }
+ };
+ // does an <img> load from here? (no CORS needed to find out)
+ const imageAnswers = (url, ms = 8000) => new Promise((resolve) => {
+ const im = new Image();
+ const timer = setTimeout(() => { im.onload = im.onerror = null; im.src = ''; resolve(false); }, ms);
+ im.onload = () => { clearTimeout(timer); resolve(true); };
+ im.onerror = () => { clearTimeout(timer); resolve(false); };
+ im.src = url;
+ });
+ function findBlobAlt(url, pk) {
+ if (blobAlts.has(url)) return Promise.resolve(blobAlts.get(url));
+ if (blobProbing.has(url)) return blobProbing.get(url);
+ const m = BLOB_RE.exec(url || '');
+ if (!m || typeof Image === 'undefined') return Promise.resolve(null);
+ const task = (async () => {
+ const origin = m[1].toLowerCase(), name = m[2] + (m[3] || '');
+ const hosts = [...new Set([...(pk ? await blobServersOf(pk) : []), ...BLOB_ALT_HOSTS])]
+ .filter((h) => h.toLowerCase() !== origin);
+ // asked together (a host that hangs mustn't hold the rest), the
+ // person's own servers preferred among those that answer
+ const answers = await Promise.all(hosts.map((h) => imageAnswers(h + '/' + name).then((ok) => (ok ? h + '/' + name : null))));
+ const alt = answers.find(Boolean) || null;
+ blobAlts.set(url, alt);
+ if (alt) saveBlobAlts();
+ return alt;
+ })().finally(() => blobProbing.delete(url));
+ blobProbing.set(url, task);
+ return task;
+ }
+ // Centre-crop to a square (the way background-size:cover paints it),
+ // shrink, and encode — off the main thread where the browser allows: the
+ // crop and resize through createImageBitmap, the encode through an
+ // OffscreenCanvas's convertToBlob. The synchronous canvas.toDataURL it
+ // replaces cost ~30 ms a face on a phone, mid-scroll (2026-11-07).
+ async function encodeThumb(bmp) {
+ const side = Math.min(bmp.width, bmp.height);
+ if (!side) throw new Error('empty');
+ const sx = (bmp.width - side) / 2, sy = (bmp.height - side) / 2;
+ if (typeof OffscreenCanvas !== 'undefined' && OffscreenCanvas.prototype.convertToBlob) {
+ let small = null;
+ try {
+ small = await createImageBitmap(bmp, sx, sy, side, side, { resizeWidth: THUMB_PX, resizeHeight: THUMB_PX, resizeQuality: 'high' });
+ const oc = new OffscreenCanvas(THUMB_PX, THUMB_PX);
+ oc.getContext('2d').drawImage(small, 0, 0);
+ const asUrl = (b) => new Promise((ok, bad) => { const r = new FileReader(); r.onload = () => ok(r.result); r.onerror = () => bad(r.error); r.readAsDataURL(b); });
+ let blob = await oc.convertToBlob({ type: 'image/webp', quality: 0.75 });
+ if (blob.type !== 'image/webp') blob = await oc.convertToBlob({ type: 'image/jpeg', quality: 0.7 });
+ if (blob.size * 4 / 3 > THUMB_MAX) blob = await oc.convertToBlob({ type: 'image/webp', quality: 0.5 }); // a busy picture, leaned on harder
+ const data = await asUrl(blob);
+ if (data.length > THUMB_MAX) throw new Error('too big');
+ return data;
+ } finally { try { small && small.close(); } catch {} }
+ }
+ const c = document.createElement('canvas');
+ c.width = c.height = THUMB_PX;
+ c.getContext('2d').drawImage(bmp, sx, sy, side, side, 0, 0, THUMB_PX, THUMB_PX);
+ let data = c.toDataURL('image/webp', 0.75);
+ if (!data.startsWith('data:image/webp')) data = c.toDataURL('image/jpeg', 0.7);
+ if (data.length > THUMB_MAX) data = c.toDataURL('image/webp', 0.5);
+ if (data.length > THUMB_MAX) throw new Error('too big');
+ return data;
+ }
function makeThumb(pk, p) {
if (!p || !p.picture || typeof document === 'undefined') return;
if (noCorsHost(p.picture)) return; // a host that won't hand over bytes; the <img> shows it anyway
@@ -1054,21 +1201,23 @@ export function messagesFeature(ctx) {
// the browser's cache is welcome: the face was just painted from this
// very URL, and 'reload' re-downloaded every original (38 MB in one
// scroll) — a stale copy still makes a fine thumbnail
- const res = await corsFetch(url, AbortSignal.timeout(THUMB_SLOW));
- if (!res.ok) throw new Error('http ' + res.status);
+ let res = null;
+ try { res = await corsFetch(url, AbortSignal.timeout(THUMB_SLOW)); } catch (e) {
+ if (e && e.corsRefused) noteNoCors(url);
+ if (!BLOB_RE.test(url)) throw e;
+ }
+ // the host no longer has it (or won't answer): the same blob on
+ // another server is as good — and the face it paints is this one
+ if (!res || !res.ok) {
+ const alt = BLOB_RE.test(url) ? await findBlobAlt(url, pk) : null;
+ if (!alt) throw new Error('http ' + (res ? res.status : 'none'));
+ res = await corsFetch(alt, AbortSignal.timeout(THUMB_SLOW));
+ if (!res.ok) throw new Error('http ' + res.status);
+ scheduleRepaint(); // the big face, where one is up, can paint from the copy now
+ }
bmp = await createImageBitmap(await res.blob());
- // centre-crop to a square, the way background-size:cover paints it
- const side = Math.min(bmp.width, bmp.height);
- if (!side) throw new Error('empty');
- const c = document.createElement('canvas');
- c.width = c.height = THUMB_PX;
- c.getContext('2d').drawImage(bmp, (bmp.width - side) / 2, (bmp.height - side) / 2,
- side, side, 0, 0, THUMB_PX, THUMB_PX);
- let data = c.toDataURL('image/webp', 0.75);
- if (!data.startsWith('data:image/webp')) data = c.toDataURL('image/jpeg', 0.7);
- if (data.length > THUMB_MAX) data = c.toDataURL('image/webp', 0.5); // a busy picture, leaned on harder
- if (data.length > THUMB_MAX) throw new Error('too big');
- done({ thumb: data, thumbFor: url, thumbPx: THUMB_PX });
+ const data = await encodeThumb(bmp);
+ whenSettled(() => done({ thumb: data, thumbFor: url, thumbPx: THUMB_PX }));
} catch (e) {
// a quick TypeError is the CORS refusal (a dead host takes longer)
// only a refusal corsFetch confirmed (a body cut off mid-download
@@ -1458,6 +1607,7 @@ export function messagesFeature(ctx) {
for (const room of wanted) subscribeRoom(room);
if (wn) wn.resubscribe();
if (cd) cd.resubscribe();
+ if (ng) ng.resubscribe();
}
// ---- subscription watchdog ------------------------------------------------
@@ -1869,9 +2019,12 @@ export function messagesFeature(ctx) {
const mine = my.includes(m.author);
const reacts = room.reactions.get(m.rumor.id);
const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
- const close = () => { ui.msgSheet = null; ui.emojiPick = null; render(); };
- const item = (icon, label, onClick) => h('button', { class: 'msg-sheet-item', onClick },
+ const close = () => { ui.msgSheet = null; ui.emojiPick = null; ui.msgBanArm = null; render(); };
+ const item = (icon, label, onClick, cls = '') => h('button', { class: 'msg-sheet-item' + cls, onClick },
h('span', { class: 'msg-sheet-ico' }, icon), label);
+ // the community's admin can take a person out, with everything they said
+ const canBan = !mine && canModerate(room) && m.author !== room.jm.owner;
+ const armed = ui.msgBanArm === m.rumor.id;
return h('div', {
class: 'confirm-pop-backdrop',
onClick: (e) => { if (e.target === e.currentTarget) close(); },
@@ -1888,7 +2041,54 @@ export function messagesFeature(ctx) {
try { await navigator.clipboard.writeText(msgSnippet(room, m, 100000)); toast(t('copied')); } catch {}
close();
}),
- !ui.emojiPick && mine ? item('✕', t('msgDelete'), () => { close(); deleteMessage(room, chId, m); }) : null));
+ !ui.emojiPick && mine ? item('✕', t('msgDelete'), () => { close(); deleteMessage(room, chId, m); }) : null,
+ // two taps: the first asks, the second does it
+ !ui.emojiPick && canBan ? item('🚫', t(armed ? 'msgBanConfirm' : 'msgBan', { name: displayName(m.author) }), () => {
+ if (!armed) { ui.msgBanArm = m.rumor.id; render(); return; }
+ close(); setBanned(room, m.author, true);
+ }, ' danger' + (armed ? ' armed' : '')) : null));
+ }
+
+ // Removing someone from a community is the owner's ban list (CORD-04 vsk 4):
+ // one owner-signed edition naming every removed key. Every client that
+ // folds the control plane drops those authors' messages, old and new, and
+ // takes them off the member list. Only where we hold the control stream's
+ // signing key (a community founded here, or the built-in one).
+ const canModerate = (room) => !!room.control.sk && myPubkeys().includes(room.jm.owner);
+ let banBusy = false;
+ async function setBanned(room, pk, banned) {
+ if (banBusy) return false;
+ const id = await identity();
+ if (!id || id.pubkey !== room.jm.owner || !room.control.sk) { toast(t('msgOwnerOnly')); return false; }
+ banBusy = true;
+ try {
+ // The new edition replaces the list whole, so it must be built on the
+ // newest one: ask the relays now rather than trust what has streamed
+ // in. A relay that hands back nothing at all (the founding editions
+ // are always there) is not an answer, and we stop.
+ const wraps = await queryOn(room.relays, { kinds: [1059], authors: [room.control.pk], limit: 500 }, 5000).catch(() => []);
+ if (!wraps.length) { toast(t('msgSendFailed')); return false; }
+ const have = new Set(room.controlEntries.map((e) => e.rumor.id));
+ for (const w of wraps) {
+ const o = openWrap(w, room.control);
+ if (o && o.rumor.kind === 3308 && !have.has(o.rumor.id)) { have.add(o.rumor.id); room.controlEntries.push(o); }
+ }
+ const head = banlistHead(room.controlEntries, { ownerHex: room.jm.owner, cid: room.jm.community_id });
+ const list = head.list.filter((x) => x !== pk);
+ if (banned) list.push(pk);
+ if (list.length === head.list.length) { room.scheduleFold(); return true; } // already so
+ const edition = { ...makeBanlist(head, list, Date.now()), pubkey: id.pubkey };
+ const wrap = await wrapRumor(edition, id.signer, room.control, { plaintext: true });
+ if (!(await publishOn(room.relays, wrap))) { toast(t('msgSendFailed')); return false; }
+ room.controlEntries.push({ rumor: rumorWithId(edition), author: id.pubkey });
+ room.scheduleFold();
+ bumpMsgRev();
+ toast(t(banned ? 'msgBanned' : 'msgUnbanned', { name: displayName(pk) }));
+ return true;
+ } catch (e) {
+ toast(t('msgSendFailed'));
+ return false;
+ } finally { banBusy = false; }
}
// The composer's "replying to" context bar, with its way out.
@@ -2184,6 +2384,13 @@ export function messagesFeature(ctx) {
// An invite link opened in the browser lands here before the wallet exists.
const urlInvite = typeof location !== 'undefined' ? parseInviteLink(location.href) : null;
if (urlInvite) { try { history.replaceState(null, '', '/'); } catch {} }
+ // /?chat: the public chat page's button on a device that has an account.
+ // It opens the coinos community's room itself once the wallet is open
+ // (init below), where "Open coinos" used to leave a signed-in reader on
+ // the wallet to find the chat (Andy, 2026-11-10).
+ let urlChat = typeof location !== 'undefined' && !urlInvite && location.pathname === '/'
+ && /(?:^|&)chat(?:=|&|$)/.test((location.search || '').slice(1));
+ if (urlChat) { try { history.replaceState(null, '', '/'); } catch {} }
// coinos's own pack share link, /emojis/pack/<naddr> — the Android app
// owns every v3.coinos.io path, so one tapped on a phone lands here, not
// in a browser; added once a wallet is open (init below).
@@ -2271,6 +2478,22 @@ export function messagesFeature(ctx) {
}, 0);
}
+ // /naddr1… of a live stream (kind 30311) opens the stream, public like a
+ // note: a visitor watches over the front door. A reload the history
+ // restores by itself needs nothing.
+ const urlLive = (() => {
+ if (typeof location === 'undefined' || urlInvite) return null;
+ const m = location.pathname.match(/^\/(naddr1[a-z0-9]+)\/?$/i);
+ let ref = null; try { ref = m ? parseNostrRef(m[1].toLowerCase()) : null; } catch {}
+ return ref && ref.type === 'addr' && ref.kind === LIVE_KIND ? ref : null;
+ })();
+ if (urlLive && (() => { try { return history.state?.nav?.liveStream?.a !== LIVE_KIND + ':' + urlLive.pk + ':' + urlLive.d; } catch { return true; } })()) {
+ try { history.replaceState(null, '', '/'); } catch {}
+ ui.pubProf = true;
+ ui.pubNotePending = 'live';
+ setTimeout(() => { openLiveRef(urlLive).catch(() => {}).finally(() => { ui.pubNotePending = null; render(); }); }, 0);
+ }
+
// Resolve and open right away — not in init(), which only runs once a
// wallet opens (and would replay on every wallet born in this tab). For a
// visitor with no wallet the profile renders as a truly public page over
@@ -2392,7 +2615,7 @@ export function messagesFeature(ctx) {
// never sends what the user turned off (a suppressed-but-delivered push
// would earn Chrome's generic "updated in background" nag instead)
const want = (k) => s.reasons?.[k] !== false;
- const reasons = { payment: want('payment'), zap: want('zap'), dm: want('dm'), mention: want('mention'), reaction: want('reaction') };
+ const reasons = { payment: want('payment'), zap: want('zap'), dm: want('dm'), mention: want('mention'), reaction: want('reaction'), call: want('call') };
// Stamp the network: the same seed makes the same nostr pubkey on mainnet
// AND staging, so without this the notifier fans a mainnet payment push
// out to the staging PWA's subscription too — and tapping it opened
@@ -2456,6 +2679,7 @@ export function messagesFeature(ctx) {
rowT(t('notifDm'), 'dm'),
rowT(t('notifMention'), 'mention'),
rowT(t('notifReaction'), 'reaction'),
+ rowT(t('notifCall'), 'call'),
h('div', { class: 'small faint' }, t('notifChatHint')));
}
@@ -2463,13 +2687,17 @@ export function messagesFeature(ctx) {
// stranger's: our key (only if we actually hold one), who we follow, and the
// names we already know. See dm-inbox.js for the threat model — a remote
// signer stores no key here and simply gets unfiltered notifications.
- let inboxAt = 0;
+ let inboxAt = 0, inboxTries = 0;
async function syncInbox({ force = false } = {}) {
if (!force && Date.now() - inboxAt < 5 * 60_000) return;
inboxAt = Date.now();
try {
const id = await identity();
- if (!id) return;
+ // the keys not there yet (a wallet still opening): try again shortly —
+ // this used to count as done for five minutes, and a phone woken by a
+ // push in that time had no key to open a DM or a call with
+ if (!id) { if (++inboxTries <= 10) { inboxAt = 0; setTimeout(() => { syncInbox().catch(() => {}); }, 3000); } return; }
+ inboxTries = 0;
const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])],
{ kinds: [3], authors: [id.pubkey] }, 4000);
const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
@@ -2477,6 +2705,9 @@ export function messagesFeature(ctx) {
? [...new Set(newest.tags.filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1]))]
: [];
const known = [...threads.keys()];
+ // who may ring us when the app is shut: those we've written to (the
+ // follows ride separately); `known` stays the DM filter's wider list
+ const rings = known.filter((pk) => wroteTo(pk));
const names = {};
for (const pk of [...follows, ...known]) {
const p = profiles.get(pk);
@@ -2485,7 +2716,7 @@ export function messagesFeature(ctx) {
await saveInbox(wallet._cacheKey(), {
pubkey: id.pubkey,
sk: id.signer instanceof Uint8Array ? bytesToHex(id.signer) : null,
- follows, known, names, hasList: !!newest, updated: Date.now(),
+ follows, known, rings, names, hasList: !!newest, updated: Date.now(),
muted: [...mutesNow().set], // no buzz from a muted sender either
});
} catch { inboxAt = 0; }
@@ -3081,6 +3312,10 @@ export function messagesFeature(ctx) {
} else if (got.rumor.kind === 444 && !isMe(got.author)) {
// a White Noise invitation: the group itself says who is asking
whiteNoise().then((c) => c && c.welcome(got.rumor)).catch(() => {});
+ } else if (got.rumor.kind === CALL_LOG && isMe(got.author)) {
+ // a call, as one of our devices logged it, under the person it was with
+ const with_ = got.rumor.tags?.find((x) => x[0] === 'p')?.[1];
+ if (with_ && /^[0-9a-f]{64}$/.test(with_)) { noteDM(with_, got.rumor, true); persistDms(); }
}
return true;
}
@@ -3233,6 +3468,14 @@ export function messagesFeature(ctx) {
return true;
}
dmSub(DM_RELAYS);
+ // calls ringing in (ephemeral wraps: only what comes while we listen)
+ const callSub = (relays, authed) => {
+ const f = { kinds: [CALL_WRAP], '#p': pks, since: Math.floor(Date.now() / 1000) - 20 };
+ const on = (w) => { onCallWrap(w).catch(() => {}); };
+ const u = authed ? subscribeAuthed(relays, f, on, { onauth: relayAuth, onclose: noteSubClosed }) : subscribeOn(relays, f, on, { onclose: noteSubClosed });
+ allUnsubs.push(u); dmUnsubs.push(u);
+ };
+ callSub(DM_RELAYS, false);
// Senders deliver to the relays our kind-10050 advertises — a list other
// clients may have published with relays beyond our defaults. Read those
// too, or a compliant sender's DM lands somewhere we never look (a reply
@@ -3247,6 +3490,7 @@ export function messagesFeature(ctx) {
// in Adam's list, while a cap of three read the first three)
.slice(0, 8);
ownInbox = extras;
+ if (extras.length && dmStarted) callSub(extras, true);
// inbox relays are often NIP-42 gated: authenticate as the identity
if (extras.length && dmStarted) {
const u = subscribeAuthed(extras, { kinds: [1059], '#p': pks, limit: 400 }, (wrap) => {
@@ -3264,12 +3508,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: '',
@@ -3366,6 +3617,10 @@ export function messagesFeature(ctx) {
if (rumor.kind === 15) {
row.k = 15;
row.tg = (rumor.tags || []).filter((x) => x[0] !== 'p');
+ } else if (rumor.kind === CALL_LOG) {
+ // a call: its who, how and how long are all in its tags
+ row.k = CALL_LOG;
+ row.tg = rumor.tags || [];
} else {
// a message's custom emoji ride along, or they'd be text after a reload
const em = [...emojiTagMap(rumor.tags)];
@@ -3481,8 +3736,43 @@ export function messagesFeature(ctx) {
bumpMsgRev();
scheduleRepaint();
}
- const gClient = (g) => (g && g.cordn ? cd : wn);
- const findGroup = (id) => (wn && wn.groups.get(id)) || (cd && cd.groups.get(id)) || null;
+ // NIP-29 groups (nip29-client.js): a group on one relay that keeps its
+ // members and signs its metadata; messages are plain signed events with
+ // an `h` tag. Not encrypted. Joined by address (host'id, a client's link),
+ // and the list of them is the NIP-51 kind 10009 other clients keep too.
+ let ng = null, ngLoading = null;
+ function nip29Chat() {
+ const pk = identityPk();
+ if (!pk || !wallet._cacheKey) return Promise.resolve(null);
+ if (ng && ng.pubkey === pk) return Promise.resolve(ng);
+ if (ngLoading && ngLoading.pk === pk) return ngLoading.p;
+ if (ng) { try { ng.stop(); } catch {} ng = null; }
+ const p = import('../nip29-client.js').then(async (m) => {
+ if (identityPk() !== pk) return null;
+ const c = m.nip29Client({
+ scope: wallet._cacheKey() + ':' + pk, pubkey: pk, identity, on: onNg,
+ listRelays: async (deep) => deep
+ ? [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS, ...(await relaysOf(pk).catch(() => []))])]
+ : zapRelays(),
+ });
+ ng = c;
+ ngLoading = null;
+ await c.start();
+ return c;
+ }).catch((e) => { console.warn('chat: relay groups unavailable', e); ngLoading = null; return null; });
+ ngLoading = { pk, p };
+ return p;
+ }
+ function onNg(type, g, data) {
+ if (!ng) return;
+ if (type === 'message') { try { noteEmoji(data); } catch {} }
+ if (g) wnFolds.delete(g.id);
+ bumpMsgRev();
+ scheduleRepaint();
+ }
+ const gClient = (g) => (g && g.nip29 ? ng : g && g.cordn ? cd : wn);
+ const gOn = (g) => (g.nip29 ? onNg : g.cordn ? onCd : onWn);
+ const findGroup = (id) => (wn && wn.groups.get(id)) || (cd && cd.groups.get(id)) || (ng && ng.groups.get(id)) || null;
// One delivered event of a direct group, into that person's thread.
function wnIntoThread(g, peer, m) {
@@ -3632,14 +3922,14 @@ export function messagesFeature(ctx) {
const inner = wn.event(7, emoji, [['e', m.rumor.id], ['p', m.rumor.pubkey], ['k', String(m.rumor.kind)], ...reactEmojiTags(emoji)]);
const ok = await wn.send(g, inner).catch(() => false);
if (!ok) { toast(t('msgSendFailed')); return; }
- onWn('message', g, inner);
+ gOn(g)('message', g, inner);
}
// ---- groups ----
const wnRead = (id) => 'wn:' + id;
// groups with a screen of their own (a direct group lives in its DM thread)
- const wnGroups = () => [...(wn ? [...wn.groups.values()].filter((g) => !wn.peer(g)) : []), ...(cd ? cd.groups.values() : [])];
+ const wnGroups = () => [...(wn ? [...wn.groups.values()].filter((g) => !wn.peer(g)) : []), ...(cd ? cd.groups.values() : []), ...(ng ? ng.groups.values() : [])];
function wnTitle(g) {
const c = gClient(g);
@@ -3754,7 +4044,7 @@ export function messagesFeature(ctx) {
const sent = wn.send(g, inner).catch(() => false);
wnFolds.delete(g.id);
render();
- if (!(await sent)) { wnFolds.delete(g.id); toast(t('msgSendFailed')); render(); }
+ if (!(await sent)) { wnFolds.delete(g.id); toast(g.nip29 && g.sendRefused ? t('msgSendFailed') + ': ' + g.sendRefused : t('msgSendFailed')); render(); }
}
async function wnAct(fn) {
@@ -3788,8 +4078,9 @@ export function messagesFeature(ctx) {
const punk = localPunk(p.picture, big);
if (punk) return `url(${JSON.stringify(punk)})`;
const local = p.thumb && p.thumbFor === p.picture ? p.thumb : null;
- if (!local) return `url(${JSON.stringify(p.picture)})`;
- return (big ? `url(${JSON.stringify(p.picture)}),` : '') + `url(${JSON.stringify(local)})`;
+ const pic = blobAltOf(p.picture) || p.picture; // the same blob elsewhere, when the host lost it
+ if (!local) return `url(${JSON.stringify(pic)})`;
+ return (big ? `url(${JSON.stringify(pic)}),` : '') + `url(${JSON.stringify(local)})`;
}
const FACE_WAIT_MS = 1000;
@@ -3866,6 +4157,15 @@ export function messagesFeature(ctx) {
node.onclick = (e) => { e.stopPropagation(); openProfile(pk); };
(node._evs || (node._evs = new Set())).add('onpointerdown').add('onclick');
}
+ // streaming now: a red ring, and the face opens the stream (the name
+ // beside it still opens the profile, which says they're on too)
+ let on = null;
+ try { on = liveHostNow(pk); } catch {} // (an avatar drawn while the feature is still being built)
+ if (on) {
+ node.classList.add('live-ring');
+ // (on that stream's own page, the face is a way out: to their profile)
+ if (clickable) node.onclick = (e) => { e.stopPropagation(); if (ui.liveStream && ui.liveStream.a === liveAddr(on)) openProfile(pk); else openLive(on); };
+ }
return hook('wrapAvatar', pk, node) || hatStamp(pk, node) || node;
};
@@ -3986,12 +4286,29 @@ export function messagesFeature(ctx) {
};
function warmBanner(pk) {
const b = bannerOf(pk);
- if (b && !mediaReady.has(b)) return warmMedia(b, { thumb: true }).then(() => scheduleRepaint());
+ if (!b) return;
+ const shown = blobAltOf(b) || b;
+ if (mediaReady.has(shown)) return;
+ return warmMedia(shown, { thumb: true }).then(async () => {
+ // the host lost it: the same blob on another server paints instead
+ if (!mediaReady.has(shown) && shown === b && BLOB_RE.test(b)) {
+ const alt = await findBlobAlt(b, pk);
+ if (alt) await warmMedia(alt, { thumb: true });
+ }
+ scheduleRepaint();
+ });
}
- function prefetchProfilePage(pk) {
- if (!pk || prefetched.has(pk)) return;
+ // first: ahead of everything queued (the top search results — the queue
+ // can hold a dozen people from the letters typed before them)
+ function prefetchProfilePage(pk, { first = false } = {}) {
+ if (!pk) return;
+ if (prefetched.has(pk)) {
+ const i = prefetchQueue.indexOf(pk);
+ if (first && i > 0) { prefetchQueue.splice(i, 1); prefetchQueue.unshift(pk); }
+ return;
+ }
prefetched.add(pk);
- prefetchQueue.push(pk);
+ if (first) prefetchQueue.unshift(pk); else prefetchQueue.push(pk);
drainPrefetch();
}
function drainPrefetch() {
@@ -4012,7 +4329,7 @@ export function messagesFeature(ctx) {
// The same for a post opened into its thread: Back lands on the row the
// reader tapped, not the top of the feed.
const pageReturn = []; // [{ key, y }] per profile/thread opened, newest last
- const pageKey = () => ui.noteThread && !(ui.profilePk && ui.profOverThread) ? 'thread'
+ const pageKey = () => ui.liveStream ? 'live' : ui.noteThread && !(ui.profilePk && ui.profOverThread) ? 'thread'
: ui.profilePk ? 'p:' + ui.profilePk : '';
function rememberPlace(key) {
if (pageKey() === key) return;
@@ -4043,6 +4360,8 @@ export function messagesFeature(ctx) {
}
function openProfile(pk) {
rememberPlace('p:' + pk);
+ viewedProfiles.set(pk, Date.now());
+ ui.liveStream = null;
ui.profilePk = pk;
// Opened from inside a thread (an author's avatar/name), the profile
// stacks ON TOP of it — back returns to the conversation. The screen
@@ -4059,7 +4378,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
@@ -4157,6 +4477,8 @@ export function messagesFeature(ctx) {
if (persist) persistThread(c);
}
const tagOf = (ev, k) => (ev.tags.find((x) => x[0] === k) || [])[1];
+ const APP_KIND = 32267; // a Zapstore app listing (NIP-82): zaps on one are zaps on your app
+ const APP_RELAYS = ['wss://relay.zapstore.dev'];
function receiptSats(ev) {
if (ev.kind === 9737) {
const net = tagOf(ev, 'network');
@@ -4177,6 +4499,16 @@ export function messagesFeature(ctx) {
if (ev.kind === 9737) return String(ev.content || '').slice(0, 200);
try { return String((JSON.parse(tagOf(ev, 'description') || 'null') || {}).content || '').slice(0, 200); } catch { return ''; }
}
+ // The address (kind:pubkey:d) a zap was for, when it wasn't a note: a
+ // stream (30311) or a Zapstore app listing (32267). LNURL servers often
+ // leave the a tag off the receipt (Zapstore's did, 2026-11-07), so the zap
+ // request inside it is asked too.
+ function zapAddrOf(ev) {
+ const a = (e) => ((e && e.tags) || []).find((x) => x[0] === 'a' && x[1]);
+ const own = a(ev);
+ if (own) return own[1];
+ try { const r = a(JSON.parse(tagOf(ev, 'description') || 'null')); return r ? r[1] : null; } catch { return null; }
+ }
function zapperOf(ev) {
if (ev.kind === 9737) {
// Signed by the wallet key; the sender tag names the person behind it.
@@ -4444,7 +4776,83 @@ export function messagesFeature(ctx) {
// Where an event about a note goes. A zap receipt is money and has its own
// bookkeeping (see below); a like and a boost are just tallies of who.
+ const timedActivity = new Map();
+ function rememberMoment(ev) {
+ const moment = readMoment(ev);
+ if (!moment || ![1, 1111, 7, 9735, 9737].includes(ev.kind)) return;
+ const target = ev.tags.filter(x => x[0] === 'e' && x[3] !== 'mention').at(-1)?.[1];
+ if (!target) return;
+ if (!timedActivity.has(target)) timedActivity.set(target, new Map());
+ const items = timedActivity.get(target);
+ if (items.has(ev.id)) return;
+ items.set(ev.id, { id: ev.id, ev, moment,
+ icon: ev.kind === 7 ? ev.content || '♡' : [9735, 9737].includes(ev.kind) ? '⚡' : '↩',
+ text: [9735, 9737].includes(ev.kind) ? zapText(ev) : ev.content });
+ if (items.size > 300) items.delete(items.keys().next().value);
+ if (timedActivity.size > 200) timedActivity.delete(timedActivity.keys().next().value);
+ queueMicrotask(() => document.querySelectorAll('audio, video').forEach(v => { if (v._momentUrl) v.dispatchEvent(new Event('mediaactivity')); }));
+ }
+ // a post's timed activity on one of its clips, in order, each with who and what
+ 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(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 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]);
+ return tag ? reactImg(code, tag[2]) : reactNode(x.ev.content === '+' || !x.ev.content ? '❤️' : x.ev.content);
+ }
+ // Where a post's clip is up to, if it has been played: a reply, reaction or
+ // zap made then is about that moment. (No buttons of their own for it: the
+ // usual ones carry the time.)
+ function momentOf(ev) {
+ if (!ev) return null;
+ const cur = pager && pager.cur;
+ const players = cur && cur._ev && cur._ev.id === ev.id
+ ? [cur.querySelector('.mp-media')]
+ : [...document.querySelectorAll('[data-zap-post="' + CSS.escape(ev.id) + '"] :is(video, audio)')];
+ for (const v of players) {
+ if (v && v._momentUrl && v.currentTime > 0 && Number.isFinite(v.duration)) return mediaMoment(v._momentUrl, v.currentTime);
+ }
+ 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);
+ // the moment is only offered: a reaction is about it once the toggle says so
+ const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, momentOffer: m } : ev; };
+ const tieLabel = (m) => t('mediaTieTo', { time: mediaClock(m.seconds) });
+ function attachMediaTimeline(player, url, explicitEvent) {
+ if (player._timeline) return;
+ player._timeline = true;
+ player._momentUrl = url;
+ const event = () => {
+ const ev = explicitEvent || noteInHand(player.closest('[data-zap-post]')?.getAttribute('data-zap-post'));
+ return ev && (String(ev.content || '').includes(url) || ev.tags.some(tag => tag.includes('url ' + url) || tag[1] === url)) ? ev : null;
+ };
+ const box = player.parentElement;
+ box._skipMorph = true;
+ 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) {
+ rememberMoment(ev);
if (ev.kind === 1 || ev.kind === 1111) { noteReply(ev); return; }
if (EDIT_KINDS.includes(ev.kind)) { notePostEdit(ev); return; }
if (ev.kind === 7 || ev.kind === 6) {
@@ -4482,6 +4890,7 @@ export function messagesFeature(ctx) {
// root and reply (or the bare positional e tags of older clients), NIP-22's
// E and e. A 'mention' e tag is a quote, not a reply.
function noteReply(ev) {
+ rememberMoment(ev);
let changed = false;
for (const x of ev.tags || []) {
if (!x[1] || x[1] === ev.id) continue;
@@ -4502,6 +4911,7 @@ export function messagesFeature(ctx) {
}
function noteReceipt(ev) {
+ rememberMoment(ev);
const sats = receiptSats(ev);
if (!sats) return;
const my = myPubkeys();
@@ -4770,25 +5180,38 @@ export function messagesFeature(ctx) {
const notesCache = new Map(); // pk -> { status: 'loading'|'ready', notes: [kind-1 events] }
// NIP-65: where this author actually writes. Their notes and threads live
// there first — our default relays are just the common ground.
+ // Asked one at a time — a quoted note's author, a face tapped, a reply's
+ // target — these went out as one REQ per author per relay: a feed with
+ // six quotes on screen sent eighteen. Asks now wait a beat and go out
+ // together, one REQ with every author wanted, through the feed's own
+ // batched fetch, which also remembers who has no list so nobody is asked
+ // twice.
const relayListCache = new Map(); // pk -> Promise<string[]>
+ const RELAY_ASK_MS = 80;
+ let relayAskQ = new Map(), relayAskTimer = null; // pk -> [resolve]
function relaysOf(pk) {
let p = relayListCache.get(pk);
if (p) return p;
// the feed's batched fetch has probably already asked for this one
const known = relayListsNow().get(pk);
if (known) { p = Promise.resolve(known.r || []); relayListCache.set(pk, p); return p; }
- p = queryOn([...new Set([...PROFILE_RELAYS, ...NOTE_RELAYS])], { kinds: [10002], authors: [pk] }, 3500)
- .then((evs) => {
- const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
- if (!newest) return [];
- return [...new Set(newest.tags
- .filter((x) => x[0] === 'r' && x[1] && x[2] !== 'read' && /^wss:\/\//.test(x[1]))
- .map((x) => x[1].replace(/\/$/, '')))].slice(0, 4);
- })
- .catch(() => []);
+ p = new Promise((resolve) => {
+ if (!relayAskQ.has(pk)) relayAskQ.set(pk, []);
+ relayAskQ.get(pk).push(resolve);
+ if (!relayAskTimer) relayAskTimer = setTimeout(flushRelayAsks, RELAY_ASK_MS);
+ });
relayListCache.set(pk, p);
return p;
}
+ async function flushRelayAsks() {
+ relayAskTimer = null;
+ const batch = relayAskQ; relayAskQ = new Map();
+ try { await fetchRelayLists([...batch.keys()], [...new Set([...PROFILE_RELAYS, ...NOTE_RELAYS])]); } catch {}
+ for (const [pk, waiters] of batch) {
+ const r = ((relayListsNow().get(pk) || {}).r || []).slice(0, 4);
+ for (const w of waiters) w(r);
+ }
+ }
// Plus relays that keep history: the big ones prune within days, and an
// author without a NIP-65 list (Joe Nakamoto, 2026-10-01) otherwise shows
// only whatever primal still holds — 2 posts of 22.
@@ -4823,8 +5246,16 @@ export function messagesFeature(ctx) {
// Threads"): the replies these people write, each under the post it
// answers, instead of their posts. Asked for as notes and NIP-22 comments;
// reposts have no place in it. (REPLY_KINDS, above: a note or a comment.)
- const feedKinds = (def) => (def && def.replies ? REPLY_KINDS : FEED_KINDS);
- const feedKeeps = (def, e) => (def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e));
+ // A word search (def.search) asks NIP-50 relays for notes and replies
+ // whose text holds it: kind 1 only, replies kept as rows of their own.
+ const feedKinds = (def) => (def && def.search ? [1] : def && def.replies ? REPLY_KINDS : FEED_KINDS);
+ // A search within someone's posts reads their own relays too (few people
+ // are in any search index), so it checks the words itself: every word,
+ // anywhere in the text, case and accents aside.
+ const foldText = (x) => String(x || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
+ const searchWords = (q) => foldText(q).split(/\s+/).map((w) => w.replace(/^#/, '')).filter(Boolean);
+ const saysWords = (q, e) => { const text = foldText(e.content); return searchWords(q).every((w) => text.includes(w)); };
+ const feedKeeps = (def, e) => (def && def.search ? e.kind === 1 && (!(def.authors || []).length || saysWords(def.search, e)) : def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e));
// What a reply answers: the e tag marked 'reply' (NIP-10), else 'root'
// (a reply straight to the root), else — the deprecated positional form —
// the last e tag; a NIP-22 comment's lowercase e (its parent), else its E.
@@ -4836,12 +5267,31 @@ export function messagesFeature(ctx) {
else tag = es.find((x) => x[3] === 'reply') || es.find((x) => x[3] === 'root') || es[es.length - 1];
if (!tag) return null;
const ref = { type: 'event', id: tag[1], relays: tag[2] ? [tag[2]] : [] };
- if (/^[0-9a-f]{64}$/i.test(tag[4] || '')) ref.author = tag[4].toLowerCase();
+ // the parent's author: NIP-22 carries it at [3], NIP-10 at [4] (read at
+ // [4] only, every comment's parent lost its author, and its outbox went
+ // unasked: fiatjaf's comment on Kieran's, 2026-10-20). Without one, the
+ // people the reply is addressed to: their outboxes are where it was written.
+ const hex = (x) => (/^[0-9a-f]{64}$/i.test(x || '') ? x.toLowerCase() : null);
+ ref.author = hex(ev.kind === 1111 ? tag[3] : tag[4]) || hex(tag[3]);
+ if (!ref.author) ref.authors = [...new Set((ev.tags || []).filter((x) => x[0] === 'p').map((x) => hex(x[1])).filter((p) => p && p !== ev.pubkey))].slice(0, 3);
return ref;
}
+ // The web page a NIP-22 comment is on (its I tag, an http(s) URL), with
+ // the label its alt tag gives it — DaddyTube: "Comment on Sheep
+ // Detectives (2025) in DaddyTube" — or else the address, host and path.
+ function webScopeOf(ev) {
+ const url = ((ev.tags || []).find((x) => x[0] === 'I' && /^https?:\/\/\S+$/i.test(x[1] || '')) || [])[1];
+ if (!url) return null;
+ let where = url;
+ try { const u = new URL(url); where = (u.host + u.pathname).replace(/^www\./, '').replace(/\/$/, ''); } catch {}
+ const alt = ((ev.tags || []).find((x) => x[0] === 'alt' && String(x[1] || '').trim()) || [])[1];
+ return { url, label: alt ? String(alt).trim().slice(0, 140) : t('noteCommentOn', { where }) };
+ }
// A note already in hand — in a feed, a thread, someone's page — before
// asking any relay for it: the post a reply answers is usually right
// there in the Following feed.
+ // a reply whose parent every lookup came back without
+ const orphaned = (ev) => { const p = parentRefOf(ev); const q = p && quoted.get(p.id); return !!q && q.status === 'missing' && !q.ev; };
function noteInHand(id) {
for (const c of feedStates.values()) for (const e of c.notes) {
if (e.id === id) return e;
@@ -4852,6 +5302,24 @@ export function messagesFeature(ctx) {
for (const e of c.replies || []) if (e.id === id) return e;
}
for (const c of notesCache.values()) for (const e of c.notes || []) if (e.id === id) return e;
+ return noteOnDisk(id);
+ }
+ // ...or on disk with the feed it was read in: a Conversations view opened
+ // straight after a reload has the posts its replies answer in Following's
+ // cache, not in any feed state yet (and without them, those replies were
+ // taken for replies to nothing and left out)
+ const diskHeld = new Map(); // feed id -> Map(note id -> note), read once a session
+ function noteOnDisk(id) {
+ for (const f of new Set([FOLLOWING, curFeedId])) {
+ let m = diskHeld.get(f);
+ if (!m) {
+ let notes = null;
+ try { notes = feedDisk()?.peekNotes(f) || wallet.loadFeatureState(feedCacheKey(f), []); } catch {}
+ m = new Map((Array.isArray(notes) ? notes : []).filter((e) => e && e.id).map((e) => [e.id, e]));
+ diskHeld.set(f, m);
+ }
+ if (m.has(id)) return m.get(id);
+ }
return null;
}
function notesFor(pk) {
@@ -4873,22 +5341,64 @@ export function messagesFeature(ctx) {
fetchNotes(pk, c);
return c;
}
+ // Posts arrive as the relays send them: whatever the quick ones hold
+ // paints while a slow one (or the author's own relays, still being looked
+ // up) is still answering. It used to wait for the slowest relay (4.5 s),
+ // after looking up the author's relay list, then for every post's media
+ // (up to 8 s), and the whole page landed at once — several seconds of
+ // blank on a first visit (Ben Arc from search, Adam 2026-11-13).
+ // Batches merge into what's on the page, never swap it: the relays answer
+ // unevenly (primal held 2 of Joe Nakamoto's posts, ours 18, the archives 30).
+ const NOTES_FIRST_READY_MS = 1200; // a first screen's media: worth a beat, not a wait
function fetchNotes(pk, c) {
c.fetching = true;
+ const filter = { kinds: PROFILE_KINDS, authors: [pk], limit: 30 };
+ const incoming = new Map();
+ let chain = Promise.resolve(), timer = 0, any = false;
+ const flush = () => {
+ timer = 0;
+ if (!incoming.size) return chain;
+ const batch = [...incoming.values()]; incoming.clear();
+ chain = chain.then(async () => {
+ const byId = new Map(c.notes.map((e) => [e.id, e]));
+ // older than the page already settled: kept back until paging gets there
+ const fresh = batch.filter((e) => !byId.has(e.id) && !holdBack(c, e));
+ if (!fresh.length) return;
+ for (const e of fresh) byId.set(e.id, e);
+ const merged = newestArticles([...byId.values()]).sort((a, b) => b.created_at - a.created_at);
+ // the rows about to be on screen, ready (media sized, quotes in hand)
+ // — briefly: a slow picture host must not hold the page
+ const top = new Set(merged.slice(0, FEED_PAGE).map((e) => e.id));
+ await notesReady(fresh.filter((e) => top.has(e.id)), undefined, NOTES_FIRST_READY_MS);
+ c.notes = merged;
+ c.end = false;
+ any = true;
+ if (ui.profilePk === pk) render();
+ }).catch(() => {});
+ return chain;
+ };
+ const take = (e) => {
+ if (!e || e.pubkey !== pk) return;
+ incoming.set(e.id, e);
+ // the first post paints at once; after that, a batch every 300 ms
+ if (!timer) timer = setTimeout(flush, any || c.notes.length ? 300 : 0);
+ };
+ const asked = new Set([...NOTE_RELAYS, ...PROFILE_ARCHIVE_RELAYS]);
(async () => {
- const evs = await queryOn(await notesRelays(pk), { kinds: PROFILE_KINDS, authors: [pk], limit: 30 }, 4500);
- // Merged with what's already on the page, never swapped for it: the
- // relays answer unevenly (primal held 2 of Joe Nakamoto's posts, ours
- // 18, the archives 30), and a thin answer used to erase a full page.
- const byId = new Map(c.notes.map((e) => [e.id, e]));
- let added = 0;
- for (const e of evs || []) if (!byId.has(e.id)) { byId.set(e.id, e); added++; }
- if (!added && c.notes.length) return;
- const merged = newestArticles([...byId.values()]).sort((a, b) => b.created_at - a.created_at);
- await notesReady(merged.slice(0, FEED_PAGE)); // the first screen arrives whole
- c.notes = merged;
- c.end = false;
- persistPage('notes', pk, merged.slice(0, 20).map(slimNote)); // cache stays bounded
+ const depths = await Promise.all([
+ queryDepthOn([...asked], filter, take, 4500),
+ // the author's own relays, as soon as their list is known
+ relaysOf(pk).then((own) => {
+ const more = (own || []).filter((r) => !asked.has(r));
+ return more.length ? queryDepthOn(more, filter, take, 4500) : [];
+ }).catch(() => []),
+ primalNotes(pk, filter.limit, 0, take),
+ ]);
+ clearTimeout(timer);
+ await flush();
+ await chain;
+ settlePage(c, depths.flat(), filter.limit);
+ if (any) persistPage('notes', pk, c.notes.slice(0, 20).map(slimNote)); // cache stays bounded
})().catch(() => {}).finally(() => {
c.status = 'ready';
c.fetching = false;
@@ -4914,24 +5424,22 @@ export function messagesFeature(ctx) {
lastScrollAt = Date.now();
if (!ui.profilePk && (!(ui.chatOpen && ui.msgView === 'feed') || ui.noteThread)) return;
windowScrolled(ui.profilePk ? notesCache.get(ui.profilePk) : feed);
- // back at the top by yourself: the new posts are under your eyes, so
- // the notice has done its job (only the pill repaints — the rows are
- // keyed and stay put, so nothing moves under a finger)
+ scrollWhen(ui.profilePk ? notesCache.get(ui.profilePk) : feed);
+ // Starting to scroll up dismisses the notice: the reader is already
+ // heading toward the new posts. Keyed rows keep their positions.
// Upward only: holding the page still as posts go in above scrolls it
// DOWN, and that must not count as having gone up to look at them.
const y = window.scrollY || 0, up = y < lastFeedY;
lastFeedY = y;
if (!ui.profilePk && Date.now() - lastInputAt < 2500) noteScrollTrail(y); // the reader's own travel (not a held-still insert)
- // Scrolling recounts the pill: posts you've gone up past drop off it,
- // and once none are left above you the notice is done.
+ // Keep tracking which posts are ahead, even after hiding the pill.
if (!ui.profilePk && feed && feed.ahead?.size && up && !pillFrame) pillFrame = requestAnimationFrame(() => {
pillFrame = 0;
if (!feed) return;
markReached(feed);
if (!feed.unseen) return;
- const n = pillCount(feed);
- if (!n) { feed.unseen = 0; render(); }
- else if (n !== feed.pillN) render();
+ feed.unseen = 0;
+ render();
});
if (!ui.profilePk && feed?.deferred?.length) admitFeed(feed.deferred, feed);
if (window.innerHeight + window.scrollY < (document.documentElement.scrollHeight || 0) - (ui.profilePk ? 600 : feedLead())) return;
@@ -4939,22 +5447,144 @@ export function messagesFeature(ctx) {
else loadOlderFeed().catch(() => {});
}, { passive: true });
}
+ // How far back you've scrolled: while the feed (or a profile's posts)
+ // moves, a small chip under the top bar says when the post at the top of
+ // the screen was written, and goes the moment the scrolling stops
+ // ("some sort of little counter that shows the date and time of posts
+ // where I'm in the timeline", Adam, 2026-11-17). Painted straight into the
+ // DOM, outside render(): it changes every frame of a fling.
+ let whenEl = null, whenRaf = 0, whenHide = 0, whenIdx = { list: null, map: null };
+ function whenLabel(sec) {
+ const d = new Date(sec * 1000), now = new Date();
+ const time = d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
+ const date = d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', ...(d.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}) });
+ const ago = Math.max(0, (now - d) / 1000);
+ let rel = '';
+ try {
+ const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
+ rel = ago < 3600 ? rtf.format(-Math.max(1, Math.round(ago / 60)), 'minute')
+ : ago < 86400 ? rtf.format(-Math.round(ago / 3600), 'hour')
+ : ago < 86400 * 60 ? rtf.format(-Math.round(ago / 86400), 'day')
+ : ago < 86400 * 730 ? rtf.format(-Math.round(ago / (86400 * 30.4)), 'month')
+ : rtf.format(-Math.round(ago / (86400 * 365)), 'year');
+ } catch {}
+ const today = d.toDateString() === now.toDateString();
+ return (today ? time : date + ' · ' + time) + (rel ? ' · ' + rel : '');
+ }
+ function scrollWhen(c) {
+ if (whenRaf || typeof document === 'undefined') return;
+ whenRaf = requestAnimationFrame(() => {
+ whenRaf = 0;
+ const list = c?.winList ? c.winList() : null;
+ const rows = list ? document.querySelectorAll('.notes-feed > .row[data-key]') : [];
+ const head = document.querySelector('.brand-header');
+ const top = head ? Math.max(0, head.getBoundingClientRect().bottom) : 0;
+ // the post at the top of the screen, below the bar
+ let key = null, box = null, frac = 0, nextKey = null;
+ for (let i = 0; i < rows.length; i++) {
+ const b = rows[i].getBoundingClientRect();
+ if (b.bottom <= top + 12) continue;
+ key = rows[i].getAttribute('data-key');
+ box = rows[i].parentElement.getBoundingClientRect();
+ // how far through this post the top of the screen is, to blend its
+ // time toward the next post's: the clock rolls with the scroll
+ // instead of jumping post to post ("I'm good with blending", Adam)
+ frac = b.height > 0 ? Math.min(1, Math.max(0, (top + 12 - b.top) / b.height)) : 0;
+ nextKey = rows[i + 1]?.getAttribute('data-key');
+ break;
+ }
+ if (whenIdx.list !== list) whenIdx = { list, map: list ? new Map(list.map((e) => [e.id, e])) : null };
+ const ev = key && whenIdx.map?.get(key);
+ const next = nextKey && whenIdx.map?.get(nextKey);
+ // only once you're past the first screenful: at the top the posts' own times say it
+ if (!ev || (window.scrollY || 0) < window.innerHeight * 0.75) { if (whenEl) whenEl.classList.remove('on'); return; }
+ if (!whenEl) {
+ whenEl = document.createElement('div');
+ whenEl.className = 'feed-when';
+ whenEl.setAttribute('aria-hidden', 'true');
+ document.body.appendChild(whenEl);
+ }
+ const label = whenLabel(next ? ev.created_at + (next.created_at - ev.created_at) * frac : ev.created_at);
+ if (whenEl.textContent !== label) whenEl.textContent = label;
+ whenEl.style.top = (top + 8) + 'px';
+ whenEl.style.left = (box.left + box.width / 2) + 'px';
+ whenEl.classList.add('on');
+ clearTimeout(whenHide);
+ // gone as soon as you stop to read ("I want it gone as soon as I'm
+ // stopped to look at something", Adam): a coast keeps sending scroll
+ // events, so this only fires once the page is still
+ whenHide = setTimeout(() => whenEl && whenEl.classList.remove('on'), 250);
+ });
+ }
+ // How far back a page of someone's posts can be trusted. Relays each hold
+ // their own part of an author's history, so the oldest post of a merged
+ // answer says little: ours held 6 of Ben Arc's posts reaching back to
+ // April while his own relay's newest 30 ended in late September, and
+ // "older than the oldest" then asked for posts before April — five months
+ // never shown, his Napstr launch among them (Adam, 2026-11-20). A source
+ // that sent a full page has more below its oldest post; the page is
+ // complete down to the NEWEST such floor. Posts below it wait in c.held
+ // and join the page that reaches them. No source full: nothing is left.
+ const fullPage = (n, limit) => n >= Math.ceil(limit / 2);
+ const holdBack = (c, e) => {
+ if (!c.floor || e.created_at >= c.floor) return false;
+ (c.held ||= new Map()).set(e.id, e);
+ return true;
+ };
+ function settlePage(c, depths, limit) {
+ const floors = depths.filter((d) => d && fullPage(d.n, limit) && Number.isFinite(d.min)).map((d) => d.min);
+ const floor = floors.length ? Math.max(...floors) : 0;
+ // a refresh of a page already scrolled deeper never raises the floor
+ c.floor = c.floor && floor ? Math.min(c.floor, floor) : (c.floor && !floor ? c.floor : floor);
+ const all = new Map([...(c.held || new Map()), ...c.notes.map((e) => [e.id, e])]);
+ c.held = new Map();
+ const shown = [];
+ for (const e of all.values()) (c.floor && e.created_at < c.floor ? c.held.set(e.id, e) : shown.push(e));
+ c.notes = newestArticles(shown).sort((a, b) => b.created_at - a.created_at);
+ if (!floors.length && !c.floor) c.end = true;
+ else if (floors.length) c.end = false;
+ return floors.length > 0;
+ }
+ // Primal's cache keeps what relays have pruned (of the nine posts around
+ // the Napstr launch, the relays we ask held none). It answers posts and
+ // replies as separate feeds; each is a source with its own depth. The
+ // events are the signed originals, checked like a relay's.
+ async function primalNotes(pk, limit, until, take) {
+ const ask = async (notes) => {
+ const args = { pubkey: pk, notes, limit };
+ if (until) args.until = until;
+ const evs = await primalCache('feed', args, 5000).catch(() => []);
+ const good = await verifiedPrimal((evs || []).filter((e) => e.pubkey === pk), PROFILE_KINDS);
+ for (const e of good) take(e);
+ return { url: 'primal:' + notes, n: good.length, min: good.length ? Math.min(...good.map((e) => e.created_at)) : Infinity };
+ };
+ return Promise.all([ask('authored'), ask('replies')]);
+ }
async function loadOlderNotes(pk) {
const c = notesCache.get(pk);
if (!c || c.status !== 'ready' || c.loadingMore || c.end) return;
const oldest = c.notes[c.notes.length - 1];
- if (!oldest) { c.end = true; return; }
+ if (!oldest && !c.floor) { c.end = true; return; }
c.loadingMore = true;
render();
try {
- const evs = await queryOn(await notesRelays(pk),
- { kinds: PROFILE_KINDS, authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500);
+ const limit = 30;
+ const until = (c.floor || oldest.created_at) - 1;
+ const got = new Map();
+ const take = (e) => { if (e && e.pubkey === pk && e.created_at <= until) got.set(e.id, e); };
+ const depths = await Promise.all([
+ queryDepthOn(await notesRelays(pk), { kinds: PROFILE_KINDS, authors: [pk], limit, until }, take, 4500),
+ primalNotes(pk, limit, until, take),
+ ]);
+ const before = c.notes.length;
const seen = new Set(c.notes.map((e) => e.id));
- const older = (evs || [])
- .filter((e) => !seen.has(e.id) && seen.add(e.id))
- .sort((a, b) => b.created_at - a.created_at);
- if (older.length) { await notesReady(older); c.notes = newestArticles([...c.notes, ...older]); }
- else c.end = true; // the relays have nothing older
+ for (const e of got.values()) if (!seen.has(e.id)) (c.held ||= new Map()).set(e.id, e);
+ // this page reaches down to the new floor (or to the bottom: no source had more)
+ c.floor = 0;
+ const more = settlePage(c, depths.flat(), limit);
+ if (!more) { c.floor = 0; c.end = true; }
+ const added = c.notes.slice(before);
+ if (added.length) await notesReady(added.slice(0, FEED_PAGE));
} catch {} finally {
c.loadingMore = false;
if (ui.profilePk === pk) render();
@@ -5009,7 +5639,8 @@ export function messagesFeature(ctx) {
]);
const all = [...(relayEvs || []), ...primalEvs].filter((e) => e.pubkey === pk);
const list = all.filter((e) => e.kind === 3).sort((a, b) => b.created_at - a.created_at)[0] || null;
- return { list, existing: all.length > 0 };
+ const profile = all.filter((e) => e.kind === 0).sort((a, b) => b.created_at - a.created_at)[0] || null;
+ return { list, profile, existing: all.length > 0 };
}
// Fetch the newest list from the relays. Older than what we hold is
@@ -5208,12 +5839,12 @@ export function messagesFeature(ctx) {
// small, widely mirrored, and worth having before anything else is asked.
// Authors with no list at all are remembered as such, so we don't ask again
// every time the feed refreshes.
- async function fetchRelayLists(pks) {
+ async function fetchRelayLists(pks, relays = NOTE_RELAYS) {
const want = [...new Set(pks)].filter((pk) => !relayListsNow().has(pk));
if (!want.length) return;
for (let i = 0; i < want.length; i += 100) {
const batch = want.slice(i, i + 100);
- const evs = await queryOn(NOTE_RELAYS, { kinds: [10002], authors: batch }, 4500).catch(() => []);
+ const evs = await queryOn(relays, { kinds: [10002], authors: batch }, 4500).catch(() => []);
const newest = new Map();
for (const ev of evs || []) {
const cur = newest.get(ev.pubkey);
@@ -5513,13 +6144,16 @@ export function messagesFeature(ctx) {
// posts from anyone on these tags, as well as the feed's people (Everything)
const orTopicsOf = (def) => [...new Set(((def && def.orTopics) || []).map(normTopic).filter(Boolean))];
const feedTopics = (def = feedDef()) => [...new Set(((def && def.topics) || []).map(normTopic).filter(Boolean))].slice(0, 20);
- const feedHasQuery = (def = feedDef()) => !!def && (!!def.all || feedAuthors(def).length > 0 || feedTopics(def).length > 0);
+ const feedHasQuery = (def = feedDef()) => !!def && (!!def.all || !!def.search || feedAuthors(def).length > 0 || feedTopics(def).length > 0);
// A feed's own relay list, when it has one, replaces the usual choice
// (the authors' outboxes, or the wide relays for a topic) everywhere the
// feed reads. Independent of what the feed asks for.
// Popular relays that answer a bare "everything" query (probed 2026-09-27;
// paid/search relays like nostr.wine and nostr.band answer nothing and are
// left out). The firehose reads a few of them by default.
+ // NIP-50 full-text search over notes (probed 2026-11-11: these three
+ // answer `search` on kind 1; nostr.band and primal answered nothing).
+ const TEXT_SEARCH_RELAYS = ['wss://relay.ditto.pub', 'wss://search.nos.today', 'wss://nostr.wine'];
const RELAY_PICKS = ['wss://relay.coinos.io', 'wss://relay.ditto.pub', 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net', 'wss://relay.snort.social',
'wss://nostr.mom', 'wss://nostr.bitcoiner.social', 'wss://eden.nostr.land', 'wss://nostr.land', 'wss://nostr.oxtr.dev',
'wss://relay.nostrplebs.com', 'wss://offchain.pub', 'wss://nostr21.com', 'wss://relay.nostr.net', 'wss://nostr-pub.wellorder.net'];
@@ -5765,7 +6399,7 @@ export function messagesFeature(ctx) {
const own = p.pk === mePk() ? st().feeds.find((f) => f.d === p.d) : null;
const id = own ? own.id : 'list:' + packKey(p);
if (!own) adhocFeeds.set(id, { id, name: p.title || p.d, packs: [{ pk: p.pk, d: p.d, kind: p.kind === PACK_KIND ? undefined : p.kind, relays: [], title: p.title || '' }] });
- ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.feedEdit = null; ui.profOverThread = false;
+ ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null; ui.profOverThread = false;
ui.chatOpen = true; ui.msgView = 'feed';
switchFeed(id);
}
@@ -5812,7 +6446,7 @@ export function messagesFeature(ctx) {
onClick: () => {
ui.listPick = null;
// the editor lives on the feed screen; the profile gives way to it
- ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.userSearch = null;
+ ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = null;
ui.chatOpen = true; ui.msgView = 'feed';
openFeedEditor(null);
ui.feedEdit.authors = [pk];
@@ -6039,9 +6673,15 @@ export function messagesFeature(ctx) {
async function prefetchFeed(c) {
const def = feedDef(c.id);
const authors = feedAuthors(def), topics = feedTopics(def);
- if (!authors.length && !topics.length && !(def && def.all)) { c.status = 'ready'; return; }
+ if (!authors.length && !topics.length && !(def && (def.all || def.search))) { c.status = 'ready'; return; }
c.at = Date.now();
const merge = { newerThan: c.notes.length ? c.notes[0].created_at : Infinity };
+ if (def.search) {
+ try { await searchPass(def, c, merge); } catch {} finally {
+ if (!c.stopped) { c.status = 'ready'; if (c === feed && ui.chatOpen && ui.msgView === 'feed') scheduleRepaint(); }
+ }
+ return;
+ }
if (def && def.curated) {
try { await popularPass({}, merge, c, def); } catch {} finally {
if (!c.stopped) { c.status = 'ready'; if (c === feed && ui.chatOpen && ui.msgView === 'feed') { scheduleRepaint(); watchFeed(); } }
@@ -6050,13 +6690,17 @@ export function messagesFeature(ctx) {
}
try {
const orT = orTopicsOf(def);
+ // the feed's own kinds: a Conversations view asks for replies and
+ // NIP-22 comments (asked for posts, it painted no comment at all
+ // until a refresh half a minute on; the pass below holds for them)
+ const kinds = feedKinds(def);
await Promise.all([
// people's reposts with their posts (a topic or firehose ask: posts only);
// every author, a chunk of them per ask
...(authors.length ? authorChunks(authors) : [null]).map((chunk) =>
- queryFeed(feedRelaysOr(def, def && def.all ? FIREHOSE_RELAYS : NOTE_RELAYS), { kinds: chunk && !topics.length ? [...FEED_KINDS, REPOST] : FEED_KINDS, limit: FEED_PAGE,
+ queryFeed(feedRelaysOr(def, def && def.all ? FIREHOSE_RELAYS : NOTE_RELAYS), { kinds: chunk && !topics.length && !def.replies ? [...kinds, REPOST] : kinds, limit: FEED_PAGE,
...(chunk ? { authors: chunk } : {}), ...(topics.length ? { '#t': topics } : {}) }, merge, c, 3000)),
- orT.length ? queryFeed(feedRelaysOr(def, TOPIC_RELAYS), { kinds: FEED_KINDS, limit: FEED_PAGE, '#t': orT }, merge, c, 3000) : null]);
+ orT.length ? queryFeed(feedRelaysOr(def, TOPIC_RELAYS), { kinds, limit: FEED_PAGE, '#t': orT }, merge, c, 3000) : null]);
} catch {} finally {
if (!c.stopped) {
c.status = 'ready';
@@ -6075,8 +6719,10 @@ export function messagesFeature(ctx) {
const fits = (e) => feedKeeps(def, e) && (((!authors.size || authors.has(e.pubkey))
&& (!topics.size || tagged(e, topics))) || (orT.size && tagged(e, orT)));
const seen = new Set(), out = [];
- for (const o of feedStates.values()) {
- for (const e of o.notes) if (!seen.has(e.id) && fits(e) && !hidden(e)) { seen.add(e.id); out.push(e); }
+ // a search within someone's posts: what their profile already loaded
+ const pools = [...[...feedStates.values()].map((o) => o.notes), ...(def.search ? [...authors].map((pk) => (notesCache.get(pk) || {}).notes || []) : [])];
+ for (const notes of pools) {
+ for (const e of notes) if (!seen.has(e.id) && fits(e) && !hidden(e)) { seen.add(e.id); out.push(e); }
}
return out.sort((a, b) => b.created_at - a.created_at).slice(0, FEED_PAGE);
}
@@ -6130,8 +6776,15 @@ export function messagesFeature(ctx) {
// ---- feeds anyone can open --------------------------------------------
// Every kind of feed has a URL, and a visitor with no wallet can read it.
const isVisitor = () => !wallet.mnemonic && !wallet.xpub && !wallet.xprv;
+ // Whose page is painted: a visitor's (no wallet on this device), or the
+ // wallet's that boot is about to restore (ctx.restorePending). The feed,
+ // reached by URL, paints before that restore lands; painted as a visitor's
+ // it had no post button, chips or nav until the wallet opened a beat later
+ // (Adam, 2026-10-31). Taps go by isVisitor(): by the time one lands the
+ // restore, synchronous, has run.
+ const visitorView = () => isVisitor() && !(ctx.restorePending && ctx.restorePending());
const showFeed = (id) => {
- ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.feedEdit = null;
+ ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null;
ui.chatOpen = true; ui.msgView = 'feed';
if (ui.screen === 'wallet') ui.pubProf = null; // the wallet's chrome owns it
switchFeed(id);
@@ -6179,6 +6832,8 @@ export function messagesFeature(ctx) {
const topics = [...new Set((q.get('t') || '').split(',').map(normTopic).filter(Boolean))];
const packs = (q.get('pack') || '').split(',').map((x) => parsePackLink(x.trim())).filter(Boolean);
const relays = urlRelays(q);
+ const words = (q.get('q') || '').trim();
+ if (words) { openTextSearch(words, relays, authors); return true; }
if (!authors.length && !topics.length && !packs.length) { openFirehose(relays); return true; }
const sig = JSON.stringify([authors, topics, packs.map(packKey), relays]);
let hsh = 5381; for (let i = 0; i < sig.length; i++) hsh = ((hsh * 33) ^ sig.charCodeAt(i)) >>> 0;
@@ -6209,6 +6864,7 @@ export function messagesFeature(ctx) {
if (def.all) return (def.curated ? '/feed' : '/feed/all') + r;
if (def.builtin) return share && mePk() && !def.replies ? '/feed/' + npubOf(mePk()) + r : null;
if (def.of) return '/feed/' + npubOf(def.of) + r;
+ if (def.search) return '/feed?q=' + encodeURIComponent(def.search) + ((def.authors || []).length ? '&p=' + def.authors.map(npubOf).join(',') : '') + (r ? '&' + r.slice(1) : '');
const authors = def.authors || [], topics = feedTopics(def), packs = def.packs || [];
if (!authors.length && !packs.length && topics.length === 1) return '/feed/t/' + encodeURIComponent(topics[0]) + r;
if (!authors.length && !topics.length && packs.length === 1) {
@@ -6332,10 +6988,22 @@ export function messagesFeature(ctx) {
const saved = relays.length ? null : st().feeds.find((f) => !f.follows && !(f.authors || []).length && feedTopics(f).length === 1 && feedTopics(f)[0] === tag);
const id = saved ? saved.id : 'topic:' + tag + (relays.length ? '@' + relays.join(',') : '');
if (!saved && !adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: '#' + tag, topics: [tag], relays });
- ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.feedEdit = null;
+ ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null;
ui.chatOpen = true; ui.msgView = 'feed';
switchFeed(id);
}
+ // Words typed into search and submitted without picking a suggestion:
+ // the notes and replies that say them, as a feed for this session.
+ // `authors`: only what these people posted ("search Franca's posts").
+ function openTextSearch(q, relays = [], authors = []) {
+ q = String(q || '').replace(/\s+/g, ' ').trim().slice(0, 200);
+ if (!q) return;
+ authors = hexList(authors).slice(0, 5);
+ const id = 'search:' + q.toLowerCase() + (authors.length ? '~' + authors.join(',') : '') + (relays.length ? '@' + relays.join(',') : '');
+ const name = '\u201c' + q + '\u201d' + (authors.length ? ' \u00b7 ' + authors.map((pk) => displayName(pk)).join(', ') : '');
+ if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name, follows: false, authors, packs: [], topics: [], search: q, relays });
+ showFeed(id);
+ }
// Something above the posts is in use — a post being written, the relay
// panel, a focused field — so new posts wait behind the pill rather than
// push it off the screen.
@@ -6377,6 +7045,8 @@ export function messagesFeature(ctx) {
if (!r) return null;
const dims = JSON.parse(r.headers.get('x-dims') || 'null');
if (!dims || !dims.width) return null;
+ // a GIF kept before GIFs were looped: made again, to loop
+ if (r.headers.get('x-original') === '1' && r.headers.get('x-gif') !== '1' && /\.gif(\?|$)/i.test(url)) return null;
const src = r.headers.get('x-original') === '1' ? null : URL.createObjectURL(await r.blob());
return { ...dims, thumb: src };
} catch { return null; }
@@ -6392,17 +7062,22 @@ export function messagesFeature(ctx) {
if (e && e.corsRefused) { noteNoCors(url); corsRefused.add(url); } // refused, as corsFetch confirmed
return null;
}
+ const gif = /gif/i.test(blob.type);
+ // a GIF that would play once and stop is painted from a copy that loops
+ let looped = null;
+ // (up to 4 MB: the copy is kept on disk beside the column copies)
+ if (gif && blob.size < 4e6) { try { const fixed = loopGif(await blob.arrayBuffer()); if (fixed) looped = new Blob([fixed], { type: 'image/gif' }); } catch {} }
const result = await makeImageThumbnails(blob, {
width: MEDIA_THUMB_W, tileSize: tileThumbs.has(url) ? 0 : TILE_PX,
});
if (!result) return null;
- const dims = { width: result.width, height: result.height }, out = result.media;
+ const dims = { width: result.width, height: result.height }, out = result.media || looped;
// Both sizes share one decode in the worker; only cache writes and object
// URLs come back to the page. The lightbox still uses the original.
if (result.tile) await saveTileThumb(url, result.tile).catch(() => {});
try {
const store = await thumbStore();
- await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1' } }));
+ await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1', ...(gif ? { 'x-gif': '1' } : {}) } }));
const keys = await store.keys();
for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k);
} catch {}
@@ -6425,9 +7100,12 @@ export function messagesFeature(ctx) {
// make it): the server makes one
if (!got && (noCorsHost(url) || corsRefused.has(url) || typeof OffscreenCanvas === 'undefined')) got = await serverMediaThumb(url).catch(() => null);
if (got) {
+ // the grid tile made alongside it, for a post's run of pictures
+ // (see pictureRuns): looked up from disk when the copy was
+ await warmTileThumbs([url]).catch(() => {});
// no copy (small already, or a GIF): the original is what paints,
// so it's the one decoded ahead — the row mustn't decode it on sight
- await decodeAhead(got.thumb || url);
+ await Promise.all([decodeAhead(got.thumb || url), tileThumbs.has(url) ? decodeAhead(tileThumbs.get(url)) : null]);
mediaReady.set(url, got);
return;
}
@@ -6466,21 +7144,23 @@ export function messagesFeature(ctx) {
// publish it); otherwise the metadata alone is fetched — a few KB for a
// moov-first file — with a short cap, since it gates the row. Remembered
// on disk so a clip seen once is never probed again.
- const VIDEO_RE = /\.(mp4|webm|mov|m4v)(\?[^\s]*)?$/i;
+ const VIDEO_RE = /\.(mp4|webm|mov|m4v|m3u8)(\?[^\s]*)?$/i; // (an .m3u8 is an HLS stream: a long clip, posted the way jb55 does)
// files known to be clips without saying so in their name (divine.video's
// have no extension): an imeta tag's video/* type, or a video event's file
const videoUrls = new Set();
const isVideoUrl = (url) => VIDEO_RE.test(url) || videoUrls.has(url);
const imetaFields = (tag) => { const f = {}; for (const p of tag.slice(1)) { const i = typeof p === 'string' ? p.indexOf(' ') : -1; if (i > 0) f[p.slice(0, i)] = p.slice(i + 1); } return f; };
- // A video event's file: of the versions its imeta tags offer, the one
- // nearest 1080 on its short side (a phone's screen; not the 4K original),
- // never an HLS playlist; else its url tag.
+ // A video event's file: its HLS stream where the browser plays one (the
+ // player picks the rendition); else of the versions its imeta tags
+ // offer, the one nearest 1080 on its short side (a phone's screen; not the
+ // 4K original); else its url tag.
function videoEventFile(ev) {
- let best = null;
+ let best = null, stream = null;
for (const tag of ev.tags || []) {
if (tag[0] !== 'imeta') continue;
const f = imetaFields(tag);
- if (!/^https?:\/\//.test(f.url || '') || /mpegurl/i.test(f.m || '') || /\.m3u8(\?|$)/i.test(f.url)) continue;
+ if (/^https?:\/\//.test(f.url || '') && (/mpegurl/i.test(f.m || '') || /\.m3u8(\?|$)/i.test(f.url))) { stream = stream || { url: f.url, image: f.image }; continue; }
+ if (!/^https?:\/\//.test(f.url || '')) continue;
if (f.m && !/^video\//.test(f.m)) continue;
const dm = /^(\d+)(?:\.0+)?x(\d+)/.exec(f.dim || '');
const edge = dm ? Math.min(+dm[1], +dm[2]) : 0;
@@ -6488,6 +7168,7 @@ export function messagesFeature(ctx) {
if (!best || score > best.score) best = { url: f.url, image: f.image, score };
}
if (!best) { const u = (ev.tags.find((x) => x[0] === 'url') || [])[1]; if (/^https?:\/\//.test(u || '')) best = { url: u }; }
+ if (stream && canHls()) best = { ...stream, image: stream.image || (best && best.image) };
if (best) videoUrls.add(best.url);
return best;
}
@@ -6566,7 +7247,8 @@ export function messagesFeature(ctx) {
const d = {};
if (!have.size && +f.size > 0) d.size = +f.size;
// no size, but a bitrate (bits/s) and a duration (Primal posts these): near enough
- else if (!have.size && +f.bitrate > 0 && +f.duration > 0) d.size = Math.round(+f.bitrate * +f.duration / 8);
+ // (a guess: never taken for the file's identity, see mediaItems)
+ else if (!have.size && +f.bitrate > 0 && +f.duration > 0) { d.size = Math.round(+f.bitrate * +f.duration / 8); d.sizeGuess = true; }
if (!have.dur && +f.duration > 0) d.dur = +f.duration;
const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(f.dim || '');
if (!have.w && m) { d.w = +m[1]; d.h = +m[2]; }
@@ -6605,11 +7287,20 @@ export function messagesFeature(ctx) {
// an iPhone's HEVC (hvc1/hev1 in the sample description)
let hevc = false;
for (let j = 0; j + 4 <= b.length && !hevc; j++) if (b[j] === 0x68 && (type(j) === 'hvc1' || type(j) === 'hev1')) hevc = true;
- return { faststart, ...(moovEnd ? { moovEnd } : {}), ...(w ? { w, h } : {}), ...(hevc ? { hevc } : {}) };
+ // its length, from the movie header (a long clip plays as HLS: playSrc)
+ let dur = 0;
+ for (let j = 4; j + 32 <= b.length && !dur; j++) {
+ if (b[j] !== 0x6d || type(j) !== 'mvhd') continue; // 'm'
+ const v1 = b[j + 4] === 1, scale = u32(j + (v1 ? 24 : 16));
+ const units = v1 ? u32(j + 28) * 2 ** 32 + u32(j + 32) : u32(j + 20);
+ if (scale && units && units !== 0xffffffff) dur = units / scale;
+ }
+ return { faststart, ...(moovEnd ? { moovEnd } : {}), ...(w ? { w, h } : {}), ...(hevc ? { hevc } : {}), ...(dur ? { dur } : {}) };
}
const videoProbes = new Map();
let videoProbing = 0;
const videoProbeQueue = [];
+ const clipGone = (url) => { const d = videoInfo.get(url); return !!d && typeof d.goneAt === 'number' && Date.now() - d.goneAt < 86_400_000; };
const probeFailedLately = (d) => !!d && typeof d.failedAt === 'number' && Date.now() - d.failedAt < 3_600_000;
function probeVideo(url, layout = false) {
const have = videoInfo.get(url);
@@ -6633,6 +7324,7 @@ export function messagesFeature(ctx) {
}
}
async function runVideoProbe(url) {
+ if (isHls(url)) return probeStream(url);
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 10_000);
try {
@@ -6642,7 +7334,7 @@ export function messagesFeature(ctx) {
// player's plain load answers this request without them, and it fails.
// Any clip that had played in the feed was "unmeasurable" that way.
const r = await fetch(url, { headers: { Range: 'bytes=0-' + (VIDEO_PROBE_BYTES - 1) }, cache: 'no-store', signal: ctrl.signal });
- if (!r.ok) throw new Error('HTTP ' + r.status);
+ if (!r.ok) throw Object.assign(new Error('HTTP ' + r.status), { status: r.status });
const ranges = r.status === 206;
const total = ranges ? +(/\/(\d+)\s*$/.exec(r.headers.get('content-range') || '') || [])[1] : +r.headers.get('content-length');
// never more than the first bytes, even from a server that ignored the range
@@ -6659,25 +7351,49 @@ export function messagesFeature(ctx) {
let o = 0;
for (const p of parts) { if (o >= buf.length) break; buf.set(p.subarray(0, buf.length - o), o); o += p.length; }
const head = readMp4Head(buf);
- const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}) };
- if (total > 0) d.size = total;
+ const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, goneAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) };
+ if (total > 0) { d.size = total; d.sizeGuess = undefined; }
else {
// a server that hides Content-Range from scripts (Primal's) still
// says Content-Length to a HEAD, which any page may read
try {
const hr = await fetch(url, { method: 'HEAD', cache: 'no-store', signal: AbortSignal.timeout(5000) });
const n = +hr.headers.get('content-length');
- if (hr.ok && n > 0) d.size = n;
+ if (hr.ok && n > 0) { d.size = n; d.sizeGuess = undefined; }
} catch {}
}
if (head.w && !(videoInfo.get(url) || {}).w) { d.w = head.w; d.h = head.h; }
if (head.w) rememberVideo(url, head.w, head.h);
noteVideoInfo(url, d);
- } catch {
- noteVideoInfo(url, { failedAt: Date.now() }); // a host that won't say (no CORS, down, slow): asked again in an hour
+ } catch (e) {
+ // a host that won't say (no CORS, down, slow): asked again in an hour.
+ // One that says the file is gone (deleted: a 404 or 410) is believed
+ // for a day, and the grid leaves the clip out (clipGone).
+ const gone = e && (e.status === 404 || e.status === 410);
+ noteVideoInfo(url, { failedAt: Date.now(), ...(gone ? { goneAt: Date.now() } : {}) });
+ if (gone && mediaMode === 'videos') scheduleRepaint();
} finally { clearTimeout(timer); }
return videoInfo.get(url);
}
+ // A stream is measured by a player: its playlist says nothing of the
+ // picture's size. Where HLS doesn't play, it can't be measured either.
+ async function probeStream(url) {
+ if (!canHls()) { noteVideoInfo(url, { failedAt: Date.now() }); return videoInfo.get(url); }
+ const v = document.createElement('video');
+ v.muted = true; v.preload = 'metadata';
+ const ok = await new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(false), 15_000);
+ v.onloadedmetadata = () => { clearTimeout(timer); resolve(!!v.videoWidth); };
+ v.onerror = () => { clearTimeout(timer); resolve(false); };
+ v.src = url;
+ });
+ if (ok) {
+ noteVideoInfo(url, { probed: true, stream: true, failedAt: undefined, ...(Number.isFinite(v.duration) ? { dur: v.duration } : {}) });
+ rememberVideo(url, v.videoWidth, v.videoHeight);
+ } else noteVideoInfo(url, { failedAt: Date.now() });
+ v.removeAttribute('src'); v.load();
+ return videoInfo.get(url);
+ }
// How much a clip may cost before it waits for a tap: less on a slow or
// metered connection.
const largeVideosOk = () => { try { return localStorage.getItem(VIDEO_LARGE_KEY) === '1'; } catch { return false; } };
@@ -6692,16 +7408,28 @@ export function messagesFeature(ctx) {
// Data Saver on, or a slow link: the connection to be careful with
const frugalData = () => { try { const c = navigator.connection; return !!(c && (c.saveData || /(^|-)2g$|^3g$/.test(c.effectiveType || ''))); } catch { return false; } };
const tappedClips = new Set(); // asked for by hand this session: plays, whatever it costs
- function videoHeavy(url) {
- if (tappedClips.has(url) || largeVideosOk()) return false;
+ // A clip too big to play as it is: over the budget, past 1080p, its index
+ // at the end of a big file — or (known) unmeasurable. Such a clip plays as
+ // an HLS stream where it can (playSrc); else it waits for a tap.
+ function bigClip(url, known = false) {
const d = videoInfo.get(url) || {};
if (d.w && d.h && Math.min(d.w, d.h) > 1080) return true;
- if (!d.size) return true; // nothing known: don't spend data blind
+ if (!d.size) return !known || d.probed || probeFailedLately(d); // nothing known: don't spend data blind
if (d.size > videoBudget()) return true;
// the whole file before the first frame: only worth it for a small one
if (d.probed && !d.faststart && !d.ranges && d.size > 8e6) return true;
return false;
}
+ function videoHeavy(url) {
+ if (tappedClips.has(url) || largeVideosOk()) return false;
+ const d = videoInfo.get(url) || {};
+ if (d.stream) return false; // a stream takes the rendition the connection carries
+ // one that streams costs what the connection carries: it plays like any
+ // other (Adam, 2026-10-18) — but not over Data Saver or a slow link,
+ // where even a stream is the reader's call
+ if (streamsHere(url) && !frugalData()) return false;
+ return bigClip(url);
+ }
const fmtBytes = (n) => n >= 1e9 ? (n / 1e9).toFixed(1) + ' GB' : n >= 1e6 ? Math.round(n / 1e6) + ' MB' : Math.max(1, Math.round(n / 1e3)) + ' KB';
function heavyLabel(url) {
const d = videoInfo.get(url) || {};
@@ -6713,7 +7441,7 @@ export function messagesFeature(ctx) {
if (!url || mediaReady.has(url)) return Promise.resolve();
const known = videoDims.get(url) || dim;
if (known) { rememberVideo(url, known.width, known.height); return Promise.resolve(); }
- if (typeof document === 'undefined' || videoUnknown.has(url)) return Promise.resolve();
+ if (typeof document === 'undefined' || videoUnknown.has(url) || clipGone(url)) return Promise.resolve(); // (gone: nothing to measure)
if (mediaWarming.has(url)) return mediaWarming.get(url);
// the 64 KB probe first: it reads the shape from the file's own header
// and costs nothing like a player's metadata load of an index-last file
@@ -6789,7 +7517,7 @@ export function messagesFeature(ctx) {
for (const part of String(content || '').split(NOTE_SPLIT)) {
if (!part || urls.length >= 2) continue;
const md = MD_PARTS.exec(part);
- const url = md ? md[3] : (/^https?:\/\//i.test(part) ? part : null);
+ const url = md ? md[3] : partUrl(part);
if (url && !(md && md[1]) && previewable(url) && !PACK_LINK_RE.test(url)) urls.push(url);
}
return urls;
@@ -6818,10 +7546,11 @@ export function messagesFeature(ctx) {
for (const part of String(content || '').split(NOTE_SPLIT)) {
if (!part) continue;
const md = MD_PARTS.exec(part);
- const url = md ? md[3] : (/^https?:\/\//i.test(part) ? part : null);
+ const url = md ? md[3] : partUrl(part);
if (!url) continue;
if ((md && md[1]) || /\.(png|jpe?g|gif|webp|avif)(\?[^\s]*)?$/i.test(url)) urls.push(url);
else if (youtubeId(url)) urls.push('https://i.ytimg.com/vi/' + youtubeId(url) + '/hqdefault.jpg');
+ else if ((paffEmbedUrl(url) || paffMusicUrl(url)) && previews.get(url)?.image) urls.push(previews.get(url).image);
}
return urls;
}
@@ -6829,13 +7558,13 @@ export function messagesFeature(ctx) {
const urls = [];
for (const part of String(content || '').split(NOTE_SPLIT)) {
const md = part && MD_PARTS.exec(part);
- const url = md ? md[3] : (/^https?:\/\//i.test(part || '') ? part : null);
+ const url = md ? md[3] : partUrl(part);
if (url && !(md && md[1]) && isVideoUrl(url)) urls.push(url);
}
return urls;
}
const avatarUrl = (p, pk) => p?.picture
- ? localPunk(p.picture) || (p.thumbFor === p.picture && p.thumb) || p.picture
+ ? localPunk(p.picture) || (p.thumbFor === p.picture && p.thumb) || blobAltOf(p.picture) || p.picture
: punkSmallUrl(pk);
async function warmAvatar(pk, deadline) {
let p = liveProfileOf(pk);
@@ -6878,7 +7607,7 @@ export function messagesFeature(ctx) {
await Promise.race([Promise.all(tasks), new Promise((r) => { timer = setTimeout(r, Math.max(0, deadline - Date.now())); })]);
} catch {} finally { clearTimeout(timer); }
}
- const notesReady = (evs, opts) => { const deadline = Date.now() + READY_MS; return Promise.all(evs.map((e) => noteReady(e, deadline, 0, opts))); };
+ const notesReady = (evs, opts, ms = READY_MS) => { const deadline = Date.now() + ms; return Promise.all(evs.map((e) => noteReady(e, deadline, 0, opts))); };
const keyed = (node, key) => { node.setAttribute('data-key', key); return node; };
// Keep only the resources this row actually uses. Copying the entire
// session media cache into every row grows quadratically as you scroll.
@@ -7008,27 +7737,63 @@ export function messagesFeature(ctx) {
// Posts at the door: filtered in synchronously, so the same note from a
// second relay is dropped while the first copy is still warming.
const feedStaged = new WeakMap();
+ // A word search turns up bot fleets posting one newsletter dozens of times
+ // from a dozen keys, each copy reworded a little (an emoji, "BREAKING", the
+ // picture moved) so it isn't the same text. Words and links as a set: a
+ // post sharing half of them with one already in the search feed is that
+ // post again, and only the first is shown.
+ const textSigs = new WeakMap(); // event -> Set of words
+ function textSig(e) {
+ let sig = textSigs.get(e);
+ if (!sig) {
+ const words = String(e.content || '').toLowerCase().match(/https?:\/\/\S+|[\p{L}\p{N}]{3,}/gu) || [];
+ textSigs.set(e, sig = new Set(words));
+ }
+ return sig;
+ }
+ const NEAR_COPY = 0.5; // measured 2026-11-11: copies 0.53+, distinct posts at most 0.45
+ const nearCopies = new WeakMap(); // feed state -> sigs admitted
+ function nearCopy(c, held, e) {
+ const sig = textSig(e);
+ if (sig.size < 8) return false; // short posts ("gm fiatjaf") are allowed to agree
+ let seen = nearCopies.get(c);
+ if (!seen) nearCopies.set(c, seen = held.map(textSig).filter((x) => x.size >= 8));
+ for (const o of seen) {
+ let both = 0;
+ for (const w of sig) if (o.has(w)) both++;
+ if (both / (sig.size + o.size - both) >= NEAR_COPY) return true;
+ }
+ seen.push(sig);
+ return false;
+ }
async function mergeFeed(evs, opts = {}, c = feedNow()) {
let staged = feedStaged.get(c);
if (!staged) feedStaged.set(c, staged = new Set());
// (with those waiting a moment to go in together — admitQueues — or a
// copy from a second relay, or another version of a clip, slips in)
+ const noteOf = (e) => (e.kind === REPOST ? repostInner(e) : e);
+ // Your own boost is the exception: it has a row of its own at the time
+ // you boosted, whether or not the post is in the feed already, and it
+ // doesn't keep the post itself (or someone else's repost of it) out.
+ const own = (e) => e.kind === REPOST && isMe(e.pubkey);
const held = [...c.notes, ...(c.deferred || []), ...((admitQueues.get(c) || {}).evs || [])];
const known = new Set(held.map((e) => e.id));
for (const e of evs || []) noteForSpam(e);
// A note shows once: as itself, or under the first repost of it to
// arrive — counting the ones still warming at the door.
// (`staged` holds the note's id too, for a repost)
- const noteOf = (e) => (e.kind === REPOST ? repostInner(e) : e);
- const notesIn = new Set(held.map((e) => noteOf(e)?.id).filter(Boolean));
+ const notesIn = new Set(held.filter((e) => !own(e)).map((e) => noteOf(e)?.id).filter(Boolean));
+ const boostedIn = new Set(held.filter(own).map((e) => noteOf(e)?.id).filter(Boolean));
// an addressable post (a 34235/34236 clip) once, however many versions of it come
- for (const e of held) { const a = noteOf(e) && addrOf(noteOf(e)); if (a) notesIn.add(a); }
- const addrNew = (e) => { const n = noteOf(e); const a = n && addrOf(n); return !a || (!notesIn.has(a) && !staged.has(a) && !!staged.add(a)); };
- const fresh = (e) => { const n = noteOf(e); return !!n && !notesIn.has(n.id) && !staged.has(n.id); };
- const unstage = (e) => { staged.delete(e.id); const n = noteOf(e); if (n) { staged.delete(n.id); const a = addrOf(n); if (a) staged.delete(a); } };
+ for (const e of held) { const a = !own(e) && noteOf(e) && addrOf(noteOf(e)); if (a) notesIn.add(a); }
+ const addrNew = (e) => { const n = noteOf(e); const a = !own(e) && n && addrOf(n); return !a || (!notesIn.has(a) && !staged.has(a) && !!staged.add(a)); };
+ const stageId = (e) => (own(e) ? 'own:' : '') + noteOf(e).id;
+ const fresh = (e) => { const n = noteOf(e); return !!n && !(own(e) ? boostedIn : notesIn).has(n.id) && !staged.has(stageId(e)); };
+ const unstage = (e) => { staged.delete(e.id); const n = noteOf(e); if (n) { staged.delete(stageId(e)); const a = !own(e) && addrOf(n); if (a) staged.delete(a); } };
const def = feedDef(c.id);
let add = (evs || []).filter((e) => (e.kind === REPOST ? !(def && def.replies) && !!repostInner(e) && !hidden(repostInner(e)) && !reboosted(e) : feedKeeps(def, e)) && !hidden(e)
- && fresh(e) && !known.has(e.id) && !staged.has(e.id) && addrNew(e) && known.add(e.id) && staged.add(e.id) && staged.add(noteOf(e).id));
+ && fresh(e) && !known.has(e.id) && !staged.has(e.id) && addrNew(e) && known.add(e.id) && staged.add(e.id) && staged.add(stageId(e)));
+ if (def && def.search) add = add.filter((e) => !nearCopy(c, held, e));
if (!add.length) return false;
if (def && def.curated) {
const kept = curateFeed(add);
@@ -7058,6 +7823,7 @@ export function messagesFeature(ctx) {
await noteReady(e, undefined, 0, { parent: feedReplies(c) });
unstage(e);
if (c.stopped) return false;
+ if (feedReplies(c) && orphaned(e)) return false; // a reply to nothing anyone can find
// Cached rows can still be warming. This new row is already prepared
// and can take its stable presentation without waiting for that page.
if (c.booting) { c.prepared ||= new Set(); c.prepared.add(e.id); }
@@ -7139,7 +7905,7 @@ export function messagesFeature(ctx) {
// The pill's tap: the posts are already in, so this just goes up to them —
// to the OLDEST of them, the one right above where you were reading, so
- // you read on upward through the rest. Reaching the top by yourself clears
+ // you read on upward through the rest. Starting to scroll up by yourself clears
// the pill too (see the scroll listener).
// Drag the new-posts pill any way but up and let go past a short
// distance: it flies off that way and onDismiss runs. A short drag springs
@@ -7295,6 +8061,34 @@ export function messagesFeature(ctx) {
for (const e of evs || []) if (e && e.created_at && !(c.seenBack <= e.created_at)) c.seenBack = e.created_at;
c.sawAny = (c.sawAny || 0) + ((evs || []).length);
}
+ // A word search: the NIP-50 relays, and for a search within someone's
+ // posts their own recent posts too, read here a page at a time until a
+ // few match (most people's posts are in no search index at all).
+ async function searchPass(def, c, merge, extra = {}, limit = FEED_PAGE, relays = null) {
+ const authors = def.authors || [];
+ const indexed = queryFeed(relays || feedRelaysOr(def, TEXT_SEARCH_RELAYS),
+ { kinds: [1], search: def.search, limit, ...(authors.length ? { authors } : {}), ...extra }, merge, c, 5000).catch(() => false);
+ if (!authors.length) return indexed;
+ const read = (async () => {
+ const from = relays || [...new Set([...NOTE_RELAYS, ...PROFILE_ARCHIVE_RELAYS,
+ ...(await Promise.all(authors.map((pk) => relaysOf(pk).catch(() => [])))).flat()])];
+ let until = extra.until, got = false, hits = 0;
+ for (let page = 0; page < 4 && !c.stopped; page++) {
+ let oldest = Infinity, n = 0;
+ await queryStreamOn(from, { kinds: [1], authors, limit: 400, ...(until ? { until } : {}) }, async (ev) => {
+ if (c.stopped) return;
+ n++;
+ if (ev.created_at < oldest) oldest = ev.created_at;
+ if (saysWords(def.search, ev) && await mergeFeed([ev], merge, c)) { got = true; hits++; }
+ }, 6000);
+ if (hits >= 10 || n < 100 || !isFinite(oldest)) break;
+ until = oldest - 1;
+ }
+ return got;
+ })().catch(() => false);
+ const [a, b] = await Promise.all([indexed, read]);
+ return a || b;
+ }
async function queryFeed(relays, filter, merge, c, maxWait = 5000, qualifies = () => true) {
let got = false;
await queryStreamOn(relays, filter, async (ev) => {
@@ -7305,7 +8099,9 @@ export function messagesFeature(ctx) {
}, maxWait);
return got;
}
- async function feedPass(extra = {}, merge = {}, c = feedNow(), kinds = FEED_KINDS, limit = FEED_LIMIT) {
+ // (relays: asked in place of the feed's own — the archives, for history
+ // the feed's relays have let go)
+ async function feedPass(extra = {}, merge = {}, c = feedNow(), kinds = FEED_KINDS, limit = FEED_LIMIT, relays = null) {
const def = feedDef(c.id);
if (!def) return false;
if (kinds === FEED_KINDS) kinds = feedKinds(def); // a conversations feed asks for replies
@@ -7313,16 +8109,16 @@ export function messagesFeature(ctx) {
const tag = topics.length ? { '#t': topics } : {};
let got = false;
if (def.curated) return popularPass(extra, merge, c, def);
+ if (def.search) return searchPass(def, c, merge, extra, limit, relays);
const orT = orTopicsOf(def);
const orPass = orT.length
- ? queryFeed(feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, limit, ...extra }, merge, c).then((x) => { if (x) got = true; })
+ ? queryFeed(relays || feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, limit, ...extra }, merge, c).then((x) => { if (x) got = true; })
: null;
if (!authors.length) {
// topics alone: nobody's outbox to read, so the wide relays, one ask;
// the firehose asks its relays for everything
if (!topics.length && !def.all) return false;
- const relays = feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS);
- return queryFeed(relays, { kinds, ...tag, limit, ...extra }, merge, c);
+ return queryFeed(relays || feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds, ...tag, limit, ...extra }, merge, c);
}
const readPlan = async (plan) => {
await Promise.all(plan.flatMap(({ relays, authors: a }) => {
@@ -7335,7 +8131,7 @@ export function messagesFeature(ctx) {
});
}));
};
- if (feedRelays(def)) await readPlan([{ relays: feedRelays(def), authors }]);
+ if (relays || feedRelays(def)) await readPlan([{ relays: relays || feedRelays(def), authors }]);
else {
const initial = outboxPlan(authors);
const reading = readPlan(initial);
@@ -7534,22 +8330,33 @@ export function messagesFeature(ctx) {
}
// While the feed is what's on screen, new posts arrive by themselves — on
// the same relays the pass above reads, one subscription each.
+ // The live subscriptions stay up across refreshes. Every refresh pass
+ // used to end by closing and reopening all of them — seventeen REQs over
+ // eight relays, twice per opening of Following — for subscriptions whose
+ // relays and authors hadn't changed; only the head they count fresh posts
+ // against moves, and that is read at each event.
+ let feedWatchKey = '', feedWatchHead = { t: Infinity };
function watchFeed() {
- stopFeedWatch();
const c = feedNow();
const def = feedDef(c.id); // the Conversations view has its own
- if (!feedHasQuery(def) || !ui.chatOpen || ui.msgView !== 'feed') return;
+ if (!feedHasQuery(def) || def.search || !ui.chatOpen || ui.msgView !== 'feed') { stopFeedWatch(); return; }
const newerThan = c.notes.length ? c.notes[0].created_at : Infinity;
const since = Math.floor(Date.now() / 1000) - 60;
const topics = feedTopics(def), tag = topics.length ? { '#t': topics } : {};
const kinds = feedKinds(def);
- const on = (ev) => { mergeFeed([ev], { live: true, newerThan }, c).then((ok) => { if (ok) scheduleRepaint(); }).catch(() => {}); };
const authors = feedAuthors(def);
+ const orT = orTopicsOf(def);
+ const plan = def.curated || !authors.length ? [] : feedRelays(def) ? [{ relays: feedRelays(def), authors }] : outboxPlan(authors);
+ const key = [c.id, !!def.curated, !!def.all, !!def.replies, kinds.join(), topics.join(), orT.join(), (feedRelays(def) || []).join(),
+ ...plan.map(({ relays, authors: a }) => relays.join() + '>' + a.join())].join('\n');
+ if (feedUnsubs.length && key === feedWatchKey) { feedWatchHead.t = newerThan; return; }
+ stopFeedWatch();
+ feedWatchKey = key;
+ const head = feedWatchHead = { t: newerThan };
+ const on = (ev) => { mergeFeed([ev], { live: true, newerThan: head.t }, c).then((ok) => { if (ok) scheduleRepaint(); }).catch(() => {}); };
if (def.curated) { const iv = setInterval(() => { if (c === feed && ui.chatOpen && ui.msgView === 'feed') refreshFeed({ force: true, live: true }, c).catch(() => {}); }, 120_000); feedUnsubs.push(() => clearInterval(iv)); return; }
if (!authors.length) { feedUnsubs.push(subscribeOn(feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds, ...tag, since }, on)); return; }
- const orT = orTopicsOf(def);
if (orT.length) feedUnsubs.push(subscribeOn(feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, since }, on));
- const plan = feedRelays(def) ? [{ relays: feedRelays(def), authors }] : outboxPlan(authors);
for (const { relays, authors: a } of plan)
for (let i = 0; i < a.length; i += REQ_AUTHORS)
feedUnsubs.push(subscribeOn(relays, { kinds: topics.length || def.replies ? kinds : [...kinds, REPOST], authors: a.slice(i, i + REQ_AUTHORS), ...tag, since }, on));
@@ -7557,6 +8364,7 @@ export function messagesFeature(ctx) {
function stopFeedWatch() {
for (const u of feedUnsubs) { try { u(); } catch {} }
feedUnsubs = [];
+ feedWatchKey = '';
}
// Prepare older pages several screens ahead of the reader. A scroll while
// preparation is underway shares the same work instead of exposing it early.
@@ -7566,6 +8374,7 @@ export function messagesFeature(ctx) {
feedAheadTimer = setTimeout(() => {
feedAheadTimer = null;
if (c !== feed || !ui.chatOpen || ui.msgView !== 'feed' || ui.profilePk || ui.noteThread) return;
+ if (mediaMode === 'live') return;
if (!listView()) {
// a grid holds only the posts with media: keep fetching while its
// foot is near (within reason — a firehose has no end)
@@ -7687,7 +8496,25 @@ export function messagesFeature(ctx) {
// A bare npub/nprofile — with or without an @ in front, no nostr: prefix —
// is how Vector (and people) write a mention; it resolves to the name too.
const BARE_KEY = '(?<![\\w/])@?(?:npub|nprofile)1[a-z0-9]{20,}(?![\\w])';
- const NOTE_SPLIT = new RegExp('(' + MD_LINK + '|https?:\\/\\/[^\\s]+|nostr:(?:npub|nprofile|note|nevent|naddr)1[a-z0-9]+|' + BARE_KEY + '|' + MENTION + '|' + HASHTAG + ')', 'gi');
+ // A web address written without its https:// ("Join the rally:
+ // saturdaybitcoin.com/rally/1?utm_source=nostr", Adam, 2026-11-22: Amethyst
+ // made it a link, we left it as text). Only names ending in a TLD people
+ // actually link to, so "node.js", "app.py", "e.g." and "README.md" stay
+ // words; never the domain of an email or nip05 (an @ or word sits before
+ // it) nor anything inside a longer URL (a / or : sits before it).
+ const BARE_TLDS = 'com|org|net|io|co|app|dev|me|xyz|info|biz|news|blog|tv|ai|gg|ly|fm|so|tech|site|online|store|shop|live|social|club|world|space|cloud|pub|wtf|lol|art|money|cash|finance|capital|network|chat|email|link|page|wiki|pro|academy|ca|us|uk|de|fr|nl|ch|at|be|es|it|pt|se|no|dk|fi|pl|cz|ie|eu|au|nz|jp|kr|in|br|mx|ar|cl|sv|za|ng|ke|ru|ua|tr|il|sg|hk|tw|cn|vc';
+ const BARE_URL = '(?<![\\w@./:#-])(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+(?:' + BARE_TLDS + ')(?![\\w-])(?::\\d{2,5})?(?:\\/[^\\s]*)?';
+ const BARE_URL_RE = new RegExp('^' + BARE_URL + '$', 'i');
+ // A bare address's href and what to show: trailing sentence punctuation
+ // stays text, as it does after a full URL in prose.
+ const bareLink = (part) => {
+ if (!part || /^https?:/i.test(part) || !BARE_URL_RE.test(part)) return null;
+ const [, addr, tail] = /^(.*?)([.,;:!?)\]'"]*)$/.exec(part);
+ return { url: 'https://' + addr, text: addr, tail };
+ };
+ // the https URL a split part stands for, written in full or bare
+ const partUrl = (part) => (/^https?:\/\//i.test(part || '') ? part : bareLink(part)?.url || null);
+ const NOTE_SPLIT = new RegExp('(' + MD_LINK + '|https?:\\/\\/[^\\s]+|wss?:\\/\\/[^\\s]+|nostr:(?:npub|nprofile|note|nevent|naddr)1[a-z0-9]+|' + BARE_KEY + '|' + MENTION + '|' + HASHTAG + '|' + BARE_URL + ')', 'gi');
const MD_PARTS = new RegExp('^(!?)\\[([^\\]\\n]{0,300})\\]\\(\\s*<?(https?:\\/\\/[^\\s>)]+)>?[^)\\n]{0,300}\\)$', 'i');
// A YouTube link is a video, so show the video. All three shapes it comes
@@ -7749,13 +8576,13 @@ 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
// by the morph from here, or a repaint would take the cover off.
function heavyCover(box, url, onPlay) {
- if (box.querySelector('.vid-heavy')) return;
+ if (box.querySelector('.vid-heavy') || box.classList.contains('gone')) return;
box._skipMorph = true;
const cover = h('button', { class: 'vid-heavy', type: 'button', 'aria-label': t('videoTapToPlay'),
onClick: (e) => {
@@ -7767,7 +8594,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);
@@ -7787,6 +8614,7 @@ export function messagesFeature(ctx) {
const h264Of = (url) => VMEDIA + 'h264.mp4?u=' + encodeURIComponent(url);
const noPicture = new Set(), h264Failed = new Set();
const serverThumbFailed = new Set(); // clips vmedia had no picture for (this session)
+ const deadTiles = new Set(); // grid pictures that wouldn't load (this session): left out
// A picture from a host that won't hand over its bytes (no CORS: primal's
// blossom, nostrcheck, most personal sites) can't have its column copy made
// here, so the server makes it (pic.webp: 1100px wide, or a 360px square
@@ -7832,17 +8660,60 @@ export function messagesFeature(ctx) {
const canHevc = () => hevcPlays ??= (() => {
try { return !!document.createElement('video').canPlayType('video/mp4; codecs="hvc1.1.6.L93.B0"'); } catch { return true; }
})();
- // what a player for this clip loads: the copy, once the original is known
- // not to show here
- const playSrc = (url) => vmediaOk(url) && !h264Failed.has(url)
- && (noPicture.has(url) || ((videoInfo.get(url) || {}).hevc && !canHevc())) ? h264Of(url) : url;
+ // A long clip (or a big one whose length isn't known) plays as HLS from
+ // vmedia: a 360p and a 720p rendition, the player taking the one the
+ // connection carries, in 4-second pieces made as they're watched — not a
+ // whole file streamed at its own bitrate (Adam, 2026-10-18; jb55: "you
+ // should use hls (m3u8 ext) for long videos"). Where the browser plays HLS
+ // itself (Chrome since 2025, Safari, Android); elsewhere (Firefox) the
+ // original as before.
+ const HLS_MIN_S = 90, HLS_MIN_BYTES = 60e6;
+ const hlsOf = (url) => VMEDIA + 'hls.m3u8?u=' + encodeURIComponent(url);
+ const isHls = (src) => (src || '').startsWith(VMEDIA + 'hls') || /\.m3u8(\?|#|$)/i.test(src || '');
+ const hlsFailed = new Set();
+ let hlsPlays;
+ const canHls = () => hlsPlays ??= (() => {
+ try { return !!document.createElement('video').canPlayType('application/vnd.apple.mpegurl'); } catch { return false; }
+ })();
+ const longClip = (url) => { const d = videoInfo.get(url) || {}; return d.dur ? d.dur >= HLS_MIN_S : (d.size || 0) >= HLS_MIN_BYTES; };
+ // Long, or too big to play as it is (a 4K clip, a 140 MB one: these
+ // waited for a tap with their cost on them) — streamed at a rendition the
+ // connection carries instead. A small short clip plays as it is: one
+ // request, its own quality, no work for the server.
+ const streamsHere = (url) => vmediaOk(url) && !isHls(url) && canHls() && !hlsFailed.has(url) && (longClip(url) || bigClip(url, true));
+ // what a player for this clip loads: the stream for a long or big one;
+ // the copy, once the original is known not to show here
+ const playSrc = (url) => !vmediaOk(url) || isHls(url) ? url
+ : streamsHere(url) ? hlsOf(url)
+ : !h264Failed.has(url) && (noPicture.has(url) || ((videoInfo.get(url) || {}).hevc && !canHevc())) ? h264Of(url) : url;
+ // A clip whose file its host no longer has: the player is the first to
+ // know (Primal's blossom answers a 404 with no CORS headers, so the
+ // probe couldn't read it and the box sat as a dead "Tap to play" — a
+ // post whose video "won't play", Adam, 2026-11-01). It says so where the
+ // player stood, with the file's link, and the grid leaves the clip out
+ // for a day, as it does a 404 the probe could read. The copy is tried
+ // first: a file the browser can't decode fails the same way, and the
+ // copy plays that one.
+ function clipDead(v, url) {
+ noteVideoInfo(url, { goneAt: Date.now() });
+ v._gone = true;
+ v.controls = false;
+ const box = v.parentElement;
+ if (!box) return;
+ box._skipMorph = true;
+ box.classList.add('gone');
+ for (const el of box.querySelectorAll('.vid-heavy, .vid-pp, .vid-sound')) el.remove();
+ if (!box.querySelector('.vid-nopic')) box.append(h('div', { class: 'vid-nopic' }, h('span', {}, t('videoGone')),
+ h('a', { href: url, target: '_blank', rel: 'noopener noreferrer', onClick: (e) => e.stopPropagation() }, t('videoOpenFile'))));
+ }
// A player whose clip turns out to have no picture it can show (its
// metadata says zero width) switches to the copy; if the copy fails too,
// the original's sound plays under a line saying why, with the file.
+ // One whose original won't load at all tries the copy too; the copy
+ // failing as well means the file is gone (clipDead).
function guardPicture(v, url) {
- if (!vmediaOk(url)) return;
const onCopy = () => (v.getAttribute('src') || '').startsWith(VMEDIA);
- v.addEventListener('loadedmetadata', () => {
+ if (vmediaOk(url)) v.addEventListener('loadedmetadata', () => {
if (v.videoWidth || onCopy() || h264Failed.has(url)) return;
noPicture.add(url);
const want = !v.paused;
@@ -7850,8 +8721,28 @@ export function messagesFeature(ctx) {
if (want) v.play().catch(() => {});
});
v.addEventListener('error', () => {
- if (!onCopy()) return;
+ if (!v.getAttribute('src')) return; // let go of (scrolled off), not failed
+ if (!onCopy()) {
+ if (vmediaOk(url) && !h264Failed.has(url) && !v._origFailed) {
+ v._origFailed = true;
+ const want = !v.paused;
+ v.setAttribute('src', h264Of(url));
+ if (want) v.play().catch(() => {});
+ return;
+ }
+ clipDead(v, url);
+ return;
+ }
+ // the stream failed: the copy or the original, as it would have been
+ if (isHls(v.getAttribute('src'))) {
+ hlsFailed.add(url);
+ const want = !v.paused;
+ v.setAttribute('src', playSrc(url));
+ if (want) v.play().catch(() => {});
+ return;
+ }
h264Failed.add(url);
+ if (v._origFailed) { clipDead(v, url); return; } // neither the file nor a copy of it: gone
const want = !v.paused;
v.setAttribute('src', url);
if (want) v.play().catch(() => {});
@@ -7864,10 +8755,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 && !v._gone; };
+ 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) {
@@ -7889,12 +8808,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
@@ -7902,12 +8833,27 @@ export function messagesFeature(ctx) {
Promise.resolve(go.call(v)).catch(() => {});
return true;
}
+ // A YouTube box we took full screen still shows YouTube's own full-screen
+ // button, and a press on it asks for full screen again from inside the
+ // frame — nothing to see, and no way out ("worked to make the video
+ // fullscreen but not toggle it off"). The page does see that happen: the
+ // frame becomes the full-screen element in place of its box. The press
+ // meant "out", so out it goes, both steps.
+ let ytFs = null, ytLeaving = false;
if (typeof document !== 'undefined') document.addEventListener('fullscreenchange', () => {
const el = fsElement();
+ const leave = () => Promise.resolve((document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)).catch(() => {});
+ if (!el) { ytFs = null; ytLeaving = false; }
+ else if (el.classList && el.classList.contains('yt-embed')) {
+ if (ytLeaving) { ytLeaving = false; ytFs = null; leave(); return; }
+ ytFs = el;
+ } else if (el.tagName === 'IFRAME' && ytFs && ytFs.contains(el)) { ytLeaving = true; leave(); return; }
// The player's own full-screen button on a feed clip: the pager, not
// Chrome's full screen (no next clip there). The button stays on the bar
// (left off, Chrome greys it out) and is taken over here.
- if (el && !pager && el.matches && el.matches('.notes-feed video.note-video') && el.dataset.clip) {
+ // (only a clip the pager has: taken out of full screen for a pager that
+ // then wouldn't open, a quoted post's clip went nowhere at all)
+ if (el && !pager && el.matches && el.matches('.notes-feed video.note-video') && el.dataset.clip && clipItem(el, el.dataset.clip)) {
const url = el.dataset.clip;
Promise.resolve((document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)).catch(() => {})
.then(() => { if (!pager && document.contains(el)) openClip(el, url); });
@@ -7932,10 +8878,9 @@ export function messagesFeature(ctx) {
preload: 'none', playsinline: true, muted: loud ? undefined : true,
style: stable ? videoBoxStyle(feedMedia(url)) : undefined,
// learned now, used by the next paint of any row with this clip
- onLoadedmetadata: (e) => rememberVideo(url, e.target.videoWidth, e.target.videoHeight),
+ onLoadedmetadata: (e) => { rememberVideo(url, e.target.videoWidth, e.target.videoHeight); attachMediaTimeline(e.target, url); },
// a touch's tap was taken at pointerup (below): its click, if one comes, is spent
- onClick: (e) => { if (Date.now() - (e.currentTarget._tapAt || 0) < 800) { e.stopPropagation(); e.preventDefault(); return; } videoTap(e, url); },
- onError: (e) => { if (!stable && !(e.target.getAttribute('src') || '').startsWith(VMEDIA)) { const b = e.target.parentElement; if (b) b.style.display = 'none'; } } });
+ onClick: (e) => { if (Date.now() - (e.currentTarget._tapAt || 0) < 800) { e.stopPropagation(); e.preventDefault(); return; } videoTap(e, url); } });
guardPicture(v, url);
// With its own controls up, Chrome on Android keeps a tap on the clip for
// them (it shows or hides the bar) and the page never gets the click — so
@@ -7954,13 +8899,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) => {
@@ -7969,14 +8939,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);
@@ -7988,6 +8963,7 @@ export function messagesFeature(ctx) {
() => {
box._inView = true;
clearTimeout(box._release);
+ if (v._gone) return; // nothing to load, and nothing to ask
if (!v.getAttribute('src') && !v.getAttribute('data-lazy-src')) {
v.setAttribute('src', playSrc(url));
v.addEventListener('loadedmetadata', () => { v.style.minHeight = ''; }, { once: true });
@@ -8016,6 +8992,9 @@ export function messagesFeature(ctx) {
try { v.removeAttribute('src'); v.load(); } catch {}
}, 2500);
});
+ // known gone already (this player, or one before it, found the file
+ // missing): said at once, no request made
+ if (clipGone(url)) clipDead(v, url);
return box;
}
@@ -8074,15 +9053,26 @@ export function messagesFeature(ctx) {
if (!go) return;
Promise.resolve(go.call(box, { navigationUI: 'hide' })).catch(() => {});
};
+ // With a mouse the player's own buttons are all in reach, so its clicks
+ // are its own: the shield is off while a mouse is over the box (by-mouse;
+ // a finger on the same screen gets it back) and the middle button pauses, the
+ // corner one goes full screen and back (Adam, 2026-11-10: the pause button
+ // "didn't pause, it fullscreened. it should just pause"). A click on the
+ // still plays it where it is.
const tapped = (e) => {
if (e.target.closest('.yt-open, .vid-sound, iframe')) return;
e.stopPropagation(); e.preventDefault();
const box = e.currentTarget;
if (!box.dataset.playing) load(box, false); // a tap means sound
else { post(box, 'unMute'); post(box, 'playVideo'); if (box._soundOn) box._soundOn(); }
- full(box);
+ if (e.pointerType !== 'mouse') full(box);
};
- const frame = h('div', { class: 'yt-embed', onClick: tapped },
+ const byMouse = (e) => { e.currentTarget.classList.toggle('by-mouse', e.pointerType === 'mouse'); };
+ const frame = h('div', {
+ class: 'yt-embed', onClick: tapped,
+ onPointerEnter: byMouse, onPointerMove: byMouse, onPointerDown: byMouse,
+ onPointerLeave: (e) => { e.currentTarget.classList.remove('by-mouse'); },
+ },
h('img', {
class: 'yt-poster', loading: 'lazy', alt: '',
src: !feedPaint || feedMedia('https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg')
@@ -8104,6 +9094,169 @@ export function messagesFeature(ctx) {
return frame;
}
+ // A PAFF film or episode link (paff.club/movie/<slug>[/play]?t=…, or
+ // /show/<slug>/s1e2[/play]) plays inside the post, as a YouTube link does:
+ // its backdrop and title (the page's own preview), a play button, and on
+ // the tap PAFF's bare player (/embed/…, the link's query kept: q quality,
+ // c copy, t start) in its place ("What would it take … to have it play in
+ // line like other videos and YouTube videos do?", Adam, 2026-11-17).
+ // Only ever on a tap, never on scroll: a PAFF film starts a torrent swarm
+ // in the viewer's browser. Scrolled off, it pauses (paffWatch).
+ function paffEmbedUrl(url) {
+ let u;
+ try { u = new URL(url); } catch { return null; }
+ if (u.hostname !== 'paff.club' && u.hostname !== 'www.paff.club') return null;
+ const m = u.pathname.match(/^\/(movie\/[^/]+|show\/[^/]+\/s\d+e\d+)(?:\/play)?\/?$/i);
+ return m ? 'https://paff.club/embed/' + m[1] + u.search : null;
+ }
+ // A playing film pauses once its post is off the screen and carries on
+ // when it comes back, if it was us that paused it ("can you ask paff to
+ // do the pause command?", Adam, 2026-11-17). The embed takes
+ // {source:'paff', command} and tells us its state as {source:'paff', event}.
+ let paffObserver = null, paffHeard = false;
+ const paffSay = (box, command) => {
+ const f = box.querySelector('iframe');
+ try { f?.contentWindow?.postMessage({ source: 'paff', command }, 'https://paff.club'); } catch {}
+ };
+ function paffWatch(box) {
+ if (typeof window === 'undefined') return;
+ if (!paffHeard) {
+ paffHeard = true;
+ window.addEventListener('message', (e) => {
+ if (e.origin !== 'https://paff.club' || e.data?.source !== 'paff') return;
+ for (const b of document.querySelectorAll('.paff-embed[data-playing]')) {
+ if (b.querySelector('iframe')?.contentWindow !== e.source) continue;
+ if (e.data.event === 'playing') { b._paffPlaying = true; b._pausedByUs = false; }
+ else if (e.data.event === 'pause' || e.data.event === 'ended') b._paffPlaying = false;
+ }
+ });
+ }
+ if (typeof IntersectionObserver === 'undefined') return;
+ if (!paffObserver) paffObserver = new IntersectionObserver((entries) => {
+ for (const en of entries) {
+ const b = en.target;
+ if (!b.isConnected) { paffObserver.unobserve(b); continue; }
+ if (!en.isIntersecting) {
+ if (b._paffPlaying) { b._pausedByUs = true; paffSay(b, 'pause'); }
+ } else if (en.intersectionRatio >= 0.5 && b._pausedByUs) {
+ b._pausedByUs = false; paffSay(b, 'play');
+ }
+ }
+ }, { threshold: [0, 0.5] });
+ paffObserver.observe(box);
+ }
+ // A PAFF song or album link: a slim card in the post (cover, title, ▶).
+ // The tap doesn't play it there: PAFF's slim player loads into a bar
+ // pinned above the bottom nav, outside the page, so the music carries on
+ // while you scroll, open threads, change tabs ("make songs embed nicely
+ // in nostr posts" … "From the start please", Adam, 2026-11-17). The bar
+ // is never moved (a moved iframe reloads); a new song changes its src,
+ // its × removes it.
+ function paffMusicUrl(url) {
+ let u;
+ try { u = new URL(url); } catch { return null; }
+ if (u.hostname !== 'paff.club' && u.hostname !== 'www.paff.club') return null;
+ const m = u.pathname.match(/^\/(?:play\/)?(song|album)\/([^/]+)\/?$/i);
+ if (!m) return null;
+ const q = new URLSearchParams(u.search);
+ q.set('bar', '1');
+ return 'https://paff.club/embed/' + m[1].toLowerCase() + '/' + m[2] + '?' + q;
+ }
+ let musicBar = null, musicUrl = null;
+ function playInBar(url, title) {
+ if (typeof document === 'undefined') return;
+ if (!musicBar) {
+ musicBar = document.createElement('div');
+ musicBar.className = 'music-bar';
+ const f = document.createElement('iframe');
+ f.allow = 'autoplay; fullscreen; picture-in-picture';
+ f.referrerPolicy = 'strict-origin-when-cross-origin';
+ const x = document.createElement('button');
+ x.type = 'button'; x.className = 'music-close'; x.textContent = '×';
+ x.setAttribute('aria-label', t('musicClose')); x.title = t('musicClose');
+ x.onclick = (e) => { e.stopPropagation(); closeMusic(); };
+ musicBar.append(f, x);
+ document.body.append(musicBar);
+ }
+ const f = musicBar.querySelector('iframe');
+ f.title = title || 'PAFF';
+ if (musicUrl !== url) f.src = paffMusicUrl(url);
+ musicUrl = url;
+ document.body.classList.add('music-open');
+ render();
+ }
+ function closeMusic() {
+ if (musicBar) { musicBar.remove(); musicBar = null; }
+ musicUrl = null;
+ document.body.classList.remove('music-open');
+ render();
+ }
+ function paffSongCard(url, pv) {
+ const on = musicUrl === url;
+ return h('div', {
+ class: 'paff-song' + (on ? ' on' : ''), role: 'button', tabindex: '0',
+ onClick: (e) => {
+ if (e.target.closest('.paff-song-open')) return;
+ e.stopPropagation(); e.preventDefault();
+ playInBar(url, pv?.title);
+ },
+ },
+ pv?.image ? h('img', {
+ class: 'paff-song-cover', loading: 'lazy', alt: '',
+ src: !feedPaint || feedMedia(pv.image) ? pv.image : undefined,
+ onError: (e) => { e.target.style.visibility = 'hidden'; },
+ }) : h('div', { class: 'paff-song-cover' }),
+ h('div', { class: 'paff-song-meta' },
+ h('div', { class: 'paff-song-title' }, pv?.title || t('musicSong')),
+ h('div', { class: 'small faint' }, on ? t('musicPlayingBelow') : pv?.description || 'paff.club')),
+ h('span', { class: 'paff-song-play', 'aria-hidden': 'true', html: on
+ ? '<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="10" width="3" height="9" rx="1"/><rect x="10.5" y="5" width="3" height="14" rx="1"/><rect x="16" y="8" width="3" height="11" rx="1"/></svg>'
+ : '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>' }),
+ h('a', {
+ class: 'paff-song-open', href: url, target: '_blank', rel: 'noopener noreferrer',
+ title: t('openOnPaff'), onClick: (e) => e.stopPropagation(),
+ }, '↗'));
+ }
+ function paffEmbed(url, pv) {
+ const embed = paffEmbedUrl(url);
+ const load = (box) => {
+ if (box.dataset.playing) return;
+ box.dataset.playing = '1';
+ // once playing, the box is the viewer's: no repaint rebuilds it (see youtubeEmbed)
+ box._skipMorph = true;
+ box.textContent = '';
+ const f = document.createElement('iframe');
+ f.src = embed;
+ f.title = pv?.title || 'PAFF';
+ f.allow = 'autoplay; fullscreen; picture-in-picture';
+ f.allowFullscreen = true;
+ f.referrerPolicy = 'strict-origin-when-cross-origin';
+ box.append(f);
+ paffWatch(box);
+ };
+ return h('div', {
+ class: 'yt-embed paff-embed',
+ onClick: (e) => {
+ if (e.target.closest('.yt-open, iframe')) return;
+ e.stopPropagation(); e.preventDefault();
+ load(e.currentTarget);
+ },
+ },
+ pv?.image ? h('img', {
+ class: 'yt-poster', loading: 'lazy', alt: '',
+ src: !feedPaint || feedMedia(pv.image) ? pv.image : undefined,
+ onError: (e) => { e.target.style.display = 'none'; },
+ }) : null,
+ h('button', {
+ class: 'yt-play', type: 'button', 'aria-label': t('playVideo'), title: t('playVideo'),
+ }, h('span', { style: 'display:flex', html: '<svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor" style="display:block"><path d="M8 5v14l11-7z"/></svg>' })),
+ h('div', { class: 'paff-title' }, pv?.title || 'PAFF'),
+ h('a', {
+ class: 'yt-open', href: url, target: '_blank', rel: 'noopener noreferrer',
+ title: t('openOnPaff'), onClick: (e) => e.stopPropagation(),
+ }, '↗'));
+ }
+
// ---- quoted notes ---------------------------------------------------------
// A nostr:note1/nevent1 in someone's post IS a post, so show it: the thing
// they're talking about, inside what they said about it. Fetched once per
@@ -8130,8 +9283,10 @@ export function messagesFeature(ctx) {
// dozen relays a fresh REQ for each quote it met).
const findQ = new Map(); // relay -> Map(id -> waiters)
let findTimer = null;
- function askNote(relays, id) {
- relays = readRelayList(relays);
+ function askNote(relays, id, hints = []) {
+ // (a relay the reference itself names is asked even when this device has
+ // marked it sick: it's the strongest clue there is to where the note lives)
+ relays = [...new Set([...readRelayList(relays), ...hints.filter((r) => /^wss:\/\/[^\s]+$/.test(r || '')).map(normRelay)])];
if (!relays.length) return Promise.resolve(null);
return new Promise((resolve) => {
const w = { left: relays.length, resolve, done: false };
@@ -8163,19 +9318,35 @@ export function messagesFeature(ctx) {
}
}
}
- // All at once, first answer wins: asked in turn, a note on a far relay
- // took longer than the feed waits for a row.
+ // The near relays first — the reference's hints, ours, the author's own
+ // — and the wide net only once those have come back empty, or after a
+ // moment if they are slow about it (asked in turn, a note on a far relay
+ // took longer than the feed waits for a row; asked all at once, every
+ // quoted note and every reply's parent went to a dozen relays, and the
+ // Conversations view spent half its REQs — three hundred in twenty
+ // seconds — on notes our own relays answered in the first beat).
+ const WIDE_AFTER_MS = 1200;
function findNote(ref) {
const ask = (relays) => askNote(relays, ref.id);
const near = [...new Set([...(ref.relays || []), ...zapRelays()])];
- const asks = [
- ask(near),
- ref.author ? relaysOf(ref.author).catch(() => []).then((rs) => ask(rs.filter((r) => !near.includes(r)))) : Promise.resolve(null),
- ask(WIDE_RELAYS.filter((r) => !near.includes(r))),
- ];
+ const authors = [...new Set([ref.author, ...(ref.authors || [])].filter(Boolean))];
return new Promise((resolve) => {
- let left = asks.length;
- for (const a of asks) a.then((ev) => { if (ev) resolve(ev); else if (--left === 0) resolve(null); });
+ let done = false;
+ const found = (ev) => { if (!done && ev) { done = true; resolve(ev); } };
+ const nearAsks = [
+ askNote(near, ref.id, ref.relays || []),
+ ...authors.map((a) => relaysOf(a).catch(() => []).then((rs) => ask(rs.filter((r) => !near.includes(r))))),
+ ];
+ for (const a of nearAsks) a.then(found);
+ const nearDone = Promise.all(nearAsks);
+ let wide = null;
+ const goWide = () => {
+ if (done || wide) return;
+ wide = ask(WIDE_RELAYS.filter((r) => !near.includes(r)));
+ wide.then(found);
+ };
+ const timer = setTimeout(goWide, WIDE_AFTER_MS);
+ nearDone.then(() => { clearTimeout(timer); if (done) return; goWide(); wide.then((ev) => { if (!done) { done = true; resolve(ev || null); } }); });
});
}
function quotedNote(ref) {
@@ -8289,6 +9460,7 @@ export function messagesFeature(ctx) {
if (feedPaint && c.ev) feedPaint.quotes.set(key, { ...c });
}
const isList = ref.kind === LIST_KIND || ref.kind === PACK_KIND;
+ if (c.ev && ref.kind === LIVE_KIND && !hiddenPk(liveHost(c.ev))) return liveCard(c.ev);
if (!c.ev && isList) {
// a list needs nothing fetched to open: the feed resolves its members
return h('div', { class: 'quote-card clickable', onClick: (e) => { e.stopPropagation(); openListFeed({ pk: ref.pk, d: ref.d, kind: ref.kind, title: '' }); } },
@@ -8358,6 +9530,1487 @@ export function messagesFeature(ctx) {
return out;
}
+ // ---- live streams (NIP-53) -----------------------------------------------
+ // What's on now, newest copy of each stream by its address: asked of the
+ // relays streams are announced on every couple of minutes while a feed or
+ // profile wants it. A feed shows the ones its people are in (Following:
+ // your follows; Everything and Popular: all of them) in a row above its
+ // posts; a profile says when its person is on; a post linking a stream
+ // shows it as a card. Any of them opens the stream's own screen.
+ const liveSeen = new Map(); // addr -> newest 30311
+ let liveAt = 0, liveAsking = null;
+ const liveAskedOf = new Map(); // pk -> when their own streams were asked for
+ function takeLive(evs) {
+ let changed = false;
+ for (const [a, ev] of newestByAddr(evs)) {
+ const cur = liveSeen.get(a);
+ if (!cur || cur.created_at < ev.created_at) { liveSeen.set(a, ev); changed = true; }
+ }
+ if (changed) liveHostsAt = 0;
+ return changed;
+ }
+ // who is on now (host -> their stream), for the rings round faces: worked
+ // out again when a stream changes and every half minute (one goes stale)
+ let liveHostsAt = 0, liveHosts = new Map();
+ // Our own live server knows better than an announcement: a stream it
+ // carries that it says is over (or taken down) is over, whatever its last
+ // 30311 claims — an app closed mid-stream never says `ended`, and the
+ // announcement reads live for an hour. Asked at most every 20 s a stream.
+ const OUR_LIVE = /^(https:\/\/v3\.coinos\.io|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)\/live\/[0-9a-f]{16}\/live\.m3u8$/;
+ const liveServerSays = new Map(); // stats url -> { state, seconds, at, asking }
+ function liveServerState(ev) {
+ const url = liveStream(ev) || '';
+ if (!OUR_LIVE.test(url)) return null;
+ const u = url.replace(/live\.m3u8$/, 'stats');
+ let k = liveServerSays.get(u);
+ if (!k) liveServerSays.set(u, k = { state: null, at: 0, asking: false });
+ if (!k.asking && Date.now() - k.at > 20_000) {
+ k.asking = true;
+ fetch(u, { cache: 'no-store' })
+ .then((r) => (r.status === 404 ? { state: 'ended' } : r.json()))
+ .then((j) => { const was = k.state; k.state = j.state || null; k.seconds = j.seconds; if (was !== k.state) { liveHostsAt = 0; scheduleRepaint(); } })
+ .catch(() => {}).finally(() => { k.asking = false; k.at = Date.now(); });
+ }
+ return k.state;
+ }
+ // taken down by an admin, or deleted by its streamer: nothing to play
+ const serverGone = (ev) => { const st = liveServerState(ev); return st === 'removed' || st === 'deleted'; };
+ const serverOver = (ev) => liveServerState(ev) === 'ended' || serverGone(ev);
+ const liveStatus = (ev, now) => { const st = announcedStatus(ev, now); return st === 'live' && serverOver(ev) ? 'ended' : st; };
+ const isLiveNow = (ev, now) => isLiveAnnounced(ev, now) && !serverOver(ev);
+ // Your own stream announced live that this tab isn't sending (the app was
+ // closed, reloaded, or lost it): end the announcement, its recording kept.
+ async function endAnnounced(ev) {
+ if (!confirm(t('goLiveEndAsk'))) return;
+ try {
+ const id = await requireIdentity();
+ if (id.pubkey !== ev.pubkey) { toast(t('liveNotYours')); return; }
+ const now = Math.floor(Date.now() / 1000);
+ const tags = ev.tags.filter((x) => !['status', 'current_participants', 'ends', 'recording', 'client'].includes(x[0]))
+ .concat([['status', 'ended'], ['ends', String(now)], CLIENT_TAG]);
+ const k = liveServerSays.get((liveStream(ev) || '').replace(/live\.m3u8$/, 'stats'));
+ if (OUR_LIVE.test(liveStream(ev)) && k && k.state !== 'removed' && k.state !== 'deleted' && (k.seconds || 0) >= 6) tags.push(['recording', liveStream(ev).replace(/live\.m3u8$/, 'index.m3u8')]);
+ const partial = { kind: LIVE_KIND, content: ev.content || '', created_at: Math.max(now, ev.created_at + 1), tags };
+ const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ takeLive([evt]);
+ liveHostsAt = 0;
+ render();
+ await publishOn([...new Set([...LIVE_RELAYS, ...liveRelays(ev), ...wallet.nostrRelays()])], evt);
+ } catch (e) { toast(e.message || String(e)); }
+ }
+ // ---- moderation: a viewer reports a stream we carry; an admin takes it
+ // down (the server ends it and keeps it from everyone, for reporting)
+ const LIVE_ADMIN = '98ae4da926c471c23fd12d1ebdd5839ba82917baa618e184e0c9916d93dcf4f7';
+ const ourStreamId = (ev) => { const m = OUR_LIVE.test(liveStream(ev) || '') && /\/live\/([0-9a-f]{16})\/live\.m3u8$/.exec(liveStream(ev)); return m ? m[1] : null; };
+ async function livePost(path, body) {
+ const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + path], ['method', 'POST']] });
+ const r = await fetch(liveBase() + path, { method: 'POST', headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)), 'content-type': 'application/json' }, body: JSON.stringify(body || {}), signal: AbortSignal.timeout(10000) });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
+ return j;
+ }
+ const REPORT_REASONS = ['csam', 'sexual', 'violence', 'illegal', 'spam', 'other'];
+ async function sendLiveReport(ev) {
+ const r = ui.liveReport;
+ if (!r || !r.reason) return;
+ r.busy = true; render();
+ try {
+ await livePost('/live/' + ourStreamId(ev) + '/report', { reason: r.reason, text: (r.text || '').trim() });
+ ui.liveReport = null;
+ toast(t('liveReported'));
+ } catch (e) { r.busy = false; toast(e.message || String(e)); }
+ render();
+ }
+ function liveReportPanel(ev) {
+ const r = ui.liveReport;
+ return h('div', { class: 'card col live-report', style: 'gap:8px', 'data-key': 'live-report' },
+ h('strong', {}, t('liveReportTitle')),
+ h('div', { class: 'small muted' }, t('liveReportDesc')),
+ ...REPORT_REASONS.map((x) => h('label', { class: 'row gap6', style: 'align-items:center' },
+ h('input', { type: 'radio', name: 'live-report-reason', value: x, checked: r.reason === x, onChange: () => { r.reason = x; render(); } }),
+ h('span', {}, t('liveReason_' + x)))),
+ h('textarea', { class: 'live-report-text', rows: '2', maxlength: '500', placeholder: t('liveReportTextPh'), value: r.text || '', onInput: (e) => { r.text = e.target.value; } }),
+ h('div', { class: 'row gap6' },
+ h('button', { class: 'btn-primary btn-sm live-report-send', disabled: !r.reason || !!r.busy, onClick: () => sendLiveReport(ev) }, r.busy ? h('span', { class: 'spinner sm' }) : t('liveReportSend')),
+ h('button', { class: 'btn-sm', onClick: () => { ui.liveReport = null; render(); } }, t('cancel'))));
+ }
+ async function takeDown(ev) {
+ if (!confirm(t('liveTakeDownAsk'))) return;
+ const ban = confirm(t('liveBanAsk'));
+ try {
+ await livePost('/live/' + ourStreamId(ev) + '/remove', { ban });
+ const k = liveServerSays.get(liveStream(ev).replace(/live\.m3u8$/, 'stats'));
+ if (k) { k.state = 'removed'; k.at = Date.now(); }
+ toast(t(ban ? 'liveTakenDownBanned' : 'liveTakenDown'));
+ render();
+ } catch (e) { toast(e.message || String(e)); }
+ }
+ // Your own stream's recording, deleted: the server lets its files go, and the
+ // announcement is said again without it (other apps drop the link too).
+ async function deleteRecording(ev) {
+ if (!confirm(t('liveDeleteAsk'))) return;
+ try {
+ const id = await requireIdentity();
+ if (id.pubkey !== ev.pubkey) { toast(t('liveNotYours')); return; }
+ await livePost('/live/' + ourStreamId(ev) + '/delete', {});
+ const k = liveServerSays.get(liveStream(ev).replace(/live\.m3u8$/, 'stats'));
+ if (k) { k.state = 'deleted'; k.at = Date.now(); }
+ const now = Math.floor(Date.now() / 1000);
+ const tags = ev.tags.filter((x) => !['status', 'current_participants', 'recording', 'client'].includes(x[0]))
+ .concat([['status', 'ended'], CLIENT_TAG]);
+ if (!tags.some((x) => x[0] === 'ends')) tags.push(['ends', String(now)]);
+ const evt = await signAsMe({ kind: LIVE_KIND, content: ev.content || '', created_at: Math.max(now, ev.created_at + 1), tags });
+ takeLive([evt]);
+ liveHostsAt = 0;
+ publishOn([...new Set([...liveRelays(ev), ...LIVE_RELAYS, ...wallet.nostrRelays()])], evt).catch(() => {});
+ toast(t('liveDeleted'));
+ render();
+ } catch (e) { if (!(e instanceof NoIdentity)) toast(e.message || String(e)); }
+ }
+ function liveHostNow(pk) {
+ if (!liveSeen.size) return null;
+ if (Date.now() - liveHostsAt > 30_000) {
+ liveHostsAt = Date.now();
+ const now = Date.now() / 1000;
+ liveHosts = new Map();
+ for (const ev of liveSeen.values()) {
+ if (!isLiveNow(ev, now) || !liveShowable(ev)) continue;
+ const h = liveHost(ev), cur = liveHosts.get(h);
+ if (!cur || cur.created_at < ev.created_at) liveHosts.set(h, ev);
+ }
+ }
+ return liveHosts.get(pk) || null;
+ }
+ const liveSince = () => Math.floor(Date.now() / 1000) - 6 * 3600;
+ function refreshLive() {
+ if (liveAsking || Date.now() - liveAt < 120_000) return;
+ liveAt = Date.now();
+ liveAsking = queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], since: liveSince(), limit: 300 }, 4000)
+ .then((evs) => { if (takeLive(evs)) scheduleRepaint(); })
+ .catch(() => {}).finally(() => { liveAsking = null; });
+ }
+ // the streams someone is in, asked of their own relays as well (a
+ // streamer's on a relay we don't otherwise read)
+ function askLiveOf(pk) {
+ if (Date.now() - (liveAskedOf.get(pk) || 0) < 120_000) return;
+ liveAskedOf.set(pk, Date.now());
+ Promise.resolve(relaysOf(pk)).catch(() => []).then((theirs) => {
+ const relays = [...new Set([...LIVE_RELAYS, ...(theirs || []).slice(0, 4)])];
+ return Promise.all([
+ queryOn(relays, { kinds: [LIVE_KIND], '#p': [pk], since: pastSince(), limit: 30 }, 4000),
+ queryOn(relays, { kinds: [LIVE_KIND], authors: [pk], since: pastSince(), limit: 30 }, 4000),
+ ]);
+ }).then(([a, b]) => { if (takeLive([...a, ...b])) scheduleRepaint(); }).catch(() => {});
+ }
+ // Past streams: ended ones that left a recording, the last month of them.
+ // A feed asks for its people's (all of them for Everything), a profile for
+ // its person's; opening one plays the recording (livePlayable).
+ const PAST_DAYS = 30;
+ const pastSince = () => Math.floor(Date.now() / 1000) - PAST_DAYS * 86400;
+ const pastAsked = new Map(); // what was asked -> when
+ let pastAsking = 0;
+ function askPast(key, filters) {
+ if (Date.now() - (pastAsked.get(key) || 0) < 300_000) return;
+ pastAsked.set(key, Date.now());
+ pastAsking++;
+ Promise.all(filters.map((f) => queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], since: pastSince(), ...f }, 5000).catch(() => [])))
+ .then((rs) => { if (takeLive(rs.flat())) scheduleRepaint(); })
+ .finally(() => { pastAsking--; scheduleRepaint(); });
+ }
+ const isPast = (ev) => liveStatus(ev) === 'ended' && !!liveRecording(ev) && !serverGone(ev);
+ const liveEndedAt = (ev) => +(ev.tags.find((x) => x[0] === 'ends') || [])[1] || ev.created_at;
+ const pastPeople = (def) => {
+ const fol = followsNow().set;
+ const people = def.all ? null : [...new Set([...feedAuthors(def), ...(def.follows ? fol : [])])];
+ return people && people.slice(0, 400);
+ };
+ const pastFilters = (ps, limit) => (ps ? [{ authors: ps, limit }, { '#p': ps, limit }] : [{ limit }]);
+ function pastForFeed(def) {
+ const ps = pastPeople(def);
+ if (ps && !ps.length) return [];
+ askPast('feed:' + def.id, pastFilters(ps, ps ? 200 : 300));
+ const set = ps && new Set(ps);
+ return [...liveSeen.values()]
+ .filter((ev) => isPast(ev) && liveShowable(ev) && !liveNsfw(ev) && (!set || set.has(liveHost(ev)) || set.has(ev.pubkey)))
+ .sort((a, b) => liveEndedAt(b) - liveEndedAt(a));
+ }
+ const pastOf = (pk) => [...liveSeen.values()].filter((ev) => liveHost(ev) === pk && isPast(ev) && liveShowable(ev))
+ .sort((a, b) => liveEndedAt(b) - liveEndedAt(a));
+ const liveNsfw = (ev) => ev.tags.some((x) => x[0] === 'content-warning' || (x[0] === 't' && /^nsfw$/i.test(x[1] || '')));
+ const liveShowable = (ev) => !hiddenPk(liveHost(ev)) && !hiddenPk(ev.pubkey);
+ function liveNowOf(pk) {
+ const now = Date.now() / 1000;
+ return [...liveSeen.values()].filter((ev) => liveHost(ev) === pk && isLiveNow(ev, now) && liveShowable(ev))
+ .sort((a, b) => b.created_at - a.created_at)[0] || null;
+ }
+ function liveForFeed(def) {
+ const now = Date.now() / 1000;
+ const fol = followsNow().set;
+ const people = def.all ? null : new Set([...feedAuthors(def), ...(def.follows ? fol : [])]);
+ if (people && !people.size) return [];
+ return [...liveSeen.values()]
+ .filter((ev) => isLiveNow(ev, now) && liveShowable(ev) && !liveNsfw(ev) && (!people || people.has(liveHost(ev)) || people.has(ev.pubkey)))
+ .sort((a, b) => (fol.has(liveHost(b)) - fol.has(liveHost(a))) || ((liveViewers(b) || 0) - (liveViewers(a) || 0)));
+ }
+ const liveCoverStyle = (ev) => { const img = liveImage(ev); return img ? 'background-image:url(' + JSON.stringify(img) + ')' : undefined; };
+ function liveBadge(ev) {
+ const s = liveStatus(ev);
+ return h('span', { class: 'live-badge ' + s }, t(s === 'live' ? 'liveBadge' : s === 'planned' ? 'livePlanned' : 'liveEnded'));
+ }
+ // Past streams scroll on: more tiles as the grid's foot comes near, and
+ // once those we hold run out, older ones from the relays (before the oldest
+ // asked so far) until a page brings nothing back.
+ const PAST_STEP = 24;
+ const pastPages = new Map(); // feed id -> { shown, until, end, busy }
+ const pastPage = (def) => { let p = pastPages.get(def.id); if (!p) pastPages.set(def.id, p = { shown: PAST_STEP, until: null, end: false, busy: false }); return p; };
+ function morePast() {
+ if (mediaMode !== 'live' || !ui.chatOpen || ui.msgView !== 'feed' || ui.profilePk || ui.noteThread || ui.liveStream) return;
+ const g = document.querySelector('.live-past') || document.querySelector('[data-key="live-past-wait"]');
+ if (!g || g.getBoundingClientRect().bottom > window.innerHeight * 2) return;
+ const def = feedDef(), p = pastPage(def), all = pastForFeed(def);
+ if (p.shown < all.length) { p.shown += PAST_STEP; scheduleRepaint(); return; }
+ if (p.end || p.busy || pastAsking) return;
+ const ps = pastPeople(def);
+ if (ps && !ps.length) { p.end = true; return; }
+ // older than the oldest we hold (the first ask's page may stop short of its month)
+ if (p.until == null) p.until = Math.min(Math.floor(Date.now() / 1000), ...all.map((e) => e.created_at));
+ p.busy = true;
+ scheduleRepaint();
+ Promise.all(pastFilters(ps, 100).map((f) => queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], until: p.until - 1, ...f }, 5000).catch(() => [])))
+ .then((rs) => {
+ const evs = rs.flat();
+ if (!evs.length) { p.end = true; return; }
+ p.until = Math.min(...evs.map((e) => e.created_at));
+ takeLive(evs);
+ p.shown += PAST_STEP;
+ })
+ .finally(() => { p.busy = false; scheduleRepaint(); setTimeout(morePast, 300); }); // still short of the screen: on
+ }
+ let pastScrollQueued = false;
+ if (typeof document !== 'undefined') document.addEventListener('scroll', () => {
+ if (pastScrollQueued || mediaMode !== 'live') return;
+ pastScrollQueued = true;
+ requestAnimationFrame(() => { pastScrollQueued = false; morePast(); });
+ }, { capture: true, passive: true });
+ // the feed's Live chip: its streams on now, as a grid of tiles
+ function liveGrid(def) {
+ const evs = liveForFeed(def).slice(0, 60);
+ const pp = pastPage(def);
+ const past = pastForFeed(def).slice(0, pp.shown);
+ setTimeout(morePast, 0); // a short grid fills the screen without a scroll
+ return h('div', { class: 'col', style: 'gap:12px', 'data-key': 'live-view' },
+ evs.length ? h('div', { class: 'live-grid', 'data-key': 'live-grid' }, ...evs.map(liveTile))
+ : liveAsking ? h('div', { class: 'row gap6', 'data-key': 'live-empty', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
+ : h('div', { class: 'small faint', 'data-key': 'live-empty', style: 'text-align:center;padding:12px 0' }, t('mediaNoLive')),
+ past.length ? h('h4', { class: 'live-past-title', 'data-key': 'live-past-title' }, t('livePast')) : null,
+ past.length ? h('div', { class: 'live-grid live-past', 'data-key': 'live-past' }, ...past.map(liveTile)) : null,
+ pastAsking || pp.busy ? h('div', { class: 'row gap6', 'data-key': 'live-past-wait', style: 'justify-content:center;padding:8px 0' }, h('span', { class: 'spinner sm' })) : null);
+ }
+ // a stream's tile: on now (how many watch) or past (when it ended)
+ function liveTile(ev) {
+ const host = liveHost(ev), n = liveViewers(ev), now = isLiveNow(ev);
+ return h('button', { type: 'button', class: 'live-tile', 'data-key': 'live:' + liveAddr(ev), onClick: (e) => { e.stopPropagation(); openLive(ev); } },
+ h('div', { class: 'live-cover', style: liveCoverStyle(ev) },
+ now ? liveBadge(ev) : h('span', { class: 'live-badge' }, t('liveRecordingBadge')),
+ now ? (n != null ? h('span', { class: 'live-viewers' }, t('liveWatching', { n })) : null)
+ : h('span', { class: 'live-viewers' }, timeLabel(liveEndedAt(ev) * 1000))),
+ h('div', { class: 'live-tile-title' }, liveTitle(ev) || t('liveUntitled')),
+ h('div', { class: 'row gap6 live-tile-host' }, avatar(host, 'chat-avatar mini', false), h('span', { class: 'small muted' }, displayName(host))));
+ }
+ // a profile's Streams tab: their past streams, as the Live chip's tiles
+ function pastStreams(pk) {
+ return h('div', { class: 'live-grid live-past', 'data-key': 'live-past-of:' + pk }, ...pastOf(pk).slice(0, 60).map(liveTile));
+ }
+ // a profile's "on now" line
+ function liveBanner(pk) {
+ askLiveOf(pk);
+ const ev = liveNowOf(pk);
+ if (!ev) {
+ // yours, still announced live, but nothing's going out: say so, and End it
+ const stale = pk === mePk() && !(bc && bc.phase === 'live') && [...liveSeen.values()]
+ .find((x) => x.pubkey === pk && liveHost(x) === pk && isLiveAnnounced(x) && serverOver(x));
+ return stale ? h('div', { class: 'live-banner', 'data-key': 'live-stale:' + liveAddr(stale) },
+ h('span', { class: 'live-banner-title' }, t('liveStaleMine', { title: liveTitle(stale) || t('liveUntitled') })),
+ h('button', { class: 'btn-sm live-end-stale', onClick: () => endAnnounced(stale) }, t('goLiveEnd'))) : null;
+ }
+ return h('button', { type: 'button', class: 'live-banner', 'data-key': 'live-banner:' + liveAddr(ev), onClick: () => openLive(ev) },
+ h('span', { class: 'live-badge live' }, t('liveBadge')),
+ h('span', { class: 'live-banner-title' }, liveTitle(ev) || t('liveUntitled')),
+ h('span', { class: 'small muted' }, t('liveWatch')));
+ }
+ // a post linking a stream (nostr:naddr of a 30311)
+ function liveCard(ev) {
+ const host = liveHost(ev);
+ return h('div', { class: 'quote-card clickable live-card', onClick: (e) => { e.stopPropagation(); openLive(ev); } },
+ h('div', { class: 'live-cover', style: liveCoverStyle(ev) }, liveBadge(ev)),
+ h('div', { class: 'col', style: 'gap:4px;min-width:0' },
+ h('div', { class: 'addr-title' }, liveTitle(ev) || t('liveUntitled')),
+ h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
+ avatar(host, 'chat-avatar mini', false), h('span', { class: 'quote-name' }, displayName(host)))));
+ }
+
+ function openLive(ev) {
+ rememberPlace('live');
+ const a = liveAddr(ev);
+ takeLive([ev]);
+ setZapAddr(ev.id, a);
+ ui.liveStream = { a, seed: ev };
+ ui.noteThread = null; ui.profilePk = null; ui.profOverThread = false; ui.userSearch = null;
+ render();
+ }
+ // a link to a stream (/naddr1…, nostr:naddr in a post we couldn't show)
+ async function openLiveRef(ref) {
+ const ev = liveSeen.get(LIVE_KIND + ':' + ref.pk + ':' + ref.d) || await findAddr(ref).catch(() => null);
+ if (ev) openLive(ev);
+ else toast(t('liveNotFound'));
+ }
+
+ // The open stream: its chat (1311) and zaps (9735, and coinos's Ark
+ // receipts) as they come, and the stream event itself as it's refreshed
+ // (the viewer count, `ended`).
+ let liveWatch = null;
+ function watchLive(s) {
+ if (liveWatch && liveWatch.a === s.a) return liveWatch;
+ stopLiveWatch();
+ const [, pk, ...rest] = s.a.split(':');
+ const d = rest.join(':');
+ takeLive([s.seed]);
+ const w = liveWatch = { a: s.a, lines: new Map(), stops: [], video: null, hls: null, err: null, actions: new Map(), actionTimer: null, actionStop: null, actionKey: '', sheet: null, reply: null, reacting: new Set() };
+ let mine = []; try { mine = wallet.nostrRelays(); } catch {}
+ const relays = w.relays = [...new Set([...liveRelays(s.seed), ...mine])];
+ const add = (e) => {
+ if (liveWatch !== w || w.lines.has(e.id)) return;
+ if (e.kind === 7 || e.kind === 5) { takeLiveAction(w, e); return; }
+ w.lines.set(e.id, e);
+ if (w.lines.size > 200) {
+ const oldest = [...w.lines.values()].sort((a, b) => a.created_at - b.created_at)[0];
+ w.lines.delete(oldest.id);
+ }
+ if (e.kind === LIVE_CHAT_KIND) { setZapAddr(e.id, w.a); watchLiveActions(w); }
+ else noteReceipt(e);
+ scheduleRepaint();
+ };
+ w.stops.push(subscribeOn(relays, { kinds: [LIVE_CHAT_KIND, 9735, 9737], '#a': [s.a], limit: 200 }, add));
+ w.stops.push(subscribeOn(relays, { kinds: [7, 5], '#a': [s.a], limit: 1000 }, e => takeLiveAction(w, e)));
+ w.stops.push(subscribeOn(relays, { kinds: [LIVE_KIND], authors: [pk], '#d': [d] }, (e) => { if (takeLive([e])) scheduleRepaint(); }));
+ // who's here: NIP-53 presence (kind 10312, the stream in its a tag) —
+ // Shosho, zap.stream and others say it, and so do we while it's open
+ w.here = new Map(); // pubkey -> when they last said so
+ w.stops.push(subscribeOn(relays, { kinds: [PRESENCE_KIND], '#a': [s.a], since: Math.floor(Date.now() / 1000) - PRESENCE_FRESH }, (e) => {
+ if (liveWatch !== w || (w.here.get(e.pubkey) || 0) >= e.created_at) return;
+ w.here.set(e.pubkey, e.created_at);
+ scheduleRepaint();
+ }));
+ sayHere(w);
+ return w;
+ }
+ // Presence counts for half an hour (some clients say it once, on joining);
+ // ours is said again every five minutes while the stream is open, and
+ // taken back (an empty one) on leaving. Only with a key held here: a
+ // signer app would be asked to sign every five minutes.
+ const PRESENCE_KIND = 10312, PRESENCE_FRESH = 1800;
+ async function presence(w, here) {
+ const id = await identity().catch(() => null);
+ if (!id || !(id.signer instanceof Uint8Array) || isVisitor()) return;
+ const ev = liveSeen.get(w.a);
+ if (here && (!ev || liveHost(ev) === id.pubkey || !isLiveNow(ev))) return; // not for your own, nor one that's over
+ const evt = finalizeEvent({ kind: PRESENCE_KIND, created_at: Math.floor(Date.now() / 1000), content: '',
+ tags: here ? [['a', w.a, w.relays[0] || '', 'root'], CLIENT_TAG] : [CLIENT_TAG] }, id.signer);
+ if (here) { w.here.set(evt.pubkey, evt.created_at); scheduleRepaint(); w.said = true; }
+ publishOn(w.relays, evt).catch(() => {});
+ }
+ function sayHere(w) {
+ presence(w, true);
+ w.hereTimer = setInterval(() => { if (liveWatch === w) presence(w, true); }, 5 * 60_000);
+ }
+ // the people known to be watching (fresh presence), newest first
+ const watchersOf = (w) => {
+ const since = Date.now() / 1000 - PRESENCE_FRESH;
+ return w && w.here ? [...w.here].filter(([, at]) => at >= since).sort((a, b) => b[1] - a[1]).map(([pk]) => pk) : [];
+ };
+ // "4 watching": hover names who (as many as are known), a tap shows their faces
+ function watchingLine(w, n, cls = 'small muted') {
+ const who = watchersOf(w);
+ const names = who.slice(0, 30).map((pk) => displayName(pk)).join(', ') + (who.length > 30 ? '…' : '');
+ return h('span', { class: cls + (who.length ? ' live-watching has-who' : ' live-watching'), title: who.length ? names : undefined,
+ role: who.length ? 'button' : undefined,
+ onClick: who.length ? (e) => { e.stopPropagation(); w.showWho = !w.showWho; render(); } : undefined },
+ t('liveWatching', { n: Math.max(n || 0, who.length) }));
+ }
+ function watchersRow(w) {
+ const who = watchersOf(w);
+ if (!w || !w.showWho || !who.length) return null;
+ return h('div', { class: 'live-who', 'data-key': 'live-who' },
+ ...who.slice(0, 60).map((pk) => h('button', { type: 'button', class: 'live-who-p', 'data-key': 'who:' + pk, title: displayName(pk), onClick: () => openProfile(pk) },
+ avatar(pk, 'chat-avatar mini', false), h('span', { class: 'small' }, displayName(pk)))));
+ }
+ // Include reactions/receipts from clients that only tag the comment's e,
+ // plus deletions of known reactions. Batch changes into one subscription.
+ function watchLiveActions(w) {
+ if (w.actionTimer || liveWatch !== w) return;
+ w.actionTimer = setTimeout(() => {
+ w.actionTimer = null;
+ if (liveWatch !== w) return;
+ const ids = [...w.lines.values()].filter(e => e.kind === LIVE_CHAT_KIND).map(e => e.id);
+ const reactions = [...w.actions.values()].filter(e => e.kind === 7 && ids.includes(e.tags.filter(t => t[0] === 'e').at(-1)?.[1])).slice(-400).map(e => e.id);
+ const all = [...ids, ...reactions];
+ const key = all.join(',');
+ if (key === w.actionKey) return;
+ w.actionKey = key;
+ if (w.actionStop) w.actionStop();
+ w.actionStop = all.length ? subscribeOn(w.relays, { kinds: [7, 5, 9735, 9737], '#e': all, limit: 1000 }, e => takeLiveAction(w, e)) : null;
+ }, 1000);
+ }
+ function takeLiveAction(w, ev) {
+ if (liveWatch !== w) return;
+ if (ev.kind === 9735 || ev.kind === 9737) { noteReceipt(ev); return; }
+ if (w.actions.has(ev.id)) return;
+ w.actions.set(ev.id, ev);
+ while (w.actions.size > 2000) w.actions.delete(w.actions.keys().next().value);
+ noteEmoji(ev);
+ watchLiveActions(w);
+ scheduleRepaint();
+ }
+ async function sendLiveReaction(w, ev, emoji) {
+ if (w.reacting.has(ev.id)) return;
+ w.reacting.add(ev.id);
+ try {
+ const id = await requireIdentity();
+ const current = liveReactions([...w.actions.values()]).get(ev.id)?.get(id.pubkey);
+ const old = [...w.actions.values()].filter(e => e.kind === 7 && e.pubkey === id.pubkey && e.tags.filter(t => t[0] === 'e').at(-1)?.[1] === ev.id);
+ const sign = partial => id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : id.signer.signEvent(partial);
+ const events = [];
+ const now = old.reduce((n, e) => Math.max(n, e.created_at + 1), Math.floor(Date.now() / 1000));
+ if (old.length) events.push(await sign({ kind: 5, content: '', created_at: now,
+ tags: [['a', w.a], ['k', '7'], ...old.map(e => ['e', e.id])] }));
+ const currentEmoji = current && (!current.content || current.content === '+' ? '❤️' : current.content);
+ if (currentEmoji !== emoji) events.push(await sign({ kind: 7, content: emoji, created_at: now,
+ tags: [['a', w.a], ['e', ev.id, w.relays[0] || ''], ['p', ev.pubkey], ['k', String(LIVE_CHAT_KIND)], ...reactEmojiTags(emoji), CLIENT_TAG] }));
+ if (liveWatch !== w) return;
+ const added = new Set(events.filter(e => !w.actions.has(e.id)).map(e => e.id));
+ for (const e of events) takeLiveAction(w, e);
+ render();
+ const results = await Promise.all(events.map(e => publishOn(w.relays, e).catch(() => false)));
+ // what no relay took is taken back off the screen
+ results.forEach((ok, i) => { if (!ok && added.has(events[i].id)) w.actions.delete(events[i].id); });
+ if (results.some(ok => !ok)) { toast(t('msgSendFailed')); render(); }
+ } catch (e) { if (!(e instanceof NoIdentity)) toast(t('msgSendFailed')); }
+ finally { w.reacting.delete(ev.id); scheduleRepaint(); }
+ }
+ function stopLivePlayer(w = liveWatch) {
+ if (!w) return;
+ if (w.hls) { try { w.hls.destroy(); } catch {} w.hls = null; }
+ if (w.pc) { try { w.pc.close(); } catch {} w.pc = null; }
+ clearInterval(w.rtcBeat);
+ const v = w.video;
+ w.video = null;
+ if (v) { try { v.pause(); v.srcObject = null; v.removeAttribute('src'); v.load(); } catch {} }
+ }
+ // A stream of ours as WebRTC: the live server gets Cloudflare's SFU to offer
+ // the sender's tracks, we answer. Resolves once connected (rejects after
+ // 8 s, or if there's no WebRTC for it); after that, a lost connection or a
+ // new publish (the sender reconnected) mounts the player again.
+ async function rtcWatch(w, el, src, go) {
+ const base = src.replace(/live\.m3u8$/, '');
+ const pc = w.pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }], bundlePolicy: 'max-bundle' });
+ const media = new MediaStream();
+ pc.ontrack = (e) => {
+ media.addTrack(e.track);
+ if (w.video === el && el.srcObject !== media) { el.srcObject = media; go(); }
+ };
+ const r = await fetch(base + 'rtc/watch', { method: 'POST', signal: AbortSignal.timeout(8000) });
+ if (!r.ok) throw new Error('watch ' + r.status);
+ const j = await r.json();
+ if (w.pc !== pc) return;
+ await pc.setRemoteDescription({ type: 'offer', sdp: j.sdp });
+ await pc.setLocalDescription(await pc.createAnswer());
+ const r2 = await fetch(base + 'rtc/answer', { method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ session: j.session, sdp: pc.localDescription.sdp }), signal: AbortSignal.timeout(8000) });
+ if (!r2.ok) throw new Error('answer ' + r2.status);
+ await new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error('rtc timeout')), 8000);
+ const on = () => {
+ if (pc.connectionState === 'connected') { clearTimeout(t); resolve(); }
+ else if (pc.connectionState === 'failed' || pc.connectionState === 'closed') { clearTimeout(t); reject(new Error('rtc ' + pc.connectionState)); }
+ };
+ pc.addEventListener('connectionstatechange', on);
+ on();
+ });
+ if (w.pc !== pc) return;
+ w.rtcFails = 0;
+ const again = (giveUp) => {
+ if (w.pc !== pc || w.video !== el) return;
+ if (giveUp || ++w.rtcFails > 3) w.noRtc = true;
+ stopLivePlayer(w);
+ scheduleRepaint();
+ };
+ pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed') again(); });
+ // counted as watching (no playlist is asked for), and told of a new publish
+ w.rtcBeat = setInterval(() => {
+ fetch(base + 'stats?watching=1', { cache: 'no-store' }).then((x) => x.json())
+ .then((st) => { if (st.state === 'live' && st.rtc !== j.gen) again(st.rtc == null); }).catch(() => {});
+ }, 10_000);
+ }
+ function stopLiveWatch() {
+ const w = liveWatch;
+ if (!w) return;
+ liveWatch = null;
+ clearTimeout(w.actionTimer);
+ if (w.actionStop) w.actionStop();
+ if (w.sheet) ui.emojiPick = null;
+ for (const stop of w.stops) { try { stop(); } catch {} }
+ clearInterval(w.hereTimer);
+ if (w.said) presence(w, false); // gone
+ stopLivePlayer(w);
+ }
+ // What to play: the stream while it's on, its recording once it's over.
+ // A recording is played here only when it's video (HLS, MP4, WebM); some
+ // services name a web page instead (zap.stream streams kept on Rumble), and
+ // that gets a link out — a player can't play a page.
+ const videoFile = (u) => /\.(m3u8|mp4|m4v|webm|mov)(\?|#|$)/i.test(u || '');
+ const liveRecordingPage = (ev) => { const u = liveRecording(ev); return u && !videoFile(u) ? u : ''; };
+ const livePlayable = (ev) => (serverGone(ev) ? '' : isLiveNow(ev) ? liveStream(ev) : liveStatus(ev) === 'ended' && videoFile(liveRecording(ev)) ? liveRecording(ev) : '');
+ // The <video> is the page's own once it plays: Chrome takes the playlist as
+ // its src; anywhere without HLS of its own, hls.js feeds it. The morph
+ // leaves it alone from then on (it would strip the src hls.js set).
+ function mountLivePlayer() {
+ const w = liveWatch;
+ const el = document.querySelector('video.live-video:not(.bc-preview)');
+ if (!w || !el || el === w.video) return;
+ stopLivePlayer(w);
+ const ev = liveSeen.get(w.a);
+ const src = ev && livePlayable(ev);
+ if (!src) return;
+ w.video = el;
+ el._skipMorph = true;
+ w.err = null;
+ // a stream that drops (the streamer's link, a restart) is tried again
+ const fail = () => {
+ if (w.video !== el) return;
+ stopLivePlayer(w);
+ w.err = 'offline';
+ scheduleRepaint();
+ setTimeout(() => { if (liveWatch === w && w.err === 'offline') { w.err = null; scheduleRepaint(); } }, 10_000);
+ };
+ el.addEventListener('error', fail);
+ el.addEventListener('hlsfatal', fail);
+ el.addEventListener('playing', () => { if (w.err) { w.err = null; scheduleRepaint(); } });
+ const go = () => el.play().catch(() => { el.muted = true; el.play().catch(() => {}); });
+ // A stream that's on plays through hls.js wherever it runs: it keeps the
+ // viewer near the live edge (starts 1.5 s back, speeds up when it falls
+ // behind). Chrome's own HLS player starts three segments back, never
+ // catches up, and fails outright if a page changes its speed. Its player
+ // still takes recordings, and live streams where hls.js can't run (iOS).
+ // Measured (go-live-test LATENCY=1, one machine): 2 s segments on
+ // Chrome's player 8.6 s behind the broadcaster; 1 s segments 4.5 s.
+ // Ours, on: WebRTC first (a fraction of a second behind), HLS if it
+ // can't be had — no WebRTC for the stream, or no connection in 8 s
+ if (src === liveStream(ev) && OUR_LIVE.test(src) && typeof RTCPeerConnection !== 'undefined' && !w.noRtc) {
+ rtcWatch(w, el, src, go).catch(() => {
+ if (w.video !== el) return;
+ w.noRtc = true;
+ stopLivePlayer(w);
+ scheduleRepaint(); // mounted again, as HLS
+ });
+ return;
+ }
+ const live = src === liveStream(ev) && isHls(src) && typeof MediaSource !== 'undefined';
+ if (!isHls(src) || (canHls() && !live)) { el.src = src; go(); return; }
+ import('../hls-player.js').then((m) => m.attachHls(el, src, { live })).then((hls) => {
+ if (w.video !== el) { try { hls && hls.destroy(); } catch {} return; }
+ if (!hls) { w.err = 'noplayer'; scheduleRepaint(); return; }
+ w.hls = hls; go();
+ }).catch(() => { w.err = 'noplayer'; scheduleRepaint(); });
+ }
+ // after every render: a stream screen gone takes its player and watch with
+ // it (a <video> taken out of the page plays on, unheard and unseen)
+ let liveShown = false;
+ function liveAfterRender() {
+ // the camera shown before going live: let go of it once that screen is left
+ if (!ui.goLive && bc && bc.phase === 'setup') { bcStopMedia(); bc = null; }
+ const pv = document.querySelector('video.bc-preview');
+ if (pv && bc && bc.media && pv.srcObject !== bc.media) { pv._skipMorph = true; pv.srcObject = bc.media; pv.play().catch(() => {}); }
+ if (!ui.liveStream) { stopLiveWatch(); return; }
+ if (!liveShown) { stopLivePlayer(); return; }
+ mountLivePlayer();
+ const box = document.querySelector('.live-chat');
+ fitLiveChat(box);
+ if (box && box._stick !== false) box.scrollTop = box.scrollHeight;
+ }
+ // On a phone the chat is as tall as the room left under the stream, so the
+ // message box (and the newest line above it) sits on screen, over the nav:
+ // at a fixed 60vh the card ran off the bottom, and a swipe inside the chat
+ // never moved the page to bring it up (Adam, 2026-11-20). A long
+ // description leaves little room: the chat keeps a floor and the page
+ // scrolls. On a variable of the document: a render takes inline styles back.
+ function fitLiveChat(box) {
+ const root = document.documentElement;
+ const card = box && box.closest('.live-chat-card');
+ if (!card || !matchMedia('(max-width: 520px)').matches) { root.style.removeProperty('--live-chat-max'); return; }
+ const nav = document.querySelector('.app-bottom-nav');
+ const b = box.getBoundingClientRect();
+ const under = card.getBoundingClientRect().bottom - b.bottom; // the message box and the card's foot
+ const room = window.innerHeight - (nav ? nav.getBoundingClientRect().height : 0) - (b.top + window.scrollY) - under;
+ const px = Math.max(170, Math.floor(room)) + 'px';
+ if (root.style.getPropertyValue('--live-chat-max') !== px) root.style.setProperty('--live-chat-max', px);
+ }
+ if (typeof window !== 'undefined') window.addEventListener('resize', () => {
+ const box = ui.liveStream && document.querySelector('.live-chat');
+ if (!box) return;
+ fitLiveChat(box);
+ if (box._stick !== false) box.scrollTop = box.scrollHeight;
+ });
+
+ async function sendLiveChat(w, text, reply) {
+ const id = await requireIdentity();
+ const ev = liveSeen.get(w.a);
+ const relays = [...new Set([...liveRelays(ev), ...wallet.nostrRelays()])];
+ const partial = { kind: LIVE_CHAT_KIND, content: text, created_at: Math.floor(Date.now() / 1000),
+ tags: [['a', w.a, relays[0] || '', 'root'], ...(reply ? [['e', reply.id, relays[0] || '', 'reply'], ['p', reply.pubkey]] : []), ...outboundEmojiTags(text), CLIENT_TAG] };
+ const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ w.lines.set(evt.id, evt);
+ setZapAddr(evt.id, w.a); watchLiveActions(w);
+ render();
+ if (!(await publishOn(relays, evt))) {
+ w.lines.delete(evt.id);
+ throw new Error(t('msgSendFailed'));
+ }
+ }
+
+ function liveMessageSheet(w) {
+ const ev = w.lines.get(w.sheet);
+ if (!ev || ev.kind !== LIVE_CHAT_KIND) return null;
+ const mine = liveReactions([...w.actions.values()]).get(ev.id)?.get(identityPk());
+ const close = () => { w.sheet = null; ui.emojiPick = null; render(); };
+ const item = (icon, label, onClick) => h('button', { class: 'msg-sheet-item', onClick }, h('span', { class: 'msg-sheet-ico' }, icon), label);
+ return h('div', { class: 'confirm-pop-backdrop', onClick: e => { if (e.target === e.currentTarget) close(); } },
+ h('div', { class: 'card col msg-sheet' },
+ reactRow(mine?.content, emoji => { close(); sendLiveReaction(w, ev, emoji); }),
+ ui.emojiPick ? null : item('↩', t('msgReply'), () => { w.reply = ev.id; close(); setTimeout(() => document.getElementById('msg-draft')?.focus(), 50); }),
+ !ui.emojiPick && canZapPk(ev.pubkey) && !isMe(ev.pubkey) ? item('⚡', t('msgZap'), () => { close(); zapMessage(ev.pubkey, ev.id); }) : null,
+ ui.emojiPick ? null : item('⧉', t('copy'), async () => { try { await navigator.clipboard.writeText(ev.content); toast(t('copied')); } catch {} close(); })));
+ }
+ function liveLine(ev, w, reactions) {
+ if (ev.kind === LIVE_CHAT_KIND) {
+ if (hiddenPk(ev.pubkey)) return null;
+ const em = noteEmojiTags(ev), mine = isMe(ev.pubkey);
+ const counts = new Map();
+ for (const r of reactions.get(ev.id)?.values() || []) {
+ if (hiddenPk(r.pubkey)) continue;
+ const emoji = !r.content || r.content === '+' ? '❤️' : r.content;
+ const url = emojiTagMap(r.tags).get(shortcodeOf(emoji)) || null;
+ const key = JSON.stringify([emoji, url]);
+ const c = counts.get(key) || { emoji, url, n: 0, mine: false };
+ c.n++; c.mine ||= isMe(r.pubkey); counts.set(key, c);
+ }
+ const canZap = canZapPk(ev.pubkey) && !mine;
+ const zc = zapChip(ev.id, { cls: 'chat-react', onClick: canZap ? () => zapMessage(ev.pubkey, ev.id) : null, onHold: () => openZapSettings(ev.pubkey, ev.id) });
+ const reply = w.lines.get(ev.tags.find(t => t[0] === 'e')?.[1]);
+ return keyed(h('div', { class: 'chat-row live-message' + (mine ? ' mine' : '') },
+ avatar(ev.pubkey),
+ h('div', { class: 'chat-body' },
+ h('div', { class: 'chat-meta' },
+ h('span', { class: 'chat-name clickable', onClick: () => openProfile(ev.pubkey) }, displayName(ev.pubkey)),
+ h('span', { class: 'chat-time' }, timeLabel(ev.created_at * 1000))),
+ h('div', { class: 'chat-line' },
+ h('div', { class: 'chat-bubble clickable' + (emojiJumbo(ev.content, em) ? ' jumbo' : ''),
+ onClick: chatBubbleClick(() => { if (!isVisitor()) { w.sheet = ev.id; ui.emojiPick = null; syncEmoji().catch(() => {}); render(); } }),
+ },
+ reply && !hiddenPk(reply.pubkey) ? h('div', { class: 'chat-quote' },
+ h('span', { class: 'chat-quote-name' }, displayName(reply.pubkey)),
+ h('span', { class: 'chat-quote-text' }, reply.content.slice(0, 160))) : null,
+ ...noteBody(ev.content, 0, em),
+ zc || counts.size ? h('div', { class: 'chat-reacts' }, zc,
+ [...counts.values()].map(c => h('button', { type: 'button', class: 'chat-react' + (c.mine ? ' on' : ''), title: t('msgReact'), disabled: isVisitor(),
+ onClick: e => { e.stopPropagation(); sendLiveReaction(w, ev, c.emoji); },
+ }, postReactNode(c), c.n > 1 ? ' ' + c.n : ''))) : null),
+ msgZapBtn(ev.pubkey, ev.id)))), ev.id);
+ }
+ const z = zapLine(ev, decodeBolt11);
+ if (!z.sats || (z.pk && hiddenPk(z.pk))) return null;
+ return keyed(h('div', { class: 'live-line live-zap' },
+ z.pk ? avatar(z.pk, 'chat-avatar mini') : h('span', {}, '⚡'),
+ h('div', { class: 'live-line-body' },
+ h('span', { class: 'quote-name' }, z.pk ? displayName(z.pk) : t('liveSomeone')), ' ',
+ h('b', {}, t('liveZapped', { n: z.sats.toLocaleString() })),
+ z.text ? h('span', {}, ' ' + z.text.slice(0, 280)) : null)), ev.id);
+ }
+
+ function liveScreen() {
+ const s = ui.liveStream;
+ const w = watchLive(s);
+ liveShown = true;
+ // your own stream, going out: the camera itself, not the stream seconds behind it
+ const mine = !!bc && bc.phase === 'live' && bc.a === s.a;
+ if (mine) setTimeout(scheduleRepaint, 1000); // the clock
+ const ev = liveSeen.get(s.a) || s.seed;
+ const host = liveHost(ev), status = liveStatus(ev), n = liveViewers(ev);
+ const src = livePlayable(ev);
+ const reactions = liveReactions([...w.actions.values()]);
+ const lines = [...w.lines.values()].sort((a, b) => a.created_at - b.created_at).slice(-200).map(e => liveLine(e, w, reactions)).filter(Boolean);
+ const draftKey = 'live:' + w.a;
+ const reply = w.lines.get(w.reply);
+ const say = liveServerState(ev) === 'removed' ? t('liveRemoved') : liveServerState(ev) === 'deleted' ? t('liveDeletedSay') : w.err === 'offline' ? t('liveOffline') : w.err === 'noplayer' ? t('liveNoPlayer')
+ : !src ? (status === 'planned' ? t('liveStartsAt', { when: timeLabel(liveStarts(ev) * 1000) }) : t('liveOver')) : null;
+ const send = () => {
+ const text = draftFor(draftKey).trim();
+ if (!text || w.sending) return;
+ w.sending = true;
+ setDraft(draftKey, '');
+ w.reply = null;
+ const inp = document.getElementById('msg-draft');
+ if (inp) inp.value = '';
+ sendLiveChat(w, text, reply).catch(e => {
+ setDraft(draftKey, text + (draftFor(draftKey) ? '\n' + draftFor(draftKey) : ''));
+ if (!w.reply) w.reply = reply?.id || null;
+ if (!(e instanceof NoIdentity)) toast(t('msgSendFailed'));
+ }).finally(() => { w.sending = false; render(); });
+ };
+ return h('div', { class: 'col live-page', style: 'gap:12px' },
+ ctx.brandHeader(!ui.pubProf && wallet.loaded),
+ 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; }),
+ h('h3', { class: 'live-title' }, liveTitle(ev) || t('liveUntitled')),
+ // yours, said to be on, but not going out from here: End it
+ !mine && ev.pubkey === mePk() && announcedStatus(ev) === 'live'
+ ? h('button', { class: 'btn-sm live-end-stale', onClick: () => endAnnounced(ev) }, t('goLiveEnd')) : null,
+ liveBadge(ev)),
+ mine ? h('div', { class: 'row gap6 bc-bar', style: 'align-items:center' },
+ h('span', { class: 'bc-clock' }, clockOf(Date.now() / 1000 - bc.starts)),
+ watchingLine(w, bc.viewers || 0),
+ bc.reconnecting ? h('span', { class: 'small', style: 'color:var(--red)' }, t('goLiveReconnecting'))
+ : bc.behind ? h('span', { class: 'small', style: 'color:var(--red)' }, t('goLiveBehind')) : null,
+ // camera ⇄ screen, without stopping the stream
+ navigator.mediaDevices?.getDisplayMedia ? h('button', { class: 'btn-sm bc-switch', style: 'margin-left:auto', onClick: () => { bc.source = bc.source === 'screen' ? 'camera' : 'screen'; bcPreview(); } },
+ t(bc.source === 'screen' ? 'goLiveToCamera' : 'callShare')) : null,
+ h('button', { class: 'btn-sm bc-end', style: navigator.mediaDevices?.getDisplayMedia ? undefined : 'margin-left:auto', onClick: () => { if (confirm(t('goLiveEndAsk'))) endBroadcast(); } }, t('goLiveEnd'))) : null,
+ mine ? h('div', { class: 'live-player', 'data-key': 'bc-player:' + s.a },
+ h('div', { class: 'live-frame', 'data-key': 'bc-frame:' + (bc.media ? bc.media.id : '') },
+ h('video', { class: 'live-video bc-preview' + (bc.source === 'camera' && bc.facing === 'user' ? ' mirror' : ''), muted: '', playsinline: '', autoplay: '' })))
+ : h('div', { class: 'live-player', 'data-key': 'live-player:' + s.a },
+ // the frame is keyed by what plays in it: the <video> itself is
+ // never morphed, so a stream that ends or drops swaps the frame
+ src && !w.err
+ ? h('div', { class: 'live-frame', 'data-key': 'live-frame:' + src },
+ h('video', { class: 'live-video', controls: '', playsinline: '', autoplay: '', poster: liveImage(ev) || undefined }))
+ : h('div', { class: 'live-cover live-still', 'data-key': 'live-still', style: liveCoverStyle(ev) },
+ h('span', { class: 'live-say' }, say),
+ !src && liveRecordingPage(ev) ? h('a', { class: 'btn-sm live-rec-link', href: liveRecordingPage(ev), target: '_blank', rel: 'noopener noreferrer' }, t('liveWatchRecording')) : null)),
+ h('div', { class: 'row gap6', style: 'align-items:center;flex-wrap:wrap' },
+ avatar(host, 'chat-avatar mini'),
+ h('a', { href: '#', class: 'quote-name', onClick: (e) => { e.preventDefault(); openProfile(host); } }, displayName(host)),
+ n != null && status === 'live' ? watchingLine(w, n) : null,
+ h('span', { style: 'margin-left:auto' }),
+ canZapPk(host) ? h('button', { class: 'btn-sm', onClick: (e) => { setZapAddr(ev.id, s.a); zapNote(host, ev, e.currentTarget.getBoundingClientRect()); } }, '⚡ ' + t('liveZap')) : null,
+ // ours to answer for: anyone signed in can report it, an admin can take it down
+ ourStreamId(ev) && !mine && !isVisitor() && host !== mePk() && !serverGone(ev)
+ ? h('button', { class: 'btn-sm live-report-btn', title: t('liveReport'), 'aria-label': t('liveReport'), onClick: () => { ui.liveReport = ui.liveReport ? null : { a: s.a, reason: null, text: '' }; render(); } }, '⚑') : null,
+ ourStreamId(ev) && mePk() === LIVE_ADMIN && host !== mePk() && !serverGone(ev)
+ ? h('button', { class: 'btn-sm live-takedown', style: 'color:var(--red)', onClick: () => takeDown(ev) }, t('liveTakeDown')) : null,
+ // your own, over: its recording is yours to delete
+ ourStreamId(ev) && !mine && ev.pubkey === mePk() && status === 'ended' && !serverGone(ev)
+ ? h('button', { class: 'btn-sm live-delete', style: 'color:var(--red)', title: t('liveDelete'), 'aria-label': t('liveDelete'), onClick: () => deleteRecording(ev) },
+ h('span', { style: 'display:flex', html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6"/></svg>' })) : null,
+ h('button', { class: 'btn-sm', title: t('postShare'), 'aria-label': t('postShare'), onClick: async () => {
+ const url = location.origin + '/' + packNaddr(s.a);
+ try { if (navigator.share) await navigator.share({ url }); else { await navigator.clipboard.writeText(url); toast(t('copied')); } } catch {}
+ } }, h('span', { style: 'display:flex', html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></svg>' }))),
+ 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 live-chat-card', style: 'gap:8px' },
+ h('div', { class: 'small muted' }, t('liveChat')),
+ h('div', {
+ class: 'live-chat', 'data-key': 'live-chat:' + s.a,
+ onScroll: (e) => { const b = e.currentTarget; b._stick = b.scrollHeight - b.scrollTop - b.clientHeight < 40; },
+ }, ...(lines.length ? lines : [keyed(h('div', { class: 'small faint' }, t('liveChatEmpty')), 'empty')])),
+ reply ? h('div', { class: 'reply-bar' },
+ h('div', { class: 'col grow', style: 'min-width:0' },
+ h('span', { class: 'small' }, '↩ ', displayName(reply.pubkey)),
+ h('span', { class: 'small muted chat-quote-text' }, reply.content.slice(0, 160))),
+ h('button', { class: 'btn-ghost', onClick: () => { w.reply = null; render(); } }, '×')) : null,
+ isVisitor() ? null : composer(t('liveChatHint'), send, null, draftKey)),
+ w.sheet ? liveMessageSheet(w) : null,
+ ...noteOverlays());
+ }
+
+ // ---- going live -----------------------------------------------------------
+ // The camera (or the screen) recorded in half-second chunks and sent over a
+ // WebSocket to coinos's live server (coinosv3-server live/), which makes HLS
+ // of it; the stream is announced as your kind 30311, refreshed every minute
+ // with how many watch, and ended with its recording. A coinos name's owner
+ // only: the server asks the registrar. One at a time.
+ const liveIngest = () => {
+ const local = typeof location !== 'undefined' && /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
+ return (local ? location.origin : APP_BASE).replace(/^http/, 'ws') + '/live/ingest';
+ };
+ const recType = () => {
+ if (typeof MediaRecorder === 'undefined') return null;
+ return ['video/webm;codecs=h264,opus', 'video/webm;codecs=vp8,opus', 'video/webm', 'video/mp4'].find((m) => { try { return MediaRecorder.isTypeSupported(m); } catch { return false; } }) || null;
+ };
+ const canGoLive = () => !isVisitor() && typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia && !!recType();
+ const clockOf = (sec) => { sec = Math.max(0, Math.floor(sec)); const hh = Math.floor(sec / 3600), mm = Math.floor(sec / 60) % 60, ss = sec % 60; return (hh ? hh + ':' + String(mm).padStart(2, '0') : String(mm)) + ':' + String(ss).padStart(2, '0'); };
+ let bc = null; // the broadcast: { phase, title, source, facing, media, rec, ws, id, a, ev, err, ... }
+ function openGoLive() {
+ if (bc && bc.a && bc.phase === 'live') { openLive(bc.ev); return; }
+ bc = { phase: 'setup', title: '', source: 'camera', facing: 'user', media: null, err: null };
+ ui.goLive = true;
+ ui.liveStream = null;
+ render();
+ bcPreview().catch(() => {});
+ }
+ function bcStopMedia() {
+ if (bc && bc.media) for (const tr of bc.media.getTracks()) { try { tr.stop(); } catch {} }
+ if (bc) bc.media = null;
+ }
+ // the picture to send: the camera (with its microphone), or the screen
+ // (with the microphone beside it, and the tab's sound when shared)
+ async function bcPreview() {
+ const b = bc;
+ if (!b) return;
+ // live, the old picture keeps going out until the new one is there (a
+ // cancelled screen picker mustn't leave the stream with nothing)
+ const live = b.phase === 'live', was = b.source === 'screen' ? 'camera' : 'screen';
+ if (!live) bcStopMedia();
+ b.err = null;
+ try {
+ let media;
+ if (b.source === 'screen') {
+ media = await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 30 }, audio: true });
+ const mic = await navigator.mediaDevices.getUserMedia({ audio: true }).catch(() => null);
+ if (mic && !media.getAudioTracks().length) for (const tr of mic.getAudioTracks()) media.addTrack(tr);
+ // the browser's own "Stop sharing", live: back to the camera
+ media.getVideoTracks()[0]?.addEventListener('ended', () => { if (bc === b && b.phase === 'live' && b.media === media) { b.source = 'camera'; bcPreview(); } });
+ } else {
+ media = await navigator.mediaDevices.getUserMedia({
+ video: { facingMode: b.facing, width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } },
+ audio: { echoCancellation: true, noiseSuppression: true },
+ });
+ }
+ if (bc !== b) { for (const tr of media.getTracks()) tr.stop(); return; }
+ if (live) bcStopMedia();
+ b.media = media;
+ // a switch mid-stream: the recorder carries on with the new picture,
+ // and the WebRTC copy swaps it in where it is
+ if (b.phase === 'live') { bcRecord(b, true); bcRtcSwap(b); }
+ } catch (e) {
+ if (bc !== b) return;
+ if (live) b.source = was; // no screen after all: the camera goes on
+ else b.err = t(b.source === 'screen' ? 'goLiveNoScreen' : 'goLiveNoCamera');
+ }
+ render();
+ }
+ async function liveAuth(b) {
+ const id = await requireIdentity();
+ const partial = { kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '',
+ tags: [['u', APP_BASE + '/live/ingest'], ['method', 'GET']] };
+ const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ b.pk = id.pubkey;
+ return btoa(JSON.stringify(evt));
+ }
+ // one connection to the server: its first word is where the stream is
+ function bcConnect(b, resume) {
+ return liveAuth(b).then((auth) => new Promise((resolve, reject) => {
+ const name = (hook('namesAddress') || '').split('@')[0];
+ const ws = new WebSocket(liveIngest() + '?auth=' + encodeURIComponent(auth) + '&name=' + encodeURIComponent(name) + (resume ? '&resume=' + resume : ''));
+ ws.binaryType = 'arraybuffer';
+ let hello = false;
+ ws.onmessage = (e) => {
+ if (hello || typeof e.data !== 'string') return;
+ hello = true;
+ try { resolve({ ws, info: JSON.parse(e.data) }); } catch (err) { reject(err); }
+ };
+ ws.onerror = () => { if (!hello) reject(new Error(t('goLiveRefused'))); };
+ ws.onclose = () => {
+ if (!hello) { reject(new Error(t('goLiveRefused'))); return; }
+ if (bc === b && b.ws === ws && b.phase === 'live') bcReconnect(b);
+ };
+ }));
+ }
+ // a recorder over the current picture, its chunks to the server; a new one
+ // (a new connection, a new camera) starts a fresh recording, header and all
+ function bcRecord(b, again = false) {
+ if (b.rec) { try { b.rec.ondataavailable = null; b.rec.stop(); } catch {} }
+ if (again && b.ws) { try { b.ws.close(1000, 'switch'); } catch {} return; } // the reconnect brings the new recording
+ const rec = new MediaRecorder(b.media, { mimeType: recType(), videoBitsPerSecond: 2_500_000, audioBitsPerSecond: 128_000 });
+ rec.ondataavailable = (e) => {
+ if (!e.data || !e.data.size || bc !== b || !b.ws || b.ws.readyState !== 1) return;
+ // more than a few seconds unsent: the link can't keep up
+ b.behind = b.ws.bufferedAmount > 4_000_000;
+ e.data.arrayBuffer().then((buf) => { if (b.ws && b.ws.readyState === 1) b.ws.send(buf); });
+ };
+ rec.start(500);
+ b.rec = rec;
+ }
+ async function bcReconnect(b) {
+ if (b.reconnecting) return;
+ b.reconnecting = true;
+ b.ws = null;
+ render();
+ for (let i = 0; i < 10 && bc === b && b.phase === 'live'; i++) {
+ try {
+ const { ws, info } = await bcConnect(b, b.id);
+ if (bc !== b || b.phase !== 'live') { ws.close(); break; }
+ b.ws = ws;
+ bcRecord(b);
+ b.reconnecting = false;
+ // The server couldn't take us back (it restarted, or we were gone
+ // too long): this is a new stream at a new address. The old one is
+ // over — said so, with no recording (there's next to nothing in
+ // it) — and the new one is announced as soon as it plays.
+ if (info.id !== b.id) {
+ toast(t('goLiveRestarted'));
+ const old = { ...b, recording: null };
+ Object.assign(b, { id: info.id, liveUrl: info.live, recording: info.recording, a: LIVE_KIND + ':' + b.pk + ':' + info.id });
+ bcRtc(b).catch(() => {});
+ bcAnnounce(old, 'ended').catch(() => {});
+ bcPlaying(b).then(() => (bc === b && b.phase === 'live' ? bcAnnounce(b, 'live') : null)).then(() => {
+ // the streamer's own view of it follows to the new address
+ if (bc === b && b.ev && ui.liveStream && ui.liveStream.a === old.a) { ui.liveStream = { a: b.a, seed: b.ev }; render(); }
+ }).catch(() => {});
+ }
+ render();
+ return;
+ } catch {}
+ await new Promise((r) => setTimeout(r, 3000));
+ }
+ b.reconnecting = false;
+ if (bc === b && b.phase === 'live') { toast(t('goLiveLost')); endBroadcast(); }
+ }
+ // The stream as WebRTC, for the app's own viewers: the picture also goes to
+ // Cloudflare's SFU (the live server brokers it), and a viewer pulls it from
+ // there a fraction of a second behind — HLS is seconds behind. Best effort:
+ // the HLS above is the stream either way, and the recording.
+ async function bcRtc(b, tries = 0) {
+ if (typeof RTCPeerConnection === 'undefined' || bc !== b || b.phase !== 'live' || !b.id || !b.media) return;
+ bcRtcStop(b);
+ const id = b.id;
+ const pc = b.pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }], bundlePolicy: 'max-bundle' });
+ const again = () => {
+ if (bc !== b || b.pc !== pc || b.phase !== 'live' || tries >= 5) return;
+ bcRtcStop(b);
+ setTimeout(() => bcRtc(b, tries + 1).catch(() => {}), 3000 * (tries + 1));
+ };
+ pc.onconnectionstatechange = () => { if (pc.connectionState === 'failed') again(); else if (pc.connectionState === 'connected') tries = 0; };
+ try {
+ const vt = b.media.getVideoTracks()[0], at = b.media.getAudioTracks()[0];
+ const tv = pc.addTransceiver(vt || 'video', { direction: 'sendonly', sendEncodings: [{ maxBitrate: 2_500_000 }] });
+ const ta = pc.addTransceiver(at || 'audio', { direction: 'sendonly' });
+ await pc.setLocalDescription(await pc.createOffer());
+ const u = liveBase() + '/live/' + id + '/rtc/publish';
+ const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/' + id + '/rtc/publish'], ['method', 'POST']] });
+ const r = await fetch(u, { method: 'POST', headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)), 'content-type': 'application/json' },
+ body: JSON.stringify({ sdp: pc.localDescription.sdp, tracks: [{ mid: tv.mid, trackName: 'video' }, { mid: ta.mid, trackName: 'audio' }] }) });
+ if (r.status === 501 || r.status === 403) { bcRtcStop(b); return; } // no WebRTC on this server
+ if (!r.ok) throw new Error('publish ' + r.status);
+ const j = await r.json();
+ if (b.pc !== pc) return;
+ await pc.setRemoteDescription({ type: 'answer', sdp: j.sdp });
+ } catch { again(); }
+ }
+ function bcRtcSwap(b) {
+ if (!b.pc || !b.media) return;
+ for (const tr of b.pc.getTransceivers()) {
+ const kind = tr.receiver && tr.receiver.track && tr.receiver.track.kind;
+ const next = kind === 'video' ? b.media.getVideoTracks()[0] : kind === 'audio' ? b.media.getAudioTracks()[0] : null;
+ if (kind) tr.sender.replaceTrack(next || null).catch(() => {});
+ }
+ }
+ function bcRtcStop(b) {
+ if (b && b.pc) { try { b.pc.close(); } catch {} b.pc = null; }
+ }
+ // the announcement: your 30311, and its copies as the stream goes on
+ async function bcAnnounce(b, status) {
+ const id = await requireIdentity();
+ const relays = [...new Set([...LIVE_RELAYS, ...wallet.nostrRelays()])];
+ const me = profileOf(id.pubkey) || {};
+ const tags = [['d', b.id], ['title', b.title || t('goLiveDefaultTitle', { name: displayName(id.pubkey) })],
+ ['status', status], ['streaming', b.liveUrl], ['starts', String(b.starts)],
+ ['p', id.pubkey, '', 'Host'], ['relays', ...relays.slice(0, 6)], CLIENT_TAG];
+ if (me.picture) tags.push(['image', me.picture]);
+ if (status === 'live' && b.viewers != null) tags.push(['current_participants', String(b.viewers)]);
+ if (status === 'ended') tags.push(['ends', String(Math.floor(Date.now() / 1000))]);
+ if (status === 'ended' && b.recording) tags.push(['recording', b.recording]);
+ // each copy newer than the last, to the second: an `ended` stamped the
+ // same second as the `live` before it lost to it (relays keep the lower
+ // id on a tie) and the stream read live for good
+ const prev = liveSeen.get(LIVE_KIND + ':' + id.pubkey + ':' + b.id);
+ const partial = { kind: LIVE_KIND, content: '', created_at: Math.max(Math.floor(Date.now() / 1000), prev ? prev.created_at + 1 : 0), tags };
+ const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ takeLive([evt]);
+ if (bc === b) b.ev = evt;
+ scheduleRepaint();
+ return publishOn(relays, evt);
+ }
+ async function bcPlaying(b) {
+ const url = b.liveUrl;
+ for (let i = 0; i < 40 && bc === b && b.phase === 'live' && b.liveUrl === url; i++) {
+ await new Promise((r) => setTimeout(r, 500));
+ const pl = await fetch(url, { cache: 'no-store' }).then((r) => r.text()).catch(() => '');
+ if ((pl.match(/\.ts\s*$/gm) || []).length >= 3) break;
+ }
+ }
+ async function startBroadcast() {
+ const b = bc;
+ if (!b || b.phase !== 'setup' || !b.media) return;
+ b.phase = 'starting'; b.err = null;
+ render();
+ try {
+ const { ws, info } = await bcConnect(b, null);
+ if (bc !== b) { ws.close(); return; }
+ Object.assign(b, { ws, id: info.id, liveUrl: info.live, recording: info.recording, starts: Math.floor(Date.now() / 1000), viewers: 0 });
+ b.phase = 'live';
+ b.a = LIVE_KIND + ':' + b.pk + ':' + b.id;
+ bcRecord(b);
+ bcRtc(b).catch(() => {});
+ try { b.lock = await navigator.wakeLock?.request('screen'); } catch {}
+ // the stream is a few seconds behind the camera: announced once it has
+ // three segments — Chrome's own player won't start a live playlist with
+ // fewer (it fails to parse it), so a viewer who comes at once would get
+ // an error, not the stream
+ await bcPlaying(b);
+ if (bc !== b || b.phase !== 'live') return;
+ await bcAnnounce(b, 'live');
+ b.tick = setInterval(() => bcTick(b), 60_000);
+ ui.goLive = null;
+ openLive(b.ev);
+ } catch (e) {
+ if (bc !== b) return;
+ b.phase = 'setup';
+ b.err = (e && e.message) || t('goLiveRefused');
+ try { b.ws && b.ws.close(); } catch {}
+ render();
+ }
+ }
+ // every minute: how many watch, into a fresh copy of the announcement
+ async function bcTick(b) {
+ if (bc !== b || b.phase !== 'live') return;
+ try {
+ const st = await (await fetch(b.liveUrl.replace(/live\.m3u8$/, 'stats'))).json();
+ b.viewers = st.viewers;
+ } catch {}
+ bcAnnounce(b, 'live').catch(() => {});
+ }
+ async function endBroadcast() {
+ const b = bc;
+ if (!b || b.phase === 'ended') return;
+ const was = b.phase;
+ b.phase = 'ended';
+ clearInterval(b.tick);
+ try { b.rec && b.rec.stop(); } catch {}
+ bcRtcStop(b);
+ try { if (b.ws && b.ws.readyState === 1) b.ws.send('end'); } catch {}
+ setTimeout(() => { try { b.ws && b.ws.close(1000, 'ended'); } catch {} }, 500);
+ bcStopMedia();
+ try { b.lock && b.lock.release(); } catch {}
+ bc = null;
+ ui.goLive = null;
+ render();
+ if (was === 'live' && b.id) {
+ await bcAnnounce(b, 'ended').catch(() => {});
+ toast(t('goLiveEnded'));
+ }
+ }
+ // the screen before going live: what to send, a title, the picture itself
+ function goLiveScreen() {
+ if (!bc) { bc = { phase: 'setup', title: '', source: 'camera', facing: 'user', media: null, err: null }; queueMicrotask(() => bcPreview().catch(() => {})); } // (a reload, back on this screen)
+ const b = bc;
+ const name = hook('namesAddress');
+ const screenOk = !!navigator.mediaDevices?.getDisplayMedia;
+ queueMicrotask(() => {
+ const v = document.querySelector('video.bc-preview');
+ if (v && b.media && v.srcObject !== b.media) { v._skipMorph = true; v.srcObject = b.media; v.play().catch(() => {}); }
+ });
+ const pick = (src) => { if (b.source === src) return; b.source = src; render(); bcPreview(); };
+ // the server's say first (a name a day old, not barred), so Start doesn't just fail
+ if (name && b.allowed === undefined) {
+ b.allowed = null;
+ signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/allowed'], ['method', 'GET']] })
+ .then((auth) => fetch(liveBase() + '/live/allowed?name=' + encodeURIComponent(name.split('@')[0]), { headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)) }, signal: AbortSignal.timeout(8000) }))
+ .then((r) => r.json()).then((j) => { b.allowed = j; render(); })
+ .catch(() => { b.allowed = { ok: true }; render(); }); // unasked: the server still decides at Start
+ }
+ const refused = b.allowed && b.allowed.ok === false ? b.allowed : null;
+ return h('div', { class: 'col live-page', style: 'gap:12px' },
+ ctx.brandHeader(true),
+ h('div', { class: 'card col', style: 'gap:12px' },
+ h('div', { class: 'row gap6', style: 'align-items:center' },
+ backBtn(() => { bcStopMedia(); bc = null; ui.goLive = null; }),
+ h('h3', { style: 'margin:0' }, t('goLive'))),
+ !name ? h('div', { class: 'notice small' }, t('goLiveNeedsName')) : null,
+ refused ? h('div', { class: 'notice small go-live-refused' }, refused.reason === 'new-name' && refused.until
+ ? t('goLiveNewName', { when: timeLabel(refused.until) }) : refused.reason === 'banned' ? t('goLiveBanned') : t('goLiveNeedsName')) : null,
+ h('div', { class: 'live-player', 'data-key': 'bc-player:' + b.source },
+ b.media
+ ? h('div', { class: 'live-frame', 'data-key': 'bc-frame:' + b.media.id }, h('video', { class: 'live-video bc-preview' + (b.source === 'camera' && b.facing === 'user' ? ' mirror' : ''), muted: '', playsinline: '', autoplay: '' }))
+ : h('div', { class: 'live-cover live-still', 'data-key': 'bc-still' }, h('span', { class: 'live-say' }, b.err || t('goLiveAsking')))),
+ h('div', { class: 'row gap6 wrap' },
+ h('button', { class: 'btn-sm' + (b.source === 'camera' ? ' on' : ''), onClick: () => pick('camera') }, t('goLiveCamera')),
+ screenOk ? h('button', { class: 'btn-sm' + (b.source === 'screen' ? ' on' : ''), onClick: () => pick('screen') }, t('goLiveScreen')) : null,
+ b.source === 'camera' ? h('button', { class: 'btn-sm', title: t('goLiveFlip'), onClick: () => { b.facing = b.facing === 'user' ? 'environment' : 'user'; bcPreview(); } }, '⇄ ' + t('goLiveFlip')) : null),
+ h('input', { type: 'text', class: 'go-live-title', placeholder: t('goLiveTitlePh'), value: b.title, maxlength: '120',
+ onInput: (e) => { b.title = e.target.value; } }),
+ b.err && b.media ? h('div', { class: 'notice err small' }, b.err) : null,
+ h('button', { class: 'btn-primary btn-block go-live-start', disabled: !name || !b.media || b.phase !== 'setup' || !!refused, onClick: startBroadcast },
+ b.phase === 'starting' ? h('span', { class: 'spinner sm' }) : null, ' ', t(b.phase === 'starting' ? 'goLiveStarting' : 'goLiveStart')),
+ h('div', { class: 'small faint' }, t('goLiveHint'))));
+ }
+
+ // ---- calls (NIP-AC: src/calls.js) ------------------------------------------
+ // A 📞 or 🎥 in a conversation's header calls that person; a call from
+ // someone you follow (or talk to) rings over whatever page is up. The setup
+ // goes as ephemeral gift wraps to their DM inboxes and ours; TURN comes from
+ // coinos's live server (Cloudflare's), for the connections that can't go direct.
+ const liveBase = () => {
+ const local = typeof location !== 'undefined' && /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
+ return local ? location.origin : APP_BASE;
+ };
+ let calls = null;
+ const callInbox = new Map(); // peer -> their inbox relays, for this session
+ // Relays that turned a call message away are left out of the next ones: a
+ // relay that won't take the kind (nip17.com: "only kind 1059") for a day,
+ // one rate-limiting or banning us for ten minutes. Kept on this device.
+ const CALL_SHUN_KEY = 'coinos-call-shun';
+ let callShun = (() => { try { return JSON.parse(localStorage.getItem(CALL_SHUN_KEY) || '{}'); } catch { return {}; } })(); // relay -> until
+ function callRefused(url, msg) {
+ const kindRule = /only kind|not (accepted|allowed)|blocked|unsupported|restricted|kind \d+/i.test(msg) && !/rate|too many|banned|slow down/i.test(msg);
+ callShun[url] = Date.now() + (kindRule ? 86400_000 : 600_000);
+ try { localStorage.setItem(CALL_SHUN_KEY, JSON.stringify(callShun)); } catch {}
+ }
+ function callRelaysOf(relays) {
+ const now = Date.now();
+ const ok = relays.filter((r) => !(callShun[r] > now));
+ return ok.length ? ok : relays; // all of them shunned: try them anyway
+ }
+ async function inboxFor(pk) {
+ if (callInbox.has(pk)) return callInbox.get(pk);
+ const p = (isMe(pk) ? Promise.resolve(ownInbox) : fetchInboxRelays(pk).catch(() => []))
+ .then((l) => [...new Set([...DM_RELAYS, ...(l || []).filter((r) => /^wss:\/\//i.test(r)).slice(0, 4)])]);
+ callInbox.set(pk, p);
+ return p;
+ }
+ async function signAsMe(tmpl) {
+ const id = await requireIdentity();
+ return id.signer instanceof Uint8Array ? finalizeEvent(tmpl, id.signer) : id.signer.signEvent(tmpl);
+ }
+ let iceCache = null; // { servers, until }
+ async function callIce() {
+ if (iceCache && Date.now() < iceCache.until) return iceCache.servers;
+ const STUN = [{ urls: ['stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302'] }];
+ try {
+ const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/turn'], ['method', 'GET']] });
+ const r = await fetch(liveBase() + '/live/turn', { headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)) }, signal: AbortSignal.timeout(8000) });
+ const j = await r.json();
+ if (!Array.isArray(j.iceServers) || !j.iceServers.length) return STUN;
+ iceCache = { servers: j.iceServers, until: Date.now() + Math.max(60, (j.ttl || 600) - 600) * 1000 };
+ return j.iceServers;
+ } catch { return STUN; }
+ }
+ function callMedia(type, facing = 'user') {
+ const video = { facingMode: facing, width: { ideal: 1280 }, height: { ideal: 720 } };
+ const audio = { echoCancellation: true, noiseSuppression: true, autoGainControl: true };
+ if (type === 'video-only') return navigator.mediaDevices.getUserMedia({ video });
+ if (type === 'screen') return navigator.mediaDevices.getDisplayMedia({ video: { frameRate: { ideal: 15 } }, audio: false });
+ return navigator.mediaDevices.getUserMedia(type === 'video' ? { audio, video } : { audio });
+ }
+ // who may ring: someone you follow, or someone you've written to
+ // who may ring: someone you follow, or someone you've written to. Anyone
+ // else's call doesn't ring but is told of, as a missed call that didn't
+ // ring (a wife's call must not vanish because you never followed her);
+ // a muted person's leaves nothing.
+ const mayRing = (pk) => hiddenPk(pk) ? null
+ : followsNow().set.has(pk) || wroteTo(pk) ? 'ring' : 'quiet';
+ // a message of ours in the conversation — not a call logged there (a
+ // stranger's unrung call would otherwise let their next one ring)
+ function wroteTo(pk) {
+ for (const m of (threads.get(pk) || new Map()).values()) if (m.mine && m.rumor.kind !== CALL_LOG) return true;
+ return false;
+ }
+ function callsNow() {
+ if (calls) return calls;
+ calls = createCalls({
+ me: () => dmSubKeys()[0],
+ sign: signAsMe,
+ // An offer, answer, hang-up or decline nobody took is tried again for a
+ // while (a relay's per-minute limit, a socket reconnecting): a lost
+ // answer left the caller ringing on and the callee "Connecting…".
+ // A late route isn't worth the wait.
+ send: async (pk, signed) => {
+ const tries = signed.kind === CALL.ICE ? 1 : 4;
+ for (let i = 0; i < tries; i++) {
+ if (i) await new Promise((r) => setTimeout(r, 1500 * 2 ** (i - 1)));
+ const relays = callRelaysOf(await inboxFor(pk));
+ if (await publishOn(relays, wrapCall(signed, pk), { onauth: relayAuth, onrefused: callRefused })) return;
+ }
+ throw new Error('not delivered');
+ },
+ iceServers: callIce,
+ media: callMedia,
+ mayRing: async (pk) => mayRing(pk),
+ changed: () => { callRing(); render(); },
+ ended: (rec) => { logCall(rec).catch(() => {}); },
+ warm: (pk) => callWarm(pk),
+ // a key of our own signs each candidate at once; a remote signer gets
+ // them all inside the offer or answer instead
+ trickle: () => { try { if (localStorage.getItem('coinos-call-trickle') === '0') return false; } catch {} const id = hook('nostrLoginIdentity'); return !id || id.signer instanceof Uint8Array; },
+ });
+ return calls;
+ }
+ // a wrap addressed to us: opened by whichever of our keys it's for
+ async function onCallWrap(wrap) {
+ for (const d of dmDecryptors()) {
+ const dec = d instanceof Uint8Array ? async (pk, ct) => nip44.decrypt(ct, nip44.getConversationKey(d, pk)) : (pk, ct) => d.decryptFrom(pk, ct);
+ const inner = await openCall(wrap, dec).catch(() => null);
+ if (inner) { profileOf(inner.pubkey); await callsNow().handle(inner); return; }
+ }
+ }
+ // The call log: each call a row in its conversation ("Outgoing video call
+ // 4:12", "Missed voice call"), kept like a message and sent to our own
+ // inbox (kind 1405 in a gift wrap, to us alone — a kind the NIP-AC
+ // discussion uses for logs, which other clients pass over) so our other
+ // devices list it too. A call rung on two of our devices is logged by
+ // both; the conversation shows it once, by its call-id.
+ const callStatus = (rec) => rec.connected ? 'answered'
+ : rec.reason === 'missed' || rec.reason === 'unrung' ? 'missed'
+ : rec.reason === 'declined' || rec.reason === 'peer-declined' ? 'declined'
+ : rec.reason === 'no-answer' ? 'no-answer'
+ : rec.reason === 'busy' ? 'busy'
+ : rec.reason === 'hung-up' ? 'cancelled'
+ : 'failed';
+ const CALL_RANK = { answered: 5, declined: 4, busy: 3, 'no-answer': 2, cancelled: 2, failed: 1, missed: 0 };
+ function callLogText(dir, type, status, seconds) {
+ const video = type === 'video';
+ const key = status === 'answered' ? (dir === 'out' ? 'callLogOut' : 'callLogIn')
+ : status === 'missed' ? 'callLogMissed'
+ : status === 'declined' ? (dir === 'out' ? 'callLogTheyDeclined' : 'callLogDeclined')
+ : status === 'no-answer' ? 'callLogNoAnswer'
+ : status === 'cancelled' ? 'callLogCancelled'
+ : status === 'busy' ? 'callLogBusy' : 'callLogFailed';
+ const what = t(key, { what: t(video ? 'callLogVideo' : 'callLogVoice') });
+ return status === 'answered' && seconds ? what + ' · ' + clockOf(seconds) : what;
+ }
+ async function logCall(rec) {
+ if (!rec || !rec.peer || /elsewhere$/.test(rec.reason || '')) return; // the device that took it logs it
+ // (a missed call found as the app opens may come before its keys do)
+ let id = await identity();
+ for (let i = 0; !id && i < 15; i++) { await new Promise((r) => setTimeout(r, 1000)); id = await identity(); }
+ if (!id) return;
+ const status = callStatus(rec);
+ const rumor = rumorWithId({
+ kind: CALL_LOG, pubkey: id.pubkey, created_at: Math.floor((rec.at || Date.now()) / 1000),
+ content: callLogText(rec.dir, rec.type, status, rec.seconds),
+ tags: [['p', rec.peer], ['call-id', rec.id], ['call-type', rec.type], ['direction', rec.dir], ['status', status],
+ ['duration', String(rec.seconds || 0)], ...(rec.reason === 'unrung' ? [['rang', 'no']] : []), ['alt', 'Call log']],
+ });
+ noteDM(rec.peer, rumor, true);
+ persistDms();
+ // to our other devices — not through Amber, a prompt per call for a log line
+ if (!(id.signer instanceof Uint8Array) && (id.signer.interactive || !id.signer.encryptTo)) return;
+ const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
+ publishOn(DM_RELAYS, toSelf);
+ toOwnInbox(toSelf);
+ }
+ // A conversation's rows with each call once: its most telling log (one
+ // device answered it while another only saw it ring)
+ function foldCallLogs(msgs) {
+ const best = new Map();
+ for (const m of msgs) {
+ if (m.rumor.kind !== CALL_LOG) continue;
+ const cid = (m.rumor.tags.find((x) => x[0] === 'call-id') || [])[1] || m.rumor.id;
+ const st2 = (x) => CALL_RANK[(x.rumor.tags.find((y) => y[0] === 'status') || [])[1]] ?? 0;
+ const cur = best.get(cid);
+ if (!cur || st2(m) > st2(cur)) best.set(cid, m);
+ }
+ return msgs.filter((m) => m.rumor.kind !== CALL_LOG || best.get((m.rumor.tags.find((x) => x[0] === 'call-id') || [])[1] || m.rumor.id) === m);
+ }
+ function callLogRow(m, peer) {
+ const tag = (k) => (m.rumor.tags.find((x) => x[0] === k) || [])[1];
+ const type = tag('call-type') === 'video' ? 'video' : 'voice', status = tag('status') || 'failed', dir = tag('direction') || 'out';
+ const missed = status === 'missed' || (dir === 'in' && status === 'declined');
+ // a call that didn't ring (someone you don't follow), saying so — and,
+ // while that's still so, how to have them ring next time
+ const unrung = tag('rang') === 'no';
+ return h('div', { class: 'chat-row call-log' + (missed ? ' missed' : ''), 'data-call-log': tag('call-id') || '' },
+ h('button', { type: 'button', class: 'call-log-pill', title: t(type === 'video' ? 'callVideo' : 'callVoice'), onClick: () => startCall(peer, type) },
+ callIcon(type === 'video' ? 'video' : 'phone'),
+ h('span', {}, callLogText(dir, type, status, +tag('duration') || 0)),
+ h('span', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000))),
+ unrung ? h('div', { class: 'small faint call-log-why' }, t(mayRing(peer) === 'ring' ? 'callLogUnrungWas' : 'callLogUnrung')) : null);
+ }
+
+ // the call offer a push brought (sw-nwc.js keeps it): rung now, once
+ async function pendingCall() {
+ try {
+ if (typeof caches === 'undefined') return;
+ const cache = await caches.open('coinos-call');
+ // calls the worker saw from people who don't ring us: logged, unrung
+ const quiet = await cache.match('/__quiet-calls');
+ if (quiet) {
+ await cache.delete('/__quiet-calls');
+ for (const offer of (await quiet.json()) || []) {
+ if (!offer || !offer.pubkey || !mayRing(offer.pubkey)) continue;
+ const id = (offer.tags.find((x) => x[0] === 'call-id') || [])[1];
+ const type = (offer.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice';
+ if (id) logCall({ id, peer: offer.pubkey, type, dir: 'in', reason: 'unrung', seconds: 0, at: offer.created_at * 1000 }).catch(() => {});
+ }
+ }
+ const r = await cache.match('/__pending-call');
+ if (!r) return;
+ await cache.delete('/__pending-call');
+ const { offer, at } = await r.json();
+ if (!offer) return;
+ if (Date.now() - at < RING_S * 1000) { await callsNow().handle(offer, { maxAge: RING_S }); return; }
+ // rang while the app was shut, and nobody came: a missed call in the conversation
+ if (mayRing(offer.pubkey)) {
+ const type = (offer.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice';
+ const id = (offer.tags.find((x) => x[0] === 'call-id') || [])[1];
+ if (id) logCall({ id, peer: offer.pubkey, type, dir: 'in', reason: 'missed', seconds: 0, at: offer.created_at * 1000 }).catch(() => {});
+ }
+ } catch {}
+ }
+ // A call with them may be coming (it rings, or their conversation is open):
+ // their relays looked up, TURN fetched — the seconds the first send or
+ // answer used to spend on it. Not through Amber: a prompt to open a chat.
+ const warmed = new Set();
+ function callWarm(pk) {
+ if (!pk || warmed.has(pk)) return;
+ warmed.add(pk);
+ inboxFor(pk).catch(() => {});
+ const login = hook('nostrLoginIdentity');
+ if (!(login && login.signer && login.signer.interactive)) callIce().catch(() => {});
+ }
+ function startCall(peer, type) {
+ if (typeof RTCPeerConnection === 'undefined' || !navigator.mediaDevices?.getUserMedia) { toast(t('callUnsupported')); return; }
+ const cur = callsNow().call;
+ if (cur && cur.state !== 'ended') { ui.callMin = false; render(); return; }
+ ui.callMin = false;
+ callsNow().start(peer, type).catch(() => {});
+ }
+
+ // The ring: a tone (two short bursts every few seconds) and the phone's
+ // buzz for a call coming in, a softer one while ours rings them; and, with
+ // the app out of sight, a notification.
+ let ringCtx = null, ringTimer = null, ringFor = null;
+ function tone(ctx, freqs, at, len, vol) {
+ for (const f of freqs) {
+ const o = ctx.createOscillator(), g = ctx.createGain();
+ o.frequency.value = f; o.connect(g); g.connect(ctx.destination);
+ g.gain.setValueAtTime(0, at); g.gain.linearRampToValueAtTime(vol, at + 0.02); g.gain.setValueAtTime(vol, at + len - 0.05); g.gain.linearRampToValueAtTime(0, at + len);
+ o.start(at); o.stop(at + len + 0.05);
+ }
+ }
+ function callRing() {
+ const c = calls && calls.call;
+ const want = c && (c.state === 'incoming' || c.state === 'offering') ? c.id + ':' + c.state : null;
+ if (want === ringFor) return;
+ ringFor = want;
+ clearInterval(ringTimer); ringTimer = null;
+ try { navigator.vibrate && navigator.vibrate(0); } catch {}
+ // answered, declined or over: its "is calling" notification goes too
+ if (!want || want.endsWith(':offering')) {
+ try { navigator.serviceWorker?.ready.then((r) => r.getNotifications({ tag: 'call' })).then((ns) => { for (const n of ns || []) n.close(); }).catch(() => {}); } catch {}
+ }
+ if (!want) return;
+ const incoming = c.state === 'incoming';
+ const beat = () => {
+ try {
+ ringCtx = ringCtx || new (window.AudioContext || window.webkitAudioContext)();
+ if (ringCtx.state === 'suspended') ringCtx.resume().catch(() => {});
+ const t0 = ringCtx.currentTime + 0.05;
+ if (incoming) { tone(ringCtx, [440, 480], t0, 0.4, 0.12); tone(ringCtx, [440, 480], t0 + 0.6, 0.4, 0.12); }
+ else tone(ringCtx, [440, 480], t0, 1.2, 0.05); // the ringback, heard by the caller
+ } catch {}
+ if (incoming) { try { navigator.vibrate && navigator.vibrate([400, 200, 400]); } catch {} }
+ };
+ beat();
+ ringTimer = setInterval(beat, incoming ? 3000 : 4000);
+ if (incoming && typeof document !== 'undefined' && document.hidden) {
+ try {
+ if (Notification.permission === 'granted') navigator.serviceWorker?.ready.then((r) => r.showNotification(t('callIncomingFrom', { name: displayName(c.peer) }), {
+ body: t(c.type === 'video' ? 'callIncomingVideo' : 'callIncomingVoice'), tag: 'call', renotify: true, requireInteraction: true,
+ })).catch(() => {});
+ } catch {}
+ }
+ }
+
+ // the call's sound and pictures into their elements, after each paint
+ function mountCallMedia() {
+ const c = calls && calls.call;
+ const put = (sel, stream) => {
+ const el = document.querySelector(sel);
+ if (el && stream && el.srcObject !== stream) { el.srcObject = stream; el.play().catch(() => {}); }
+ };
+ if (!c) return;
+ put('audio.call-audio', c.remote);
+ put('video.call-remote', c.remote);
+ put('video.call-local', c.local);
+ }
+ const callReason = (r) => t({ 'no-answer': 'callNoAnswer', 'peer-declined': 'callDeclined', busy: 'callBusy', failed: 'callFailed', error: 'callFailed',
+ 'no-permission': 'callNoPermission', missed: 'callMissed', 'answered-elsewhere': 'callAnsweredElsewhere', 'declined-elsewhere': 'callDeclinedElsewhere' }[r] || 'callEnded');
+ const CALL_ICONS = {
+ phone: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z"/></svg>',
+ video: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 8-6 4 6 4V8z"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>',
+ mic: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0M12 17v5"/></svg>',
+ micOff: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 2 20 20M9 9v1a3 3 0 0 0 5.1 2.1M15 9.3V5a3 3 0 0 0-5.9-.6M17 16.9A7 7 0 0 1 5 10M19 10a7 7 0 0 1-.3 2M12 17v5"/></svg>',
+ camOff: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 2 20 20M16 16v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2m4 0h4a2 2 0 0 1 2 2v3.3l1 1 5-3.3v8"/></svg>',
+ flip: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7h-3l-2-3H9L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><path d="m14 11 2 2-2 2M10 15l-2-2 2-2M8 13h8"/></svg>',
+ screen: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4M9 10l3-3 3 3M12 7v6"/></svg>',
+ hang: '<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 9c-1.6 0-3.2.3-4.6.7v3.1c0 .4-.2.7-.6.9-1 .5-1.9 1.1-2.7 1.8-.2.2-.4.3-.7.3s-.5-.1-.7-.3L.3 13.1c-.2-.2-.3-.4-.3-.7s.1-.5.3-.7C3.3 8.9 7.4 7 12 7s8.7 1.9 11.7 4.7c.2.2.3.4.3.7s-.1.5-.3.7l-2.4 2.4c-.2.2-.4.3-.7.3s-.5-.1-.7-.3c-.8-.7-1.7-1.3-2.7-1.8-.3-.2-.6-.5-.6-.9V9.7C15.2 9.3 13.6 9 12 9z"/></svg>',
+ min: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m4 14 6 0 0 6M20 10l-6 0 0-6M14 10l7-7M3 21l7-7"/></svg>',
+ };
+ const callIcon = (k) => h('span', { style: 'display:flex', html: CALL_ICONS[k] });
+ // The call, over any page: who, how it's going, and its buttons; minimized,
+ // a bar across the top to come back by.
+ function callOverlay() {
+ const c = calls && calls.call;
+ if (!c) return null;
+ queueMicrotask(mountCallMedia);
+ if (c.state === 'connected') setTimeout(scheduleRepaint, 1000); // the clock
+ const video = c.type === 'video';
+ // a picture that's coming (a muted track: they stopped their camera or share)
+ const remoteVideo = video && c.remote && c.remote.getVideoTracks().some((x) => x.readyState === 'live' && !x.muted);
+ const camOn = !!c.local && c.local.getVideoTracks().length > 0;
+ const sound = h('audio', { class: 'call-audio', 'data-key': 'call-audio:' + c.id, autoplay: '' });
+ const status = c.state === 'incoming' ? t(video ? 'callIncomingVideo' : 'callIncomingVoice')
+ : c.state === 'starting' || c.state === 'offering' ? t('callCalling')
+ : c.state === 'connecting' ? t('callConnecting')
+ : c.state === 'connected' ? clockOf((Date.now() - c.connectedAt) / 1000)
+ : callReason(c.reason);
+ if (ui.callMin && c.state !== 'incoming' && c.state !== 'ended') {
+ return h('div', { class: 'call-overlay call-min', 'data-key': 'call-overlay' }, sound,
+ h('button', { class: 'call-min-bar', onClick: () => { ui.callMin = false; render(); } },
+ h('span', { class: 'go-live-dot' }), h('span', { class: 'call-min-name' }, displayName(c.peer)), h('span', { class: 'call-min-status' }, status)));
+ }
+ const btn = (cls, icon, label, onClick, on = false) => h('button', { class: 'call-btn ' + cls + (on ? ' on' : ''), title: label, 'aria-label': label, onClick }, callIcon(icon));
+ return h('div', { class: 'call-overlay' + (remoteVideo && c.state === 'connected' ? ' has-video' : ''), 'data-key': 'call-overlay' },
+ sound,
+ video ? h('video', { class: 'call-remote', 'data-key': 'call-remote:' + c.id, autoplay: '', playsinline: '', muted: '' }) : null,
+ h('div', { class: 'call-who' },
+ avatar(c.peer, 'chat-avatar profile-avatar call-avatar', false),
+ h('div', { class: 'call-name' }, displayName(c.peer)),
+ h('div', { class: 'call-status' }, status)),
+ video && c.local && c.local.getVideoTracks().length ? h('video', { class: 'call-local' + (c.facing === 'user' && !c.sharing ? ' mirror' : '') + (c.sharing ? ' sharing' : ''), 'data-key': 'call-local:' + c.id, autoplay: '', playsinline: '', muted: '' }) : null,
+ c.state === 'incoming'
+ ? h('div', { class: 'call-bar' },
+ btn('call-decline', 'hang', t('callDecline'), () => callsNow().reject()),
+ btn('call-accept', video ? 'video' : 'phone', t('callAccept'), () => callsNow().accept()))
+ : c.state === 'ended' ? null
+ : h('div', { class: 'call-bar' },
+ btn('', c.muted ? 'micOff' : 'mic', t(c.muted ? 'callUnmute' : 'callMute'), () => callsNow().setMuted(!c.muted), c.muted),
+ // a camera in the call: off/on and flip; none yet (a voice call, or
+ // theirs came on first): one tap puts ours in
+ camOn ? btn('', c.camOff ? 'camOff' : 'video', t(c.camOff ? 'callCamOn' : 'callCamOff'), () => callsNow().setCamOff(!c.camOff), c.camOff) : null,
+ camOn && !c.sharing ? btn('', 'flip', t('callFlip'), () => callsNow().flip()) : null,
+ !camOn && c.state === 'connected' ? btn('call-add-video', 'video', t('callAddVideo'), () => callsNow().addVideo()) : null,
+ // a browser that can share its screen (desktops; not phones' Chrome)
+ c.state === 'connected' && navigator.mediaDevices?.getDisplayMedia
+ ? btn('call-share', 'screen', t(c.sharing ? 'callStopShare' : 'callShare'), () => (c.sharing ? callsNow().stopShare() : callsNow().shareScreen()), !!c.sharing) : null,
+ btn('', 'min', t('callMinimize'), () => { ui.callMin = true; render(); }),
+ btn('call-hang', 'hang', t('callHangUp'), () => callsNow().hangup())));
+ }
+
// A quote inside a quote: one line of who and what, never a third level
// of cards (a bare "view note" link said nothing about where it leads).
function quoteMini(ref) {
@@ -8385,6 +11038,7 @@ export function messagesFeature(ctx) {
// opens the thread — not on the picture.
function onPicture(e) {
const el = e.currentTarget;
+ if (el.closest('.note-gallery')) return true; // a gallery tile is all picture (cropped to fill)
const r = el.getBoundingClientRect();
const nw = el.naturalWidth, nh = el.naturalHeight;
if (!nw || !nh || !r.width || !r.height) return true;
@@ -8393,7 +11047,7 @@ export function messagesFeature(ctx) {
const x = e.clientX - (r.left + (r.width - w) / 2), y = e.clientY - (r.top + (r.height - hh) / 2);
return x >= 0 && x <= w && y >= 0 && y <= hh;
}
- function urlNode(url, { label = null, isImage = false } = {}) {
+ function urlNode(url, { label = null, isImage = false, shown: written = null } = {}) {
if (isVideoUrl(url)) {
return videoNode(url, { stable: !!feedPaint });
}
@@ -8415,9 +11069,9 @@ export function messagesFeature(ctx) {
// height-capped: see .note-img)
const known = size || mediaReady.get(url);
return h('img', {
- src: mediaSrc(url, known), class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '',
+ src: mediaSrc(url, known), 'data-pic': url, class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '',
// a few-ms decode of the copy paints with the page; an original never holds the page for its decode
- decoding: known && known.thumb ? 'sync' : 'async',
+ decoding: known && known.thumb && !/\.gif(\?|$)/i.test(url) ? 'sync' : 'async', // (a looped GIF's copy is the whole animation)
width: size?.width, height: size?.height,
style: size ? 'height:auto;aspect-ratio:' + size.width + '/' + size.height + ';--ar:' + (size.width / size.height).toFixed(4) : undefined,
onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); },
@@ -8427,6 +11081,22 @@ export function messagesFeature(ctx) {
});
}
if (youtubeId(url)) return youtubeEmbed(url, youtubeId(url));
+ if (!label && paffMusicUrl(url)) {
+ let pv = previews.get(url) || null;
+ if (feedPaint) {
+ if (!feedPaint.media.has('pv:' + url)) feedPaint.media.set('pv:' + url, pv);
+ pv = feedPaint.media.get('pv:' + url);
+ }
+ return paffSongCard(url, pv);
+ }
+ if (!label && paffEmbedUrl(url)) {
+ let pv = previews.get(url) || null;
+ if (feedPaint) {
+ if (!feedPaint.media.has('pv:' + url)) feedPaint.media.set('pv:' + url, pv);
+ pv = feedPaint.media.get('pv:' + url);
+ }
+ return paffEmbed(url, pv);
+ }
if (!label && previewable(url)) {
// a frozen feed row keeps the card (or the bare link) it first painted
let pv = previews.get(url) || null;
@@ -8436,7 +11106,8 @@ export function messagesFeature(ctx) {
}
if (pv) return linkCard(url, pv);
}
- const shown = label || (url.length > 64 ? url.slice(0, 61) + '…' : url);
+ const text = written || url;
+ const shown = label || (text.length > 64 ? text.slice(0, 61) + '…' : text);
return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, shown);
}
@@ -8458,6 +11129,7 @@ export function messagesFeature(ctx) {
h('span', { class: 'note-audio-ico', 'aria-hidden': 'true' }, '\u{1F3A7}'),
h('a', { href: url, target: '_blank', rel: 'noopener noreferrer', class: 'small muted note-audio-name' }, name)),
h('audio', {
+ onLoadedmetadata: e => attachMediaTimeline(e.target, url),
controls: true, preload: 'none', src: url,
onPlay: (e) => { const box = e.target.closest('.note-audio'); if (box) box._skipMorph = true; },
}));
@@ -8582,7 +11254,7 @@ export function messagesFeature(ctx) {
// key and 16-byte nonce per file, the ciphertext uploaded as an opaque
// blob, the key riding inside the (already encrypted) message. The media
// host never sees a picture. coinos's own Blossom server stores only sync
- // envelopes, so these go to public hosts that take anonymous blobs.
+ // envelopes, so these go to the configured media hosts or public defaults.
const MEDIA_SERVERS = ['https://blossom.ditto.pub', 'https://nostr.download', 'https://blossom.yakihonne.com'];
const MEDIA_MAX = 20 * 1024 * 1024;
async function encryptFile(file) {
@@ -8609,7 +11281,7 @@ export function messagesFeature(ctx) {
const auth = id.signer instanceof Uint8Array ? finalizeEvent(evt, id.signer) : await id.signer.signEvent(evt);
const header = 'Nostr ' + btoa(JSON.stringify(auth));
const urls = [];
- for (const server of MEDIA_SERVERS) {
+ for (const server of mediaServers(MEDIA_SERVERS)) {
try {
const r = await fetch(server + '/upload', {
method: 'PUT', body: enc.cipher, signal: AbortSignal.timeout(60_000),
@@ -8781,6 +11453,18 @@ export function messagesFeature(ctx) {
} else if (/^https?:\/\//i.test(part)) {
const pack = PACK_LINK_RE.exec(part);
out.push(pack ? packLinkNode(part, pack[1]) : urlNode(part));
+ } else if (bareLink(part)) {
+ const { url, text, tail } = bareLink(part);
+ out.push(urlNode(url, { shown: text }));
+ if (tail) out.push(tail);
+ } else if (/^wss?:\/\//i.test(part)) {
+ // a relay named in a post opens what's on it (the raw firehose)
+ const [, addr, tail] = /^(.*?)([.,;:!?)\]'"]*)$/.exec(part);
+ const relay = normRelay(addr);
+ out.push(relay ? h('a', {
+ href: '/feed/all?r=' + encodeURIComponent(relay), title: t('relayLinkOpen'),
+ onClick: (e) => { e.preventDefault(); e.stopPropagation(); openFeedUrl('all', '?r=' + encodeURIComponent(relay)); },
+ }, addr) : addr, tail);
} else if (/^(nostr:|@?)(npub|nprofile)1/i.test(part)) {
const bare = part.replace(/^(nostr:|@)/i, '');
const ref = parseNostrRef(bare);
@@ -8799,7 +11483,7 @@ export function messagesFeature(ctx) {
const ref = parseNostrRef(part.slice(6));
if (ref && ref.type === 'addr' && !depth) out.push(addrCard(ref));
else if (ref && ref.type === 'addr') out.push(h('a', {
- href: '#', onClick: (e) => { e.preventDefault(); e.stopPropagation(); const c = addrNote(ref); if (c.ev) openNoteThread(c.ev); },
+ href: '#', onClick: (e) => { e.preventDefault(); e.stopPropagation(); if (ref.kind === LIVE_KIND) { openLiveRef(ref); return; } const c = addrNote(ref); if (c.ev) openNoteThread(c.ev); },
}, t('noteRefLink')));
else out.push(h('span', { class: 'faint' }, part.slice(6, 18) + '…'));
} else if (/^nostr:/i.test(part)) {
@@ -8807,7 +11491,9 @@ export function messagesFeature(ctx) {
} else if (/^@[A-Za-z0-9_]{2,32}$/.test(part)) {
out.push(h('a', {
href: '#', title: t('searchPeopleFor', { q: part.slice(1) }),
- onClick: (e) => { e.preventDefault(); e.stopPropagation(); openPeopleSearch(part.slice(1)); },
+ // the one person you follow by that name is who it means; anyone
+ // else is a search
+ onClick: (e) => { e.preventDefault(); e.stopPropagation(); const pk = followNamed(part.slice(1)); if (pk) openProfile(pk); else openPeopleSearch(part.slice(1)); },
}, part));
} else if (/^#[A-Za-z0-9_\u00C0-\uFFFF]{2,64}$/.test(part)) {
out.push(h('a', {
@@ -8818,12 +11504,45 @@ export function messagesFeature(ctx) {
for (const p of splitEmoji(part, emojiAt)) out.push(...(typeof p === 'string' ? mdInline(p) : [emojiImg(p.code, p.url)]));
} else out.push(...mdInline(part));
}
+ return pictureRuns(out);
+ }
+ // Two or more pictures in a row (only blank space between them) share one
+ // box of justified rows, the way the Images feed lays them out, instead of
+ // a screen each: a post of thirteen photos was thirteen screens to scroll
+ // past ("could we put them into a masonry grid layout within the post kinda
+ // like we do on our images feed", Adam, 2026-11-18). A tap still opens the
+ // picture in the pager, with the rest a swipe away.
+ const isNoteImg = (n) => !!n && n.nodeType === 1 && n.tagName === 'IMG' && n.classList.contains('note-img');
+ function pictureRuns(nodes) {
+ const out = [];
+ for (let i = 0; i < nodes.length; i++) {
+ if (!isNoteImg(nodes[i])) { out.push(nodes[i]); continue; }
+ const run = [nodes[i]];
+ let j = i + 1, last = i;
+ for (; j < nodes.length; j++) {
+ const n = nodes[j];
+ if (isNoteImg(n)) { run.push(n); last = j; continue; }
+ if (typeof n === 'string' && !n.trim()) continue;
+ break;
+ }
+ if (run.length < 2) { out.push(nodes[i]); continue; }
+ // A tile is painted from the Images feed's tile copy (360px, cut with a
+ // proper resize), not the 1100px column copy: shrunk eight times by the
+ // browser, that came out grainy (Adam, 2026-11-18).
+ for (const img of run) {
+ const url = img.getAttribute('data-pic'), tile = url && tileThumbs.get(url);
+ if (tile) img.setAttribute(img.hasAttribute('data-lazy-src') ? 'data-lazy-src' : 'src', tile);
+ else if (url && /^https?:/i.test(url)) queueTileThumbs([url]);
+ }
+ out.push(h('div', { class: 'note-gallery' }, ...run));
+ i = last;
+ }
return out;
}
// The header magnifier's search, opened with a name already typed.
function openPeopleSearch(q) {
- ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null;
+ ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
ui.userSearch = { q, rows: null };
warmSearch();
userSearcher.update(q);
@@ -8854,15 +11573,15 @@ export function messagesFeature(ctx) {
ui.screen = 'accounts';
render();
}
- function zapNote(pk, ev, origin) {
+ function zapNote(pk, ev, origin, moment = null) {
const npubStr = npubOf(pk);
const def = ctx.zapDefaultSat ? ctx.zapDefaultSat() : 0;
if (!def) { // the first tap ever sets the amount; the reader's place is kept for the way back
let scrollY = 0; try { scrollY = window.scrollY || 0; } catch {}
- ui.zapSetup = { pk, npub: npubStr, eventId: ev.id, amount: '21', origin, scrollY }; render(); return;
+ ui.zapSetup = { pk, npub: npubStr, eventId: ev.id, amount: '21', origin, scrollY, moment }; render(); return;
}
markZapPending(ev.id, def, origin); // strike now; settlement only corrects the tally
- if (!hook('zapNpub', pk, npubStr, ev.id, def) && !hook('lnZapNpub', pk, npubStr, ev.id, def)) {
+ if (!hook('zapNpub', pk, npubStr, ev.id, def, moment) && !hook('lnZapNpub', pk, npubStr, ev.id, def, moment)) {
settleZap(ev.id, false);
toast('⚡ ' + t('lnZapFailed'), 4000);
}
@@ -8904,7 +11623,7 @@ export function messagesFeature(ctx) {
const { pk, npub, eventId } = s;
closeZapSetup();
markZapPending(eventId, n, s.origin);
- if (!hook('zapNpub', pk, npub, eventId, n) && !hook('lnZapNpub', pk, npub, eventId, n)) {
+ if (!hook('zapNpub', pk, npub, eventId, n, s.moment) && !hook('lnZapNpub', pk, npub, eventId, n, s.moment)) {
settleZap(eventId, false);
toast('⚡ ' + t('lnZapFailed'), 4000);
}
@@ -8958,13 +11677,18 @@ export function messagesFeature(ctx) {
// A like is kind 7 on the note (NIP-25). Tapping it again withdraws it the
// only way nostr has: a deletion request for the reaction we sent.
// Reply: open (or re-aim) the thread and put the cursor in the box.
- function replyToNote(ev) {
+ function replyToNote(ev, moment = null) {
+ // the post opened from a clip as it played: a reply to it is about that moment
+ const offered = ui.noteThread && ui.noteThread.momentFor;
+ if (!moment && offered && offered.id === ev.id) moment = offered.moment;
if (ui.noteThread && ui.noteThread.rootId === rootIdOf(ev)) {
ui.noteThread.focusId = ev.id;
ui.noteThread.seed = ev;
} else ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev };
const s = ui.noteThread;
ui.profOverThread = false;
+ s.momentOffer = moment; // offered, not taken: the toggle in the box ties it
+ s.mediaMoment = null;
s.replying = true; // the box appears under this note
s.scrollPending = false; // focus the composer, without a competing note scroll
s.refocus = true;
@@ -9108,7 +11832,7 @@ export function messagesFeature(ctx) {
const id = await requireIdentity();
const partial = {
kind: 7, content: emoji || '❤️', created_at: Math.floor(Date.now() / 1000),
- tags: [['e', ev.id], ['p', ev.pubkey], ...reactEmojiTags(emoji), CLIENT_TAG],
+ tags: [['e', ev.id], ['p', ev.pubkey], ...momentTags(ev.mediaMoment), ...reactEmojiTags(emoji), CLIENT_TAG],
};
const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
myReactEv.set(ev.id, evt.id);
@@ -9123,13 +11847,26 @@ export function messagesFeature(ctx) {
if (iBoosted(ev.id)) { toast(t('postBoostedAlready')); return; }
const id = await requireIdentity();
const relays = await noteRelaysFor(ev);
+ // The copy inside must carry its author's signature, or every client
+ // that checks it (this one too) throws the boost away. A post painted
+ // from the saved feed was stored without one: fetch it whole first.
+ let whole = ev.sig && verifyEvent({ ...ev }) ? ev : null;
+ if (!whole) {
+ const got = await queryOn([...new Set([...relays, ...NOTE_RELAYS])], { ids: [ev.id] }, 4000).catch(() => []);
+ whole = got.find((e) => e.id === ev.id && e.sig && verifyEvent(e)) || null;
+ }
+ if (!whole) { toast(t('msgSendFailed')); return; }
+ whole = { id: whole.id, pubkey: whole.pubkey, created_at: whole.created_at, kind: whole.kind, tags: whole.tags, content: whole.content, sig: whole.sig };
const partial = {
- kind: 6, content: JSON.stringify(ev), created_at: Math.floor(Date.now() / 1000),
+ kind: 6, content: JSON.stringify(whole), created_at: Math.floor(Date.now() / 1000),
tags: [['e', ev.id, relays[0] || '', 'mention'], ['p', ev.pubkey], CLIENT_TAG],
};
const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
noteEvent(evt);
render();
+ // in the feeds that carry your posts now, as your own post is
+ const carries = (def) => !!def && !def.replies && (!!def.all || feedAuthors(def).includes(id.pubkey));
+ for (const c of new Set([feed, feedStates.get(FOLLOWING)])) if (c && !c.stopped && carries(feedDef(c.id))) mergeFeed([evt], {}, c).catch(() => {});
const ok = await publishOn(relays, evt);
toast(ok ? t('postBoosted') : t('msgSendFailed'));
}
@@ -9144,7 +11881,7 @@ export function messagesFeature(ctx) {
const next = (cur ? cur + '\n\n' : '') + ref;
ui.profCompose = next;
setDraft(POST_DRAFT, next);
- ui.noteThread = null;
+ ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
ui.profilePk = null;
ui.chatOpen = true;
ui.msgView = 'feed';
@@ -9370,6 +12107,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));
@@ -9399,10 +12140,14 @@ export function messagesFeature(ctx) {
function noteReport(ev) { indexReport(reportsNow(), ev, myPubkeys().includes(ev.pubkey)); }
function indexReport(r, ev, mine) {
const hex = (v) => /^[0-9a-f]{64}$/.test(v || '');
+ // every post named counts toward es, the 'other' ones too: a report
+ // of a post as 'other' with its author's p tag beside it used to have
+ // es = 0 and land on the AUTHOR as a person report
let es = 0;
for (const x of ev.tags || []) {
- if (x[0] !== 'e' || !hex(x[1]) || x[2] === 'other') continue;
+ if (x[0] !== 'e' || !hex(x[1])) continue;
es++;
+ if (x[2] === 'other') continue;
(r.ev.get(x[1]) || r.ev.set(x[1], new Set()).get(x[1])).add(ev.pubkey);
if (mine) r.mine.add(x[1]);
}
@@ -9416,10 +12161,16 @@ export function messagesFeature(ctx) {
}
}
const REPORTS_MS = 30 * 60_000;
+ // The half hour counts from the last sync the device SAVED, so a reload
+ // (every open of the installed app is one) doesn't ask the outbox relays
+ // again — some forty REQs with every follow's reports — and a sync after
+ // one asks only for what came since. (The index is kept.)
async function syncReports({ force = false } = {}) {
if (!modOn('reports') || !myPubkeys().length) return;
- if (!force && Date.now() - reportsAt < REPORTS_MS) return;
+ const last = Math.max(reportsAt, reportsNow().at || 0);
+ if (!force && Date.now() - last < REPORTS_MS) return;
reportsAt = Date.now();
+ const since = last ? { since: Math.floor(last / 1000) - 3600 } : {};
const authors = [...new Set([...myPubkeys(), ...followsNow().set])].slice(0, FEED_AUTHORS_MAX);
const from = new Set(authors);
try {
@@ -9428,7 +12179,7 @@ export function messagesFeature(ctx) {
const got = await Promise.all(plan.flatMap(({ relays, authors: a }) => {
const chunks = [];
for (let i = 0; i < a.length; i += REQ_AUTHORS) chunks.push(a.slice(i, i + REQ_AUTHORS));
- return chunks.map((chunk) => queryOn(relays, { kinds: [1984], authors: chunk, limit: 500 }, 5000).catch(() => []));
+ return chunks.map((chunk) => queryOn(relays, { kinds: [1984], authors: chunk, limit: 500, ...since }, 5000).catch(() => []));
}));
for (const ev of got.flat()) if (ev && ev.kind === 1984 && from.has(ev.pubkey)) noteReport(ev);
reportsNow().at = Date.now();
@@ -10068,8 +12819,16 @@ export function messagesFeature(ctx) {
const rm = reacts.get(ev.id);
const cached = ui.noteThread
? threadCache.get(ui.noteThread.rootId)?.counts?.[ev.id] : null;
- const likeN = cached ? cached.likes : rm ? [...rm.values()].reduce((n, { who }) => n + visiblePks(who).length, 0) : 0;
- const boostN = cached ? cached.boosts : visiblePks(boosts.get(ev.id) || new Set()).length;
+ // A thread remembers its counts between visits, so a short relay answer
+ // can't erase them — but what the relays HAVE brought since (a heart
+ // the feed's own count fetch tallied before this visit) outranks the
+ // memory: the number says what the who-panel below it lists. "Why does
+ // the count beside the heart say 1 if I have 2 heart reactions?"
+ // (Adam, 2026-11-02): the memory said 1, the tally in hand 2.
+ const liveLikes = rm ? [...rm.values()].reduce((n, { who }) => n + visiblePks(who).length, 0) : 0;
+ const liveBoosts = visiblePks(boosts.get(ev.id) || new Set()).length;
+ const likeN = cached ? Math.max(cached.likes || 0, liveLikes) : liveLikes;
+ const boostN = cached ? Math.max(cached.boosts || 0, liveBoosts) : liveBoosts;
const btn = (icon, label, count, on, onClick, cls = '', extra = null) => h('button', {
class: 'note-act' + (on ? ' on' : '') + (cls ? ' ' + cls : ''), title: label, 'aria-label': label,
'aria-disabled': onClick ? undefined : 'true',
@@ -10085,20 +12844,20 @@ export function messagesFeature(ctx) {
const z = zapTotals.get(ev.id) || zapSeeds().get(ev.id);
const zp = pendingOf(ev.id);
const optimistic = zp ? zp.sats : 0;
- const zapSats = (cached ? cached.sats : z ? z.sats : 0) + optimistic;
+ const zapSats = Math.max(cached ? cached.sats || 0 : 0, z ? z.sats : 0) + optimistic;
const zapFlying = !!zp && zp.flying;
// tap pays the default amount; hold opens the screen that sets it
const zapHold = canZap ? holdable((el) => openZapSettings(pk, ev.id, el.getBoundingClientRect()),
- (e) => { zapNote(pk, ev, e.currentTarget.getBoundingClientRect()); recheckZap(ev.id); }) : null;
+ (e) => { zapNote(pk, ev, e.currentTarget.getBoundingClientRect(), momentOf(ev)); recheckZap(ev.id); }) : null;
const zapMine = !!((z && z.mine) || optimistic);
const zapLabel = zapFlying ? t('zapSending') : zapSats ? t('zapTallyTitle', { n: zapSats.toLocaleString() }) : t('zapTitle');
return h('div', { class: 'row note-acts' },
- btn(I_REPLY, t('msgReply'), replyCount(ev.id), false, () => { if (!signinAsk()) replyToNote(ev); }),
+ btn(I_REPLY, t('msgReply'), replyCount(ev.id), false, () => { if (!signinAsk()) replyToNote(ev, momentOf(ev)); }),
btn(I_BOOST, t('postBoost'), boostN, iBoosted(ev.id), () => boostNote(ev).catch(() => {})),
btn(I_QUOTE, t('postQuote'), 0, false, () => { if (!signinAsk()) quoteNote(ev); }),
// tap to choose how you feel about it; tap again to take it back
btn(mineReact ? postReactNode(mineReact) : I_HEART(false), t('postLike'), likeN, !!mineReact,
- () => { if (signinAsk()) return; if (mineReact) unreact(ev).catch(() => {}); else { ui.reactPick = ev; render(); } }),
+ () => { if (signinAsk()) return; if (mineReact) unreact(ev).catch(() => {}); else { ui.reactPick = withMoment(ev); render(); } }),
// always in the bar — the same row of buttons on every post, so nothing
// shifts when a wallet comes online; without one it is just the number
btn(I_ZAP, zapLabel, zapSats ? fmtSats(zapSats) : 0, zapMine,
@@ -10179,6 +12938,8 @@ export function messagesFeature(ctx) {
},
h('div', { class: 'card col msg-sheet' },
reactRow(null, (e2) => { close(); reactTo(ev, e2).catch(() => {}).finally(after); setTimeout(after, 50); }),
+ ev.momentOffer ? h('div', { class: 'row', style: 'justify-content:center' },
+ momentToggle(h, ev.momentOffer, !!ev.mediaMoment, (on) => { ev.mediaMoment = on ? ev.momentOffer : null; render(); }, tieLabel(ev.momentOffer))) : null,
h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
}
@@ -10217,6 +12978,11 @@ export function messagesFeature(ctx) {
const altText = foreign ? ((ev.tags.find((x) => x[0] === 'alt') || [])[1] || t('noteForeignKind', { kind: ev.kind })) : null;
const isReply = ev.kind === COMMENT || (!foreign && !zapRec && ev.tags.some((x) => x[0] === 'e'));
const parent = context && !foreign && !zapRec ? parentRefOf(ev) : null;
+ // A NIP-22 comment on something that isn't an event — a web page (I
+ // tag: DaddyTube comments on a film's IMDb page) — has no post to show
+ // above it; the page it is on goes there instead, named by the
+ // comment's own alt tag when it carries one, else by the address.
+ const scope = ev.kind === COMMENT && !parent && !(ev.tags || []).some((x) => (x[0] === 'e' || x[0] === 'E') && x[1]) ? webScopeOf(ev) : null;
const canZap = canZapPk(pk);
// an optimistic post mid-publish: visible but not yet a real event —
// dimmed, and no thread/reply/zap until its signed self takes over
@@ -10259,6 +13025,9 @@ export function messagesFeature(ctx) {
parent ? h('div', { class: 'note-context', 'data-context-of': parent.id },
h('div', { class: 'small faint note-context-label' }, '\u21a9 ' + t('noteReplyingTo')),
quoteCard(parent, 0)) : null,
+ scope ? h('div', { class: 'note-context note-scope' },
+ h('a', { class: 'small faint note-context-label', href: scope.url, target: '_blank', rel: 'noopener noreferrer', onClick: (e) => e.stopPropagation() },
+ '\u{1F4AC} ' + scope.label)) : null,
h('div', { class: 'row between note-header', style: 'align-items:center;gap:8px' },
h('div', { class: 'row', style: 'gap:7px;align-items:baseline;min-width:0' },
h('span', {
@@ -10268,7 +13037,7 @@ export function messagesFeature(ctx) {
onClick: (e) => { e.stopPropagation(); openProfile(pk); },
}, name),
h('span', { class: 'small faint', style: 'white-space:nowrap' },
- (isReply && !parent ? '↩ ' + t('profReplyTag') + ' · ' : '') + timeLabel(ev.created_at * 1000)
+ (isReply && !parent && !scope ? '↩ ' + t('profReplyTag') + ' · ' : '') + timeLabel(ev.created_at * 1000)
+ (edited ? ' · ' + t('postEditedTag') : ''))),
pending ? null : h('button', {
// the overflow stays up here; reply, boost, quote, react and zap
@@ -10283,7 +13052,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)))),
+ : 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 }),
@@ -10520,6 +13291,7 @@ export function messagesFeature(ctx) {
}
function openNoteThread(ev) {
rememberPlace('thread');
+ ui.liveStream = null;
ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev, scrollPending: true };
ui.profOverThread = false; // a freshly opened thread goes on top
render();
@@ -10543,12 +13315,25 @@ export function messagesFeature(ctx) {
// at the top of the feed before any signing or relay round-trip (a remote
// signer alone can take seconds), swapped for the signed event on success
// and withdrawn on failure.
+ // the hashtags in the text as t tags (NIP-24), so topic feeds and other
+ // clients' searches find the post — up to the count past which a post
+ // reads as hashtag spam
+ const postHashtags = (text) => [...new Set([...String(text || '').matchAll(/(^|[^\w#/&])#([\p{L}\p{N}_]{2,64})(?![\w])/gu)].map((m) => normTopic(m[2])))].slice(0, HASHTAG_MAX);
+ function postTags(text, media, me) {
+ // NIP-92: what we uploaded, described, so clients needn't sniff the URL
+ const imeta = media.filter((m) => m && m.url).map(mediaImeta);
+ // NIP-18 quote: the reference is already in the text; the tags let a
+ // client render the quoted post inline and tell its author
+ const q = ui.quoteOf && text.includes(ui.quoteOf.id.slice(0, 8))
+ ? [] : ui.quoteOf ? [['q', ui.quoteOf.id], ['p', ui.quoteOf.pubkey]] : [];
+ // the people it mentions are told (NIP-27 p tags)
+ const mentions = mentionedPks(text).filter((pk) => pk !== me && !q.some((x) => x[0] === 'p' && x[1] === pk)).map((pk) => ['p', pk]);
+ return [...imeta, ...q, ...mentions, ...postHashtags(text).map((x) => ['t', x]), CLIENT_TAG];
+ }
async function publishPost(text, media = []) {
const id = await requireIdentity();
- // the hashtags in the text as t tags (NIP-24), so topic feeds and other
- // clients' searches find the post — up to the count past which a post
- // reads as hashtag spam
- const hashtags = [...new Set([...String(text || '').matchAll(/(^|[^\w#/&])#([\p{L}\p{N}_]{2,64})(?![\w])/gu)].map((m) => normTopic(m[2])))].slice(0, HASHTAG_MAX);
+ text = linkNamed(text);
+ const hashtags = postHashtags(text);
const temp = {
id: 'pending:' + Math.random().toString(36).slice(2),
pubkey: id.pubkey, content: text, created_at: Math.floor(Date.now() / 1000),
@@ -10567,15 +13352,7 @@ export function messagesFeature(ctx) {
for (const c of feeds) c.notes = [temp, ...c.notes];
render();
try {
- // NIP-92: what we uploaded, described, so clients needn't sniff the URL
- const imeta = media.filter((m) => m && m.url).map(mediaImeta);
- // NIP-18 quote: the reference is already in the text; the tags let a
- // client render the quoted post inline and tell its author
- const q = ui.quoteOf && text.includes(ui.quoteOf.id.slice(0, 8))
- ? [] : ui.quoteOf ? [['q', ui.quoteOf.id], ['p', ui.quoteOf.pubkey]] : [];
- // the people it mentions are told (NIP-27 p tags)
- const mentions = mentionedPks(text).filter((pk) => pk !== id.pubkey && !q.some((x) => x[0] === 'p' && x[1] === pk)).map((pk) => ['p', pk]);
- const partial = { kind: 1, content: text, created_at: temp.created_at, tags: [...imeta, ...q, ...mentions, ...temp.tags, CLIENT_TAG] };
+ const partial = { kind: 1, content: text, created_at: temp.created_at, tags: postTags(text, media, id.pubkey) };
const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
const relays = [...new Set([...(await notesRelays(id.pubkey)), ...wallet.nostrRelays()])];
const ok = await publishOn(relays, evt);
@@ -10591,8 +13368,97 @@ export function messagesFeature(ctx) {
}
}
+ // ---- scheduled posts -----------------------------------------------------
+ // Signed now, with created_at = when it should appear, and handed to the
+ // notifier, which holds it and publishes it then (relays refuse notes from
+ // the future). Signing now means a remote signer is asked while you're
+ // here, and the note that goes out is exactly the one you wrote. This
+ // device remembers what it scheduled, to show and cancel; the post itself
+ // turns up in the feeds once it's out.
+ const SCHED_MIN_AHEAD = 120;
+ async function schedulePost(text, media, at) {
+ const id = await requireIdentity();
+ text = linkNamed(text);
+ if (!(at > Math.floor(Date.now() / 1000) + SCHED_MIN_AHEAD)) throw new Error(t('schedTooSoon'));
+ const partial = { kind: 1, content: text, created_at: at, tags: postTags(text, media, id.pubkey) };
+ const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ const relays = [...new Set([...(await notesRelays(id.pubkey)), ...wallet.nostrRelays()])];
+ const res = await fetch(`${NOTIFIER}/schedule`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ event: evt, relays }),
+ }).then((r) => r.json()).catch(() => ({ error: t('msgSendFailed') }));
+ if (!res.ok) throw new Error(res.error || t('msgSendFailed'));
+ ui.quoteOf = null;
+ const s = st();
+ s.scheduled ||= {};
+ s.scheduled[evt.id] = { at, text, pubkey: id.pubkey };
+ save(s);
+ render();
+ return evt;
+ }
+ // what this account has waiting, soonest first; anything past its time
+ // has gone out (or the notifier gave up) and leaves the list
+ function scheduledPosts() {
+ const s = st(), me = mePk(), now = Math.floor(Date.now() / 1000);
+ let dropped = false;
+ for (const [k, v] of Object.entries(s.scheduled || {})) if (v.at < now - 60) { delete s.scheduled[k]; dropped = true; }
+ if (dropped) save(s);
+ return Object.entries(s.scheduled || {}).filter(([, v]) => v.pubkey === me)
+ .map(([id, v]) => ({ id, ...v })).sort((a, b) => a.at - b.at);
+ }
+ // once a session, ask which are still held: one cancelled on another
+ // device is gone from the notifier, so it goes from here too
+ let schedChecked = false;
+ function checkScheduled(list) {
+ if (schedChecked || !list.length) return;
+ schedChecked = true;
+ fetch(`${NOTIFIER}/schedule/status?ids=${list.map((x) => x.id).join(',')}`).then((r) => r.json()).then((st_) => {
+ const s = st();
+ let n = 0;
+ for (const [k, v] of Object.entries(st_ || {})) if (v === 'gone' && s.scheduled?.[k]) { delete s.scheduled[k]; n++; }
+ if (n) { save(s); render(); }
+ }).catch(() => {});
+ }
+ async function cancelScheduled(item) {
+ const id = await requireIdentity();
+ const partial = { kind: 5, content: '', created_at: Math.floor(Date.now() / 1000), tags: [['e', item.id]] };
+ const del = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
+ const res = await fetch(`${NOTIFIER}/schedule/cancel`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ event: del }),
+ }).then((r) => r.json()).catch(() => ({}));
+ if (!res.ok) throw new Error(res.error || t('msgSendFailed'));
+ const s = st();
+ delete s.scheduled?.[item.id];
+ save(s);
+ render();
+ }
+ const schedWhen = (at) => new Date(at * 1000).toLocaleString(undefined, { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+ // <input type=datetime-local> speaks local wall-clock time
+ const localInput = (ms) => { const d = new Date(ms); d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); return d.toISOString().slice(0, 16); };
+ function scheduledList() {
+ const list = scheduledPosts();
+ checkScheduled(list);
+ if (!list.length) return null;
+ return h('div', { class: 'card col sched-list', 'data-key': 'sched-list', style: 'gap:8px' },
+ h('div', { class: 'small muted' }, t('schedListTitle', { n: list.length })),
+ ...list.map((x) => h('div', { class: 'row gap6 sched-item', 'data-key': 'sched:' + x.id, style: 'align-items:flex-start' },
+ h('div', { class: 'col grow', style: 'min-width:0;gap:2px' },
+ h('div', { class: 'small', style: 'font-weight:600' }, '\u{1F552} ' + schedWhen(x.at)),
+ h('div', { class: 'small muted', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, x.text)),
+ h('button', {
+ class: 'btn-ghost btn-sm', disabled: ui.schedCancelling === x.id,
+ onClick: async () => {
+ ui.schedCancelling = x.id; render();
+ try { await cancelScheduled(x); toast(t('schedCancelled')); }
+ catch (e) { if (!e.silent) toast(e.message || String(e)); }
+ ui.schedCancelling = null; render();
+ },
+ }, ui.schedCancelling === x.id ? h('span', { class: 'spinner sm' }) : t('cancel')))));
+ }
+
async function publishReply(c, s, text) {
const id = await requireIdentity();
+ text = linkNamed(text);
const target = c.replies.find((e) => e.id === s.focusId) || c.root || s.seed;
const rootId = c.rootId;
const pTags = [...new Set([
@@ -10636,6 +13502,8 @@ export function messagesFeature(ctx) {
CLIENT_TAG,
],
};
+ note.tags.push(...momentTags(s.mediaMoment));
+ if (s.mediaMoment) note.content = '[' + mediaClock(s.mediaMoment.seconds) + '] ' + note.content;
const evt = id.signer instanceof Uint8Array ? finalizeEvent(note, id.signer) : await id.signer.signEvent(note);
const relays = [...new Set([...(await notesRelays(target.pubkey)), ...wallet.nostrRelays()])];
const ok = await publishOn(relays, evt);
@@ -10702,6 +13570,9 @@ export function messagesFeature(ctx) {
class: 'col thread-reply' + (joined ? ' joined' : ''),
style: 'gap:8px;margin:0 -8px;padding:' + (joined ? '2px' : '8px') + ' 8px 10px;background:var(--accent-soft,rgba(128,128,128,.08));border-radius:' + (joined ? '0 0 8px 8px' : '8px'),
},
+ // the moment of the clip this reply is about, and a way to make it about the whole post
+ s.momentOffer ? h('div', { class: 'row' },
+ momentToggle(h, s.momentOffer, !!s.mediaMoment, (on) => { s.mediaMoment = on ? s.momentOffer : null; render(); }, tieLabel(s.momentOffer))) : null,
s.preview ? draftPreview(s.draft) : null,
mediaBar(),
// A textarea that grows with the reply, like the chat composer: Enter
@@ -10726,7 +13597,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;
@@ -10767,7 +13640,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; 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; s.momentOffer = 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,
@@ -10783,7 +13668,7 @@ export function messagesFeature(ctx) {
// focused field's value — clear it by hand
const inp = document.querySelector('.thread-reply-input');
if (inp) inp.value = '';
- s.replying = false; s.preview = false; // sent: the box folds away
+ s.replying = false; s.preview = false; s.mediaMoment = null; s.momentOffer = null; // sent: the box folds away
toast(t('threadReplied'));
} catch (e) { if (!e.silent) toast(e.message); }
s.sending = false; render();
@@ -10861,17 +13746,52 @@ export function messagesFeature(ctx) {
// (or profile) and its scroll place. A thread opened straight from a
// link has nothing of ours under it, so no button that invents one.
!ctx.canGoBack || ctx.canGoBack()
- ? h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.noteThread = null; }) }, t('back'))
+ ? h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.noteThread = null; ui.liveStream = null; ui.goLive = null; }) }, t('back'))
: null,
...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; };
+ // A kind 0 is replaceable too: one built on a profile we failed to find
+ // wipes the real one wherever it lands. 2026-10-30, a long-time nostr
+ // user signed in with his key for the first time; our relays had never
+ // seen his kind 0 (it lived on ditto, snort and oxtr), the lookup below
+ // came back empty, and the payment-address publish went out as
+ // {lud16, nip05} alone — name, picture and banner gone everywhere. So an
+ // empty quick lookup widens to the same search the follow list gets
+ // (indexes, archives, his own write relays, Primal's signed copy) before
+ // anything is written. Once per key per session: a key with no profile
+ // anywhere is new, and its first publish shouldn't wait twice.
+ const kind0DeepMiss = new Set();
+ 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 (!newest && !(kind0Last && kind0Last.pk === pk) && !kind0DeepMiss.has(pk)) {
+ try { newest = (await deepContactList(pk)).profile || null; } catch {}
+ if (!newest) kind0DeepMiss.add(pk);
+ }
+ 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
@@ -10885,12 +13805,15 @@ export function messagesFeature(ctx) {
if (opts.fieldWhen && opts.fieldWhen[k] && !opts.fieldWhen[k](base)) continue;
merged[k] = v;
}
+ // fields to take out altogether (an address that no longer exists)
+ for (const k of opts.remove || []) if (!opts.fieldWhen || !opts.fieldWhen[k] || opts.fieldWhen[k](base)) delete merged[k];
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;
@@ -10904,11 +13827,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');
@@ -10928,26 +13860,134 @@ 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;
+ }
+ // ---- profile history: undo a kind 0 that replaced the real one ---------
+ // Relays holding the newest copy dropped the older ones; the archives
+ // often haven't. An older copy fills the editor's EMPTY fields (name,
+ // bio, picture, banner) — nothing typed or already set is touched, and
+ // nothing is published until Save.
+ const PROFILE_HISTORY_FIELDS = ['name', 'about', 'picture', 'banner'];
+ async function findProfileHistory() {
+ const me = mePk();
+ if (!me) return [];
+ const relays = [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS, ...PROFILE_ARCHIVE_RELAYS, ...FOLLOW_HISTORY_RELAYS,
+ ...(await relaysOf(me).catch(() => []))])];
+ const evs = await queryOn(relays, { kinds: [0], authors: [me], limit: 50 }, 8000).catch(() => []);
+ const byId = new Map();
+ for (const e of evs || []) if (e.pubkey === me) byId.set(e.id, e);
+ return [...byId.values()].sort((a, b) => b.created_at - a.created_at);
+ }
+ const profileFieldsOf = (e) => {
+ let c = {};
+ try { c = JSON.parse(e.content) || {}; } catch {}
+ const out = {};
+ for (const k of PROFILE_HISTORY_FIELDS) {
+ const v = k === 'name' ? (c.display_name || c.name) : c[k];
+ if (typeof v === 'string' && v.trim()) out[k] = v.trim();
+ }
+ return out;
+ };
+ // what an older copy has that the draft is missing
+ const profileHistoryExtra = (e, draft) => Object.keys(profileFieldsOf(e)).filter((k) => !(draft && String(draft[k] || '').trim()));
+ function fillProfileFrom(e) {
+ const draft = ui.profEdit;
+ if (!draft) return 0;
+ const old = profileFieldsOf(e);
+ let n = 0;
+ for (const k of profileHistoryExtra(e, draft)) { draft[k] = old[k]; (draft.touched ||= {})[k] = true; n++; }
+ if (n) {
+ if (old.picture && draft.picture === old.picture) preloadPicture({ picture: old.picture });
+ toast(t('profHistFilled', { n }));
+ } else toast(t('profHistNothing'));
+ if (ui.profHist) ui.profHist.done = true;
+ render();
+ return n;
+ }
+ function profileHistoryCard() {
+ const draft = ui.profEdit;
+ if (!draft || !mePk()) return null;
+ const ph = ui.profHist;
+ const look = () => {
+ ui.profHist = { loading: true };
render();
+ findProfileHistory().then((vs) => { ui.profHist = { versions: vs }; render(); })
+ .catch(() => { ui.profHist = { versions: [] }; render(); });
+ };
+ const versions = (ph && ph.versions) || [];
+ const offers = versions.map((e) => ({ e, extra: profileHistoryExtra(e, draft) })).filter((v) => v.extra.length);
+ return h('div', { class: 'col prof-hist-card', style: 'gap:8px' },
+ h('p', { class: 'small muted', style: 'margin:0' }, t('profHistDesc')),
+ !ph || ph.done
+ ? h('button', { class: 'btn-sm', type: 'button', style: 'align-self:flex-start', onClick: look }, t('profHistLook'))
+ : ph.loading
+ ? h('div', { class: 'row', style: 'justify-content:center;padding:6px' }, h('span', { class: 'spinner sm' }))
+ : offers.length
+ ? h('div', { class: 'col', style: 'gap:8px' }, ...offers.slice(0, 6).map(({ e, extra }) => {
+ const f = profileFieldsOf(e);
+ return h('div', { class: 'row between gap6', style: 'align-items:center' },
+ h('div', { class: 'col', style: 'gap:1px;min-width:0' },
+ h('div', { class: 'break' }, f.name || t('profHistNoName')),
+ h('div', { class: 'small faint' }, new Date(e.created_at * 1000).toLocaleDateString()
+ + ' · ' + extra.map((k) => t('profHist_' + k)).join(', '))),
+ h('button', { class: 'btn-sm', type: 'button', onClick: () => fillProfileFrom(e) }, t('profHistUse')));
+ }))
+ : h('div', { class: 'small faint' }, t('profHistNone')));
+ }
+ // 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;
@@ -11087,9 +14127,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
@@ -11115,7 +14163,8 @@ export function messagesFeature(ctx) {
// doesn't drop by the height of a cover photo when it arrives
: urlish(lp.banner);
const draftPic = draft && urlish(draft.picture);
- if (bannerUrl && !draft && !mediaReady.has(bannerUrl)) warmBanner(pk);
+ const bannerShown = bannerUrl && !draft ? blobAltOf(bannerUrl) || bannerUrl : bannerUrl;
+ if (bannerUrl && !draft && !mediaReady.has(bannerShown)) warmBanner(pk);
return h('div', { class: 'col', style: 'gap:16px' },
// full header on profiles too — losing the search button here made
// finding the NEXT person a trek back home
@@ -11124,7 +14173,7 @@ export function messagesFeature(ctx) {
t(full || lp.eventAt || lp.name || lp.picture ? 'profFetchFailed' : 'profNotFound'),
h('button', { class: 'btn-sm', onClick: () => { fetchFullProfile(pk); render(); } }, t('retry'))) : null,
h('div', { class: 'card col', style: 'gap:12px' },
- bannerUrl ? h('div', { class: 'profile-banner', style: `background-image:url(${JSON.stringify(draft ? bannerUrl : mediaSrc(bannerUrl, mediaReady.get(bannerUrl)))})` }) : null,
+ bannerUrl ? h('div', { class: 'profile-banner', style: `background-image:url(${JSON.stringify(draft ? bannerUrl : mediaSrc(bannerShown, mediaReady.get(bannerShown)))})` }) : null,
h('div', { class: 'row gap6', style: 'align-items:center' },
draftPic
? h('div', { class: 'chat-avatar profile-avatar ava-img', style: `background-image:url(${JSON.stringify(draftPic)})` })
@@ -11140,6 +14189,9 @@ export function messagesFeature(ctx) {
showLud ? h('div', { class: 'muted small break' }, '⚡ ' + lud16) : null,
// the hat pitch lives beside the avatar it decorates
mine ? hook('hatShopEntry') : null)),
+ ui.profEdit ? null : liveBanner(pk),
+ mine && !ui.profEdit && canGoLive() && !liveNowOf(pk) ? h('button', { class: 'btn-sm go-live-btn', style: 'align-self:flex-start', onClick: openGoLive },
+ h('span', { class: 'go-live-dot' }), t('goLive')) : null,
// no spinner while the kind 0 loads — prefetch keeps this rare, and
// an empty beat reads calmer than a spinner
// The bio rides the same renderer as notes: npub mentions become
@@ -11229,6 +14281,7 @@ export function messagesFeature(ctx) {
ui.profUploading = false; render();
},
})),
+ profileHistoryCard(),
h('button', { class: 'btn-primary btn-block', disabled: ui.profSaving, onClick: saveProfile },
ui.profSaving ? h('span', { class: 'spinner sm' }) : t('save')),
h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.profEdit = null; ui.profEditFilled = false; render(); } }, t('cancel')))
@@ -11242,6 +14295,7 @@ export function messagesFeature(ctx) {
// the half-written post back, composer open. Posting clears
// it; Cancel just closes the composer and keeps the text.
postComposer(),
+ ui.profCompose == null ? scheduledList() : null,
// the non-destructive way out: add another identity (Nostr,
// passkey, Google) next to this one and switch between them
// on the Accounts screen — logout stays for actually leaving
@@ -11266,7 +14320,7 @@ export function messagesFeature(ctx) {
// screen router shows an open thread before the chat, so
// a reply half-typed under their post used to win here
ui.profilePk = null; ui.profOverThread = false;
- ui.noteThread = null; ui.userSearch = null; ui.feedEdit = null;
+ ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = null; ui.feedEdit = null;
ui.chatOpen = true;
ui.msgView = 'dm';
ui.msgPeer = peer;
@@ -11280,7 +14334,7 @@ export function messagesFeature(ctx) {
// and the Send tab would never appear
ui.profilePk = null;
ui.profOverThread = false;
- ui.noteThread = null;
+ ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
ui.userSearch = null;
ui.chatOpen = false;
ctx.showSend({ fresh: true });
@@ -11327,23 +14381,27 @@ export function messagesFeature(ctx) {
const c = notesFor(pk);
// Posts | Replies: the replies are their side of other people's
// conversations, apart from what they posted themselves
- const tab = profTab(pk);
- const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e));
+ // Streams joins the tabs once they've streamed
+ const streamed = pastOf(pk).length > 0;
+ const tab = profTab(pk) === 'streams' && !streamed ? 'posts' : profTab(pk);
+ // 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
// (five pages at most per tab: someone who never replies must not
// have their whole history paged through looking for one)
const fill = c.autoFill && c.autoFill.tab === tab ? c.autoFill : (c.autoFill = { tab, n: 0 });
- if (c.status === 'ready' && shown.length < 12 && !c.end && !c.loadingMore && fill.n < 5) {
+ if (tab !== 'streams' && c.status === 'ready' && shown.length < 12 && !c.end && !c.loadingMore && fill.n < 5) {
fill.n++;
queueMicrotask(() => loadOlderNotes(pk).catch(() => {}));
}
const tabs = h('div', { class: 'seg prof-tabs', style: 'display:flex;width:100%' },
- ...['posts', 'replies'].map((k) => h('button', {
+ ...['posts', 'replies', ...(streamed ? ['streams'] : [])].map((k) => h('button', {
type: 'button', class: (tab === k ? 'active ' : '') + 'grow', 'data-tab': k,
onClick: () => { if (tab === k) return; ui.profTab = { pk, tab: k }; c.win = null; render(); },
- }, t(k === 'posts' ? 'profTabPosts' : 'profTabReplies'))));
+ }, t(k === 'posts' ? 'profTabPosts' : k === 'replies' ? 'profTabReplies' : 'profTabStreams'))));
+ if (tab === 'streams') return h('div', { class: 'col', style: 'gap:8px' }, tabs, pastStreams(pk));
// while loading with nothing to show: an invisible copy of the
// empty-state line holds the height, so the page doesn't jump when
// the answer lands (no spinner). With posts already in hand — from
@@ -11354,13 +14412,23 @@ export function messagesFeature(ctx) {
return h('div', { class: 'col', style: 'gap:8px' }, tabs,
waiting && c.notes.length
? h('div', { class: 'row gap6', style: 'justify-content:center;padding:8px 0' }, h('span', { class: 'spinner sm' }))
- // nothing in hand yet: the empty line holds the height, unseen (no spinner)
- : h('div', { class: 'small faint', style: 'text-align:center' + (waiting ? ';visibility:hidden' : '') }, none));
+ // nothing in hand yet: the shapes of posts to come, so a first
+ // visit reads as loading rather than empty ("there's no
+ // indication that it's loading posts", Adam 2026-11-13)
+ : waiting
+ ? h('div', { class: 'card col notes-feed note-ghosts', style: 'gap:0', 'aria-busy': 'true', 'aria-label': t('profNotesLoading') },
+ ...[0, 1, 2].map((i) => h('div', { class: 'note-ghost' },
+ h('span', { class: 'ng-ava' }),
+ h('span', { class: 'col grow', style: 'gap:8px' },
+ h('span', { class: 'ng-line', style: 'width:38%' }),
+ h('span', { class: 'ng-line', style: 'width:' + [92, 80, 86][i] + '%' }),
+ h('span', { class: 'ng-line', style: 'width:' + [64, 72, 48][i] + '%' })))))
+ : h('div', { class: 'small faint', style: 'text-align:center' }, none));
}
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' }))
@@ -11388,11 +14456,13 @@ export function messagesFeature(ctx) {
if (!file || !upload) return;
ui.postUploading = true; render();
try {
- const url = await upload(file);
+ // (a URL, or what a stream's upload says of it: its type, size, length)
+ const got = await upload(file);
+ const url = typeof got === 'string' ? got : got.url;
// A post canceled while its upload was in flight must stay canceled.
// `false` lets that composer reject the late result without affecting
// the reply composer, which shares this helper.
- if (place(url) !== false) (ui.postMedia ||= []).push({ url, m: file.type || '' });
+ if (place(url) !== false) (ui.postMedia ||= []).push(typeof got === 'string' ? { url, m: file.type || '' } : { m: file.type || '', ...got });
} catch (e) { toast(e.message || String(e)); }
ui.postUploading = false; render();
}
@@ -11416,6 +14486,7 @@ export function messagesFeature(ctx) {
ui.profCompose = null;
ui.postMedia = [];
ui.postPreview = false;
+ ui.postSchedule = null;
discardDraft(POST_DRAFT);
render();
}
@@ -11450,8 +14521,21 @@ export function messagesFeature(ctx) {
// You could only find out by posting. This runs the draft through noteBody
// — the very renderer the feed uses — so the preview is not a lookalike of
// the real thing, it IS the real thing.
+ // A link's card needs its page read first: the feed warms that before a
+ // post shows, a draft only once the typing settles (not one registrar call
+ // per keystroke of a URL), then repaints into the card.
+ let draftPvTimer = null;
+ function warmDraftPreviews(body) {
+ const want = notePreviewUrls(body).filter((u) => !previews.has(u));
+ clearTimeout(draftPvTimer);
+ if (!want.length) return;
+ draftPvTimer = setTimeout(() => {
+ for (const u of want) warmPreview(u).then(() => { if (previews.get(u)) scheduleRepaint(); });
+ }, 500);
+ }
function draftPreview(text) {
const body = String(text || '').trim();
+ warmDraftPreviews(body);
return h('div', { class: 'draft-preview' },
h('div', { class: 'draft-preview-tag' }, t('composePreviewTag')),
body
@@ -11505,15 +14589,40 @@ export function messagesFeature(ctx) {
type: 'button', class: 'compose-tool', title: t('feedAttach'), 'aria-label': t('feedAttach'), disabled: !!ui.postUploading,
onClick: () => document.getElementById('post-file')?.click(),
}, ui.postUploading ? h('span', { class: 'spinner sm' }) : h('span', { style: 'display:flex', html: CLIP })) : null,
- gifs.button('post', 'compose-tool gif-btn'))),
+ gifs.button('post', 'compose-tool gif-btn'),
+ canGoLive() ? h('button', { type: 'button', class: 'compose-tool go-live-tool', title: t('goLive'), 'aria-label': t('goLive'), onClick: openGoLive },
+ h('span', { class: 'go-live-dot' })) : null)),
mentionList('.post-input'),
ui.postPreview ? draftPreview(text) : null,
mediaBar(),
+ ui.postSchedule != null ? h('label', { class: 'row gap6 sched-pick', style: 'align-items:center' },
+ h('span', { class: 'small muted' }, t('schedAt')),
+ h('input', {
+ type: 'datetime-local', class: 'grow', value: ui.postSchedule,
+ min: localInput(Date.now() + SCHED_MIN_AHEAD * 1000), max: localInput(Date.now() + 90 * 86400_000),
+ onInput: (ev) => { ui.postSchedule = ev.target.value; },
+ })) : null,
h('div', { class: 'row gap6 wrap post-actions' },
- h('button', { class: 'btn-primary grow', disabled: !!ui.postUploading, onClick: async () => {
+ h('button', { class: 'btn-primary grow', disabled: !!ui.postUploading || !!ui.postScheduling, onClick: async () => {
const body = composeText().trim();
if (!body) return;
const media = (ui.postMedia || []).filter((m) => body.includes(m.url));
+ if (ui.postSchedule != null) {
+ // nothing goes on screen yet, so the composer stays open until
+ // the notifier has it (a signer may ask first)
+ const at = Math.floor(new Date(ui.postSchedule).getTime() / 1000);
+ ui.postScheduling = true; render();
+ try {
+ await schedulePost(body, media, at);
+ ui.profCompose = null; ui.postMedia = []; ui.postSchedule = null;
+ setDraft(POST_DRAFT, '');
+ const inp = document.querySelector('.post-input');
+ if (inp) inp.value = '';
+ toast(t('schedDone', { when: schedWhen(at) }));
+ } catch (e) { if (!e.silent) toast(e.message || String(e)); }
+ ui.postScheduling = false; render();
+ return;
+ }
// the post is on screen instantly (publishPost is optimistic) —
// close the composer now; a failure reopens it with the text intact
ui.profCompose = null;
@@ -11527,14 +14636,21 @@ export function messagesFeature(ctx) {
if (!e.silent) toast(e.message || String(e));
render();
}
- } }, t('profPostBtn')),
+ } }, ui.postScheduling ? h('span', { class: 'spinner sm' }) : t(ui.postSchedule != null ? 'schedBtn' : 'profPostBtn')),
h('input', {
type: 'file', id: 'post-file', accept: 'image/*,video/*', style: 'display:none',
onChange: async (e) => { const f = e.target.files && e.target.files[0]; e.target.value = ''; await attachMedia(f); },
}),
h('div', { class: 'row gap6 composer-options' },
previewBtn(!!ui.postPreview, () => { ui.postPreview = !ui.postPreview; render(); }),
+ h('button', {
+ type: 'button', class: 'btn-ghost btn-sm', title: t('schedToggle'), 'aria-label': t('schedToggle'),
+ 'aria-pressed': String(ui.postSchedule != null),
+ // an hour from now, on the next quarter hour
+ onClick: () => { ui.postSchedule = ui.postSchedule != null ? null : localInput(Math.ceil((Date.now() + 3600_000) / 900_000) * 900_000); render(); },
+ }, '\u{1F552}'),
h('button', { class: 'btn-ghost btn-sm', onClick: requestCancelPost }, t('cancel')))),
+ scheduledList(),
postCancelWarning(),
gifs.sheet('post', (g) => {
const cur = composeText().replace(/\s+$/, '');
@@ -11566,10 +14682,13 @@ export function messagesFeature(ctx) {
function feedChips() {
const items = feedList();
const cur = feedDef();
- if (cur && adhocFeeds.has(cur.id)) items.push(cur);
+ // (a wallet restoring behind /feed is on the visitor's copy of Popular
+ // for a beat: the built-in chip stands for it, not a second Popular)
+ const onVisitorCopy = curFeedId === 'all:visitor';
+ if (cur && adhocFeeds.has(cur.id) && !onVisitorCopy) items.push(cur);
return h('div', { class: 'row feed-chips', 'data-key': 'feed-chips' },
...items.map((f) => h('button', {
- class: 'feed-chip' + (f.id === curFeedId ? ' on' : ''), type: 'button', 'data-key': 'chip:' + f.id,
+ class: 'feed-chip' + (f.id === curFeedId || (onVisitorCopy && f.id === EVERYTHING) ? ' on' : ''), type: 'button', 'data-key': 'chip:' + f.id,
onClick: () => switchFeed(f.id),
// someone's timeline carries the person, not a name — an empty
// label left a blank black pill
@@ -11617,7 +14736,7 @@ export function messagesFeature(ctx) {
function toFrontDoor() {
rememberReturn();
ui.signinAsk = null; ui.pubProf = null; ui.chatOpen = false; ui.msgView = null;
- ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.feedRelayEdit = null;
+ ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedRelayEdit = null;
render();
try { window.scrollTo({ top: 0 }); } catch {}
}
@@ -11648,14 +14767,17 @@ export function messagesFeature(ctx) {
}, 0);
}
function appBottomNav() {
- const visitor = isVisitor();
+ const visitor = visitorView();
const me = !visitor && ctx.shownPubkey ? ctx.shownPubkey() : null;
- const active = ui.userSearch ? 'search' : me && ui.profilePk === me && !ui.noteThread ? 'profile' : ui.noteThread || ui.profilePk ? 'feed' : ui.chatOpen
+ // a stream (or Go live) over the shell is a place of its own: no button
+ // is "here", so the one tapped goes there (Feed under a stream thought it
+ // was home and only scrolled the hidden feed)
+ const active = ui.liveStream || ui.goLive ? 'live' : ui.userSearch ? 'search' : me && ui.profilePk === me && !ui.noteThread ? 'profile' : ui.noteThread || ui.profilePk ? 'feed' : ui.chatOpen
? ui.msgView === 'feed' ? 'feed' : ui.msgView === 'notifs' ? 'notifs' : 'messages' : ui.tab === 'settings' ? 'settings' : 'wallet';
const leavePage = () => {
stopFeedWatch(); stopNotifWatch();
// Top-level destinations must leave any feature page covering the shell.
- for (const key of ['profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'noteThread', 'userSearch',
+ for (const key of ['profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'noteThread', 'liveStream', 'goLive', 'liveReport', 'userSearch',
'zapSetup', 'hatShop', 'feedEdit', 'feedMenu', 'feedRelayEdit', 'noteSheet', 'reactPick', 'reportSheet',
'msgReplyTo', 'msgSheet', 'arkCoinsPage', 'arkExitPage', 'nameEditOpen', 'nostrReconnect', 'nostrLoginOpen',
'pos', 'lockedGift', 'viewGift', 'claimChoose', 'signinAsk']) ui[key] = null;
@@ -11736,7 +14858,7 @@ export function messagesFeature(ctx) {
// it), built outside the morph so a repaint never restarts a playing clip.
const MEDIA_MODE_KEY = 'coinos-feed-media';
let mediaMode = 'all';
- try { const m = localStorage.getItem(MEDIA_MODE_KEY); if (m === 'replies' || m === 'images' || m === 'videos' || m === 'articles') mediaMode = m; } catch {}
+ try { const m = localStorage.getItem(MEDIA_MODE_KEY); if (m === 'replies' || m === 'images' || m === 'videos' || m === 'live' || m === 'articles') mediaMode = m; } catch {}
// Notes and Conversations are lists of posts (the feed's own state, or its
// Conversations view); the rest are grids read from the media index.
const listView = () => mediaMode === 'all' || mediaMode === 'replies';
@@ -11764,7 +14886,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) {
@@ -11775,11 +14899,7 @@ export function messagesFeature(ctx) {
if (rec.art.until && (!r.art.until || rec.art.until < r.art.until)) r.art.until = rec.art.until;
if (rec.art.end && Date.now() - rec.art.end < 86_400_000) r.art.end = r.art.end || rec.art.end;
}
- // the bottom of a feed is looked for again after a day (a relay
- // added, a follow back-filled)
- // (only an end confirmed by repeated empty answers: one empty
- // answer was a timeout as often as the bottom, and held for a day)
- if (rec.end && rec.endSure && Date.now() - rec.end < 86_400_000) r.end = r.end || rec.end;
+ // (the bottom of a feed isn't kept: see crawlMedia)
}
// kept frames first, so the first paint of the grid is pictures
await Promise.all([warmVideoThumbs([...r.videos.values()]),
@@ -11794,7 +14914,7 @@ export function messagesFeature(ctx) {
r.saveT = setTimeout(() => {
const list = (m) => [...m.values()].sort((a, b) => b.created_at - a.created_at);
saveMediaIndex(r.key, { images: list(r.images), videos: list(r.videos), articles: list(r.articles),
- art: { until: r.art.until, end: r.art.end }, until: r.until, end: r.end, endSure: !!r.end });
+ art: { until: r.art.until, end: r.art.end }, until: r.until });
}, 1500);
}
// file the posts that carry media; each post is looked at once
@@ -11818,6 +14938,10 @@ export function messagesFeature(ctx) {
if (!def || !feedHasQuery(def)) return Promise.resolve();
if (def.curated) return loadOlderFeed(); // a curated feed pages its own way
const r = mediaIndex(c.id);
+ // A grid is never at its end (Adam, 2026-10-17: "I should never be all
+ // caught up"): the bottom it found — the relays answering empty — is
+ // looked past again a few minutes on.
+ if (r.end && Date.now() - r.end > 300_000) { r.end = false; r.empty = 0; }
if (!r.loaded || r.end || mediaCrawling) return mediaCrawling || Promise.resolve();
mediaCrawling = (async () => {
scheduleRepaint();
@@ -11834,9 +14958,13 @@ export function messagesFeature(ctx) {
noteForSpam(ev);
indexMedia(r, [ev]);
};
- try { await feedPass({ until, limit: 100 }, { sink }, c); } catch {}
+ try { await feedPass({ until, limit: 100 }, { sink }, c, FEED_KINDS, FEED_LIMIT, r.deep ? TOPIC_ARCHIVE_RELAYS : null); } catch {}
if (c.stopped) break;
if (saw) { r.empty = 0; r.until = Math.min(oldest, until); continue; }
+ // Nothing older on the feed's relays: the big ones keep days, so
+ // the history goes on on the archive relays, which keep years (the
+ // grid stopped at five clips, "all caught up")
+ if (!r.deep) { r.deep = true; pass--; continue; }
// an empty answer is the bottom only when it repeats: a relay that
// timed out, or a socket the phone froze, answers empty too
if (++r.empty >= 3) { r.end = Date.now(); break; }
@@ -11987,12 +15115,17 @@ export function messagesFeature(ctx) {
// <img> of the original (or the 1100px column copy) to fetch and decode,
// and the browser's lazy margin is a screen or two. These are local and a
// few KB, so every tile loads at once and decodes in no time.
- const TILE_CACHE = 'coinos-tile-thumbs-v1', TILE_PX = 360, TILE_MAX = 1200;
+ const TILE_CACHE = 'coinos-tile-thumbs-v2', TILE_PX = 360, TILE_MAX = 1200;
const tileThumbs = new Map(); // url -> object URL
const tileKey = (url) => 'https://tile-thumb.invalid/?u=' + encodeURIComponent(url);
const tileQueue = [], tileTried = new Set(), tileLooked = new Set();
let tileBusy = 0, tileRepaint = null;
- const tileStore = () => caches.open(TILE_CACHE);
+ let tileOldGone = false;
+ const tileStore = () => {
+ // the square tiles of before (v1) go: the grid's rows want each shape
+ if (!tileOldGone) { tileOldGone = true; caches.delete('coinos-tile-thumbs-v1').catch(() => {}); }
+ return caches.open(TILE_CACHE);
+ };
async function warmTileThumbs(urls) {
if (typeof caches === 'undefined') return;
let found = 0;
@@ -12012,7 +15145,7 @@ export function messagesFeature(ctx) {
const kept = mediaReady.get(url)?.thumb;
if (!kept && (noCorsHost(url) || corsRefused.has(url))) {
// the host keeps its bytes: the server cuts the tile
- const tile = await serverPicBlob(url, 'tile');
+ const tile = await serverPicBlob(url, 'row');
if (tile) await saveTileThumb(url, tile);
return;
}
@@ -12022,7 +15155,7 @@ export function messagesFeature(ctx) {
if (!res.ok) return;
blob = await res.blob();
} catch (e) {
- if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'tile'); if (tile) await saveTileThumb(url, tile); }
+ if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'row'); if (tile) await saveTileThumb(url, tile); }
return;
}
if (/gif/i.test(blob.type)) return; // animated: the tile shows the original
@@ -12177,25 +15310,61 @@ export function messagesFeature(ctx) {
// videos by default on a phone that's in vertical orientation and only
// horizontal videos if the phone is in landscape but have some kind of
// control to toggle the ability to see all videos".)
- const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', or unset: the screen's way round
- const clipsAll = () => { try { return localStorage.getItem(CLIPS_FIT_KEY) === 'all'; } catch { return false; } };
- const setClipsAll = (all) => { try { if (all) localStorage.setItem(CLIPS_FIT_KEY, 'all'); else localStorage.removeItem(CLIPS_FIT_KEY); } catch {} };
+ // On a desktop-sized window every shape is the default (Adam, 2026-10-22:
+ // the justified rows hold both); a phone keeps to its way round.
+ const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', 'fit' (the screen's way round), or unset: the device's default
+ const bigWindow = () => { try { return matchMedia('(min-width: 1000px) and (min-height: 600px)').matches; } catch { return false; } };
+ const clipsAll = () => { try { const v = localStorage.getItem(CLIPS_FIT_KEY); return v === 'all' || (v !== 'fit' && bigWindow()); } catch { return bigWindow(); } };
+ const setClipsAll = (all) => { try { if (all === bigWindow()) localStorage.removeItem(CLIPS_FIT_KEY); else localStorage.setItem(CLIPS_FIT_KEY, all ? 'all' : 'fit'); } catch {} };
const screenTall = () => window.innerHeight >= window.innerWidth;
- const clipShape = (url) => {
+ const clipSize = (url) => {
const d = videoInfo.get(url) || {};
const k = d.w && d.h ? d : videoDims.get(url) || mediaReady.get(url);
const w = k && (k.w || k.width), hh = k && (k.h || k.height);
- return w && hh ? (hh > w ? 'tall' : hh < w ? 'wide' : 'square') : null;
+ return w && hh ? { w, h: hh } : null;
+ };
+ // (no size yet: the still's proportions, which a grid of every shape has
+ // loaded without measuring anything — so going back to one shape finds
+ // the clips' shapes known)
+ const clipShape = (url) => {
+ const z = clipSize(url), r = z ? z.w / z.h : posterAr.get(url);
+ return r ? (r < 0.99 ? 'tall' : r > 1.01 ? 'wide' : 'square') : null;
};
+ // width over height, kept between a phone's upright 9:16 and a cinema 2:1
+ // (a stray 32:9 or 1:4 would make a tile a sliver); unknown: a square
+ // (until the clip's size is known, the still's own proportions: the
+ // server's and a frame grab keep the clip's shape)
+ const posterAr = new Map();
+ const clampAr = (r) => Math.min(2, Math.max(0.5, r));
+ const clipRatio = (url) => { const z = clipSize(url); return z ? clampAr(z.w / z.h) : posterAr.get(url) || 1; };
+ // a grid item's: the file's measured size, the post's word for it (NIP-92
+ // dim), or its still once that has loaded
+ function itemRatio(it) {
+ if (clipSize(it.url)) return clipRatio(it.url);
+ for (const tag of it.ev.tags || []) {
+ if (tag[0] !== 'imeta' || !tag.includes('url ' + it.url)) continue;
+ const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(imetaFields(tag).dim || '');
+ if (m && +m[1] && +m[2]) return clampAr(+m[1] / +m[2]);
+ }
+ return posterAr.get(it.url) || 1;
+ }
+ function arFromStill(img, url) {
+ if (clipSize(url) || !img.naturalWidth || !img.naturalHeight) return;
+ const r = clampAr(img.naturalWidth / img.naturalHeight);
+ posterAr.set(url, r);
+ const tile = img.closest('.media-grid.justified .media-tile');
+ if (tile) tile.style.setProperty('--ar', r.toFixed(3));
+ }
// true/false, or null while the clip's shape isn't known
const clipFits = (url) => { if (clipsAll()) return true; const sh = clipShape(url); return sh === null ? null : sh === 'square' || sh === (screenTall() ? 'tall' : 'wide'); };
const clipsLabel = () => t(clipsAll() ? 'clipsAll' : screenTall() ? 'clipsTall' : 'clipsWide');
- // the toggle: in the pager's top bar and over the Videos grid
+ // the toggle: in the pager's top bar only (over the grid it sat oddly
+ // apart from the chips); the grid follows the same setting
function clipsToggle(cls, after) {
return h('button', { class: cls, type: 'button', title: t('clipsToggleTitle'), onClick: (e) => {
e.stopPropagation();
setClipsAll(!clipsAll());
- for (const b of document.querySelectorAll('.mp-fit, .media-fit-btn')) b.textContent = clipsLabel();
+ for (const b of document.querySelectorAll('.mp-fit')) b.textContent = clipsLabel();
if (after) after();
if (mediaMode === 'videos') scheduleRepaint();
} }, clipsLabel());
@@ -12215,8 +15384,17 @@ export function messagesFeature(ctx) {
if (d && d.probed && !d.w && d.ranges && !videoDims.has(url)) return playerShape(url);
}).finally(() => { if (mediaMode === 'videos') scheduleRepaint(); });
}
- function mediaItems(c, kind) {
- const out = [], seen = new Set();
+ // One picture or clip shows once in the grid, however many posts carry it
+ // (Adam, 2026-10-22: a conference promo filled the Videos view with
+ // copies): the same file (a Blossom hash names it wherever it's hosted),
+ // or the same words from the same person posted again with another upload.
+ const sameFile = (url) => { const m = /\/([0-9a-f]{64})(?:\.\w+)?(?:[?#]|$)/i.exec(url); return m ? m[1].toLowerCase() : url.replace(/[?#].*$/, ''); };
+ const saidAgain = (ev) => { const w = String(ev.content || '').replace(/https?:\/\/\S+/g, '').replace(/\s+/g, ' ').trim(); return w.length >= 8 ? ev.pubkey + '|' + w : null; };
+ // (anyShape: the pager's list — every clip, the ones the wrong way round
+ // for the screen held out of sight by pagerFit, so "All shapes" there has
+ // them to show)
+ function mediaItems(c, kind, anyShape = false) {
+ const out = [], seen = new Set(), said = new Map();
const r = mediaIndex(c.id);
indexMedia(r, c.notes);
const evs = [...r[kind].values()].sort((a, b) => b.created_at - a.created_at);
@@ -12225,17 +15403,51 @@ export function messagesFeature(ctx) {
if (hidden(ev)) continue;
// a grid shows the picture itself — no warning to fold it behind
if (curated ? notForPublic(ev) : modOn('sensitive') && sensitiveWhy(ev) !== null && !isMe(ev.pubkey)) continue;
+ const again = saidAgain(ev);
+ if (again && said.has(again) && said.get(again) !== ev.id) continue;
if (kind === 'videos') learnVideoMeta(ev);
- const urls = kind === 'videos' ? clipUrlsOf(ev).filter(fitClip)
+ // (a clip whose host says it's deleted has nothing to show: a blank tile)
+ const urls = kind === 'videos' ? clipUrlsOf(ev).filter((u) => !clipGone(u) && (anyShape || fitClip(u)))
: noteMediaUrls(ev.content).filter((u) => !u.startsWith('https://i.ytimg.com/'));
+ // (the words are taken by a post that shows: one whose clip doesn't fit
+ // the screen leaves them to the next)
+ if (again && urls.length) said.set(again, ev.id);
for (const url of urls) {
- const it = { ev, url };
- if (seen.has(mediaKey(it))) continue;
- seen.add(mediaKey(it));
- out.push(it);
+ if (deadTiles.has(url)) continue;
+ const f = sameFile(url);
+ if (seen.has(f)) continue;
+ seen.add(f);
+ // the same clip uploaded twice by one person (a note and a video
+ // event a few minutes apart) gets two hashes but keeps its size to
+ // the byte
+ const d = kind === 'videos' ? videoInfo.get(url) || {} : {};
+ const twin = d.size && !d.sizeGuess ? ev.pubkey + '|' + d.size : null;
+ if (twin && seen.has(twin)) continue;
+ if (twin) seen.add(twin);
+ 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
@@ -12339,12 +15551,22 @@ export function messagesFeature(ctx) {
// (what the player's own full screen did). The screen isn't turned for a
// wide clip — Adam would rather it play with bars and turn the phone
// himself — so it follows the phone throughout.
- function openClip(v, url) {
+ // The pager's item for a clip on the page, if the pager has it: a clip in
+ // the post a reply answers (its "Replying to" card) isn't one of the
+ // feed's own, and gets the browser's full screen instead.
+ function clipItem(v, url) {
try {
const on = pageRowOf(v);
- if (!on) return false;
+ if (!on) return null;
const it = feedMediaItems(on.c, 'videos').find((x) => (x.row.id === on.rowId || x.ev.id === on.rowId) && x.url === url);
- if (!it) return false;
+ return it ? { on, it } : null;
+ } catch { return null; }
+ }
+ function openClip(v, url) {
+ try {
+ const found = clipItem(v, url);
+ if (!found) return false;
+ const { on, it } = found;
tappedClips.add(url); // asked for by hand: no tap-to-play cover
const at = v.currentTime || 0;
v.pause();
@@ -12419,8 +15641,13 @@ export function messagesFeature(ctx) {
class: 'feed-chip media-mode' + (mediaMode === m ? ' on' : ''), type: 'button', 'data-mode': m,
onClick: () => setMediaMode(m),
}, label);
+ // Live wears a red dot while someone in the feed is streaming
+ const def = feedDef(curFeedId);
+ const onAir = def && liveForFeed(def).length > 0;
return h('div', { class: 'row media-modes', 'data-key': 'media-modes' },
- b('all', t('mediaAll')), b('replies', t('mediaConversations')), b('images', t('mediaImages')), b('videos', t('mediaVideos')), b('articles', t('mediaArticles')));
+ b('all', t('mediaAll')), b('replies', t('mediaConversations')), b('images', t('mediaImages')), b('videos', t('mediaVideos')),
+ b('live', onAir ? [h('span', { class: 'live-dot', 'aria-hidden': 'true' }), t('mediaLive')] : t('mediaLive')),
+ b('articles', t('mediaArticles')));
}
function mediaGrid(c) {
const items = mediaItems(c, mediaMode);
@@ -12437,8 +15664,16 @@ export function messagesFeature(ctx) {
for (const u of missing) tileLooked.add(u);
if (missing.length) warmTileThumbs(missing).then(() => queueTileThumbs(missing.filter((u) => !tileThumbs.has(u))));
}
- return h('div', { class: 'media-grid', 'data-key': 'media-grid:' + mediaMode },
- mediaMode === 'videos' ? h('div', { class: 'media-fit', 'data-key': 'media-fit' }, clipsToggle('media-fit-btn')) : null,
+ if (mediaMode === 'videos') for (const it of items.slice(0, 24)) preconnect(playSrc(it.url));
+ // The tiles take the clips' shape (Adam, 2026-10-22): wide clips only (a
+ // wide screen) go one to a row, their posters whole, not slivers cut to
+ // portrait tiles; every shape ("All shapes") is laid out in justified
+ // rows, each tile its clip's own proportions and each row as tall as it
+ // takes to fill the width; tall ones only (a phone held upright) keep
+ // the tall tiles three across.
+ // Pictures go in justified rows too, in their own shapes.
+ const shape = mediaMode === 'images' ? ' justified' : mediaMode !== 'videos' ? '' : clipsAll() ? ' justified' : screenTall() ? '' : ' wide';
+ return h('div', { class: 'media-grid' + shape, 'data-key': 'media-grid:' + mediaMode },
...items.map((it) => {
const k = mediaKey(it);
// a video tile shows a still at once: kept, given, or the server's
@@ -12451,18 +15686,28 @@ export function messagesFeature(ctx) {
const fromServer = mediaMode === 'videos' && poster && poster === serverThumb(it.url);
return h('button', {
class: 'media-tile' + (mediaMode === 'videos' ? ' video' : ''), type: 'button', 'data-key': 'tile:' + k,
+ style: shape === ' justified' ? '--ar:' + itemRatio(it).toFixed(3) : undefined,
'aria-label': displayName(it.ev.pubkey), onClick: () => openMediaPager(mediaMode, k),
+ onPointerDown: mediaMode === 'videos' ? () => earlyPlayer(it.url) : undefined,
},
mediaMode === 'images' || poster
? h('img', { src: poster || tileThumbs.get(it.url) || mediaSrc(it.url), alt: '', draggable: 'false',
loading: poster || tileThumbs.has(it.url) ? 'eager' : 'lazy', decoding: 'async',
+ onLoad: (e) => arFromStill(e.currentTarget, it.url),
onError: (e) => {
if (fromServer) { serverThumbFailed.add(it.url); render(); return; } // the frame grab's turn
+ // remembered, not only a class on the tile: the next
+ // repaint rewrites the class list, and the broken-picture
+ // glyph came back (a deleted nostr.media file in #artstr)
+ deadTiles.add(it.url);
const b = e.target.closest('.media-tile'); if (b) b.classList.add('broken');
+ scheduleRepaint();
} })
// no still to show: the clip's first frame, fetched once the tile is near
: h('video', { 'data-src': it.url + '#t=0.1', muted: true, playsinline: true, preload: 'metadata' }),
- mediaMode === 'videos' && poster && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null,
+ // (drawn here whatever the tile shows, so a repaint keeps the one
+ // the frame-grab added)
+ mediaMode === 'videos' && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null,
mediaMode === 'videos' ? h('span', { class: 'media-tile-play', 'aria-hidden': 'true' }, '▶') : null);
}));
}
@@ -12476,8 +15721,14 @@ export function messagesFeature(ctx) {
if (!e.isIntersecting) continue;
const v = e.target;
tileObs.unobserve(v);
- const tile = v.closest('.media-tile');
- if (tile) tile._skipMorph = true;
+ // the player (and whatever stands in for it) is left alone by
+ // repaints, which would strip its src; the tile around it keeps up
+ // with them (its shape when the grid's layout changes, its class).
+ // Freezing the whole tile kept a tile built for one-to-a-row out of
+ // the justified rows: no --ar, no width.
+ v._skipMorph = true;
+ const standIn = (el) => { el._skipMorph = true; return el; };
+ const badge = (el) => { if (!el.parentNode.querySelector('.media-tile-badge')) el.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); };
// A first frame costs the start of the file when the index leads or
// the server serves ranges — whatever the clip's size. Only an
// index-last file without ranges would have to come down whole for
@@ -12491,9 +15742,11 @@ export function messagesFeature(ctx) {
if (await grabFrame(url)) {
if (!v.isConnected) return;
const img = document.createElement('img');
- img.alt = ''; img.draggable = false; img.src = videoThumbs.get(url);
+ img.alt = ''; img.draggable = false;
+ img.addEventListener('load', () => arFromStill(img, url), { once: true });
+ img.src = videoThumbs.get(url);
v.replaceWith(img);
- if (heavy && d.size) img.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url)));
+ if (heavy && d.size) badge(img);
return;
}
if (!v.isConnected) return;
@@ -12505,7 +15758,7 @@ export function messagesFeature(ctx) {
const cap = setTimeout(() => {
if (v.readyState >= 2 || !v.isConnected) return;
try { v.removeAttribute('src'); v.load(); } catch {}
- v.replaceWith(h('span', { class: 'media-tile-cost' }, ''));
+ v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, '')));
}, 8000);
v.addEventListener('loadeddata', () => clearTimeout(cap), { once: true });
}
@@ -12513,11 +15766,23 @@ export function messagesFeature(ctx) {
// (a plain load: shown, not kept — a player's pixels can only be
// read from a CORS load, and those fail on a cached plain copy)
v.muted = true;
+ // a clip the player can't load either is gone as far as the grid
+ // goes: a deleted file whose 404 came without CORS headers
+ // (Primal's blossom) only looked like a quiet host to the probe,
+ // and its tile sat blank. Left out for a day, like a 404 the
+ // probe could read.
+ v.addEventListener('error', () => {
+ if (!v.isConnected || !v.getAttribute('src')) return; // let go of by the eight-second cap
+ noteVideoInfo(url, { goneAt: Date.now() });
+ const b = v.closest('.media-tile');
+ if (b) b.classList.add('broken');
+ scheduleRepaint();
+ }, { once: true });
v.src = v.getAttribute('data-src');
- if (heavy && d.size) v.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url)));
+ if (heavy && d.size) badge(v);
return;
}
- v.replaceWith(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : ''));
+ v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : '')));
});
}
}, { rootMargin: '400px 0px' });
@@ -12527,6 +15792,51 @@ export function messagesFeature(ctx) {
}
}
+ // Opening a clip from the grid: on Adam's phone a player made at the tap
+ // took ~0.65 s to move (making it ~0.25, its first frame ~0.15, starting
+ // its sound ~0.3 — the clip's opening already in the cache saved nothing),
+ // and 1.8 s when the host's connection had to be made too. So the grid's
+ // clip hosts are connected to ahead (a preconnect: cheap), and the
+ // player starts loading when the finger comes down on the tile — the
+ // pager adopts that same element (pagerSlide), so the load overlaps the
+ // tap and the pager's opening. One the tap doesn't follow (a scroll) is
+ // let go.
+ const preconnected = new Set();
+ function preconnect(url) {
+ let origin; try { origin = new URL(url, location.href).origin; } catch { return; }
+ if (origin === location.origin || preconnected.has(origin) || preconnected.size > 24 || typeof document === 'undefined') return;
+ preconnected.add(origin);
+ const l = document.createElement('link');
+ l.rel = 'preconnect'; l.href = origin;
+ document.head.append(l);
+ }
+ let early = null; // { url, v, timer }
+ function earlyPlayer(url) {
+ if (frugalData() || (early && early.url === url)) return;
+ dropEarly();
+ const v = document.createElement('video');
+ v.playsInline = true; v.loop = true; v.preload = 'auto'; v.muted = true;
+ v.setAttribute('src', playSrc(url));
+ v.dataset.early = '1'; // (the pager's adoption of it, for tests)
+ // on the page (out of sight) while it waits: a detached player isn't loaded everywhere
+ v.style.cssText = 'position:fixed;left:-9999px;top:0;width:2px;height:2px;opacity:0;pointer-events:none';
+ document.body.append(v);
+ early = { url, v, timer: setTimeout(dropEarly, 2500) };
+ }
+ function dropEarly() {
+ if (!early) return;
+ clearTimeout(early.timer);
+ try { early.v.removeAttribute('src'); early.v.load(); early.v.remove(); } catch {}
+ early = null;
+ }
+ function takeEarly(url) {
+ if (!early || early.url !== url) return null;
+ const { v } = early;
+ clearTimeout(early.timer);
+ early = null;
+ return v;
+ }
+
// `fromFeed`: opened from a picture or clip in the feed (its pictures or
// clips, in the feed's order), rather than from the media grid; `at`: where
// the clip it opened on was, so it carries on from there
@@ -12677,7 +15987,10 @@ export function messagesFeature(ctx) {
// was tried: it pulled the whole file down.) On a connection to be
// careful with the poster stays: the clip may never load (a heavy one
// waits for a tap), and the still is what there is.
- const media = video
+ // (the clip a grid tile was pressed on: the player already loading since the finger came down)
+ const adopted = video && !frugalData() ? takeEarly(url) : null;
+ if (adopted) { adopted.removeAttribute('style'); adopted.className = 'mp-media'; adopted.setAttribute('data-src', url); adopted.setAttribute('playsinline', ''); adopted.setAttribute('loop', ''); }
+ const media = adopted || (video
? h('video', { class: 'mp-media', 'data-src': url, loop: true, playsinline: true, preload: 'none',
poster: frugalData() ? videoThumbs.get(url) || posterOf(ev, url) || (videoInfo.get(url) || {}).image || serverThumb(url) : undefined })
: h('img', { class: 'mp-media', 'data-src': quick, 'data-full': url, alt: '', draggable: 'false', decoding: 'async',
@@ -12689,7 +16002,8 @@ export function messagesFeature(ctx) {
let host = ''; try { host = new URL(url).hostname; } catch {}
m.closest('.mp-slide').classList.add('mp-gone');
m.insertAdjacentElement('afterend', h('div', { class: 'mp-missing' }, h('div', { class: 'mp-missing-ico' }, '🖼'), h('div', {}, t('mediaPicGone')), host ? h('div', { class: 'small muted' }, host) : null));
- } });
+ } }));
+ if (video) capUpscale(media);
const caption = mediaCaption(ev, true);
const stop = (fn) => (e) => { e.stopPropagation(); fn(e); };
const slide = h('div', { class: 'mp-slide', 'data-k': mediaKey(it) },
@@ -12705,18 +16019,22 @@ export function messagesFeature(ctx) {
h('button', { class: 'mp-like', type: 'button', 'aria-label': t('postLike'), onClick: stop(() => {
if (signinAsk()) { leavePager(); render(); return; }
if (myReactOn(ev.id)) { unreact(ev).catch(() => {}).finally(() => pagerCounts(slide)); setTimeout(() => pagerCounts(slide), 50); return; }
- ui.reactPick = ev; render();
+ ui.reactPick = withMoment(ev); render();
}) }, h('span', { class: 'i', html: I_HEART(false) }), h('span', { class: 'n' })),
// the post itself, as the feed would open it: the whole text, the replies
h('button', { class: 'mp-post', type: 'button', 'aria-label': t('mediaOpenPost'), title: t('mediaOpenPost'), onClick: stop(() => {
+ // a reply written there is about where the clip was
+ const moment = momentOf(ev);
leavePager(); openNoteThread(ev);
+ if (moment && ui.noteThread) ui.noteThread.momentFor = { id: ev.id, moment };
}) }, h('span', { class: 'i', html: I_REPLY }), h('span', { class: 'n' })),
h('button', { class: 'mp-zap', type: 'button', 'aria-label': t('zapTitle'), onClick: stop((e) => {
if (signinAsk()) { leavePager(); render(); return; }
// the first zap ever asks for an amount on a page of its own
const at = e.currentTarget.getBoundingClientRect();
+ const moment = momentOf(ev);
if (!(ctx.zapDefaultSat && ctx.zapDefaultSat())) leavePager();
- zapNote(ev.pubkey, ev, at);
+ zapNote(ev.pubkey, ev, at, moment);
recheckZap(ev.id);
setTimeout(() => pagerCounts(slide), 50);
}) }, h('span', { class: 'i', html: I_ZAP }), h('span', { class: 'n' })))));
@@ -12728,7 +16046,8 @@ export function messagesFeature(ctx) {
guardPicture(media, url);
media.muted = !pagerLoud;
media.addEventListener('click', () => {}); // a tap is the pager's (overlay), not the player's
- slide.append(seekBar(media));
+ media._momentUrl = url;
+ slide.append(seekBar(media, () => momentsOn(ev.id, url)));
}
return slide;
}
@@ -12737,14 +16056,75 @@ export function messagesFeature(ctx) {
// (the clip holds still meanwhile, and the time shows); the drag is the
// bar's alone, never the pager's swipe or its tap.
const clock = (t) => { t = Math.max(0, Math.floor(t || 0)); const m = Math.floor(t / 60), x = t % 60; return m + ':' + String(x).padStart(2, '0'); };
- function seekBar(v) {
+ // A big screen blew a small clip up into blocks (Adam, 2026-10-22: "videos
+ // that are low res … so pixellated on my large 1920 monitor"). In a big
+ // window (a phone on its side is too short) a clip is drawn at most 1.5×
+ // its own pixels,
+ // smaller ones sitting in the middle on the pager's black. A phone fills
+ // its screen as before.
+ const MAX_UPSCALE = 1.5;
+ function capUpscale(v) {
+ const fit = () => {
+ const big = v.videoWidth && matchMedia('(min-width: 1000px) and (min-height: 600px)').matches;
+ const k = MAX_UPSCALE / (window.devicePixelRatio || 1);
+ v.style.maxWidth = big ? Math.round(v.videoWidth * k) + 'px' : '';
+ v.style.maxHeight = big ? Math.round(v.videoHeight * k) + 'px' : '';
+ };
+ v.addEventListener('loadedmetadata', fit);
+ if (v.readyState >= 1) fit();
+ }
+ // up for a few seconds, and on while a finger is on it
+ // (a mouse brings it up by moving, so it goes sooner once the mouse is
+ // still, and stays while the pointer rests on the bar itself)
+ function revealSeek(bar, ms = 3500) {
+ bar.classList.add('reveal');
+ clearTimeout(bar._hide);
+ bar._hide = setTimeout(() => { if (bar._drag || bar._hover) revealSeek(bar, ms); else bar.classList.remove('reveal'); }, ms);
+ }
+ // What was said, reacted or zapped at a moment of the clip sits over the
+ // bar at that moment (a tap goes there and says who and what), and floats
+ // up off it as the clip plays past.
+ function seekBar(v, moments = () => []) {
const fill = h('div', { class: 'mp-seek-fill' });
const time = h('span', { class: 'mp-seek-time' });
- const bar = h('div', { class: 'mp-seek' }, h('div', { class: 'mp-seek-track' }, fill), time);
+ const marks = h('div', { class: 'mp-marks' });
+ const bar = h('div', { class: 'mp-seek' }, marks, h('div', { class: 'mp-seek-track' }, fill), time);
+ bar.addEventListener('pointerenter', (e) => { if (e.pointerType === 'mouse') bar._hover = true; });
+ bar.addEventListener('pointerleave', () => { bar._hover = false; });
+ let items = [], sig = '', checked = 0, last = 0;
+ const say = (x) => {
+ time.textContent = clock(x.moment.seconds) + ' ' + x.text;
+ bar.classList.add('say');
+ clearTimeout(bar._say);
+ bar._say = setTimeout(() => bar.classList.remove('say'), 3000);
+ revealSeek(bar);
+ };
+ const paintMarks = () => {
+ checked = performance.now();
+ items = moments();
+ const next = items.map((x) => x.id).join(',') + '@' + v.duration;
+ if (next === sig) return;
+ sig = next;
+ marks.replaceChildren(...items.map((x) => h('button', {
+ type: 'button', class: 'mp-mark', title: clock(x.moment.seconds) + ' ' + x.text,
+ style: 'left:' + markAt(x.moment.seconds, v.duration) + '%',
+ onPointerdown: (e) => e.stopPropagation(),
+ onClick: (e) => { e.stopPropagation(); try { v.currentTime = x.moment.seconds; } catch {} say(x); },
+ }, momentGlyph(x))));
+ };
+ v.addEventListener('mediaactivity', () => { checked = 0; });
+ // a moment the clip just played through floats up from its place
+ const pop = (x) => {
+ const slide = bar.closest('.mp-slide');
+ if (!slide || !pager || pager.cur !== slide) return;
+ const el = h('div', { class: 'mp-pop', style: 'left:calc(' + bar.offsetLeft + 'px + ' + (markAt(x.moment.seconds, v.duration) / 100) + ' * ' + bar.offsetWidth + 'px)' }, momentGlyph(x));
+ slide.append(el);
+ setTimeout(() => el.remove(), 1700);
+ };
const frac = (e) => { const r = bar.getBoundingClientRect(); return Math.min(1, Math.max(0, (e.clientX - r.left) / (r.width || 1))); };
const show = (f) => {
fill.style.width = (f * 100).toFixed(2) + '%';
- time.textContent = clock(f * v.duration) + ' / ' + clock(v.duration);
+ if (!bar.classList.contains('say')) time.textContent = clock(f * v.duration) + ' / ' + clock(v.duration); // (unless it's saying a moment)
};
const to = (f) => { try { v.currentTime = f * v.duration; } catch {} };
bar.addEventListener('pointerdown', (e) => {
@@ -12753,6 +16133,7 @@ export function messagesFeature(ctx) {
try { bar.setPointerCapture(e.pointerId); } catch {}
bar._drag = { playing: !v.paused, id: e.pointerId };
bar.classList.add('drag');
+ bar.classList.remove('say');
v.pause();
const f = frac(e); show(f); to(f);
});
@@ -12767,6 +16148,7 @@ export function messagesFeature(ctx) {
if (!d || d.id !== e.pointerId) return;
bar._drag = null;
bar.classList.remove('drag');
+ if (bar.classList.contains('reveal')) revealSeek(bar); // a few seconds more after the drag
if (e.type === 'pointerup') to(frac(e));
if (d.playing) v.play().catch(() => {});
};
@@ -12777,7 +16159,12 @@ export function messagesFeature(ctx) {
if (bar._drag) return;
const ok = v.duration > 0 && isFinite(v.duration);
bar.classList.toggle('ready', ok);
- if (ok) show(v.currentTime / v.duration);
+ if (!ok) return;
+ show(v.currentTime / v.duration);
+ if (performance.now() - checked > 1000) paintMarks();
+ const now = v.currentTime;
+ if (!v.paused && now > last && now - last < 1) for (const x of items) if (x.moment.seconds > last && x.moment.seconds <= now) pop(x);
+ last = now;
};
return bar;
}
@@ -12790,6 +16177,8 @@ export function messagesFeature(ctx) {
// is kept out — see pagerReveal, pagerFit), or every one built (all)
const PAGER_ON = '.mp-group:not(.mp-wait):not(.mp-off)';
const pagerGroups = (all = false) => (pager ? [...pager.scroller.querySelectorAll(':scope > ' + (all ? '.mp-group' : PAGER_ON))] : []);
+ // the posts found: the ready ones and those still warming, not those kept out for their shape
+ const pagerFound = () => (pager ? [...pager.scroller.querySelectorAll(':scope > .mp-group:not(.mp-off)')] : []);
// the slide a post's row rests on
const rowSlide = (g) => { const row = g && g._row; if (!row || !row.children.length) return null; return row.children[Math.min(row.children.length - 1, Math.round(row.scrollLeft / (row.clientWidth || 1)))]; };
// bring a slide to the screen: its post, and within it, the slide
@@ -12814,6 +16203,7 @@ export function messagesFeature(ctx) {
const prevGroup = (g) => { let n = g && g.previousElementSibling; while (n && (!n.classList.contains('mp-group') || n.classList.contains('mp-off'))) n = n.previousElementSibling; return n; };
const up = prevGroup(slide.closest('.mp-group')), back = up && rowSlide(up);
if (back) out.push(back); // (the one before: ready again for the swipe back)
+ out.back = back || null;
return out;
}
function pagerAttach(slide) {
@@ -12836,9 +16226,41 @@ export function messagesFeature(ctx) {
im.src = full;
}, 300);
}
+ // A player's first play with sound waits on the phone's audio output to
+ // start: on Adam's Android ~250 ms of a still picture, every clip, warm
+ // or not (muted, 60 ms; a muted start then unmuted freezes the picture
+ // for those 250 ms instead). A player that has played with sound resumes
+ // in 20-80 ms, even many seconds later. So a warm player plays at a
+ // volume nobody hears until its picture moves (a frame or two in: the
+ // audio's start is the wait) and pauses there — not back to 0: a seek
+ // undoes it. Only while the pager has sound on, and the browser lets it.
+ // Having played, the player no longer stops reading at its first frame —
+ // it fetches the rest of the file — so only a clip known to be small
+ // enough to be worth that is primed (most are 3-25 MB).
+ const PRIME_MAX = 25e6;
+ function primeSound(s, v) {
+ if (!pagerLoud || v._primed || (navigator.userActivation && !navigator.userActivation.hasBeenActive)) return;
+ const d = videoInfo.get(v.getAttribute('data-src')) || {};
+ if (!(d.size > 0 && d.size <= PRIME_MAX)) return;
+ const go = () => {
+ if (!pager || pager.cur === s || !s.isConnected || !v.getAttribute('src') || !v.paused || v._primed) return;
+ v._primed = true;
+ v.muted = false; v.volume = 0.001;
+ const done = () => {
+ clearTimeout(v._primeTimer);
+ if (pager && pager.cur !== s) { try { v.pause(); } catch {} }
+ v.volume = 1;
+ if (pager && pager.cur !== s) v.muted = true;
+ };
+ v._primeTimer = setTimeout(done, 2000);
+ const f = () => { if (v.currentTime >= 0.03 || v.paused) done(); else v.requestVideoFrameCallback(f); };
+ v.play().then(() => (v.requestVideoFrameCallback ? v.requestVideoFrameCallback(f) : setTimeout(done, 400)), () => { v._primed = false; done(); });
+ };
+ if (v.readyState >= 3) go(); else v.addEventListener('canplay', go, { once: true });
+ }
function pagerRelease(slide) {
const m = slide.querySelector('video.mp-media');
- if (m && m.getAttribute('src')) { try { m.pause(); m.removeAttribute('src'); m.load(); } catch {} }
+ if (m && m.getAttribute('src')) { try { m.pause(); m.removeAttribute('src'); m.load(); m._primed = false; } catch {} }
}
// Flipping through clips is asking to watch them: whatever they cost, the
// one on screen plays at once (streaming the rest as it goes), and the
@@ -12866,8 +16288,25 @@ export function messagesFeature(ctx) {
if (j === i) return;
const v = s.querySelector('video.mp-media');
if (eager && k >= 0) {
+ // the next clip and the one before: a player of its own, warm — once
+ // its opening is in the cache, given the file to read up to its
+ // first frame (preload 'metadata': Chrome reads ~2 s of it and
+ // stops) and paused there, so the swipe onto it is only play and
+ // sound (TikTok's trick). The one just left keeps the player it
+ // played in (a swipe back to it took 0.7 s on a phone, built anew).
+ // The others ahead get their opening only.
+ const warm = k === 0 || s === ahead.back;
+ if (warm && v.getAttribute('src')) return; // warm already
pagerRelease(s);
- headStart(playSrc(v.getAttribute('data-src')), k === 0 ? 1 : 0.5);
+ const head = headStart(playSrc(v.getAttribute('data-src')), k === 0 ? 1 : 0.5);
+ if (warm) head.then(() => {
+ const now = pager && pager.cur && pagerAhead(pager.cur);
+ if (!now || !s.isConnected || pager.cur === s || v.getAttribute('src') || (now[0] !== s && now.back !== s)) return;
+ v.preload = 'metadata';
+ v.muted = true;
+ pagerAttach(s);
+ primeSound(s, v);
+ });
return;
}
if (k === 0) {
@@ -12893,21 +16332,23 @@ export function messagesFeature(ctx) {
// it starts playing"). The server's first frame (vmedia first.jpg: frame
// 0 at full size, any host, any layout, cached at the CDN) is the first
// choice, fetched and decoded aside and put on the slide when it is
- // ready; the frame drawn here is the fallback for the next clip; a clip
- // with neither keeps the still there is (a kept frame, the post's
- // picture), soft but not black, replaced by a first frame when one comes.
+ // ready; the frame drawn here is the fallback for the next clip. A clip
+ // with neither gets no picture at all — and so stays out of the carousel
+ // (pagerReveal): the post's own still, put up meanwhile, was often not
+ // the clip's first frame, and the swap from one to the other jarred
+ // (Adam, 2026-10-17: "i don't want to show posters and then switch to
+ // the first frame … could we just always wait until we have a non-black
+ // frame before including the video in the pager?").
function slideFrame(s, k) {
const v = s.querySelector('video.mp-media');
if (!v || v._frame === 'first' || v._frameBusy) return;
const url = v.getAttribute('data-src');
const put = (p, kind) => {
if (!p || !pager || !s.isConnected || v._frame === 'first') return false;
- if (kind === 'soft' && (v._frame || pager.cur === s)) return false; // never a soft still under the clip on screen
v.setAttribute('poster', p); v._frame = kind;
pagerReveal();
return true;
};
- const soft = () => put(videoThumbs.get(url) || posterOf(s._ev, url), 'soft');
const first = serverFirst(url);
if (first && !serverFirstFailed.has(url)) {
v._frameBusy = true;
@@ -12926,10 +16367,8 @@ export function messagesFeature(ctx) {
if (k === 0 && !v._grabbed) { // the next clip: its opening is in the cache, the frame comes from there
v._grabbed = true;
v._frameBusy = true;
- pagerPoster(playSrc(url)).then((p) => { v._frameBusy = false; if (!put(p, 'first')) soft(); });
- return;
+ pagerPoster(playSrc(url)).then((p) => { v._frameBusy = false; put(p, 'first'); });
}
- if (first) soft(); // (the server had none: the still, if any, rather than black)
}
// The opening of a clip about to be reached, fetched into the browser's
// HTTP cache with a range request: the player's own request for the file
@@ -12968,6 +16407,11 @@ export function messagesFeature(ctx) {
function headStart(url, share = 1) {
if (!url || url.startsWith('blob:') || frugalData()) return Promise.resolve();
if (headStarted.has(url)) return headStarted.get(url);
+ if (isHls(url)) { // a stream's head start: its playlists and its first piece, the smaller rendition's
+ const task = hlsHead(url).catch(() => {}).finally(() => { headDone.add(url); pagerReveal(); });
+ headStarted.set(url, task);
+ return task;
+ }
const want = Math.max(HEAD_MIN, Math.round(headStartBytes(url) * share));
const t0 = performance.now();
const task = fetch(url, { headers: { Range: 'bytes=0-' + (want - 1) } }).then(async (r) => {
@@ -12987,6 +16431,16 @@ export function messagesFeature(ctx) {
if (headStarted.size > 300) { const k = headStarted.keys().next().value; headStarted.delete(k); headDone.delete(k); }
return task;
}
+ async function hlsHead(url) {
+ const get = async (u) => { const r = await fetch(u, { signal: AbortSignal.timeout(20_000) }); if (!r.ok) throw new Error('HTTP ' + r.status); return r; };
+ const uri = (text, base) => { const l = text.split('\n').map((x) => x.trim()).find((x) => x && !x.startsWith('#')); return l && new URL(l, base).href; };
+ const master = await get(url), text = await master.text();
+ // a master playlist's first rendition (vmedia lists the smaller first), or a media playlist itself
+ let list = text, at = master.url || url;
+ if (/#EXT-X-STREAM-INF/.test(text)) { at = uri(text, at); list = await (await get(at)).text(); }
+ const seg = uri(list, at);
+ if (seg) await (await get(seg)).arrayBuffer();
+ }
function playSlide(slide) {
const v = slide.querySelector('video.mp-media');
if (!v) return;
@@ -13051,6 +16505,9 @@ export function messagesFeature(ctx) {
else v.addEventListener('loadedmetadata', () => { try { v.currentTime = at; } catch {} }, { once: true });
}
v.muted = !pagerLoud;
+ v.volume = 1;
+ clearTimeout(v._primeTimer);
+ clockStart(slide, v);
v.play().catch((err) => {
// sound needs a tap the browser counted: play quietly, the button says so
if (err && err.name === 'NotAllowedError' && !v.muted) {
@@ -13060,6 +16517,37 @@ export function messagesFeature(ctx) {
}
});
}
+ // How long from landing on a clip to its picture moving, kept for the
+ // last hundred (coinosPagerStarts() in the console, and dlog), with what
+ // shape the player was in when the swipe landed (warm: it had its frame).
+ const pagerStarts = [];
+ function clockStart(slide, v) {
+ const t0 = slide._arriveAt;
+ slide._arriveAt = 0;
+ if (!t0) return;
+ const url = v.getAttribute('data-src') || '', warm = v.readyState >= 2, rs = v.readyState;
+ const primed = !!v._primed;
+ const buf = v.buffered && v.buffered.length ? +v.buffered.end(v.buffered.length - 1).toFixed(1) : 0;
+ const d = videoInfo.get(url) || {};
+ let host = ''; try { host = new URL(url).hostname; } catch {}
+ const done = () => {
+ const ms = Math.round(performance.now() - t0);
+ pagerStarts.push({ ms, warm, primed, rs, buf, host, mb: d.size ? +(d.size / 1e6).toFixed(1) : null, faststart: d.faststart ?? null, src: (v.getAttribute('src') || '').startsWith(VMEDIA) ? 'copy' : 'original', url });
+ if (pagerStarts.length > 100) pagerStarts.shift();
+ dlog('pager start', ms + ' ms', warm ? 'warm' : 'cold', host);
+ };
+ const tick = () => {
+ if (!v.isConnected || performance.now() - t0 > 20000) return;
+ if (v.currentTime > 0 && !v.paused) { done(); return; }
+ if (v.requestVideoFrameCallback) v.requestVideoFrameCallback(tick); else requestAnimationFrame(tick);
+ };
+ tick();
+ }
+ if (typeof window !== 'undefined') window.coinosPagerStarts = () => {
+ const ms = pagerStarts.map((x) => x.ms).sort((a, b) => a - b);
+ const q = (f) => ms.length ? ms[Math.min(ms.length - 1, Math.floor(f * ms.length))] : null;
+ return { n: ms.length, median: q(0.5), p90: q(0.9), max: ms.at(-1) ?? null, warm: pagerStarts.filter((x) => x.warm).length, starts: pagerStarts.slice() };
+ };
function pagerSound(on) {
pagerLoud = on;
if (!pager) return;
@@ -13073,7 +16561,7 @@ export function messagesFeature(ctx) {
// still after a fast flick; snapping stays off until it lands.
// A longer glide (a flight past several posts) says how long it takes;
// onDone hears the landing, or the interruption (true) that caught it.
- function pagerGlide(box, axis, to, vel = 0, { ms: want = 0, onDone = null } = {}) {
+ function pagerGlide(box, axis, to, vel = 0, { ms: want = 0, onDone = null, ease = 3 } = {}) {
pagerHold(box); // a glide under way is caught where it is
const y = axis === 'y', from = y ? box.scrollTop : box.scrollLeft, dist = to - from;
box.style.scrollSnapType = 'none';
@@ -13086,7 +16574,7 @@ export function messagesFeature(ctx) {
let t0 = 0;
const step = (now) => {
if (!t0) t0 = now - 8; // (a frame's worth in already: no frame stands still)
- const k = Math.max(0, Math.min(1, (now - t0) / ms)), e = 1 - Math.pow(1 - k, 3);
+ const k = Math.max(0, Math.min(1, (now - t0) / ms)), e = 1 - Math.pow(1 - k, ease);
if (y) box.scrollTop = from + dist * e; else box.scrollLeft = from + dist * e;
if (k < 1) box._glide = requestAnimationFrame(step); else done();
};
@@ -13115,12 +16603,9 @@ export function messagesFeature(ctx) {
if (v) {
const groups = pagerGroups();
const from = here && here.closest('.mp-group');
- const index = groups.indexOf(from) + v;
- const to = groups[(index + groups.length) % groups.length];
- if (to) {
- if (index < 0 || index >= groups.length) pagerWrap(to);
- else pagerGlide(pager.scroller, 'y', pagerAt(pager.scroller, to, true));
- }
+ // the ends are ends: no going round to the other (Adam, 2026-10-18)
+ const to = groups[groups.indexOf(from) + v];
+ if (to) pagerGlide(pager.scroller, 'y', pagerAt(pager.scroller, to, true));
return !!to;
}
if (hz) {
@@ -13139,6 +16624,15 @@ export function messagesFeature(ctx) {
// it is passing and steps back from there; a touch or a key catches it
// too (pagerHold → onDone). A notch from rest is the single step it was.
let fly = null; // { to: the post flown to, n: notches in this run, at, dir }
+ // A pager flies only once ten posts are ready (in the carousel: clips
+ // ready to play, pictures decoded): before that a fling outran the
+ // warming, landing on whatever was ready and fighting the posts joining
+ // (Adam, 2026-10-17: "let's not allow flying/coasting until we have at
+ // least 10 videos fully warmed up"; the picture pager the same: "image
+ // pager should work similar"). Until then a flick or a spin of the wheel
+ // is one post at a time.
+ const PAGER_FLY_READY = 10;
+ const pagerCanFly = () => !pager || (pager.kind === 'videos' && frugalData()) || pagerGroups().length >= PAGER_FLY_READY;
function pagerFly(dir, now) {
if (!pager) return;
const stops = pagerGroups();
@@ -13153,10 +16647,10 @@ export function messagesFeature(ctx) {
const here = pagerHere();
from = here && here.closest('.mp-group');
}
- const next = stops.indexOf(from) + dir * (n <= 2 ? 1 : 2);
- const i = (next % stops.length + stops.length) % stops.length;
- if (next < 0 || next >= stops.length) { fly = null; pagerWrap(stops[i]); return; }
+ // a flight stops at the end it reaches
+ const i = Math.min(stops.length - 1, Math.max(0, stops.indexOf(from) + dir * (n <= 2 || !pagerCanFly() ? 1 : 2)));
const to = stops[i];
+ if (to === from && !live) return;
fly = { to, n, at: now, dir };
if (live) pager.scroller._onDone = null; // the flight goes on: not a landing
pagerFlyTo(to);
@@ -13168,14 +16662,30 @@ export function messagesFeature(ctx) {
const dest = pagerAt(pager.scroller, to, true);
const screens = Math.abs(dest - pager.scroller.scrollTop) / Math.max(1, pager.scroller.clientHeight);
pager.flying = true;
+ pager.flyDir = Math.sign(dest - pager.scroller.scrollTop);
const land = pager.kind === 'videos' && !frugalData() && rowSlide(to); // the landing's first frame, fetched on the way
if (land) slideFrame(land, -1);
+ // A flight eases out on a square, not a cube: on a cube a long one
+ // spent its last 400 ms creeping under 3 px a frame (Adam's phone, a
+ // nine-post flight), and the picture coming to rest stepped a pixel
+ // at a time — the stutter "towards the end of the fly as it's
+ // snapping" (Adam, 2026-10-17); and it set off at three times its
+ // average speed, faster than the finger that flung it.
pagerGlide(pager.scroller, 'y', dest, vel, {
+ ease: screens > 1.05 ? 2 : 3,
ms: screens > 1.05 ? Math.min(most, 100 + pace * screens) : 0,
- onDone: () => { if (!pager) return; pager.flying = false; const s = pagerHere(); if (s && s !== pager.cur) pagerArrive(s); },
+ onDone: () => { if (!pager) return; pager.flying = false; const s = pagerHere(); if (s && s !== pager.cur) pagerArrive(s); pagerPosition(); },
});
}
const pagerArrive = (slide) => { if (pager && pager.arrive) pager.arrive(slide); };
+ // A finger down on a flight stops it there and then, settling on the post
+ // most on screen (Adam, 2026-10-17: "Tapping … should instantly stop the
+ // flying … and snap to the video that's most on screen").
+ function pagerCatch() {
+ pagerHold(pager.scroller); // the flight's onDone: no longer flying, arrived at the post most on screen
+ const here = pagerHere(), g = here && here.closest('.mp-group');
+ if (g) pagerGlide(pager.scroller, 'y', pagerAt(pager.scroller, g, true));
+ }
// the sideways arrows show only where the post has a picture that way
function pagerArrows(slide) {
if (!pager || !slide) return;
@@ -13183,37 +16693,44 @@ export function messagesFeature(ctx) {
pager.el.classList.toggle('has-right', !!slide.nextElementSibling);
}
- // Crossing the boundary jumps directly to the other end, without flying
- // backwards through every loaded post or waiting for a network request.
- function pagerWrap(group) {
- if (!pager || !group) return;
- pager.scroller._onDone = null;
- pagerHold(pager.scroller);
- pager.scroller.style.scrollSnapType = '';
- pager.flying = false;
- const slide = rowSlide(group);
- if (slide) { pagerShow(slide); pagerArrive(slide); }
- }
+ // Counted: the posts in the carousel — the ones that can be reached. (All
+ // the posts found, the waiting ones too, was tried and undone: a count
+ // that can't be scrolled to confused — Adam, 2026-10-17.)
function pagerPosition() {
if (!pager) return;
const groups = pagerGroups();
const slide = pager.cur || pager.anchor;
- const index = groups.indexOf(slide && slide.closest('.mp-group'));
- pager.el.querySelector('.mp-position').textContent = (index < 0 ? 0 : index + 1) + ' / ' + groups.length;
+ let index = groups.indexOf(slide && slide.closest('.mp-group'));
+ // in a flight, the post passing under the reader: the count runs with
+ // the slides rather than jumping on landing (Adam, 2026-10-17: "the
+ // counter should animate as we fly")
+ if (pager.flying && groups.length) {
+ const y = pager.scroller.scrollTop + pager.scroller.clientHeight / 2;
+ let lo = 0, hi = groups.length - 1; // the last post whose top is above the middle of the screen
+ while (lo < hi) { const m = (lo + hi + 1) >> 1; if (groups[m].offsetTop <= y) lo = m; else hi = m - 1; }
+ index = lo;
+ }
+ const text = (index < 0 ? 0 : index + 1) + ' / ' + groups.length, el = pager.el.querySelector('.mp-position');
+ if (el.textContent !== text) el.textContent = text;
+ // a video pager shows no count until it can fly: ten clips ready (Adam,
+ // 2026-10-17: "let's also not show the position/total counter until we have 10")
+ // (one with fewer posts than that, every one of them ready, counts them)
+ pager.el.classList.toggle('few', !pagerCanFly() && !!pager.scroller.querySelector(':scope > .mp-group.mp-wait:not(.mp-off)'));
}
function buildPager(want) {
const video = want.kind === 'videos';
const scroller = h('div', { class: 'mp-scroll' });
+ scroller.addEventListener('scroll', () => { if (pager && pager.flying) pagerPosition(); }, { passive: true });
const el = h('div', { class: 'media-pager' + (video ? ' videos' : '') + (pagerLoud ? '' : ' quiet'), role: 'dialog', 'aria-modal': 'true' },
scroller,
h('div', { class: 'mp-position', role: 'status' }, '0 / 0'),
h('div', { class: 'mp-top' },
h('button', { class: 'mp-x', type: 'button', 'aria-label': t('close'), onClick: (e) => { e.stopPropagation(); dismissPager(); } }, '×'),
- video ? h('div', { class: 'mp-top-r' },
- clipsToggle('mp-fit', () => pagerFit()),
- h('button', { class: 'mp-sound', type: 'button', onClick: (e) => { e.stopPropagation(); pagerSound(!pagerLoud); } },
- h('span', { class: 'on' }, '\u{1F50A}'), h('span', { class: 'off' }, '\u{1F507} ' + t('videoUnmute')))) : null),
+ h('div', { class: 'mp-top-r' },
+ clipsToggle('mp-fit', () => { pagerFit(); pagerWarmPics(); }),
+ video ? h('button', { class: 'mp-sound', type: 'button', onClick: (e) => { e.stopPropagation(); pagerSound(!pagerLoud); } },
+ h('span', { class: 'on' }, '\u{1F50A}'), h('span', { class: 'off' }, '\u{1F507} ' + t('videoUnmute'))) : null)),
// a mouse's way through (shown where there is a pointer to hover with,
// style.css): up and down the posts at the right edge, left and right
// along a post's pictures when it has more than one (has-left/right)
@@ -13284,10 +16801,16 @@ export function messagesFeature(ctx) {
let touch = null, pendingTap = 0, tapDoneAt = 0;
el.addEventListener('touchstart', (e) => {
const t = e.touches[0];
+ // caught in flight: stopped where it is (a two-finger touch, a touch
+ // on the seek bar too); a swipe back from there is the post before it
+ // however hard (Adam, 2026-10-17: "reverse swiping should go to the
+ // previous video"), one on the way it was flying takes it on
+ const caught = !!pager && pager.flying && !!pager.scroller._glide ? pager.flyDir || 0 : 0;
+ if (caught) pagerCatch();
const img = e.target.closest && e.target.closest('img.mp-media');
// not a touch on the seek bar, in an opened caption, or on a picture zoomed in (each its own)
touch = e.touches.length === 1 && pager && !e.target.closest('.mp-seek, .mp-caption.open') && !(img && img.style.touchAction === 'none')
- ? { x: t.clientX, y: t.clientY, at: Date.now(), slide: pager.cur, target: e.target } : null;
+ ? { x: t.clientX, y: t.clientY, at: Date.now(), slide: pager.cur, target: e.target, caught } : null;
}, { passive: true });
el.addEventListener('touchmove', (e) => {
const d = touch;
@@ -13307,7 +16830,15 @@ export function messagesFeature(ctx) {
const delta = d.axis === 'y' ? dy : dx;
d.far = Math.max(d.far || 0, Math.hypot(dx, dy));
if (d.axis === 'y') d.box.scrollTop = d.start - delta; else d.box.scrollLeft = d.start - delta;
- d.track.push({ t: performance.now(), v: delta }); // (when handled: synthetic moves can share a timeStamp)
+ // Timed when the finger moved (the event's timeStamp), not when the
+ // move was handled: right after a refresh, with clips warming, moves
+ // queue behind other work and arrive in bursts — timed on handling, a
+ // burst after a stall read as a fling (a short flick flew) and a
+ // stall at the end as a crawl (a long flick took one step) (Adam,
+ // 2026-10-17: "sometimes a quick long flick only proceeds to the next
+ // video … sometimes … a short flick does fly"). The handling time is
+ // kept for moves that share a timeStamp (synthetic ones can).
+ d.track.push({ t: e.timeStamp, h: performance.now(), v: delta });
while (d.track.length > 2 && d.track[d.track.length - 1].t - d.track[1].t >= TRACK_MS) d.track.shift();
}, { passive: false });
// let go of a drag: on to the next (or the one before), or back
@@ -13317,14 +16848,15 @@ export function messagesFeature(ctx) {
if (!stops.length) return;
// the stop it set off from, then one along (or back) — or, flung, several
const from = stops.reduce((bi, p, i) => (Math.abs(p - d.start) < Math.abs(stops[bi] - d.start) ? i : bi), 0);
- const posts = y && step && Math.abs(vel) >= FLY_V ? Math.min(FLY_MAX, Math.max(1, Math.round(Math.abs(vel) * FLY_TAU / Math.max(1, box.clientHeight)))) : 1;
+ const posts = y && step && Math.abs(vel) >= FLY_V && pagerCanFly() && !(d.caught && step !== d.caught) ? Math.min(FLY_MAX, Math.max(1, Math.round(Math.abs(vel) * FLY_TAU / Math.max(1, box.clientHeight)))) : 1;
+ // past either end, it stops at the end: going round to the other end
+ // was tried and undone (Adam, 2026-10-18: "let's not make the media
+ // pager circle around to the start anymore")
const next = from + step * posts;
if (y && posts > 1) {
const i = Math.min(stops.length - 1, Math.max(0, next));
if (i !== from) { pagerFlyTo(pagerGroups()[i], { vel, pace: 260, most: 4000 }); return; }
}
- // past either end: round to the other (a fling at the end too — one post of wrap, not its whole count)
- if (y && (next < 0 || next >= stops.length)) { pagerWrap(pagerGroups()[(from + step + stops.length) % stops.length]); return; }
pagerGlide(box, d.axis, stops[Math.min(stops.length - 1, Math.max(0, next))], vel);
}
el.addEventListener('touchend', (e) => {
@@ -13336,18 +16868,21 @@ export function messagesFeature(ctx) {
const delta = d.axis === 'y' ? t.clientY - d.y : t.clientX - d.x;
const size = d.axis === 'y' ? d.box.clientHeight : d.box.clientWidth;
const a = d.track[0], b = d.track[d.track.length - 1];
- const vel = a && b && b.t > a.t ? (b.v - a.v) / (b.t - a.t) : 0;
+ const dt = a && b ? (b.t - a.t >= 8 ? b.t - a.t : b.h - a.h) : 0;
+ const vel = dt > 0 ? (b.v - a.v) / dt : 0;
const tap = d.far < TAP_SLOP && Date.now() - d.at < TAP_MS;
const go = !tap && (Math.abs(delta) > size * (d.axis === 'y' ? SWIPE_Y : SWIPE_X) || (Math.abs(delta) >= FLICK_MIN && Math.abs(vel) > FLICK && Math.sign(vel) === Math.sign(delta)));
settle(d, go ? (delta < 0 ? 1 : -1) : 0, go ? vel : 0);
if (!tap) return;
}
+ // the tap that caught a flight only stopped it (the buttons still work)
+ if (d.caught && !(d.target.closest && d.target.closest('button, a'))) { tapDoneAt = Date.now(); return; }
if (Date.now() - d.at > 500) return; // a press, not a tap
clearTimeout(pendingTap);
pendingTap = setTimeout(() => {
pendingTap = 0;
const btn = d.target.closest && d.target.closest('button, a');
- if (btn) btn.click(); else pagerTap(d.target); // (the click here is before tapDoneAt: not swallowed)
+ if (btn) btn.click(); else pagerTap(d.target, t.clientY); // (the click here is before tapDoneAt: not swallowed)
tapDoneAt = Date.now();
}, 120);
}, { passive: true });
@@ -13362,11 +16897,23 @@ export function messagesFeature(ctx) {
if (pendingTap) { clearTimeout(pendingTap); pendingTap = 0; }
else if (Date.now() - tapDoneAt < 700) { e.stopPropagation(); e.preventDefault(); }
}, true);
- el.addEventListener('click', (e) => pagerTap(e.target));
+ el.addEventListener('click', (e) => pagerTap(e.target, e.clientY));
+ // On a desktop the bar comes up while the mouse moves over a playing
+ // clip and fades once it's been still a moment (Adam, 2026-10-22).
+ el.addEventListener('pointermove', (e) => {
+ if (e.pointerType !== 'mouse' || !pager || !video) return;
+ const bar = pager.cur && pager.cur.querySelector('.mp-seek.ready');
+ if (bar) revealSeek(bar, 2000);
+ });
// a tap shows (or hides) who posted it and what they said
- function pagerTap(target) {
+ function pagerTap(target, y) {
if (target.closest('button, a, .mp-caption, .mp-seek')) return;
if (Date.now() - videoTapAt < 800) return; // the click of the touch that opened it
+ // The seek bar is out of sight while a clip plays (Adam, 2026-10-19:
+ // only when someone goes for it, or pauses): a tap near the foot of
+ // the screen, where it sits, brings it up without pausing.
+ const bar = pager && video && pager.cur && pager.cur.querySelector('.mp-seek.ready');
+ if (bar && y != null && !el.classList.contains('show') && y >= bar.getBoundingClientRect().top - 72) { revealSeek(bar); return; }
if (pager && video) {
// A clip (from the feed or the media grid): a tap anywhere but the
// seek bar and the buttons pauses it and brings up who posted it,
@@ -13421,6 +16968,7 @@ export function messagesFeature(ctx) {
pager.cur = slide;
pager.anchor = slide;
pager.curAt = Date.now();
+ slide._arriveAt = performance.now();
pagerSharpen(slide);
pagerArrows(slide);
pagerPosition();
@@ -13429,6 +16977,7 @@ export function messagesFeature(ctx) {
playSlide(slide);
pagerCounts(slide);
pagerLoadAhead();
+ pagerWarmPics();
};
pager.io = new IntersectionObserver((entries) => {
for (const e of entries) {
@@ -13453,8 +17002,9 @@ export function messagesFeature(ctx) {
// clip's slide is off its mark, and the bar rode along with it, a
// white line sliding up the screen (Adam, 2026-10-16: "i don't want to
// see the seek bar while i'm transitioning to the next video"). It
- // fades back in once the clip is square on the screen.
- if (video) {
+ // fades back in once the clip is square on the screen. (The motion flag
+ // is a picture pager's too: its counter shows while it moves.)
+ {
const p = pager;
const frame = () => {
if (pager !== p) return;
@@ -13520,7 +17070,8 @@ export function messagesFeature(ctx) {
try {
// Bound each run; the timer resumes if sparse media needs more pages.
for (let pages = 0; pages < 8 && pager === p; pages++) {
- if (pagerGroups().length >= Math.max(PAGER_INITIAL, p.furthest + 1 + PAGER_AHEAD)) break;
+ // (the posts found, waiting ones too: ready ones come only as fast as they warm)
+ if (pagerFound().length >= Math.max(PAGER_INITIAL, p.furthest + 1 + PAGER_AHEAD)) break;
const src = pagerLoadSource(p);
if (src.done()) break;
const before = src.progress();
@@ -13543,7 +17094,7 @@ export function messagesFeature(ctx) {
const c = feedNow();
pager.groups ||= new Map();
const src = pagerSource();
- for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind))) {
+ for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind, true))) {
const k = mediaKey(it);
if (pager.keys.has(k)) continue;
pager.keys.add(k);
@@ -13552,7 +17103,8 @@ export function messagesFeature(ctx) {
let g = pager.groups.get(gk);
if (!g) {
g = pagerGroup();
- if (pager.kind === 'videos' && !frugalData()) g.classList.add('mp-wait'); // out of the carousel until its clip is ready to play
+ // out of the carousel until it's ready: a clip to play, a picture decoded
+ if (pager.kind === 'images' || !frugalData()) g.classList.add('mp-wait');
pager.groups.set(gk, g);
pager.scroller.append(g);
}
@@ -13564,6 +17116,53 @@ export function messagesFeature(ctx) {
}
pagerFit();
pagerPosition();
+ pagerWarmPics();
+ }
+ // A picture post is ready once its picture is decoded: only then does it
+ // join the carousel, so a flight passes over pictures already in hand.
+ // They were fetched and decoded as the flight came near them, and the
+ // flight stuttered — dropped frames with no script running, the decoding
+ // (Adam, 2026-10-17: "some stutter/choppiness when flying images"; seen
+ // on his phone: 66 ms frames mid-flight as pictures arrived). A few at a
+ // time are decoded ahead of the reader (and a few behind, for the way
+ // back), out of sight; its size learned, a picture the wrong way round
+ // for the screen stays out like a clip (pagerFit). One that can't be had
+ // at all — copy and original both gone — stays out.
+ const PIC_WARM_AT_ONCE = 4, PIC_READY_AHEAD = 16, PIC_WARM_BEHIND = 3;
+ function pagerWarmPics() {
+ if (!pager || pager.kind !== 'images') return;
+ const all = pagerFound();
+ const cur = pager.cur || pager.anchor, ci = Math.max(0, all.indexOf(cur && cur.closest('.mp-group')));
+ let busy = all.filter((g) => g._warming).length;
+ const want = (g) => g.classList.contains('mp-wait') && !g._warming && !g._failed;
+ for (let j = ci + 1, ready = 0; j < all.length && busy < PIC_WARM_AT_ONCE && ready < PIC_READY_AHEAD; j++) {
+ if (!all[j].classList.contains('mp-wait')) { ready++; continue; }
+ if (want(all[j])) { warmPic(all[j]); busy++; }
+ }
+ for (let j = ci - 1; j >= Math.max(0, ci - PIC_WARM_BEHIND) && busy < PIC_WARM_AT_ONCE; j--) if (want(all[j])) { warmPic(all[j]); busy++; }
+ }
+ function warmPic(g) {
+ const p = pager;
+ g._warming = true;
+ for (const x of g._row.children) pagerAttach(x);
+ const m = g._row.firstElementChild && g._row.firstElementChild.querySelector('img.mp-media');
+ // the copy failing falls back to the original (its onError): decoded again
+ const decode = (n) => {
+ const src = m.getAttribute('src');
+ return m.decode().then(() => true, () => new Promise((r) => setTimeout(r, 60)).then(() =>
+ n < 2 && m.getAttribute('src') !== src && !m.closest('.mp-slide').classList.contains('mp-gone') ? decode(n + 1) : false));
+ };
+ const timeout = new Promise((r) => setTimeout(() => r(false), 20000));
+ Promise.race([m ? decode(0) : Promise.resolve(true), timeout]).then((ok) => {
+ g._warming = false;
+ if (pager !== p || !g.isConnected) return;
+ if (!ok) { g._failed = true; pagerWarmPics(); return; }
+ const url = m && m.getAttribute('data-full');
+ if (url && m.naturalWidth && !mediaReady.has(url)) mediaReady.set(url, { width: m.naturalWidth, height: m.naturalHeight }); // its shape
+ pagerFit();
+ pagerToggleGroup(g, 'mp-wait', false);
+ pagerWarmPics();
+ });
}
// A post's clip is ready to play when its first frame is on the slide and
// its opening is in the cache (the head start done): only then does the
@@ -13589,10 +17188,15 @@ export function messagesFeature(ctx) {
// the posts whose clips are the wrong way round for the screen stay out
// (not the one opened on; a shape not yet known is let in)
function pagerFit() {
- if (!pager || pager.kind !== 'videos') return;
+ if (!pager) return;
const cur = pager.cur || pager.anchor, cg = cur && cur.closest('.mp-group');
+ // the grid's pager goes by the grid's rule: a clip of a shape not yet
+ // known stays out until it's measured (fitClip measures it); a page's
+ // pager shows one until it's known not to fit
+ const strict = pager.kind === 'videos' && !pagerSource();
+ const ok = (u) => (strict ? fitClip(u) : clipFits(u) !== false);
for (const g of pagerGroups(true)) {
- const fits = g._opened || g === cg || [...g._row.children].some((s) => { const v = s.querySelector('video.mp-media'); return !v || clipFits(v.getAttribute('data-src')) !== false; });
+ const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || ok(m.getAttribute('data-full') || m.getAttribute('data-src')); });
pagerToggleGroup(g, 'mp-off', !fits);
}
}
@@ -13645,6 +17249,9 @@ export function messagesFeature(ctx) {
window.addEventListener('popstate', () => setTimeout(syncMediaPager, 0));
}
+ // what the feed floats over the page (post button, new-posts pill): the
+ // shell takes them each render, see pageFloaters in the hooks
+ let pageFloaters = [];
function feedView() {
syncFollowSets().catch(() => {}); // throttled inside
syncReports().catch(() => {}); // likewise
@@ -13654,7 +17261,7 @@ export function messagesFeature(ctx) {
const c = feedNow();
c.opened = true;
const def = feedDef();
- const visitor = isVisitor();
+ const visitor = visitorView();
queueMicrotask(() => {
syncMediaPager();
if (listView()) watchSeen();
@@ -13671,7 +17278,10 @@ export function messagesFeature(ctx) {
// their settled presentation once the warm-up lands. The spinner is
// for a feed with nothing cached at all.
const curatedFeed = !!(feedDef(c.id) || {}).curated;
- const shownHere = (ev) => !hidden(ev) && !(curatedFeed && notForPublic(ev));
+ // (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) && !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
@@ -13706,9 +17316,28 @@ export function messagesFeature(ctx) {
}, '↑ ', h('span', { class: 'n', 'data-key': 'n:' + waiting }, String(waiting)), ' ',
waiting === 1 ? t('feedOneNewWord') : t('feedNNewWord'))
: null;
+ // The post button floats bottom right wherever the reader is in the
+ // feed; the composer opens at the top and takes the focus. It and the
+ // pill are position: fixed — and a page sliding in has a transform on
+ // it, which makes fixed descendants position within the page instead:
+ // the button rode at the foot of the feed card, below the screen, until
+ // the entrance animation ended ("not seeing the Post button right away",
+ // Adam, 2026-11-02; measured on his phone: 4109 px down at 87 ms, in
+ // place at 562 ms). So they're handed to the shell, which paints them
+ // beside the page, outside anything that animates.
+ const fab = visitor || ui.profCompose != null ? null : h('button', {
+ class: 'btn-primary feed-post-fab', 'data-key': 'feed-post-fab', type: 'button', title: t('profNewPost'), 'aria-label': t('profNewPost'),
+ onClick: () => {
+ ui.profCompose = draftFor(POST_DRAFT) || '';
+ render();
+ try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch { window.scrollTo(0, 0); }
+ setTimeout(() => document.querySelector('.post-input')?.focus(), 60);
+ },
+ }, h('span', { class: 'feed-compose-icon', 'aria-hidden': 'true', html:
+ '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path stroke="currentColor" d="M12 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6"/><path stroke="currentColor" opacity=".5" d="M8 17h5"/><path class="compose-pen-fill" d="m16.5 3.5 3 3-8 8-4 1 1-4Z"/><path class="compose-pen" d="M16.5 3.5a2.1 2.1 0 0 1 3 3l-8 8-4 1 1-4Z"/><path class="compose-pen" d="m14.5 5.5 3 3"/></svg>' }), h('span', {}, t('feedPostFab')));
+ pageFloaters = [pill, fab].filter(Boolean);
// the chat shell draws the brand header; this is just the page under it
return h('div', { class: 'card col chat-page feed-page', style: 'gap:10px' },
- h('div', { 'data-key': 'feed-notice', style: 'display:contents' }, pill),
h('div', { class: 'row gap6', style: 'align-items:center' },
backBtn(() => {
stopFeedWatch();
@@ -13730,19 +17359,7 @@ export function messagesFeature(ctx) {
),
ui.feedRelayEdit && ui.feedRelayEdit.id === def.id ? relayPanel(def) : null,
visitor ? null : feedChips(),
- mediaModes(),
- // floating bottom right, wherever the reader is in the feed: the
- // composer opens at the top and takes the focus
- visitor || ui.profCompose != null ? null : h('button', {
- class: 'btn-primary feed-post-fab', 'data-key': 'feed-post-fab', type: 'button', title: t('profNewPost'), 'aria-label': t('profNewPost'),
- onClick: () => {
- ui.profCompose = draftFor(POST_DRAFT) || '';
- render();
- try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch { window.scrollTo(0, 0); }
- setTimeout(() => document.querySelector('.post-input')?.focus(), 60);
- },
- }, h('span', { class: 'feed-compose-icon', 'aria-hidden': 'true', html:
- '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path stroke="currentColor" d="M12 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6"/><path stroke="currentColor" opacity=".5" d="M8 17h5"/><path class="compose-pen-fill" d="m16.5 3.5 3 3-8 8-4 1 1-4Z"/><path class="compose-pen" d="M16.5 3.5a2.1 2.1 0 0 1 3 3l-8 8-4 1 1-4Z"/><path class="compose-pen" d="m14.5 5.5 3 3"/></svg>' }), h('span', {}, t('feedPostFab'))),
+ (refreshLive(), mediaModes()),
visitor ? null : postComposer(),
def.of && !ofLoaded(def)
? h('div', { class: 'row gap6', style: 'justify-content:center;align-items:center;padding:12px 0' },
@@ -13759,6 +17376,7 @@ export function messagesFeature(ctx) {
: h('div', { class: 'col', style: 'gap:8px' },
h('div', { class: 'small muted' }, t('feedNoQuery')),
h('button', { class: 'btn-sm', onClick: () => openFeedEditor(def) }, t('feedEdit')))
+ : mediaMode === 'live' ? liveGrid(def)
: (c.booting || c.status === 'loading') && !visible.length
? h('div', { class: 'row gap6', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
: !visible.length
@@ -13770,10 +17388,11 @@ export function messagesFeature(ctx) {
// posts on their way, or nothing older left to fetch. (Older pages
// prepare offscreen, so the line is mostly seen by a reader who
// outruns them.)
- c.loadingMore || (mediaMode === 'articles' ? articlesCrawling && mediaIndex(c.id).articles.size : !listView() && mediaCrawling)
+ mediaMode === 'live' ? null
+ : c.loadingMore || (mediaMode === 'articles' ? articlesCrawling && mediaIndex(c.id).articles.size : !listView() && mediaCrawling)
? h('div', { class: 'row gap6 feed-foot', style: 'justify-content:center;align-items:center;padding:10px 0' },
h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('feedLoadingMore')))
- : !listView() ? ((mediaMode === 'articles' ? mediaIndex(c.id).art.end : mediaIndex(c.id).end) ? h('div', { class: 'small faint feed-foot', style: 'text-align:center;padding:10px 0' }, t('feedEnd')) : null)
+ : !listView() ? (mediaMode === 'articles' && mediaIndex(c.id).art.end ? h('div', { class: 'small faint feed-foot', style: 'text-align:center;padding:10px 0' }, t('feedEnd')) : null)
: c.end && visible.length && !(c.win && c.win.bottom) && c.shown >= visible.length
? h('div', { class: 'small faint feed-foot', style: 'text-align:center;padding:10px 0' }, t('feedEnd'))
: null,
@@ -14002,25 +17621,170 @@ export function messagesFeature(ctx) {
e.id && !e.isNew ? h('button', { class: 'btn-ghost btn-block', onClick: () => deleteFeed(e.id) }, t('feedDelete')) : null);
}
+ // People search looks among your follows first (recipient-search.js). Their
+ // names come from the profiles this device holds; the ones it has never
+ // seen are fetched once a session, the first time a search asks.
+ let followFacesAsked = false, followFacesPending = false;
+ setLocalPeople(() => {
+ const set = follows && follows.set;
+ if (!set || !set.size) return [];
+ if (!followFacesAsked) {
+ followFacesAsked = true;
+ const missing = [...set].filter((pk) => !profiles.get(pk)?.name && !profInFlight.has(pk));
+ if (missing.length) {
+ followFacesPending = true;
+ fetchProfiles(missing.slice(0, 2000)).catch(() => {}).finally(() => { followFacesPending = false; });
+ }
+ }
+ const out = [];
+ out.partial = followFacesPending;
+ for (const pk of set) {
+ const p = profiles.get(pk);
+ if (p && (p.name || p.nip05)) out.push({ pk, name: p.name, nip05: p.nip05, picture: p.picture });
+ }
+ return out;
+ });
+
// ---- user search: the header magnifier ----------------------------------
// Same engine the Send form and DMs use (registrar names + Primal cache +
// NIP-50 relays); tapping a result opens their profile, and profile-Back
// lands here again since the search state survives.
const userSearcher = makeSearcher((q, rows) => {
if (ui.userSearch && ui.userSearch.q === q) { ui.userSearch.rows = rows; render(); }
- for (const r of rows || []) if (r.pk) prefetchProfilePage(r.pk);
+ // the likely taps: the top two, warmed first (their posts, profile and
+ // cover) — not every row of every letter typed, which queued the one
+ // tapped behind a dozen others
+ if (!ui.userSearch || ui.userSearch.q !== q) return;
+ const top = (rows || []).filter((r) => r.pk).slice(0, 2);
+ for (const r of top.reverse()) prefetchProfilePage(r.pk, { first: true });
});
+ // ---- searching inside someone's posts --------------------------------
+ // "i found him by searching franca but then i was wanting some way to
+ // search his feed for something … i was wanting to search 'franca
+ // wildwood' but knew it wouldn't work" (Adam, 2026-11-14). Two ways in,
+ // no new field: a profile on screen puts its person in the search field as
+ // a chip (× or Backspace takes it out), and words that start or end with
+ // someone's name ("franca wildwood") are offered as that person's posts.
+ const viewedProfiles = new Map(); // pk -> when its profile was opened (this session)
+ // Whose posts the field searches: the open profile's person (unless taken
+ // out), else whoever the search page was scoped to.
+ function searchScope() {
+ if (ui.profilePk) return ui.searchScopeOff === ui.profilePk ? null : ui.profilePk;
+ return (ui.userSearch && ui.userSearch.scope) || null;
+ }
+ function unscopeSearch() {
+ if (ui.profilePk) ui.searchScopeOff = ui.profilePk;
+ if (ui.userSearch) ui.userSearch.scope = null;
+ if (ui.userSearch) guessScope(ui.userSearch.q || '');
+ render();
+ setTimeout(() => document.querySelector('.header-search-field, .user-search-input.user-search-main')?.focus(), 30);
+ }
+ function scopeChip() {
+ const pk = searchScope();
+ if (!pk) return null;
+ return h('span', { class: 'search-scope-chip', title: t('searchInPosts', { name: displayName(pk) }) },
+ avatar(pk, 'chat-avatar mini', false),
+ h('span', { class: 'search-scope-name' }, displayName(pk)),
+ h('button', { type: 'button', class: 'search-scope-x', 'aria-label': t('searchScopeRemove'), onMousedown: (e) => e.preventDefault(), onClick: unscopeSearch }, '\u00d7'));
+ }
+ // "franca wildwood": the first or last word or two may be a person. Asked
+ // of the people search; a hit must have the word at the start of a word of
+ // its name or address. Someone you follow, or whose profile you opened
+ // this session, is a strong guess (Enter goes there); anyone else is only
+ // offered as a row ("bitcoin wallet" is not Bitcoin Magazine's posts).
+ let guessSeq = 0, guessTimer = null;
+ function guessScope(q) {
+ clearTimeout(guessTimer);
+ const my = ++guessSeq;
+ const s = ui.userSearch;
+ if (s) s.guess = null;
+ const words = String(q || '').trim().split(/\s+/).filter(Boolean);
+ if (!s || s.scope || words.length < 2 || words.length > 8) return;
+ const splits = [[words.slice(0, 1), words.slice(1)], [words.slice(-1), words.slice(0, -1)]];
+ if (words.length >= 3) splits.push([words.slice(0, 2), words.slice(2)], [words.slice(-2), words.slice(0, -2)]);
+ guessTimer = setTimeout(async () => {
+ let best = null;
+ await Promise.all(splits.map(async ([who, what]) => {
+ const part = who.join(' ').replace(/^@/, '');
+ if (part.length < 3 || !searchable(part)) return;
+ const rows = await searchRecipients(part).catch(() => []);
+ const needle = ' ' + foldText(part);
+ rows.slice(0, 6).forEach((r, i) => {
+ if (!r.pk) return;
+ const hay = ' ' + foldText([r.name, r.address, r.nip05].filter(Boolean).join(' ')).replace(/[^\p{L}\p{N}]+/gu, ' ');
+ if (!hay.includes(needle)) return;
+ const known = isFollowing(r.pk) || viewedProfiles.has(r.pk);
+ const score = (known ? 100 : 0) + who.length * 5 + (i === 0 ? 3 : 0) - i;
+ if (!best || score > best.score) best = { pk: r.pk, text: what.join(' '), score, strong: known };
+ });
+ }));
+ if (my !== guessSeq || ui.userSearch !== s || s.q !== q) return;
+ s.guess = best;
+ render();
+ }, 300);
+ }
+ // A guess is off when the whole query is someone's name ("jack dorsey").
+ function usableGuess(s) {
+ const g = s && s.guess;
+ if (!g || s.scope) return null;
+ const whole = foldText(s.q).trim();
+ if ((s.rows || []).some((r) => foldText(r.name).includes(whole))) return null;
+ return g;
+ }
+ // Where Enter goes: the scoped search, a strong guess, else everywhere.
+ function submitUserSearch(q) {
+ q = String(q || '').trim();
+ if (!q) return;
+ const scope = searchScope();
+ const s = ui.userSearch;
+ const g = s && s.q.trim() === q ? usableGuess(s) : null;
+ if (scope) openTextSearch(q, [], [scope]);
+ else if (g && g.strong) openTextSearch(g.text, [], [g.pk]);
+ else openTextSearch(q);
+ render();
+ }
+ function scopedRows(s) {
+ const q = s.q.trim();
+ if (q.length < 2 || /^(npub1|nprofile1|nevent1|note1|naddr1|nostr:)/i.test(q)) return [];
+ const scope = searchScope(), g = usableGuess(s);
+ const row = (pk, words, enter) => h('div', { class: 'item chat-thread-row search-scoped-row', onClick: () => { openTextSearch(words, [], [pk]); render(); } },
+ avatar(pk, 'chat-avatar', false),
+ h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
+ h('span', { class: 'chat-name' }, '\u201c' + words + '\u201d'),
+ h('div', { class: 'muted small' }, t('searchInPosts', { name: displayName(pk) }))),
+ enter ? h('kbd', { class: 'search-enter-hint' }, '\u21b5') : null);
+ if (scope) return [row(scope, q, true)];
+ if (g) return [row(g.pk, g.text, g.strong)];
+ return [];
+ }
+
function userSearchScreen() {
const s = ui.userSearch;
+ const scoped = scopedRows(s);
return h('div', { class: 'col', style: 'gap:16px' },
ctx.brandHeader(!ui.pubProf && wallet.loaded),
h('div', { class: 'card col', style: 'gap:10px' },
h('h3', { class: 'user-search-main', style: 'margin:0' }, t('searchUsers')),
- h('input', {
- type: 'text', class: 'user-search-input user-search-main', placeholder: t('searchUsersHint'), value: s.q,
- autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
- onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); },
- }),
+ h('div', { class: 'row gap6 user-search-main', style: 'align-items:center' },
+ scopeChip(),
+ h('input', {
+ type: 'text', class: 'user-search-input user-search-main grow', placeholder: searchScope() ? t('searchScopedHint') : t('searchUsersHint'), value: s.q,
+ autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
+ onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); guessScope(s.q); },
+ onKeydown: (e) => {
+ if (e.key === 'Enter' && !e.isComposing && s.q.trim()) { e.preventDefault(); submitUserSearch(s.q); }
+ else if (e.key === 'Backspace' && !e.target.value && searchScope()) { e.preventDefault(); unscopeSearch(); }
+ },
+ })),
+ scoped.length ? h('div', { class: 'list' }, ...scoped) : null,
+ // the words themselves: every note and reply that says them
+ s.q.trim().length >= 2 && !/^(npub1|nprofile1|nevent1|note1|naddr1|nostr:)/i.test(s.q.trim())
+ ? h('div', { class: 'list' }, h('div', { class: 'item chat-thread-row', onClick: () => { openTextSearch(s.q); render(); } },
+ h('div', { class: 'chat-avatar fallback' }, '\u{1F50D}'),
+ h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
+ h('span', { class: 'chat-name' }, '\u201c' + s.q.trim() + '\u201d'),
+ h('div', { class: 'muted small' }, t(scoped.length ? 'searchPostsRowAll' : 'searchPostsRow')))))
+ : null,
// a word is a topic too: posts tagged with it, as a feed
(() => {
const m = /^#?([A-Za-z0-9_\u00C0-\uFFFF]{2,64})$/.exec(s.q.trim());
@@ -14345,6 +18109,29 @@ export function messagesFeature(ctx) {
return h('div', { class: 'mention-ac', onMousedown: (e) => e.preventDefault() }, // the box keeps focus and caret
...(hits.length ? resultRows(h, hits, pickMention, (pk, ava) => ava) : []));
}
+ // A name typed out after an @ and never picked from the list ("thanks to
+ // @pnk") went out as plain text: no key, no p tag, and a tap on it could
+ // only search for the name (Adam, 2026-11-22). When exactly one person you
+ // follow goes by that name, that is who it means: the tap opens them, and
+ // a post or reply being sent gets their nostr:npub in its place, so every
+ // client shows the mention and they are told. Two follows by the same
+ // name, or none, and it stays as typed.
+ function followNamed(handle) {
+ const want = String(handle || '').toLowerCase();
+ let hit = null;
+ for (const pk of followsNow().set) {
+ if (isMe(pk) || hiddenPk(pk)) continue;
+ const p = profiles.get(pk);
+ if (!p || !p.name || String(p.name).trim().toLowerCase() !== want) continue;
+ if (hit) return null;
+ hit = pk;
+ }
+ return hit;
+ }
+ const linkNamed = (text) => String(text || '').split(NOTE_SPLIT).map((part) => {
+ const pk = part && /^@[A-Za-z0-9_]{2,32}$/.test(part) ? followNamed(part.slice(1)) : null;
+ return pk ? 'nostr:' + npubOf(pk) : part;
+ }).join('');
// The people a text mentions (nostr:npub / nprofile), for its p tags.
const mentionedPks = (text) => [...new Set([...String(text || '').matchAll(/nostr:((?:npub|nprofile)1[a-z0-9]+)/gi)]
.map((m) => parseNostrRef(m[1].toLowerCase())).filter((r) => r && r.type === 'pubkey').map((r) => r.pk))];
@@ -14429,6 +18216,7 @@ export function messagesFeature(ctx) {
// login is asked when it first opens a Cordn group or invites someone).
if (ui.msgView !== 'grp' && cd) cd.focus(null);
cordnChat().then((c) => { if (c && !cdReadied) { cdReadied = true; c.ready(); } });
+ nip29Chat();
// Group chats ride along: the client loads with the wallet, and standing
// on this screen is what makes us invitable (a KeyPackage on the relays).
whiteNoise().then(async (c) => {
@@ -14555,7 +18343,10 @@ export function messagesFeature(ctx) {
// one list, newest first: a group chat is a conversation like any other
const chatRows = [
...dmRows.map((x) => ({ at: x.last.rumor.created_at, dm: x })),
- ...wnGroups().filter((g) => !g.fresh).map((g) => ({ at: (wnFold(g).rows.at(-1) || {}).rumor?.created_at || g.at, g })),
+ // a relay group with nothing said yet sorts by when it was joined
+ // HERE: one that only arrived on the 10009 list (joined elsewhere,
+ // maybe years ago, maybe on a relay long gone) waits at the bottom
+ ...wnGroups().filter((g) => !g.fresh).map((g) => ({ at: (wnFold(g).rows.at(-1) || {}).rumor?.created_at || (g.nip29 ? g.joinedAt || 0 : g.at), g })),
].sort((a, b) => b.at - a.at);
const shownDms = ui.msgAllDms ? chatRows : chatRows.slice(0, LIST_PREVIEW);
kids.push(
@@ -14759,6 +18550,13 @@ export function messagesFeature(ctx) {
render();
}
+ const chatBubbleClick = (open) => (e) => {
+ if (e.target.closest && e.target.closest('a, button, img:not(.cemoji)')) return;
+ const sel = window.getSelection && window.getSelection();
+ if (sel && String(sel).length) return;
+ open();
+ };
+
function messageRows(room, chId) {
const my = myPubkeys();
const msgs = [...(room.byChannel.get(chId)?.values() || [])]
@@ -14788,7 +18586,7 @@ export function messagesFeature(ctx) {
// the message's own custom emoji (an edit brings its own set)
const em = emojiTagMap((edit && edit.author === m.author ? edit.rumor : m.rumor).tags);
return h(
- 'div', { class: 'chat-row' + (mine ? ' mine' : '') + (grouped ? ' grouped' : '') },
+ 'div', { class: 'chat-row group' + (mine ? ' mine' : '') + (grouped ? ' grouped' : '') },
grouped ? h('div', { class: 'chat-avatar spacer' }) : avatar(m.author),
h('div', { class: 'chat-body' },
grouped ? null : h('div', { class: 'chat-meta' },
@@ -14807,13 +18605,10 @@ export function messagesFeature(ctx) {
// ends in a click too, and must not pop the sheet over the copy.
// A custom emoji is an <img> too, but tapping it should open the
// sheet like tapping any other word.
- onClick: (e) => {
- if (e.target.closest && e.target.closest('a, button, img:not(.cemoji)')) return;
- const sel = window.getSelection && window.getSelection();
- if (sel && String(sel).length) return;
+ onClick: chatBubbleClick(() => {
ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
render();
- },
+ }),
},
replyQuote(room, chId, m),
...noteBody(text, 0, em),
@@ -14833,8 +18628,7 @@ export function messagesFeature(ctx) {
title: t('msgReact'),
onClick: (e) => { e.stopPropagation(); sendReaction(room, chId, m, emoji); },
}, reactNode(emoji), n > 1 ? ' ' + n : '')))
- : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null, onHold: () => openZapSettings(m.author, m.rumor.id) }))),
- msgZapBtn(m.author, m.rumor.id)))
+ : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null, onHold: () => openZapSettings(m.author, m.rumor.id) })))))
);
});
}
@@ -14942,7 +18736,14 @@ export function messagesFeature(ctx) {
h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
h('span', { class: 'chat-name' }, displayName(r.pk)),
r.pk === room.jm.owner ? h('span', { class: 'chat-badge' }, t('msgAdmin')) : null),
- h('div', { class: 'muted small' + (r.online ? ' is-online' : '') }, seenLabel(room, r.pk))))));
+ h('div', { class: 'muted small' + (r.online ? ' is-online' : '') }, seenLabel(room, r.pk))))),
+ ...(canModerate(room) && room.folded && room.folded.banned.size ? [
+ h('div', { class: 'small muted chat-removed-head' }, t('msgBannedHead')),
+ ...[...room.folded.banned].map((pk) => h('div', { class: 'item chat-thread-row', onClick: () => openProfile(pk) },
+ h('span', { class: 'ava-wrap' }, avatar(pk)),
+ h('span', { class: 'chat-name grow', style: 'min-width:0' }, displayName(pk)),
+ h('button', { class: 'btn-sm', onClick: (e) => { e.stopPropagation(); setBanned(room, pk, false); } }, t('msgUnban')))),
+ ] : []));
}
function invitePanel(room) {
@@ -15011,6 +18812,7 @@ export function messagesFeature(ctx) {
h('div', { class: 'muted small chat-preview' },
g.removed ? t('msgGroupGone')
: last ? (last.mine ? t('msgYouPrefix') : displayName(last.rumor.pubkey) + ':') + ' ' + (last.rumor.content || '📎 ' + t('msgGroupAttachment'))
+ : g.nip29 && !wn.accounts(g).length ? t(g.unreachable ? 'msgNip29Unreachable' : 'msgNip29Waiting', { host: g.relay.replace(/^wss?:\/\//, '').replace(/\/$/, '') })
: t('msgMembers', { n: wn.accounts(g).length }))),
unread ? h('i', { class: 'thread-dot' }) : null);
}
@@ -15066,7 +18868,42 @@ export function messagesFeature(ctx) {
// which protocol the group speaks: White Noise (Marmot) or Cordn
h('div', { class: 'seg' },
h('button', { class: proto === 'wn' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'wn'; render(); } }, t('msgGroupProtoWn')),
- h('button', { class: proto === 'cd' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'cd'; render(); } }, t('msgGroupProtoCd'))),
+ h('button', { class: proto === 'cd' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'cd'; render(); } }, t('msgGroupProtoCd')),
+ h('button', { class: proto === 'n29' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'n29'; render(); } }, t('msgGroupProtoN29'))),
+ proto === 'n29' ? nip29JoinPanel() : null,
+ proto === 'n29' ? null : wnNewGroupForm(proto, picks, ready));
+ }
+ // Join a NIP-29 group by its address (they're made in other clients).
+ async function nip29Join() {
+ const raw = (ui.msgN29Addr || '').trim();
+ if (!raw || ui.msgBusy) return;
+ const m = await import('../nip29-client.js');
+ const a = m.parseGroupAddress(raw);
+ if (!a) { toast(t('msgNip29BadAddress')); return; }
+ ui.msgBusy = true; render();
+ try {
+ const c = await nip29Chat();
+ if (!c) throw new Error('no signer');
+ const g = await c.join(a);
+ ui.msgN29Addr = ''; ui.msgHomePanel = null;
+ ui.msgView = 'grp'; ui.msgPeer = g.id; ui.msgStick = true;
+ if (g.joinRefused) toast(t('msgNip29JoinRefused', { why: g.joinRefused }));
+ } catch (e) { wnFail(e); } finally { ui.msgBusy = false; render(); }
+ }
+ function nip29JoinPanel() {
+ return h('div', { class: 'col gap6' },
+ h('div', { class: 'small muted' }, t('msgGroupProtoN29Hint')),
+ h('div', { class: 'row gap6' },
+ h('input', {
+ class: 'grow nip29-address', type: 'text', placeholder: t('msgNip29Address'), autocapitalize: 'none', spellcheck: 'false',
+ value: ui.msgN29Addr || '', onInput: (e) => { ui.msgN29Addr = e.target.value; },
+ onKeydown: (e) => { if (e.key === 'Enter') nip29Join(); },
+ }),
+ h('button', { class: 'btn-primary btn-sm', disabled: ui.msgBusy, onClick: nip29Join },
+ ui.msgBusy ? h('span', { class: 'spinner sm' }) : t('msgJoin'))));
+ }
+ function wnNewGroupForm(proto, picks, ready) {
+ return h('div', { class: 'col gap6' },
proto === 'cd' ? h('div', { class: 'small muted' }, t('msgGroupProtoCdHint')) : null,
h('input', {
type: 'text', placeholder: t('msgGroupName'), maxlength: '64',
@@ -15085,7 +18922,11 @@ export function messagesFeature(ctx) {
const accounts = wn.accounts(g);
const picks = ui.msgGroupAdd || (ui.msgGroupAdd = []);
return h('div', { class: 'col chat-members' },
- h('div', { class: 'muted small', style: 'padding:8px 12px 2px' }, t(g.cordn ? 'msgCordnInfo' : 'msgGroupInfo')),
+ h('div', { class: 'muted small', style: 'padding:8px 12px 2px' }, g.nip29 ? t('msgNip29Info', { relay: wn.groupRef(g) }) : t(g.cordn ? 'msgCordnInfo' : 'msgGroupInfo')),
+ g.nip29 && v.about ? h('div', { class: 'small', style: 'padding:2px 12px 6px' }, v.about) : null,
+ g.nip29 ? h('div', { class: 'row gap6', style: 'padding:0 12px 6px' }, h('button', { class: 'btn-ghost btn-sm', onClick: async () => {
+ try { await navigator.clipboard.writeText(wn.groupRef(g)); toast(t('copied')); } catch {}
+ } }, t('msgNip29CopyAddress'))) : null,
...accounts.map((pk) => h('div', { class: 'item chat-thread-row', onClick: () => openProfile(pk) },
avatar(pk),
h('div', { class: 'row gap6 grow', style: 'align-items:center;min-width:0' },
@@ -15145,15 +18986,20 @@ export function messagesFeature(ctx) {
!ui.emojiPick && m.mine && !g.removed ? item('×', t('msgDelete'), async () => {
close();
const del = wn.event(5, '', [['e', m.rumor.id], ['k', '9']]);
- if (await wn.send(g, del).catch(() => false)) (g.cordn ? onCd : onWn)('message', g, del);
+ if (await wn.send(g, del).catch(() => false)) gOn(g)('message', g, del);
}) : null));
}
+ // Outside wnView: its own `const wn = gClient(g)` shadows the module's wn
+ // for the whole function, so a `!wn` in there read the inner one before
+ // it was set — a ReferenceError the moment a group was left from its own
+ // screen (Adam's phone, 2026-11-13).
+ const groupClientsLoading = () => !wn || wnLoading || !cd || cdLoading || !ng || ngLoading;
function wnView() {
const g = findGroup(ui.msgPeer);
if (!g) {
// the groups are still loading (a reload straight into this screen)
- if (!wn || wnLoading || !cd || cdLoading) { Promise.all([whiteNoise(), cordnChat()]).then(() => scheduleRepaint()); return h('div', { class: 'card col chat-card chat-page' }, h('span', { class: 'spinner' })); }
+ if (groupClientsLoading()) { Promise.all([whiteNoise(), cordnChat(), nip29Chat()]).then(() => scheduleRepaint()); return h('div', { class: 'card col chat-card chat-page' }, h('span', { class: 'spinner' })); }
ui.msgView = 'home';
return homeView();
}
@@ -15204,13 +19050,10 @@ export function messagesFeature(ctx) {
h('span', { class: 'chat-time' }, timeLabel(tms))),
h('div', {
class: 'chat-bubble clickable' + (emojiJumbo(m.rumor.content, em) ? ' jumbo' : ''),
- onClick: (e) => {
- if (e.target.closest && e.target.closest('a, button, img:not(.cemoji)')) return;
- const sel = window.getSelection && window.getSelection();
- if (sel && String(sel).length) return;
+ onClick: chatBubbleClick(() => {
ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
render();
- },
+ }),
},
src ? h('div', { class: 'chat-quote' },
h('span', { class: 'chat-quote-name' }, displayName(src.rumor.pubkey)),
@@ -15265,7 +19108,7 @@ export function messagesFeature(ctx) {
h('span', { class: 'small muted chat-quote-text' }, ...snippetNodes(reply.rumor))),
h('button', { class: 'chat-del', style: 'position:static;display:flex;flex-shrink:0', onClick: () => { ui.msgReplyTo = null; render(); } }, '×')) : null,
live
- ? composer(t('msgDmPlaceholder'), () => wnSend(g), null, 'wn:' + g.id, g.cordn ? null : (f) => wnSendFile(g, f))
+ ? composer(t('msgDmPlaceholder'), () => wnSend(g), null, 'wn:' + g.id, g.cordn || g.nip29 ? null : (f) => wnSendFile(g, f))
: h('div', { class: 'muted small', style: 'text-align:center;padding:12px' }, t('msgGroupGone')),
ui.msgSheet ? wnSheet(g) : null);
}
@@ -15328,7 +19171,8 @@ export function messagesFeature(ctx) {
const peer = ui.msgPeer;
if (!peer) { ui.msgView = 'home'; return homeView(); }
const thread = threads.get(peer) || new Map();
- const msgs = [...thread.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at);
+ if (!isMe(peer)) setTimeout(() => callWarm(peer), 1500); // a call may be next
+ const msgs = foldCallLogs([...thread.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at));
// a first message may go by White Noise: have their KeyPackage looked up before Send
wnKnow(peer);
const choice = routeChoice(peer);
@@ -15376,12 +19220,16 @@ export function messagesFeature(ctx) {
h('div', { class: 'col clickable', style: 'gap:2px;min-width:0', onClick: () => openProfile(peer) },
h('div', { class: 'chat-title' }, displayName(peer)),
h('div', { class: 'muted small' }, t('msgDmEncrypted'))),
- // Only where there is a choice: this person can be reached two ways.
- // The pill says which way the next message goes; tapping it pins one.
- choice ? h('button', {
- class: 'btn-sm route-pill', style: 'margin-left:auto;flex-shrink:0', title: t('msgRouteTitle'), 'aria-haspopup': 'true',
- onClick: () => { ui.msgRoutePick = !ui.msgRoutePick; render(); },
- }, t(choice.now === 'wn' ? 'msgRouteWn' : 'msgRouteDm'), ' ▾') : null),
+ h('div', { class: 'row gap6', style: 'margin-left:auto;flex-shrink:0;align-items:center' },
+ // a call: voice or video, to this one person
+ isMe(peer) ? null : h('button', { class: 'iconbtn call-start', 'data-call': 'voice', title: t('callVoice'), 'aria-label': t('callVoice'), onClick: () => startCall(peer, 'voice') }, callIcon('phone')),
+ isMe(peer) ? null : h('button', { class: 'iconbtn call-start', 'data-call': 'video', title: t('callVideo'), 'aria-label': t('callVideo'), onClick: () => startCall(peer, 'video') }, callIcon('video')),
+ // Only where there is a choice: this person can be reached two ways.
+ // The pill says which way the next message goes; tapping it pins one.
+ choice ? h('button', {
+ class: 'btn-sm route-pill', style: 'flex-shrink:0', title: t('msgRouteTitle'), 'aria-haspopup': 'true',
+ onClick: () => { ui.msgRoutePick = !ui.msgRoutePick; render(); },
+ }, t(choice.now === 'wn' ? 'msgRouteWn' : 'msgRouteDm'), ' ▾') : null)),
h('div', {
class: 'chat-log',
onScroll: (e) => {
@@ -15390,21 +19238,17 @@ export function messagesFeature(ctx) {
},
},
...(msgs.length
- ? msgs.map((m) =>
+ ? msgs.map((m) => m.rumor.kind === CALL_LOG ? callLogRow(m, peer) :
h('div', { class: 'chat-row dm' + (m.mine ? ' mine' : '') },
h('div', { class: 'chat-body' },
h('div', { class: 'chat-line' }, h('div', {
class: 'chat-bubble clickable' + (m.mine ? ' me' : '') + (emojiJumbo(m.rumor.content, emojiTagMap(m.rumor.tags)) ? ' jumbo' : ''),
// same tap-for-actions as community bubbles
- onClick: (e) => {
- if (e.target.closest && e.target.closest('a, button, img:not(.cemoji)')) return;
- const sel = window.getSelection && window.getSelection();
- if (sel && String(sel).length) return;
+ onClick: chatBubbleClick(() => {
ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
render();
- },
- }, dmQuote(m), ...(m.rumor.kind === 15 ? [] : noteBody(m.rumor.content, 0, emojiTagMap(m.rumor.tags))), ...attachmentNodes(m.rumor, m.wn), dmChips(m)),
- m.mine ? null : msgZapBtn(m.rumor.pubkey, m.rumor.id)),
+ }),
+ }, dmQuote(m), ...(m.rumor.kind === 15 ? [] : noteBody(m.rumor.content, 0, emojiTagMap(m.rumor.tags))), ...attachmentNodes(m.rumor, m.wn), dmChips(m))),
h('div', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000)))))
: [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgNoDmsYet'))])),
dmReplyBar(),
@@ -15552,7 +19396,11 @@ export function messagesFeature(ctx) {
if (ZAP_KINDS.includes(ev.kind)) {
const actor = zapperOf(ev), sats = receiptSats(ev);
if (!actor || my.includes(actor) || !sats) return null;
- return { id: ev.id, what: 'zap', actor, target: lastE, hint, sats, text: zapText(ev), ts: ev.created_at };
+ // a zap on a stream or an app names it by address, not by an e tag
+ const addr = !lastE ? zapAddrOf(ev) : null;
+ const stream = addr && addr.startsWith(LIVE_KIND + ':') ? addr : null;
+ const app = addr && addr.startsWith(APP_KIND + ':') ? addr : null;
+ return { id: ev.id, what: 'zap', actor, target: lastE, stream, ...(app ? { app } : {}), hint, sats, text: zapText(ev), ts: ev.created_at };
}
if (my.includes(ev.pubkey)) return null;
if (ev.kind === 7) {
@@ -15589,6 +19437,12 @@ export function messagesFeature(ctx) {
const old = c.items.find((y) => y.id === x.id);
if (old && !old.emojiUrl) { old.emojiUrl = x.emojiUrl; old.emoji = x.emoji; healed = true; }
}
+ // ...and a zap on an app saved before rows knew one
+ for (const x of items) {
+ if (!x || !x.app || !known.has(x.id)) continue;
+ const old = c.items.find((y) => y.id === x.id);
+ if (old && !old.app) { old.app = x.app; healed = true; }
+ }
const add = items.filter((x) => x && !hiddenPk(x.actor) && !known.has(x.id) && known.add(x.id));
if (!add.length) { if (healed) persistNotifs(); return healed; }
warmNotifFaces(add);
@@ -15706,7 +19560,32 @@ export function messagesFeature(ctx) {
return ref && ref.type === 'pubkey' ? '@' + displayName(ref.pk) : m.slice(6, 18) + '\u2026';
}).replace(/\s+/g, ' ').trim();
}
+ // Zapstore app listings (NIP-82 kind 32267): a zap on one is a zap on your
+ // app. Its name is asked of Zapstore's relay once per session.
+ const appIdOf = (addr) => String(addr || '').split(':').slice(2).join(':');
+ const appNames = new Map(); // app id -> name | null (asking / none)
+ function appName(addr) {
+ const id = appIdOf(addr);
+ if (!id) return null;
+ if (!appNames.has(id)) {
+ appNames.set(id, null);
+ queryOn(APP_RELAYS, { kinds: [APP_KIND], '#d': [id], limit: 5 }, 5000).then((evs) => {
+ const ev = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
+ const name = ev && tagOf(ev, 'name');
+ if (name) { appNames.set(id, String(name).slice(0, 60)); scheduleRepaint(); }
+ }).catch(() => {});
+ }
+ return appNames.get(id);
+ }
+ const openApp = (addr) => {
+ const url = 'https://zapstore.dev/apps/' + encodeURIComponent(appIdOf(addr));
+ if (ctx.openExternal) ctx.openExternal(url); else window.open(url, '_blank', 'noopener');
+ };
function notifLabel(x) {
+ if (x.what === 'zap' && x.app) {
+ const name = appName(x.app);
+ return name ? t('alertZapApp', { name, sats: fmtSats(x.sats) + ' sats' }) : t('alertZapAppAnon', { sats: fmtSats(x.sats) + ' sats' });
+ }
if (x.what === 'zap') return t('alertZap', { sats: fmtSats(x.sats) + ' sats' });
if (x.what === 'react') {
const code = shortcodeOf(x.emoji);
@@ -15741,6 +19620,24 @@ export function messagesFeature(ctx) {
if (target) openNoteThread(target);
// a note we couldn't find is asked for again on tap, hints and all
else if (x.target) openNoteRef({ id: x.target, relays: x.hint || [] }).catch(() => {});
+ // a zap on a stream opens the stream; one on your profile (no post
+ // at all) opens the zapper's — the tap used to do nothing
+ else if (x.stream) { const [, pk, ...d] = x.stream.split(':'); stopNotifWatch(); openLiveRef({ pk, d: d.join(':') }).catch(() => {}); }
+ else if (x.app) openApp(x.app);
+ // a row saved before rows read the zap request's address: look at
+ // the receipt once, then go where it says
+ else if (x.what === 'zap' && !x.addrChecked) {
+ x.addrChecked = true;
+ queryOn(zapRelays(), { ids: [x.id] }, 4500).catch(() => []).then((evs) => {
+ const addr = evs && evs[0] ? zapAddrOf(evs[0]) : null;
+ if (addr && addr.startsWith(APP_KIND + ':')) x.app = addr;
+ else if (addr && addr.startsWith(LIVE_KIND + ':')) x.stream = addr;
+ persistNotifs();
+ render();
+ open();
+ });
+ }
+ else { stopNotifWatch(); openProfile(x.actor); }
}
};
return h('div', {
@@ -15835,10 +19732,14 @@ export function messagesFeature(ctx) {
resumed(awayMs) {
// a blink between apps didn't kill anything
if (awayMs && awayMs < 5_000) return;
- resubscribeStreams(); // DMs and rooms, whether or not chat is on screen
- if (!ui.chatOpen || !['feed', 'notifs'].includes(ui.msgView)) return true;
- if (ui.msgView === 'notifs') refreshNotifs(true).catch(() => {});
- else refreshFeed({ force: true }).catch(() => {});
+ // the sockets first: after a freeze they read open and are dead, and
+ // a refresh sent on them finds nothing (wakeRelays)
+ wakeRelays().catch(() => {}).then(() => {
+ resubscribeStreams(); // DMs and rooms, whether or not chat is on screen
+ if (!ui.chatOpen || !['feed', 'notifs'].includes(ui.msgView)) return;
+ if (ui.msgView === 'notifs') refreshNotifs(true).catch(() => {});
+ else refreshFeed({ force: true }).catch(() => {});
+ });
return true;
},
// A zap flow reporting how its payment went, so the chip that appeared
@@ -15893,14 +19794,18 @@ export function messagesFeature(ctx) {
return unreadCount();
},
bottomNav: appBottomNav,
+ // taken once per render: a page that isn't the feed leaves none
+ pageFloaters() { const f = pageFloaters; pageFloaters = []; return f; },
notifySettingsCards() { return [notifyCard()]; },
screenView() {
+ liveShown = false;
+ queueMicrotask(liveAfterRender);
// A profile deep link mid-resolution holds the frame over EVERY screen
// — an auto-restored wallet would otherwise flash its home page for the
// beat the registrar lookup takes. The shell shows the name straight
// off the URL; no spinner, the empty beat reads calmer.
// Same for a note deep link while its thread is being found.
- if (ui.pubNotePending && !ui.noteThread) return h('div', { class: 'col', style: 'gap:16px' },
+ if (ui.pubNotePending && !ui.noteThread && !ui.liveStream) return h('div', { class: 'col', style: 'gap:16px' },
ctx.brandHeader(false),
h('div', { class: 'card row gap6', style: 'justify-content:center;align-items:center;padding:16px' },
h('span', { class: 'spinner sm' }), h('span', { class: 'small faint' }, t('noteRefLoading'))));
@@ -15916,6 +19821,8 @@ export function messagesFeature(ctx) {
// threads reachable from it, are public nostr content — shown
// without an account. Back falls through to the app's own screens.
if (ui.pubProf) {
+ if (ui.zapSetup && ui.liveStream) return zapSetupScreen();
+ if (ui.liveStream) return liveScreen();
if (ui.profOverThread && ui.profilePk) return profileScreen();
if (ui.noteThread) return threadScreen();
if (ui.profilePk) return profileScreen();
@@ -15925,6 +19832,8 @@ export function messagesFeature(ctx) {
return null;
}
if (ui.zapSetup) return zapSetupScreen();
+ if (ui.goLive) return goLiveScreen();
+ if (ui.liveStream) return liveScreen();
if (ui.profOverThread && ui.profilePk) return profileScreen();
if (ui.noteThread) return threadScreen();
if (ui.profilePk) return profileScreen();
@@ -15937,15 +19846,35 @@ export function messagesFeature(ctx) {
// The header magnifier: search anyone on nostr, results open profiles.
userSearchAvailable() { return true; },
// the desktop header's search field: typing there IS the search page's query
+ userSearchSubmit(q) { submitUserSearch(q); },
+ userSearchScopeChip() { return scopeChip(); },
+ userSearchScoped() { return !!searchScope(); },
+ userSearchUnscope() { unscopeSearch(); },
+ // before the header field's first keystroke takes the profile away
+ userSearchHoldScope() {
+ if (!ui.profilePk) return;
+ if (!ui.userSearch) { ui.userSearch = { q: '', rows: null }; warmSearch(); }
+ ui.userSearch.scope = ui.searchScopeOff === ui.profilePk ? null : ui.profilePk;
+ },
userSearchQuery(q) {
- if (!ui.userSearch) { if (!isVisitor()) ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null; ui.userSearch = { q: '', rows: null }; warmSearch(); }
- ui.userSearch.q = q; userSearcher.update(q); render();
+ if (!ui.userSearch) { ui.userSearch = { q: '', rows: null }; warmSearch(); }
+ // typed from a profile: its person is what the field searches, until taken out
+ if (ui.profilePk) ui.userSearch.scope = ui.searchScopeOff === ui.profilePk ? null : ui.profilePk;
+ // Typing brings the results forward every time, not only the first:
+ // the search is kept (Back from a profile lands on it), so a second
+ // search typed from a profile opened from the first one updated a
+ // page hidden under that profile ("the search box stops working",
+ // Adam 2026-11-14). Back still returns to the profile.
+ if (!isVisitor()) ui.chatOpen = false;
+ ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
+ ui.userSearch.q = q; userSearcher.update(q); guessScope(q); render();
return true;
},
- openUserSearch() {
+ userSearchScopePk() { return searchScope(); },
+ openUserSearch(scope = searchScope()) {
if (!isVisitor()) ui.chatOpen = false; // a visitor's feed stays underneath, for Back
ui.profilePk = null;
- ui.userSearch = { q: '', rows: null };
+ ui.userSearch = { q: '', rows: null, scope };
warmSearch(); // the field is about to be typed into — open the pipes
return true;
},
@@ -16019,13 +19948,22 @@ 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') },
+ addressRenamed(oldAddr, newAddr) { return repointAddress(oldAddr, newAddr).catch(() => {}); },
+ // the address was given up with nothing in its place (account deleted):
+ // a profile still naming it would send zaps to nobody
+ addressGone(oldAddr) {
+ const is = (k) => (base) => base[k] === oldAddr;
+ return publishProfileFields({}, {
+ onlyWhen: (base) => is('lud16')(base) || is('nip05')(base),
+ remove: ['lud16', 'nip05'], fieldWhen: { lud16: is('lud16'), nip05: is('nip05') },
}).catch(() => {});
},
+ // older copies of our kind 0 on history-keeping relays, and filling the
+ // open editor's empty fields from one (tests)
+ profileHistory() { return findProfileHistory(); },
+ fillProfileFrom(e) { return fillProfileFrom(e); },
+ // 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) {
@@ -16037,6 +19975,21 @@ export function messagesFeature(ctx) {
}, avatar(pk, 'chat-avatar ' + (big ? 'send-avatar' : 'mini'), false),
h('span', { class: big ? '' : 'small' }, displayName(pk)));
},
+ // a gift link names its sender: sign its template as us (gifts.js)
+ async signGiftFrom(tmpl) {
+ const id = await identity();
+ if (!id) return null;
+ return id.signer instanceof Uint8Array ? finalizeEvent(tmpl, id.signer) : id.signer.signEvent(tmpl);
+ },
+ // A claimed gift's sender: follow them, once any follow publish in
+ // flight (a fresh wallet's starter follows) has landed — followMany
+ // drops a call that arrives mid-publish.
+ async followGiftSender(pk) {
+ for (let i = 0; followsPub && i < 60; i++) await new Promise((r) => setTimeout(r, 500));
+ if (!(await identity())) return false;
+ await followMany([pk]).catch(() => {});
+ return true;
+ },
// A sign-in (Google, passkey, key) that found no wallet on its identity:
// the same start, but only the follows of an identity that follows
// nobody yet — an established nostr user keeps their own list.
@@ -16047,8 +20000,9 @@ export function messagesFeature(ctx) {
visitorSignIn() { toFrontDoor(); return true; },
visitorSearch() {
rememberReturn();
- ui.profilePk = null; ui.noteThread = null; ui.profOverThread = false;
- ui.userSearch = { q: '', rows: null };
+ const scope = searchScope(); // from a profile: search inside its person's posts
+ ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.profOverThread = false;
+ ui.userSearch = { q: '', rows: null, scope };
warmSearch();
render();
return true;
@@ -16060,11 +20014,13 @@ export function messagesFeature(ctx) {
return true;
},
navPath(snap) {
+ if (snap && snap.liveStream && snap.liveStream.a) { const n = packNaddr(snap.liveStream.a); if (n) return '/' + n; }
if (!snap || !snap.chatOpen || snap.msgView !== 'feed' || snap.profilePk || snap.noteThread || snap.userSearch) return null;
const def = feedDef(snap.feedId || curFeedId);
return def && adhocFeeds.has(def.id) ? feedPath(def) : null;
},
avatarNode(pk, cls) { return avatar(pk, cls || 'chat-avatar mini', false); },
+ callOverlay() { return callOverlay(); },
init() {
const session = ++feedWarmSession;
// this wallet's own feed (the feature outlives a sign-out): a feed
@@ -16096,12 +20052,26 @@ export function messagesFeature(ctx) {
try {
navigator.serviceWorker?.addEventListener('message', (ev) => {
if (ev.data && ev.data.type === 'open' && ev.data.view === 'notifs') openNotifs();
+ // a call the worker was woken for: rung here too (an app in the
+ // background may have missed it live), or picked up from the tap
+ if (ev.data && ev.data.type === 'call-offer' && ev.data.offer) callsNow().handle(ev.data.offer, { maxAge: RING_S }).catch(() => {});
+ if (ev.data && ev.data.type === 'open' && ev.data.view === 'call') pendingCall();
});
} catch {}
+ // a tapped "is calling" opened the app, or brought it back: the offer the worker kept
+ setTimeout(pendingCall, 0);
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') pendingCall(); });
if (urlInvite && !pendingLink) {
loadLinkInvite(urlInvite);
setTimeout(() => { ui.chatOpen = true; ui.msgView = 'home'; render(); }, 0);
}
+ if (urlChat) {
+ urlChat = false; // once: init runs again for every wallet born in this tab
+ setTimeout(() => {
+ ui.chatOpen = true; ui.msgView = 'room'; ui.msgCommunity = COMMUNITY.community_id;
+ ui.msgChannel = null; ui.msgStick = true; render();
+ }, 0);
+ }
if (urlPack) {
addPack(urlPack).catch(() => {});
setTimeout(() => { ui.chatOpen = true; ui.msgView = 'home'; render(); }, 0);
@@ -16154,6 +20124,7 @@ export function messagesFeature(ctx) {
clearTimeout(drainTimer);
pendingWraps.clear();
dmStarted = false;
+ if (calls) { try { calls.stop(); } catch {} calls = null; callInbox.clear(); iceCache = null; warmed.clear(); callRing(); }
listsSynced = false;
if (zapLiveUnsub) { try { zapLiveUnsub(); } catch {} zapLiveUnsub = null; }
clearTimeout(zapTimer); zapTimer = null; zapQueue = new Set(); zapRecent = [];
@@ -16169,9 +20140,9 @@ export function messagesFeature(ctx) {
follows = null; followsAt = 0; feed = null; relayLists = null;
mutes = null; mutesAt = 0;
stCache = null; stAt = 0; // the next account's state, not this one's
- if (profFlush) { clearTimeout(profFlush); flushProfiles(); } // this account's faces, written before the blob is dropped
+ if (profFlush) { clearTimeout(profFlush); flushProfiles(true); } // this account's faces, written before the blob is dropped
profBlob = null;
- reacts.clear(); boosts.clear(); seenNoteEv.clear(); myReactEv.clear(); quoted.clear();
+ timedActivity.clear(); diskHeld.clear(); reacts.clear(); boosts.clear(); seenNoteEv.clear(); myReactEv.clear(); quoted.clear();
noteCountsReady.clear();
// what happened to THEIR posts stays with them — the next identity
// starts its list empty and asks the relays under its own key
diff --git a/src/features/names.js b/src/features/names.js
index fe5ab0a..701b474 100644
--- a/src/features/names.js
+++ b/src/features/names.js
@@ -17,7 +17,7 @@ import { nip98Header } from '../nip98.js';
import { qrSvg } from '../qr.js';
import { bech32 } from '@scure/base';
import { isArkAddress } from './ark.js';
-import { getNetwork } from '../api.js';
+import { getNetwork, getArkProviderId } from '../api.js';
import { t } from '../i18n.js';
import { getCurrency } from '../rates.js';
@@ -132,6 +132,27 @@ export function namesFeature(ctx) {
return j;
}
+ // Delete the account at the registrar: every name this wallet's key owns
+ // or manages is freed and what the server filed under them goes with it
+ // (coinosv3-server names/forget.js). `check` only asks what stands in the
+ // way: sats still on their way here, or held in a withdraw link.
+ async function accountDelete(check) {
+ const url = `${REGISTRAR}/account/delete`;
+ const body = JSON.stringify(check ? { check: true } : {});
+ const auth = await withTimeout(nip98Header(walletSigner(), url, 'POST', body), 12000, 'signing');
+ const r = await withTimeout(fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', authorization: auth }, body }), 30000, 'registrar');
+ const j = await r.json().catch(() => ({}));
+ if (j.error === 'funds') return { blocked: true, ...j };
+ if (!r.ok || j.error) throw new Error(j.error || `registrar refused (${r.status})`);
+ if (!check) {
+ // a profile still pointing at a freed address would pay nobody (or its next owner)
+ for (const key of j.names || [])
+ await Promise.race([Promise.resolve(hook('addressGone', key)).catch(() => {}), new Promise((res) => setTimeout(res, 8000))]);
+ wallet.saveFeatureState('names', {});
+ }
+ return j;
+ }
+
async function release() {
const st = load();
if (!st.name) return;
@@ -411,6 +432,7 @@ export function namesFeature(ctx) {
// should have to retype who they already are — but only when that name is
// actually free on the registrar (or already theirs to retake).
let lnReceipts = { at: 0, p: null };
+ let listeningAt = 0;
let suggestedFor = null;
function suggestName() {
@@ -455,29 +477,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 +518,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 +588,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
@@ -621,6 +683,10 @@ export function namesFeature(ctx) {
onClick: () => copy(addr),
html: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',
}))),
+ // ask for a sum: the point of sale's amount pad and invoice, simplified
+ hook('posAvailable') ? h('button', { class: 'btn-block', id: 'recv-amount', onClick: () => hook('openAmountRequest') }, t('recvAmount')) : null,
+ // one balance: an on-chain address for the payers who need one
+ ctx.receiveOnchainBtn ? ctx.receiveOnchainBtn() : null,
moreSection());
}
@@ -694,14 +760,25 @@ export function namesFeature(ctx) {
try {
const a = await hook('arkMakeInvoice', sat, (inv.memo || '').trim().slice(0, 100));
inv.invoice = a.invoice;
+ inv.expiresAt = a.expiresAt || 0;
+ // the QR gives way to "expired" when the hour is up
+ if (inv.expiresAt) setTimeout(() => { if (ui.namesInv === inv) render(); }, Math.max(0, inv.expiresAt - Date.now()) + 500);
} catch (e) { inv.error = e.message; }
inv.busy = false; render();
}
function invoicePane() {
const inv = ui.namesInv || (ui.namesInv = {});
+ // The server finishes a Lightning receive only while this wallet is
+ // open to take it: paid with coinos shut, the money goes back to the
+ // payer. The invoice lasts an hour, and the screen says both.
+ if (inv.invoice && inv.expiresAt && Date.now() >= inv.expiresAt)
+ return h('div', { class: 'col', style: 'gap:10px;width:100%;align-items:center' },
+ h('div', { class: 'small muted', style: 'text-align:center' }, t('namesInvExpired')),
+ h('button', { class: 'btn-sm', onClick: () => { ui.namesInv = {}; render(); } }, t('namesInvNew')));
if (inv.invoice)
return h('div', { class: 'col', style: 'gap:10px;width:100%;align-items:center' },
+ h('div', { class: 'notice small names-inv-open', style: 'width:100%;text-align:center' }, t('namesInvKeepOpen')),
h('div', { html: qrSvg(inv.invoice.toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }) }),
h('div', { class: 'addr-box break', style: 'width:100%;font-size:11px' }, inv.invoice),
h('div', { class: 'row gap6' },
@@ -812,6 +889,23 @@ export function namesFeature(ctx) {
h('p', { class: 'small muted', style: 'margin:0' }, t('namesZapCodeHow')));
}
+ // The public pay page (v3.coinos.io/<name>/receive, src/pay-page.js): the
+ // link a website puts behind its Donate button, as coinos.io/<name>/receive
+ // was on the old coinos. coinos.io names only: the page pays those.
+ function payPagePane() {
+ const st = load();
+ const domain = st.domain || DOMAIN();
+ if (!st.name || (domain !== 'coinos.io' && domain !== 'staging.coinos.io')) return h('div', { class: 'small muted' }, t('namesNeedArk'));
+ const host = domain === 'staging.coinos.io' ? location.origin : 'https://v3.coinos.io';
+ const link = `${host}/${st.name}/receive`;
+ return h('div', { class: 'col', style: 'gap:10px;width:100%;align-items:center' },
+ h('div', { class: 'addr-box break', style: 'width:100%' }, link),
+ h('div', { class: 'row gap6' },
+ copyBtn(link, t('copy')),
+ h('button', { class: 'btn-ghost btn-sm', onClick: () => window.open(link, '_blank', 'noopener') }, t('namesPageOpen'))),
+ h('p', { class: 'small muted', style: 'margin:0' }, t('namesPageHow')));
+ }
+
// ---- more options -------------------------------------------------------
// The address covers almost everyone; behind one link live the other codes
// a payer might insist on.
@@ -824,6 +918,7 @@ export function namesFeature(ctx) {
h('strong', { class: 'small' }, label),
h('span', { class: 'small muted' }, how));
return h('div', { class: 'list', style: 'width:100%' },
+ opt('page', t('namesMorePage'), t('namesMorePageHow')),
opt('bolt11', t('namesMoreBolt11'), t('namesMoreBolt11How')),
opt('bolt12', t('namesMoreBolt12'), t('namesMoreBolt12How'), loadOffers),
opt('ark', t('namesMoreArk'), t('namesMoreArkHow')),
@@ -850,12 +945,14 @@ export function namesFeature(ctx) {
ark: t('namesMoreArk'),
clink: t('namesMoreClink'),
ownnode: t('namesOwnNode'),
+ page: t('namesMorePage'),
};
const body = ui.namesMore === 'bolt11' ? invoicePane()
: ui.namesMore === 'bolt12' ? offerPane()
: ui.namesMore === 'ark' ? arkPane()
: ui.namesMore === 'clink' ? clinkPane()
: ui.namesMore === 'ownnode' ? ownNodeSection()
+ : ui.namesMore === 'page' ? payPagePane()
: menuPane();
return h('div', { class: 'col', style: 'gap:10px;width:100%' },
h('div', { class: 'row between', style: 'align-items:baseline' },
@@ -873,7 +970,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
@@ -908,6 +1005,20 @@ export function namesFeature(ctx) {
};
return lnReceipts.p;
},
+ // A wallet on another ark server (Second, a custom one) gets its name's
+ // Lightning receives only while it is open to answer the registrar's
+ // offer request — the registrar can't arkoor to a server it has no
+ // float on — and its hourly retry rarely met a short session (52 sats
+ // waited 449 tries, 2026-10-18 → 11-03). So once the offer listener is
+ // up, say so: whatever is queued for this name goes now. Once per ten
+ // minutes; a wallet on the coinos server is paid while asleep and
+ // never needs to (and never spends a signature on it).
+ namesListening() {
+ if (!available() || !load().name || getArkProviderId() === 'coinos') return null;
+ if (Date.now() - listeningAt < 600_000) return null;
+ listeningAt = Date.now();
+ return post('/listening', 'POST', {}).catch(() => { listeningAt = 0; return null; });
+ },
// the claimed payment address, for anyone prefilling a lightning address
namesAddress() { const st = load(); return st.name ? `${st.name}@${st.domain || DOMAIN()}` : null; },
// Sign-in races this lookup against the seed work: by the time the
@@ -990,6 +1101,7 @@ export function namesFeature(ctx) {
return null;
},
settingsCards() { return namesCards(); },
+ accountDelete(check) { return wallet.watchOnly || !wallet.nostrSign ? null : accountDelete(check); },
posSettingsCards() { return posSettingsCardsForName(); },
// the Ark server changed: the name's ark= instruction must follow
namesRefresh() { refresh().catch(() => {}); return true; },
diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js
index f7f9e16..5ef6fb8 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';
+ 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>';
@@ -69,7 +69,7 @@ export function nostrLoginFeature(ctx) {
// decrypt that" is a healthy connection doing its job — the DM inbox probes
// it with wraps that turn out to be someone else's, and treating each
// refusal as a dead signer disconnected Amethyst users over and over.
- const SIGNER_DEAD = /did not answer|timed? ?out|connect|closed|socket|relay|network/i;
+ const SIGNER_DEAD = /did not answer|timed? ?out|connect|closed|not open|socket|relay|network/i;
const selfHealing = (signer) => {
if (!signer || signer.kind !== 'bunker') return signer;
const guard = (fn) => async (...args) => {
@@ -158,6 +158,17 @@ export function nostrLoginFeature(ctx) {
// and the payment name too — the Receive pane should open with its QR
const nameHintP = ctx.hook('namesLookupByPk', signer.pubkey);
const res = await walletForSigner(signer);
+ // A way back in (added from Settings): the key holds a copy of an
+ // account's seed, and opens that account as ITSELF — its own name,
+ // profile and identity. Nothing about the key is adopted or kept.
+ if (res.mode === 'restored' && res.recovery) {
+ try { if (signer.kind === 'bunker' && signer.close) signer.close(); } catch {}
+ ctx.onbNostrLogin(true);
+ ui.navAnimSkip = true;
+ await ctx.openMnemonic(res.mnemonic, res.passphrase || '', { spendingHint: !!res.spending, spendingOnly: !!res.spendingOnly });
+ busy(false);
+ return;
+ }
if (res.mode === 'new') {
// No wallet on this identity yet — make one and walk straight in.
// The interstitial that used to ask first read as an error screen to
@@ -364,6 +375,11 @@ export function nostrLoginFeature(ctx) {
await run(() => keySigner(sk));
} catch (e) {
if (/derive a wallet key/.test(e.message) || e.message === pass.LOCK_PASSKEY) { ui.nostrLoginError = e.message; render(); return; }
+ // Only "no passkey here" (NotAllowedError, as browsers report it) rolls
+ // into creating one; anything else is a failure to show, not a reason
+ // to make a second passkey (the Beta's "RP ID cannot be validated" went
+ // on to fail a create too, 2026-11-06).
+ if (e && e.name && e.name !== 'NotAllowedError') { ui.nostrLoginError = e.message || String(e); render(); return; }
try {
const sk = await pass.passkeyCreate();
await run(() => keySigner(sk));
@@ -408,7 +424,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',
@@ -416,21 +438,25 @@ export function nostrLoginFeature(ctx) {
h('button', { class: 'btn-sm', type: 'button', onClick: () => { if (amberDeliver(e.text)) e.text = ''; else { ui.nostrLoginError = t('nlAmberBadPaste'); render(); } } }, t('nlAmberPasteBtn'))),
h('button', { class: 'btn-ghost btn-sm', type: 'button', onClick: () => amberCancel() }, t('cancel')));
}
- function externalButtons(run, big = false) {
+ // passkeyFirst: the front door lists the passkey right under the seed
+ // phrase, before Google (Adam, 2026-11-06)
+ // short: under a "Sign in" heading the buttons just name the way in
+ function externalButtons(run, big = false, passkeyFirst = false, short = false) {
const hasPasskey = typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials;
const pad = big ? 'padding:14px' : '';
- return [
+ const google = [
h('button', { class: 'btn-block', style: pad, disabled: ui.nostrLoginBusy,
onClick: () => googleLogin(run) },
- markedLabel(GOOGLE_MARK, t('nlGoogle'), ui.nostrLoginVia === 'google')),
+ markedLabel(GOOGLE_MARK, t(short ? 'doorGoogle' : 'nlGoogle'), ui.nostrLoginVia === 'google')),
GOOGLE_CENTRAL !== GOOGLE_LEGACY
? h('button', { class: 'linklike small', style: 'align-self:center', disabled: ui.nostrLoginBusy, onClick: () => googleLogin(run, GOOGLE_LEGACY) }, t('nlGooglePrev'))
: null,
- hasPasskey
- ? h('button', { class: 'btn-block', style: pad, disabled: ui.nostrLoginBusy,
- onClick: () => passkeyLogin(run) }, markedLabel(PASSKEY_MARK, t('nlPasskey'), ui.nostrLoginVia === 'passkey'))
- : null,
];
+ const passkey = hasPasskey
+ ? h('button', { class: 'btn-block', style: pad, disabled: ui.nostrLoginBusy,
+ onClick: () => passkeyLogin(run) }, markedLabel(PASSKEY_MARK, t(short ? 'doorPasskey' : 'nlPasskey'), ui.nostrLoginVia === 'passkey'))
+ : null;
+ return passkeyFirst ? [passkey, ...google] : [...google, passkey];
}
// The ways in, as buttons. `run` receives a signer factory. The expanded
@@ -457,12 +483,11 @@ export function nostrLoginFeature(ctx) {
onClick: () => run(() => extensionSigner()) }, t('nlExtension'))
: null,
nostrConnectSection(run),
- // On Android, the signer app straight through an intent (NIP-55): works
- // with Amber offline, no bunker, no relay — one trip through the app
- // per signature.
- amberAvailable()
- ? h('button', { class: 'btn-block', disabled: ui.nostrLoginBusy, onClick: () => run(() => amberSigner()) }, t('nlAmber'))
- : null,
+ // No separate Android-intent (NIP-55) door any more (Adam, 2026-11-15):
+ // it opened the same Amber as Connect a signer app, but a login made
+ // that way couldn't read messages. Accounts that already came in by
+ // intent keep working (resumeLogin), and their pending requests still
+ // show here.
amberWaitCard(),
// These are alternatives, not steps: without the divider the field under
// the button reads as something you also have to fill in.
@@ -605,12 +630,18 @@ export function nostrLoginFeature(ctx) {
// time, and a pause after a failure: identity() asks on every send, and a
// signer that isn't answering shouldn't mean a new relay connection per
// keystroke.
- async function resumeLogin() {
+ const tabHidden = () => typeof document !== 'undefined' && document.visibilityState === 'hidden';
+ async function resumeLogin({ force = false } = {}) {
if (liveSigner()) return live;
const st = load();
if (!st.pubkey) return null;
if (resuming) return resuming;
- if (Date.now() - resumeFailedAt < 20_000) return null;
+ if (!force && Date.now() - resumeFailedAt < 20_000) return null;
+ // A phone freezes a hidden tab: a remote signer asked from there can't be
+ // heard, and that silence isn't the session failing — don't count it.
+ let wasHidden = tabHidden();
+ const onVis = () => { if (tabHidden()) wasHidden = true; };
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVis);
resuming = (async () => {
// a stored passkey-derived key reattaches instantly — no network, no
// dialog; see sessionOf for why this key (alone among keys) is kept
@@ -639,10 +670,13 @@ export function nostrLoginFeature(ctx) {
})();
try {
const s = await resuming;
- if (!s) resumeFailedAt = Date.now();
- else announceLive();
+ if (!s && !wasHidden) resumeFailedAt = Date.now();
+ else if (s) announceLive();
return s;
- } finally { resuming = null; }
+ } finally {
+ resuming = null;
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVis);
+ }
}
// Which door this account came through, for the reconnect surfaces. State
@@ -657,6 +691,124 @@ export function nostrLoginFeature(ctx) {
resumeLogin().then((s) => { if (s) render(); }).catch(() => {});
}
+ // ---- ways back in ------------------------------------------------------
+ // Settings → Wallet: the sign-in methods that can open THIS account on
+ // another device, added after the fact — a passkey, Google, a nostr key —
+ // next to the recovery phrase. Each one gets a copy of the seed encrypted
+ // to its own key (kind 30078, marked `recovery`), so signing in with it
+ // anywhere opens this account as itself. Unlike linking a login, the
+ // account's identity doesn't change.
+ async function addRecovery(makeSigner, via, label = '') {
+ ui.waysBackError = ''; ui.waysBackBusy = via; ui.nostrLoginBusy = true; render();
+ let signer = null;
+ try {
+ if (!wallet.mnemonic) throw new Error(t('nlNeedSeed'));
+ signer = await makeSigner();
+ const st = load();
+ if (st.pubkey && st.pubkey === signer.pubkey) throw new Error(t('waysBackIsLogin'));
+ // a key that already opens a DIFFERENT wallet keeps it: never overwrite
+ const existing = await fetchWalletBackup(signer);
+ if (existing && existing.mnemonic
+ && (existing.mnemonic !== wallet.mnemonic || (existing.passphrase || '') !== (wallet.passphrase || ''))) {
+ throw new Error(t('waysBackTaken'));
+ }
+ await publishWalletBackup(signer, {
+ mnemonic: wallet.mnemonic, passphrase: wallet.passphrase || '',
+ spending: true, recovery: true, spendingOnly: !!ctx.spendingOnlyAccount(),
+ });
+ ctx.addRecoveryMethod({ via, id: signer.pubkey, label });
+ ui.waysBackNostr = false;
+ toast(t('waysBackAdded'));
+ } catch (e) {
+ const msg = String((e && e.message) || e || '');
+ // a dismissed passkey or Google dialog is a plain cancel
+ if (!/NotAllowed|abort/i.test(String((e && e.name) || '') + ' ' + msg)) ui.waysBackError = msg;
+ } finally {
+ try { if (signer && signer.kind === 'bunker' && signer.close) signer.close(); } catch {}
+ ui.waysBackBusy = null; ui.nostrLoginBusy = false;
+ render();
+ }
+ }
+ async function passkeyRecovery() {
+ const pass = await import('../passkey.js');
+ const name = ctx.hook('namesAddress') || 'coinos';
+ await addRecovery(async () => keySigner(await pass.passkeyCreate({ name, displayName: name })), 'passkey');
+ }
+ async function googleRecovery() {
+ // opened in the click itself (user activation) — see googleLogin
+ const popup = window.open('about:blank', 'OAuth', 'width=600,height=600');
+ ui.waysBackError = ''; ui.waysBackBusy = 'google'; render();
+ try {
+ const pome = await import('../pomegranate.js');
+ const { uri, email } = await pome.loginWithGoogle(popup, {});
+ await addRecovery(() => bunkerSigner(uri, { onAuth: (url) => { ui.nostrLoginAuthUrl = url; render(); } }), 'google', email || '');
+ } catch (e) {
+ try { popup && popup.close(); } catch {}
+ ui.waysBackError = (e && e.message) || String(e);
+ ui.waysBackBusy = null;
+ render();
+ }
+ }
+ // pen over a sheet of paper, in the line style of the passkey mark
+ const PAPER_MARK = '<svg width="19" height="19" style="display:block" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><path d="M13 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"/><path d="M8 9h4"/><path d="M8 13h3"/><path d="M8 17h6"/><path d="M18.4 2.6a2 2 0 0 1 2.8 2.8L14 12.6l-3.6.9.9-3.6z"/></svg>';
+ const fmtDay = (ms) => { try { return new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }); } catch { return ''; } };
+ function waysBackCard() {
+ if (wallet.watchOnly || !wallet.mnemonic) return null;
+ const methods = ctx.recoveryMethods() || [];
+ const st = load();
+ const busyVia = ui.waysBackBusy;
+ const hasPasskey = typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials;
+ const done = (mark, title, detail, key) => h('div', { class: 'row gap6 ways-back-row', 'data-way': key, style: 'align-items:center;padding:8px 2px' },
+ h('span', { style: 'display:flex;flex-shrink:0;width:23px;justify-content:center', html: mark }),
+ h('span', { class: 'col', style: 'flex:1;gap:1px;min-width:0' },
+ h('span', { style: 'font-weight:600' }, title),
+ detail ? h('span', { class: 'small muted break' }, detail) : null),
+ h('span', { class: 'ways-back-check', 'aria-label': t('waysBackOn') }, '✓'));
+ const add = (mark, label, via, onClick) => h('button', {
+ class: 'btn-block ways-back-add', 'data-way': via, disabled: !!busyVia, onClick,
+ }, markedLabel(mark, label, busyVia === via));
+ const rows = [];
+ // the sign-in this account came through is a way back in already
+ if (st.pubkey) {
+ const via = st.via || 'nostr';
+ rows.push(done(via === 'google' ? GOOGLE_MARK : via === 'passkey' ? PASSKEY_MARK : OSTRICH,
+ t('waysBackLogin', { via: via === 'google' ? 'Google' : via === 'passkey' ? t('doorPasskey') : 'Nostr' }),
+ via === 'google' || via === 'passkey' ? '' : (npubOf(st.pubkey) || '').slice(0, 20) + '…', 'login'));
+ }
+ for (const m of methods) {
+ if (m.via === 'passkey') rows.push(done(PASSKEY_MARK, t('doorPasskey'), t('waysBackAddedOn', { date: fmtDay(m.at) }), 'passkey'));
+ else if (m.via === 'google') rows.push(done(GOOGLE_MARK, 'Google', m.label || t('waysBackAddedOn', { date: fmtDay(m.at) }), 'google'));
+ else rows.push(done(OSTRICH, 'Nostr', (npubOf(m.id) || '').slice(0, 20) + '…', 'nostr'));
+ }
+ const seen = ctx.seedSeen();
+ const have = (via) => methods.some((m) => m.via === via) || (via !== 'nostr' && st.via === via);
+ const adds = [
+ hasPasskey && !have('passkey') ? add(PASSKEY_MARK, t('waysBackAddPasskey'), 'passkey', () => passkeyRecovery()) : null,
+ !have('google') ? add(GOOGLE_MARK, t('waysBackAddGoogle'), 'google', () => googleRecovery()) : null,
+ ui.waysBackNostr
+ ? h('div', { class: 'col', style: 'gap:8px' },
+ h('div', { class: 'row between' },
+ h('strong', { class: 'small' }, t('waysBackAddNostr')),
+ h('span', { class: 'linklike small', onClick: () => { ui.waysBackNostr = false; ui.waysBackError = ''; render(); } }, t('cancel'))),
+ signerButtons((make) => addRecovery(make, 'nostr'), { nostrOnly: true }))
+ : add(OSTRICH, t('waysBackAddNostr'), 'nostr', () => { ui.waysBackNostr = true; ui.waysBackError = ''; ui.nostrLoginError = ''; render(); }),
+ // the recovery phrase, as one more button (Adam, 2026-11-15): it opens
+ // the masked words below, ticked once they've been seen
+ h('button', { class: 'btn-block ways-back-add', 'data-way': 'phrase', disabled: !!busyVia, onClick: () => ctx.showRecoveryPhrase() },
+ h('span', { style: 'display:flex;align-items:center;justify-content:center;gap:8px' },
+ h('span', { style: 'display:flex;flex-shrink:0', html: PAPER_MARK }),
+ t('waysBackPaper'),
+ seen ? h('span', { class: 'ways-back-check', 'aria-label': t('waysBackOn') }, '✓') : null)),
+ ].filter(Boolean);
+ return h('div', { class: 'card col ways-back', style: 'gap:6px' },
+ h('h3', {}, t('waysBackTitle')),
+ h('p', { class: 'small muted', style: 'margin:0 0 4px' }, t('waysBackDesc')),
+ h('div', { class: 'col', style: 'gap:0' }, ...rows),
+ adds.length ? h('div', { class: 'col', style: 'gap:8px;margin-top:6px' }, ...adds) : null,
+ ui.waysBackError ? h('div', { class: 'notice err' }, ui.waysBackError) : null,
+ h('p', { class: 'small faint', style: 'margin:4px 0 0' }, t('waysBackNote')));
+ }
+
function settingsCard() {
if (wallet.watchOnly || !wallet.mnemonic) return null;
const st = load();
@@ -702,8 +854,31 @@ export function nostrLoginFeature(ctx) {
// reattach silently). Same guarded buttons as the settings card — an
// extension, the signer-app deeplink/QR, or a pasted key — and the run
// refuses a different account.
+ // While the reconnect screen is up, keep trying the stored session: the
+ // remote signer authorised this client key long ago and nearly always still
+ // answers — it just wasn't heard the moment the screen opened (tab frozen,
+ // relay socket cut, the signer app asleep until opened). One try and then
+ // nothing meant a brand-new connection every time.
+ let retryT = 0;
+ const retryStored = () => {
+ clearTimeout(retryT); retryT = 0;
+ if (ui.nostrReconnect !== true || liveSigner()) return;
+ const st = load();
+ if (!st.session || st.session.amber) return;
+ if (!tabHidden()) {
+ resumeLogin({ force: true }).then((sg) => {
+ if (sg && ui.nostrReconnect === true) { stopNostrConnect(); ui.nostrReconnect = null; ui.nostrConnectOpen = false; render(); }
+ }).catch(() => {});
+ }
+ retryT = setTimeout(retryStored, 10_000);
+ };
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', () => { if (!tabHidden() && ui.nostrReconnect === true) retryStored(); });
+ }
+
function reconnectScreen() {
const st = load();
+ if (ui.nostrReconnect === true && !retryT && st.session && !st.session.amber) retryT = setTimeout(retryStored, 0);
// 'upgrade': Amber by intent is live but can't read messages — offer
// only its NIP-46 door (nostrconnect), same account enforced
const upgrade = ui.nostrReconnect === 'upgrade';
@@ -750,7 +925,7 @@ export function nostrLoginFeature(ctx) {
if (!st.pubkey || liveSigner()) return false;
ui.nostrReconnect = true;
ui.nostrLoginError = '';
- this.nostrLoginResume().then((sg) => {
+ resumeLogin({ force: true }).then((sg) => {
if (sg && ui.nostrReconnect) { ui.nostrReconnect = null; render(); }
}).catch(() => {});
render();
@@ -814,9 +989,12 @@ export function nostrLoginFeature(ctx) {
.catch(() => { _spendingHinted = false; });
return true;
},
- frontDoorSignin() {
- return h('div', { class: 'col', style: 'gap:8px' },
- ...externalButtons(loginWith, true),
+ // The front door's ways in, loose: the page spaces them evenly with the
+ // seed-phrase and coinos.io doors around them (a wrapper of their own
+ // put 8px between these and 20px between them and the rest).
+ frontDoorSignin({ short = false } = {}) {
+ return [
+ ...externalButtons(loginWith, true, true, short),
h('button', { class: 'btn-block', style: 'padding:14px', onClick: () => {
if (ui.onb) ui.onb.step = 'signin';
ui.nostrLoginOpen = true;
@@ -824,9 +1002,11 @@ export function nostrLoginFeature(ctx) {
render();
} }, h('span', { style: 'display:flex;align-items:center;justify-content:center;gap:8px' },
h('span', { style: 'display:flex;flex-shrink:0', html: OSTRICH }),
- t('nlSignInNostr'))),
- ui.nostrLoginError ? h('div', { class: 'notice err' }, ui.nostrLoginError) : null);
+ t(short ? 'doorNostr' : 'nlSignInNostr'))),
+ ui.nostrLoginError ? h('div', { class: 'notice err' }, ui.nostrLoginError) : null,
+ ].filter(Boolean);
},
nostrSettingsCards() { return [settingsCard()]; },
+ waysBackCard() { return waysBackCard(); },
};
}
diff --git a/src/features/nwc.js b/src/features/nwc.js
index ec79081..741b0a4 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 {
@@ -388,7 +388,10 @@ export function nwcFeature(ctx) {
return !!(prior && prior.length);
};
if (age > 5 && await lookBack()) return dlog('nwc: skip — request already answered elsewhere', ev.id.slice(0, 8));
- if (mobile && age <= 5) await new Promise((r) => setTimeout(r, 1000));
+ // (a phone with this app on screen is as awake as any computer: only
+ // one behind another app holds back — every zap answered by an open
+ // phone used to wait this second for nobody)
+ if (mobile && age <= 5 && typeof document !== 'undefined' && document.hidden) await new Promise((r) => setTimeout(r, 1000));
claimed = await claim(ev.id);
if (claimed === false) return dlog('nwc: standing down — another device claimed', ev.id.slice(0, 8));
if (claimed === null && age <= 5) {
@@ -478,11 +481,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 } };
@@ -614,12 +627,23 @@ export function nwcFeature(ctx) {
if (!o || !pend.length) return;
const moves = hook('arkMovements') || [];
const keep = [];
+ // The pending list rides the synced wallet state, and every device holds
+ // the offer key: phone and laptop each published the same receipt a
+ // minute apart (Helen's 88-sat zap, Adam 2026-11-14). A receipt already
+ // out — sent from here, or found on the relays — isn't sent again.
+ const done = new Set(st.zapDone || []);
+ const sent = [];
for (const z of pend) {
if (Date.now() - z.ts > 86400_000) continue; // expired unpaid
+ if (done.has(z.invoice)) continue;
const paid = moves.find((m) => m.type === 'ln-receive' && m.status === 'complete' && m.invoice === z.invoice);
if (!paid) { keep.push(z); continue; }
try {
const zapReq = JSON.parse(z.zap);
+ const offerPk = getPublicKey(hex.decode(o.sk));
+ const to = (zapReq.tags.find((t2) => t2[0] === 'p') || [])[1];
+ const out = await query(NWC_RELAYS, { kinds: [9735], authors: [offerPk], ...(to ? { '#p': [to] } : {}), since: Math.floor(z.ts / 1000) - 120 }, 2500).catch(() => []);
+ if ((out || []).some((r) => (r.tags || []).some((t2) => t2[0] === 'bolt11' && t2[1] === z.invoice))) { sent.push(z.invoice); continue; }
const tags = [
...zapReq.tags.filter((t2) => t2[0] === 'p' || t2[0] === 'e'),
['P', zapReq.pubkey],
@@ -631,10 +655,12 @@ export function nwcFeature(ctx) {
const relayTag = zapReq.tags.find((t2) => t2[0] === 'relays');
const relays = [...new Set([...(relayTag ? relayTag.slice(1) : []), ...NWC_RELAYS])].slice(0, 8);
await publish(relays, receipt);
+ sent.push(z.invoice);
} catch (e) { console.warn('nwc: zap receipt failed', e.message); }
}
const st2 = load();
st2.zapPending = keep;
+ st2.zapDone = [...new Set([...(st2.zapDone || []), ...sent])].slice(-100);
save(st2);
}
@@ -661,6 +687,10 @@ export function nwcFeature(ctx) {
{ kinds: [OFFER_KIND], '#p': [o.pk], since: nowSec() - MAX_AGE_SEC },
(ev) => { onOfferRequest(ev).catch((e) => console.warn('nwc: offer handler', e.message)); },
));
+ // a beat for the subscription to reach the relays, then tell the
+ // registrar this wallet is here to answer: Lightning deliveries
+ // queued for a wallet on another ark server go out now (names)
+ setTimeout(() => { if (gen === listenGen) Promise.resolve(hook('namesListening')).catch(() => {}); }, 1500);
}
const list = [...conns(), ...revokedConns()];
dlog(`nwc: listen() gen ${gen} — ${list.length} connection(s)`);
@@ -822,6 +852,25 @@ export function nwcFeature(ctx) {
// wrong keys — background wake-ups silently die the first time a
// connection is recreated. Debounced; the server replaces by endpoint.
let regTimer = null;
+ // The browser's subscription, made again when it's gone: iOS drops it after
+ // three pushes that showed no notification (and a key rotation strands an
+ // old one), and nothing else re-arms a wallet whose `background` is still on.
+ async function currentSub() {
+ const reg = await navigator.serviceWorker.ready;
+ const { publicKey } = await (await fetch(`${NOTIFIER}/vapid`)).json();
+ const want = b64ToBytes(publicKey);
+ let sub = await reg.pushManager.getSubscription();
+ if (sub) {
+ let have = [];
+ try { have = new Uint8Array(sub.options.applicationServerKey || []); } catch {}
+ if (have.length === want.length && have.every((b, i) => b === want[i])) return sub.toJSON();
+ try { await sub.unsubscribe(); } catch {}
+ }
+ if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return null;
+ sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: want });
+ dlog('nwc: push subscription was gone, made a new one');
+ return sub.toJSON();
+ }
function refreshRegistration() {
if (!load().background) return;
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return;
@@ -831,8 +880,7 @@ export function nwcFeature(ctx) {
const pks = watchPks();
if (!pks.length) return;
const up2 = upEndpoint();
- const sub = up2 ? { endpoint: up2, unifiedpush: true }
- : await (await navigator.serviceWorker.ready).pushManager.getSubscription().then((x) => x && x.toJSON());
+ const sub = up2 ? { endpoint: up2, unifiedpush: true } : await currentSub();
if (!sub) return;
await fetch(`${NOTIFIER}/register`, {
method: 'POST', headers: { 'content-type': 'application/json' },
@@ -949,7 +997,14 @@ export function nwcFeature(ctx) {
if (typeof window !== 'undefined') {
window.addEventListener('online', () => listen());
document.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'visible' && conns().length) listen();
+ if (document.visibilityState === 'visible' && conns().length) {
+ listen(); refreshRegistration();
+ // the worker may have paid while this app sat behind another one
+ Promise.resolve(hook('arkBgAbsorb')).then((had) => { if (had) return reconcileBg(); }).catch(() => {});
+ }
+ // going behind another app: the worker answers from the mirror now, so
+ // it gets this moment's coins, not the last minute-and-a-half's
+ if (document.visibilityState === 'hidden' && conns().length) writeBg();
});
}
}
@@ -1064,6 +1119,8 @@ export function nwcFeature(ctx) {
id: 'nwc',
nwcOfferPubkey() { return (hook('arkReady') && !wallet.watchOnly) ? offerKeys().pk : null; },
nwcOfferString() { return hook('arkReady') && !wallet.watchOnly ? offerString() : null; },
+ // tests: the receipt pass on demand (normally the watchdog's and the reconcile's)
+ nwcPublishZapReceipts() { return publishZapReceipts(); },
init() { listen(); startWatchdog(); refreshRegistration(); reconcileBg(); ensureBackground(false); serveWake(); },
stop() { stop(); if (watchdog) { clearInterval(watchdog); watchdog = null; } },
nostrSettingsCards() { return [nwcCard()]; },
@@ -1075,7 +1132,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/features/pos.js b/src/features/pos.js
index 3727862..eb4b0e9 100644
--- a/src/features/pos.js
+++ b/src/features/pos.js
@@ -44,8 +44,11 @@ export function posFeature(ctx) {
// ---- flow ----------------------------------------------------------------
// ui.pos: { step: 'amount'|'tip'|'invoice'|'paid', amount, note, tipMode, tipCustom, sale, error, busy }
- function open() {
- ui.pos = { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '' };
+ // `request`: Receive → Amount (Adam, 2026-11-15) — the same amount pad
+ // and invoice for asking someone for a sum, without the till around it:
+ // no tip prompt, no tip settings or day's sales, and Back is Receive.
+ function open(opts = {}) {
+ ui.pos = { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '', request: !!opts.request };
render();
}
// Digits on screen, into the same field a keyboard or a paste would fill.
@@ -90,7 +93,7 @@ export function posFeature(ctx) {
if (!bill) { p.error = t('posEnterAmount'); render(); return; }
p.error = '';
if (!hook('arkReady')) { p.error = t('posNeedsSpending'); render(); return; }
- if (st().askTip) { p.step = 'tip'; p.tipMode = null; p.tipCustom = ''; render(); return; }
+ if (st().askTip && !p.request) { p.step = 'tip'; p.tipMode = null; p.tipCustom = ''; render(); return; }
makeSale(bill, 0, 0);
}
function tipSat() {
@@ -107,6 +110,7 @@ export function posFeature(ctx) {
id: 's' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
at: Date.now(), billSat: bill, tipSat: tip, tipPct, note: (p.note || '').trim().slice(0, 80),
status: 'open', fiat: rateNow() ? { code: getCurrency(), rate: rateNow() } : null,
+ ...(p.request ? { request: true } : {}),
};
try {
const memo = (sale.note ? sale.note + ' · ' : '') + t('posMemo', { bill: fmtAmount(bill) + ' ' + unitLabel(), tip: tip ? fmtAmount(tip) + ' ' + unitLabel() : '0' });
@@ -145,7 +149,7 @@ export function posFeature(ctx) {
function newSale() {
const p = ui.pos;
if (p.sale && p.sale.status === 'open') voidSale(p.sale);
- Object.assign(p, { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '' });
+ Object.assign(p, { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '', request: p.request });
render();
}
@@ -194,7 +198,7 @@ export function posFeature(ctx) {
return h('div', { class: 'col', style: 'gap:16px' },
ctx.brandHeader(false),
h('div', { class: 'card col', style: 'gap:12px' },
- h('h3', { style: 'margin:0' }, t('posTitle')),
+ h('h3', { style: 'margin:0' }, t(p.request ? 'recvAmountTitle' : 'posTitle')),
h('div', { class: 'input-group' },
h('input', {
type: 'text', inputmode: 'decimal', class: 'pos-amount', placeholder: '0', value: p.amount,
@@ -204,12 +208,12 @@ export function posFeature(ctx) {
unitTag()),
getUnit() !== 'fiat' && billSat() && fiatLine(billSat()) ? h('div', { class: 'small muted', style: 'text-align:right' }, fiatLine(billSat())) : null,
numpad(() => p.amount, (v) => { p.amount = v; }),
- h('input', { type: 'text', placeholder: t('posNoteHint'), value: p.note, maxlength: '80', onInput: (e) => { p.note = e.target.value; } }),
+ h('input', { type: 'text', placeholder: t(p.request ? 'recvAmountNote' : 'posNoteHint'), value: p.note, maxlength: '80', onInput: (e) => { p.note = e.target.value; } }),
p.error ? h('div', { class: 'notice error small' }, p.error) : null,
- h('button', { class: 'btn-primary btn-block', disabled: !!p.busy, onClick: charge }, p.busy ? h('span', { class: 'spinner sm' }) : t('posCharge')),
+ h('button', { class: 'btn-primary btn-block', id: 'pos-charge', disabled: !!p.busy, onClick: charge }, p.busy ? h('span', { class: 'spinner sm' }) : t(p.request ? 'recvAmountGo' : 'posCharge')),
p.busy ? h('div', { class: 'small muted', style: 'text-align:center' }, t('posMakingInvoice')) : null),
- tipSettingsCard(s),
- salesCard(s),
+ p.request ? null : tipSettingsCard(s),
+ p.request ? null : salesCard(s),
back());
}
function tipSettingsCard(s) {
@@ -231,7 +235,7 @@ export function posFeature(ctx) {
}
function salesCard(s) {
adoptPaid(s);
- const sales = [...s.sales].reverse();
+ const sales = s.sales.filter((x) => !x.request).reverse(); // Receive → Amount isn't a sale
if (!sales.length) return null;
const today = dayKey(Date.now());
const paidToday = sales.filter((x) => x.status === 'paid' && dayKey(x.paidAt || x.at) === today);
@@ -310,8 +314,8 @@ export function posFeature(ctx) {
h('h3', { style: 'margin:0' }, t('posPaid')),
money(sale.billSat + sale.tipSat, sale.fiat && sale.fiat.rate),
sale.tipSat ? h('div', { class: 'small muted' }, t('posBreakdown', { bill: fmtAmount(sale.billSat), tip: fmtAmount(sale.tipSat), u: unitLabel() })) : null,
- h('button', { class: 'btn-primary btn-block', onClick: newSale }, t('posNewSale'))),
- back());
+ p.request ? null : h('button', { class: 'btn-primary btn-block', onClick: newSale }, t('posNewSale'))),
+ p.request ? h('button', { class: 'btn-primary btn-block', onClick: close }, t('recvAmountDone')) : back());
}
function posScreen() {
const p = ui.pos;
@@ -346,6 +350,8 @@ export function posFeature(ctx) {
h('p', { class: 'small faint', style: 'margin:0' }, t('posLinkHint', { url })))];
},
openPos: open,
+ openAmountRequest: () => open({ request: true }),
+ posAvailable: () => !!hook('arkReady'),
// The history detail of a till payment says what was the bill and what the tip.
arkMoveDetailExtra(m, row) {
const sale = saleOfMovement(m);
diff --git a/src/features/withdraw-links.js b/src/features/withdraw-links.js
new file mode 100644
index 0000000..38b2d8c
--- /dev/null
+++ b/src/features/withdraw-links.js
@@ -0,0 +1,218 @@
+// Prepaid Lightning withdraw links (LNURL-withdraw): make a link or QR that
+// whoever holds it can pull sats from — a voucher, a faucet, a printed card —
+// even while this wallet is asleep. "Do we have lnurl withdraw links
+// somewhere? can we add them?" → "Prepaid" (Adam, 2026-11-07).
+//
+// The money is paid up front, from Spending over Lightning, to the coinos
+// registrar (coinosv3-server names/withdraw.js), which pays each claim out of
+// it; until claimed it sits there, and the creator can take back whatever is
+// left at any time ("Take back"), which closes the link. Links belong to the
+// wallet's own nostr key, so every device with the seed sees them.
+//
+// It lives on the Send page as a sibling of the gift link: ui.giftMode ===
+// 'lnurl' (giftMode is already a navigation field with its resets).
+import { nip98Header } from '../nip98.js';
+import { encodeLnurl } from '../lnurl.js';
+import { qrSvg } from '../qr.js';
+import { getNetwork } from '../api.js';
+import { t } from '../i18n.js';
+
+const REGISTRAR = 'https://names.coinos.io';
+const NOTE_MAX = 120;
+const net = () => (getNetwork() === 'mutinynet' ? 'mutinynet' : 'mainnet');
+const available = () => ['mainnet', 'mutinynet'].includes(getNetwork());
+
+export function withdrawLinks(ctx) {
+ const { h, ui, render, wallet, toast, copyBtn, goBack, fmtAmount, unitLabel, unitTag, parseAmount, getUnit } = ctx;
+ const hook = ctx.hook || (() => null);
+ const base = () => ctx.withdrawRegistrar || REGISTRAR;
+ // ui.wl: { list: [...]|null, listError, amount, uses, note, busy, error, open: id|null, made: id|null, taking: id|null }
+ const st = () => (ui.wl ||= { list: null, amount: '', uses: '1', note: '' });
+
+ const signer = { signEvent: (e) => wallet.nostrSign(e) };
+ async function call(method, path, payload) {
+ const url = base() + path;
+ const body = payload ? JSON.stringify(payload) : '';
+ const auth = await nip98Header(signer, url, method, body);
+ const r = await fetch(url, { method, headers: { authorization: auth, ...(body ? { 'content-type': 'application/json' } : {}) }, ...(body ? { body } : {}) });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok || j.error) throw new Error(j.error || `registrar refused (${r.status})`);
+ return j;
+ }
+
+ async function load() {
+ const s = st();
+ try {
+ const j = await call('GET', '/withdraw/mine');
+ s.list = (j.links || []).filter((l) => l.net === net());
+ s.listError = '';
+ } catch (e) { s.listError = e.message; s.list ||= []; }
+ render();
+ }
+
+ function open() {
+ ui.wl = null;
+ ui.giftMode = 'lnurl';
+ ui.sendError = '';
+ st();
+ render();
+ load();
+ }
+
+ const lnurlOf = (l) => encodeLnurl(l.url).toUpperCase();
+ const amt = (sat) => fmtAmount(sat) + ' ' + unitLabel();
+
+ async function create() {
+ const s = st();
+ const sat = parseAmount(s.amount, getUnit()) || 0;
+ const uses = Math.floor(Number(s.uses) || 1);
+ s.error = '';
+ if (!(sat >= 1)) { s.error = t('wlAmountInvalid'); render(); return; }
+ if (!(uses >= 1 && uses <= 1000)) { s.error = t('wlUsesInvalid'); render(); return; }
+ if (wallet.watchOnly) { s.error = t('lnWithdrawWatchOnly'); render(); return; }
+ if (!hook('arkReady')) { s.error = t('hatNeedSpending'); render(); return; }
+ const total = sat * uses;
+ if ((hook('arkSpendableSat') || 0) < total + Math.max(10, Math.ceil(total * 0.002))) { s.error = t('wlNoFunds', { amount: amt(total) }); render(); return; }
+ s.busy = true; render();
+ try {
+ const inv = await call('POST', '/withdraw/new', { sat, uses, note: String(s.note || '').trim().slice(0, NOTE_MAX), net: net() });
+ await hook('arkPayInvoice', inv.invoice, { maxAmountSat: inv.totalSat });
+ let link = null;
+ for (let i = 0; i < 10 && !link; i++) {
+ try { link = await call('POST', '/withdraw/funded', { id: inv.id }); }
+ catch (e) { if (!/not paid/i.test(e.message)) throw e; await new Promise((r) => setTimeout(r, 1500)); }
+ }
+ if (!link) throw new Error(t('wlNotConfirmed'));
+ s.list = [link, ...(s.list || []).filter((l) => l.id !== link.id)];
+ s.made = link.id; s.open = link.id;
+ s.amount = ''; s.uses = '1'; s.note = '';
+ } catch (e) {
+ s.error = e.message || String(e);
+ } finally { s.busy = false; render(); }
+ }
+
+ async function takeBack(l) {
+ const s = st();
+ s.taking = l.id; s.error = ''; render();
+ let lnId = null;
+ try {
+ if (l.remainingSat > 0) {
+ const inv = await hook('arkLnInvoice', l.remainingSat, t('wlTakeBackMemo'));
+ if (!inv || !inv.invoice) throw new Error(t('lnWithdrawNoInvoice'));
+ lnId = inv.id;
+ // the wallet has to claim the held payment while the registrar pays it
+ hook('arkLnWatch', inv.id, () => {});
+ const r = await call('POST', '/withdraw/reclaim', { id: l.id, invoice: inv.invoice });
+ Object.assign(l, r);
+ toast(r.paid === false ? t('wlTakeBackFailed') : t('wlTakenBack', { amount: amt(inv.amountSat) }));
+ } else {
+ Object.assign(l, await call('POST', '/withdraw/reclaim', { id: l.id }));
+ }
+ } catch (e) {
+ if (lnId) hook('arkLnCancel', lnId);
+ s.error = e.message || String(e);
+ } finally { s.taking = null; render(); load(); }
+ }
+
+ // What became of the latest claim someone made (reclaims aside): on its
+ // way, or turned back with the sats still here. "I made a transaction for
+ // 1,000,000 sats using the Withdraw link method, but they never arrived"
+ // (a user, 2026-11-14): the claim had failed and the link said only
+ // "1,000,000 sats left".
+ function lastClaim(l) {
+ const c = (l.claims || []).filter((x) => !x.reclaim).at(-1);
+ if (!c || c.status === 'paid') return null;
+ if (c.status === 'paying') return { kind: 'paying', c };
+ return l.status === 'open' && l.remainingSat >= c.sat ? { kind: 'failed', c } : null;
+ }
+
+ function linkCard(l) {
+ const s = st();
+ const lnurl = lnurlOf(l);
+ let svg = null;
+ try { svg = qrSvg(lnurl, { ec: 'M', mode: 'Alphanumeric' }); } catch {}
+ const live = l.status === 'open' && l.remainingSat > 0 && l.used < l.uses;
+ return h('div', { class: 'card col', style: 'align-items:center;gap:10px' },
+ h('h3', { style: 'align-self:stretch' }, s.made === l.id ? t('wlReady') : t('wlTitle')),
+ live && svg ? h('div', { html: svg }) : null,
+ l.note ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, l.note) : null,
+ h('div', { class: 'small muted', style: 'text-align:center' },
+ l.uses > 1 ? t('wlTermsMany', { amount: amt(l.sat), n: l.uses - l.used, total: l.uses }) : t('wlTermsOne', { amount: amt(l.sat) }),
+ ' · ', t('wlLeft', { amount: amt(l.remainingSat) })),
+ live ? h('div', { class: 'addr-box break mono', style: 'width:100%;font-size:11px' }, lnurl) : h('div', { class: 'notice small' }, l.status === 'closed' ? t('wlClosed') : t('wlUsedUp')),
+ live ? h('div', { class: 'row gap6 wrap', style: 'width:100%' }, copyBtn(lnurl, t('wlCopy'))) : null,
+ live ? h('div', { class: 'small faint', style: 'text-align:center' }, t('wlBearer')) : null,
+ (() => {
+ const lc = lastClaim(l);
+ if (!lc) return null;
+ // while it's being paid, look again every 10 s so the answer shows up here
+ if (lc.kind === 'paying' && !s.poll) s.poll = setTimeout(() => { st().poll = null; if (ui.giftMode === 'lnurl') load(); }, 10_000);
+ return lc.kind === 'paying'
+ ? h('div', { class: 'notice info small wl-claim-paying', style: 'width:100%' }, t(lc.c.tries > 1 ? 'wlClaimRetrying' : 'wlClaimPaying', { amount: amt(lc.c.sat) }))
+ : h('div', { class: 'notice err small wl-claim-failed', style: 'width:100%' }, t('wlClaimFailed', { amount: amt(lc.c.sat) }));
+ })(),
+ s.error && h('div', { class: 'notice err', style: 'width:100%' }, s.error),
+ live || (l.status === 'open' && l.remainingSat > 0)
+ ? (s.taking === l.id
+ ? h('button', { class: 'btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
+ : h('button', { class: 'btn-ghost btn-block', onClick: () => takeBack(l) }, t('wlTakeBack', { amount: amt(l.remainingSat) })))
+ : null,
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { s.open = null; s.made = null; s.error = ''; render(); } }, t('back')));
+ }
+
+ function formCard() {
+ const s = st();
+ const sat = parseAmount(s.amount, getUnit()) || 0;
+ const uses = Math.max(1, Math.floor(Number(s.uses) || 1));
+ return h('div', { class: 'card col gap6' },
+ h('h3', {}, t('wlTitle')),
+ h('div', { class: 'small muted' }, t('wlDesc')),
+ h('div', { class: 'input-group' },
+ h('input', { id: 'wl-amount', type: 'number', min: '0', inputmode: 'decimal', step: getUnit() === 'sats' ? '1' : '0.00000001',
+ placeholder: t('wlAmount'), value: s.amount, onInput: (e) => { s.amount = e.target.value; render(); } }),
+ h('div', { style: 'display:flex;align-items:center' }, unitTag())),
+ h('label', { class: 'row gap6', style: 'align-items:center' },
+ h('span', { class: 'small grow' }, t('wlUses')),
+ h('input', { id: 'wl-uses', type: 'number', min: '1', max: '1000', step: '1', inputmode: 'numeric', style: 'width:90px',
+ value: s.uses, onInput: (e) => { s.uses = e.target.value; render(); } })),
+ h('textarea', { class: 'gift-note-input', rows: 2, maxlength: NOTE_MAX, placeholder: t('wlNote'), value: s.note, onInput: (e) => { s.note = e.target.value; } }),
+ h('div', { class: 'small faint' }, sat >= 1 && uses > 1 ? t('wlPayNowMany', { total: amt(sat * uses), n: uses, amount: amt(sat) }) : t('wlPayNow')),
+ s.error && !s.open ? h('div', { class: 'notice err' }, s.error) : null,
+ s.busy
+ ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
+ : h('button', { id: 'wl-create', class: 'btn-primary btn-block', onClick: create }, sat >= 1 ? t('wlCreateFor', { amount: amt(sat * uses) }) : t('wlCreate')));
+ }
+
+ function listCard() {
+ const s = st();
+ if (s.list == null) return h('div', { class: 'card', style: 'text-align:center' }, h('span', { class: 'spinner sm' }));
+ if (!s.list.length) return s.listError ? h('div', { class: 'notice err small' }, s.listError) : null;
+ return h('div', { class: 'card col gap6' },
+ h('span', { class: 'small muted' }, t('wlYours')),
+ ...s.list.map((l) => h('button', { class: 'row between wl-row', style: 'text-align:left', onClick: () => { s.open = l.id; s.made = null; s.error = ''; render(); } },
+ h('span', { class: 'small' }, amt(l.sat), l.uses > 1 ? ` × ${l.uses}` : '', l.note ? h('span', { class: 'faint' }, ' · ' + l.note) : null),
+ h('span', { class: 'small faint' },
+ l.status === 'closed' ? t('wlClosedTag') : l.remainingSat < 1 || l.used >= l.uses ? t('wlUsedUpTag')
+ : lastClaim(l)?.kind === 'failed' ? t('wlClaimFailedTag', { amount: amt(l.remainingSat) })
+ : t('wlLeft', { amount: amt(l.remainingSat) })))));
+ }
+
+ function view() {
+ const s = st();
+ if (!available()) {
+ return h('div', { class: 'col', style: 'gap:12px' },
+ h('div', { class: 'card col' }, h('h3', {}, t('wlTitle')), h('div', { class: 'small muted' }, t('wlMainnetOnly'))),
+ h('button', { class: 'btn-ghost btn-block', onClick: () => goBack(() => { ui.giftMode = false; }) }, t('back')));
+ }
+ const l = s.open && (s.list || []).find((x) => x.id === s.open);
+ if (l) return h('div', { class: 'col', style: 'gap:12px' }, linkCard(l));
+ return h('div', { class: 'col', style: 'gap:12px' },
+ formCard(),
+ listCard(),
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.wl = null; goBack(() => { ui.giftMode = false; }); } }, t('back')));
+ }
+
+ const entry = () => h('button', { id: 'wl-open', class: 'linklike small', style: 'align-self:center;margin-top:2px', onClick: open }, '⚡ ' + t('wlTitle'));
+
+ return { view, entry, open };
+}
diff --git a/src/features/zaps.js b/src/features/zaps.js
index d364738..49e457f 100644
--- a/src/features/zaps.js
+++ b/src/features/zaps.js
@@ -12,10 +12,11 @@
// land here directly.
import { t } from '../i18n.js';
+import { momentToggle, mediaClock } from '../media-timeline.js';
import { npubOf } from '../nostr.js';
import { parseZapTarget, zapTargetFromProfile, fetchPayParams, buildZapRequest, requestInvoice, parseLnurlAuth, lnurlAuthKey, lnurlAuthLogin, submitWithdraw } from '../lnurl.js';
import { HDKey } from '@scure/bip32';
-import { mnemonicToSeedSync } from '@scure/bip39';
+import { seedSync } from '../seed.js';
import { decodeNoffer } from '../noffer.js';
import { requestOfferInvoice } from '../clink.js';
import { decodeOffer } from '../bolt12.js';
@@ -132,7 +133,7 @@ export function zapsFeature(ctx) {
if (profile && profile.name) z.name = profile.name;
const lnTarget = zapTargetFromProfile(profile, target.pk);
if (!lnTarget) { z.status = 'error'; z.error = t('lnZapNoAddress'); render(); return; }
- z.target = target = { ...lnTarget, eventId: target.eventId || null }; // keep the note being zapped
+ z.target = target = { ...lnTarget, eventId: target.eventId || null, moment: target.moment }; // keep the note being zapped
z.address = lnTarget.address || z.address;
}
@@ -196,6 +197,16 @@ export function zapsFeature(ctx) {
render();
}
+ // A zap request is signed as the person zapping: the login identity when
+ // there is one (the face their chat line and the streamer's overlay
+ // show), else the wallet's own key. It used to be the wallet key always,
+ // and a signed-in person's zaps showed under a stranger's npub.
+ async function zapSigner() {
+ const id = hook('nostrLoginIdentity');
+ const signer = id && (id.signer || await Promise.resolve(hook('nostrLoginResume')).catch(() => null));
+ return signer ? (e) => signer.signEvent(e) : (e) => wallet.nostrSign(e);
+ }
+
// One-tap zap at the user's default amount: resolve, invoice, pay through
// the ark seam (its quote + retries included), and report by toast — the
// whole flow without a single screen.
@@ -203,7 +214,8 @@ export function zapsFeature(ctx) {
const profile = await wallet.nostrProfile(target.pk);
const lnTarget = zapTargetFromProfile(profile, target.pk);
if (!lnTarget) throw new Error(t('lnZapNoAddress'));
- const t2 = { ...lnTarget, eventId: target.eventId || null };
+ // a one-tap zap has no sheet to tick: never tied to a moment
+ const t2 = { ...lnTarget, eventId: target.eventId || null, moment: null };
const p = await fetchPayParams(t2.url);
const msat = sats * 1000;
if (msat < p.minSendable || msat > p.maxSendable) {
@@ -214,10 +226,11 @@ export function zapsFeature(ctx) {
}
let zapRequest = null;
if (p.allowsNostr && t2.pk && wallet.nostrSign) {
- zapRequest = buildZapRequest({
+ const sign = await zapSigner();
+ zapRequest = await buildZapRequest({
amountMsat: msat, relays: wallet.nostrRelays(), lnurlBech32: t2.lnurlBech32,
- recipientPk: t2.pk, eventId: t2.eventId || null, comment: '',
- signFn: (partial) => wallet.nostrSign(partial),
+ recipientPk: t2.pk, eventId: t2.eventId || null, moment: t2.moment, comment: '',
+ signFn: sign,
});
}
const invoice = await requestInvoice(p, { amountMsat: msat, zapRequest, lnurlBech32: t2.lnurlBech32 });
@@ -272,10 +285,11 @@ export function zapsFeature(ctx) {
let zapRequest = null;
const canZap = p.allowsNostr && z.target.pk && wallet.nostrSign;
if (canZap) {
- zapRequest = buildZapRequest({
+ const sign = await zapSigner();
+ zapRequest = await buildZapRequest({
amountMsat: msat, relays: wallet.nostrRelays(), lnurlBech32: z.target.lnurlBech32,
- recipientPk: z.target.pk, eventId: z.target.eventId || null, comment: z.comment,
- signFn: (partial) => wallet.nostrSign(partial),
+ recipientPk: z.target.pk, eventId: z.target.eventId || null, moment: z.momentOn ? z.target.moment : null, comment: z.comment,
+ signFn: sign,
});
}
const invoice = await requestInvoice(p, { amountMsat: msat, zapRequest, lnurlBech32: z.target.lnurlBech32, comment: z.comment });
@@ -310,7 +324,7 @@ export function zapsFeature(ctx) {
render();
}
const masterKey = () => {
- if (wallet.mnemonic) return HDKey.fromMasterSeed(mnemonicToSeedSync(wallet.mnemonic, wallet.passphrase || ''));
+ if (wallet.mnemonic) return HDKey.fromMasterSeed(seedSync(wallet.mnemonic, wallet.passphrase || ''));
if (wallet.xprv) return HDKey.fromExtendedKey(wallet.xprv);
return null;
};
@@ -475,7 +489,7 @@ export function zapsFeature(ctx) {
// what this payment needs (extra is one edit away).
const typedSats = parseAmount(z.amount, getUnit()) || 0;
const theirMaxSat = Math.floor(p.maxSendable / 1000);
- const boardable = !!hook('arkReady') && ours != null;
+ const boardable = !!hook('arkReady') && ours != null && !!hook('arkSavingsCanBoard');
const renewing = hook('spendingRenewingSat') || 0;
const waitingOnRenewal = renewing > 0 && broke && ours + renewing >= Math.max(min, p.fixedSat || typedSats);
const needsBoard = !waitingOnRenewal && boardable && (broke || (typedSats > 0 && typedSats > ours && typedSats <= theirMaxSat));
@@ -505,6 +519,8 @@ export function zapsFeature(ctx) {
maxlength: p.allowsNostr ? '280' : String(p.commentAllowed || 280),
onInput: (e) => { z.comment = e.target.value; } })
: null,
+ p.allowsNostr && z.target && z.target.moment ? h('div', { class: 'row' }, momentToggle(h, z.target.moment, !!z.momentOn, (on) => { z.momentOn = on; render(); },
+ t('mediaTieTo', { time: mediaClock(z.target.moment.seconds) }))) : null,
z.social ? h('div', { class: 'small faint' }, p.allowsNostr ? t('lnZapHintNostr') : t('lnZapHintPlain')) : null),
z.error ? h('div', { class: 'notice err' }, z.error) : null,
h('div', { class: 'row gap6' },
@@ -521,7 +537,15 @@ export function zapsFeature(ctx) {
// a login challenge needs no balance, only the wallet's key
const auth = parseLnurlAuth(text);
if (auth) { beginLogin(auth); return true; }
- if (!canPay() || !ui.send || ui.send.recipients.length !== 1) return false;
+ if (!ui.send || ui.send.recipients.length !== 1) return false;
+ // An LNURL may be a withdraw — it pays US, so it needs no spendable
+ // balance, and right after a refresh (Spending still connecting) the
+ // check below turned a scanned withdraw link into a "Zap LNURL…"
+ // recipient (Adam, 2026-11-08). Only the GET can tell: take it now,
+ // and a pay one meets the pay checks where it's paid.
+ const early = parseZapTarget(text);
+ if (early && early.kind === 'lnurl' && !typed) { begin(early, zapDisplay(early, text), true); return true; }
+ if (!canPay()) return false;
const tap = !typed; // scanned/pasted (a tap), not a keystroke
const nof = maybeNoffer(text);
if (nof) {
@@ -585,12 +609,12 @@ export function zapsFeature(ctx) {
// Ark's "no Ark address published" screen offers a Lightning fallback,
// which lands here with the recipient's pubkey (and, when the zap was
// aimed at a note, its event id for the zap request's e tag).
- lnZapNpub(pk, npub, eventId, autoSat) {
+ lnZapNpub(pk, npub, eventId, autoSat, moment) {
if (!canPay() || !wallet.nostrProfile) return false;
if (autoSat && hook('arkReady')) {
// the chip on the zapped note is pulsing since the tap — tell it how
// this went, either way
- autoZap({ kind: 'npub', pk, eventId: eventId || null }, autoSat)
+ autoZap({ kind: 'npub', pk, eventId: eventId || null, moment }, autoSat)
.then(() => hook('zapSettled', eventId, true, autoSat))
.catch((e) => { hook('zapSettled', eventId, false); toast('⚡ ' + (e.message || t('lnZapFailed')), 4000); });
return true;
@@ -599,7 +623,7 @@ export function zapsFeature(ctx) {
hook('zapSettled', eventId, false);
if (eventId) { toast('⚡ ' + t('lnZapFailed'), 4000); return true; }
}
- begin({ kind: 'npub', pk, eventId: eventId || null }, shortNpub(npub || npubOf(pk)));
+ begin({ kind: 'npub', pk, eventId: eventId || null, moment }, shortNpub(npub || npubOf(pk)));
return true;
},
resetSend() { ui.zap = null; ui.lnAuth = null; ui.lnWithdraw = null; },
diff --git a/src/feed-cache.js b/src/feed-cache.js
index a4f3ac9..cf3323e 100644
--- a/src/feed-cache.js
+++ b/src/feed-cache.js
@@ -54,6 +54,8 @@ export function createFeedCache(storage, prefix, now = Date.now) {
return value.notes;
} catch { return []; }
},
+ // a feed's posts as stored, without counting as a read
+ peekNotes(id) { const v = peek(id); return v && Array.isArray(v.notes) ? v.notes : null; },
save(id, notes) {
try { storage.setItem(keyOf(id), JSON.stringify({ at: now(), notes: compact(notes) })); sweep(keyOf(id)); } catch {}
},
diff --git a/src/hls-player.js b/src/hls-player.js
new file mode 100644
index 0000000..18292dd
--- /dev/null
+++ b/src/hls-player.js
@@ -0,0 +1,20 @@
+// HLS where the browser has none of its own (Firefox): hls.js feeds the
+// <video> through Media Source. Chrome and Safari play the playlist as a
+// plain src, so this file is fetched only when needed. The single-file
+// build replaces it with a stub (attachHls → null): no stream there.
+// A stream that's on (`live`) is held near its live edge: started 1.5 s
+// back, played up to 1.1× when it drifts past 5 s.
+export async function attachHls(video, src, { live = false } = {}) {
+ const { default: Hls } = await import('hls.js');
+ if (!Hls.isSupported()) return null;
+ const hls = new Hls({ lowLatencyMode: true, backBufferLength: 30,
+ ...(live ? { liveSyncDuration: 1.5, liveMaxLatencyDuration: 5, maxLiveSyncPlaybackRate: 1.1 } : {}) });
+ hls.loadSource(src);
+ hls.attachMedia(video);
+ hls.on(Hls.Events.ERROR, (_, d) => {
+ if (!d.fatal) return;
+ if (d.type === Hls.ErrorTypes.MEDIA_ERROR) { hls.recoverMediaError(); return; }
+ video.dispatchEvent(new Event('hlsfatal'));
+ });
+ return hls;
+}
diff --git a/src/i18n.js b/src/i18n.js
index ef56389..e3a1ad7 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -35,6 +35,10 @@ export const isRTL = (l) => RTL.has(l || lang);
const STR = {
en: {
+ mediaSeek: 'Seek',
+ mediaMomentDrop: 'About the whole post, not this moment',
+ mediaCommentAt: 'Comment at',
+ mediaTieTo: 'About {time} in the clip',
arkHistoryIncomplete: 'History incomplete',
arkDetailsNotSynced: 'Payment details not synced',
arkHistoryIncompleteHelp: 'These coins have been used, but the payment details and any remaining change have not synced to this device. Open the wallet that made the payments and let it sync.',
@@ -65,6 +69,20 @@ const STR = {
logoutAll: 'Log out of all accounts',
clearAllWarn: '⚠ This removes every account from this device. Any account whose recovery phrase or key you have not backed up will be lost for good.',
removeWalletTitle: 'Remove account',
+ delAcctTitle: 'Delete account',
+ delAcctBlurb: 'Give up your Coinos name, have our servers forget this account, and remove it from this device.',
+ delAcctChecking: 'Checking your account…',
+ delAcctName: '{name} is released. Anyone can claim it afterwards, and payments sent to it will no longer reach you.',
+ delAcctRecords: 'Our servers delete what they hold for this account: its payment address, notification registrations, scheduled posts, hats, point-of-sale and receipt records.',
+ delAcctDevice: '“{name}” is removed from this device.',
+ delAcctStays: 'Not deleted: your coins, which only your recovery phrase controls, and what you have published to nostr relays (profile, posts, messages).',
+ delAcctOwed: '⚠ {sat} sats are still on their way to you or held in your withdraw links. Wait for payments to arrive, take back your withdraw links (Send → Withdraw link), then try again.',
+ delAcctFunds: '⚠ This account still holds {sat} sats. Deleting does not move them. Send them somewhere first, or make sure you have the recovery phrase: without it they are lost for good.',
+ delAcctSure: 'I understand this cannot be undone.',
+ delAcctSureFunds: 'I have moved my funds or saved my recovery phrase, and I understand this cannot be undone.',
+ delAcctGo: 'Delete account',
+ delAcctDone: 'Account deleted',
+ delAcctUnlockFirst: 'Lock Coinos and unlock it with your password first, then try again',
removeWalletWarn: '⚠ Remove “{name}” from this device? It will be gone from this browser. Make sure you have its recovery phrase. Other accounts aren’t affected.',
rename: 'Rename',
remove: 'Remove',
@@ -106,6 +124,17 @@ const STR = {
profDisplayName: 'Display name',
profPublicKey: 'Nostr public key',
profKeyLink: 'Public key',
+ profHistDesc: 'If another app replaced your profile, an older copy may still be on a relay that keeps history. Using one fills only the fields that are empty here.',
+ profHistLook: 'Look for older copies',
+ profHistUse: 'Use',
+ profHistNoName: '(no name)',
+ profHistNone: 'No older copy has anything this one is missing.',
+ profHistNothing: 'Everything in that copy is already here.',
+ profHistFilled: 'Filled {n} fields from the older copy. Save to publish.',
+ profHist_name: 'name',
+ profHist_about: 'bio',
+ profHist_picture: 'picture',
+ profHist_banner: 'banner',
followHistTitle: 'Follow list',
followHistDesc: 'You follow {n} people. If another app replaced your follow list, an older copy may still be on a relay that keeps history. Restoring adds everyone from it back; nobody is removed.',
followHistLook: 'Look for older copies',
@@ -183,6 +212,19 @@ const STR = {
skipVerification: 'Skip verification',
confirmBackupIntro: 'Confirm your backup by entering the requested words.',
wordN: 'Word #{n}',
+ seedIntroBody: 'Next you’ll see your seed phrase: {n} words that are your wallet. Write them down on paper, in order, and keep them somewhere safe. They’re the only way to get your coins back if you lose this device.',
+ seedIntroPrivate: 'Anyone who sees them can take your coins, so make sure no one is looking at your screen.',
+ seedIntroShow: 'Show seed phrase',
+ next: 'Next',
+ passStepTitle: 'Add a passphrase?',
+ passStepBody: 'A passphrase is an extra secret you choose yourself, on top of your {n} words. Anyone who finds your seed phrase still can’t open your wallet without it.',
+ passStepNote: 'It’s optional, but recommended. Write it down with your seed phrase: you’ll need both to recover your wallet, exactly as written, and nobody can reset it for you.',
+ passStepNone: 'Continue without one',
+ skip: 'Skip',
+ quizPrompt: 'Which one is word #{n}?',
+ quizWrong: 'Not that one. Check what you wrote down.',
+ quizBack: 'Show the words again',
+ onbBackupShow: 'Show seed phrase',
reenterPassphrase: 'Re-enter passphrase',
back: '← Back',
cancel: 'Cancel',
@@ -194,12 +236,15 @@ const STR = {
seedPlaceholder: 'enter your seed words separated by spaces',
passphrase: 'Passphrase',
passWhatsThis: 'What’s this?',
+ addPassphrase: 'Add passphrase',
+ passphraseOptional: 'Passphrase (optional)',
+ passOptionalHint: 'Leave it empty unless you want one. Most wallets have none.',
passInfo: 'An optional 13th word: if someone gets hold of your 12 seed words, they still can’t open your wallet without this one. It’s not a login password and it doesn’t encrypt anything: each passphrase opens its own separate wallet, so to recover your funds you’ll need your seed words and this passphrase, exactly as written.',
show: 'Show',
hide: 'Hide',
invalidSeed: 'Invalid seed phrase. Check the spelling and word order.',
- importLabel: 'Recovery phrase or key',
- importPlaceholder: 'Your seed words, or an xpub / xprv',
+ importLabel: 'Seed phrase',
+ importPlaceholder: 'Your seed words',
invalidImport: 'That is not a valid recovery phrase, xpub, or xprv.',
importedKey: 'Imported key',
importedKeyNote: 'This wallet was imported from an extended private key, so there is no recovery phrase. Back up that key itself to keep the wallet.',
@@ -224,6 +269,9 @@ const STR = {
moveToSavingDesc: 'Park money in ordinary on-chain Bitcoin.',
moveToSavingBtn: 'Move to Savings',
spendingLabel: 'Spending',
+ historyExportTitle: 'Transaction history',
+ historyExportDesc: 'Download every payment in Spending and Savings as a CSV file, for a spreadsheet or your accountant.',
+ historyExportBtn: 'Export CSV',
savingLabel: 'Savings',
balanceSwitch: 'Switch to {name}',
movingLabel: 'Moving…',
@@ -249,6 +297,7 @@ const STR = {
msgUploadFailed: 'Upload failed. Check your connection and try again',
mediaUploadTooBig: 'That file is too big for the available media hosts',
mediaUploadUnsupported: 'That file format is not supported',
+ mediaUploadUnauthorized: 'The media server denied this upload. Check that your Nostr identity is allowed to upload there.',
msgPhoto: 'Photo',
searchPeopleFor: 'Search people for {q}',
msgEmojiSearch: 'Search emoji…',
@@ -275,6 +324,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",
@@ -283,6 +334,7 @@ const STR = {
pagerPrevPic: 'Previous picture',
pagerNextPic: 'Next picture',
videoNoPicture: "This browser can’t show this video’s picture",
+ videoGone: "This video couldn’t be loaded from its host",
videoOpenFile: "Open the file",
wnDevicesTitle: 'Group invitations',
wnDevicesHelp: 'White Noise and other Marmot apps invite one of your devices, and only that device gets the group. Keep the invitations coming to the device you actually use.',
@@ -300,6 +352,10 @@ const STR = {
videoLargeHelp: "Videos over {mb} MB or above 1080p wait for a tap, so the feed doesn’t eat your data. The limit is lower on a slow or data-saving connection.",
videoMute: 'Mute',
openInYouTube: 'Open on YouTube',
+ openOnPaff: 'Open on PAFF',
+ musicClose: 'Stop and close',
+ musicSong: 'Song on PAFF',
+ musicPlayingBelow: 'Playing below',
accountsThisOne: 'signed in',
worthThen: 'Worth then',
worthNow: 'Worth now',
@@ -308,6 +364,7 @@ const STR = {
feedTitle: 'Feed',
feedFollowingName: 'Following',
noteReplyingTo: 'Replying to',
+ noteCommentOn: 'Comment on {where}',
feedNew: 'New feed',
feedNewName: 'New feed',
feedEdit: 'Edit feed',
@@ -348,10 +405,12 @@ const STR = {
mediaConversations: "Conversations",
mediaImages: "Images",
mediaVideos: "Videos",
+ mediaLive: "Live",
mediaArticles: "Articles",
mediaNoArticles: "No articles in this feed yet.",
mediaNoImages: "No pictures in this feed yet.",
mediaNoVideos: "No vertical videos in this feed yet.",
+ mediaNoLive: "Nobody in this feed is live right now.",
feedRelays: 'Relays',
feedRelaysFormHelp: 'Read this feed from these relays only. Leave empty for the usual ones.',
feedAllToggle: 'Every post on these relays (a firehose)',
@@ -429,12 +488,20 @@ const STR = {
listNew: 'New list…',
profLists: 'Lists',
searchTopicRow: 'Posts on this topic',
+ searchPostsRow: 'Posts and replies that say this',
+ searchPostsRowAll: 'Everywhere: posts and replies that say this',
+ searchInPosts: "in {name}'s posts",
+ searchScopedHint: 'Search their posts, or anyone…',
+ searchScopeRemove: 'Search everywhere',
searchTopicFor: 'Posts tagged #{q}',
+ relayLinkOpen: 'See what’s posted on this relay',
alertsTitle: 'Notifications',
alertsSub: 'Zaps, reactions and replies to your posts',
alertsNew: '{n} new',
alertsEmpty: 'Nothing yet. Zaps, reactions and replies to your posts will show up here.',
alertZap: 'zapped you {sats}',
+ alertZapApp: 'zapped your app {name} {sats}',
+ alertZapAppAnon: 'zapped your app {sats}',
alertReact: 'reacted {emoji}',
alertBoost: 'boosted your post',
alertReply: 'replied to you',
@@ -452,7 +519,120 @@ const STR = {
feedFindPeople: 'Find people',
feedEmpty: 'Nothing posted yet.',
feedLoadingMore: 'Loading more posts…',
+ profNotesLoading: 'Loading posts…',
feedEnd: 'You’re all caught up.',
+ liveBadge: 'LIVE',
+ livePlanned: 'SOON',
+ liveEnded: 'ENDED',
+ livePast: 'Past streams',
+ liveReport: 'Report this stream',
+ liveReportTitle: 'Report this stream',
+ liveReportDesc: 'coinos carries this stream. Tell us what’s wrong and we’ll look at it right away.',
+ liveReason_csam: 'Sexual content involving a minor',
+ liveReason_sexual: 'Sexual content',
+ liveReason_violence: 'Violence or gore',
+ liveReason_illegal: 'Something else illegal',
+ liveReason_spam: 'Spam or a scam',
+ liveReason_other: 'Something else',
+ liveReportTextPh: 'Anything we should know (optional)',
+ liveReportSend: 'Send report',
+ liveReported: 'Reported. Thank you.',
+ liveTakeDown: 'Take down',
+ liveTakeDownAsk: 'Take this stream down? It ends now, and its recording is kept from everyone (preserved for reporting).',
+ liveBanAsk: 'Also stop this account from streaming again?',
+ liveTakenDown: 'Taken down.',
+ liveTakenDownBanned: 'Taken down, and the account can’t stream again.',
+ liveRemoved: 'This stream was taken down.',
+ liveDelete: 'Delete recording',
+ liveDeleteAsk: 'Delete this stream’s recording? Nobody will be able to watch it again.',
+ liveDeleted: 'Recording deleted.',
+ liveDeletedSay: 'The streamer deleted this recording.',
+ goLiveNewName: 'Your name can go live a day after you claimed it: from {when}.',
+ goLiveBanned: 'This account can’t go live on coinos.',
+ liveWatchRecording: 'Watch the recording',
+ liveStaleMine: '“{title}” still says live, but nothing is going out.',
+ liveNotYours: 'Only the account that started this stream can end it.',
+ liveRecordingBadge: 'RECORDING',
+ liveUntitled: 'Live stream',
+ liveWatching: '{n} watching',
+ liveWatch: 'Watch',
+ liveZap: 'Zap',
+ liveChat: 'Chat',
+ liveChatEmpty: 'No messages yet.',
+ liveChatHint: 'Say something',
+ liveSend: 'Send',
+ liveZapped: 'zapped {n} sats',
+ liveSomeone: 'Someone',
+ liveOffline: 'The stream isn’t playing right now.',
+ liveNoPlayer: 'This browser can’t play the stream.',
+ liveOver: 'This stream has ended.',
+ liveStartsAt: 'Starts {when}',
+ liveNotFound: 'Couldn’t find that stream.',
+ goLive: 'Go live',
+ goLiveCamera: 'Camera',
+ goLiveScreen: 'Screen',
+ goLiveFlip: 'Flip',
+ goLiveTitlePh: 'What’s your stream about?',
+ goLiveDefaultTitle: '{name} is live',
+ goLiveStart: 'Go live',
+ goLiveStarting: 'Starting…',
+ goLiveAsking: 'Asking for the camera…',
+ goLiveNoCamera: 'The camera isn’t available. Check that the browser may use it.',
+ goLiveNoScreen: 'Screen sharing was cancelled or isn’t available.',
+ goLiveNeedsName: 'Going live needs a coinos name: claim one in Settings first.',
+ goLiveRefused: 'The live server didn’t take the stream.',
+ goLiveHint: 'Your stream is public: anyone can watch it and its recording, kept for a week. Keep this page open while you’re live.',
+ goLiveEnd: 'End',
+ goLiveEndAsk: 'End your stream?',
+ goLiveEnded: 'Your stream has ended.',
+ goLiveReconnecting: 'Reconnecting…',
+ goLiveBehind: 'Your connection is falling behind',
+ goLiveLost: 'Lost the connection to the live server.',
+ goLiveRestarted: 'The stream had to start over.',
+ callVoice: 'Voice call',
+ callVideo: 'Video call',
+ callIncomingVoice: 'Voice call',
+ callIncomingVideo: 'Video call',
+ callIncomingFrom: '{name} is calling',
+ callCalling: 'Calling…',
+ callConnecting: 'Connecting…',
+ callAccept: 'Answer',
+ callDecline: 'Decline',
+ callHangUp: 'Hang up',
+ callMute: 'Mute',
+ callUnmute: 'Unmute',
+ callCamOff: 'Turn camera off',
+ callCamOn: 'Turn camera on',
+ goLiveToCamera: 'Back to camera',
+ callShare: 'Share screen',
+ callStopShare: 'Stop sharing',
+ callAddVideo: 'Turn on camera',
+ callFlip: 'Switch camera',
+ callMinimize: 'Minimize',
+ callEnded: 'Call ended',
+ callNoAnswer: 'No answer',
+ callDeclined: 'Declined',
+ callBusy: 'They’re on another call',
+ callFailed: 'Couldn’t connect',
+ callNoPermission: 'The microphone or camera isn’t allowed',
+ callMissed: 'Missed call',
+ callAnsweredElsewhere: 'Answered on another device',
+ callDeclinedElsewhere: 'Declined on another device',
+ callUnsupported: 'This browser can’t make calls.',
+ notifCall: 'Calls',
+ callLogVoice: 'voice call',
+ callLogVideo: 'video call',
+ callLogOut: 'Outgoing {what}',
+ callLogIn: 'Incoming {what}',
+ callLogMissed: 'Missed {what}',
+ callLogDeclined: 'Declined {what}',
+ callLogTheyDeclined: 'Outgoing {what} · Declined',
+ callLogNoAnswer: 'Outgoing {what} · No answer',
+ callLogCancelled: 'Cancelled {what}',
+ callLogBusy: 'Outgoing {what} · Busy',
+ callLogFailed: '{what} · Couldn’t connect',
+ callLogUnrung: 'This didn’t ring: calls ring from people you follow or have written to.',
+ callLogUnrungWas: 'This didn’t ring: you didn’t follow them then.',
feedAttach: 'Attach a picture or video',
postLike: 'Like',
postBoost: 'Boost',
@@ -544,12 +724,26 @@ const STR = {
profComposePh: "What's on your mind?",
profPostBtn: 'Post',
profPosted: 'Posted',
+ schedToggle: 'Schedule for later',
+ schedAt: 'Post at',
+ schedBtn: 'Schedule',
+ schedDone: 'Scheduled for {when}',
+ schedTooSoon: 'Pick a time at least two minutes from now',
+ schedListTitle: 'Scheduled ({n})',
+ schedCancelled: 'Scheduled post cancelled',
publicChatTitle: '{name} community',
publicChatDesc: 'Live chat: read along, sign in to join the conversation',
publicChatSignIn: 'Sign in to chat',
- publicChatOpenApp: 'Open coinos',
+ publicChatDescMember: 'Live chat: open the chat in Coinos to join the conversation',
+ publicChatOpenApp: 'Join the chat',
publicChatLoading: 'Loading messages…',
msgDelete: 'Delete message',
+ msgBan: 'Remove {name} and their messages',
+ msgBanConfirm: 'Remove {name} for everyone? Tap again',
+ msgBanned: '{name} removed',
+ msgUnbanned: '{name} restored',
+ msgBannedHead: 'Removed from this community',
+ msgUnban: 'Restore',
msgNoIdentity: "Your nostr signer isn't connected. Reconnect it to send as yourself",
msgSendFailed: 'No relay accepted the message',
msgLockedChat: 'Your wallet is locked, so it can’t sign messages.',
@@ -563,8 +757,8 @@ const STR = {
addrRead: '{min} min read',
addrList: 'A list by {name}',
msgSignerOff: "Your nostr signer isn't connected, so you can't post as yourself yet.",
- msgAmberDms: 'Signed in with Amber, messages sent to you can’t be opened here, only ones you sent from this device.',
- msgAmberConnect: 'Connect Amber',
+ msgAmberDms: 'Signed in with a signer app, messages sent to you can’t be opened here, only ones you sent from this device.',
+ msgAmberConnect: 'Connect signer',
postRepostedBy: '{name} reposted',
gifBtnTitle: 'Add a GIF',
gifSearchPh: 'Search GIFs',
@@ -606,6 +800,15 @@ const STR = {
msgGroupProtoWn: 'Marmot (MLS)',
msgGroupProtoCd: 'Cordn',
msgGroupProtoCdHint: 'Cordn groups work with Amethyst and the Cordn app; messages travel through a coordinator server that cannot read them.',
+ msgGroupProtoN29: 'Relay group',
+ msgGroupProtoN29Hint: 'Join a NIP-29 group made in Chachi, Flotilla, 0xchat or another client: paste its address (relay\'id) or a link to it. Relay groups are not encrypted; the relay keeps the members and can read the messages.',
+ msgNip29Address: 'relay.example.com\'groupid or a link',
+ msgNip29BadAddress: 'That isn\'t a group address. It looks like relay.example.com\'groupid',
+ msgNip29JoinRefused: 'The relay didn\'t let you in yet ({why}). You can still read the group if it\'s open.',
+ msgNip29Info: 'Relay group {relay} · not encrypted · the relay keeps the members',
+ msgNip29CopyAddress: 'Copy group address',
+ msgNip29Unreachable: "{host} isn't answering",
+ msgNip29Waiting: 'On {host}',
msgCordnInfo: 'Cordn group · end-to-end encrypted · delivered by a coordinator',
msgCordnNoFiles: 'Attachments are not available in Cordn groups yet',
msgRouteTitle: 'Send messages by',
@@ -655,6 +858,31 @@ const STR = {
arkFeeChain: 'On-chain fee',
arkFeeService: 'Service fee',
arkCoinsExpired: 'expired',
+ arkCoinsHeld: 'held by Coinos',
+ arkCoopSelected: 'Only the {n} coins ticked above will move.',
+ arkCoopSelectedOne: 'Only the coin ticked above will move.',
+ arkCoopSelectedAmt: '{n} selected coins · {amount}',
+ arkCoopSelectedAmtOne: '1 selected coin · {amount}',
+ arkCustodyTitle: 'Custody strategy',
+ safeBootTitle: 'Coinos opened in safe mode',
+ safeBootBody: 'The app was closed {n} times in a row before it finished opening, so automatic connections are paused this time. Your coins and keys are untouched. Last step reached: {phase}.',
+ safeBootOpen: 'Open normally',
+ safeBootCopy: 'Copy report',
+ safeBootCopied: 'Copied',
+ arkCustodyDesc: 'Each coin expires about {days} days after it was made. Until then you can bring it on-chain yourself, without Coinos; after that, Coinos keeps honoring it. Renewing before expiry keeps your own exit, for a fee, so it is a choice:',
+ arkCustodyCustodial: 'Allow coins to expire',
+ arkCustodyCustodialDesc: 'Nothing renews and no renewal fees are paid. A coin keeps its own exit until it expires. After that, paying still works, but bringing it on-chain needs Coinos’s cooperation. The one exception: a coin whose payment history has grown very long is renewed free of the base fee, so it stays spendable.',
+ arkCustodySelf: 'Minimize renewal cost',
+ arkCustodySelfDesc: 'Coins renew in the last hours before they expire, when renewal is cheapest, so you can always exit on your own without Coinos. Roughly once every {days} days per coin. Coins too small to be worth the fee are left alone.',
+ arkCustodyExit: 'Minimize exit cost',
+ arkCustodyExitDesc: 'Every transfer adds a hop to a coin’s history, and a unilateral exit pays one on-chain transaction per hop. This renews a coin before it expires, and also as soon as its history is {hops} hops deep, so bringing any coin on-chain stays close to a fresh coin’s price. Only for coins worth it: never more than a tenth of a coin on its renewal.',
+ arkCustodyCostNone: 'no fees',
+ arkCustodyCostSelf: '{base} per renewal',
+ arkCustodyCostExit: '{base} near expiry, {pct} + {base} when early',
+ arkCustodySaved: 'Custody choice saved',
+ arkCustodyNotHere: 'This server does not honor expired coins, so they renew automatically here.',
+ arkExitNoneExitable: 'Every coin has expired, so there is nothing a unilateral exit can take on-chain: Coinos holds them now. Renewing restores your own exit; withdrawing with Coinos’s cooperation works as before.',
+ arkCoinsRenewDescCustodial: 'With “Allow coins to expire”, nothing renews on its own. A renewal replaces the selected coins with a single fresh one and restores your own exit for them. Every renewal costs a flat {base} toward its on-chain fee, plus a share that depends on how close each coin is to expiry. The closer, the cheaper:',
noteForeignKind: 'A kind {kind} event this app doesn’t show.',
zapRowText: 'zapped {n} sats',
pollVoter: '{n} vote',
@@ -678,8 +906,10 @@ const STR = {
arkRenewStageRetry: 'The last check with the server didn’t go through; the wallet keeps trying.',
arkRenewingHistory: 'Renewing',
arkRenewingOpen: 'See the coins',
- arkCoinsExitTitle: 'Unilateral exit',
- arkCoinsCoopTitle: 'Co-operative exit',
+ arkCoinsExitTitle: 'Exit',
+ arkCoinsCoopTitle: 'Withdraw',
+ arkCoinsWithdrawBtn: 'Withdraw {amount}',
+ arkCoinsExitBtnAmt: 'Exit {amount}',
arkOffboardBadAddress: 'Enter a valid on-chain address for this network.',
arkCoinsExitBtn: 'Exit now',
arkExitConfirmTitle: 'Start a unilateral exit?',
@@ -772,6 +1002,7 @@ const STR = {
profNotesNone: 'No recent posts found.',
profTabPosts: 'Posts',
profTabReplies: 'Replies',
+ profTabStreams: 'Streams',
profRepliesNone: 'No recent replies found.',
profReplyTag: 'reply',
msgSearching: 'Searching…',
@@ -792,6 +1023,12 @@ const STR = {
msgBadInvite: 'Not a valid invite link',
msgInviteLoading: 'Fetching invite…',
msgInviteNotFound: 'Invite not found on its relays',
+ mediaServersTitle: 'Media servers',
+ mediaServersHow: 'Blossom servers for chat attachments and post media, including videos. Enter up to 6 HTTPS server addresses, one per line. Custom servers replace the public upload defaults. Saved on this device; existing uploads stay where they are.',
+ mediaServersDefault: 'Using public media servers',
+ mediaServersSaved: 'Media servers saved',
+ mediaServersInvalid: 'Enter 1–6 HTTPS server addresses without paths, credentials, queries or fragments.',
+ mediaServersSaveFailed: 'Could not save media servers on this device.',
syncStorageTitle: 'Sync storage',
syncStorageHow: 'Wallet state too large for a relay event is encrypted and stored as a blob on these Blossom servers (one per line). Any Blossom server works. Run your own or use another provider.',
syncStorageSave: 'Save servers',
@@ -901,6 +1138,10 @@ const STR = {
giftWelcome: 'You’ve been sent Bitcoin',
giftBackedUp: 'I’ve written it down',
giftLink: 'Gift some Bitcoin',
+ giftNotePlaceholder: 'Add a note (optional)',
+ giftFromMe: 'Show it’s from me (whoever claims it follows you)',
+ giftFrom: 'From',
+ giftClaimFollows: 'Claiming it follows them',
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',
@@ -964,6 +1205,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.',
@@ -994,6 +1236,9 @@ const STR = {
explorerUrlHint: 'Esplora / electrs REST base, e.g. https://mempool.space/api',
walletName: 'Account name',
walletSettings: 'Account settings',
+ balanceSettingsTitle: 'Balance settings',
+ spendingSettingsDesc: 'Coins, renewals, who holds them, moving them out',
+ savingsSettingsDesc: 'Lock, password, recovery phrase, public key',
securityTitle: 'Security',
walletSettingsDesc: 'Name, recovery phrase, public key, and auto-logout for this account.',
autolockTitle: 'Log out automatically',
@@ -1052,7 +1297,10 @@ const STR = {
arkRenewForecast: 'Coins renew in ~{when} for {fee}.',
arkRenewForecastNow: 'Coins renew shortly for {fee}.',
arkBoardStuck: 'Moving money hit a snag and will keep retrying: {error}',
- arkRenewWarnPush: 'Your Spending balance is too small to renew itself and expires around {date}. Receive any amount or spend it to keep it alive.',
+ // the push's words are measured against Chrome's spam model (src/notify-text.js):
+ // 'too small to renew itself and expires around' scored 98, this 11
+ arkRenewWarnTitle: 'Spending balance',
+ arkRenewWarnPush: 'Receive or spend sats before {date} to keep it alive.',
giftArkOutstanding: '{n} unclaimed instant gift(s)',
giftArkRevoked: 'Gift swept back into Spending.',
claimArkFree: 'instant, no fee',
@@ -1173,6 +1421,8 @@ const STR = {
arkLnFromSavingsShort: 'Spending can’t cover this one. Move funds over from Savings first. That takes an on-chain confirmation, so ask for a fresh invoice afterwards.',
arkLnUseSpending: 'Switch to Spending and continue',
arkLnMoveFirst: 'Move Savings into Spending first',
+ arkLnSavingsTooSmall: 'Savings holds {have}, and a move into Spending needs at least {min} plus the on-chain fee. Receive over Lightning to fund Spending directly, or add to Savings first.',
+ arkLnReceiveInstead: 'Receive over Lightning instead',
arkLnFee: 'Fee',
arkLnPaying: 'Paying invoice…',
arkLnRetrying: 'Route failed. Retrying with a bigger fee budget ({n}/{of})…',
@@ -1213,6 +1463,13 @@ const STR = {
backupReminder: 'Your recovery phrase is still unwritten.',
backupReminderGo: 'Write it down',
onbSeedTitle: 'Set up your wallet',
+ onbRestoreTitle: 'Enter seed phrase',
+ onbRestoreDoor: 'Seed phrase',
+ doorPasskey: 'Passkey',
+ doorGoogle: 'Google',
+ doorNostr: 'Nostr',
+ addAccountTitle: 'Add an account',
+ onbSignInExisting: 'Sign in to an existing account',
onbSigninTitle: 'Sign in',
onbLegacyTitle: 'Move your coinos.io account',
onbLegacyBody: 'The original coinos. We can move your balance over and point your username here. Your old account keeps working, it just stops receiving payments.',
@@ -1230,6 +1487,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',
@@ -1243,6 +1502,31 @@ const STR = {
onbContinue: 'Continue',
onbSkipAvatar: 'Continue',
onbDoneTitle: "You're all set!",
+ onbCreateAccount: 'Create an account',
+ onbNameTitle: 'Claim your name',
+ onbNameBody: "It's your username and your payment address: people pay you, follow you and message you with just your name.",
+ waysBackReminder: 'Add a way back into your account, in case you lose this device.',
+ waysBackPrompt: 'You have bitcoin in here now. Add a way back into your account, in case you lose this device.',
+ waysBackReminderGo: 'Add one',
+ addSavings: 'Add a savings account',
+ addSavingsDesc: 'On-chain bitcoin, for keeping. Same account, a second balance.',
+ savingsAddedToast: 'Savings added',
+ waysBackTitle: 'Ways back in',
+ waysBackDesc: 'Any one of these opens this account on a new device, or if this one is lost.',
+ waysBackNote: 'Each one can open your account and spend its money, so only add ones you control.',
+ waysBackOn: 'Set up',
+ waysBackLogin: 'Signed in with {via}',
+ waysBackAddedOn: 'Added {date}',
+ waysBackPhraseSeen: 'Seen. Keep it written down somewhere safe',
+ waysBackPhraseUnseen: 'Twelve words that open this account in any wallet',
+ waysBackShow: 'Show',
+ waysBackAddPasskey: 'Passkey auth',
+ waysBackAddGoogle: 'Google auth',
+ waysBackAddNostr: 'Nostr auth',
+ waysBackPaper: 'Pen and paper',
+ waysBackAdded: 'Added. You can sign in with it now',
+ waysBackIsLogin: 'That is the account you signed in with; it already opens this one.',
+ waysBackTaken: 'That sign-in already opens a different coinos account, so it can’t open this one too.',
onbDoneBody: 'Your spending account is set up. Your address is live and the coinos community chat is waiting for you.',
onbEnter: 'Enter coinos',
spendSetup: 'Set up a spending account',
@@ -1253,8 +1537,10 @@ const STR = {
nlSignInNostr: 'Sign in with Nostr',
nlDesc: 'Use your Nostr account to open your wallet, on any device, with the same account.',
nlExtension: 'Use browser extension',
- nlAmber: 'Sign in with Amber (Android)',
+ nlAmber: 'Sign in with a signer app (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',
@@ -1263,7 +1549,7 @@ const STR = {
nlPasskey: 'Sign in with a passkey',
nlKeyOrBunker: 'nsec, private key, or bunker://…',
nlGo: 'Log in',
- nlHint: 'Works with Amber, Amethyst and other remote signers (paste their bunker:// address), or a browser extension. A pasted key is used once and never stored.',
+ nlHint: 'Works with remote signer apps (paste their bunker:// address) or a browser extension. A pasted key is used once and never stored.',
nlApprove: 'Approve the request in your signer →',
nlUnrecognized: 'That doesn’t look like a private key or a bunker:// address.',
nlNewTitle: 'Create a wallet for this account',
@@ -1284,7 +1570,7 @@ const STR = {
nlReconnectDesc: "Your signer isn't connected, so this app can't sign as you. Reconnect it to post and update your profile. Your wallet and balance aren't affected.",
nlReconnectTitle: 'Reconnect your signer',
nlAmberUpgradeTitle: 'Read your messages',
- nlAmberUpgradeBody: 'Amber can only open messages here when it’s connected as a remote signer. Tap below, approve in Amber (allow decrypting), and your messages will load. Signing works as before.',
+ nlAmberUpgradeBody: 'Your signer app can only open messages here when it’s connected as a remote signer. Tap below, approve in the signer app (allow decrypting), and your messages will load. Signing works as before.',
nlReconnectBody: 'Your Nostr signer isn’t connected on this device. Reconnect to keep acting as {npub}…',
nlWrongAccount: 'That signer is a different Nostr account. Reconnect with {npub}.',
nlLinked: 'Wallet linked to your Nostr account',
@@ -1316,6 +1602,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)',
@@ -1326,12 +1613,18 @@ const STR = {
namesMoreArkHow: 'Get paid directly from any Ark wallet',
namesMoreClink: 'Nostr offer (CLINK)',
namesMoreClinkHow: 'A static code Nostr wallets can pay',
+ namesMorePage: 'Payment page',
+ namesMorePageHow: 'A link for your website: anyone can pay you over Lightning',
+ namesPageHow: 'Put this link behind a "Donate" or "Pay in Bitcoin" button. Whoever opens it can pay you over Lightning from any wallet, no account needed. Add ?amount=5000 to the link to fill in an amount.',
+ namesPageOpen: 'Open page',
namesMoreOnchain: 'Bitcoin address (on-chain)',
namesMoreOnchainHow: 'Switch to Savings for a regular on-chain address',
namesInvAmountPh: 'Amount (sats)',
namesInvMemoPh: 'Description (optional)',
namesInvCreate: 'Create invoice',
namesInvNew: 'New invoice',
+ namesInvKeepOpen: 'Keep coinos open until this is paid. If it\u2019s paid while coinos is closed, the money goes back to the sender. It expires in an hour.',
+ namesInvExpired: 'This invoice has expired. Make a new one when you\u2019re ready to be paid.',
namesInvBadAmount: 'Enter an amount in sats',
namesOfferMemoPh: 'Label (e.g. Ocean payout)',
namesOfferCreate: 'Create',
@@ -1392,6 +1685,28 @@ const STR = {
settingsNostrDesc: 'Identity and connections',
settingsNotifDesc: 'What buzzes this device',
settingsAdvancedDesc: 'Network, rarities, rescues',
+ aboutTitle: 'About',
+ recvAmount: 'Amount',
+ recvOnchain: 'Bitcoin address',
+ recvPaymentAddress: 'Payment address',
+ recvOnchainNote: 'For a payment on-chain, from an exchange or another wallet. It stays on-chain until you spend it.',
+ receiveOfflineOnchain: "You're offline. This on-chain address still takes payments.",
+ balInstant: 'Ark',
+ balOnchain: 'On-chain',
+ balGifts: 'Gifts',
+ showBreakdown: 'Breakdown',
+ hideBreakdown: 'Hide breakdown',
+ topUpInstant: 'Make on-chain bitcoin instant',
+ allSettingsDesc: 'Coins, renewals, lock, recovery phrase, public key',
+ separateBalances: 'Show Spending and Savings separately',
+ movedInstant: 'Made instant',
+ movingInstant: 'Making instant',
+ movedOnchain: 'Moved on-chain',
+ recvAmountTitle: 'Request an amount',
+ recvAmountNote: 'What it’s for (optional)',
+ recvAmountGo: 'Create invoice',
+ recvAmountDone: 'Done',
+ settingsAboutDesc: 'How it works, support, app, theme',
settingsPosDesc: 'Till mode, tips and the /pos link',
unlockForLabel: 'Stay unlocked',
unlockFor5m: '5 minutes',
@@ -1437,6 +1752,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.',
@@ -1522,6 +1840,39 @@ const STR = {
lnWithdrawPaid: 'Received {amount}',
lnWithdrawNotPaid: 'They took the invoice but the payment didn’t arrive. Check with them before trying again.',
lnWithdrawNoInvoice: 'Couldn’t make an invoice to be paid to.',
+ wlTitle: 'Withdraw link',
+ wlReady: 'Your withdraw link is ready',
+ wlDesc: 'A Lightning link or QR code that anyone can withdraw sats from, like a voucher. It works with most Lightning wallets, even while your phone is off. You pay for it up front; Coinos holds the sats until they’re claimed, and you can take back whatever is left at any time.',
+ wlAmount: 'Amount per withdrawal',
+ wlUses: 'How many withdrawals',
+ wlNote: 'Description (optional)',
+ wlPayNow: 'Paid now from Spending.',
+ wlPayNowMany: '{total} paid now from Spending: {n} withdrawals of up to {amount}.',
+ wlCreate: 'Create withdraw link',
+ wlCreateFor: 'Create link for {amount}',
+ wlAmountInvalid: 'Enter an amount.',
+ wlUsesInvalid: 'Between 1 and 1000 withdrawals.',
+ wlNoFunds: 'Not enough in Spending for {amount}.',
+ wlNotConfirmed: 'Paid, but the link isn’t confirmed yet. It will appear under your links in a moment.',
+ wlTermsOne: 'Up to {amount}, once',
+ wlTermsMany: 'Up to {amount} each, {n} of {total} withdrawals left',
+ wlLeft: '{amount} left',
+ wlCopy: 'Copy LNURL',
+ wlBearer: 'Anyone with this link or QR code can withdraw from it. Share it only with whoever it’s for.',
+ wlTakeBack: 'Take back {amount}',
+ wlTakeBackMemo: 'Withdraw link taken back',
+ wlTakenBack: '{amount} is back in Spending',
+ wlTakeBackFailed: 'Couldn’t pay it back just now. The link stays open; try again in a moment.',
+ wlClosed: 'This link is closed.',
+ wlUsedUp: 'This link has been used up.',
+ wlClaimPaying: 'A claim of {amount} is on its way to the wallet that asked.',
+ wlClaimRetrying: "A claim of {amount} couldn't find a Lightning route yet. Still trying for a few minutes.",
+ wlClaimFailed: "A claim of {amount} couldn't be delivered: there was no Lightning route to the wallet that asked. Nothing was sent and the sats are still in this link. Claim it again, maybe for less or from another wallet, or take them back.",
+ wlClaimFailedTag: 'claim failed · {amount} left',
+ wlClosedTag: 'closed',
+ wlUsedUpTag: 'used up',
+ wlYours: 'Your withdraw links',
+ wlMainnetOnly: 'Withdraw links are only available on mainnet.',
lnWithdrawWatchOnly: 'This device can’t receive: the wallet is watch-only here.',
lnWithdrawMemo: 'Withdrawal from {domain}',
lnPayAmount: 'Amount',
diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js
index ffac4b9..80e6915 100644
--- a/src/image-thumbnails.js
+++ b/src/image-thumbnails.js
@@ -14,16 +14,21 @@ function thumbnailWorker() {
const result = { width: bitmap.width, height: bitmap.height, media: null, tile: null };
// GIFs must keep animating; a canvas copy would freeze their first frame.
if (!/gif/i.test(blob.type)) {
+ // The grid's tile: the picture in its own shape (justified rows),
+ // tileSize tall, its middle cut to between 1:2 and 2:1 — the most a
+ // tile stretches either way.
if (tileSize) {
- const side = Math.min(bitmap.width, bitmap.height), px = Math.min(tileSize, side);
- let square;
+ const W = bitmap.width, H = bitmap.height;
+ const cw = Math.min(W, H * 2), ch = Math.min(H, W * 2);
+ const th = Math.min(tileSize, ch), tw = Math.max(1, Math.round(th * cw / ch));
+ let cut;
try {
- square = await createImageBitmap(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side,
- { resizeWidth: px, resizeHeight: px, resizeQuality: 'high' });
- const canvas = new OffscreenCanvas(px, px);
- canvas.getContext('2d').drawImage(square, 0, 0);
+ cut = await createImageBitmap(bitmap, (W - cw) / 2, (H - ch) / 2, cw, ch,
+ { resizeWidth: tw, resizeHeight: th, resizeQuality: 'high' });
+ const canvas = new OffscreenCanvas(tw, th);
+ canvas.getContext('2d').drawImage(cut, 0, 0);
result.tile = await encode(canvas, 0.8);
- } catch {} finally { square?.close(); }
+ } catch {} finally { cut?.close(); }
}
if (width && bitmap.width > width * 1.25) {
try {
@@ -91,3 +96,32 @@ export function makeImageThumbnails(blob, { width = 0, tileSize = 0 } = {}) {
|| typeof createImageBitmap === 'undefined' || queue.length >= MAX_QUEUE) return Promise.resolve(null);
return new Promise((resolve) => { queue.push({ input: { blob, width, tileSize }, resolve }); drain(); });
}
+
+// A GIF with no loop instruction (the NETSCAPE2.0 application extension)
+// plays once and stops on its last frame: every browser reads it that way.
+// Plenty of GIFs are made without one (a gifs.nostr.build reply GIF froze
+// after a second, Adam, 2026-11-19), and people expect a GIF to loop. The
+// extension, "loop forever", goes right after the global colour table.
+// Returns the patched bytes, or null when the file loops already or isn't
+// a GIF.
+export function loopGif(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ if (b.length < 13 || b[0] !== 0x47 || b[1] !== 0x49 || b[2] !== 0x46) return null; // "GIF"
+ const tag = [0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30]; // NETSCAPE2.0
+ const anim = [0x41, 0x4e, 0x49, 0x4d, 0x45, 0x58, 0x54, 0x53, 0x31, 0x2e, 0x30]; // ANIMEXTS1.0
+ outer: for (let i = 13; i < b.length - 11; i++) {
+ if (b[i] !== 0x4e && b[i] !== 0x41) continue;
+ const t = b[i] === 0x4e ? tag : anim;
+ for (let j = 1; j < 11; j++) if (b[i + j] !== t[j]) continue outer;
+ return null;
+ }
+ const packed = b[10];
+ const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0);
+ if (at > b.length) return null;
+ const ext = new Uint8Array([0x21, 0xff, 0x0b, ...tag, 0x03, 0x01, 0x00, 0x00, 0x00]);
+ const out = new Uint8Array(b.length + ext.length);
+ out.set(b.subarray(0, at), 0);
+ out.set(ext, at);
+ out.set(b.subarray(at), at + ext.length);
+ return out;
+}
diff --git a/src/lang-guess.js b/src/lang-guess.js
index 6d62e30..6911f73 100644
--- a/src/lang-guess.js
+++ b/src/lang-guess.js
@@ -26,7 +26,7 @@ const STOP = {
en: 'the and is to of in that it for you with this on are be have not was but they'.split(' '),
es: 'el la de que y en los es un una por con para las del se no como más pero'.split(' '),
fr: 'le la les de des et est un une pour que qui dans pas sur avec ce il nous vous'.split(' '),
- de: 'der die und das ist nicht ein eine ich zu mit den auf für sich dem des auch wir'.split(' '),
+ de: 'der die und das ist nicht ein eine ich zu mit den auf für sich dem des auch wir du wie man noch schon aber oder wenn hast habe bin bist kann nur mal jetzt hier sind wird'.split(' '),
pt: 'o a de que e do da em um uma para com não os as se mais por isso você'.split(' '),
id: 'yang dan di ini itu dengan untuk tidak dari ada saya akan ke juga bisa kita sudah atau kalau aku'.split(' '),
tr: 've bir bu için ile de da çok ne gibi daha ama var ben sen mi değil kadar her olan'.split(' '),
@@ -37,6 +37,13 @@ const STOP = {
pl: 'i w nie na się z to że jest do co jak ale tak o po czy już'.split(' '),
};
const STOPSETS = Object.fromEntries(Object.entries(STOP).map(([k, v]) => [k, new Set(v)]));
+// Letters only some languages write: one counts as one more common word.
+// A short line has few of those ("Weißt Du wie man die kriegt?" had only
+// "die" before the list grew, and went untranslated as maybe-English).
+const MARKS = {
+ de: /[ßäöü]/i, es: /[ñ¿¡]/i, pt: /[ãõ]/i, fr: /[œèêëîïû]/i, tr: /[ğşı]/i, pl: /[łąęśźżń]/i,
+ vi: /[ạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹđ]/i,
+};
// The text a reader actually reads: no links, no nostr references, no tags.
export const proseOf = (text) => String(text || '')
@@ -67,6 +74,7 @@ export function guessLang(text) {
if (words.length < 4) return null;
const score = {};
for (const w of words) for (const [l, set] of Object.entries(STOPSETS)) if (set.has(w)) score[l] = (score[l] || 0) + 1;
+ for (const [l, re] of Object.entries(MARKS)) if (re.test(prose)) score[l] = (score[l] || 0) + 1;
const ranked = Object.entries(score).sort((a, b) => b[1] - a[1]);
if (!ranked.length || ranked[0][1] < 2) return null;
if (ranked[1] && ranked[0][1] < ranked[1][1] * 1.5) return null;
diff --git a/src/live.js b/src/live.js
new file mode 100644
index 0000000..d31c548
--- /dev/null
+++ b/src/live.js
@@ -0,0 +1,101 @@
+// Live streams (NIP-53). A stream is a kind 30311 event: its title, cover,
+// where to watch (`streaming`, almost always an HLS playlist), whether it's
+// on (`status`), how many watch, and who's in it (p tags with a role). Its
+// chat is kind 1311, addressed to the stream with an `a` tag; zaps carry
+// that `a` too, which is how zap.stream and the rest count them.
+export const LIVE_KIND = 30311;
+export const LIVE_CHAT_KIND = 1311;
+// Where streams are announced: zap.stream, Shosho and the rest publish to
+// the big public relays (a 2026-10-18 survey found every live one on damus,
+// nos.lol and ditto, most on primal; relay.zap.stream held none).
+export const LIVE_RELAYS = ['wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net', 'wss://relay.ditto.pub'];
+// A stream still marked live that hasn't been refreshed in an hour is over:
+// plenty of publishers never say `ended` (NIP-53 allows reading it so).
+export const LIVE_STALE_S = 3600;
+
+// https, or a stream on this machine (a test's, a streamer's own preview)
+const WATCHABLE = /^(https:\/\/\S+|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\/\S*)$/;
+const tag = (ev, k) => ((ev && ev.tags) || []).find((x) => x[0] === k)?.[1] || '';
+export const liveAddr = (ev) => LIVE_KIND + ':' + ev.pubkey + ':' + tag(ev, 'd');
+export const liveTitle = (ev) => tag(ev, 'title').trim();
+export const liveSummary = (ev) => tag(ev, 'summary').trim();
+export const liveImage = (ev) => { const u = tag(ev, 'image').trim(); return /^https:\/\/\S+$/.test(u) ? u : ''; };
+export const liveViewers = (ev) => { const n = parseInt(tag(ev, 'current_participants'), 10); return n >= 0 ? n : null; };
+export const liveStarts = (ev) => +tag(ev, 'starts') || ev.created_at;
+
+// The person streaming: the host named in its p tags (zap.stream signs the
+// event with its own key and names the streamer as Host), else its author.
+export function liveHost(ev) {
+ const p = (ev.tags || []).find((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || '') && /^host$/i.test(x[3] || ''));
+ return p ? p[1] : ev.pubkey;
+}
+// Where to watch: an HLS playlist first (what browsers can play), else any https address.
+export function liveStream(ev) {
+ const urls = (ev.tags || []).filter((x) => x[0] === 'streaming' && WATCHABLE.test(x[1] || '')).map((x) => x[1]);
+ return urls.find((u) => /\.m3u8(\?|#|$)/i.test(u)) || urls[0] || '';
+}
+export function liveRecording(ev) {
+ const u = tag(ev, 'recording');
+ return WATCHABLE.test(u) ? u : '';
+}
+export function liveStatus(ev, now = Date.now() / 1000) {
+ const s = tag(ev, 'status').toLowerCase();
+ if (s === 'live') return now - ev.created_at > LIVE_STALE_S ? 'ended' : 'live';
+ return s === 'planned' ? 'planned' : 'ended';
+}
+export const isLiveNow = (ev, now) => liveStatus(ev, now) === 'live' && !!liveStream(ev);
+// The relays the stream names for its chat, then the ones it's announced on.
+export function liveRelays(ev) {
+ const named = (ev.tags || []).filter((x) => x[0] === 'relays').flatMap((x) => x.slice(1)).filter((r) => /^wss:\/\/\S+$/.test(r));
+ return [...new Set([...named.slice(0, 6), ...LIVE_RELAYS])];
+}
+// Newest copy of each stream (it's replaceable: the address is the stream).
+export function newestByAddr(evs) {
+ const out = new Map();
+ for (const ev of evs) {
+ if (!ev || ev.kind !== LIVE_KIND) continue;
+ const a = liveAddr(ev), cur = out.get(a);
+ if (!cur || cur.created_at < ev.created_at) out.set(a, ev);
+ }
+ return out;
+}
+
+// The zap on a chat line: a 9735 receipt's amount from its bolt11, its
+// sender and words from the zap request inside it; coinos's own Ark receipt
+// (9737) says them in tags. `decode` is the bolt11 decoder (millisats).
+export function zapLine(ev, decode) {
+ if (ev.kind === 9737) {
+ return { pk: tag(ev, 'P') || ev.pubkey, sats: +tag(ev, 'amount') || 0, text: ev.content || '' };
+ }
+ let req = null;
+ try { req = JSON.parse(tag(ev, 'description')); } catch {}
+ let sats = 0;
+ try { sats = Math.floor(Number(decode(tag(ev, 'bolt11'))?.amountMsat || 0) / 1000); } catch {}
+ if (!sats && req) sats = Math.floor((+((req.tags || []).find((x) => x[0] === 'amount') || [])[1] || 0) / 1000);
+ return { pk: (req && /^[0-9a-f]{64}$/.test(req.pubkey || '') && req.pubkey) || tag(ev, 'P') || '', sats, text: (req && req.content) || '' };
+}
+
+// Zaps aimed at a stream carry its address: the zap request (kind 9734) and
+// coinos's Ark receipt look the event they're zapping up here.
+const zapAddrs = new Map();
+export const setZapAddr = (eventId, addr) => { if (eventId && addr) zapAddrs.set(eventId, addr); };
+export const zapAddrOf = (eventId) => (eventId && zapAddrs.get(eventId)) || null;
+
+// One current reaction per person/message, independent of relay arrival order.
+// A deletion only removes reactions signed by its own author.
+export function liveReactions(events) {
+ const deleted = new Set();
+ for (const ev of events) if (ev.kind === 5)
+ for (const tag of ev.tags || []) if (tag[0] === 'e') deleted.add(ev.pubkey + ':' + tag[1]);
+ const out = new Map();
+ for (const ev of events) {
+ if (ev.kind !== 7 || deleted.has(ev.pubkey + ':' + ev.id)) continue;
+ const target = (ev.tags || []).filter(t => t[0] === 'e').at(-1)?.[1];
+ if (!target) continue;
+ const by = out.get(target) || new Map();
+ const old = by.get(ev.pubkey);
+ if (!old || ev.created_at > old.created_at || (ev.created_at === old.created_at && ev.id > old.id)) by.set(ev.pubkey, ev);
+ out.set(target, by);
+ }
+ return out;
+}
diff --git a/src/lnurl.js b/src/lnurl.js
index bfebf0d..134edcf 100644
--- a/src/lnurl.js
+++ b/src/lnurl.js
@@ -1,3 +1,4 @@
+import { momentTags } from './media-timeline.js';
// LNURL-pay + NIP-57 ("lightning zap") logic — no DOM, so it stays testable.
//
// The wallet already pays bolt11 invoices over a Boltz submarine swap; this
@@ -10,6 +11,7 @@
// (bolt11) → hand that to the swap engine. The recipient's server is the one
// that broadcasts the receipt; we only sign the request.
+import { zapAddrOf } from './live.js';
import { bech32 } from '@scure/base';
import { secp256k1 } from '@noble/curves/secp256k1';
import { hmac } from '@noble/hashes/hmac';
@@ -122,11 +124,15 @@ export async function fetchPayParams(url) {
}
// A signed kind-9734 zap request (NIP-57). signFn(partial) → finalized event.
-export function buildZapRequest({ amountMsat, relays, lnurlBech32, recipientPk, eventId, comment, signFn }) {
+export function buildZapRequest({ amountMsat, relays, lnurlBech32, recipientPk, eventId, comment, signFn, moment }) {
const tags = [['relays', ...relays], ['amount', String(amountMsat)], ['p', recipientPk]];
if (lnurlBech32) tags.push(['lnurl', lnurlBech32]);
if (eventId) tags.push(['e', eventId]);
- return signFn({ kind: 9734, content: comment || '', tags });
+ // a live stream's address too, so its chat and zap.stream count the zap
+ const addr = zapAddrOf(eventId);
+ if (addr) tags.push(['a', addr]);
+ tags.push(...momentTags(moment));
+ return signFn({ kind: 9734, created_at: Math.floor(Date.now() / 1000), content: comment || '', tags });
}
// GET the callback for a bolt11. When zapRequest is present this is a real zap;
diff --git a/src/locales/ar.json b/src/locales/ar.json
index f112568..a60f6ba 100644
--- a/src/locales/ar.json
+++ b/src/locales/ar.json
@@ -364,6 +364,10 @@
"giftWelcome": "لقد أُرسلت إليك عملة Bitcoin",
"giftBackedUp": "لقد دوّنتها",
"giftLink": "أهدِ بعض عملات Bitcoin",
+ "giftNotePlaceholder": "أضف ملاحظة (اختياري)",
+ "giftFromMe": "قل إنها مني (المطالبة بها تتابعك)",
+ "giftFrom": "من",
+ "giftClaimFollows": "المطالبة بها تعني متابعة المُرسِل",
"giftLinkDesc": "وقّع مبلغاً مسبقاً كرابط. من يفتحه يطالب بعملات Bitcoin في محفظة جديدة تماماً يتحكم بها وحده.",
"giftLinkWarn": "⚠ أي شخص يفتح هذا الرابط يمكنه المطالبة بالمبلغ، لذا شاركه فقط مع الشخص الذي تهديه إياه. أبقِ المبالغ صغيرة.",
"giftLinkReveal": "إنشاء رابط الإهداء",
@@ -425,6 +429,7 @@
"claimOr": "أو",
"goToWallet": "اذهب إلى المحفظة",
"claimBtn": "طالب بها",
+ "claimNowBtn": "استلمها الآن",
"claimFeeNote": "♪{n} الرسوم",
"claimFailed": "تمت المطالبة بهذه الهدية بالفعل أو لم تعد متاحة.",
"claimNotVisibleBody": "والعملات التي تمول هذه الهدية غير مرئية من مصدر هذه المحفظة/البيانات. تأكد من استخدام هذه المحفظة نفس الشبكة ومصدر البيانات كمرسل، ثم محاولة مرة أخرى.",
@@ -618,6 +623,8 @@
"onbSpendBody": "اطالب بلقب مستخدم والحصول على عنوان الدفع الخاص بك - الناس يمكن أن ترسل لك قليلا على الفور، مع مجرد اسمك.",
"onbNameWait": "جهز الأشياء",
"onbNotNow": "ليس الآن",
+ "onbGiftNameTitle": "الآن اختر اسم مستخدم",
+ "onbGiftNameBody": "احجز اسمًا واحصل على عنوان دفع خاص بك، ليتمكن الناس من إرسال البيتكوين إليك باسمك فقط. ثم اختر صورة وغلافًا.",
"onbAvatarTitle": "اختر مظهرك",
"onbAvatarBody": "اختر صورة رمزية أو ارفع صورتك. يمكنك تغييرها في أي وقت",
"onbUpload": "تحميل الصورة",
@@ -678,6 +685,7 @@
"namesClaim": "المطالبة",
"namesClaimed": "أنت الآن {name}",
"namesCopy": "عنوان الرسالة",
+ "namesChangeTo": "غيّره إلى {addr}",
"namesMoreOpen": "المزيد من الخيارات",
"namesMoreTitle": "المزيد من الطرق للحصول على أجر",
"namesMoreBolt11": "فاتورة البرق (BOLT 11)",
@@ -878,6 +886,17 @@
"followHistNone": "لا توجد نسخة أقدم فيها أحد تفتقده قائمتك.",
"followHistNothing": "كل من في تلك النسخة موجود في قائمتك بالفعل.",
"followHistRestored": "تمت استعادة {n} متابَعًا.",
+ "profHistDesc": "إذا استبدل تطبيق آخر ملفك الشخصي، فقد تبقى نسخة أقدم على مرحّل يحتفظ بالسجل. استخدامها يملأ فقط الحقول الفارغة هنا.",
+ "profHistLook": "البحث عن نسخ أقدم",
+ "profHistUse": "استخدام",
+ "profHistNoName": "(بلا اسم)",
+ "profHistNone": "لا توجد نسخة أقدم فيها شيء ينقص هنا.",
+ "profHistNothing": "كل ما في تلك النسخة موجود هنا بالفعل.",
+ "profHistFilled": "تم ملء {n} حقول من النسخة الأقدم. احفظ للنشر.",
+ "profHist_name": "الاسم",
+ "profHist_about": "النبذة",
+ "profHist_picture": "الصورة",
+ "profHist_banner": "الغلاف",
"securityTitle": "الأمان",
"arkCoinsNone": "لا توجد عملات في الإنفاق بعد.",
"profKeyLink": "المفتاح العام",
@@ -910,6 +929,8 @@
"mediaNoImages": "لا صور في هذه الخلاصة بعد.",
"mediaNoVideos": "لا فيديوهات عمودية في هذه الخلاصة بعد.",
"videoTapToPlay": "انقر للتشغيل",
+ "videoPlay": "تشغيل",
+ "videoPause": "إيقاف مؤقت",
"videoLargeTitle": "الفيديوهات",
"videoLargeToggle": "تشغيل الفيديوهات الكبيرة تلقائيًا",
"videoLargeHelp": "الفيديوهات التي تزيد على {mb} ميغابايت أو تتجاوز 1080p تنتظر نقرة، حتى لا تستهلك الخلاصة بياناتك. الحد أقل على الاتصال البطيء أو عند توفير البيانات.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "عرض معاملة الجولة",
"pagerFetchingVideo": "جارٍ جلب الفيديو التالي…",
"pagerFetchingPictures": "جارٍ جلب المزيد من الصور…",
- "pagerCaughtUp": "هذا كل شيء الآن"
+ "pagerCaughtUp": "هذا كل شيء الآن",
+ "schedToggle": "جدولة لوقت لاحق",
+ "schedAt": "النشر في",
+ "schedBtn": "جدولة",
+ "schedDone": "مجدول في {when}",
+ "schedTooSoon": "اختر وقتًا بعد دقيقتين على الأقل من الآن",
+ "schedListTitle": "مجدولة ({n})",
+ "schedCancelled": "أُلغي المنشور المجدول"
}
diff --git a/src/locales/bn.json b/src/locales/bn.json
index 85ce58a..0f627b2 100644
--- a/src/locales/bn.json
+++ b/src/locales/bn.json
@@ -364,6 +364,10 @@
"giftWelcome": "আপনাকে Bitcoin পাঠানো হয়েছে",
"giftBackedUp": "আমি এটি লিখে রেখেছি",
"giftLink": "কিছু Bitcoin উপহার দিন",
+ "giftNotePlaceholder": "একটি নোট যোগ করুন (ঐচ্ছিক)",
+ "giftFromMe": "জানাও এটা আমার কাছ থেকে (দাবি করলে তোমাকে ফলো করবে)",
+ "giftFrom": "পাঠিয়েছেন",
+ "giftClaimFollows": "দাবি করলে তাঁকে ফলো করা হবে",
"giftLinkDesc": "একটি পরিমাণ লিঙ্ক হিসেবে আগে থেকে সই করুন। যে এটি খুলবে সে Bitcoin-টি একটি একদম নতুন ওয়ালেটে দাবি করে, যা কেবল সে-ই নিয়ন্ত্রণ করে।",
"giftLinkWarn": "⚠ যে কেউ এই লিঙ্ক খুললে পরিমাণটি দাবি করতে পারে, তাই কেবল যাকে উপহার দিচ্ছেন তার সাথেই এটি শেয়ার করুন। পরিমাণ কম রাখুন।",
"giftLinkReveal": "লিংক নির্মাণ করুন",
@@ -425,6 +429,7 @@
"claimOr": "অথবা",
"goToWallet": "ওয়ালেট যাও",
"claimBtn": "দাবি করুন",
+ "claimNowBtn": "এখনই নিন",
"claimFeeNote": "একটিও নয়{n} কাগজ",
"claimFailed": "এই উপহারটি আগেই দাবি করা হয়েছে অথবা আর পাওয়া যাচ্ছে না।",
"claimNotVisibleBody": "এই দানের অর্থ এই ওয়ালেটের নেটওয়ার্ক/ডাটা উৎস থেকে দেখা যাচ্ছে না। নিশ্চিত করুন যে এই ওয়ালেট একই নেটওয়ার্ক এবং ডাটা উৎস ব্যবহার করে, অতঃপর পুনরায় চেষ্টা করুন ।",
@@ -618,6 +623,8 @@
"onbSpendBody": "আপনার নাম শুধু আপনার নামের সঙ্গে সঙ্গে সঙ্গে সঙ্গে আপনি আপনার পেকেন পাঠাতে পারেন ।",
"onbNameWait": "জিনিস প্রস্তুত করা হচ্ছে...",
"onbNotNow": "এই মুহূর্তে নয়",
+ "onbGiftNameTitle": "এবার একটি ইউজারনেম বেছে নিন",
+ "onbGiftNameBody": "একটি নাম নিন এবং নিজের পেমেন্ট ঠিকানা পান, যাতে লোকে শুধু আপনার নাম দিয়েই আপনাকে বিটকয়েন পাঠাতে পারে। তারপর একটি ছবি আর একটি কভার বেছে নিন।",
"onbAvatarTitle": "আপনার চেহারা পছন্দ করুন",
"onbAvatarBody": "একটি অবতার বেছে নাও অথবা নিজের ছবি আপলোড করো। যেকোনো সময় এটি বদলাতে পারো।",
"onbUpload": "একটি ছবি আপলোড করুন",
@@ -678,6 +685,7 @@
"namesClaim": "মুছে ফেলুন (_D)",
"namesClaimed": "তুমি এখন {name}",
"namesCopy": "ঠিকানা কপি করো",
+ "namesChangeTo": "{addr}-এ বদলান",
"namesMoreOpen": "অতিরিক্ত বিকল্প",
"namesMoreTitle": "আরো টাকা পেতে",
"namesMoreBolt11": "(বিওএল ১১)",
@@ -878,6 +886,17 @@
"followHistNone": "কোনো পুরোনো কপিতে এমন কেউ নেই যিনি আপনার তালিকায় নেই।",
"followHistNothing": "ওই কপির সবাই ইতিমধ্যে আপনার তালিকায় আছেন।",
"followHistRestored": "{n} জনকে আবার ফলো করা হয়েছে।",
+ "profHistDesc": "অন্য কোনো অ্যাপ আপনার প্রোফাইল বদলে দিলে, ইতিহাস রাখে এমন কোনো রিলেতে পুরোনো কপি এখনও থাকতে পারে। সেটি ব্যবহার করলে এখানে শুধু খালি ঘরগুলো পূরণ হয়।",
+ "profHistLook": "পুরোনো কপি খুঁজুন",
+ "profHistUse": "ব্যবহার করুন",
+ "profHistNoName": "(নাম নেই)",
+ "profHistNone": "কোনো পুরোনো কপিতে এমন কিছু নেই যা এখানে নেই।",
+ "profHistNothing": "ওই কপির সবকিছু এখানে আগে থেকেই আছে।",
+ "profHistFilled": "পুরোনো কপি থেকে {n}টি ঘর পূরণ হয়েছে। প্রকাশ করতে সংরক্ষণ করুন।",
+ "profHist_name": "নাম",
+ "profHist_about": "পরিচিতি",
+ "profHist_picture": "ছবি",
+ "profHist_banner": "ব্যানার",
"securityTitle": "নিরাপত্তা",
"arkCoinsNone": "স্পেন্ডিং-এ এখনও কোনো কয়েন নেই।",
"profKeyLink": "পাবলিক কী",
@@ -910,6 +929,8 @@
"mediaNoImages": "এই ফিডে এখনও কোনো ছবি নেই।",
"mediaNoVideos": "এই ফিডে এখনও কোনো খাড়া ভিডিও নেই।",
"videoTapToPlay": "চালাতে ট্যাপ করুন",
+ "videoPlay": "চালান",
+ "videoPause": "বিরতি",
"videoLargeTitle": "ভিডিও",
"videoLargeToggle": "বড় ভিডিও নিজে থেকে চালান",
"videoLargeHelp": "{mb} MB-এর বেশি বা 1080p-এর ওপরের ভিডিও ট্যাপের অপেক্ষায় থাকে, যাতে ফিড আপনার ডেটা না খায়। ধীর বা ডেটা-সেভার সংযোগে সীমা কম।",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "রাউন্ডের লেনদেন দেখুন",
"pagerFetchingVideo": "পরের ভিডিও আনা হচ্ছে…",
"pagerFetchingPictures": "আরও ছবি আনা হচ্ছে…",
- "pagerCaughtUp": "আপাতত এটুকুই"
+ "pagerCaughtUp": "আপাতত এটুকুই",
+ "schedToggle": "পরে পোস্ট করার সময় ঠিক করুন",
+ "schedAt": "পোস্টের সময়",
+ "schedBtn": "সময় ঠিক করুন",
+ "schedDone": "{when}-এ নির্ধারিত",
+ "schedTooSoon": "এখন থেকে অন্তত দুই মিনিট পরের সময় বেছে নিন",
+ "schedListTitle": "নির্ধারিত ({n})",
+ "schedCancelled": "নির্ধারিত পোস্ট বাতিল হয়েছে"
}
diff --git a/src/locales/de.json b/src/locales/de.json
index 0210332..11fde22 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -364,6 +364,10 @@
"giftWelcome": "Dir wurde Bitcoin gesendet",
"giftBackedUp": "Ich habe sie aufgeschrieben",
"giftLink": "Bitcoin verschenken",
+ "giftNotePlaceholder": "Notiz hinzufügen (optional)",
+ "giftFromMe": "Zeigen, dass es von mir ist (wer es einlöst, folgt dir)",
+ "giftFrom": "Von",
+ "giftClaimFollows": "Beim Einlösen folgst du dieser Person",
"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 +429,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 +623,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",
@@ -640,7 +647,7 @@
"nlPasskey": "Anmelden mit einem Passkey",
"nlKeyOrBunker": "nsec, private Schlüssel oder Bunker://...",
"nlGo": "Anmelden",
- "nlHint": "Funktioniert mit Amber, Amethyst und anderen Remote-Signern (paste ihre Bunker://-Adresse), oder einer Browser-Erweiterung. Ein geklebter Schlüssel wird einmal verwendet und nie gespeichert.",
+ "nlHint": "Funktioniert mit Remote-Signer-Apps (füge ihre bunker://-Adresse ein) oder einer Browser-Erweiterung. Ein eingefügter Schlüssel wird einmal verwendet und nie gespeichert.",
"nlApprove": "billigt den Antrag in Ihrem Schilder →",
"nlUnrecognized": "Das sieht nicht aus wie ein privater Schlüssel oder eine Bunkeradresse.",
"nlNewTitle": "Erstellen Sie eine Brieftasche für dieses Konto",
@@ -678,6 +685,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)",
@@ -878,6 +886,17 @@
"followHistNone": "Keine ältere Kopie enthält jemanden, der in deiner Liste fehlt.",
"followHistNothing": "Alle aus dieser Kopie sind schon in deiner Liste.",
"followHistRestored": "{n} Follows wiederhergestellt.",
+ "profHistDesc": "Hat eine andere App dein Profil ersetzt, liegt vielleicht noch eine ältere Kopie auf einem Relay, das den Verlauf aufbewahrt. Eine zu übernehmen füllt nur die Felder, die hier leer sind.",
+ "profHistLook": "Nach älteren Kopien suchen",
+ "profHistUse": "Übernehmen",
+ "profHistNoName": "(kein Name)",
+ "profHistNone": "Keine ältere Kopie enthält etwas, das hier fehlt.",
+ "profHistNothing": "Alles aus dieser Kopie ist schon hier.",
+ "profHistFilled": "{n} Felder aus der älteren Kopie gefüllt. Speichern, um zu veröffentlichen.",
+ "profHist_name": "Name",
+ "profHist_about": "Bio",
+ "profHist_picture": "Bild",
+ "profHist_banner": "Banner",
"securityTitle": "Sicherheit",
"arkCoinsNone": "Noch keine Coins in Ausgaben.",
"profKeyLink": "Öffentlicher Schlüssel",
@@ -910,6 +929,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.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "Transaktion der Runde ansehen",
"pagerFetchingVideo": "Nächstes Video wird geladen …",
"pagerFetchingPictures": "Weitere Bilder werden geladen …",
- "pagerCaughtUp": "Das ist vorerst alles"
+ "pagerCaughtUp": "Das ist vorerst alles",
+ "schedToggle": "Für später planen",
+ "schedAt": "Posten am",
+ "schedBtn": "Planen",
+ "schedDone": "Geplant für {when}",
+ "schedTooSoon": "Wähle eine Zeit mindestens zwei Minuten ab jetzt",
+ "schedListTitle": "Geplant ({n})",
+ "schedCancelled": "Geplanter Beitrag abgebrochen"
}
diff --git a/src/locales/es.json b/src/locales/es.json
index 9637b0a..28e2489 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -364,6 +364,10 @@
"giftWelcome": "Te han enviado Bitcoin",
"giftBackedUp": "Ya la anoté",
"giftLink": "Regala algo de Bitcoin",
+ "giftNotePlaceholder": "Añade una nota (opcional)",
+ "giftFromMe": "Decir que es mío (quien lo reclame te seguirá)",
+ "giftFrom": "De",
+ "giftClaimFollows": "Al reclamarlo, seguirás a esta persona",
"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 +429,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 +623,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",
@@ -640,7 +647,7 @@
"nlPasskey": "Inicie sesión con un passkey",
"nlKeyOrBunker": "nsec, private key, or bunker://...",
"nlGo": "Iniciar sesión",
- "nlHint": "Trabaja con Amber, Amethyst y otros firmantes remotos (pasar su bunker:// dirección), o una extensión del navegador. Una llave pegada se utiliza una vez y nunca se almacena.",
+ "nlHint": "Funciona con apps firmantes remotas (pega su dirección bunker://) o una extensión del navegador. Una clave pegada se usa una vez y nunca se guarda.",
"nlApprove": "Aprobar la solicitud en su firmante →",
"nlUnrecognized": "Eso no parece una llave privada o una dirección bunker://.",
"nlNewTitle": "Crear una cartera para esta cuenta",
@@ -678,6 +685,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)",
@@ -878,6 +886,17 @@
"followHistNone": "Ninguna copia anterior tiene a alguien que falte en tu lista.",
"followHistNothing": "Todos los de esa copia ya están en tu lista.",
"followHistRestored": "Se restauraron {n} seguidos.",
+ "profHistDesc": "Si otra app reemplazó tu perfil, puede que aún haya una copia anterior en un relay que guarda el historial. Usarla solo rellena los campos que aquí están vacíos.",
+ "profHistLook": "Buscar copias anteriores",
+ "profHistUse": "Usar",
+ "profHistNoName": "(sin nombre)",
+ "profHistNone": "Ninguna copia anterior tiene algo que falte aquí.",
+ "profHistNothing": "Todo lo de esa copia ya está aquí.",
+ "profHistFilled": "{n} campos rellenados desde la copia anterior. Guarda para publicar.",
+ "profHist_name": "nombre",
+ "profHist_about": "bio",
+ "profHist_picture": "foto",
+ "profHist_banner": "banner",
"securityTitle": "Seguridad",
"arkCoinsNone": "Aún no hay monedas en Gastos.",
"profKeyLink": "Clave pública",
@@ -910,6 +929,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.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "Ver la transacción de la ronda",
"pagerFetchingVideo": "Cargando el siguiente vídeo…",
"pagerFetchingPictures": "Cargando más imágenes…",
- "pagerCaughtUp": "Eso es todo por ahora"
+ "pagerCaughtUp": "Eso es todo por ahora",
+ "schedToggle": "Programar para más tarde",
+ "schedAt": "Publicar el",
+ "schedBtn": "Programar",
+ "schedDone": "Programado para {when}",
+ "schedTooSoon": "Elige una hora al menos dos minutos a partir de ahora",
+ "schedListTitle": "Programadas ({n})",
+ "schedCancelled": "Publicación programada cancelada"
}
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 280be04..54c6eda 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -364,6 +364,10 @@
"giftWelcome": "Vous avez reçu des Bitcoin",
"giftBackedUp": "Je l’ai notée",
"giftLink": "Offrir des Bitcoin",
+ "giftNotePlaceholder": "Ajouter un mot (facultatif)",
+ "giftFromMe": "Dire que ça vient de moi (qui le réclame vous suivra)",
+ "giftFrom": "De",
+ "giftClaimFollows": "En le réclamant, vous suivrez cette personne",
"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 +429,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 +623,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",
@@ -640,7 +647,7 @@
"nlPasskey": "Connectez-vous avec un mot de passe",
"nlKeyOrBunker": "nsec, clé privée, ou bunker://...",
"nlGo": "Connexion",
- "nlHint": "Fonctionne avec Amber, Amethyst et d'autres signataires distants (collez leur adresse de bunker://), ou une extension de navigateur. Une clé collée est utilisée une fois et jamais stockée.",
+ "nlHint": "Fonctionne avec les applis de signature à distance (collez leur adresse bunker://) ou une extension de navigateur. Une clé collée est utilisée une fois et jamais enregistrée.",
"nlApprove": "Approuver la demande dans votre signataire →",
"nlUnrecognized": "Ça ne ressemble pas à une clé privée ou à une adresse de bunker://.",
"nlNewTitle": "Créer un portefeuille pour ce compte",
@@ -678,6 +685,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)",
@@ -878,6 +886,17 @@
"followHistNone": "Aucune copie plus ancienne ne contient quelqu’un qui manque à votre liste.",
"followHistNothing": "Tout le monde dans cette copie est déjà dans votre liste.",
"followHistRestored": "{n} abonnements restaurés.",
+ "profHistDesc": "Si une autre app a remplacé votre profil, une copie plus ancienne est peut-être encore sur un relais qui garde l’historique. En utiliser une ne remplit que les champs vides ici.",
+ "profHistLook": "Chercher des copies plus anciennes",
+ "profHistUse": "Utiliser",
+ "profHistNoName": "(sans nom)",
+ "profHistNone": "Aucune copie plus ancienne n’a quelque chose qui manque ici.",
+ "profHistNothing": "Tout ce que contient cette copie est déjà ici.",
+ "profHistFilled": "{n} champs remplis depuis la copie plus ancienne. Enregistrez pour publier.",
+ "profHist_name": "nom",
+ "profHist_about": "bio",
+ "profHist_picture": "photo",
+ "profHist_banner": "bannière",
"securityTitle": "Sécurité",
"arkCoinsNone": "Aucune pièce dans Dépenses pour l’instant.",
"profKeyLink": "Clé publique",
@@ -910,6 +929,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.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "Voir la transaction du tour",
"pagerFetchingVideo": "Chargement de la vidéo suivante…",
"pagerFetchingPictures": "Chargement d’autres images…",
- "pagerCaughtUp": "C’est tout pour le moment"
+ "pagerCaughtUp": "C’est tout pour le moment",
+ "schedToggle": "Programmer pour plus tard",
+ "schedAt": "Publier le",
+ "schedBtn": "Programmer",
+ "schedDone": "Programmé pour {when}",
+ "schedTooSoon": "Choisis une heure au moins deux minutes après maintenant",
+ "schedListTitle": "Programmés ({n})",
+ "schedCancelled": "Publication programmée annulée"
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 8057344..527eb27 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -364,6 +364,10 @@
"giftWelcome": "आपको Bitcoin भेजा गया है",
"giftBackedUp": "मैंने इसे लिख लिया है",
"giftLink": "कुछ Bitcoin उपहार में दें",
+ "giftNotePlaceholder": "एक नोट जोड़ें (वैकल्पिक)",
+ "giftFromMe": "बताएं कि यह मेरी ओर से है (दावा करने पर आपको फ़ॉलो करेंगे)",
+ "giftFrom": "भेजने वाले",
+ "giftClaimFollows": "दावा करने पर आप उन्हें फ़ॉलो करेंगे",
"giftLinkDesc": "एक राशि को लिंक के रूप में पहले से साइन करें। जो भी इसे खोलेगा, वह Bitcoin को एक बिल्कुल नए वॉलेट में प्राप्त कर लेगा जिसे केवल वही नियंत्रित करता है।",
"giftLinkWarn": "⚠ जो भी इस लिंक को खोलेगा वह राशि प्राप्त कर सकता है, इसलिए इसे केवल उसी व्यक्ति के साथ साझा करें जिसे आप उपहार दे रहे हैं। राशि कम रखें।",
"giftLinkReveal": "उपहार लिंक बनाएँ",
@@ -425,6 +429,7 @@
"claimOr": "या",
"goToWallet": "वॉलेट पर जाएं",
"claimBtn": "इसे प्राप्त करें",
+ "claimNowBtn": "अभी लें",
"claimFeeNote": "~{n} शुल्क",
"claimFailed": "इस उपहार का दावा पहले ही किया जा चुका है या यह अब उपलब्ध नहीं है।",
"claimNotVisibleBody": "इस उपहार को वित्तपोषित करने वाले सिक्के इस वॉलेट के नेटवर्क / डेटा स्रोत से दिखाई नहीं देते हैं। सुनिश्चित करें कि यह वॉलेट प्रेषक के समान नेटवर्क और डेटा स्रोत का उपयोग करता है, फिर फिर से प्रयास करें।",
@@ -618,6 +623,8 @@
"onbSpendBody": "एक उपयोगकर्ता नाम का दावा करें और अपना खुद का भुगतान पता प्राप्त करें - लोग तुरंत अपने नाम के साथ बिटकॉइन भेज सकते हैं।",
"onbNameWait": "चीजों को तैयार करना",
"onbNotNow": "अब नहीं",
+ "onbGiftNameTitle": "अब एक यूज़रनेम चुनें",
+ "onbGiftNameBody": "एक नाम लें और अपना भुगतान पता पाएं, ताकि लोग सिर्फ़ आपके नाम से आपको बिटकॉइन भेज सकें। फिर एक तस्वीर और एक कवर चुनें।",
"onbAvatarTitle": "अपना लुक चुनें",
"onbAvatarBody": "एक अवतार चुनें या अपनी तस्वीर अपलोड करें। आप इसे कभी भी बदल सकते हैं।",
"onbUpload": "फ़ोटो अपलोड करें",
@@ -678,6 +685,7 @@
"namesClaim": "दावा",
"namesClaimed": "अब {name}",
"namesCopy": "पता कॉपी करें",
+ "namesChangeTo": "{addr} में बदलें",
"namesMoreOpen": "अधिक विकल्प",
"namesMoreTitle": "भुगतान करने के तरीके",
"namesMoreBolt11": "बिजली चालान (BOLT 11)",
@@ -878,6 +886,17 @@
"followHistNone": "किसी पुरानी कॉपी में ऐसा कोई नहीं जो आपकी सूची में न हो।",
"followHistNothing": "उस कॉपी के सभी लोग पहले से आपकी सूची में हैं।",
"followHistRestored": "{n} फ़ॉलो बहाल किए गए।",
+ "profHistDesc": "अगर किसी दूसरे ऐप ने आपकी प्रोफ़ाइल बदल दी है, तो इतिहास रखने वाले किसी रिले पर पुरानी प्रति अब भी हो सकती है। उसे इस्तेमाल करने से यहाँ सिर्फ़ खाली फ़ील्ड भरते हैं।",
+ "profHistLook": "पुरानी प्रतियाँ खोजें",
+ "profHistUse": "इस्तेमाल करें",
+ "profHistNoName": "(बिना नाम)",
+ "profHistNone": "किसी पुरानी प्रति में ऐसा कुछ नहीं जो यहाँ न हो।",
+ "profHistNothing": "उस प्रति की हर चीज़ यहाँ पहले से है।",
+ "profHistFilled": "पुरानी प्रति से {n} फ़ील्ड भरे गए। प्रकाशित करने के लिए सहेजें।",
+ "profHist_name": "नाम",
+ "profHist_about": "परिचय",
+ "profHist_picture": "फ़ोटो",
+ "profHist_banner": "बैनर",
"securityTitle": "सुरक्षा",
"arkCoinsNone": "स्पेंडिंग में अभी कोई कॉइन नहीं।",
"profKeyLink": "पब्लिक की",
@@ -910,6 +929,8 @@
"mediaNoImages": "इस फ़ीड में अभी कोई तस्वीर नहीं।",
"mediaNoVideos": "इस फ़ीड में अभी कोई वर्टिकल वीडियो नहीं।",
"videoTapToPlay": "चलाने के लिए टैप करें",
+ "videoPlay": "चलाएँ",
+ "videoPause": "रोकें",
"videoLargeTitle": "वीडियो",
"videoLargeToggle": "बड़े वीडियो अपने आप चलाएँ",
"videoLargeHelp": "{mb} MB से बड़े या 1080p से ऊपर के वीडियो टैप का इंतज़ार करते हैं, ताकि फ़ीड आपका डेटा न खाए। धीमे या डेटा-सेवर कनेक्शन पर सीमा कम होती है।",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "राउंड का लेनदेन देखें",
"pagerFetchingVideo": "अगला वीडियो लाया जा रहा है…",
"pagerFetchingPictures": "और तस्वीरें लाई जा रही हैं…",
- "pagerCaughtUp": "अभी के लिए बस इतना ही"
+ "pagerCaughtUp": "अभी के लिए बस इतना ही",
+ "schedToggle": "बाद के लिए शेड्यूल करें",
+ "schedAt": "पोस्ट करने का समय",
+ "schedBtn": "शेड्यूल करें",
+ "schedDone": "{when} के लिए शेड्यूल किया गया",
+ "schedTooSoon": "अभी से कम से कम दो मिनट बाद का समय चुनें",
+ "schedListTitle": "शेड्यूल किए गए ({n})",
+ "schedCancelled": "शेड्यूल की गई पोस्ट रद्द हुई"
}
diff --git a/src/locales/id.json b/src/locales/id.json
index 6773d96..e2402eb 100644
--- a/src/locales/id.json
+++ b/src/locales/id.json
@@ -137,6 +137,10 @@
"giftSkip": "Lewati dulu",
"giftBackedUp": "Saya sudah mencatatnya",
"giftLink": "Hadiahkan Bitcoin",
+ "giftNotePlaceholder": "Tambahkan catatan (opsional)",
+ "giftFromMe": "Tunjukkan ini dari saya (yang mengklaim akan mengikuti Anda)",
+ "giftFrom": "Dari",
+ "giftClaimFollows": "Mengklaimnya akan mengikuti pengirim",
"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 +149,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.",
@@ -215,6 +220,17 @@
"followHistNone": "Tidak ada salinan lama yang berisi orang yang hilang dari daftarmu.",
"followHistNothing": "Semua orang di salinan itu sudah ada di daftarmu.",
"followHistRestored": "{n} ikutan dipulihkan.",
+ "profHistDesc": "Jika aplikasi lain mengganti profil Anda, salinan lama mungkin masih ada di relay yang menyimpan riwayat. Memakainya hanya mengisi kolom yang kosong di sini.",
+ "profHistLook": "Cari salinan lama",
+ "profHistUse": "Pakai",
+ "profHistNoName": "(tanpa nama)",
+ "profHistNone": "Tidak ada salinan lama yang punya sesuatu yang kurang di sini.",
+ "profHistNothing": "Semua isi salinan itu sudah ada di sini.",
+ "profHistFilled": "{n} kolom diisi dari salinan lama. Simpan untuk menerbitkan.",
+ "profHist_name": "nama",
+ "profHist_about": "bio",
+ "profHist_picture": "foto",
+ "profHist_banner": "spanduk",
"securityTitle": "Keamanan",
"arkCoinsNone": "Belum ada koin di Belanja.",
"profKeyLink": "Kunci publik",
@@ -247,6 +263,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 +279,15 @@
"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}",
+ "schedToggle": "Jadwalkan untuk nanti",
+ "schedAt": "Posting pada",
+ "schedBtn": "Jadwalkan",
+ "schedDone": "Dijadwalkan untuk {when}",
+ "schedTooSoon": "Pilih waktu setidaknya dua menit dari sekarang",
+ "schedListTitle": "Terjadwal ({n})",
+ "schedCancelled": "Postingan terjadwal dibatalkan"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index 7ac8b00..1844905 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -28,6 +28,20 @@
"logoutOneBlurbSeed": "Esce solo questo account. Gli altri restano connessi. Verrà rimosso da questo dispositivo, quindi assicurati di avere la sua frase di recupero.",
"logoutAll": "Esci da tutti gli account",
"clearAllWarn": "⚠ Questo rimuove tutti gli account da questo dispositivo. Ogni account di cui non hai salvato la frase di recupero o la chiave andrà perso per sempre.",
+ "delAcctTitle": "Elimina account",
+ "delAcctBlurb": "Rinuncia al tuo nome Coinos, fai dimenticare questo account ai nostri server e rimuovilo da questo dispositivo.",
+ "delAcctChecking": "Controllo del tuo account…",
+ "delAcctName": "{name} viene rilasciato. Chiunque potrà richiederlo in seguito e i pagamenti inviati a quel nome non ti arriveranno più.",
+ "delAcctRecords": "I nostri server eliminano ciò che conservano per questo account: indirizzo di pagamento, registrazioni delle notifiche, post programmati, cappelli, dati del punto vendita e delle ricevute.",
+ "delAcctDevice": "“{name}” viene rimosso da questo dispositivo.",
+ "delAcctStays": "Non eliminati: le tue monete, controllate solo dalla tua frase di recupero, e ciò che hai pubblicato sui relay nostr (profilo, post, messaggi).",
+ "delAcctOwed": "⚠ {sat} sat sono ancora in arrivo o trattenuti nei tuoi link di prelievo. Attendi i pagamenti, riprendi i link di prelievo (Invia → Link di prelievo) e riprova.",
+ "delAcctFunds": "⚠ Questo account contiene ancora {sat} sat. L'eliminazione non li sposta. Inviali altrove prima, oppure assicurati di avere la frase di recupero: senza di essa sono persi per sempre.",
+ "delAcctSure": "Ho capito che non si può annullare.",
+ "delAcctSureFunds": "Ho spostato i miei fondi o salvato la frase di recupero, e ho capito che non si può annullare.",
+ "delAcctGo": "Elimina account",
+ "delAcctDone": "Account eliminato",
+ "delAcctUnlockFirst": "Blocca Coinos e sbloccalo con la tua password, poi riprova",
"removeWalletTitle": "Rimuovi account",
"removeWalletWarn": "⚠ Rimuovere “{name}” da questo dispositivo? Sparirà da questo browser. Assicurati di avere la sua frase di recupero. Gli altri account non vengono toccati.",
"rename": "Rinomina",
@@ -96,6 +110,17 @@
"relaysReload": "Ricarica",
"followHistNothing": "Tutti quelli presenti in quella copia sono già nella tua lista.",
"followHistRestored": "Ripristinati {n} seguiti.",
+ "profHistDesc": "Se un’altra app ha sostituito il tuo profilo, una copia più vecchia potrebbe essere ancora su un relay che conserva la cronologia. Usarne una riempie solo i campi qui vuoti.",
+ "profHistLook": "Cerca copie più vecchie",
+ "profHistUse": "Usa",
+ "profHistNoName": "(senza nome)",
+ "profHistNone": "Nessuna copia più vecchia ha qualcosa che manca qui.",
+ "profHistNothing": "Tutto ciò che c’è in quella copia è già qui.",
+ "profHistFilled": "{n} campi riempiti dalla copia più vecchia. Salva per pubblicare.",
+ "profHist_name": "nome",
+ "profHist_about": "bio",
+ "profHist_picture": "foto",
+ "profHist_banner": "banner",
"profFollowing": "Seguiti",
"profFollowers": "Follower",
"profFollowsNone": "Non segui ancora nessuno.",
@@ -222,6 +247,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",
@@ -473,9 +500,16 @@
"publicChatTitle": "Community {name}",
"publicChatDesc": "Chat dal vivo: leggi, accedi per partecipare alla conversazione",
"publicChatSignIn": "Accedi per chattare",
- "publicChatOpenApp": "Apri coinos",
+ "publicChatDescMember": "Chat dal vivo: apri la chat in Coinos per partecipare alla conversazione",
+ "publicChatOpenApp": "Partecipa alla chat",
"publicChatLoading": "Caricamento messaggi…",
"msgDelete": "Elimina messaggio",
+ "msgBan": "Rimuovi {name} e i suoi messaggi",
+ "msgBanConfirm": "Rimuovere {name} per tutti? Tocca di nuovo",
+ "msgBanned": "{name} rimosso",
+ "msgUnbanned": "{name} ripristinato",
+ "msgBannedHead": "Rimossi da questa community",
+ "msgUnban": "Ripristina",
"msgNoIdentity": "Il tuo signer nostr non è connesso. Riconnettilo per inviare a tuo nome",
"msgSendFailed": "Nessun relay ha accettato il messaggio",
"msgLockedChat": "Il tuo portafoglio è bloccato, quindi non può firmare i messaggi.",
@@ -488,8 +522,8 @@
"addrRead": "Lettura di {min} min",
"addrList": "Una lista di {name}",
"msgSignerOff": "Il tuo signer nostr non è connesso, quindi non puoi ancora pubblicare a tuo nome.",
- "msgAmberDms": "Hai effettuato l’accesso con Amber: i messaggi inviati a te non possono essere aperti qui, solo quelli che hai inviato da questo dispositivo.",
- "msgAmberConnect": "Connetti Amber",
+ "msgAmberDms": "Hai effettuato l’accesso con un’app di firma: i messaggi inviati a te non possono essere aperti qui, solo quelli inviati da questo dispositivo.",
+ "msgAmberConnect": "Connetti il firmatario",
"postRepostedBy": "{name} ha ripubblicato",
"gifBtnTitle": "Aggiungi una GIF",
"gifSearchPh": "Cerca GIF",
@@ -825,6 +859,10 @@
"giftWelcome": "Ti hanno inviato dei Bitcoin",
"giftBackedUp": "L'ho scritta",
"giftLink": "Regala dei Bitcoin",
+ "giftNotePlaceholder": "Aggiungi un messaggio (facoltativo)",
+ "giftFromMe": "Di’ che è da parte mia (chi lo riscatta ti segue)",
+ "giftFrom": "Da",
+ "giftClaimFollows": "Riscattandolo seguirai questa persona",
"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 +926,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 +1193,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",
@@ -1177,7 +1218,7 @@
"nlSignInNostr": "Accedi con Nostr",
"nlDesc": "Usa il tuo account Nostr per aprire il portafoglio, su qualsiasi dispositivo, con lo stesso account.",
"nlExtension": "Usa l’estensione del browser",
- "nlAmber": "Accedi con Amber (Android)",
+ "nlAmber": "Accedi con un’app di firma (Android)",
"nlAmberWait": "In attesa dell’app di firma… approva lì, poi torna qui.",
"nlAmberPasteHint": "La risposta viene letta dagli appunti al tuo ritorno. Se non succede nulla, incollala qui:",
"nlAmberPastePh": "Incolla la risposta del firmatario",
@@ -1187,7 +1228,7 @@
"nlPasskey": "Accedi con una passkey",
"nlKeyOrBunker": "nsec, chiave privata o bunker://…",
"nlGo": "Accedi",
- "nlHint": "Funziona con Amber, Amethyst e altri firmatari remoti (incolla il loro indirizzo bunker://), o con un’estensione del browser. Una chiave incollata viene usata una sola volta e mai salvata.",
+ "nlHint": "Funziona con le app di firma remota (incolla il loro indirizzo bunker://) o con un’estensione del browser. Una chiave incollata viene usata una volta e mai salvata.",
"nlApprove": "Approva la richiesta nel tuo firmatario →",
"nlUnrecognized": "Non sembra una chiave privata né un indirizzo bunker://.",
"nlNewTitle": "Crea un portafoglio per questo account",
@@ -1208,7 +1249,7 @@
"nlReconnectDesc": "Il tuo signer non è connesso, quindi questa app non può firmare per te. Ricollegalo per pubblicare e aggiornare il profilo. Il portafoglio e il saldo non ne risentono.",
"nlReconnectTitle": "Ricollega il signer",
"nlAmberUpgradeTitle": "Leggi i tuoi messaggi",
- "nlAmberUpgradeBody": "Amber può aprire i messaggi qui solo se è connesso come signer remoto. Tocca qui sotto, approva in Amber (consenti la decifratura) e i messaggi verranno caricati. La firma funziona come prima.",
+ "nlAmberUpgradeBody": "La tua app di firma può aprire i messaggi qui solo se è connessa come firmatario remoto. Tocca qui sotto, approva nell’app di firma (consenti la decifratura) e i messaggi verranno caricati. La firma funziona come prima.",
"nlReconnectBody": "Il tuo signer Nostr non è connesso su questo dispositivo. Ricollegalo per continuare ad agire come {npub}…",
"nlWrongAccount": "Quel signer è di un altro account Nostr. Ricollega {npub}.",
"nlLinked": "Portafoglio collegato al tuo account Nostr",
@@ -1240,6 +1281,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)",
@@ -1458,5 +1500,12 @@
"lockPwOrPassword": "oppure imposta una password:",
"pagerFetchingVideo": "Caricamento del prossimo video…",
"pagerFetchingPictures": "Caricamento di altre immagini…",
- "pagerCaughtUp": "Per ora è tutto"
+ "pagerCaughtUp": "Per ora è tutto",
+ "schedToggle": "Programma per dopo",
+ "schedAt": "Pubblica il",
+ "schedBtn": "Programma",
+ "schedDone": "Programmato per {when}",
+ "schedTooSoon": "Scegli un orario almeno due minuti da adesso",
+ "schedListTitle": "Programmati ({n})",
+ "schedCancelled": "Post programmato annullato"
}
diff --git a/src/locales/ja.json b/src/locales/ja.json
index b8968cc..27970db 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -364,6 +364,10 @@
"giftWelcome": "Bitcoin が届きました",
"giftBackedUp": "書き留めました",
"giftLink": "Bitcoin を贈る",
+ "giftNotePlaceholder": "メッセージを添える(任意)",
+ "giftFromMe": "自分からだと伝える(受け取った人があなたをフォローします)",
+ "giftFrom": "送り主",
+ "giftClaimFollows": "受け取ると送り主をフォローします",
"giftLinkDesc": "金額をリンクとして事前署名します。リンクを開いた人が、その人だけが管理できる真新しいウォレットに Bitcoin を受け取ります。",
"giftLinkWarn": "⚠ このリンクを開いた人は誰でもその金額を受け取れるので、贈る相手とだけ共有してください。金額は少なめにしましょう。",
"giftLinkReveal": "ギフトリンクを作成",
@@ -425,6 +429,7 @@
"claimOr": "または",
"goToWallet": "ウォレットに行く",
"claimBtn": "受け取る",
+ "claimNowBtn": "今すぐ受け取る",
"claimFeeNote": "ふりがな{n} 料金について",
"claimFailed": "このギフトはすでに受け取られたか、現在利用できません。",
"claimNotVisibleBody": "このギフトに資金を調達するコインは、このウォレットのネットワーク/データソースから表示されません。 このウォレットは、送信者と同じネットワークとデータソースを使用していて、もう一度お試しください。",
@@ -618,6 +623,8 @@
"onbSpendBody": "ユーザー名を主張し、独自の支払いアドレスを取得する, 人々は、あなたの名前だけで、即座にビットコインを送ることができます。",
"onbNameWait": "物事を準備する...",
"onbNotNow": "今は今",
+ "onbGiftNameTitle": "次にユーザー名を選びましょう",
+ "onbGiftNameBody": "名前を取得して自分の支払いアドレスを手に入れましょう。名前だけでビットコインを受け取れます。そのあと写真とカバーを選びます。",
"onbAvatarTitle": "お問い合わせ",
"onbAvatarBody": "アバターを選ぶか、自分の写真をアップロードしてください。いつでも変更できます。",
"onbUpload": "写真をアップロードする",
@@ -640,7 +647,7 @@
"nlPasskey": "パスキーでサインイン",
"nlKeyOrBunker": "nsec, プライベートキー, またはバンカー://...",
"nlGo": "ログイン",
- "nlHint": "Amber、Amethyst、その他のリモートサイダー(Bunker://アドレスを貼り付ける)、またはブラウザ拡張で動作します。 過去のキーは一度使用され、貯えられません。",
+ "nlHint": "リモート署名アプリ(bunker:// アドレスを貼り付け)またはブラウザ拡張機能で使えます。貼り付けた鍵は一度だけ使われ、保存されません。",
"nlApprove": "申請書の承認 →",
"nlUnrecognized": "つまり、秘密鍵や2段のアドレスは見えません。",
"nlNewTitle": "このアカウントのウォレットを作成する",
@@ -678,6 +685,7 @@
"namesClaim": "ログイン",
"namesClaimed": "これから {name}",
"namesCopy": "コピーアドレス",
+ "namesChangeTo": "{addr} に変更",
"namesMoreOpen": "その他のオプション",
"namesMoreTitle": "支払われるより多くの方法",
"namesMoreBolt11": "ライトニングインボイス(BOLT 11)",
@@ -878,6 +886,17 @@
"followHistNone": "あなたのリストに欠けている人を含む古いコピーはありません。",
"followHistNothing": "そのコピーの全員がすでにリストにいます。",
"followHistRestored": "{n}人のフォローを復元しました。",
+ "profHistDesc": "別のアプリがプロフィールを置き換えた場合、履歴を保持するリレーに古いコピーが残っていることがあります。使うと、ここで空欄の項目だけが埋まります。",
+ "profHistLook": "古いコピーを探す",
+ "profHistUse": "使う",
+ "profHistNoName": "(名前なし)",
+ "profHistNone": "ここに足りないものを持つ古いコピーはありません。",
+ "profHistNothing": "そのコピーの内容はすべてここにあります。",
+ "profHistFilled": "古いコピーから{n}項目を埋めました。公開するには保存してください。",
+ "profHist_name": "名前",
+ "profHist_about": "自己紹介",
+ "profHist_picture": "写真",
+ "profHist_banner": "バナー",
"securityTitle": "セキュリティ",
"arkCoinsNone": "支出にはまだコインがありません。",
"profKeyLink": "公開鍵",
@@ -910,6 +929,8 @@
"mediaNoImages": "このフィードにはまだ画像がありません。",
"mediaNoVideos": "このフィードにはまだ縦型動画がありません。",
"videoTapToPlay": "タップして再生",
+ "videoPlay": "再生",
+ "videoPause": "一時停止",
"videoLargeTitle": "動画",
"videoLargeToggle": "大きな動画を自動再生",
"videoLargeHelp": "{mb} MBを超える動画や1080pを超える動画は、データを使いすぎないようタップするまで再生しません。低速回線やデータセーバー時は上限が下がります。",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "ラウンドのトランザクションを見る",
"pagerFetchingVideo": "次の動画を取得中…",
"pagerFetchingPictures": "画像をさらに取得中…",
- "pagerCaughtUp": "今のところ以上です"
+ "pagerCaughtUp": "今のところ以上です",
+ "schedToggle": "あとで投稿する",
+ "schedAt": "投稿日時",
+ "schedBtn": "予約する",
+ "schedDone": "{when} に予約しました",
+ "schedTooSoon": "今から2分以上先の時刻を選んでください",
+ "schedListTitle": "予約済み({n})",
+ "schedCancelled": "予約投稿を取り消しました"
}
diff --git a/src/locales/ko.json b/src/locales/ko.json
index e4bf342..94f9f0e 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -363,6 +363,10 @@
"giftWelcome": "Bitcoin을 받았습니다",
"giftBackedUp": "적어 두었습니다",
"giftLink": "Bitcoin 선물하기",
+ "giftNotePlaceholder": "메시지 추가 (선택)",
+ "giftFromMe": "내가 보냈다고 알리기 (받는 사람이 나를 팔로우함)",
+ "giftFrom": "보낸 사람",
+ "giftClaimFollows": "받으면 보낸 사람을 팔로우합니다",
"giftLinkDesc": "금액을 링크로 미리 서명하세요. 링크를 여는 사람은 그 Bitcoin을 자신만 통제하는 완전히 새로운 지갑으로 받게 됩니다.",
"giftLinkWarn": "⚠ 이 링크를 여는 사람은 누구나 금액을 받을 수 있으니, 선물할 상대에게만 공유하세요. 금액은 적게 유지하세요.",
"giftLinkReveal": "선물 링크 만들기",
@@ -424,6 +428,7 @@
"claimOr": "또는",
"goToWallet": "지갑 바로가기",
"claimBtn": "받기",
+ "claimNowBtn": "지금 받기",
"claimFeeNote": "·{n} 요금안내",
"claimFailed": "이 선물은 이미 수령되었거나 더 이상 이용할 수 없습니다.",
"claimNotVisibleBody": "이 선물은 이 지갑의 네트워크/데이터 소스에서 볼 수 없습니다. 이 지갑이 같은 네트워크와 데이터 소스를 보낸 후 다시 시도하십시오.",
@@ -617,6 +622,8 @@
"onbSpendBody": "사용자 이름 및 자신의 지불 주소를 얻기, 사람들은 즉시 Bitcoin을 보낼 수 있습니다, 그냥 당신의 이름.",
"onbNameWait": "준비하는 것들 ...",
"onbNotNow": "현재 위치",
+ "onbGiftNameTitle": "이제 사용자 이름을 고르세요",
+ "onbGiftNameBody": "이름을 등록하고 나만의 결제 주소를 받으세요. 이름만으로 비트코인을 받을 수 있어요. 그다음 사진과 커버를 고르세요.",
"onbAvatarTitle": "자주 묻는 질문",
"onbAvatarBody": "아바타를 선택하거나 사진을 업로드하세요. 언제든지 변경할 수 있습니다.",
"onbUpload": "사진 업로드",
@@ -639,7 +646,7 @@
"nlPasskey": "패스키로 로그인",
"nlKeyOrBunker": "nsec, 개인 키, 또는 벙커://...",
"nlGo": "로그인",
- "nlHint": "Amber, Amethyst 및 기타 원격 Signers와 함께 작동합니다. (이층 http:// 주소) 또는 브라우저 확장. 과거의 열쇠는 한 번 이용되고 결코 저장되지 않습니다.",
+ "nlHint": "원격 서명 앱(bunker:// 주소를 붙여넣기) 또는 브라우저 확장 프로그램과 함께 작동합니다. 붙여넣은 키는 한 번만 사용되며 저장되지 않습니다.",
"nlApprove": "당신의 signer에 있는 요구에 찬성하십시오 →",
"nlUnrecognized": "그것은 개인 키 또는 벙커처럼 보이지 않습니다.:// 주소.",
"nlNewTitle": "이 계정의 지갑 만들기",
@@ -677,6 +684,7 @@
"namesClaim": "계정 만들기",
"namesClaimed": "현재 위치 {name}",
"namesCopy": "본문 바로가기",
+ "namesChangeTo": "{addr}(으)로 변경",
"namesMoreOpen": "더 많은 옵션",
"namesMoreTitle": "지불하는 방법",
"namesMoreBolt11": "번개 송장 (BOLT 11)",
@@ -877,6 +885,17 @@
"followHistNone": "목록에 빠진 사람이 들어 있는 예전 사본이 없습니다.",
"followHistNothing": "그 사본의 모든 사람이 이미 목록에 있습니다.",
"followHistRestored": "팔로우 {n}명을 복원했습니다.",
+ "profHistDesc": "다른 앱이 프로필을 덮어썼다면, 기록을 보관하는 릴레이에 이전 사본이 남아 있을 수 있습니다. 사용하면 여기서 비어 있는 항목만 채웁니다.",
+ "profHistLook": "이전 사본 찾기",
+ "profHistUse": "사용",
+ "profHistNoName": "(이름 없음)",
+ "profHistNone": "여기에 없는 내용을 가진 이전 사본이 없습니다.",
+ "profHistNothing": "그 사본의 내용은 모두 이미 여기에 있습니다.",
+ "profHistFilled": "이전 사본에서 {n}개 항목을 채웠습니다. 게시하려면 저장하세요.",
+ "profHist_name": "이름",
+ "profHist_about": "소개",
+ "profHist_picture": "사진",
+ "profHist_banner": "배너",
"securityTitle": "보안",
"arkCoinsNone": "지출에 아직 코인이 없습니다.",
"profKeyLink": "공개 키",
@@ -909,6 +928,8 @@
"mediaNoImages": "이 피드에는 아직 이미지가 없습니다.",
"mediaNoVideos": "이 피드에는 아직 세로 동영상이 없습니다.",
"videoTapToPlay": "탭하여 재생",
+ "videoPlay": "재생",
+ "videoPause": "일시정지",
"videoLargeTitle": "동영상",
"videoLargeToggle": "큰 동영상 자동 재생",
"videoLargeHelp": "{mb}MB를 넘거나 1080p보다 높은 동영상은 데이터를 아끼기 위해 탭할 때까지 기다립니다. 느린 연결이나 데이터 절약 모드에서는 한도가 더 낮습니다.",
@@ -923,5 +944,12 @@
"arkRenewViewTx": "라운드 거래 보기",
"pagerFetchingVideo": "다음 동영상을 가져오는 중…",
"pagerFetchingPictures": "사진을 더 가져오는 중…",
- "pagerCaughtUp": "지금은 여기까지예요"
+ "pagerCaughtUp": "지금은 여기까지예요",
+ "schedToggle": "나중에 게시 예약",
+ "schedAt": "게시 시간",
+ "schedBtn": "예약",
+ "schedDone": "{when}에 예약됨",
+ "schedTooSoon": "지금부터 최소 2분 뒤의 시간을 고르세요",
+ "schedListTitle": "예약됨 ({n})",
+ "schedCancelled": "예약 게시물이 취소되었습니다"
}
diff --git a/src/locales/mr.json b/src/locales/mr.json
index 17ee1d5..a7ad2b4 100644
--- a/src/locales/mr.json
+++ b/src/locales/mr.json
@@ -137,6 +137,10 @@
"giftSkip": "आत्ता वगळा",
"giftBackedUp": "मी ते लिहून ठेवले आहे",
"giftLink": "थोडे Bitcoin भेट द्या",
+ "giftNotePlaceholder": "एक नोंद जोडा (पर्यायी)",
+ "giftFromMe": "हे माझ्याकडून आहे असे सांगा (दावा करणारे तुम्हाला फॉलो करतील)",
+ "giftFrom": "पाठवणारे",
+ "giftClaimFollows": "दावा केल्यावर तुम्ही त्यांना फॉलो कराल",
"giftLinkDesc": "एखादी रक्कम लिंक म्हणून आधीच स्वाक्षरित करा. ती उघडणारा कोणीही ते Bitcoin फक्त त्याच्याच नियंत्रणातील एका नव्या कोऱ्या वॉलेटमध्ये घेतो.",
"giftLinkWarn": "⚠ ही लिंक उघडणारा कोणीही ती रक्कम घेऊ शकतो, म्हणून ज्याला भेट देत आहात फक्त त्याच्यासोबतच ती शेअर करा. रक्कम कमी ठेवा.",
"giftAmountLabel": "भेट देण्याची रक्कम",
@@ -145,6 +149,7 @@
"giftReserved": "दावा न केलेल्या भेट लिंक ({n})",
"claimBody": "ते फक्त तुमच्याच नियंत्रणातील एका नव्या कोऱ्या वॉलेटमध्ये घ्या.",
"claimBtn": "ते घ्या",
+ "claimNowBtn": "आता घ्या",
"claimFailed": "ही भेट आधीच घेतली गेली आहे किंवा आता उपलब्ध नाही.",
"claimedTitle": "घेतले!",
"claimedBody": "तुमचे Bitcoin येत आहे. ते सुरक्षित ठेवण्यासाठी तुमच्या रिकव्हरी वाक्यांशाचा बॅकअप घ्या.",
@@ -215,6 +220,17 @@
"followHistNone": "तुमच्या यादीत नसलेले कोणी असलेली जुनी प्रत नाही.",
"followHistNothing": "त्या प्रतीतील सर्वजण आधीच तुमच्या यादीत आहेत.",
"followHistRestored": "{n} फॉलो पुनर्संचयित केले.",
+ "profHistDesc": "दुसऱ्या अ‍ॅपने तुमची प्रोफाइल बदलली असेल, तर इतिहास ठेवणाऱ्या रिलेवर जुनी प्रत अजूनही असू शकते. ती वापरल्यास येथे फक्त रिकामी फील्ड भरली जातात.",
+ "profHistLook": "जुन्या प्रती शोधा",
+ "profHistUse": "वापरा",
+ "profHistNoName": "(नाव नाही)",
+ "profHistNone": "कोणत्याही जुन्या प्रतीत येथे नसलेले काही नाही.",
+ "profHistNothing": "त्या प्रतीतील सर्व काही येथे आधीच आहे.",
+ "profHistFilled": "जुन्या प्रतीतून {n} फील्ड भरली. प्रकाशित करण्यासाठी जतन करा.",
+ "profHist_name": "नाव",
+ "profHist_about": "परिचय",
+ "profHist_picture": "फोटो",
+ "profHist_banner": "बॅनर",
"securityTitle": "सुरक्षा",
"arkCoinsNone": "स्पेंडिंगमध्ये अद्याप कोणतेही कॉइन नाहीत.",
"profKeyLink": "सार्वजनिक की",
@@ -247,6 +263,8 @@
"mediaNoImages": "या फीडमध्ये अजून चित्रे नाहीत.",
"mediaNoVideos": "या फीडमध्ये अजून उभे व्हिडिओ नाहीत.",
"videoTapToPlay": "चालवण्यासाठी टॅप करा",
+ "videoPlay": "चालवा",
+ "videoPause": "थांबवा",
"videoLargeTitle": "व्हिडिओ",
"videoLargeToggle": "मोठे व्हिडिओ आपोआप चालवा",
"videoLargeHelp": "{mb} MB पेक्षा मोठे किंवा 1080p पेक्षा वरचे व्हिडिओ तुमचा डेटा वाचवण्यासाठी टॅपची वाट पाहतात. धीम्या किंवा डेटा-सेव्हर कनेक्शनवर मर्यादा कमी असते.",
@@ -261,5 +279,15 @@
"arkRenewViewTx": "राउंडचा व्यवहार पहा",
"pagerFetchingVideo": "पुढचा व्हिडिओ आणत आहे…",
"pagerFetchingPictures": "आणखी चित्रे आणत आहे…",
- "pagerCaughtUp": "सध्या एवढेच"
+ "pagerCaughtUp": "सध्या एवढेच",
+ "onbGiftNameTitle": "आता एक युजरनेम निवडा",
+ "onbGiftNameBody": "एक नाव घ्या आणि स्वतःचा पेमेंट पत्ता मिळवा, म्हणजे लोक फक्त तुमच्या नावाने तुम्हाला बिटकॉइन पाठवू शकतील. मग एक फोटो आणि कव्हर निवडा.",
+ "namesChangeTo": "{addr} मध्ये बदला",
+ "schedToggle": "नंतरसाठी वेळ ठरवा",
+ "schedAt": "पोस्टची वेळ",
+ "schedBtn": "वेळ ठरवा",
+ "schedDone": "{when} साठी ठरवले",
+ "schedTooSoon": "आतापासून किमान दोन मिनिटांनंतरची वेळ निवडा",
+ "schedListTitle": "ठरवलेल्या ({n})",
+ "schedCancelled": "ठरवलेली पोस्ट रद्द झाली"
}
diff --git a/src/locales/pt.json b/src/locales/pt.json
index 11ff22c..56e8cda 100644
--- a/src/locales/pt.json
+++ b/src/locales/pt.json
@@ -364,6 +364,10 @@
"giftWelcome": "Você recebeu Bitcoin",
"giftBackedUp": "Já anotei",
"giftLink": "Presentear Bitcoin",
+ "giftNotePlaceholder": "Adicione um recado (opcional)",
+ "giftFromMe": "Dizer que é meu (quem resgatar vai te seguir)",
+ "giftFrom": "De",
+ "giftClaimFollows": "Ao resgatar, você passa a seguir essa pessoa",
"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 +429,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 +623,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",
@@ -640,7 +647,7 @@
"nlPasskey": "Entrar com uma chave-mestra",
"nlKeyOrBunker": "Nsec, chave privada, ou bunker://...",
"nlGo": "Entrar",
- "nlHint": "Funciona com Amber, Amethyst e outros sinalizadores remotos (colar seu bunker://endereço), ou uma extensão do navegador. Uma chave colada é usada uma vez e nunca armazenada.",
+ "nlHint": "Funciona com apps de assinatura remota (cole o endereço bunker:// delas) ou uma extensão do navegador. Uma chave colada é usada uma vez e nunca guardada.",
"nlApprove": "Aprovar o pedido em seu assinante →",
"nlUnrecognized": "Isso não se parece com uma chave privada ou um endereço bunker://.",
"nlNewTitle": "Criar uma carteira para esta conta",
@@ -678,6 +685,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)",
@@ -878,6 +886,17 @@
"followHistNone": "Nenhuma cópia antiga tem alguém que falte na sua lista.",
"followHistNothing": "Todos dessa cópia já estão na sua lista.",
"followHistRestored": "{n} seguidos restaurados.",
+ "profHistDesc": "Se outro app substituiu seu perfil, uma cópia mais antiga ainda pode estar em um relay que guarda histórico. Usá-la preenche apenas os campos que estão vazios aqui.",
+ "profHistLook": "Procurar cópias mais antigas",
+ "profHistUse": "Usar",
+ "profHistNoName": "(sem nome)",
+ "profHistNone": "Nenhuma cópia mais antiga tem algo que falte aqui.",
+ "profHistNothing": "Tudo dessa cópia já está aqui.",
+ "profHistFilled": "{n} campos preenchidos da cópia mais antiga. Salve para publicar.",
+ "profHist_name": "nome",
+ "profHist_about": "bio",
+ "profHist_picture": "foto",
+ "profHist_banner": "capa",
"securityTitle": "Segurança",
"arkCoinsNone": "Ainda não há moedas em Gastos.",
"profKeyLink": "Chave pública",
@@ -910,6 +929,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.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "Ver a transação da rodada",
"pagerFetchingVideo": "Buscando o próximo vídeo…",
"pagerFetchingPictures": "Buscando mais imagens…",
- "pagerCaughtUp": "Por enquanto é só isso"
+ "pagerCaughtUp": "Por enquanto é só isso",
+ "schedToggle": "Agendar para depois",
+ "schedAt": "Publicar em",
+ "schedBtn": "Agendar",
+ "schedDone": "Agendado para {when}",
+ "schedTooSoon": "Escolha um horário pelo menos dois minutos a partir de agora",
+ "schedListTitle": "Agendados ({n})",
+ "schedCancelled": "Publicação agendada cancelada"
}
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 0f2936d..7ec23b3 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -364,6 +364,10 @@
"giftWelcome": "Вам отправили Bitcoin",
"giftBackedUp": "Я записал(а)",
"giftLink": "Подарить немного Bitcoin",
+ "giftNotePlaceholder": "Добавьте записку (необязательно)",
+ "giftFromMe": "Указать, что это от меня (получатель подпишется на вас)",
+ "giftFrom": "От",
+ "giftClaimFollows": "Получив подарок, вы подпишетесь на отправителя",
"giftLinkDesc": "Заранее подпишите сумму в виде ссылки. Тот, кто откроет её, получит Bitcoin в совершенно новый кошелёк, которым управляет только он.",
"giftLinkWarn": "⚠ Любой, кто откроет эту ссылку, может получить эту сумму, поэтому делитесь ею только с тем, кому дарите. Держите суммы небольшими.",
"giftLinkReveal": "Создать ссылку-подарок",
@@ -425,6 +429,7 @@
"claimOr": "или",
"goToWallet": "Иди к кошельку",
"claimBtn": "Получить",
+ "claimNowBtn": "Получить сейчас",
"claimFeeNote": "~{n} взнос",
"claimFailed": "Этот подарок уже получен или больше недоступен.",
"claimNotVisibleBody": "Монеты, финансирующие этот подарок, не видны из сети / источника данных этого кошелька. Убедитесь, что этот кошелек использует ту же сеть и источник данных, что и отправитель.",
@@ -618,6 +623,8 @@
"onbSpendBody": "Заявите имя пользователя и получите свой собственный платежный адрес, люди могут отправить вам биткойн мгновенно, только с вашим именем.",
"onbNameWait": "Готовить вещи...",
"onbNotNow": "Не сейчас",
+ "onbGiftNameTitle": "Теперь выберите имя пользователя",
+ "onbGiftNameBody": "Займите имя и получите свой платёжный адрес — тогда вам смогут отправлять биткоин просто по имени. Потом выберите фото и обложку.",
"onbAvatarTitle": "Выберите свой взгляд",
"onbAvatarBody": "Выберите аватар или загрузите свою фотографию. Его можно изменить в любое время.",
"onbUpload": "Загрузить фото",
@@ -640,7 +647,7 @@
"nlPasskey": "Зарегистрируйтесь с Passkey",
"nlKeyOrBunker": "nsec, закрытый ключ или бункер:",
"nlGo": "Входите.",
- "nlHint": "Работает с Amber, Amethyst и другими удаленными подписчиками (вставьте их бункер://адрес) или расширение браузера. Вставленный ключ используется один раз и никогда не хранится.",
+ "nlHint": "Работает с приложениями удалённой подписи (вставьте их адрес bunker://) или с расширением браузера. Вставленный ключ используется один раз и никогда не сохраняется.",
"nlApprove": "Утвердить запрос в вашем подписчике",
"nlUnrecognized": "Это не похоже на закрытый ключ или бункер:",
"nlNewTitle": "Создайте кошелек для этого аккаунта",
@@ -678,6 +685,7 @@
"namesClaim": "Претензия",
"namesClaimed": "Ты теперь {name}",
"namesCopy": "Адрес копии",
+ "namesChangeTo": "Сменить на {addr}",
"namesMoreOpen": "Больше вариантов",
"namesMoreTitle": "Больше способов получить оплату",
"namesMoreBolt11": "Инвойс молнии (BOLT 11)",
@@ -878,6 +886,17 @@
"followHistNone": "Нет старых копий с людьми, которых не хватает в вашем списке.",
"followHistNothing": "Все из этой копии уже есть в вашем списке.",
"followHistRestored": "Восстановлено подписок: {n}.",
+ "profHistDesc": "Если другое приложение заменило ваш профиль, более старая копия может ещё храниться на релее с историей. Её использование заполняет только пустые здесь поля.",
+ "profHistLook": "Поискать старые копии",
+ "profHistUse": "Использовать",
+ "profHistNoName": "(без имени)",
+ "profHistNone": "Ни в одной старой копии нет того, чего здесь не хватает.",
+ "profHistNothing": "Всё из этой копии уже здесь.",
+ "profHistFilled": "Заполнено полей из старой копии: {n}. Сохраните, чтобы опубликовать.",
+ "profHist_name": "имя",
+ "profHist_about": "о себе",
+ "profHist_picture": "фото",
+ "profHist_banner": "баннер",
"securityTitle": "Безопасность",
"arkCoinsNone": "В расходах пока нет монет.",
"profKeyLink": "Открытый ключ",
@@ -910,6 +929,8 @@
"mediaNoImages": "В этой ленте пока нет фото.",
"mediaNoVideos": "В этой ленте пока нет вертикальных видео.",
"videoTapToPlay": "Нажмите, чтобы воспроизвести",
+ "videoPlay": "Воспроизвести",
+ "videoPause": "Пауза",
"videoLargeTitle": "Видео",
"videoLargeToggle": "Автовоспроизведение больших видео",
"videoLargeHelp": "Видео больше {mb} МБ или выше 1080p ждут нажатия, чтобы лента не съедала трафик. На медленном соединении или в режиме экономии лимит ниже.",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "Посмотреть транзакцию раунда",
"pagerFetchingVideo": "Загружаем следующее видео…",
"pagerFetchingPictures": "Загружаем ещё картинки…",
- "pagerCaughtUp": "Пока это всё"
+ "pagerCaughtUp": "Пока это всё",
+ "schedToggle": "Запланировать",
+ "schedAt": "Опубликовать",
+ "schedBtn": "Запланировать",
+ "schedDone": "Запланировано на {when}",
+ "schedTooSoon": "Выберите время не раньше чем через две минуты",
+ "schedListTitle": "Запланировано ({n})",
+ "schedCancelled": "Запланированный пост отменён"
}
diff --git a/src/locales/sw.json b/src/locales/sw.json
index b130faf..e5aba2e 100644
--- a/src/locales/sw.json
+++ b/src/locales/sw.json
@@ -137,6 +137,10 @@
"giftSkip": "Ruka kwa sasa",
"giftBackedUp": "Nimeshakiandika",
"giftLink": "Toa Bitcoin kama zawadi",
+ "giftNotePlaceholder": "Ongeza ujumbe (si lazima)",
+ "giftFromMe": "Sema ni kutoka kwangu (atakayedai atakufuata)",
+ "giftFrom": "Kutoka kwa",
+ "giftClaimFollows": "Ukidai utamfuata",
"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 +149,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.",
@@ -215,6 +220,17 @@
"followHistNone": "Hakuna nakala ya zamani yenye mtu anayekosekana kwenye orodha yako.",
"followHistNothing": "Wote kwenye nakala hiyo tayari wamo kwenye orodha yako.",
"followHistRestored": "Umerejesha unaowafuata {n}.",
+ "profHistDesc": "Ikiwa programu nyingine ilibadilisha wasifu wako, nakala ya zamani huenda bado iko kwenye relay inayohifadhi historia. Kuitumia hujaza tu sehemu zilizo tupu hapa.",
+ "profHistLook": "Tafuta nakala za zamani",
+ "profHistUse": "Tumia",
+ "profHistNoName": "(hakuna jina)",
+ "profHistNone": "Hakuna nakala ya zamani iliyo na kitu kinachokosekana hapa.",
+ "profHistNothing": "Kila kitu kwenye nakala hiyo tayari kipo hapa.",
+ "profHistFilled": "Sehemu {n} zimejazwa kutoka nakala ya zamani. Hifadhi ili kuchapisha.",
+ "profHist_name": "jina",
+ "profHist_about": "wasifu",
+ "profHist_picture": "picha",
+ "profHist_banner": "bango",
"securityTitle": "Usalama",
"arkCoinsNone": "Bado hakuna sarafu kwenye Matumizi.",
"profKeyLink": "Ufunguo wa umma",
@@ -247,6 +263,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 +279,15 @@
"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}",
+ "schedToggle": "Panga kwa baadaye",
+ "schedAt": "Chapisha saa",
+ "schedBtn": "Panga",
+ "schedDone": "Imepangwa {when}",
+ "schedTooSoon": "Chagua muda angalau dakika mbili kuanzia sasa",
+ "schedListTitle": "Zilizopangwa ({n})",
+ "schedCancelled": "Chapisho lililopangwa limeghairiwa"
}
diff --git a/src/locales/ta.json b/src/locales/ta.json
index da4e5b0..a15043d 100644
--- a/src/locales/ta.json
+++ b/src/locales/ta.json
@@ -137,6 +137,10 @@
"giftSkip": "இப்போதைக்குத் தவிர்",
"giftBackedUp": "நான் எழுதி வைத்துவிட்டேன்",
"giftLink": "கொஞ்சம் Bitcoin பரிசளி",
+ "giftNotePlaceholder": "ஒரு குறிப்பைச் சேர்க்கவும் (விருப்பம்)",
+ "giftFromMe": "இது என்னிடமிருந்து என்று சொல் (பெறுபவர் உங்களைப் பின்தொடர்வார்)",
+ "giftFrom": "அனுப்பியவர்",
+ "giftClaimFollows": "பெற்றால் அவரைப் பின்தொடர்வீர்கள்",
"giftLinkDesc": "ஒரு தொகையை இணைப்பாக முன்கூட்டியே கையொப்பமிடுங்கள். இதைத் திறப்பவர், அவர்கள் மட்டுமே கட்டுப்படுத்தும் புத்தம்புதிய வாலட்டிற்குள் Bitcoin-ஐ உரிமை கொள்வார்கள்.",
"giftLinkWarn": "⚠ இந்த இணைப்பைத் திறக்கும் எவரும் தொகையை உரிமை கொள்ளலாம், எனவே நீங்கள் பரிசளிக்கும் நபருடன் மட்டுமே இதைப் பகிரவும். தொகையைக் குறைவாக வைத்திருங்கள்.",
"giftAmountLabel": "பரிசளிக்கும் தொகை",
@@ -145,6 +149,7 @@
"giftReserved": "கோரப்படாத பரிசு இணைப்புகள் ({n})",
"claimBody": "நீங்கள் மட்டுமே கட்டுப்படுத்தும் புத்தம்புதிய வாலட்டிற்குள் இதை உரிமை கொள்ளுங்கள்.",
"claimBtn": "உரிமை கொள்",
+ "claimNowBtn": "இப்போதே பெறுங்கள்",
"claimFailed": "இந்தப் பரிசு ஏற்கனவே உரிமை கொள்ளப்பட்டுவிட்டது அல்லது இனி கிடைக்கவில்லை.",
"claimedTitle": "உரிமை கொள்ளப்பட்டது!",
"claimedBody": "உங்கள் Bitcoin வந்துகொண்டிருக்கிறது. அதைப் பாதுகாப்பாக வைக்க உங்கள் மீட்பு சொற்றொடரைக் காப்புப்பிரதி எடுங்கள்.",
@@ -215,6 +220,17 @@
"followHistNone": "உங்கள் பட்டியலில் இல்லாதவர் உள்ள பழைய நகல் இல்லை.",
"followHistNothing": "அந்த நகலில் உள்ள அனைவரும் ஏற்கனவே உங்கள் பட்டியலில் உள்ளனர்.",
"followHistRestored": "{n} பின்தொடர்வுகள் மீட்டெடுக்கப்பட்டன.",
+ "profHistDesc": "வேறு ஒரு செயலி உங்கள் சுயவிவரத்தை மாற்றியிருந்தால், வரலாற்றை வைத்திருக்கும் ரிலேயில் பழைய நகல் இன்னும் இருக்கலாம். அதைப் பயன்படுத்தினால் இங்கே காலியாக உள்ள புலங்கள் மட்டும் நிரப்பப்படும்.",
+ "profHistLook": "பழைய நகல்களைத் தேடு",
+ "profHistUse": "பயன்படுத்து",
+ "profHistNoName": "(பெயர் இல்லை)",
+ "profHistNone": "இங்கே இல்லாத எதுவும் எந்தப் பழைய நகலிலும் இல்லை.",
+ "profHistNothing": "அந்த நகலில் உள்ள அனைத்தும் ஏற்கனவே இங்கே உள்ளன.",
+ "profHistFilled": "பழைய நகலிலிருந்து {n} புலங்கள் நிரப்பப்பட்டன. வெளியிட சேமிக்கவும்.",
+ "profHist_name": "பெயர்",
+ "profHist_about": "அறிமுகம்",
+ "profHist_picture": "படம்",
+ "profHist_banner": "பேனர்",
"securityTitle": "பாதுகாப்பு",
"arkCoinsNone": "செலவுக் கணக்கில் இன்னும் நாணயங்கள் இல்லை.",
"profKeyLink": "பொது விசை",
@@ -247,6 +263,8 @@
"mediaNoImages": "இந்த ஊட்டத்தில் இன்னும் படங்கள் இல்லை.",
"mediaNoVideos": "இந்த ஊட்டத்தில் இன்னும் செங்குத்து வீடியோக்கள் இல்லை.",
"videoTapToPlay": "இயக்கத் தட்டவும்",
+ "videoPlay": "இயக்கு",
+ "videoPause": "இடைநிறுத்து",
"videoLargeTitle": "வீடியோக்கள்",
"videoLargeToggle": "பெரிய வீடியோக்களைத் தானாக இயக்கு",
"videoLargeHelp": "{mb} MB-க்கு மேல் அல்லது 1080p-க்கு மேலான வீடியோக்கள் உங்கள் டேட்டாவைச் சேமிக்க, தட்டும் வரை காத்திருக்கும். மெதுவான அல்லது டேட்டா சேமிப்பு இணைப்பில் வரம்பு குறைவு.",
@@ -261,5 +279,15 @@
"arkRenewViewTx": "சுற்றின் பரிவர்த்தனையைக் காண்க",
"pagerFetchingVideo": "அடுத்த வீடியோவைப் பெறுகிறது…",
"pagerFetchingPictures": "மேலும் படங்களைப் பெறுகிறது…",
- "pagerCaughtUp": "இப்போதைக்கு இவ்வளவுதான்"
+ "pagerCaughtUp": "இப்போதைக்கு இவ்வளவுதான்",
+ "onbGiftNameTitle": "இப்போது ஒரு பயனர்பெயரைத் தேர்ந்தெடுங்கள்",
+ "onbGiftNameBody": "ஒரு பெயரைப் பெற்று உங்கள் சொந்த பணம் பெறும் முகவரியைப் பெறுங்கள்; உங்கள் பெயரை மட்டும் வைத்தே மற்றவர்கள் பிட்காயின் அனுப்பலாம். பிறகு ஒரு படத்தையும் அட்டைப்படத்தையும் தேர்ந்தெடுங்கள்.",
+ "namesChangeTo": "{addr} ஆக மாற்று",
+ "schedToggle": "பின்னர் இடுகையிட திட்டமிடு",
+ "schedAt": "இடுகை நேரம்",
+ "schedBtn": "திட்டமிடு",
+ "schedDone": "{when} க்கு திட்டமிடப்பட்டது",
+ "schedTooSoon": "இப்போதிலிருந்து குறைந்தது இரண்டு நிமிடங்களுக்குப் பிந்தைய நேரத்தைத் தேர்ந்தெடுக்கவும்",
+ "schedListTitle": "திட்டமிடப்பட்டவை ({n})",
+ "schedCancelled": "திட்டமிட்ட இடுகை ரத்து செய்யப்பட்டது"
}
diff --git a/src/locales/te.json b/src/locales/te.json
index 7e60eaf..2f6c298 100644
--- a/src/locales/te.json
+++ b/src/locales/te.json
@@ -137,6 +137,10 @@
"giftSkip": "ప్రస్తుతానికి దాటవేయి",
"giftBackedUp": "నేను దాన్ని రాసుకున్నాను",
"giftLink": "కొంత Bitcoin బహుమతిగా ఇవ్వండి",
+ "giftNotePlaceholder": "ఒక సందేశం జోడించండి (ఐచ్ఛికం)",
+ "giftFromMe": "ఇది నా నుండి అని చెప్పు (క్లెయిమ్ చేసినవారు మిమ్మల్ని ఫాలో అవుతారు)",
+ "giftFrom": "పంపినవారు",
+ "giftClaimFollows": "క్లెయిమ్ చేస్తే వారిని ఫాలో అవుతారు",
"giftLinkDesc": "ఒక మొత్తాన్ని ముందుగా సంతకం చేసి లింక్‌గా ఇవ్వండి. దాన్ని తెరిచినవారు ఆ Bitcoinను తాము మాత్రమే నియంత్రించే సరికొత్త వాలెట్‌లోకి క్లెయిమ్ చేసుకుంటారు.",
"giftLinkWarn": "⚠ ఈ లింక్ తెరిచిన ఎవరైనా ఆ మొత్తాన్ని క్లెయిమ్ చేయగలరు, కాబట్టి మీరు బహుమతి ఇస్తున్న వ్యక్తికి మాత్రమే దీన్ని పంచుకోండి. మొత్తాలను తక్కువగా ఉంచండి.",
"giftAmountLabel": "బహుమతిగా ఇచ్చే మొత్తం",
@@ -145,6 +149,7 @@
"giftReserved": "దావా చేయని బహుమతి లింకులు ({n})",
"claimBody": "మీరు మాత్రమే నియంత్రించే సరికొత్త వాలెట్‌లోకి దాన్ని క్లెయిమ్ చేసుకోండి.",
"claimBtn": "క్లెయిమ్ చేసుకోండి",
+ "claimNowBtn": "ఇప్పుడే పొందండి",
"claimFailed": "ఈ బహుమతి ఇప్పటికే క్లెయిమ్ చేయబడింది లేదా ఇక అందుబాటులో లేదు.",
"claimedTitle": "క్లెయిమ్ అయింది!",
"claimedBody": "మీ Bitcoin మీ వద్దకు వస్తోంది. దాన్ని సురక్షితంగా ఉంచడానికి మీ రికవరీ ఫ్రేజ్‌ను బ్యాకప్ చేయండి.",
@@ -213,6 +218,17 @@
"followHistNone": "మీ జాబితాలో లేని వ్యక్తి ఉన్న పాత కాపీ ఏదీ లేదు.",
"followHistNothing": "ఆ కాపీలోని అందరూ ఇప్పటికే మీ జాబితాలో ఉన్నారు.",
"followHistRestored": "{n} ఫాలోలు పునరుద్ధరించబడ్డాయి.",
+ "profHistDesc": "మరో యాప్ మీ ప్రొఫైల్‌ను మార్చేస్తే, చరిత్రను ఉంచే రిలేలో పాత కాపీ ఇంకా ఉండవచ్చు. దాన్ని వాడితే ఇక్కడ ఖాళీగా ఉన్న ఫీల్డ్‌లు మాత్రమే నిండుతాయి.",
+ "profHistLook": "పాత కాపీలను వెతకండి",
+ "profHistUse": "వాడండి",
+ "profHistNoName": "(పేరు లేదు)",
+ "profHistNone": "ఇక్కడ లేనిది ఏ పాత కాపీలోనూ లేదు.",
+ "profHistNothing": "ఆ కాపీలో ఉన్నదంతా ఇప్పటికే ఇక్కడ ఉంది.",
+ "profHistFilled": "పాత కాపీ నుండి {n} ఫీల్డ్‌లు నింపబడ్డాయి. ప్రచురించడానికి సేవ్ చేయండి.",
+ "profHist_name": "పేరు",
+ "profHist_about": "పరిచయం",
+ "profHist_picture": "ఫోటో",
+ "profHist_banner": "బ్యానర్",
"securityTitle": "భద్రత",
"arkCoinsNone": "ఖర్చు ఖాతాలో ఇంకా నాణేలు లేవు.",
"profKeyLink": "పబ్లిక్ కీ",
@@ -245,6 +261,8 @@
"mediaNoImages": "ఈ ఫీడ్‌లో ఇంకా చిత్రాలు లేవు.",
"mediaNoVideos": "ఈ ఫీడ్‌లో ఇంకా నిలువు వీడియోలు లేవు.",
"videoTapToPlay": "ప్లే చేయడానికి నొక్కండి",
+ "videoPlay": "ప్లే",
+ "videoPause": "పాజ్",
"videoLargeTitle": "వీడియోలు",
"videoLargeToggle": "పెద్ద వీడియోలను ఆటో‌ప్లే చేయి",
"videoLargeHelp": "{mb} MB కంటే పెద్దవి లేదా 1080p పైబడిన వీడియోలు మీ డేటా ఆదా కోసం నొక్కే వరకు ఆగుతాయి. నెమ్మదైన లేదా డేటా సేవర్ కనెక్షన్‌లో పరిమితి తక్కువ.",
@@ -259,5 +277,15 @@
"arkRenewViewTx": "రౌండ్ లావాదేవీని చూడండి",
"pagerFetchingVideo": "తదుపరి వీడియోను తెస్తోంది…",
"pagerFetchingPictures": "మరిన్ని చిత్రాలను తెస్తోంది…",
- "pagerCaughtUp": "ప్రస్తుతానికి ఇంతే"
+ "pagerCaughtUp": "ప్రస్తుతానికి ఇంతే",
+ "onbGiftNameTitle": "ఇప్పుడు ఒక యూజర్‌నేమ్ ఎంచుకోండి",
+ "onbGiftNameBody": "ఒక పేరు తీసుకుని మీ సొంత చెల్లింపు చిరునామా పొందండి, అప్పుడు మీ పేరుతోనే ఎవరైనా మీకు బిట్‌కాయిన్ పంపవచ్చు. తర్వాత ఒక ఫోటో, ఒక కవర్ ఎంచుకోండి.",
+ "namesChangeTo": "{addr}కి మార్చు",
+ "schedToggle": "తర్వాత కోసం షెడ్యూల్ చేయండి",
+ "schedAt": "పోస్ట్ సమయం",
+ "schedBtn": "షెడ్యూల్ చేయండి",
+ "schedDone": "{when}కి షెడ్యూల్ చేయబడింది",
+ "schedTooSoon": "ఇప్పటి నుండి కనీసం రెండు నిమిషాల తర్వాతి సమయాన్ని ఎంచుకోండి",
+ "schedListTitle": "షెడ్యూల్ చేసినవి ({n})",
+ "schedCancelled": "షెడ్యూల్ చేసిన పోస్ట్ రద్దయింది"
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 1e60eeb..407bcc0 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -363,6 +363,10 @@
"giftWelcome": "Size Bitcoin gönderildi",
"giftBackedUp": "Yazdım",
"giftLink": "Bitcoin hediye et",
+ "giftNotePlaceholder": "Not ekle (isteğe bağlı)",
+ "giftFromMe": "Benden olduğunu söyle (alan seni takip eder)",
+ "giftFrom": "Gönderen",
+ "giftClaimFollows": "Alınca gönderen kişiyi takip edersin",
"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 +428,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 +622,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",
@@ -639,7 +646,7 @@
"nlPasskey": "Sign in with a passkey",
"nlKeyOrBunker": "nsec, private key, or bunker:",
"nlGo": "Giriş yapın",
- "nlHint": "Amber, Amethyst ve diğer uzaktan işaretçileri ile çalışır (bunker'ı http adrese atlar), veya bir tarayıcı uzatması. Bir geçmiş anahtar bir kez kullanılır ve asla depolanmaz.",
+ "nlHint": "Uzaktan imzalama uygulamalarıyla (bunker:// adreslerini yapıştırın) veya bir tarayıcı eklentisiyle çalışır. Yapıştırılan anahtar bir kez kullanılır ve asla saklanmaz.",
"nlApprove": "Approve the request in your signer",
"nlUnrecognized": "Bu özel bir anahtar ya da bir bunker gibi görünmüyor:",
"nlNewTitle": "Bu hesap için bir cüzdan oluşturun",
@@ -677,6 +684,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)",
@@ -877,6 +885,17 @@
"followHistNone": "Hiçbir eski kopyada listende eksik olan biri yok.",
"followHistNothing": "O kopyadaki herkes zaten listende.",
"followHistRestored": "{n} takip geri yüklendi.",
+ "profHistDesc": "Başka bir uygulama profilinizi değiştirdiyse, geçmişi saklayan bir relayde daha eski bir kopya hâlâ olabilir. Birini kullanmak yalnızca burada boş olan alanları doldurur.",
+ "profHistLook": "Eski kopyaları ara",
+ "profHistUse": "Kullan",
+ "profHistNoName": "(adsız)",
+ "profHistNone": "Hiçbir eski kopyada burada eksik olan bir şey yok.",
+ "profHistNothing": "O kopyadaki her şey zaten burada.",
+ "profHistFilled": "Eski kopyadan {n} alan dolduruldu. Yayınlamak için kaydedin.",
+ "profHist_name": "ad",
+ "profHist_about": "hakkında",
+ "profHist_picture": "fotoğraf",
+ "profHist_banner": "kapak",
"securityTitle": "Güvenlik",
"arkCoinsNone": "Harcama’da henüz coin yok.",
"profKeyLink": "Açık anahtar",
@@ -909,6 +928,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.",
@@ -923,5 +944,12 @@
"arkRenewViewTx": "Turun işlemini görüntüle",
"pagerFetchingVideo": "Sonraki video getiriliyor…",
"pagerFetchingPictures": "Daha fazla resim getiriliyor…",
- "pagerCaughtUp": "Şimdilik bu kadar"
+ "pagerCaughtUp": "Şimdilik bu kadar",
+ "schedToggle": "Sonrası için zamanla",
+ "schedAt": "Paylaşım zamanı",
+ "schedBtn": "Zamanla",
+ "schedDone": "{when} için zamanlandı",
+ "schedTooSoon": "Şu andan en az iki dakika sonrasını seç",
+ "schedListTitle": "Zamanlanmış ({n})",
+ "schedCancelled": "Zamanlanmış gönderi iptal edildi"
}
diff --git a/src/locales/ur.json b/src/locales/ur.json
index 6efb6ec..bdcfa7a 100644
--- a/src/locales/ur.json
+++ b/src/locales/ur.json
@@ -137,6 +137,10 @@
"giftSkip": "ابھی چھوڑیں",
"giftBackedUp": "میں نے اسے لکھ لیا ہے",
"giftLink": "کچھ Bitcoin تحفے میں دیں",
+ "giftNotePlaceholder": "ایک نوٹ شامل کریں (اختیاری)",
+ "giftFromMe": "بتائیں کہ یہ میری طرف سے ہے (وصول کرنے والا آپ کو فالو کرے گا)",
+ "giftFrom": "بھیجنے والا",
+ "giftClaimFollows": "وصول کرنے پر آپ انہیں فالو کریں گے",
"giftLinkDesc": "ایک رقم کو بطور لنک پہلے سے دستخط کریں۔ جو بھی اسے کھولے وہ Bitcoin کو ایک بالکل نئے والیٹ میں وصول کر لیتا ہے جو صرف اسی کے کنٹرول میں ہوتا ہے۔",
"giftLinkWarn": "⚠ جو بھی یہ لنک کھولے وہ اس رقم کا دعویٰ کر سکتا ہے، اس لیے اسے صرف اسی شخص کے ساتھ شیئر کریں جسے آپ تحفہ دے رہے ہیں۔ رقم کم رکھیں۔",
"giftLinkReveal": "تحفہ لنک بنائیں",
@@ -147,6 +151,7 @@
"giftReserved": "غیر دعویٰ شدہ تحفہ لنکس ({n})",
"claimBody": "اسے ایک بالکل نئے والیٹ میں وصول کریں جو صرف آپ کے کنٹرول میں ہو۔",
"claimBtn": "وصول کریں",
+ "claimNowBtn": "ابھی حاصل کریں",
"claimFailed": "اس تحفے کا پہلے ہی دعویٰ کیا جا چکا ہے یا یہ اب دستیاب نہیں۔",
"claimedTitle": "وصول ہو گیا!",
"claimedBody": "آپ کا Bitcoin راستے میں ہے۔ اسے محفوظ رکھنے کے لیے اپنے بحالی فقرے کا بیک اپ بنا لیں۔",
@@ -215,6 +220,17 @@
"followHistNone": "کسی پرانی کاپی میں ایسا کوئی نہیں جو آپ کی فہرست میں نہ ہو۔",
"followHistNothing": "اس کاپی کے سب لوگ پہلے سے آپ کی فہرست میں ہیں۔",
"followHistRestored": "{n} فالو بحال ہو گئے۔",
+ "profHistDesc": "اگر کسی اور ایپ نے آپ کا پروفائل بدل دیا ہے تو تاریخ محفوظ رکھنے والے کسی ریلے پر پرانی نقل اب بھی ہو سکتی ہے۔ اسے استعمال کرنے سے یہاں صرف خالی خانے بھرتے ہیں۔",
+ "profHistLook": "پرانی نقلیں تلاش کریں",
+ "profHistUse": "استعمال کریں",
+ "profHistNoName": "(بغیر نام)",
+ "profHistNone": "کسی پرانی نقل میں ایسا کچھ نہیں جو یہاں نہ ہو۔",
+ "profHistNothing": "اس نقل کی ہر چیز پہلے سے یہاں موجود ہے۔",
+ "profHistFilled": "پرانی نقل سے {n} خانے بھرے گئے۔ شائع کرنے کے لیے محفوظ کریں۔",
+ "profHist_name": "نام",
+ "profHist_about": "تعارف",
+ "profHist_picture": "تصویر",
+ "profHist_banner": "بینر",
"securityTitle": "سیکیورٹی",
"arkCoinsNone": "خرچ میں ابھی کوئی کوائن نہیں۔",
"profKeyLink": "پبلک کی",
@@ -247,6 +263,8 @@
"mediaNoImages": "اس فیڈ میں ابھی کوئی تصویر نہیں۔",
"mediaNoVideos": "اس فیڈ میں ابھی کوئی عمودی ویڈیو نہیں۔",
"videoTapToPlay": "چلانے کے لیے ٹیپ کریں",
+ "videoPlay": "چلائیں",
+ "videoPause": "روکیں",
"videoLargeTitle": "ویڈیوز",
"videoLargeToggle": "بڑی ویڈیوز خود چلائیں",
"videoLargeHelp": "{mb} MB سے بڑی یا 1080p سے اوپر کی ویڈیوز ٹیپ کا انتظار کرتی ہیں، تاکہ فیڈ آپ کا ڈیٹا نہ کھائے۔ سست یا ڈیٹا بچت والے کنکشن پر حد کم ہوتی ہے۔",
@@ -261,5 +279,15 @@
"arkRenewViewTx": "راؤنڈ کی ٹرانزیکشن دیکھیں",
"pagerFetchingVideo": "اگلی ویڈیو لائی جا رہی ہے…",
"pagerFetchingPictures": "مزید تصاویر لائی جا رہی ہیں…",
- "pagerCaughtUp": "فی الحال بس اتنا ہی"
+ "pagerCaughtUp": "فی الحال بس اتنا ہی",
+ "onbGiftNameTitle": "اب ایک یوزرنیم چنیں",
+ "onbGiftNameBody": "ایک نام لیں اور اپنا ادائیگی کا پتہ پائیں، تاکہ لوگ صرف آپ کے نام سے آپ کو بٹ کوائن بھیج سکیں۔ پھر ایک تصویر اور ایک کور چنیں۔",
+ "namesChangeTo": "{addr} میں بدلیں",
+ "schedToggle": "بعد کے لیے شیڈول کریں",
+ "schedAt": "پوسٹ کا وقت",
+ "schedBtn": "شیڈول کریں",
+ "schedDone": "{when} کے لیے شیڈول",
+ "schedTooSoon": "ابھی سے کم از کم دو منٹ بعد کا وقت چنیں",
+ "schedListTitle": "شیڈول شدہ ({n})",
+ "schedCancelled": "شیڈول شدہ پوسٹ منسوخ ہو گئی"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 415f4e7..5490c34 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -137,6 +137,10 @@
"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)",
+ "giftFromMe": "Cho biết là từ tôi (người nhận sẽ theo dõi bạn)",
+ "giftFrom": "Từ",
+ "giftClaimFollows": "Nhận quà sẽ theo dõi người gửi",
"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 +149,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.",
@@ -215,6 +220,17 @@
"followHistNone": "Không bản cũ nào có người mà danh sách của bạn đang thiếu.",
"followHistNothing": "Mọi người trong bản đó đã có trong danh sách của bạn.",
"followHistRestored": "Đã khôi phục {n} người theo dõi.",
+ "profHistDesc": "Nếu một ứng dụng khác đã thay thế hồ sơ của bạn, bản cũ hơn có thể vẫn còn trên relay lưu lịch sử. Dùng một bản chỉ điền vào các ô đang trống ở đây.",
+ "profHistLook": "Tìm bản cũ hơn",
+ "profHistUse": "Dùng",
+ "profHistNoName": "(không tên)",
+ "profHistNone": "Không bản cũ nào có thứ còn thiếu ở đây.",
+ "profHistNothing": "Mọi thứ trong bản đó đã có ở đây.",
+ "profHistFilled": "Đã điền {n} ô từ bản cũ hơn. Lưu để đăng.",
+ "profHist_name": "tên",
+ "profHist_about": "tiểu sử",
+ "profHist_picture": "ảnh",
+ "profHist_banner": "ảnh bìa",
"securityTitle": "Bảo mật",
"arkCoinsNone": "Chưa có coin nào trong Chi tiêu.",
"profKeyLink": "Khóa công khai",
@@ -247,6 +263,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 +279,15 @@
"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}",
+ "schedToggle": "Hẹn giờ đăng",
+ "schedAt": "Đăng lúc",
+ "schedBtn": "Hẹn giờ",
+ "schedDone": "Đã hẹn lúc {when}",
+ "schedTooSoon": "Chọn thời điểm ít nhất hai phút kể từ bây giờ",
+ "schedListTitle": "Đã hẹn ({n})",
+ "schedCancelled": "Đã huỷ bài hẹn giờ"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 6b3cc49..4fc2f4b 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -364,6 +364,10 @@
"giftWelcome": "有人给你转了 Bitcoin",
"giftBackedUp": "我已经抄写下来了",
"giftLink": "赠送一些 Bitcoin",
+ "giftNotePlaceholder": "添加留言(可选)",
+ "giftFromMe": "显示是我送的(领取者会关注你)",
+ "giftFrom": "来自",
+ "giftClaimFollows": "领取后会关注对方",
"giftLinkDesc": "将一笔金额预签为一个链接。打开链接的人可将这笔 Bitcoin 领取到一个仅由他们自己掌控的全新钱包中。",
"giftLinkWarn": "⚠ 任何打开此链接的人都能领取这笔金额,所以请仅分享给你要赠送的对象。请保持金额较小。",
"giftLinkReveal": "创建赠送链接",
@@ -425,6 +429,7 @@
"claimOr": "或者说",
"goToWallet": "转到钱包",
"claimBtn": "领取",
+ "claimNowBtn": "立即领取",
"claimFeeNote": "~ (法语){n} 收费",
"claimFailed": "此礼物已被领取或不再可用。",
"claimNotVisibleBody": "从这个钱包的网络/数据来源看, 确保这个钱包使用与发送者相同的网络和数据源,然后再次尝试.",
@@ -618,6 +623,8 @@
"onbSpendBody": "要求一个用户名并获得你自己的付款地址,人们可以立刻发送你比特币,只要你的名字.",
"onbNameWait": "准备...",
"onbNotNow": "现在不行",
+ "onbGiftNameTitle": "现在选一个用户名",
+ "onbGiftNameBody": "领取一个名字,获得你自己的收款地址,别人只用你的名字就能给你发比特币。然后选一张头像和封面。",
"onbAvatarTitle": "选择你的外观",
"onbAvatarBody": "选择一个头像或上传自己的照片。你可以随时更改",
"onbUpload": "上传相片",
@@ -640,7 +647,7 @@
"nlPasskey": "用密码签名",
"nlKeyOrBunker": "nsec,私人钥匙,或地堡://.",
"nlGo": "登录",
- "nlHint": "与Amber,Amethyst等远程签名者(打上他们的地堡/地址)合作,或是一个浏览器扩展. 粘贴的密钥使用一次, 并且从未被存储 。",
+ "nlHint": "支持远程签名应用(粘贴其 bunker:// 地址)或浏览器扩展。粘贴的密钥只使用一次,从不保存。",
"nlApprove": "批准您签名人的请求 。",
"nlUnrecognized": "这不是私人钥匙或地堡地址。",
"nlNewTitle": "为此账户创建钱包",
@@ -678,6 +685,7 @@
"namesClaim": "索赔",
"namesClaimed": "你现在是 {name}",
"namesCopy": "复制地址",
+ "namesChangeTo": "改为 {addr}",
"namesMoreOpen": "更多选项",
"namesMoreTitle": "更多赚钱的方法",
"namesMoreBolt11": "闪电发票(BOLT 11)",
@@ -878,6 +886,17 @@
"followHistNone": "没有旧副本包含你列表中缺少的人。",
"followHistNothing": "该副本中的所有人都已在你的列表中。",
"followHistRestored": "已恢复 {n} 个关注。",
+ "profHistDesc": "如果其他应用替换了你的资料,保留历史的中继上可能还有旧副本。使用它只会填入这里为空的字段。",
+ "profHistLook": "查找旧副本",
+ "profHistUse": "使用",
+ "profHistNoName": "(无名称)",
+ "profHistNone": "没有旧副本包含这里缺少的内容。",
+ "profHistNothing": "那份副本里的内容这里都已有了。",
+ "profHistFilled": "已从旧副本填入 {n} 个字段。保存即可发布。",
+ "profHist_name": "名称",
+ "profHist_about": "简介",
+ "profHist_picture": "头像",
+ "profHist_banner": "横幅",
"securityTitle": "安全",
"arkCoinsNone": "支出账户中还没有币。",
"profKeyLink": "公钥",
@@ -910,6 +929,8 @@
"mediaNoImages": "此动态中还没有图片。",
"mediaNoVideos": "此动态中还没有竖屏视频。",
"videoTapToPlay": "点按播放",
+ "videoPlay": "播放",
+ "videoPause": "暂停",
"videoLargeTitle": "视频",
"videoLargeToggle": "自动播放大视频",
"videoLargeHelp": "超过 {mb} MB 或高于 1080p 的视频会等你点按再播放,以免动态耗尽流量。在慢速或省流量连接下,上限更低。",
@@ -924,5 +945,12 @@
"arkRenewViewTx": "查看该轮交易",
"pagerFetchingVideo": "正在获取下一个视频…",
"pagerFetchingPictures": "正在获取更多图片…",
- "pagerCaughtUp": "暂时就这些了"
+ "pagerCaughtUp": "暂时就这些了",
+ "schedToggle": "定时发布",
+ "schedAt": "发布时间",
+ "schedBtn": "定时",
+ "schedDone": "已定时于 {when}",
+ "schedTooSoon": "请选择至少两分钟之后的时间",
+ "schedListTitle": "已定时({n})",
+ "schedCancelled": "已取消定时帖子"
}
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-servers.js b/src/media-servers.js
new file mode 100644
index 0000000..e2220d7
--- /dev/null
+++ b/src/media-servers.js
@@ -0,0 +1,27 @@
+// Upload destinations are a device preference, separate from wallet sync storage.
+const KEY = 'btc-wallet-media-servers';
+export function parseMediaServers(text) {
+ const entries = String(text).trim().split(/\s+/).filter(Boolean);
+ if (!entries.length) throw new Error('invalid');
+ const servers = [...new Set(entries.map((entry) => {
+ let url;
+ try { url = new URL(entry); } catch { throw new Error('invalid'); }
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !/^\/*$/.test(url.pathname)) throw new Error('invalid');
+ return url.origin;
+ }))];
+ if (servers.length > 6) throw new Error('invalid');
+ return servers;
+}
+export function customMediaServers() {
+ try {
+ const saved = JSON.parse(localStorage.getItem(KEY));
+ return Array.isArray(saved) ? parseMediaServers(saved.join('\n')) : null;
+ } catch { return null; }
+}
+export const mediaServers = (defaults) => customMediaServers() || defaults;
+export function saveMediaServers(text) {
+ const servers = parseMediaServers(text);
+ localStorage.setItem(KEY, JSON.stringify(servers));
+ return servers;
+}
+export function resetMediaServers() { localStorage.removeItem(KEY); }
diff --git a/src/media-timeline.js b/src/media-timeline.js
new file mode 100644
index 0000000..a70a46c
--- /dev/null
+++ b/src/media-timeline.js
@@ -0,0 +1,152 @@
+// Timestamp annotations retain the usual Nostr event target. `media` is a
+// client extension; the r tag is a portable media-fragment link.
+export function mediaMoment(url, seconds) {
+ try {
+ const u = new URL(url);
+ if (!/^https?:$/.test(u.protocol) || !Number.isFinite(seconds) || seconds < 0 || seconds > Number.MAX_SAFE_INTEGER) return null;
+ u.hash = '';
+ return { url: u.href, seconds: Math.floor(seconds) };
+ } catch { return null; }
+}
+export function momentTags(moment) {
+ const m = moment && mediaMoment(moment.url, moment.seconds);
+ return m ? [['media', m.url, String(m.seconds)], ['r', m.url + '#t=' + m.seconds]] : [];
+}
+export function readMoment(event, depth = 0) {
+ if (depth > 1) return null;
+ if (event?.kind === 9735) {
+ try { return readMoment(JSON.parse(event.tags.find(t => t[0] === 'description')?.[1]), depth + 1); } catch { return null; }
+ }
+ const tag = event?.tags?.find(t => t[0] === 'media');
+ return tag && /^\d+$/.test(tag[2] || '') ? mediaMoment(tag[1], Number(tag[2])) : null;
+}
+// "didn't intend to tie it to the video timestamp but i guess it did by
+// default" (Adam, 2026-11-14, a zap with a comment on a clip he'd played).
+// A reply, zap or reaction made while a clip has played is ABOUT that
+// moment only when asked: this toggle, off until tapped.
+export function momentToggle(h, moment, on, onToggle, label) {
+ if (!moment) return null;
+ return h('button', {
+ type: 'button', class: 'moment-toggle' + (on ? ' on' : ''), 'aria-pressed': on ? 'true' : 'false',
+ onClick: (e) => { e.stopPropagation(); onToggle(!on); },
+ }, h('span', { 'aria-hidden': 'true' }, on ? '\u2713' : '\u23f1'), ' ', label);
+}
+
+export function mediaClock(seconds) {
+ const s = Math.max(0, Math.floor(seconds || 0));
+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
+}
+export function waveformFromTags(event, url) {
+ const tag = event?.tags?.find(t => t[0] === 'imeta' && t.includes('url ' + url));
+ const raw = tag?.find(t => t.startsWith('waveform '))?.slice(9);
+ if (!raw) return null;
+ const values = raw.trim().split(/\s+/).map(Number);
+ return values.length > 1 && values.length <= 4096 && values.every(n => Number.isFinite(n) && n >= 0) ? values : null;
+}
+export function waveformPeaks(buffer, count = 96) {
+ const peaks = new Array(count).fill(0);
+ for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
+ const data = buffer.getChannelData(ch);
+ for (let i = 0; i < count; i++) {
+ const end = Math.floor((i + 1) * data.length / count);
+ for (let j = Math.floor(i * data.length / count); j < end; j++) peaks[i] = Math.max(peaks[i], Math.abs(data[j]));
+ }
+ }
+ return peaks;
+}
+const waves = new Map();
+let decoding = Promise.resolve();
+export function loadWaveform(url) {
+ if (waves.has(url)) return waves.get(url);
+ const job = decoding.then(async () => {
+ const limit = 20 * 1024 * 1024;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 30000);
+ let ctx;
+ try {
+ const response = await fetch(url, { signal: controller.signal, credentials: 'omit' });
+ if (!response.ok || Number(response.headers.get('content-length')) > limit) throw new Error('size');
+ const reader = response.body.getReader(), parts = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > limit) { await reader.cancel(); throw new Error('size'); }
+ parts.push(value);
+ }
+ const Audio = globalThis.AudioContext || globalThis.webkitAudioContext;
+ ctx = new Audio({ sampleRate: 8000 });
+ const buffer = await ctx.decodeAudioData(await new Blob(parts).arrayBuffer());
+ return waveformPeaks(buffer);
+ } catch { return null; }
+ finally { clearTimeout(timer); controller.abort(); if (ctx) await ctx.close().catch(() => {}); }
+ });
+ decoding = job.then(() => {});
+ waves.set(url, job);
+ if (waves.size > 24) waves.delete(waves.keys().next().value);
+ return job;
+}
+
+// Where a moment sits along a bar: a percentage of the clip, or null.
+export function markAt(seconds, duration) {
+ return Number.isFinite(duration) && duration > 0 ? Math.min(100, Math.max(0, seconds / duration * 100)) : null;
+}
+
+// The live player owns this subtree, so morphing cannot replace its handlers
+// 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, 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;
+ const bars = h('div', { class: 'media-wave', 'aria-hidden': 'true' });
+ const range = h('input', { type: 'range', min: 0, max: 1000, value: 0, step: 1, 'aria-label': label('mediaSeek'), disabled: true });
+ const marks = h('div', { class: 'media-marks' });
+ const seek = h('div', { class: 'media-seek' }, bars, range, marks);
+ const time = h('span', { class: 'small muted media-time' }, '0:00');
+ const detail = h('div', { class: 'small media-moment-detail', 'aria-live': 'polite' });
+ box.append(seek, time, detail);
+ let waveStarted = false, signature = '';
+ const draw = values => {
+ if (!values) return;
+ const max = Math.max(...values) || 1;
+ const stride = Math.max(1, Math.ceil(values.length / 96));
+ bars.replaceChildren();
+ for (let i = 0; i < values.length; i += stride) bars.append(h('i', { style: 'height:' + Math.max(3, 100 * Math.max(...values.slice(i, i + stride)) / max) + '%' }));
+ seek.classList.add('has-wave');
+ };
+ const jump = seconds => { if (Number.isFinite(player.duration)) player.currentTime = Math.min(seconds, player.duration); };
+ range.addEventListener('input', () => jump(Number(range.value) * player.duration / 1000));
+ const update = () => {
+ const ev = event();
+ const finite = Number.isFinite(player.duration) && player.duration > 0;
+ range.disabled = !finite;
+ range.value = finite ? player.currentTime / player.duration * 1000 : 0;
+ range.setAttribute('aria-valuetext', mediaClock(player.currentTime) + ' / ' + mediaClock(finite ? player.duration : 0));
+ seek.style.setProperty('--played', (finite ? player.currentTime / player.duration * 100 : 0) + '%');
+ time.textContent = mediaClock(player.currentTime) + ' / ' + mediaClock(finite ? player.duration : 0);
+ if (audio && !waveStarted && finite) {
+ waveStarted = true;
+ const published = waveformFromTags(ev, url);
+ if (published) draw(published);
+ else if (player.duration <= 1200 && !navigator.connection?.saveData) loadWaveform(url).then(draw);
+ }
+ 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,
+ style: 'left:' + markAt(x.moment.seconds, player.duration) + '%',
+ onClick: e => { e.stopPropagation(); jump(x.moment.seconds); detail.textContent = mediaClock(x.moment.seconds) + ' ' + x.text; } }, glyph(x))));
+ }
+ };
+ // Fetching/decoding starts only once the user plays (or explicitly seeks).
+ for (const type of ['timeupdate', 'playing', 'seeked', 'durationchange', 'mediaactivity']) player.addEventListener(type, update);
+ return box;
+}
diff --git a/src/media-upload.js b/src/media-upload.js
index c06771b..7f020cf 100644
--- a/src/media-upload.js
+++ b/src/media-upload.js
@@ -1,3 +1,4 @@
+import { mediaServers } from './media-servers.js';
import { sha256 } from '@noble/hashes/sha256';
import { bytesToHex } from '@noble/hashes/utils';
@@ -19,6 +20,16 @@ export class MediaUploadError extends Error {
}
}
+// Private Blossom hosts authorize the user's Nostr identity, which can differ
+// from the wallet's sync key. Resolve once for the whole upload (including HLS).
+export async function mediaUploadSigner(wallet, hook) {
+ const id = hook('nostrLoginIdentity');
+ if (!id) return (event) => wallet.nostrSign(event);
+ const signer = id.signer || await hook('nostrLoginResume');
+ if (!signer) throw new MediaUploadError('no-identity');
+ return (event) => signer.signEvent(event);
+}
+
async function fileHash(file) {
const hash = sha256.create();
const chunk = 4 * 1024 * 1024;
@@ -62,10 +73,12 @@ 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
-// always-available wallet identity, while tests need no secret key.
+// signed-in Nostr identity, while tests need no secret key.
export async function uploadPublicMedia(file, signEvent, {
- servers = PUBLIC_MEDIA_SERVERS,
+ servers = mediaServers(PUBLIC_MEDIA_SERVERS),
fetcher = globalThis.fetch,
timeoutMs = 5 * 60_000,
onProgress = null, // (fraction 0..1) as the bytes go out
@@ -86,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 = {
@@ -105,13 +118,60 @@ 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);
throw new MediaUploadError('failed', details);
}
+
+// An HLS stream (streamVideo) onto one host: the media files first, then
+// each playlist with its files' addresses written in, then the master
+// playlist naming those — its address is the post's. One host for the lot,
+// and one that serves a playlist as one (ditto and nostr.download do;
+// primal's says text/plain, nostr.build won't take it); a host that refuses
+// any piece is passed over for the next. `files` maps each name the
+// playlists use to its File.
+export const STREAM_SERVERS = ['https://blossom.ditto.pub', 'https://nostr.download', 'https://blossom.primal.net'];
+export function rewritePlaylist(text, urls) {
+ const to = (p) => urls.get(p) || p;
+ return text.split('\n').map((line) => {
+ const l = line.trim();
+ if (l && !l.startsWith('#')) return to(l);
+ return line.replace(/URI="([^"]+)"/g, (m, p) => `URI="${to(p)}"`);
+ }).join('\n');
+}
+export async function uploadStream({ files, master }, signEvent, { servers = mediaServers(STREAM_SERVERS), fetcher, onProgress = null } = {}) {
+ const media = [...files.keys()].filter((p) => !/\.m3u8$/.test(p));
+ const lists = [...files.keys()].filter((p) => /\.m3u8$/.test(p) && p !== master);
+ const total = [...files.values()].reduce((n, f) => n + f.size, 0) || 1;
+ let lastError = null;
+ for (const server of servers) {
+ let done = 0;
+ const put = async (file) => {
+ const url = await uploadPublicMedia(file, signEvent, {
+ servers: [server], ...(fetcher ? { fetcher } : {}),
+ onProgress: onProgress && ((p) => onProgress(Math.min(1, (done + p * file.size) / total))),
+ });
+ done += file.size;
+ if (onProgress) onProgress(Math.min(1, done / total)); // (the playlists grow a little with the addresses in)
+ return url;
+ };
+ try {
+ const urls = new Map();
+ for (const p of media) urls.set(p, await put(files.get(p)));
+ for (const p of lists) {
+ const text = rewritePlaylist(await files.get(p).text(), urls);
+ urls.set(p, await put(new File([text], p, { type: 'application/vnd.apple.mpegurl' })));
+ }
+ const text = rewritePlaylist(await files.get(master).text(), urls);
+ return await put(new File([text], master, { type: 'application/vnd.apple.mpegurl' }));
+ } catch (error) { lastError = error; }
+ }
+ throw lastError || new MediaUploadError('failed');
+}
diff --git a/src/nip29-client.js b/src/nip29-client.js
new file mode 100644
index 0000000..cfbd171
--- /dev/null
+++ b/src/nip29-client.js
@@ -0,0 +1,361 @@
+// NIP-29 relay-based groups in the app: the fourth way a group chat can
+// travel, beside White Noise, Cordn and Concord. A group lives on ONE relay,
+// which keeps its membership and signs its metadata (kinds 39000 name,
+// 39001 admins, 39002 members); its messages are ordinary signed events
+// (kind 9 chat, 7 reactions, 5 deletions) carrying an `h` tag with the
+// group's id. Nothing is encrypted: the relay (and, in an open group,
+// anyone) can read it. Membership is asked for with kind 9021 and given up
+// with 9022; the relay decides.
+//
+// The same interface as marmot-client.js and cordn-client.js, so the group
+// screens in features/messages.js drive all three (`g.nip29` says which).
+// Groups joined here and in other clients are one list: NIP-51 kind 10009
+// ("simple groups"), read at start and written back on join and leave —
+// replaceable, so never written without first reading the newest copy.
+
+import { subscribeAuthed, publishOn, queryOn, finalizeEvent } from './nostr.js';
+import { decode as nip19decode } from 'nostr-tools/nip19';
+import { getEventHash } from 'nostr-tools/pure';
+import { marmotStore } from './marmot-store.js';
+import { dlog } from './debug.js';
+
+const LIST = 10009;
+const CHAT_KINDS = [9, 7, 5, 9000, 9001, 9021, 9022];
+const META_KINDS = [39000, 39001, 39002];
+const LOG_MAX = 600; // events held per group in memory
+const KEEP = 200; // ...and on disk, so a reload paints at once
+const now = () => Math.floor(Date.now() / 1000);
+const GID = /^[A-Za-z0-9_-]{1,128}$/;
+
+// The relay's URL, normalized: wss://host[/path], no trailing slash.
+export function normRelay(u) {
+ let x = String(u || '').trim();
+ if (!x) return null;
+ if (!/^wss?:\/\//i.test(x)) x = 'wss://' + x.replace(/^\/+/, '');
+ try {
+ const url = new URL(x);
+ if (!/^wss?:$/.test(url.protocol) || !url.hostname.includes('.') && url.hostname !== 'localhost' && !/^\d/.test(url.hostname)) return null;
+ return (url.protocol + '//' + url.host + url.pathname).replace(/\/+$/, '').toLowerCase();
+ } catch { return null; }
+}
+
+// A group's address in whatever form someone pastes it: host'id (the
+// NIP-29 form), wss://host'id, an naddr of its kind 39000, or a web link
+// from a client (chachi.chat/<host>/<id>, flotilla's /spaces/<host>/<id>, …).
+export function parseGroupAddress(input) {
+ let s = String(input || '').trim().replace(/^nostr:/i, '');
+ if (!s) return null;
+ if (/^naddr1/i.test(s)) {
+ try {
+ const d = nip19decode(s);
+ if (d.type === 'naddr' && d.data.kind === 39000 && GID.test(d.data.identifier) && d.data.relays?.length) {
+ const relay = normRelay(d.data.relays[0]);
+ return relay ? { relay, gid: d.data.identifier } : null;
+ }
+ } catch {}
+ return null;
+ }
+ const q = s.match(/^(wss?:\/\/)?([^'\s/]+(?:\/[^'\s]*)?)'([A-Za-z0-9_-]+)$/);
+ if (q) {
+ const relay = normRelay((q[1] || 'wss://') + q[2]);
+ return relay && GID.test(q[3]) ? { relay, gid: q[3] } : null;
+ }
+ if (/^https?:\/\//i.test(s)) {
+ try {
+ const u = new URL(s);
+ const parts = u.pathname.split('/').filter(Boolean).map(decodeURIComponent);
+ for (let i = 0; i < parts.length - 1; i++) {
+ const host = parts[i].replace(/^wss?:\/\//i, '');
+ if (host.includes('.') && GID.test(parts[i + 1])) {
+ const relay = normRelay(host);
+ if (relay) return { relay, gid: parts[i + 1] };
+ }
+ }
+ } catch {}
+ }
+ return null;
+}
+
+const keyOf = (relay, gid) => relay + "'" + gid;
+
+// listRelays(deep): where our kind 10009 is read and written.
+export function nip29Client({ scope, pubkey, identity, on, listRelays, store = marmotStore(scope + '|nip29') }) {
+ const groups = new Map(); // key -> record
+ let loaded = null, stopped = false, list = null; // list: { tags, at }
+ const subs = new Map(); // key -> unsubscribe
+ const leftNow = new Set(); // left this session: a list read still in flight mustn't bring them back
+ const emit = (type, g, data) => { try { on(type, g, data); } catch (e) { dlog('nip29: listener', e); } };
+
+ // ---- signing ----
+ async function sign(tmpl, { interactive = true } = {}) {
+ const id = await identity();
+ if (!id || !id.signer || id.pubkey !== pubkey) throw new Error('no signer');
+ if (id.signer instanceof Uint8Array) return finalizeEvent(tmpl, id.signer);
+ if (id.signer.interactive && !interactive) throw new Error('signer is interactive');
+ return id.signer.signEvent(tmpl);
+ }
+ // NIP-42: a private group shows itself, and any group takes a post, only
+ // from a signed-in member. Never a trip through another app unasked.
+ const onauth = (tmpl) => sign(tmpl, { interactive: false });
+
+ // ---- storage ----
+ function record(relay, gid) {
+ const id = keyOf(relay, gid);
+ let g = groups.get(id);
+ if (!g) {
+ g = { id, nip29: true, relay, gid, log: [], at: now(), meta: {}, admins: [], members: [], metaAt: {} };
+ groups.set(id, g);
+ }
+ return g;
+ }
+ let flushTimer = 0;
+ const dirty = new Set();
+ const touch = (g) => { dirty.add(g.id); clearTimeout(flushTimer); flushTimer = setTimeout(flush, 600); };
+ async function flush() {
+ clearTimeout(flushTimer);
+ const ids = [...dirty];
+ dirty.clear();
+ await Promise.all(ids.map((id) => {
+ const g = groups.get(id);
+ if (!g) return store.del('g:' + id);
+ const { log, ...rest } = g;
+ return store.put('g:' + id, { ...rest, log: log.filter((e) => !e.pending).slice(-KEEP) });
+ })).catch((e) => dlog('nip29: save', e));
+ }
+ function load() {
+ if (!loaded)
+ loaded = store.all().then((all) => {
+ for (const [k, v] of all) if (k.startsWith('g:') && v && v.relay && v.gid) groups.set(v.id, { ...v, log: v.log || [], unreachable: '' });
+ const l = all.get('list');
+ if (l && Array.isArray(l.tags)) list = l;
+ }).catch((e) => dlog('nip29: store', e));
+ return loaded;
+ }
+
+ // ---- events in ----
+ // A reply in NIP-29 chat quotes what it answers (`q`); the group screens
+ // read a reply's target from its first `e`, so one is added for display.
+ function display(ev) {
+ if (ev.kind !== 9 || ev.tags.some((x) => x[0] === 'e')) return ev;
+ const q = ev.tags.find((x) => x[0] === 'q' && /^[0-9a-f]{64}$/.test(x[1] || ''));
+ return q ? { ...ev, tags: [...ev.tags, ['e', q[1]]] } : ev;
+ }
+ function take(g, ev) {
+ if (META_KINDS.includes(ev.kind)) {
+ if ((g.metaAt[ev.kind] || 0) >= ev.created_at) return;
+ g.metaAt[ev.kind] = ev.created_at;
+ const tag = (k) => (ev.tags.find((x) => x[0] === k) || [])[1];
+ if (ev.kind === 39000) {
+ g.meta = { name: tag('name') || '', about: tag('about') || '', picture: tag('picture') || '',
+ closed: ev.tags.some((x) => x[0] === 'closed'), private: ev.tags.some((x) => x[0] === 'private') };
+ } else {
+ const pks = [...new Set(ev.tags.filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1]))];
+ if (ev.kind === 39001) g.admins = pks; else g.members = pks;
+ }
+ touch(g);
+ emit('meta', g);
+ return;
+ }
+ if (g.log.some((e) => e.id === ev.id && !e.pending)) return;
+ const i = g.log.findIndex((e) => e.id === ev.id);
+ if (i >= 0) g.log.splice(i, 1); // our own, confirmed by the relay
+ const shown = display(ev);
+ g.log.push(shown);
+ g.log.sort((a, b) => a.created_at - b.created_at);
+ if (g.log.length > LOG_MAX) g.log.splice(0, g.log.length - LOG_MAX);
+ if (!ev.pending) g.seen = Math.max(g.seen || 0, ev.created_at);
+ touch(g);
+ emit('message', g, shown);
+ }
+
+ function subscribe(g) {
+ if (subs.has(g.id) || stopped) return;
+ const since = g.seen ? g.seen - 60 : undefined;
+ // a relay that can't be reached (groups.0xchat.com stopped resolving)
+ // is said on the group's row instead of "0 members"
+ const reached = () => { if (g.unreachable) { g.unreachable = ''; touch(g); emit('loaded', g); } };
+ const a = subscribeAuthed([g.relay], { kinds: CHAT_KINDS, '#h': [g.gid], limit: 300, ...(since ? { since } : {}) },
+ (ev) => { reached(); if (ev.tags.some((x) => x[0] === 'h' && x[1] === g.gid)) take(g, ev); },
+ { onauth, onclose: (why) => { if (!g.log.length && !g.members.length) { g.unreachable = String((why && why[0]) || 'unreachable'); touch(g); emit('loaded', g); } } });
+ // metadata: only what the group's own relay signed (the copies other
+ // relays carry are read nowhere)
+ const b = subscribeAuthed([g.relay], { kinds: META_KINDS, '#d': [g.gid] },
+ (ev) => { if (ev.tags.some((x) => x[0] === 'd' && x[1] === g.gid)) take(g, ev); }, { onauth });
+ subs.set(g.id, () => { a(); b(); });
+ }
+ function unsubscribe(g) { const u = subs.get(g.id); if (u) { u(); subs.delete(g.id); } }
+
+ // ---- the joined-groups list (kind 10009) ----
+ const listGroups = (tags) => (tags || []).filter((x) => x[0] === 'group' && GID.test(x[1] || '') && normRelay(x[2]))
+ .map((x) => ({ gid: x[1], relay: normRelay(x[2]), name: x[3] || '' }));
+ async function readList(deep = false) {
+ const relays = await listRelays(deep);
+ const evs = await queryOn(relays, { kinds: [LIST], authors: [pubkey] }, deep ? 7000 : 5000);
+ const newest = (evs || []).filter((e) => e.pubkey === pubkey).sort((a, b) => b.created_at - a.created_at)[0];
+ if (newest && (!list || newest.created_at > list.at)) {
+ list = { tags: newest.tags || [], content: newest.content || '', at: newest.created_at };
+ store.put('list', list).catch(() => {});
+ }
+ return list;
+ }
+ // Apply one change to the newest list the relays hold (never to a copy
+ // we only assume is current), then publish it.
+ async function writeList(change) {
+ const cur = await readList(true).catch(() => list);
+ const base = cur || { tags: [], content: '', at: 0 };
+ const tags = change(base.tags);
+ if (!tags) return;
+ const created_at = Math.max(now(), base.at + 1);
+ const ev = await sign({ kind: LIST, created_at, tags, content: base.content || '' });
+ // everywhere a reader looks: a phone that asks only the relays a copy
+ // missed would never learn of a group joined on the laptop
+ const ok = await publishOn(await listRelays(true), ev);
+ if (ok) { list = { tags, content: base.content || '', at: created_at }; store.put('list', list).catch(() => {}); }
+ }
+ // The list as another device changed it: read at start, again whenever the
+ // app comes back (resubscribe), and followed live while it's open, so a
+ // group joined on the laptop shows up on the phone (Adam, 2026-11-12).
+ let adoptedAt = 0, listSub = null;
+ async function adoptList() {
+ adoptedAt = Date.now();
+ try {
+ await readList(true);
+ const l = list; // the newest, a leave's own write included
+ if (!l || stopped) return;
+ for (const x of listGroups(l.tags)) {
+ if (groups.has(keyOf(x.relay, x.gid)) || leftNow.has(keyOf(x.relay, x.gid))) continue;
+ const g = record(x.relay, x.gid);
+ if (x.name && !g.meta.name) g.meta = { ...g.meta, name: x.name };
+ touch(g);
+ subscribe(g);
+ emit('loaded', g);
+ }
+ } catch (e) { dlog('nip29: list', e); }
+ }
+
+ // ---- actions ----
+ // Ask the relay to let us in, and hold the group here either way: an
+ // open group can be read before (or without) the relay's yes.
+ async function join(address, { code = '' } = {}) {
+ const a = typeof address === 'string' ? parseGroupAddress(address) : address;
+ if (!a) throw new Error('bad address');
+ await load();
+ leftNow.delete(keyOf(a.relay, a.gid));
+ const g = record(a.relay, a.gid);
+ g.joinedAt = now(); // sorts a group joined here, still quiet, as new
+ touch(g);
+ subscribe(g);
+ emit('joined', g);
+ let refused = '';
+ const req = await sign({ kind: 9021, created_at: now(), content: '', tags: [['h', a.gid], ...(code ? [['code', code]] : [])] });
+ const ok = await publishOn([a.relay], req, { onauth, onrefused: (_, why) => { refused = why; } });
+ // "duplicate"/"already a member" is a yes
+ if (!ok && !/already|duplicate/i.test(refused)) g.joinRefused = refused || 'unreachable';
+ else g.joinRefused = '';
+ touch(g);
+ writeList((tags) => tags.some((x) => x[0] === 'group' && x[1] === a.gid && normRelay(x[2]) === a.relay) ? null
+ : [...tags, ['group', a.gid, a.relay, g.meta.name || ''].filter((v, i) => i < 3 || v)]).catch((e) => dlog('nip29: list write', e));
+ return g;
+ }
+
+ // The NIP-29 "previous" tags: the first 8 characters of a few recent
+ // events this relay sent us, so it can tell we've seen the timeline.
+ const previous = (g) => g.log.filter((e) => !e.pending && e.pubkey !== pubkey).slice(-3).map((e) => ['previous', e.id.slice(0, 8)]);
+
+ function event(kind, content, tags = []) {
+ const ev = { kind, content, tags, created_at: now(), pubkey };
+ return { ...ev, id: getEventHash(ev) };
+ }
+ // A reply's `e` becomes the `q` NIP-29 chat clients read.
+ function outTags(g, inner) {
+ let tags = inner.tags || [];
+ if (inner.kind === 9) tags = tags.map((x) => {
+ if (x[0] !== 'e') return x;
+ const target = g.log.find((e) => e.id === x[1]);
+ return ['q', x[1], g.relay, ...(target ? [target.pubkey] : [])];
+ });
+ return [['h', g.gid], ...tags.filter((x) => x[0] !== 'h'), ...previous(g)];
+ }
+ async function send(g, inner) {
+ const ev = await sign({ kind: inner.kind, content: inner.content || '', created_at: inner.created_at || now(), tags: outTags(g, inner) });
+ take(g, { ...ev, pending: true });
+ let refused = '';
+ const ok = await publishOn([g.relay], ev, { onauth, onrefused: (_, why) => { refused = why; } });
+ const i = g.log.findIndex((e) => e.id === ev.id);
+ if (!ok) {
+ if (i >= 0) g.log.splice(i, 1);
+ g.sendRefused = refused;
+ emit('message', g, ev);
+ return false;
+ }
+ if (i >= 0) { const { pending, ...clean } = g.log[i]; g.log[i] = clean; }
+ g.sendRefused = '';
+ touch(g);
+ emit('message', g, ev);
+ return true;
+ }
+
+ async function leave(g) {
+ unsubscribe(g);
+ leftNow.add(g.id);
+ groups.delete(g.id);
+ touch(g);
+ emit('left', g);
+ try {
+ const ev = await sign({ kind: 9022, created_at: now(), content: '', tags: [['h', g.gid]] });
+ publishOn([g.relay], ev, { onauth }).catch(() => {});
+ } catch {}
+ await writeList((tags) => {
+ const next = tags.filter((x) => !(x[0] === 'group' && x[1] === g.gid && normRelay(x[2]) === g.relay));
+ return next.length === tags.length ? null : next;
+ }).catch((e) => dlog('nip29: list write', e));
+ }
+
+ function adoptLive(ev) {
+ if (stopped || ev.pubkey !== pubkey || ev.kind !== LIST) return;
+ if (list && ev.created_at <= list.at) return;
+ list = { tags: ev.tags || [], content: ev.content || '', at: ev.created_at };
+ store.put('list', list).catch(() => {});
+ adoptList();
+ }
+ async function followList() {
+ if (listSub || stopped) return;
+ const relays = await listRelays(false);
+ if (stopped || listSub) return;
+ listSub = subscribeAuthed(relays, { kinds: [LIST], authors: [pubkey], limit: 1 }, adoptLive);
+ }
+ async function start() {
+ await load();
+ if (stopped) return;
+ for (const g of groups.values()) subscribe(g);
+ emit('loaded', null);
+ adoptList();
+ followList().catch(() => {});
+ }
+ function resubscribe() {
+ for (const g of groups.values()) { unsubscribe(g); subscribe(g); }
+ if (listSub) { try { listSub(); } catch {} listSub = null; }
+ followList().catch(() => {});
+ if (Date.now() - adoptedAt > 30_000) adoptList();
+ }
+ function stop() {
+ stopped = true;
+ for (const g of groups.values()) unsubscribe(g);
+ if (listSub) { try { listSub(); } catch {} listSub = null; }
+ flush();
+ }
+ const no = async () => { throw new Error('not supported'); };
+
+ return {
+ pubkey, groups, load, start, stop, resubscribe, join, send, leave,
+ forget: leave, accept: () => {}, focus: () => {}, ready: () => {}, poll: () => {}, lookup: async () => null,
+ create: no, add: no, kick: no, rename: no,
+ event,
+ view: (g) => ({ name: g.meta.name || g.gid, about: g.meta.about || '', picture: g.meta.picture || '', admins: g.admins, closed: !!g.meta.closed, private: !!g.meta.private }),
+ peer: () => null,
+ accounts: (g) => g.members.length ? g.members : [...new Set(g.log.filter((e) => e.kind === 9).map((e) => e.pubkey))],
+ isAdmin: () => false,
+ groupRef: (g) => g.relay.replace(/^wss:\/\//, '') + "'" + g.gid,
+ isSetUp: () => true,
+ };
+}
diff --git a/src/nostr-login.js b/src/nostr-login.js
index fe60261..e5490ec 100644
--- a/src/nostr-login.js
+++ b/src/nostr-login.js
@@ -36,7 +36,7 @@ import { hex, bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { entropyToMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
-import { getPublicKey, finalizeEvent, nip44 } from './nostr.js';
+import { getPublicKey, finalizeEvent, nip44, liveRelayList } from './nostr.js';
import { SimplePool } from 'nostr-tools/pool';
import { generateSecretKey } from 'nostr-tools/pure';
import { decode as nip19decode } from 'nostr-tools/nip19';
@@ -208,7 +208,24 @@ export function nostrConnectPending(timeoutMs = 180_000) {
} catch {}
return null;
}
-export async function nostrConnect({ relays = ['wss://relay.coinos.io', 'wss://nos.lol'], timeoutMs = 180_000, resume = null } = {}) {
+// The relays a nostrconnect:// link names: the signer app publishes its
+// approval there and we wait there, so a dead one is a login that spins
+// until it times out. A PAFF account's Amber sign-in sat on "waiting for
+// signer" while nos.lol (the link's second relay) refused connections, and
+// relay.nsec.app was down the same night (Adam, 2026-11-19). So the link
+// leads with relay.coinos.io and relay.primal.net (up, and both keep NIP-46
+// traffic), leaves out any relay this device has recently found dead, and
+// names three: one relay's outage no longer strands the handshake.
+const CONNECT_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://offchain.pub'];
+export function connectRelays(candidates = CONNECT_RELAYS, n = 3) {
+ let live = candidates;
+ try { live = liveRelayList(candidates); } catch {}
+ const picked = live.slice(0, n);
+ // our own relay always: its ops are ours to fix, and the poller reads it
+ if (!picked.includes(candidates[0])) picked.unshift(candidates[0]);
+ return picked.slice(0, n);
+}
+export async function nostrConnect({ relays = connectRelays(), timeoutMs = 180_000, resume = null } = {}) {
const { BunkerSigner, createNostrConnectURI } = await loadNip46();
const local = resume ? hex.decode(resume.local) : generateSecretKey();
const secret = resume ? resume.secret : hex.encode(crypto.getRandomValues(new Uint8Array(16)));
@@ -324,7 +341,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 +401,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 +415,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 +453,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(() => {});
@@ -482,8 +531,14 @@ export async function fetchWalletBackup(signer, relays = BACKUP_RELAYS) {
// `spending` rides along as a hint: a restored wallet paints its Spending
// side from the first frame instead of reflowing when the name lookup proves
// it seconds later.
-export async function publishWalletBackup(signer, { mnemonic, passphrase, spending }, relays = BACKUP_RELAYS) {
- const content = await signer.encryptSelf(JSON.stringify({ mnemonic, passphrase: passphrase || '', ...(spending ? { spending: true } : {}) }));
+// `recovery` marks a copy kept by a WAY BACK IN (a passkey, Google or nostr
+// key added from Settings): signing in with that key opens the account as
+// itself — its own identity, name and profile — rather than adopting the
+// key as the account's nostr identity the way a login does. `spendingOnly`
+// carries a sign-up's shape (no Savings side yet) to the next device.
+export async function publishWalletBackup(signer, { mnemonic, passphrase, spending, recovery, spendingOnly }, relays = BACKUP_RELAYS) {
+ const content = await signer.encryptSelf(JSON.stringify({ mnemonic, passphrase: passphrase || '',
+ ...(spending ? { spending: true } : {}), ...(recovery ? { recovery: true } : {}), ...(spendingOnly ? { spendingOnly: true } : {}) }));
const evt = await signer.signEvent({
kind: BACKUP_KIND, created_at: Math.floor(Date.now() / 1000),
tags: [['d', SEED_DTAG]], content,
@@ -505,7 +560,7 @@ export async function publishWalletBackup(signer, { mnemonic, passphrase, spendi
// deriving (key in hand) or generating (signer only).
export async function walletForSigner(signer) {
const found = await fetchWalletBackup(signer);
- if (found) return { mnemonic: found.mnemonic, passphrase: found.passphrase, spending: !!found.spending, mode: 'restored' };
+ if (found) return { mnemonic: found.mnemonic, passphrase: found.passphrase, spending: !!found.spending, recovery: !!found.recovery, spendingOnly: !!found.spendingOnly, mode: 'restored' };
if (signer.secret) {
// Publishing the derived seed costs nothing: the derivation is public,
// so anyone holding this key could compute it anyway. It buys the thing
diff --git a/src/nostr.js b/src/nostr.js
index 8dcab01..d2c9e44 100644
--- a/src/nostr.js
+++ b/src/nostr.js
@@ -9,7 +9,8 @@
// Sync is on by default (relay.coinos.io) but can be turned off or pointed at
// other relays in Settings; the preference lives in localStorage.
-import * as nip06 from 'nostr-tools/nip06';
+import { HDKey } from '@scure/bip32';
+import { seedSync } from './seed.js';
import * as nip44 from 'nostr-tools/nip44';
import * as nip04 from 'nostr-tools/nip04';
import { getPublicKey, finalizeEvent, generateSecretKey, verifyEvent } from 'nostr-tools/pure';
@@ -186,7 +187,12 @@ pool.ensureRelay = async (url, params) => {
relay._coinosRL = true;
const notice = relay.onnotice;
relay.onnotice = (msg) => {
- if (RATE_LIMITED.test(String(msg))) markRelayRateLimited(relay.url, String(msg));
+ // Primal's "too many concurrent REQs" is advice, not a refusal: every
+ // REQ past its twenty is answered all the same (measured: 60 at once,
+ // 60 EOSEs, 12 notices). Cooling it off for 30 s at every boot — when
+ // the relay lists, profiles and the feed all ask at once — only lost
+ // us its answers. A CLOSED with that reason still counts (below).
+ if (RATE_LIMITED.test(String(msg)) && !/concurrent/i.test(String(msg))) markRelayRateLimited(relay.url, String(msg));
try { notice?.call(relay, msg); } catch {}
};
const subscribe = relay.subscribe.bind(relay);
@@ -284,6 +290,54 @@ export function resetRelay(url) {
try { r.close(); } catch {}
pool.relays.delete(n);
}
+// Back from a freeze (a phone's backgrounded tab: timers stopped, the
+// network's idea of every socket long gone), the pool's sockets still read
+// OPEN, and anything sent on them vanishes. Left to itself the library
+// notices one in up to 29 s (its ping) + 20 s (the ping's timeout), then
+// waits 10 s more before redialing — a minute of a feed that won't catch up
+// ("no new notes since 11:35?", Adam, 2026-11-01). So on resume every open
+// socket is asked one tiny REQ; one that answers within the deadline is
+// fine, one that doesn't is closed and redialed now, its subscriptions
+// refired by the library with `since` set to the last event each saw. A
+// relay already waiting out a reconnect backoff is dialed now too.
+const WAKE_PING_MS = 2500;
+const DUMMY_ID = 'a'.repeat(64);
+function pingRelay(r, ms) {
+ return new Promise((resolve) => {
+ let done = false;
+ const fin = (ok) => { if (done) return; done = true; clearTimeout(t); resolve(ok); };
+ const t = setTimeout(() => fin(false), ms);
+ try {
+ const sub = r.subscribe([{ ids: [DUMMY_ID], limit: 0 }], {
+ label: '<wake-ping>',
+ oneose: () => { fin(true); try { sub.close(); } catch {} },
+ onclose: () => fin(true), // a relay refusing the REQ is a relay that answers
+ eoseTimeout: ms + 1000, // ours fires first: the library's would count as an EOSE
+ });
+ } catch { fin(false); }
+ });
+}
+function redialRelay(r, why) {
+ console.warn('nostr: ' + r.url + ' ' + why + ' — redialing');
+ // the dead socket's close would reach the library long after (a closing
+ // handshake nobody answers), and undo the new connection: detached first
+ const ws = r.ws;
+ try { if (ws) { ws.onopen = ws.onclose = ws.onerror = ws.onmessage = null; ws.close(); } } catch {}
+ try { r.handleHardClose(why); } catch {} // the library's own path: subscriptions kept, a reconnect queued
+ if (r.reconnectTimeoutHandle) { clearTimeout(r.reconnectTimeoutHandle); r.reconnectTimeoutHandle = undefined; }
+ r.connect().catch(() => {}); // now, not after the backoff
+}
+export async function wakeRelays(ms = WAKE_PING_MS) {
+ const checks = [];
+ for (const r of pool.relays.values()) {
+ if (r.connected && r.ws && r.ws.readyState === 1) checks.push(pingRelay(r, ms).then((ok) => { if (!ok) redialRelay(r, 'silent after resume'); }));
+ else if (!r.connectionPromise && r.reconnectTimeoutHandle) {
+ clearTimeout(r.reconnectTimeoutHandle); r.reconnectTimeoutHandle = undefined;
+ r.connect().catch(() => {});
+ }
+ }
+ await Promise.all(checks);
+}
// the relays a subscription on this list actually dials (sick ones skipped)
export const liveRelayList = (list) => liveRelays(list);
// ...and the ones a one-shot read goes to (rate-limited ones skipped too)
@@ -354,12 +408,77 @@ async function authRelay(relay, onauth) {
}
return relay.auth(onauth);
}
+// ---- one-shot reads: per relay, closed on its own EOSE, a few at a time --
+// The pool's own querySync keeps every relay's REQ open until the SLOWEST
+// relay has answered or the wait runs out: asked beside a relay still
+// dialing, our own relay — done in fifty milliseconds — carried each REQ
+// for five seconds, and a feed's opening asks stacked up on it by the
+// dozen. Each relay's REQ now closes on that relay's EOSE. And no relay
+// carries more than REQ_SLOTS of them at once: the rest wait their turn,
+// which is a beat on a relay that answers and no longer than the wait on
+// one that doesn't. (A Following feed opened from the laptop sent some 560
+// REQs in twenty seconds across 57 relays, over a hundred each to damus
+// and primal; damus answered the home IP "banned: too many rate-limit
+// violations" on 2026-11-02, and primal notices past twenty at once.)
+const REQ_SLOTS = 10;
+const slots = new Map(); // normalized url -> { n, q: [resolve] }
+function takeSlot(url) {
+ const k = relayKey(url);
+ let s = slots.get(k);
+ if (!s) slots.set(k, (s = { n: 0, q: [] }));
+ if (s.n < REQ_SLOTS) { s.n++; return Promise.resolve(false); }
+ const at = Date.now();
+ return new Promise((resolve) => s.q.push(() => resolve(Date.now() - at))); // how long it waited
+}
+function freeSlot(url) {
+ const s = slots.get(relayKey(url));
+ if (!s) return;
+ const next = s.q.shift();
+ if (next) next(); // the slot passes straight to the next in line
+ else s.n--;
+}
+export const reqSlotsOf = (url) => { const s = slots.get(relayKey(url)); return s ? { busy: s.n, waiting: s.q.length } : { busy: 0, waiting: 0 }; };
+// One REQ carrying `filters` on one relay. Settles at the relay's EOSE, its
+// CLOSED, a failed dial, or maxWait — whichever is first — and sends CLOSE.
+function askRelay(url, filters, maxWait, onEvent) {
+ return new Promise((resolve) => {
+ let finished = false, sub = null, timer = 0;
+ const finish = () => {
+ if (finished) return;
+ finished = true;
+ clearTimeout(timer);
+ if (sub) { try { sub.close('done'); } catch {} }
+ freeSlot(url);
+ resolve();
+ };
+ takeSlot(url).then((waited) => {
+ // a turn that came only after the ask's own wait had run out: the
+ // caller has moved on, and a storm of late REQs helps nobody
+ if (waited > maxWait) { finish(); return; }
+ timer = setTimeout(finish, maxWait + 1000);
+ try {
+ sub = pool.subscribeMap(filters.map((filter) => ({ url, filter })), { maxWait, onevent: onEvent, oneose: finish, onclose: finish });
+ if (finished) { try { sub.close('done'); } catch {} }
+ } catch { finish(); }
+ });
+ });
+}
+// All relays asked at once; an event is counted once however many hold it.
+async function askRelays(relays, filters, maxWait, onEvent) {
+ const seen = new Set();
+ await Promise.all(relays.map((url) => askRelay(url, filters, maxWait, (ev) => {
+ if (!ev || seen.has(ev.id)) return;
+ seen.add(ev.id);
+ onEvent(ev);
+ })));
+}
export async function queryOn(relays, filter, maxWait = 1500) {
probeRelays(relays);
try {
const live = readRelays(relays);
if (!live.length) return [];
- const evs = await pool.querySync(live, filter, { maxWait });
+ const evs = [];
+ await askRelays(live, [filter], maxWait, (ev) => evs.push(ev));
const oks = await verifyEventsAsync(evs);
return evs.filter((_, i) => oks[i]);
} catch { return []; }
@@ -464,17 +583,8 @@ export async function queryManyOn(relays, filters, maxWait = 1500) {
try {
const live = readRelays(relays);
if (!live.length || !filters.length) return [];
- const evs = await new Promise((resolve) => {
- const got = [];
- let sub = null, done = false;
- const finish = () => { if (!done) { done = true; resolve(got); } };
- sub = pool.subscribeMap(live.flatMap((url) => filters.map((filter) => ({ url, filter }))), {
- maxWait,
- onevent: (e) => got.push(e),
- oneose: () => { try { sub?.close('closed automatically on eose'); } catch {} finish(); },
- onclose: finish,
- });
- });
+ const evs = [];
+ await askRelays(live, filters, maxWait, (ev) => evs.push(ev));
const oks = await verifyEventsAsync(evs);
return evs.filter((_, i) => oks[i]);
} catch { return []; }
@@ -487,18 +597,37 @@ export async function queryStreamOn(relays, filter, onEvent, maxWait = 1500) {
try {
const live = readRelays(relays);
if (!live.length) return;
- await new Promise((resolve) => {
- pool.subscribeManyEose(live, filter, {
- maxWait,
- onevent(event) {
- pending.push(verifyOneAsync(event).then((ok) => ok && onEvent(event)).catch(() => {}));
- },
- onclose: resolve,
- });
+ await askRelays(live, [filter], maxWait, (event) => {
+ pending.push(verifyOneAsync(event).then((ok) => ok && onEvent(event)).catch(() => {}));
});
} catch {} finally { await Promise.all(pending); }
}
-export async function publishOn(relays, evt, { onauth = null } = {}) {
+// queryStreamOn that also says how deep each relay's answer went: resolves
+// with [{ url, n, min }] — how many events that relay sent for the filter and
+// the oldest created_at among them. A caller paging backwards needs it:
+// relays hold different parts of an author's history, and the oldest event
+// of the merged answer may be one relay's stray copy from months earlier.
+export async function queryDepthOn(relays, filter, onEvent, maxWait = 1500) {
+ probeRelays(relays);
+ const pending = [], stats = [], seen = new Set();
+ try {
+ const live = readRelays(relays);
+ await Promise.all(live.map((url) => {
+ const s = { url, n: 0, min: Infinity };
+ stats.push(s);
+ return askRelay(url, [filter], maxWait, (event) => {
+ if (!event) return;
+ s.n++;
+ if (event.created_at < s.min) s.min = event.created_at;
+ if (seen.has(event.id)) return;
+ seen.add(event.id);
+ pending.push(verifyOneAsync(event).then((ok) => ok && onEvent(event)).catch(() => {}));
+ });
+ }));
+ } catch {} finally { await Promise.all(pending); }
+ return stats;
+}
+export async function publishOn(relays, evt, { onauth = null, onrefused = null } = {}) {
try {
const live = liveRelays(relays);
// A rejected publish is a relay refusing the event (policy, rate limit,
@@ -520,7 +649,12 @@ export async function publishOn(relays, evt, { onauth = null } = {}) {
// "relay connection errored/closed" means the socket never came up —
// that's a sick relay, not a rejected event.
if (/connect|closed|errored|timeout|network/i.test(msg)) markRelaySick(live[i], msg);
- else console.warn(`nostr: publish kind ${evt.kind} refused by ${live[i]}:`, msg);
+ else {
+ console.warn(`nostr: publish kind ${evt.kind} refused by ${live[i]}:`, msg);
+ // the relay said no to this event (policy, a rate limit, a ban): a
+ // caller can stop asking it
+ if (onrefused) try { onrefused(live[i], msg); } catch {}
+ }
return false;
}));
// The first acceptance IS delivery — one durable copy is enough, and
@@ -542,13 +676,21 @@ export { getPublicKey, finalizeEvent, generateSecretKey };
// The nostr identity a seed carries (NostrSync#load's key, without the
// wallet) — so the account switcher can put a face on every account on the
-// device, not just the one that's open. Memoized: nip06 stretches the seed.
+// device, not just the one that's open. Memoized: the seed is stretched.
+// NIP-06: m/44'/1237'/<account>'/0/0 of the BIP-39 seed — what nostr-tools'
+// privateKeyFromSeedWords derives, from the seed the wallet already stretched
+// (seed.js) instead of stretching the words a second time.
+export function nostrKeyFromSeed(mnemonic, passphrase = '', accountIndex = 0) {
+ const sk = HDKey.fromMasterSeed(seedSync(mnemonic, passphrase || '')).derive(`m/44'/1237'/${accountIndex || 0}'/0/0`).privateKey;
+ if (!sk) throw new Error('could not derive private key');
+ return sk;
+}
const _seedPks = new Map();
export function seedPubkey(mnemonic, passphrase = '', accountIndex = 0) {
const k = `${mnemonic}\n${passphrase}\n${accountIndex}`;
if (_seedPks.has(k)) return _seedPks.get(k);
let pk = null;
- try { pk = getPublicKey(nip06.privateKeyFromSeedWords(mnemonic, passphrase || undefined, accountIndex || 0)); } catch {}
+ try { pk = getPublicKey(nostrKeyFromSeed(mnemonic, passphrase, accountIndex)); } catch {}
_seedPks.set(k, pk);
return pk;
}
@@ -599,7 +741,7 @@ export const PROFILE_RELAYS = HOME_RELAYS;
// Fetch a recipient's profile (name + picture) for a pubkey, newest across relays.
export async function fetchNostrProfile(pubkeyHex, relays = PROFILE_RELAYS) {
let events;
- try { events = await pool.querySync(relays, { kinds: [0], authors: [pubkeyHex] }, { maxWait: 5000 }); } catch { return null; }
+ try { events = await queryOn(relays, { kinds: [0], authors: [pubkeyHex] }, 5000); } catch { return null; }
const best = events.sort((a, b) => b.created_at - a.created_at)[0];
if (!best) return null;
try {
@@ -621,7 +763,7 @@ export async function fetchNostrProfile(pubkeyHex, relays = PROFILE_RELAYS) {
// 10050), else their NIP-65 read relays (kind 10002), else [] (caller falls back).
export async function fetchInboxRelays(pubkeyHex, relays = PROFILE_RELAYS) {
let events;
- try { events = await pool.querySync(relays, { kinds: [10002, 10050], authors: [pubkeyHex] }, { maxWait: 5000 }); } catch { return []; }
+ try { events = await queryOn(relays, { kinds: [10002, 10050], authors: [pubkeyHex] }, 5000); } catch { return []; }
const newest = (kind) => events.filter((e) => e.kind === kind).sort((a, b) => b.created_at - a.created_at)[0];
const dm = newest(10050);
if (dm) { const r = dm.tags.filter((t) => t[0] === 'relay' && t[1]).map((t) => t[1]); if (r.length) return r; }
@@ -731,8 +873,8 @@ export class NostrSync {
load(mnemonic, passphrase = '', accountIndex = 0) {
// a derived sibling wallet (same seed, higher BIP84 account) gets its own
- // nostr identity and sync slots — nip06 shifts by account index
- this.sk = nip06.privateKeyFromSeedWords(mnemonic, passphrase || undefined, accountIndex || 0);
+ // nostr identity and sync slots — NIP-06 shifts by account index
+ this.sk = nostrKeyFromSeed(mnemonic, passphrase, accountIndex);
this.pk = getPublicKey(this.sk);
this.ck = nip44.getConversationKey(this.sk, this.pk);
}
diff --git a/src/notify-text.js b/src/notify-text.js
new file mode 100644
index 0000000..a88ab14
--- /dev/null
+++ b/src/notify-text.js
@@ -0,0 +1,79 @@
+// The words of every notification the worker shows while the app is closed.
+//
+// Chrome on Android (and, quietly, on desktop) scores each web notification's
+// title and body with an on-device "unwanted notification" model before it
+// shows it, and above 90 of 100 the notification is replaced by a "Possible
+// spam" warning — hidden until the user taps "Show notification", and nine
+// such in a week revoke the site's permission outright on a phone that
+// doesn't visit much (Chromium kAutoRevokeSuspiciousNotification). Our old
+// wording scored 92–99 across the board: "Payment received", "Incoming
+// payment", "Payment request", "alice is calling", "New message", "alice
+// sent you a message" — the exact shape of the scam notifications the model
+// was trained (on synthetic data) to catch. What it lets through is less a
+// rule than a measurement; the scores here come from Chrome 156's model via
+// tools/notif-spam-score.js, which re-scores SAMPLES in a throwaway Chrome.
+// Measured 2026-11-03: "sats" reads as money without reading as a payment
+// scam (9–14), "payment" does not (95–97); a person's NAME in the body of a
+// message or reaction line pushes it over (80–99), "New chat" / "<name>"
+// does not (8–32); "reply" in any title is 96–99, "Someone replied" /
+// "Open coinos to see it." is 13; a reply's TEXT is uncontrollable (an
+// "@name" or a link in it scores 97+), so none rides along; "Calling" /
+// "<name>" is 11–29 where every "<name> is calling" shape is 80–99.
+// Re-run the scorer before changing any of these.
+
+export const OPEN = 'Open coinos to see it.';
+
+function sats(n) {
+ const v = Number(n);
+ return v > 0 ? `+${v.toLocaleString()} sats. ${OPEN}` : OPEN;
+}
+
+// A user-facing notification by reason. `d` is the push payload (amountSat,
+// emoji) plus what the device adds (a sender's name).
+export function notifyText(reason, d = {}) {
+ switch (reason) {
+ case 'payment': return ['Sats received', sats(d.amountSat)];
+ case 'zap': return ['Zap received', sats(d.amountSat)];
+ case 'dm': return ['New chat', d.name || 'Someone wrote to you'];
+ case 'chat': return ['New chat activity', 'There are new messages in your communities.'];
+ case 'mention': return [d.reply ? 'Someone replied' : 'You were mentioned', OPEN];
+ case 'reaction': {
+ // a unicode emoji in the title is fine (17); a :shortcode: is not (85)
+ const e = d.emoji && !/^:[\w-]+:$/.test(d.emoji) ? ' ' + d.emoji : '';
+ return ['New reaction' + e, `to your post. ${OPEN}`];
+ }
+ case 'call': return ['Calling', d.name || 'Someone'];
+ // the wallet was asked for an invoice while closed (someone paying its name)
+ case 'incoming': return ['Someone is sending sats', 'Open coinos to receive them.'];
+ // a connected app asked the closed wallet to pay
+ case 'spend': return ['Spend request', 'A connected app asked to spend sats. Open coinos to approve.'];
+ default: return notifyText('chat');
+ }
+}
+
+// What tools/notif-spam-score.js scores: one line per shape a user can see.
+export const SAMPLES = [
+ notifyText('payment', { amountSat: 1000 }),
+ notifyText('payment', { amountSat: 21 }),
+ notifyText('payment'),
+ notifyText('zap', { amountSat: 1000 }),
+ notifyText('zap'),
+ notifyText('dm', { name: 'alice' }),
+ notifyText('dm', { name: 'Bitcoin Bob' }),
+ notifyText('dm', { name: 'Jarryd' }),
+ notifyText('dm'),
+ notifyText('chat'),
+ notifyText('mention'),
+ notifyText('mention', { reply: true }),
+ notifyText('reaction', { emoji: '❤️' }),
+ notifyText('reaction', { emoji: '🤙' }),
+ notifyText('reaction', { emoji: ':pepe:' }),
+ notifyText('call', { name: 'alice' }),
+ notifyText('call', { name: 'Bitcoin Bob' }),
+ notifyText('call', { name: 'Alice Caller' }),
+ notifyText('call'),
+ notifyText('incoming'),
+ notifyText('spend'),
+ ['Payment sent', '-1,000 sats via Damus'],
+ ['Spending balance', 'Receive or spend sats before 11/20/2026 to keep it alive.'],
+];
diff --git a/src/nwc-bg.js b/src/nwc-bg.js
index 3bdef08..9e7a303 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);
@@ -76,15 +133,22 @@ export async function allBgs() {
}
// How many upcoming change/refund indices travel with the record: the worker
-// cannot derive keys, so its allocations must land inside this window.
-export const BG_KEY_LOOKAHEAD = 25;
+// cannot derive keys, so its allocations must land inside this window. Each
+// Lightning send burns a change and an HTLC index, so 25 keys lasted PullCap
+// about 19 hourly payments (2026-10-26, "key window exhausted" after a day
+// with the app closed). 250 keys are 16 KB in the record and cover weeks of
+// hourly payments, or years of monthly ones; the app tops the window up
+// every time it writes the mirror.
+export const BG_KEY_LOOKAHEAD = 250;
+// ...and the receive preimages a closed wallet can mint invoices with
+export const BG_RECV_LOOKAHEAD = 60;
// { ark } endpoints, the manager state to mirror, and a keyFor(chain, index)
// derive function (the caller owns the account node — it never enters this
// module). Chain 3 covers coins + change, chain 4/0 the mailbox, chain 5 a
// window of receive preimages — everything the worker needs to pay AND to
// mint invoices while the app is closed.
-export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdraw }) {
+export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdraw, custody }) {
const keys = {};
const idx = new Set((mgrState.vtxos || []).filter((v) => v.state !== 'spent').map((v) => v.keyIndex));
for (let i = 0; i < BG_KEY_LOOKAHEAD; i++) idx.add((mgrState.nextKeyIndex || 1) + i);
@@ -96,7 +160,7 @@ export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdra
idx.add(0); // the receive-address key: mailbox/refund defaults land on it
for (const i of idx) keys[String(i)] = keyFor(3, i);
const keys5 = {};
- for (let i = 0; i < 15; i++) {
+ for (let i = 0; i < BG_RECV_LOOKAHEAD; i++) {
const n = (mgrState.nextLnRecvIndex || 0) + i;
keys5[String(n)] = keyFor(5, n);
}
@@ -112,11 +176,14 @@ export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdra
// { on, threshold, keep, target: { kind, address, url?, spkHex? } } — the
// destination is resolved by the app, so the worker never needs a relay
autowithdraw: autowithdraw || null,
+ // the custody tier ('custodial' | 'self' | 'early'): whether the worker
+ // registers renewal orders for bare coins, and how far ahead
+ custody: custody || null,
// The budget's spent counter rides along (stamped with its window) so the
// 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 ec19923..311b928 100644
--- a/src/nwc-respond.js
+++ b/src/nwc-respond.js
@@ -14,6 +14,7 @@
// to a notification that opens the wallet.
import { hex } from '@scure/base';
+import { notifyText } from './notify-text.js';
import * as nip04 from 'nostr-tools/nip04';
import * as nip44 from 'nostr-tools/nip44';
import { finalizeEvent } from 'nostr-tools/pure';
@@ -21,9 +22,17 @@ import { ArkManager } from './ark/manager.js';
import { maybeBolt11 } from './ark/lightning.js';
import { allBgs, saveBg } from './nwc-bg.js';
import { budgetRenewsAt, renewalPeriod, spentInWindow } from './nwc-budget.js';
-import { backstopMargin } from './ark/manager.js';
+import { renewPolicy } from './ark/manager.js';
const MAX_AGE_SEC = 120;
+// A request the worker can't act on (keys or coins short in the mirror, an
+// old mirror) wakes the user — and, unless someone answers first, tells the
+// other app so (PullCap read the silence as "no answer" and suspended the
+// subscription; with an error it can tell the payer their wallet is waiting
+// for them). The notifier holds the reply this long before sending it.
+const DECLINE_AFTER_MS = 20_000;
+const FAIL_AFTER_MS = 5_000; // the notifier's shortest hold
+const WAIT_MSG = 'Coinos is waiting for its owner to open the app and approve. Look this request up again later.';
const PAY_WAIT_MS = 20_000; // inside the SW's ~30s budget, with reply margin
const nowSec = () => Math.floor(Date.now() / 1000);
const errRes = (t, code, message) => ({ result_type: t, error: { code, message } });
@@ -61,15 +70,97 @@ 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 : ''}`);
+ }
+ }
+ // the worker's hand on the mirror, for an app alive behind it: it
+ // folds this state in before it next writes its own over it
+ rec.workerAt = Date.now();
+ Promise.resolve(saveFn(walletKey, rec)).catch(() => {});
+ },
};
- return new ArkManager({
+ const m = new ArkManager({
account: shimAccount(rec), storage,
arkUrl: rec.ark.arkUrl, esploraUrl: rec.ark.esploraUrl, network: rec.ark.network,
- }).init();
+ honorsExpired: !!rec.ark.honorsExpired,
+ lnOldestFirst: () => !!rec.custody && rec.custody !== 'custodial',
+ });
+ // the chain tip a payment needs, asked for while the manager starts
+ try { m.warmTip().catch(() => {}); } catch { /* asked again when needed */ }
+ return m.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
@@ -114,7 +205,8 @@ async function respondOffer(ev, rec, walletKey, { notifier, fetchFn, saveFn, log
await saveFn(walletKey, rec);
await publish({ bolt11: a.invoice });
log(`minted ${sat} sat offer invoice while closed`);
- return { notify: { title: 'Incoming payment', body: 'Someone is paying you. Open Coinos to receive it.' } };
+ const [title, body] = notifyText('incoming');
+ return { notify: { title, body } };
} catch (e) {
log('offer mint failed: ' + e.message);
await publish({ error: 'Temporary Failure', code: 2 }).catch(() => {});
@@ -127,11 +219,14 @@ 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;
- if (nowSec() - (ev.created_at || 0) > MAX_AGE_SEC) return false;
+ // Older than the request window (a push that sat at APNs while the phone
+ // was out of reach): the other app has moved on — nothing to answer, and
+ // no "Payment request" to show for it. The wake still tends what's in flight.
+ if (nowSec() - (ev.created_at || 0) > MAX_AGE_SEC) { log(`request ${String(ev.id).slice(0, 8)} is ${nowSec() - ev.created_at} s old — ignored`); return true; }
const target = (ev.tags?.find((t) => t[0] === 'p') || [])[1];
if (!target) return false;
@@ -175,6 +270,23 @@ 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 || {};
+ // Wake the user, out loud: the wait reply is left with the notifier, which
+ // sends it only if nobody (a sibling device, the woken user) answers in
+ // time — so it can never land on top of a real payment.
+ const declineLater = async (why) => {
+ log(why + ' — waking the user; the app is told to wait');
+ try {
+ const evt = await buildReply(conn, ev, scheme, errRes(method || 'error', 'OTHER', WAIT_MSG));
+ await fetchFn(`${notifier}/decline`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ event: evt, afterMs: DECLINE_AFTER_MS }),
+ });
+ } catch (e) { log('could not leave the wait reply: ' + (e && e.message)); }
+ return false;
+ };
+ // 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) {
@@ -194,6 +306,8 @@ export async function respondFromBg(data, {
// ...and hands each pay request to the first device that claims it, so
// two awake devices don't each lock an HTLC for one zap. Unreachable →
// proceed: a lone worker must not go silent over a notifier hiccup.
+ // (the same call says when a reply already exists: one round trip where
+ // "answered?" and "mine?" used to be two, one after the other)
const claim = async () => {
try {
const r = await fetchFn(`${notifier}/claim`, {
@@ -201,9 +315,25 @@ export async function respondFromBg(data, {
body: JSON.stringify({ event: ev.id, by: `sw-${walletKey}`.slice(0, 64) }),
});
if (!r.ok) return true;
- return (await r.json()).ok !== false;
+ const j = await r.json();
+ if (j.answered) return 'answered';
+ return j.ok !== false;
} catch { return true; }
};
+ // a claim this worker can't make good on (the wallet's server unreachable)
+ // is handed back, so the app the user opens isn't told to stand down
+ const unclaim = () => {
+ try {
+ Promise.resolve(fetchFn(`${notifier}/claim`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ event: ev.id, by: `sw-${walletKey}`.slice(0, 64), release: true }),
+ })).catch(() => {});
+ } catch { /* it lapses by itself */ }
+ };
+ const lostClaim = (c) => {
+ log(c === 'answered' ? 'already answered elsewhere' : 'another device claimed this request — standing down');
+ return true;
+ };
if (method === 'get_info') {
await publish({
@@ -223,9 +353,9 @@ export async function respondFromBg(data, {
if (method === 'make_invoice') {
const sat = Math.floor((params.amount || 0) / 1000);
if (!sat) { await publish(errRes('make_invoice', 'OTHER', 'amount required (msat)')); return true; }
- if (!rec.keys5 || !rec.key4 || !rec.mgr) return false; // old mirror: wake the user
- if (!rec.keys5[String(rec.mgr.nextLnRecvIndex || 0)]) return false; // preimage window exhausted
- if (!rec.keys[String(rec.mgr.nextKeyIndex || 1)]) return false; // claim key window exhausted
+ if (!rec.keys5 || !rec.key4 || !rec.mgr) return declineLater('old mirror, no receive keys');
+ if (!rec.keys5[String(rec.mgr.nextLnRecvIndex || 0)]) return declineLater('preimage window exhausted');
+ if (!rec.keys[String(rec.mgr.nextKeyIndex || 1)]) return declineLater('key window exhausted');
let a;
try {
const mgr = await bgManager(rec, walletKey, saveFn);
@@ -251,23 +381,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 declineLater('old mirror, no state to look up');
+ // 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 } });
@@ -303,12 +457,21 @@ export async function respondFromBg(data, {
}
// ---- pay_invoice ------------------------------------------------------
- if (await answered()) { log('already answered elsewhere'); return true; }
-
+ // What the mirror alone can decide comes first, with no network at all;
+ // then the claim (which also says if someone already answered) goes out
+ // beside the manager's start. Each of these used to wait for the one
+ // before it: a zap answered from a closed phone spent about six seconds
+ // getting to the payment (398ja, 2026-11-10: "a lot more slower").
+ // A refusal never goes out over another device's answer.
+ const refuse = async (code, message) => {
+ if (await answered()) { log('already answered elsewhere'); return true; }
+ await publish(errRes('pay_invoice', code, message));
+ return true;
+ };
const invoice = params.invoice;
const dec = invoice && maybeBolt11(invoice);
- if (!dec) { await publish(errRes('pay_invoice', 'OTHER', 'not a bolt11 invoice')); return true; }
- if (!dec.amountSat) { await publish(errRes('pay_invoice', 'OTHER', 'zero-amount invoices are not supported')); return true; }
+ if (!dec) return refuse('OTHER', 'not a bolt11 invoice');
+ if (!dec.amountSat) return refuse('OTHER', 'zero-amount invoices are not supported');
// The bolt11 names its network; only a record on that network can pay it.
// A mismatched copy fails in milliseconds with a nonsense error that beats
// a sibling device's real payment to the client — so stand down instead,
@@ -321,54 +484,135 @@ export async function respondFromBg(data, {
return answered();
}
({ walletKey, rec, conn } = fit);
- if (dec.amountSat > conn.maxSat) {
- await publish(errRes('pay_invoice', 'QUOTA_EXCEEDED', `over the ${conn.maxSat} sat per-payment limit`));
- return true;
- }
+ if (dec.amountSat > conn.maxSat) return refuse('QUOTA_EXCEEDED', `over the ${conn.maxSat} sat per-payment limit`);
// What the app spent this window rides on the mirrored connection; the
// worker's own spends the app has not yet folded in are counted from its log.
const { left } = spentInWindow(conn, rec.spends || []);
- if (dec.amountSat > left) {
- 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 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.
+ if (dec.amountSat > left) return refuse('QUOTA_EXCEEDED', `over the remaining ${renewalPeriod(conn.period)} budget (${left} sat)`);
+ // 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 — a sibling device's slower SUCCESS
+ // reply must win the client's eyes instead of being shouted over. The
+ // error is left with the notifier, which sends it only if nobody answers
+ // in FAIL_AFTER_MS: waiting here instead ran past iOS's ten seconds after
+ // a failed send, and the other app heard nothing at all (PullCap,
+ // 2026-10-29). Waiting here is the fallback when the notifier won't take it.
const failQuietly = async (message) => {
+ const code = /insufficient/i.test(message || '') ? 'INSUFFICIENT_BALANCE' : 'PAYMENT_FAILED';
+ try {
+ const evt = await buildReply(conn, ev, scheme, errRes('pay_invoice', code, message));
+ const r = await fetchFn(`${notifier}/decline`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ event: evt, afterMs: FAIL_AFTER_MS }),
+ });
+ if (r.ok) { log(`payment failed (${message}) — ${code} goes out unless someone answers first`); return true; }
+ } catch {}
await new Promise((r) => setTimeout(r, errGraceMs));
if (!(await answered())) {
- await publish(errRes('pay_invoice', 'INTERNAL', message)).catch(() => {});
+ await publish(errRes('pay_invoice', code, message)).catch(() => {});
}
return true;
};
- if (!(await claim())) { log('another device claimed this request — standing down'); return true; }
- const deadline = Date.now() + PAY_WAIT_MS;
+ 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) {
+ const c = await claim();
+ if (c !== true) return lostClaim(c);
+ 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) {
+ if (await answered()) { log('already answered elsewhere'); return true; }
+ 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) return declineLater(`${spendable} sat spendable in the mirror, ${dec.amountSat} asked`);
+
+ // 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)]) return declineLater('key window exhausted');
+ // the claim and the manager's start (begun above), side by side
+ const claimP = claim();
+ try { await ready(); } catch (e) {
+ const c = await claimP;
+ if (c !== true) return lostClaim(c);
+ unclaim();
+ return declineLater('ark init failed: ' + e.message);
+ }
+ const mine = await claimP;
+ if (mine !== true) return lostClaim(mine);
+ // whose send this is, for the wake that finishes it should this one not
+ notePending(rec, dec.paymentHash, conn);
+ // (not waited on: the manager's own save of the new send, a moment on,
+ // writes this same record)
+ Promise.resolve(saveFn(walletKey, rec)).catch(() => {});
+ 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.
@@ -383,6 +627,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; }
@@ -393,38 +638,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
@@ -460,12 +717,21 @@ export async function tendRenewals({ recordsFn = allBgs, saveFn = saveBg, log =
if (a.step === 'done') { n++; log('claimed a renewal while closed'); }
}
// coins without an order: register one, as long as the output key the
- // order burns is inside the mirrored window (the worker can't derive)
+ // order burns is inside the mirrored window (the worker can't derive).
+ // Only under a custody tier that renews at all — the default lets coins
+ // run past their timelock in coinos's hands, by choice, and pays nothing.
+ const policy = renewPolicy(rec.custody || 'custodial', rec.ark.network);
let room = 0;
while (rec.keys[String((mgr.state.nextKeyIndex || 1) + room)] && room < 4) room++;
- if (room) {
- const got = await bounded(mgr.ensureScheduledRefreshes(margin ?? backstopMargin(rec.ark.network), room)).catch((e) => { log('renewal order: ' + e.message); return 0; });
- if (got) { n += got; log(`registered ${got} renewal order(s) while closed`); }
+ if (room && policy) {
+ const got = await bounded(mgr.ensureScheduledRefreshes(margin ?? policy.margin, room, policy.grid)).catch((e) => { log('renewal order: ' + e.message); return 0; });
+ if (got) { n += got; room -= got; log(`registered ${got} renewal order(s) while closed`); }
+ }
+ // Under every tier: a coin near the server's depth cap must be
+ // flattened to stay spendable (the base fee is waived for it).
+ if (room > 0) {
+ const got = await bounded(mgr.ensureDeepRefreshes(room)).catch((e) => { log('deep refresh order: ' + e.message); return 0; });
+ if (got) { n += got; log(`registered ${got} deep-coin renewal order(s) while closed`); }
}
await saveFn(walletKey, rec);
} catch (e) { log('renewals: ' + e.message); }
diff --git a/src/passkey.js b/src/passkey.js
index 248e1e6..7d5e6e5 100644
--- a/src/passkey.js
+++ b/src/passkey.js
@@ -54,14 +54,16 @@ export async function passkeySignIn() {
// Create a passkey, then derive the key from it. Some platforms evaluate PRF
// during creation; the rest need a follow-up assertion against the new
// credential — both paths end at the same bytes.
-export async function passkeyCreate() {
+// `name` labels the credential in the platform's passkey picker (a way back
+// into a named account reads "[email protected]", not just "coinos").
+export async function passkeyCreate({ name = 'coinos', displayName = 'Coinos wallet' } = {}) {
const cred = await navigator.credentials.create({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rp: { name: 'Coinos', id: location.hostname },
user: {
id: crypto.getRandomValues(new Uint8Array(16)),
- name: 'coinos', displayName: 'Coinos wallet',
+ name, displayName,
},
pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
authenticatorSelection: { residentKey: 'required', userVerification: 'required' },
diff --git a/src/pay-page.html b/src/pay-page.html
new file mode 100644
index 0000000..87c4739
--- /dev/null
+++ b/src/pay-page.html
@@ -0,0 +1,67 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="color-scheme" content="light dark">
+<title>Pay with Lightning · coinos</title>
+<meta name="description" content="Pay a coinos address over Lightning.">
+<link rel="icon" href="/icon.svg" type="image/svg+xml">
+<style>
+@font-face { font-family: 'Public Sans'; src: url('/PublicSans.woff2') format('woff2'); font-weight: 100 900; font-display: swap; }
+:root {
+ --bg: #eef0f3; --paper: #fff; --ink: #15171a; --muted: #6b7280; --faint: #9aa1ac;
+ --line: #e6e8ec; --fill: #15171a; --fill-fg: #fff; --green: #14935a; --red: #c43b3b; --soft: #f4f5f7;
+}
+@media (prefers-color-scheme: dark) {
+ :root { --bg: #0b0c0e; --paper: #16181b; --ink: #f2f3f5; --muted: #a0a6b0; --faint: #6b7280;
+ --line: #2a2d32; --fill: #f2f3f5; --fill-fg: #15171a; --green: #3fbf7f; --red: #ef6b6b; --soft: #1f2226; }
+}
+* { box-sizing: border-box; }
+body { margin: 0; background: var(--bg); color: var(--ink); font: 16px/1.5 'Public Sans', system-ui, sans-serif; }
+main { max-width: 420px; margin: 0 auto; padding: 28px 16px 48px; }
+.who { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 4px; margin-bottom: 18px; color: inherit; text-decoration: none; }
+.who img { width: 72px; height: 72px; border-radius: 50%; object-fit: cover; background: var(--soft); }
+.who .display { font-weight: 700; font-size: 20px; }
+.who .handle { color: var(--muted); font-size: 14px; overflow-wrap: anywhere; }
+.card { background: var(--paper); border: 1px solid var(--line); border-radius: 16px; padding: 18px; margin-bottom: 14px; display: flex; flex-direction: column; gap: 12px; }
+.qr { display: block; background: #fff; border-radius: 12px; padding: 10px; }
+.qr svg { display: block; width: 100%; height: auto; }
+.hint { margin: 0; color: var(--muted); font-size: 14px; text-align: center; }
+.row { display: flex; gap: 8px; align-items: center; }
+.row > * { flex: 1; }
+.row > button { flex: 0 0 auto; white-space: nowrap; }
+.addr { font: 14px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; flex: 2; }
+label { font-weight: 600; }
+input { width: 100%; font: inherit; color: inherit; background: var(--soft); border: 1px solid var(--line); border-radius: 10px; padding: 11px 12px; }
+input:focus { outline: 2px solid var(--fill); outline-offset: -1px; }
+.amount-form { display: flex; flex-direction: column; gap: 10px; }
+button, .button { font: inherit; font-weight: 600; border-radius: 10px; padding: 11px 14px; cursor: pointer; text-align: center; text-decoration: none; border: 1px solid var(--line); background: var(--soft); color: var(--ink); }
+.primary { background: var(--fill); color: var(--fill-fg); border-color: var(--fill); }
+button:disabled { opacity: .6; cursor: default; }
+.link { background: none; border: 0; color: var(--muted); padding: 4px; font-weight: 500; }
+.err { color: var(--red); font-size: 14px; }
+.err:empty { display: none; }
+.big { font-size: 28px; font-weight: 700; text-align: center; }
+.big span { font-size: 16px; font-weight: 500; color: var(--muted); }
+.status { text-align: center; color: var(--muted); font-size: 14px; }
+.done { align-items: center; text-align: center; }
+.done p { margin: 0; color: var(--muted); }
+.tick { width: 56px; height: 56px; border-radius: 50%; background: var(--green); color: #fff; font-size: 30px; line-height: 56px; }
+footer { text-align: center; color: var(--faint); font-size: 13px; margin-top: 22px; }
+footer a { color: var(--muted); }
+</style>
+</head>
+<body>
+<main>
+<a class="who" id="profile-link" href="/">
+ <img id="avatar" alt="" hidden>
+ <div class="display" id="display">Pay with Lightning</div>
+ <div class="handle" id="who"></div>
+</a>
+<div id="body"><div class="card"><p class="hint">Loading…</p></div></div>
+<footer>Powered by <a href="/">coinos</a>, a free bitcoin wallet. <a href="/">Get your own</a>.</footer>
+</main>
+<script>/*PAY_PAGE_JS*/</script>
+</body>
+</html>
diff --git a/src/pay-page.js b/src/pay-page.js
new file mode 100644
index 0000000..d34b1a5
--- /dev/null
+++ b/src/pay-page.js
@@ -0,0 +1,190 @@
+// v3.coinos.io/<name>/receive (and /<name>/pay): a page anyone can open to
+// pay a coinos name over Lightning, no wallet of their own on this site
+// needed. The link a shop or a blog puts behind its "Donate / Pay in
+// Bitcoin" button, as coinos.io/<name>/receive was on the old coinos
+// ("The old Coinos I could point this link onto my website ... I'm not
+// seeing an option to do this thru V3", JuryImagePro, relayed by Adam
+// 2026-11-23).
+//
+// Its own small page, not the app: a visitor from a website should not
+// boot a whole wallet to see a QR code. Everything comes from the names
+// registrar's public LNURL-pay endpoints; the invoice is minted by the
+// recipient's wallet when it is open, by coinos' node otherwise (forwarded
+// on settle). Only the second can be watched (LUD-21 verify), so the page
+// says "Paid" when it can and otherwise leaves it to the payer's wallet.
+//
+// On-chain is not offered: a v3 name publishes no on-chain address.
+
+import { bech32 } from '@scure/base';
+import { qrSvg } from './qr.js';
+
+const REGISTRAR = 'https://names.coinos.io';
+const DOMAIN = /(^|\.)staging\./.test(location.hostname) ? 'staging.coinos.io' : 'coinos.io';
+const PROFILE_RELAYS = ['wss://relay.coinos.io', 'wss://purplepag.es', 'wss://relay.damus.io'];
+
+const $ = (id) => document.getElementById(id);
+const el = (tag, attrs = {}, ...kids) => {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k.startsWith('on')) n.addEventListener(k.slice(2).toLowerCase(), v);
+ else if (k === 'html') n.innerHTML = v;
+ else n.setAttribute(k, v === true ? '' : v);
+ }
+ for (const k of kids.flat()) if (k != null && k !== false) n.append(k);
+ return n;
+};
+const fmt = (n) => Number(n).toLocaleString('en-US');
+
+const m = location.pathname.match(/^\/([A-Za-z0-9_][A-Za-z0-9._-]{0,29})\/(?:receive|pay)\/?$/);
+const name = m ? m[1].toLowerCase() : '';
+const address = `${name}@${DOMAIN}`;
+const lnurlpUrl = `${REGISTRAR}/lnurlp/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`;
+const params = new URLSearchParams(location.search);
+
+let payReq = null; // the name's LNURL-pay answer
+let watch = null; // the verify poll for the invoice on screen
+
+async function getJson(url, ms = 10000) {
+ const r = await fetch(url, { signal: AbortSignal.timeout(ms) });
+ const j = await r.json().catch(() => null);
+ if (!r.ok || !j || j.status === 'ERROR') throw new Error((j && j.reason) || `HTTP ${r.status}`);
+ return j;
+}
+
+// The name's face: its nostr profile, best effort. The page works without it.
+function fetchProfile(pk) {
+ return new Promise((resolve) => {
+ let best = null, left = PROFILE_RELAYS.length;
+ const socks = [];
+ const done = () => { for (const s of socks) try { s.close(); } catch {} resolve(best); };
+ const timer = setTimeout(done, 2500);
+ for (const url of PROFILE_RELAYS) {
+ let ws;
+ try { ws = new WebSocket(url); } catch { if (!--left) { clearTimeout(timer); done(); } continue; }
+ socks.push(ws);
+ ws.onopen = () => ws.send(JSON.stringify(['REQ', 'p', { kinds: [0], authors: [pk], limit: 1 }]));
+ ws.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ if (msg[0] === 'EVENT' && msg[2]?.pubkey === pk && (!best || msg[2].created_at > best.created_at)) best = msg[2];
+ if (msg[0] === 'EOSE' || msg[0] === 'CLOSED') { ws.close(); if (!--left) { clearTimeout(timer); done(); } }
+ };
+ ws.onerror = () => { if (!--left) { clearTimeout(timer); done(); } };
+ }
+ });
+}
+
+async function copy(text, btn) {
+ try { await navigator.clipboard.writeText(text); } catch {
+ const ta = el('textarea', {}, text); document.body.append(ta); ta.select();
+ try { document.execCommand('copy'); } catch {} ta.remove();
+ }
+ const was = btn.textContent;
+ btn.textContent = 'Copied';
+ setTimeout(() => { btn.textContent = was; }, 1500);
+}
+
+function qrBox(data, label) {
+ return el('a', { class: 'qr', href: data, 'aria-label': label, html: qrSvg(data, { ec: 'L', mode: /^[0-9A-Z $%*+\-./:]+$/.test(data) ? 'Alphanumeric' : undefined }) });
+}
+
+function stopWatch() { if (watch) { clearInterval(watch); watch = null; } }
+
+// The start: the name's own QR (any amount, picked in the payer's wallet)
+// and a form for a set amount.
+function showStart() {
+ stopWatch();
+ const lnurl = bech32.encode('lnurl', bech32.toWords(new TextEncoder().encode(lnurlpUrl)), 2000).toUpperCase();
+ const minSat = Math.ceil((payReq.minSendable || 1000) / 1000);
+ const maxSat = Math.floor((payReq.maxSendable || 1e11) / 1000);
+ const amount = el('input', { id: 'amount', type: 'text', inputmode: 'numeric', placeholder: 'Amount in sats', autocomplete: 'off', value: params.get('amount') || null });
+ const note = payReq.commentAllowed ? el('input', { id: 'note', type: 'text', maxlength: String(payReq.commentAllowed), placeholder: 'Note (optional)', value: params.get('memo') || params.get('note') || null }) : null;
+ const err = el('div', { class: 'err', id: 'err' });
+ const go = el('button', { class: 'primary', type: 'submit' }, 'Create invoice');
+ const form = el('form', {
+ class: 'amount-form',
+ onSubmit: async (e) => {
+ e.preventDefault();
+ err.textContent = '';
+ const sat = Number(String(amount.value).replace(/[\s,_]/g, ''));
+ if (!Number.isInteger(sat) || sat < minSat) { err.textContent = `Enter at least ${fmt(minSat)} sats.`; amount.focus(); return; }
+ if (sat > maxSat) { err.textContent = `At most ${fmt(maxSat)} sats.`; amount.focus(); return; }
+ go.disabled = true; go.textContent = 'Creating invoice…';
+ try { await createInvoice(sat, note ? note.value.trim() : ''); } catch (x) {
+ err.textContent = 'Could not create an invoice: ' + (x.message || x);
+ } finally { go.disabled = false; go.textContent = 'Create invoice'; }
+ },
+ }, el('label', { for: 'amount' }, 'Pay a set amount'), amount, note, go, err);
+ const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(address, e.currentTarget) }, 'Copy address');
+ $('body').replaceChildren(
+ el('div', { class: 'card' },
+ qrBox('lightning:' + lnurl, 'Open in a Lightning wallet'),
+ el('p', { class: 'hint' }, 'Scan with any Lightning wallet and pick the amount there.'),
+ el('div', { class: 'row' }, el('code', { class: 'addr' }, address), copyBtn)),
+ el('div', { class: 'card' }, form));
+}
+
+async function createInvoice(sat, comment) {
+ const u = new URL(payReq.callback);
+ u.searchParams.set('amount', String(sat * 1000));
+ if (comment) u.searchParams.set('comment', comment);
+ const j = await getJson(u.toString(), 30000);
+ if (!j.pr) throw new Error('no invoice came back');
+ showInvoice(sat, j.pr, j.verify || null);
+}
+
+function showInvoice(sat, pr, verify) {
+ stopWatch();
+ const status = el('div', { class: 'status', id: 'status' }, verify ? 'Waiting for payment…' : 'Pay it from your Lightning wallet.');
+ const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(pr, e.currentTarget) }, 'Copy invoice');
+ const open = el('a', { class: 'button primary', href: 'lightning:' + pr }, 'Open in wallet');
+ const back = el('button', { class: 'link', type: 'button', onClick: showStart }, '← Another amount');
+ $('body').replaceChildren(el('div', { class: 'card', id: 'invoice' },
+ el('div', { class: 'big' }, fmt(sat), el('span', {}, ' sats')),
+ qrBox('lightning:' + pr.toUpperCase(), 'Open in a Lightning wallet'),
+ el('div', { class: 'row' }, copyBtn, open),
+ status, back));
+ if (!verify) return;
+ const started = Date.now();
+ watch = setInterval(async () => {
+ if (Date.now() - started > 15 * 60_000) { stopWatch(); status.textContent = 'This invoice has expired.'; return; }
+ try {
+ const v = await getJson(verify, 8000);
+ if (v.settled) { stopWatch(); paid(sat); }
+ } catch {}
+ }, 3000);
+}
+
+function paid(sat) {
+ $('body').replaceChildren(el('div', { class: 'card done', id: 'paid' },
+ el('div', { class: 'tick', 'aria-hidden': 'true' }, '✓'),
+ el('div', { class: 'big' }, 'Paid'),
+ el('p', {}, `${fmt(sat)} sats sent to ${address}. Thank you!`),
+ el('button', { class: 'link', type: 'button', onClick: showStart }, 'Pay again')));
+}
+
+async function main() {
+ if (!name) { $('body').replaceChildren(el('div', { class: 'card' }, el('p', {}, 'No such page.'))); return; }
+ $('who').textContent = address;
+ document.title = `Pay ${address}`;
+ let rec = null;
+ try {
+ [payReq, rec] = await Promise.all([getJson(lnurlpUrl), getJson(`${REGISTRAR}/name/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`).catch(() => null)]);
+ } catch (x) {
+ $('body').replaceChildren(el('div', { class: 'card' }, el('p', { class: 'err' },
+ /unknown address/i.test(x.message) ? `${address} is not a coinos address.` : `Could not reach ${address} right now. Try again in a moment.`)));
+ return;
+ }
+ showStart();
+ const pk = rec && /^[0-9a-f]{64}$/.test(rec.pubkey || '') ? rec.pubkey : null;
+ if (!pk) return;
+ $('profile-link').href = '/' + name;
+ const ev = await fetchProfile(pk);
+ let p = null; try { p = ev && JSON.parse(ev.content); } catch {}
+ if (!p) return;
+ const shown = String(p.display_name || p.name || '').trim().slice(0, 60);
+ if (shown) { $('display').textContent = shown; document.title = `Pay ${shown}`; }
+ if (/^https:\/\//.test(p.picture || '')) { const img = $('avatar'); img.src = p.picture; img.hidden = false; }
+}
+
+main();
diff --git a/src/public-chat.js b/src/public-chat.js
index 9cce6f5..dd54342 100644
--- a/src/public-chat.js
+++ b/src/public-chat.js
@@ -213,7 +213,9 @@ export function mountPublicChat() {
const hasAccount = (() => {
try {
- return !!(sessionStorage.getItem('btc-wallet-accounts') || (JSON.parse(localStorage.getItem('btc-wallet-watch') || '[]')).length);
+ // a session in this tab, a saved wallet (a tab opened from a link has no session yet), or a watch-only one
+ return !!(sessionStorage.getItem('btc-wallet-accounts') || localStorage.getItem('btc-wallet-vault')
+ || (JSON.parse(localStorage.getItem('btc-wallet-watch') || '[]')).length);
} catch { return false; }
})();
@@ -306,8 +308,9 @@ export function mountPublicChat() {
h('div', { class: 'row between', style: 'align-items:center;gap:10px' },
h('div', { class: 'col', style: 'gap:2px;min-width:0' },
h('div', { class: 'chat-title' }, t('publicChatTitle', { name: COMMUNITY.name })),
- h('div', { class: 'small muted' }, t('publicChatDesc'))),
- h('button', { class: 'btn-primary btn-sm', style: 'flex-shrink:0', onClick: () => { location.href = '/'; } },
+ h('div', { class: 'small muted' }, t(hasAccount ? 'publicChatDescMember' : 'publicChatDesc'))),
+ // with an account on the device the button opens the room itself (/?chat)
+ h('button', { class: 'btn-primary btn-sm', style: 'flex-shrink:0', onClick: () => { location.href = hasAccount ? '/?chat' : '/'; } },
hasAccount ? t('publicChatOpenApp') : t('publicChatSignIn'))),
tabs),
log));
diff --git a/src/pull-refresh.js b/src/pull-refresh.js
new file mode 100644
index 0000000..e05fa9a
--- /dev/null
+++ b/src/pull-refresh.js
@@ -0,0 +1,97 @@
+// Pull down at the top of the page to reload it — where the browser doesn't.
+//
+// Chrome's own pull-to-refresh is off whenever the page runs full screen,
+// which the Android app (a TWA in immersive mode) always is, and a WebView
+// (the Beta and F-Droid builds) and an installed PWA have none at all: "pull
+// down to refresh isn't working for me in the apk" (Adam, 2026-11-06). In
+// those, this one takes over, and the browser's is switched off so the two
+// never both fire; a plain browser tab keeps the browser's.
+//
+// A pull counts only when the page is at its top and the finger isn't in
+// something scrolled down (a chat, a picker) or something over the page (a
+// dialog, the media viewer): those keep their own drags. It's vertical only —
+// sideways swipes belong to the tab navigation.
+
+const PULL = 80; // px of (damped) pull that reloads on release
+const MAX = 120;
+
+export function appLike() {
+ try {
+ if (typeof window !== 'undefined' && window.CoinosHost) return true;
+ return matchMedia('(display-mode: standalone)').matches || matchMedia('(display-mode: fullscreen)').matches;
+ } catch { return false; }
+}
+
+// something under the finger that is scrolled away from its top, or a layer
+// over the page, owns this drag
+function blocked(el) {
+ for (let n = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
+ if (n.scrollTop > 0) return true;
+ if (n.matches && n.matches('.lightbox, .confirm-pop-backdrop, .msg-sheet, [role=dialog], dialog, input, textarea, select, [contenteditable=true]')) return true;
+ }
+ return false;
+}
+
+export function initPullRefresh({ reload = () => location.reload() } = {}) {
+ if (typeof document === 'undefined' || !appLike()) return false;
+ document.documentElement.style.overscrollBehaviorY = 'contain'; // the browser's off: this one instead
+
+ const ind = document.createElement('div');
+ ind.className = 'ptr';
+ ind.setAttribute('aria-hidden', 'true');
+ ind.innerHTML = '<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
+ document.body.appendChild(ind);
+
+ let y0 = null, x0 = 0, dy = 0, active = false, done = false;
+ const show = (d) => {
+ const p = Math.min(1, d / PULL);
+ ind.style.transform = `translate(-50%, ${Math.min(d, MAX) - 48}px) rotate(${p * 270}deg)`;
+ ind.style.opacity = String(Math.min(1, p * 1.2));
+ ind.classList.toggle('ready', d >= PULL);
+ };
+ const reset = () => {
+ ind.classList.remove('ready');
+ ind.style.transition = 'transform .2s ease, opacity .2s ease';
+ ind.style.transform = 'translate(-50%, -48px)';
+ ind.style.opacity = '0';
+ setTimeout(() => { ind.style.transition = ''; }, 220);
+ };
+
+ addEventListener('touchstart', (e) => {
+ if (done || e.touches.length !== 1) { y0 = null; return; }
+ const top = (document.scrollingElement || document.documentElement).scrollTop <= 0;
+ if (!top || blocked(e.target)) { y0 = null; return; }
+ y0 = e.touches[0].clientY; x0 = e.touches[0].clientX; dy = 0; active = false;
+ }, { passive: true });
+
+ addEventListener('touchmove', (e) => {
+ if (y0 == null || done) return;
+ const t = e.touches[0];
+ const ry = t.clientY - y0, rx = t.clientX - x0;
+ if (!active) {
+ // decide once: a clear downward pull, not a sideways swipe or a scroll up
+ if (Math.abs(ry) < 8 && Math.abs(rx) < 8) return;
+ if (ry <= 0 || Math.abs(rx) > ry) { y0 = null; return; }
+ active = true;
+ }
+ dy = ry * 0.5; // damped, like the browser's
+ show(dy);
+ }, { passive: true });
+
+ const end = () => {
+ if (y0 == null) return;
+ y0 = null;
+ if (active && dy >= PULL) {
+ done = true;
+ ind.classList.add('spin');
+ ind.style.transform = 'translate(-50%, 24px)';
+ reload();
+ return;
+ }
+ if (active) reset();
+ active = false;
+ };
+ addEventListener('touchend', end, { passive: true });
+ addEventListener('touchcancel', () => { if (y0 != null) { y0 = null; if (active) reset(); active = false; } }, { passive: true });
+ return true;
+}
diff --git a/src/recipient-search.js b/src/recipient-search.js
index 4853c66..285221c 100644
--- a/src/recipient-search.js
+++ b/src/recipient-search.js
@@ -114,7 +114,8 @@ export function warmSearch() {
// Profiles cap at 200 by recency; whole-query results keep for 12 hours.
const PROF_KEY = 'btc-wallet-search-profiles';
// Discard old results that identified migrated accounts by their wallet key.
-const QUERY_KEY = 'btc-wallet-search-queries-v2';
+// v3: results from before the people-you-follow source came in
+const QUERY_KEY = 'btc-wallet-search-queries-v3';
const QUERY_TTL = 12 * 3600_000;
const profileCache = new Map(); // pk -> { name, picture }
const queryCache = new Map(); // q -> rows
@@ -150,6 +151,15 @@ function persistCaches() {
}, 800);
}
+// The people this account follows, as the chat feature knows them
+// ([{ pk, name, nip05, picture }], profiles it already holds). A match among
+// them outranks the search indexes: Primal ranks by its own trust score and
+// doesn't index a brand-new key for a while, so someone you follow who just
+// moved to a new npub (Derek Ross, 2026-11-17: an empty impostor came up
+// instead) is found where you'd look first.
+let localPeople = null;
+export function setLocalPeople(fn) { localPeople = fn; }
+
// Worth searching? A partial username or npub — never an address, invoice,
// or key the Send form knows how to handle whole. Known payment prefixes are
// excluded so typing an address never triggers a search.
@@ -214,6 +224,19 @@ export async function searchRecipients(qRaw, onPartial = null) {
const exact = parseNostrPubkey(q);
if (exact) { add(exact, {}, 0); emit(); }
+ let partial = false; // follows' names still loading: don't keep these rows
+ if (!exact && localPeople) {
+ const joined = q.replace(/ /g, '');
+ const hit = (v) => { const x = String(v || '').toLowerCase().replace(/\s+/g, ' '); return x.includes(q) || (joined !== q && x.replace(/ /g, '').includes(joined)); };
+ let people = [];
+ try { people = localPeople() || []; } catch {}
+ if (people.partial) partial = true;
+ for (const p of people) {
+ const nip05 = typeof p.nip05 === 'string' ? p.nip05.replace(/^_@/, '') : undefined;
+ if (hit(p.name) || hit(nip05)) add(p.pk, { name: p.name, picture: p.picture, nip05 }, 1);
+ }
+ emit();
+ }
await Promise.allSettled([
fetch(`${REGISTRAR}/search?q=${encodeURIComponent(q)}`)
@@ -243,6 +266,7 @@ export async function searchRecipients(qRaw, onPartial = null) {
const rows = snapshot();
await fillProfiles(rows).catch(() => {});
for (const r of rows) r.known = true; // looked: no picture now means none
+ if (partial) return rows;
if (queryCache.size > 200) { queryCache.clear(); queryAt.clear(); }
queryCache.set(q, rows);
queryAt.set(q, Date.now());
diff --git a/src/seed.js b/src/seed.js
new file mode 100644
index 0000000..0592035
--- /dev/null
+++ b/src/seed.js
@@ -0,0 +1,53 @@
+// The BIP-39 seed of a recovery phrase, stretched once per phrase.
+//
+// Stretching is PBKDF2-HMAC-SHA512 over 2048 rounds. Done in JavaScript
+// (@scure/bip39, nostr-tools' nip06) it cost every launch twice over — the
+// wallet's account key and the nostr identity each stretched the same words —
+// and was the largest single piece of opening a wallet on a phone. The browser
+// has the same function built in (WebCrypto), many times faster but
+// asynchronous: warmSeed() runs it before a wallet opens, and the synchronous
+// readers (seedSync) find the result waiting. A reader that comes first
+// still gets the right seed, the slow way, and leaves it for the rest.
+import { mnemonicToSeedSync } from '@scure/bip39';
+
+const seeds = new Map(); // `${phrase}\n${passphrase}` → Uint8Array(64)
+const MAX = 8; // a few accounts on one device; oldest out first
+const key = (mnemonic, passphrase) => `${mnemonic}\n${passphrase || ''}`;
+function keep(k, seed) {
+ seeds.delete(k);
+ seeds.set(k, seed);
+ while (seeds.size > MAX) seeds.delete(seeds.keys().next().value);
+}
+
+export function seedSync(mnemonic, passphrase = '') {
+ const k = key(mnemonic, passphrase);
+ const hit = seeds.get(k);
+ if (hit) return hit;
+ const seed = mnemonicToSeedSync(mnemonic, passphrase || '');
+ keep(k, seed);
+ return seed;
+}
+
+// BIP-39 exactly: password = NFKD(phrase), salt = NFKD("mnemonic" + passphrase).
+// Anything that goes wrong leaves the cache empty; seedSync does it the slow way.
+export async function warmSeed(mnemonic, passphrase = '') {
+ if (!mnemonic) return;
+ const k = key(mnemonic, passphrase);
+ if (seeds.has(k)) return;
+ // what @scure/bip39 accepts; anything else is left for it to refuse
+ if (![12, 15, 18, 21, 24].includes(mnemonic.normalize('NFKD').split(' ').length)) return;
+ try {
+ const subtle = globalThis.crypto && globalThis.crypto.subtle;
+ if (!subtle) return;
+ const enc = new TextEncoder();
+ const pw = await subtle.importKey('raw', enc.encode(mnemonic.normalize('NFKD')), 'PBKDF2', false, ['deriveBits']);
+ const bits = await subtle.deriveBits(
+ { name: 'PBKDF2', hash: 'SHA-512', salt: enc.encode(('mnemonic' + (passphrase || '')).normalize('NFKD')), iterations: 2048 },
+ pw, 512,
+ );
+ if (!seeds.has(k)) keep(k, new Uint8Array(bits));
+ } catch {}
+}
+
+// A locked or removed wallet's seed doesn't stay behind in memory.
+export function forgetSeeds() { seeds.clear(); }
diff --git a/src/style.css b/src/style.css
index c621b13..311cfbb 100644
--- a/src/style.css
+++ b/src/style.css
@@ -30,6 +30,12 @@
--accent-fg: #ffffff; /* text on accent */
--accent-ink: #000000;
--accent-soft: #ececef;
+ /* a button's fill (primary, chosen chip or tab): the accent in light; in
+ dark a lifted grey, not a white slab (Adam, 2026-10-18: "Probably
+ shouldn't have white buttons in dark mode") */
+ --fill: var(--accent);
+ --fill-hover: var(--accent-hover);
+ --fill-fg: var(--accent-fg);
--green: #14935a;
--green-soft: #e7f6ee;
--green-line: #c4e7d4;
@@ -65,6 +71,9 @@
--accent-fg: #0f1216; /* text on accent */
--accent-ink: #e7e9ee;
--accent-soft: #262b33;
+ --fill: #353b45;
+ --fill-hover: #404753;
+ --fill-fg: #f3f5f8;
--green: #2dbd80;
--green-soft: #14271d;
--green-line: #235340;
@@ -86,6 +95,8 @@
* { box-sizing: border-box; }
html {
+ /* a post scrolled into view lands below the sticky top bar */
+ scroll-padding-top: 72px;
/* Reserve the scrollbar's gutter always, so it doesn't appear the instant
the history list fills the page and shrink the viewport — that width
change re-centered the balance carousel's snapped card, the "slight move
@@ -167,6 +178,17 @@ input { scroll-margin-top: 12px; }
.logo-full { height: 40px; flex: none; color: var(--ink); display: grid; place-items: center; }
.logo-full svg { height: 40px; width: auto; display: block; }
.brand h1 { font-size: 19px; }
+/* The top bar (logo, search, settings, avatar) stays on screen while the
+ page scrolls under it (Adam, 2026-11-12). A frosted strip the width of the
+ column, padded out by the same amount it's pulled in, so the layout at
+ rest doesn't move; the safe-area inset keeps it clear of a notch. */
+.brand-header {
+ position: sticky; top: 0; z-index: 30;
+ margin: -8px -16px; padding: 8px 16px;
+ padding-top: max(8px, env(safe-area-inset-top));
+ background: color-mix(in srgb, var(--bg) 84%, transparent);
+ -webkit-backdrop-filter: saturate(1.4) blur(14px); backdrop-filter: saturate(1.4) blur(14px);
+}
.badge {
font-size: 12px; font-weight: 600; padding: 3px 9px; border-radius: 999px;
@@ -209,6 +231,7 @@ input { scroll-margin-top: 12px; }
.balance .split .k { font-size: 12px; color: var(--faint); text-transform: uppercase; letter-spacing: .04em; }
.balance .split .v { font-family: var(--mono); font-size: 14px; }
.balance .split .v.pending { color: var(--accent-ink); }
+.balance .breakdown-toggle { margin-top: 10px; color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
/* ---- tabs ---- */
.page-pick { width: auto; padding: 6px 28px 6px 10px; font-size: 13px; border-radius: 9px; background-color: var(--paper); }
@@ -230,8 +253,8 @@ button, .btn {
button:hover { background: var(--surface2); }
button:active { transform: translateY(1px); }
button:disabled { opacity: .5; cursor: not-allowed; }
-.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
-.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
+.btn-primary { background: var(--fill); border-color: var(--fill); color: var(--fill-fg); }
+.btn-primary:hover { background: var(--fill-hover); border-color: var(--fill-hover); }
.btn-ghost { background: transparent; }
.btn-sm { padding: 7px 11px; font-size: 13px; border-radius: 9px; }
.btn-sm.on { border-color: var(--accent); color: var(--accent); }
@@ -242,7 +265,7 @@ button:disabled { opacity: .5; cursor: not-allowed; }
/* ---- inputs ---- */
label.field { display: block; }
.field .lab { font-size: 13px; font-weight: 600; color: var(--muted); margin-bottom: 6px; display: block; }
-input[type=text], input[type=search], input[type=password], input[type=number], textarea, select {
+input[type=text], input[type=search], input[type=password], input[type=number], input[type=datetime-local], textarea, select {
width: 100%; font: inherit; color: var(--ink); background: var(--paper);
border: 1px solid var(--line-strong); border-radius: 11px; padding: 11px 13px;
}
@@ -296,7 +319,7 @@ textarea.send-dest::placeholder { font-family: var(--sans); }
colour matched the posts under it). So these take the feed chips' look:
the chosen tab solid accent, the other one quiet (Adam, 2026-10-16). */
.prof-tabs button { background: var(--surface2); color: var(--muted); }
-.prof-tabs button.active { background: var(--accent); color: var(--accent-fg); }
+.prof-tabs button.active { background: var(--fill); color: var(--fill-fg); }
/* ---- address / qr ---- */
.qr { width: 220px; height: 220px; display: block; border-radius: 12px; border: 1px solid var(--line); }
@@ -335,6 +358,10 @@ textarea.send-dest::placeholder { font-family: var(--sans); }
eight-letter word ("resemble") pushed the third column out past the
card's padding. The cells are a touch tighter so every BIP-39 word (eight
letters at most) still fits whole in a third of a narrow card. */
+/* The one-word check after the phrase: four of its words, tap the right one. */
+.quiz-opts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
+.quiz-opt { font-family: var(--mono); font-size: 16px; padding: 14px 8px; }
+.quiz-opt.wrong { border-color: var(--red); color: var(--red); background: var(--red-soft); }
.words { display: grid; grid-auto-flow: row; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.words .w {
display: flex; align-items: baseline; gap: 5px; background: var(--surface2); min-width: 0;
@@ -350,6 +377,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); }
@@ -357,7 +388,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); }
@@ -504,6 +535,13 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
}
.chat-row { display: flex; gap: 9px; align-items: flex-start; }
.chat-row.grouped { margin-top: -6px; }
+/* group chats: the avatar sits beside the name and the bubble starts at the
+ left edge under both, instead of indented a whole avatar column */
+.chat-row.group { display: grid; grid-template-columns: 30px minmax(0, 1fr); column-gap: 9px; row-gap: 3px; align-items: center; }
+.chat-row.group > .chat-body { display: contents; }
+.chat-row.group .chat-meta { grid-column: 2; margin-bottom: 0; }
+.chat-row.group .chat-line { grid-column: 1 / -1; }
+.chat-row.group > .chat-avatar.spacer { display: none; }
.chat-avatar {
width: 30px; height: 30px; border-radius: 50%; flex-shrink: 0; object-fit: cover;
background: var(--accent-soft);
@@ -562,6 +600,9 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
border: none; background: none; padding: 11px 8px; font-weight: 550; border-radius: 10px;
}
.msg-sheet-item:hover { background: var(--surface2); }
+.msg-sheet-item.danger, .msg-sheet-item.danger .msg-sheet-ico { color: var(--red); }
+.msg-sheet-item.danger.armed { background: color-mix(in srgb, var(--red) 12%, transparent); }
+.chat-removed-head { padding: 10px 4px 2px; }
.msg-sheet-ico { width: 20px; text-align: center; color: var(--muted); flex-shrink: 0; }
/* the quoted message a reply carries, and the composer's replying-to bar */
.chat-quote {
@@ -590,7 +631,8 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
.chat-react.on { border-color: color-mix(in srgb, currentColor 55%, transparent); font-weight: 600; }
/* zap tally: a little bolt + sats, amber on both themes; .on = we zapped it */
.zap-tally { display: inline-flex; align-items: center; gap: 2px; font-size: 11px; font-weight: 650; color: #e6a800; white-space: nowrap; flex-shrink: 0; }
-.zap-tally.chat-react { font-size: 12px; padding: 1px 7px 1px 5px; }
+/* in a bubble the zap total is just the amber bolt + sats: no pill, no ring */
+.zap-tally.chat-react { font-size: 12px; padding: 1px 2px 1px 0; background: none; border: none; }
.zap-tally.clickable { cursor: pointer; }
/* the one-tap ⚡ beside someone else's chat bubble */
.chat-line { display: flex; align-items: center; gap: 4px; }
@@ -726,7 +768,7 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
.pos-big { font-size: 34px; font-weight: 700; line-height: 1.1; letter-spacing: -.5px; }
.pos-tips { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; width: 100%; }
.pos-tip { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 12px 6px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface2); color: var(--ink); cursor: pointer; }
-.pos-tip.on { border-color: var(--accent); background: var(--accent); color: var(--accent-fg); }
+.pos-tip.on { border-color: var(--fill); background: var(--fill); color: var(--fill-fg); }
.pos-tip.on .muted { color: inherit; opacity: .8; }
.pos-tip-label { font-size: 20px; font-weight: 600; }
.pos-total { font-size: 22px; font-weight: 600; margin-top: 4px; }
@@ -735,14 +777,12 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
.pos-sale.faint { opacity: .55; }
.pos-pad { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; width: 100%; }
.pos-key { padding: 14px 0; font-size: 22px; font-weight: 600; border: 1px solid var(--line); border-radius: 12px; background: var(--surface2); color: var(--ink); cursor: pointer; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
-.pos-key:active { background: var(--accent); color: var(--accent-fg); }
+.pos-key:active { background: var(--fill); color: var(--fill-fg); }
.pos-key.del { font-weight: 400; }
/* the feeds row: pills that scroll sideways, the one on screen filled */
.feed-chips { gap: 6px; flex-wrap: nowrap; overflow-x: auto; margin: 0 -14px; padding: 2px 14px; scrollbar-width: none; -webkit-overflow-scrolling: touch; }
.feed-chips::-webkit-scrollbar { display: none; }
/* with a mouse: a thin bar says the strip scrolls, and it drags (app.js) */
-/* grabbing the feed to scroll it (app.js) */
-.grab-scrolling, .grab-scrolling * { cursor: grabbing !important; user-select: none !important; }
@media (hover: hover) and (pointer: fine) {
.feed-chips { scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; padding-bottom: 6px; cursor: grab; }
.feed-chips::-webkit-scrollbar { display: block; height: 6px; }
@@ -751,7 +791,7 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
.feed-chips.dragging .feed-chip { pointer-events: none; }
}
.feed-chip { flex: 0 0 auto; border: 1px solid var(--line); background: var(--surface2); color: var(--muted); border-radius: 999px; padding: 5px 12px; font-size: 14px; line-height: 1.2; cursor: pointer; white-space: nowrap; max-width: 180px; overflow: hidden; text-overflow: ellipsis; }
-.feed-chip.on { background: var(--accent); color: var(--accent-fg); border-color: var(--accent); }
+.feed-chip.on { background: var(--fill); color: var(--fill-fg); border-color: var(--fill); }
.feed-chip.add { font-weight: 600; padding: 5px 11px; }
.note-act {
background: none; border: 0; padding: 4px 6px; margin: 0; line-height: 1;
@@ -840,11 +880,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;
@@ -879,6 +937,74 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.addr-cover { width: 100%; aspect-ratio: 2 / 1; object-fit: cover; display: block; background: var(--line); }
.addr-title { font-weight: 650; font-size: 1.05em; line-height: 1.3; }
.addr-summary { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; white-space: normal; }
+/* Live streams (NIP-53): the row of what's on above a feed, a profile's
+ "on now", a post's card, and the stream's own page (player over chat). */
+/* a face whose person is streaming now: a red ring, and LIVE under the bigger ones */
+.chat-avatar.live-ring { box-shadow: 0 0 0 2px var(--paper), 0 0 0 4px #e0245e; position: relative; overflow: visible; }
+.chat-avatar.mini.live-ring { box-shadow: 0 0 0 1px var(--paper), 0 0 0 2.5px #e0245e; }
+.chat-avatar.live-ring:not(.mini)::after { content: 'LIVE'; position: absolute; left: 50%; bottom: -7px; transform: translateX(-50%);
+ padding: 0 4px; border-radius: 3px; font-size: 9px; font-weight: 700; line-height: 13px; letter-spacing: .04em;
+ color: #fff; background: #e0245e; box-shadow: 0 0 0 2px var(--paper); text-transform: none; }
+.live-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 14px 10px; padding: 2px 0 4px; }
+.live-past-title { margin: 6px 0 0; font-size: 15px; }
+.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #e0245e; margin-right: 5px; vertical-align: 1px; }
+.live-tile { display: flex; flex-direction: column; gap: 5px; padding: 0; text-align: left;
+ background: none; border: 0; color: inherit; cursor: pointer; min-width: 0; }
+.live-cover { position: relative; width: 100%; aspect-ratio: 16 / 9; border-radius: 10px; overflow: hidden;
+ background: var(--line) center / cover no-repeat; }
+.live-badge { display: inline-block; padding: 1px 6px; border-radius: 4px; font-size: 11px; font-weight: 700;
+ letter-spacing: .04em; color: #fff; background: #555; line-height: 1.5; flex-shrink: 0; }
+.live-badge.live { background: #e0245e; }
+.live-cover .live-badge { position: absolute; top: 6px; left: 6px; }
+.live-viewers { position: absolute; bottom: 6px; left: 6px; padding: 1px 6px; border-radius: 4px; font-size: 11px;
+ color: #fff; background: rgba(0, 0, 0, .6); }
+.live-tile-title { font-weight: 600; font-size: 14px; line-height: 1.25; display: -webkit-box; -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical; overflow: hidden; }
+.live-tile-host { align-items: center; min-width: 0; }
+.live-tile-host .small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.live-banner { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid #e0245e;
+ border-radius: 10px; background: none; color: inherit; cursor: pointer; text-align: left; min-width: 0; }
+.live-banner-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
+.live-card { flex-direction: row; align-items: center; gap: 10px; }
+.live-card .live-cover { flex: 0 0 120px; width: 120px; }
+.live-title { margin: 0; min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.live-player { width: 100%; aspect-ratio: 16 / 9; background: #000; border-radius: 10px; overflow: hidden; }
+.live-frame { width: 100%; height: 100%; }
+.live-video { width: 100%; height: 100%; display: block; background: #000; }
+.live-still { border-radius: 0; height: 100%; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; }
+.live-rec-link { background: var(--paper); color: var(--ink); text-decoration: none; }
+.live-say { padding: 6px 12px; border-radius: 8px; color: #fff; background: rgba(0, 0, 0, .65); font-size: 14px; text-align: center; }
+/* the top padding is headroom for a hat on the first line's face: a scroller clips what rises out of it */
+/* no overscroll-behavior here: at the end of the chat the swipe carries on to
+ the page, or the last lines and the message box stay under the screen edge
+ with no way to reach them (Adam, 2026-11-20) */
+.live-chat { display: flex; flex-direction: column; gap: 8px; max-height: 46vh; min-height: 120px; overflow-y: auto; padding-top: 12px; }
+.live-line { display: flex; gap: 8px; align-items: flex-start; min-width: 0; }
+.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: var(--live-chat-max, 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); }
+.go-live-btn { display: inline-flex; align-items: center; gap: 8px; }
+.go-live-title { width: 100%; }
.article-title { font-size: 1.35em; font-weight: 700; line-height: 1.25; margin-bottom: 6px; white-space: normal; }
.article-h1, .article-h2, .article-h3 { font-weight: 650; line-height: 1.3; margin: 10px 0 2px; white-space: normal; }
.article-h1 { font-size: 1.2em; } .article-h2 { font-size: 1.1em; } .article-h3 { font-size: 1em; }
@@ -941,29 +1067,27 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.feed-compose-icon { display: flex; flex-shrink: 0; }
.feed-compose-icon .compose-pen { stroke: #14935a; }
.feed-compose-icon .compose-pen-fill { fill: #14935a; opacity: .18; }
-.feed-page .feed-new-pill {
- bottom: calc(env(safe-area-inset-bottom, 0px) + 82px);
-}
-/* a phone is too narrow for it beside the Post button: it rides above */
-@media (max-width: 480px) {
- .feed-page .feed-new-pill { bottom: calc(env(safe-area-inset-bottom, 0px) + 142px); }
-}
.feed-new-pill {
- /* Rides at the bottom of the window, where a thumb already is; the tap
- takes the reader up to the new posts. */
- position: fixed; bottom: calc(env(safe-area-inset-bottom, 0px) + 18px);
+ /* Rides at the bottom of the window, where a thumb already is, above the
+ nav; the tap takes the reader up to the new posts. (Painted beside the
+ page, not inside it: see page-floaters in app.js.) */
+ position: fixed; bottom: calc(env(safe-area-inset-bottom, 0px) + 82px);
left: 50%; transform: translateX(-50%);
z-index: 30; width: auto; padding: 12px 24px; border-radius: 999px;
- background: var(--accent); color: var(--accent-fg); border: none;
+ background: var(--fill); color: var(--fill-fg); border: none;
font-size: 16px; font-weight: 650; cursor: pointer;
touch-action: none; user-select: none; -webkit-user-select: none; /* it swipes away */
box-shadow: 0 3px 12px rgba(0, 0, 0, .28);
animation: pill-in .18s ease-out;
}
+/* a phone is too narrow for it beside the Post button: it rides above */
+@media (max-width: 480px) {
+ .feed-new-pill { bottom: calc(env(safe-area-inset-bottom, 0px) + 142px); }
+}
/* the generic button hover (a light surface) and press (a 1px drop, which
REPLACED the centring transform and threw the pill half its width to the
right, out from under the pointer, so the tap never landed) stay off it */
-.feed-new-pill:hover { background: var(--accent-hover); color: var(--accent-fg); }
+.feed-new-pill:hover { background: var(--fill-hover); color: var(--fill-fg); }
.feed-new-pill:active { transform: translate(-50%, 1px); }
/* the count bumps each time it changes: a fresh node per value replays it */
.feed-new-pill .n { display: inline-block; min-width: 1.1em; text-align: center; animation: pill-bump .32s cubic-bezier(.2,.9,.3,1.4); }
@@ -1025,9 +1149,19 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
/* over a playing clip: a tap takes it full screen; YouTube's control bar
along the bottom is left uncovered, and full screen it all is */
.yt-shield { position: absolute; left: 0; right: 0; top: 0; bottom: 52px; z-index: 1; cursor: pointer; }
+/* a mouse reaches the player's own buttons (pause in the middle, full screen
+ in the corner): while one is over the box its clicks go to the player */
+.yt-embed.by-mouse .yt-shield { display: none; }
.yt-embed:fullscreen { border-radius: 0; aspect-ratio: auto; width: 100%; height: 100%; }
.yt-embed:fullscreen .yt-shield { display: none; }
.yt-embed:fullscreen iframe { object-fit: contain; }
+/* a PAFF film: its title along the foot of the backdrop until it plays */
+.paff-title {
+ position: absolute; left: 0; right: 0; bottom: 0; padding: 18px 12px 9px;
+ color: #fff; font-weight: 650; font-size: 14px; pointer-events: none;
+ background: linear-gradient(transparent, rgba(0, 0, 0, .7));
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
/* A link, as the card its page describes: picture on top, title, a line,
the site. The whole card is the link. */
.link-card {
@@ -1125,7 +1259,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.
@@ -1166,6 +1301,8 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.chat-avatar.header-ava { width: 30px; height: 30px; font-size: 11px; }
.composer-options { margin-inline-start: auto; flex-shrink: 0; }
.compose-preview-toggle[aria-pressed="true"] { background: var(--accent-soft); color: var(--ink); }
+.post-actions button[aria-pressed="true"]:not(.compose-preview-toggle) { background: var(--accent-soft); color: var(--ink); }
+.sched-pick input { min-width: 0; }
/* the post composer: Preview and Cancel stand as tall as Post and the
attach square beside them, in the same type */
.post-actions .composer-options > button { padding: 11px 16px; font-size: inherit; border-radius: 11px; min-height: 44px; }
@@ -1189,7 +1326,7 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.hat-demo { position: relative; display: inline-flex; width: 34px; height: 34px; flex-shrink: 0; margin-top: 12px; }
.hat-demo-head { width: 100%; height: 100%; border-radius: 50%; background: var(--accent-soft); }
.hat-btn { white-space: nowrap; flex-shrink: 0; }
-.hat-btn.wearing { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
+.hat-btn.wearing { background: var(--fill); border-color: var(--fill); color: var(--fill-fg); }
.hat-btn.confirm { border-color: var(--green); color: var(--green); }
/* a small centered confirm popup over a dimmed page */
@@ -1259,7 +1396,7 @@ button, .btn { transition: filter .12s, background .15s, border-color .15s, box-
.chat-avatar.clickable:hover { transform: scale(1.07); }
.header-avatar .chat-avatar { transition: transform .15s ease; }
.header-avatar:hover .chat-avatar { transform: scale(1.08); }
-input[type=text], input[type=search], input[type=password], input[type=number], textarea, select { transition: border-color .15s, box-shadow .15s; }
+input[type=text], input[type=search], input[type=password], input[type=number], input[type=datetime-local], textarea, select { transition: border-color .15s, box-shadow .15s; }
.settings-nav::after { transition: transform .18s ease, color .18s; }
.settings-nav:hover::after { transform: translateX(3px); color: var(--ink); }
@@ -1483,6 +1620,28 @@ body::after {
background: var(--surface2); overflow: hidden; cursor: pointer;
}
.media-tile.video { aspect-ratio: 9 / 16; }
+/* only wide clips in it: one to a row, the poster whole */
+.media-grid.wide { grid-template-columns: 1fr; gap: 6px; }
+.media-grid.wide .media-tile.video { aspect-ratio: 16 / 9; }
+/* every shape in it: justified rows. A tile starts at its proportions at
+ the row height and grows in proportion to them, so a row's tiles share one
+ height and fill the width; the filler takes the last row's slack instead
+ of stretching its few tiles. */
+.media-grid.justified { display: flex; flex-wrap: wrap; --row-h: 140px; }
+.media-grid.justified .media-tile { aspect-ratio: var(--ar); flex: var(--ar) 1 calc(var(--ar) * var(--row-h)); min-width: 0; }
+.media-grid.justified::after { content: ''; flex: 1000 1 0; }
+/* the picture fills the tile without sizing it: a frame-grab <video>'s own
+ 320px would widen its tile, and the row's height with it */
+.media-grid.justified .media-tile > img, .media-grid.justified .media-tile > video { position: absolute; inset: 0; }
+@media (max-width: 600px) { .media-grid.justified { --row-h: 100px; } }
+/* a post's run of pictures: the same justified rows, inside the post */
+.note-gallery { display: flex; flex-wrap: wrap; gap: 3px; margin-top: 6px; border-radius: 10px; overflow: hidden; --row-h: 140px; }
+.note-gallery::after { content: ''; flex: 1000 1 0; }
+.note-gallery .note-img, .note-gallery .note-img.note-img-late {
+ margin: 0; border-radius: 0; width: auto; height: auto; max-width: none; max-height: none; min-width: 0;
+ aspect-ratio: var(--ar, 1); flex: var(--ar, 1) 1 calc(var(--ar, 1) * var(--row-h)); object-fit: cover; cursor: zoom-in;
+}
+@media (max-width: 600px) { .note-gallery { --row-h: 100px; } }
.media-tile img, .media-tile video { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; }
.media-tile.broken { display: none; }
.media-tile-play {
@@ -1559,7 +1718,8 @@ body::after {
}
.mp-counts .i { font-size: 24px; line-height: 1; display: flex; }
.mp-counts .i svg { width: 28px; height: 28px; filter: drop-shadow(0 1px 2px rgba(0, 0, 0, .6)); }
-.mp-like.on { color: #ff4d6d; }
+/* yours: the heart goes red; the count stays white (a 🤣 of yours left only the number red) */
+.mp-like.on .i { color: #ff4d6d; }
.mp-like .i .cemoji { width: 28px; height: 28px; }
/* the emoji sheet over the media pager (z-index 200) */
.confirm-pop-backdrop.over-pager { z-index: 300; }
@@ -1575,7 +1735,7 @@ body::after {
.mp-sound { font-size: 15px; }
.mp-sound .off { display: none; }
.mp-top-r { display: flex; align-items: center; gap: 8px; }
-.mp-fit { height: 32px; padding: 0 12px; font-size: 13px; font-weight: 600; border-radius: 999px; border: 0; color: #fff; background: rgba(255, 255, 255, .16); }
+.mp-fit { height: 40px; padding: 0 14px; font-size: 14px; font-weight: 600; border-radius: 999px; border: 0; color: #fff; background: rgba(255, 255, 255, .16); }
.media-pager.quiet .mp-top .mp-fit { pointer-events: auto; }
/* a post out of the carousel: its clip not ready to play yet (mp-wait), or
the wrong way round for the screen (mp-off). Parked far above the screen
@@ -1585,8 +1745,6 @@ body::after {
screen; its clip's poster still loads there. */
.mp-group.mp-wait, .mp-group.mp-off { position: fixed; top: -400vh; left: 0; height: 0; visibility: hidden; pointer-events: none; }
/* over the Videos grid: which shapes */
-.media-fit { grid-column: 1 / -1; display: flex; justify-content: flex-end; padding: 2px 8px 0; }
-.media-fit-btn { height: 28px; padding: 0 12px; font-size: 12px; font-weight: 600; border-radius: 999px; border: 0; color: var(--text, inherit); background: var(--chip-bg, rgba(127, 127, 127, .15)); }
/* A mouse's way through the pager: arrows, where there is a pointer to
hover with (a phone swipes). Faint until the pointer is over the pager;
the sideways pair only when the post has a picture that way. */
@@ -1676,7 +1834,10 @@ body::after {
position: absolute; left: 16px; right: 16px; bottom: var(--mp-seek-lift); z-index: 3; height: 28px;
display: flex; align-items: flex-end; touch-action: none; cursor: pointer; visibility: hidden; opacity: 0;
}
-.mp-seek.ready { visibility: visible; opacity: 1; transition: opacity .18s; }
+/* out of sight (and out of reach: a tap there must not jump the clip) while
+ it plays; up when paused (.show), after a tap near the foot (.reveal), or held */
+.mp-seek.ready { visibility: visible; opacity: 0; pointer-events: none; transition: opacity .18s; }
+.media-pager.show .mp-seek.ready, .mp-seek.ready.reveal, .mp-seek.ready.drag { opacity: 1; pointer-events: auto; }
/* only the clip on screen's bar, and not while the pager is in motion (a
finger, a glide, a flight): it goes at once and fades back in on landing */
.mp-slide:not(.mp-cur) .mp-seek, .media-pager.moving .mp-seek { opacity: 0; transition: none; pointer-events: none; }
@@ -1733,6 +1894,7 @@ body::after {
color: #fff; font-size: 14px; text-align: center; text-shadow: 0 1px 3px rgba(0, 0, 0, .6);
}
.vid-nopic a { color: #fff; text-decoration: underline; pointer-events: auto; }
+.note-video-box.gone .note-video { max-height: 160px !important; aspect-ratio: 16 / 9; }
.media-tile-cost {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
color: rgba(255, 255, 255, .8); font-size: 12px; font-weight: 600; background: #16181d;
@@ -1780,7 +1942,7 @@ body::after {
min-height: 48px; padding: 8px 14px; font-size: 16px;
}
.feed-post-fab { right: calc(50% - var(--col-edge) + 16px); bottom: 24px; }
- .feed-new-pill, .feed-page .feed-new-pill { left: calc(50% + var(--col-mid)); bottom: 24px; }
+ .feed-new-pill { left: calc(50% + var(--col-mid)); bottom: 24px; }
.toast { left: calc(50% + var(--col-mid)); }
}
@media (min-width: 1220px) {
@@ -1835,6 +1997,8 @@ body::after {
/* a reply shown with the post it answers above it (Conversations, a profile's Replies) */
.note-context { margin-bottom: 6px; }
.note-context-label { margin-bottom: 2px; }
+.note-scope .note-context-label { display: inline-block; text-decoration: none; }
+.note-scope .note-context-label:hover { text-decoration: underline; }
.note-context .quote-card { margin-top: 0; }
.note-context .quote-card .note-text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; }
/* attach + GIF inside the composer's field, bottom right; the field keeps
@@ -1856,3 +2020,260 @@ body::after {
/* Always visible, including when the media controls are tucked away. */
.mp-position { position: absolute; top: calc(env(safe-area-inset-top, 0px) + 16px); left: 50%; transform: translateX(-50%); padding: 5px 10px; border-radius: 20px; background: #0009; color: #fff; font-size: 13px; font-variant-numeric: tabular-nums; pointer-events: none; z-index: 5; }
+/* the counter shows while the pager is in motion and fades out a moment
+ after it settles (the animation restarts each time `moving` comes off) */
+.media-pager .mp-position { animation: mp-position-out .4s 1.2s both; }
+.media-pager.moving .mp-position { animation: none; opacity: 1; }
+@keyframes mp-position-out { from { opacity: 1; } to { opacity: 0; } }
+.media-pager.few .mp-position { visibility: hidden; }
+
+/* A call (calls.js): over every page, its picture filling it when there is
+ one; minimized, a bar along the top. */
+.call-overlay { position: fixed; inset: 0; z-index: 1000; background: #101318; color: #fff;
+ display: flex; flex-direction: column; align-items: center; justify-content: space-between;
+ padding: max(28px, env(safe-area-inset-top)) 16px max(28px, env(safe-area-inset-bottom)); }
+/* the whole of their picture, whatever its shape and the window's: a phone's
+ portrait camera filled a laptop's wide window by cropping to a forehead */
+.call-overlay .call-remote { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #000; display: none; }
+/* a call over the whole window: the page under it stays put */
+html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: auto; }
+.call-overlay.has-video .call-remote { display: block; }
+.call-overlay.has-video .call-who { position: relative; text-shadow: 0 1px 3px rgba(0, 0, 0, .7); }
+.call-overlay.has-video .call-who .call-avatar { display: none; }
+.call-who { display: flex; flex-direction: column; align-items: center; gap: 10px; margin-top: 8vh; z-index: 1; }
+.call-who .call-avatar { width: 112px; height: 112px; font-size: 32px; }
+.call-name { font-size: 22px; font-weight: 650; }
+.call-status { font-size: 15px; opacity: .8; font-variant-numeric: tabular-nums; }
+.call-local { position: absolute; right: 16px; bottom: 120px; width: 28vw; max-width: 180px; aspect-ratio: 3 / 4; object-fit: cover;
+ border-radius: 12px; background: #000; box-shadow: 0 2px 12px rgba(0, 0, 0, .5); z-index: 2; }
+.call-local.mirror { transform: scaleX(-1); }
+.call-local.sharing { aspect-ratio: 16 / 10; object-fit: contain; background: #000; }
+.call-bar { display: flex; gap: 18px; z-index: 2; flex-wrap: wrap; justify-content: center; }
+.call-btn { width: 60px; height: 60px; border-radius: 50%; border: 0; display: flex; align-items: center; justify-content: center;
+ background: rgba(255, 255, 255, .16); color: #fff; cursor: pointer; padding: 0; }
+.call-btn:hover { background: rgba(255, 255, 255, .26); }
+.call-btn.on { background: #fff; color: #101318; }
+.call-btn.call-hang, .call-btn.call-decline { background: #e0245e; }
+.call-btn.call-accept { background: #1fa45a; }
+.call-overlay.call-min { inset: 0 0 auto 0; padding: 0; background: none; height: auto; justify-content: flex-start; pointer-events: none; }
+.call-min-bar { pointer-events: auto; margin: max(8px, env(safe-area-inset-top)) auto 0; display: flex; align-items: center; gap: 10px;
+ padding: 8px 16px; border-radius: 999px; border: 0; background: #1fa45a; color: #fff; font-weight: 600; cursor: pointer; box-shadow: 0 2px 10px rgba(0, 0, 0, .3); }
+.call-min-status { font-variant-numeric: tabular-nums; opacity: .9; }
+.call-min .call-audio { display: none; }
+/* a call in its conversation: a row of its own, centred, a tap calls back */
+.chat-row.call-log { justify-content: center; margin: 6px 0; flex-direction: column; align-items: center; gap: 3px; }
+.call-log-why { text-align: center; max-width: 320px; }
+.call-log-pill { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--surface2); color: inherit; font-size: 13px; cursor: pointer; }
+.call-log-pill .chat-time { margin: 0; font-size: 11px; opacity: .7; }
+.call-log-pill svg { width: 16px; height: 16px; }
+.chat-row.call-log.missed .call-log-pill { color: var(--red); border-color: color-mix(in srgb, var(--red) 40%, var(--line)); }
+
+/* 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: 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;
+ background: linear-gradient(to right, var(--accent) var(--played), var(--line) var(--played)); }
+.media-wave:empty { height: 4px; top: 19px; }
+.media-wave i { flex: 1; background: var(--accent); border-radius: 2px; min-width: 1px; }
+.has-wave .media-wave { background: none; }
+.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; }
+/* 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)); }
+.mp-mark .cemoji { width: 24px; height: 24px; }
+.mp-seek-time { max-width: calc(100% - 16px); overflow: hidden; text-overflow: ellipsis; }
+.mp-seek.say .mp-seek-time { opacity: 1; }
+.mp-marks:not(:empty) ~ .mp-seek-time { bottom: 42px; }
+/* ...and a moment the clip plays through floats up off the bar */
+.mp-pop {
+ position: absolute; bottom: calc(var(--mp-seek-lift) + 12px); z-index: 4; transform: translateX(-50%);
+ font-size: 30px; line-height: 1; pointer-events: none; filter: drop-shadow(0 1px 3px rgba(0, 0, 0, .6));
+ animation: mp-pop 1.6s ease-out forwards;
+}
+.mp-pop .cemoji { width: 34px; height: 34px; }
+@keyframes mp-pop {
+ 0% { opacity: 0; transform: translate(-50%, 8px) scale(.6); }
+ 15% { opacity: 1; transform: translate(-50%, 0) scale(1.1); }
+ 100% { opacity: 0; transform: translate(-50%, -90px) scale(1); }
+}
+@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); }
+
+/* pull to refresh, where the browser has none (src/pull-refresh.js) */
+.ptr {
+ position: fixed; top: env(safe-area-inset-top, 0px); left: 50%; z-index: 2147483000;
+ width: 40px; height: 40px; border-radius: 50%; display: grid; place-items: center;
+ background: var(--paper); color: var(--muted); box-shadow: 0 2px 10px rgba(0, 0, 0, .18);
+ transform: translate(-50%, -48px); opacity: 0; pointer-events: none;
+}
+.ptr.ready { color: var(--ink); }
+.ptr.spin svg { animation: ptr-spin .8s linear infinite; }
+@keyframes ptr-spin { to { transform: rotate(360deg); } }
+
+/* a profile's posts on their way: three faint post shapes, breathing */
+.note-ghost { display: flex; gap: 12px; padding: 14px 14px 18px; border-bottom: 1px solid var(--line); }
+.note-ghost:last-child { border-bottom: 0; }
+.note-ghost .ng-ava { width: 40px; height: 40px; border-radius: 50%; background: color-mix(in srgb, var(--ink) 9%, transparent); flex: none; }
+.note-ghost .ng-line { display: block; height: 11px; border-radius: 6px; background: color-mix(in srgb, var(--ink) 9%, transparent); }
+.note-ghosts { animation: ng-breathe 1.4s ease-in-out infinite; }
+@keyframes ng-breathe { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
+@media (prefers-reduced-motion: reduce) { .note-ghosts { animation: none; } }
+
+/* search within someone's posts: their chip in the field */
+.search-scope-chip {
+ display: inline-flex; align-items: center; gap: 5px; flex-shrink: 0; max-width: 55%;
+ padding: 2px 2px 2px 3px; border-radius: 999px; background: var(--chip, rgba(127,127,127,.14));
+ font-size: 13px; font-weight: 600; color: var(--ink);
+}
+.search-scope-chip .chat-avatar.mini { width: 20px; height: 20px; min-width: 20px; font-size: 10px; }
+.search-scope-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.search-scope-x {
+ border: 0; background: none; color: var(--muted); font-size: 16px; line-height: 1;
+ width: 22px; height: 22px; padding: 0; border-radius: 50%; cursor: pointer; flex-shrink: 0;
+}
+.search-scope-x:hover { color: var(--ink); background: rgba(127,127,127,.18); }
+.header-search.header-search-scoped {
+ align-items: center; gap: 4px; padding: 3px 6px 3px 4px;
+ border: 1px solid var(--line-strong); background: var(--paper);
+}
+.header-search.header-search-scoped:focus-within { outline: 2px solid var(--accent); outline-offset: -1px; border-color: var(--accent); }
+.header-search-scoped > input.header-search-field {
+ flex: 1; min-width: 0; border: 0; background: none; padding: 5px 4px; font-size: 14px; border-radius: 0;
+}
+.header-search-scoped > input.header-search-field:focus { outline: none; }
+@media (min-width: 900px) {
+ #app:has(> .app-bottom-nav) .header-search.header-search-scoped { display: flex; }
+}
+.search-enter-hint {
+ flex-shrink: 0; font: 600 12px/1 inherit; color: var(--muted); padding: 4px 6px;
+ border: 1px solid var(--line-strong); border-radius: 6px;
+}
+
+/* "About 0:12 in the clip": off until tapped */
+.moment-toggle {
+ display: inline-flex; align-items: center; gap: 2px; min-height: 0;
+ padding: 4px 10px; border-radius: 999px; font-size: 13px; font-weight: 600;
+ background: none; color: var(--muted); border: 1px dashed var(--line-strong); cursor: pointer;
+}
+.moment-toggle:hover { color: var(--ink); }
+/* on: the accent with its own text colour (accent-fg). accent-ink, used
+ before, is light on dark mode's white accent: unreadable (Adam, 2026-11-15) */
+.moment-toggle.on { color: var(--accent-fg); background: var(--accent); border: 1px solid var(--accent); }
+
+/* Settings → Wallet: the ways back into an account */
+.ways-back .ways-back-row + .ways-back-row { border-top: 1px solid var(--line); }
+.ways-back .ways-back-check { color: var(--green, #2e9d5b); font-weight: 700; font-size: 16px; padding: 0 4px; }
+
+/* Settings → Wallet → Balance settings rows */
+.balance-settings-row { display: flex; align-items: center; gap: 14px; width: 100%; text-align: left;
+ padding: 14px 16px; border: 1px solid var(--line); border-radius: 14px; background: transparent; color: inherit; font: inherit; cursor: pointer; }
+@media (hover: hover) { .balance-settings-row:hover { background: rgba(127,127,127,.06); } }
+.balance-settings-row .bs-tile { display: flex; align-items: center; justify-content: center; flex-shrink: 0;
+ width: 38px; height: 38px; border-radius: 11px; }
+.balance-settings-row .bs-tile.spend { color: #7c3aed; background: rgba(124, 58, 237, .14); }
+.balance-settings-row .bs-tile.save { color: #f7931a; background: rgba(247, 147, 26, .14); }
+.balance-settings-row .bs-text { flex: 1; gap: 3px; min-width: 0; }
+.balance-settings-row .bs-title { font-weight: 600; }
+.balance-settings-row .bs-tail { color: var(--muted); font-size: 20px; line-height: 1; flex-shrink: 0; width: 14px; text-align: center; }
+.settings-prefs select { flex: 1 1 0; min-width: 0; }
+
+/* How far back the feed is scrolled: the post at the top of the screen's
+ date, under the top bar while scrolling (scrollWhen in messages.js). */
+.feed-when {
+ position: fixed; z-index: 29; transform: translate(-50%, -4px);
+ padding: 5px 12px; border-radius: 999px; white-space: nowrap;
+ font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums;
+ background: color-mix(in srgb, var(--bg) 88%, transparent); color: var(--ink);
+ border: 1px solid var(--line-strong);
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ box-shadow: 0 2px 10px rgba(0, 0, 0, .14);
+ pointer-events: none; opacity: 0; transition: opacity .12s, transform .12s;
+}
+.feed-when.on { opacity: 1; transform: translate(-50%, 0); transition-duration: .08s; }
+
+/* A PAFF song or album in a post: cover, title, play. It plays in the
+ music bar, not here (paffSongCard / playInBar in messages.js). */
+.paff-song {
+ display: flex; align-items: center; gap: 12px; margin-top: 6px; padding: 8px;
+ border: 1px solid var(--line); border-radius: 10px; background: var(--surface2);
+ cursor: pointer; position: relative;
+}
+.paff-song:hover { border-color: var(--line-strong); }
+.paff-song.on { border-color: var(--accent, var(--line-strong)); }
+.paff-song-cover { width: 64px; height: 64px; flex: none; border-radius: 6px; object-fit: cover; background: var(--line); }
+.paff-song-meta { min-width: 0; flex: 1; }
+.paff-song-title { font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.paff-song-meta .small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.paff-song-play {
+ flex: none; width: 40px; height: 40px; border-radius: 50%; display: grid; place-items: center;
+ background: var(--fill); color: var(--fill-fg);
+}
+.paff-song-open { position: absolute; top: 4px; right: 8px; font-size: 13px; color: var(--faint); text-decoration: none; }
+
+/* The music bar: PAFF's slim player, pinned above the bottom nav and
+ outside the page, so a song plays on wherever you go. */
+.music-bar {
+ position: fixed; z-index: 29; left: 50%; transform: translateX(-50%);
+ bottom: env(safe-area-inset-bottom, 0px);
+ width: min(560px, 100%); height: 64px; box-sizing: border-box;
+ display: flex; align-items: stretch;
+ background: #0a0b0e; /* PAFF's player's own */ border: 1px solid var(--line); border-bottom: 0;
+ border-radius: 12px 12px 0 0; box-shadow: 0 -4px 18px rgba(0, 0, 0, .08); overflow: hidden;
+}
+body:has(.app-bottom-nav) .music-bar { bottom: calc(env(safe-area-inset-bottom, 0px) + 65px); }
+.music-bar iframe { flex: 1; min-width: 0; height: 100%; border: 0; background: transparent; }
+.music-close {
+ flex: none; width: 40px; margin: 0; padding: 0; border: 0; border-radius: 0;
+ background: none; color: rgba(255, 255, 255, .6); font-size: 22px; cursor: pointer;
+}
+.music-close:hover { color: #fff; background: none; }
+body.music-open .feed-post-fab, body.music-open .feed-new-pill { bottom: calc(env(safe-area-inset-bottom, 0px) + 82px + 68px); }
+body.music-open #app { padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px)); }
+body.music-open #app:has(> .app-bottom-nav) { padding-bottom: calc(150px + env(safe-area-inset-bottom, 0px)); }
+@media (min-width: 900px) {
+ .music-bar, body:has(.app-bottom-nav) .music-bar {
+ left: calc(50% + var(--col-mid)); bottom: 16px; width: min(600px, calc(100% - 32px));
+ border-radius: 12px; border-bottom: 1px solid var(--line);
+ }
+ body.music-open .feed-post-fab, body.music-open .feed-new-pill { bottom: 96px; }
+ body.music-open #app:has(> .app-bottom-nav) { padding-bottom: 96px; }
+}
diff --git a/src/sw-nwc.js b/src/sw-nwc.js
index 3dac246..b0ef49f 100644
--- a/src/sw-nwc.js
+++ b/src/sw-nwc.js
@@ -4,20 +4,125 @@
// 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 } from './dm-inbox.js';
+import { allInboxes, classifyDm, shouldNotifyDm, classifyCall } from './dm-inbox.js';
+import { notifyText } from './notify-text.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
+const WRAPS = /^(localhost|127\.0\.0\.1)$/.test(self.location.hostname) ? self.location.origin + '/nwcpush' : NOTIFIER;
+
+// WebKit (Safari, and every browser on iOS) allows no silent pushes: a push
+// event that ends without showing a notification is a strike, even with the
+// app open, and after three it drops the subscription. The wallet then stops
+// waking until it is opened again. Elsewhere a quiet push is fine, so only an
+// Apple endpoint gets a stand-in where we'd otherwise stay silent: closed at
+// once when the app is on screen (it shows everything live there), left as
+// one self-replacing silent line in the background.
+async function applePush() {
+ try {
+ const s = await self.registration.pushManager.getSubscription();
+ return !!s && /(^|\.)push\.apple\.com$/.test(new URL(s.endpoint).hostname);
+ } catch (_) { return false; }
+}
+async function standIn(visible) {
+ 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: './' },
+ });
+ if (visible) {
+ const open = await self.registration.getNotifications({ tag: 'coinos-bg' }).catch(() => []);
+ for (const n of open) n.close();
+ }
+ return true;
+}
self.addEventListener('push', (e) => {
let data = {};
try { data = e.data ? e.data.json() : {}; } catch (_) {}
+ // every path below ends in a notification or, failing that, the stand-in
+ let showed = false;
+ // 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 () => {
+ if (showed) return;
+ showed = true;
+ const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }).catch(() => []);
+ await standIn(clients.some((c) => c.visibilityState === 'visible')).catch(() => {});
+ };
+ const settle = (work) => e.waitUntil((async () => {
+ try { await work(); } finally { await quiet(); }
+ })());
// User-facing notifications (payments, DMs, community chat). An open
// window already shows everything live — stay quiet then.
+ // A call ringing in: the push names the offer's wrap, kept at the notifier
+ // (too big to ride in a push). Opened here with our key; a fresh offer
+ // from someone we follow or talk to rings, as a notification that stays
+ // until it's answered or missed. The offer is kept for the app to pick up
+ // when the tap opens it (CALL_CACHE). An open window rings by itself.
+ if (data.type === 'notify' && data.reason === 'call') {
+ settle(async () => {
+ const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
+ if (clients.some((c) => c.visibilityState === 'visible')) return;
+ let ring = null;
+ try {
+ const r = await fetch(WRAPS + '/wrap/' + encodeURIComponent(data.wrapId || ''));
+ if (r.ok) ring = await classifyCall(await r.json(), await allInboxes());
+ } catch (err) { console.warn('[sw-call] could not open:', err && err.message); }
+ if (!ring) return;
+ if (ring.quiet) {
+ // no ring for them; a note for the app, which lists it as a missed call
+ try {
+ const cache = await caches.open(CALL_CACHE);
+ const had = await cache.match('/__quiet-calls');
+ const list = had ? await had.json() : [];
+ list.push(ring.offer);
+ await cache.put('/__quiet-calls', new Response(JSON.stringify(list.slice(-20)), { headers: { 'content-type': 'application/json' } }));
+ } catch (_) {}
+ return;
+ }
+ try {
+ const cache = await caches.open(CALL_CACHE);
+ await cache.put('/__pending-call', new Response(JSON.stringify({ offer: ring.offer, at: Date.now() }), { headers: { 'content-type': 'application/json' } }));
+ } catch (_) {}
+ for (const c of clients) { try { c.postMessage({ type: 'call-offer', offer: ring.offer }); } catch (_) {} }
+ // the words are measured against Chrome's spam model (notify-text.js):
+ // "<name> is calling" is hidden behind a warning, "Calling" / "<name>" shows
+ const [callTitle, callBody] = notifyText('call', { name: ring.name });
+ await show(callTitle, {
+ body: callBody,
+ icon: 'icon-192.png', badge: 'badge-96.png',
+ tag: 'call', renotify: true, requireInteraction: true, vibrate: [400, 200, 400, 200, 400],
+ data: { url: './?open=call', view: 'call' },
+ });
+ });
+ return;
+ }
if (data.type === 'notify') {
- e.waitUntil((async () => {
+ settle(async () => {
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
if (clients.some((c) => c.visibilityState === 'visible')) return;
// Money landing is exactly when a forwarding rule wants to run, and this
@@ -40,85 +145,131 @@ self.addEventListener('push', (e) => {
if (verdict && verdict.name) dmName = verdict.name;
} catch (err) { console.warn('[sw-dm] could not classify:', err && err.message); }
}
- // A reaction names who, when this device knows them, and is dropped
- // when they are muted here — the notifier can't know either.
- let who = null;
+ // A reaction from someone muted on this device is dropped — the
+ // notifier can't know. (It no longer names who: a name in the line
+ // is what tips Chrome's spam model over, see notify-text.js.)
if (data.reason === 'reaction' && data.from) {
const boxes = await allInboxes().catch(() => []);
if (boxes.some((b) => (b.muted || []).includes(data.from))) return;
- who = boxes.map((b) => b.names && b.names[data.from]).find(Boolean) || null;
}
const emoji = !data.emoji || data.emoji === '+' ? '\u2764\ufe0f' : /^:[\w-]+:$/.test(data.emoji) ? data.emoji : data.emoji.slice(0, 8);
- const T = {
- payment: ['Payment received', data.amountSat ? `+${Number(data.amountSat).toLocaleString()} sats. Open coinos to see it.` : 'Open coinos to see it.'],
- dm: dmName ? [dmName, 'sent you a message.'] : ['New message', 'You have a new private message.'],
- chat: ['New chat activity', 'There are new messages in your communities.'],
- mention: [data.reply ? 'New reply to your post' : 'You were mentioned', data.text || 'Open coinos to see it.'],
- zap: ['Zap received', data.amountSat ? `+${Number(data.amountSat).toLocaleString()} sats. Open coinos to see it.` : 'Someone zapped you. Open coinos to see it.'],
- reaction: [who ? `${who} reacted ${emoji}` : `New reaction ${emoji}`, 'to your post. Open coinos to see it.'],
- };
- const [title, body] = T[data.reason] || T.chat;
+ const [title, body] = notifyText(data.reason, { amountSat: data.amountSat, name: dmName, reply: data.reply, emoji });
// a reply lands you in the Notifications list, where it is
const target = data.reason === 'mention' || data.reason === 'reaction' ? { url: './?open=notifs', view: 'notifs' } : { url: './' };
- await self.registration.showNotification(title, {
+ await show(title, {
body,
icon: 'icon-192.png', badge: 'badge-96.png',
tag: 'notify-' + (data.reason || 'chat'), renotify: ['payment', 'zap', 'mention'].includes(data.reason),
data: target,
});
- })());
+ });
return;
}
- if (data.type !== 'nwc') return;
+ if (data.type !== 'nwc') { settle(async () => {}); return; }
const startedAt = Date.now();
- e.waitUntil((async () => {
+ settle(async () => {
+ // WebKit's silent-push quota counts a push whose notification comes
+ // late: a payment can take most of the push budget, and a worker stopped
+ // before its last line never shows one (PullCap's night of 2026-10-22:
+ // 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 && 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.
- const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
+ // 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.
+ // Android does the same to an app behind another one, minutes in: the
+ // page is frozen, its relay sockets dead, and the nudge sat unread until
+ // the app was opened — the zap spun for as long (wake to payment: 15 s
+ // at the median on Android phones against 6 for a closed app, 2026-11-10).
+ // So on any phone only a window on screen is handed the request; one
+ // behind another app is nudged too, in case it is still awake, and the
+ // request's lock decides between it and this worker.
+ const phone = apple || /Mobi|Android/i.test((self.navigator && self.navigator.userAgent) || '');
+ const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
+ const clients = all.filter((c) => !phone || c.visibilityState === 'visible');
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;
}
+ if (!apple) for (const c of all) { try { c.postMessage({ type: 'nwc-wake', servicePubkey: data.servicePubkey }); } catch (_) {} }
+ 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 self.registration.showNotification(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');
+ const [reqTitle, reqBody] = notifyText(incoming ? 'incoming' : 'spend');
+ await show(reqTitle, {
+ body: reqBody,
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 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 self.registration.showNotification(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: './' },
- });
- })());
+ }, { lease: () => takeLease('work', { wait: Math.max(0, budgetEnd - Date.now() - 3_000) }) });
+ diary(`push done in ${Date.now() - startedAt} ms`);
+ });
});
self.addEventListener('notificationclick', (e) => {
diff --git a/src/video-compress.js b/src/video-compress.js
index 53d4eb0..8fe0856 100644
--- a/src/video-compress.js
+++ b/src/video-compress.js
@@ -52,3 +52,66 @@ export async function compressVideo(file, onProgress = () => {}) {
try { input.dispose?.(); } catch {}
}
}
+
+// A long video as an HLS stream (Adam, 2026-10-18; jb55: "you should use
+// hls (m3u8 ext) for long videos"): a 720p and a 360p rendition, the
+// player taking the one the connection carries, so an hour-long clip
+// neither stalls on mobile data nor costs the whole file to watch a
+// minute of it. Made here, like the shrinking above, in 4-second segments,
+// each rendition (and the sound) one file read in ranges — a handful of
+// uploads, not hundreds. The files keep the names the playlists give them;
+// uploadStream puts them on a host and the playlists on after them.
+// Anything short of a stream — a short clip, no WebCodecs, an error — is
+// null, and the video goes up as one file as before.
+export const STREAM_MIN_S = 90;
+export async function streamVideo(file, onProgress = () => {}) {
+ if (!file || !/^video\//.test(file.type || '')) return null;
+ if (typeof VideoEncoder === 'undefined' || typeof VideoDecoder === 'undefined') return null;
+ let mb;
+ try { mb = await import('mediabunny'); } catch { return null; }
+ const { Input, Output, Conversion, BlobSource, BufferTarget, PathedTarget, HlsOutputFormat, CmafOutputFormat, ALL_FORMATS } = mb;
+ if (!HlsOutputFormat || !PathedTarget) return null;
+ const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
+ try {
+ const video = await input.getPrimaryVideoTrack();
+ if (!video) return null;
+ const seconds = await input.computeDuration();
+ if (!(seconds >= STREAM_MIN_S)) return null;
+ const w = video.displayWidth, h = video.displayHeight, short = Math.min(w, h);
+ const edge = (n) => (w >= h ? { height: Math.min(n, short) } : { width: Math.min(n, short) });
+ const rungs = [{ ...edge(SHORT_EDGE), bitrate: VIDEO_BPS }, { ...edge(360), bitrate: 800_000 }];
+ const files = new Map(); // path -> { target, mime }
+ const target = new PathedTarget('master.m3u8', (req) => {
+ const t = new BufferTarget();
+ files.set(req.path, { target: t, mime: req.mimeType });
+ return t;
+ });
+ const output = new Output({
+ target,
+ format: new HlsOutputFormat({
+ segmentFormat: new CmafOutputFormat(), singleFilePerPlaylist: true, targetDuration: 4,
+ getPlaylistPath: ({ n }) => `p${n}.m3u8`,
+ getSegmentPath: ({ playlist }) => `s${playlist.n}.mp4`, // (a host serves .mp4 to anyone; .m4s it may not take)
+ }),
+ });
+ const conversion = await Conversion.init({
+ input, output,
+ video: rungs.map((r) => ({ ...r, codec: 'avc', keyFrameInterval: 4, forceTranscode: true })),
+ });
+ if (!conversion.isValid) return null;
+ conversion.onProgress = (p) => { try { onProgress(p); } catch {} };
+ await conversion.execute();
+ const out = new Map();
+ for (const [path, { target: t, mime }] of files) {
+ if (!t.buffer) return null;
+ out.set(path, new File([t.buffer], path, { type: /m3u8$/.test(path) ? 'application/vnd.apple.mpegurl' : mime || 'video/mp4' }));
+ }
+ if (!out.has('master.m3u8')) return null;
+ const dim = w >= h ? `${Math.round(w * Math.min(1, SHORT_EDGE / short))}x${Math.min(SHORT_EDGE, short)}` : `${Math.min(SHORT_EDGE, short)}x${Math.round(h * Math.min(1, SHORT_EDGE / short))}`;
+ return { files: out, master: 'master.m3u8', seconds, dim };
+ } catch {
+ return null;
+ } finally {
+ try { input.dispose?.(); } catch {}
+ }
+}
diff --git a/src/wallet.js b/src/wallet.js
index aca11e1..72e0c33 100644
--- a/src/wallet.js
+++ b/src/wallet.js
@@ -9,7 +9,8 @@
// transactions, only the (txid, vout, value, address) of each UTXO.
import { HDKey } from '@scure/bip32';
-import { generateMnemonic, mnemonicToSeedSync, validateMnemonic, entropyToMnemonic } from '@scure/bip39';
+import { generateMnemonic, validateMnemonic, entropyToMnemonic } from '@scure/bip39';
+import { seedSync } from './seed.js';
import { wordlist } from '@scure/bip39/wordlists/english';
import { hex, base64urlnopad, base32nopad, base58check } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
@@ -87,7 +88,7 @@ export function accountXpubFor({ mnemonic, passphrase = '', xprv } = {}, netName
const node = HDKey.fromExtendedKey(xprv);
acct = node.depth === 0 ? node.derive(`m/84'/${coin}'/0'`) : node;
} else {
- acct = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)).derive(`m/84'/${coin}'/0'`);
+ acct = HDKey.fromMasterSeed(seedSync(mnemonic, passphrase)).derive(`m/84'/${coin}'/0'`);
}
return acct.publicExtendedKey;
}
@@ -278,7 +279,7 @@ export class Wallet {
const node = HDKey.fromExtendedKey(this.xprv);
acct = node.depth === 0 ? node.derive(`m/84'/${coin}'/${this.accountIndex || 0}'`) : node;
} else {
- acct = HDKey.fromMasterSeed(mnemonicToSeedSync(this.mnemonic, this.passphrase)).derive(`m/84'/${coin}'/${this.accountIndex || 0}'`);
+ acct = HDKey.fromMasterSeed(seedSync(this.mnemonic, this.passphrase)).derive(`m/84'/${coin}'/${this.accountIndex || 0}'`);
}
this._account = acct;
this._accountKey = key;
@@ -2013,11 +2014,38 @@ export function parseExtendedKey(s) {
// wrong password fails to decrypt rather than returning garbage). All fields
// are hex so the blob is JSON-serializable for localStorage.
const _SCRYPT = { N: 2 ** 15, r: 8, p: 1, dkLen: 32 };
+// A vault under the BLANK password (the default: wallets save themselves to
+// the device unless a password is set) gets nothing from scrypt — anyone with
+// the blob can compute scrypt('') — yet paid for it on every cold launch:
+// ~130 ms on a Pixel 9, half a second on a slower phone, before anything
+// opened. Its key is kept beside the blob instead, and new seals reuse that
+// salt so the kept key stays good. A real password is stretched every time,
+// as before, and never kept.
+const BLANK_KEY = 'btc-wallet-vault-k0';
+let _blank = null; // { salt: hex, key: Uint8Array }
+function blankKey() {
+ if (_blank) return _blank;
+ try {
+ const j = JSON.parse(globalThis.localStorage?.getItem(BLANK_KEY) || 'null');
+ if (j && typeof j.salt === 'string' && typeof j.key === 'string') _blank = { salt: j.salt, key: hex.decode(j.key) };
+ } catch {}
+ return _blank;
+}
function _vaultKey(password, salt) {
- return scrypt(utf8ToBytes(password), salt, _SCRYPT);
+ if (password !== '') return scrypt(utf8ToBytes(password), salt, _SCRYPT);
+ const k = blankKey();
+ const sh = hex.encode(salt);
+ if (k && k.salt === sh) return k.key;
+ const key = scrypt(utf8ToBytes(''), salt, _SCRYPT);
+ _blank = { salt: sh, key };
+ try { globalThis.localStorage?.setItem(BLANK_KEY, JSON.stringify({ salt: sh, key: hex.encode(key) })); } catch {}
+ return key;
}
export function encryptVault(obj, password) {
- const salt = randomBytes(16);
+ // sealed under a real password now: the blank one's key has nothing to open
+ if (password !== '') { _blank = null; try { globalThis.localStorage?.removeItem(BLANK_KEY); } catch {} }
+ const kept = password === '' ? blankKey() : null;
+ const salt = kept ? hex.decode(kept.salt) : randomBytes(16);
const nonce = randomBytes(24);
const ct = xchacha20poly1305(_vaultKey(password, salt), nonce).encrypt(utf8ToBytes(JSON.stringify(obj)));
return { v: 1, salt: hex.encode(salt), nonce: hex.encode(nonce), ct: hex.encode(ct) };