+
Recent repos
- {feed.loading ?
: null}
+
+ {feed.loading ? : null}
+ {v2 ? (
+
+ Explore more
+
+ ) : null}
+
{!deployed ? (
diff --git a/forge-web/components/app-footer.tsx b/forge-web/components/app-footer.tsx
index 7ee7b1774..b93a3ac24 100644
--- a/forge-web/components/app-footer.tsx
+++ b/forge-web/components/app-footer.tsx
@@ -15,6 +15,9 @@ export function AppFooter(): JSX.Element {
Discover
+
+ Explore
+
New repo
diff --git a/forge-web/components/app-header.tsx b/forge-web/components/app-header.tsx
index ffbd4c902..9a8b45d68 100644
--- a/forge-web/components/app-header.tsx
+++ b/forge-web/components/app-header.tsx
@@ -1,71 +1,66 @@
'use client'
/**
- * App header — the persistent foundry chrome: wordmark, global repo jump, network badge (every
- * network except mainnet), theme toggle, and the auth surface (sign-in trigger, or balance +
- * identity + logout when signed in).
+ * App header (`ux-dx-spec.md` §5.2): wordmark · network badge (every network except mainnet) ·
+ * jump box (`owner/name`, `@name`, `#n` in a repo) · New ▾ (Repository, Mirror a GitHub repo) ·
+ * notifications bell with the unread count · identity pill. Below `sm` the jump box moves to a
+ * second row so the bar fits 360 px.
*/
import Link from 'next/link'
-import { useRouter } from 'next/navigation'
-import { useEffect, useRef, useState } from 'react'
-import { Hammer, LogOut, Search, Wallet } from 'lucide-react'
+import { usePathname, useRouter, useSearchParams } from 'next/navigation'
+import { Suspense, useEffect, useRef, useState, type ReactNode } from 'react'
+import { Bell, ChevronDown, Compass, GitFork, Hammer, LogOut, Plus, Search, Wallet } from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'
import { useUiStore } from '@/hooks/use-ui-store'
+import { useUnreadCount } from '@/hooks/use-inbox'
+import { addressFromParams, repoHref } from '@/hooks/use-query-param'
import { Button } from '@/components/ui/button'
import { IdentityPill } from '@/components/ui/identity-pill'
import { ThemeToggle } from '@/components/theme-toggle'
import { NetworkBadge } from '@/components/ui/network-badge'
-import { creditsToDash } from '@/lib/sdk'
+import { ACTIVE_NETWORK, DEFAULT_NETWORK } from '@/lib/constants'
+import { resolveAnyRepo } from '@/lib/repo'
+import { creditsToDash, ensureSdk } from '@/lib/sdk'
+import { errorMessage } from '@/lib/utils'
+import { numberTargets, parseJump } from '@/lib/view/jump'
import { balanceToDash, dashToUsd } from '@/lib/view/format'
import { FundsPill } from '@/components/funds-pill'
+/** The mirror guide (the `/mirror` wizard does not exist yet). */
+export const MIRROR_GUIDE_URL = 'https://github.com/PastaPastaPasta/dash-forge/blob/master/docs/guides/mirror-a-github-repo.md'
+
export function AppHeader(): JSX.Element {
const openLogin = useUiStore((s) => s.openLogin)
const { identity, balance, logout } = useAuth()
- const router = useRouter()
- const [query, setQuery] = useState('')
-
- const onSearch = (e: React.FormEvent): void => {
- e.preventDefault()
- const q = query.trim()
- if (!q) return
- // Accept "owner/name" jump (owner: identity id or DPNS name); otherwise treat it as an
- // owner profile lookup (`alice`, `@alice`, or an identity id).
- if (q.includes('/')) {
- const [owner, name] = q.split('/')
- router.push(`/repo?owner=${encodeURIComponent(owner ?? '')}&name=${encodeURIComponent(name ?? '')}`)
- } else {
- router.push(`/u?name=${encodeURIComponent(q.replace(/^@/, ''))}`)
- }
- }
return (
-
-
+
+
-
- Dash Forge
-
+
Dash Forge
-
-
-
+
+
+
+
+
+
+
+
+ Explore
+
+
+ {identity ? : null}
{identity ? (
<>
@@ -79,76 +74,279 @@ export function AppHeader(): JSX.Element {
)}
+
+
+
+
+
)
}
-function AccountMenu({
- identity,
- balance,
- onLogout,
-}: {
- identity: string
- balance: string | null
- onLogout: (forget?: boolean) => void
-}): JSX.Element {
+/**
+ * The jump box. `#n` resolves against the repo the page shows (from its query string): issue
+ * first, then PR; both existing opens a choice. `owner/name#n` does the same for that repo.
+ */
+function JumpBox({ compact = false }: { compact?: boolean }): JSX.Element {
+ const router = useRouter()
+ const pathname = usePathname()
+ const params = useSearchParams()
+ const [query, setQuery] = useState('')
+ const [note, setNote] = useState
(null)
+ const [busy, setBusy] = useState(false)
+ // Only the newest #n lookup may act: a slow one must not navigate after the query changed.
+ const request = useRef(0)
+ const here = addressFromParams(params)
+ const inRepo = pathname.startsWith('/repo') && here.owner !== '' && here.name !== ''
+ const id = compact ? 'jump-compact' : 'jump'
+
+ const goNumber = async (addr: typeof here, n: number): Promise => {
+ const mine = ++request.current
+ const current = (): boolean => request.current === mine
+ setBusy(true)
+ setNote(null)
+ try {
+ const sdk = await ensureSdk(DEFAULT_NETWORK)
+ const resolved = await resolveAnyRepo(sdk, { network: DEFAULT_NETWORK, ...addr })
+ if (!current()) return
+ if (resolved === null) {
+ setNote(`No repo ${addr.owner}/${addr.name} here.`)
+ return
+ }
+ const found = await numberTargets(sdk, resolved.repo, n)
+ if (!current()) return
+ const issue = repoHref('/repo/issue', addr, { number: String(n) })
+ const pull = repoHref('/repo/pull', addr, { number: String(n) })
+ if (found.issue && found.pull) {
+ setNote(
+
+ #{n} is both:{' '}
+ setNote(null)}>issue #{n} ·{' '}
+ setNote(null)}>PR #{n}
+ ,
+ )
+ } else if (found.issue || found.pull) {
+ setQuery('')
+ router.push(found.issue ? issue : pull)
+ } else {
+ setNote(`No issue or PR #${n} in ${addr.name}.`)
+ }
+ } catch (e) {
+ if (current()) setNote(errorMessage(e))
+ } finally {
+ if (current()) setBusy(false)
+ }
+ }
+
+ const onSubmit = (e: React.FormEvent): void => {
+ e.preventDefault()
+ const jump = parseJump(query, inRepo)
+ if (jump === null) return
+ switch (jump.kind) {
+ case 'invalid':
+ setNote(jump.message)
+ return
+ case 'number':
+ void goNumber(here, jump.number)
+ return
+ case 'repo':
+ if (jump.number !== undefined) {
+ void goNumber({ owner: jump.owner, name: jump.name }, jump.number)
+ return
+ }
+ setQuery('')
+ setNote(null)
+ router.push(repoHref('/repo', { owner: jump.owner, name: jump.name }))
+ return
+ case 'profile':
+ setQuery('')
+ setNote(null)
+ router.push(`/u?name=${encodeURIComponent(jump.name)}`)
+ }
+ }
+
+ return (
+
+ )
+}
+
+/**
+ * A disclosure popover (button with `aria-expanded` + a panel of plain links): closes on an
+ * outside click, on Escape (focus returns to the trigger), and when focus leaves it (Tab).
+ */
+function usePopover(): { open: boolean; setOpen: (v: boolean) => void; ref: React.RefObject; trigger: React.RefObject } {
const [open, setOpen] = useState(false)
const ref = useRef(null)
-
+ const trigger = useRef(null)
useEffect(() => {
if (!open) return
const onDoc = (e: MouseEvent): void => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
}
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape') {
+ setOpen(false)
+ trigger.current?.focus()
+ }
+ }
+ const onFocus = (e: FocusEvent): void => {
+ if (ref.current && e.target instanceof Node && !ref.current.contains(e.target)) setOpen(false)
+ }
document.addEventListener('mousedown', onDoc)
- return () => document.removeEventListener('mousedown', onDoc)
+ document.addEventListener('keydown', onKey)
+ document.addEventListener('focusin', onFocus)
+ return () => {
+ document.removeEventListener('mousedown', onDoc)
+ document.removeEventListener('keydown', onKey)
+ document.removeEventListener('focusin', onFocus)
+ }
}, [open])
+ return { open, setOpen, ref, trigger }
+}
+const MENU_ITEM = 'flex w-full items-start gap-2 rounded-md px-3 py-2 text-left text-dense hover:bg-anvil-100 focus-visible:bg-anvil-100 dark:hover:bg-anvil-800 dark:focus-visible:bg-anvil-800'
+
+function NewMenu(): JSX.Element | null {
+ const { open, setOpen, ref, trigger } = usePopover()
+ // No "New" on a network without Forge (spec §6.3: no New repo button in that state).
+ if (ACTIVE_NETWORK.v2 === null && ACTIVE_NETWORK.registryContractId === null) return null
+ return (
+
+
setOpen(!open)}
+ aria-expanded={open}
+ aria-controls="new-panel"
+ className="inline-flex h-8 items-center gap-1 rounded-md px-2 text-dense text-anvil-700 hover:bg-anvil-100 dark:text-anvil-200 dark:hover:bg-anvil-800"
+ >
+
+ New
+
+
+ {open ? (
+
+ setOpen(false)}>
+
+
+ Repository
+ Create a repo on {ACTIVE_NETWORK.key}
+
+
+ setOpen(false)}>
+
+
+ Mirror a GitHub repo
+ Guide on GitHub (opens a new tab)
+
+
+
+ ) : null}
+
+ )
+}
+
+function NotificationsBell(): JSX.Element {
+ const unread = useUnreadCount()
+ const label = unread === 0 ? 'Notifications, none unread' : `Notifications, ${unread} unread`
+ return (
+
+
+ {unread > 0 ? (
+
+ {unread > 99 ? '99+' : unread}
+
+ ) : null}
+
+ )
+}
+
+function AccountMenu({
+ identity,
+ balance,
+ onLogout,
+}: {
+ identity: string
+ balance: string | null
+ onLogout: (forget?: boolean) => void
+}): JSX.Element {
+ const { open, setOpen, ref, trigger } = usePopover()
const credits = balance ? Number(balance) : 0
const dash = balanceToDash(balance ?? '0')
return (
setOpen((o) => !o)}
- aria-haspopup="menu"
+ ref={trigger}
+ onClick={() => setOpen(!open)}
aria-expanded={open}
+ aria-controls="account-panel"
+ aria-label="Account menu"
className="flex items-center gap-2 rounded-full py-0.5 pl-0.5 pr-1 hover:bg-anvil-100 dark:hover:bg-anvil-800"
>
-
+
{open ? (
-
+
Balance
{dash} DASH
-
+
{credits.toLocaleString()} credits · ≈ {dashToUsd(creditsToDash(credits))}
-
setOpen(false)}
- >
+
setOpen(false)}>
+ Notifications
+
+
setOpen(false)}>
+ Explore
+
+
setOpen(false)}>
Settings & spend
-
setOpen(false)}
- >
+
setOpen(false)}>
Your profile
{
setOpen(false)
onLogout(false)
diff --git a/forge-web/components/key-top-up-dialog.tsx b/forge-web/components/key-top-up-dialog.tsx
new file mode 100644
index 000000000..d5c686868
--- /dev/null
+++ b/forge-web/components/key-top-up-dialog.tsx
@@ -0,0 +1,314 @@
+'use client'
+
+/**
+ * Top up this browser's key (`ux-dx-spec.md` §2.3; `IdentityKeyLimitsUpdate`, protocol 14):
+ * add budget to the key this browser signs with and, optionally, push its expiry out. The key
+ * id and the private key stay the same. The master key comes from the identity file or the
+ * recovery phrase, signs this one update, and is not stored (the file text lives in a ref, not
+ * React state, and is dropped after use; the caller mounts this only while it is open, so
+ * closing unmounts it and drops everything).
+ */
+
+import { useRef, useState } from 'react'
+import { create } from 'zustand'
+import { CheckCircle2, KeyRound, Upload } from 'lucide-react'
+import { useAuth } from '@/contexts/auth-context'
+import { Dialog } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Field, Input, Textarea } from '@/components/ui/input'
+import { CostPreview } from '@/components/ui/cost-preview'
+import { ErrorBox } from '@/components/auth/protection-fields'
+import { TOP_UP_DEFAULTS, TOP_UP_MAX_DAYS, TopUpPendingError, masterMaterialFromFile, parseDashAmount, topUpExpiry } from '@/lib/auth'
+import { KEY_LIMITS_UPDATE_CREDITS, previewCredits } from '@/lib/sdk'
+import type { KeyLimits } from '@/lib/view/funds'
+import { creditsAsDash, formatDate } from '@/lib/view/format'
+import { cn, errorMessage } from '@/lib/utils'
+
+const DAY_MS = 24 * 60 * 60 * 1000
+
+/** `yyyy-mm-dd` for a date input, in local time. */
+function isoDay(ms: number): string {
+ const d = new Date(ms)
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
+}
+
+/** A date input's value as end-of-day local time (ms), or null when empty / invalid. */
+function fromIsoDay(v: string): number | null {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v)
+ if (m === null) return null
+ return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 23, 59, 0).getTime()
+}
+
+interface PendingTopUp {
+ readonly before: KeyLimits | null
+ readonly message: string
+}
+
+/**
+ * Top-ups sent but not yet seen on chain, per identity. Module-level so closing and reopening
+ * the dialog still shows "sent, check again" instead of a form that could send a second
+ * `IdentityKeyLimitsUpdate`. Cleared once the chain shows limits different from `before`.
+ */
+const usePendingTopUps = create<{ byIdentity: Readonly> }>(() => ({ byIdentity: {} }))
+
+function setPendingTopUp(identity: string, pending: PendingTopUp | null): void {
+ const { [identity]: _dropped, ...rest } = usePendingTopUps.getState().byIdentity
+ usePendingTopUps.setState({ byIdentity: pending === null ? rest : { ...rest, [identity]: pending } })
+}
+
+export function KeyTopUpDialog({ onClose }: { onClose: () => void }): JSX.Element {
+ const { identity, keyLimits, topUpKey, refreshBalance, isLoading } = useAuth()
+ const [amount, setAmount] = useState(String(TOP_UP_DEFAULTS.addDash))
+ const current = keyLimits?.expiresAt ?? null
+ const suggested = Date.now() + TOP_UP_DEFAULTS.days * DAY_MS
+ const [extend, setExtend] = useState(current === null || current < suggested)
+ const [expiry, setExpiry] = useState(isoDay(suggested))
+ const [mode, setMode] = useState<'file' | 'mnemonic'>('file')
+ const fileRef = useRef(null)
+ const fileInput = useRef(null)
+ const [fileName, setFileName] = useState('')
+ // The recovery phrase never enters React state: an uncontrolled textarea, read at submit
+ // and cleared afterwards. Only "something was typed" is state.
+ const phraseRef = useRef(null)
+ const [phraseTyped, setPhraseTyped] = useState(false)
+ const [error, setError] = useState(null)
+ const [done, setDone] = useState<{ before: KeyLimits | null; after: KeyLimits } | null>(null)
+ // Sent, but not visible on chain yet: re-read, never re-send (kept across close / reopen).
+ const pending = usePendingTopUps((s) => (identity === null ? null : s.byIdentity[identity] ?? null))
+ const setPending = (p: PendingTopUp | null): void => {
+ if (identity !== null) setPendingTopUp(identity, p)
+ }
+ const [checking, setChecking] = useState(false)
+
+ let credits: bigint | null = null
+ let amountError: string | null = null
+ if (amount.trim() !== '') {
+ try {
+ credits = parseDashAmount(amount)
+ } catch (e) {
+ amountError = errorMessage(e)
+ }
+ }
+ let newExpiry: number | null = null
+ let expiryError: string | null = null
+ if (extend) {
+ try {
+ newExpiry = topUpExpiry(current, fromIsoDay(expiry))
+ if (newExpiry === null) expiryError = 'pick a date later than the current expiry, or leave the expiry as it is'
+ } catch (e) {
+ expiryError = errorMessage(e)
+ }
+ }
+ const hasMaster = mode === 'file' ? fileName !== '' : phraseTyped
+ const changes = credits !== null || newExpiry !== null
+ const ready = hasMaster && changes && amountError === null && expiryError === null && !isLoading
+
+ const onFile = async (f: File): Promise => {
+ setError(null)
+ const text = await f.text()
+ try {
+ const m = masterMaterialFromFile(text)
+ if (m.identityId !== identity) throw new Error('that identity file is for another identity')
+ fileRef.current = text
+ setFileName(f.name)
+ } catch (e) {
+ fileRef.current = null
+ setFileName('')
+ setError(errorMessage(e))
+ }
+ }
+
+ const clearSecrets = (): void => {
+ fileRef.current = null
+ setFileName('')
+ if (phraseRef.current) phraseRef.current.value = ''
+ setPhraseTyped(false)
+ }
+
+ const submit = async (): Promise => {
+ if (!ready) return
+ setError(null)
+ const before = keyLimits
+ try {
+ const input = mode === 'file' ? { fileText: fileRef.current ?? '' } : { mnemonic: phraseRef.current?.value ?? '' }
+ const after = await topUpKey(input, { addCredits: credits, expiresAt: newExpiry })
+ setDone({ before, after })
+ } catch (e) {
+ if (e instanceof TopUpPendingError) setPending({ before, message: e.message })
+ else setError(errorMessage(e))
+ } finally {
+ clearSecrets()
+ }
+ }
+
+ /** Re-read the key (no signature, no fee): did the sent update land? */
+ const checkAgain = async (): Promise => {
+ if (pending === null) return
+ setChecking(true)
+ try {
+ await refreshBalance()
+ } finally {
+ setChecking(false)
+ }
+ }
+ // After a refresh, the session's limits show whether the update landed.
+ const landed =
+ pending !== null &&
+ keyLimits !== null &&
+ ((keyLimits.total ?? 0n) !== (pending.before?.total ?? 0n) || keyLimits.expiresAt !== (pending.before?.expiresAt ?? null))
+ // Once the chain shows the change, the marker has done its job; this view stays until Close.
+ const closeDialog = (): void => {
+ if (landed) setPending(null)
+ onClose()
+ }
+
+ const dash = (c: bigint | null): string => (c === null ? '—' : `${creditsAsDash(Number(c))} DASH`)
+
+ return (
+
+ {pending !== null && done === null ? (
+
+ {landed ? (
+
+ The update landed: this key now has{' '}
+ {dash(keyLimits?.total ?? null)} of budget
+ {keyLimits?.expiresAt ? `, until ${formatDate(keyLimits.expiresAt)}` : ''}.
+
+ ) : (
+ <>
+
+ The update was sent, but the chain does not show the new limits yet. Do not send it again: a second top-up would
+ add the budget twice.
+
+
{pending.message}
+ >
+ )}
+
Your master key was used once and was not stored.
+
+ {landed ? null : (
+ void checkAgain()}>
+ Check again
+
+ )}
+
+ Close
+
+
+
+ ) : done ? (
+
+
+ Key limits updated on chain.
+
+
+
+ Before
+ Now (read back from the chain)
+ Budget
+ {dash(done.before?.total ?? null)}
+ {dash(done.after.total)}
+ Left
+ {dash(done.before?.remaining ?? null)}
+ {dash(done.after.remaining)}
+ Expires
+ {done.before?.expiresAt ? formatDate(done.before.expiresAt) : '—'}
+ {done.after.expiresAt ? formatDate(done.after.expiresAt) : 'never'}
+
+
Your master key was used for this one update and was not stored.
+
+ Done
+
+
+ ) : (
+
+ )}
+
+ )
+}
diff --git a/forge-web/components/keys-panel.tsx b/forge-web/components/keys-panel.tsx
index d01fc7fc1..cdd757a97 100644
--- a/forge-web/components/keys-panel.tsx
+++ b/forge-web/components/keys-panel.tsx
@@ -2,13 +2,14 @@
/**
* Settings → This browser's key (`ux-dx-spec.md` §2.3): which key signs here, what is left of
- * its budget, when it expires, and how to renew it. Renewal registers a fresh limited key (it
- * needs the master key once: import the identity file or phrase again); raising an existing
- * key's limits (`IdentityKeyLimitsUpdate`) is P1. Also: lock now, and sign out + forget.
+ * its budget, when it expires, and how to extend it. **Top up** raises this key's budget and
+ * expiry in place (`IdentityKeyLimitsUpdate`; same key). **Renew** registers a fresh limited key
+ * and disables this one. Both need the master key once (identity file or phrase), which is not
+ * stored. Also: lock now, and sign out + forget.
*/
import { useRef, useState } from 'react'
-import { Lock, LogOut, RefreshCw, ShieldOff } from 'lucide-react'
+import { BatteryCharging, Lock, LogOut, RefreshCw, ShieldOff } from 'lucide-react'
import { errorMessage } from '@/lib/utils'
import { useAuth } from '@/contexts/auth-context'
import { useUiStore } from '@/hooks/use-ui-store'
@@ -16,6 +17,7 @@ import { Button } from '@/components/ui/button'
import { Field, Input } from '@/components/ui/input'
import { creditsAsDash, formatDate } from '@/lib/view/format'
import { INSIGHT_OVERRIDE_KEY } from '@/lib/auth/asset-lock'
+import { KeyTopUpDialog } from '@/components/key-top-up-dialog'
/** Shown before deleting a stored key: for a wallet-granted key this is the only copy. */
export const FORGET_CONFIRM =
@@ -39,6 +41,9 @@ export function KeysPanel(): JSX.Element {
typeof window === 'undefined' ? '' : window.localStorage.getItem(INSIGHT_OVERRIDE_KEY) ?? '',
)
const low = funds?.reason === 'key-budget' || funds?.reason === 'key-expiry'
+ const [topUpOpen, setTopUpOpen] = useState(false)
+ // Only a stored Forge browser key (a budget on a group-bound key) can be topped up here.
+ const canTopUp = storage === 'vault' && keyLimits?.total != null
return (
@@ -61,9 +66,14 @@ export function KeysPanel(): JSX.Element {
This key has no budget or expiry.
)}
{low ? (
-
This browser's key is nearly used up. Renew it (uses your master key once).
+
This browser's key is nearly used up. Top it up or renew it (uses your master key once).
) : null}
+ {canTopUp ? (
+ setTopUpOpen(true)}>
+ Top up key budget
+
+ ) : null}
openLogin('import')}>
Renew key
@@ -99,6 +109,11 @@ export function KeysPanel(): JSX.Element {
>
) : null}
+
+ Top-up keeps this key and adds budget (or a later expiry). Renew replaces it with a new key and disables this one.
+ Both use your master key once and do not store it.
+
+ {topUpOpen ?
setTopUpOpen(false)} /> : null}
Forgetting deletes the key from this device only. Revoking disables it on chain (needs your identity file once).
diff --git a/forge-web/components/providers.tsx b/forge-web/components/providers.tsx
index daa58fca0..8a12a2e6b 100644
--- a/forge-web/components/providers.tsx
+++ b/forge-web/components/providers.tsx
@@ -3,11 +3,13 @@
import { ThemeProvider } from 'next-themes'
import type { ReactNode } from 'react'
import { AuthProvider } from '@/contexts/auth-context'
+import { InboxPoller } from '@/hooks/use-inbox'
/**
* App-wide client providers. Dark mode is the primary theme (class-based, per style guide);
* light mode fully supported. `next-themes` toggles the `class` on . {@link AuthProvider}
- * wraps the headless identity session so `useAuth()` works anywhere in the tree.
+ * wraps the headless identity session so `useAuth()` works anywhere in the tree; the local
+ * notifications poller runs once under it.
*/
export function Providers({ children }: { children: ReactNode }): JSX.Element {
return (
@@ -17,7 +19,11 @@ export function Providers({ children }: { children: ReactNode }): JSX.Element {
enableSystem
disableTransitionOnChange
>
- {children}
+
+ {/* Once, app-wide: page navigations remount the header, never the poller. */}
+
+ {children}
+
)
}
diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx
index d07e9e0d4..961254fd1 100644
--- a/forge-web/contexts/auth-context.tsx
+++ b/forge-web/contexts/auth-context.tsx
@@ -12,7 +12,16 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type { EvoSDK } from '@dashevo/evo-sdk'
-import { AuthController, type AuthSession, type LimitedKey, type LimitedKeyRequest, type Protection, type VaultInfo } from '../lib/auth'
+import {
+ AuthController,
+ type AuthSession,
+ type LimitedKey,
+ type LimitedKeyRequest,
+ type MasterInput,
+ type Protection,
+ type TopUpRequest,
+ type VaultInfo,
+} from '../lib/auth'
import { DEFAULT_NETWORK, NETWORKS, type Network } from '../lib/constants'
import { ensureSdk, type SpendEvent, type WriteAuth } from '../lib/sdk'
import { recordSpend } from '../lib/spend'
@@ -74,7 +83,9 @@ interface AuthContextValue {
/** Delete the stored key of `identityId` from this device (does not revoke it on chain). */
forget: (identityId: string) => Promise
/** Disable this device's key on chain with the master key (file or phrase), then forget it. */
- revokeStored: (identityId: string, input: { fileText: string } | { mnemonic: string }) => Promise
+ revokeStored: (identityId: string, input: MasterInput) => Promise
+ /** Raise this browser key's budget / expiry in place (the master key signs once). */
+ topUpKey: (input: MasterInput, request: TopUpRequest) => Promise
reloadVaults: () => void
/** The headless controller (identity creation stores its key before registering it). */
readonly controller: AuthController
@@ -123,6 +134,7 @@ export function AuthProvider({
logout: () => controller.logout(),
forget: withReload(controller.forget.bind(controller)),
revokeStored: withReload(controller.revokeStored.bind(controller)),
+ topUpKey: (input: MasterInput, request: TopUpRequest) => controller.topUpKey(input, request),
}),
[controller, withReload],
)
diff --git a/forge-web/e2e/v2-explore.spec.ts b/forge-web/e2e/v2-explore.spec.ts
new file mode 100644
index 000000000..a12fc5944
--- /dev/null
+++ b/forge-web/e2e/v2-explore.spec.ts
@@ -0,0 +1,102 @@
+import { test, expect } from '@playwright/test'
+import { collectPageErrors, E2E_DEVNET, runAxe, shot } from './helpers'
+
+/**
+ * Explore, the header and the notifications page, signed out, on a devnet (reads only):
+ *
+ * E2E_DEVNET=moutai E2E_PORT=4323 pnpm exec playwright test v2-explore.spec.ts
+ *
+ * The signed-in halves (my repos, the inbox, the key top-up) are in v2-inbox-topup.spec.ts,
+ * gated on E2E_WRITE because signing in registers a key.
+ */
+
+test.skip(E2E_DEVNET === '', 'forge-v2 lives on a devnet; set E2E_DEVNET=moutai')
+
+test('x1. explore lists recent repos and says what it cannot know', async ({ page }) => {
+ const { errors } = collectPageErrors(page)
+ await page.goto('/explore/', { waitUntil: 'domcontentloaded' })
+ await expect(page.getByRole('heading', { name: 'Explore', level: 1 })).toBeVisible()
+ const recent = page.getByTestId('explore-recent-repos')
+ await expect(recent.locator('a[href*="/repo"]').first()).toBeVisible({ timeout: 60_000 })
+ await expect(page.getByTestId('trending-note')).toHaveText("Trending needs an indexer. Forge doesn't run one; you can (docs).")
+ const released = page.getByTestId('explore-recently-released')
+ await expect(released).toContainText('no cross-repo index')
+ await expect(released.locator('[data-empty], li').first()).toBeVisible({ timeout: 60_000 })
+ await expect(page.getByText(/sign in to see your repos/i)).toBeVisible()
+ await shot(page, 'd-explore-signed-out')
+ const serious = await runAxe(page, 'explore')
+ expect(serious, serious.map((v) => `${v.id}: ${v.help}`).join('\n')).toEqual([])
+ expect(errors, errors.join('\n')).toEqual([])
+})
+
+test('x2. the header: New menu, jump box, and the landing links Explore', async ({ page }) => {
+ await page.goto('/', { waitUntil: 'domcontentloaded' })
+ await expect(page.getByRole('link', { name: 'Explore' }).first()).toBeVisible()
+ await page.getByRole('button', { name: 'New', exact: true }).click()
+ const menu = page.getByRole('navigation', { name: 'New' })
+ await expect(menu.getByRole('link', { name: /Repository/ })).toHaveAttribute('href', /\/new/)
+ await expect(menu.getByRole('link', { name: /Mirror a GitHub repo/ })).toHaveAttribute('href', /mirror-a-github-repo\.md$/)
+ await page.waitForTimeout(300)
+ await shot(page, 'd-header-new-menu')
+ await expect(page.getByRole('button', { name: 'New', exact: true })).toHaveAttribute('aria-expanded', 'true')
+ await page.keyboard.press('Escape')
+ await expect(menu).toBeHidden()
+ await expect(page.getByRole('button', { name: 'New', exact: true })).toBeFocused()
+
+ // #n outside a repo explains itself; owner/name jumps.
+ const jump = page.getByLabel(/jump to a repo/i).first()
+ await jump.fill('#1')
+ await jump.press('Enter')
+ await expect(page.getByRole('status').filter({ hasText: /inside a repo/ })).toBeVisible()
+ await jump.fill('9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD/forge-v2-demo')
+ await jump.press('Enter')
+ await expect(page).toHaveURL(/\/repo\/?\?owner=9r27/)
+})
+
+test('x3. #n in a repo opens that issue', async ({ page }) => {
+ await page.goto('/repo/?owner=9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD&name=forge-v2-demo', { waitUntil: 'domcontentloaded' })
+ const jump = page.getByLabel(/jump to a repo/i).first()
+ // The fixture has issue #1 and PR #1: both are offered.
+ await jump.fill('#1')
+ await jump.press('Enter')
+ const note = page.getByRole('status').filter({ hasText: /#1 is both/ })
+ await expect(note).toBeVisible({ timeout: 60_000 })
+ await note.getByRole('link', { name: 'issue #1' }).click()
+ await expect(page).toHaveURL(/\/repo\/issue\/?\?.*number=1/)
+ // #3 is an issue only: straight there.
+ await page.getByLabel(/jump to a repo/i).first().fill('#3')
+ await page.getByLabel(/jump to a repo/i).first().press('Enter')
+ await expect(page).toHaveURL(/\/repo\/issue\/?\?.*number=3/, { timeout: 60_000 })
+})
+
+test('x4. notifications, signed out, say what they are', async ({ page }) => {
+ await page.goto('/notifications/', { waitUntil: 'domcontentloaded' })
+ await expect(page.getByText('Notifications are computed in this browser from the chain. Nothing is sent to you; nothing leaves your device.', { exact: false })).toBeVisible()
+ const serious = await runAxe(page, 'notifications-signed-out')
+ expect(serious, serious.map((v) => `${v.id}: ${v.help}`).join('\n')).toEqual([])
+})
+
+test('x5. the header fits a 390 px phone', async ({ browser }) => {
+ const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true })
+ const page = await context.newPage()
+ await page.goto('/explore/', { waitUntil: 'domcontentloaded' })
+ await expect(page.getByRole('heading', { name: 'Explore', level: 1 })).toBeVisible()
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)
+ expect(overflow).toBeLessThanOrEqual(0)
+ await expect(page.getByLabel(/jump to a repo/i).last()).toBeVisible()
+ await expect(page.getByRole('button', { name: 'New', exact: true })).toBeVisible()
+ await expect(page.getByRole('button', { name: /^sign in$/i }).first()).toBeVisible()
+ await page.getByRole('button', { name: 'New', exact: true }).click()
+ await expect(page.getByRole('link', { name: /Mirror a GitHub repo/ })).toBeVisible()
+ // The menu paints above the jump-box row: the point under its last item is the item.
+ const item = page.getByRole('link', { name: /Mirror a GitHub repo/ })
+ const box = await item.boundingBox()
+ const hit = await page.evaluate(([x, y]) => document.elementFromPoint(x ?? 0, y ?? 0)?.closest('a')?.textContent ?? '', [(box?.x ?? 0) + 20, (box?.y ?? 0) + 10])
+ expect(hit).toContain('Mirror a GitHub repo')
+ await page.getByTestId('explore-recent-repos').locator('a[href*="/repo"]').first().waitFor({ timeout: 60_000 })
+ await page.waitForTimeout(300)
+ await shot(page, 'd-header-mobile-390')
+ const serious = await runAxe(page, 'header-mobile')
+ expect(serious, serious.map((v) => `${v.id}: ${v.help}`).join('\n')).toEqual([])
+ await context.close()
+})
diff --git a/forge-web/e2e/v2-inbox-topup.spec.ts b/forge-web/e2e/v2-inbox-topup.spec.ts
new file mode 100644
index 000000000..95ae8c419
--- /dev/null
+++ b/forge-web/e2e/v2-inbox-topup.spec.ts
@@ -0,0 +1,183 @@
+import { test, expect, type Page } from '@playwright/test'
+import { existsSync, readFileSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { E2E_DEVNET, SCREENSHOT_DIR, idFile, runAxe, shot, signedIn, unlock } from './helpers'
+
+/**
+ * Signed in as CI-RUNNER, live on a devnet (real spend, ~0.0003 DASH plus a key if the stored
+ * one is gone):
+ *
+ * E2E_DEVNET=moutai E2E_WRITE=1 E2E_PORT=4323 pnpm exec playwright test v2-inbox-topup.spec.ts
+ *
+ * t1. Explore's "my" sections render honest empty states or data.
+ * t2. The inbox starts empty with the local-only copy; after CI-RUNNER stars a repo the write
+ * spec made (never the read fixture) and opts in to starred repos, the other identities'
+ * issues there show up, the header badge counts them, and mark read / mark all read work.
+ * t3. Top up this browser's key by +0.01 DASH with the identity file; Node reads the identity
+ * from Platform and checks the same key id now has +0.01 DASH of budget and no key was added.
+ *
+ * CI-RUNNER only: the other test identities sign concurrently in other suites, and parallel
+ * writers from one identity collide on nonces.
+ */
+
+test.skip(E2E_DEVNET === '' || process.env['E2E_WRITE'] !== '1', 'live devnet writes: set E2E_DEVNET=moutai E2E_WRITE=1')
+test.skip(!existsSync(idFile('CI-RUNNER')), 'devnet test identities not found')
+test.describe.configure({ mode: 'serial', timeout: 10 * 60_000 })
+
+const ROOT = resolve(__dirname, '../..')
+const OWNER = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD'
+const RUNNER = String(JSON.parse(readFileSync(idFile('CI-RUNNER'), 'utf8')).identityId)
+
+interface NodeSdk {
+ identities: {
+ fetch(id: string): Promise<{ publicKeys: { keyId: number; totalBudget?: bigint }[] }>
+ keysRemainingBudgets(id: string, ids: number[]): Promise>
+ }
+ documents: { query(q: unknown): Promise } | undefined>> }
+}
+
+let sdkPromise: Promise<{ sdk: NodeSdk; collab: string; core: string }> | null = null
+/** evo-sdk in Node, independent of the app (as v2-auth.spec.ts). */
+function nodeSdk(): Promise<{ sdk: NodeSdk; collab: string; core: string }> {
+ sdkPromise ??= (async () => {
+ const evo = await import(pathToFileURL(join(ROOT, 'forge-web/node_modules/@dashevo/evo-sdk/dist/evo-sdk.module.js')).href)
+ const dep = JSON.parse(readFileSync(join(ROOT, `forge-contracts/deployments/devnet-${E2E_DEVNET}.json`), 'utf8'))
+ const sdk = new evo.EvoSDK({ network: 'devnet', trusted: true, devnetName: E2E_DEVNET, addresses: dep.dapiAddresses })
+ await sdk.connect()
+ return { sdk: sdk as NodeSdk, collab: String(dep.v2.forgeCollab.contractId), core: String(dep.v2.forgeCore.contractId) }
+ })()
+ return sdkPromise
+}
+
+async function docs(query: Record): Promise[]> {
+ const { sdk } = await nodeSdk()
+ const r = await sdk.documents.query(query)
+ return [...r.values()].filter((d): d is { toJSON(v: number): Record } => d !== undefined).map((d) => d.toJSON(14))
+}
+
+/** A repo the write spec made (OWNER's `e2e-*`) with an issue by someone other than CI-RUNNER. */
+async function writeSpecRepo(): Promise {
+ const { core, collab } = await nodeSdk()
+ const repos = await docs({ dataContractId: core, documentTypeName: 'repo', where: [['$ownerId', '==', OWNER]], orderBy: [['name', 'asc']], limit: 100 })
+ const candidates = repos.filter((r) => String(r['name']).startsWith('e2e-')).sort((a, b) => Number(b['$createdAt']) - Number(a['$createdAt']))
+ for (const r of candidates) {
+ const issues = await docs({ dataContractId: collab, documentTypeName: 'issue', where: [['repoId', '==', r['$id']]], orderBy: [['$createdAt', 'desc']], limit: 5 })
+ if (issues.some((i) => i['$ownerId'] !== RUNNER)) return String(r['name'])
+ }
+ return null
+}
+
+async function budgets(): Promise> {
+ const { sdk } = await nodeSdk()
+ const identity = await sdk.identities.fetch(RUNNER)
+ const out = new Map()
+ for (const k of identity.publicKeys) out.set(k.keyId, k.totalBudget ?? null)
+ return out
+}
+
+async function inboxReady(page: Page): Promise {
+ await expect(page.getByRole('heading', { name: 'Notifications' })).toBeVisible()
+ await expect(page.getByText(/Last checked/)).toBeVisible({ timeout: 120_000 })
+}
+
+test('t1. explore, signed in: my sections are honest', async ({ browser }) => {
+ const page = await signedIn(browser, 'CI-RUNNER', '/explore/')
+ const mine = page.getByTestId('explore-mine')
+ await expect(mine).toBeVisible({ timeout: 60_000 })
+ for (const id of ['explore-my-repos', 'explore-repos-i-maintain-or-write-to', 'explore-my-issues', 'explore-my-pull-requests', 'explore-starred', 'explore-assigned-to-me-or-mentioning-me']) {
+ const section = page.getByTestId(id)
+ // Either an honest empty line or data, never a spinner forever or an error.
+ await expect(section.locator('[data-empty], a[href*="/repo"]').first()).toBeVisible({ timeout: 90_000 })
+ await expect(section.getByText(/did not land/)).toHaveCount(0)
+ }
+ await expect(page.getByTestId('explore-assigned-to-me-or-mentioning-me')).toContainText('have no index')
+ await shot(page, 'd-explore-signed-in')
+ const serious = await runAxe(page, 'explore-signed-in')
+ expect(serious, serious.map((v) => `${v.id}: ${v.help}`).join('\n')).toEqual([])
+})
+
+test('t2. inbox: empty first, then items from a starred repo, badge and mark read', async ({ browser }) => {
+ const page = await signedIn(browser, 'CI-RUNNER', '/notifications/')
+ await inboxReady(page)
+ await expect(page.getByText(/no email, no push and no\s+sync/i)).toBeVisible()
+ const empty = page.getByTestId('inbox-empty')
+ if (await empty.isVisible()) {
+ await expect(empty).toContainText('Notifications are computed in this browser from the chain. Nothing is sent to you; nothing leaves your device.')
+ await shot(page, 'd-notifications-empty')
+ }
+ const serious = await runAxe(page, 'notifications')
+ expect(serious, serious.map((v) => `${v.id}: ${v.help}`).join('\n')).toEqual([])
+
+ const repo = await writeSpecRepo()
+ test.skip(repo === null, 'no write-spec repo with an issue on this devnet; run v2-writes.spec.ts first')
+ // A full navigation reloads the app, which locks the vault: unlock again after each.
+ await page.goto(`/repo/?owner=${OWNER}&name=${repo}`, { waitUntil: 'domcontentloaded' })
+ await unlock(page)
+ const starred = page.getByRole('button', { name: /starred/i })
+ const star = page.getByRole('button', { name: /^star/i })
+ await expect(starred.or(star)).toBeEnabled({ timeout: 60_000 })
+ if (!(await starred.isVisible())) {
+ await star.click()
+ await expect(starred).toBeVisible({ timeout: 90_000 })
+ }
+
+ await page.goto('/notifications/', { waitUntil: 'domcontentloaded' })
+ await unlock(page)
+ await inboxReady(page)
+ const watchStars = page.getByLabel('Also watch repos I starred')
+ if (!(await watchStars.isChecked())) await watchStars.check()
+ const list = page.getByTestId('inbox-list')
+ // A new watch set is read at once, then round-robin; items land within a couple of rounds.
+ await expect(list.locator('li').first()).toBeVisible({ timeout: 180_000 })
+ await expect(list).toContainText(repo ?? '')
+ const bell = page.getByTestId('notifications-bell')
+ await expect(bell).not.toHaveAttribute('data-unread', '0')
+ await expect(bell).toHaveAccessibleName(/\d+ unread/)
+ await shot(page, 'd-notifications-items')
+
+ const before = Number(await bell.getAttribute('data-unread'))
+ await list.getByRole('button', { name: /^Mark read/ }).first().click()
+ await expect(bell).toHaveAttribute('data-unread', String(before - 1))
+ if (before > 1) await page.getByRole('button', { name: 'Mark all read' }).click()
+ await expect(bell).toHaveAttribute('data-unread', '0')
+ await expect(page.getByTestId('inbox-empty')).toContainText('All caught up')
+ await page.getByRole('button', { name: /^All/ }).click()
+ await expect(list.locator('li[data-read="true"]').first()).toBeVisible()
+ // Read state survives a reload (IndexedDB), and items link to their thread.
+ await page.reload({ waitUntil: 'domcontentloaded' })
+ await unlock(page)
+ await expect(page.getByTestId('notifications-bell')).toHaveAttribute('data-unread', '0')
+ await page.getByRole('button', { name: /^All/ }).click()
+ await expect(page.getByTestId('inbox-list').locator('li[data-read="true"]').first()).toBeVisible()
+})
+
+test('t3. top up this browser key by +0.01 DASH, same key on chain', async ({ browser }) => {
+ const page = await signedIn(browser, 'CI-RUNNER', '/settings/')
+ await expect(page.getByTestId('key-budget')).toBeVisible({ timeout: 60_000 })
+ const before = await budgets()
+ await page.getByRole('button', { name: 'Top up key budget' }).click()
+ const dialog = page.getByRole('dialog', { name: "Top up this browser's key" })
+ await expect(dialog).toContainText('signs this one update and is not stored')
+ await dialog.getByLabel('Add to the budget (DASH)').fill('0.01')
+ const extend = dialog.getByLabel(/Extend the expiry/)
+ if (await extend.isChecked()) await extend.uncheck()
+ await dialog.getByLabel('Identity file for the top-up').setInputFiles(idFile('CI-RUNNER'))
+ await expect(dialog.getByTestId('cost-preview')).toContainText('DASH')
+ // The dialog is a fixed overlay: a viewport screenshot, not a full-page one.
+ await page.screenshot({ path: join(SCREENSHOT_DIR, 'd-key-topup-dialog.png') })
+ await dialog.getByRole('button', { name: /sign once & top up/i }).click()
+ await expect(dialog.getByTestId('key-top-up-done')).toBeVisible({ timeout: 120_000 })
+ await page.screenshot({ path: join(SCREENSHOT_DIR, 'd-key-topup-result.png') })
+
+ const after = await budgets()
+ expect([...after.keys()].sort()).toEqual([...before.keys()].sort())
+ const changed = [...after].filter(([id, b]) => b !== before.get(id))
+ expect(changed).toHaveLength(1)
+ const [keyId, total] = changed[0] ?? [-1, null]
+ expect((total ?? 0n) - (before.get(keyId) ?? 0n)).toBe(1_000_000_000n)
+ test.info().annotations.push({ type: 'topped-up', description: `key ${keyId}: ${before.get(keyId)} → ${total}` })
+ await dialog.getByRole('button', { name: 'Done' }).click()
+ // The settings row shows the new total from the session's refreshed limits.
+ await expect(page.getByTestId('key-budget')).toContainText(`of ${Number(total) / 1e11} DASH`)
+})
diff --git a/forge-web/hooks/use-inbox.ts b/forge-web/hooks/use-inbox.ts
new file mode 100644
index 000000000..d06ef36ba
--- /dev/null
+++ b/forge-web/hooks/use-inbox.ts
@@ -0,0 +1,191 @@
+'use client'
+
+/**
+ * The local notifications inbox, as React state (`ux-dx-spec.md` §5.10). One poller, mounted
+ * by the header on every page, reads the chain every 60 s while the tab is visible and the
+ * viewer is signed in; the header badge and `/notifications` read the same store. Everything
+ * is computed and kept in this browser (IndexedDB); nothing is sent anywhere.
+ */
+
+import { useCallback, useEffect } from 'react'
+import { create } from 'zustand'
+
+import { useAuth } from '@/contexts/auth-context'
+import { DEFAULT_NETWORK, NETWORKS, type Network } from '@/lib/constants'
+import { ensureSdk } from '@/lib/sdk'
+import { errorMessage } from '@/lib/utils'
+import {
+ POLL_MS,
+ loadItems,
+ loadPrefs,
+ loadSubs,
+ markRead,
+ pollOnce,
+ savePrefs,
+ type InboxItem,
+ type InboxPrefs,
+ type Subscriptions,
+} from '@/lib/view/inbox'
+
+interface InboxState {
+ /** `:` the state belongs to, or null when signed out. */
+ readonly owner: string | null
+ readonly items: readonly InboxItem[]
+ readonly subs: Subscriptions | null
+ readonly prefs: InboxPrefs | null
+ readonly polling: boolean
+ readonly lastPoll: number | null
+ readonly lastFeeds: { read: number; total: number; failed: number } | null
+ readonly error: string | null
+ /** Bumped to ask the poller for an immediate round (optionally recomputing subscriptions). */
+ readonly nudge: { n: number; refreshSubs: boolean }
+}
+
+const initial: InboxState = {
+ owner: null,
+ items: [],
+ subs: null,
+ prefs: null,
+ polling: false,
+ lastPoll: null,
+ lastFeeds: null,
+ error: null,
+ nudge: { n: 0, refreshSubs: false },
+}
+
+export const useInboxStore = create(() => initial)
+
+const set = (patch: Partial): void => useInboxStore.setState(patch)
+
+/** Ask the poller for a round now, recomputing subscriptions (queued if one is in flight). */
+function nudge(): void {
+ set({ nudge: { n: useInboxStore.getState().nudge.n + 1, refreshSubs: true } })
+}
+
+/** Unread items, for the header badge. */
+export function useUnreadCount(): number {
+ return useInboxStore((s) => s.items.reduce((n, i) => n + (i.read ? 0 : 1), 0))
+}
+
+async function reloadLocal(owner: string, network: Network, me: string): Promise {
+ const [items, subs, prefs] = await Promise.all([loadItems(network, me), loadSubs(network, me), loadPrefs(network, me)])
+ const state = useInboxStore.getState()
+ // Prefs are the store's once loaded: a poll finishing mid-toggle must not revert them.
+ if (state.owner === owner) set({ items, subs: subs ?? null, prefs: state.prefs ?? prefs })
+}
+
+/**
+ * Run the inbox poller for the signed-in identity. Mount exactly once, app-wide (the
+ * `InboxPoller` in `Providers`), so page navigations never restart it. Polls on sign-in, then
+ * every {@link POLL_MS} while the document is visible, and at once when the tab becomes
+ * visible again or {@link useInboxActions} nudges. A nudge that arrives while a poll is in
+ * flight is queued and runs right after it, never dropped.
+ */
+export function useInboxPoller(): void {
+ const { identity } = useAuth()
+ const network = DEFAULT_NETWORK
+ const forge = NETWORKS[network].v2
+
+ useEffect(() => {
+ if (identity === null || forge === null) {
+ set(initial)
+ return
+ }
+ const owner = `${network}:${identity}`
+ if (useInboxStore.getState().owner !== owner) set({ ...initial, owner })
+ void reloadLocal(owner, network, identity)
+
+ let cancelled = false
+ let timer: ReturnType | null = null
+ // Per effect (so a new identity never waits on the old one's poll).
+ let inFlight = false
+ let queued: { refreshSubs: boolean } | null = null
+ const run = async (refreshSubs: boolean): Promise => {
+ if (cancelled) return
+ if (inFlight) {
+ queued = { refreshSubs: refreshSubs || (queued?.refreshSubs ?? false) }
+ return
+ }
+ if (document.visibilityState !== 'visible') return
+ inFlight = true
+ set({ polling: true })
+ try {
+ const sdk = await ensureSdk(network)
+ const r = await pollOnce(sdk, network, forge, identity, { refreshSubs })
+ if (cancelled || useInboxStore.getState().owner !== owner) return
+ set({ lastPoll: Date.now(), lastFeeds: { read: r.feedsRead, total: r.feedsTotal, failed: r.failed }, error: null })
+ await reloadLocal(owner, network, identity)
+ } catch (e) {
+ if (!cancelled) set({ error: errorMessage(e) })
+ } finally {
+ inFlight = false
+ if (!cancelled) set({ polling: false })
+ const next = queued
+ queued = null
+ if (next !== null && !cancelled) void run(next.refreshSubs)
+ }
+ }
+ const schedule = (): void => {
+ timer = setTimeout(() => {
+ void run(false).finally(() => {
+ if (!cancelled) schedule()
+ })
+ }, POLL_MS)
+ }
+ const onVisible = (): void => {
+ if (document.visibilityState === 'visible') void run(false)
+ }
+ const unsubscribe = useInboxStore.subscribe((state, prev) => {
+ if (state.nudge.n !== prev.nudge.n) void run(state.nudge.refreshSubs)
+ })
+ void run(false)
+ schedule()
+ document.addEventListener('visibilitychange', onVisible)
+ return () => {
+ cancelled = true
+ if (timer !== null) clearTimeout(timer)
+ unsubscribe()
+ document.removeEventListener('visibilitychange', onVisible)
+ }
+ }, [identity, forge, network])
+}
+
+/** The app-wide inbox poller as a component, for `Providers` (renders nothing). */
+export function InboxPoller(): null {
+ useInboxPoller()
+ return null
+}
+
+/** Mark read, mark all read, change what is watched, poll now. */
+export function useInboxActions(): {
+ markRead: (ids: readonly string[]) => Promise
+ markAllRead: () => Promise
+ setPrefs: (prefs: InboxPrefs) => Promise
+ pollNow: () => void
+} {
+ const { identity } = useAuth()
+ const network = DEFAULT_NETWORK
+ const owner = identity === null ? null : `${network}:${identity}`
+ const mark = useCallback(
+ async (ids?: readonly string[]) => {
+ if (identity === null || owner === null) return
+ await markRead(network, identity, ids)
+ await reloadLocal(owner, network, identity)
+ },
+ [identity, network, owner],
+ )
+ return {
+ markRead: useCallback((ids: readonly string[]) => mark(ids), [mark]),
+ markAllRead: useCallback(() => mark(), [mark]),
+ setPrefs: useCallback(
+ async (prefs: InboxPrefs) => {
+ if (identity === null) return
+ set({ prefs })
+ await savePrefs(network, identity, prefs)
+ nudge()
+ },
+ [identity, network],
+ ),
+ pollNow: useCallback(() => nudge(), []),
+ }
+}
diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts
index f5d075df2..25f479091 100644
--- a/forge-web/lib/auth/controller.ts
+++ b/forge-web/lib/auth/controller.ts
@@ -27,7 +27,15 @@ import type { KeyLimits } from '../view/funds'
import { normalizeToWif } from './wif'
import { identityFileMatchesNetwork, masterMaterialFromFile } from './identity-file'
import { deriveMasterKey, isValidMnemonic } from './hd'
-import { readKeyLimits, registerLimitedKey, revokeLimitedKey, type LimitedKey, type LimitedKeyRequest } from './limited-key'
+import {
+ readKeyLimits,
+ registerLimitedKey,
+ revokeLimitedKey,
+ topUpLimitedKey,
+ type LimitedKey,
+ type LimitedKeyRequest,
+ type TopUpRequest,
+} from './limited-key'
import {
VaultLockedError,
forgetVault,
@@ -68,6 +76,9 @@ export interface AuthState {
type Listener = (state: AuthState) => void
+/** Where a one-time master key comes from: an identity file, or the recovery phrase. */
+export type MasterInput = { fileText: string } | { mnemonic: string }
+
/** How the SDK is obtained — injected so the controller stays testable and SSR-safe. */
export type SdkProvider = () => Promise
@@ -366,26 +377,58 @@ export class AuthController {
* Disable this device's key for `identityId` on chain (the identity file or phrase supplies
* the master key, used once), then forget it here. Forgetting alone does not revoke.
*/
- async revokeStored(identityId: string, input: { fileText: string } | { mnemonic: string }): Promise {
+ async revokeStored(identityId: string, input: MasterInput): Promise {
return this.run(async () => {
const stored = (await listVaults(this.network)).find((v) => v.identityId === identityId)
if (!stored) throw new Error('no key for this identity is stored here')
- let masterWif: string | null
- if ('fileText' in input) {
- const m = masterMaterialFromFile(input.fileText)
- if (m.identityId !== identityId) throw new Error('that identity file is for another identity')
- this.checkFileNetwork(m.networkKey)
- masterWif = m.masterWif ?? (m.mnemonic ? (await deriveMasterKey(m.mnemonic, this.network)).wif : null)
- } else {
- masterWif = (await deriveMasterKey(input.mnemonic, this.network)).wif
- }
- if (!masterWif) throw new Error('no master key found')
+ let masterWif: string | null = await this.masterWifFor(identityId, input)
await revokeLimitedKey(await this.getSdk(), { network: this.network, identityId, masterWif, keyId: stored.keyId })
masterWif = null
await this.forget(identityId)
})
}
+ /**
+ * Raise the limits of the key this session signs with (`IdentityKeyLimitsUpdate`): the
+ * identity file or phrase supplies the master key, which signs once and is not retained.
+ * The key id and the stored private key do not change. The session's `keyLimits` are
+ * replaced with what the chain now shows.
+ */
+ async topUpKey(input: MasterInput, request: TopUpRequest): Promise {
+ return this.run(async () => {
+ const session = this.state.session
+ if (!session || session.storage !== 'vault' || session.keyId === undefined) {
+ throw new Error("only a stored Forge browser key can be topped up; sign in with your identity first")
+ }
+ const { identityId, keyId } = session
+ let masterWif: string | null = await this.masterWifFor(identityId, input)
+ const limits = await topUpLimitedKey(await this.getSdk(), { network: this.network, identityId, masterWif, keyId, request })
+ masterWif = null
+ const current = this.state.session
+ if (current?.identityId === identityId && current.keyId === keyId) this.setState({ session: { ...current, keyLimits: limits } })
+ return limits
+ })
+ }
+
+ /**
+ * The master key (WIF) of `identityId` from an identity file or recovery phrase. The caller
+ * drops it as soon as it has signed. A file for another identity or network is refused.
+ */
+ private async masterWifFor(identityId: string, input: MasterInput): Promise {
+ let masterWif: string | null
+ if ('fileText' in input) {
+ const m = masterMaterialFromFile(input.fileText)
+ if (m.identityId !== identityId) throw new Error('that identity file is for another identity')
+ this.checkFileNetwork(m.networkKey)
+ masterWif = m.masterWif ?? (m.mnemonic ? (await deriveMasterKey(m.mnemonic, this.network)).wif : null)
+ } else {
+ if (!(await isValidMnemonic(input.mnemonic))) throw new Error('those words are not a valid recovery phrase')
+ masterWif = (await deriveMasterKey(input.mnemonic, this.network)).wif
+ }
+ if (!masterWif) throw new Error('no master key found')
+ return masterWif
+ }
+
/** Delete the stored key of `identityId` from this device (ending its session if open). */
async forget(identityId: string): Promise {
if (this.state.session?.identityId === identityId) this.logout()
diff --git a/forge-web/lib/auth/identity-file.ts b/forge-web/lib/auth/identity-file.ts
index 54eec6d55..e2c897e3f 100644
--- a/forge-web/lib/auth/identity-file.ts
+++ b/forge-web/lib/auth/identity-file.ts
@@ -95,8 +95,9 @@ function fileHeader(json: unknown): { obj: Record; identityId:
function parseJson(text: string): unknown {
try {
return JSON.parse(text)
- } catch (e) {
- throw new Error(`identity file is not valid JSON: ${(e as Error).message}`)
+ } catch {
+ // Never forward the parser's message: it quotes the input, which may hold a private key.
+ throw new Error('identity file is not valid JSON')
}
}
diff --git a/forge-web/lib/auth/index.ts b/forge-web/lib/auth/index.ts
index ad3895891..c7ad951d8 100644
--- a/forge-web/lib/auth/index.ts
+++ b/forge-web/lib/auth/index.ts
@@ -37,7 +37,18 @@ export {
type Protection,
type VaultInfo,
} from './vault'
-export { BROWSER_KEY_DEFAULTS, defaultLimits, type LimitedKey, type LimitedKeyRequest } from './limited-key'
+export {
+ BROWSER_KEY_DEFAULTS,
+ TOP_UP_DEFAULTS,
+ TOP_UP_MAX_DAYS,
+ TopUpPendingError,
+ defaultLimits,
+ parseDashAmount,
+ topUpExpiry,
+ type LimitedKey,
+ type LimitedKeyRequest,
+ type TopUpRequest,
+} from './limited-key'
export {
masterMaterialFromFile,
parseIdentityFile,
@@ -50,5 +61,6 @@ export {
purgeLegacyKeystore,
type AuthSession,
type AuthState,
+ type MasterInput,
type SdkProvider,
} from './controller'
diff --git a/forge-web/lib/auth/key-top-up.test.ts b/forge-web/lib/auth/key-top-up.test.ts
new file mode 100644
index 000000000..e8428f558
--- /dev/null
+++ b/forge-web/lib/auth/key-top-up.test.ts
@@ -0,0 +1,78 @@
+/**
+ * Key top-up (`IdentityKeyLimitsUpdate`), the pure parts: amount parsing, the expiry rule, the
+ * "something to change" check, and the Forge-browser-key guard.
+ */
+
+import { describe, expect, it } from 'vitest'
+
+import { CREDITS_PER_DASH } from '../sdk/cost'
+import { TOP_UP_MAX_DASH, TOP_UP_MAX_DAYS, assertTopUp, isForgeBrowserKey, parseDashAmount, topUpExpiry } from './limited-key'
+
+const DASH = BigInt(CREDITS_PER_DASH)
+
+describe('parseDashAmount', () => {
+ it('converts DASH to credits exactly, without floats', () => {
+ expect(parseDashAmount('0.05')).toBe(5_000_000_000n)
+ expect(parseDashAmount('0.01')).toBe(1_000_000_000n)
+ expect(parseDashAmount(' 1 ')).toBe(DASH)
+ expect(parseDashAmount('.5')).toBe(DASH / 2n)
+ expect(parseDashAmount('0.00000000001')).toBe(1n)
+ // 0.1 + 0.2 is not 0.3 in floats; here it is exact.
+ expect(parseDashAmount('0.3')).toBe(30_000_000_000n)
+ })
+
+ it('refuses what is not a plain positive amount', () => {
+ for (const bad of ['', 'abc', '-1', '1e3', '0', '0.000', '1,5', '0.000000000001', '1.2.3', '$1']) {
+ expect(() => parseDashAmount(bad), bad).toThrow()
+ }
+ })
+
+ it('caps one top-up', () => {
+ expect(parseDashAmount(String(TOP_UP_MAX_DASH))).toBe(BigInt(TOP_UP_MAX_DASH) * DASH)
+ expect(() => parseDashAmount(String(TOP_UP_MAX_DASH + 1))).toThrow(/at most/)
+ })
+})
+
+describe('topUpExpiry', () => {
+ const now = 1_000_000
+ it('asks for a later expiry only', () => {
+ expect(topUpExpiry(now + 10, now + 20, now)).toBe(now + 20)
+ expect(topUpExpiry(now + 20, now + 20, now)).toBeNull()
+ expect(topUpExpiry(now + 30, now + 20, now)).toBeNull()
+ })
+ it('keeps the expiry when none is wanted, and sets one on a key without', () => {
+ expect(topUpExpiry(now + 10, null, now)).toBeNull()
+ expect(topUpExpiry(null, now + 5, now)).toBe(now + 5)
+ })
+ it('refuses a date in the past, and one more than a year out', () => {
+ expect(() => topUpExpiry(now - 100, now - 1, now)).toThrow(/future/)
+ const day = 24 * 60 * 60 * 1000
+ expect(topUpExpiry(now, now + TOP_UP_MAX_DAYS * day, now)).toBe(now + TOP_UP_MAX_DAYS * day)
+ expect(() => topUpExpiry(now, now + TOP_UP_MAX_DAYS * day + 1, now)).toThrow(/at most 365 days/)
+ })
+})
+
+describe('assertTopUp', () => {
+ it('needs budget or an expiry', () => {
+ expect(() => assertTopUp({ addCredits: null, expiresAt: null })).toThrow(/nothing to change/)
+ expect(() => assertTopUp({ addCredits: 0n, expiresAt: null })).toThrow(/nothing to change/)
+ expect(() => assertTopUp({ addCredits: 1n, expiresAt: null })).not.toThrow()
+ expect(() => assertTopUp({ addCredits: null, expiresAt: 5 })).not.toThrow()
+ })
+})
+
+describe('isForgeBrowserKey', () => {
+ const bound = (type: string) => ({ toJSON: () => ({ $type: type, id: 'G6T1mjQZJ4pqjaraEw71RRSbVasd7JSbgsWfmLUgNhL2' }) })
+ const key = { purposeNumber: 0, securityLevelNumber: 2, contractBounds: bound('contractGroup'), totalBudget: 5n }
+ it('accepts an AUTHENTICATION / HIGH, group-bound, budgeted key', () => {
+ expect(isForgeBrowserKey(key)).toBe(true)
+ })
+ it('refuses the master key, other purposes, unbounded keys, other bounds and unbudgeted keys', () => {
+ expect(isForgeBrowserKey({ ...key, securityLevelNumber: 0 })).toBe(false)
+ expect(isForgeBrowserKey({ ...key, securityLevelNumber: 1 })).toBe(false)
+ expect(isForgeBrowserKey({ ...key, purposeNumber: 1 })).toBe(false)
+ expect(isForgeBrowserKey({ ...key, contractBounds: undefined })).toBe(false)
+ expect(isForgeBrowserKey({ ...key, contractBounds: bound('singleContract') })).toBe(false)
+ expect(isForgeBrowserKey({ ...key, totalBudget: undefined })).toBe(false)
+ })
+})
diff --git a/forge-web/lib/auth/limited-key.ts b/forge-web/lib/auth/limited-key.ts
index 9ba300904..1f4061dd8 100644
--- a/forge-web/lib/auth/limited-key.ts
+++ b/forge-web/lib/auth/limited-key.ts
@@ -215,12 +215,156 @@ export async function assertGroupHolds(sdk: EvoSDK, group: string, contracts: re
}
/**
- * A key Forge may renew over or revoke: HIGH, bound to a contract group, with a budget. Any
- * group, not just the current one, so a key left on an old group by a contract
+ * A key Forge may renew over, revoke or top up: AUTHENTICATION / HIGH, bound to a contract
+ * group, with a budget. Any group, not just the current one, so a key left on an old group by a contract
* re-registration can still be disabled.
*/
-function isForgeBrowserKey(k: WasmKey): boolean {
- return k.securityLevelNumber === 2 && k.contractBounds?.toJSON().$type === 'contractGroup' && k.totalBudget !== undefined
+export function isForgeBrowserKey(k: Pick): boolean {
+ return (
+ k.purposeNumber === 0 &&
+ k.securityLevelNumber === 2 &&
+ k.contractBounds?.toJSON().$type === 'contractGroup' &&
+ k.totalBudget !== undefined
+ )
+}
+
+/** The top-up defaults: +0.05 DASH, and an expiry pushed out to 90 days from now if sooner. */
+export const TOP_UP_DEFAULTS = { addDash: 0.05, days: 90 } as const
+/** The most one top-up adds (a typo guard, not a protocol limit). */
+export const TOP_UP_MAX_DASH = 10
+/** The latest expiry a top-up may set, in days from now (a browser key should not live for years). */
+export const TOP_UP_MAX_DAYS = 365
+
+/**
+ * Parse a DASH amount typed by a person into credits: a plain decimal, at most 11 decimal
+ * places (1 credit = 10⁻¹¹ DASH), above zero and at most {@link TOP_UP_MAX_DASH}. Exact: the
+ * digits are converted as integers, never through a float.
+ */
+export function parseDashAmount(input: string): bigint {
+ const s = input.trim()
+ const m = /^(\d{1,6})(?:\.(\d{1,11}))?$|^\.(\d{1,11})$/.exec(s)
+ if (m === null) throw new Error('enter an amount in DASH, like 0.05')
+ const whole = m[1] ?? '0'
+ const frac = (m[2] ?? m[3] ?? '').padEnd(11, '0')
+ const credits = BigInt(whole) * BigInt(CREDITS_PER_DASH) + BigInt(frac)
+ if (credits <= 0n) throw new Error('the amount must be more than 0')
+ if (credits > BigInt(TOP_UP_MAX_DASH * CREDITS_PER_DASH)) throw new Error(`at most ${TOP_UP_MAX_DASH} DASH per top-up`)
+ return credits
+}
+
+/**
+ * The expiry a top-up asks for: `wanted` when it is later than the key's current expiry, else
+ * none (the protocol refuses an expiry that is not later, and an unchanged one is not a
+ * change). `wanted` must be in the future and at most {@link TOP_UP_MAX_DAYS} days out.
+ */
+export function topUpExpiry(current: number | null, wanted: number | null, now = Date.now()): number | null {
+ if (wanted === null) return null
+ if (wanted <= now) throw new Error('the new expiry must be in the future')
+ if (wanted > now + TOP_UP_MAX_DAYS * DAY_MS) throw new Error(`the new expiry can be at most ${TOP_UP_MAX_DAYS} days from now`)
+ return current === null || wanted > current ? wanted : null
+}
+
+/** What a top-up will send: at least one of the two (the protocol requires one). */
+export interface TopUpRequest {
+ readonly addCredits: bigint | null
+ readonly expiresAt: number | null
+}
+
+/** Check a top-up request has something to do. */
+export function assertTopUp(req: TopUpRequest): void {
+ if ((req.addCredits === null || req.addCredits <= 0n) && req.expiresAt === null) {
+ throw new Error('nothing to change: add budget, or pick an expiry later than the current one')
+ }
+}
+
+/**
+ * The top-up was broadcast (or may have been), but its effect is not visible yet. Submitting
+ * again could add the budget twice: the caller re-reads instead of retrying.
+ */
+export class TopUpPendingError extends Error {
+ constructor(message = 'the update was sent, but the chain does not show the new limits yet') {
+ super(message)
+ this.name = 'TopUpPendingError'
+ }
+}
+
+/**
+ * Raise a Forge browser key's limits in place (`IdentityKeyLimitsUpdate`, protocol 14): add
+ * budget and/or push the expiry out. The key id and private key stay the same. Signed once by
+ * `masterWif` (checked to be a live MASTER key of the identity first), which is not retained.
+ * Refuses a key that is not a live Forge browser key ({@link isForgeBrowserKey}). Reads the
+ * key back from the chain and returns its limits.
+ */
+export async function topUpLimitedKey(
+ sdk: EvoSDK,
+ params: {
+ readonly network: Network
+ readonly identityId: string
+ readonly masterWif: string
+ readonly keyId: number
+ readonly request: TopUpRequest
+ },
+): Promise {
+ assertTopUp(params.request)
+ const { IdentitySigner, PrivateKey } = await import('@dashevo/evo-sdk')
+ const identity = await authSdk(sdk).identities.fetch(params.identityId)
+ const k = identity?.publicKeys.find((x) => x.keyId === params.keyId)
+ if (!identity || !k) throw new Error(`key ${params.keyId} is not on identity ${params.identityId}`)
+ if (k.disabledAt !== undefined) throw new Error(`key ${params.keyId} is disabled; renew instead`)
+ if (!isForgeBrowserKey(k)) throw new Error(`key ${params.keyId} is not a Forge browser key; refusing to change its limits here`)
+ const expiresAt = topUpExpiry(k.expiresAt === undefined ? null : Number(k.expiresAt), params.request.expiresAt)
+ const addBudget = params.request.addCredits !== null && params.request.addCredits > 0n ? params.request.addCredits : null
+ assertTopUp({ addCredits: addBudget, expiresAt })
+
+ let master: ReturnType | null = null
+ let signer: InstanceType | null = null
+ let sent = false
+ let landed: KeyLimits | null = null
+ try {
+ master = PrivateKey.fromWIF(params.masterWif)
+ signer = new IdentitySigner()
+ const bytes = master.toBytes()
+ const isMaster = identity.publicKeys.some(
+ (x) => x.securityLevelNumber === 0 && x.disabledAt === undefined && safeValidate(x, bytes, params.network),
+ )
+ bytes.fill(0)
+ if (!isMaster) throw new Error("that key is not this identity's master key")
+ signer.addKey(master)
+ sent = true
+ const updated = await authSdk(sdk).identities.updateKeyLimits({
+ identity,
+ keyId: params.keyId,
+ ...(addBudget !== null ? { addBudget } : {}),
+ ...(expiresAt !== null ? { expiresAt: BigInt(expiresAt) } : {}),
+ signer,
+ })
+ try {
+ if (updated.totalBudget !== undefined || updated.expiresAt !== undefined) {
+ landed = { remaining: null, total: updated.totalBudget ?? null, expiresAt: updated.expiresAt === undefined ? null : Number(updated.expiresAt) }
+ }
+ } finally {
+ updated.free()
+ }
+ } catch (e) {
+ // Past the broadcast, a failure may still have landed: never invite a second top-up.
+ if (sent) throw new TopUpPendingError(`the update may have been sent (${e instanceof Error ? e.message : String(e)}); check the key's limits before trying again`)
+ throw e
+ } finally {
+ signer?.free()
+ master?.free()
+ }
+ if (landed === null) throw new TopUpPendingError()
+
+ // Read it back until a node shows what the update returned (one a block behind shows the
+ // old limits for a moment); the remaining budget comes only from the chain read.
+ const want = landed
+ const limits = await retryWhileMissing(async () => {
+ const l = await readKeyLimits(sdk, params.identityId, params.keyId)
+ const ok = l !== null && l.total === want.total && l.expiresAt === want.expiresAt
+ return ok ? l : null
+ }, 6)
+ if (limits === null) throw new TopUpPendingError()
+ return limits
}
/**
@@ -239,13 +383,15 @@ export async function revokeLimitedKey(
if (!isForgeBrowserKey(k)) {
throw new Error(`key ${params.keyId} is not a Forge browser key; refusing to disable it here`)
}
- const master = PrivateKey.fromWIF(params.masterWif)
- const signer = new IdentitySigner()
+ let master: ReturnType | null = null
+ let signer: InstanceType | null = null
try {
+ master = PrivateKey.fromWIF(params.masterWif)
+ signer = new IdentitySigner()
signer.addKey(master)
await authSdk(sdk).identities.update({ identity, disablePublicKeys: [params.keyId], signer })
} finally {
- signer.free()
- master.free()
+ signer?.free()
+ master?.free()
}
}
diff --git a/forge-web/lib/idb.ts b/forge-web/lib/idb.ts
index b9b93a87c..def2802ac 100644
--- a/forge-web/lib/idb.ts
+++ b/forge-web/lib/idb.ts
@@ -2,16 +2,18 @@
* A minimal IndexedDB key-value layer: one database, a few object stores, promise-shaped.
*
* Holds the browser's local state that must survive a reload but never leaves the device:
- * the spend ledger, write journals (a repo creation interrupted half-way), and the key vault.
+ * the spend ledger, write journals (a repo creation interrupted half-way), the key vault, and
+ * the local notifications inbox (items, per-feed cursors, subscriptions).
* Every call is browser-only; outside a browser (SSR, vitest) the stores are in-memory maps,
* so the modules built on this stay testable without a fake IndexedDB.
*/
-export type StoreName = 'spend' | 'journal' | 'vault'
+export type StoreName = 'spend' | 'journal' | 'vault' | 'inbox'
const DB_NAME = 'dash-forge'
-const DB_VERSION = 1
-const STORES: readonly StoreName[] = ['spend', 'journal', 'vault']
+// Bump on every new store; the upgrade only ever adds stores (STORES stays additive).
+const DB_VERSION = 2
+const STORES: readonly StoreName[] = ['spend', 'journal', 'vault', 'inbox']
let dbPromise: Promise | null = null
const memory = new Map>()
@@ -29,7 +31,17 @@ function open(): Promise {
if (!req.result.objectStoreNames.contains(name)) req.result.createObjectStore(name)
}
}
- req.onsuccess = () => resolve(req.result)
+ // Another tab still holds the old version open: the upgrade waits on it forever.
+ req.onblocked = () => reject(new Error('Close other Dash Forge tabs to finish the update'))
+ req.onsuccess = () => {
+ const db = req.result
+ // A newer tab wants to upgrade: let go so it is not blocked, and reopen on next use.
+ db.onversionchange = () => {
+ db.close()
+ dbPromise = null
+ }
+ resolve(db)
+ }
req.onerror = () => reject(req.error ?? new Error('IndexedDB open failed'))
})
dbPromise.catch(() => {
diff --git a/forge-web/lib/sdk/cost.ts b/forge-web/lib/sdk/cost.ts
index cd471dc0c..6ba8fae17 100644
--- a/forge-web/lib/sdk/cost.ts
+++ b/forge-web/lib/sdk/cost.ts
@@ -66,6 +66,12 @@ export const DELETE_CREDITS: Readonly> = {
review: -20_000_000,
}
+/**
+ * An `IdentityKeyLimitsUpdate` (top up a key's budget / expiry), signed by the master key and
+ * paid from the identity balance. Measured on moutai (2026-09-26): 2,267,600 credits.
+ */
+export const KEY_LIMITS_UPDATE_CREDITS = 2_300_000
+
/** The fee a v1 token-admin action (mint / freeze / destroy) is estimated at. */
export const TOKEN_ADMIN_CREDITS = 15_000_000
diff --git a/forge-web/lib/sdk/facade.ts b/forge-web/lib/sdk/facade.ts
index da73cf878..ef88d5b11 100644
--- a/forge-web/lib/sdk/facade.ts
+++ b/forge-web/lib/sdk/facade.ts
@@ -4,7 +4,7 @@
* site free of `as unknown as` casts.
*/
-import type { EvoSDK } from '@dashevo/evo-sdk'
+import type { EvoSDK, IdentityKeyLimitsUpdateOptions, IdentityPublicKey } from '@dashevo/evo-sdk'
/** An identity public key, as the auth layer reads it. */
export interface WasmKey {
@@ -31,6 +31,11 @@ export interface AuthSdk {
update(options: unknown): Promise
create(options: unknown): Promise
keysRemainingBudgets(id: string, keyIds: number[]): Promise>
+ /**
+ * `IdentityKeyLimitsUpdate` (protocol 14): the key as it now stands. `identity` is the
+ * object `fetch` returned (the wasm Identity, narrowed here to {@link WasmIdentity}).
+ */
+ updateKeyLimits(options: Omit & { identity: WasmIdentity }): Promise
}
documents: { query(q: unknown): Promise> }
contracts: { fetch(id: string): Promise }
diff --git a/forge-web/lib/sdk/index.ts b/forge-web/lib/sdk/index.ts
index 44cb5e2f2..a977b49c7 100644
--- a/forge-web/lib/sdk/index.ts
+++ b/forge-web/lib/sdk/index.ts
@@ -38,6 +38,7 @@ export {
} from './write'
export {
CREDITS_PER_DASH,
+ KEY_LIMITS_UPDATE_CREDITS,
TOKEN_ADMIN_CREDITS,
creditsToDash,
previewCreate,
diff --git a/forge-web/lib/view/inbox.test.ts b/forge-web/lib/view/inbox.test.ts
new file mode 100644
index 000000000..1831070bb
--- /dev/null
+++ b/forge-web/lib/view/inbox.test.ts
@@ -0,0 +1,234 @@
+/**
+ * The local inbox, offline: feed planning and round-robin, cursors, item classification (never
+ * my own actions), the jump-box parser, mentions and the assignment fold.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { resetMemoryStores } from '../idb'
+import {
+ BACKFILL_MS,
+ DEFAULT_PREFS,
+ PAGE,
+ advanceCursor,
+ feedKey,
+ feedQuery,
+ initialCursor,
+ itemsToDrop,
+ loadItems,
+ markRead,
+ pickRound,
+ planFeeds,
+ stateWhat,
+ toItems,
+ type Feed,
+ type InboxItem,
+ type Subscriptions,
+ type ThreadSub,
+} from './inbox'
+import { assignedTargets, mentions } from './mine'
+import { parseJump } from './jump'
+import { idbPut } from '../idb'
+
+const ME = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD'
+const OTHER = 'Dd1m1JJM3M5DjBaXaCbC5hXBsU6248KHpGcBAtaHsqc7'
+const REPO = { id: '8H5JaQm8Z765UunuttoUuVsVMCmDoy2EBKgmGKYpdB2z', ownerId: ME, name: 'demo', private: false }
+const FORGE = { core: 'CORE', collab: 'COLLAB', group: 'GROUP' }
+
+const thread = (over: Partial = {}): ThreadSub => ({
+ id: 'CR1u2SvFB97NvTF5zoqtYjjP4t2M5PyKEgFqPkKVThZP',
+ kind: 'pull',
+ number: 7,
+ title: 'Fix it',
+ repo: REPO,
+ reason: 'author',
+ since: 1000,
+ ...over,
+})
+
+const subs = (over: Partial = {}): Subscriptions => ({
+ at: 0,
+ repos: [{ repo: REPO, reason: 'owner' }],
+ threads: [thread()],
+ droppedRepos: 0,
+ droppedThreads: 0,
+ ...over,
+})
+
+describe('planFeeds', () => {
+ it('reads threads, their repos state feed, and my repos new-item feeds', () => {
+ const keys = planFeeds(subs(), DEFAULT_PREFS).map(feedKey)
+ expect(keys).toEqual([
+ `comments:${thread().id}`,
+ `reviews:${thread().id}`,
+ `state:event:${REPO.id}`,
+ `state:authorEvent:${REPO.id}`,
+ `new:issue:${REPO.id}`,
+ `new:patch:${REPO.id}`,
+ ])
+ })
+ it('reads reviews only on PRs I opened, stars and pushes only when opted in', () => {
+ const starred = { repo: { ...REPO, id: 'S' }, reason: 'starred' as const }
+ const s = subs({ repos: [{ repo: REPO, reason: 'owner' }, starred], threads: [thread({ reason: 'commented' }), thread({ id: 'I', kind: 'issue' })] })
+ const off = planFeeds(s, DEFAULT_PREFS).map(feedKey)
+ expect(off.filter((k) => k.startsWith('reviews:'))).toEqual([])
+ expect(off.some((k) => k.endsWith(':S'))).toBe(false)
+ expect(off.some((k) => k.startsWith('push:'))).toBe(false)
+ const on = planFeeds(s, { stars: true, pushes: true }).map(feedKey)
+ expect(on).toContain('new:issue:S')
+ expect(on).toContain(`push:refUpdate:${REPO.id}`)
+ expect(on).toContain('push:protectedRefUpdate:S')
+ })
+})
+
+describe('pickRound', () => {
+ it('takes everything when under budget', () => {
+ expect(pickRound([1, 2, 3], 5, 4)).toEqual({ round: [1, 2, 3], next: 0 })
+ })
+ it('round-robins with wrap-around so every feed is read in turn', () => {
+ const feeds = [0, 1, 2, 3, 4]
+ const a = pickRound(feeds, 0, 2)
+ const b = pickRound(feeds, a.next, 2)
+ const c = pickRound(feeds, b.next, 2)
+ expect([a.round, b.round, c.round]).toEqual([
+ [0, 1],
+ [2, 3],
+ [4, 0],
+ ])
+ })
+})
+
+describe('cursors', () => {
+ it('starts a thread feed where I joined, others a week before the feed was first watched', () => {
+ const seen = 10 * BACKFILL_MS
+ expect(initialCursor({ kind: 'comments', thread: thread({ since: seen - 5 }) }, seen)).toEqual({ at: seen - 5 })
+ expect(initialCursor({ kind: 'comments', thread: thread({ since: 0 }) }, seen)).toEqual({ at: seen - BACKFILL_MS })
+ expect(initialCursor({ kind: 'new', type: 'issue', repo: REPO }, seen)).toEqual({ at: seen - BACKFILL_MS })
+ })
+ it('moves to the last row on a short page, and keeps its id on a full one', () => {
+ const row = (at: number, i = at) => ({ at, id: `id${i}` })
+ expect(advanceCursor({ at: 5 }, [])).toEqual({ at: 5 })
+ expect(advanceCursor({ at: 5 }, [row(6), row(9)])).toEqual({ at: 9 })
+ const full = Array.from({ length: PAGE }, (_, i) => row(100 + i))
+ expect(advanceCursor({ at: 5 }, full)).toEqual({ at: 100 + PAGE - 1, afterId: `id${100 + PAGE - 1}` })
+ // A full page from one busy block: continue inside the block, after its last id.
+ const block = Array.from({ length: PAGE }, (_, i) => row(50, i))
+ expect(advanceCursor({ at: 5 }, block)).toEqual({ at: 50, afterId: `id${PAGE - 1}` })
+ })
+ it('queries past the cursor on the right index', () => {
+ const q = feedQuery(FORGE, { kind: 'comments', thread: thread() }, { at: 42 })
+ expect(q).toMatchObject({ dataContractId: 'COLLAB', documentTypeName: 'comment', orderBy: [['$createdAt', 'asc']], limit: PAGE })
+ expect(q.where).toEqual([['targetId', '==', thread().id], ['$createdAt', '>', 42]])
+ expect(q.startAfter).toBeUndefined()
+ const inBlock = feedQuery(FORGE, { kind: 'comments', thread: thread() }, { at: 42, afterId: 'X' })
+ expect(inBlock.where?.[1]).toEqual(['$createdAt', '>=', 42])
+ expect(inBlock.startAfter).toBe('X')
+ expect(feedQuery(FORGE, { kind: 'push', type: 'refUpdate', repo: REPO }, { at: 1 }).dataContractId).toBe('CORE')
+ expect(feedQuery(FORGE, { kind: 'reviews', thread: thread() }, { at: 1 }).where?.[0]).toEqual(['patchId', '==', thread().id])
+ })
+})
+
+describe('toItems', () => {
+ const doc = (owner: string, at: number, extra: Record = {}): Record => ({ $id: `d${at}`, $ownerId: owner, $createdAt: at, ...extra })
+
+ it('never notifies me of my own actions', () => {
+ const f: Feed = { kind: 'comments', thread: thread() }
+ expect(toItems(f, [doc(ME, 2000, { targetId: thread().id })], ME)).toEqual([])
+ expect(toItems(f, [doc(OTHER, 2000, { targetId: thread().id })], ME)).toHaveLength(1)
+ })
+ it('turns new issues and PRs in my repos into items with their number and title', () => {
+ const f: Feed = { kind: 'new', type: 'patch', repo: REPO }
+ const [item] = toItems(f, [doc(OTHER, 5, { repoId: REPO.id, number: 3, title: 'Add X' })], ME)
+ expect(item).toMatchObject({ kind: 'pull', what: 'opened a pull request', target: { kind: 'pull', number: 3, title: 'Add X' }, actor: OTHER, read: false })
+ })
+ it('reports state changes only on my threads, after I joined', () => {
+ const t = thread({ since: 100 })
+ const f: Feed = { kind: 'state', type: 'event', repo: REPO, threads: [t] }
+ const items = toItems(
+ f,
+ [
+ doc(OTHER, 50, { targetId: t.id, kind: 1 }),
+ doc(OTHER, 150, { targetId: t.id, kind: 3 }),
+ doc(OTHER, 160, { targetId: 'someone-elses-thread', kind: 1 }),
+ doc(OTHER, 170, { targetId: t.id, kind: 4, value: 'bug' }),
+ doc(ME, 180, { targetId: t.id, kind: 2 }),
+ ],
+ ME,
+ )
+ expect(items.map((i) => i.what)).toEqual(['marked merged', 'labelled bug'])
+ })
+ it('names review verdicts and pushes', () => {
+ const reviews = toItems({ kind: 'reviews', thread: thread() }, [doc(OTHER, 5, { verdict: 1 }), doc(OTHER, 6, { verdict: 2 })], ME)
+ expect(reviews.map((i) => i.what)).toEqual(['approved', 'requested changes'])
+ const push = toItems({ kind: 'push', type: 'refUpdate', repo: REPO }, [doc(OTHER, 5, { refName: 'refs/heads/main' })], ME)
+ expect(push[0]?.what).toBe('pushed to main')
+ })
+ it('drops documents that do not parse instead of casting them', () => {
+ expect(toItems({ kind: 'new', type: 'issue', repo: REPO }, [{ $id: 'x', $ownerId: OTHER }], ME)).toEqual([])
+ })
+})
+
+describe('stateWhat', () => {
+ it('says who was assigned', () => {
+ expect(stateWhat(6, ME, ME)).toBe('assigned you')
+ expect(stateWhat(6, OTHER, ME)).toBe('assigned someone')
+ expect(stateWhat(99, undefined, ME)).toBeNull()
+ })
+})
+
+describe('inbox state', () => {
+ beforeEach(() => resetMemoryStores())
+ const item = (id: string, at: number, read = false): InboxItem => ({ id, kind: 'comment', repo: REPO, what: 'commented', actor: OTHER, at, read })
+
+ it('marks one, then all, read; per identity', async () => {
+ for (const it of [item('a', 1), item('b', 2)]) await idbPut('inbox', `devnet:${ME}:item:${it.id}`, it)
+ await idbPut('inbox', `devnet:${OTHER}:item:z`, item('z', 3))
+ await markRead('devnet', ME, ['a'])
+ expect((await loadItems('devnet', ME)).map((i) => [i.id, i.read])).toEqual([
+ ['b', false],
+ ['a', true],
+ ])
+ await markRead('devnet', ME)
+ expect((await loadItems('devnet', ME)).every((i) => i.read)).toBe(true)
+ expect((await loadItems('devnet', OTHER))[0]?.read).toBe(false)
+ })
+ it('drops the oldest read items first when over the cap', () => {
+ expect(itemsToDrop([item('new', 3), item('oldRead', 1, true), item('oldUnread', 0)], 2)).toEqual(['oldRead'])
+ expect(itemsToDrop([item('a', 1)], 2)).toEqual([])
+ })
+})
+
+describe('mentions and assignments (bounded scans)', () => {
+ it('finds @name and the identity id, not look-alikes', () => {
+ expect(mentions('ping @alice please', ME, 'alice.dash')).toBe(true)
+ expect(mentions('@Alice: see this', ME, 'alice.dash')).toBe(true)
+ expect(mentions('mail me at x@alice.dash', ME, 'alice.dash')).toBe(false)
+ expect(mentions('@alicedev here', ME, 'alice.dash')).toBe(false)
+ expect(mentions(`cc ${ME}`, ME, null)).toBe(true)
+ expect(mentions(undefined, ME, 'alice')).toBe(false)
+ })
+ it('folds assign and unassign in ($createdAt, $id) order', () => {
+ const ev = (targetId: string, kind: number, value: string, at: number, id = `e${at}`) => ({ $id: id, targetId, kind, value, $createdAt: at })
+ const got = assignedTargets([ev('t1', 6, ME, 1), ev('t2', 6, ME, 2), ev('t2', 7, ME, 3), ev('t3', 6, OTHER, 4), ev('t1', 7, OTHER, 5)], ME)
+ expect([...got]).toEqual(['t1'])
+ // Same block: ($createdAt, $id) decides, whatever the input order.
+ expect([...assignedTargets([ev('t4', 7, ME, 9, 'B'), ev('t4', 6, ME, 9, 'A')], ME)]).toEqual([])
+ expect([...assignedTargets([ev('t4', 6, ME, 9, 'B'), ev('t4', 7, ME, 9, 'A')], ME)]).toEqual(['t4'])
+ })
+})
+
+describe('parseJump', () => {
+ it('reads owner/name, owner/name#n, @name and #n', () => {
+ expect(parseJump('alice/project', false)).toEqual({ kind: 'repo', owner: 'alice', name: 'project' })
+ expect(parseJump('@alice/project#12', false)).toEqual({ kind: 'repo', owner: 'alice', name: 'project', number: 12 })
+ expect(parseJump('@alice', false)).toEqual({ kind: 'profile', name: 'alice' })
+ expect(parseJump(ME, false)).toEqual({ kind: 'profile', name: ME })
+ expect(parseJump(' #42 ', true)).toEqual({ kind: 'number', number: 42 })
+ expect(parseJump('', true)).toBeNull()
+ })
+ it('explains #n outside a repo and junk', () => {
+ expect(parseJump('#3', false)).toMatchObject({ kind: 'invalid' })
+ expect(parseJump('a b', false)).toMatchObject({ kind: 'invalid' })
+ expect(parseJump('a/b/c', false)).toMatchObject({ kind: 'invalid' })
+ })
+})
diff --git a/forge-web/lib/view/inbox.ts b/forge-web/lib/view/inbox.ts
new file mode 100644
index 000000000..b1ad93ce8
--- /dev/null
+++ b/forge-web/lib/view/inbox.ts
@@ -0,0 +1,521 @@
+/**
+ * The local notifications inbox (`ux-dx-spec.md` §5.10). Computed in this browser from the
+ * chain; nothing is sent anywhere, and there is no email, push or cross-device sync.
+ *
+ * **Subscriptions** (recomputed every {@link SUBS_TTL_MS}): repos I own or belong to (`repo` by
+ * `$ownerId`, `maintainer`/`writer` by `memberId`), repos I starred (opt-in, `star.byOwner`),
+ * and the issues and PRs I opened (`issue`/`patch` `author`) or commented on (`comment.author`
+ * → `targetId`). Both sets are capped ({@link MAX_REPOS}, {@link MAX_THREADS}), newest first.
+ *
+ * **Feeds**, one proof-checked query each, `$createdAt > cursor` ascending, {@link PAGE} rows:
+ * - my repos: new issues and PRs (`issue`/`patch` `created`), pushes (opt-in, the reflogs);
+ * - repos holding my threads: state changes on those threads (`event`/`authorEvent` `feed`);
+ * - each thread: comments (`comment.target`); each PR I opened: reviews (`review.patch`).
+ * A poll runs at most {@link ROUND_BUDGET} feeds, round-robin, so a big watch list is spread
+ * over several minutes instead of bursting DAPI. My own documents never become items.
+ *
+ * State (items, per-feed cursors, subscriptions, prefs) lives in the IndexedDB `inbox` store,
+ * keyed `::…`, so two identities on one device never mix.
+ */
+
+import type { EvoSDK } from '@dashevo/evo-sdk'
+import { z } from 'zod'
+
+import type { Network } from '../constants'
+import type { ForgeIds } from '../deployments'
+import { idbDelete, idbEntries, idbGet, idbPut } from '../idb'
+import { DOC } from '../repo/contract'
+import { queryDocumentsWithProof, type DocumentQuery, type PlainDocument } from '../sdk'
+import { listReposByOwner } from './discovery'
+import {
+ baseDoc,
+ eventDoc,
+ int,
+ listMyCommentTargets,
+ listMyTargets,
+ listStarredRepoIds,
+ parseDocs,
+ readReposByIds,
+ readTargetsByIds,
+ repoLite,
+ targetDoc,
+ titleOf,
+ type RepoLite,
+ type TargetRow,
+} from './mine'
+
+/** The empty-state sentence (spec §5.10, verbatim). */
+export const INBOX_EMPTY = 'Notifications are computed in this browser from the chain. Nothing is sent to you; nothing leaves your device.'
+
+/** Poll interval while a tab is open and visible. */
+export const POLL_MS = 60_000
+/** How long a computed subscription set is reused. */
+export const SUBS_TTL_MS = 15 * 60_000
+export const MAX_REPOS = 20
+export const MAX_THREADS = 30
+/** Feeds read per poll. */
+export const ROUND_BUDGET = 12
+/** Rows per feed query. */
+export const PAGE = 20
+/** On first sight a feed reaches back this far, so a new inbox is not empty for no reason. */
+export const BACKFILL_MS = 7 * 24 * 60 * 60_000
+/** Items kept; the oldest read ones go first. */
+export const MAX_ITEMS = 300
+
+export type RepoReason = 'owner' | 'maintainer' | 'writer' | 'starred'
+
+export interface RepoSub {
+ readonly repo: RepoLite
+ readonly reason: RepoReason
+}
+
+export interface ThreadSub {
+ readonly id: string
+ readonly kind: 'issue' | 'pull'
+ readonly number: number
+ readonly title: string
+ readonly repo: RepoLite
+ readonly reason: 'author' | 'commented'
+ /** When I joined the thread: activity before it is not news to me. */
+ readonly since: number
+}
+
+export interface Subscriptions {
+ readonly at: number
+ readonly repos: RepoSub[]
+ readonly threads: ThreadSub[]
+ /** How many were left out by the caps. */
+ readonly droppedRepos: number
+ readonly droppedThreads: number
+ /**
+ * Sources that could not be read (or only partly), in words, e.g. "comments you wrote".
+ * What they would have added is not watched this time; the next recompute retries.
+ */
+ readonly incomplete?: readonly string[]
+}
+
+export interface InboxPrefs {
+ /** Watch starred repos too (new issues and PRs; pushes when `pushes` is on). */
+ readonly stars: boolean
+ /** Report pushes to the repos I watch. */
+ readonly pushes: boolean
+}
+
+export const DEFAULT_PREFS: InboxPrefs = { stars: false, pushes: false }
+
+export type ItemKind = 'issue' | 'pull' | 'comment' | 'state' | 'review' | 'push'
+
+/** One notification. `id` is the document it came from, so a re-read never duplicates it. */
+export interface InboxItem {
+ readonly id: string
+ readonly kind: ItemKind
+ readonly repo: RepoLite
+ /** The issue or PR it is about (absent for pushes). */
+ readonly target?: { readonly kind: 'issue' | 'pull'; readonly number: number; readonly title: string }
+ /** What happened, in a few words ("closed", "approved", "pushed to main"). */
+ readonly what: string
+ readonly actor: string
+ readonly at: number
+ readonly read: boolean
+}
+
+// ---------------------------------------------------------------------------
+// Feeds (pure)
+// ---------------------------------------------------------------------------
+
+export type Feed =
+ | { readonly kind: 'new'; readonly type: 'issue' | 'patch'; readonly repo: RepoLite }
+ | { readonly kind: 'push'; readonly type: 'refUpdate' | 'protectedRefUpdate'; readonly repo: RepoLite }
+ | { readonly kind: 'state'; readonly type: 'event' | 'authorEvent'; readonly repo: RepoLite; readonly threads: readonly ThreadSub[] }
+ | { readonly kind: 'comments'; readonly thread: ThreadSub }
+ | { readonly kind: 'reviews'; readonly thread: ThreadSub }
+
+/** A feed's stable cursor key. */
+export function feedKey(f: Feed): string {
+ switch (f.kind) {
+ case 'new':
+ case 'push':
+ case 'state':
+ return `${f.kind}:${f.type}:${f.repo.id}`
+ case 'comments':
+ case 'reviews':
+ return `${f.kind}:${f.thread.id}`
+ }
+}
+
+/** Every feed a subscription set implies, threads first (they are the most personal). */
+export function planFeeds(subs: Subscriptions, prefs: InboxPrefs): Feed[] {
+ const feeds: Feed[] = []
+ for (const t of subs.threads) {
+ feeds.push({ kind: 'comments', thread: t })
+ if (t.kind === 'pull' && t.reason === 'author') feeds.push({ kind: 'reviews', thread: t })
+ }
+ const threadsByRepo = new Map()
+ for (const t of subs.threads) threadsByRepo.set(t.repo.id, [...(threadsByRepo.get(t.repo.id) ?? []), t])
+ for (const [, threads] of threadsByRepo) {
+ const repo = threads[0]!.repo
+ feeds.push({ kind: 'state', type: 'event', repo, threads }, { kind: 'state', type: 'authorEvent', repo, threads })
+ }
+ for (const { repo, reason } of subs.repos) {
+ if (reason === 'starred' && !prefs.stars) continue
+ feeds.push({ kind: 'new', type: 'issue', repo }, { kind: 'new', type: 'patch', repo })
+ if (prefs.pushes) feeds.push({ kind: 'push', type: 'refUpdate', repo }, { kind: 'push', type: 'protectedRefUpdate', repo })
+ }
+ return feeds
+}
+
+/** This round's feeds: `budget` of them from `offset`, wrapping; and the next offset. */
+export function pickRound(feeds: readonly T[], offset: number, budget = ROUND_BUDGET): { round: T[]; next: number } {
+ if (feeds.length <= budget) return { round: [...feeds], next: 0 }
+ const start = offset % feeds.length
+ const round = Array.from({ length: budget }, (_, i) => feeds[(start + i) % feeds.length] as T)
+ return { round, next: (start + budget) % feeds.length }
+}
+
+/**
+ * Where a feed has read to: every document up to `at` (ms), and, when a page ended inside one
+ * block, also the documents at `at` up to and including `afterId` (index order).
+ */
+export interface Cursor {
+ readonly at: number
+ readonly afterId?: string
+}
+
+/**
+ * Where a feed starts the first time it is read: a week before the feed was first watched
+ * (not before the inbox started), so a repo added months later does not flood the inbox with
+ * its history. Thread feeds never start before I joined the thread.
+ */
+export function initialCursor(f: Feed, firstSeen: number): Cursor {
+ const floor = firstSeen - BACKFILL_MS
+ return { at: f.kind === 'comments' || f.kind === 'reviews' ? Math.max(floor, f.thread.since) : floor }
+}
+
+/**
+ * The cursor after reading a page (ascending `($createdAt, $id)`, past `prev`, `limit` rows).
+ * A short page read everything so far: the cursor is its last timestamp. A full page may have
+ * stopped inside a block, so the cursor keeps the last `$id` too and the next read continues
+ * after it at the same timestamp: nothing of a busy block is skipped or read twice.
+ */
+export function advanceCursor(prev: Cursor, page: readonly { at: number; id: string }[], limit = PAGE): Cursor {
+ const last = page[page.length - 1]
+ if (last === undefined) return prev
+ return page.length < limit ? { at: last.at } : { at: last.at, afterId: last.id }
+}
+
+/** The query for a feed after `cursor`. */
+export function feedQuery(forge: ForgeIds, f: Feed, cursor: Cursor): DocumentQuery {
+ const after = cursor.afterId === undefined ? (['$createdAt', '>', cursor.at] as const) : (['$createdAt', '>=', cursor.at] as const)
+ const shape = { orderBy: [['$createdAt', 'asc'] as const], limit: PAGE, ...(cursor.afterId === undefined ? {} : { startAfter: cursor.afterId }) }
+ switch (f.kind) {
+ case 'new':
+ case 'state':
+ return { dataContractId: forge.collab, documentTypeName: f.type, where: [['repoId', '==', f.repo.id], after], ...shape }
+ case 'push':
+ return { dataContractId: forge.core, documentTypeName: f.type, where: [['repoId', '==', f.repo.id], after], ...shape }
+ case 'comments':
+ return { dataContractId: forge.collab, documentTypeName: DOC.comment, where: [['targetId', '==', f.thread.id], after], ...shape }
+ case 'reviews':
+ return { dataContractId: forge.collab, documentTypeName: DOC.review, where: [['patchId', '==', f.thread.id], after], ...shape }
+ }
+}
+
+/** A stored cursor (an earlier build stored a bare timestamp). */
+function asCursor(v: unknown): Cursor | undefined {
+ if (typeof v === 'number') return { at: v }
+ if (typeof v === 'object' && v !== null && typeof (v as Cursor).at === 'number') {
+ const afterId = (v as Cursor).afterId
+ return typeof afterId === 'string' ? { at: (v as Cursor).at, afterId } : { at: (v as Cursor).at }
+ }
+ return undefined
+}
+
+const reviewDoc = baseDoc.extend({ verdict: int })
+const refDoc = baseDoc.extend({ refName: z.string().optional().catch(undefined) })
+
+/** What an `event` / `authorEvent` kind means to a reader of the inbox. */
+export function stateWhat(kind: number, value: string | undefined, me: string): string | null {
+ switch (kind) {
+ case 1:
+ return 'closed'
+ case 2:
+ return 'reopened'
+ case 3:
+ return 'marked merged'
+ case 4:
+ return value ? `labelled ${value}` : 'labelled'
+ case 5:
+ return value ? `removed label ${value}` : 'removed a label'
+ case 6:
+ return value === me ? 'assigned you' : 'assigned someone'
+ case 7:
+ return value === me ? 'unassigned you' : 'unassigned someone'
+ case 8:
+ return 'retargeted'
+ case 9:
+ return 'marked draft'
+ case 10:
+ return 'marked ready for review'
+ default:
+ return null
+ }
+}
+
+const VERDICT_WHAT: Readonly> = { 1: 'approved', 2: 'requested changes', 3: 'reviewed' }
+
+function shortRef(name: string | undefined): string {
+ if (!name) return 'a branch'
+ return name.replace(/^refs\/(heads|tags)\//, '')
+}
+
+/** The items a feed's documents make. Never my own; never before I joined a thread. */
+export function toItems(f: Feed, docs: readonly PlainDocument[], me: string): InboxItem[] {
+ const item = (d: { $id: string; $ownerId: string; $createdAt: number }, rest: Pick & Partial): InboxItem => ({
+ id: d.$id,
+ actor: d.$ownerId,
+ at: d.$createdAt,
+ read: false,
+ ...rest,
+ })
+ const notMine = (d: T): boolean => d.$ownerId !== me
+ switch (f.kind) {
+ case 'new': {
+ const kind = f.type === 'issue' ? 'issue' : 'pull'
+ return parseDocs(targetDoc, docs)
+ .filter(notMine)
+ .map((d) => item(d, { kind, repo: f.repo, what: kind === 'issue' ? 'opened an issue' : 'opened a pull request', target: { kind, number: d.number, title: titleOf(d) } }))
+ }
+ case 'push':
+ return parseDocs(refDoc, docs)
+ .filter(notMine)
+ .map((d) => item(d, { kind: 'push', repo: f.repo, what: `pushed to ${shortRef(d.refName)}` }))
+ case 'state': {
+ const threads = new Map(f.threads.map((t) => [t.id, t]))
+ return parseDocs(eventDoc, docs).flatMap((d) => {
+ const t = threads.get(d.targetId)
+ const what = stateWhat(d.kind, d.value, me)
+ if (!t || what === null || !notMine(d) || d.$createdAt <= t.since) return []
+ return [item(d, { kind: 'state', repo: t.repo, what, target: { kind: t.kind, number: t.number, title: t.title } })]
+ })
+ }
+ case 'comments':
+ case 'reviews': {
+ const t = f.thread
+ const target = { kind: t.kind, number: t.number, title: t.title }
+ if (f.kind === 'comments') {
+ return parseDocs(baseDoc, docs)
+ .filter((d) => notMine(d) && d.$createdAt > t.since)
+ .map((d) => item(d, { kind: 'comment', repo: t.repo, what: 'commented', target }))
+ }
+ return parseDocs(reviewDoc, docs)
+ .filter(notMine)
+ .map((d) => item(d, { kind: 'review', repo: t.repo, what: VERDICT_WHAT[d.verdict] ?? 'reviewed', target }))
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Subscriptions (chain reads)
+// ---------------------------------------------------------------------------
+
+const EMPTY_PAGE: { rows: never[]; more: boolean } = { rows: [], more: false }
+
+function threadOf(t: TargetRow, repo: RepoLite, reason: ThreadSub['reason'], since: number): ThreadSub {
+ return { id: t.id, kind: t.kind, number: t.number, title: t.title, repo, reason, since }
+}
+
+/** Read what `me` is subscribed to. Each source fails alone; all failing is an error. */
+export async function computeSubscriptions(
+ sdk: EvoSDK,
+ network: Network,
+ forge: ForgeIds,
+ me: string,
+ prefs: InboxPrefs,
+ now = Date.now(),
+): Promise {
+ const settled = await Promise.allSettled([
+ listReposByOwner(sdk, me, { network }),
+ prefs.stars ? listStarredRepoIds(sdk, forge, me) : Promise.resolve(EMPTY_PAGE),
+ listMyTargets(sdk, forge, me, 'issue'),
+ listMyTargets(sdk, forge, me, 'pull'),
+ listMyCommentTargets(sdk, forge, me),
+ ] as const)
+ // Only sources actually read count: stars are skipped (not read) when the preference is off.
+ const read = settled.filter((_, i) => i !== 1 || prefs.stars)
+ if (read.every((r) => r.status === 'rejected')) throw (read[0] as PromiseRejectedResult).reason
+ const [owned, starred, issues, pulls, commented] = settled
+ const ok = (r: PromiseSettledResult, fallback: T): T => (r.status === 'fulfilled' ? r.value : fallback)
+
+ const repoSubs: RepoSub[] = []
+ const seen = new Set()
+ const addRepo = (repo: RepoLite, reason: RepoReason): void => {
+ if (seen.has(repo.id)) return
+ seen.add(repo.id)
+ repoSubs.push({ repo, reason })
+ }
+ const mine = ok(owned, { owned: [], member: [] })
+ for (const r of mine.owned) if (r.kind === 'v2') addRepo(repoLite(r), 'owner')
+ for (const r of mine.member) addRepo(repoLite(r), r.role ?? 'writer')
+ const starIds = ok(starred, EMPTY_PAGE).rows.filter((id) => !seen.has(id))
+ const commentedTargets = ok(commented, [])
+ const myIssues = ok(issues, EMPTY_PAGE)
+ const myPulls = ok(pulls, EMPTY_PAGE)
+ const authored = [...myIssues.rows, ...myPulls.rows]
+ const authoredIds = new Set(authored.map((t) => t.id))
+ const incomplete: string[] = []
+ const labels = ['repos you own or belong to', 'your stars', 'issues you opened', 'pull requests you opened', 'comments you wrote'] as const
+ settled.forEach((r, i) => {
+ if (r.status === 'rejected') incomplete.push(labels[i] ?? 'a source')
+ })
+ if (myIssues.more) incomplete.push('issues you opened (more than the first 500)')
+ if (myPulls.more) incomplete.push('pull requests you opened (more than the first 500)')
+ const commentedRows = await readTargetsByIds(sdk, forge, commentedTargets.map((c) => c.targetId).filter((id) => !authoredIds.has(id))).catch(() => {
+ incomplete.push('the threads you commented on')
+ return new Map()
+ })
+
+ // Repo rows for stars and for threads whose repo is not one of mine.
+ const needed = [...starIds, ...authored.map((t) => t.repoId), ...[...commentedRows.values()].map((t) => t.repoId)].filter((id) => !seen.has(id))
+ const extra = await readReposByIds(sdk, forge, needed).catch(() => {
+ incomplete.push('the repos of your threads and stars')
+ return new Map()
+ })
+ for (const id of starIds) {
+ const repo = extra.get(id)
+ if (repo) addRepo(repo, 'starred')
+ }
+ const repoById = new Map([...repoSubs.map((s) => [s.repo.id, s.repo] as const), ...extra])
+
+ const threads: ThreadSub[] = []
+ for (const t of authored) {
+ const repo = t.repo ?? repoById.get(t.repoId)
+ if (repo) threads.push(threadOf(t, repo, 'author', t.createdAt))
+ }
+ for (const c of commentedTargets) {
+ const t = commentedRows.get(c.targetId)
+ const repo = t ? repoById.get(t.repoId) : undefined
+ if (t && repo) threads.push(threadOf(t, repo, 'commented', c.firstAt))
+ }
+ threads.sort((a, b) => b.since - a.since)
+ return {
+ at: now,
+ repos: repoSubs.slice(0, MAX_REPOS),
+ threads: threads.slice(0, MAX_THREADS),
+ droppedRepos: Math.max(0, repoSubs.length - MAX_REPOS),
+ droppedThreads: Math.max(0, threads.length - MAX_THREADS),
+ ...(incomplete.length > 0 ? { incomplete } : {}),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Local state (IndexedDB `inbox` store)
+// ---------------------------------------------------------------------------
+
+function prefix(network: Network, me: string): string {
+ return `${network}:${me}:`
+}
+
+export async function loadItems(network: Network, me: string): Promise {
+ const rows = await idbEntries('inbox', `${prefix(network, me)}item:`)
+ return rows.map(([, v]) => v).sort((a, b) => b.at - a.at)
+}
+
+export async function loadPrefs(network: Network, me: string): Promise {
+ return { ...DEFAULT_PREFS, ...((await idbGet('inbox', `${prefix(network, me)}prefs`)) ?? {}) }
+}
+
+export async function savePrefs(network: Network, me: string, prefs: InboxPrefs): Promise {
+ await idbPut('inbox', `${prefix(network, me)}prefs`, prefs)
+ // A different watch set: recompute on the next poll.
+ await idbDelete('inbox', `${prefix(network, me)}subs`)
+}
+
+export async function loadSubs(network: Network, me: string): Promise {
+ return idbGet('inbox', `${prefix(network, me)}subs`)
+}
+
+/** Mark items read (all unread ones when `ids` is omitted). */
+export async function markRead(network: Network, me: string, ids?: readonly string[]): Promise {
+ const want = ids === undefined ? null : new Set(ids)
+ for (const item of await loadItems(network, me)) {
+ if (!item.read && (want === null || want.has(item.id))) {
+ await idbPut('inbox', `${prefix(network, me)}item:${item.id}`, { ...item, read: true })
+ }
+ }
+}
+
+/** Which items to drop to stay within `max`: the oldest read ones, then the oldest. */
+export function itemsToDrop(items: readonly InboxItem[], max = MAX_ITEMS): string[] {
+ if (items.length <= max) return []
+ const oldestFirst = [...items].sort((a, b) => Number(b.read) - Number(a.read) || a.at - b.at)
+ return oldestFirst.slice(0, items.length - max).map((i) => i.id)
+}
+
+/** What one poll did. */
+export interface PollResult {
+ readonly added: number
+ readonly feedsRead: number
+ readonly feedsTotal: number
+ readonly failed: number
+ readonly subs: Subscriptions
+}
+
+const roundOffsets = new Map()
+
+/**
+ * One poll: (re)compute subscriptions when stale, read this round's feeds past their cursors,
+ * store new items and advance the cursors. A feed that fails keeps its cursor and is retried
+ * next round.
+ */
+export async function pollOnce(
+ sdk: EvoSDK,
+ network: Network,
+ forge: ForgeIds,
+ me: string,
+ opts: { now?: number; refreshSubs?: boolean } = {},
+): Promise {
+ const now = opts.now ?? Date.now()
+ const p = prefix(network, me)
+ const prefs = await loadPrefs(network, me)
+ let subs = await loadSubs(network, me)
+ if (subs === undefined || opts.refreshSubs || now - subs.at > SUBS_TTL_MS) {
+ subs = await computeSubscriptions(sdk, network, forge, me, prefs, now)
+ await idbPut('inbox', `${p}subs`, subs)
+ }
+ const feeds = planFeeds(subs, prefs)
+ // When each feed was first watched (planned, not first read: a round may reach it minutes
+ // later). One record for all feeds; only feeds still watched are kept.
+ const seenBefore = (await idbGet>('inbox', `${p}seen`)) ?? {}
+ const seen: Record = {}
+ for (const f of feeds) seen[feedKey(f)] = seenBefore[feedKey(f)] ?? now
+ await idbPut('inbox', `${p}seen`, seen)
+ const { round, next } = pickRound(feeds, roundOffsets.get(p) ?? 0)
+ roundOffsets.set(p, next)
+
+ const existing = new Set((await loadItems(network, me)).map((i) => i.id))
+ let added = 0
+ let failed = 0
+ for (const f of round) {
+ const key = `${p}cursor:${feedKey(f)}`
+ const cursor = asCursor(await idbGet('inbox', key)) ?? initialCursor(f, seen[feedKey(f)] ?? now)
+ let docs: PlainDocument[]
+ try {
+ docs = (await queryDocumentsWithProof(sdk, feedQuery(forge, f, cursor))).documents
+ } catch {
+ failed++
+ continue
+ }
+ for (const it of toItems(f, docs, me)) {
+ if (existing.has(it.id)) continue
+ existing.add(it.id)
+ await idbPut('inbox', `${p}item:${it.id}`, it)
+ added++
+ }
+ const page = parseDocs(baseDoc, docs).map((d) => ({ at: d.$createdAt, id: d.$id }))
+ await idbPut('inbox', key, advanceCursor(cursor, page))
+ }
+ if (added > 0) {
+ for (const id of itemsToDrop(await loadItems(network, me))) await idbDelete('inbox', `${p}item:${id}`)
+ }
+ return { added, feedsRead: round.length - failed, feedsTotal: feeds.length, failed, subs }
+}
diff --git a/forge-web/lib/view/jump.ts b/forge-web/lib/view/jump.ts
new file mode 100644
index 000000000..962f23fe3
--- /dev/null
+++ b/forge-web/lib/view/jump.ts
@@ -0,0 +1,48 @@
+/**
+ * The header jump box (`ux-dx-spec.md` §5.2, §5.11): `owner/name`, `owner/name#n`, `@name`
+ * (or a bare name / identity id), and `#n` inside a repo, which opens issue or PR n of it.
+ */
+
+import type { EvoSDK } from '@dashevo/evo-sdk'
+
+import { DOC, repoSource, type RepoRef } from '../repo'
+import { queryDocumentsWithProof } from '../sdk'
+
+export type Jump =
+ | { readonly kind: 'repo'; readonly owner: string; readonly name: string; readonly number?: number }
+ | { readonly kind: 'number'; readonly number: number }
+ | { readonly kind: 'profile'; readonly name: string }
+ | { readonly kind: 'invalid'; readonly message: string }
+
+const NUMBER = /^#(\d{1,10})$/
+const REPO = /^@?([^\s/#@]+)\/([^\s/#]+?)(?:#(\d{1,10}))?$/
+const PROFILE = /^@?([^\s/#@]+)$/
+
+/** Parse what was typed. `inRepo`: the page is a repo page, so `#n` has a repo to mean. */
+export function parseJump(input: string, inRepo: boolean): Jump | null {
+ const q = input.trim()
+ if (q === '') return null
+ const n = NUMBER.exec(q)
+ if (n) {
+ if (!inRepo) return { kind: 'invalid', message: '#n works inside a repo; try owner/name#n' }
+ return { kind: 'number', number: Number(n[1]) }
+ }
+ const r = REPO.exec(q)
+ if (r) {
+ const owner = r[1] ?? ''
+ return r[3] === undefined ? { kind: 'repo', owner, name: r[2] ?? '' } : { kind: 'repo', owner, name: r[2] ?? '', number: Number(r[3]) }
+ }
+ const p = PROFILE.exec(q)
+ if (p) return { kind: 'profile', name: p[1] ?? '' }
+ return { kind: 'invalid', message: 'type owner/name, @name, or #n inside a repo' }
+}
+
+/** Which of issue n and PR n exist in `repo` (a `(repoId, number)` lookup each). */
+export async function numberTargets(sdk: EvoSDK, repo: RepoRef, number: number): Promise<{ issue: boolean; pull: boolean }> {
+ const exists = async (type: string): Promise => {
+ const { documents } = await queryDocumentsWithProof(sdk, repoSource(repo).repoQuery(type, { where: [['number', '==', number]], limit: 1 }))
+ return documents.length > 0
+ }
+ const [issue, pull] = await Promise.all([exists(DOC.issue), exists(DOC.patch)])
+ return { issue, pull }
+}
diff --git a/forge-web/lib/view/mine.ts b/forge-web/lib/view/mine.ts
new file mode 100644
index 000000000..a3473aa9d
--- /dev/null
+++ b/forge-web/lib/view/mine.ts
@@ -0,0 +1,398 @@
+/**
+ * Cross-repo "mine" reads (`ux-dx-spec.md` §5.10, §5.11): what one identity authored, starred
+ * or belongs to, across every forge-v2 repo. Only what an index proves is read:
+ *
+ * - issues / PRs I opened: `issue.author` / `patch.author` = `($ownerId, repoId, number)`, so
+ * `$ownerId ==` alone walks every repo (index prefix), ordered `(repoId, number)`;
+ * - threads I commented on: `comment.author` = `($ownerId, $createdAt)`, newest first;
+ * - stars: `star.byOwner` (`indexOnly`, no `$createdAt`: index order, no star time);
+ * - repo rows for all of these: `repo` by `$id in` (one query per 100 ids).
+ *
+ * Not indexable and so never claimed complete: releases across repos (`release` indexes lead
+ * with `repoId`), assignments (an `event` with kind assign and a value, indexed by repo and
+ * target, not by assignee) and mentions (free text). {@link scanAssignedAndMentions} computes
+ * those over a bounded set of repos the caller already watches.
+ *
+ * Documents are parsed with zod here, at the trust boundary; nothing downstream casts.
+ */
+
+import type { EvoSDK } from '@dashevo/evo-sdk'
+import { z } from 'zod'
+
+import type { ForgeIds } from '../deployments'
+import { DOC, V2_DOC, asIdentifierString } from '../repo/contract'
+import { queryDocumentsWithProof, type DocumentQuery, type PlainDocument } from '../sdk'
+import type { DiscoveredRepo } from './discovery'
+import { mapPooled } from './pool'
+import { compareStrings } from '../rules'
+
+/** A base58 identifier field (identifiers come back base58 or base64; both normalize). */
+export const ident = z.unknown().transform(asIdentifierString).pipe(z.string().min(1))
+/** A content integer (number from `toJSON`, bigint from `toObject`). */
+export const int = z.union([z.number(), z.bigint()]).transform(Number)
+const text = z.string().optional().catch(undefined)
+
+/** The fields of a forge document every reader here needs. */
+export const baseDoc = z.object({ $id: z.string().min(1), $ownerId: z.string().min(1), $createdAt: z.number() })
+
+/** An `issue` or `patch` row. */
+export const targetDoc = baseDoc.extend({ repoId: ident, number: int, title: text, body: text, enc: z.unknown().optional() })
+export type TargetDoc = z.infer
+
+/** A `repo` row. */
+const repoDoc = baseDoc.extend({ name: z.string().min(1), visibility: z.string().optional() })
+
+/** Parse every document that fits `schema`; drop (never cast) the rest. */
+export function parseDocs(schema: z.ZodType, docs: readonly PlainDocument[]): T[] {
+ const out: T[] = []
+ for (const d of docs) {
+ const r = schema.safeParse(d)
+ if (r.success) out.push(r.data)
+ }
+ return out
+}
+
+async function read(sdk: EvoSDK, q: DocumentQuery): Promise {
+ return (await queryDocumentsWithProof(sdk, q)).documents
+}
+
+/** A repo as the cross-repo lists link to it. */
+export interface RepoLite {
+ readonly id: string
+ readonly ownerId: string
+ readonly name: string
+ readonly private: boolean
+}
+
+/** A discovery row as the cross-repo lists link to it. */
+export function repoLite(r: DiscoveredRepo): RepoLite {
+ return { id: r.key, ownerId: r.ownerId, name: r.slug, private: r.visibility === 'private' }
+}
+
+/** The `$id in` batch size: Platform caps an `in` list and a page at 100. */
+const IN_MAX = 100
+
+function chunks(xs: readonly T[], n: number): T[][] {
+ const out: T[][] = []
+ for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n))
+ return out
+}
+
+/** `repo` rows by id (missing ids are simply absent from the map). */
+export async function readReposByIds(sdk: EvoSDK, forge: ForgeIds, ids: readonly string[]): Promise> {
+ const unique = [...new Set(ids.filter((id) => id !== ''))]
+ const out = new Map()
+ for (const batch of chunks(unique, IN_MAX)) {
+ const docs = await read(sdk, {
+ dataContractId: forge.core,
+ documentTypeName: V2_DOC.repo,
+ where: [['$id', 'in', batch]],
+ limit: batch.length,
+ })
+ for (const d of parseDocs(repoDoc, docs)) {
+ out.set(d.$id, { id: d.$id, ownerId: d.$ownerId, name: d.name, private: d.visibility === 'private' })
+ }
+ }
+ return out
+}
+
+/** An issue or PR, with its repo when that resolved. */
+export interface TargetRow {
+ readonly id: string
+ readonly kind: 'issue' | 'pull'
+ readonly repoId: string
+ readonly number: number
+ readonly title: string
+ readonly author: string
+ readonly createdAt: number
+ readonly repo: RepoLite | null
+}
+
+/** A row's title; a private repo's ciphertext says so rather than showing nothing. */
+export function titleOf(d: TargetDoc): string {
+ if (d.title) return d.title
+ return d.enc != null ? 'Encrypted (not readable here)' : '(untitled)'
+}
+
+/** A page that may have been cut short: `more` says a full page came back. */
+export interface Page {
+ readonly rows: T[]
+ readonly more: boolean
+}
+
+/** How many of my issues (or PRs) are read at most; past it the list says it is partial. */
+export const MY_TARGETS_MAX = 500
+
+/**
+ * Issues (`kind: 'issue'`) or PRs I opened, in every repo, newest first. The `author` index
+ * (`$ownerId` prefix) is ordered by `(repoId, number)`, not by time, so "newest first" needs
+ * all of them: it is paged (`startAfter`) up to `max`. `more` is true when that cap was hit,
+ * so the caller says the list is partial instead of implying completeness.
+ */
+export async function listMyTargets(
+ sdk: EvoSDK,
+ forge: ForgeIds,
+ me: string,
+ kind: 'issue' | 'pull',
+ max = MY_TARGETS_MAX,
+): Promise> {
+ const raw: PlainDocument[] = []
+ let startAfter: string | undefined
+ let more = false
+ while (raw.length < max) {
+ const page = await read(sdk, {
+ dataContractId: forge.collab,
+ documentTypeName: kind === 'issue' ? DOC.issue : DOC.patch,
+ where: [['$ownerId', '==', me]],
+ orderBy: [
+ ['repoId', 'asc'],
+ ['number', 'asc'],
+ ],
+ limit: IN_MAX,
+ ...(startAfter === undefined ? {} : { startAfter }),
+ })
+ raw.push(...page)
+ const last = page[page.length - 1]?.['$id']
+ if (page.length < IN_MAX || typeof last !== 'string') break
+ startAfter = last
+ more = raw.length >= max
+ }
+ const docs = parseDocs(targetDoc, raw)
+ const repos = await readReposByIds(sdk, forge, docs.map((d) => d.repoId))
+ const rows = docs
+ .map((d) => ({
+ id: d.$id,
+ kind,
+ repoId: d.repoId,
+ number: d.number,
+ title: titleOf(d),
+ author: d.$ownerId,
+ createdAt: d.$createdAt,
+ repo: repos.get(d.repoId) ?? null,
+ }))
+ .sort((a, b) => b.createdAt - a.createdAt)
+ return { rows, more }
+}
+
+const commentDoc = baseDoc.extend({ repoId: ident, targetId: ident })
+
+/** A thread I commented on: the target, its repo, and my first comment there (in the page). */
+export interface CommentedTarget {
+ readonly targetId: string
+ readonly repoId: string
+ readonly firstAt: number
+}
+
+/** The threads of my newest comments (`comment.author`, `$createdAt` descending). */
+export async function listMyCommentTargets(sdk: EvoSDK, forge: ForgeIds, me: string, limit = IN_MAX): Promise {
+ const docs = parseDocs(
+ commentDoc,
+ await read(sdk, {
+ dataContractId: forge.collab,
+ documentTypeName: DOC.comment,
+ where: [['$ownerId', '==', me]],
+ orderBy: [['$createdAt', 'desc']],
+ limit,
+ }),
+ )
+ const byTarget = new Map()
+ for (const d of docs) {
+ const prev = byTarget.get(d.targetId)
+ if (prev === undefined || d.$createdAt < prev.firstAt) {
+ byTarget.set(d.targetId, { targetId: d.targetId, repoId: d.repoId, firstAt: d.$createdAt })
+ }
+ }
+ return [...byTarget.values()]
+}
+
+/** `issue` / `patch` rows by id, each tagged with the type it was found in. */
+export async function readTargetsByIds(sdk: EvoSDK, forge: ForgeIds, ids: readonly string[]): Promise> {
+ const out = new Map()
+ const unique = [...new Set(ids)]
+ for (const kind of ['issue', 'pull'] as const) {
+ for (const batch of chunks(unique.filter((id) => !out.has(id)), IN_MAX)) {
+ const docs = parseDocs(
+ targetDoc,
+ await read(sdk, {
+ dataContractId: forge.collab,
+ documentTypeName: kind === 'issue' ? DOC.issue : DOC.patch,
+ where: [['$id', 'in', batch]],
+ limit: batch.length,
+ }),
+ )
+ for (const d of docs) {
+ out.set(d.$id, {
+ id: d.$id,
+ kind,
+ repoId: d.repoId,
+ number: d.number,
+ title: titleOf(d),
+ author: d.$ownerId,
+ createdAt: d.$createdAt,
+ repo: null,
+ })
+ }
+ }
+ }
+ return out
+}
+
+const starDoc = z.object({ repoId: ident })
+
+/** The repos I starred (`star.byOwner`; index order, and a star records no time). */
+export async function listStarredRepoIds(sdk: EvoSDK, forge: ForgeIds, me: string, limit = IN_MAX): Promise> {
+ const docs = await read(sdk, {
+ dataContractId: forge.collab,
+ documentTypeName: V2_DOC.star,
+ where: [['$ownerId', '==', me]],
+ limit,
+ })
+ return { rows: parseDocs(starDoc, docs).map((d) => d.repoId), more: docs.length >= limit }
+}
+
+/** A release, for the Explore "Recently released" row. */
+export interface ReleaseRow {
+ readonly repo: RepoLite
+ readonly tagName: string
+ readonly name: string
+ readonly createdAt: number
+}
+
+const releaseDoc = baseDoc.extend({ tagName: z.string().min(1), name: text })
+
+/** A scan over several repos: what it found, and how many repos could not be read. */
+export interface Scan {
+ readonly rows: T[]
+ /** Repos whose read failed: the rows cover the others only. */
+ readonly failed: number
+ readonly total: number
+}
+
+/**
+ * Read `fn` for every repo, `concurrency` at a time, counting failures instead of turning them
+ * into empty answers. Every repo failing (with at least one repo) is an error.
+ */
+async function perRepo(repos: readonly RepoLite[], concurrency: number, fn: (repo: RepoLite) => Promise): Promise<{ ok: T[]; failed: number }> {
+ let lastError: unknown = null
+ const results = await mapPooled(repos, concurrency, (repo) =>
+ fn(repo).then(
+ (v) => ({ v }),
+ (e: unknown) => {
+ lastError = e
+ return null
+ },
+ ),
+ )
+ const ok = results.filter((r): r is { v: Awaited } => r !== null).map((r) => r.v)
+ const failed = results.length - ok.length
+ if (repos.length > 0 && ok.length === 0) throw lastError instanceof Error ? lastError : new Error('no repo could be read')
+ return { ok, failed }
+}
+
+/**
+ * The newest release of each of `repos` (`release.created` = `(repoId, $createdAt)`, one query
+ * per repo, 4 at a time), newest first. There is no cross-repo release index, so this only
+ * sees the repos passed in; the caller says so, and says how many could not be read.
+ */
+export async function latestReleases(sdk: EvoSDK, forge: ForgeIds, repos: readonly RepoLite[]): Promise> {
+ const { ok, failed } = await perRepo(repos, 4, async (repo) => {
+ const docs = await read(sdk, {
+ dataContractId: forge.core,
+ documentTypeName: DOC.release,
+ where: [['repoId', '==', repo.id]],
+ orderBy: [['$createdAt', 'desc']],
+ limit: 1,
+ })
+ const d = parseDocs(releaseDoc, docs)[0]
+ return d ? { repo, tagName: d.tagName, name: d.name ?? '', createdAt: d.$createdAt } : null
+ })
+ const rows = ok.filter((r): r is ReleaseRow => r !== null).sort((a, b) => b.createdAt - a.createdAt)
+ return { rows, failed, total: repos.length }
+}
+
+/** Whether `body` mentions `@name` (DPNS label, case-insensitive) or the identity id. */
+export function mentions(body: string | undefined, me: string, name: string | null): boolean {
+ if (!body) return false
+ if (body.includes(me)) return true
+ if (name === null || name === '') return false
+ const label = name.split('.')[0] ?? ''
+ if (label === '') return false
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ return new RegExp(`(^|[^\\w@])@${escaped}(?![\\w-])`, 'i').test(body)
+}
+
+/** An `event` / `authorEvent` row (`value` only on label / assign kinds). */
+export const eventDoc = baseDoc.extend({ targetId: ident, kind: int, value: z.string().optional().catch(undefined) })
+
+/** Assign (6) and unassign (7): `event.kind` codes (data-contracts §2.3). */
+const ASSIGN = 6
+const UNASSIGN = 7
+
+/**
+ * Fold assign / unassign events (oldest first) into the targets `me` is assigned to now.
+ * Pure; the events must be the complete window being judged.
+ */
+export function assignedTargets(events: readonly { $id: string; targetId: string; kind: number; value?: string; $createdAt: number }[], me: string): Set {
+ const assigned = new Set()
+ // The fold order is ($createdAt, $id), by code point (forge-v2.md §3), as the issue fold.
+ const ordered = [...events].sort((a, b) => a.$createdAt - b.$createdAt || compareStrings(a.$id, b.$id))
+ for (const e of ordered) {
+ if (e.value !== me) continue
+ if (e.kind === ASSIGN) assigned.add(e.targetId)
+ else if (e.kind === UNASSIGN) assigned.delete(e.targetId)
+ }
+ return assigned
+}
+
+/** What {@link scanAssignedAndMentions} found, and over how much it looked. */
+export interface AssignedScan {
+ readonly assigned: TargetRow[]
+ readonly mentioned: TargetRow[]
+ readonly reposScanned: number
+ /** Repos whose activity could not be read. */
+ readonly failed: number
+}
+
+/**
+ * Issues and PRs assigned to me or mentioning me, **within the newest activity of `repos`**
+ * only: per repo, the newest 100 member `event`s and the newest 30 issues and 30 PRs. Mentions
+ * are looked for in issue and PR descriptions only, not in comments. Neither question has an
+ * index, so this is a bounded scan the caller must present as one.
+ */
+export async function scanAssignedAndMentions(
+ sdk: EvoSDK,
+ forge: ForgeIds,
+ me: string,
+ name: string | null,
+ repos: readonly RepoLite[],
+): Promise {
+ const { ok: scanned, failed } = await perRepo(repos, 3, async (repo) => {
+ const feed = (type: string, limit: number): Promise =>
+ read(sdk, {
+ dataContractId: forge.collab,
+ documentTypeName: type,
+ where: [['repoId', '==', repo.id]],
+ orderBy: [['$createdAt', 'desc']],
+ limit,
+ })
+ const [events, issues, patches] = await Promise.all([feed(DOC.event, 100), feed(DOC.issue, 30), feed(DOC.patch, 30)])
+ const mentioned = (docs: PlainDocument[], kind: 'issue' | 'pull'): TargetRow[] =>
+ parseDocs(targetDoc, docs)
+ .filter((d) => d.$ownerId !== me && mentions(d.body, me, name))
+ .map((d) => ({ id: d.$id, kind, repoId: repo.id, number: d.number, title: titleOf(d), author: d.$ownerId, createdAt: d.$createdAt, repo }))
+ return {
+ assignedIds: [...assignedTargets(parseDocs(eventDoc, events), me)],
+ mentioned: [...mentioned(issues, 'issue'), ...mentioned(patches, 'pull')],
+ repo,
+ }
+ })
+ const repoOf = new Map(scanned.map((r) => [r.repo.id, r.repo]))
+ const assignedRows = await readTargetsByIds(sdk, forge, scanned.flatMap((r) => r.assignedIds))
+ const newestFirst = (a: TargetRow, b: TargetRow): number => b.createdAt - a.createdAt
+ return {
+ assigned: [...assignedRows.values()].map((t) => ({ ...t, repo: repoOf.get(t.repoId) ?? null })).sort(newestFirst),
+ mentioned: scanned.flatMap((r) => r.mentioned).sort(newestFirst),
+ reposScanned: repos.length,
+ failed,
+ }
+}