diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/README.md b/packages/browser-sdk/example/feedback-after-submit-demo/README.md new file mode 100644 index 000000000..99ba556b7 --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/README.md @@ -0,0 +1,41 @@ +# `onAfterSubmit` timing demo + +Shows the real gap between a user submitting feedback and `onAfterSubmit` +firing, and proves what happens to that callback — and to the feedback +itself — if the tab goes away before the request completes. + +Builds the actual widget from this branch's `src/`, talking to a local mock +API instead of `front.reflag.com`. + +## Run it + +From the repo root, with dependencies installed for `@reflag/browser-sdk` +(`yarn install` once): + +```sh +cd packages/browser-sdk +node example/feedback-after-submit-demo/start.mjs +``` + +Open the printed URL (defaults to `http://localhost:5183`). + +## What to look at + +1. **Artificial latency** — widen the delay so the gap between submit and + `onAfterSubmit` is easy to see. +2. **Live widget** — submit feedback for real. The banner stays red for as + long as the request is pending (`onAfterSubmit` has not run yet) and only + turns green once the callback actually fires. +3. **Navigate away mid-submit** — fires the same request the widget's Send + button does, then navigates away before the response can arrive, + simulating a closed tab. The table's "server actually received it?" column + is ground truth from the mock API's own log, independent of whatever the + tab believes happened. On localhost this often still arrives — the request + is tiny and loopback latency is near zero, so sending finishes before the + navigation can interrupt it. On a real network that's not guaranteed: + without `keepalive` (which the SDK doesn't set for this request), a slower + connection can lose it outright; the `keepalive` checkbox bypasses the SDK + to show what setting it would buy you. What's guaranteed every time, + regardless of network speed or `keepalive`, is the other column: the + client never sees `onAfterSubmit` fire, because the page that would have + run it is gone. diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/gone.html b/packages/browser-sdk/example/feedback-after-submit-demo/gone.html new file mode 100644 index 000000000..964adda47 --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/gone.html @@ -0,0 +1,39 @@ + + + + + Tab closed (simulated) + + + +

💥 This page just replaced the one that submitted feedback

+

+ Exactly like closing the tab or clicking a link right after hitting Send: + whatever JavaScript was waiting on the feedback response is gone now. No + onAfterSubmit can fire here — there is no callback left + to call it on. +

+

Returning to the demo in a few seconds to check what the server saw…

+ + + diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/index.html b/packages/browser-sdk/example/feedback-after-submit-demo/index.html new file mode 100644 index 000000000..e67f351bf --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/index.html @@ -0,0 +1,230 @@ + + + + + + onAfterSubmit timing demo + + + +

Does onAfterSubmit survive the user closing the tab?

+

+ onAfterSubmit only fires once the feedback POST to Reflag + resolves, which means there is a real gap between the user clicking Send/a + score and the callback actually running. This page makes that gap visible, + and then proves what happens if the tab goes away before it closes. +

+ +
+

1. Artificial network latency

+

+ Widens the gap between submit and onAfterSubmit so it's + easy to watch. The mock API server delays its response by this many + milliseconds. +

+
+ + + +
+
+ +
+

2. Live widget

+

+ Open the real feedback widget (built from this branch's + src/, not a mock) and submit a score/comment. Watch the + banner and log below. +

+ +
+
+
+ +
+

3. Prove it: navigate away mid-submit

+

+ This calls the exact same feedback() request the widget's + Send button triggers, then navigates away a moment later — simulating + the user closing the tab (or clicking a link) right after submitting, + before the response comes back. "Server actually received it?" is ground + truth from the mock API's own log, independent of anything the browser + tab believes happened. +

+

+ On localhost, the request body is tiny and the round-trip to the mock + server is near-instant, so it often finishes sending before the + navigation can interrupt it — the row below may well show the server + received it either way. On a real network, with real latency, that's + not guaranteed: without `keepalive`, closing the tab can lose the + request outright. What is guaranteed, every time, is the + other column: the client never sees onAfterSubmit fire, + because the page that would have run it is gone. +

+
+ +
+
+ + +
+ + + + + + + + + + + + +
AttemptModeSentClient saw onAfterSubmit?Server actually received it?Verdict
+

+ Every row here is a deliberately interrupted attempt — that's the + point of this button. "Client saw onAfterSubmit?" reproduces the + widget's own await-then-notify sequence; "no" means the page was gone + before that sequence could finish. +

+
+ + + + diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/main.ts b/packages/browser-sdk/example/feedback-after-submit-demo/main.ts new file mode 100644 index 000000000..d4ca3e9de --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/main.ts @@ -0,0 +1,304 @@ +import { ReflagClient } from "../../src"; + +const FLAG_KEY = "demo-flag"; +const ATTEMPTS_STORAGE_KEY = "reflag-demo-attempts"; +const API_BASE = `${location.origin}/api`; + +// --- Event log (section 2: the live widget) ------------------------------ + +const logEl = document.querySelector("#log")!; +const bannerEl = document.querySelector("#risk-banner")!; + +let pendingSince: number | null = null; +let requestInFlight = false; +let bannerTimer: number | undefined; + +function logLine(text: string, kind: "ok" | "pending" | "err" = "pending") { + const line = document.createElement("div"); + line.className = kind; + const t = new Date().toLocaleTimeString([], { hour12: false }); + line.textContent = `[${t}] ${text}`; + logEl.appendChild(line); + logEl.scrollTop = logEl.scrollHeight; +} + +function openRiskWindow() { + pendingSince = performance.now(); + requestInFlight = true; + bannerEl.className = "pending"; + tickBanner(); + if (bannerTimer === undefined) + bannerTimer = window.setInterval(tickBanner, 50); +} + +function onFeedbackRequestSettled() { + // The POST resolved, so the data is safely on the server. onAfterSubmit is + // still deferred until Send or a dialog close, by design (see + // withFeedbackSubmissionCallback) — so an abrupt tab close here loses the + // callback even though it would NOT lose the feedback itself. + requestInFlight = false; + tickBanner(); +} + +function tickBanner() { + if (pendingSince === null) return; + const elapsed = Math.round(performance.now() - pendingSince); + bannerEl.textContent = requestInFlight + ? `⚠ request pending for ${elapsed}ms — closing the tab right now would lose this feedback entirely. onAfterSubmit has NOT fired yet.` + : `⚠ response received ${elapsed}ms ago, feedback is saved server-side — but onAfterSubmit is still waiting on Send or the dialog closing. Closing the tab right now would lose the callback (not the data).`; +} + +function closeRiskWindow(fired: boolean) { + if (bannerTimer !== undefined) { + clearInterval(bannerTimer); + bannerTimer = undefined; + } + if (pendingSince === null) return; + const elapsed = Math.round(performance.now() - pendingSince); + pendingSince = null; + requestInFlight = false; + if (fired) { + bannerEl.className = "resolved"; + bannerEl.textContent = `✓ onAfterSubmit fired after ${elapsed}ms. Safe to close the tab now.`; + } +} + +// Intercept fetch purely to see exactly when the request to /api/feedback +// leaves the browser and when its response comes back — this is the gap +// onAfterSubmit waits out, observed from the outside without touching the +// widget's internals. +const originalFetch = window.fetch.bind(window); +window.fetch = (input, init) => { + const url = String(input instanceof Request ? input.url : input); + const method = + init?.method ?? (input instanceof Request ? input.method : "GET"); + const isFeedbackSubmit = url.endsWith("/api/feedback") && method === "POST"; + + if (isFeedbackSubmit) { + logLine("→ POST /feedback sent", "pending"); + openRiskWindow(); + } + + const result = originalFetch(input, init); + + if (isFeedbackSubmit) { + result + .then(() => { + logLine("← response received from server", "ok"); + onFeedbackRequestSettled(); + }) + .catch(() => { + logLine("✕ request failed/aborted", "err"); + onFeedbackRequestSettled(); + }); + } + + return result; +}; + +// --- Reflag client --------------------------------------------------------- + +const reflag = new ReflagClient({ + publishableKey: "demo-publishable-key", + user: { id: "demo-user" }, + company: { id: "demo-company" }, + apiBaseUrl: API_BASE, + enableTracking: false, + feedback: { enableAutoFeedback: false }, +}); + +reflag.initialize(); + +document.querySelector("#open-widget")!.addEventListener("click", (event) => { + reflag.requestFeedback({ + flagKey: FLAG_KEY, + title: "How do you like this demo?", + position: { type: "POPOVER", anchor: event.currentTarget as HTMLElement }, + onAfterSubmit: (data) => { + logLine( + `✓ onAfterSubmit called (score=${data.score}, comment=${JSON.stringify(data.comment)}, feedbackId=${data.feedbackId})`, + "ok", + ); + closeRiskWindow(true); + }, + }); +}); + +// --- Artificial latency control -------------------------------------------- + +const delayInput = document.querySelector("#delay-input")!; +const delayStatus = document.querySelector("#delay-status")!; + +async function refreshDelay() { + const res = await fetch(`${API_BASE}/log`); + const { delayMs } = await res.json(); + delayInput.value = String(delayMs); + delayStatus.textContent = `current: ${delayMs}ms`; +} + +document.querySelector("#apply-delay")!.addEventListener("click", async () => { + const delayMs = Number(delayInput.value); + const res = await fetch(`${API_BASE}/config`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ delayMs }), + }); + const body = await res.json(); + delayStatus.textContent = `current: ${body.delayMs}ms`; +}); + +refreshDelay(); + +// --- Danger zone: navigate away mid-submit ---------------------------------- + +type Attempt = { + id: string; + mode: "sdk (no keepalive)" | "raw fetch (keepalive)"; + sentAt: number; + clientConfirmedAt: number | null; + serverConfirmedAt: number | null; +}; + +function loadAttempts(): Attempt[] { + try { + return JSON.parse(localStorage.getItem(ATTEMPTS_STORAGE_KEY) ?? "[]"); + } catch { + return []; + } +} + +function saveAttempts(attempts: Attempt[]) { + localStorage.setItem(ATTEMPTS_STORAGE_KEY, JSON.stringify(attempts)); +} + +function renderAttempts( + serverReceived: { attemptId: string | null; receivedAt: number }[], +) { + const attempts = loadAttempts(); + const tbody = document.querySelector("#attempts tbody")!; + tbody.innerHTML = ""; + + for (const attempt of attempts) { + const serverHit = serverReceived.find((r) => r.attemptId === attempt.id); + if (serverHit && !attempt.serverConfirmedAt) { + attempt.serverConfirmedAt = serverHit.receivedAt; + } + + const clientOk = attempt.clientConfirmedAt !== null; + const serverOk = attempt.serverConfirmedAt !== null; + + let verdict: string; + let verdictClass: string; + if (clientOk && serverOk) { + verdict = "delivered, callback fired"; + verdictClass = "verdict-ok"; + } else if (!clientOk && serverOk) { + verdict = + "server got it, but onAfterSubmit never ran — don't rely on it for anything that must survive navigation"; + verdictClass = "verdict-partial"; + } else { + verdict = + "feedback lost entirely — the request itself was killed by the navigation"; + verdictClass = "verdict-lost"; + } + + const row = document.createElement("tr"); + row.innerHTML = ` + ${attempt.id.slice(0, 8)} + ${attempt.mode} + ${new Date(attempt.sentAt).toLocaleTimeString([], { hour12: false })} + ${clientOk ? "yes" : "no"} + ${serverOk ? "yes" : "no"} + ${verdict} + `; + tbody.appendChild(row); + } + + saveAttempts(attempts); +} + +async function pollServerLog() { + const res = await fetch(`${API_BASE}/log`); + const { received } = await res.json(); + renderAttempts(received); +} + +setInterval(pollServerLog, 1000); +pollServerLog(); + +function markClientConfirmed(id: string) { + const attempts = loadAttempts(); + const attempt = attempts.find((a) => a.id === id); + if (attempt) attempt.clientConfirmedAt = Date.now(); + saveAttempts(attempts); +} + +document.querySelector("#run-danger")!.addEventListener("click", () => { + const id = crypto.randomUUID(); + const useKeepalive = + document.querySelector("#use-keepalive")!.checked; + const comment = `[demo:${id}] sent right before navigating away`; + + const attempts = loadAttempts(); + attempts.push({ + id, + mode: useKeepalive ? "raw fetch (keepalive)" : "sdk (no keepalive)", + sentAt: Date.now(), + clientConfirmedAt: null, + serverConfirmedAt: null, + }); + saveAttempts(attempts); + + // Reproduces exactly what the widget's Send button does: await the POST, + // then call onAfterSubmit. `reflag.feedback()` is the same method the + // widget's onSubmit handler calls; `keepalive` isn't something the SDK + // exposes, so that variant bypasses it entirely to show what a fix for the + // *data-loss* half of the problem could look like. Either way, the + // `.then()` below — standing in for onAfterSubmit — never gets a chance to + // run: the navigation below destroys the page before the response arrives. + const request = useKeepalive + ? fetch(`${API_BASE}/feedback`, { + method: "POST", + keepalive: true, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + key: FLAG_KEY, + userId: "demo-user", + companyId: "demo-company", + score: 5, + comment, + source: "widget", + }), + }) + : reflag.feedback({ flagKey: FLAG_KEY, score: 5, comment }); + + request.then(() => markClientConfirmed(id)); + + logLine( + `→ sent attempt ${id.slice(0, 8)}, navigating away in 30ms…`, + "pending", + ); + + setTimeout(() => { + location.href = `gone.html?attempt=${id}`; + }, 30); +}); + +document.querySelector("#reset")!.addEventListener("click", async () => { + localStorage.removeItem(ATTEMPTS_STORAGE_KEY); + await fetch(`${API_BASE}/reset`, { method: "POST" }); + logEl.innerHTML = ""; + await pollServerLog(); +}); + +// If we just came back from gone.html, highlight that this round-trip proves +// the point: reloading this script resets all in-memory state, so the only +// way `clientConfirmedAt` gets set below is if onAfterSubmit manages to run +// before navigation — which, for the danger-zone button, it never does. +const params = new URLSearchParams(location.search); +if (params.get("checkAttempt")) { + logLine( + `Back from navigating away mid-submit (attempt ${params.get("checkAttempt")!.slice(0, 8)}). Check the table below.`, + "err", + ); +} diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/server.mjs b/packages/browser-sdk/example/feedback-after-submit-demo/server.mjs new file mode 100644 index 000000000..a4ae8e592 --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/server.mjs @@ -0,0 +1,109 @@ +import { randomUUID } from "node:crypto"; +import http from "node:http"; + +// Minimal mock of the Reflag API, just enough for the feedback widget demo: +// - GET /features/evaluated so ReflagClient.initialize() resolves +// - POST /feedback the endpoint the widget's onSubmit/onScoreSubmit calls, +// delayed by `state.delayMs` to make the async gap visible +// - GET /log, POST /reset ground truth for what the server actually received, +// independent of whatever the browser tab believes happened + +const MIN_DELAY_MS = 0; +const MAX_DELAY_MS = 20_000; + +const state = { + delayMs: 1500, + received: [], +}; + +const ATTEMPT_RE = /\[demo:([a-f0-9-]+)\]/i; + +function send(res, status, body) { + const json = JSON.stringify(body); + res.writeHead(status, { + "Content-Type": "application/json", + "Access-Control-Allow-Origin": "*", + }); + res.end(json); +} + +function readBody(req) { + return new Promise((resolve, reject) => { + let data = ""; + req.on("data", (chunk) => (data += chunk)); + req.on("end", () => { + try { + resolve(data ? JSON.parse(data) : {}); + } catch (e) { + reject(e); + } + }); + req.on("error", reject); + }); +} + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, "http://localhost"); + + if (req.method === "GET" && url.pathname === "/features/evaluated") { + return send(res, 200, { success: true, features: {} }); + } + + if (req.method === "POST" && url.pathname === "/feedback/prompting-init") { + return send(res, 200, { success: false }); + } + + if (req.method === "POST" && url.pathname === "/feedback") { + const body = await readBody(req); + const receivedAt = Date.now(); + + // Simulate real-world network/processing latency, so the window between + // "request sent" and "onAfterSubmit fires" is long enough to see. + await new Promise((resolve) => setTimeout(resolve, state.delayMs)); + + const feedbackId = randomUUID(); + const attemptMatch = ATTEMPT_RE.exec(body.comment ?? ""); + + state.received.push({ + feedbackId, + receivedAt, + respondedAt: Date.now(), + score: body.score, + comment: body.comment, + attemptId: attemptMatch?.[1] ?? null, + }); + + return send(res, 200, { feedbackId }); + } + + if (req.method === "GET" && url.pathname === "/log") { + return send(res, 200, { delayMs: state.delayMs, received: state.received }); + } + + if (req.method === "POST" && url.pathname === "/config") { + const body = await readBody(req); + const requestedDelay = body.delayMs; + // Reject anything out of range rather than clamping it, so the value + // the timer below ever sees is always one we validated ourselves. + if ( + Number.isFinite(requestedDelay) && + requestedDelay >= MIN_DELAY_MS && + requestedDelay <= MAX_DELAY_MS + ) { + state.delayMs = requestedDelay; + } + return send(res, 200, { delayMs: state.delayMs }); + } + + if (req.method === "POST" && url.pathname === "/reset") { + state.received = []; + return send(res, 200, { ok: true }); + } + + send(res, 404, { error: "not found", path: url.pathname }); +}); + +const PORT = Number(process.env.PORT ?? 4100); +server.listen(PORT, () => { + console.log(`[mock-api] listening on http://localhost:${PORT}`); +}); diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/start.mjs b/packages/browser-sdk/example/feedback-after-submit-demo/start.mjs new file mode 100644 index 000000000..c518e5451 --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/start.mjs @@ -0,0 +1,31 @@ +import { spawn } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { createServer } from "vite"; + +const dir = path.dirname(fileURLToPath(import.meta.url)); + +const api = spawn(process.execPath, [path.join(dir, "server.mjs")], { + stdio: "inherit", +}); + +const vite = await createServer({ + configFile: path.join(dir, "vite.config.mjs"), +}); +await vite.listen(); +vite.printUrls(); + +function shutdown() { + api.kill(); + vite.close().finally(() => process.exit(0)); +} + +process.on("SIGINT", shutdown); +process.on("SIGTERM", shutdown); +api.on("exit", (code) => { + if (code !== 0 && code !== null) { + console.error(`[mock-api] exited with code ${code}`); + shutdown(); + } +}); diff --git a/packages/browser-sdk/example/feedback-after-submit-demo/vite.config.mjs b/packages/browser-sdk/example/feedback-after-submit-demo/vite.config.mjs new file mode 100644 index 000000000..100958c63 --- /dev/null +++ b/packages/browser-sdk/example/feedback-after-submit-demo/vite.config.mjs @@ -0,0 +1,17 @@ +import { defineConfig } from "vite"; + +const API_PORT = Number(process.env.PORT ?? 4100); + +export default defineConfig({ + root: __dirname, + server: { + port: 5183, + strictPort: true, + proxy: { + "/api": { + target: `http://localhost:${API_PORT}`, + rewrite: (path) => path.replace(/^\/api/, ""), + }, + }, + }, +});