diff options
30 files changed, 1659 insertions, 322 deletions
@@ -16,7 +16,7 @@ import { nip98Header } from './nip98.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'; @@ -375,49 +375,42 @@ function setupFooter() { 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'; @@ -1883,7 +1876,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 }); } @@ -2193,7 +2201,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() { @@ -2210,7 +2223,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 {} @@ -3072,19 +3089,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(); } }, + 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() { @@ -3094,8 +3128,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); }, @@ -3213,13 +3248,17 @@ function settingsTab() { // matters if the phone is lost tonight case 'wallet': if (ui.delAcct && a) return deleteAccountView(a); - return page(a ? [recoveryCard(a), balanceSettingsCard(a), walletNameCard(a), pubkeyCard(a), historyExportCard(), deleteAccountCard(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 = { @@ -3230,6 +3269,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) => @@ -3248,6 +3288,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')), @@ -3255,6 +3297,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')) ); @@ -3668,8 +3711,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; @@ -3873,12 +3916,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) => @@ -3910,18 +3953,34 @@ function recoveryCard(a) { // cannot find this option" (Nils, 2026-11-12) about the Spending card's gear. function balanceSettingsCard(a) { if (a.id !== activeId) return null; - const views = a.kind ? [a.kind] : spendingActive() ? ['spending', 'savings'] : ['savings']; - const row = (view) => h('button', { - class: 'btn-ghost btn-block balance-settings-row', 'data-view': view, - style: 'display:flex;align-items:center;gap:10px;text-align:left;padding:10px 4px', - onClick: () => openWalletSettings(view), - }, - h('span', { style: 'display:flex;color:var(--muted)', html: GEAR_ICON(18) }), - h('span', { class: 'col', style: 'flex:1;gap:2px' }, - h('span', { style: 'font-weight:600' }, viewLabel(a, view)), - h('span', { class: 'small muted' }, t(view === 'spending' ? 'spendingSettingsDesc' : 'savingsSettingsDesc'))), - h('span', { class: 'muted' }, '›')); - return h('div', { class: 'card col', style: 'gap:4px' }, h('h3', {}, t('balanceSettingsTitle')), ...views.map(row)); + 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 = () => { @@ -4052,7 +4111,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', @@ -4256,6 +4315,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; @@ -4292,7 +4366,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. @@ -4300,10 +4375,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 } @@ -4397,6 +4473,24 @@ 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 = ''; @@ -4425,11 +4519,16 @@ function onboardScreen() { title(t('onbWelcomeTitle')), // spaced as the sign-in list is (10px) h('div', { class: 'col', style: 'gap:10px' }, - 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')), + 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', @@ -4554,14 +4653,18 @@ function onboardScreen() { ]); } 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(o.fromGift ? 'onbGiftNameTitle' : 'onbSpendTitle')), - h('p', { class: 'muted', style: 'margin:0' }, t(o.fromGift ? 'onbGiftNameBody' : '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 (or, after a // gift, the account the gift arrived in). - h('button', { class: 'btn-ghost btn-block', onClick: () => { + 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 {} @@ -4719,7 +4822,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) ]); } @@ -4897,22 +5001,142 @@ 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 @@ -4947,6 +5171,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), @@ -5004,6 +5268,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) { @@ -5020,6 +5285,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; @@ -5056,12 +5324,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 @@ -5076,8 +5341,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')))), @@ -5136,7 +5401,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' : '' }, @@ -5186,7 +5453,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 @@ -5211,6 +5478,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 @@ -5504,6 +5807,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 @@ -5569,7 +5873,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); } @@ -5597,6 +5902,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'); @@ -5635,6 +5945,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. @@ -5657,7 +5978,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() ); } } @@ -6583,7 +6906,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; @@ -6601,15 +6924,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); @@ -6837,8 +7156,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 diff --git a/src/features/ark.js b/src/features/ark.js index 1b8c591..2c1a581 100644 --- a/src/features/ark.js +++ b/src/features/ark.js @@ -1,4 +1,4 @@ -import { momentTags } from '../media-timeline.js'; +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. @@ -1516,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. @@ -1892,7 +1906,8 @@ export function arkFeature(ctx) { // 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, moment = null) { - const z = { npub, pk, eventId, moment, amount: '', comment: '', status: 'lookup', autoSat }; + // `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. @@ -1974,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, z.moment); 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)) { @@ -2227,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')), @@ -2237,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, 0, z.moment); } }, '⚡ ' + 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')) @@ -4267,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: '' }; @@ -4330,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 @@ -4346,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. @@ -4429,7 +4480,7 @@ export function arkFeature(ctx) { } } this._histFolded = folded; // a folded row's detail shows the whole payment - return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }))); + return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, m, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }))); }, historyDetail() { if (ui.arkExitDetail) { diff --git a/src/features/gifts.js b/src/features/gifts.js index c6ccbd9..30b8d5e 100644 --- a/src/features/gifts.js +++ b/src/features/gifts.js @@ -1096,7 +1096,7 @@ export function giftsFeature(ctx) { 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/messages.js b/src/features/messages.js index 2892153..d5d286a 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -1,4 +1,4 @@ -import { mediaMoment, momentTags, readMoment, mediaClock, mediaTimeline, markAt } from '../media-timeline.js'; +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. // @@ -39,7 +39,7 @@ import { createThreadPrefetch } from '../thread-prefetch.js'; import { makeImageThumbnails } 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 } from '../recipient-search.js'; import { getNetwork } from '../api.js'; import { decodeBolt11 } from '../ark/lightning.js'; import { hexToBytes, bytesToHex } from '@noble/hashes/utils'; @@ -4360,6 +4360,7 @@ 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 @@ -4833,7 +4834,9 @@ export function messagesFeature(ctx) { } }, '▶ ' + mediaClock(m.seconds)); } const momentStripped = (ev, text) => (readMoment(ev) ? String(text || '').replace(/^\s*\[\d{1,2}(?::\d{2}){1,2}\]\s*/, '') : text); - const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, mediaMoment: m } : ev; }; + // 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; @@ -5246,7 +5249,13 @@ export function messagesFeature(ctx) { // 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); - const feedKeeps = (def, e) => (def && def.search ? e.kind === 1 : def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e)); + // 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. @@ -6541,7 +6550,7 @@ export function messagesFeature(ctx) { c.at = Date.now(); const merge = { newerThan: c.notes.length ? c.notes[0].created_at : Infinity }; if (def.search) { - try { await queryFeed(feedRelaysOr(def, TEXT_SEARCH_RELAYS), { kinds: [1], search: def.search, limit: FEED_PAGE }, merge, c, 5000); } catch {} finally { + try { await searchPass(def, c, merge); } catch {} finally { if (!c.stopped) { c.status = 'ready'; if (c === feed && ui.chatOpen && ui.msgView === 'feed') scheduleRepaint(); } } return; @@ -6583,8 +6592,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); } @@ -6695,7 +6706,7 @@ export function messagesFeature(ctx) { 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); return true; } + 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; @@ -6726,7 +6737,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) + (r ? '&' + r.slice(1) : ''); + 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) { @@ -6856,11 +6867,14 @@ export function messagesFeature(ctx) { } // Words typed into search and submitted without picking a suggestion: // the notes and replies that say them, as a feed for this session. - function openTextSearch(q, relays = []) { + // `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; - const id = 'search:' + q.toLowerCase() + (relays.length ? '@' + relays.join(',') : ''); - if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: '\u201c' + q + '\u201d', follows: false, authors: [], packs: [], topics: [], search: q, relays }); + 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 @@ -7903,6 +7917,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) => { @@ -7923,7 +7965,7 @@ 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 queryFeed(relays || feedRelaysOr(def, TEXT_SEARCH_RELAYS), { kinds: [1], search: def.search, limit, ...extra }, merge, c); + if (def.search) return searchPass(def, c, merge, extra, limit, relays); const orT = orTopicsOf(def); const orPass = orT.length ? queryFeed(relays || feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, limit, ...extra }, merge, c).then((x) => { if (x) got = true; }) @@ -11239,7 +11281,8 @@ export function messagesFeature(ctx) { } else ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev }; const s = ui.noteThread; ui.profOverThread = false; - s.mediaMoment = moment; + 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; @@ -12476,6 +12519,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')))); } @@ -13104,10 +13149,8 @@ export function messagesFeature(ctx) { 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.mediaMoment ? h('div', { class: 'row small muted', style: 'gap:6px;align-items:center' }, - t('mediaCommentAt') + ' ' + mediaClock(s.mediaMoment.seconds), - h('button', { type: 'button', class: 'btn-ghost btn-sm', 'aria-label': t('mediaMomentDrop'), title: t('mediaMomentDrop'), - style: 'padding:0 6px;min-height:0', onClick: () => { s.mediaMoment = null; if (s.momentFor) s.momentFor = null; render(); } }, '×')) : null, + 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 @@ -13182,7 +13225,7 @@ export function messagesFeature(ctx) { // 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.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 = ''; @@ -13203,7 +13246,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; s.mediaMoment = null; // 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(); @@ -17156,25 +17199,132 @@ export function messagesFeature(ctx) { 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); }, - onKeydown: (e) => { if (e.key === 'Enter' && !e.isComposing && s.q.trim()) { e.preventDefault(); openTextSearch(s.q); render(); } }, - }), + 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('searchPostsRow'))))) + h('div', { class: 'muted small' }, t(scoped.length ? 'searchPostsRowAll' : 'searchPostsRow'))))) : null, // a word is a topic too: posts tagged with it, as a feed (() => { @@ -17954,7 +18104,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' }, @@ -17996,8 +18146,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) }))))) ); }); } @@ -18617,8 +18766,7 @@ export function messagesFeature(ctx) { 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(), @@ -19216,16 +19364,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) { if (String(q || '').trim()) { openTextSearch(q); render(); } }, + 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.liveStream = null; ui.goLive = 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; }, @@ -19351,8 +19518,9 @@ export function messagesFeature(ctx) { visitorSignIn() { toFrontDoor(); return true; }, visitorSearch() { rememberReturn(); + 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 }; + ui.userSearch = { q: '', rows: null, scope }; warmSearch(); render(); return true; diff --git a/src/features/names.js b/src/features/names.js index 3f23a0c..e1f23ce 100644 --- a/src/features/names.js +++ b/src/features/names.js @@ -683,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()); } diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js index 4a811fc..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, amberOpen, 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>'; @@ -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 @@ -472,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. @@ -681,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(); @@ -879,5 +1007,6 @@ export function nostrLoginFeature(ctx) { ].filter(Boolean); }, nostrSettingsCards() { return [settingsCard()]; }, + waysBackCard() { return waysBackCard(); }, }; } diff --git a/src/features/nwc.js b/src/features/nwc.js index 9768740..741b0a4 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -627,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], @@ -644,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); } @@ -1106,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()]; }, 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 index a63d180..38b2d8c 100644 --- a/src/features/withdraw-links.js +++ b/src/features/withdraw-links.js @@ -114,6 +114,18 @@ export function withdrawLinks(ctx) { } 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); @@ -130,6 +142,15 @@ export function withdrawLinks(ctx) { 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 @@ -171,7 +192,9 @@ export function withdrawLinks(ctx) { ...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') : t('wlLeft', { amount: amt(l.remainingSat) }))))); + 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() { diff --git a/src/features/zaps.js b/src/features/zaps.js index 8e29409..49e457f 100644 --- a/src/features/zaps.js +++ b/src/features/zaps.js @@ -12,6 +12,7 @@ // 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'; @@ -213,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, moment: target.moment }; + // 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) { @@ -286,7 +288,7 @@ export function zapsFeature(ctx) { 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, moment: z.target.moment, comment: z.comment, + recipientPk: z.target.pk, eventId: z.target.eventId || null, moment: z.momentOn ? z.target.moment : null, comment: z.comment, signFn: sign, }); } @@ -517,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' }, diff --git a/src/i18n.js b/src/i18n.js index baf2012..db7d267 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -38,6 +38,7 @@ const STR = { 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.', @@ -484,6 +485,10 @@ const STR = { 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', @@ -1493,6 +1498,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', @@ -1647,6 +1677,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', @@ -1805,6 +1857,10 @@ const STR = { 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', diff --git a/src/media-timeline.js b/src/media-timeline.js index d8ae008..a70a46c 100644 --- a/src/media-timeline.js +++ b/src/media-timeline.js @@ -20,6 +20,18 @@ export function readMoment(event, depth = 0) { 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'); diff --git a/src/nostr-login.js b/src/nostr-login.js index 3357f61..562a5d4 100644 --- a/src/nostr-login.js +++ b/src/nostr-login.js @@ -514,8 +514,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, @@ -537,7 +543,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/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/style.css b/src/style.css index 55badb6..9f2cd35 100644 --- a/src/style.css +++ b/src/style.css @@ -231,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); } @@ -534,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); @@ -623,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; } @@ -2130,3 +2139,61 @@ html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: aut .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; } diff --git a/tools/amber-login-test.js b/tools/amber-login-test.js deleted file mode 100644 index 46a16f6..0000000 --- a/tools/amber-login-test.js +++ /dev/null @@ -1,104 +0,0 @@ -// NIP-55: on Android, "Sign in with Amber" opens a nostrsigner: intent for the -// pubkey; the answer is read from the clipboard when the tab comes back (or -// pasted); creating the wallet then makes an encrypt and a sign round trip. -// The intent launcher and the clipboard are stubbed; relays answer nothing. -// Run: bun tools/amber-login-test.js -import puppeteer from './puppeteer.js'; -import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; -import { npubEncode } from 'nostr-tools/nip19'; -import { buildHtml } from '../build.js'; -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); -let ok = true; -const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; -const SK = generateSecretKey(); const PK = getPublicKey(SK); -const html = await buildHtml({ minify: true, pwa: false }); -const server = Bun.serve({ port: 5308, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); -const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); -const page = await browser.newPage(); -await page.setUserAgent('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Mobile Safari/537.36'); -await page.evaluateOnNewDocument(() => { - window.__amberUrls = []; - window.__coinosAmberLaunch = (u) => { window.__amberUrls.push(u); }; - window.__clip = ''; - Object.defineProperty(navigator, 'clipboard', { value: { readText: async () => window.__clip, writeText: async () => {} }, configurable: true }); - const Real = window.WebSocket; - window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') { window.__published = (window.__published || []).concat([m[1]]); setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['OK', m[1].id, true, '']) })), 0); return; } } catch {} return send(d); }; return ws; }; - window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); -}); -const errs = []; -page.on('pageerror', (e) => errs.push(String(e))); -const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); -const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; -const urls = () => page.evaluate(() => window.__amberUrls); -const lastType = async () => { const u = await urls(); const last = u[u.length - 1] || ''; return (last.match(/[?&]type=([a-z_0-9]+)/) || [])[1] || null; }; -const deliver = (text) => page.evaluate((t) => { window.__clip = t; document.dispatchEvent(new Event('visibilitychange')); window.dispatchEvent(new Event('focus')); }, text); - -try { - await page.setViewport({ width: 390, height: 844 }); - await page.goto('http://localhost:5308/', { waitUntil: 'domcontentloaded' }); - await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); - await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(500); - console.log('\n[the Amber door]'); - await click('sign in to an existing account'); await sleep(300); - check('the front door offers Nostr sign-in', await click('sign in with nostr') || await click('nostr')); - await sleep(500); - check('on Android, the login offers Amber', await waitText('sign in with a signer app', 5000)); - await click('sign in with a signer app'); await sleep(400); - check('tapping it opens a get_public_key intent', (await lastType()) === 'get_public_key', JSON.stringify(await urls())); - check('...and shows the waiting card with a paste box', await waitText('waiting for your signer', 2000) && !!(await page.$('.amber-paste'))); - await deliver(npubEncode(PK)); - // a fresh account: the wallet is minted and its backup goes to the app to be encrypted - let t0 = Date.now(); while (Date.now() - t0 < 15000 && (await lastType()) !== 'nip44_encrypt') await sleep(250); - check('the pubkey read off the clipboard signs the account in; the seed goes to the app for encryption', (await lastType()) === 'nip44_encrypt', JSON.stringify((await urls()).map((u) => (u.match(/[?&]type=([a-z_0-9]+)/) || [])[1]))); - check('...and the npub left on the clipboard is not mistaken for the ciphertext', await page.evaluate(() => !!document.querySelector('.amber-paste'))); - - console.log('\n[creating the wallet: encrypt, then sign, each a round trip]'); - const encUrl = (await urls()).pop(); - check('...addressed to the user\'s own key', new URL(encUrl.replace('nostrsigner:', 'http://x/')).searchParams.get('pubkey') === PK); - // this time the clipboard is not readable: the answer is pasted - await page.evaluate(() => { navigator.clipboard.readText = async () => { throw new Error('denied'); }; }); - const fakeCipher = 'Ag' + btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(96)))).replace(/=+$/, '').replace(/[^A-Za-z0-9+/]/g, 'a'); - await page.type('.amber-paste', fakeCipher); - await click('use it'); await sleep(800); - check('the pasted ciphertext moves things on to a signature', (await lastType()) === 'sign_event', await lastType()); - const signUrl = (await urls()).pop(); - const unsigned = JSON.parse(decodeURIComponent(signUrl.slice('nostrsigner:'.length).split('?')[0])); - check('...of an event under the signed-in pubkey', unsigned.pubkey === PK && typeof unsigned.kind === 'number', JSON.stringify({ kind: unsigned.kind, pk: unsigned.pubkey.slice(0, 8) })); - const signed = finalizeEvent({ kind: unsigned.kind, created_at: unsigned.created_at, tags: unsigned.tags, content: unsigned.content }, SK); - await page.evaluate(() => { navigator.clipboard.readText = async () => window.__clip; }); - await deliver(JSON.stringify(signed)); await sleep(2500); - const pub = await page.evaluate(() => (window.__published || []).map((e) => e.kind)); - check('the signed backup is published and the new identity walks into onboarding', pub.includes(30078) && await waitText('write down your recovery phrase', 10000), 'published kinds ' + JSON.stringify(pub)); - // the rest of the first run: every further signature (relay list, follows) - // is one more trip through Amber, taken in turn, while the words screen is - // walked through - const signedKinds = []; - let signedUrls = 1; - // answer the next sign_event intent, if one is waiting - const signNext = async () => { - const pend = (await urls()).filter((u) => /type=sign_event/.test(u)); - if (pend.length <= signedUrls) return false; - const u = pend[signedUrls]; signedUrls++; - const ev = JSON.parse(decodeURIComponent(u.slice('nostrsigner:'.length).split('?')[0])); - signedKinds.push(ev.kind); - await deliver(JSON.stringify(finalizeEvent({ kind: ev.kind, created_at: ev.created_at, tags: ev.tags, content: ev.content }, SK))); - return true; - }; - for (let i = 0; i < 80 && !(await page.evaluate(() => document.body.innerText.toLowerCase().includes('receive'))); i++) { - if (!(await signNext())) { await click('later') || await click('skip verification') || await click("i've written it down") || await click('continue'); } - await sleep(500); - } - // The starter follows wait on a deep look for a list this key may already - // have (2026-10-02 follows-overwrite fix), so their signature can arrive - // after the wallet is open: keep answering until things go quiet. - for (let i = 0, idle = 0; i < 60 && idle < 8; i++) { - if (await signNext()) idle = 0; else if (signedKinds.length) idle++; - await sleep(500); - } - if (!(await page.evaluate(() => document.body.innerText.toLowerCase().includes('receive')))) console.log(' DEBUG loop end:', JSON.stringify(await page.evaluate(() => ({ btns: [...document.querySelectorAll('button')].map((b) => b.textContent.trim()).filter(Boolean).slice(0, 12), text: document.body.innerText.slice(0, 160).replace(/\n+/g, ' | ') })))); - check('each later signature (follows, relays) was its own trip, and the wallet opens on Receive', await waitText('receive', 5000) && signedKinds.length > 0, 'signed kinds after the backup ' + JSON.stringify(signedKinds)); - check('no request cancelled another', !(await page.evaluate(() => document.body.innerText)).includes('took its place')); - check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); -} finally { await browser.close(); server.stop(true); } -console.log(ok ? '\n✅ Amber signs in and signs, one trip at a time' : '\n❌ failed'); -process.exit(ok ? 0 : 1); diff --git a/tools/balance-settings-row-test.js b/tools/balance-settings-row-test.js index 89e68d9..351e2fe 100644 --- a/tools/balance-settings-row-test.js +++ b/tools/balance-settings-row-test.js @@ -2,7 +2,9 @@ // balance card's gear opens. "I simply cannot find this option" (Nils, // 2026-11-12) — the Spending gear was the only way in. // Run: bun tools/balance-settings-row-test.js (NO_BUILD=1 to reuse dist/) -import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; @@ -29,16 +31,19 @@ const openWalletPage = async () => { try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); - await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'mainnet')); + await page.evaluate(() => (localStorage.setItem('btc-wallet-network', 'mainnet'), localStorage.setItem('btc-wallet-separate-balances', '1'))); await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); - await click('create a new wallet'); await sleep(600); - await seedWords(page); - await skipSeedCheck(page); + // on mainnet Create makes a Spending-only account (signup-quick-test); a + // seed wallet with Savings alone comes in through the seed-phrase door + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); + await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); if (await waitText('claim a username', 8000)) { await click('not now'); await sleep(800); } await waitText('receive'); await sleep(1500); check('savings-only wallet lists Savings alone', await (async () => { await openWalletPage(); const v = await page.$$eval('.balance-settings-row', (l) => l.map((e) => e.dataset.view)); await page.goBack(); await page.goBack(); await sleep(500); return v.join() === 'savings'; })()); + await waitText('set up a spending account', 30000); await click('set up a spending account'); await sleep(800); if (await waitText('claim a username', 5000)) { await click('not now'); await sleep(800); } await waitText('receive'); await sleep(800); diff --git a/tools/chat-layout-test.js b/tools/chat-layout-test.js index 7c79858..a0f00ad 100644 --- a/tools/chat-layout-test.js +++ b/tools/chat-layout-test.js @@ -164,7 +164,7 @@ try { console.log('\n[direct messages]'); await page.click('.chat-back'); await sleep(500); - check('footer returns when the conversation closes', await page.$eval('.footer', (el) => getComputedStyle(el).display !== 'none')); + // (no footer to bring back: with a wallet open the pickers live in Settings, 2026-11-15) await click('button', 'New message'); await setInput('input[placeholder*="npub" i]', '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'); await click('button', 'Open'); diff --git a/tools/footer-support-test.js b/tools/footer-support-test.js index a37c070..0de6c9a 100644 --- a/tools/footer-support-test.js +++ b/tools/footer-support-test.js @@ -1,5 +1,6 @@ -// The footer's "Show your support" link opens the hat shop, from any page, -// and only shows once a wallet is open (the shop pays from it). +// "Show your support" lives on Settings → About (2026-11-15: the footer is +// gone once a wallet is open; language and currency top the Settings hub) and opens the hat shop; it shows only +// once a wallet is open (the shop pays from it). // Run: bun tools/footer-support-test.js import puppeteer from './puppeteer.js'; import { generateMnemonic } from '@scure/bip39'; @@ -18,31 +19,43 @@ const browser = await puppeteer.launch({ executablePath: process.env.CHROME || ' const page = await browser.newPage(); const errs = []; page.on('pageerror', (e) => errs.push(String(e))); const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); -const link = () => page.evaluate(() => [...document.querySelectorAll('.footer button')].some((b) => b.textContent.trim() === 'Show your support')); +const link = () => page.evaluate(() => !!document.getElementById('about-support')); +const footerOnly = () => page.evaluate(() => { const f = document.querySelector('.footer'); return f ? { selects: f.querySelectorAll('select').length, other: f.querySelectorAll('button, a').length, text: f.innerText.replace(/\s+/g, ' ').trim() } : null; }); +const openAbout = async () => { + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^About/.test(e.textContent.trim())).click()); await sleep(500); +}; try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); await sleep(600); check('no link before there is a wallet', !(await link())); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /^(not now|skip|continue|later)$/i.test(b.textContent.trim()))?.click()); await sleep(400); } await sleep(1500); - check('the footer has "Show your support"', await link()); - // from another page: the feed - await page.evaluate(() => [...document.querySelectorAll('nav button, .bottom-nav button')].find((b) => /feed/i.test(b.textContent))?.click()); await sleep(800); - await page.evaluate(() => [...document.querySelectorAll('.footer button')].find((b) => b.textContent.trim() === 'Show your support').click()); + const f = await footerOnly(); + check('with a wallet open there is no footer', !f || (await page.$eval('.footer', (el) => getComputedStyle(el).display === 'none')), JSON.stringify(f)); + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + check('Settings carries the language and currency', await page.evaluate(() => document.querySelectorAll('.settings-prefs select').length) === 2); + if (process.env.SHOT2) await page.screenshot({ path: process.env.SHOT2 }); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^About/.test(e.textContent.trim())).click()); await sleep(500); + const about = await page.evaluate(() => document.querySelector('.about-card')?.innerText || ''); + check('About has the credits, How it works, the theme and the commit', /Adam Soltys/.test(about) && /git\.coinos\.io/.test(about) && /How it works/.test(about) && /(Dark|Light) mode/.test(about) && /Running git commit [0-9a-f]{7}/.test(about), about.replace(/\n/g, ' | ')); + check('...and "Show your support"', await link()); + const th = await page.evaluate(() => document.documentElement.dataset.theme); + await page.click('#about-theme'); await sleep(300); + check('the theme switch works from there', await page.evaluate(() => document.documentElement.dataset.theme) !== th); + await page.click('#about-theme'); await sleep(300); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); + await page.click('#about-support'); await sleep(1200); const txt = await page.evaluate(() => document.body.innerText); - check('it opens the hat shop', /hat/i.test(txt) && !!(await page.evaluate(() => document.querySelector('.hat-btn') || /Crown|Top hat|hats?/i.test(document.querySelector('.card')?.innerText || ''))), txt.slice(0, 160).replace(/\n/g, ' | ')); - await page.evaluate(() => { document.querySelector('.bottom-nav, nav')?.remove(); window.scrollTo(0, 1e6); }); - await sleep(300); - if (process.env.SHOT) await (await page.$('.footer')).screenshot({ path: process.env.SHOT }); - else await page.screenshot({ path: '/tmp/footer-support.png', fullPage: true }); - // || '/tmp/footer-support.png', fullPage: true }); + check('it opens the hat shop', /hat/i.test(txt), txt.slice(0, 160).replace(/\n/g, ' | ')); check('no page errors', errs.length === 0, errs.join('; ').slice(0, 300)); } catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } console.log(ok ? 'PASS' : 'FAIL'); diff --git a/tools/lnurl-withdraw-links-test.js b/tools/lnurl-withdraw-links-test.js index b349e17..0e0b340 100644 --- a/tools/lnurl-withdraw-links-test.js +++ b/tools/lnurl-withdraw-links-test.js @@ -66,13 +66,13 @@ const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content // ---- the stand-in registrar: the real service, a fake node ---- const OUR = '02' + 'aa'.repeat(32), THEIRS = '03' + 'bb'.repeat(32); const invoices = {}, decoded = {}, outbound = {}; -let seq = 0, circular = 0; +let seq = 0, circular = 0, routeless = false; const mk = (sat, payee) => { const hash = (++seq).toString(16).padStart(64, '0'); const b = 'lnbc' + sat + 'n1fake' + seq; decoded[b] = { valid: true, payment_hash: hash, amount_msat: sat * 1000, payee, created_at: Math.floor(Date.now() / 1000), expiry: 3600 }; return { b, hash }; }; const ln = { async call(m, p) { if (m === 'invoice') { const { b, hash } = mk(p.amount_msat / 1000, OUR); invoices[hash] = { status: 'unpaid', bolt11: b }; return { bolt11: b, payment_hash: hash }; } if (m === 'listinvoices') return { invoices: invoices[p.payment_hash] ? [invoices[p.payment_hash]] : [] }; if (m === 'decode') { if (!decoded[p.string]) throw new Error('bad'); return decoded[p.string]; } - if (m === 'pay') { const d = decoded[p.bolt11]; outbound[d.payment_hash] = 'complete'; return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat }; } + if (m === 'pay') { const d = decoded[p.bolt11]; if (routeless) { outbound[d.payment_hash] = 'failed'; throw new Error('Failed: We could not find a usable set of paths'); } outbound[d.payment_hash] = 'complete'; return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat }; } if (m === 'waitsendpay') { outbound[p.payment_hash] = 'complete'; return { status: 'complete' }; } if (m === 'listsendpays') return { payments: outbound[p.payment_hash] ? [{ status: outbound[p.payment_hash] }] : [] }; throw new Error('unexpected ' + m); @@ -105,7 +105,7 @@ const server = Bun.serve({ port: 0, async fetch(req) { return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, - circularPick: async () => ({ cap: 1e9 }), payCircular: async () => { circular++; return { feeMsat: 0 }; }, publicBase: server.url.origin.replace(/\/$/, '') }); + circularPick: async () => ({ cap: 1e9 }), payCircular: async () => { circular++; return { feeMsat: 0 }; }, wait: async () => {}, publicBase: server.url.origin.replace(/\/$/, '') }); const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] }); const page = await browser.newPage(); @@ -161,6 +161,27 @@ try { check('…and the wallet watched for that payment', (await page.evaluate(() => test.watched.length)) >= 1); check('…the toast says so', (await page.evaluate(() => window.toasts || [])).some((m) => /1,000 sats is back in Spending/.test(m))); check('a closed link refuses claims', svc.params(link.id).status === 'ERROR'); + + console.log('\n[a claim with no route to the wallet that asked]'); + await click('← Back'); + if (!(await page.$('#wl-amount'))) await page.evaluate(() => document.querySelector('#wl-open')?.click()); + await page.waitForSelector('#wl-amount', { timeout: 3000 }).catch(async () => { throw new Error('no form: ' + await text()); }); + await type('#wl-amount', '700'); await type('#wl-uses', '1'); await type('textarea', ''); + await page.click('#wl-create'); + check('a second link is made', await waitText(/Your withdraw link is ready/)); + const link2 = Object.values(state.withdraws).find((x) => x.id !== link.id); + routeless = true; + const theirs = mk(700, THEIRS).b; + check('the claimer is told OK (LUD-03 pays after)', (await svc.callback(link2.id, link2.k1, theirs)).status === 'OK'); + for (let i = 0; i < 50 && link2.claims[0]?.status !== 'failed'; i++) await pause(20); + check('it was tried again before giving up, and the sats went back', link2.claims[0].status === 'failed' && link2.claims[0].tries > 1 && link2.spentSat === 0, JSON.stringify(link2)); + await page.evaluate(() => { test.ui.giftMode = false; test.render(); document.querySelector('#wl-open').click(); }); + check('the list says the claim failed', await waitText(/claim failed · 700 sats left/), await text()); + await page.evaluate(() => [...document.querySelectorAll('.wl-row')].find((b) => /claim failed/.test(b.textContent)).click()); + check('the link page says nothing was sent and the sats are still here', await waitText(/A claim of 700 sats couldn't be delivered.*sats are still in this link/), await text()); + check('…and still offers the QR and take back', !!(await page.$('svg')) && /Take back 700 sats/.test(await text())); + routeless = false; + check('the same link pays a claim once a route is there', (await svc.callback(link2.id, link2.k1, mk(700, THEIRS).b)).status === 'OK' && (await (async () => { await pause(50); return link2.claims[1]?.status === 'paid'; })()), JSON.stringify(link2.claims)); check('no page errors', errors.length === 0, errors.join('; ')); console.log('\n✅ prepaid withdraw links'); } catch (e) { console.error('\n❌', e.message); process.exitCode = 1; } finally { await browser.close(); server.stop(true); } diff --git a/tools/media-moments-feed-test.js b/tools/media-moments-feed-test.js index 5b4c8fb..00baf9c 100644 --- a/tools/media-moments-feed-test.js +++ b/tools/media-moments-feed-test.js @@ -140,7 +140,10 @@ try { check('no "at this time" buttons', await page.evaluate(() => !document.body.innerText.includes('at this time'))); await act('.note-audio', 'Like'); await page.waitForSelector('.msg-sheet'); - await page.evaluate(() => document.querySelector('.msg-sheet button').click()); + // the moment is offered, not taken (Adam, 2026-11-14): tick it to tie the reaction to 0:05 + check('the reaction sheet offers the moment, off', await page.evaluate(() => { const b = document.querySelector('.msg-sheet .moment-toggle'); return !!b && b.getAttribute('aria-pressed') === 'false' && b.textContent.includes('0:05'); })); + await page.click('.msg-sheet .moment-toggle'); + await page.evaluate(() => document.querySelector('.msg-sheet button:not(.moment-toggle)').click()); await sleep(400); const reaction = await page.evaluate(() => window.__relayGuard.events.find(e => e.kind === 7 && e.tags.some(t => t[0] === 'media'))); check('reaction is signed with the selected file and position', reaction?.tags.some(t => t[0] === 'media' && t[2] === '5')); @@ -149,7 +152,9 @@ try { await page.screenshot({ path: '/tmp/media-timeline-playing.png' }); await act('.note-audio', 'Reply'); await page.waitForSelector('.thread-reply-input'); - check('timestamp is visible in the reply composer', (await page.evaluate(() => document.body.innerText)).includes('Comment at 0:05')); + check('the reply composer offers the moment, off', await page.evaluate(() => { const b = document.querySelector('.thread-reply .moment-toggle'); return !!b && b.getAttribute('aria-pressed') === 'false' && b.textContent.includes('0:05'); })); + await page.click('.thread-reply .moment-toggle'); + check('…tapped, it is on', await page.evaluate(() => document.querySelector('.thread-reply .moment-toggle').getAttribute('aria-pressed') === 'true')); await page.evaluate(() => { const input = document.querySelector('.thread-reply-input'); input.value = 'Great moment'; input.dispatchEvent(new Event('input', { bubbles: true })); }); await page.click('.thread-reply-send'); await sleep(500); @@ -169,7 +174,8 @@ try { await sleep(150); await page.evaluate(() => document.querySelector('.media-pager .mp-cur .mp-like').click()); await page.waitForSelector('.msg-sheet'); - await page.evaluate(() => document.querySelector('.msg-sheet button').click()); + await page.evaluate(() => document.querySelector('.msg-sheet .moment-toggle').click()); + await page.evaluate(() => document.querySelector('.msg-sheet button:not(.moment-toggle)').click()); await sleep(300); check('video reaction carries the video URL and selected second', await page.evaluate(() => window.__relayGuard.events.some(e => e.kind === 7 && e.tags.some(t => t[0] === 'media' && t[1].endsWith('.mp4') && t[2] === '1')))); check('...and shows over the pager\'s seek bar', await page.waitForFunction(() => !!document.querySelector('.media-pager .mp-cur .mp-seek .mp-mark'), { timeout: 3000 }).then(() => true, () => false)); diff --git a/tools/noffer-test.js b/tools/noffer-test.js index 152ef0b..5886f84 100644 --- a/tools/noffer-test.js +++ b/tools/noffer-test.js @@ -31,8 +31,9 @@ const published = []; const nwcTransport = { subscribe: (relays, filter, on) => { subHandlers.push({ filter, on }); return () => {}; }, publish: async (relays, evt) => { published.push(evt); return true; }, - query: async () => [], + query: async (relays, filter) => queryImpl(relays, filter), }; +let queryImpl = async () => []; const wallet = { watchOnly: false, loadFeatureState: (n, fb) => JSON.parse(store['fs:' + n] || 'null') || fb, @@ -95,5 +96,24 @@ await offerSub.on(reqEv); await new Promise((r) => setTimeout(r, 60)); check('replayed request ignored', published.filter((e) => e.kind === 21001).length === before); +console.log('\n[the receipt, from two devices]'); +// the zap is paid: this device publishes its receipt once +hooks.arkMovements = () => [{ type: 'ln-receive', status: 'complete', invoice: 'lnbc_mock_21', preimage: 'ee'.repeat(32) }]; +const receipts = () => published.filter((e) => e.kind === 9735); +queryImpl = async (relays, filter) => published.filter((e) => (filter.kinds || []).includes(e.kind) && (!filter.authors || filter.authors.includes(e.pubkey))); +await f.nwcPublishZapReceipts(); +check('the paid zap gets its receipt', receipts().length === 1 && receipts()[0].pubkey === offer.pubkey); +await f.nwcPublishZapReceipts(); +check('…once, however often the pass runs', receipts().length === 1); +// another device: the synced state still lists it pending (it synced before +// this device's pass), and the relays have the receipt already +const st3 = JSON.parse(store['fs:nwc']); +st3.zapPending = [{ zap: JSON.stringify(zapReq), invoice: 'lnbc_mock_21', ts: Date.now() }]; +st3.zapDone = []; +store['fs:nwc'] = JSON.stringify(st3); +await f.nwcPublishZapReceipts(); +check('a second device finds it on the relays and stays quiet', receipts().length === 1, receipts().length + ' receipts'); +check('…and drops it from the pending list', (JSON.parse(store['fs:nwc']).zapPending || []).length === 0); + console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ offer service behaves'); process.exit(fails ? 1 : 0); diff --git a/tools/onboard-backup-test.js b/tools/onboard-backup-test.js index 8fc1071..946f342 100644 --- a/tools/onboard-backup-test.js +++ b/tools/onboard-backup-test.js @@ -64,6 +64,10 @@ try { const page = await browser.newPage(); await page.setViewport({ width: 390, height: 844 }); await page.goto('http://localhost:5291/', { waitUntil: 'domcontentloaded' }); + // regtest: the classic phrase flow. Where a name can be claimed (mainnet, + // mutinynet) Create is the quick sign-up instead — signup-quick-test.js. + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(1500); // Two choices and nothing else (2026-11-06): a new wallet, or one you // already have — the sign-in methods wait behind the second. diff --git a/tools/pos-test.js b/tools/pos-test.js index 55349cb..2b6a0b7 100644 --- a/tools/pos-test.js +++ b/tools/pos-test.js @@ -30,7 +30,7 @@ const ctx = { }; const feature = posFeature(ctx); window.__feature = feature; function render() { document.querySelector('#app').replaceChildren(feature.screenView() || h('div', { id: 'closed' }, 'closed')); } -window.test = { open: () => { feature.openPos(); }, init: () => { feature.init(); render(); }, +window.test = { open: () => { feature.openPos(); }, request: () => { feature.openAmountRequest(); }, init: () => { feature.init(); render(); }, cards: () => { document.querySelector('#app').replaceChildren(...feature.posSettingsCards()); }, settle: (ok) => { const w = watch; watch = null; w.cb({ step: ok ? 'done' : 'failed' }); }, get watch() { return watch && watch.id; }, get cancelled() { return cancelled; }, get sales() { return (state.pos || {}).sales || []; }, ui }; render(); `; @@ -128,6 +128,24 @@ try { check("the old device-wide flag is dropped on start (it can't say whose it was)", await page.evaluate(() => (test.ui.pos = null, true)) && (await boot('owner')) && await page.evaluate(() => localStorage.getItem('btc-wallet-pos-mode') === null)); check('another wallet on the same device does not start in point of sale', !(await boot('someone-else'))); check('the owner still does, after anyone else has been in', await boot('owner')); + + console.log('\n[Receive → Amount]'); + await page.evaluate(() => { localStorage.removeItem('btc-wallet-pos-mode:owner'); test.ui.pos = null; test.request(); }); await pause(50); + let rq = await text(); + check('opens as Request an amount, without the till around it', /Request an amount/.test(rq) && !/ask for a tip|Tips today|Sales today/i.test(rq) && !(await page.$('.pos-sale')), rq.slice(0, 200)); + const before = await page.evaluate(() => test.sales.length); + await type('.pos-amount', '2100'); + await page.click('#pos-charge'); await pause(100); + rq = await text(); + check('straight to the invoice, no tip prompt', /Scan to pay/i.test(rq) && /2,100/.test(rq) && !!(await page.$('.pos-qr')), rq.slice(0, 200)); + const req = await page.evaluate(() => test.sales[test.sales.length - 1]); + check('the request is for the amount, no tip, and marked', req.billSat === 2100 && req.tipSat === 0 && req.request === true, JSON.stringify(req)); + await page.evaluate(() => test.settle(true)); await pause(100); + check('paid, with Done back to Receive', /Done/.test(await text()) && !/New sale/.test(await text())); + await click('Done'); await pause(50); + check('Done closes it', !!(await page.$('#closed'))); + await page.evaluate(() => { test.ui.pos = null; test.open(); }); await pause(50); + check("the till's sales list leaves requests out", !(await text()).includes('2,100'), String(before)); check('no browser errors', errors.length === 0); } finally { await browser.close(); server.stop(true); } console.log('\n✅ point of sale'); diff --git a/tools/profile-stream-test.js b/tools/profile-stream-test.js index 8d15775..2b426bb 100644 --- a/tools/profile-stream-test.js +++ b/tools/profile-stream-test.js @@ -17,7 +17,7 @@ const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); const page = await browser.newPage(); const errs = []; -page.on('pageerror', (e) => errs.push(String(e))); +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); try { await page.setViewport({ width: 390, height: 844 }); if (process.env.DARK) await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]); @@ -27,7 +27,7 @@ try { await page.waitForSelector('.user-search-main', { timeout: 10000 }); await page.type('.user-search-main', Q, { delay: 60 }); // the result rows: people (not the "posts that say this" or #topic rows) - const rows = () => page.evaluate(() => [...document.querySelectorAll('.list .item')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim())).map((r) => r.textContent.trim().slice(0, 40))); + const rows = () => page.evaluate(() => [...document.querySelectorAll('.list .item:not(.search-scoped-row)')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim())).map((r) => r.textContent.trim().slice(0, 40))); let found = []; for (let i = 0; i < 60 && !found.length; i++) { found = await rows(); if (!found.length) await sleep(250); } if (!found.length) console.log(await page.evaluate(() => document.querySelector('.user-search-main')?.closest('.col')?.parentElement?.innerHTML.slice(0, 1500))); @@ -35,7 +35,7 @@ try { const wait = Number(process.env.WAIT || 0); // ms between results and the tap (prefetch's head start) if (wait) await sleep(wait); const t0 = Date.now(); - await page.evaluate(() => [...document.querySelectorAll('.list .item')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim()))[0].click()); + await page.evaluate(() => [...document.querySelectorAll('.list .item:not(.search-scoped-row)')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim()))[0].click()); let ghostAt = 0, firstAt = 0, rowsAt3 = 0; for (let i = 0; i < 200; i++) { const s = await page.evaluate(() => ({ @@ -52,6 +52,23 @@ try { console.log(` placeholder ${ghostAt ? ghostAt + ' ms' : 'not seen'}, first post ${firstAt || '—'} ms, rows at 3 s ${rowsAt3}`); check('posts arrive', firstAt > 0); check('...while waiting, the page says posts are loading', !!ghostAt || firstAt < 300, ghostAt ? 'placeholder shown' : 'posts were already in hand'); + // a second search typed into the desktop header field while that profile + // is open: the results come forward ("the search box stops working", + // Adam 2026-11-14 — they updated a page hidden under the profile) + await page.setViewport({ width: 1300, height: 900 }); + await sleep(500); + const field = await page.$('input.header-search, .header-search-field'); + check('the desktop header has a search field', !!field); + if (field) { + await page.evaluate(() => { const f = document.querySelector('input.header-search, .header-search-field'); f.focus(); f.value = ''; }); + await field.type('jack', { delay: 60 }); + let again = []; + for (let i = 0; i < 80 && !(again.length && again[0] !== found[0]); i++) { again = await rows(); if (!(again.length && again[0] !== found[0])) await sleep(250); } + const onProfile = await page.evaluate(() => !!document.querySelector('.prof-tabs')); + check('typing a new search from a profile shows its results', again.length > 0 && !onProfile, again.slice(0, 2).join(' | ')); + await page.goBack(); await sleep(800); + check('...and Back returns to the profile', await page.evaluate(() => !!document.querySelector('.prof-tabs'))); + } check('no page errors', !errs.length, errs.join(' | ')); } catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } console.log(ok ? '\nPASS' : '\nFAIL'); diff --git a/tools/search-scope-test.js b/tools/search-scope-test.js new file mode 100644 index 0000000..122fcd0 --- /dev/null +++ b/tools/search-scope-test.js @@ -0,0 +1,96 @@ +// Searching inside one person's posts (Adam, 2026-11-14: "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'"). On a profile the +// header field carries the person as a chip and Enter searches their posts; +// words that begin with the name of someone whose profile you opened +// ("fiatjaf relay") are offered, and Enter takes them there. Reads real +// relays (relays: 'read'; nothing is published). +// Run: bun tools/search-scope-test.js (WHO=npub… NAME=fiatjaf WORD=relay) +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const WHO = process.env.WHO || 'npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6'; // fiatjaf +const NAME = process.env.NAME || 'fiatjaf'; +const WORD = process.env.WORD || 'relay'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); +const until = async (fn, ms = 15000, arg) => { for (let i = 0; i < ms / 200; i++) { const v = await page.evaluate(fn, arg); if (v) return v; await sleep(200); } return null; }; +const feedState = () => page.evaluate((word) => { + const posts = [...document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key]')].filter((p) => !/^(hr:|win-)/.test(p.getAttribute('data-key'))); + return { path: location.pathname + location.search, title: document.querySelector('.feed-page h2, .feed-title, .feed-name')?.textContent || '', + n: posts.length, without: posts.filter((p) => !p.textContent.toLowerCase().includes(word)).length }; +}, WORD); +try { + await page.setViewport({ width: 1300, height: 900 }); + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + check('the profile opens', !!(await until(() => document.querySelector('.prof-tabs')))); + const chip = await until((n) => { const c = document.querySelector('.header-search-scoped .search-scope-chip')?.textContent || ''; return c.toLowerCase().includes(n) && c; }, 15000, NAME.toLowerCase()); + check('the header field carries the person as a chip', !!chip && chip.toLowerCase().includes(NAME.toLowerCase()), chip || ''); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-chip.png'), clip: { x: 0, y: 0, width: 1300, height: 120 } }); + + await page.click('.header-search-field'); + await page.type('.header-search-field', WORD, { delay: 50 }); + const row = await until(() => document.querySelector('.search-scoped-row')?.textContent); + check('the results offer the words in their posts, first', !!row && row.includes(WORD) && /posts/.test(row), row || ''); + const people = await until(() => document.querySelectorAll('.list .item:not(.search-scoped-row)').length > 2); + check('…and still find people', !!people); + await page.keyboard.press('Enter'); + const f1 = await until(async () => document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key]').length >= 1 && location.search.includes('p=npub'), 25000); + const s1 = await feedState(); + check('Enter searches only their posts (URL carries the person)', !!f1 && s1.path.includes('q=' + WORD) && s1.path.includes('p=npub'), JSON.stringify(s1)); + check('…every post says the word', s1.n > 0 && s1.without === 0, `${s1.n} posts, ${s1.without} without "${WORD}"`); + const authors = await page.evaluate(() => [...new Set([...document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key] .note-author, .notes-feed:not(.note-ghosts) > [data-key] .chat-name')].map((n) => n.textContent.trim()))].slice(0, 5)); + console.log(' authors seen:', authors.join(', ')); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-feed.png') }); + + // the guess: "<name> <word>" from scratch, the profile having been opened + await page.goto(server.url.href + 'feed', { waitUntil: 'domcontentloaded' }); + await sleep(1500); + await page.evaluate((pk) => { /* nothing: a reload forgets the session's profiles */ }, WHO); + check('no chip away from a profile', !(await page.$('.search-scope-chip'))); + // open the profile in this session, then go back and type the combined query + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + await until(() => document.querySelector('.prof-tabs')); + await page.click('.search-scope-x'); + check('× takes the chip out', !!(await until(() => !document.querySelector('.search-scope-chip')))); + await page.click('input.header-search'); + await page.type('input.header-search', `${NAME} ${WORD}`, { delay: 50 }); + const guess = await until(() => document.querySelector('.search-scoped-row')?.textContent, 15000); + check('"name word" is offered as their posts', !!guess && guess.includes(`“${WORD}”`) && guess.toLowerCase().includes(NAME.toLowerCase()), guess || ''); + check('…as the strong guess (Enter hint)', !!(await page.$('.search-scoped-row .search-enter-hint'))); + await page.keyboard.press('Enter'); + const f2 = await until(() => location.search.includes('p=npub') && location.search.includes('q=' + encodeURIComponent('relay').slice(0, 3)), 15000); + check('Enter takes the guess', !!f2, (await feedState()).path); + + // a query that is someone's whole name is not split + await page.click('input.header-search, .header-search-field'); + await page.evaluate(() => { const f = document.querySelector('input.header-search, .header-search-field'); f.value = ''; }); + await page.type('input.header-search, .header-search-field', 'nobody wordthatmatchesnoone', { delay: 30 }); + await sleep(3000); + check('no guess when no name starts the words', !(await page.$('.search-scoped-row'))); + // a phone: the magnifier on a profile opens search with the chip in it + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + await until(() => document.querySelector('.prof-tabs')); + await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Search' && b.offsetParent)?.click()); + const mchip = await until(() => document.querySelector('.user-search-main .search-scope-chip')?.textContent); + check('phone: search from a profile carries the chip', !!mchip, mchip || ''); + await page.type('.user-search-input', WORD, { delay: 40 }); + check('phone: …and offers their posts', !!(await until(() => document.querySelector('.search-scoped-row')))); + await page.click('.user-search-input'); + await page.keyboard.press('End'); + for (let i = 0; i < WORD.length; i++) await page.keyboard.press('Backspace'); + await page.keyboard.press('Backspace'); + check('phone: Backspace on the empty field takes the chip out', !!(await until(() => !document.querySelector('.search-scope-chip')))); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-phone.png') }); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/send-enter-keys-test.js b/tools/send-enter-keys-test.js index aac95f8..54f2c02 100644 --- a/tools/send-enter-keys-test.js +++ b/tools/send-enter-keys-test.js @@ -45,8 +45,13 @@ const armPrimary = () => page.evaluate(() => { try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); + // the two-card carousel is the "separately" view now (one balance is the default) + await page.evaluate(() => localStorage.setItem('btc-wallet-separate-balances', '1')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + // a seed wallet comes in through the seed-phrase door (Create is a sign-up on mainnet) + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /^(not now|skip|continue|later)$/i.test(b.textContent.trim()))?.click()); diff --git a/tools/send-lnaddr-advance-test.js b/tools/send-lnaddr-advance-test.js index fd6c1a1..14640ca 100644 --- a/tools/send-lnaddr-advance-test.js +++ b/tools/send-lnaddr-advance-test.js @@ -43,7 +43,8 @@ try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); await sleep(400); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); // mainnet onboarding: skip the username step (and anything after it) for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { diff --git a/tools/signup-quick-test.js b/tools/signup-quick-test.js new file mode 100644 index 0000000..5005d6a --- /dev/null +++ b/tools/signup-quick-test.js @@ -0,0 +1,236 @@ +// Signing up is a name and a look, nothing else (Adam, 2026-11-15): "i'd like +// to move away from requiring people to backup and verify a seed phrase to +// sign up. we should just have them claim a name and pick their avatar/cover +// and they should be in. we should also not create a savings account by +// default but let them add it later … adding additional auth methods like +// passkey, nostr, or google should be possible once they've created their +// account." +// +// Mainnet, with the Ark server's info read for real and the names registrar +// mocked (nothing is claimed): Create an account → no twelve words, no check +// → Claim your name (no "Not now") → Choose your look → in, on ONE balance +// (no carousel; on-chain is part of the account, a Bitcoin address a tap away +// on Receive); Settings → Wallet shows "Ways back in" (passkey via a CDP +// virtual authenticator → listed) and one balance row, with "Show Spending +// and Savings separately" (→ the two faces; a reload keeps them). +// Run: bun tools/signup-quick-test.js (NO_BUILD=1 to reuse dist/) +import puppeteer from './puppeteer.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +if (!process.env.NO_BUILD && Bun.spawnSync(['bun', 'build.js']).exitCode !== 0) throw new Error('build failed'); +const server = Bun.serve({ port: 0, fetch: async (req) => { + const path = new URL(req.url).pathname; + const f = Bun.file('dist' + path); + return path.includes('.') && await f.exists() ? new Response(f) : new Response(Bun.file('dist/index.html')); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +const registered = []; +const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type,authorization', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS' }; +await page.setRequestInterception(true); +page.on('request', (r) => { + const u = new URL(r.url()); + if (u.origin === server.url.origin || u.hostname === 'ark.coinos.io') return r.continue(); + if (u.hostname !== 'names.coinos.io') return r.abort(); + if (r.method() === 'OPTIONS') return r.respond({ status: 200, headers: cors, body: '{}' }); + const reply = (j, status = 200) => r.respond({ status, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(j) }); + if (u.pathname === '/register' && r.method() === 'POST') { const j = JSON.parse(r.postData() || '{}'); registered.push(j.name); return reply({ ok: true, name: j.name }); } + if (u.pathname.startsWith('/name/')) return reply({ taken: false }); + if (u.pathname.startsWith('/pubkey/')) return reply({}); + return reply({}); +}); +page.on('pageerror', (e) => errs.push(String(e))); +const click = (x) => page.evaluate((s) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(s)); if (e) e.click(); return !!e; }, x); +const text = () => page.evaluate(() => document.body.innerText); +const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const openWalletPage = async () => { + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^Wallet/.test(e.textContent.trim())).click()); await sleep(600); +}; +try { + await page.setViewport({ width: 390, height: 844 }); + const cdp = await page.createCDPSession(); + await cdp.send('WebAuthn.enable'); + await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { + protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, hasPrf: true, automaticPresenceSimulation: true } }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'mainnet')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#onb-create', { timeout: 15000 }); + check('the front door says Create an account', (await page.$eval('#onb-create', (e) => e.textContent.trim())) === 'Create an account'); + await page.click('#onb-create'); + check('no seed screens: straight to Claim your name', await waitText('claim your name', 20000)); + const t1 = await text(); + check('no twelve words or check on the way', !(await page.$('.words')) && !/which word/i.test(t1)); + check('no "Not now" on a sign-up\'s name step', !/not now/i.test(t1)); + await page.waitForSelector('.onb input[type=text]', { timeout: 20000 }); + await page.type('.onb input[type=text]', 'quicktester'); + await click('claim'); + check('the name goes to the registrar', await (async () => { for (let i = 0; i < 80 && !registered.length; i++) await sleep(250); return registered.includes('quicktester'); })(), registered.join()); + check('then the look: avatar and cover', await (async () => { for (let i = 0; i < 80; i++) { if (await page.$('.onb-cover')) return true; await sleep(250); } return false; })()); + await click('continue'); await sleep(800); + if (await waitText("you're all set", 8000)) await click('enter'); + await page.waitForSelector('.balance-face', { timeout: 20000 }); + await sleep(1500); + const shape = async () => page.evaluate(() => ({ + faces: document.querySelectorAll('.balance-face').length, + carousel: !!document.querySelector('.bal-carousel'), + label: document.querySelector('.balance-face .small.faint')?.textContent.trim(), + body: document.body.innerText, + })); + let s = await shape(); + check('in, on one balance (no carousel, no name on it)', s.faces === 1 && !s.carousel && !s.label && !!(await page.$('.balance-one')), JSON.stringify({ faces: s.faces, carousel: s.carousel, label: s.label })); + // asked once, and only with money in the account (2026-11-15): not on an empty one + check('no way-back-in prompt on an empty account', !/add a way back into your account/i.test(s.body) && !(await page.$('.ways-back-prompt'))); + // money arrives in Spending (the ark feature, found on the heap, made to + // report a balance; then a repaint) + const giveBalance = async () => { + const protoH = await page.evaluateHandle(() => Object.prototype); + const all = await page.queryObjects(protoH); + const found = await page.evaluate((objs) => { + const f = objs.find((o) => { try { return o && o.id === 'ark' && typeof o.spendingSat === 'function'; } catch { return false; } }); + if (!f) return false; + f.spendingSat = () => 5000; + window.dispatchEvent(new Event('resize')); + document.querySelector('.tabs button')?.click(); document.querySelector('.tabs button')?.click(); + return true; + }, all); + await all.dispose(); await protoH.dispose(); + await sleep(800); + return found; + }; + check('(test: found the ark feature)', await giveBalance()); + check('with a balance, it asks once for a way back in', !!(await page.$('.ways-back-prompt')), (await text()).slice(0, 300).replace(/\n/g, ' | ')); + await page.evaluate(() => [...document.querySelectorAll('.ways-back-prompt button')].find((b) => /not now/i.test(b.textContent)).click()); await sleep(400); + check('Not now puts it away', !(await page.$('.ways-back-prompt'))); + await page.reload({ waitUntil: 'domcontentloaded' }); await page.waitForSelector('.balance-face', { timeout: 20000 }); await sleep(1500); + await giveBalance(); + check('...and never again, not after a reload', !(await page.$('.ways-back-prompt'))); + // the breakdown (Ark / On-chain / Gifts) folds away under the total; a + // gift line stands in for it here (the ark feature made to report one) + { + const protoH = await page.evaluateHandle(() => Object.prototype); + const all = await page.queryObjects(protoH); + await page.evaluate((objs) => { + const f = objs.find((o) => { try { return o && o.id === 'ark' && typeof o.balanceLines === 'function'; } catch { return false; } }); + f.balanceLines = () => [{ label: 'Gifts', sat: 700, side: 'savings', part: true }]; + document.querySelector('.tabs button')?.click(); document.querySelector('.tabs button')?.click(); + }, all); + await all.dispose(); await protoH.dispose(); await sleep(600); + const face = () => page.evaluate(() => ({ t: document.querySelector('.balance-one')?.innerText || '', btn: document.querySelector('.balance-one .breakdown-toggle')?.textContent || '' })); + let f = await face(); + check('breakdown folded by default, with a way to open it', !/GIFTS/i.test(f.t.replace(f.btn, '')) && /breakdown/i.test(f.btn), JSON.stringify(f)); + await page.click('.balance-one .breakdown-toggle'); await sleep(400); + f = await face(); + check('opened, it shows the Gifts line', /Gifts/i.test(f.t.replace(f.btn, '')) && /hide/i.test(f.btn), JSON.stringify(f)); + if (process.env.SHOT3) await page.screenshot({ path: process.env.SHOT3 }); + check('remembered on this device', await page.evaluate(() => localStorage.getItem('btc-wallet-balance-breakdown') === '1')); + await page.evaluate(() => localStorage.removeItem('btc-wallet-balance-breakdown')); + } + for (let i = 0; i < 60 && !(await page.$('#recv-amount')); i++) await sleep(250); + check('Receive has an Amount button', !!(await page.$('#recv-amount'))); + check('no History heading on an empty wallet', !/\bHISTORY\b/.test(await page.evaluate(() => document.body.innerText))); + if (process.env.SHOT3) await page.screenshot({ path: process.env.SHOT3 }); + await page.click('#recv-amount'); await sleep(500); + check('Amount opens the amount pad', !!(await page.$('.pos-amount')) && /request an amount/i.test(await text())); + if (process.env.SHOT4) await page.screenshot({ path: process.env.SHOT4 }); + await click('back'); await sleep(500); + check('Back returns to Receive', !(await page.$('.pos-amount')) && !!(await page.$('#recv-amount'))); + // one account takes on-chain payments too: its address under the payment one + check('Receive offers a Bitcoin address', !!(await page.$('#recv-onchain'))); + await page.click('#recv-onchain'); await sleep(400); + const oc = await page.evaluate(() => document.querySelector('.addr-box')?.textContent.trim() || ''); + check('...an on-chain address', /^bc1q/.test(oc), oc); + await page.click('#recv-payaddr'); await sleep(400); + check('...and back to the payment address', !!(await page.$('#recv-amount')) && !(await page.$('#recv-payaddr'))); + const acct = await page.evaluate(() => JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}')); + const a0 = (acct.accounts || [])[0] || {}; + check('the account: one balance (no kind), phrase unseen, saved to the device', !a0.kind && !a0.savingsLater && !!a0.spendingSetup && a0.seedSeen === false && a0.persisted, JSON.stringify({ kind: a0.kind, later: a0.savingsLater, seen: a0.seedSeen, persisted: a0.persisted })); + + await openWalletPage(); + check('Settings → Wallet opens with Ways back in', !!(await page.$('.ways-back')) && /ways back in/i.test(await text())); + const views = await page.$$eval('.balance-settings-row[data-view]', (l) => l.map((e) => e.dataset.view)); + check('the ways back in read as auth buttons', (await page.$$eval('.ways-back-add', (l) => l.map((e) => e.textContent.trim()))).join('|') === 'Passkey auth|Google auth|Nostr auth|Pen and paper', (await page.$$eval('.ways-back-add', (l) => l.map((e) => e.textContent.trim()))).join('|')); + check('one balance row, nothing to add', views.join() === 'all' && !(await page.$('#add-savings')), views.join()); + if (process.env.SHOT2) { await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); await page.evaluate(() => document.querySelector('.balance-settings-row').closest('.card').scrollIntoView()); await sleep(300); await page.screenshot({ path: process.env.SHOT2 }); await page.evaluate(() => document.documentElement.removeAttribute('data-theme')); } + if (process.env.SHOT) { await page.evaluate(() => document.querySelector('.ways-back').scrollIntoView()); await page.screenshot({ path: process.env.SHOT }); } + // a passkey: the relays are stubbed, so the publish fails offline — the + // error says so and nothing is listed + await page.evaluate(() => document.querySelector('.ways-back-add[data-way="passkey"]')?.click()); + await sleep(4000); + const pk = await page.evaluate(() => ({ rows: [...document.querySelectorAll('.ways-back-row')].map((e) => e.dataset.way), err: document.querySelector('.ways-back .notice.err')?.textContent || '' })); + check('adding a passkey lists it', pk.rows.includes('passkey') && !pk.err, JSON.stringify(pk)); + const backups = await page.evaluate(() => (window.__relayGuard.events || []).filter((e) => e.kind === 30078 && e.tags.some((t) => t[0] === 'd' && t[1] === 'coinos:wallet:v1'))); + // the list and the reminder, as the app sees them (record a method directly) + check('the phrase card waits behind Pen and paper', !(await page.$('.recovery-card'))); + await page.evaluate(() => document.querySelector('.ways-back-add[data-way="phrase"]')?.click()); + await sleep(500); + check('Pen and paper opens the recovery phrase card', !!(await page.$('.recovery-card .words'))); + + await page.evaluate(() => document.getElementById('separate-balances')?.click()); await sleep(800); + const views2 = await page.$$eval('.balance-settings-row[data-view]', (l) => l.map((e) => e.dataset.view)); + check('Show separately lists Spending and Savings', views2.join() === 'spending,savings', views2.join()); + await page.goBack(); await page.goBack(); await sleep(800); + s = await shape(); + check('...and the wallet has both faces', s.carousel && s.faces === 2, JSON.stringify({ faces: s.faces, carousel: s.carousel })); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.balance-face', { timeout: 20000 }); await sleep(1500); + s = await shape(); + check('a reload keeps them apart', s.carousel && s.faces === 2); + await openWalletPage(); + await page.evaluate(() => document.getElementById('separate-balances')?.click()); await sleep(800); + await page.goBack(); await page.goBack(); await sleep(800); + s = await shape(); + check('unticked, one balance again', !s.carousel && s.faces === 1 && !!(await page.$('.balance-one'))); + + // A new device: everything here wiped, the relays holding only what the + // passkey published. Sign in → Passkey opens THIS account, as itself. + const before = await page.evaluate(() => { + const st = JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}'); + const a = (st.accounts || [])[0] || {}; + return { mnemonic: a.mnemonic, nostrPk: a.nostrPk }; + }); + before.backups = backups; + check('the passkey published one encrypted seed copy', before.backups.length >= 1 && !before.backups[0].content.includes(before.mnemonic.split(' ')[0] + ' '), String(before.backups.length)); + const backup = before.backups[before.backups.length - 1]; + await page.evaluateOnNewDocument((ev) => { + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (d) { + try { + const m = JSON.parse(d); + if (m[0] === 'REQ' && m.slice(2).some((f) => (f.kinds || []).includes(30078) && (f.authors || []).includes(ev.pubkey))) { + const ws = this; + setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], ev]) })), 1); + } + } catch {} + return send.call(this, d); + }; + }, backup); + await page.evaluate(async () => { + localStorage.clear(); sessionStorage.clear(); + for (const d of (await indexedDB.databases?.() || [])) if (d.name) indexedDB.deleteDatabase(d.name); + localStorage.setItem('btc-wallet-network', 'mainnet'); + }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#onb-signin', { timeout: 15000 }); + await page.click('#onb-signin'); await sleep(500); + await click('passkey'); + for (let i = 0; i < 120 && !(await page.$('.balance-face')); i++) await sleep(250); + if (!(await page.$('.balance-face'))) console.log((await text()).slice(0, 800), errs); + const after = await page.evaluate(() => { + const st = JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}'); + const a = (st.accounts || [])[0] || {}; + const login = Object.keys(localStorage).concat([]).filter((k) => /:nostrlogin$/.test(k)).map((k) => localStorage.getItem(k)); + return { mnemonic: a.mnemonic, nostrPk: a.nostrPk, kind: a.kind, login, onb: localStorage.getItem('btc-wallet-onb-step') }; + }); + check('the passkey opened the same account', after.mnemonic === before.mnemonic); + check('as itself: same identity, the passkey key not adopted', after.nostrPk === before.nostrPk && !after.login.some((v) => v && v.includes(backup.pubkey)), JSON.stringify({ was: before.nostrPk?.slice(0, 8), now: after.nostrPk?.slice(0, 8) })); + check('no wizard on the way back in', !after.onb && !(await page.$('.onb'))); + check('no page errors', errs.length === 0, errs.join(' | ')); +} finally { + await browser.close(); server.stop(true); +} +console.log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/unified-balance-test.js b/tools/unified-balance-test.js new file mode 100644 index 0000000..c349368 --- /dev/null +++ b/tools/unified-balance-test.js @@ -0,0 +1,127 @@ +// 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"). The Ark feature's side of it, without a browser: +// - the combined timeline tells a move between the two halves once: a board +// (its on-chain Sent + its Boarded) and an offboard to our own address +// (its Moved to Savings + the on-chain Received) are one row each, worth +// what the move cost; a board still confirming is one pending row; an +// offboard to someone else stays a payment +// - the separate Spending timeline is untouched +// - an on-chain address is paid from on-chain coins when there are any, and +// leaves Ark (offboard) only when there aren't +// Run: bun tools/unified-balance-test.js +import { buildFeatures } from '../src/features/index.js'; +import { getArkConfig } from '../src/api.js'; + +let fails = 0; +const check = (name, ok, detail = '') => { + console.log(` ${ok ? '✓' : '✗'} ${name}${detail ? ' — ' + String(detail).slice(0, 240) : ''}`); + if (!ok) fails++; +}; + +globalThis.fetch = async () => { throw new Error('offline (test)'); }; +globalThis.window = undefined; +globalThis.localStorage = { + _d: {}, getItem(k) { return this._d[k] ?? null; }, setItem(k, v) { this._d[k] = String(v); }, + removeItem(k) { delete this._d[k]; }, key(i) { return Object.keys(this._d)[i] ?? null; }, + get length() { return Object.keys(this._d).length; }, +}; +const cfg = getArkConfig(); +localStorage.setItem('btc-wallet-arkinfo:' + cfg.ark, JSON.stringify({ info: { minBoardAmountSat: 1000, boardFees: {} }, tip: 1, at: Date.now() })); + +const T = Date.now() - 3600_000; +const A = 'a'.repeat(64), B = 'b'.repeat(64), C = 'c'.repeat(64), D = 'd'.repeat(64), E = 'e'.repeat(64); +const arkState = { + _rev: 1, + vtxos: [{ id: 'v1', amountSat: 20000, state: 'spendable' }], + movements: [ + { id: 'm-board', type: 'board', amountSat: 9000, status: 'complete', txid: A, ts: T }, + { id: 'm-off', type: 'offboard', amountSat: 5000, feeSat: 300, status: 'complete', txid: B, to: 'bc1qown', ts: T + 1000 }, + { id: 'm-off-ext', type: 'offboard', amountSat: 7000, feeSat: 300, status: 'complete', txid: D, to: 'bc1qsomeoneelse', ts: T + 2000 }, + { id: 'm-recv', type: 'receive', amountSat: 1234, status: 'complete', vtxoId: 'v1', ts: T + 3000 }, + ], + actions: [ + { id: `board-${T + 4000}`, type: 'board', step: 'funded', amountSat: 3000, feeSat: 0, fundingTxid: C }, + ], +}; +// the on-chain wallet's view: board fundings out, the own offboard in +const txs = [ + { txid: A, net: -9200, confirmed: true, blockTime: T / 1000 }, + { txid: B, net: 5000, confirmed: true, blockTime: (T + 1000) / 1000 }, + { txid: C, net: -3150, confirmed: false }, + { txid: E, net: 40000, confirmed: true, blockTime: (T + 5000) / 1000 }, +]; + +const store = {}; +const wallet = { + watchOnly: false, offline: false, spendable: 0, feeRates: { halfHourFee: 1 }, + utxos: [], txs, history: txs, receive: [], change: [], + account: () => ({}), + isOnchainAddress: (a) => /^bc1q/.test(a), + loadFeatureState: (n, fb) => JSON.parse(store[n] || 'null') || fb, + saveFeatureState: (n, st) => { store[n] = JSON.stringify(st); }, + _cacheKey: () => 'test', saveCache: () => {}, + nostrPubkey: () => 'ab'.repeat(32), + registerCacheExtension: () => {}, registerRealtimeHook: () => {}, registerLoadHook: () => {}, + registerScanHook: () => {}, registerCacheSavedHook: () => {}, registerCoinLock: () => {}, + loadArkState: () => arkState, peekArkState: () => arkState, saveArkState: () => {}, + _arkNs: () => 'ns', _arkKey: () => 'k', _arkHoldKey: () => 'h', _arkVtxoOwner: () => null, adoptArkState: () => null, + freshReceive: () => ({ address: 'bc1qtest' }), freshChange: () => ({ address: 'bc1qchange' }), + balance: () => ({ spendableSat: 0 }), emit: () => {}, on: () => {}, +}; +let unified = true; +const ui = { account: 'spending', send: { recipients: [{ address: '' }] } }; +let features = []; +const ctx = { + h: (tag, attrs, ...kids) => ({ tag, attrs: attrs || {}, kids: kids.flat().filter((k) => k != null && k !== false) }), + ui, render: () => {}, wallet, + hook: (name, ...args) => { for (const f of features) if (f[name]) { const v = f[name](...args); if (v) return v; } return null; }, + getAccount: () => ui.account, setAccount: (a) => { ui.account = a; }, unifiedBalance: () => unified, + goHome: () => {}, openMnemonic: async () => {}, + fmtAmount: (n) => Number(n).toLocaleString('en-US'), unitLabel: () => 'sats', unitTag: () => 'sats', getUnit: () => 'sats', + parseAmount: (v) => parseInt(v, 10) || 0, amountField: (n) => String(n), + copyBtn: () => null, pasteBtn: () => null, toast: () => {}, blankSend: () => ({ recipients: [{ address: '' }] }), + openExternal: () => {}, +}; +features = buildFeatures(ctx); +const ark = features.find((f) => f.id === 'ark'); +const text = (n) => typeof n === 'string' || typeof n === 'number' ? String(n) : n && n.kids ? n.kids.map(text).join(' ') : ''; + +console.log('[one timeline]'); +{ + const rows = ark.historyEntries(txs, 'all'); + const replaced = rows.map((e) => e.replacesTxid).filter(Boolean).sort(); + check('the board, the own offboard and the confirming board stand in for their on-chain rows', replaced.join() === [A, B, C].sort().join(), replaced.map((x) => x[0]).join()); + check('the offboard to someone else is not a move', !replaced.includes(D)); + const byTx = Object.fromEntries(rows.filter((e) => e.replacesTxid).map((e) => [e.replacesTxid, text(e.render())])); + check('the board reads Made instant, worth its cost (9,200 out, 9,000 in)', /Made instant/.test(byTx[A]) && /\b200\b/.test(byTx[A]) && /9,000/.test(byTx[A]), byTx[A]); + check('the own offboard reads Moved on-chain, worth its fee', /Moved on-chain/.test(byTx[B]) && /\b300\b/.test(byTx[B]), byTx[B]); + check('the confirming board is one pending row', /Making instant/.test(byTx[C]) && /Pending/.test(byTx[C]) && /\b150\b/.test(byTx[C]), byTx[C]); + const others = rows.filter((e) => !e.replacesTxid).map((e) => text(e.render())).join(' | '); + check('the other Ark rows are as they were', /Received/.test(others) && !/Boarded/.test(others), others); + check('the offboard to someone else reads Sent, not Moved to Savings', /Sent/.test(others) && !/Savings/.test(others), others); +} + +console.log('[the Spending timeline, shown apart]'); +{ + const rows = ark.historyEntries([], 'spending'); + check('no row stands in for an on-chain one', rows.every((e) => !e.replacesTxid), rows.length); + check('the board is still its own Boarded row', rows.some((e) => /Boarded/.test(text(e.render())))); + check('Savings gets no Ark rows', ark.historyEntries(txs, 'savings').length === 0); +} + +console.log('[paying an on-chain address]'); +{ + ui.arkOffboardSend = null; wallet.spendable = 50000; + ark.matchSendText('bc1qrecipient'); + check('with on-chain coins it is an ordinary on-chain send', !ui.arkOffboardSend); + ui.arkOffboardSend = null; wallet.spendable = 0; + ark.matchSendText('bc1qrecipient'); + check('without them it leaves Ark', !!ui.arkOffboardSend && ui.arkOffboardSend.address === 'bc1qrecipient'); + ui.arkOffboardSend = null; wallet.spendable = 50000; unified = false; + ark.matchSendText('bc1qrecipient'); + check('shown apart, Spending still pays it from Ark (as before)', !!ui.arkOffboardSend); +} + +console.log(fails ? `FAIL (${fails})` : 'PASS'); +process.exit(fails ? 1 : 0); |
