Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/features/friends/InboxBoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { strings } from '@/strings'

import { notifyFriendOnline } from './friendOnlineNotify'
import { subscribeToOwnInbox, type ValidInvite } from './inbox'
import { usePendingInvitesStore } from './pendingInvitesStore'
import { inviteRetryManager } from './invite'
import { isOnline, startPresence, type PresenceMap } from './presence'

Expand Down Expand Up @@ -197,6 +198,10 @@ async function handleValidInvite(
strings.friends.inbox.senderFallback
const message = strings.friends.inbox.inviteBody(senderName)

// #47 B1 — hold the invite on the persistent main-view surface for its
// full 5-minute validity; the toast below is just the immediate nudge.
usePendingInvitesStore.getState().add(invite)

toast(message, {
action: {
label: strings.friends.inbox.acceptAction,
Expand Down
132 changes: 132 additions & 0 deletions src/features/friends/PendingInvites.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { useEffect, useState } from 'react'
import { MailIcon } from 'lucide-react'

import { Button } from '@/components/ui/button'
import { tokens } from '@/design/tokens'
import { strings } from '@/strings'

import type { ValidInvite } from './inbox'
import {
usePendingInvitesStore,
type PendingInviteEntry,
} from './pendingInvitesStore'

// #47 B1 — the persistent accept surface for incoming invites. The sonner
// toast (InboxBoot) stays as the immediate affordance; these rows survive on
// the main view until the envelope's expires_at passes, so a recipient who
// was tabbed away for a minute still sees and can accept the invite.

export type PendingInvitesViewProps = {
entries: ReadonlyArray<PendingInviteEntry>
now: number
onAccept: (entry: PendingInviteEntry) => void
onDismiss: (entry: PendingInviteEntry) => void
}

function senderName(invite: ValidInvite): string {
return (
invite.payload.our_display_name?.trim() ||
strings.friends.inbox.senderFallback
)
}

export function PendingInvitesView({
entries,
now,
onAccept,
onDismiss,
}: PendingInvitesViewProps) {
if (entries.length === 0) return null
return (
<section
aria-label={strings.friends.inbox.pending.listAriaLabel}
className="mx-auto w-full px-4 pt-4 sm:px-6"
style={{ maxWidth: tokens.sizes.readingMaxWidth }}
>
<ul className="flex flex-col gap-2">
{entries.map((entry) => {
const name = senderName(entry.invite)
const minutesLeft = Math.max(
1,
Math.ceil((entry.invite.payload.expires_at - now) / 60_000)
)
return (
<li
key={entry.key}
className="flex items-center justify-between gap-3 rounded-lg border border-border-subtle bg-bg-surface px-4 py-3"
>
<span className="flex min-w-0 items-center gap-3">
<MailIcon
className="size-4 shrink-0 text-accent-default"
aria-hidden="true"
/>
<span className="flex min-w-0 flex-col">
<span className="truncate text-sm text-text-primary">
{strings.friends.inbox.inviteBody(name)}
</span>
<span className="text-xs text-text-muted">
{strings.friends.inbox.pending.expiresIn(minutesLeft)}
</span>
</span>
</span>
<span className="flex shrink-0 items-center gap-2">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => onDismiss(entry)}
aria-label={strings.friends.inbox.pending.dismissAriaLabel(
name
)}
>
{strings.friends.inbox.pending.dismissCta}
</Button>
<Button
type="button"
variant="default"
size="sm"
onClick={() => onAccept(entry)}
aria-label={strings.friends.inbox.pending.acceptAriaLabel(
name
)}
>
{strings.friends.inbox.acceptAction}
</Button>
</span>
</li>
)
})}
</ul>
</section>
)
}

export type PendingInvitesProps = {
onAccept: (invite: ValidInvite) => void
}

export function PendingInvites({ onAccept }: PendingInvitesProps) {
const pending = usePendingInvitesStore((s) => s.pending)
const [now, setNow] = useState(() => Date.now())

// Refresh the countdown + drop expired rows on a slow tick, only while
// anything is pending. Acceptance-time expiry is separately re-checked in
// Home's runGuestJoin, so a stale row can never join a dead session.
useEffect(() => {
if (pending.length === 0) return
const id = setInterval(() => {
setNow(Date.now())
usePendingInvitesStore.getState().prune()
}, 10_000)
return () => clearInterval(id)
}, [pending.length])

return (
<PendingInvitesView
entries={pending}
now={now}
onAccept={(entry) => onAccept(entry.invite)}
onDismiss={(entry) => usePendingInvitesStore.getState().remove(entry.key)}
/>
)
}
Comment on lines +108 to +132

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Stale now causes incorrect countdown on first invite arrival.

now is initialized once via useState(() => Date.now()) and only updated by the 10-second interval — which doesn't start until pending.length > 0. If the component has been mounted on the main view for minutes without invites, the first invite's countdown will be based on the stale initial now, showing a much higher "Expires in N min" than reality for up to 10 seconds until the first interval tick fires.

The actual expiry behavior is unaffected (prune and runGuestJoin both use Date.now()), so this is display-only.

Fix: refresh `now` when the interval starts
   useEffect(() => {
     if (pending.length === 0) return
+    setNow(Date.now())
     const id = setInterval(() => {
       setNow(Date.now())
       usePendingInvitesStore.getState().prune()
     }, 10_000)
     return () => clearInterval(id)
   }, [pending.length])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function PendingInvites({ onAccept }: PendingInvitesProps) {
const pending = usePendingInvitesStore((s) => s.pending)
const [now, setNow] = useState(() => Date.now())
// Refresh the countdown + drop expired rows on a slow tick, only while
// anything is pending. Acceptance-time expiry is separately re-checked in
// Home's runGuestJoin, so a stale row can never join a dead session.
useEffect(() => {
if (pending.length === 0) return
const id = setInterval(() => {
setNow(Date.now())
usePendingInvitesStore.getState().prune()
}, 10_000)
return () => clearInterval(id)
}, [pending.length])
return (
<PendingInvitesView
entries={pending}
now={now}
onAccept={(entry) => onAccept(entry.invite)}
onDismiss={(entry) => usePendingInvitesStore.getState().remove(entry.key)}
/>
)
}
export function PendingInvites({ onAccept }: PendingInvitesProps) {
const pending = usePendingInvitesStore((s) => s.pending)
const [now, setNow] = useState(() => Date.now())
// Refresh the countdown + drop expired rows on a slow tick, only while
// anything is pending. Acceptance-time expiry is separately re-checked in
// Home's runGuestJoin, so a stale row can never join a dead session.
useEffect(() => {
if (pending.length === 0) return
setNow(Date.now())
const id = setInterval(() => {
setNow(Date.now())
usePendingInvitesStore.getState().prune()
}, 10_000)
return () => clearInterval(id)
}, [pending.length])
return (
<PendingInvitesView
entries={pending}
now={now}
onAccept={(entry) => onAccept(entry.invite)}
onDismiss={(entry) => usePendingInvitesStore.getState().remove(entry.key)}
/>
)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/features/friends/PendingInvites.tsx` around lines 108 - 132, Refresh the
countdown timestamp immediately when pending invites first appear. Update the
useEffect in PendingInvites to call setNow(Date.now()) before starting the
interval, while preserving the existing periodic refresh and cleanup behavior.

11 changes: 11 additions & 0 deletions src/features/friends/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ export {
export { FriendsList, type FriendsListProps } from './FriendsList'
export { FriendsListView, type FriendsListViewProps } from './FriendsListView'
export { InboxBoot, type InboxBootProps } from './InboxBoot'
export {
PendingInvites,
PendingInvitesView,
type PendingInvitesProps,
type PendingInvitesViewProps,
} from './PendingInvites'
export {
pendingInviteKey,
usePendingInvitesStore,
type PendingInviteEntry,
} from './pendingInvitesStore'
export {
PairDeepLinkBoot,
type PairDeepLinkBootProps,
Expand Down
58 changes: 58 additions & 0 deletions src/features/friends/pendingInvitesStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { create } from 'zustand'

import type { ValidInvite } from './inbox'

// #47 B1 — a persistent home for incoming invites. Envelopes are valid for
// INVITE_TTL_MS (5 min) but the only accept affordance was a ~4s sonner
// toast; a recipient who was tabbed away missed it and the invite was
// unrecoverable on their side while the host saw "Invite sent". Each valid
// invite is held here until it expires, is dismissed, or is accepted;
// PendingInvites renders the list as rows on the main view. Lives in
// features/friends (the alertsUiStore precedent), not src/stores — stores/
// modules must not import feature types.

export type PendingInviteEntry = {
key: string
invite: ValidInvite
receivedAt: number
}

// One row per sender+session: a re-sent invite for the same session (the F6
// retry path) replaces the earlier entry instead of stacking duplicates.
export function pendingInviteKey(invite: ValidInvite): string {
return `${invite.from_ed_pubkey}:${invite.payload.session_topic}`
}

type PendingInvitesState = {
pending: PendingInviteEntry[]
add: (invite: ValidInvite, now?: number) => void
remove: (key: string) => void
// Drop entries whose expires_at has passed. Called on a slow interval by
// the banner while anything is pending.
prune: (now?: number) => void
clear: () => void
}

export const usePendingInvitesStore = create<PendingInvitesState>((set) => ({
pending: [],
add: (invite, now = Date.now()) =>
set((s) => {
const key = pendingInviteKey(invite)
const kept = s.pending.filter(
(e) => e.key !== key && e.invite.payload.expires_at > now
)
return { pending: [...kept, { key, invite, receivedAt: now }] }
}),
remove: (key) =>
set((s) =>
s.pending.some((e) => e.key === key)
? { pending: s.pending.filter((e) => e.key !== key) }
: s
),
prune: (now = Date.now()) =>
set((s) => {
const kept = s.pending.filter((e) => e.invite.payload.expires_at > now)
return kept.length === s.pending.length ? s : { pending: kept }
}),
clear: () => set({ pending: [] }),
}))
19 changes: 18 additions & 1 deletion src/routes/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ import {
InviteRelayError,
InviteTimeoutError,
PairDeepLinkBoot,
PendingInvites,
pendingInviteKey,
usePendingInvitesStore,
type ContactImportSource,
type PresenceMap,
} from '@/features/friends'
Expand Down Expand Up @@ -137,11 +140,21 @@ export function Home() {
const runGuestJoin = useCallback((invite: ValidInvite) => {
// Joining while already in a session would tear down the existing one;
// refuse — the user explicitly leaves first. (Moved here from InboxBoot
// so the gate + guard share one decision point.)
// so the gate + guard share one decision point.) The invite stays on the
// #47 B1 pending surface for after they leave.
if (useSessionStore.getState().status === 'active') {
toast.error(strings.errors.leaveSessionFirst)
return
}
// #47 B1 — re-check expiry at accept time: the toast/banner row may be
// minutes old, and joining a dead session would strand the user on a
// waiting tile.
if (invite.payload.expires_at <= Date.now()) {
usePendingInvitesStore.getState().remove(pendingInviteKey(invite))
toast.error(strings.friends.inbox.pending.expired)
return
}
usePendingInvitesStore.getState().remove(pendingInviteKey(invite))
try {
joinSession(invite.payload.session_topic, invite.payload.session_password)
} catch (err) {
Expand Down Expand Up @@ -369,6 +382,10 @@ export function Home() {
<Settings2Icon /> {strings.settings.heading}
</Button>
</div>
{/* #47 B1 — pending incoming invites persist here for their full
5-minute validity; accepting funnels through the same topic-gated
path as the toast. */}
<PendingInvites onAccept={handleInviteAccepted} />
<FriendsList
presence={presence}
onAddFriend={() => setAddOpen(true)}
Expand Down
59 changes: 59 additions & 0 deletions src/stories/PendingInvites.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Meta, StoryObj } from '@storybook/react-vite'

import { PendingInvitesView } from '@/features/friends'
import type { PendingInviteEntry } from '@/features/friends'

// #47 B1 — persistent pending-invite rows on the main view (pure view;
// store + expiry wiring live in the PendingInvites container).

const NOW = 1_700_000_000_000

function entry(
seed: string,
name: string | null,
msLeft: number
): PendingInviteEntry {
return {
key: `${seed}:topic-${seed}`,
receivedAt: NOW - 30_000,
invite: {
from_ed_pubkey: seed.repeat(64).slice(0, 64),
payload: {
session_topic: `topic-${seed}`,
session_password: 'pw',
our_display_name: name ?? '',
expires_at: NOW + msLeft,
sig: '',
},
},
}
}

const meta = {
title: 'Friends/PendingInvites',
component: PendingInvitesView,
args: {
now: NOW,
onAccept: () => {},
onDismiss: () => {},
entries: [entry('a', 'Alex', 4 * 60_000), entry('b', null, 90_000)],
},
} satisfies Meta<typeof PendingInvitesView>

export default meta
type Story = StoryObj<typeof meta>

// Two pending invites: a named sender with minutes left and a fallback-named
// sender about to expire.
export const TwoPending: Story = {}

export const SingleInvite: Story = {
args: {
entries: [entry('a', 'Alex', 3 * 60_000)],
},
}

// Renders nothing — the section only exists while invites are pending.
export const Empty: Story = {
args: { entries: [] },
}
10 changes: 10 additions & 0 deletions src/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,16 @@ export const strings = {
senderFallback: 'A friend',
inviteBody: (name: string) => `${name} invites you to study`,
acceptAction: 'Accept',
// #47 B1 — persistent pending-invite rows on the main view (invites
// are valid 5 minutes; the toast alone was missable).
pending: {
listAriaLabel: 'Pending invites',
expiresIn: (min: number) => `Expires in ${min} min`,
dismissCta: 'Dismiss',
dismissAriaLabel: (name: string) => `Dismiss the invite from ${name}`,
acceptAriaLabel: (name: string) => `Accept the invite from ${name}`,
expired: 'That invite expired. Ask your friend to invite you again.',
},
},
inviteSent: (name: string) => `Invite sent to ${name}.`,
inviteSendErrorFallback: "Couldn't send the invite.",
Expand Down
Loading
Loading