Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(quality): show each rewards notice once, never for spins earned, and only when the user is idle

ogsamrat208188db6a68
diff --git a/apps/app/src/app/lib/quality-popups.ts b/apps/app/src/app/lib/quality-popups.ts
new file mode 100644
index 00000000..ed02c5df
--- /dev/null
+++ b/apps/app/src/app/lib/quality-popups.ts
@@ -0,0 +1,109 @@
+// When the quality rewards may interrupt. The server sends notices (tier
+// changes, spins earned, the daily coaching tip) and a nudge, each with an id;
+// /device/me is re-read every 15 minutes and on every window focus. These
+// rules keep that from turning into popups at random moments:
+//
+// - a notice or nudge pops up at most once: seen ids persist (a list, not
+// just the last id, so a server alternating between two ids cannot bring
+// one back) and are marked seen as soon as one shows, not on dismiss;
+// - "you earned N spins" never pops up: the sidebar's spin count says it;
+// - coaching (tier and daily reminder) pops up at most once a UTC day;
+// - nothing pops up while a turn runs or the user is typing (the caller
+// holds a pending popup until a quiet moment).
+
+import type { AccountQuality, QualityNotice } from "./quality";
+import { NOTICE_SEEN_STORAGE_KEY, NUDGE_SEEN_STORAGE_KEY, isCoachingNotice, latestNotice, readPref, writePref } from "./quality";
+
+export const SEEN_NOTICES_STORAGE_KEY = "omnirush.quality.seenNoticeIds.v2";
+export const SEEN_NUDGES_STORAGE_KEY = "omnirush.quality.seenNudgeIds.v2";
+export const COACHING_DAY_STORAGE_KEY = "omnirush.quality.coachingShownDay.v1";
+const MAX_SEEN_IDS = 100;
+
+type KeyValueStore = Pick<Storage, "getItem" | "setItem">;
+
+/** The seen ids under `key`, plus the single id the previous version stored under `legacyKey`. */
+export function readSeenIds(key: string, legacyKey: string | null, storage?: KeyValueStore | null): string[] {
+ const ids: string[] = [];
+ try {
+ const parsed = JSON.parse(readPref(key, storage) ?? "[]");
+ if (Array.isArray(parsed)) ids.push(...parsed.filter((id): id is string => typeof id === "string"));
+ } catch {
+ // A corrupt list only means a popup may show once more.
+ }
+ const legacy = legacyKey ? readPref(legacyKey, storage) : null;
+ if (legacy && !ids.includes(legacy)) ids.push(legacy);
+ return ids;
+}
+
+/** Adds `id` to the seen list (newest last, bounded) and returns the new list. */
+export function rememberSeenId(key: string, id: string, storage?: KeyValueStore | null): string[] {
+ const ids = readSeenIds(key, null, storage).filter((seen) => seen !== id);
+ ids.push(id);
+ const next = ids.slice(-MAX_SEEN_IDS);
+ writePref(key, JSON.stringify(next), storage);
+ return next;
+}
+
+export function readSeenNotices(storage?: KeyValueStore | null): string[] {
+ return readSeenIds(SEEN_NOTICES_STORAGE_KEY, NOTICE_SEEN_STORAGE_KEY, storage);
+}
+
+export function readSeenNudges(storage?: KeyValueStore | null): string[] {
+ return readSeenIds(SEEN_NUDGES_STORAGE_KEY, NUDGE_SEEN_STORAGE_KEY, storage);
+}
+
+/** "You earned N spins": the sidebar count announces it, never a popup. */
+export function isSpinsNotice(notice: QualityNotice | null | undefined): boolean {
+ if (!notice) return false;
+ return notice.kind === "spins" || (!notice.kind && notice.id.startsWith("spins-"));
+}
+
+/** The UTC day, as the server dates its daily notices. */
+export function utcDay(now: number): string {
+ return new Date(now).toISOString().slice(0, 10);
+}
+
+/**
+ * The notice that may pop up now, or null. `coachingDay` is the UTC day a
+ * coaching notice last popped up.
+ */
+export function noticeToPopUp(input: {
+ quality: AccountQuality | null | undefined;
+ seenIds: readonly string[];
+ coachingDay: string | null;
+ now: number;
+}): QualityNotice | null {
+ const notice = latestNotice(input.quality);
+ if (!notice?.id || input.seenIds.includes(notice.id)) return null;
+ if (isSpinsNotice(notice)) return null;
+ if (isCoachingNotice(notice, input.quality) && input.coachingDay === utcDay(input.now)) return null;
+ return notice;
+}
+
+/** The server's nudge, once per id. */
+export function nudgeToPopUp(input: {
+ quality: AccountQuality | null | undefined;
+ seenIds: readonly string[];
+}): { id: string; text: string } | null {
+ const nudge = input.quality?.nudge ?? null;
+ return nudge?.id && !input.seenIds.includes(nudge.id) ? nudge : null;
+}
+
+/**
+ * Records that `notice` popped up: it never pops up again, and a coaching
+ * notice holds the next one back until tomorrow.
+ */
+export function recordNoticeShown(
+ notice: QualityNotice,
+ quality: AccountQuality | null | undefined,
+ now: number,
+ storage?: KeyValueStore | null,
+): void {
+ rememberSeenId(SEEN_NOTICES_STORAGE_KEY, notice.id, storage);
+ if (isCoachingNotice(notice, quality)) writePref(COACHING_DAY_STORAGE_KEY, utcDay(now), storage);
+}
+
+/** A popup may show only when no turn is running and the user is not typing. */
+export function isQuietMoment(input: { turnRunning: boolean; typing: boolean }): boolean {
+ return !input.turnRunning && !input.typing;
+}
diff --git a/apps/app/src/react-app/domains/quality/quality-notice.tsx b/apps/app/src/react-app/domains/quality/quality-notice.tsx
index cec56623..7d20776b 100644
--- a/apps/app/src/react-app/domains/quality/quality-notice.tsx
+++ b/apps/app/src/react-app/domains/quality/quality-notice.tsx
@@ -8,24 +8,19 @@ import { omnirushAccountStatus, omnirushQualityDetails } from "../../../app/lib/
import {
CLIENT_GRADE_NOTE,
REPLAY_READY_LABEL,
- 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";
+import { useQualityPopups } from "./use-quality-popups";
/** Used only when the server sends no `fail_labels` entry for a code. */
const FALLBACK_FAIL_LABELS: Record<string, string> = {
@@ -240,16 +235,17 @@ export function QualityNudge(props: { text: string; onDismiss: () => void }) {
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).
+ * Quality rewards over the app: a notice (once per id, never for spins
+ * earned, coaching at most once a day, only at a quiet moment), the panel
+ * the sidebar opens, the server's nudge (once per id, hides by itself) 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));
+ const { notice, nudge, dismissNotice, dismissNudge } = useQualityPopups(quality);
useEffect(() => {
const read = () => void refreshAccountStatus(omnirushAccountStatus);
@@ -258,24 +254,15 @@ export function QualityRewards() {
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();
+ dismissNotice();
useQualityUiStore.getState().closePanel();
- }, [markNoticeSeen]);
+ }, [dismissNotice]);
const spin = useCallback(() => {
- markNoticeSeen();
+ dismissNotice();
useQualityUiStore.getState().openSpin();
- }, [markNoticeSeen]);
+ }, [dismissNotice]);
const loadSessions = useCallback(async (): Promise<QualitySessionReasons | null> => {
const details = await omnirushQualityDetails();
@@ -289,13 +276,7 @@ export function QualityRewards() {
{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);
- }}
- />
+ <QualityNudge text={nudge.text} onDismiss={dismissNudge} />
) : null}
{spinOpen ? <QualitySpinDialog quality={quality} onClose={() => useQualityUiStore.getState().closeSpin()} /> : null}
</>
diff --git a/apps/app/src/react-app/domains/quality/use-quality-popups.ts b/apps/app/src/react-app/domains/quality/use-quality-popups.ts
new file mode 100644
index 00000000..6273be91
--- /dev/null
+++ b/apps/app/src/react-app/domains/quality/use-quality-popups.ts
@@ -0,0 +1,94 @@
+import { useCallback, useEffect, useState } from "react";
+
+import type { AccountQuality, QualityNotice } from "../../../app/lib/quality";
+import {
+ COACHING_DAY_STORAGE_KEY,
+ SEEN_NOTICES_STORAGE_KEY,
+ SEEN_NUDGES_STORAGE_KEY,
+ isQuietMoment,
+ noticeToPopUp,
+ nudgeToPopUp,
+ readSeenNotices,
+ readSeenNudges,
+ recordNoticeShown,
+ rememberSeenId,
+} from "../../../app/lib/quality-popups";
+import { readPref } from "../../../app/lib/quality";
+import { hasLiveSessionActivity, useSessionActivityStore } from "../session/status/session-activity-store";
+
+/** How long after the last keystroke the user counts as no longer typing. */
+const QUIET_AFTER_TYPING_MS = 30_000;
+/** A nudge is a hint, not a question: it hides by itself. */
+const NUDGE_VISIBLE_MS = 12_000;
+
+/** True while no turn is running and the user has not typed for QUIET_AFTER_TYPING_MS. */
+export function useQuietMoment(quietAfterMs = QUIET_AFTER_TYPING_MS): boolean {
+ const turnRunning = useSessionActivityStore((store) => hasLiveSessionActivity(store.statusesByWorkspaceId));
+ const [typing, setTyping] = useState(false);
+ useEffect(() => {
+ let timer: number | undefined;
+ const onKey = () => {
+ setTyping(true);
+ window.clearTimeout(timer);
+ timer = window.setTimeout(() => setTyping(false), quietAfterMs);
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => {
+ window.removeEventListener("keydown", onKey, true);
+ window.clearTimeout(timer);
+ };
+ }, [quietAfterMs]);
+ return isQuietMoment({ turnRunning, typing });
+}
+
+/**
+ * The notice and nudge to show over the app (quality-popups.ts has the
+ * rules). A popup is chosen only at a quiet moment and is marked seen as it
+ * appears, so it shows once even if the app quits before it is dismissed;
+ * it then stays until dismissed (a nudge hides by itself).
+ */
+export function useQualityPopups(quality: AccountQuality | null) {
+ const quiet = useQuietMoment();
+ const [seenNotices, setSeenNotices] = useState(() => readSeenNotices());
+ const [seenNudges, setSeenNudges] = useState(() => readSeenNudges());
+ const [notice, setNotice] = useState<QualityNotice | null>(null);
+ const [nudge, setNudge] = useState<{ id: string; text: string } | null>(null);
+
+ // Another window (or a second copy of the renderer) marking an id seen.
+ useEffect(() => {
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === SEEN_NOTICES_STORAGE_KEY || event.key === COACHING_DAY_STORAGE_KEY) setSeenNotices(readSeenNotices());
+ if (event.key === SEEN_NUDGES_STORAGE_KEY) setSeenNudges(readSeenNudges());
+ };
+ window.addEventListener("storage", onStorage);
+ return () => window.removeEventListener("storage", onStorage);
+ }, []);
+
+ useEffect(() => {
+ if (!quiet || notice) return;
+ const now = Date.now();
+ const next = noticeToPopUp({ quality, seenIds: seenNotices, coachingDay: readPref(COACHING_DAY_STORAGE_KEY), now });
+ if (!next) return;
+ recordNoticeShown(next, quality, now);
+ setSeenNotices(readSeenNotices());
+ setNotice(next);
+ }, [notice, quality, quiet, seenNotices]);
+
+ useEffect(() => {
+ if (!quiet || nudge || notice) return;
+ const next = nudgeToPopUp({ quality, seenIds: seenNudges });
+ if (!next) return;
+ setSeenNudges(rememberSeenId(SEEN_NUDGES_STORAGE_KEY, next.id));
+ setNudge(next);
+ }, [notice, nudge, quality, quiet, seenNudges]);
+
+ useEffect(() => {
+ if (!nudge) return;
+ const timer = window.setTimeout(() => setNudge(null), NUDGE_VISIBLE_MS);
+ return () => window.clearTimeout(timer);
+ }, [nudge]);
+
+ const dismissNotice = useCallback(() => setNotice(null), []);
+ const dismissNudge = useCallback(() => setNudge(null), []);
+ return { notice, nudge, dismissNotice, dismissNudge };
+}
diff --git a/apps/app/src/react-app/domains/session/status/session-activity-store.ts b/apps/app/src/react-app/domains/session/status/session-activity-store.ts
index f4552ad9..77a0c15f 100644
--- a/apps/app/src/react-app/domains/session/status/session-activity-store.ts
+++ b/apps/app/src/react-app/domains/session/status/session-activity-store.ts
@@ -7,6 +7,28 @@ import { t } from "../../../../i18n";
export type SessionActivityStatus = "idle" | "thinking" | "responding" | "error" | "compacting" | "waiting";
+const LIVE_ACTIVITY_STATUSES: SessionActivityStatus[] = [
+ "thinking",
+ "responding",
+ "compacting",
+ "waiting",
+];
+
+/**
+ * Real-time "anything in flight?" signal across all workspaces. The route
+ * session lists used for `activeSessions` refresh on a slower cadence, so
+ * the SSE-fed activity store is the authoritative gate before disposing the
+ * engine: it flips busy on task submit and also covers sessions waiting on
+ * permission/question prompts (a dispose would orphan those).
+ */
+export function hasLiveSessionActivity(
+ statusesByWorkspaceId: Record<string, Record<string, SessionActivityStatus>>,
+): boolean {
+ return Object.values(statusesByWorkspaceId).some((sessions) =>
+ Object.values(sessions).some((status) => LIVE_ACTIVITY_STATUSES.includes(status)),
+ );
+}
+
type SessionMessageRole = "assistant" | "system" | "user";
type SessionActivityRecord = {
diff --git a/apps/app/src/react-app/shell/reload-coordinator.tsx b/apps/app/src/react-app/shell/reload-coordinator.tsx
index f6af11c6..594d7ab8 100644
--- a/apps/app/src/react-app/shell/reload-coordinator.tsx
+++ b/apps/app/src/react-app/shell/reload-coordinator.tsx
@@ -13,8 +13,8 @@ import {
import type { ReloadReason, ReloadTrigger } from "@/app/types";
import { t } from "@/i18n";
import {
+ hasLiveSessionActivity,
useSessionActivityStore,
- type SessionActivityStatus,
} from "@/react-app/domains/session/status/session-activity-store";
import { useSystemState } from "@/react-app/kernel/system-state";
import { notifyAlert, notifyEvent } from "./notifications";
@@ -104,28 +104,6 @@ function describeApplied(trigger: ReloadTrigger | null): string {
return `${label} changes are now active.`;
}
-const LIVE_ACTIVITY_STATUSES: SessionActivityStatus[] = [
- "thinking",
- "responding",
- "compacting",
- "waiting",
-];
-
-/**
- * Real-time "anything in flight?" signal across all workspaces. The route
- * session lists used for `activeSessions` refresh on a slower cadence, so
- * the SSE-fed activity store is the authoritative gate before disposing the
- * engine: it flips busy on task submit and also covers sessions waiting on
- * permission/question prompts (a dispose would orphan those).
- */
-function hasLiveSessionActivity(
- statusesByWorkspaceId: Record<string, Record<string, SessionActivityStatus>>,
-): boolean {
- return Object.values(statusesByWorkspaceId).some((sessions) =>
- Object.values(sessions).some((status) => LIVE_ACTIVITY_STATUSES.includes(status)),
- );
-}
-
type ReloadSession = { id: string; title: string };
export type WorkspaceReloadControls = {
diff --git a/apps/app/tests/quality-popups.test.ts b/apps/app/tests/quality-popups.test.ts
new file mode 100644
index 00000000..d0446845
--- /dev/null
+++ b/apps/app/tests/quality-popups.test.ts
@@ -0,0 +1,150 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, test } from "bun:test";
+
+import { NOTICE_SEEN_STORAGE_KEY, type AccountQuality, type QualityNotice } from "../src/app/lib/quality";
+import {
+ COACHING_DAY_STORAGE_KEY,
+ SEEN_NOTICES_STORAGE_KEY,
+ isQuietMoment,
+ isSpinsNotice,
+ noticeToPopUp,
+ nudgeToPopUp,
+ readSeenNotices,
+ recordNoticeShown,
+ rememberSeenId,
+} from "../src/app/lib/quality-popups";
+
+const read = (relative: string) => readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");
+
+function memoryStorage(initial: Record<string, string> = {}) {
+ const data = new Map(Object.entries(initial));
+ return {
+ getItem: (key: string) => data.get(key) ?? null,
+ setItem: (key: string, value: string) => void data.set(key, value),
+ data,
+ };
+}
+
+const NOON = Date.parse("2026-10-05T12:00:00Z");
+const notice = (id: string, kind: string | null): QualityNotice => ({ id, kind, title: id, body: "" });
+
+function qualityWith(notices: QualityNotice[], over: Partial<AccountQuality> = {}): AccountQuality {
+ return {
+ tier: "standard",
+ score: 0.3,
+ tokensMultiplier: 1,
+ spinsAvailable: 3,
+ reproSpinsAvailable: 0,
+ clientSpinsAvailable: 0,
+ spinsExpireAt: null,
+ nextTierHint: "",
+ tips: [],
+ notice: notices[0] ?? null,
+ notices,
+ mode: "enforce",
+ resting: false,
+ preview: false,
+ streakDays: 0,
+ streakMultiplier: 1,
+ streakNext: null,
+ nextSpinHint: null,
+ biggestWinToday: null,
+ nudge: null,
+ ...over,
+ } as AccountQuality;
+}
+
+/** One hourly /device/me read: what pops up, and record it as the hook does. */
+function pass(quality: AccountQuality, storage: ReturnType<typeof memoryStorage>, now = NOON): string | null {
+ const shown = noticeToPopUp({
+ quality,
+ seenIds: readSeenNotices(storage),
+ coachingDay: storage.getItem(COACHING_DAY_STORAGE_KEY),
+ now,
+ });
+ if (shown) recordNoticeShown(shown, quality, now, storage);
+ return shown?.id ?? null;
+}
+
+describe("quality notices pop up at most once", () => {
+ test("'you earned N spins' never pops up, every hour or otherwise", () => {
+ const storage = memoryStorage();
+ for (let hour = 0; hour < 6; hour += 1) {
+ const spins = notice(`spins-20261005${String(hour).padStart(2, "0")}00-abc`, "spins");
+ expect(pass(qualityWith([spins]), storage, NOON + hour * 3_600_000)).toBeNull();
+ }
+ expect(isSpinsNotice(notice("spins-20261005-abc", null))).toBe(true);
+ expect(isSpinsNotice(notice("tier-gold-20261005-abc", "tier-gold"))).toBe(false);
+ });
+
+ test("a tier notice pops up once, and stays seen after a restart", () => {
+ const storage = memoryStorage();
+ const gold = notice("tier-gold-20261005-abc", "tier-gold");
+ expect(pass(qualityWith([gold]), storage)).toBe(gold.id);
+ expect(pass(qualityWith([gold]), storage)).toBeNull();
+ // A restart reads the list back from storage.
+ const restarted = memoryStorage(Object.fromEntries(storage.data));
+ expect(pass(qualityWith([gold]), restarted)).toBeNull();
+ });
+
+ test("a server alternating between two ids cannot bring one back", () => {
+ const storage = memoryStorage();
+ const a = notice("tier-gold-a", "tier-gold");
+ const b = notice("tier-standard-b", "tier-standard");
+ expect(pass(qualityWith([a]), storage)).toBe(a.id);
+ expect(pass(qualityWith([b, a]), storage)).toBe(b.id);
+ expect(pass(qualityWith([a, b]), storage)).toBeNull();
+ });
+
+ test("the id the previous version stored counts as seen", () => {
+ const storage = memoryStorage({ [NOTICE_SEEN_STORAGE_KEY]: "tier-gold-old" });
+ expect(pass(qualityWith([notice("tier-gold-old", "tier-gold")]), storage)).toBeNull();
+ expect(JSON.parse(storage.getItem(SEEN_NOTICES_STORAGE_KEY) ?? "[]")).toEqual([]);
+ });
+
+ test("coaching pops up at most once a UTC day", () => {
+ const storage = memoryStorage();
+ const coaching = qualityWith([notice("tier-coaching-1", "tier-coaching")], { tier: "coaching" });
+ expect(pass(coaching, storage)).toBe("tier-coaching-1");
+ const reminder = qualityWith([notice("reminder-coaching-2", "reminder-coaching"), notice("tier-coaching-1", "tier-coaching")], { tier: "coaching" });
+ expect(pass(reminder, storage, NOON + 3_600_000)).toBeNull();
+ // Tomorrow's tip shows.
+ expect(pass(reminder, storage, NOON + 24 * 3_600_000)).toBe("reminder-coaching-2");
+ expect(pass(reminder, storage, NOON + 25 * 3_600_000)).toBeNull();
+ });
+
+ test("the seen list is bounded", () => {
+ const storage = memoryStorage();
+ for (let index = 0; index < 150; index += 1) rememberSeenId(SEEN_NOTICES_STORAGE_KEY, `n-${index}`, storage);
+ const ids = JSON.parse(storage.getItem(SEEN_NOTICES_STORAGE_KEY) ?? "[]");
+ expect(ids).toHaveLength(100);
+ expect(ids.at(-1)).toBe("n-149");
+ });
+});
+
+describe("the nudge", () => {
+ test("pops up once per id", () => {
+ const quality = qualityWith([], { nudge: { id: "nudge-1", text: "Keep going and add tests." } });
+ expect(nudgeToPopUp({ quality, seenIds: [] })?.id).toBe("nudge-1");
+ expect(nudgeToPopUp({ quality, seenIds: ["nudge-1"] })).toBeNull();
+ });
+});
+
+describe("quiet moments", () => {
+ test("nothing pops up while a turn runs or the user types", () => {
+ expect(isQuietMoment({ turnRunning: false, typing: false })).toBe(true);
+ expect(isQuietMoment({ turnRunning: true, typing: false })).toBe(false);
+ expect(isQuietMoment({ turnRunning: false, typing: true })).toBe(false);
+ });
+
+ test("the popup host waits for a quiet moment and marks a popup seen as it appears", () => {
+ const hook = read("../src/react-app/domains/quality/use-quality-popups.ts");
+ expect(hook).toContain("hasLiveSessionActivity");
+ expect(hook).toContain('addEventListener("keydown"');
+ expect(hook).toMatch(/if \(!quiet \|\| notice\) return;/);
+ expect(hook).toContain("recordNoticeShown(next, quality, now)");
+ expect(hook).toContain('addEventListener("storage"');
+ expect(read("../src/react-app/domains/quality/quality-notice.tsx")).toContain("useQualityPopups(quality)");
+ });
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
index ab8167c2..61a675d5 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
@@ -74,4 +74,32 @@ describe("account budget wrap plugin", () => {
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_2" } } });
expect(calls).toHaveLength(0);
});
+
+ test("a failed wrap retries on the next idle without showing the toast again", async () => {
+ process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
+ const toasts: string[] = [];
+ let attempts = 0;
+ const hooks = await OmniRushBudgetWrap({
+ client: { tui: { showToast: async ({ body }) => { toasts.push(body.title); } } },
+ fetch: async () => {
+ attempts += 1;
+ return new Response(null, { status: attempts < 3 ? 500 : 204 });
+ },
+ });
+ const request = new Request("http://gateway.test/v1/responses", {
+ headers: { "x-omnirush-session-id": "ses_3" },
+ });
+ const required = () => hooks["omnirush.http.response"]!({
+ request,
+ response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-required": "1" } }),
+ });
+ await required();
+ for (let idle = 0; idle < 3; idle += 1) {
+ // Every answer of the retried turns still asks for the wrap.
+ await required();
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_3" } } });
+ }
+ expect(attempts).toBe(3);
+ expect(toasts).toEqual(["Wrapping up", "Wrap up complete"]);
+ });
});
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
index e57cb7c3..cbe95c4f 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
@@ -8,7 +8,7 @@
*/
const REQUIRED_HEADER = "x-omnirush-wrap-required";
const WRAP_UP_HEADER = "x-omnirush-wrap-up";
-const pending = new Map<string, { inFlight: boolean }>();
+const pending = new Map<string, { inFlight: boolean; announced?: boolean }>();
type BudgetFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
type BudgetClient = {
tui?: { showToast?: (input: { query?: { directory?: string }; body: { title: string; message: string; variant: string; duration: number } }) => Promise<unknown> };
@@ -65,7 +65,12 @@ export const OmniRushBudgetWrap = async (input: {
const entry = pending.get(sessionID);
if (!entry || entry.inFlight || !baseUrl) return;
entry.inFlight = true;
- await notify("Wrapping up", "Your token allowance is nearly exhausted. Saving a handoff now.", "warning");
+ // Once per wrap: a failed summarize retries on the next idle without
+ // showing the toast again.
+ if (!entry.announced) {
+ entry.announced = true;
+ await notify("Wrapping up", "Your token allowance is nearly exhausted. Saving a handoff now.", "warning");
+ }
try {
const response = await fetcher(
baseUrl + "/session/" + encodeURIComponent(sessionID) + "/summarize",
@@ -107,7 +112,7 @@ export const OmniRushBudgetWrap = async (input: {
pending.delete(sessionID);
return;
}
- if (response.headers.get(REQUIRED_HEADER) === "1") {
+ if (response.headers.get(REQUIRED_HEADER) === "1" && !pending.has(sessionID)) {
pending.set(sessionID, { inFlight: false });
}
},