-
Notifications
You must be signed in to change notification settings - Fork 120
feat(browser): headless user feedback API #1155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+260
−7
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
338c1b5
feat(browser): headless user feedback API
Makisuo 5a40027
Merge branch 'feat/browser-sdk-error-replay' into feat/browser-sdk-fe…
Makisuo 1af65de
fix(browser): has_replay reflects the buffered replay feedback keeps
Makisuo 04e5138
fix(browser): forget the last error when the SDK restarts
Makisuo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| // TEST-SEAM: This focused test replaces process-global modules that have no instance-level injection seam. | ||
| import type { ReadableLogRecord } from "@opentelemetry/sdk-logs" | ||
| import type { ReadableSpan } from "@opentelemetry/sdk-trace-base" | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" | ||
|
|
||
| const exportedSpans: ReadableSpan[] = [] | ||
| const exportedLogs: ReadableLogRecord[] = [] | ||
| const exporter = <T>(sink: T[]) => | ||
| class { | ||
| export(items: T[], callback: (result: { code: number }) => void): void { | ||
| sink.push(...items) | ||
| callback({ code: 0 }) | ||
| } | ||
| forceFlush(): Promise<void> { | ||
| return Promise.resolve() | ||
| } | ||
| shutdown(): Promise<void> { | ||
| return Promise.resolve() | ||
| } | ||
| } | ||
| vi.mock("@opentelemetry/exporter-trace-otlp-http", () => ({ OTLPTraceExporter: exporter(exportedSpans) })) | ||
| vi.mock("@opentelemetry/exporter-logs-otlp-http", () => ({ OTLPLogExporter: exporter(exportedLogs) })) | ||
|
|
||
| const { MapleBrowser } = await import("./index") | ||
| const { resetFeedbackForTests } = await import("./feedback") | ||
| const { resetReportedErrorsForTests } = await import("./errors") | ||
|
|
||
| type InitConfig = Parameters<typeof MapleBrowser.init>[0] | ||
| const BASE: InitConfig = { | ||
| ingestKey: "k", | ||
| serviceName: "web", | ||
| endpoint: "https://ingest.test", | ||
| replay: { enabled: false }, | ||
| tracing: { instrumentFetch: false, instrumentXhr: false }, | ||
| webVitals: false, | ||
| breadcrumbs: false, | ||
| } | ||
|
|
||
| let handle: ReturnType<typeof MapleBrowser.init> | undefined | ||
| const stop = async (): Promise<void> => { | ||
| await handle?.shutdown() | ||
| handle = undefined | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.stubGlobal( | ||
| "fetch", | ||
| vi.fn(async () => new Response("{}")), | ||
| ) | ||
| }) | ||
|
|
||
| afterEach(async () => { | ||
| await stop() | ||
| exportedSpans.length = 0 | ||
| exportedLogs.length = 0 | ||
| resetFeedbackForTests() | ||
| resetReportedErrorsForTests() | ||
| vi.unstubAllGlobals() | ||
| }) | ||
|
|
||
| const feedback = () => exportedLogs.filter((log) => log.eventName === "maple.user_feedback") | ||
|
|
||
| describe("MapleBrowser.sendFeedback", () => { | ||
| it("sends a feedback event linked to the last error the user hit", async () => { | ||
| handle = MapleBrowser.init(BASE) | ||
| MapleBrowser.captureException(new Error("checkout failed")) | ||
| expect( | ||
| MapleBrowser.sendFeedback({ | ||
| message: " the pay button does nothing ", | ||
| email: "ada@example.com", | ||
| name: "Ada", | ||
| attributes: { "feedback.category": "bug" }, | ||
| }), | ||
| ).toBe(true) | ||
| await stop() | ||
|
|
||
| const error = exportedSpans.find((span) => span.name === "exception") | ||
| const [sent] = feedback() | ||
| expect(sent?.body).toBe("the pay button does nothing") | ||
| expect(sent?.attributes["user.email"]).toBe("ada@example.com") | ||
| expect(sent?.attributes["user.name"]).toBe("Ada") | ||
| expect(sent?.attributes["feedback.category"]).toBe("bug") | ||
| expect(sent?.attributes["maple.feedback.error_trace_id"]).toBe(error?.spanContext().traceId) | ||
| expect(sent?.spanContext?.spanId).toBe(error?.spanContext().spanId) | ||
| expect(typeof sent?.attributes["session.id"]).toBe("string") | ||
| }) | ||
|
|
||
| it("does not link feedback to an error from before a shutdown and re-init", async () => { | ||
| handle = MapleBrowser.init(BASE) | ||
| MapleBrowser.captureException(new Error("old page state")) | ||
| await stop() | ||
| handle = MapleBrowser.init(BASE) | ||
| MapleBrowser.sendFeedback({ message: "still broken" }) | ||
| await stop() | ||
| expect(feedback()[0]?.attributes["maple.feedback.error_trace_id"]).toBeUndefined() | ||
| }) | ||
|
|
||
| it("keeps the email out when captureUserEmail is off, and sends nothing without a message", async () => { | ||
| handle = MapleBrowser.init({ ...BASE, privacy: { captureUserEmail: false } }) | ||
| expect(MapleBrowser.sendFeedback({ message: " " })).toBe(false) | ||
| MapleBrowser.sendFeedback({ message: "slow", email: "ada@example.com" }) | ||
| await stop() | ||
| expect(feedback()).toHaveLength(1) | ||
| expect(feedback()[0]?.attributes["user.email"]).toBeUndefined() | ||
| expect(feedback()[0]?.attributes["maple.feedback.error_trace_id"]).toBeUndefined() | ||
| }) | ||
|
|
||
| it("reports has_replay for the buffered replay the feedback itself keeps", async () => { | ||
| // Headless Chromium's user agent is classified as a bot, which never gets replay. | ||
| Object.defineProperty(navigator, "userAgent", { | ||
| value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36", | ||
| configurable: true, | ||
| }) | ||
| const urls: string[] = [] | ||
| vi.stubGlobal( | ||
| "fetch", | ||
| vi.fn(async (input: RequestInfo | URL) => { | ||
| urls.push(String(input)) | ||
| return new Response("{}") | ||
| }), | ||
| ) | ||
| try { | ||
| handle = MapleBrowser.init({ ...BASE, replay: { sampleRate: 0, onErrorSampleRate: 1 } }) | ||
| await vi.waitFor(() => | ||
| expect(urls.some((url) => url.endsWith("/v1/sessionReplays/meta"))).toBe(true), | ||
| ) | ||
| MapleBrowser.sendFeedback({ message: "it froze" }) | ||
| await stop() | ||
| expect(feedback()[0]?.attributes["maple.feedback.has_replay"]).toBe(true) | ||
| } finally { | ||
| Reflect.deleteProperty(navigator, "userAgent") | ||
| sessionStorage.clear() | ||
| } | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| // End-user feedback ("this page is broken"), as an OTel log event linked to | ||
| // the session and to the last error the user hit. Headless: bring your own UI. | ||
| import { getSession, hasConsent } from "@maple/browser-session" | ||
| import type { SpanContext } from "@opentelemetry/api" | ||
| import { onErrorRecorded } from "./errors" | ||
| import { emitLog, type LogAttributeValue, Severity } from "./logs" | ||
|
|
||
| export interface FeedbackInput { | ||
| /** What the user wrote. Required; trimmed and capped at 5,000 characters. */ | ||
| readonly message: string | ||
| /** Sent as `user.email` unless `privacy.captureUserEmail` is false. */ | ||
| readonly email?: string | undefined | ||
| /** Sent as `user.name`. */ | ||
| readonly name?: string | undefined | ||
| /** Extra attributes, e.g. `{ "feedback.category": "bug" }`. */ | ||
| readonly attributes?: Readonly<Record<string, LogAttributeValue>> | undefined | ||
| } | ||
|
|
||
| const MAX_MESSAGE = 5_000 | ||
|
|
||
| let lastError: SpanContext | undefined | ||
| let captureEmail = true | ||
| /** Keeps a buffered replay; set by `init()`. */ | ||
| let keepReplay: () => void = () => {} | ||
|
|
||
| // Module-level: the last error is whatever the user saw most recently, whichever `init()` recorded it. | ||
| onErrorRecorded((spanContext) => { | ||
| lastError = spanContext | ||
| }) | ||
|
|
||
| export function configureFeedback(options: { | ||
| readonly captureUserEmail: boolean | ||
| readonly keepReplay: () => void | ||
| }): void { | ||
| captureEmail = options.captureUserEmail | ||
| keepReplay = options.keepReplay | ||
| // init() and shutdown() both start a new lifecycle: an earlier error's trace is not this one's. | ||
| lastError = undefined | ||
| } | ||
|
|
||
| export function resetFeedbackForTests(): void { | ||
| lastError = undefined | ||
| captureEmail = true | ||
| keepReplay = () => {} | ||
| } | ||
|
|
||
| /** Send feedback. Returns false when there was nothing to send (empty message, no consent). */ | ||
| export function sendFeedback(input: FeedbackInput): boolean { | ||
| const message = String(input.message ?? "") | ||
| .trim() | ||
| .slice(0, MAX_MESSAGE) | ||
| if (!message || !hasConsent()) return false | ||
| const email = captureEmail ? input.email?.trim() : undefined | ||
| const name = input.name?.trim() | ||
| // Keep a buffered replay first: the trigger marks the session recorded synchronously, so | ||
| // `has_replay` then reflects the minute this feedback just kept. | ||
| keepReplay() | ||
| const recorded = typeof window === "undefined" ? false : getSession().replaySampled === true | ||
| emitLog({ | ||
| eventName: "maple.user_feedback", | ||
| severityNumber: Severity.INFO, | ||
| severityText: "INFO", | ||
| body: message, | ||
| spanContext: lastError, | ||
| attributes: { | ||
| ...input.attributes, | ||
| ...(email ? { "user.email": email } : undefined), | ||
| ...(name ? { "user.name": name } : undefined), | ||
| ...(lastError ? { "maple.feedback.error_trace_id": lastError.traceId } : undefined), | ||
| "maple.feedback.has_replay": recorded, | ||
| }, | ||
| }) | ||
| return true | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.