Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat(desktop): quality rewards: tier badge, notices, spin wheel

ogsamrat7ccd254dd4a0
diff --git a/apps/app/src/app/index.css b/apps/app/src/app/index.css
index f6f9f9df..22f740ea 100644
--- a/apps/app/src/app/index.css
+++ b/apps/app/src/app/index.css
@@ -824,3 +824,19 @@ select:disabled {
[data-update-gate-shifted] .min-h-screen {
min-height: 100%;
}
+
+/* Quality rewards wheel (react-app/domains/quality/quality-wheel.tsx): the
+ rim's bulbs chase while it spins. */
+@keyframes quality-wheel-bulb {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.25; }
+}
+[data-spinning="true"] .quality-wheel-bulb {
+ animation: quality-wheel-bulb 0.45s ease-in-out infinite;
+}
+[data-spinning="true"] .quality-wheel-bulb:nth-of-type(even) {
+ animation-delay: 0.22s;
+}
+@media (prefers-reduced-motion: reduce) {
+ [data-spinning="true"] .quality-wheel-bulb { animation: none; }
+}
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index 3e6ca377..19e18c85 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -750,6 +750,9 @@ const {
sandboxCleanupOmniRushContainers,
omnirushServerInfo,
omnirushAccountStatus,
+ omnirushQualityDetails,
+ omnirushQualitySpins,
+ omnirushQualitySpin,
omnirushAccountConnect,
omnirushAccountSignOut,
omnirushServerRestart,
@@ -810,6 +813,9 @@ export {
sandboxCleanupOmniRushContainers,
omnirushServerInfo,
omnirushAccountStatus,
+ omnirushQualityDetails,
+ omnirushQualitySpins,
+ omnirushQualitySpin,
omnirushAccountConnect,
omnirushAccountSignOut,
omnirushServerRestart,
diff --git a/apps/app/src/app/lib/quality.ts b/apps/app/src/app/lib/quality.ts
new file mode 100644
index 00000000..393a3ce0
--- /dev/null
+++ b/apps/app/src/app/lib/quality.ts
@@ -0,0 +1,326 @@
+// Quality rewards, renderer side. The Electron main process reads `quality`
+// from /device/me (apps/desktop/electron/quality.mjs) and spins the wheel
+// with the device credential; these helpers decide what the sidebar badge,
+// the notice popup and the spin dialog show. The server picks every prize:
+// the app only animates the wheel to `segmentIndex` and renders its flags.
+
+import { create } from "zustand";
+
+import type {
+ OmniRushAccountQuality,
+ OmniRushAccountStatus,
+ OmniRushQualityNotice,
+ OmniRushQualitySpin,
+ OmniRushQualitySpinOutcome,
+ OmniRushQualityTier,
+ OmniRushWheelSegment,
+} from "@omnirush/types/desktop-ipc";
+
+import { compactTokenCount } from "./omnirush-usage";
+
+export type AccountQuality = OmniRushAccountQuality;
+export type QualitySpin = OmniRushQualitySpin;
+export type QualitySpinOutcome = OmniRushQualitySpinOutcome;
+export type QualityTier = OmniRushQualityTier;
+export type WheelSegment = OmniRushWheelSegment;
+export type QualityNotice = OmniRushQualityNotice;
+
+/** The wheel as the API documents it; used until GET /me/quality answers. */
+export const DEFAULT_WHEEL_SEGMENTS: WheelSegment[] = [
+ { tokens: 250_000, weight: 35 },
+ { tokens: 500_000, weight: 30 },
+ { tokens: 1_000_000, weight: 20 },
+ { tokens: 2_000_000, weight: 10 },
+ { tokens: 5_000_000, weight: 4 },
+ { tokens: 10_000_000, weight: 1 },
+];
+
+const TIER_LABELS: Record<QualityTier, string> = {
+ new: "New",
+ standard: "Standard",
+ gold: "Gold",
+ coaching: "Coaching",
+ limited: "Limited",
+};
+
+export function qualityTierLabel(tier: QualityTier): string {
+ return TIER_LABELS[tier] ?? "Standard";
+}
+
+/** The badge's text: "Gold", or "Gold · Preview" while spins pay nothing. */
+export function qualityBadgeText(quality: AccountQuality): string {
+ return quality.preview ? `${qualityTierLabel(quality.tier)} · Preview` : qualityTierLabel(quality.tier);
+}
+
+/** The badge's tooltip: the hint to the next tier and, while limited, the token cut. */
+export function qualityBadgeTitle(quality: AccountQuality): string {
+ const parts = [`Quality: ${qualityTierLabel(quality.tier)}`];
+ if (quality.tokensMultiplier < 1) parts.push(`tokens ×${quality.tokensMultiplier}`);
+ if (quality.preview) parts.push("preview: spins pay 0 tokens");
+ const head = parts.join(" · ");
+ return quality.nextTierHint ? `${head}\n${quality.nextTierHint}` : head;
+}
+
+/** Whether the spin button can spin now: spins left, and not all of them held back by a resting wheel. */
+export function canSpinNow(quality: AccountQuality | null | undefined): boolean {
+ if (!quality || quality.spinsAvailable <= 0) return false;
+ return !quality.resting || quality.reproSpinsAvailable > 0;
+}
+
+// --- Notices, nudges: once per id ---------------------------------------
+
+export const NOTICE_SEEN_STORAGE_KEY = "omnirush.quality.lastNoticeId.v1";
+export const NUDGE_SEEN_STORAGE_KEY = "omnirush.quality.lastNudgeId.v1";
+export const SOUND_STORAGE_KEY = "omnirush.quality.sound.v1";
+
+type KeyValueStore = Pick<Storage, "getItem" | "setItem">;
+
+function defaultStorage(): KeyValueStore | null {
+ try {
+ return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
+ } catch {
+ return null;
+ }
+}
+
+export function readPref(key: string, storage: KeyValueStore | null = defaultStorage()): string | null {
+ try {
+ return storage?.getItem(key) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function writePref(key: string, value: string, storage: KeyValueStore | null = defaultStorage()): void {
+ try {
+ storage?.setItem(key, value);
+ } catch {
+ // A full or blocked storage only means the notice may show once more.
+ }
+}
+
+/** The newest notice: `notices[0]`, or `notice` from a server without the list. */
+export function latestNotice(quality: AccountQuality | null | undefined): QualityNotice | null {
+ if (!quality) return null;
+ return quality.notices?.[0] ?? quality.notice ?? null;
+}
+
+/** The notice to pop up, or null when it was already seen (a new id is a new notice). */
+export function noticeToShow(quality: AccountQuality | null | undefined, lastSeenId: string | null): QualityNotice | null {
+ const notice = latestNotice(quality);
+ return notice && notice.id !== lastSeenId ? notice : null;
+}
+
+/** The server's nudge, once per id. Never guessed on the client. */
+export function nudgeToShow(
+ quality: AccountQuality | null | undefined,
+ lastSeenId: string | null,
+): { id: string; text: string } | null {
+ const nudge = quality?.nudge ?? null;
+ return nudge && nudge.id !== lastSeenId ? nudge : null;
+}
+
+/** Coaching (and its reminders) reads as "here is how to get spins". */
+export function isCoachingNotice(notice: QualityNotice | null, quality: AccountQuality | null | undefined): boolean {
+ if (notice?.kind) return notice.kind === "tier-coaching" || notice.kind === "reminder-coaching";
+ return quality?.tier === "coaching";
+}
+
+// --- The wheel's geometry -------------------------------------------------
+
+export type WheelSlice = { index: number; start: number; end: number; mid: number; segment: WheelSegment };
+
+/**
+ * Slices in degrees clockwise from the top (where the pointer is), sized by
+ * `weight` so the wheel shows the real odds; equal slices when no weight is
+ * usable.
+ */
+export function wheelSlices(segments: WheelSegment[]): WheelSlice[] {
+ const total = segments.reduce((sum, segment) => sum + Math.max(0, segment.weight), 0);
+ let start = 0;
+ return segments.map((segment, index) => {
+ const share = total > 0 ? Math.max(0, segment.weight) / total : 1 / segments.length;
+ const end = index === segments.length - 1 ? 360 : start + share * 360;
+ const slice = { index, start, end, mid: (start + end) / 2, segment };
+ start = end;
+ return slice;
+ });
+}
+
+function mod360(value: number): number {
+ return ((value % 360) + 360) % 360;
+}
+
+/** The slice under the pointer when the wheel is turned `rotation` degrees clockwise. */
+export function sliceAtPointer(slices: WheelSlice[], rotation: number): number {
+ const at = mod360(-rotation);
+ const found = slices.find((slice) => at >= slice.start && at < slice.end);
+ return found ? found.index : slices.length - 1;
+}
+
+/**
+ * The rotation that stops slice `index` under the pointer, at least `turns`
+ * full turns past `from`. `offset` (-1..1) moves the stop inside the slice
+ * (0 is its middle), so the pointer never stops on a boundary.
+ */
+export function wheelTargetRotation(
+ segments: WheelSegment[],
+ index: number,
+ from = 0,
+ turns = 5,
+ offset = 0,
+): number {
+ const slices = wheelSlices(segments);
+ const slice = slices[Math.min(Math.max(0, index), slices.length - 1)];
+ if (!slice) return from;
+ const half = (slice.end - slice.start) / 2;
+ const clamped = Math.max(-0.7, Math.min(0.7, offset));
+ const stopAt = slice.mid + clamped * half;
+ const base = from + turns * 360;
+ return base + mod360(-stopAt - base);
+}
+
+/**
+ * The spin's shape over time: a short acceleration, a long deceleration
+ * that overshoots the stop by `overshoot` degrees, and a settle back onto
+ * it. `progress` is 0..1; the result goes from `from` to `to`.
+ */
+export function wheelAngleAt(progress: number, from: number, to: number, overshoot = 0): number {
+ const p = Math.min(1, Math.max(0, progress));
+ const distance = to - from;
+ const ACCEL = 0.12;
+ const SETTLE = 0.88;
+ // Velocity ramps up linearly over ACCEL and decays as a cubic after it, so
+ // the curve is smooth where the phases meet. Normalised so it ends on `to + overshoot`.
+ const accelArea = ACCEL / 2;
+ const decelArea = (SETTLE - ACCEL) / 4;
+ const total = accelArea + decelArea;
+ const reach = distance + overshoot;
+ if (p >= SETTLE) {
+ const q = (p - SETTLE) / (1 - SETTLE);
+ const ease = q * q * (3 - 2 * q);
+ return to + overshoot * (1 - ease);
+ }
+ if (p <= ACCEL) {
+ const area = (p * p) / (2 * ACCEL);
+ return from + reach * (area / total);
+ }
+ const d = (p - ACCEL) / (SETTLE - ACCEL);
+ const area = accelArea + ((SETTLE - ACCEL) * (1 - (1 - d) ** 4)) / 4;
+ return from + reach * (area / total);
+}
+
+/** How far the wheel may overshoot its stop without leaving the slice. */
+export function wheelOvershoot(segments: WheelSegment[], index: number, offset = 0): number {
+ const slice = wheelSlices(segments)[index];
+ if (!slice) return 0;
+ const half = (slice.end - slice.start) / 2;
+ const room = half * (1 - Math.max(-0.7, Math.min(0.7, offset)));
+ return Math.min(6, room * 0.6);
+}
+
+/** "12%": a segment's share of the weights. */
+export function segmentOdds(segments: WheelSegment[], index: number): string {
+ const total = segments.reduce((sum, segment) => sum + Math.max(0, segment.weight), 0);
+ const weight = Math.max(0, segments[index]?.weight ?? 0);
+ if (total <= 0) return `${Math.round(100 / Math.max(1, segments.length))}%`;
+ const share = (weight * 100) / total;
+ return share < 1 ? `${share.toFixed(1)}%` : `${Math.round(share)}%`;
+}
+
+// --- Spin outcome text ------------------------------------------------------
+
+export function spinRefusalMessage(reason: Exclude<QualitySpinOutcome, { ok: true }>["reason"]): string {
+ switch (reason) {
+ case "wheel_resting":
+ return "The wheel is resting, back tomorrow.";
+ case "no_spins":
+ return "No spins yet: good sessions earn spins.";
+ case "quality_rewards_off":
+ return "Quality rewards are switched off right now.";
+ case "signed_out":
+ return "Sign in to omnirush.ai to spin.";
+ case "unreachable":
+ return "omnirush.ai could not be reached. Try again in a moment.";
+ default:
+ return "The spin did not go through. Try again.";
+ }
+}
+
+/** The line under the prize: what the spin paid. */
+export function spinPayoutText(spin: QualitySpin): string {
+ if (spin.preview) return "Preview: no tokens paid";
+ if (spin.capped) return "Pot cap reached: this spin pays 0";
+ return `+${compactTokenCount(spin.tokens)} tokens added to your pot`;
+}
+
+/** The near-miss tease, only when the server flags it. */
+export function nearMissText(spin: QualitySpin): string | null {
+ if (!spin.nearMiss) return null;
+ const jackpot = spin.jackpotTokens || Math.max(...spin.segments.map((segment) => segment.tokens));
+ return `So close to ${compactTokenCount(jackpot)}!`;
+}
+
+export function newSpinIdempotencyKey(): string {
+ return globalThis.crypto.randomUUID();
+}
+
+// --- Shared account status (sidebar footer + notice popup) -----------------
+
+type AccountStatusStore = {
+ status: OmniRushAccountStatus | null;
+ set: (status: OmniRushAccountStatus | null) => void;
+};
+
+export const useAccountStatusStore = create<AccountStatusStore>((set) => ({
+ status: null,
+ set: (status) => set({ status }),
+}));
+
+let inFlight: Promise<OmniRushAccountStatus | null> | null = null;
+
+/**
+ * Reads the account status (/device/me) once for every caller in flight:
+ * the sidebar footer and the quality popup share one request.
+ */
+export function refreshAccountStatus(
+ read: () => Promise<OmniRushAccountStatus>,
+): Promise<OmniRushAccountStatus | null> {
+ inFlight ??= read()
+ .then((status) => {
+ useAccountStatusStore.getState().set(status);
+ return status;
+ })
+ .catch(() => {
+ const fallback = { connected: false, gatewayConfigured: false } satisfies OmniRushAccountStatus;
+ useAccountStatusStore.getState().set(fallback);
+ return fallback;
+ })
+ .finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+}
+
+export function useAccountQuality(): AccountQuality | null {
+ return useAccountStatusStore((store) => (store.status?.connected ? store.status.quality ?? null : null));
+}
+
+type QualityUiStore = {
+ /** The panel (notice, tips, streak, coaching) opened from the sidebar. */
+ panelOpen: boolean;
+ spinOpen: boolean;
+ openPanel: () => void;
+ closePanel: () => void;
+ openSpin: () => void;
+ closeSpin: () => void;
+};
+
+export const useQualityUiStore = create<QualityUiStore>((set) => ({
+ panelOpen: false,
+ spinOpen: false,
+ openPanel: () => set({ panelOpen: true }),
+ closePanel: () => set({ panelOpen: false }),
+ openSpin: () => set({ spinOpen: true, panelOpen: false }),
+ closeSpin: () => set({ spinOpen: false }),
+}));
diff --git a/apps/app/src/react-app/domains/quality/quality-notice.tsx b/apps/app/src/react-app/domains/quality/quality-notice.tsx
new file mode 100644
index 00000000..9f6d1570
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/quality-notice.tsx
@@ -0,0 +1,270 @@
+/** @jsxImportSource react */
+import { useCallback, useEffect, useState } from "react";
+import { ChevronDown, Gift, Lightbulb, Sparkles, X } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { omnirushAccountStatus, omnirushQualityDetails } from "../../../app/lib/desktop";
+import {
+ NOTICE_SEEN_STORAGE_KEY,
+ NUDGE_SEEN_STORAGE_KEY,
+ canSpinNow,
+ isCoachingNotice,
+ noticeToShow,
+ nudgeToShow,
+ qualityTierLabel,
+ readPref,
+ refreshAccountStatus,
+ useAccountQuality,
+ useQualityUiStore,
+ writePref,
+ type AccountQuality,
+ type QualityNotice,
+} from "../../../app/lib/quality";
+import type { OmniRushQualitySession } from "@omnirush/types/desktop-ipc";
+import { BiggestWinTicker, NextSpinHint, QualityTierBadge, StreakLine } from "./quality-parts";
+import { QualitySpinDialog } from "./quality-spin-dialog";
+
+const FAIL_LABELS: Record<string, string> = {
+ outside_path: "edits outside the project folder",
+ windows: "recorded on Windows",
+ no_tests: "no tests",
+ too_small: "too little work to count",
+};
+
+function failLabel(fail: string): string {
+ return FAIL_LABELS[fail] ?? fail.replace(/[_-]+/g, " ");
+}
+
+/** "See why": each recent session, with what earned spins and what held it back. */
+function SessionReasons({ sessions }: { sessions: OmniRushQualitySession[] | null }) {
+ if (sessions === null) return <div className="text-xs text-white/50">Loading your sessions…</div>;
+ if (!sessions.length) return <div className="text-xs text-white/50">No sessions checked yet. They are checked about once an hour.</div>;
+ return (
+ <ul className="space-y-2" data-testid="quality-session-reasons">
+ {sessions.slice(0, 6).map((session) => (
+ <li key={session.sessionId} className="rounded-xl border border-white/10 bg-black/20 px-3 py-2">
+ <div className="flex items-center justify-between gap-2 text-[11px] text-white/50">
+ <span className="truncate">{session.workspace ?? "session"}</span>
+ {session.spins > 0 ? (
+ <span className="shrink-0 font-semibold text-[#bef264]">+{session.spins} spin{session.spins === 1 ? "" : "s"}</span>
+ ) : null}
+ </div>
+ {session.why ? <div className="mt-0.5 text-xs leading-5 text-white/80">{session.why}</div> : null}
+ {session.fails.length ? (
+ <div className="mt-1 flex flex-wrap gap-1">
+ {session.fails.map((fail) => (
+ <span key={fail} className="rounded-full bg-white/[0.06] px-1.5 py-0.5 text-[10px] text-white/60">
+ {failLabel(fail)}
+ </span>
+ ))}
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+export type QualityNoticeCardProps = {
+ quality: AccountQuality;
+ /** The notice to announce; null when the user opened the panel from the sidebar. */
+ notice: QualityNotice | null;
+ onSpin: () => void;
+ onDismiss: () => void;
+ /** GET /me/quality sessions for "see why"; fetched when first opened. */
+ loadSessions?: () => Promise<OmniRushQualitySession[] | null>;
+};
+
+/**
+ * The quality popup, modelled on the update banner: fixed over the app,
+ * with the notice, the tips and, when spins are ready, a Spin button.
+ * Coaching reads as "here is how to get spins", never as a penalty.
+ */
+export function QualityNoticeCard(props: QualityNoticeCardProps) {
+ const { quality, notice } = props;
+ const coaching = isCoachingNotice(notice, quality);
+ const [whyOpen, setWhyOpen] = useState(false);
+ const [sessions, setSessions] = useState<OmniRushQualitySession[] | null>(null);
+ const title = notice?.title ?? `Quality: ${qualityTierLabel(quality.tier)}`;
+ const body = notice?.body || (notice ? "" : quality.nextTierHint ?? "");
+ const spinnable = canSpinNow(quality);
+
+ const toggleWhy = () => {
+ setWhyOpen((open) => !open);
+ if (sessions === null && props.loadSessions) {
+ void props.loadSessions().then((next) => setSessions(next ?? [])).catch(() => setSessions([]));
+ }
+ };
+
+ return (
+ <aside
+ role="status"
+ aria-live="polite"
+ data-testid="quality-notice"
+ data-notice-id={notice?.id ?? undefined}
+ data-coaching={coaching ? "" : undefined}
+ className="fixed bottom-4 right-4 z-[65] w-[380px] max-w-[calc(100vw-2rem)] overflow-hidden rounded-3xl border border-white/10 bg-[#0b1120]/95 text-white shadow-2xl shadow-black/50 backdrop-blur"
+ >
+ <div className={cn("h-1 w-full", coaching ? "bg-violet-300/70" : "bg-[#a3e635]")} />
+ <div className="p-5">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.2em] text-white/50">
+ {coaching ? <Lightbulb className="size-3.5 text-violet-300" /> : <Sparkles className="size-3.5 text-[#a3e635]" />}
+ {coaching ? "How to earn spins" : "Quality rewards"}
+ <QualityTierBadge quality={quality} />
+ </div>
+ <button
+ type="button"
+ onClick={props.onDismiss}
+ aria-label="Dismiss"
+ data-testid="quality-notice-dismiss"
+ className="-me-1 -mt-1 flex size-7 items-center justify-center rounded-full text-white/50 transition hover:bg-white/10 hover:text-white"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ <h3 className="mt-3 text-lg font-semibold leading-6 tracking-[-0.01em]" data-testid="quality-notice-title">{title}</h3>
+ {body ? <p className="mt-1.5 text-sm leading-6 text-white/70" data-testid="quality-notice-body">{body}</p> : null}
+
+ <div className="mt-3 space-y-2.5">
+ <StreakLine quality={quality} />
+ <NextSpinHint quality={quality} />
+ </div>
+
+ {quality.tips.length ? (
+ <ul className="mt-3 space-y-1.5 rounded-2xl border border-white/10 bg-white/[0.03] p-3" data-testid="quality-notice-tips">
+ {quality.tips.map((tip) => (
+ <li key={tip} className="flex gap-2 text-xs leading-5 text-white/75">
+ <span className="mt-[7px] size-1.5 shrink-0 rounded-full bg-[#a3e635]" aria-hidden="true" />
+ <span>{tip}</span>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {coaching ? (
+ <div className="mt-3">
+ <button
+ type="button"
+ onClick={toggleWhy}
+ aria-expanded={whyOpen}
+ data-testid="quality-see-why"
+ className="inline-flex items-center gap-1 text-xs font-medium text-violet-200 hover:text-violet-100"
+ >
+ See why
+ <ChevronDown className={cn("size-3.5 transition", whyOpen && "rotate-180")} />
+ </button>
+ {whyOpen ? <div className="mt-2 max-h-56 overflow-y-auto pe-1"><SessionReasons sessions={sessions} /></div> : null}
+ </div>
+ ) : null}
+
+ <BiggestWinTicker quality={quality} className="mt-3 w-fit" />
+
+ <div className="mt-4 flex items-center gap-2">
+ {quality.spinsAvailable > 0 ? (
+ <button
+ type="button"
+ onClick={props.onSpin}
+ disabled={!spinnable}
+ data-testid="quality-notice-spin"
+ className="inline-flex items-center gap-2 rounded-full bg-[#a3e635] px-4 py-2 text-sm font-bold text-[#1a2e05] shadow-[0_0_20px_rgba(163,230,53,0.4)] transition hover:bg-[#bef264] disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Gift className="size-4" aria-hidden="true" />
+ Spin{quality.spinsAvailable > 1 ? ` (${quality.spinsAvailable})` : ""}
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={props.onDismiss}
+ className="rounded-full px-3 py-2 text-sm font-medium text-white/60 transition hover:bg-white/10 hover:text-white"
+ >
+ Got it
+ </button>
+ {quality.spinsAvailable > 0 && !spinnable ? (
+ <span className="text-xs text-amber-200">The wheel is resting, back tomorrow.</span>
+ ) : null}
+ </div>
+ </div>
+ </aside>
+ );
+}
+
+/** The server's nudge, once per id. */
+export function QualityNudge(props: { text: string; onDismiss: () => void }) {
+ return (
+ <div
+ role="status"
+ data-testid="quality-nudge"
+ className="fixed bottom-4 right-4 z-[64] flex max-w-[360px] items-start gap-2 rounded-2xl border border-[#a3e635]/30 bg-[#0b1120]/95 px-4 py-3 text-sm text-white shadow-xl shadow-black/40"
+ >
+ <Sparkles className="mt-0.5 size-4 shrink-0 text-[#a3e635]" aria-hidden="true" />
+ <span className="leading-5 text-white/85">{props.text}</span>
+ <button type="button" onClick={props.onDismiss} aria-label="Dismiss" className="-me-1 text-white/50 hover:text-white">
+ <X className="size-4" />
+ </button>
+ </div>
+ );
+}
+
+const PROFILE_REFRESH_MS = 15 * 60_000;
+
+/**
+ * Quality rewards over the app: the notice popup (once per notice id), the
+ * panel the sidebar opens, the server's nudge (once per id) and the spin
+ * dialog. Renders nothing while `quality` is null (the feature is off).
+ */
+export function QualityRewards() {
+ const quality = useAccountQuality();
+ const panelOpen = useQualityUiStore((store) => store.panelOpen);
+ const spinOpen = useQualityUiStore((store) => store.spinOpen);
+ const [seenNotice, setSeenNotice] = useState(() => readPref(NOTICE_SEEN_STORAGE_KEY));
+ const [seenNudge, setSeenNudge] = useState(() => readPref(NUDGE_SEEN_STORAGE_KEY));
+
+ useEffect(() => {
+ const read = () => void refreshAccountStatus(omnirushAccountStatus);
+ read();
+ const timer = window.setInterval(read, PROFILE_REFRESH_MS);
+ return () => window.clearInterval(timer);
+ }, []);
+
+ const notice = noticeToShow(quality, seenNotice);
+ const nudge = nudgeToShow(quality, seenNudge);
+
+ const markNoticeSeen = useCallback(() => {
+ if (!notice) return;
+ writePref(NOTICE_SEEN_STORAGE_KEY, notice.id);
+ setSeenNotice(notice.id);
+ }, [notice]);
+
+ const dismiss = useCallback(() => {
+ markNoticeSeen();
+ useQualityUiStore.getState().closePanel();
+ }, [markNoticeSeen]);
+
+ const spin = useCallback(() => {
+ markNoticeSeen();
+ useQualityUiStore.getState().openSpin();
+ }, [markNoticeSeen]);
+
+ const loadSessions = useCallback(async () => (await omnirushQualityDetails())?.sessions ?? null, []);
+
+ if (!quality) return null;
+ const showCard = !spinOpen && (panelOpen || notice !== null);
+ return (
+ <>
+ {showCard ? (
+ <QualityNoticeCard quality={quality} notice={notice} onSpin={spin} onDismiss={dismiss} loadSessions={loadSessions} />
+ ) : nudge && !spinOpen ? (
+ <QualityNudge
+ text={nudge.text}
+ onDismiss={() => {
+ writePref(NUDGE_SEEN_STORAGE_KEY, nudge.id);
+ setSeenNudge(nudge.id);
+ }}
+ />
+ ) : null}
+ {spinOpen ? <QualitySpinDialog quality={quality} onClose={() => useQualityUiStore.getState().closeSpin()} /> : null}
+ </>
+ );
+}
diff --git a/apps/app/src/react-app/domains/quality/quality-parts.tsx b/apps/app/src/react-app/domains/quality/quality-parts.tsx
new file mode 100644
index 00000000..688a2fdb
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/quality-parts.tsx
@@ -0,0 +1,161 @@
+/** @jsxImportSource react */
+import { Flame, Gift, Trophy } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { compactTokenCount } from "../../../app/lib/omnirush-usage";
+import { qualityBadgeText, qualityBadgeTitle, type AccountQuality, type QualityTier } from "../../../app/lib/quality";
+
+const TIER_STYLES: Record<QualityTier, string> = {
+ new: "border-sky-400/40 bg-sky-400/10 text-sky-200",
+ standard: "border-slate-300/30 bg-slate-300/10 text-slate-200",
+ gold: "border-amber-300/60 bg-amber-300/15 text-amber-200",
+ coaching: "border-violet-300/45 bg-violet-300/10 text-violet-200",
+ limited: "border-rose-300/45 bg-rose-400/10 text-rose-200",
+};
+
+/** The tier, as a small pill. Dashed and dimmed in preview (spins pay nothing). */
+export function QualityTierBadge({ quality, className }: { quality: AccountQuality | null; className?: string }) {
+ // Null: quality rewards are switched off, and nothing shows.
+ if (!quality) return null;
+ return (
+ <span
+ data-testid="quality-tier-badge"
+ data-tier={quality.tier}
+ data-preview={quality.preview ? "" : undefined}
+ title={qualityBadgeTitle(quality)}
+ className={cn(
+ "inline-flex h-4 shrink-0 items-center gap-1 rounded-full border px-1.5 text-[9.5px] font-semibold uppercase leading-none tracking-[0.06em]",
+ TIER_STYLES[quality.tier],
+ quality.preview && "border-dashed opacity-80",
+ className,
+ )}
+ >
+ {quality.tier === "gold" ? <Trophy className="size-2.5" aria-hidden="true" /> : null}
+ {qualityBadgeText(quality)}
+ </span>
+ );
+}
+
+/** A ring that fills as the latest session gets closer to earning a spin. */
+export function ProgressRing({ progress, size = 18, stroke = 2.5, className }: { progress: number; size?: number; stroke?: number; className?: string }) {
+ const radius = (size - stroke) / 2;
+ const circumference = 2 * Math.PI * radius;
+ const value = Math.min(1, Math.max(0, progress));
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ className={cn("shrink-0 -rotate-90", className)}
+ data-testid="quality-progress-ring"
+ data-progress={value.toFixed(2)}
+ aria-hidden="true"
+ >
+ <circle cx={size / 2} cy={size / 2} r={radius} fill="none" stroke="currentColor" strokeOpacity={0.18} strokeWidth={stroke} />
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ r={radius}
+ fill="none"
+ stroke="#a3e635"
+ strokeWidth={stroke}
+ strokeLinecap="round"
+ strokeDasharray={circumference}
+ strokeDashoffset={circumference * (1 - value)}
+ />
+ </svg>
+ );
+}
+
+/** "Spin" with a pulsing count of the spins that are ready. */
+export function SpinButton(props: {
+ quality: AccountQuality;
+ onClick: () => void;
+ className?: string;
+ label?: string;
+ testId?: string;
+}) {
+ const { quality } = props;
+ const ready = quality.spinsAvailable;
+ return (
+ <button
+ type="button"
+ onClick={props.onClick}
+ data-testid={props.testId ?? "quality-spin-button"}
+ data-spins={ready}
+ title={ready > 0 ? `${ready} spin${ready === 1 ? "" : "s"} ready` : "No spins yet: good sessions earn spins."}
+ className={cn(
+ "relative inline-flex h-6 items-center gap-1.5 rounded-full px-2.5 text-[11px] font-semibold transition",
+ ready > 0
+ ? "bg-[#a3e635] text-[#1a2e05] shadow-[0_0_14px_rgba(163,230,53,0.45)] hover:bg-[#bef264]"
+ : "border border-sidebar-border text-muted-foreground hover:text-foreground",
+ props.className,
+ )}
+ >
+ <Gift className="size-3.5" aria-hidden="true" />
+ {props.label ?? "Spin"}
+ {ready > 0 ? (
+ <span className="relative ms-0.5 flex size-4 items-center justify-center">
+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-white/70 motion-reduce:hidden" />
+ <span className="relative inline-flex size-4 items-center justify-center rounded-full bg-[#0b1120] text-[9.5px] font-bold text-[#a3e635]">
+ {ready > 9 ? "9+" : ready}
+ </span>
+ </span>
+ ) : null}
+ </button>
+ );
+}
+
+/** "4-day streak · +1 spin per reproducible session · 7 days: +2". */
+export function streakText(quality: Pick<AccountQuality, "streakDays" | "streakMultiplier" | "streakNext">): string | null {
+ if (quality.streakDays <= 0 && !quality.streakNext) return null;
+ const parts: string[] = [];
+ parts.push(quality.streakDays > 0 ? `${quality.streakDays}-day streak` : "No streak yet");
+ if (quality.streakMultiplier > 0) parts.push(`+${quality.streakMultiplier} spin${quality.streakMultiplier === 1 ? "" : "s"} per reproducible session`);
+ if (quality.streakNext) parts.push(`${quality.streakNext.days} days: +${quality.streakNext.bonusSpins}`);
+ return parts.join(" · ");
+}
+
+export function StreakLine({ quality, className }: { quality: AccountQuality; className?: string }) {
+ const text = streakText(quality);
+ if (!text) return null;
+ return (
+ <div className={cn("flex items-center gap-1.5 text-xs text-orange-200", className)} data-testid="quality-streak">
+ <Flame className="size-3.5 shrink-0 text-orange-400" aria-hidden="true" />
+ <span>{text}</span>
+ </div>
+ );
+}
+
+export function BiggestWinTicker({ quality, className }: { quality: AccountQuality; className?: string }) {
+ if (!quality.biggestWinToday) return null;
+ return (
+ <div
+ className={cn("flex items-center gap-1.5 overflow-hidden rounded-full border border-amber-300/25 bg-amber-300/10 px-2.5 py-1 text-[11px] text-amber-100", className)}
+ data-testid="quality-biggest-win"
+ >
+ <Trophy className="size-3 shrink-0 text-amber-300" aria-hidden="true" />
+ <span className="truncate">
+ Today&apos;s biggest win: <strong className="font-semibold text-amber-200">{compactTokenCount(quality.biggestWinToday.tokens)} tokens</strong>
+ </span>
+ </div>
+ );
+}
+
+/** The ring with the server's text: what the latest session still needs to earn a spin. */
+export function NextSpinHint({ quality, className }: { quality: AccountQuality; className?: string }) {
+ const hint = quality.nextSpinHint;
+ if (!hint) return null;
+ return (
+ <div className={cn("flex items-start gap-2 text-xs text-white/75", className)} data-testid="quality-next-spin">
+ <ProgressRing progress={hint.progress} size={22} stroke={3} className="mt-0.5 text-white" />
+ <div className="min-w-0">
+ <div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[#a3e635]">
+ Next spin · {Math.round(hint.progress * 100)}%
+ </div>
+ <div className="leading-5">{hint.text}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx b/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx
new file mode 100644
index 00000000..0c191629
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx
@@ -0,0 +1,319 @@
+/** @jsxImportSource react */
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader2, Sparkles, Volume2, VolumeX, X } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { omnirushAccountStatus, omnirushQualityDetails, omnirushQualitySpin, omnirushQualitySpins } from "../../../app/lib/desktop";
+import { compactTokenCount } from "../../../app/lib/omnirush-usage";
+import {
+ DEFAULT_WHEEL_SEGMENTS,
+ SOUND_STORAGE_KEY,
+ canSpinNow,
+ nearMissText,
+ newSpinIdempotencyKey,
+ readPref,
+ refreshAccountStatus,
+ segmentOdds,
+ spinPayoutText,
+ spinRefusalMessage,
+ writePref,
+ type AccountQuality,
+ type QualitySpin,
+ type QualitySpinOutcome,
+ type WheelSegment,
+} from "../../../app/lib/quality";
+import { BiggestWinTicker, QualityTierBadge, StreakLine } from "./quality-parts";
+import { QualityWheel } from "./quality-wheel";
+
+export function usePrefersReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(() =>
+ typeof window !== "undefined" && typeof window.matchMedia === "function"
+ ? window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ : false,
+ );
+ useEffect(() => {
+ if (typeof window.matchMedia !== "function") return;
+ const media = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const listener = () => setReduced(media.matches);
+ media.addEventListener?.("change", listener);
+ return () => media.removeEventListener?.("change", listener);
+ }, []);
+ return reduced;
+}
+
+/** Counts up to `value` once `active`; jumps straight there with reduced motion. */
+function useCountUp(value: number, active: boolean, reducedMotion: boolean, durationMs = 1_400): number {
+ const [shown, setShown] = useState(0);
+ useEffect(() => {
+ if (!active) {
+ setShown(0);
+ return;
+ }
+ if (reducedMotion) {
+ setShown(value);
+ return;
+ }
+ let frame = 0;
+ const started = performance.now();
+ const step = (now: number) => {
+ const progress = Math.min(1, (now - started) / durationMs);
+ setShown(Math.round(value * (1 - (1 - progress) ** 3)));
+ if (progress < 1) frame = requestAnimationFrame(step);
+ };
+ frame = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(frame);
+ }, [active, durationMs, reducedMotion, value]);
+ return shown;
+}
+
+type Phase = "idle" | "requesting" | "spinning" | "result" | "error";
+
+export type QualitySpinDialogProps = {
+ quality: AccountQuality;
+ onClose: () => void;
+ /** Injected in tests; the desktop bridge otherwise. */
+ spin?: (input: { idempotencyKey: string }) => Promise<QualitySpinOutcome>;
+};
+
+/**
+ * The spin dialog: the wheel, the prizes with their odds, and the result.
+ * The server picks the segment; the wheel animates to it, then the prize
+ * counts up and the profile is read again.
+ */
+export function QualitySpinDialog(props: QualitySpinDialogProps) {
+ const { quality, onClose } = props;
+ const reducedMotion = usePrefersReducedMotion();
+ const [segments, setSegments] = useState<WheelSegment[]>(DEFAULT_WHEEL_SEGMENTS);
+ const [expectedTokens, setExpectedTokens] = useState<number | null>(null);
+ const [totals, setTotals] = useState<{ spun: number; paidTokens: number } | null>(null);
+ const [phase, setPhase] = useState<Phase>("idle");
+ const [result, setResult] = useState<QualitySpin | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [spinId, setSpinId] = useState(0);
+ const [soundEnabled, setSoundEnabled] = useState(() => readPref(SOUND_STORAGE_KEY) === "on");
+ const spinsLeft = result ? result.spinsAvailable : quality.spinsAvailable;
+ const prize = useCountUp(result?.prizeTokens ?? 0, phase === "result", reducedMotion);
+ const closeRef = useRef<HTMLButtonElement | null>(null);
+
+ useEffect(() => {
+ let active = true;
+ void omnirushQualityDetails()
+ .then((details) => {
+ if (!active || !details) return;
+ if (details.segments.length) setSegments(details.segments);
+ setExpectedTokens(details.expectedTokens);
+ })
+ .catch(() => undefined);
+ void omnirushQualitySpins()
+ .then((next) => { if (active) setTotals(next); })
+ .catch(() => undefined);
+ return () => { active = false; };
+ }, []);
+
+ useEffect(() => {
+ closeRef.current?.focus();
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [onClose]);
+
+ const runSpin = useCallback(async () => {
+ if (phase === "requesting" || phase === "spinning") return;
+ setPhase("requesting");
+ setError(null);
+ // One key per click: a retry of this click gets this click's result back.
+ const idempotencyKey = newSpinIdempotencyKey();
+ const send = props.spin ?? ((input: { idempotencyKey: string }) => omnirushQualitySpin(input));
+ let outcome: QualitySpinOutcome;
+ try {
+ outcome = await send({ idempotencyKey });
+ } catch {
+ outcome = { ok: false, reason: "unreachable", status: null };
+ }
+ if (!outcome.ok) {
+ setPhase("error");
+ setError(spinRefusalMessage(outcome.reason));
+ void refreshAccountStatus(omnirushAccountStatus);
+ return;
+ }
+ if (outcome.spin.segments.length) setSegments(outcome.spin.segments);
+ setResult(outcome.spin);
+ setSpinId((value) => value + 1);
+ setPhase("spinning");
+ }, [phase, props.spin]);
+
+ const landed = useCallback(() => {
+ setPhase("result");
+ void refreshAccountStatus(omnirushAccountStatus);
+ void omnirushQualitySpins().then(setTotals).catch(() => undefined);
+ }, []);
+
+ const toggleSound = () => {
+ setSoundEnabled((value) => {
+ writePref(SOUND_STORAGE_KEY, value ? "off" : "on");
+ return !value;
+ });
+ };
+
+ const resting = !canSpinNow(quality) && quality.spinsAvailable > 0;
+ const tease = result && phase === "result" ? nearMissText(result) : null;
+ const celebrate = result?.celebrate ?? "none";
+ const busy = phase === "requesting" || phase === "spinning";
+ const canSpin = !busy && spinsLeft > 0 && !(phase !== "result" && resting);
+
+ return (
+ <div className="fixed inset-0 z-[76] flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm" data-testid="quality-spin-overlay">
+ <section
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="quality-spin-title"
+ data-testid="quality-spin-dialog"
+ data-phase={phase}
+ className="relative w-full max-w-[520px] overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(ellipse_at_top,#1a2e05_0%,#0b1120_45%,#05070c_100%)] p-6 text-white shadow-2xl shadow-black/60"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <QualityTierBadge quality={quality} />
+ <span className="text-[11px] text-white/50">
+ {spinsLeft} spin{spinsLeft === 1 ? "" : "s"} ready
+ </span>
+ </div>
+ <h2 id="quality-spin-title" className="mt-2 text-2xl font-semibold tracking-[-0.02em]">
+ Spin for tokens
+ </h2>
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={toggleSound}
+ aria-pressed={soundEnabled}
+ aria-label={soundEnabled ? "Turn sound off" : "Turn sound on"}
+ data-testid="quality-sound-toggle"
+ className="flex size-8 items-center justify-center rounded-full text-white/60 transition hover:bg-white/10 hover:text-white"
+ >
+ {soundEnabled ? <Volume2 className="size-4" /> : <VolumeX className="size-4" />}
+ </button>
+ <button
+ ref={closeRef}
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="flex size-8 items-center justify-center rounded-full text-white/60 transition hover:bg-white/10 hover:text-white"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <BiggestWinTicker quality={quality} />
+ <StreakLine quality={quality} />
+ </div>
+
+ <div className="relative mt-4">
+ <QualityWheel
+ segments={segments}
+ targetIndex={result ? result.segmentIndex : null}
+ spinId={spinId}
+ onDone={landed}
+ celebrate={celebrate}
+ nearMiss={result?.nearMiss ?? false}
+ soundEnabled={soundEnabled}
+ reducedMotion={reducedMotion}
+ size={300}
+ />
+ </div>
+
+ <div className="mt-3 flex flex-wrap justify-center gap-1.5" data-testid="quality-wheel-legend">
+ {segments.map((segment, index) => (
+ <span
+ key={index}
+ className={cn(
+ "rounded-full border px-2 py-0.5 text-[10.5px] tabular-nums",
+ result && phase === "result" && index === result.segmentIndex
+ ? "border-[#a3e635] bg-[#a3e635]/20 text-[#ecfccb]"
+ : "border-white/10 text-white/55",
+ )}
+ >
+ {compactTokenCount(segment.tokens)} · {segmentOdds(segments, index)}
+ </span>
+ ))}
+ </div>
+
+ <div className="mt-4 min-h-[92px] text-center" aria-live="polite">
+ {phase === "result" && result ? (
+ <div data-testid="quality-spin-result" data-celebrate={celebrate}>
+ <div
+ className={cn(
+ "font-semibold tabular-nums tracking-[-0.03em]",
+ celebrate === "jackpot" ? "text-5xl text-amber-200" : celebrate === "big" ? "text-5xl text-[#d9f99d]" : "text-4xl text-white",
+ )}
+ data-testid="quality-spin-prize"
+ >
+ {prize.toLocaleString("en-US")}
+ <span className="ms-2 text-base font-medium text-white/60">tokens</span>
+ </div>
+ {celebrate === "jackpot" ? (
+ <div className="mt-1 text-sm font-semibold uppercase tracking-[0.3em] text-amber-300">Jackpot</div>
+ ) : null}
+ <div className={cn("mt-1 text-sm", result.preview || result.capped ? "text-amber-200" : "text-[#bef264]")} data-testid="quality-spin-payout">
+ {spinPayoutText(result)}
+ </div>
+ <div className="mt-2 flex flex-wrap items-center justify-center gap-2 text-[11px]">
+ {result.reproducible ? (
+ <span className="inline-flex items-center gap-1 rounded-full border border-[#a3e635]/40 bg-[#a3e635]/10 px-2 py-0.5 text-[#d9f99d]">
+ <Sparkles className="size-3" aria-hidden="true" /> Reproducible session
+ </span>
+ ) : null}
+ {result.alreadySpun ? <span className="text-white/50">This spin was already counted.</span> : null}
+ {result.potBalance !== null && !result.preview ? (
+ <span className="text-white/50">Pot: {compactTokenCount(result.potBalance)} tokens</span>
+ ) : null}
+ </div>
+ {tease ? (
+ <div className="mt-2 text-sm font-semibold text-amber-300" data-testid="quality-near-miss">{tease}</div>
+ ) : null}
+ </div>
+ ) : phase === "error" && error ? (
+ <div className="pt-4 text-sm text-amber-200" data-testid="quality-spin-error">{error}</div>
+ ) : phase === "spinning" ? (
+ <div className="pt-6 text-sm text-white/60">Good luck…</div>
+ ) : resting ? (
+ <div className="pt-4 text-sm text-amber-200">The wheel is resting, back tomorrow.</div>
+ ) : (
+ <div className="pt-4 text-sm text-white/60">
+ {quality.preview ? "Preview: spins show what you would win, and pay 0 tokens." : "The wheel decides. Every prize goes into your pot."}
+ {expectedTokens ? <span className="block text-white/40">Average spin: {compactTokenCount(expectedTokens)} tokens</span> : null}
+ </div>
+ )}
+ </div>
+
+ <div className="mt-2 flex flex-col items-center gap-2">
+ {spinsLeft > 0 || busy ? (
+ <button
+ type="button"
+ onClick={() => void runSpin()}
+ disabled={!canSpin}
+ data-testid="quality-spin-go"
+ className="inline-flex min-w-[200px] items-center justify-center gap-2 rounded-full bg-[#a3e635] px-6 py-3 text-sm font-bold uppercase tracking-[0.12em] text-[#1a2e05] shadow-[0_0_30px_rgba(163,230,53,0.45)] transition hover:bg-[#bef264] disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {busy ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
+ {busy ? "Spinning" : phase === "result" ? `Spin again (${spinsLeft} left)` : spinsLeft > 1 ? `Spin (${spinsLeft} ready)` : "Spin"}
+ </button>
+ ) : (
+ <div className="text-xs text-white/50">No spins left. Good sessions earn more.</div>
+ )}
+ {totals && totals.spun > 0 ? (
+ <div className="text-[11px] text-white/40" data-testid="quality-spin-totals">
+ {totals.spun} spin{totals.spun === 1 ? "" : "s"} so far · {compactTokenCount(totals.paidTokens)} tokens won
+ </div>
+ ) : null}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/quality/quality-wheel.tsx b/apps/app/src/react-app/domains/quality/quality-wheel.tsx
new file mode 100644
index 00000000..7e066448
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/quality-wheel.tsx
@@ -0,0 +1,230 @@
+/** @jsxImportSource react */
+import { useEffect, useMemo, useRef } from "react";
+
+import {
+ sliceAtPointer,
+ wheelAngleAt,
+ wheelOvershoot,
+ wheelSlices,
+ wheelTargetRotation,
+ type WheelSegment,
+} from "../../../app/lib/quality";
+import { compactTokenCount } from "../../../app/lib/omnirush-usage";
+import { createWheelSounds, type WheelSounds } from "./wheel-sounds";
+import { burstConfetti } from "./wheel-confetti";
+
+export type QualityWheelProps = {
+ segments: WheelSegment[];
+ /** The server's `segment_index`; null leaves the wheel at rest. */
+ targetIndex: number | null;
+ /** Changes for every spin, so a second spin to the same index spins again. */
+ spinId?: string | number;
+ onDone?: () => void;
+ celebrate?: "none" | "big" | "jackpot";
+ nearMiss?: boolean;
+ soundEnabled?: boolean;
+ reducedMotion?: boolean;
+ /** Pixel size of the wheel (square). */
+ size?: number;
+ durationMs?: number;
+};
+
+/** Low prizes in slate and teal, rising to the lime jackpot. */
+const SEGMENT_COLORS = ["#1e293b", "#334155", "#115e59", "#3f6212", "#65a30d", "#a3e635"];
+const SEGMENT_TEXT = ["#cbd5e1", "#e2e8f0", "#ccfbf1", "#ecfccb", "#f7fee7", "#1a2e05"];
+const RADIUS = 100;
+const LABEL_INSIDE_MIN_DEGREES = 14;
+
+function point(angle: number, radius: number): [number, number] {
+ const radians = (angle * Math.PI) / 180;
+ return [radius * Math.sin(radians), -radius * Math.cos(radians)];
+}
+
+function slicePath(start: number, end: number): string {
+ const [x1, y1] = point(start, RADIUS);
+ const [x2, y2] = point(end, RADIUS);
+ const large = end - start > 180 ? 1 : 0;
+ return `M0 0 L${x1.toFixed(3)} ${y1.toFixed(3)} A${RADIUS} ${RADIUS} 0 ${large} 1 ${x2.toFixed(3)} ${y2.toFixed(3)} Z`;
+}
+
+function colorFor(index: number, count: number, palette: string[]): string {
+ // Spread the palette over the segments so the top prize always gets the lime.
+ const at = count <= 1 ? palette.length - 1 : Math.round((index * (palette.length - 1)) / (count - 1));
+ return palette[at] ?? palette[0];
+}
+
+/**
+ * The quality-rewards wheel: slices sized by the real odds, a pointer that
+ * ticks over every boundary, a spin that accelerates, decelerates for a long
+ * time, overshoots a little and settles on `targetIndex`. The server chose
+ * the index; this only animates to it.
+ */
+export function QualityWheel(props: QualityWheelProps) {
+ const {
+ segments,
+ targetIndex,
+ spinId,
+ onDone,
+ celebrate = "none",
+ soundEnabled = false,
+ reducedMotion = false,
+ size = 320,
+ durationMs = 5600,
+ } = props;
+ const slices = useMemo(() => wheelSlices(segments), [segments]);
+ const wheelRef = useRef<SVGGElement | null>(null);
+ const pointerRef = useRef<SVGGElement | null>(null);
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const confettiRef = useRef<HTMLCanvasElement | null>(null);
+ const rotation = useRef(0);
+ const sounds = useRef<WheelSounds | null>(null);
+ const soundOn = useRef(soundEnabled);
+ soundOn.current = soundEnabled;
+ const done = useRef(onDone);
+ done.current = onDone;
+
+ useEffect(() => () => sounds.current?.dispose(), []);
+
+ useEffect(() => {
+ if (targetIndex === null || targetIndex < 0 || targetIndex >= segments.length) return;
+ const root = rootRef.current;
+ const apply = (angle: number) => {
+ rotation.current = angle;
+ wheelRef.current?.setAttribute("transform", `rotate(${angle.toFixed(3)})`);
+ root?.setAttribute("data-rotation", angle.toFixed(2));
+ };
+ const finish = () => {
+ root?.setAttribute("data-spinning", "false");
+ root?.setAttribute("data-landed-index", String(targetIndex));
+ if (celebrate !== "none" && !reducedMotion && confettiRef.current) {
+ burstConfetti(confettiRef.current, celebrate);
+ }
+ if (soundOn.current) {
+ sounds.current ??= createWheelSounds();
+ sounds.current?.win(celebrate);
+ }
+ done.current?.();
+ };
+ // A small random offset inside the slice: the pointer never rests on a line.
+ const offset = (Math.random() - 0.5) * 0.9;
+ const from = rotation.current;
+ const to = wheelTargetRotation(segments, targetIndex, from, 6, offset);
+ root?.setAttribute("data-spinning", "true");
+ root?.removeAttribute("data-landed-index");
+ if (reducedMotion) {
+ apply(to);
+ const timer = window.setTimeout(finish, 0);
+ return () => window.clearTimeout(timer);
+ }
+ const overshoot = wheelOvershoot(segments, targetIndex, offset);
+ let lastSlice = sliceAtPointer(slices, from);
+ let frame = 0;
+ let kick = 0;
+ const started = performance.now();
+ const step = (now: number) => {
+ const progress = (now - started) / durationMs;
+ const angle = wheelAngleAt(progress, from, to, overshoot);
+ apply(angle);
+ const slice = sliceAtPointer(slices, angle);
+ if (slice !== lastSlice) {
+ lastSlice = slice;
+ kick = 1;
+ if (soundOn.current) {
+ sounds.current ??= createWheelSounds();
+ sounds.current?.tick();
+ }
+ }
+ // The pointer flicks back on every boundary and springs home.
+ kick *= 0.82;
+ pointerRef.current?.setAttribute("transform", `rotate(${(-22 * kick).toFixed(2)} 0 -112)`);
+ if (progress < 1) {
+ frame = requestAnimationFrame(step);
+ } else {
+ apply(to);
+ pointerRef.current?.setAttribute("transform", "rotate(0 0 -112)");
+ finish();
+ }
+ };
+ frame = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(frame);
+ // A new spin is a new `spinId` or target; the rest is read through refs.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [targetIndex, spinId]);
+
+ const jackpot = segments.length - 1;
+ return (
+ <div
+ ref={rootRef}
+ className="relative mx-auto"
+ style={{ width: size, height: size }}
+ data-testid="quality-wheel"
+ data-spinning="false"
+ data-rotation="0"
+ >
+ <svg viewBox="-130 -130 260 260" width={size} height={size} role="img" aria-label="Prize wheel">
+ <defs>
+ <radialGradient id="quality-wheel-hub" cx="50%" cy="40%" r="60%">
+ <stop offset="0%" stopColor="#1f2937" />
+ <stop offset="100%" stopColor="#030712" />
+ </radialGradient>
+ <filter id="quality-wheel-glow" x="-50%" y="-50%" width="200%" height="200%">
+ <feGaussianBlur stdDeviation="4" result="blur" />
+ <feMerge>
+ <feMergeNode in="blur" />
+ <feMergeNode in="SourceGraphic" />
+ </feMerge>
+ </filter>
+ </defs>
+ <circle r={RADIUS + 9} fill="#0b1120" stroke="#a3e635" strokeOpacity={0.55} strokeWidth={2} filter="url(#quality-wheel-glow)" />
+ <g ref={wheelRef} transform="rotate(0)">
+ {slices.map((slice) => {
+ const fill = colorFor(slice.index, slices.length, SEGMENT_COLORS);
+ const ink = colorFor(slice.index, slices.length, SEGMENT_TEXT);
+ const wide = slice.end - slice.start >= LABEL_INSIDE_MIN_DEGREES;
+ const label = compactTokenCount(slice.segment.tokens);
+ const [lx, ly] = point(slice.mid, wide ? 68 : 90);
+ return (
+ <g key={slice.index} data-segment-index={slice.index}>
+ <path d={slicePath(slice.start, slice.end)} fill={fill} stroke="#020617" strokeWidth={1.2} />
+ {slice.index === jackpot ? (
+ <path d={slicePath(slice.start, slice.end)} fill="#ecfccb" opacity={0.35} filter="url(#quality-wheel-glow)" />
+ ) : null}
+ <text
+ x={lx}
+ y={ly}
+ fill={ink}
+ fontSize={wide ? 13 : 7.5}
+ fontWeight={700}
+ textAnchor="middle"
+ dominantBaseline="central"
+ transform={`rotate(${wide ? slice.mid : slice.mid - 90} ${lx} ${ly})`}
+ style={{ fontFamily: "ui-sans-serif, system-ui", letterSpacing: "0.02em" }}
+ >
+ {label}
+ </text>
+ </g>
+ );
+ })}
+ {slices.map((slice) => {
+ const [x, y] = point(slice.start, RADIUS + 4.5);
+ return <circle key={`bulb-${slice.index}`} cx={x} cy={y} r={2.6} fill="#f7fee7" className="quality-wheel-bulb" />;
+ })}
+ </g>
+ <circle r={24} fill="url(#quality-wheel-hub)" stroke="#a3e635" strokeWidth={2} />
+ <text y={1} fill="#a3e635" fontSize={10} fontWeight={800} textAnchor="middle" dominantBaseline="central" style={{ letterSpacing: "0.12em" }}>
+ SPIN
+ </text>
+ <g ref={pointerRef} transform="rotate(0 0 -112)">
+ <path d="M0 -94 L-11 -122 L11 -122 Z" fill="#a3e635" stroke="#0b1120" strokeWidth={2} strokeLinejoin="round" />
+ <circle cx={0} cy={-118} r={3} fill="#0b1120" />
+ </g>
+ </svg>
+ <canvas
+ ref={confettiRef}
+ className="pointer-events-none absolute"
+ style={{ inset: -size * 0.35, width: size * 1.7, height: size * 1.7 }}
+ aria-hidden="true"
+ />
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/quality/wheel-confetti.ts b/apps/app/src/react-app/domains/quality/wheel-confetti.ts
new file mode 100644
index 00000000..1608ca13
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/wheel-confetti.ts
@@ -0,0 +1,75 @@
+// A confetti burst on a canvas over the wheel: "big" wins get one burst,
+// the jackpot three bigger ones with gold. Never runs with reduced motion.
+
+const COLORS = ["#a3e635", "#d9f99d", "#f7fee7", "#facc15", "#22d3ee", "#ffffff"];
+const JACKPOT_COLORS = ["#facc15", "#fde047", "#a3e635", "#fef9c3", "#ffffff", "#f59e0b"];
+
+type Particle = { x: number; y: number; vx: number; vy: number; spin: number; angle: number; size: number; color: string; life: number };
+
+export function burstConfetti(canvas: HTMLCanvasElement, celebrate: "big" | "jackpot"): () => void {
+ const scale = window.devicePixelRatio || 1;
+ const width = canvas.clientWidth;
+ const height = canvas.clientHeight;
+ canvas.width = Math.round(width * scale);
+ canvas.height = Math.round(height * scale);
+ const context = canvas.getContext("2d");
+ if (!context) return () => undefined;
+ context.scale(scale, scale);
+ const particles: Particle[] = [];
+ const palette = celebrate === "jackpot" ? JACKPOT_COLORS : COLORS;
+ const burst = (count: number, power: number) => {
+ for (let index = 0; index < count; index += 1) {
+ const direction = Math.random() * Math.PI * 2;
+ const speed = power * (0.35 + Math.random() * 0.65);
+ particles.push({
+ x: width / 2,
+ y: height / 2,
+ vx: Math.cos(direction) * speed,
+ vy: Math.sin(direction) * speed - power * 0.35,
+ spin: (Math.random() - 0.5) * 0.4,
+ angle: Math.random() * Math.PI,
+ size: 4 + Math.random() * 5,
+ color: palette[index % palette.length],
+ life: 1,
+ });
+ }
+ };
+ const timers: number[] = [];
+ if (celebrate === "jackpot") {
+ burst(200, 11);
+ timers.push(window.setTimeout(() => burst(160, 9), 350));
+ timers.push(window.setTimeout(() => burst(160, 12), 800));
+ } else {
+ burst(130, 9);
+ }
+ let frame = 0;
+ const started = performance.now();
+ const lifetime = celebrate === "jackpot" ? 3_600 : 2_400;
+ const step = (now: number) => {
+ context.clearRect(0, 0, width, height);
+ for (const particle of particles) {
+ particle.vy += 0.22;
+ particle.vx *= 0.985;
+ particle.vy *= 0.985;
+ particle.x += particle.vx;
+ particle.y += particle.vy;
+ particle.angle += particle.spin;
+ particle.life = Math.max(0, particle.life - 0.008);
+ context.save();
+ context.globalAlpha = particle.life;
+ context.translate(particle.x, particle.y);
+ context.rotate(particle.angle);
+ context.fillStyle = particle.color;
+ context.fillRect(-particle.size / 2, -particle.size / 4, particle.size, particle.size / 2);
+ context.restore();
+ }
+ if (now - started < lifetime) frame = requestAnimationFrame(step);
+ else context.clearRect(0, 0, width, height);
+ };
+ frame = requestAnimationFrame(step);
+ return () => {
+ cancelAnimationFrame(frame);
+ timers.forEach((timer) => window.clearTimeout(timer));
+ context.clearRect(0, 0, width, height);
+ };
+}
diff --git a/apps/app/src/react-app/domains/quality/wheel-sounds.ts b/apps/app/src/react-app/domains/quality/wheel-sounds.ts
new file mode 100644
index 00000000..22d7083b
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/wheel-sounds.ts
@@ -0,0 +1,57 @@
+// Wheel sounds, made with WebAudio (no files to ship). Off unless the user
+// turns them on in the spin dialog.
+
+export type WheelSounds = {
+ tick: () => void;
+ win: (celebrate: "none" | "big" | "jackpot") => void;
+ dispose: () => void;
+};
+
+type AudioContextConstructor = typeof AudioContext;
+
+export function createWheelSounds(): WheelSounds | null {
+ if (typeof window === "undefined") return null;
+ const Context = (window.AudioContext ?? (window as unknown as { webkitAudioContext?: AudioContextConstructor }).webkitAudioContext) as
+ | AudioContextConstructor
+ | undefined;
+ if (!Context) return null;
+ let context: AudioContext;
+ try {
+ context = new Context();
+ } catch {
+ return null;
+ }
+
+ const tone = (frequency: number, at: number, length: number, volume: number, type: OscillatorType) => {
+ const oscillator = context.createOscillator();
+ const gain = context.createGain();
+ oscillator.type = type;
+ oscillator.frequency.setValueAtTime(frequency, at);
+ gain.gain.setValueAtTime(0, at);
+ gain.gain.linearRampToValueAtTime(volume, at + 0.004);
+ gain.gain.exponentialRampToValueAtTime(0.0001, at + length);
+ oscillator.connect(gain).connect(context.destination);
+ oscillator.start(at);
+ oscillator.stop(at + length + 0.02);
+ };
+
+ return {
+ tick() {
+ if (context.state === "suspended") void context.resume();
+ tone(1_700, context.currentTime, 0.03, 0.08, "square");
+ },
+ win(celebrate) {
+ if (context.state === "suspended") void context.resume();
+ const now = context.currentTime;
+ const notes = celebrate === "jackpot"
+ ? [523, 659, 784, 1047, 784, 1047, 1319, 1568]
+ : celebrate === "big"
+ ? [523, 659, 784, 1047]
+ : [659, 880];
+ notes.forEach((note, index) => tone(note, now + index * 0.09, 0.22, 0.12, "triangle"));
+ },
+ dispose() {
+ void context.close().catch(() => undefined);
+ },
+ };
+}
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index 5d2f61d6..00521743 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -40,6 +40,8 @@ import { getDisplaySessionTitle } from "../../../../app/lib/session-title";
import { omnirushAccountStatus, type WorkspaceInfo } from "../../../../app/lib/desktop";
import { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";
import { isDesktopRuntime } from "../../../../app/lib/runtime-env";
+import { refreshAccountStatus, useAccountStatusStore, useQualityUiStore, type AccountQuality } from "../../../../app/lib/quality";
+import { ProgressRing, QualityTierBadge, SpinButton } from "../../quality/quality-parts";
import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";
import { NotificationBell } from "../../../shell/notification-center";
import { useUiStateStore } from "../../../shell/ui-state-store";
@@ -976,22 +978,47 @@ function OmniRushWordmark({ className }: { className?: string }) {
);
}
+/**
+ * Quality rewards under the account: the spin button with the count of
+ * ready spins, and the ring filling toward the next spin. Opens the quality
+ * panel (tips, streak, coaching) or the spin dialog. Nothing while `quality`
+ * is null.
+ */
+function QualityFooterStrip({ quality }: { quality: AccountQuality }) {
+ const openPanel = useQualityUiStore((store) => store.openPanel);
+ const openSpin = useQualityUiStore((store) => store.openSpin);
+ const hint = quality.nextSpinHint;
+ return (
+ <div
+ className="flex items-center gap-1.5 px-2 pb-1 pt-0.5 group-data-[collapsible=icon]:hidden"
+ data-testid="quality-footer-strip"
+ >
+ <SpinButton quality={quality} onClick={quality.spinsAvailable > 0 ? openSpin : openPanel} />
+ <button
+ type="button"
+ onClick={openPanel}
+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded-md px-1 py-0.5 text-left text-[10.5px] text-muted-foreground transition hover:bg-sidebar-accent hover:text-foreground"
+ title={hint?.text ?? quality.nextTierHint ?? "Quality rewards"}
+ data-testid="quality-footer-next"
+ >
+ {hint ? <ProgressRing progress={hint.progress} size={16} stroke={2.25} /> : null}
+ <span className="truncate">
+ {hint ? `next ${Math.round(hint.progress * 100)}%` : quality.streakDays > 0 ? `${quality.streakDays}-day streak` : "How to earn spins"}
+ </span>
+ </button>
+ </div>
+ );
+}
+
function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings: () => void }) {
- const [status, setStatus] = React.useState<NativeAccountStatus | null>(null);
+ // Shared with the quality popup (QualityRewards): one /device/me read for both.
+ const status: NativeAccountStatus | null = useAccountStatusStore((store) => store.status);
React.useEffect(() => {
- let active = true;
- const refresh = () => {
- void omnirushAccountStatus()
- .then((next) => { if (active) setStatus(next); })
- .catch(() => { if (active) setStatus({ connected: false, gatewayConfigured: false }); });
- };
+ const refresh = () => void refreshAccountStatus(omnirushAccountStatus);
refresh();
window.addEventListener("focus", refresh);
- return () => {
- active = false;
- window.removeEventListener("focus", refresh);
- };
+ return () => window.removeEventListener("focus", refresh);
}, []);
const connected = status?.connected === true;
@@ -999,6 +1026,7 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
? status?.displayName?.trim() || status?.email?.trim() || "Your account"
: "sign in to omnirush.ai";
const usage = connected && status?.usage ? omnirushUsageSummary(status.usage) : null;
+ const quality = connected ? status?.quality ?? null : null;
// The account server label ("omnirush.ai", "localhost:8090 (local API)")
// only matters while connected; a signed-out footer keeps the sign-in hint.
const serverHost = connected ? status?.gatewayHost?.trim() || null : null;
@@ -1040,8 +1068,11 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
/>
</span>
<span className="min-w-0 flex-1 text-left">
- <span className="block truncate text-xs font-medium">{accountLabel}</span>
- <span className="block truncate text-[10.5px] text-muted-foreground">
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-xs font-medium">{accountLabel}</span>
+ {quality ? <QualityTierBadge quality={quality} /> : null}
+ </span>
+ <span className="block truncate text-[10.5px] text-muted-foreground" data-testid="native-account-detail">
{accountDetail}
</span>
{usage ? (
@@ -1052,6 +1083,11 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
</span>
</SidebarMenuButton>
</SidebarMenuItem>
+ {quality ? (
+ <SidebarMenuItem>
+ <QualityFooterStrip quality={quality} />
+ </SidebarMenuItem>
+ ) : null}
<SidebarMenuItem>
<SidebarMenuButton
type="button"
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index efe2c6e8..d873f44c 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -46,6 +46,7 @@ import { OmniRushContextPublisher } from "./omnirush-context-publisher";
import { SessionRoute } from "./session-route";
import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";
import { UpdateGate } from "./update-gate";
+import { QualityRewards } from "../domains/quality/quality-notice";
import { SettingsRoute } from "./settings-route";
import { ShellConfigProvider } from "./shell-config";
import { WelcomeRoute } from "./welcome-route";
@@ -510,6 +511,7 @@ export function AppRoot() {
</Routes>
<LoadingOverlay />
<CloudWorkspaceOverlay />
+ {isDesktopRuntime() ? <QualityRewards /> : null}
</CloudWorkspaceStatusProvider>
</OmniRushWebAccessGate>
</DenSigninGate>
diff --git a/apps/app/tests/quality.test.tsx b/apps/app/tests/quality.test.tsx
new file mode 100644
index 00000000..8f045d7d
--- /dev/null
+++ b/apps/app/tests/quality.test.tsx
@@ -0,0 +1,244 @@
+import { describe, expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import {
+ DEFAULT_WHEEL_SEGMENTS,
+ NOTICE_SEEN_STORAGE_KEY,
+ canSpinNow,
+ nearMissText,
+ noticeToShow,
+ nudgeToShow,
+ qualityBadgeText,
+ readPref,
+ sliceAtPointer,
+ spinPayoutText,
+ spinRefusalMessage,
+ useAccountStatusStore,
+ wheelAngleAt,
+ wheelOvershoot,
+ wheelSlices,
+ wheelTargetRotation,
+ writePref,
+ type AccountQuality,
+ type QualitySpin,
+ type QualityTier,
+} from "../src/app/lib/quality";
+import { QualityTierBadge, streakText } from "../src/react-app/domains/quality/quality-parts";
+import { QualityNoticeCard, QualityRewards } from "../src/react-app/domains/quality/quality-notice";
+import { QualitySpinDialog } from "../src/react-app/domains/quality/quality-spin-dialog";
+
+const quality: AccountQuality = {
+ tier: "gold",
+ score: 0.52,
+ tokensMultiplier: 1,
+ spinsAvailable: 2,
+ reproSpinsAvailable: 1,
+ spinsExpireAt: "2026-10-06T10:00:00Z",
+ nextTierHint: "Score 0.52. Stay above 0.45 to keep Gold.",
+ tips: ["Start omnirush inside the project folder, not ~, and keep edits there.", "Add tests: tested work earns spins."],
+ notice: { id: "spins-1", kind: "spins", title: "You earned 2 spins", body: "Two sessions in my-app were reproducible." },
+ notices: [{ id: "spins-1", kind: "spins", title: "You earned 2 spins", body: "Two sessions in my-app were reproducible." }],
+ mode: "enforce",
+ resting: false,
+ preview: false,
+ streakDays: 4,
+ streakMultiplier: 1,
+ streakNext: { days: 7, bonusSpins: 2 },
+ nextSpinHint: { progress: 0.6, text: "Add tests to earn a spin.", sessionId: "ses_1" },
+ biggestWinToday: { tokens: 10_000_000, at: "2026-10-04T09:00:00Z" },
+ nudge: null,
+};
+
+const spin: QualitySpin = {
+ tokens: 1_000_000,
+ prizeTokens: 1_000_000,
+ segmentIndex: 2,
+ segments: DEFAULT_WHEEL_SEGMENTS,
+ preview: false,
+ capped: false,
+ reproducible: true,
+ alreadySpun: false,
+ spunAt: "2026-10-04T12:00:00Z",
+ spinsAvailable: 1,
+ potBalance: 12_500_000,
+ celebrate: "none",
+ nearMiss: false,
+ jackpotTokens: 10_000_000,
+ streakDays: 4,
+};
+
+function memoryStorage() {
+ const values = new Map<string, string>();
+ return { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => void values.set(key, value) };
+}
+
+describe("tier badge", () => {
+ const labels: Record<QualityTier, string> = { new: "New", standard: "Standard", gold: "Gold", coaching: "Coaching", limited: "Limited" };
+ for (const [tier, label] of Object.entries(labels) as [QualityTier, string][]) {
+ test(`shows ${label} for ${tier}`, () => {
+ const html = renderToStaticMarkup(<QualityTierBadge quality={{ ...quality, tier, preview: false }} />);
+ expect(html).toContain(`data-tier="${tier}"`);
+ expect(html).toContain(`>${label}</span>`);
+ expect(html).not.toContain("data-preview");
+ });
+ }
+
+ test("preview: dashed, and says Preview", () => {
+ const html = renderToStaticMarkup(<QualityTierBadge quality={{ ...quality, preview: true }} />);
+ expect(qualityBadgeText({ ...quality, preview: true })).toBe("Gold · Preview");
+ expect(html).toContain("Gold · Preview");
+ expect(html).toContain("data-preview");
+ expect(html).toContain("border-dashed");
+ });
+
+ test("renders nothing while quality is null (feature off)", () => {
+ expect(renderToStaticMarkup(<QualityTierBadge quality={null} />)).toBe("");
+ });
+
+ test("the quality overlay renders nothing while quality is null, or signed out", () => {
+ useAccountStatusStore.getState().set({ connected: true, gatewayConfigured: true, quality: null });
+ expect(renderToStaticMarkup(<QualityRewards />)).toBe("");
+ useAccountStatusStore.getState().set({ connected: false, gatewayConfigured: true, quality });
+ expect(renderToStaticMarkup(<QualityRewards />)).toBe("");
+ useAccountStatusStore.getState().set(null);
+ });
+});
+
+describe("notice: once per id", () => {
+ test("a notice shows until its id is seen; a new id shows again", () => {
+ const storage = memoryStorage();
+ expect(noticeToShow(quality, readPref(NOTICE_SEEN_STORAGE_KEY, storage))?.id).toBe("spins-1");
+ writePref(NOTICE_SEEN_STORAGE_KEY, "spins-1", storage);
+ expect(noticeToShow(quality, readPref(NOTICE_SEEN_STORAGE_KEY, storage))).toBeNull();
+ const next = { id: "tier-gold-2", kind: "tier-gold", title: "You reached Gold", body: "" };
+ expect(noticeToShow({ ...quality, notice: next, notices: [next, quality.notices[0]] }, "spins-1")?.id).toBe("tier-gold-2");
+ expect(noticeToShow({ ...quality, notice: null, notices: [] }, null)).toBeNull();
+ expect(noticeToShow(null, null)).toBeNull();
+ });
+
+ test("the nudge shows only when the server sends one, once per id", () => {
+ expect(nudgeToShow(quality, null)).toBeNull();
+ const nudged = { ...quality, nudge: { id: "nudge-1", text: "This session can earn spins: add tests." } };
+ expect(nudgeToShow(nudged, null)?.text).toContain("add tests");
+ expect(nudgeToShow(nudged, "nudge-1")).toBeNull();
+ });
+
+ test("the popup shows the notice, the tips and a Spin button while spins are ready", () => {
+ const html = renderToStaticMarkup(
+ <QualityNoticeCard quality={quality} notice={quality.notice} onSpin={() => undefined} onDismiss={() => undefined} />,
+ );
+ expect(html).toContain("data-notice-id=\"spins-1\"");
+ expect(html).toContain("You earned 2 spins");
+ expect(html).toContain("Two sessions in my-app were reproducible.");
+ expect(html).toContain("keep edits there.");
+ expect(html).toContain("data-testid=\"quality-notice-spin\"");
+ expect(html).toContain("Spin (2)");
+ expect(html).toContain("4-day streak");
+ expect(html).toContain("Next spin · 60%");
+ });
+
+ test("no Spin button without spins; a resting wheel says so", () => {
+ const none = renderToStaticMarkup(
+ <QualityNoticeCard quality={{ ...quality, spinsAvailable: 0, reproSpinsAvailable: 0 }} notice={quality.notice} onSpin={() => undefined} onDismiss={() => undefined} />,
+ );
+ expect(none).not.toContain("quality-notice-spin");
+ const resting = { ...quality, resting: true, reproSpinsAvailable: 0 };
+ expect(canSpinNow(resting)).toBe(false);
+ expect(canSpinNow({ ...resting, reproSpinsAvailable: 1 })).toBe(true);
+ const html = renderToStaticMarkup(<QualityNoticeCard quality={resting} notice={null} onSpin={() => undefined} onDismiss={() => undefined} />);
+ expect(html).toContain("The wheel is resting, back tomorrow.");
+ });
+
+ test("coaching reads as how to earn spins, with a see-why list", () => {
+ const coaching = { ...quality, tier: "coaching" as const, spinsAvailable: 0 };
+ const notice = { id: "c-1", kind: "tier-coaching", title: "Here is how to get spins", body: "A few habits make sessions count." };
+ const html = renderToStaticMarkup(<QualityNoticeCard quality={coaching} notice={notice} onSpin={() => undefined} onDismiss={() => undefined} />);
+ expect(html).toContain("How to earn spins");
+ expect(html).toContain("See why");
+ expect(html).toContain("data-coaching");
+ });
+
+ test("streak text", () => {
+ expect(streakText(quality)).toBe("4-day streak · +1 spin per reproducible session · 7 days: +2");
+ expect(streakText({ streakDays: 0, streakMultiplier: 0, streakNext: null })).toBeNull();
+ });
+});
+
+describe("wheel geometry", () => {
+ const slices = wheelSlices(DEFAULT_WHEEL_SEGMENTS);
+
+ test("slices follow the weights and fill the circle", () => {
+ expect(slices[0].start).toBe(0);
+ expect(slices.at(-1)!.end).toBe(360);
+ expect(slices[0].end - slices[0].start).toBeCloseTo(126, 5);
+ expect(slices[5].end - slices[5].start).toBeCloseTo(3.6, 5);
+ });
+
+ test("the target rotation stops every index under the pointer, after full turns", () => {
+ for (let index = 0; index < DEFAULT_WHEEL_SEGMENTS.length; index += 1) {
+ for (const from of [0, 137.5, 2_000]) {
+ for (const offset of [-0.9, 0, 0.45]) {
+ const target = wheelTargetRotation(DEFAULT_WHEEL_SEGMENTS, index, from, 6, offset);
+ expect(sliceAtPointer(slices, target)).toBe(index);
+ expect(target - from).toBeGreaterThanOrEqual(6 * 360);
+ expect(target - from).toBeLessThan(7 * 360);
+ }
+ }
+ }
+ });
+
+ test("index 2 (1M) stops at the middle of its slice with no offset", () => {
+ const target = wheelTargetRotation(DEFAULT_WHEEL_SEGMENTS, 2, 0, 5);
+ // Slice 2 spans 234°..306°: its middle (270°) is turned to the top.
+ expect(((-target % 360) + 360) % 360).toBeCloseTo(270, 6);
+ });
+
+ test("the spin starts and ends where it should, and the overshoot stays in the slice", () => {
+ const to = wheelTargetRotation(DEFAULT_WHEEL_SEGMENTS, 5, 0, 6);
+ const overshoot = wheelOvershoot(DEFAULT_WHEEL_SEGMENTS, 5);
+ expect(wheelAngleAt(0, 0, to, overshoot)).toBe(0);
+ expect(wheelAngleAt(1, 0, to, overshoot)).toBeCloseTo(to, 6);
+ let previous = 0;
+ let peak = 0;
+ let arrived = false;
+ for (let step = 1; step <= 1_000; step += 1) {
+ const angle = wheelAngleAt(step / 1_000, 0, to, overshoot);
+ if (step / 1_000 <= 0.88) expect(angle).toBeGreaterThanOrEqual(previous);
+ previous = angle;
+ peak = Math.max(peak, angle);
+ // Once the wheel reaches the stop it overshoots and settles without leaving the 10M slice.
+ arrived ||= angle >= to;
+ if (arrived) expect(sliceAtPointer(slices, angle)).toBe(5);
+ }
+ expect(arrived).toBe(true);
+ expect(peak).toBeCloseTo(to + overshoot, 3);
+ });
+});
+
+describe("spin results", () => {
+ test("refusals read as the API asks", () => {
+ expect(spinRefusalMessage("wheel_resting")).toBe("The wheel is resting, back tomorrow.");
+ expect(spinRefusalMessage("no_spins")).toBe("No spins yet: good sessions earn spins.");
+ expect(spinRefusalMessage("quality_rewards_off")).toContain("switched off");
+ });
+
+ test("paid, preview and capped", () => {
+ expect(spinPayoutText(spin)).toBe("+1M tokens added to your pot");
+ expect(spinPayoutText({ ...spin, preview: true, tokens: 0 })).toBe("Preview: no tokens paid");
+ expect(spinPayoutText({ ...spin, capped: true, tokens: 0 })).toBe("Pot cap reached: this spin pays 0");
+ });
+
+ test("the near-miss tease only when the server flags it", () => {
+ expect(nearMissText(spin)).toBeNull();
+ expect(nearMissText({ ...spin, nearMiss: true, segmentIndex: 4 })).toBe("So close to 10M!");
+ });
+
+ test("the dialog shows the wheel, the odds and the Spin button", () => {
+ const html = renderToStaticMarkup(<QualitySpinDialog quality={quality} onClose={() => undefined} />);
+ expect(html).toContain("data-testid=\"quality-wheel\"");
+ expect(html).toContain("10M · 1%");
+ expect(html).toContain("250K · 35%");
+ expect(html).toContain("Spin (2 ready)");
+ expect(html).toContain("Today&#x27;s biggest win");
+ });
+});
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 741fb22e..7ff20778 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -2150,6 +2150,20 @@ const desktopCommandHandlers = {
"omnirushAccountStatus": async (event, ...args) => {
return omnirushAccountStore.status();
},
+ // Quality rewards: the wheel's segments and recent sessions, spin totals, and one spin with the device
+ // credential (X-OmniRush-Client like every account request). A refusal
+ // (409 no_spins / wheel_resting / quality_rewards_off) comes back as a
+ // value, not a thrown error, so the dialog can say which one it was.
+ "omnirushQualityDetails": async () => {
+ return omnirushAccountStore.qualityDetails();
+ },
+ "omnirushQualitySpins": async () => {
+ return omnirushAccountStore.qualitySpinTotals();
+ },
+ "omnirushQualitySpin": async (event, ...args) => {
+ const input = args[0] && typeof args[0] === "object" ? args[0] : {};
+ return omnirushAccountStore.spinQuality({ idempotencyKey: typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined });
+ },
"omnirushAccountConnect": async (event, ...args) => {
const input = args[0] ?? {};
const result = await omnirushAccountStore.authorize({
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index 1e063299..659e8466 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -13,6 +13,7 @@ import {
writePlaintextCredentialFile,
} from "./plaintext-credential-file.mjs";
import { CLIENT_HEADER, guiClientHeaderValue, parseClientUpdate } from "./update-gate.mjs";
+import { parseAccountQuality, parseQualitySessions, parseSpinResult, parseWheelSegments, spinIdempotencyKey, spinRefusal } from "./quality.mjs";
const execFileAsync = promisify(execFile);
@@ -238,6 +239,8 @@ function accountProfile(value) {
status: normalizeCredential(value.status),
usage,
clientUpdate: parseClientUpdate(value.client_update),
+ // Quality rewards (quality.mjs); null while the feature is off.
+ quality: parseAccountQuality(value.quality),
};
}
@@ -1054,6 +1057,7 @@ export function createDesktopOmniRushAccountStore({
accountStatus: profile?.status ?? null,
usage: profile?.usage ?? null,
clientUpdate: profile?.clientUpdate ?? null,
+ quality: profile?.quality ?? null,
};
} catch (error) {
if (error instanceof InvalidAccountCredentialsError) {
@@ -1068,6 +1072,7 @@ export function createDesktopOmniRushAccountStore({
displayName: null,
accountStatus: null,
usage: null,
+ quality: null,
};
}
// Offline profile lookup must not make a securely stored account look
@@ -1081,10 +1086,94 @@ export function createDesktopOmniRushAccountStore({
displayName: null,
accountStatus: null,
usage: null,
+ quality: null,
};
}
}
+ /**
+ * A request to the account server with the device credential, refreshed
+ * once on a 401 (as the profile check does). Null while signed out.
+ */
+ async function sendAuthorized(pathname, init = {}, refreshesLeft = 1, credentials = undefined) {
+ const current = credentials === undefined ? await load() : credentials;
+ if (!current) return null;
+ const url = controlPlaneBase(current.gatewayUrl);
+ url.pathname += pathname;
+ const headers = new Headers(init.headers);
+ headers.set("Authorization", `Bearer ${current.accessToken}`);
+ const response = await send(url, { ...init, headers, signal: AbortSignal.timeout(20_000) });
+ if (response.status === 401 && refreshesLeft > 0) {
+ const refreshed = await refresh(current.accessToken);
+ if (!refreshed) return response;
+ return sendAuthorized(pathname, init, refreshesLeft - 1, refreshed);
+ }
+ return response;
+ }
+
+ /**
+ * The wheel's segments, the expected payout and the recent sessions with
+ * why each did or did not earn spins (GET /me/quality), for the spin
+ * dialog and the coaching card. Null while signed out, offline or off.
+ */
+ async function qualityDetails() {
+ try {
+ const response = await sendAuthorized("/me/quality", { method: "GET" });
+ if (!response?.ok) return null;
+ const payload = await response.json();
+ if (!payload || typeof payload !== "object" || !payload.quality) return null;
+ const expected = Number(payload.expected_tokens);
+ return {
+ segments: parseWheelSegments(payload.segments),
+ expectedTokens: Number.isFinite(expected) ? expected : null,
+ sessions: parseQualitySessions(payload.sessions),
+ };
+ } catch {
+ return null;
+ }
+ }
+
+ /** GET /me/quality/spins totals; null when unavailable. */
+ async function qualitySpinTotals() {
+ try {
+ const response = await sendAuthorized("/me/quality/spins", { method: "GET" });
+ if (!response?.ok) return null;
+ const payload = await response.json();
+ const totals = payload && typeof payload === "object" ? payload.totals : null;
+ if (!totals || typeof totals !== "object") return null;
+ return { spun: Math.max(0, Number(totals.spun) || 0), paidTokens: Math.max(0, Number(totals.paid_tokens) || 0) };
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * One spin of the quality wheel (POST /me/quality/spin). The key comes from
+ * the click, so a retry of the same click is answered with the same result.
+ * @param {{ idempotencyKey?: string }} [input]
+ * @returns {Promise<import("./quality.mjs").QualitySpinOutcome>}
+ */
+ async function spinQuality(input = {}) {
+ const idempotencyKey = spinIdempotencyKey(input.idempotencyKey);
+ let response;
+ try {
+ response = await sendAuthorized("/me/quality/spin", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ idempotency_key: idempotencyKey }),
+ });
+ } catch {
+ return { ok: false, reason: "unreachable", status: null };
+ }
+ if (!response) return { ok: false, reason: "signed_out", status: null };
+ const payload = await response.json().catch(() => null);
+ if (response.status === 401 || response.status === 403) return { ok: false, reason: "signed_out", status: response.status };
+ if (response.status === 409) return { ok: false, reason: spinRefusal(payload) ?? "failed", status: 409 };
+ if (!response.ok) return { ok: false, reason: "failed", status: response.status };
+ const spin = parseSpinResult(payload);
+ return spin ? { ok: true, spin } : { ok: false, reason: "failed", status: response.status };
+ }
+
/**
* Sign out locally and, for a user-initiated sign-out, revoke the device
* session remotely and forget the keychain gateway URL so the next sign-in
@@ -1124,5 +1213,5 @@ export function createDesktopOmniRushAccountStore({
}
}
- return { load, save, refresh, authorize, status, clear };
+ return { load, save, refresh, authorize, status, clear, qualityDetails, qualitySpinTotals, spinQuality };
}
diff --git a/apps/desktop/electron/quality.mjs b/apps/desktop/electron/quality.mjs
new file mode 100644
index 00000000..eb699851
--- /dev/null
+++ b/apps/desktop/electron/quality.mjs
@@ -0,0 +1,214 @@
+/**
+ * Quality rewards: the `quality` block on /device/me, the wheel's
+ * segments (GET /me/quality) and a spin (POST /me/quality/spin).
+ *
+ * `quality: null` means the feature is switched off: the app shows nothing.
+ * The server picks every spin's outcome; the app only animates the wheel to
+ * `segment_index`.
+ */
+
+export const QUALITY_TIERS = /** @type {const} */ (["new", "standard", "gold", "coaching", "limited"]);
+export const SPIN_REFUSALS = /** @type {const} */ (["no_spins", "wheel_resting", "quality_rewards_off"]);
+
+/**
+ * @typedef {{ id: string, kind: string | null, title: string, body: string }} QualityNotice
+ * @typedef {{
+ * tier: typeof QUALITY_TIERS[number],
+ * score: number,
+ * tokensMultiplier: number,
+ * spinsAvailable: number,
+ * reproSpinsAvailable: number,
+ * spinsExpireAt: string | null,
+ * nextTierHint: string | null,
+ * tips: string[],
+ * notice: QualityNotice | null,
+ * mode: "shadow" | "enforce",
+ * resting: boolean,
+ * preview: boolean,
+ * notices: QualityNotice[],
+ * streakDays: number,
+ * streakMultiplier: number,
+ * streakNext: { days: number, bonusSpins: number } | null,
+ * nextSpinHint: { progress: number, text: string, sessionId: string | null } | null,
+ * biggestWinToday: { tokens: number, at: string | null } | null,
+ * nudge: { id: string, text: string } | null,
+ * }} AccountQuality
+ * @typedef {{ tokens: number, weight: number }} WheelSegment
+ * @typedef {{
+ * tokens: number,
+ * prizeTokens: number,
+ * segmentIndex: number,
+ * segments: WheelSegment[],
+ * preview: boolean,
+ * capped: boolean,
+ * reproducible: boolean,
+ * alreadySpun: boolean,
+ * spunAt: string | null,
+ * spinsAvailable: number,
+ * potBalance: number | null,
+ * celebrate: "none" | "big" | "jackpot",
+ * nearMiss: boolean,
+ * jackpotTokens: number | null,
+ * streakDays: number | null,
+ * }} QualitySpin
+ * @typedef {{ ok: true, spin: QualitySpin }
+ * | { ok: false, reason: typeof SPIN_REFUSALS[number] | "signed_out" | "unreachable" | "failed", status: number | null }} QualitySpinOutcome
+ */
+
+function text(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+function count(value) {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
+}
+
+function isoTime(value) {
+ const raw = text(value);
+ return raw && Number.isFinite(Date.parse(raw)) ? raw : null;
+}
+
+/** @returns {QualityNotice | null} */
+function parseNotice(value) {
+ if (!value || typeof value !== "object") return null;
+ const id = text(value.id);
+ const title = text(value.title);
+ if (!id || !title) return null;
+ return { id, kind: text(value.kind), title, body: text(value.body) ?? "" };
+}
+
+function fraction(value) {
+ const number = Number(value);
+ return Number.isFinite(number) ? Math.min(1, Math.max(0, number)) : 0;
+}
+
+function parseStreakNext(value) {
+ if (!value || typeof value !== "object") return null;
+ const days = count(value.days);
+ return days ? { days, bonusSpins: count(value.bonus_spins) } : null;
+}
+
+function parseNextSpinHint(value) {
+ if (!value || typeof value !== "object") return null;
+ const hint = text(value.text);
+ return hint ? { progress: fraction(value.progress), text: hint, sessionId: text(value.session_id) } : null;
+}
+
+function parseBiggestWin(value) {
+ if (!value || typeof value !== "object") return null;
+ const tokens = count(value.tokens);
+ return tokens ? { tokens, at: isoTime(value.at) } : null;
+}
+
+function parseNudge(value) {
+ if (!value || typeof value !== "object") return null;
+ const id = text(value.id);
+ const message = text(value.text);
+ return id && message ? { id, text: message } : null;
+}
+
+/**
+ * The `quality` block of a /device/me (or /me) answer; null when the
+ * feature is off, the block is missing or it names no known tier.
+ * @returns {AccountQuality | null}
+ */
+export function parseAccountQuality(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const tier = text(value.tier)?.toLowerCase();
+ if (!tier || !QUALITY_TIERS.includes(/** @type {any} */ (tier))) return null;
+ const score = Number(value.score);
+ const multiplier = Number(value.tokens_multiplier);
+ const spinsAvailable = count(value.spins_available);
+ const notices = Array.isArray(value.notices) ? value.notices.map(parseNotice).filter((notice) => notice !== null).slice(0, 5) : [];
+ return {
+ tier: /** @type {AccountQuality["tier"]} */ (tier),
+ score: Number.isFinite(score) ? Math.min(1, Math.max(0, score)) : 0,
+ tokensMultiplier: Number.isFinite(multiplier) && multiplier > 0 ? multiplier : 1,
+ spinsAvailable,
+ reproSpinsAvailable: Math.min(spinsAvailable, count(value.repro_spins_available)),
+ spinsExpireAt: isoTime(value.spins_expire_at),
+ nextTierHint: text(value.next_tier_hint),
+ tips: Array.isArray(value.tips) ? value.tips.map(text).filter((tip) => tip !== null).slice(0, 8) : [],
+ notice: notices[0] ?? parseNotice(value.notice),
+ notices: notices.length ? notices : [parseNotice(value.notice)].filter((notice) => notice !== null),
+ mode: value.mode === "enforce" ? "enforce" : "shadow",
+ resting: value.resting === true,
+ preview: value.preview === true,
+ streakDays: count(value.streak_days),
+ streakMultiplier: count(value.streak_multiplier),
+ streakNext: parseStreakNext(value.streak_next),
+ nextSpinHint: parseNextSpinHint(value.next_spin_hint),
+ biggestWinToday: parseBiggestWin(value.biggest_win_today),
+ nudge: parseNudge(value.nudge),
+ };
+}
+
+/** @returns {WheelSegment[]} */
+export function parseWheelSegments(value) {
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter((segment) => segment && typeof segment === "object")
+ .map((segment) => ({ tokens: count(segment.tokens), weight: Math.max(0, Number(segment.weight) || 0) }));
+}
+
+/**
+ * A 200 from POST /me/quality/spin; null when it does not name a segment
+ * the wheel can land on.
+ * @returns {QualitySpin | null}
+ */
+export function parseSpinResult(value) {
+ if (!value || typeof value !== "object") return null;
+ const segments = parseWheelSegments(value.segments);
+ const segmentIndex = Number(value.segment_index);
+ if (!Number.isInteger(segmentIndex) || segmentIndex < 0 || segmentIndex >= segments.length) return null;
+ const pot = Number(value.pot_balance);
+ return {
+ tokens: count(value.tokens),
+ prizeTokens: count(value.prize_tokens) || segments[segmentIndex].tokens,
+ segmentIndex,
+ segments,
+ preview: value.preview === true,
+ capped: value.capped === true,
+ reproducible: value.reproducible === true,
+ alreadySpun: value.already_spun === true,
+ spunAt: isoTime(value.spun_at),
+ spinsAvailable: count(value.spins_available),
+ potBalance: value.pot_balance === null || value.pot_balance === undefined || !Number.isFinite(pot) ? null : Math.max(0, pot),
+ celebrate: value.celebrate === "big" || value.celebrate === "jackpot" ? value.celebrate : "none",
+ nearMiss: value.near_miss === true,
+ jackpotTokens: count(value.jackpot_tokens) || null,
+ streakDays: value.streak_days === undefined || value.streak_days === null ? null : count(value.streak_days),
+ };
+}
+
+/** The `sessions` of GET /me/quality, for the coaching card's "see why". */
+export function parseQualitySessions(value) {
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter((session) => session && typeof session === "object" && text(session.session_id))
+ .slice(0, 50)
+ .map((session) => ({
+ sessionId: text(session.session_id),
+ at: isoTime(session.at),
+ verdict: text(session.verdict),
+ why: text(session.why),
+ fails: Array.isArray(session.fails) ? session.fails.map(text).filter((fail) => fail !== null) : [],
+ workspace: text(session.workspace),
+ spins: count(session.spins),
+ counted: session.counted === true,
+ }));
+}
+
+/** `{"detail": "wheel_resting"}` (or `{"detail": {"code": ...}}`) from a 409. */
+export function spinRefusal(payload) {
+ const detail = payload && typeof payload === "object" ? payload.detail : null;
+ const code = typeof detail === "string" ? detail : detail && typeof detail === "object" ? detail.code : null;
+ return SPIN_REFUSALS.includes(code) ? code : null;
+}
+
+/** A caller's key, or a fresh one: at most 64 characters, as the server requires. */
+export function spinIdempotencyKey(value) {
+ const key = text(value);
+ return key && key.length <= 64 && /^[0-9A-Za-z._:-]+$/.test(key) ? key : globalThis.crypto.randomUUID();
+}
diff --git a/apps/desktop/electron/quality.test.mjs b/apps/desktop/electron/quality.test.mjs
new file mode 100644
index 00000000..c1d047b6
--- /dev/null
+++ b/apps/desktop/electron/quality.test.mjs
@@ -0,0 +1,230 @@
+import assert from "node:assert/strict";
+import { mkdtemp } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";
+import { parseAccountQuality, parseSpinResult, spinIdempotencyKey, spinRefusal } from "./quality.mjs";
+
+const GATEWAY = "http://localhost:8090/omnirush/v1";
+const SEGMENTS = [
+ { tokens: 250000, weight: 35 }, { tokens: 500000, weight: 30 }, { tokens: 1000000, weight: 20 },
+ { tokens: 2000000, weight: 10 }, { tokens: 5000000, weight: 4 }, { tokens: 10000000, weight: 1 },
+];
+const QUALITY = {
+ tier: "gold",
+ score: 0.52,
+ tokens_multiplier: 1,
+ spins_available: 2,
+ repro_spins_available: 1,
+ spins_expire_at: "2026-10-06T10:00:00Z",
+ next_tier_hint: "Keep it up.",
+ tips: ["Start omnirush inside the project folder.", "", 7],
+ notice: { id: "spins-1", title: "You earned 2 spins", body: "Nice work." },
+ notices: [{ id: "spins-1", kind: "spins", title: "You earned 2 spins", body: "Nice work." }],
+ mode: "enforce",
+ resting: false,
+ preview: false,
+ streak_days: 4,
+ streak_multiplier: 1,
+ streak_next: { days: 7, bonus_spins: 2 },
+ next_spin_hint: { progress: 0.6, text: "Add tests to earn a spin.", session_id: "ses_1" },
+ biggest_win_today: { tokens: 10000000, at: "2026-10-04T09:00:00Z" },
+ nudge: null,
+};
+const SPIN = {
+ tokens: 1000000, prize_tokens: 1000000, segment_index: 2, segments: SEGMENTS, preview: false, capped: false,
+ reproducible: true, already_spun: false, spun_at: "2026-10-04T12:00:00Z", spins_available: 1, pot_balance: 12500000,
+ celebrate: "none", near_miss: false, jackpot_tokens: 10000000, streak_days: 4,
+};
+
+function testStorage() {
+ return {
+ isAsyncEncryptionAvailable: async () => true,
+ getSelectedStorageBackend: () => "keychain",
+ encryptStringAsync: async (value) => Buffer.from(value, "utf8"),
+ decryptStringAsync: async (value) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),
+ };
+}
+
+async function signedInStore(fetchImpl, overrides = {}) {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-quality-"));
+ const store = createDesktopOmniRushAccountStore({
+ filePath: path.join(directory, "account.bin"),
+ loadSafeStorage: () => testStorage(),
+ platform: /** @type {NodeJS.Platform} */ ("linux"),
+ env: { OMNIRUSH_DEV_MODE: "1" },
+ sleep: async () => undefined,
+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },
+ clientVersion: "3.2.0",
+ fetchImpl,
+ ...overrides,
+ });
+ await store.save({ gatewayUrl: GATEWAY, accessToken: "access-1", refreshToken: "refresh-1" });
+ return store;
+}
+
+test("quality: null, missing or an unknown tier means the feature is off", () => {
+ assert.equal(parseAccountQuality(null), null);
+ assert.equal(parseAccountQuality(undefined), null);
+ assert.equal(parseAccountQuality({ tier: "platinum" }), null);
+ assert.equal(parseAccountQuality([]), null);
+});
+
+test("quality block parses every field, including revision 2", () => {
+ const quality = parseAccountQuality(QUALITY);
+ assert.deepEqual(quality, {
+ tier: "gold",
+ score: 0.52,
+ tokensMultiplier: 1,
+ spinsAvailable: 2,
+ reproSpinsAvailable: 1,
+ spinsExpireAt: "2026-10-06T10:00:00Z",
+ nextTierHint: "Keep it up.",
+ tips: ["Start omnirush inside the project folder."],
+ notice: { id: "spins-1", kind: "spins", title: "You earned 2 spins", body: "Nice work." },
+ notices: [{ id: "spins-1", kind: "spins", title: "You earned 2 spins", body: "Nice work." }],
+ mode: "enforce",
+ resting: false,
+ preview: false,
+ streakDays: 4,
+ streakMultiplier: 1,
+ streakNext: { days: 7, bonusSpins: 2 },
+ nextSpinHint: { progress: 0.6, text: "Add tests to earn a spin.", sessionId: "ses_1" },
+ biggestWinToday: { tokens: 10000000, at: "2026-10-04T09:00:00Z" },
+ nudge: null,
+ });
+ // A server without `notices` still has its one `notice`.
+ const legacy = parseAccountQuality({ tier: "limited", tokens_multiplier: 0.3, notice: { id: "n", title: "Hi" } });
+ assert.equal(legacy.notices[0].id, "n");
+ assert.equal(legacy.tokensMultiplier, 0.3);
+ assert.equal(legacy.preview, false);
+});
+
+test("a spin answer must name a segment the wheel can land on", () => {
+ const spin = parseSpinResult(SPIN);
+ assert.equal(spin.segmentIndex, 2);
+ assert.equal(spin.prizeTokens, 1000000);
+ assert.equal(spin.reproducible, true);
+ assert.equal(spin.celebrate, "none");
+ assert.equal(spin.jackpotTokens, 10000000);
+ assert.equal(parseSpinResult({ ...SPIN, segment_index: 6 }), null);
+ assert.equal(parseSpinResult({ ...SPIN, segment_index: -1 }), null);
+ assert.equal(parseSpinResult({ ...SPIN, segments: [] }), null);
+ assert.equal(parseSpinResult({ ...SPIN, celebrate: "party" }).celebrate, "none");
+});
+
+test("409 details map to refusals; anything else is not one", () => {
+ assert.equal(spinRefusal({ detail: "no_spins" }), "no_spins");
+ assert.equal(spinRefusal({ detail: "wheel_resting" }), "wheel_resting");
+ assert.equal(spinRefusal({ detail: { code: "quality_rewards_off" } }), "quality_rewards_off");
+ assert.equal(spinRefusal({ detail: "nope" }), null);
+ assert.equal(spinRefusal(null), null);
+});
+
+test("the idempotency key is the caller's, or a fresh UUID when it is unusable", () => {
+ assert.equal(spinIdempotencyKey("b3f1c1f2-6a7e-4c1a-9a43-0d8f8e9a1b2c"), "b3f1c1f2-6a7e-4c1a-9a43-0d8f8e9a1b2c");
+ assert.match(spinIdempotencyKey("x".repeat(65)), /^[0-9a-f-]{36}$/);
+ assert.match(spinIdempotencyKey(undefined), /^[0-9a-f-]{36}$/);
+});
+
+test("the profile carries `quality` to the renderer, null when the server sends none", async () => {
+ let quality = QUALITY;
+ const store = await signedInStore(async () => Response.json({ email: "[email protected]", status: "active", quality }));
+ assert.equal((await store.status()).quality.tier, "gold");
+ quality = null;
+ assert.equal((await store.status()).quality, null);
+});
+
+test("spin: POST with the device credential, the click's key and X-OmniRush-Client", async () => {
+ const seen = [];
+ const store = await signedInStore(async (url, init = {}) => {
+ const headers = new Headers(init.headers);
+ seen.push({
+ url: String(url),
+ method: init.method,
+ body: init.body ? JSON.parse(init.body) : null,
+ client: headers.get("x-omnirush-client"),
+ authorization: headers.get("authorization"),
+ contentType: headers.get("content-type"),
+ });
+ return Response.json(SPIN);
+ });
+ const outcome = await store.spinQuality({ idempotencyKey: "key-123" });
+ assert.equal(outcome.ok, true);
+ assert.equal(outcome.spin.segmentIndex, 2);
+ assert.deepEqual(seen, [{
+ url: "http://localhost:8090/omnirush/me/quality/spin",
+ method: "POST",
+ body: { idempotency_key: "key-123" },
+ client: "gui/3.2.0",
+ authorization: "Bearer access-1",
+ contentType: "application/json",
+ }]);
+});
+
+test("spin: a 409 comes back as its refusal, never as a thrown error", async () => {
+ for (const detail of ["no_spins", "wheel_resting", "quality_rewards_off"]) {
+ const store = await signedInStore(async () => Response.json({ detail }, { status: 409 }));
+ assert.deepEqual(await store.spinQuality({ idempotencyKey: "k" }), { ok: false, reason: detail, status: 409 });
+ }
+ const odd = await signedInStore(async () => Response.json({ detail: "busy" }, { status: 409 }));
+ assert.deepEqual(await odd.spinQuality({ idempotencyKey: "k" }), { ok: false, reason: "failed", status: 409 });
+ const broken = await signedInStore(async () => Response.json({ detail: "boom" }, { status: 500 }));
+ assert.deepEqual(await broken.spinQuality({ idempotencyKey: "k" }), { ok: false, reason: "failed", status: 500 });
+ const offline = await signedInStore(async () => { throw new TypeError("fetch failed"); });
+ assert.deepEqual(await offline.spinQuality({ idempotencyKey: "k" }), { ok: false, reason: "unreachable", status: null });
+});
+
+test("spin: a 401 refreshes once and retries with the same key", async () => {
+ const spins = [];
+ const store = await signedInStore(async (url, init = {}) => {
+ const pathname = new URL(url).pathname;
+ if (pathname.endsWith("/device/refresh")) {
+ return Response.json({ access_token: "access-2", refresh_token: "refresh-2", gateway_url: GATEWAY });
+ }
+ const authorization = new Headers(init.headers).get("authorization");
+ spins.push({ authorization, key: JSON.parse(init.body).idempotency_key });
+ return authorization === "Bearer access-1" ? new Response(null, { status: 401 }) : Response.json(SPIN);
+ });
+ const outcome = await store.spinQuality({ idempotencyKey: "same-key" });
+ assert.equal(outcome.ok, true);
+ assert.deepEqual(spins, [
+ { authorization: "Bearer access-1", key: "same-key" },
+ { authorization: "Bearer access-2", key: "same-key" },
+ ]);
+});
+
+test("spin while signed out never calls the server", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-quality-"));
+ let calls = 0;
+ const store = createDesktopOmniRushAccountStore({
+ filePath: path.join(directory, "account.bin"),
+ loadSafeStorage: () => testStorage(),
+ platform: /** @type {NodeJS.Platform} */ ("linux"),
+ env: { OMNIRUSH_DEV_MODE: "1" },
+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },
+ fetchImpl: async () => { calls += 1; return Response.json({}); },
+ });
+ assert.deepEqual(await store.spinQuality({ idempotencyKey: "k" }), { ok: false, reason: "signed_out", status: null });
+ assert.equal(calls, 0);
+});
+
+test("quality details: segments, expected tokens and the sessions' reasons", async () => {
+ const store = await signedInStore(async (url) => {
+ assert.equal(new URL(url).pathname, "/omnirush/me/quality");
+ return Response.json({
+ quality: QUALITY,
+ sessions: [{ session_id: "ses_1", at: "2026-10-04T10:00:00Z", verdict: "review", why: "Edits outside the project.", fails: ["outside_path"], workspace: "my-app", spins: 0, counted: true }],
+ segments: SEGMENTS,
+ expected_tokens: 1037500,
+ });
+ });
+ const details = await store.qualityDetails();
+ assert.equal(details.segments.length, 6);
+ assert.equal(details.expectedTokens, 1037500);
+ assert.deepEqual(details.sessions[0].fails, ["outside_path"]);
+ const off = await signedInStore(async () => Response.json({ quality: null, sessions: [], segments: [] }));
+ assert.equal(await off.qualityDetails(), null);
+});
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 3de0947c..f0562ecb 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,7 +27,7 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
"test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index e29d7696..8f0836d2 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -201,6 +201,100 @@ export type OmniRushUpdateGateState = {
source: "profile" | "header" | "rejection" | null;
};
+export type OmniRushQualityTier = "new" | "standard" | "gold" | "coaching" | "limited";
+
+/**
+ * Quality rewards (/device/me `quality`). Absent or null: the feature is
+ * off and the app shows nothing. `preview`: spins pay 0 tokens.
+ */
+export type OmniRushAccountQuality = {
+ tier: OmniRushQualityTier;
+ /** 0..1 */
+ score: number;
+ /** Below 1 while "limited" and the cut is in force. */
+ tokensMultiplier: number;
+ spinsAvailable: number;
+ /** Of `spinsAvailable`, those earned by reproducible sessions (always payable). */
+ reproSpinsAvailable: number;
+ /** UTC ISO 8601, the soonest expiry. */
+ spinsExpireAt: string | null;
+ nextTierHint: string | null;
+ tips: string[];
+ /** Shown once per `id`; the same as `notices[0]`. */
+ notice: OmniRushQualityNotice | null;
+ /** Newest first, up to 5. */
+ notices: OmniRushQualityNotice[];
+ mode: "shadow" | "enforce";
+ /** The daily budget is spent: only reproducible spins can be spun until tomorrow. */
+ resting: boolean;
+ preview: boolean;
+ /** Consecutive UTC days with a reproducible session. */
+ streakDays: number;
+ /** Extra spins per reproducible good session right now. */
+ streakMultiplier: number;
+ streakNext: { days: number; bonusSpins: number } | null;
+ /** How close the latest session is to earning a spin (progress 0..1). */
+ nextSpinHint: { progress: number; text: string; sessionId: string | null } | null;
+ /** Anonymised, across all accounts. */
+ biggestWinToday: { tokens: number; at: string | null } | null;
+ /** Shown once per `id`, only when the server sends one. */
+ nudge: { id: string; text: string } | null;
+};
+
+export type OmniRushQualityNotice = { id: string; kind: string | null; title: string; body: string };
+
+/** One session in GET /me/quality: why it earned (or did not earn) spins. */
+export type OmniRushQualitySession = {
+ sessionId: string;
+ at: string | null;
+ verdict: string | null;
+ why: string | null;
+ fails: string[];
+ workspace: string | null;
+ spins: number;
+ counted: boolean;
+};
+
+export type OmniRushQualityDetails = {
+ segments: OmniRushWheelSegment[];
+ expectedTokens: number | null;
+ sessions: OmniRushQualitySession[];
+};
+
+/** GET /me/quality/spins totals. */
+export type OmniRushQualitySpinTotals = { spun: number; paidTokens: number };
+
+export type OmniRushWheelSegment = { tokens: number; weight: number };
+
+/** A 200 from POST /me/quality/spin. The server picks `segmentIndex`; the app only animates to it. */
+export type OmniRushQualitySpin = {
+ /** Paid into the pot: 0 in preview or past the pot cap. */
+ tokens: number;
+ /** The segment the wheel landed on. */
+ prizeTokens: number;
+ segmentIndex: number;
+ segments: OmniRushWheelSegment[];
+ preview: boolean;
+ capped: boolean;
+ reproducible: boolean;
+ alreadySpun: boolean;
+ spunAt: string | null;
+ spinsAvailable: number;
+ potBalance: number | null;
+ /** big: prize >= 2M; jackpot: the top segment. */
+ celebrate: "none" | "big" | "jackpot";
+ /** Landed next to the jackpot. */
+ nearMiss: boolean;
+ jackpotTokens: number | null;
+ streakDays: number | null;
+};
+
+export type OmniRushQualitySpinRefusal = "no_spins" | "wheel_resting" | "quality_rewards_off";
+
+export type OmniRushQualitySpinOutcome =
+ | { ok: true; spin: OmniRushQualitySpin }
+ | { ok: false; reason: OmniRushQualitySpinRefusal | "signed_out" | "unreachable" | "failed"; status: number | null };
+
export type OmniRushAccountStatus = {
connected: boolean;
gatewayConfigured: boolean;
@@ -226,6 +320,8 @@ export type OmniRushAccountStatus = {
keyringUnavailable?: boolean;
/** /device/me `client_update` for this app; absent from an older desktop bridge. */
clientUpdate?: OmniRushClientUpdate | null;
+ /** Quality rewards; null (or absent from an older bridge) while the feature is off. */
+ quality?: OmniRushAccountQuality | null;
};
export type EngineDoctorResult = {
@@ -641,6 +737,12 @@ export type DesktopCommandMap = {
args: [];
result: OmniRushAccountStatus;
};
+ omnirushQualityDetails: { args: []; result: OmniRushQualityDetails | null };
+ omnirushQualitySpins: { args: []; result: OmniRushQualitySpinTotals | null };
+ omnirushQualitySpin: {
+ args: [input: { idempotencyKey: string }];
+ result: OmniRushQualitySpinOutcome;
+ };
omnirushAccountConnect: {
args: [options?: { gatewayUrl?: string; deviceName?: string }];
result: { connected: true; userCode: string };