Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: in-app feedback

Samrat Talukdar2a5586ebc6e7
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index 0a85b63c..2d7efdd9 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -810,6 +810,12 @@ const {
omnirushBuildathonJoin,
omnirushPlacement,
omnirushPlacementAction,
+ omnirushFeedbackPolicy,
+ omnirushFeedbackStatus,
+ omnirushFeedbackSessionStarted,
+ omnirushFeedbackOffer,
+ omnirushFeedbackShown,
+ omnirushFeedbackSubmit,
omnirushBuildathonTagSession,
omnirushBuildathonChecklist,
omnirushAccountConnect,
@@ -884,6 +890,12 @@ export {
omnirushBuildathonJoin,
omnirushPlacement,
omnirushPlacementAction,
+ omnirushFeedbackPolicy,
+ omnirushFeedbackStatus,
+ omnirushFeedbackSessionStarted,
+ omnirushFeedbackOffer,
+ omnirushFeedbackShown,
+ omnirushFeedbackSubmit,
omnirushBuildathonTagSession,
omnirushBuildathonChecklist,
omnirushAccountConnect,
diff --git a/apps/app/src/app/lib/in-app-feedback.ts b/apps/app/src/app/lib/in-app-feedback.ts
new file mode 100644
index 00000000..d8c9468b
--- /dev/null
+++ b/apps/app/src/app/lib/in-app-feedback.ts
@@ -0,0 +1,428 @@
+// In-app feedback, renderer side. The Electron main process decides and
+// sends (apps/desktop/electron/feedback-desktop.mjs and the shared
+// feedback/feedback.mjs, the same rules as the CLI's): whether to ask after
+// a finished turn (the server's policy, once per session, once a day, the
+// sample rate, the pulse), the payload, the queue (feedback.json in the app's
+// data folder) and the analytics event names.
+//
+// Here: how the last turn ended (from the transcript the window already
+// shows), the prompt under the last answer and the "Send feedback" dialog
+// (both in a small store, never in a session's messages), and the toast after
+// a send. Feedback never goes into the transcript, the composer, the model's
+// context or anything a session uploads.
+
+import type { UIMessage } from "ai";
+import { create } from "zustand";
+
+import type {
+ OmniRushFeedbackInput,
+ OmniRushFeedbackOffer,
+ OmniRushFeedbackResult,
+ OmniRushFeedbackTrigger,
+ OmniRushFeedbackTurnOutcome,
+} from "@omnirush/types/desktop-ipc";
+
+import { captureAnalyticsEvent, type AnalyticsProperties } from "./analytics";
+import {
+ omnirushFeedbackOffer,
+ omnirushFeedbackSessionStarted,
+ omnirushFeedbackShown,
+ omnirushFeedbackSubmit,
+} from "./desktop";
+import { messageFacts } from "./good-session";
+
+/** After a thumbs down (the shared module's TURN_REASONS, same ids and words). */
+export const TURN_REASONS = [
+ { id: "wrong", label: "Wrong" },
+ { id: "slow", label: "Too slow" },
+ { id: "instructions", label: "Didn't follow instructions" },
+ { id: "broke", label: "Broke something" },
+ { id: "ui", label: "UI problem" },
+ { id: "other", label: "Other" },
+] as const;
+/** Anytime feedback (the shared module's GENERAL_CATEGORIES). */
+export const GENERAL_CATEGORIES = [
+ { id: "bug", label: "Bug" },
+ { id: "idea", label: "Idea" },
+ { id: "praise", label: "Praise" },
+ { id: "other", label: "Other" },
+] as const;
+export const PULSE_QUESTION = "How likely are you to recommend OmniRush to a friend?";
+export const COMMENT_MAX = 1_000;
+export const SENT_TOAST = "Thanks, sent.";
+/** Kept for later (offline, signed out, the server has none yet): never an error look. */
+export const QUEUED_TOAST = "Thanks, saved for later.";
+/** Under the follow-up: what the rating carries. */
+export const RATING_NOTE = "Sent to the OmniRush team with this chat's id. Not part of the chat.";
+/** The two analytics events the main process forwards (labels only). */
+const EVENT_NAMES = new Set(["feedback_prompt_shown", "feedback_submitted"]);
+const EVENT_CHANNEL = "omnirush:feedback:event";
+
+export type TurnReasonId = (typeof TURN_REASONS)[number]["id"];
+export type GeneralCategoryId = (typeof GENERAL_CATEGORIES)[number]["id"];
+
+// --- how the last turn ended -------------------------------------------------------
+
+export type FinishedTurn = {
+ outcome: OmniRushFeedbackTurnOutcome;
+ toolCalls: number;
+ /** ms from the prompt to the end of the answer; null when the transcript does not say. */
+ durationMs: number | null;
+ /** The answer's final text (at most 700 characters): only to tell a refusal. */
+ text: string;
+ /** 1-based index of the prompt this answers. */
+ turn: number;
+ /** The last assistant message of the turn. */
+ messageId: string;
+};
+
+function record(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
+}
+
+function opencodeMeta(message: UIMessage): Record<string, unknown> {
+ return record(record(message.metadata).opencode);
+}
+
+/**
+ * How the last turn of a transcript ended, or null when it has no answer
+ * yet. Uses the same reading as the Good-session checklist (messageFacts):
+ * a normal finish is "ok"; the Stop button "stopped"; a gateway refusal,
+ * a spent allowance or any other error "error".
+ */
+export function finishedTurn(messages: readonly UIMessage[]): FinishedTurn | null {
+ let start = messages.length;
+ while (start > 0 && messages[start - 1]!.role !== "user") start -= 1;
+ if (start === 0) return null;
+ const prompt = messages[start - 1]!;
+ if (opencodeMeta(prompt).compaction === true) return null;
+ const answer = messages.slice(start).filter((message) => message.role === "assistant");
+ const last = answer.at(-1);
+ if (!last) return null;
+ // A compaction (its summary) is no agent turn: never rated.
+ if (answer.some((message) => opencodeMeta(message).compaction === true)) return null;
+ const facts = messageFacts(messages);
+ if (facts.replyOpen || facts.ended === "none") return null;
+ let outcome: OmniRushFeedbackTurnOutcome;
+ if (facts.ended === "pass" || facts.ended === "awaiting") outcome = "ok";
+ else if (facts.ended === "stopped") outcome = "stopped";
+ else outcome = "error";
+ let toolCalls = 0;
+ let text = "";
+ for (const message of answer) {
+ for (const part of message.parts) {
+ if (part.type === "dynamic-tool" || part.type.startsWith("tool-")) {
+ toolCalls += 1;
+ text = "";
+ } else if (part.type === "text") {
+ const value = (part as { text?: unknown }).text;
+ if (typeof value === "string" && value.trim()) text = value;
+ }
+ }
+ }
+ const created = opencodeMeta(prompt).created;
+ const completed = opencodeMeta(last).completed;
+ const durationMs = typeof created === "number" && typeof completed === "number" && completed >= created ? completed - created : null;
+ const turn = messages.slice(0, start).filter((message) => message.role === "user" && opencodeMeta(message).compaction !== true).length;
+ return { outcome, toolCalls, durationMs, text: text.trim().slice(0, 700), turn, messageId: last.id };
+}
+
+/** The running → done edge of one session's turn. */
+export function turnJustFinished(before: { sessionId: string; running: boolean }, now: { sessionId: string; running: boolean }): boolean {
+ return before.sessionId === now.sessionId && before.running && !now.running;
+}
+
+// --- the store ---------------------------------------------------------------------
+
+export type TurnPromptStage = "rate" | "down" | "up" | "pulse";
+
+export type TurnPrompt = {
+ sessionId: string;
+ kind: "turn" | "pulse";
+ stage: TurnPromptStage;
+ /** The rated answer: its prompt's index, the model and effort of the turn. */
+ turn: number;
+ messageId: string;
+ modelId: string | null;
+ effort: string | null;
+ rating: "up" | "down" | number | null;
+ reasons: TurnReasonId[];
+ comment: string;
+};
+
+export type FeedbackDialogState = {
+ open: boolean;
+ trigger: "menu" | "command";
+ /** The session open when the dialog opened (offered as "Include this session's id"). */
+ sessionId: string | null;
+ category: GeneralCategoryId;
+ text: string;
+ /** null: the default for the category (on for Bug); true/false: the person's own choice. */
+ includeSession: boolean | null;
+ sending: boolean;
+};
+
+type FeedbackState = {
+ prompt: TurnPrompt | null;
+ dialog: FeedbackDialogState;
+};
+
+const closedDialog: FeedbackDialogState = { open: false, trigger: "menu", sessionId: null, category: "bug", text: "", includeSession: null, sending: false };
+
+export const useFeedbackStore = create<FeedbackState>(() => ({ prompt: null, dialog: closedDialog }));
+
+function setPrompt(update: Partial<TurnPrompt>) {
+ useFeedbackStore.setState((state) => ({ prompt: state.prompt ? { ...state.prompt, ...update } : null }));
+}
+
+function setDialog(update: Partial<FeedbackDialogState>) {
+ useFeedbackStore.setState((state) => ({ dialog: { ...state.dialog, ...update } }));
+}
+
+// --- the main process ----------------------------------------------------------------
+
+type Bridge = {
+ offer: (input: { sessionId: string; outcome: OmniRushFeedbackTurnOutcome; toolCalls: number; durationMs: number; text?: string }) => Promise<OmniRushFeedbackOffer>;
+ sessionStarted: (input: { sessionId: string }) => Promise<unknown>;
+ shown: (input: { kind: "turn" | "pulse" }) => Promise<unknown>;
+ submit: (input: OmniRushFeedbackInput) => Promise<OmniRushFeedbackResult>;
+};
+
+let bridge: Bridge = {
+ offer: (input) => omnirushFeedbackOffer(input),
+ sessionStarted: (input) => omnirushFeedbackSessionStarted(input),
+ shown: (input) => omnirushFeedbackShown(input),
+ submit: (input) => omnirushFeedbackSubmit(input),
+};
+
+type Notify = (result: OmniRushFeedbackResult) => void;
+let notify: Notify = () => undefined;
+
+/** The toast after a send (the feedback UI sets it). */
+export function setFeedbackNotifier(next: Notify) {
+ notify = next;
+}
+
+/** Tests: a stand-in for the main process, and a fresh state. */
+export function setFeedbackBridgeForTests(next: Bridge | null): void {
+ if (next) bridge = next;
+ useFeedbackStore.setState({ prompt: null, dialog: closedDialog });
+}
+
+/** The words of the toast after a send: sent, or kept for later (never an error look). */
+export function resultToast(result: OmniRushFeedbackResult): { kind: "sent" | "queued"; title: string } | null {
+ if (!result.ok) return null;
+ return result.sent ? { kind: "sent", title: SENT_TOAST } : { kind: "queued", title: QUEUED_TOAST };
+}
+
+async function send(input: OmniRushFeedbackInput, { toast = true } = {}): Promise<OmniRushFeedbackResult> {
+ let result: OmniRushFeedbackResult;
+ try {
+ result = await bridge.submit(input);
+ } catch {
+ result = { ok: false, error: "failed" };
+ }
+ if (toast) notify(result);
+ return result;
+}
+
+// --- after a turn ----------------------------------------------------------------------
+
+/** A turn started in this session: the pulse counts sessions; an open prompt goes (its rating is sent). */
+export function feedbackTurnStarted(sessionId: string) {
+ void bridge.sessionStarted({ sessionId }).catch(() => undefined);
+ if (useFeedbackStore.getState().prompt) void closePrompt();
+}
+
+/**
+ * The turn of `sessionId` finished: ask the main process whether to ask
+ * now. Shows the prompt (and reports it shown once) when it says so.
+ */
+export async function offerFeedbackAfterTurn(input: {
+ sessionId: string;
+ turn: FinishedTurn;
+ fallbackDurationMs: number;
+ modelId: string | null;
+ effort: string | null;
+}): Promise<OmniRushFeedbackOffer> {
+ const { turn } = input;
+ let offer: OmniRushFeedbackOffer = null;
+ try {
+ offer = await bridge.offer({
+ sessionId: input.sessionId,
+ outcome: turn.outcome,
+ toolCalls: turn.toolCalls,
+ durationMs: turn.durationMs ?? Math.max(0, input.fallbackDurationMs),
+ text: turn.text,
+ });
+ } catch {
+ offer = null;
+ }
+ if (!offer || (offer.kind !== "turn" && offer.kind !== "pulse")) return null;
+ useFeedbackStore.setState({
+ prompt: {
+ sessionId: input.sessionId,
+ kind: offer.kind,
+ stage: offer.kind === "pulse" ? "pulse" : "rate",
+ turn: turn.turn,
+ messageId: turn.messageId,
+ modelId: input.modelId,
+ effort: input.effort,
+ rating: null,
+ reasons: [],
+ comment: "",
+ },
+ });
+ void bridge.shown({ kind: offer.kind }).catch(() => undefined);
+ return offer;
+}
+
+function promptInput(prompt: TurnPrompt): OmniRushFeedbackInput {
+ return {
+ kind: prompt.kind,
+ rating: prompt.rating,
+ categories: prompt.kind === "turn" && prompt.rating === "down" ? [...prompt.reasons] : [],
+ comment: prompt.comment.trim() ? prompt.comment.slice(0, COMMENT_MAX) : null,
+ sessionId: prompt.sessionId,
+ turn: prompt.turn,
+ trigger: prompt.kind === "pulse" ? "pulse" : "sampled",
+ modelId: prompt.modelId,
+ effort: prompt.effort,
+ };
+}
+
+/** Thumbs up / down: the follow-up opens; the rating is sent with it, or when the prompt goes. */
+export function rateTurn(rating: "up" | "down") {
+ const prompt = useFeedbackStore.getState().prompt;
+ if (!prompt || prompt.kind !== "turn") return;
+ setPrompt({ rating, stage: rating, reasons: rating === "down" ? prompt.reasons : [] });
+}
+
+/** The pulse's 0-10 score. */
+export function ratePulse(score: number) {
+ const prompt = useFeedbackStore.getState().prompt;
+ if (!prompt || prompt.kind !== "pulse" || !Number.isInteger(score) || score < 0 || score > 10) return;
+ setPrompt({ rating: score });
+}
+
+export function toggleTurnReason(id: TurnReasonId) {
+ const prompt = useFeedbackStore.getState().prompt;
+ if (!prompt) return;
+ setPrompt({ reasons: prompt.reasons.includes(id) ? prompt.reasons.filter((r) => r !== id) : [...prompt.reasons, id] });
+}
+
+export function setPromptComment(comment: string) {
+ setPrompt({ comment: comment.slice(0, COMMENT_MAX) });
+}
+
+/** Send, or Skip (the rating alone, without reasons or comment). Without a rating the prompt just goes. */
+export async function sendPrompt({ skip = false } = {}): Promise<OmniRushFeedbackResult | null> {
+ const prompt = useFeedbackStore.getState().prompt;
+ useFeedbackStore.setState({ prompt: null });
+ if (!prompt || prompt.rating === null) return null;
+ const input = skip ? { ...promptInput(prompt), categories: [], comment: null } : promptInput(prompt);
+ return send(input);
+}
+
+/**
+ * The prompt goes (×, Esc, the next turn, typing a new prompt, another
+ * session): a rating already chosen still counts (the click is the
+ * signal) and is sent quietly, without the follow-up's extras (as Skip).
+ */
+export function closePrompt(): Promise<OmniRushFeedbackResult | null> {
+ const prompt = useFeedbackStore.getState().prompt;
+ useFeedbackStore.setState({ prompt: null });
+ if (!prompt || prompt.rating === null) return Promise.resolve(null);
+ return send({ ...promptInput(prompt), categories: [], comment: null }, { toast: false });
+}
+
+// --- "Send feedback" ----------------------------------------------------------------------
+
+/** Whether "Include this session's id" is ticked: the person's own choice, else on for Bug. */
+export function includeSessionChecked(dialog: Pick<FeedbackDialogState, "category" | "includeSession">): boolean {
+ return dialog.includeSession ?? dialog.category === "bug";
+}
+
+let currentSessionId: string | null = null;
+
+/** The session open in the window (offered by "Send feedback" opened from a menu that does not know it). */
+export function setFeedbackCurrentSession(sessionId: string | null | undefined) {
+ currentSessionId = typeof sessionId === "string" && sessionId.trim() ? sessionId : null;
+}
+
+/** `sessionId` omitted: the session open in the window, if any. */
+export function openFeedbackDialog(input: { trigger: "menu" | "command"; sessionId?: string | null }) {
+ const given = input.sessionId === undefined ? currentSessionId : input.sessionId;
+ const sessionId = typeof given === "string" && given.trim() ? given : null;
+ useFeedbackStore.setState({ dialog: { ...closedDialog, open: true, trigger: input.trigger, sessionId } });
+}
+
+export function closeFeedbackDialog() {
+ setDialog({ open: false, sending: false });
+}
+
+export function setDialogCategory(category: GeneralCategoryId) {
+ setDialog({ category });
+}
+
+export function setDialogText(text: string) {
+ setDialog({ text });
+}
+
+export function setDialogIncludeSession(include: boolean) {
+ setDialog({ includeSession: include });
+}
+
+export async function sendFeedbackDialog(): Promise<OmniRushFeedbackResult | null> {
+ const dialog = useFeedbackStore.getState().dialog;
+ if (!dialog.open || dialog.sending || !dialog.text.trim()) return null;
+ setDialog({ sending: true });
+ const trigger: OmniRushFeedbackTrigger = dialog.trigger;
+ const result = await send({
+ kind: "general",
+ rating: null,
+ categories: [dialog.category],
+ comment: dialog.text.slice(0, COMMENT_MAX),
+ sessionId: dialog.sessionId && includeSessionChecked(dialog) ? dialog.sessionId : null,
+ turn: null,
+ trigger,
+ modelId: null,
+ effort: null,
+ });
+ if (result.ok) useFeedbackStore.setState({ dialog: closedDialog });
+ else setDialog({ sending: false });
+ return result;
+}
+
+// --- analytics ----------------------------------------------------------------------------
+
+function cleanProperties(value: unknown): AnalyticsProperties {
+ const out: AnalyticsProperties = {};
+ for (const [key, v] of Object.entries(record(value))) {
+ // Labels only: the main process never sends the comment; anything long is dropped too.
+ if (key === "comment") continue;
+ if (v === null || typeof v === "boolean" || typeof v === "number" || (typeof v === "string" && v.length <= 120)) out[key] = v;
+ }
+ return out;
+}
+
+/** Pass the main process's two feedback events on to the app's analytics. */
+export function handleFeedbackEvent(detail: unknown): boolean {
+ const value = record(detail);
+ if (typeof value.name !== "string" || !EVENT_NAMES.has(value.name)) return false;
+ captureAnalyticsEvent(value.name, cleanProperties(value.properties));
+ return true;
+}
+
+const NATIVE_MENU_SEND_FEEDBACK_EVENT = "omnirush:native-menu:send-feedback";
+
+let installed = false;
+/** Once per window: the analytics hand-off and Help > Send Feedback…. */
+export function installFeedbackAnalytics() {
+ if (installed || typeof window === "undefined") return;
+ installed = true;
+ window.addEventListener(EVENT_CHANNEL, (event) => {
+ handleFeedbackEvent((event as CustomEvent).detail);
+ });
+ window.addEventListener(NATIVE_MENU_SEND_FEEDBACK_EVENT, () => openFeedbackDialog({ trigger: "menu" }));
+}
diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.ts
index 045e6549..6f660a91 100644
--- a/apps/app/src/i18n/locales/en.ts
+++ b/apps/app/src/i18n/locales/en.ts
@@ -1404,7 +1404,7 @@ export default {
"session.run_status_stopping_action": "Stopping…",
"session.run_status_queued": "{count} follow-up message(s) will wait until this run finishes.",
"session.support_docs": "Open documentation",
- "session.support_feedback": "Open feedback",
+ "session.support_feedback": "Send feedback",
"session.todo_label": "Tasks",
"session.todo_progress": "{completed} out of {total} tasks completed",
"session.todo_progress_label": "Progress",
@@ -1992,7 +1992,7 @@ export default {
"status.disconnected_hint": "Open settings to reconnect",
"status.disconnected_label": "Disconnected",
"status.docs": "Docs",
- "status.feedback": "Feedback",
+ "status.feedback": "Send feedback",
"status.limited_hint": "Reconnect to restore full omnirush.ai features",
"status.limited_mcp_hint": "{count} MCP connected · reconnect for full features",
"status.limited_mode": "Limited Mode",
diff --git a/apps/app/src/react-app/domains/feedback/feedback.tsx b/apps/app/src/react-app/domains/feedback/feedback.tsx
new file mode 100644
index 00000000..2d834be1
--- /dev/null
+++ b/apps/app/src/react-app/domains/feedback/feedback.tsx
@@ -0,0 +1,406 @@
+/** @jsxImportSource react */
+// In-app feedback (app/lib/in-app-feedback.ts; the main process decides).
+//
+// - After a finished, eligible turn, when the main process says so: a quiet
+// "How was this?" with thumbs up / down under the last answer, fading in.
+// Not modal, never while a turn runs; it goes when the next turn starts,
+// when a new prompt is typed, on × or Esc. Thumbs down opens reasons and
+// a one-line comment, thumbs up a one-line "What worked?"; the rating is
+// sent even when the follow-up is ignored. Or, instead, the 0-10 pulse.
+// - Anytime: "Send feedback" (account menu, command palette) opens a small
+// dialog: category, text, "Include this session's id".
+// The prompt is drawn next to the transcript, never part of its messages.
+
+import { useEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from "react";
+import type { UIMessage } from "ai";
+import { ThumbsDown, ThumbsUp, X } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { toast } from "@/components/ui/sonner";
+import { Textarea } from "@/components/ui/textarea";
+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
+import { cn } from "@/lib/utils";
+
+import {
+ closeFeedbackDialog,
+ closePrompt,
+ COMMENT_MAX,
+ feedbackTurnStarted,
+ finishedTurn,
+ GENERAL_CATEGORIES,
+ includeSessionChecked,
+ installFeedbackAnalytics,
+ offerFeedbackAfterTurn,
+ PULSE_QUESTION,
+ RATING_NOTE,
+ ratePulse,
+ rateTurn,
+ resultToast,
+ sendFeedbackDialog,
+ sendPrompt,
+ setDialogCategory,
+ setDialogIncludeSession,
+ setDialogText,
+ setFeedbackNotifier,
+ setPromptComment,
+ toggleTurnReason,
+ TURN_REASONS,
+ turnJustFinished,
+ useFeedbackStore,
+ type FeedbackDialogState,
+ type GeneralCategoryId,
+ type TurnPrompt,
+ type TurnReasonId,
+} from "../../../app/lib/in-app-feedback";
+
+/** The engine says idle a moment before it writes a failed turn's error: the turn is read after this. */
+const SETTLE_MS = 1_200;
+/** …and waited for up to this long while the answer still looks open. */
+const SETTLE_MAX_MS = 4_500;
+
+// --- after a turn -----------------------------------------------------------------------
+
+export type FeedbackTurnPromptProps = {
+ sessionId: string;
+ messages: readonly UIMessage[];
+ turnRunning: boolean;
+ /** The composer's draft: typing a new prompt puts the prompt away. */
+ draft: string;
+ modelId: string | null;
+ effort: string | null;
+};
+
+/**
+ * Watches this session's turns: on the running → done edge it reads how
+ * the turn ended and asks the main process; draws the prompt it gets.
+ */
+export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
+ const prompt = useFeedbackStore((state) => state.prompt);
+ const latest = useRef(props);
+ latest.current = props;
+ const edge = useRef({ sessionId: props.sessionId, running: props.turnRunning });
+ const startedAt = useRef<number | null>(null);
+
+ useEffect(() => {
+ const before = edge.current;
+ const now = { sessionId: props.sessionId, running: props.turnRunning };
+ edge.current = now;
+ if (props.turnRunning) {
+ if (!before.running || before.sessionId !== props.sessionId) {
+ startedAt.current = Date.now();
+ feedbackTurnStarted(props.sessionId);
+ }
+ return;
+ }
+ if (!turnJustFinished(before, now)) return;
+ const sessionId = props.sessionId;
+ const began = startedAt.current ?? Date.now();
+ const deadline = Date.now() + SETTLE_MAX_MS;
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const judge = () => {
+ if (cancelled) return;
+ const current = latest.current;
+ if (current.sessionId !== sessionId || current.turnRunning) return;
+ const turn = finishedTurn(current.messages);
+ if (!turn) {
+ if (Date.now() < deadline) timer = setTimeout(judge, 150);
+ return;
+ }
+ void offerFeedbackAfterTurn({ sessionId, turn, fallbackDurationMs: Date.now() - began, modelId: current.modelId, effort: current.effort });
+ };
+ timer = setTimeout(judge, SETTLE_MS);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [props.sessionId, props.turnRunning]);
+
+ // This pane switches to another session: the prompt of the one it left goes (its rating, if chosen, is sent).
+ const shownSession = useRef(props.sessionId);
+ useEffect(() => {
+ const left = shownSession.current;
+ shownSession.current = props.sessionId;
+ if (left === props.sessionId) return;
+ if (useFeedbackStore.getState().prompt?.sessionId === left) void closePrompt();
+ }, [props.sessionId]);
+
+ const visible = Boolean(prompt) && prompt?.sessionId === props.sessionId && !props.turnRunning;
+ // Typing a new prompt (the draft changing after the prompt showed) puts it away.
+ const draftAtShow = useRef<string | null>(null);
+ useEffect(() => {
+ if (!visible) {
+ draftAtShow.current = null;
+ return;
+ }
+ if (draftAtShow.current === null) {
+ draftAtShow.current = props.draft;
+ return;
+ }
+ if (props.draft !== draftAtShow.current && props.draft.trim()) void closePrompt();
+ }, [visible, props.draft]);
+
+ if (!visible || !prompt) return null;
+ return (
+ <FeedbackTurnPromptView
+ prompt={prompt}
+ onRate={rateTurn}
+ onPulse={ratePulse}
+ onToggleReason={toggleTurnReason}
+ onComment={setPromptComment}
+ onSend={() => void sendPrompt()}
+ onSkip={() => void sendPrompt({ skip: true })}
+ onDismiss={() => void closePrompt()}
+ />
+ );
+}
+
+export type FeedbackTurnPromptViewProps = {
+ prompt: TurnPrompt;
+ onRate: (rating: "up" | "down") => void;
+ onPulse: (score: number) => void;
+ onToggleReason: (id: TurnReasonId) => void;
+ onComment: (text: string) => void;
+ onSend: () => void;
+ onSkip: () => void;
+ onDismiss: () => void;
+};
+
+const thumbClass = "size-7 rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground aria-pressed:bg-muted aria-pressed:text-foreground";
+const chipClass = "inline-flex h-7 items-center rounded-full border border-border px-2.5 text-[12px] leading-none text-muted-foreground transition-colors hover:border-foreground/20 hover:text-foreground aria-pressed:border-foreground/25 aria-pressed:bg-muted aria-pressed:text-foreground";
+
+function CommentRow(props: { prompt: TurnPrompt; placeholder: string; onComment: (text: string) => void; onSend: () => void; onSkip: () => void; testId: string }) {
+ return (
+ <>
+ <div className="flex w-full max-w-xl items-center gap-2">
+ <Input
+ autoFocus
+ value={props.prompt.comment}
+ maxLength={COMMENT_MAX}
+ placeholder={props.placeholder}
+ aria-label={props.placeholder}
+ onChange={(event) => props.onComment(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ props.onSend();
+ }
+ }}
+ className="h-8 flex-1 text-[13px]"
+ data-testid={props.testId}
+ />
+ <Button size="sm" className="h-8" onClick={props.onSend} data-testid="feedback-send">Send</Button>
+ <Button size="sm" variant="ghost" className="h-8 text-muted-foreground" onClick={props.onSkip} data-testid="feedback-skip">Skip</Button>
+ </div>
+ <p className="text-[11px] leading-4 text-muted-foreground/80" data-testid="feedback-note">{RATING_NOTE}</p>
+ </>
+ );
+}
+
+/** The prompt itself (tests render it directly). */
+export function FeedbackTurnPromptView(props: FeedbackTurnPromptViewProps) {
+ const { prompt } = props;
+ const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ props.onDismiss();
+ }
+ };
+ const dismiss = (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Dismiss"
+ title="Dismiss (Esc)"
+ onClick={props.onDismiss}
+ className="text-muted-foreground/70 hover:text-foreground"
+ data-testid="feedback-dismiss"
+ >
+ <X aria-hidden="true" />
+ </Button>
+ );
+ return (
+ <div
+ role="group"
+ aria-label={prompt.kind === "pulse" ? PULSE_QUESTION : "How was this?"}
+ data-testid={prompt.kind === "pulse" ? "feedback-pulse" : "feedback-turn"}
+ data-stage={prompt.stage}
+ data-feedback-ui="true"
+ onKeyDown={onKeyDown}
+ className="not-prose mx-auto flex w-full max-w-3xl flex-col items-start gap-2 px-2 pb-2 duration-200 animate-in fade-in-0 motion-reduce:animate-none md:px-10"
+ >
+ {prompt.kind === "pulse" ? (
+ <>
+ <div className="flex w-full items-center gap-2">
+ <span className="text-[12.5px] text-muted-foreground">{PULSE_QUESTION}</span>
+ <span className="flex-1" />
+ {dismiss}
+ </div>
+ <div className="flex flex-wrap items-center gap-1" role="radiogroup" aria-label="0 = not likely, 10 = very likely">
+ <span className="me-1 text-[11px] text-muted-foreground/80">Not likely</span>
+ {Array.from({ length: 11 }, (_, score) => (
+ <button
+ key={score}
+ type="button"
+ role="radio"
+ aria-checked={prompt.rating === score}
+ onClick={() => props.onPulse(score)}
+ className={cn(
+ "inline-flex size-7 items-center justify-center rounded-lg border border-border text-[12px] tabular-nums text-muted-foreground transition-colors hover:border-foreground/20 hover:text-foreground",
+ prompt.rating === score && "border-foreground bg-foreground text-background hover:text-background",
+ )}
+ data-testid={`feedback-pulse-${score}`}
+ >
+ {score}
+ </button>
+ ))}
+ <span className="ms-1 text-[11px] text-muted-foreground/80">Very likely</span>
+ </div>
+ {typeof prompt.rating === "number" ? (
+ <CommentRow prompt={prompt} placeholder="Why? (optional)" onComment={props.onComment} onSend={props.onSend} onSkip={props.onSkip} testId="feedback-comment" />
+ ) : null}
+ </>
+ ) : (
+ <>
+ <div className="flex items-center gap-1">
+ <span className="me-1 text-[12px] text-muted-foreground">How was this?</span>
+ <Button variant="ghost" size="icon-xs" className={thumbClass} aria-label="Good answer" title="Good answer" aria-pressed={prompt.rating === "up"} onClick={() => props.onRate("up")} data-testid="feedback-up">
+ <ThumbsUp className="size-3.5" aria-hidden="true" />
+ </Button>
+ <Button variant="ghost" size="icon-xs" className={thumbClass} aria-label="Bad answer" title="Bad answer" aria-pressed={prompt.rating === "down"} onClick={() => props.onRate("down")} data-testid="feedback-down">
+ <ThumbsDown className="size-3.5" aria-hidden="true" />
+ </Button>
+ {dismiss}
+ </div>
+ {prompt.stage === "down" ? (
+ <>
+ <div className="flex flex-wrap items-center gap-1.5" aria-label="What went wrong?">
+ {TURN_REASONS.map((reason) => (
+ <button
+ key={reason.id}
+ type="button"
+ aria-pressed={prompt.reasons.includes(reason.id)}
+ onClick={() => props.onToggleReason(reason.id)}
+ className={chipClass}
+ data-testid={`feedback-reason-${reason.id}`}
+ >
+ {reason.label}
+ </button>
+ ))}
+ </div>
+ <CommentRow prompt={prompt} placeholder="Anything to add? (optional)" onComment={props.onComment} onSend={props.onSend} onSkip={props.onSkip} testId="feedback-comment" />
+ </>
+ ) : prompt.stage === "up" ? (
+ <CommentRow prompt={prompt} placeholder="What worked? (optional)" onComment={props.onComment} onSend={props.onSend} onSkip={props.onSkip} testId="feedback-comment" />
+ ) : null}
+ </>
+ )}
+ </div>
+ );
+}
+
+// --- "Send feedback" ----------------------------------------------------------------------
+
+export type FeedbackFormViewProps = {
+ dialog: FeedbackDialogState;
+ onCategory: (category: GeneralCategoryId) => void;
+ onText: (text: string) => void;
+ onIncludeSession: (include: boolean) => void;
+ onSend: () => void;
+ onCancel: () => void;
+};
+
+export const FEEDBACK_DIALOG_DESCRIPTION = "Tell us what's working and what isn't. It goes to the OmniRush team with your account.";
+
+/** The dialog's form under its title (tests render it directly). */
+export function FeedbackFormView(props: FeedbackFormViewProps) {
+ const { dialog } = props;
+ const canSend = Boolean(dialog.text.trim()) && !dialog.sending;
+ return (
+ <>
+ <div className="flex flex-col gap-3" data-testid="feedback-form">
+ <ToggleGroup
+ aria-label="Category"
+ variant="outline"
+ size="sm"
+ value={[dialog.category]}
+ onValueChange={(value) => {
+ const next = value[0];
+ if (GENERAL_CATEGORIES.some((c) => c.id === next)) props.onCategory(next as GeneralCategoryId);
+ }}
+ className="w-full"
+ >
+ {GENERAL_CATEGORIES.map((category) => (
+ <ToggleGroupItem key={category.id} value={category.id} className="flex-1" data-testid={`feedback-category-${category.id}`}>
+ {category.label}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ <Textarea
+ autoFocus
+ value={dialog.text}
+ maxLength={COMMENT_MAX}
+ rows={4}
+ placeholder={dialog.category === "bug" ? "What happened, and what did you expect?" : dialog.category === "idea" ? "What would make OmniRush better for you?" : "Your feedback"}
+ aria-label="Your feedback"
+ onChange={(event) => props.onText(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && canSend) {
+ event.preventDefault();
+ props.onSend();
+ }
+ }}
+ className="min-h-24"
+ data-testid="feedback-text"
+ />
+ {dialog.sessionId ? (
+ <label className="flex cursor-pointer items-center gap-2 text-[13px] text-muted-foreground" data-testid="feedback-include-session">
+ <Checkbox checked={includeSessionChecked(dialog)} onCheckedChange={(checked) => props.onIncludeSession(checked === true)} />
+ Include this session's id
+ </label>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={props.onCancel} data-testid="feedback-cancel">Cancel</Button>
+ <Button onClick={props.onSend} disabled={!canSend} data-testid="feedback-dialog-send">Send</Button>
+ </DialogFooter>
+ </>
+ );
+}
+
+function notifyResult(result: Parameters<Parameters<typeof setFeedbackNotifier>[0]>[0]) {
+ const words = resultToast(result);
+ if (!words) return;
+ if (words.kind === "sent") toast.success(words.title, { id: "feedback-result", duration: 3_000 });
+ else toast(words.title, { id: "feedback-result", duration: 4_000 });
+}
+
+/** Mounted once in the app: the dialog, the toast after a send, the analytics hand-off. */
+export function FeedbackDialog() {
+ const dialog = useFeedbackStore((state) => state.dialog);
+ useEffect(() => {
+ installFeedbackAnalytics();
+ setFeedbackNotifier(notifyResult);
+ }, []);
+ return (
+ <Dialog open={dialog.open} onOpenChange={(open) => { if (!open) closeFeedbackDialog(); }}>
+ <DialogContent className="lg:max-w-lg" data-testid="feedback-dialog">
+ <DialogHeader>
+ <DialogTitle>Send feedback</DialogTitle>
+ <DialogDescription>{FEEDBACK_DIALOG_DESCRIPTION}</DialogDescription>
+ </DialogHeader>
+ <FeedbackFormView
+ dialog={dialog}
+ onCategory={setDialogCategory}
+ onText={setDialogText}
+ onIncludeSession={setDialogIncludeSession}
+ onSend={() => void sendFeedbackDialog()}
+ onCancel={closeFeedbackDialog}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
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 55ecb8d4..43a87f7b 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
@@ -34,6 +34,7 @@ import {
UserRound,
X,
Workflow,
+ MessageCircleMore,
} from "lucide-react";
import { LazyMotion, Reorder, domMax, m, useDragControls } from "motion/react";
@@ -64,6 +65,7 @@ import { resolveExtensionIconSrc } from "../../../design-system/extension-icon-s
import { useBrandAppName, useBrandLogoUrl } from "../../cloud/brand-theme";
import { canCreateWorkspaces } from "../../../../app/lib/workspace-creation-policy";
import { useShellConfig } from "../../../shell/shell-config";
+import { openFeedbackDialog } from "../../../../app/lib/in-app-feedback";
import {
Sidebar,
@@ -1029,6 +1031,7 @@ function QualitySpinRow({ quality }: { quality: AccountQuality }) {
function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings: () => void }) {
// Shared with the quality popup (QualityRewards): one /device/me read for both.
const status: NativeAccountStatus | null = useAccountStatusStore((store) => store.status);
+ const { config: shellConfig } = useShellConfig();
React.useEffect(() => {
const refresh = () => void refreshAccountStatus(omnirushAccountStatus);
@@ -1100,6 +1103,20 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
</SidebarMenuButton>
</SidebarMenuItem>
{quality ? <QualitySpinRow quality={quality} /> : null}
+ {shellConfig.feedbackButton ? (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ type="button"
+ onClick={() => openFeedbackDialog({ trigger: "menu" })}
+ tooltip="Send feedback"
+ aria-label="Send feedback"
+ data-testid="sidebar-send-feedback"
+ >
+ <MessageCircleMore className="size-4" />
+ <span>Send feedback</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ) : null}
<SidebarMenuItem>
<SidebarMenuButton
type="button"
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index f840d1a3..ca89c060 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -101,6 +101,7 @@ import { QuestionPanel } from "@/react-app/domains/session/modals/question-modal
import { QueuedMessagesPanel } from "@/react-app/domains/session/modals/queued-messages-panel";
import { GoodSessionChecklistBar, noteUserStop } from "@/react-app/domains/quality/good-session";
import { PlacementTurnFooter } from "@/react-app/domains/placements/placements";
+import { FeedbackTurnPrompt } from "@/react-app/domains/feedback/feedback";
import { deriveOpenTargets, sameOpenTargets, selectAutoOpenTarget, type OpenTarget } from "@/react-app/domains/session/artifacts/open-target";
import { usePanelTabStore } from "@/react-app/domains/session/panel/panel-tab-store";
import {
@@ -3399,6 +3400,15 @@ export function SessionSurface(props: SessionSurfaceProps) {
</OpenTargetProvider>
</DevProfiler>
)}
+ {/* In-app feedback: under the last answer, drawn beside the transcript (never one of its messages). */}
+ <FeedbackTurnPrompt
+ sessionId={props.sessionId}
+ messages={renderedMessages}
+ turnRunning={chatStreaming || (effectiveActivityStatus !== "idle" && effectiveActivityStatus !== "error")}
+ draft={draft}
+ modelId={sessionModel.selectedModel?.modelID ?? null}
+ effort={sessionModel.modelVariant ?? null}
+ />
{admissionOutcomeUnresolved && queuedDrainState.phase.kind !== "admission_unknown" && renderedMessages.length > 0 ? (
<AdmissionOutcomeUnknownCard
resuming={resuming}
diff --git a/apps/app/src/react-app/shell/command-palette.tsx b/apps/app/src/react-app/shell/command-palette.tsx
index 46bcc515..3eae08d1 100644
--- a/apps/app/src/react-app/shell/command-palette.tsx
+++ b/apps/app/src/react-app/shell/command-palette.tsx
@@ -28,6 +28,8 @@ import {
} from "@/components/ui/command";
import { Button } from "@/components/ui/button";
import { DEFAULT_FEEDBACK_URL } from "@/app/lib/feedback";
+import { openFeedbackDialog } from "@/app/lib/in-app-feedback";
+import { isDesktopRuntime } from "@/app/utils";
import { ChevronLeftIcon } from "lucide-react";
import type { ModelOption, ModelRef } from "@/app/types";
import { useCheckDesktopRestriction } from "../domains/cloud/desktop-config-provider";
@@ -354,11 +356,13 @@ export function CommandPalette(props: CommandPaletteProps) {
id: "open-feedback",
title: t("session.support_feedback"),
meta: t("session.cmd_settings_meta"),
- keywords: ["feedback", "issue", "bug", "support"],
+ keywords: ["feedback", "issue", "bug", "idea", "support", "report"],
group: ACTIONS_GROUP,
action: () => {
props.onClose();
- openUrl(DEFAULT_FEEDBACK_URL);
+ // The desktop sends it to the OmniRush team (in-app); elsewhere the public issue form.
+ if (isDesktopRuntime()) openFeedbackDialog({ trigger: "command", sessionId: props.currentSession?.sessionId ?? null });
+ else openUrl(DEFAULT_FEEDBACK_URL);
},
},
], [accessibleTargetCount, canMoveCurrentSessionToGroup, hasNestedModelPicker, props, sessionGroupCount, sessionNumberHelp]);
diff --git a/apps/app/src/react-app/shell/providers.tsx b/apps/app/src/react-app/shell/providers.tsx
index 7b97e51c..7c3ec681 100644
--- a/apps/app/src/react-app/shell/providers.tsx
+++ b/apps/app/src/react-app/shell/providers.tsx
@@ -23,6 +23,7 @@ import { useEnterpriseActivationRequired } from "@/react-app/domains/cloud/enter
import { startDebugLogger, stopDebugLogger } from "./debug-logger";
import { resolveOmniRushConnection } from "./omnirush-connection";
import { ReloadCoordinatorProvider } from "./reload-coordinator";
+import { FeedbackDialog } from "../domains/feedback/feedback";
function resolveDefaultServerUrl(): string {
if (isDesktopRuntime()) return "http://127.0.0.1:4096";
@@ -68,6 +69,7 @@ function EnterpriseAwareAppProviders({ children }: AppProvidersProps) {
<GlobalQueueDrainerBridge />
<ReloadCoordinatorProvider>{children}</ReloadCoordinatorProvider>
<Toaster />
+ <FeedbackDialog />
</LocalProvider>
</RestrictionNoticeProvider>
</BrandThemeProvider>
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index ce51984d..49d8e041 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -65,6 +65,7 @@ import type {
WorkspaceSessionGroup,
} from "@/app/types";
import { buildFeedbackUrl } from "@/app/lib/feedback";
+import { openFeedbackDialog, setFeedbackCurrentSession } from "@/app/lib/in-app-feedback";
import {
getWorkspaceTaskLoadErrorDisplay,
isDesktopRuntime,
@@ -521,6 +522,11 @@ export function SessionRoute() {
onServerSettingsChanged: () => setOmniRushServerSettingsVersion((value) => value + 1),
onHostInfo: setOmniRushServerHostInfoState,
});
+ // "Send feedback" from a menu that does not know the open session (Help menu, sidebar).
+ useEffect(() => {
+ setFeedbackCurrentSession(selectedSessionId ?? null);
+ return () => setFeedbackCurrentSession(null);
+ }, [selectedSessionId]);
const routeNavigationRef = useRef({ locationKey: location.key, generation: 0 });
if (routeNavigationRef.current.locationKey !== location.key) {
routeNavigationRef.current = {
@@ -3422,6 +3428,11 @@ export function SessionRoute() {
providers={providers}
mcpConnectedCount={mcpConnectedCount}
onSendFeedback={() => {
+ // The desktop sends it to the OmniRush team (in-app); elsewhere the public issue form.
+ if (isDesktopRuntime()) {
+ openFeedbackDialog({ trigger: "menu", sessionId: selectedSessionId ?? null });
+ return;
+ }
platform.openLink(
buildFeedbackUrl({
entrypoint: "status-bar",
diff --git a/apps/app/tests/in-app-feedback.test.tsx b/apps/app/tests/in-app-feedback.test.tsx
new file mode 100644
index 00000000..9883e21d
--- /dev/null
+++ b/apps/app/tests/in-app-feedback.test.tsx
@@ -0,0 +1,297 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import type { UIMessage } from "ai";
+import { renderToStaticMarkup } from "react-dom/server";
+import type { OmniRushFeedbackInput } from "@omnirush/types/desktop-ipc";
+
+class MemoryStorage {
+ private values = new Map<string, string>();
+ getItem(key: string) { return this.values.has(key) ? this.values.get(key)! : null; }
+ setItem(key: string, value: string) { this.values.set(key, String(value)); }
+ removeItem(key: string) { this.values.delete(key); }
+ clear() { this.values.clear(); }
+}
+const storage = new MemoryStorage();
+if (typeof (globalThis as { window?: unknown }).window === "undefined") {
+ Object.defineProperty(globalThis, "window", { configurable: true, value: { localStorage: storage, addEventListener: () => undefined } });
+}
+
+const lib = await import("../src/app/lib/in-app-feedback");
+const analytics = await import("../src/app/lib/analytics");
+const { FeedbackFormView, FeedbackTurnPrompt, FeedbackTurnPromptView } = await import("../src/react-app/domains/feedback/feedback");
+
+type Input = OmniRushFeedbackInput;
+
+const MARKER = "MARKER-only-in-feedback-91c2";
+
+function fakeMain(offer: { kind: "turn" | "pulse" } | null = { kind: "turn" }, result: unknown = { ok: true, sent: true, queued: false }) {
+ const offers: unknown[] = [];
+ const shown: unknown[] = [];
+ const started: unknown[] = [];
+ const submitted: Input[] = [];
+ lib.setFeedbackBridgeForTests({
+ offer: async (input) => { offers.push(input); return offer; },
+ sessionStarted: async (input) => { started.push(input); return true; },
+ shown: async (input) => { shown.push(input); return { ok: true }; },
+ submit: async (input) => { submitted.push(input); return result as never; },
+ });
+ const toasts: unknown[] = [];
+ lib.setFeedbackNotifier((r) => toasts.push(lib.resultToast(r)));
+ return { offers, shown, started, submitted, toasts };
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+function user(id: string, text: string, created = 1_000): UIMessage {
+ return { id, role: "user", parts: [{ type: "text", text }], metadata: { opencode: { created } } } as UIMessage;
+}
+function assistant(id: string, parts: unknown[], meta: Record<string, unknown> = { created: 1_100, completed: 41_000, finish: "stop" }): UIMessage {
+ return { id, role: "assistant", parts, metadata: { opencode: meta } } as unknown as UIMessage;
+}
+const toolPart = { type: "dynamic-tool", toolName: "bash", toolCallId: "c1", state: "output-available", input: { command: "ls" }, output: "a\nb" };
+const text = (t: string) => ({ type: "text", text: t, state: "done" });
+
+const TURN = { outcome: "ok" as const, toolCalls: 1, durationMs: 4000, text: "Done.", turn: 2, messageId: "a2" };
+
+afterEach(() => lib.setFeedbackBridgeForTests(null));
+
+describe("in-app feedback: how the last turn ended", () => {
+ test("a finished turn with a tool: ok, its tool count, duration and turn index", () => {
+ const messages = [user("u1", "first"), assistant("a1", [text("hi")]), user("u2", "list files", 10_000), assistant("a2", [toolPart, text("Two files: a and b.")], { created: 10_100, completed: 25_000, finish: "stop" })];
+ expect(lib.finishedTurn(messages)).toEqual({ outcome: "ok", toolCalls: 1, durationMs: 15_000, text: "Two files: a and b.", turn: 2, messageId: "a2" });
+ });
+
+ test("no answer yet, an open answer, a compaction: nothing", () => {
+ expect(lib.finishedTurn([user("u1", "x")])).toBeNull();
+ expect(lib.finishedTurn([user("u1", "x"), assistant("a1", [text("partial")], { created: 1 })])).toBeNull();
+ const compaction = { ...user("u1", "compact"), metadata: { opencode: { created: 1, compaction: true } } } as UIMessage;
+ expect(lib.finishedTurn([compaction, assistant("a1", [text("summary")])])).toBeNull();
+ expect(lib.finishedTurn([user("u1", "x"), assistant("a1", [text("summary")], { created: 1, completed: 2, finish: "stop", compaction: true })])).toBeNull();
+ });
+
+ test("an error, a gateway refusal and the Stop button are not ok", () => {
+ const failed = assistant("e1", [{ type: "text", text: "Model error", state: "done", providerMetadata: { opencode: { sessionError: { kind: "provider-error", title: "Model error", technicalDetails: "boom" } } } }]);
+ expect(lib.finishedTurn([user("u1", "x"), failed])?.outcome).toBe("error");
+ const refusal = assistant("e2", [{ type: "text", text: "OmniRush can't help with this request.", state: "done", providerMetadata: { opencode: { sessionError: { kind: "provider-error", title: "omnirush.ai: OmniRush can't help with this request.", technicalDetails: "Error type: APIError", omnirush: { code: "request_policy_refused", retry: false } } } } }]);
+ expect(lib.finishedTurn([user("u1", "x"), refusal])?.outcome).toBe("error");
+ const stopped = assistant("e3", [{ type: "text", text: "Stopped", state: "done", providerMetadata: { opencode: { sessionError: { kind: "aborted", title: "Stopped" } } } }]);
+ expect(lib.finishedTurn([user("u1", "x"), stopped])?.outcome).toBe("stopped");
+ });
+});
+
+describe("in-app feedback: after a turn", () => {
+ test("the main process says turn: the prompt shows (once reported shown) with the turn's facts", async () => {
+ const main = fakeMain();
+ const offer = await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: "gpt-6-astra", effort: "high" });
+ expect(offer).toEqual({ kind: "turn" });
+ expect(main.offers).toEqual([{ sessionId: "ses_1", outcome: "ok", toolCalls: 1, durationMs: 4000, text: "Done." }]);
+ expect(main.shown).toEqual([{ kind: "turn" }]);
+ expect(lib.useFeedbackStore.getState().prompt).toMatchObject({ sessionId: "ses_1", kind: "turn", stage: "rate", turn: 2, modelId: "gpt-6-astra", effort: "high", rating: null });
+ });
+
+ test("the main process says no: nothing shows, nothing reported", async () => {
+ const main = fakeMain(null);
+ expect(await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: { ...TURN, durationMs: null }, fallbackDurationMs: 31_000, modelId: null, effort: null })).toBeNull();
+ expect((main.offers[0] as { durationMs: number }).durationMs).toBe(31_000);
+ expect(main.shown).toEqual([]);
+ expect(lib.useFeedbackStore.getState().prompt).toBeNull();
+ });
+
+ test("thumbs down + reasons + comment: the payload input, then a thank-you", async () => {
+ const main = fakeMain();
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: "gpt-6-astra", effort: "high" });
+ lib.rateTurn("down");
+ expect(lib.useFeedbackStore.getState().prompt?.stage).toBe("down");
+ lib.toggleTurnReason("wrong");
+ lib.toggleTurnReason("broke");
+ lib.toggleTurnReason("broke");
+ lib.toggleTurnReason("slow");
+ lib.setPromptComment(`It deleted the wrong file ${MARKER}`);
+ await lib.sendPrompt();
+ expect(main.submitted).toEqual([{ kind: "turn", rating: "down", categories: ["wrong", "slow"], comment: `It deleted the wrong file ${MARKER}`, sessionId: "ses_1", turn: 2, trigger: "sampled", modelId: "gpt-6-astra", effort: "high" }]);
+ expect(main.toasts).toEqual([{ kind: "sent", title: "Thanks, sent." }]);
+ expect(lib.useFeedbackStore.getState().prompt).toBeNull();
+ });
+
+ test("thumbs up then Skip: the rating alone", async () => {
+ const main = fakeMain();
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });
+ lib.rateTurn("up");
+ lib.setPromptComment("typed but skipped");
+ await lib.sendPrompt({ skip: true });
+ expect(main.submitted[0]).toMatchObject({ kind: "turn", rating: "up", categories: [], comment: null });
+ });
+
+ test("a rating chosen and then left (next turn, typing, ×): the rating alone, sent quietly", async () => {
+ const main = fakeMain();
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });
+ lib.rateTurn("down");
+ lib.toggleTurnReason("ui");
+ lib.feedbackTurnStarted("ses_1");
+ await flush();
+ expect(main.started).toEqual([{ sessionId: "ses_1" }]);
+ expect(main.submitted[0]).toMatchObject({ rating: "down", categories: [], comment: null });
+ expect(main.toasts).toEqual([]);
+ expect(lib.useFeedbackStore.getState().prompt).toBeNull();
+ });
+
+ test("dismissed without a rating: nothing is sent", async () => {
+ const main = fakeMain();
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });
+ await lib.closePrompt();
+ await lib.sendPrompt({ skip: true });
+ expect(main.submitted).toEqual([]);
+ });
+
+ test("the pulse: a 0-10 score and why", async () => {
+ const main = fakeMain({ kind: "pulse" });
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_9", turn: TURN, fallbackDurationMs: 0, modelId: "m", effort: null });
+ expect(main.shown).toEqual([{ kind: "pulse" }]);
+ lib.rateTurn("up");
+ lib.ratePulse(11);
+ lib.ratePulse(9);
+ lib.setPromptComment("fast and handy");
+ await lib.sendPrompt();
+ expect(main.submitted).toEqual([{ kind: "pulse", rating: 9, categories: [], comment: "fast and handy", sessionId: "ses_9", turn: 2, trigger: "pulse", modelId: "m", effort: null }]);
+ });
+
+ test("queued (offline / the server has none yet): the saved wording, never an error", async () => {
+ const main = fakeMain({ kind: "turn" }, { ok: true, sent: false, queued: true, reason: "unavailable" });
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });
+ lib.rateTurn("up");
+ await lib.sendPrompt();
+ expect(main.toasts).toEqual([{ kind: "queued", title: "Thanks, saved for later." }]);
+ });
+});
+
+describe("in-app feedback: Send feedback", () => {
+ test("Bug includes the open session by default; other categories do not; the person's choice wins", async () => {
+ const main = fakeMain();
+ lib.openFeedbackDialog({ trigger: "menu", sessionId: "ses_open" });
+ expect(lib.includeSessionChecked(lib.useFeedbackStore.getState().dialog)).toBe(true);
+ lib.setDialogCategory("idea");
+ expect(lib.includeSessionChecked(lib.useFeedbackStore.getState().dialog)).toBe(false);
+ lib.setDialogIncludeSession(true);
+ lib.setDialogCategory("praise");
+ expect(lib.includeSessionChecked(lib.useFeedbackStore.getState().dialog)).toBe(true);
+ lib.setDialogCategory("bug");
+ lib.setDialogIncludeSession(false);
+ lib.setDialogText(" ");
+ expect(await lib.sendFeedbackDialog()).toBeNull();
+ lib.setDialogText("The sidebar flickers\nwhen I resize");
+ await lib.sendFeedbackDialog();
+ expect(main.submitted).toEqual([{ kind: "general", rating: null, categories: ["bug"], comment: "The sidebar flickers\nwhen I resize", sessionId: null, turn: null, trigger: "menu", modelId: null, effort: null }]);
+ expect(lib.useFeedbackStore.getState().dialog.open).toBe(false);
+ });
+
+ test("from the palette, with the session", async () => {
+ const main = fakeMain();
+ lib.openFeedbackDialog({ trigger: "command", sessionId: "ses_open" });
+ lib.setDialogText("crash on start");
+ await lib.sendFeedbackDialog();
+ expect(main.submitted[0]).toMatchObject({ kind: "general", categories: ["bug"], sessionId: "ses_open", trigger: "command" });
+ expect(main.toasts).toEqual([{ kind: "sent", title: "Thanks, sent." }]);
+ });
+
+ test("a refused input keeps the dialog open", async () => {
+ fakeMain(null, { ok: false, error: "comment" });
+ lib.openFeedbackDialog({ trigger: "menu" });
+ lib.setDialogText("x");
+ await lib.sendFeedbackDialog();
+ expect(lib.useFeedbackStore.getState().dialog).toMatchObject({ open: true, sending: false });
+ });
+});
+
+describe("in-app feedback: analytics", () => {
+ const realFetch = globalThis.fetch;
+ let sent: Array<{ event: string; properties: Record<string, unknown> }> = [];
+ beforeEach(() => {
+ sent = [];
+ analytics.disposeAnalytics();
+ analytics.configureAnalyticsForTests({ key: "phc_test", host: "http://127.0.0.1:9/", appVersion: "3.6.1" });
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ sent.push(...JSON.parse(String(init?.body)).batch);
+ return new Response("{}");
+ }) as unknown as typeof fetch;
+ });
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ test("the two events pass on with labels only; anything else is dropped", async () => {
+ expect(lib.handleFeedbackEvent({ name: "feedback_prompt_shown", properties: { kind: "turn", trigger: "sampled" } })).toBe(true);
+ expect(lib.handleFeedbackEvent({ name: "feedback_submitted", properties: { kind: "turn", rating_bucket: "down", categories: "wrong+slow", has_comment: true, trigger: "sampled", comment: MARKER } })).toBe(true);
+ expect(lib.handleFeedbackEvent({ name: "app_opened", properties: {} })).toBe(false);
+ await analytics.flushAnalytics();
+ expect(sent.map((e) => e.event)).toEqual(["feedback_prompt_shown", "feedback_submitted"]);
+ expect(sent[1].properties).toMatchObject({ kind: "turn", rating_bucket: "down", categories: "wrong+slow", has_comment: true, trigger: "sampled" });
+ expect(JSON.stringify(sent)).not.toContain(MARKER);
+ });
+});
+
+describe("in-app feedback: the views", () => {
+ const base = { sessionId: "ses_1", kind: "turn" as const, stage: "rate" as const, turn: 2, messageId: "a2", modelId: null, effort: null, rating: null, reasons: [], comment: "" };
+ const noop = () => undefined;
+ const handlers = { onRate: noop, onPulse: noop, onToggleReason: noop, onComment: noop, onSend: noop, onSkip: noop, onDismiss: noop };
+
+ test("the rating row: muted label, two thumbs, ×, a gentle fade-in, no follow-up yet", () => {
+ const html = renderToStaticMarkup(<FeedbackTurnPromptView prompt={base} {...handlers} />);
+ expect(html).toContain("How was this?");
+ expect(html).toContain('data-testid="feedback-up"');
+ expect(html).toContain('data-testid="feedback-down"');
+ expect(html).toContain('data-testid="feedback-dismiss"');
+ expect(html).toContain("fade-in-0");
+ expect(html).toContain("duration-200");
+ expect(html).not.toContain("feedback-reason-");
+ expect(html).not.toContain("feedback-comment");
+ expect(html).not.toContain("feedback-note");
+ expect(html).not.toContain('role="dialog"');
+ });
+
+ test("thumbs down: the six reasons (chosen ones pressed), a one-line comment, Send / Skip", () => {
+ const html = renderToStaticMarkup(<FeedbackTurnPromptView prompt={{ ...base, stage: "down", rating: "down", reasons: ["slow"] }} {...handlers} />);
+ for (const label of ["Wrong", "Too slow", "Didn&#x27;t follow instructions", "Broke something", "UI problem", "Other"]) expect(html).toContain(label);
+ expect(html).toMatch(/aria-pressed="true"[^>]*data-testid="feedback-reason-slow"/);
+ expect(html).toMatch(/aria-pressed="false"[^>]*data-testid="feedback-reason-wrong"/);
+ expect(html).toContain("Anything to add? (optional)");
+ expect(html).toContain("Sent to the OmniRush team with this chat&#x27;s id. Not part of the chat.");
+ expect(html).toContain('data-testid="feedback-send"');
+ expect(html).toContain('data-testid="feedback-skip"');
+ });
+
+ test("thumbs up: What worked?", () => {
+ const html = renderToStaticMarkup(<FeedbackTurnPromptView prompt={{ ...base, stage: "up", rating: "up" }} {...handlers} />);
+ expect(html).toContain("What worked? (optional)");
+ expect(html).toContain('data-testid="feedback-note"');
+ expect(html).not.toContain("feedback-reason-");
+ });
+
+ test("the pulse: the question, 0 to 10, why after a score", () => {
+ const before = renderToStaticMarkup(<FeedbackTurnPromptView prompt={{ ...base, kind: "pulse", stage: "pulse" }} {...handlers} />);
+ expect(before).toContain("How likely are you to recommend OmniRush to a friend?");
+ for (let i = 0; i <= 10; i++) expect(before).toContain(`data-testid="feedback-pulse-${i}"`);
+ expect(before).not.toContain("Why? (optional)");
+ const after = renderToStaticMarkup(<FeedbackTurnPromptView prompt={{ ...base, kind: "pulse", stage: "pulse", rating: 8 }} {...handlers} />);
+ expect(after).toContain("Why? (optional)");
+ expect(after).toMatch(/aria-checked="true"[^>]*data-testid="feedback-pulse-8"/);
+ });
+
+ test("the watcher draws nothing without a prompt, or while a turn runs", () => {
+ fakeMain();
+ expect(renderToStaticMarkup(<FeedbackTurnPrompt sessionId="ses_1" messages={[]} turnRunning={false} draft="" modelId={null} effort={null} />)).toBe("");
+ lib.useFeedbackStore.setState({ prompt: base });
+ expect(renderToStaticMarkup(<FeedbackTurnPrompt sessionId="ses_1" messages={[]} turnRunning draft="" modelId={null} effort={null} />)).toBe("");
+ expect(renderToStaticMarkup(<FeedbackTurnPrompt sessionId="ses_other" messages={[]} turnRunning={false} draft="" modelId={null} effort={null} />)).toBe("");
+ });
+
+ test("the dialog form: categories, text, the session box only with a session, Send off while empty", () => {
+ const dialog = { open: true, trigger: "menu" as const, sessionId: "ses_open", category: "bug" as const, text: "", includeSession: null, sending: false };
+ const props = { onCategory: noop, onText: noop, onIncludeSession: noop, onSend: noop, onCancel: noop };
+ const html = renderToStaticMarkup(<FeedbackFormView dialog={dialog} {...props} />);
+ for (const c of ["bug", "idea", "praise", "other"]) expect(html).toContain(`data-testid="feedback-category-${c}"`);
+ expect(html).toContain("Include this session&#x27;s id");
+ expect(html).toMatch(/data-testid="feedback-dialog-send"[^>]*disabled=""|disabled=""[^>]*data-testid="feedback-dialog-send"/);
+ const noSession = renderToStaticMarkup(<FeedbackFormView dialog={{ ...dialog, sessionId: null, text: "x" }} {...props} />);
+ expect(noSession).not.toContain("Include this session");
+ expect(noSession).not.toMatch(/data-testid="feedback-dialog-send"[^>]*disabled=""/);
+ });
+});
diff --git a/apps/desktop/electron/app-menu.mjs b/apps/desktop/electron/app-menu.mjs
index 08957073..f3b78ad6 100644
--- a/apps/desktop/electron/app-menu.mjs
+++ b/apps/desktop/electron/app-menu.mjs
@@ -10,6 +10,7 @@ const NATIVE_MENU_OPEN_SETTINGS_EVENT = "omnirush:native-menu:open-settings";
const NATIVE_MENU_TOGGLE_SIDEBAR_EVENT = "omnirush:native-menu:toggle-sidebar";
const NATIVE_MENU_CHECK_UPDATES_EVENT = "omnirush:native-menu:check-updates";
const NATIVE_MENU_ZOOM_EVENT = "omnirush:native-menu:zoom";
+const NATIVE_MENU_SEND_FEEDBACK_EVENT = "omnirush:native-menu:send-feedback";
export function createApplicationMenu({ appName, docsUrl, getWindow }) {
let applicationMenuVisible = process.platform === "darwin";
@@ -31,6 +32,15 @@ export function createApplicationMenu({ appName, docsUrl, getWindow }) {
win.webContents.send(NATIVE_MENU_CHECK_UPDATES_EVENT);
}
+ // Help > Send Feedback…: the window opens its feedback dialog (in-app, not a web page).
+ async function sendFeedbackFromNativeMenu() {
+ const win = await getWindow();
+ if (win.isMinimized()) win.restore();
+ win.show();
+ win.focus();
+ win.webContents.send(NATIVE_MENU_SEND_FEEDBACK_EVENT);
+ }
+
async function toggleSidebarFromNativeMenu() {
const win = await getWindow();
win.webContents.send(NATIVE_MENU_TOGGLE_SIDEBAR_EVENT);
@@ -206,6 +216,12 @@ export function createApplicationMenu({ appName, docsUrl, getWindow }) {
},
{ type: "separator" },
]),
+ {
+ label: "Send Feedback…",
+ click: () => {
+ runDetachedTask("send feedback from menu", sendFeedbackFromNativeMenu);
+ },
+ },
{
label: "Docs",
click: () => {
diff --git a/apps/desktop/electron/feedback-desktop.mjs b/apps/desktop/electron/feedback-desktop.mjs
new file mode 100644
index 00000000..e38b4d38
--- /dev/null
+++ b/apps/desktop/electron/feedback-desktop.mjs
@@ -0,0 +1,185 @@
+// In-app feedback in the desktop app (the main process's side).
+//
+// The rules live in ./feedback/feedback.mjs (the same file as the CLI's,
+// PARITY.sha256 there): the server's policy, when the app may ask after a
+// turn (once per session, `max_per_day`, the sample rate, the pulse), the
+// payload, the queue in the app's data folder (feedback.json) and the
+// sending. Here: the account's authorized call, whether this run may ask on
+// its own, and what the window may ask over IPC:
+// omnirushFeedbackPolicy {} → the policy in force
+// omnirushFeedbackOffer {sessionId, outcome, toolCalls, durationMs, text?}
+// → null | { kind: "turn" | "pulse" }
+// omnirushFeedbackShown {kind, trigger?} → analytics only
+// omnirushFeedbackSubmit {kind, rating, categories, comment, sessionId, turn, trigger, modelId, effort}
+// → { ok, sent, queued, reason? } | { ok: false, error }
+// omnirushFeedbackStatus {} → { policy, queued, unavailable, allowed }
+//
+// The two analytics events (feedback_prompt_shown, feedback_submitted;
+// labels only, never the comment) go to the window (EVENT_CHANNEL), which
+// hands them to the app's own analytics.
+//
+// "Send feedback" always works. The app asks on its own only in an
+// interactive, released build: never with OMNIRUSH_FEEDBACK=0, in CI, or in
+// a development build (unless OMNIRUSH_FEEDBACK=1, for test rigs). Nothing
+// here touches a session's messages, the engine, the model or uploads.
+
+import path from "node:path";
+
+import { createFeedback, looksLikeRefusal, osName, STATE_FILE, TURN_OUTCOMES } from "./feedback/feedback.mjs";
+
+/** Main → window: { name, properties } of one analytics event. */
+export const EVENT_CHANNEL = "omnirush:feedback:event";
+/** Production retry/refresh interval of the queue (the shared module's default). */
+export const RETRY_EVERY_MS = 5 * 60_000;
+const OFF = new Set(["0", "false", "no", "off"]);
+const ON = new Set(["1", "true", "yes", "on"]);
+const SESSION_RE = /^[A-Za-z0-9._:-]{1,128}$/;
+
+function flag(value) {
+ return String(value ?? "").trim().toLowerCase();
+}
+
+/**
+ * Whether this run may ask on its own (after a turn, the pulse). Anytime
+ * feedback works either way.
+ * @param {{ env?: Record<string, string | undefined>, packaged?: boolean, devMode?: boolean }} [input]
+ */
+export function desktopFeedbackAllowed({ env = process.env, packaged = false, devMode = false } = {}) {
+ const value = flag(env.OMNIRUSH_FEEDBACK);
+ if (OFF.has(value)) return false;
+ if (ON.has(value)) return true;
+ const ci = flag(env.CI);
+ if (ci && !OFF.has(ci)) return false;
+ return packaged === true && devMode !== true;
+}
+
+/**
+ * The queue's retry interval: 5 minutes; an unpackaged build (test rigs)
+ * may shorten it with OMNIRUSH_FEEDBACK_RETRY_MS (at least 1 s).
+ * @param {{ env?: Record<string, string | undefined>, packaged?: boolean }} [input]
+ */
+export function desktopFeedbackRetryMs({ env = process.env, packaged = false } = {}) {
+ if (packaged) return RETRY_EVERY_MS;
+ const n = Number(env.OMNIRUSH_FEEDBACK_RETRY_MS);
+ return Number.isFinite(n) && n >= 1_000 ? Math.floor(n) : RETRY_EVERY_MS;
+}
+
+function text(value, max) {
+ return typeof value === "string" ? value.slice(0, max) : "";
+}
+
+function finite(value) {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
+}
+
+/**
+ * @param {{
+ * request: import("./feedback/feedback.mjs").FeedbackRequest,
+ * userDataPath: string,
+ * version?: string,
+ * platform?: string,
+ * env?: Record<string, string | undefined>,
+ * packaged?: boolean,
+ * devMode?: boolean,
+ * emit?: ((name: string, properties: Record<string, unknown>) => void) | null,
+ * now?: () => number,
+ * random?: () => number,
+ * log?: (level: string, message: string, data?: object) => void,
+ * }} options
+ */
+export function createDesktopFeedback({
+ request,
+ userDataPath,
+ version = "",
+ platform = process.platform,
+ env = process.env,
+ packaged = false,
+ devMode = false,
+ emit = null,
+ now = Date.now,
+ random = Math.random,
+ log = () => undefined,
+}) {
+ const allowed = desktopFeedbackAllowed({ env, packaged, devMode });
+ // (The shared module's options carry no JSDoc type of their own.)
+ const service = createFeedback(/** @type {any} */ ({
+ request,
+ stateFile: path.join(userDataPath, STATE_FILE),
+ client: "desktop",
+ version,
+ os: osName(platform),
+ allowed,
+ now,
+ random,
+ log,
+ retryEveryMs: desktopFeedbackRetryMs({ env, packaged }),
+ onEvent: (name, properties) => {
+ try {
+ emit?.(name, properties);
+ } catch {
+ /* analytics never in the way */
+ }
+ },
+ }));
+
+ return {
+ service,
+ allowed,
+ start: () => service.start(),
+ stop: () => service.stop(),
+ /** IPC omnirushFeedbackPolicy: the policy in force (off when not allowed). */
+ policy: () => service.policy(),
+ /** IPC omnirushFeedbackStatus. */
+ status: () => ({ ...service.status(), allowed }),
+ /** IPC omnirushFeedbackSessionStarted {sessionId}: the pulse counts sessions. */
+ sessionStarted(input) {
+ const sessionId = typeof input?.sessionId === "string" && SESSION_RE.test(input.sessionId) ? input.sessionId : null;
+ return sessionId ? service.sessionStarted(sessionId) : false;
+ },
+ /**
+ * IPC omnirushFeedbackOffer: after a finished turn. `text` (the answer's
+ * final text, at most 700 characters) is only read here to tell a
+ * refusal that came back as an ordinary answer; it is not kept.
+ */
+ offer(input) {
+ const sessionId = typeof input?.sessionId === "string" && SESSION_RE.test(input.sessionId) ? input.sessionId : null;
+ if (!sessionId) return null;
+ let outcome = typeof input?.outcome === "string" && TURN_OUTCOMES.includes(input.outcome) ? input.outcome : "error";
+ if (outcome === "ok" && looksLikeRefusal(text(input?.text, 700))) outcome = "refused";
+ try {
+ return service.offerAfterTurn({ sessionId, outcome, toolCalls: finite(input?.toolCalls), durationMs: finite(input?.durationMs) });
+ } catch {
+ return null;
+ }
+ },
+ /** IPC omnirushFeedbackShown {kind, trigger?}: the prompt is on screen. */
+ shown(input) {
+ const kind = input?.kind === "pulse" ? "pulse" : "turn";
+ service.shown(kind, kind === "pulse" ? "pulse" : "sampled");
+ return { ok: true };
+ },
+ /**
+ * IPC omnirushFeedbackSubmit: one feedback (always allowed). Never
+ * throws: { ok: false, error } when it cannot be sent or kept.
+ * @returns {Promise<import("@omnirush/types/desktop-ipc").OmniRushFeedbackResult>}
+ */
+ async submit(input) {
+ const value = input && typeof input === "object" ? input : {};
+ try {
+ return await /** @type {any} */ (service.submit)({
+ kind: value.kind,
+ rating: value.rating,
+ categories: Array.isArray(value.categories) ? value.categories.slice(0, 12) : [],
+ comment: text(value.comment, 4_000),
+ sessionId: value.sessionId,
+ turn: value.turn,
+ trigger: value.trigger,
+ modelId: value.modelId,
+ effort: value.effort,
+ });
+ } catch {
+ return /** @type {any} */ ({ ok: false, error: "failed" });
+ }
+ },
+ };
+}
diff --git a/apps/desktop/electron/feedback-desktop.test.mjs b/apps/desktop/electron/feedback-desktop.test.mjs
new file mode 100644
index 00000000..a066d8d7
--- /dev/null
+++ b/apps/desktop/electron/feedback-desktop.test.mjs
@@ -0,0 +1,265 @@
+// In-app feedback: the shared module (./feedback/feedback.mjs, the same file
+// in the CLI, PARITY.sha256) and the main process's side (feedback-desktop.mjs,
+// the account store's clientRequest). The CLI covers the same rules with its
+// own launcher.
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { GENERAL_CATEGORIES, PULSE_QUESTION, TURN_REASONS } from "./feedback/feedback.mjs";
+import { createDesktopFeedback, desktopFeedbackAllowed, desktopFeedbackRetryMs, EVENT_CHANNEL, RETRY_EVERY_MS } from "./feedback-desktop.mjs";
+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const T0 = Date.parse("2026-10-19T09:00:00");
+const DAY = 86_400_000;
+const ON = { enabled: true, turn_sample_rate: 1, max_per_day: 1, pulse_enabled: false, pulse_after_sessions: 5, pulse_every_days: 30 };
+const OK_TURN = { outcome: "ok", toolCalls: 1, durationMs: 2_000 };
+
+function tmp() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "feedback-desk-"));
+}
+
+/**
+ * A desktop feedback with a scripted server (the policy's answer or status,
+ * the submit's status or "offline" / "signed_out"); every call is recorded.
+ * @param {{ policy?: any, submit?: any, env?: Record<string, string>, packaged?: boolean, devMode?: boolean, userDataPath?: string, now?: () => number }} [options]
+ */
+function desktop({ policy = ON, submit = 201, env = { OMNIRUSH_FEEDBACK: "1" }, packaged = false, devMode = false, userDataPath = tmp(), now = () => T0 } = {}) {
+ const calls = [];
+ const events = [];
+ /** @type {{ policy: any, submit: any }} */
+ const server = { policy, submit };
+ const d = createDesktopFeedback({
+ request: async (p, init) => {
+ calls.push({ path: p, ...init });
+ if (p === "/client/feedback-policy") return typeof server.policy === "number" ? { status: server.policy, data: null } : { status: 200, data: server.policy };
+ if (p === "/feedback") {
+ if (server.submit === "offline") throw new Error("ECONNREFUSED");
+ if (server.submit === "signed_out") return null;
+ return { status: server.submit, data: null };
+ }
+ return { status: 404, data: null };
+ },
+ userDataPath,
+ version: "3.6.1",
+ platform: "linux",
+ env,
+ packaged,
+ devMode,
+ emit: (name, properties) => events.push({ name, properties }),
+ now,
+ random: () => 0,
+ });
+ return { d, calls, events, server, userDataPath };
+}
+
+test("parity: feedback.mjs is the CLI's file, byte for byte (PARITY.sha256)", () => {
+ const listed = fs.readFileSync(path.join(here, "feedback", "PARITY.sha256"), "utf8");
+ const hash = createHash("sha256").update(fs.readFileSync(path.join(here, "feedback", "feedback.mjs"))).digest("hex");
+ const lines = listed.split("\n").filter((line) => line && !line.startsWith("#"));
+ assert.ok(lines.length >= 1);
+ for (const line of lines) assert.equal(line.split(/\s+/)[0], hash, `PARITY.sha256 lists ${line}`);
+});
+
+test("allowed: interactive released builds only; OMNIRUSH_FEEDBACK=0 off, =1 on; CI off", () => {
+ assert.equal(desktopFeedbackAllowed({ env: {}, packaged: true }), true);
+ assert.equal(desktopFeedbackAllowed({ env: {}, packaged: false }), false, "a development build never asks on its own");
+ assert.equal(desktopFeedbackAllowed({ env: {}, packaged: true, devMode: true }), false);
+ for (const off of ["0", "false", "no", "off", " OFF "]) assert.equal(desktopFeedbackAllowed({ env: { OMNIRUSH_FEEDBACK: off }, packaged: true }), false, off);
+ assert.equal(desktopFeedbackAllowed({ env: { CI: "true" }, packaged: true }), false, "CI");
+ assert.equal(desktopFeedbackAllowed({ env: { CI: "0" }, packaged: true }), true);
+ assert.equal(desktopFeedbackAllowed({ env: { OMNIRUSH_FEEDBACK: "1" }, packaged: false }), true, "test rigs");
+});
+
+test("retry interval: 5 minutes; only an unpackaged build may shorten it", () => {
+ assert.equal(RETRY_EVERY_MS, 300_000);
+ assert.equal(desktopFeedbackRetryMs({ env: {}, packaged: true }), 300_000);
+ assert.equal(desktopFeedbackRetryMs({ env: { OMNIRUSH_FEEDBACK_RETRY_MS: "3000" }, packaged: true }), 300_000);
+ assert.equal(desktopFeedbackRetryMs({ env: { OMNIRUSH_FEEDBACK_RETRY_MS: "3000" }, packaged: false }), 3_000);
+ assert.equal(desktopFeedbackRetryMs({ env: { OMNIRUSH_FEEDBACK_RETRY_MS: "10" }, packaged: false }), 300_000);
+});
+
+test("offer: an eligible turn gets the prompt, once per session and once a day", async () => {
+ let now = T0;
+ const { d, calls } = desktop({ now: () => now });
+ await d.service.refreshPolicy({ force: true });
+ assert.equal(calls[0].path, "/client/feedback-policy");
+ assert.equal(calls[0].method, "GET");
+ assert.deepEqual(d.offer({ sessionId: "ses_a", ...OK_TURN }), { kind: "turn" });
+ assert.equal(d.offer({ sessionId: "ses_a", ...OK_TURN }), null, "once per session");
+ assert.equal(d.offer({ sessionId: "ses_b", ...OK_TURN }), null, "max_per_day 1");
+ now = T0 + DAY;
+ await d.service.refreshPolicy({ force: true });
+ assert.deepEqual(d.offer({ sessionId: "ses_b", ...OK_TURN }), { kind: "turn" }, "the next day");
+});
+
+test("offer: never after an ineligible turn (no tool and short, refusal, limit, error, stop)", async () => {
+ const { d } = desktop();
+ await d.service.refreshPolicy({ force: true });
+ assert.equal(d.offer({ sessionId: "ses_1", outcome: "ok", toolCalls: 0, durationMs: 5_000 }), null, "no tool, short");
+ assert.equal(d.offer({ sessionId: "ses_2", ...OK_TURN, text: "I'm sorry, but I can't help with that." }), null, "a refusal in words");
+ for (const outcome of ["refused", "limit", "error", "stopped", "weird"]) assert.equal(d.offer({ sessionId: `ses_${outcome}`, ...OK_TURN, outcome }), null, outcome);
+ assert.equal(d.offer({ sessionId: "bad id!", ...OK_TURN }), null, "a bad session id");
+ assert.deepEqual(d.offer({ sessionId: "ses_long", outcome: "ok", toolCalls: 0, durationMs: 31_000 }), { kind: "turn" }, "no tool but 30 s+");
+});
+
+test("offer: disabled, 404 or unreachable policy, OMNIRUSH_FEEDBACK=0 or a dev build: never", async () => {
+ for (const [label, opts] of /** @type {Array<[string, any]>} */ ([
+ ["disabled", { policy: { ...ON, enabled: false } }],
+ ["404", { policy: 404 }],
+ ["500", { policy: 500 }],
+ ["off switch", { env: { OMNIRUSH_FEEDBACK: "0" } }],
+ ["dev build", { env: {}, packaged: false }],
+ ])) {
+ const { d, calls } = desktop(opts);
+ await d.service.refreshPolicy({ force: true });
+ assert.equal(d.offer({ sessionId: "ses_x", ...OK_TURN }), null, label);
+ assert.equal(d.status().policy.enabled, false, label);
+ if (label === "off switch" || label === "dev build") assert.equal(calls.length, 0, `${label}: the server is not asked`);
+ }
+});
+
+test("pulse: after pulse_after_sessions sessions, instead of the turn prompt", async () => {
+ const { d } = desktop({ policy: { ...ON, pulse_enabled: true, pulse_after_sessions: 2 } });
+ await d.service.refreshPolicy({ force: true });
+ assert.equal(d.sessionStarted({ sessionId: "ses_p1" }), true);
+ assert.equal(d.sessionStarted({ sessionId: "ses_p1" }), false, "counted once");
+ assert.deepEqual(d.offer({ sessionId: "ses_p2", ...OK_TURN }), { kind: "pulse" });
+});
+
+test("shown and submitted: analytics labels only, never the comment", async () => {
+ const { d, events, calls } = desktop();
+ d.shown({ kind: "turn" });
+ d.shown({ kind: "pulse" });
+ const marker = "MARKER-secret-comment-7f3a";
+ const result = await d.submit({ kind: "turn", rating: "down", categories: ["wrong", "slow", "bogus"], comment: marker, sessionId: "ses_abc", turn: 3, trigger: "sampled", modelId: "gpt-6-astra", effort: "high" });
+ assert.deepEqual(result, { ok: true, sent: true, queued: false });
+ assert.deepEqual(events[0], { name: "feedback_prompt_shown", properties: { kind: "turn", trigger: "sampled" } });
+ assert.deepEqual(events[1], { name: "feedback_prompt_shown", properties: { kind: "pulse", trigger: "pulse" } });
+ assert.deepEqual(events[2], { name: "feedback_submitted", properties: { kind: "turn", rating_bucket: "down", categories: "wrong+slow", has_comment: true, trigger: "sampled" } });
+ assert.ok(!JSON.stringify(events).includes(marker), "no comment text in analytics");
+ const post = calls.find((c) => c.path === "/feedback");
+ assert.equal(post.method, "POST");
+ assert.deepEqual(post.body, {
+ kind: "turn", rating: "down", categories: ["wrong", "slow"], comment: marker, session_id: "ses_abc", turn: 3,
+ trigger: "sampled", client: "desktop", app_version: "3.6.1", os: "linux", model_id: "gpt-6-astra", effort: "high",
+ });
+});
+
+test("submit: anytime feedback works whatever the policy, even switched off", async () => {
+ const { d, calls } = desktop({ policy: { ...ON, enabled: false }, env: { OMNIRUSH_FEEDBACK: "0" } });
+ const result = await d.submit({ kind: "general", rating: null, categories: ["bug"], comment: "The sidebar\nflickers", sessionId: "ses_open", turn: null, trigger: "menu" });
+ assert.deepEqual(result, { ok: true, sent: true, queued: false });
+ assert.deepEqual(calls.at(-1).body, { kind: "general", rating: null, categories: ["bug"], comment: "The sidebar\nflickers", session_id: "ses_open", turn: null, trigger: "menu", client: "desktop", app_version: "3.6.1", os: "linux", model_id: null, effort: null });
+ assert.deepEqual(await d.submit({ kind: "general", categories: ["idea"], comment: " ", trigger: "command" }), { ok: false, error: "comment" });
+});
+
+test("submit: a 404 queues it in feedback.json and stops the prompts; a later 201 drains the queue", async () => {
+ let now = T0;
+ const { d, server, userDataPath } = desktop({ submit: 404, now: () => now });
+ await d.service.refreshPolicy({ force: true });
+ const result = await d.submit({ kind: "turn", rating: "up", comment: "nice", sessionId: "ses_q", turn: 1, trigger: "sampled" });
+ assert.deepEqual(result, { ok: true, sent: false, queued: true, reason: "unavailable" });
+ const saved = JSON.parse(fs.readFileSync(path.join(userDataPath, "feedback.json"), "utf8"));
+ assert.equal(saved.spool.length, 1);
+ assert.ok(saved.absent_at > 0);
+ assert.equal(d.status().unavailable, true);
+ assert.equal(d.offer({ sessionId: "ses_new", ...OK_TURN }), null, "no more prompts while the server has none");
+ server.submit = 201;
+ now += 10 * 60_000;
+ const flushed = await d.service.flush();
+ assert.equal(flushed.sent.length, 1);
+ assert.equal(d.status().queued, 0);
+ assert.equal(d.status().unavailable, false);
+ assert.deepEqual(d.offer({ sessionId: "ses_new", ...OK_TURN }), { kind: "turn" }, "asking again once a send went through");
+});
+
+test("submit: offline, signed out and 429 are kept for later with their reason", async () => {
+ for (const [submit, reason] of [["offline", "offline"], ["signed_out", "signed_out"], [429, "rate_limited"]]) {
+ const { d } = desktop({ submit: /** @type {any} */ (submit) });
+ const r = await d.submit({ kind: "pulse", rating: 9, comment: null, trigger: "pulse" });
+ assert.deepEqual(r, { ok: true, sent: false, queued: true, reason }, String(submit));
+ assert.equal(d.status().queued, 1);
+ }
+});
+
+test("the state lives in the app's data folder (feedback.json), not in any workspace", async () => {
+ const { d, userDataPath } = desktop();
+ await d.service.refreshPolicy({ force: true });
+ d.offer({ sessionId: "ses_f", ...OK_TURN });
+ const saved = JSON.parse(fs.readFileSync(path.join(userDataPath, "feedback.json"), "utf8"));
+ assert.deepEqual(saved.asked_sessions, ["ses_f"]);
+});
+
+test("wiring: main.mjs handlers, the preload's event channel, the bridge and the renderer's labels", () => {
+ const main = fs.readFileSync(path.join(here, "main.mjs"), "utf8");
+ for (const name of ["omnirushFeedbackPolicy", "omnirushFeedbackStatus", "omnirushFeedbackSessionStarted", "omnirushFeedbackOffer", "omnirushFeedbackShown", "omnirushFeedbackSubmit"]) {
+ assert.match(main, new RegExp(`^ "${name}": async \\(event`, "m"), name);
+ }
+ assert.match(main, /omnirushAccountStore\.clientRequest\(pathAndQuery, init\)/);
+ assert.match(main, /desktopFeedback\.start\(\)/);
+ assert.match(main, /desktopFeedback\.stop\(\)/);
+ const preload = fs.readFileSync(path.join(here, "preload.mjs"), "utf8");
+ assert.ok(preload.includes(`ipcRenderer.on("${EVENT_CHANNEL}"`), "the preload passes the analytics events on");
+ const renderer = fs.readFileSync(path.join(here, "..", "..", "app", "src", "app", "lib", "in-app-feedback.ts"), "utf8");
+ for (const item of [...TURN_REASONS, ...GENERAL_CATEGORIES]) assert.ok(renderer.includes(`{ id: "${item.id}", label: "${item.label}" }`), `${item.id}: ${item.label}`);
+ assert.ok(renderer.includes(JSON.stringify(PULSE_QUESTION)));
+ assert.ok(renderer.includes(`"${EVENT_CHANNEL}"`));
+});
+
+test("account store: clientRequest posts feedback to the account server with the device credential (renewed on a 401)", async () => {
+ const seen = [];
+ const fetchImpl = async (url, init = {}) => {
+ const u = new URL(String(url));
+ const headers = new Headers(init.headers);
+ seen.push({ method: init.method ?? "GET", path: `${u.pathname}${u.search}`, auth: headers.get("authorization"), type: headers.get("content-type"), body: init.body ?? null, signal: Boolean(init.signal) });
+ if (u.pathname.endsWith("/feedback") && headers.get("authorization") === "Bearer access-1") return new Response("", { status: 401 });
+ if (u.pathname.includes("/device/token") || u.pathname.includes("/refresh")) {
+ return new Response(JSON.stringify({ access_token: "access-2", refresh_token: "refresh-2", expires_in: 3600 }), { status: 200, headers: { "content-type": "application/json" } });
+ }
+ if (u.pathname.endsWith("/feedback")) return new Response(JSON.stringify({ ok: true }), { status: 201, headers: { "content-type": "application/json" } });
+ return new Response(JSON.stringify(ON), { status: 200, headers: { "content-type": "application/json" } });
+ };
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "omnirush-feedback-"));
+ const store = createDesktopOmniRushAccountStore({
+ filePath: path.join(directory, "account.bin"),
+ loadSafeStorage: () => ({
+ isAsyncEncryptionAvailable: async () => true,
+ getSelectedStorageBackend: () => "keychain",
+ encryptStringAsync: async (value) => Buffer.from(value, "utf8"),
+ decryptStringAsync: async (value) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),
+ }),
+ platform: /** @type {NodeJS.Platform} */ ("linux"),
+ env: { OMNIRUSH_DEV_MODE: "1" },
+ sleep: async () => undefined,
+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },
+ clientVersion: "3.6.1",
+ fetchImpl,
+ });
+ const userDataPath = tmp();
+ let now = T0;
+ const d = createDesktopFeedback({ request: (p, init) => store.clientRequest(p, init), userDataPath, version: "3.6.1", platform: "darwin", env: { OMNIRUSH_FEEDBACK: "1" }, now: () => now });
+ const signedOut = await d.submit({ kind: "general", categories: ["idea"], comment: "dark mode for the sidebar", trigger: "command" });
+ assert.deepEqual(signedOut, { ok: true, sent: false, queued: true, reason: "signed_out" });
+ assert.equal(seen.length, 0, "signed out: nothing asked");
+ await store.save({ gatewayUrl: "http://localhost:8090/omnirush/v1", accessToken: "access-1", refreshToken: "refresh-1" });
+ const policy = await d.service.refreshPolicy({ force: true });
+ assert.equal(policy.enabled, true);
+ assert.equal(seen[0].path, "/omnirush/client/feedback-policy");
+ const sent = await d.submit({ kind: "turn", rating: "up", comment: null, sessionId: "ses_1", turn: 2, trigger: "sampled" });
+ assert.deepEqual(sent, { ok: true, sent: true, queued: false });
+ const posts = seen.filter((s) => s.path === "/omnirush/feedback");
+ assert.equal(posts[0].auth, "Bearer access-1");
+ assert.equal(posts.at(-1).auth, "Bearer access-2", "renewed once after a 401");
+ assert.equal(posts.at(-1).type, "application/json");
+ assert.equal(JSON.parse(posts.at(-1).body).os, "mac");
+ assert.ok(seen.every((s) => s.signal), "always with a timeout");
+ now += 2 * 60_000;
+ await d.service.flush();
+ assert.equal(d.status().queued, 0, "the signed-out one went too, at its retry");
+});
diff --git a/apps/desktop/electron/feedback/PARITY.sha256 b/apps/desktop/electron/feedback/PARITY.sha256
new file mode 100644
index 00000000..95126e4a
--- /dev/null
+++ b/apps/desktop/electron/feedback/PARITY.sha256
@@ -0,0 +1,3 @@
+# In-app feedback: the same file in omnirush-cli (assets/extensions/omnirush/feedback/)
+# and omnirush-gui (apps/desktop/electron/feedback/). A change to one must be ported to the other and this list updated in both.
+667c049238433b39be32d54796ae78b585e9478660521ef9ec734dc9c4a38e88 feedback.mjs
diff --git a/apps/desktop/electron/feedback/feedback.mjs b/apps/desktop/electron/feedback/feedback.mjs
new file mode 100644
index 00000000..caa04c80
--- /dev/null
+++ b/apps/desktop/electron/feedback/feedback.mjs
@@ -0,0 +1,657 @@
+// In-app feedback: the rules both apps share. The same file ships in
+// omnirush-cli (assets/extensions/omnirush/feedback/) and omnirush-gui
+// (apps/desktop/electron/feedback/); both list it in PARITY.sha256 there.
+//
+// Three ways in:
+// - after a turn (sampled): one quiet "How was this?" after a finished,
+// eligible turn. Eligible = it finished normally (not a refusal, a spent
+// allowance or an error) and ran at least one tool or 30 s. At most once
+// per session and `max_per_day` per local day, on `turn_sample_rate` of
+// the eligible turns;
+// - the pulse (0-10): instead of the after-turn prompt, once the app saw
+// `pulse_after_sessions` sessions, then at most every `pulse_every_days`;
+// - anytime (the person asks: /feedback, "Send feedback"): always
+// available, whatever the policy says.
+//
+// The server decides whether the app asks at all (GET
+// /client/feedback-policy). Anything but a usable answer with `enabled: true`
+// (a 404, an error, a 2 s timeout, a malformed answer, a cached answer older
+// than a day) means the app never asks on its own. The answer is cached in
+// the app's data folder and asked again after an hour; start-up never waits
+// for it.
+//
+// Sending: POST /feedback with the fields of the contract and nothing else.
+// What is sent is queued first in the same file and sent from there (a small
+// spool: 50 entries, each dropped after 7 days), so offline, signed out, a 429
+// or a 5xx keep it for later. A 404 (the server has no feedback yet) keeps it
+// too and the app stops asking on its own until a queued send goes through.
+// A 2xx or a 4xx that is final (400, 413, 422) removes it.
+//
+// Nothing here touches sessions, prompts, the model, files or uploads, and
+// the comment never goes to analytics (analyticsProperties). Node builtins
+// only; the transport (`request`) is the app's own authorized call.
+
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+export const POLICY_PATH = "/client/feedback-policy";
+export const SUBMIT_PATH = "/feedback";
+export const STATE_FILE = "feedback.json";
+export const KINDS = Object.freeze(["turn", "general", "pulse"]);
+export const TRIGGERS = Object.freeze(["sampled", "command", "menu", "pulse"]);
+export const CLIENTS = Object.freeze(["cli", "desktop", "web"]);
+/** After a 👎: what went wrong (the server's category ids). */
+export const TURN_REASONS = Object.freeze([
+ Object.freeze({ id: "wrong", label: "Wrong" }),
+ Object.freeze({ id: "slow", label: "Too slow" }),
+ Object.freeze({ id: "instructions", label: "Didn't follow instructions" }),
+ Object.freeze({ id: "broke", label: "Broke something" }),
+ Object.freeze({ id: "ui", label: "UI problem" }),
+ Object.freeze({ id: "other", label: "Other" }),
+]);
+/** Anytime feedback: its category. */
+export const GENERAL_CATEGORIES = Object.freeze([
+ Object.freeze({ id: "bug", label: "Bug" }),
+ Object.freeze({ id: "idea", label: "Idea" }),
+ Object.freeze({ id: "praise", label: "Praise" }),
+ Object.freeze({ id: "other", label: "Other" }),
+]);
+export const CATEGORY_IDS = Object.freeze(["wrong", "slow", "instructions", "broke", "ui", "other", "bug", "idea", "praise"]);
+export const COMMENT_MAX = 1_000;
+export const PULSE_QUESTION = "How likely are you to recommend OmniRush to a friend?";
+export const DEFAULT_POLICY = Object.freeze({
+ enabled: false,
+ turnSampleRate: 0.125,
+ maxPerDay: 1,
+ pulseEnabled: false,
+ pulseAfterSessions: 5,
+ pulseEveryDays: 30,
+});
+/** An eligible turn ran at least this long, or used a tool. */
+export const ELIGIBLE_MIN_MS = 30_000;
+export const FETCH_TIMEOUT_MS = 2_000;
+export const SUBMIT_TIMEOUT_MS = 5_000;
+export const POLICY_REFRESH_MS = 3_600_000;
+/** A cached policy older than this (no fresh one since) means off. */
+export const POLICY_MAX_AGE_MS = 24 * 3_600_000;
+export const SPOOL_MAX = 50;
+export const SPOOL_MAX_AGE_MS = 7 * 86_400_000;
+/** First retry after a failed send (or the retry interval, if shorter), doubled per try up to RETRY_MAX_MS. */
+export const RETRY_MIN_MS = 60_000;
+export const RETRY_MAX_MS = 6 * 3_600_000;
+/** After a 429: the next try. After a 404: at most this long too. */
+export const RATE_LIMIT_RETRY_MS = 3_600_000;
+/** While one send is out, the entry is not due for anyone else (another window or terminal). */
+export const IN_FLIGHT_MS = SUBMIT_TIMEOUT_MS + 15_000;
+/** The state file's lock: waited for this long at most, taken over when older than LOCK_STALE_MS. */
+export const LOCK_WAIT_MS = 300;
+export const LOCK_STALE_MS = 3_000;
+/** Sessions remembered (once-per-session, the pulse's count), the newest. */
+export const MAX_SESSIONS = 500;
+const DAY_MS = 86_400_000;
+const STATE_VERSION = 1;
+const SESSION_RE = /^[A-Za-z0-9._:-]{1,128}$/;
+const LABEL_RE = /^[A-Za-z0-9._:/@+-]{1,80}$/;
+
+// --- policy -----------------------------------------------------------------
+
+function num(value) {
+ if (typeof value === "number") return value;
+ if (typeof value === "string" && value.trim()) return Number(value);
+ return NaN;
+}
+
+function intIn(value, min, max, fallback) {
+ const n = num(value);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, Math.floor(n)));
+}
+
+/**
+ * The server's policy, checked and clamped, or null when it is not an answer.
+ * Off unless `enabled` is exactly true; the pulse off unless `pulse_enabled`
+ * is exactly true.
+ */
+export function parsePolicy(body) {
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
+ const rate = num(body.turn_sample_rate);
+ return {
+ enabled: body.enabled === true,
+ turnSampleRate: Number.isFinite(rate) ? Math.min(1, Math.max(0, rate)) : DEFAULT_POLICY.turnSampleRate,
+ maxPerDay: intIn(body.max_per_day, 0, 10, DEFAULT_POLICY.maxPerDay),
+ pulseEnabled: body.pulse_enabled === true,
+ pulseAfterSessions: intIn(body.pulse_after_sessions, 1, 1_000, DEFAULT_POLICY.pulseAfterSessions),
+ pulseEveryDays: intIn(body.pulse_every_days, 1, 365, DEFAULT_POLICY.pulseEveryDays),
+ };
+}
+
+// --- turns ------------------------------------------------------------------
+
+/** Refusal / limit / error outcomes never get the after-turn prompt. */
+export const TURN_OUTCOMES = Object.freeze(["ok", "refused", "limit", "error", "stopped"]);
+
+/**
+ * Whether a finished turn may get the after-turn prompt: it finished
+ * normally (`outcome` "ok") and used at least one tool or ran 30 s.
+ */
+export function turnEligible({ outcome, toolCalls = 0, durationMs = 0 } = {}) {
+ if (outcome !== "ok") return false;
+ return (Number.isFinite(toolCalls) && toolCalls >= 1) || (Number.isFinite(durationMs) && durationMs >= ELIGIBLE_MIN_MS);
+}
+
+const REFUSAL_START = /^\s*(?:i['’]m sorry|i am sorry|sorry,? (?:but )?i can(?:no|['’])t|i can(?:no|['’])t (?:help|assist|do that|comply)|i won['’]t be able|i['’]m (?:not able|unable) to (?:help|assist))/i;
+
+/** A short answer that opens like a refusal ("I'm sorry, but I can't…"). */
+export function looksLikeRefusal(text) {
+ if (typeof text !== "string") return false;
+ const trimmed = text.trim();
+ return trimmed.length > 0 && trimmed.length <= 600 && REFUSAL_START.test(trimmed);
+}
+
+// --- payload ----------------------------------------------------------------
+
+// Control characters (except newline and tab in anytime feedback), bidi
+// overrides and zero-width marks never leave the app.
+// eslint-disable-next-line no-control-regex
+const UNSAFE_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f​-‏‪-‮⁠-⁩]/g;
+
+/** The comment as sent: trimmed, at most COMMENT_MAX characters; one line unless `multiline`; null when empty. */
+export function cleanComment(value, { multiline = false } = {}) {
+ if (typeof value !== "string") return null;
+ let text = value.replace(/\r\n?/g, "\n").replace(UNSAFE_CHARS, " ");
+ text = multiline ? text.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n") : text.replace(/\s+/g, " ");
+ text = text.trim();
+ if (!text) return null;
+ const chars = Array.from(text);
+ return chars.length <= COMMENT_MAX ? text : chars.slice(0, COMMENT_MAX).join("").trimEnd();
+}
+
+function label(value) {
+ return typeof value === "string" && LABEL_RE.test(value.trim()) ? value.trim() : null;
+}
+
+/** "0-10 pulse" bucket: promoter (9-10), passive (7-8), detractor (0-6). */
+export function npsBucket(score) {
+ if (!Number.isInteger(score) || score < 0 || score > 10) return null;
+ return score >= 9 ? "promoter" : score >= 7 ? "passive" : "detractor";
+}
+
+/**
+ * The POST body of one feedback, or { error } when it cannot be sent. Input
+ * (camelCase): kind, rating, categories, comment, sessionId, turn, trigger,
+ * modelId, effort; `ctx`: client, appVersion, os.
+ */
+export function buildPayload(input = {}, ctx = {}) {
+ const kind = KINDS.includes(input.kind) ? input.kind : null;
+ if (!kind) return { error: "kind" };
+ let rating = null;
+ if (kind === "turn") {
+ if (input.rating !== "up" && input.rating !== "down") return { error: "rating" };
+ rating = input.rating;
+ } else if (kind === "pulse") {
+ if (!Number.isInteger(input.rating) || input.rating < 0 || input.rating > 10) return { error: "rating" };
+ rating = input.rating;
+ }
+ const allowed = kind === "turn" ? (rating === "down" ? TURN_REASONS.map((r) => r.id) : []) : kind === "general" ? GENERAL_CATEGORIES.map((c) => c.id) : [];
+ const categories = [];
+ for (const id of Array.isArray(input.categories) ? input.categories : []) {
+ if (allowed.includes(id) && !categories.includes(id)) categories.push(id);
+ }
+ const comment = cleanComment(input.comment, { multiline: kind === "general" });
+ if (kind === "general" && !comment) return { error: "comment" };
+ const trigger = TRIGGERS.includes(input.trigger) ? input.trigger : kind === "turn" ? "sampled" : kind === "pulse" ? "pulse" : "command";
+ const sessionId = typeof input.sessionId === "string" && SESSION_RE.test(input.sessionId) ? input.sessionId : null;
+ const turn = Number.isInteger(input.turn) && input.turn >= 1 && input.turn <= 100_000 ? input.turn : null;
+ const client = CLIENTS.includes(ctx.client) ? ctx.client : "cli";
+ return {
+ payload: {
+ kind,
+ rating,
+ categories,
+ comment,
+ session_id: sessionId,
+ turn: sessionId ? turn : null,
+ trigger,
+ client,
+ app_version: label(ctx.appVersion) ?? "0",
+ os: ["win", "mac", "linux"].includes(ctx.os) ? ctx.os : osName(),
+ model_id: label(input.modelId),
+ effort: label(input.effort),
+ },
+ };
+}
+
+/**
+ * The analytics properties of a sent feedback: labels only, never the
+ * comment (only whether there was one).
+ */
+export function analyticsProperties(payload) {
+ const bucket = payload?.kind === "pulse" ? npsBucket(payload.rating) : payload?.rating === "up" || payload?.rating === "down" ? payload.rating : null;
+ const categories = Array.isArray(payload?.categories) ? payload.categories.filter((c) => CATEGORY_IDS.includes(c)) : [];
+ return {
+ kind: KINDS.includes(payload?.kind) ? payload.kind : "general",
+ rating_bucket: bucket,
+ categories: categories.length ? categories.join("+") : null,
+ has_comment: typeof payload?.comment === "string" && payload.comment.length > 0,
+ trigger: TRIGGERS.includes(payload?.trigger) ? payload.trigger : null,
+ };
+}
+
+// --- state ------------------------------------------------------------------
+
+/**
+ * The `os` the server sees: win, mac or linux.
+ * @param {string} [platform]
+ */
+export function osName(platform = process.platform) {
+ if (platform === "win32") return "win";
+ if (platform === "darwin") return "mac";
+ return "linux";
+}
+
+/** The local calendar day of `ms` (YYYY-MM-DD). */
+export function localDay(ms) {
+ const d = new Date(ms);
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+}
+
+export function emptyState() {
+ return {
+ v: STATE_VERSION,
+ policy: null,
+ policy_at: 0,
+ /** The send endpoint answered 404 at this time (0: not seen). */
+ absent_at: 0,
+ /** Prompts shown on `day` (after-turn and pulse together). */
+ asked: { day: "", count: 0 },
+ /** Sessions that got a prompt (once per session). */
+ asked_sessions: [],
+ /** Sessions seen (the pulse's count) and how many in total. */
+ sessions: [],
+ session_count: 0,
+ pulse_at: 0,
+ spool: [],
+ };
+}
+
+function strings(value, max) {
+ return Array.isArray(value) ? value.filter((s) => typeof s === "string" && SESSION_RE.test(s)).slice(-max) : [];
+}
+
+function validEntry(e) {
+ return Boolean(e) && typeof e === "object" && typeof e.id === "string" && Number.isFinite(e.at) && e.payload && typeof e.payload === "object" && KINDS.includes(e.payload.kind);
+}
+
+export function readState(file) {
+ let data = null;
+ try {
+ data = JSON.parse(fs.readFileSync(file, "utf8"));
+ } catch {
+ data = null;
+ }
+ const base = emptyState();
+ if (!data || typeof data !== "object" || Array.isArray(data) || data.v !== STATE_VERSION) return base;
+ const asked = data.asked && typeof data.asked === "object" ? data.asked : {};
+ return {
+ ...base,
+ policy: parsePolicyState(data.policy),
+ policy_at: Number.isFinite(data.policy_at) ? data.policy_at : 0,
+ absent_at: Number.isFinite(data.absent_at) ? data.absent_at : 0,
+ asked: { day: typeof asked.day === "string" ? asked.day : "", count: Number.isFinite(asked.count) ? Math.max(0, Math.floor(asked.count)) : 0 },
+ asked_sessions: strings(data.asked_sessions, MAX_SESSIONS),
+ sessions: strings(data.sessions, MAX_SESSIONS),
+ session_count: Number.isFinite(data.session_count) ? Math.max(0, Math.floor(data.session_count)) : 0,
+ pulse_at: Number.isFinite(data.pulse_at) ? data.pulse_at : 0,
+ spool: Array.isArray(data.spool) ? data.spool.filter(validEntry).slice(-SPOOL_MAX) : [],
+ };
+}
+
+function parsePolicyState(value) {
+ if (!value || typeof value !== "object") return null;
+ return parsePolicy({
+ enabled: value.enabled,
+ turn_sample_rate: value.turnSampleRate,
+ max_per_day: value.maxPerDay,
+ pulse_enabled: value.pulseEnabled,
+ pulse_after_sessions: value.pulseAfterSessions,
+ pulse_every_days: value.pulseEveryDays,
+ });
+}
+
+function sleepSync(ms) {
+ try {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+ } catch {
+ /* no Atomics.wait: try again at once */
+ }
+}
+
+/**
+ * Runs `fn` holding `<file>.lock` (O_EXCL), so two apps changing the file at
+ * once do not lose each other's change. Never blocks for long: after
+ * LOCK_WAIT_MS (or with a lock older than LOCK_STALE_MS, left by a crash) it
+ * goes ahead anyway.
+ */
+export function withLock(file, fn) {
+ const lock = `${file}.lock`;
+ let fd = null;
+ const until = Date.now() + LOCK_WAIT_MS;
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ } catch {
+ /* the write reports it */
+ }
+ while (fd === null) {
+ try {
+ fd = fs.openSync(lock, "wx", 0o600);
+ } catch (error) {
+ if (error?.code !== "EEXIST") break;
+ try {
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { force: true });
+ } catch {
+ /* gone meanwhile */
+ }
+ if (Date.now() >= until) break;
+ sleepSync(10);
+ }
+ }
+ try {
+ return fn();
+ } finally {
+ if (fd !== null) {
+ try {
+ fs.closeSync(fd);
+ fs.rmSync(lock, { force: true });
+ } catch {
+ /* left: stale after LOCK_STALE_MS */
+ }
+ }
+ }
+}
+
+export function writeState(file, state) {
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ const tmp = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
+ fs.writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// --- the app's feedback -----------------------------------------------------
+
+/**
+ * @typedef {(pathAndQuery: string, init: { method?: string, body?: unknown, timeoutMs: number }) => Promise<{ status: number, data: unknown } | null>} FeedbackRequest
+ */
+
+/**
+ * The app's feedback. `request(pathAndQuery, { method, body, timeoutMs })`
+ * is the app's authorized call; it resolves { status, data }, or null when
+ * signed out. `allowed`: whether the app may ask on its own in this run (an
+ * interactive window or terminal, not headless, CI or switched off); anytime
+ * feedback works either way. `onEvent(name, properties)`: the app's
+ * analytics (feedback_prompt_shown, feedback_submitted), labels only.
+ */
+export function createFeedback({
+ request,
+ stateFile,
+ client = "cli",
+ version = "",
+ os = osName(),
+ allowed = true,
+ now = Date.now,
+ random = Math.random,
+ onEvent = null,
+ log = () => undefined,
+ retryEveryMs = 5 * 60_000,
+} = {}) {
+ const ctx = { client, appVersion: version, os };
+ let fetching = null;
+ let flushing = null;
+ let timer = null;
+ let stopped = false;
+ const sentHere = new Set();
+ // The first retry: a minute, or the retry interval when that is shorter (a test rig's).
+ const retryMinMs = retryEveryMs > 0 ? Math.min(RETRY_MIN_MS, retryEveryMs) : RETRY_MIN_MS;
+
+ // Every change starts from the file (another window or terminal may have written it).
+ const read = () => readState(stateFile);
+ const mutate = (fn) =>
+ withLock(stateFile, () => {
+ const state = read();
+ const result = fn(state);
+ writeState(stateFile, state);
+ return result;
+ });
+ const emit = (name, properties) => {
+ try {
+ onEvent?.(name, properties);
+ } catch {
+ /* analytics never in the way */
+ }
+ };
+
+ /** The policy in force: off when not allowed, not fetched, stale, or while the server has no feedback. */
+ function policy(state = read()) {
+ const at = now();
+ if (!allowed || !state.policy || at - state.policy_at > POLICY_MAX_AGE_MS) return { ...DEFAULT_POLICY };
+ // The send endpoint answered 404: never ask until a send works (what was
+ // queued is tried again every few minutes; the flag goes with the last entry).
+ if (state.absent_at) return { ...DEFAULT_POLICY };
+ return { ...state.policy };
+ }
+
+ async function refreshPolicy({ force = false } = {}) {
+ if (!allowed || typeof request !== "function") return policy();
+ if (fetching) return fetching;
+ const state = read();
+ if (!force && state.policy && now() - state.policy_at < POLICY_REFRESH_MS) return policy(state);
+ fetching = (async () => {
+ let result = null;
+ try {
+ result = await request(POLICY_PATH, { method: "GET", timeoutMs: FETCH_TIMEOUT_MS });
+ } catch (error) {
+ log("debug", "feedback policy: not reachable", { error: error instanceof Error ? error.message : String(error) });
+ }
+ const parsed = result?.status === 200 ? parsePolicy(result.data) : null;
+ if (parsed) {
+ // The server answers: what is queued is tried now (it may have been waiting for a deploy).
+ const queued = mutate((s) => {
+ s.policy = parsed;
+ s.policy_at = now();
+ for (const e of s.spool) e.next_at = Math.min(e.next_at ?? 0, now());
+ return s.spool.length;
+ });
+ if (queued) void flush().catch(() => undefined);
+ } else if (result && result.status === 404) {
+ // No feedback on this server (yet): off, asked again in an hour.
+ mutate((s) => {
+ s.policy = { ...DEFAULT_POLICY };
+ s.policy_at = now();
+ });
+ }
+ return policy();
+ })().finally(() => {
+ fetching = null;
+ });
+ return fetching;
+ }
+
+ /** A session this app started or opened (the pulse counts them). */
+ function sessionStarted(sessionId) {
+ if (typeof sessionId !== "string" || !SESSION_RE.test(sessionId)) return false;
+ return mutate((s) => {
+ if (s.sessions.includes(sessionId)) return false;
+ s.sessions = [...s.sessions, sessionId].slice(-MAX_SESSIONS);
+ s.session_count += 1;
+ return true;
+ });
+ }
+
+ /**
+ * After a finished turn: null, or { kind: "turn" | "pulse" } when the app
+ * should ask now (then counted: this session and today are used up).
+ * `turn`: { sessionId, outcome, toolCalls, durationMs }.
+ */
+ function offerAfterTurn(turn = {}) {
+ const sessionId = typeof turn.sessionId === "string" && SESSION_RE.test(turn.sessionId) ? turn.sessionId : null;
+ if (!allowed || !sessionId || !turnEligible(turn)) return null;
+ return mutate((s) => {
+ const p = policy(s);
+ if (!p.enabled || p.maxPerDay < 1) return null;
+ if (s.asked_sessions.includes(sessionId)) return null;
+ const day = localDay(now());
+ const count = s.asked.day === day ? s.asked.count : 0;
+ if (count >= p.maxPerDay) return null;
+ if (!s.sessions.includes(sessionId)) {
+ s.sessions = [...s.sessions, sessionId].slice(-MAX_SESSIONS);
+ s.session_count += 1;
+ }
+ let kind = null;
+ if (p.pulseEnabled && s.session_count >= p.pulseAfterSessions && now() - s.pulse_at >= p.pulseEveryDays * DAY_MS) kind = "pulse";
+ else if (p.turnSampleRate > 0 && random() < p.turnSampleRate) kind = "turn";
+ if (!kind) return null;
+ s.asked = { day, count: count + 1 };
+ s.asked_sessions = [...s.asked_sessions, sessionId].slice(-MAX_SESSIONS);
+ if (kind === "pulse") s.pulse_at = now();
+ return { kind };
+ });
+ }
+
+ /** The prompt is on screen (analytics only). */
+ function shown(kind, trigger = kind === "pulse" ? "pulse" : "sampled") {
+ emit("feedback_prompt_shown", { kind: KINDS.includes(kind) ? kind : "turn", trigger: TRIGGERS.includes(trigger) ? trigger : "sampled" });
+ }
+
+ /**
+ * Send one feedback (queued first). Resolves { ok: true, sent, queued,
+ * reason? } or { ok: false, error } when the input cannot be sent.
+ * `reason` when queued: offline | signed_out | unavailable | rate_limited.
+ */
+ async function submit(input = {}) {
+ const built = buildPayload(input, ctx);
+ if (built.error) return { ok: false, error: built.error };
+ const entry = { id: randomUUID(), at: now(), tries: 0, next_at: 0, sending_until: 0, payload: built.payload };
+ mutate((s) => {
+ s.spool = [...s.spool, entry].slice(-SPOOL_MAX);
+ });
+ emit("feedback_submitted", analyticsProperties(built.payload));
+ const outcome = await flush({ only: entry.id });
+ // Sent here, or by a send that was already running when this one came.
+ const sent = outcome.sent.includes(entry.id) || (sentHere.has(entry.id) && !read().spool.some((e) => e.id === entry.id));
+ return sent ? { ok: true, sent: true, queued: false } : { ok: true, sent: false, queued: outcome.kept.includes(entry.id), reason: outcome.reasons[entry.id] ?? "offline" };
+ }
+
+ /** Send what is queued and due (or just `only`; `force`: also what waits for its retry, the person asked). */
+ async function flush({ only = null, force = false } = {}) {
+ if (flushing) {
+ await flushing.catch(() => undefined);
+ if (!only) return { sent: [], kept: [], reasons: {} };
+ }
+ const run = (async () => {
+ const result = { sent: [], kept: [], reasons: {} };
+ if (typeof request !== "function") return result;
+ const at = now();
+ const due = mutate((s) => {
+ s.spool = s.spool.filter((e) => at - e.at <= SPOOL_MAX_AGE_MS);
+ if (!s.spool.length) s.absent_at = 0;
+ const picked = s.spool.filter((e) => (only ? e.id === only : true) && (e.sending_until ?? 0) <= at && (force || (e.next_at ?? 0) <= at));
+ // Out now: nobody else sends these meanwhile.
+ for (const e of picked) e.sending_until = at + IN_FLIGHT_MS;
+ return picked.map((e) => ({ ...e }));
+ });
+ for (const entry of due) {
+ if (stopped && !only) break;
+ let answer = null;
+ let failed = false;
+ try {
+ answer = await request(SUBMIT_PATH, { method: "POST", body: entry.payload, timeoutMs: SUBMIT_TIMEOUT_MS });
+ } catch {
+ failed = true;
+ }
+ const status = answer?.status ?? 0;
+ const done = status >= 200 && status < 300;
+ const final = status === 400 || status === 413 || status === 422;
+ let reason = "offline";
+ if (!failed && !answer) reason = "signed_out";
+ else if (status === 401 || status === 403) reason = "signed_out";
+ else if (status === 404) reason = "unavailable";
+ else if (status === 429) reason = "rate_limited";
+ if (final) log("warn", "feedback: the server refused one", { status });
+ mutate((s) => {
+ if (done || final) {
+ s.spool = s.spool.filter((e) => e.id !== entry.id);
+ if (done) s.absent_at = 0;
+ return;
+ }
+ if (status === 404) s.absent_at = now();
+ const kept = s.spool.find((e) => e.id === entry.id);
+ if (!kept) return;
+ kept.sending_until = 0;
+ kept.tries = (kept.tries ?? 0) + 1;
+ const backoff = Math.min(RETRY_MAX_MS, retryMinMs * 2 ** Math.min(12, kept.tries - 1));
+ kept.next_at = now() + (status === 429 ? RATE_LIMIT_RETRY_MS : status === 404 ? Math.min(RATE_LIMIT_RETRY_MS, backoff) : backoff);
+ });
+ if (done) {
+ result.sent.push(entry.id);
+ sentHere.add(entry.id);
+ if (sentHere.size > 200) sentHere.delete(sentHere.values().next().value);
+ }
+ else if (!final) {
+ result.kept.push(entry.id);
+ result.reasons[entry.id] = reason;
+ }
+ // The server has none or says not now: the rest waits too.
+ if (status === 404 || status === 429) break;
+ }
+ return result;
+ })();
+ if (!only) flushing = run;
+ try {
+ return await run;
+ } finally {
+ if (flushing === run) flushing = null;
+ }
+ }
+
+ function status() {
+ const state = read();
+ return { policy: policy(state), queued: state.spool.length, unavailable: Boolean(state.absent_at) };
+ }
+
+ return {
+ /** Ask for the policy and send what is queued, in the background. */
+ start() {
+ stopped = false;
+ void refreshPolicy().catch(() => undefined);
+ void flush().catch(() => undefined);
+ if (!timer && retryEveryMs > 0) {
+ timer = setInterval(() => {
+ void refreshPolicy().catch(() => undefined);
+ void flush().catch(() => undefined);
+ }, retryEveryMs);
+ timer.unref?.();
+ }
+ },
+ /** Stop the timer; one last bounded send of what is due. */
+ async stop() {
+ if (timer) clearInterval(timer);
+ timer = null;
+ stopped = true;
+ await flushing?.catch(() => undefined);
+ },
+ policy: () => policy(),
+ refreshPolicy,
+ sessionStarted,
+ offerAfterTurn,
+ shown,
+ submit,
+ flush,
+ status,
+ allowed: () => allowed,
+ };
+}
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 55855da6..ed37315f 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -76,6 +76,7 @@ import {
import { resolveConnectLinkPublicKeys } from "./connect-link-keys.mjs";
import { openExternalUrl } from "./open-external.mjs";
import { createDesktopPlacements, watchWindowForPlacements } from "./placements-desktop.mjs";
+import { createDesktopFeedback, EVENT_CHANNEL as FEEDBACK_EVENT_CHANNEL } from "./feedback-desktop.mjs";
import { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";
import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";
import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";
@@ -1417,6 +1418,26 @@ const desktopPlacements = createDesktopPlacements({
openUrl: (url) => openExternalUrl(url),
});
+// In-app feedback (feedback-desktop.mjs): "Send feedback" anytime, and a
+// quiet, sampled "How was this?" after a finished turn when the server's
+// policy turns it on. Its two analytics events go to the window's analytics.
+const desktopFeedback = createDesktopFeedback({
+ request: (pathAndQuery, init) => omnirushAccountStore.clientRequest(pathAndQuery, init),
+ userDataPath: app.getPath("userData"),
+ version: app.getVersion(),
+ packaged: app.isPackaged,
+ devMode: isDevMode,
+ emit: (name, properties) => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ try {
+ if (!win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send(FEEDBACK_EVENT_CHANNEL, { name, properties });
+ } catch {
+ /* closing */
+ }
+ }
+ },
+});
+
function omnirushUiMcpLaunch() {
return resolveOmniRushUiMcpLaunch({
devMode: process.env.OMNIRUSH_DEV_MODE === "1",
@@ -2426,6 +2447,25 @@ const desktopCommandHandlers = {
"omnirushPlacementAction": async (event, ...args) => {
return desktopPlacements.action(args[0] && typeof args[0] === "object" ? args[0] : {}).catch(() => ({ ok: false }));
},
+ // In-app feedback: never an error to the window (null / { ok: false } instead).
+ "omnirushFeedbackPolicy": async (event) => {
+ return desktopFeedback.policy();
+ },
+ "omnirushFeedbackStatus": async (event) => {
+ return desktopFeedback.status();
+ },
+ "omnirushFeedbackSessionStarted": async (event, ...args) => {
+ return desktopFeedback.sessionStarted(args[0] && typeof args[0] === "object" ? args[0] : {});
+ },
+ "omnirushFeedbackOffer": async (event, ...args) => {
+ return desktopFeedback.offer(args[0] && typeof args[0] === "object" ? args[0] : {});
+ },
+ "omnirushFeedbackShown": async (event, ...args) => {
+ return desktopFeedback.shown(args[0] && typeof args[0] === "object" ? args[0] : {});
+ },
+ "omnirushFeedbackSubmit": async (event, ...args) => {
+ return desktopFeedback.submit(args[0] && typeof args[0] === "object" ? args[0] : {});
+ },
// Buildathon: shown only to enrolled accounts; every failure is a null
// (or a "retry"), never a thrown error, so the app quietly shows nothing.
"omnirushBuildathon": async (event) => {
@@ -3327,6 +3367,7 @@ or use: pnpm dev:worktree`);
browserLoginSync.shutdown();
// The queued placement events: best effort, never waited for (the rest go next start).
void desktopPlacements.stop().catch(() => undefined);
+ void desktopFeedback.stop().catch(() => undefined);
// The uploads finish as the services stop: the computer stays awake for them.
const releaseKeepAwake = keepAwake.hold();
runDetachedTask("stop services before quit", async () => {
@@ -3459,6 +3500,7 @@ or use: pnpm dev:worktree`);
const win = await createMainWindow();
// In the background: the window never waits for it.
desktopPlacements.start();
+ desktopFeedback.start();
if (startReset.ran && startReset.moved.length > 0) {
runDetachedTask("show app data reset notice", async () => {
const { response } = await dialog.showMessageBox(win, {
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index b25b148f..86e6ff81 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -1322,7 +1322,8 @@ export function createDesktopOmniRushAccountStore({
}
/**
- * One sponsored-placements call (placements-desktop.mjs): `pathAndQuery`
+ * One sponsored-placements or feedback call (placements-desktop.mjs,
+ * feedback-desktop.mjs as `clientRequest`): `pathAndQuery`
* under the account server, the device credential, `timeoutMs` at most.
* Resolves { status, data } (data: the JSON of a 200, else null), or null
* while signed out. Throws on network errors and timeouts.
@@ -1451,5 +1452,7 @@ export function createDesktopOmniRushAccountStore({
buildathonJoin,
buildathonTagSession,
placementsRequest,
+ /** The same call for the other small client endpoints (feedback-desktop.mjs). */
+ clientRequest: placementsRequest,
};
}
diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjs
index 3e78763e..d50b5f5c 100644
--- a/apps/desktop/electron/preload.mjs
+++ b/apps/desktop/electron/preload.mjs
@@ -357,6 +357,18 @@ ipcRenderer.on("omnirush:placements:window", (_event, detail) => {
window.dispatchEvent(new CustomEvent("omnirush:placements:window", { detail }));
});
+// Help > Send Feedback… (app-menu.mjs): the window opens its feedback dialog.
+ipcRenderer.on("omnirush:native-menu:send-feedback", () => {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new Event("omnirush:native-menu:send-feedback"));
+});
+
+// In-app feedback (feedback-desktop.mjs EVENT_CHANNEL): { name, properties } for the app's analytics (labels only).
+ipcRenderer.on("omnirush:feedback:event", (_event, detail) => {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new CustomEvent("omnirush:feedback:event", { detail }));
+});
+
ipcRenderer.on(NATIVE_MENU_ZOOM_EVENT, (_event, action) => {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent(NATIVE_MENU_ZOOM_EVENT, { detail: action }));
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 8ff42386..03fa8ec2 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/open-local-path.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/buildathon.test.mjs electron/placements-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.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/open-local-path.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/buildathon.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.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/open-local-path.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 dc5c7807..2c396faa 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -412,6 +412,39 @@ export type OmniRushPlacement = {
/** rendered / viewable / open (the click) / dismiss: about one display; conversation / activity: for the display rotation. */
export type OmniRushPlacementAction = "rendered" | "viewable" | "open" | "dismiss" | "conversation" | "activity";
+/** In-app feedback (apps/desktop/electron/feedback-desktop.mjs and the shared feedback/feedback.mjs). */
+export type OmniRushFeedbackKind = "turn" | "general" | "pulse";
+export type OmniRushFeedbackTrigger = "sampled" | "command" | "menu" | "pulse";
+/** How a finished turn ended: only "ok" turns may get the after-turn prompt. */
+export type OmniRushFeedbackTurnOutcome = "ok" | "refused" | "limit" | "error" | "stopped";
+export type OmniRushFeedbackPolicy = {
+ enabled: boolean;
+ turnSampleRate: number;
+ maxPerDay: number;
+ pulseEnabled: boolean;
+ pulseAfterSessions: number;
+ pulseEveryDays: number;
+};
+export type OmniRushFeedbackOffer = { kind: "turn" | "pulse" } | null;
+export type OmniRushFeedbackInput = {
+ kind: OmniRushFeedbackKind;
+ /** "up" | "down" for a turn, 0-10 for the pulse, null for anytime feedback. */
+ rating: "up" | "down" | number | null;
+ categories: string[];
+ comment: string | null;
+ sessionId: string | null;
+ /** 1-based user-turn index of the rated answer. */
+ turn: number | null;
+ trigger: OmniRushFeedbackTrigger;
+ modelId: string | null;
+ effort: string | null;
+};
+/** queued: kept in feedback.json and sent later (offline, signed out, the server has none yet, rate limited). */
+export type OmniRushFeedbackResult =
+ | { ok: true; sent: boolean; queued: boolean; reason?: "offline" | "signed_out" | "unavailable" | "rate_limited" }
+ | { ok: false; error: string };
+export type OmniRushFeedbackStatus = { policy: OmniRushFeedbackPolicy; queued: number; unavailable: boolean; allowed: boolean };
+
export type OmniRushSessionStatus = {
sessionId: string;
status: "on_track" | "at_risk" | "failing" | "unknown";
@@ -971,6 +1004,15 @@ export type DesktopCommandMap = {
omnirushBuildathonJoin: { args: []; result: OmniRushBuildathonLinkResult };
omnirushPlacement: { args: [input: { slot: OmniRushPlacementSlot; sessionId?: string }]; result: OmniRushPlacement | null };
omnirushPlacementAction: { args: [input: { action: OmniRushPlacementAction; id?: string; displayId?: string; sessionId?: string }]; result: { ok: boolean; opened?: boolean; rotate?: boolean } };
+ omnirushFeedbackPolicy: { args: []; result: OmniRushFeedbackPolicy };
+ omnirushFeedbackStatus: { args: []; result: OmniRushFeedbackStatus };
+ omnirushFeedbackSessionStarted: { args: [input: { sessionId: string }]; result: boolean };
+ omnirushFeedbackOffer: {
+ args: [input: { sessionId: string; outcome: OmniRushFeedbackTurnOutcome; toolCalls: number; durationMs: number; text?: string }];
+ result: OmniRushFeedbackOffer;
+ };
+ omnirushFeedbackShown: { args: [input: { kind: "turn" | "pulse" }]; result: { ok: boolean } };
+ omnirushFeedbackSubmit: { args: [input: OmniRushFeedbackInput]; result: OmniRushFeedbackResult };
omnirushBuildathonSessions: { args: []; result: OmniRushBuildathonSession[] | null };
omnirushBuildathonLink: { args: [input: { code: string }]; result: OmniRushBuildathonLinkResult };
omnirushBuildathonChecklist: {