From 3ae3fdd15c22a647bd616b3e8251614ab7d3e6fe Mon Sep 17 00:00:00 2001 From: lin1er Date: Tue, 20 Oct 2026 10:41:42 +0700 Subject: [PATCH 1/9] feat(#17): front end relay client behind proveRevenue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit proveRevenue now uses the #17 relay when NEXT_PUBLIC_RELAY_URL and NEXT_PUBLIC_GOOGLE_CLIENT_ID are set. The creator signs in with Google's own popup (Identity Services token client, adsense.readonly only), the token and the wallet's G… go once to POST /proofs, and the job is polled until it answers with request_advance's arguments. No Reclaim SDK runs in the browser. Stages keep their meaning: waiting while Google's popup is open, reading from the relay job until it ends. Closing the popup, or allowing without the AdSense scope, is ReclaimCancelledError, as closing the window was. Reopening waits on the newest popup. An abandoned session stops polling and never settles. Relay failures carry the relay's code. Three new prove failures say whose move it is: googleSignIn (sign in again), noAdsense, relayFailed. The mock is unchanged while NEXT_PUBLIC_RELAY_URL is empty. --- fe/.env.example | 7 +- fe/ARCHITECTURE.md | 4 +- fe/README.md | 9 +- fe/src/lib/errors.test.ts | 3 + fe/src/lib/errors.ts | 25 ++- fe/src/lib/reclaim/index.test.ts | 3 +- fe/src/lib/reclaim/index.ts | 22 ++- fe/src/lib/reclaim/relay.test.ts | 128 ++++++++++++ fe/src/lib/reclaim/relay.ts | 186 ++++++++++++++++++ fe/src/lib/reclaim/session.ts | 27 ++- .../advance/components/FailurePanel.tsx | 11 ++ fe/src/modules/advance/failures.test.ts | 7 +- fe/src/modules/advance/failures.ts | 7 +- 13 files changed, 417 insertions(+), 22 deletions(-) create mode 100644 fe/src/lib/reclaim/relay.test.ts create mode 100644 fe/src/lib/reclaim/relay.ts diff --git a/fe/.env.example b/fe/.env.example index 0e44fc4..9c1778d 100644 --- a/fe/.env.example +++ b/fe/.env.example @@ -15,9 +15,12 @@ NEXT_PUBLIC_USDC_ASSET= # The backend API from #16. Its /config must report the same addresses as above. NEXT_PUBLIC_API_URL= -# The proof relay from #17. While empty, proving revenue runs on a mock (src/lib/reclaim/mock.ts) whose -# proofs the real contract refuses. Only the e2e RPC stub accepts them. +# The proof relay from #17 (the same server as the API; see docs/api.md). While empty, proving revenue runs +# on a mock (src/lib/reclaim/mock.ts) whose proofs the real contract refuses. Only the e2e RPC stub accepts them. NEXT_PUBLIC_RELAY_URL= +# Google OAuth client id (type "Web application") for the AdSense sign-in popup. Its authorized JavaScript +# origins must list this front end's origins. Public by design; the client secret is never used here. +NEXT_PUBLIC_GOOGLE_CLIENT_ID= # WalletConnect, for mobile wallets. From the Reown dashboard. NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= diff --git a/fe/ARCHITECTURE.md b/fe/ARCHITECTURE.md index bf796db..af5957e 100644 --- a/fe/ARCHITECTURE.md +++ b/fe/ARCHITECTURE.md @@ -113,8 +113,8 @@ Deliberately left out: - **Animation libraries.** CSS transitions cover what the design needs (§7). - **vaul.** Mobile sheets start as a Base UI dialog styled as a sheet. Add vaul only if swipe to dismiss turns out to matter, after checking it is still maintained. -- **A Reclaim browser SDK, for now.** Which one depends on how the #17 relay is built. Ask - @Lin1er before installing anything. +- **A Reclaim browser SDK.** The #17 relay makes the proof with zkFetch; the browser only signs in + with Google Identity Services, loaded as Google's script, not a package (`lib/reclaim/relay.ts`). ## 4. State diff --git a/fe/README.md b/fe/README.md index 7f222f9..0e780d4 100644 --- a/fe/README.md +++ b/fe/README.md @@ -60,10 +60,13 @@ browser. Never put a secret in one. - **`NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID`** is only needed for mobile wallets. Without it, desktop browser wallets still work. -## Proving revenue is mocked until #17 +## Proving revenue: the relay, or a mock -The Reclaim session and the proof relay (#17) do not exist yet, so `src/lib/reclaim/` answers from a -mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and +With `NEXT_PUBLIC_RELAY_URL` and `NEXT_PUBLIC_GOOGLE_CLIENT_ID` set, the creator signs in with Google's +own popup (`adsense.readonly` only) and the #17 relay makes the proof, which takes about ten minutes +(`src/lib/reclaim/relay.ts`, `docs/api.md`). No Reclaim SDK runs in the browser. + +`src/lib/reclaim/` answers from a mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and returns fixed values. Everything after it, the offer from `quote`, the proof check, `request_advance` and the receipt, is the real contract client. On testnet the contract refuses the mock's proof, so the whole flow only completes in the e2e run, against the stubbed RPC. diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index fc87891..4f4e56b 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -123,6 +123,9 @@ describe("proveFailureCopy", () => { "walletWrongNetwork", "walletNoAnswer", "relayNotReady", + "googleSignIn", + "noAdsense", + "relayFailed", ]; it("keeps every failure inside the copy rules, and never says Something went wrong", () => { diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index bbb9072..1c15110 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -209,7 +209,10 @@ export function contractFailureCopy(code: number): FailureCopy { * - `simulationFailed`: Stellar answered, but could not run the request, with no contract code to say why. * - `notConfigured`: this build is missing an address it needs, so nothing reached the network. * - `walletLocked`, `walletWrongNetwork`, `walletNoAnswer`: the wallet could not sign, for that reason. - * - `relayNotReady`: proofs are meant to come from the #17 relay, and its client is not built yet. + * - `relayNotReady`: proofs are meant to come from the #17 relay, and this build cannot reach it. + * - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one. + * - `noAdsense`: the Google account has no approved AdSense account the relay can read. + * - `relayFailed`: the relay could not make the proof (busy, or failed on its side). Nothing was saved. */ export type ProveFailure = | "cancelled" @@ -225,7 +228,10 @@ export type ProveFailure = | "walletLocked" | "walletWrongNetwork" | "walletNoAnswer" - | "relayNotReady"; + | "relayNotReady" + | "googleSignIn" + | "noAdsense" + | "relayFailed"; export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): FailureCopy { switch (kind) { @@ -303,6 +309,21 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): title: "Proving revenue is not open yet", body: "Forepay cannot read AdSense revenue yet. Try again later.", }; + case "googleSignIn": + return { + title: "Google did not let us read AdSense", + body: "Sign in again and allow Forepay to see your AdSense reports. Nothing was saved.", + }; + case "noAdsense": + return { + title: "We found no approved AdSense account", + body: "Sign in with the Google account that owns an approved AdSense account, then try again.", + }; + case "relayFailed": + return { + title: "We could not finish your proof", + body: "Nothing was saved or charged. Try again in a few minutes.", + }; } } diff --git a/fe/src/lib/reclaim/index.test.ts b/fe/src/lib/reclaim/index.test.ts index 90d373b..b1ad6e0 100644 --- a/fe/src/lib/reclaim/index.test.ts +++ b/fe/src/lib/reclaim/index.test.ts @@ -15,8 +15,9 @@ describe("proveRevenue", () => { session.abandon(); }); - it("says the relay is not ready rather than pretending, once a relay URL is set", async () => { + it("says the relay is not ready rather than pretending, when the Google client id is missing", async () => { vi.stubEnv("NEXT_PUBLIC_RELAY_URL", "https://relay.example"); + vi.stubEnv("NEXT_PUBLIC_GOOGLE_CLIENT_ID", ""); const { proveRevenue, RelayNotReadyError } = await import("./index"); await expect(proveRevenue("GA6H", () => {}).result).rejects.toBeInstanceOf(RelayNotReadyError); }); diff --git a/fe/src/lib/reclaim/index.ts b/fe/src/lib/reclaim/index.ts index 7db4ef4..65a67af 100644 --- a/fe/src/lib/reclaim/index.ts +++ b/fe/src/lib/reclaim/index.ts @@ -1,20 +1,30 @@ /** - * Proving AdSense revenue with Reclaim, and getting back the attested values `request_advance` takes + * Proving AdSense revenue, and getting back the attested values `request_advance` takes * (ARCHITECTURE.md §2, `lib/reclaim/`). The seam between the app and the #17 relay. * - * The Reclaim session and the relay do not exist yet (#17), and which Reclaim SDK runs in the browser - * depends on how the relay is built (ARCHITECTURE.md §3), so none is installed. Until - * NEXT_PUBLIC_RELAY_URL is set, a mock walks through the same stages with realistic delays and + * With NEXT_PUBLIC_RELAY_URL and NEXT_PUBLIC_GOOGLE_CLIENT_ID set, the creator signs in with Google's + * own popup and the relay makes the proof (`relay.ts`). No Reclaim SDK runs in the browser. While + * NEXT_PUBLIC_RELAY_URL is empty, a mock walks through the same stages with realistic delays and * returns fixed values. Everything after this seam (quote, request_advance, signing, errors) is real. */ import { mockProveRevenue } from "./mock"; +import { googleSignIn, relayProveRevenue } from "./relay"; import { RelayNotReadyError, type ProveSession, type ProveStage } from "./session"; -export { ReclaimCancelledError, RelayNotReadyError, type ProveSession, type ProveStage } from "./session"; +export { + ReclaimCancelledError, + RelayError, + RelayNotReadyError, + type ProveSession, + type ProveStage, + type RelayErrorCode, +} from "./session"; const RELAY_URL = process.env.NEXT_PUBLIC_RELAY_URL ?? ""; +const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? ""; export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => void): ProveSession { if (!RELAY_URL) return mockProveRevenue(borrower, onStage); - return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; + if (!GOOGLE_CLIENT_ID) return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; + return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID) }); } diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts new file mode 100644 index 0000000..da3ab13 --- /dev/null +++ b/fe/src/lib/reclaim/relay.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import { relayProveRevenue, type SignIn } from "./relay"; +import { ReclaimCancelledError, RelayError, type ProveStage } from "./session"; + +const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2"; +const REQUEST = { + revenueUsd: "1234.56", + pubId: "pub-1234567890123456", + windowStart: "2026-07-01", + windowEnd: "2026-09-30", + timestampS: "1792467390", + epoch: "1", + signature: "ab".repeat(64), + recoveryId: 1, +}; + +/** A relay that answers POST /proofs, then `polls` job states in turn. */ +function relay(polls: object[], post: { status: number; body: object } = { status: 202, body: { id: "j1", stage: "queued" } }) { + const calls: { url: string; init?: RequestInit }[] = []; + let i = 0; + const fetch = (async (url: string, init?: RequestInit) => { + calls.push({ url, init }); + if (init?.method === "POST") return new Response(JSON.stringify(post.body), { status: post.status }); + return new Response(JSON.stringify(polls[Math.min(i++, polls.length - 1)])); + }) as unknown as typeof globalThis.fetch; + return { fetch, calls }; +} + +const signedIn: SignIn = async () => "ya29.token"; +const noSleep = async () => {}; + +describe("relayProveRevenue", () => { + it("signs in, hands the relay the borrower and the token, and returns request_advance's arguments", async () => { + const r = relay([{ id: "j1", stage: "proving" }, { id: "j1", stage: "done", request: REQUEST }]); + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { + relayUrl: "https://relay.example/", + signIn: signedIn, + fetch: r.fetch, + sleep: noSleep, + }); + const req = await s.result; + expect(stages).toEqual(["waiting", "reading"]); + expect(req).toEqual({ ...REQUEST, timestampS: 1792467390n, epoch: 1n }); + expect(r.calls[0].url).toBe("https://relay.example/proofs"); + expect(JSON.parse(String(r.calls[0].init?.body))).toEqual({ borrower: BORROWER, accessToken: "ya29.token" }); + expect(r.calls.slice(1).map((c) => c.url)).toEqual(["https://relay.example/proofs/j1", "https://relay.example/proofs/j1"]); + }); + + it("closing Google's popup is the same as closing the AdSense window", async () => { + const r = relay([]); + const s = relayProveRevenue(BORROWER, () => {}, { + relayUrl: "https://relay.example", + signIn: async () => { + throw new ReclaimCancelledError(); + }, + fetch: r.fetch, + sleep: noSleep, + }); + await expect(s.result).rejects.toBeInstanceOf(ReclaimCancelledError); + expect(r.calls).toEqual([]); + }); + + it("a failed job keeps the relay's code", async () => { + const r = relay([{ id: "j1", stage: "failed", error: { code: "account", message: "not READY" } }]); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("account"); + }); + + it("a busy relay or one already proving for this wallet is busy", async () => { + for (const status of [409, 503]) { + const r = relay([], { status, body: { error: "busy" } }); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep }); + expect(((await s.result.catch((x) => x)) as RelayError).code).toBe("busy"); + } + }); + + it("opening the window again waits on the newest popup, and an older one closing does not end it", async () => { + let n = 0; + const releases: ((t: string) => void)[] = []; + const rejects: ((e: unknown) => void)[] = []; + const signIn: SignIn = () => + new Promise((res, rej) => { + n++; + releases.push(res); + rejects.push(rej); + }); + const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch: r.fetch, sleep: noSleep }); + s.reopen(); + expect(n).toBe(2); + rejects[0](new ReclaimCancelledError()); + releases[1]("ya29.second"); + await s.result; + expect(stages).toEqual(["waiting", "waiting", "reading"]); + expect(JSON.parse(String(r.calls[0].init?.body)).accessToken).toBe("ya29.second"); + }); + + it("an abandoned session stops polling and never settles", async () => { + let polls = 0; + const fetch = (async (_url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j1", stage: "queued" }), { status: 202 }); + polls++; + return new Response(JSON.stringify({ id: "j1", stage: "proving" })); + }) as unknown as typeof globalThis.fetch; + let wake!: () => void; + const s = relayProveRevenue(BORROWER, () => {}, { + relayUrl: "https://r", + signIn: signedIn, + fetch, + sleep: () => new Promise((r) => (wake = r)), + }); + let settled = false; + s.result.then( + () => (settled = true), + () => (settled = true), + ); + await new Promise((r) => setTimeout(r, 0)); + s.abandon(); + wake(); + await new Promise((r) => setTimeout(r, 0)); + expect(polls).toBe(0); + expect(settled).toBe(false); + }); +}); diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts new file mode 100644 index 0000000..6a1d988 --- /dev/null +++ b/fe/src/lib/reclaim/relay.ts @@ -0,0 +1,186 @@ +/** + * The real session (#17): Google's own sign-in popup for a read-only AdSense token, then the relay + * proves the revenue with zkFetch and answers with `request_advance`'s arguments. The relay's API is in + * docs/api.md, "The proof relay". + * + * No Reclaim SDK runs here. The proof is made on the relay because the engine Reclaim's attestor accepts + * needs ~330 MB of circuit files and about ten minutes of CPU. The browser's part is the sign-in, and + * the token goes once to the relay, which binds the borrower's G… inside the signed claim. + * + * Stages: `waiting` while Google's popup is open, `reading` from the moment the relay has the job until + * it ends. + */ +import type { AdvanceRequest } from "@/lib/stellar/contract"; +import { ReclaimCancelledError, RelayError, type ProveSession, type ProveStage, type RelayErrorCode } from "./session"; + +export const ADSENSE_SCOPE = "https://www.googleapis.com/auth/adsense.readonly"; +const GIS_SRC = "https://accounts.google.com/gsi/client"; + +/** The slice of Google Identity Services' token client used here. */ +type TokenResponse = { access_token?: string; error?: string; scope?: string }; +type TokenClient = { requestAccessToken: (o?: { prompt?: string }) => void }; +type Gis = { + initTokenClient: (config: { + client_id: string; + scope: string; + callback: (r: TokenResponse) => void; + error_callback?: (e: { type?: string }) => void; + }) => TokenClient; +}; +declare global { + interface Window { + google?: { accounts?: { oauth2?: Gis } }; + } +} + +let gisLoading: Promise | undefined; + +/** Load Google's script once. */ +function loadGis(): Promise { + const ready = () => window.google?.accounts?.oauth2; + const existing = ready(); + if (existing) return Promise.resolve(existing); + gisLoading ??= new Promise((resolve, reject) => { + const s = document.createElement("script"); + s.src = GIS_SRC; + s.async = true; + s.onload = () => { + const gis = ready(); + if (gis) resolve(gis); + else reject(new TypeError("Google sign-in failed to load")); + }; + s.onerror = () => { + gisLoading = undefined; + reject(new TypeError("Google sign-in failed to load (network)")); + }; + document.head.appendChild(s); + }); + return gisLoading; +} + +/** Opens the popup each time it is called; resolves with the token, or rejects when the popup closes. */ +export type SignIn = () => Promise; + +export function googleSignIn(clientId: string): SignIn { + return async () => { + const gis = await loadGis(); + return new Promise((resolve, reject) => { + const client = gis.initTokenClient({ + client_id: clientId, + scope: ADSENSE_SCOPE, + callback: (r) => { + if (r.access_token && (r.scope ?? "").split(" ").includes(ADSENSE_SCOPE)) resolve(r.access_token); + // Denied, or allowed without the AdSense box ticked: the creator stopped, nothing was read. + else reject(new ReclaimCancelledError()); + }, + error_callback: () => reject(new ReclaimCancelledError()), + }); + client.requestAccessToken(); + }); + }; +} + +/** A relay job, as `GET /proofs/:id` answers it. */ +type Job = { + id: string; + stage: "queued" | "checking" | "proving" | "auditing" | "done" | "failed"; + request?: Omit & { timestampS: string; epoch: string }; + error?: { code: RelayErrorCode; message: string }; +}; + +export type RelayOptions = { + relayUrl: string; + signIn: SignIn; + fetch?: typeof fetch; + pollMs?: number; + /** Give up on a job after this long. Proofs take about ten minutes; the queue adds to that. */ + timeoutMs?: number; + sleep?: (ms: number) => Promise; +}; + +class Abandoned extends Error {} + +export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) => void, o: RelayOptions): ProveSession { + const base = o.relayUrl.replace(/\/+$/, ""); + const get = o.fetch ?? ((...a: Parameters) => fetch(...a)); + const pollMs = o.pollMs ?? 5000; + const timeoutMs = o.timeoutMs ?? 30 * 60_000; + const sleep = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + let abandoned = false; + let reading = false; + let attempt = 0; + let settleToken!: { resolve: (t: string) => void; reject: (e: unknown) => void }; + const token = new Promise((resolve, reject) => { + settleToken = { resolve, reject }; + }); + + const alive = () => { + if (abandoned) throw new Abandoned(); + }; + + /** + * Open Google's popup. Opened again ("Open the window again"), the newest popup is the one whose + * closing counts: a popup lost behind another window may never answer. + */ + function signIn() { + const mine = ++attempt; + onStage("waiting"); + o.signIn().then(settleToken.resolve, (e) => { + if (mine === attempt) settleToken.reject(e); + }); + } + + async function json(res: Response): Promise { + const body = (await res.json().catch(() => ({}))) as T & { error?: unknown }; + if (!res.ok) { + const message = typeof body.error === "string" ? body.error : `the relay answered ${res.status}`; + throw new RelayError(res.status === 409 || res.status === 503 ? "busy" : "internal", message); + } + return body; + } + + async function run(): Promise { + signIn(); + const accessToken = await token; + alive(); + reading = true; + onStage("reading"); + const started = await json( + await get(`${base}/proofs`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ borrower, accessToken }), + }), + ); + const deadline = Date.now() + timeoutMs; + let job = started; + while (job.stage !== "done" && job.stage !== "failed") { + if (Date.now() > deadline) throw new RelayError("prove", "the proof took too long"); + await sleep(pollMs); + alive(); + job = await json(await get(`${base}/proofs/${encodeURIComponent(started.id)}`, { cache: "no-store" })); + } + alive(); + if (job.stage === "failed" || !job.request) { + throw new RelayError(job.error?.code ?? "internal", job.error?.message ?? "the proof failed"); + } + return { ...job.request, timestampS: BigInt(job.request.timestampS), epoch: BigInt(job.request.epoch) }; + } + + // Never settles once abandoned, as the session promises. + const result = new Promise((resolve, reject) => { + run().then(resolve, (e) => { + if (!(e instanceof Abandoned) && !abandoned) reject(e); + }); + }); + + return { + result, + reopen: () => { + if (!reading && !abandoned) signIn(); + }, + abandon: () => { + abandoned = true; + }, + }; +} diff --git a/fe/src/lib/reclaim/session.ts b/fe/src/lib/reclaim/session.ts index 5f12002..1c20ea5 100644 --- a/fe/src/lib/reclaim/session.ts +++ b/fe/src/lib/reclaim/session.ts @@ -2,9 +2,9 @@ import type { AdvanceRequest } from "@/lib/stellar/contract"; export type ProveStage = - /** A Reclaim window is open. The creator logs in to AdSense there, not on our page. */ + /** Google's sign-in window is open. The creator signs in to AdSense there, not on our page. */ | "waiting" - /** The login worked. The revenue figure is being turned into a proof. */ + /** The sign-in worked. The relay is turning the revenue figure into a proof (#17). */ | "reading"; export type ProveSession = { @@ -24,10 +24,29 @@ export class ReclaimCancelledError extends Error { } } -/** The relay is configured, but its client is not written yet (#17). */ +/** The relay is configured without the Google OAuth client id the sign-in needs (#17). */ export class RelayNotReadyError extends Error { constructor() { - super("NEXT_PUBLIC_RELAY_URL is set, but the #17 relay client is not built yet"); + super("NEXT_PUBLIC_RELAY_URL is set, but NEXT_PUBLIC_GOOGLE_CLIENT_ID is not"); this.name = "RelayNotReadyError"; } } + +/** + * Why the relay could not make the proof, by whose move it is (docs/api.md): + * - `token`: Google refused the sign-in, for example an expired one. Signing in again fixes it. + * - `account`: no approved AdSense account behind that Google account. + * - `busy`: the relay is proving for someone else, or already for this wallet. + * - `provider`, `prove`, `audit`, `internal`: the relay's side. Trying again may work. + */ +export type RelayErrorCode = "token" | "account" | "busy" | "provider" | "prove" | "audit" | "internal"; + +export class RelayError extends Error { + constructor( + readonly code: RelayErrorCode, + message: string, + ) { + super(message); + this.name = "RelayError"; + } +} diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 1bd14cf..86a64ed 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -124,6 +124,17 @@ export function FailurePanel({ illustration = ; actions = ; break; + case "googleSignIn": + case "noAdsense": + case "relayFailed": + illustration = ; + actions = ( + <> + + {back} + + ); + break; case "declined": illustration = ; actions = ; diff --git a/fe/src/modules/advance/failures.test.ts b/fe/src/modules/advance/failures.test.ts index 2d23528..b354a2d 100644 --- a/fe/src/modules/advance/failures.test.ts +++ b/fe/src/modules/advance/failures.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { ReclaimCancelledError, RelayNotReadyError } from "@/lib/reclaim"; +import { ReclaimCancelledError, RelayError, RelayNotReadyError } from "@/lib/reclaim"; import { ContractError, MissingConfigError, SimulationError, TransactionFailedError } from "@/lib/stellar/contract"; import { WalletError } from "@/lib/stellar/wallet-error"; import { WalletSignError } from "@/lib/stellar/wallet-error"; @@ -9,6 +9,11 @@ describe("proveFailure", () => { it("names each cause on its own", () => { expect(proveFailure(new ReclaimCancelledError())).toEqual({ kind: "cancelled" }); expect(proveFailure(new RelayNotReadyError())).toEqual({ kind: "relayNotReady" }); + expect(proveFailure(new RelayError("token", "x"))).toEqual({ kind: "googleSignIn" }); + expect(proveFailure(new RelayError("account", "x"))).toEqual({ kind: "noAdsense" }); + for (const code of ["busy", "provider", "prove", "audit", "internal"] as const) { + expect(proveFailure(new RelayError(code, "x"))).toEqual({ kind: "relayFailed" }); + } expect(proveFailure(new ContractError(14, "x"))).toEqual({ code: 14 }); expect(proveFailure(new SimulationError("HostError: Error(Auth, InvalidAction)"))).toEqual({ kind: "simulationFailed" }); expect(proveFailure(new MissingConfigError("NEXT_PUBLIC_ADVANCE_CONTRACT_ID"))).toEqual({ kind: "notConfigured" }); diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index 80c63b2..b837b59 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -1,6 +1,6 @@ import { classifySignError, type ProveFailure } from "@/lib/errors"; import { formatUsd } from "@/lib/format"; -import { ReclaimCancelledError, RelayNotReadyError } from "@/lib/reclaim"; +import { ReclaimCancelledError, RelayError, RelayNotReadyError } from "@/lib/reclaim"; import { ContractError, MissingConfigError, SimulationError, TransactionFailedError } from "@/lib/stellar/contract"; import { WalletSignError } from "@/lib/stellar/wallet-error"; @@ -14,6 +14,11 @@ export type AdvanceFailure = { code: number } | { kind: ProveFailure } | { kind: function sorted(e: unknown): AdvanceFailure { if (e instanceof ReclaimCancelledError) return { kind: "cancelled" }; if (e instanceof RelayNotReadyError) return { kind: "relayNotReady" }; + if (e instanceof RelayError) { + if (e.code === "token") return { kind: "googleSignIn" }; + if (e.code === "account") return { kind: "noAdsense" }; + return { kind: "relayFailed" }; + } if (e instanceof ContractError) return { code: e.code }; if (e instanceof SimulationError) return { kind: "simulationFailed" }; if (e instanceof MissingConfigError) return { kind: "notConfigured" }; From bb65d2ec1d0dd3945fcc4fccb47b40b2793c48e3 Mon Sep 17 00:00:00 2001 From: lin1er Date: Tue, 20 Oct 2026 22:24:17 +0700 Subject: [PATCH 2/9] fix(#17): resume a running proof, and name relay failures as the relay's Review on #75: - The job id is kept in sessionStorage. Coming back to /advance, or reloading, while the relay proves waits on the same job without a second sign-in, instead of a new POST the relay refuses as already running. A kept job the relay no longer has (restart, or past its hour) starts a fresh proof. The id is cleared once the job ends, not when the screen is left. - A relay that does not answer is RelayError unreachable, not "We could not reach Stellar". Google's script failing to load is googleUnavailable. - error_callback popup_failed_to_open is popupBlocked: the creator closed nothing. - 409 is running, 503 is busy or unconfigured, read from the relay's new `code` (#73), the status as fallback. unconfigured reads like relayNotReady, not "try again". - No 30-minute give-up: polling runs to the hour after which the claim is too old and the relay has forgotten the job. - preloadSignIn() is exported for 2a to call on mount (the preload in 4). The copy for the four new panels is a first pass for Nabil to replace. --- fe/README.md | 6 +- fe/src/lib/errors.ts | 30 +++- fe/src/lib/reclaim/index.ts | 12 +- fe/src/lib/reclaim/relay.test.ts | 102 ++++++++++++- fe/src/lib/reclaim/relay.ts | 141 +++++++++++++++--- fe/src/lib/reclaim/session.ts | 21 ++- fe/src/modules/advance/Advance.tsx | 8 +- .../advance/components/FailurePanel.tsx | 4 + fe/src/modules/advance/failures.test.ts | 5 + fe/src/modules/advance/failures.ts | 15 +- 10 files changed, 304 insertions(+), 40 deletions(-) diff --git a/fe/README.md b/fe/README.md index 0e780d4..a822bbf 100644 --- a/fe/README.md +++ b/fe/README.md @@ -63,8 +63,10 @@ browser. Never put a secret in one. ## Proving revenue: the relay, or a mock With `NEXT_PUBLIC_RELAY_URL` and `NEXT_PUBLIC_GOOGLE_CLIENT_ID` set, the creator signs in with Google's -own popup (`adsense.readonly` only) and the #17 relay makes the proof, which takes about ten minutes -(`src/lib/reclaim/relay.ts`, `docs/api.md`). No Reclaim SDK runs in the browser. +own popup (`adsense.readonly` only) and the #17 relay makes the proof, which takes about a minute, more +behind a queue (`src/lib/reclaim/relay.ts`, `docs/api.md`). No Reclaim SDK runs in the browser. The job +id is kept in `sessionStorage`, so leaving /advance or reloading while it proves comes back to the same +job without a second sign-in. `src/lib/reclaim/` answers from a mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and returns fixed values. Everything after it, the offer from `quote`, the proof check, `request_advance` diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 1c15110..68ff21d 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -213,6 +213,10 @@ export function contractFailureCopy(code: number): FailureCopy { * - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one. * - `noAdsense`: the Google account has no approved AdSense account the relay can read. * - `relayFailed`: the relay could not make the proof (busy, or failed on its side). Nothing was saved. + * - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it. + * - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked. + * - `googleUnavailable`: Google's sign-in did not load. + * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. */ export type ProveFailure = | "cancelled" @@ -231,7 +235,11 @@ export type ProveFailure = | "relayNotReady" | "googleSignIn" | "noAdsense" - | "relayFailed"; + | "relayFailed" + | "proofRunning" + | "relayUnreachable" + | "googleUnavailable" + | "popupBlocked"; export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): FailureCopy { switch (kind) { @@ -324,6 +332,26 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): title: "We could not finish your proof", body: "Nothing was saved or charged. Try again in a few minutes.", }; + case "proofRunning": + return { + title: "Your proof is already being made", + body: "We started one for this wallet earlier. Nothing was charged. Try again in a few minutes to pick it up.", + }; + case "relayUnreachable": + return { + title: "We could not reach Forepay", + body: "Nothing was saved or charged. Check your connection, then try again.", + }; + case "googleUnavailable": + return { + title: "Google sign-in did not load", + body: "Nothing was read or saved. Check your connection, then try again.", + }; + case "popupBlocked": + return { + title: "Your browser blocked the Google window", + body: "Allow pop-ups for Forepay, then try again. Nothing was read or saved.", + }; } } diff --git a/fe/src/lib/reclaim/index.ts b/fe/src/lib/reclaim/index.ts index 65a67af..3db8997 100644 --- a/fe/src/lib/reclaim/index.ts +++ b/fe/src/lib/reclaim/index.ts @@ -8,7 +8,7 @@ * returns fixed values. Everything after this seam (quote, request_advance, signing, errors) is real. */ import { mockProveRevenue } from "./mock"; -import { googleSignIn, relayProveRevenue } from "./relay"; +import { googleSignIn, preloadGoogleSignIn, relayProveRevenue, sessionJobs } from "./relay"; import { RelayNotReadyError, type ProveSession, type ProveStage } from "./session"; export { @@ -28,3 +28,13 @@ export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => v if (!GOOGLE_CLIENT_ID) return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID) }); } + +/** A proof the relay is still making for this wallet, started from this tab before the creator left. */ +export function proofRunning(borrower: string): boolean { + return !!RELAY_URL && !!GOOGLE_CLIENT_ID && sessionJobs.load(borrower) !== null; +} + +/** Load Google's sign-in ahead of "Prove my revenue", so the popup opens inside the press. */ +export function preloadSignIn(): void { + if (RELAY_URL && GOOGLE_CLIENT_ID) preloadGoogleSignIn(); +} diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts index da3ab13..a3f613b 100644 --- a/fe/src/lib/reclaim/relay.test.ts +++ b/fe/src/lib/reclaim/relay.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { relayProveRevenue, type SignIn } from "./relay"; +import { relayProveRevenue, type JobStore, type SignIn } from "./relay"; import { ReclaimCancelledError, RelayError, type ProveStage } from "./session"; const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2"; @@ -27,6 +27,17 @@ function relay(polls: object[], post: { status: number; body: object } = { statu } const signedIn: SignIn = async () => "ya29.token"; + +/** A tab's job store, in memory. */ +function store(kept: { borrower: string; id: string } | null = null) { + const s = { kept }; + const jobs: JobStore = { + load: (b) => (s.kept?.borrower === b ? s.kept.id : null), + save: (borrower, id) => (s.kept = { borrower, id }), + clear: () => (s.kept = null), + }; + return Object.assign(s, { jobs }); +} const noSleep = async () => {}; describe("relayProveRevenue", () => { @@ -38,6 +49,7 @@ describe("relayProveRevenue", () => { signIn: signedIn, fetch: r.fetch, sleep: noSleep, + jobs: store().jobs, }); const req = await s.result; expect(stages).toEqual(["waiting", "reading"]); @@ -56,6 +68,7 @@ describe("relayProveRevenue", () => { }, fetch: r.fetch, sleep: noSleep, + jobs: store().jobs, }); await expect(s.result).rejects.toBeInstanceOf(ReclaimCancelledError); expect(r.calls).toEqual([]); @@ -63,20 +76,92 @@ describe("relayProveRevenue", () => { it("a failed job keeps the relay's code", async () => { const r = relay([{ id: "j1", stage: "failed", error: { code: "account", message: "not READY" } }]); - const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep }); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); const e = await s.result.catch((x) => x); expect(e).toBeInstanceOf(RelayError); expect((e as RelayError).code).toBe("account"); }); - it("a busy relay or one already proving for this wallet is busy", async () => { - for (const status of [409, 503]) { - const r = relay([], { status, body: { error: "busy" } }); - const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep }); - expect(((await s.result.catch((x) => x)) as RelayError).code).toBe("busy"); + it("names the relay's refusal by its code, and by the status when there is none", async () => { + const cases: [number, object, string][] = [ + [409, { error: "x", code: "running" }, "running"], + [503, { error: "x", code: "busy" }, "busy"], + [503, { error: "x", code: "unconfigured" }, "unconfigured"], + [409, {}, "running"], + [503, {}, "busy"], + [500, {}, "internal"], + ]; + for (const [status, body, code] of cases) { + const r = relay([], { status, body }); + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); + expect(((await s.result.catch((x) => x)) as RelayError).code, `${status} ${JSON.stringify(body)}`).toBe(code); } }); + it("a relay that does not answer is unreachable, not Stellar", async () => { + const fetch = (async () => { + throw new TypeError("Failed to fetch"); + }) as unknown as typeof globalThis.fetch; + const s = relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: store().jobs }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("unreachable"); + }); + + it("keeps the job id while proving and forgets it once the job ends", async () => { + const t = store(); + let seen: string | null = null; + const fetch = (async (_url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j1", stage: "queued" }), { status: 202 }); + seen = t.jobs.load(BORROWER); + return new Response(JSON.stringify({ id: "j1", stage: "done", request: REQUEST })); + }) as unknown as typeof globalThis.fetch; + await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(seen).toBe("j1"); + expect(t.kept).toBeNull(); + }); + + it("coming back to a job still running waits on it, with no second sign-in and no second proof", async () => { + const t = store({ borrower: BORROWER, id: "j1" }); + const r = relay([{ id: "j1", stage: "proving" }, { id: "j1", stage: "done", request: REQUEST }]); + let signIns = 0; + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { + relayUrl: "https://r", + signIn: async () => { + signIns++; + return "ya29.token"; + }, + fetch: r.fetch, + sleep: noSleep, + jobs: t.jobs, + }); + expect(await s.result).toEqual({ ...REQUEST, timestampS: 1792467390n, epoch: 1n }); + expect(signIns).toBe(0); + expect(stages).toEqual(["reading"]); + expect(r.calls.every((c) => c.init?.method !== "POST")).toBe(true); + expect(t.kept).toBeNull(); + }); + + it("a kept job the relay no longer has starts a fresh proof", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + const fetch = (async (url: string, init?: RequestInit) => { + if (init?.method === "POST") return new Response(JSON.stringify({ id: "j2", stage: "queued" }), { status: 202 }); + if (url.endsWith("/gone")) return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + return new Response(JSON.stringify({ id: "j2", stage: "done", request: REQUEST })); + }) as unknown as typeof globalThis.fetch; + const stages: ProveStage[] = []; + await relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(stages).toEqual(["reading", "waiting", "reading"]); + }); + + it("a job kept for another wallet is not this one's", async () => { + const t = store({ borrower: "GOTHER", id: "j9" }); + const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); + await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(r.calls[0].init?.method).toBe("POST"); + }); + it("opening the window again waits on the newest popup, and an older one closing does not end it", async () => { let n = 0; const releases: ((t: string) => void)[] = []; @@ -89,7 +174,7 @@ describe("relayProveRevenue", () => { }); const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); const stages: ProveStage[] = []; - const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch: r.fetch, sleep: noSleep }); + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }); s.reopen(); expect(n).toBe(2); rejects[0](new ReclaimCancelledError()); @@ -112,6 +197,7 @@ describe("relayProveRevenue", () => { signIn: signedIn, fetch, sleep: () => new Promise((r) => (wake = r)), + jobs: store().jobs, }); let settled = false; s.result.then( diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts index 6a1d988..ccfca06 100644 --- a/fe/src/lib/reclaim/relay.ts +++ b/fe/src/lib/reclaim/relay.ts @@ -4,11 +4,15 @@ * docs/api.md, "The proof relay". * * No Reclaim SDK runs here. The proof is made on the relay because the engine Reclaim's attestor accepts - * needs ~330 MB of circuit files and about ten minutes of CPU. The browser's part is the sign-in, and + * needs ~330 MB of circuit files and a minute or more of a whole CPU. The browser's part is the sign-in, and * the token goes once to the relay, which binds the borrower's G… inside the signed claim. * * Stages: `waiting` while Google's popup is open, `reading` from the moment the relay has the job until * it ends. + * + * The job id is kept for the length of the tab (`sessionJobs`). A creator who leaves /advance or reloads + * while the relay proves comes back to the same job, without a second sign-in, instead of starting a + * second proof the relay would refuse as already running (409). */ import type { AdvanceRequest } from "@/lib/stellar/contract"; import { ReclaimCancelledError, RelayError, type ProveSession, type ProveStage, type RelayErrorCode } from "./session"; @@ -47,17 +51,27 @@ function loadGis(): Promise { s.onload = () => { const gis = ready(); if (gis) resolve(gis); - else reject(new TypeError("Google sign-in failed to load")); + else reject(new RelayError("googleUnavailable", "Google sign-in failed to load")); }; s.onerror = () => { gisLoading = undefined; - reject(new TypeError("Google sign-in failed to load (network)")); + reject(new RelayError("googleUnavailable", "Google sign-in failed to load (network)")); }; document.head.appendChild(s); }); return gisLoading; } +/** + * Load Google's script ahead of the press, so "Prove my revenue" opens the popup inside the click. + * Loaded only then, the popup opens after an await, outside the click, and browsers may block it. + */ +export function preloadGoogleSignIn(): void { + loadGis().catch(() => { + // The press will try again and report it. + }); +} + /** Opens the popup each time it is called; resolves with the token, or rejects when the popup closes. */ export type SignIn = () => Promise; @@ -73,7 +87,12 @@ export function googleSignIn(clientId: string): SignIn { // Denied, or allowed without the AdSense box ticked: the creator stopped, nothing was read. else reject(new ReclaimCancelledError()); }, - error_callback: () => reject(new ReclaimCancelledError()), + error_callback: (e) => + reject( + e.type === "popup_failed_to_open" + ? new RelayError("popupBlocked", "the browser blocked Google's sign-in window") + : new ReclaimCancelledError(), + ), }); client.requestAccessToken(); }); @@ -88,23 +107,68 @@ type Job = { error?: { code: RelayErrorCode; message: string }; }; +/** Where the running job's id waits while the creator is away from /advance. */ +export type JobStore = { + load: (borrower: string) => string | null; + save: (borrower: string, id: string) => void; + clear: () => void; +}; + +const JOB_KEY = "forepay.proof.job"; + +/** + * The job id, for the length of the tab. Only the id: the token never leaves the sign-in, and the id + * reads nothing the relay would not show this tab anyway. One for another wallet is not this one's. + */ +export const sessionJobs: JobStore = { + load: (borrower) => { + try { + const s = JSON.parse(window.sessionStorage.getItem(JOB_KEY) ?? "null") as { borrower: string; id: string } | null; + return s?.borrower === borrower ? s.id : null; + } catch { + return null; + } + }, + save: (borrower, id) => { + try { + window.sessionStorage.setItem(JOB_KEY, JSON.stringify({ borrower, id })); + } catch { + // Storage unavailable: leaving the page while proving loses the job, as before. + } + }, + clear: () => { + try { + window.sessionStorage.removeItem(JOB_KEY); + } catch { + // nothing to clear + } + }, +}; + export type RelayOptions = { relayUrl: string; signIn: SignIn; fetch?: typeof fetch; + jobs?: JobStore; pollMs?: number; - /** Give up on a job after this long. Proofs take about ten minutes; the queue adds to that. */ + /** + * Give up on a job after this long. A proof takes about a minute on the relay, more behind a queue; + * past an hour the claim is too old for the contract anyway, and the relay has forgotten the job. + */ timeoutMs?: number; sleep?: (ms: number) => Promise; }; +const CODES: readonly RelayErrorCode[] = ["token", "account", "running", "busy", "unconfigured", "provider", "prove", "audit", "internal"]; + class Abandoned extends Error {} export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) => void, o: RelayOptions): ProveSession { const base = o.relayUrl.replace(/\/+$/, ""); - const get = o.fetch ?? ((...a: Parameters) => fetch(...a)); + const send = o.fetch ?? ((...a: Parameters) => fetch(...a)); + const jobs = o.jobs ?? sessionJobs; const pollMs = o.pollMs ?? 5000; - const timeoutMs = o.timeoutMs ?? 30 * 60_000; + const timeoutMs = o.timeoutMs ?? 60 * 60_000; const sleep = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); let abandoned = false; let reading = false; @@ -130,37 +194,76 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) }); } + /** A relay that does not answer is the relay's, not Stellar's (review on #75). */ + async function call(url: string, init?: RequestInit): Promise { + try { + return await send(url, init); + } catch (e) { + throw new RelayError("unreachable", `the relay did not answer: ${(e as Error)?.message ?? e}`); + } + } + async function json(res: Response): Promise { - const body = (await res.json().catch(() => ({}))) as T & { error?: unknown }; + const body = (await res.json().catch(() => ({}))) as T & { error?: unknown; code?: unknown }; if (!res.ok) { const message = typeof body.error === "string" ? body.error : `the relay answered ${res.status}`; - throw new RelayError(res.status === 409 || res.status === 503 ? "busy" : "internal", message); + // The relay names the refusal in `code` (docs/api.md); the status is the fallback. + const code = CODES.find((c) => c === body.code) ?? (res.status === 409 ? "running" : res.status === 503 ? "busy" : "internal"); + throw new RelayError(code, message); } return body; } - async function run(): Promise { + /** Poll a job until it ends. Null when the relay no longer has it (it restarted, or an hour passed). */ + async function follow(id: string, first?: Job): Promise { + const deadline = Date.now() + timeoutMs; + let job = first; + while (!job || (job.stage !== "done" && job.stage !== "failed")) { + if (Date.now() > deadline) throw new RelayError("prove", "the proof took too long"); + if (job) await sleep(pollMs); + alive(); + const res = await call(`${base}/proofs/${encodeURIComponent(id)}`, { cache: "no-store" }); + if (res.status === 404) return null; + job = await json(res); + } + return job; + } + + async function prove(): Promise { + // A job this tab started before the creator left: wait on it rather than sign in again. + const kept = jobs.load(borrower); + if (kept) { + reading = true; + onStage("reading"); + const job = await follow(kept); + if (job) return job; + jobs.clear(); + reading = false; + } signIn(); const accessToken = await token; alive(); reading = true; onStage("reading"); const started = await json( - await get(`${base}/proofs`, { + await call(`${base}/proofs`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ borrower, accessToken }), }), ); - const deadline = Date.now() + timeoutMs; - let job = started; - while (job.stage !== "done" && job.stage !== "failed") { - if (Date.now() > deadline) throw new RelayError("prove", "the proof took too long"); - await sleep(pollMs); - alive(); - job = await json(await get(`${base}/proofs/${encodeURIComponent(started.id)}`, { cache: "no-store" })); - } + jobs.save(borrower, started.id); + const job = await follow(started.id, started); + if (!job) throw new RelayError("internal", "the relay lost the proof job"); + return job; + } + + async function run(): Promise { + const job = await prove(); alive(); + // Ended either way: the next press starts a new proof. Left alone while abandoned, so coming back + // finds the result. + jobs.clear(); if (job.stage === "failed" || !job.request) { throw new RelayError(job.error?.code ?? "internal", job.error?.message ?? "the proof failed"); } diff --git a/fe/src/lib/reclaim/session.ts b/fe/src/lib/reclaim/session.ts index 1c20ea5..ea810a6 100644 --- a/fe/src/lib/reclaim/session.ts +++ b/fe/src/lib/reclaim/session.ts @@ -36,10 +36,27 @@ export class RelayNotReadyError extends Error { * Why the relay could not make the proof, by whose move it is (docs/api.md): * - `token`: Google refused the sign-in, for example an expired one. Signing in again fixes it. * - `account`: no approved AdSense account behind that Google account. - * - `busy`: the relay is proving for someone else, or already for this wallet. + * - `running`: a proof for this wallet is already running, started from a tab that no longer has it. + * - `busy`: the relay is proving for others and its queue is full. + * - `unconfigured`: the relay answers, but proving is not set up on it. + * - `unreachable`: the relay did not answer at all. + * - `googleUnavailable`: Google's sign-in script did not load. + * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. * - `provider`, `prove`, `audit`, `internal`: the relay's side. Trying again may work. */ -export type RelayErrorCode = "token" | "account" | "busy" | "provider" | "prove" | "audit" | "internal"; +export type RelayErrorCode = + | "token" + | "account" + | "running" + | "busy" + | "unconfigured" + | "unreachable" + | "googleUnavailable" + | "popupBlocked" + | "provider" + | "prove" + | "audit" + | "internal"; export class RelayError extends Error { constructor( diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index c2623ec..55ec6d9 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -7,7 +7,7 @@ import { SkeletonBlock } from "@/components/ui/Skeleton"; import { notify } from "@/components/ui/Toaster"; import { isSignatureDeclined } from "@/lib/errors"; import { formatUsd, formatWindow } from "@/lib/format"; -import { proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; +import { proofRunning, proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; import { TransactionFailedError, awaitAdvance, @@ -87,13 +87,15 @@ export function Advance() { [], ); - // Back on /advance with a `request_advance` still out from an earlier visit: wait on that one. Each + // Back on /advance with a `request_advance` still out from an earlier visit: wait on that one. Or with + // a proof the relay is still making for this wallet: wait on that, without signing in again. Each // mount waits afresh; the unmount above drops the answer of the one before. useEffect(() => { if (!address) return; const pending = loadPending(address); if (pending) void pickUp(pending); - // `pickUp` only reads refs and setters; it runs per mount and per wallet. + else if (proofRunning(address)) void prove(); + // `pickUp` and `prove` only read refs and setters; they run per mount and per wallet. // eslint-disable-next-line react-hooks/exhaustive-deps }, [address]); diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 86a64ed..44adddd 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -127,6 +127,10 @@ export function FailurePanel({ case "googleSignIn": case "noAdsense": case "relayFailed": + case "proofRunning": + case "relayUnreachable": + case "googleUnavailable": + case "popupBlocked": illustration = ; actions = ( <> diff --git a/fe/src/modules/advance/failures.test.ts b/fe/src/modules/advance/failures.test.ts index b354a2d..624551c 100644 --- a/fe/src/modules/advance/failures.test.ts +++ b/fe/src/modules/advance/failures.test.ts @@ -11,6 +11,11 @@ describe("proveFailure", () => { expect(proveFailure(new RelayNotReadyError())).toEqual({ kind: "relayNotReady" }); expect(proveFailure(new RelayError("token", "x"))).toEqual({ kind: "googleSignIn" }); expect(proveFailure(new RelayError("account", "x"))).toEqual({ kind: "noAdsense" }); + expect(proveFailure(new RelayError("running", "x"))).toEqual({ kind: "proofRunning" }); + expect(proveFailure(new RelayError("unconfigured", "x"))).toEqual({ kind: "relayNotReady" }); + expect(proveFailure(new RelayError("unreachable", "x"))).toEqual({ kind: "relayUnreachable" }); + expect(proveFailure(new RelayError("googleUnavailable", "x"))).toEqual({ kind: "googleUnavailable" }); + expect(proveFailure(new RelayError("popupBlocked", "x"))).toEqual({ kind: "popupBlocked" }); for (const code of ["busy", "provider", "prove", "audit", "internal"] as const) { expect(proveFailure(new RelayError(code, "x"))).toEqual({ kind: "relayFailed" }); } diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index b837b59..9b892ea 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -1,6 +1,6 @@ import { classifySignError, type ProveFailure } from "@/lib/errors"; import { formatUsd } from "@/lib/format"; -import { ReclaimCancelledError, RelayError, RelayNotReadyError } from "@/lib/reclaim"; +import { ReclaimCancelledError, RelayError, RelayNotReadyError, type RelayErrorCode } from "@/lib/reclaim"; import { ContractError, MissingConfigError, SimulationError, TransactionFailedError } from "@/lib/stellar/contract"; import { WalletSignError } from "@/lib/stellar/wallet-error"; @@ -15,9 +15,16 @@ function sorted(e: unknown): AdvanceFailure { if (e instanceof ReclaimCancelledError) return { kind: "cancelled" }; if (e instanceof RelayNotReadyError) return { kind: "relayNotReady" }; if (e instanceof RelayError) { - if (e.code === "token") return { kind: "googleSignIn" }; - if (e.code === "account") return { kind: "noAdsense" }; - return { kind: "relayFailed" }; + const kinds: Partial> = { + token: "googleSignIn", + account: "noAdsense", + running: "proofRunning", + unconfigured: "relayNotReady", + unreachable: "relayUnreachable", + googleUnavailable: "googleUnavailable", + popupBlocked: "popupBlocked", + }; + return { kind: kinds[e.code] ?? "relayFailed" }; } if (e instanceof ContractError) return { code: e.code }; if (e instanceof SimulationError) return { kind: "simulationFailed" }; From d4ec16b05925033153fcf299c8a31c3730157e77 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:21:40 +0700 Subject: [PATCH 3/9] fix(#17): end a kept job the relay no longer has, instead of signing in outside a press When the relay answers 404 for the job id this tab kept (it restarted, or the hour passed), the session used to clear it and call signIn() straight away. From the mount effect that opens Google's popup with no press at all, and from a press it opens after an await. The browser blocks it, and the creator read "Your browser blocked the Google window", which is not what happened. Now the session ends as RelayError("gone"), shown as "Your earlier proof has ended" with Prove my revenue, so the next sign-in opens inside a click. Co-Authored-By: Claude Opus 5.5 --- fe/src/lib/errors.test.ts | 5 +++ fe/src/lib/errors.ts | 7 +++++ fe/src/lib/reclaim/relay.test.ts | 31 +++++++++++++++++-- fe/src/lib/reclaim/relay.ts | 8 +++-- fe/src/lib/reclaim/session.ts | 2 ++ .../advance/components/FailurePanel.tsx | 1 + fe/src/modules/advance/failures.test.ts | 1 + fe/src/modules/advance/failures.ts | 1 + 8 files changed, 51 insertions(+), 5 deletions(-) diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index 4f4e56b..4854a44 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -126,6 +126,11 @@ describe("proveFailureCopy", () => { "googleSignIn", "noAdsense", "relayFailed", + "proofRunning", + "proofGone", + "relayUnreachable", + "googleUnavailable", + "popupBlocked", ]; it("keeps every failure inside the copy rules, and never says Something went wrong", () => { diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 68ff21d..5a21991 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -214,6 +214,7 @@ export function contractFailureCopy(code: number): FailureCopy { * - `noAdsense`: the Google account has no approved AdSense account the relay can read. * - `relayFailed`: the relay could not make the proof (busy, or failed on its side). Nothing was saved. * - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it. + * - `proofGone`: the proof this tab was waiting on ended while the creator was away, and is no longer kept. * - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked. * - `googleUnavailable`: Google's sign-in did not load. * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. @@ -237,6 +238,7 @@ export type ProveFailure = | "noAdsense" | "relayFailed" | "proofRunning" + | "proofGone" | "relayUnreachable" | "googleUnavailable" | "popupBlocked"; @@ -337,6 +339,11 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): title: "Your proof is already being made", body: "We started one for this wallet earlier. Nothing was charged. Try again in a few minutes to pick it up.", }; + case "proofGone": + return { + title: "Your earlier proof has ended", + body: "It finished while you were away, and is no longer kept. Prove your revenue again, it takes about a minute. Nothing was charged.", + }; case "relayUnreachable": return { title: "We could not reach Forepay", diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts index a3f613b..f0581f5 100644 --- a/fe/src/lib/reclaim/relay.test.ts +++ b/fe/src/lib/reclaim/relay.test.ts @@ -143,16 +143,41 @@ describe("relayProveRevenue", () => { expect(t.kept).toBeNull(); }); - it("a kept job the relay no longer has starts a fresh proof", async () => { + it("a kept job the relay no longer has ends as gone, and never opens Google's popup outside a press", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + const calls: string[] = []; + const fetch = (async (url: string, init?: RequestInit) => { + calls.push(`${init?.method ?? "GET"} ${url}`); + return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + }) as unknown as typeof globalThis.fetch; + let signIns = 0; + const signIn: SignIn = async () => { + signIns++; + return "ya29.token"; + }; + const stages: ProveStage[] = []; + const s = relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn, fetch, sleep: noSleep, jobs: t.jobs }); + const e = await s.result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("gone"); + expect(signIns).toBe(0); + expect(stages).toEqual(["reading"]); + expect(calls).toEqual(["GET https://r/proofs/gone"]); + expect(t.kept).toBeNull(); + }); + + it("after a gone job, the next press signs in and starts a fresh proof", async () => { const t = store({ borrower: BORROWER, id: "gone" }); const fetch = (async (url: string, init?: RequestInit) => { if (init?.method === "POST") return new Response(JSON.stringify({ id: "j2", stage: "queued" }), { status: 202 }); if (url.endsWith("/gone")) return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); return new Response(JSON.stringify({ id: "j2", stage: "done", request: REQUEST })); }) as unknown as typeof globalThis.fetch; + const o = { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }; + await relayProveRevenue(BORROWER, () => {}, o).result.catch(() => {}); const stages: ProveStage[] = []; - await relayProveRevenue(BORROWER, (st) => stages.push(st), { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }).result; - expect(stages).toEqual(["reading", "waiting", "reading"]); + await relayProveRevenue(BORROWER, (st) => stages.push(st), o).result; + expect(stages).toEqual(["waiting", "reading"]); }); it("a job kept for another wallet is not this one's", async () => { diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts index ccfca06..55668b1 100644 --- a/fe/src/lib/reclaim/relay.ts +++ b/fe/src/lib/reclaim/relay.ts @@ -12,7 +12,8 @@ * * The job id is kept for the length of the tab (`sessionJobs`). A creator who leaves /advance or reloads * while the relay proves comes back to the same job, without a second sign-in, instead of starting a - * second proof the relay would refuse as already running (409). + * second proof the relay would refuse as already running (409). A kept job the relay no longer has + * ends the session as `gone`, so the sign-in it needs starts from a press. */ import type { AdvanceRequest } from "@/lib/stellar/contract"; import { ReclaimCancelledError, RelayError, type ProveSession, type ProveStage, type RelayErrorCode } from "./session"; @@ -237,8 +238,11 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) onStage("reading"); const job = await follow(kept); if (job) return job; + // The relay no longer has it (it restarted, or the hour passed). Signing in again here would open + // Google's popup outside any press, on mount or after an await, and the browser would block it + // (review on #75). The creator's next press opens it instead. jobs.clear(); - reading = false; + throw new RelayError("gone", "the relay no longer has this proof job"); } signIn(); const accessToken = await token; diff --git a/fe/src/lib/reclaim/session.ts b/fe/src/lib/reclaim/session.ts index ea810a6..159609c 100644 --- a/fe/src/lib/reclaim/session.ts +++ b/fe/src/lib/reclaim/session.ts @@ -37,6 +37,7 @@ export class RelayNotReadyError extends Error { * - `token`: Google refused the sign-in, for example an expired one. Signing in again fixes it. * - `account`: no approved AdSense account behind that Google account. * - `running`: a proof for this wallet is already running, started from a tab that no longer has it. + * - `gone`: the proof this tab was waiting on is no longer on the relay (it restarted, or an hour passed). * - `busy`: the relay is proving for others and its queue is full. * - `unconfigured`: the relay answers, but proving is not set up on it. * - `unreachable`: the relay did not answer at all. @@ -48,6 +49,7 @@ export type RelayErrorCode = | "token" | "account" | "running" + | "gone" | "busy" | "unconfigured" | "unreachable" diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 44adddd..51d4ee1 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -128,6 +128,7 @@ export function FailurePanel({ case "noAdsense": case "relayFailed": case "proofRunning": + case "proofGone": case "relayUnreachable": case "googleUnavailable": case "popupBlocked": diff --git a/fe/src/modules/advance/failures.test.ts b/fe/src/modules/advance/failures.test.ts index 624551c..95950a2 100644 --- a/fe/src/modules/advance/failures.test.ts +++ b/fe/src/modules/advance/failures.test.ts @@ -12,6 +12,7 @@ describe("proveFailure", () => { expect(proveFailure(new RelayError("token", "x"))).toEqual({ kind: "googleSignIn" }); expect(proveFailure(new RelayError("account", "x"))).toEqual({ kind: "noAdsense" }); expect(proveFailure(new RelayError("running", "x"))).toEqual({ kind: "proofRunning" }); + expect(proveFailure(new RelayError("gone", "x"))).toEqual({ kind: "proofGone" }); expect(proveFailure(new RelayError("unconfigured", "x"))).toEqual({ kind: "relayNotReady" }); expect(proveFailure(new RelayError("unreachable", "x"))).toEqual({ kind: "relayUnreachable" }); expect(proveFailure(new RelayError("googleUnavailable", "x"))).toEqual({ kind: "googleUnavailable" }); diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index 9b892ea..cbeda0e 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -19,6 +19,7 @@ function sorted(e: unknown): AdvanceFailure { token: "googleSignIn", account: "noAdsense", running: "proofRunning", + gone: "proofGone", unconfigured: "relayNotReady", unreachable: "relayUnreachable", googleUnavailable: "googleUnavailable", From c428e18e245c07e330a8b7d64f1b3f48f932c6be Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:22:04 +0700 Subject: [PATCH 4/9] feat(#17): load Google's sign-in while 2a is open, so the press opens the popup Also on a failure panel, whose Prove my revenue starts the same sign-in. Co-Authored-By: Claude Opus 5.5 --- fe/src/modules/advance/Advance.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index 55ec6d9..1e41b5c 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -7,7 +7,7 @@ import { SkeletonBlock } from "@/components/ui/Skeleton"; import { notify } from "@/components/ui/Toaster"; import { isSignatureDeclined } from "@/lib/errors"; import { formatUsd, formatWindow } from "@/lib/format"; -import { proofRunning, proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; +import { preloadSignIn, proofRunning, proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; import { TransactionFailedError, awaitAdvance, @@ -99,6 +99,12 @@ export function Advance() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [address]); + // Google's sign-in script, loaded while 2a is open, so "Prove my revenue" opens the popup inside the + // press. Loaded only on the press, the popup opens after an await and browsers may block it. + useEffect(() => { + if (flow.at === "start" || flow.at === "failed") preloadSignIn(); + }, [flow.at]); + // The offer on 2b and 2c. Read in `check` before 2b opens, so it is already here. const req = "req" in flow ? flow.req : undefined; const offer = useQuery({ From 10cd4bfd66a6e44e7bb0e7c8dbe4d2cfdc48a4d5 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:24:53 +0700 Subject: [PATCH 5/9] feat(#17): words for the Google sign-in, the minute-long wait and the relay's panels - Waiting: "Sign in with Google in the new window", naming the account and the AdSense box to tick. 2a says "Sign in with Google" too. - Reading: about a minute, longer behind a queue; other pages are safe, a closed tab means proving again. It no longer promises a few seconds. - noAdsense names the Google account as the thing to change. - proofRunning no longer promises to pick the job up: a 409 carries no id, so it says to wait for it to end and prove again. - busy has its own panel, "Forepay is busy right now", instead of relayFailed. - "Nothing was saved" becomes "Nothing was charged", the rule the other panels follow. - "You closed the Google window", since the window is Google's now. Co-Authored-By: Claude Opus 5.5 --- fe/src/lib/errors.test.ts | 1 + fe/src/lib/errors.ts | 21 ++++++++++++------- fe/src/modules/advance/Advance.tsx | 11 +++++++--- .../advance/components/FailurePanel.tsx | 1 + .../advance/components/ProveRevenue.tsx | 2 +- fe/src/modules/advance/failures.test.ts | 3 ++- fe/src/modules/advance/failures.ts | 1 + fe/tests/e2e/advance.spec.ts | 10 ++++----- fe/tests/e2e/layout.spec.ts | 2 +- 9 files changed, 34 insertions(+), 18 deletions(-) diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index 4854a44..1ecf8bd 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -126,6 +126,7 @@ describe("proveFailureCopy", () => { "googleSignIn", "noAdsense", "relayFailed", + "relayBusy", "proofRunning", "proofGone", "relayUnreachable", diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 5a21991..9f9ec6c 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -212,7 +212,8 @@ export function contractFailureCopy(code: number): FailureCopy { * - `relayNotReady`: proofs are meant to come from the #17 relay, and this build cannot reach it. * - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one. * - `noAdsense`: the Google account has no approved AdSense account the relay can read. - * - `relayFailed`: the relay could not make the proof (busy, or failed on its side). Nothing was saved. + * - `relayFailed`: the relay could not make the proof, on its side. Nothing was charged. + * - `relayBusy`: the relay is proving for others and its queue is full. * - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it. * - `proofGone`: the proof this tab was waiting on ended while the creator was away, and is no longer kept. * - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked. @@ -237,6 +238,7 @@ export type ProveFailure = | "googleSignIn" | "noAdsense" | "relayFailed" + | "relayBusy" | "proofRunning" | "proofGone" | "relayUnreachable" @@ -247,7 +249,7 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): switch (kind) { case "cancelled": return { - title: "You closed the AdSense window", + title: "You closed the Google window", body: "Nothing was read or saved. Start again when you are ready.", }; case "declined": @@ -322,22 +324,27 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): case "googleSignIn": return { title: "Google did not let us read AdSense", - body: "Sign in again and allow Forepay to see your AdSense reports. Nothing was saved.", + body: "Sign in again and allow Forepay to see your AdSense reports. Nothing was charged.", }; case "noAdsense": return { title: "We found no approved AdSense account", - body: "Sign in with the Google account that owns an approved AdSense account, then try again.", + body: "This Google account has no AdSense account we can read. Sign in with the account that owns your AdSense, then try again. Nothing was charged.", }; case "relayFailed": return { title: "We could not finish your proof", - body: "Nothing was saved or charged. Try again in a few minutes.", + body: "Nothing was charged. Try again in a few minutes.", + }; + case "relayBusy": + return { + title: "Forepay is busy right now", + body: "Many creators are proving at once. Nothing was read or charged. Try again in a few minutes.", }; case "proofRunning": return { title: "Your proof is already being made", - body: "We started one for this wallet earlier. Nothing was charged. Try again in a few minutes to pick it up.", + body: "A proof for this wallet started earlier, in a tab that no longer has it. Wait a few minutes for it to end, then prove again. Nothing was charged.", }; case "proofGone": return { @@ -347,7 +354,7 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): case "relayUnreachable": return { title: "We could not reach Forepay", - body: "Nothing was saved or charged. Check your connection, then try again.", + body: "Nothing was charged. Check your connection, then try again.", }; case "googleUnavailable": return { diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index 1e41b5c..ee53f35 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -413,8 +413,8 @@ export function Advance() { /> ) : flow.stage === "waiting" ? ( session.current?.reopen()}> Open the window again @@ -422,7 +422,12 @@ export function Advance() { } /> ) : ( - + // About a minute on the relay, more behind a queue. The job id is kept for the tab, so other + // pages are safe; a closed tab loses it (lib/reclaim/relay.ts). + )} diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 51d4ee1..98d9b36 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -127,6 +127,7 @@ export function FailurePanel({ case "googleSignIn": case "noAdsense": case "relayFailed": + case "relayBusy": case "proofRunning": case "proofGone": case "relayUnreachable": diff --git a/fe/src/modules/advance/components/ProveRevenue.tsx b/fe/src/modules/advance/components/ProveRevenue.tsx index 014a1ad..5dce400 100644 --- a/fe/src/modules/advance/components/ProveRevenue.tsx +++ b/fe/src/modules/advance/components/ProveRevenue.tsx @@ -41,7 +41,7 @@ export function ProveRevenue({

See how much you can get

- Log in to AdSense in a secure window. We read your revenue for the last three months and nothing else. + Sign in with Google in a secure window. We read your AdSense revenue for the last three months and nothing else.

{/* Side by side only where each list keeps its longest item ("Revenue from the last three complete months", about 360 in Body) on one line: two of them and the 24 gap. */} diff --git a/fe/src/modules/advance/failures.test.ts b/fe/src/modules/advance/failures.test.ts index 95950a2..2327956 100644 --- a/fe/src/modules/advance/failures.test.ts +++ b/fe/src/modules/advance/failures.test.ts @@ -17,7 +17,8 @@ describe("proveFailure", () => { expect(proveFailure(new RelayError("unreachable", "x"))).toEqual({ kind: "relayUnreachable" }); expect(proveFailure(new RelayError("googleUnavailable", "x"))).toEqual({ kind: "googleUnavailable" }); expect(proveFailure(new RelayError("popupBlocked", "x"))).toEqual({ kind: "popupBlocked" }); - for (const code of ["busy", "provider", "prove", "audit", "internal"] as const) { + expect(proveFailure(new RelayError("busy", "x"))).toEqual({ kind: "relayBusy" }); + for (const code of ["provider", "prove", "audit", "internal"] as const) { expect(proveFailure(new RelayError(code, "x"))).toEqual({ kind: "relayFailed" }); } expect(proveFailure(new ContractError(14, "x"))).toEqual({ code: 14 }); diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index cbeda0e..2d7b4d0 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -20,6 +20,7 @@ function sorted(e: unknown): AdvanceFailure { account: "noAdsense", running: "proofRunning", gone: "proofGone", + busy: "relayBusy", unconfigured: "relayNotReady", unreachable: "relayUnreachable", googleUnavailable: "googleUnavailable", diff --git a/fe/tests/e2e/advance.spec.ts b/fe/tests/e2e/advance.spec.ts index a671147..8a014a4 100644 --- a/fe/tests/e2e/advance.spec.ts +++ b/fe/tests/e2e/advance.spec.ts @@ -55,7 +55,7 @@ test("prove, see the offer with its derivation, accept, and receive the USDC", a await page.getByRole("button", { name: "Prove my revenue" }).click(); // The Reclaim session, then the check on Stellar - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await expect(page.getByRole("button", { name: "Open the window again" })).toBeVisible(); await expect(heading(page, "Reading your revenue")).toBeVisible(); await expect(heading(page, "Checking your proof")).toBeVisible(); @@ -272,10 +272,10 @@ test("an advance under 1 USDC is refused before anything is sent, and the proof await expect(heading(page, "See how much you can get")).toBeVisible(); }); -test("closing the AdSense window is named, and proving can start again", async ({ page }) => { +test("closing the Google window is named, and proving can start again", async ({ page }) => { await connect(page, { account: true, trustline: true }, { "forepay.mock.reclaim": "cancel" }); await page.getByRole("button", { name: "Prove my revenue" }).click(); - await expect(heading(page, "You closed the AdSense window")).toBeVisible(); + await expect(heading(page, "You closed the Google window")).toBeVisible(); await expect(page.getByText("Nothing was read or saved. Start again when you are ready.")).toBeVisible(); await page.evaluate(() => window.localStorage.removeItem("forepay.mock.reclaim")); await page.getByRole("button", { name: "Prove my revenue" }).click(); @@ -342,7 +342,7 @@ test("Open the window again keeps waiting for the AdSense login, then goes on", await connect(page, { account: true, trustline: true }); await page.getByRole("button", { name: "Prove my revenue" }).click(); await page.getByRole("button", { name: "Open the window again" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); }); @@ -374,7 +374,7 @@ test("a proof that expires while the offer is open is named at accept, and Prove await expect(heading(page, "Approve the advance")).toBeVisible(); expect(chain.advance?.sent ?? 0).toBe(0); await page.getByRole("button", { name: "Prove again" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); }); test("a proof already used, found at accept, is named, and Back leaves the offer behind", async ({ page }) => { diff --git a/fe/tests/e2e/layout.spec.ts b/fe/tests/e2e/layout.spec.ts index f1390bf..f1ffc7f 100644 --- a/fe/tests/e2e/layout.spec.ts +++ b/fe/tests/e2e/layout.spec.ts @@ -302,7 +302,7 @@ test("advance in progress: proving, approving in the wallet, sending, and 2d", a // The mock's proving stages last under a second each: the walk measures whichever one shows. await page.goto("/advance"); await page.getByRole("button", { name: "Prove my revenue" }).click(); - await expect(heading(page, "Log in to AdSense in the new window")).toBeVisible(); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await holdsAtEveryWidth(page, "2a proving"); await page.setViewportSize({ width: 1440, height: 900 }); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); From e5d6303ed209fd4322275820e49f8eabdb000084 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:30:33 +0700 Subject: [PATCH 6/9] test(#17): e2e for proving through the relay A second e2e build has NEXT_PUBLIC_RELAY_URL and a Google client id set (the relay-desktop and relay-mobile projects). Google's sign-in is a stub on window.google, which relay.ts uses when it is already there, and the spec answers /proofs as docs/api.md describes. Covered: the offer after a real-shaped job, noAdsense, the Google window closed and blocked, a full queue, a 409 from a tab that lost its job, leaving and coming back to the same job with one sign-in and one POST, and a kept job the relay no longer has, which must not open Google's window until the creator presses. Jobs are polled every 200 ms under NEXT_PUBLIC_E2E, as the mock shortens its delays. Co-Authored-By: Claude Opus 5.5 --- fe/README.md | 6 +- fe/playwright.config.ts | 62 +++++++---- fe/src/lib/reclaim/index.ts | 4 +- fe/tests/e2e/relay.spec.ts | 198 ++++++++++++++++++++++++++++++++++++ fe/tsconfig.json | 4 +- 5 files changed, 252 insertions(+), 22 deletions(-) create mode 100644 fe/tests/e2e/relay.spec.ts diff --git a/fe/README.md b/fe/README.md index a822bbf..e319d92 100644 --- a/fe/README.md +++ b/fe/README.md @@ -42,8 +42,10 @@ pnpm test:e2e # Playwright, tests/e2e It uses Playwright's own Chromium. Google Chrome works too (`PW_CHANNEL=chrome`), but on a Mac with a Chrome update pending, Chrome's updater can keep a finished run from exiting. It starts its own `next dev` on port 3219 (or `PW_PORT`), built into `.next-e2e` (`NEXT_DIST_DIR`), so it runs -alongside your own `next dev`. Any other `NEXT_DIST_DIR` makes Next add its type folder to -`tsconfig.json`; do not commit that. It sets its own environment (`playwright.config.ts`): the test +alongside your own `next dev`. A second one, on the port after it and built into `.next-e2e-relay`, +has the relay and the Google client id set, for `tests/e2e/relay.spec.ts`: there Google's sign-in is +a stub on `window.google` and the spec answers the relay. Both folders' types are in `tsconfig.json`; +any other `NEXT_DIST_DIR` makes Next add its own, so do not commit that. It sets its own environment (`playwright.config.ts`): the test wallet (`NEXT_PUBLIC_E2E=1`), a fake RPC URL and a fake #16 API URL whose answers each spec decides (`tests/e2e/rpc.ts`, `tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no browser extension. diff --git a/fe/playwright.config.ts b/fe/playwright.config.ts index 3692093..1909826 100644 --- a/fe/playwright.config.ts +++ b/fe/playwright.config.ts @@ -3,35 +3,61 @@ import { defineConfig, devices } from "@playwright/test"; // End to end runs with the test wallet (NEXT_PUBLIC_E2E=1) and with every Stellar RPC call and #16 API // call answered by the spec itself (tests/e2e/rpc.ts, tests/e2e/api.ts), so a run never touches testnet // or a real API and never needs a browser extension. -// PW_PORT lets two worktrees run their e2e suites side by side. +// PW_PORT (and the port after it, for the relay build) lets two worktrees run their e2e suites side by side. const PORT = Number(process.env.PW_PORT ?? 3219); +const RELAY_PORT = PORT + 1; +const RELAY_SPEC = /relay\.spec\.ts$/; -export default defineConfig({ - testDir: "tests/e2e", - fullyParallel: true, - // Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run - // open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted. - use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" }, - projects: [ - { name: "desktop", use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } }, - { name: "mobile", use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } }, - ], - webServer: { - command: `npx next dev --port ${PORT}`, - port: PORT, +/** One dev server. `proving` sets the Reclaim seam: the mock (no relay) or the relay. */ +function server(port: number, distDir: string, proving: Record) { + return { + command: `npx next dev --port ${port}`, + port, // Never reuse whatever already listens on the port: it may be another app entirely. reuseExistingServer: false, timeout: 180_000, env: { - NEXT_DIST_DIR: ".next-e2e", + NEXT_DIST_DIR: distDir, NEXT_PUBLIC_E2E: "1", - // The Reclaim mock, whatever .env.local says. - NEXT_PUBLIC_RELAY_URL: "", + // The Reclaim mock or the stubbed relay, whatever .env.local says. + NEXT_PUBLIC_GOOGLE_CLIENT_ID: "", + ...proving, NEXT_PUBLIC_STELLAR_RPC_URL: "https://rpc.e2e.invalid", NEXT_PUBLIC_API_URL: "https://api.e2e.invalid", // Advance contract (dev), from docs/deployments.md. The stub answers for it; nothing is sent. NEXT_PUBLIC_ADVANCE_CONTRACT_ID: "CA3YGQHU42EL2TAOG7NJ5DDT5FLKKQNDWIUFFU6KV7QJHCFGLAGYXLID", NEXT_PUBLIC_USDC_ASSET: "USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5", }, - }, + }; +} + +export default defineConfig({ + testDir: "tests/e2e", + fullyParallel: true, + // Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run + // open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted. + use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" }, + projects: [ + { name: "desktop", testIgnore: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } }, + { name: "mobile", testIgnore: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } }, + // The real proving seam (#17), on a second build whose relay and Google client are set. The relay + // and Google's sign-in are answered by the spec (tests/e2e/relay.spec.ts). + { + name: "relay-desktop", + testMatch: RELAY_SPEC, + use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 }, baseURL: `http://localhost:${RELAY_PORT}` }, + }, + { + name: "relay-mobile", + testMatch: RELAY_SPEC, + use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 }, baseURL: `http://localhost:${RELAY_PORT}` }, + }, + ], + webServer: [ + server(PORT, ".next-e2e", { NEXT_PUBLIC_RELAY_URL: "" }), + server(RELAY_PORT, ".next-e2e-relay", { + NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid", + NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com", + }), + ], }); diff --git a/fe/src/lib/reclaim/index.ts b/fe/src/lib/reclaim/index.ts index 3db8997..6b0e172 100644 --- a/fe/src/lib/reclaim/index.ts +++ b/fe/src/lib/reclaim/index.ts @@ -22,11 +22,13 @@ export { const RELAY_URL = process.env.NEXT_PUBLIC_RELAY_URL ?? ""; const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? ""; +// The e2e relay answers at once, so its jobs are polled faster than a real one's. +const POLL_MS = process.env.NEXT_PUBLIC_E2E === "1" ? 200 : undefined; export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => void): ProveSession { if (!RELAY_URL) return mockProveRevenue(borrower, onStage); if (!GOOGLE_CLIENT_ID) return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} }; - return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID) }); + return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID), pollMs: POLL_MS }); } /** A proof the relay is still making for this wallet, started from this tab before the creator left. */ diff --git a/fe/tests/e2e/relay.spec.ts b/fe/tests/e2e/relay.spec.ts new file mode 100644 index 0000000..6bb00bd --- /dev/null +++ b/fe/tests/e2e/relay.spec.ts @@ -0,0 +1,198 @@ +import { expect, test, type Page } from "@playwright/test"; +import { E2E_ADDRESS } from "../../src/lib/stellar/wallet-e2e"; +import { frameLedger, mockApi } from "./api"; +import { mockRpc } from "./rpc"; + +// #17: proving through the relay, on the build whose NEXT_PUBLIC_RELAY_URL and Google client id are set +// (the relay-* projects in playwright.config.ts). Google's sign-in is a stub on `window.google`, which +// lib/reclaim/relay.ts uses when it is already there, and the relay is answered here as docs/api.md +// describes it. Everything after the proof is the stubbed contract, as in advance.spec.ts. + +test.afterEach(async ({ page }) => { + await page.unrouteAll({ behavior: "ignoreErrors" }); +}); + +/** What Google's popup does when it opens: hand back a token, close, be blocked, or stay open. */ +type Popup = "ok" | "closed" | "blocked" | "open"; + +type Gis = { mode: Popup; opened: number }; +declare global { + interface Window { + __gis: Gis; + } +} + +/** A stand-in for Google Identity Services' token client, counting the popups it opens. */ +async function stubGoogle(page: Page, mode: Popup) { + await page.addInitScript((m: Popup) => { + window.__gis = { mode: m, opened: 0 }; + type Config = { scope: string; callback: (r: object) => void; error_callback?: (e: object) => void }; + window.google = { + accounts: { + oauth2: { + initTokenClient: (c: Config) => ({ + requestAccessToken: () => { + window.__gis.opened++; + const now = window.__gis.mode; + setTimeout(() => { + if (now === "ok") c.callback({ access_token: "ya29.e2e", scope: c.scope }); + else if (now === "closed") c.error_callback?.({ type: "popup_closed" }); + else if (now === "blocked") c.error_callback?.({ type: "popup_failed_to_open" }); + }, 600); + }, + }), + }, + }, + } as unknown as Window["google"]; + }, mode); +} + +const opened = (page: Page) => page.evaluate(() => window.__gis.opened); + +const REQUEST = { + revenueUsd: "360.00", + pubId: "pub-4021783466891204", + windowStart: "2026-07-01", + windowEnd: "2026-09-30", + epoch: "1", + signature: "5a".repeat(64), + recoveryId: 0, +}; + +/** + * The relay. `post` answers POST /proofs; `jobs` lists the states each job id answers in turn (the last + * one repeats); an id not there answers 404. While `hold` is set, every job answers `proving`. + */ +type Relay = { + post: { status: number; body: object }; + jobs: Record; + hold?: boolean; + posts: { borrower: string; accessToken: string }[]; +}; + +function relayFor(jobs: Relay["jobs"] = { j1: [{ id: "j1", stage: "proving" }, done("j1")] }): Relay { + return { post: { status: 202, body: { id: "j1", stage: "queued" } }, jobs, posts: [] }; +} + +function done(id: string) { + return { id, stage: "done", request: { ...REQUEST, timestampS: String(Math.floor(Date.now() / 1000)) } }; +} + +async function mockRelay(page: Page, relay: Relay) { + await page.route("https://relay.e2e.invalid/**", async (route) => { + const headers = { "access-control-allow-origin": "*" }; + const req = route.request(); + const { pathname } = new URL(req.url()); + if (req.method() === "POST" && pathname === "/proofs") { + relay.posts.push(req.postDataJSON()); + return route.fulfill({ status: relay.post.status, headers, contentType: "application/json", body: JSON.stringify(relay.post.body) }); + } + const id = decodeURIComponent(pathname.replace(/^\/proofs\//, "")); + const states = relay.jobs[id]; + if (!states) return route.fulfill({ status: 404, headers, contentType: "application/json", body: '{"error":"no such proof job"}' }); + const state = relay.hold ? { id, stage: "proving" } : states.length > 1 ? states.shift() : states[0]; + return route.fulfill({ headers, contentType: "application/json", body: JSON.stringify(state) }); + }); +} + +async function connect(page: Page, relay: Relay, popup: Popup) { + await stubGoogle(page, popup); + await mockRelay(page, relay); + await mockRpc(page, { account: true, trustline: true }); + await mockApi(page, frameLedger()); + await page.goto("/start"); + await page.getByRole("button", { name: "Get started" }).click(); + await page.getByRole("button", { name: "Connect wallet" }).click(); + await page.getByRole("dialog", { name: "Connect wallet" }).getByRole("button").first().click(); + await expect(page).toHaveURL(/\/advance$/); +} + +const heading = (page: Page, name: string) => page.getByRole("heading", { name, exact: true }); +const prove = (page: Page) => page.getByRole("button", { name: "Prove my revenue" }).click(); + +test("signs in with Google, the relay proves, and the offer follows", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(page.getByText("This takes about a minute, longer when others are proving too.", { exact: false })).toBeVisible(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toEqual([{ borrower: E2E_ADDRESS, accessToken: "ya29.e2e" }]); + expect(await opened(page)).toBe(1); +}); + +test("a Google account with no AdSense the relay can read is named", async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code: "account", message: "no AdSense account" } }] }); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "We found no approved AdSense account")).toBeVisible(); + await expect(page.getByText("This Google account has no AdSense account we can read.", { exact: false })).toBeVisible(); + await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); +}); + +test("closing Google's window is named, and proving can start again", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "closed"); + await prove(page); + await expect(heading(page, "You closed the Google window")).toBeVisible(); + expect(relay.posts).toEqual([]); + await page.evaluate(() => (window.__gis.mode = "ok")); + await prove(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); +}); + +test("a blocked Google window is named as blocked, not closed", async ({ page }) => { + await connect(page, relayFor(), "blocked"); + await prove(page); + await expect(heading(page, "Your browser blocked the Google window")).toBeVisible(); +}); + +test("a relay whose queue is full says Forepay is busy", async ({ page }) => { + const relay = relayFor(); + relay.post = { status: 503, body: { error: "the prover is busy", code: "busy" } }; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Forepay is busy right now")).toBeVisible(); +}); + +test("a proof already running from a tab that lost it says to wait for it, not to pick it up", async ({ page }) => { + const relay = relayFor(); + relay.post = { status: 409, body: { error: "a proof for this borrower is already running", code: "running" } }; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Your proof is already being made")).toBeVisible(); + await expect(page.getByText("Wait a few minutes for it to end, then prove again.", { exact: false })).toBeVisible(); +}); + +test("leaving while the relay proves and coming back waits on the same job, with no second sign-in", async ({ page }) => { + const relay = relayFor(); + relay.hold = true; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + // The top nav on desktop, the tab bar on a phone: whichever is shown. + await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); + await expect(page).toHaveURL(/\/history$/); + relay.hold = false; + await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toHaveLength(1); + expect(await opened(page)).toBe(1); +}); + +test("a kept job the relay no longer has gets its own panel, and opens Google's window only from a press", async ({ page }) => { + await page.addInitScript((borrower) => { + if (window.location.pathname === "/start") { + window.sessionStorage.setItem("forepay.proof.job", JSON.stringify({ borrower, id: "old" })); + } + }, E2E_ADDRESS); + const relay = relayFor(); + await connect(page, relay, "ok"); + await expect(heading(page, "Your earlier proof has ended")).toBeVisible(); + expect(await opened(page)).toBe(0); + expect(relay.posts).toEqual([]); + await prove(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(await opened(page)).toBe(1); +}); diff --git a/fe/tsconfig.json b/fe/tsconfig.json index 86a7b93..38c3de8 100644 --- a/fe/tsconfig.json +++ b/fe/tsconfig.json @@ -36,7 +36,9 @@ ".next/dev/types/**/*.ts", "**/*.mts", ".next-e2e/types/**/*.ts", - ".next-e2e/dev/types/**/*.ts" + ".next-e2e/dev/types/**/*.ts", + ".next-e2e-relay/types/**/*.ts", + ".next-e2e-relay/dev/types/**/*.ts" ], "exclude": [ "node_modules" From 9914ec0f3d914575f68e364be0b5600d09757212 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:47:33 +0700 Subject: [PATCH 7/9] fix(#17): relay panels say only what is true, and coming back never flashes 2a From the strict review of the four commits before this one: - proofGone: "Your earlier proof is gone", worded for both causes (the relay restarted, or an hour passed); the proof did not necessarily finish. Proof-expired illustration. - noAdsense covers all of the relay's `account` cases: none, several, or not approved. - popupBlocked and googleUnavailable: "Nothing was read or charged", like relayBusy. The cancelled panel keeps the board's "Nothing was read or saved"; the previous commit's body overstated how far that rule went. - The relay panels pair "Prove again" with "Back" in a row, as the board's pairs do; "Prove my revenue" did not fit half the row. - Back on /advance with a kept job, "Reading your revenue" shows from the first render, as a pending advance does, so 2a's button never flashes. - Comments: why accept has no clock check on the proof (simulation refuses with 12 before the wallet is asked), the reading copy describes the relay, and JOB_KEY holds one wallet. Co-Authored-By: Claude Opus 5.5 --- fe/src/lib/errors.ts | 14 ++++---- fe/src/lib/reclaim/relay.ts | 2 ++ fe/src/modules/advance/Advance.tsx | 34 +++++++++++++++---- .../advance/components/FailurePanel.tsx | 15 ++++---- 4 files changed, 45 insertions(+), 20 deletions(-) diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 9f9ec6c..4c95cc0 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -211,11 +211,11 @@ export function contractFailureCopy(code: number): FailureCopy { * - `walletLocked`, `walletWrongNetwork`, `walletNoAnswer`: the wallet could not sign, for that reason. * - `relayNotReady`: proofs are meant to come from the #17 relay, and this build cannot reach it. * - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one. - * - `noAdsense`: the Google account has no approved AdSense account the relay can read. + * - `noAdsense`: the Google account has no AdSense account, several, or one that is not approved (relay `account`). * - `relayFailed`: the relay could not make the proof, on its side. Nothing was charged. * - `relayBusy`: the relay is proving for others and its queue is full. * - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it. - * - `proofGone`: the proof this tab was waiting on ended while the creator was away, and is no longer kept. + * - `proofGone`: the relay no longer has the proof this tab was waiting on (it restarted, or an hour passed). * - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked. * - `googleUnavailable`: Google's sign-in did not load. * - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing. @@ -329,7 +329,7 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): case "noAdsense": return { title: "We found no approved AdSense account", - body: "This Google account has no AdSense account we can read. Sign in with the account that owns your AdSense, then try again. Nothing was charged.", + body: "We could not find one approved AdSense account on this Google account. Sign in with the account that owns your AdSense, then try again. Nothing was charged.", }; case "relayFailed": return { @@ -348,8 +348,8 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): }; case "proofGone": return { - title: "Your earlier proof has ended", - body: "It finished while you were away, and is no longer kept. Prove your revenue again, it takes about a minute. Nothing was charged.", + title: "Your earlier proof is gone", + body: "We no longer have the proof you started earlier. Prove your revenue again, it takes about a minute. Nothing was charged.", }; case "relayUnreachable": return { @@ -359,12 +359,12 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): case "googleUnavailable": return { title: "Google sign-in did not load", - body: "Nothing was read or saved. Check your connection, then try again.", + body: "Nothing was read or charged. Check your connection, then try again.", }; case "popupBlocked": return { title: "Your browser blocked the Google window", - body: "Allow pop-ups for Forepay, then try again. Nothing was read or saved.", + body: "Allow pop-ups for Forepay, then try again. Nothing was read or charged.", }; } } diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts index 55668b1..63d8028 100644 --- a/fe/src/lib/reclaim/relay.ts +++ b/fe/src/lib/reclaim/relay.ts @@ -115,6 +115,8 @@ export type JobStore = { clear: () => void; }; +// One slot for the tab: proving with a second wallet in the same tab replaces the first wallet's id. +// Rare, and that wallet then proves again once its job ends. const JOB_KEY = "forepay.proof.job"; /** diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index ee53f35..0e2b3f8 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -56,6 +56,20 @@ class AbandonedError extends Error {} const quoteKey = (address: string, revenueUsd: string) => ["quote", address, revenueUsd] as const; const sizingKey = (address: string) => ["sizing", address] as const; +/** + * "Reading your revenue". The words describe the relay (#17): about a minute, more behind a queue, and + * the job id is kept for the tab, so other pages are safe and a closed tab loses it (lib/reclaim/relay.ts). + * The mock (no relay) does not resume after leaving, which is acceptable for a build without proofs. + */ +function ReadingRevenue() { + return ( + + ); +} + /** * 02 Prove and accept (#20): 2a Prove revenue, 2b Review offer, 2c Sign, 2d Receive, and every state on * the "Prove and accept / States and interactions" board. @@ -208,6 +222,9 @@ export function Advance() { } async function accept(r: AdvanceRequest) { + // No clock check on the proof's age here: `requestAdvance` simulates before it asks the wallet, and the + // contract refuses a proof over an hour old with 12 ("This proof expired"), so no signature is asked + // for a stale proof (e2e "a proof that expires while the offer is open…"). leave(); const id = attempt.current; let signed = false; @@ -378,6 +395,16 @@ export function Advance() { if (flow.at === "start") { // A transaction left waiting from an earlier visit is picked up by the effect above, after this // first render. Show it as sending from the start, so 2a and its "Prove my revenue" never flash. + // Likewise a proof the relay is still making for this wallet: the effect waits on it. + if (proofRunning(me)) { + return ( + + + + + + ); + } if (loadPending(me)) { return ( @@ -422,12 +449,7 @@ export function Advance() { } /> ) : ( - // About a minute on the relay, more behind a queue. The job id is kept for the tab, so other - // pages are safe; a closed tab loses it (lib/reclaim/relay.ts). - + )} diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index 98d9b36..aeabd54 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -124,22 +124,23 @@ export function FailurePanel({ illustration = ; actions = ; break; + case "proofGone": + illustration = ; + actions = <>{proveAgain}{back}; + row = true; + break; + // The relay's failures (#17). Not on the board yet; "Prove again" with "Back", as its pairs are. case "googleSignIn": case "noAdsense": case "relayFailed": case "relayBusy": case "proofRunning": - case "proofGone": case "relayUnreachable": case "googleUnavailable": case "popupBlocked": illustration = ; - actions = ( - <> - - {back} - - ); + actions = <>{proveAgain}{back}; + row = true; break; case "declined": illustration = ; From ec245afee9e1322085a1e3d609054a8b8662bfbc Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:47:33 +0700 Subject: [PATCH 8/9] test(#17): pin the relay's remaining panels, the preload and the resume, and make the relay build optional - Unit: a poll that fails on the network keeps the id, and the next press reaches gone with no sign-in. The relay kinds' "Nothing was charged" claims are asserted. - e2e: token and prove failures with Prove again, a relay that does not answer, Google's script loading on 2a before any press, the script failing to load, and no flash of 2a's button when coming back to a running proof. - PW_RELAY=0 leaves out the relay dev server and its projects, for quicker single-spec runs. README and .env.example say what the second build and NEXT_PUBLIC_E2E now do. Co-Authored-By: Claude Opus 5.5 --- fe/.env.example | 3 +- fe/README.md | 12 +++-- fe/playwright.config.ts | 39 +++++++++------- fe/src/lib/errors.test.ts | 7 +++ fe/src/lib/reclaim/relay.test.ts | 23 ++++++++++ fe/tests/e2e/relay.spec.ts | 79 +++++++++++++++++++++++++++++--- 6 files changed, 135 insertions(+), 28 deletions(-) diff --git a/fe/.env.example b/fe/.env.example index 9c1778d..7ec6fee 100644 --- a/fe/.env.example +++ b/fe/.env.example @@ -25,5 +25,6 @@ NEXT_PUBLIC_GOOGLE_CLIENT_ID= # WalletConnect, for mobile wallets. From the Reown dashboard. NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID= -# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet. +# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet, and shortens the +# Reclaim mock's delays and the wait between polls of a relay job. NEXT_PUBLIC_E2E= diff --git a/fe/README.md b/fe/README.md index e319d92..ae59758 100644 --- a/fe/README.md +++ b/fe/README.md @@ -44,11 +44,13 @@ a Chrome update pending, Chrome's updater can keep a finished run from exiting. `next dev` on port 3219 (or `PW_PORT`), built into `.next-e2e` (`NEXT_DIST_DIR`), so it runs alongside your own `next dev`. A second one, on the port after it and built into `.next-e2e-relay`, has the relay and the Google client id set, for `tests/e2e/relay.spec.ts`: there Google's sign-in is -a stub on `window.google` and the spec answers the relay. Both folders' types are in `tsconfig.json`; -any other `NEXT_DIST_DIR` makes Next add its own, so do not commit that. It sets its own environment (`playwright.config.ts`): the test -wallet (`NEXT_PUBLIC_E2E=1`), a fake RPC URL and a fake #16 API URL whose answers each spec decides -(`tests/e2e/rpc.ts`, `tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no -browser extension. +a stub and the spec answers the relay. Every run starts both, which takes longer and needs both +ports free; `PW_RELAY=0` leaves the relay build and its specs out. Both folders' types are in +`tsconfig.json`; any other `NEXT_DIST_DIR` makes Next add its own, so do not commit that. + +It sets its own environment (`playwright.config.ts`): the test wallet (`NEXT_PUBLIC_E2E=1`), a fake +RPC URL and a fake #16 API URL whose answers each spec decides (`tests/e2e/rpc.ts`, +`tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no browser extension. ## Environment diff --git a/fe/playwright.config.ts b/fe/playwright.config.ts index 1909826..98863b3 100644 --- a/fe/playwright.config.ts +++ b/fe/playwright.config.ts @@ -6,6 +6,8 @@ import { defineConfig, devices } from "@playwright/test"; // PW_PORT (and the port after it, for the relay build) lets two worktrees run their e2e suites side by side. const PORT = Number(process.env.PW_PORT ?? 3219); const RELAY_PORT = PORT + 1; +// PW_RELAY=0 leaves out the relay build and its specs, for a quicker run of the others. +const RELAY = process.env.PW_RELAY !== "0"; const RELAY_SPEC = /relay\.spec\.ts$/; /** One dev server. `proving` sets the Reclaim seam: the mock (no relay) or the relay. */ @@ -31,6 +33,18 @@ function server(port: number, distDir: string, proving: Record) }; } +/** + * The real proving seam (#17), on a second build whose relay and Google client are set. The relay + * and Google's sign-in are answered by the spec (tests/e2e/relay.spec.ts). + */ +function relayProjects() { + const use = { baseURL: `http://localhost:${RELAY_PORT}` }; + return [ + { name: "relay-desktop", testMatch: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 }, ...use } }, + { name: "relay-mobile", testMatch: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 }, ...use } }, + ]; +} + export default defineConfig({ testDir: "tests/e2e", fullyParallel: true, @@ -40,24 +54,17 @@ export default defineConfig({ projects: [ { name: "desktop", testIgnore: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } }, { name: "mobile", testIgnore: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } }, - // The real proving seam (#17), on a second build whose relay and Google client are set. The relay - // and Google's sign-in are answered by the spec (tests/e2e/relay.spec.ts). - { - name: "relay-desktop", - testMatch: RELAY_SPEC, - use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 }, baseURL: `http://localhost:${RELAY_PORT}` }, - }, - { - name: "relay-mobile", - testMatch: RELAY_SPEC, - use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 }, baseURL: `http://localhost:${RELAY_PORT}` }, - }, + ...(RELAY ? relayProjects() : []), ], webServer: [ server(PORT, ".next-e2e", { NEXT_PUBLIC_RELAY_URL: "" }), - server(RELAY_PORT, ".next-e2e-relay", { - NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid", - NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com", - }), + ...(RELAY + ? [ + server(RELAY_PORT, ".next-e2e-relay", { + NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid", + NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com", + }), + ] + : []), ], }); diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index 1ecf8bd..fda9173 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -143,6 +143,13 @@ describe("proveFailureCopy", () => { it("says nothing was charged only when that is true", () => { expect(proveFailureCopy("refused").body).toMatch(/Nothing was charged/); + // The relay's failures happen before anything reaches Stellar. + for (const k of ["googleSignIn", "noAdsense", "relayFailed", "proofRunning", "proofGone", "relayUnreachable"] as const) { + expect(proveFailureCopy(k).body).toMatch(/Nothing was charged/); + } + for (const k of ["relayBusy", "googleUnavailable", "popupBlocked"] as const) { + expect(proveFailureCopy(k).body).toMatch(/Nothing was read or charged/); + } expect(proveFailureCopy("charged").body).not.toMatch(/Nothing was charged/); expect(proveFailureCopy("unconfirmed").body).not.toMatch(/Nothing was charged/); }); diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts index f0581f5..92b5be6 100644 --- a/fe/src/lib/reclaim/relay.test.ts +++ b/fe/src/lib/reclaim/relay.test.ts @@ -166,6 +166,29 @@ describe("relayProveRevenue", () => { expect(t.kept).toBeNull(); }); + it("a poll that fails on the network keeps the id; the next press follows it and a 404 is still gone, with no sign-in", async () => { + const t = store({ borrower: BORROWER, id: "gone" }); + let down = true; + const fetch = (async () => { + if (down) throw new TypeError("Failed to fetch"); + return new Response(JSON.stringify({ error: "no such proof job" }), { status: 404 }); + }) as unknown as typeof globalThis.fetch; + let signIns = 0; + const signIn: SignIn = async () => { + signIns++; + return "ya29.token"; + }; + const o = { relayUrl: "https://r", signIn, fetch, sleep: noSleep, jobs: t.jobs }; + const first = await relayProveRevenue(BORROWER, () => {}, o).result.catch((x) => x); + expect((first as RelayError).code).toBe("unreachable"); + expect(t.kept).toEqual({ borrower: BORROWER, id: "gone" }); + down = false; + const second = await relayProveRevenue(BORROWER, () => {}, o).result.catch((x) => x); + expect((second as RelayError).code).toBe("gone"); + expect(signIns).toBe(0); + expect(t.kept).toBeNull(); + }); + it("after a gone job, the next press signs in and starts a fresh proof", async () => { const t = store({ borrower: BORROWER, id: "gone" }); const fetch = (async (url: string, init?: RequestInit) => { diff --git a/fe/tests/e2e/relay.spec.ts b/fe/tests/e2e/relay.spec.ts index 6bb00bd..661e535 100644 --- a/fe/tests/e2e/relay.spec.ts +++ b/fe/tests/e2e/relay.spec.ts @@ -95,8 +95,9 @@ async function mockRelay(page: Page, relay: Relay) { }); } -async function connect(page: Page, relay: Relay, popup: Popup) { - await stubGoogle(page, popup); +/** `popup` null leaves `window.google` unset, so the app loads Google's script itself (routed by the test). */ +async function connect(page: Page, relay: Relay, popup: Popup | null) { + if (popup) await stubGoogle(page, popup); await mockRelay(page, relay); await mockRpc(page, { account: true, trustline: true }); await mockApi(page, frameLedger()); @@ -109,6 +110,7 @@ async function connect(page: Page, relay: Relay, popup: Popup) { const heading = (page: Page, name: string) => page.getByRole("heading", { name, exact: true }); const prove = (page: Page) => page.getByRole("button", { name: "Prove my revenue" }).click(); +const proveAgain = (page: Page) => page.getByRole("button", { name: "Prove again" }).click(); test("signs in with Google, the relay proves, and the offer follows", async ({ page }) => { const relay = relayFor(); @@ -127,8 +129,9 @@ test("a Google account with no AdSense the relay can read is named", async ({ pa await connect(page, relay, "ok"); await prove(page); await expect(heading(page, "We found no approved AdSense account")).toBeVisible(); - await expect(page.getByText("This Google account has no AdSense account we can read.", { exact: false })).toBeVisible(); - await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); + await expect(page.getByText("We could not find one approved AdSense account on this Google account.", { exact: false })).toBeVisible(); + await expect(page.getByRole("button", { name: "Prove again" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Back" })).toBeVisible(); }); test("closing Google's window is named, and proving can start again", async ({ page }) => { @@ -189,10 +192,74 @@ test("a kept job the relay no longer has gets its own panel, and opens Google's }, E2E_ADDRESS); const relay = relayFor(); await connect(page, relay, "ok"); - await expect(heading(page, "Your earlier proof has ended")).toBeVisible(); + await expect(heading(page, "Your earlier proof is gone")).toBeVisible(); expect(await opened(page)).toBe(0); expect(relay.posts).toEqual([]); - await prove(page); + await proveAgain(page); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); expect(await opened(page)).toBe(1); }); + +for (const { what, code, title } of [ + { what: "Google refusing the token", code: "token", title: "Google did not let us read AdSense" }, + { what: "a proof that failed on the relay", code: "prove", title: "We could not finish your proof" }, +]) { + test(`${what} is named, and Prove again starts over`, async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code, message: "x" } }] }); + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, title)).toBeVisible(); + relay.jobs.j1 = [done("j1")]; + await proveAgain(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + }); +} + +test("a relay that does not answer is named as Forepay, not Stellar", async ({ page }) => { + await connect(page, relayFor(), "ok"); + await page.route("https://relay.e2e.invalid/proofs", (route) => route.abort("connectionrefused")); + await prove(page); + await expect(heading(page, "We could not reach Forepay")).toBeVisible(); +}); + +test("Google's script loads while 2a is open, before any press", async ({ page }) => { + let loads = 0; + await page.route("https://accounts.google.com/gsi/client", (route) => { + loads++; + return route.fulfill({ contentType: "text/javascript", body: "window.google = { accounts: { oauth2: { initTokenClient: () => ({ requestAccessToken() {} }) } } };" }); + }); + await connect(page, relayFor(), null); + await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); + await expect.poll(() => loads).toBe(1); + await prove(page); + await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); + expect(loads).toBe(1); +}); + +test("Google's script failing to load is named, not taken for a closed window", async ({ page }) => { + await page.route("https://accounts.google.com/gsi/client", (route) => route.abort("connectionrefused")); + await connect(page, relayFor(), null); + await prove(page); + await expect(heading(page, "Google sign-in did not load")).toBeVisible(); +}); + +test("coming back with a proof still running shows it at once, never 2a's button", async ({ page }) => { + const relay = relayFor(); + relay.hold = true; + await connect(page, relay, "ok"); + await prove(page); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); + await expect(page).toHaveURL(/\/history$/); + // Watch every change to the page from here on: 2a's button must never be put on it. + await page.evaluate(() => { + const w = window as unknown as { __sawProve: boolean }; + w.__sawProve = false; + new MutationObserver(() => { + if ([...document.querySelectorAll("button")].some((b) => b.textContent === "Prove my revenue")) w.__sawProve = true; + }).observe(document.body, { childList: true, subtree: true }); + }); + await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); + await expect(heading(page, "Reading your revenue")).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { __sawProve: boolean }).__sawProve)).toBe(false); +}); From 2fdfa597abf7a0d42f5ca2c2eb87e12b36290ce2 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:54:42 +0700 Subject: [PATCH 9/9] fix(#17): Back with a kept job waits on it, and noAdsense's title fits every account case From the strict re-review: - A failure that keeps the job id (a poll that failed on the network) left "Back" on a "Reading your revenue" spinner with nothing running: the start screen shows it for a kept job, and toStart() never started the session. toStart() now waits on the kept job, as it does on a pending advance. Two e2e: Back after a failed poll reaches the offer with one sign-in and one POST; Back after a gone job returns to 2a. - noAdsense: "We could not use your AdSense account", true for none, several, or not approved. Co-Authored-By: Claude Opus 5.5 --- fe/src/lib/errors.ts | 2 +- fe/src/modules/advance/Advance.tsx | 3 +++ fe/tests/e2e/relay.spec.ts | 28 +++++++++++++++++++++++++++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 4c95cc0..9656763 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -328,7 +328,7 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): }; case "noAdsense": return { - title: "We found no approved AdSense account", + title: "We could not use your AdSense account", body: "We could not find one approved AdSense account on this Google account. Sign in with the account that owns your AdSense, then try again. Nothing was charged.", }; case "relayFailed": diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index 0e2b3f8..1994966 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -168,6 +168,9 @@ export function Advance() { // While an advance sent earlier is still being waited on, the start is that wait, not 2a. const pending = loadPending(me); if (pending) return void pickUp(pending); + // Likewise a proof the relay may still be making (a poll that failed kept its id): wait on it, so + // "Reading your revenue" on the start is always backed by a running session. + if (proofRunning(me)) return void prove(); setFlow({ at: "start" }); } diff --git a/fe/tests/e2e/relay.spec.ts b/fe/tests/e2e/relay.spec.ts index 661e535..b361427 100644 --- a/fe/tests/e2e/relay.spec.ts +++ b/fe/tests/e2e/relay.spec.ts @@ -128,7 +128,7 @@ test("a Google account with no AdSense the relay can read is named", async ({ pa const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code: "account", message: "no AdSense account" } }] }); await connect(page, relay, "ok"); await prove(page); - await expect(heading(page, "We found no approved AdSense account")).toBeVisible(); + await expect(heading(page, "We could not use your AdSense account")).toBeVisible(); await expect(page.getByText("We could not find one approved AdSense account on this Google account.", { exact: false })).toBeVisible(); await expect(page.getByRole("button", { name: "Prove again" })).toBeVisible(); await expect(page.getByRole("button", { name: "Back" })).toBeVisible(); @@ -263,3 +263,29 @@ test("coming back with a proof still running shows it at once, never 2a's button await expect(heading(page, "Reading your revenue")).toBeVisible(); expect(await page.evaluate(() => (window as unknown as { __sawProve: boolean }).__sawProve)).toBe(false); }); + +test("Back after a poll that failed waits on the same job, never a spinner with nothing behind it", async ({ page }) => { + const relay = relayFor(); + await connect(page, relay, "ok"); + await page.route("https://relay.e2e.invalid/proofs/j1", (route) => route.abort("connectionrefused")); + await prove(page); + await expect(heading(page, "We could not reach Forepay")).toBeVisible(); + await page.unroute("https://relay.e2e.invalid/proofs/j1"); + await page.getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts).toHaveLength(1); + expect(await opened(page)).toBe(1); +}); + +test("Back after a kept job the relay no longer has returns to 2a", async ({ page }) => { + await page.addInitScript((borrower) => { + if (window.location.pathname === "/start") { + window.sessionStorage.setItem("forepay.proof.job", JSON.stringify({ borrower, id: "old" })); + } + }, E2E_ADDRESS); + await connect(page, relayFor(), "ok"); + await expect(heading(page, "Your earlier proof is gone")).toBeVisible(); + await page.getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); + expect(await opened(page)).toBe(0); +});