Show live progress during the nostrconnect login handshake

When a user tapped "Open signer app", the dialog previously stayed
frozen on the same screen — same button, same copy-URI fallback, no
feedback — until the login either succeeded (and the dialog dismissed)
or timed out after two minutes. With slow or flaky signers (Amber's
current listening-REQ bug being the immediate trigger, but any NIP-46
signer that takes more than a second or two to respond hits the same
hole) this looked indistinguishable from a hang. Users retapped the
button, closed the dialog, gave up.

Now the dialog swaps the QR / Open signer app area for a centered
spinner with a live status line as the handshake advances:

- "Waiting for signer connection…" while the signer app has the user
  and we're listening on kind 24133 for the connect-ack.
- "Getting public key…" once the connect-ack arrives and we're
  issuing the NIP-46 get_public_key RPC.

On mobile the swap happens synchronously when the user taps "Open
signer app" so they see the progress state the moment they return
from the signer. On desktop the QR stays visible through the
awaiting-connect phase (they may still be scanning with a different
device) and only swaps in once the signer has acknowledged.

The progress view includes a Cancel link that aborts the in-flight
subscription and regenerates fresh connect params.

Also fix a related effect-lifecycle bug: the listening effect
previously depended on `onClose` and `isWaitingForConnect`. Since
parents pass inline arrow functions for onClose, the effect re-ran
on every parent render and its cleanup flipped a local `cancelled`
flag — if the signer's response arrived on a re-rendered instance,
the success branch silently swallowed the login. The effect now
depends only on `nostrConnectParams` with stable refs for
onClose/login, gates the success branch on `controller.signal.aborted`
instead of a teardown flag, and handles cancellation explicitly in
the dialog-close and retry paths.

The handshake phases are surfaced via the new `onStatus` callback on
`NLogin.fromNostrConnect` in @nostrify/react 0.6.0. Bumps
@nostrify/react to ^0.6.0.

Also switches the fallback relay used for NIP-46 communication from
wss://relay.damus.io to wss://relay.ditto.pub. Only applies when the
user has no writable relays in their metadata.

Incidental cleanup while editing the dialog: the Copy URI button and
the "Open your signer app to connect." / "Scan with your signer app."
caption lines are removed. The primary Open signer app button is
self-explanatory on mobile, and the QR on desktop doesn't need a
caption.
This commit is contained in:
Alex Gleason committed 2026-05-04 21:51:06 -05:00
1 parent 551928849a
commit e289c67a70
4 files changed
+127 -65

No files matched your search

+4 -4
View File
@@ -9,7 +9,7 @@
"version": "0.0.0",
"dependencies": {
"@nostrify/nostrify": "^0.52.0",
"@nostrify/react": "^0.5.2",
"@nostrify/react": "^0.6.0",
"@radix-ui/react-toast": "^1.2.1",
"@tanstack/react-query": "^5.100.5",
"@unhead/react": "^3.1.0",
@@ -1034,9 +1034,9 @@
}
},
"node_modules/@nostrify/react": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.5.2.tgz",
"integrity": "sha512-9Djb+lHM+ius/Eu8eaC6B2VCRwtfd/qxP0bq8VE+Y+4/wuXMTw2PQ+/c4blQh6szuKwB822mkqsQhv5adT5Ofg==",
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.6.0.tgz",
"integrity": "sha512-6vjF5UagAW5QRpxAu/of9lyI7837wwoyX/NLGQbEs6fcMQXjTo/m7wUBPipoj0E460QvyNXff5O8Byn72enWbQ==",
"dependencies": {
"@nostrify/nostrify": "0.52.0",
"@nostrify/types": "0.37.0"
+1 -1
View File
@@ -10,7 +10,7 @@
},
"dependencies": {
"@nostrify/nostrify": "^0.52.0",
"@nostrify/react": "^0.5.2",
"@nostrify/react": "^0.6.0",
"@radix-ui/react-toast": "^1.2.1",
"@tanstack/react-query": "^5.100.5",
"@unhead/react": "^3.1.0",
+104 -54
View File
@@ -5,8 +5,6 @@ import {
Eye,
EyeOff,
Key,
Copy,
Check,
ChevronDown,
ChevronUp,
Loader2,
@@ -29,6 +27,7 @@ import {
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
type NostrConnectStatus,
} from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
@@ -45,6 +44,17 @@ type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login' | 'connect';
const validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
const validateBunkerUri = (uri: string) => uri.startsWith('bunker://');
const connectStatusLabel = (status: NostrConnectStatus | null): string => {
switch (status) {
case 'awaiting-connect':
return 'Waiting for signer connection…';
case 'getting-public-key':
return 'Getting public key…';
default:
return '';
}
};
/** Check if running on an actual mobile device (not just a small screen). */
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
@@ -89,18 +99,36 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
// Nostrconnect / bunker state
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState('');
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
const [connectError, setConnectError] = useState<string | null>(null);
const [uriCopied, setUriCopied] = useState(false);
// Progress status for the nostrconnect handshake. `null` means the user
// hasn't kicked off the handshake yet (or they canceled) — we show the QR
// / "Open signer app" button. Once the handshake advances we swap in a
// spinner with a live status line so the user knows something is working.
const [connectStatus, setConnectStatus] = useState<NostrConnectStatus | null>(null);
// Tracks whether the user has explicitly initiated the handshake from the
// mobile UI. The listen subscription itself starts the moment params are
// generated — without this flag we'd flip into the progress view as soon
// as the user enters the Remote Signer step, before they've done anything.
// Desktop doesn't need this: it stays on the QR until the handshake
// advances past `awaiting-connect`.
const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [bunkerUri, setBunkerUri] = useState('');
const login = useLoginActions();
// Stable ref so the nostrconnect effect doesn't restart on every render.
// Stable refs so the nostrconnect listening effect below doesn't restart on
// every parent render. Parents typically pass inline arrow functions for
// onClose, and useLoginActions returns a fresh object each render — without
// stable refs, an effect depending on them would tear down the in-flight
// subscription on every render and cause approved logins to be swallowed.
const loginRef = useRef(login);
const onCloseRef = useRef(onClose);
useEffect(() => {
loginRef.current = login;
}, [login]);
useEffect(() => {
onCloseRef.current = onClose;
}, [onClose]);
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
@@ -130,9 +158,9 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
setProfileData({ name: '', about: '', picture: '' });
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setUriCopied(false);
setConnectStatus(null);
setHasOpenedSigner(false);
setShowBunkerInput(false);
setBunkerUri('');
/* eslint-enable react-hooks/set-state-in-effect */
@@ -154,57 +182,72 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
}, [login]);
// Start listening for a nostrconnect response once params are set.
//
// Deps are intentionally limited to `nostrConnectParams` so that parent
// re-renders (which produce fresh onClose closures and a fresh `login`
// object from useLoginActions) do NOT tear down an in-flight
// subscription. An earlier version used a `cancelled` flag flipped by
// the effect's cleanup, which caused a successful nostrconnect response
// to be silently swallowed after the signer approved — the subscription
// was re-created mid-handshake and the first instance's success branch
// saw `cancelled === true`.
//
// Cancellation is handled explicitly by the `isOpen` effect (on dialog
// close) and by handleConnectRetry() (on user cancel/retry).
useEffect(() => {
if (!nostrConnectParams || isWaitingForConnect) return;
let cancelled = false;
if (!nostrConnectParams) return;
const startListening = async () => {
setIsWaitingForConnect(true);
abortControllerRef.current = new AbortController();
const controller = new AbortController();
abortControllerRef.current = controller;
try {
await loginRef.current.nostrconnect(
nostrConnectParams,
abortControllerRef.current.signal,
controller.signal,
(status) => {
if (controller.signal.aborted) return;
setConnectStatus(status);
},
);
if (!cancelled) onClose();
// If the dialog was explicitly closed (handled by the isOpen
// effect, which aborts the controller), don't try to re-close it.
// Otherwise the user is logged in — close the dialog.
if (controller.signal.aborted) return;
onCloseRef.current();
} catch (error) {
if (cancelled) return;
// AbortError means we intentionally aborted (dialog closed or retry)
if (error instanceof Error && error.name === 'AbortError') return;
if (controller.signal.aborted) return;
console.error('Nostrconnect failed:', error);
setConnectStatus(null);
setConnectError(error instanceof Error ? error.message : String(error));
setIsWaitingForConnect(false);
}
};
startListening();
return () => {
cancelled = true;
};
// NOTE: isWaitingForConnect is intentionally excluded from deps. Including
// it would cancel the first run the moment it sets the flag to true and
// spawn a duplicate listener.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nostrConnectParams, onClose]);
// No cleanup here: we do NOT want a re-render-triggered effect teardown
// to cancel the in-flight subscription.
}, [nostrConnectParams]);
const handleConnectRetry = useCallback(() => {
abortControllerRef.current?.abort();
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setConnectStatus(null);
setHasOpenedSigner(false);
setTimeout(() => generateConnectSession(), 0);
}, [generateConnectSession]);
const handleCopyUri = async () => {
await navigator.clipboard.writeText(nostrConnectUri);
setUriCopied(true);
setTimeout(() => setUriCopied(false), 2000);
};
const handleOpenSignerApp = () => {
if (!nostrConnectUri) return;
// Flip into the progress view *synchronously* before navigating so that
// when the user returns from the signer app, the dialog is already
// showing "Waiting for signer connection…" — not the original button
// they're worried they need to re-tap.
setHasOpenedSigner(true);
window.location.href = nostrConnectUri;
};
@@ -368,6 +411,18 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
}
};
// Decide whether to render the progress view in place of the QR/button.
// Mobile: flip in as soon as the user taps "Open signer app" (tracked by
// `hasOpenedSigner`) so they see feedback the moment they return from the
// signer. Desktop: keep the QR visible through the `awaiting-connect`
// phase (it's still actionable — they might scan with another device) and
// only swap in once the signer has acknowledged and we're fetching the
// pubkey.
const showProgressView = connectStatus !== null && (
connectStatus === 'getting-public-key' ||
(isMobile && hasOpenedSigner)
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-0 overflow-hidden rounded-2xl overflow-y-auto">
@@ -666,10 +721,6 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
{/* Connect step — nostrconnect QR + bunker URI fallback. */}
{step === 'connect' && (
<div className="space-y-4">
<p className="text-sm text-muted-foreground text-center">
{isMobile ? 'Open your signer app to connect.' : 'Scan with your signer app.'}
</p>
<div className="flex flex-col items-center space-y-4">
{connectError ? (
<div className="flex flex-col items-center space-y-3 py-4">
@@ -678,6 +729,24 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
Try again
</Button>
</div>
) : showProgressView ? (
// Progress view — replaces the QR/button once the handshake
// is under way. Gives the user live feedback through each
// phase so a stuck signer is visibly stuck, not silently
// stuck.
<div className="flex flex-col items-center space-y-4 py-6 w-full">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground text-center min-h-[1.25rem]">
{connectStatusLabel(connectStatus)}
</p>
<button
type="button"
onClick={handleConnectRetry}
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
>
Cancel
</button>
</div>
) : nostrConnectUri ? (
<>
{!isMobile && (
@@ -692,25 +761,6 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
Open signer app
</Button>
)}
<Button
variant="outline"
size={isMobile ? 'default' : 'sm'}
className={isMobile ? 'w-full gap-2' : 'gap-2'}
onClick={handleCopyUri}
>
{uriCopied ? (
<>
<Check className="w-4 h-4" />
Copied
</>
) : (
<>
<Copy className="w-4 h-4" />
Copy URI
</>
)}
</Button>
</>
) : (
<div className="flex items-center justify-center h-[100px]">
+18 -6
View File
@@ -1,10 +1,15 @@
import { useNostr } from '@nostrify/react';
import { NLogin, type NostrConnectParams, useNostrLogin } from '@nostrify/react/login';
import {
NLogin,
type NostrConnectParams,
type NostrConnectStatus,
useNostrLogin,
} from '@nostrify/react/login';
import { useAppContext } from '@/hooks/useAppContext';
// NOTE: This file should not be edited except for adding new login methods.
export type { NostrConnectParams };
export type { NostrConnectParams, NostrConnectStatus };
export { generateNostrConnectParams, generateNostrConnectURI } from '@nostrify/react/login';
export function useLoginActions() {
@@ -29,9 +34,16 @@ export function useLoginActions() {
addLogin(login);
},
// Login via nostrconnect:// (client-initiated NIP-46)
// The client displays a QR code and waits for the remote signer to connect
async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise<void> {
const login = await NLogin.fromNostrConnect(params, nostr, { signal });
// The client displays a QR code and waits for the remote signer to connect.
//
// `onStatus` is forwarded from @nostrify/react so the UI can render
// live progress through the handshake phases — see NostrConnectStatus.
async nostrconnect(
params: NostrConnectParams,
signal?: AbortSignal,
onStatus?: (status: NostrConnectStatus) => void,
): Promise<void> {
const login = await NLogin.fromNostrConnect(params, nostr, { signal, onStatus });
addLogin(login);
},
// Get the relay URLs for NIP-46 nostrconnect communication
@@ -39,7 +51,7 @@ export function useLoginActions() {
const relays = config.relayMetadata.relays
.filter((r) => r.write)
.map((r) => r.url);
return relays.length > 0 ? relays : ['wss://relay.damus.io'];
return relays.length > 0 ? relays : ['wss://relay.ditto.pub'];
},
// Log out the current user
async logout(): Promise<void> {