Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: quieter feedback prompt

Samrat Talukdar914627eab005
diff --git a/apps/app/src/app/lib/analytics.ts b/apps/app/src/app/lib/analytics.ts
index 91757de0..8d8364e1 100644
--- a/apps/app/src/app/lib/analytics.ts
+++ b/apps/app/src/app/lib/analytics.ts
@@ -252,8 +252,20 @@ export function attributionSurveyProperties(source: string, aiPrompt?: string |
// sync) emit nothing.
const taskRunStarts = new Map<string, number>();
+// The last prompt this window sent per session (kept after the run ends):
+// in-app feedback only asks about turns a person started here, never about
+// Workflows, automations or sub-agents.
+const promptsSentHere = new Map<string, number>();
+
export function markTaskRunStart(sessionId: string) {
- if (sessionId.trim()) taskRunStarts.set(sessionId, Date.now());
+ if (!sessionId.trim()) return;
+ taskRunStarts.set(sessionId, Date.now());
+ promptsSentHere.set(sessionId, Date.now());
+}
+
+/** When this window last sent a prompt to `sessionId` (ms), or null. */
+export function promptSentHereAt(sessionId: string): number | null {
+ return promptsSentHere.get(sessionId) ?? null;
}
export function takeTaskRunStart(sessionId: string): number | null {
diff --git a/apps/app/src/app/lib/in-app-feedback.ts b/apps/app/src/app/lib/in-app-feedback.ts
index 4b73efc9..4b0cca75 100644
--- a/apps/app/src/app/lib/in-app-feedback.ts
+++ b/apps/app/src/app/lib/in-app-feedback.ts
@@ -29,7 +29,7 @@ import {
omnirushFeedbackShown,
omnirushFeedbackSubmit,
} from "./desktop";
-import { messageFacts } from "./good-session";
+import { messageFacts, promptsInTranscript } from "./good-session";
/** After a thumbs down (the shared module's TURN_REASONS, same ids and words). */
export const TURN_REASONS = [
@@ -55,6 +55,7 @@ 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.";
export const TOO_LARGE_ERROR = "That's too long to send";
+export const SEND_FAILED = "Couldn't send. Try again.";
/** 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";
@@ -85,27 +86,35 @@ function opencodeMeta(message: UIMessage): Record<string, unknown> {
return record(record(message.metadata).opencode);
}
+/** A prompt a person sent: a user message that is not a compaction request or only synthetic text ("Continue."). */
+function isRealPrompt(message: UIMessage): boolean {
+ return message.role === "user" && opencodeMeta(message).compaction !== true && promptsInTranscript([message]) === 1;
+}
+
/**
- * 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".
+ * How the last turn of a transcript ended, or null when there is nothing to
+ * rate: no answer yet, an answer still open, an agent waiting for an answer
+ * to its question, or a compaction. The turn starts at the last prompt a
+ * person sent, past the synthetic "continue" and compaction messages an
+ * automatic compaction adds. 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;
+ while (start > 0 && !isRealPrompt(messages[start - 1]!)) 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 assistants = messages.slice(start).filter((message) => message.role === "assistant");
+ const last = assistants.at(-1);
+ // The last answer is a compaction's summary: no agent turn to rate.
+ if (!last || opencodeMeta(last).compaction === true) return null;
+ const answer = assistants.filter((message) => opencodeMeta(message).compaction !== true);
const facts = messageFacts(messages);
- if (facts.replyOpen || facts.ended === "none") return null;
+ // "awaiting": the agent asked the person something; the turn is not over.
+ if (facts.replyOpen || facts.ended === "none" || facts.ended === "awaiting") return null;
let outcome: OmniRushFeedbackTurnOutcome;
- if (facts.ended === "pass" || facts.ended === "awaiting") outcome = "ok";
+ if (facts.ended === "pass") outcome = "ok";
else if (facts.ended === "stopped") outcome = "stopped";
else outcome = "error";
let toolCalls = 0;
@@ -124,10 +133,16 @@ export function finishedTurn(messages: readonly UIMessage[]): FinishedTurn | nul
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;
+ const turn = promptsInTranscript(messages.slice(0, start));
return { outcome, toolCalls, durationMs, text: text.trim().slice(0, 700), turn, messageId: last.id };
}
+/** The last assistant message's id (the prompt shows only under that answer). */
+export function lastAnswerId(messages: readonly UIMessage[]): string | null {
+ for (let i = messages.length - 1; i >= 0; i -= 1) if (messages[i]!.role === "assistant") return messages[i]!.id;
+ return null;
+}
+
/** 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;
@@ -157,7 +172,7 @@ export type TurnPrompt = {
export type FeedbackDialogState = {
open: boolean;
trigger: "menu" | "command";
- /** The session open when the dialog opened (offered as "Include this session's id"). */
+ /** The session open when the dialog opened (offered as "Include this chat's id"). */
sessionId: string | null;
category: GeneralCategoryId;
text: string;
@@ -166,6 +181,8 @@ export type FeedbackDialogState = {
sending: boolean;
/** The server refused the last Send (shown inline; the text stays). */
error: string | null;
+ /** Which opening this is: a late answer to an earlier one leaves a reopened dialog alone. */
+ openId: number;
};
type FeedbackState = {
@@ -173,7 +190,8 @@ type FeedbackState = {
dialog: FeedbackDialogState;
};
-const closedDialog: FeedbackDialogState = { open: false, trigger: "menu", sessionId: null, category: "bug", text: "", includeSession: null, sending: false, error: null };
+const closedDialog: FeedbackDialogState = { open: false, trigger: "menu", sessionId: null, category: "bug", text: "", includeSession: null, sending: false, error: null, openId: 0 };
+let dialogOpens = 0;
export const useFeedbackStore = create<FeedbackState>(() => ({ prompt: null, dialog: closedDialog }));
@@ -247,10 +265,10 @@ async function send(input: OmniRushFeedbackInput, { toast = true } = {}): Promis
// --- after a turn ----------------------------------------------------------------------
-/** A turn started in this session: the pulse counts sessions; an open prompt goes (its rating is sent). */
+/** A turn started in this session: the pulse counts sessions; this session's open prompt goes (its rating is sent). */
export function feedbackTurnStarted(sessionId: string) {
void bridge.sessionStarted({ sessionId }).catch(() => undefined);
- if (useFeedbackStore.getState().prompt) void closePrompt();
+ void closePrompt(sessionId);
}
/**
@@ -263,6 +281,8 @@ export async function offerFeedbackAfterTurn(input: {
fallbackDurationMs: number;
modelId: string | null;
effort: string | null;
+ /** Checked again once the main process answers: same session, idle, the same last answer, nothing typed. */
+ stillCurrent?: () => boolean;
}): Promise<OmniRushFeedbackOffer> {
const { turn } = input;
let offer: OmniRushFeedbackOffer = null;
@@ -278,6 +298,7 @@ export async function offerFeedbackAfterTurn(input: {
offer = null;
}
if (!offer || (offer.kind !== "turn" && offer.kind !== "pulse")) return null;
+ if (input.stillCurrent && !input.stillCurrent()) return null;
useFeedbackStore.setState({
prompt: {
sessionId: input.sessionId,
@@ -304,8 +325,9 @@ function promptInput(prompt: TurnPrompt): OmniRushFeedbackInput {
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,
+ // The pulse is about OmniRush, not this chat: no chat id.
+ sessionId: prompt.kind === "pulse" ? null : prompt.sessionId,
+ turn: prompt.kind === "pulse" ? null : prompt.turn,
trigger: prompt.kind === "pulse" ? "pulse" : "sampled",
modelId: prompt.modelId,
effort: prompt.effort,
@@ -351,7 +373,7 @@ export async function sendPrompt({ skip = false } = {}): Promise<OmniRushFeedbac
const input = skip ? { ...promptInput(prompt), categories: [], comment: null } : promptInput(prompt);
setPrompt({ sending: true, error: null });
const result = await send(input, { toast: false });
- const refused = refusalText(result);
+ const refused = result.ok ? null : refusalText(result) ?? SEND_FAILED;
const current = useFeedbackStore.getState().prompt;
if (refused && current?.sessionId === prompt.sessionId && current.messageId === prompt.messageId) {
setPrompt({ sending: false, error: refused });
@@ -365,19 +387,21 @@ export async function sendPrompt({ skip = false } = {}): Promise<OmniRushFeedbac
/**
* 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).
+ * signal) and is sent quietly with the reasons picked, without the unsent
+ * comment. `sessionId`: only that session's prompt (split view).
*/
-export function closePrompt(): Promise<OmniRushFeedbackResult | null> {
+export function closePrompt(sessionId?: string): Promise<OmniRushFeedbackResult | null> {
const prompt = useFeedbackStore.getState().prompt;
+ if (!prompt || (sessionId !== undefined && prompt.sessionId !== sessionId)) return Promise.resolve(null);
useFeedbackStore.setState({ prompt: null });
// Not chosen, or already on its way (Send was pressed).
- if (!prompt || prompt.rating === null || prompt.sending) return Promise.resolve(null);
- return send({ ...promptInput(prompt), categories: [], comment: null }, { toast: false });
+ if (prompt.rating === null || prompt.sending) return Promise.resolve(null);
+ return send({ ...promptInput(prompt), comment: null }, { toast: false });
}
// --- "Send feedback" ----------------------------------------------------------------------
-/** Whether "Include this session's id" is ticked: the person's own choice, else on for Bug. */
+/** Whether "Include this chat'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";
}
@@ -393,7 +417,8 @@ export function setFeedbackCurrentSession(sessionId: string | null | undefined)
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 } });
+ dialogOpens += 1;
+ useFeedbackStore.setState({ dialog: { ...closedDialog, open: true, trigger: input.trigger, sessionId, openId: dialogOpens } });
}
export function closeFeedbackDialog() {
@@ -428,8 +453,10 @@ export async function sendFeedbackDialog(): Promise<OmniRushFeedbackResult | nul
modelId: null,
effort: null,
});
- if (result.ok) useFeedbackStore.setState({ dialog: closedDialog });
- else setDialog({ sending: false, error: refusalText(result) ?? "Couldn't send. Try again." });
+ // The dialog was closed or opened again meanwhile: this answer is not its business.
+ if (useFeedbackStore.getState().dialog.openId !== dialog.openId) return result;
+ if (result.ok) useFeedbackStore.setState({ dialog: { ...closedDialog, openId: dialog.openId } });
+ else setDialog({ sending: false, error: refusalText(result) ?? SEND_FAILED });
return result;
}
diff --git a/apps/app/src/react-app/domains/feedback/feedback.tsx b/apps/app/src/react-app/domains/feedback/feedback.tsx
index e821b8f5..4c54c79a 100644
--- a/apps/app/src/react-app/domains/feedback/feedback.tsx
+++ b/apps/app/src/react-app/domains/feedback/feedback.tsx
@@ -8,7 +8,7 @@
// 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".
+// dialog: category, text, "Include this chat's id".
// The prompt is drawn next to the transcript, never part of its messages.
import { useEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from "react";
@@ -31,6 +31,7 @@ import {
feedbackTurnStarted,
finishedTurn,
GENERAL_CATEGORIES,
+ lastAnswerId,
includeSessionChecked,
installFeedbackAnalytics,
offerFeedbackAfterTurn,
@@ -55,6 +56,7 @@ import {
type TurnPrompt,
type TurnReasonId,
} from "../../../app/lib/in-app-feedback";
+import { promptSentHereAt } from "../../../app/lib/analytics";
/** 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;
@@ -63,6 +65,17 @@ const SETTLE_MAX_MS = 4_500;
// --- after a turn -----------------------------------------------------------------------
+/** Typing in the composer this recently: not now. */
+const QUIET_INPUT_MS = 3_000;
+/** A toast or dialog on screen (the Good-session card, the finish guard): wait, at most this long, then let it be. */
+const WAIT_FOR_CLEAR_MS = 20_000;
+
+/** Something else is up on screen: a toast (the Good-session card) or a dialog. The thumbs never stack with it. */
+function screenBusy(): boolean {
+ if (typeof document === "undefined") return false;
+ return Boolean(document.querySelector('[data-sonner-toast]:not([data-removed="true"]), [role="dialog"], [role="alertdialog"]'));
+}
+
export type FeedbackTurnPromptProps = {
sessionId: string;
messages: readonly UIMessage[];
@@ -71,11 +84,19 @@ export type FeedbackTurnPromptProps = {
draft: string;
modelId: string | null;
effort: string | null;
+ /** Follow-ups waiting to be sent: the next turn is coming, not now. */
+ queuedCount: number;
+ /** False for sessions a person does not drive here (sub-agents, automations). */
+ askable: boolean;
+ /** After Send, Skip or ×: focus back to the composer. */
+ onDone?: () => void;
};
/**
* 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.
+ * the turn ended and, when the moment is quiet (nothing typed, nothing
+ * queued, no card or dialog up), asks the main process; draws the prompt it
+ * gets under the last answer only.
*/
export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
const prompt = useFeedbackStore((state) => state.prompt);
@@ -83,6 +104,12 @@ export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
latest.current = props;
const edge = useRef({ sessionId: props.sessionId, running: props.turnRunning });
const startedAt = useRef<number | null>(null);
+ const lastInputAt = useRef(0);
+ const draftSeen = useRef(props.draft);
+ if (draftSeen.current !== props.draft) {
+ draftSeen.current = props.draft;
+ lastInputAt.current = Date.now();
+ }
useEffect(() => {
const before = edge.current;
@@ -98,19 +125,40 @@ export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
if (!turnJustFinished(before, now)) return;
const sessionId = props.sessionId;
const began = startedAt.current ?? Date.now();
- const deadline = Date.now() + SETTLE_MAX_MS;
+ const settleBy = Date.now() + SETTLE_MAX_MS;
+ const clearBy = Date.now() + WAIT_FOR_CLEAR_MS;
let cancelled = false;
let timer: ReturnType<typeof setTimeout>;
+ // The same session, idle, the same last answer, nothing typed or queued.
+ const quiet = (messageId: string) => {
+ const current = latest.current;
+ return current.sessionId === sessionId && !current.turnRunning && current.askable && !current.draft.trim()
+ && current.queuedCount === 0 && lastAnswerId(current.messages) === messageId && Date.now() - lastInputAt.current >= QUIET_INPUT_MS;
+ };
const judge = () => {
if (cancelled) return;
const current = latest.current;
- if (current.sessionId !== sessionId || current.turnRunning) return;
+ if (current.sessionId !== sessionId || current.turnRunning || !current.askable) return;
+ // Only turns a person started from this window (never Workflows, automations or sub-agents).
+ const sent = promptSentHereAt(sessionId);
+ if (sent === null || sent < began - 60_000) return;
const turn = finishedTurn(current.messages);
if (!turn) {
- if (Date.now() < deadline) timer = setTimeout(judge, 150);
+ if (Date.now() < settleBy) timer = setTimeout(judge, 150);
+ return;
+ }
+ if (!quiet(turn.messageId) || screenBusy()) {
+ if (Date.now() < clearBy) timer = setTimeout(judge, 400);
return;
}
- void offerFeedbackAfterTurn({ sessionId, turn, fallbackDurationMs: Date.now() - began, modelId: current.modelId, effort: current.effort });
+ void offerFeedbackAfterTurn({
+ sessionId,
+ turn,
+ fallbackDurationMs: Date.now() - began,
+ modelId: current.modelId,
+ effort: current.effort,
+ stillCurrent: () => !cancelled && quiet(turn.messageId),
+ });
};
timer = setTimeout(judge, SETTLE_MS);
return () => {
@@ -119,16 +167,16 @@ export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
};
}, [props.sessionId, props.turnRunning]);
- // This pane switches to another session: the prompt of the one it left goes (its rating, if chosen, is sent).
+ // This pane switches to another session, or goes: the prompt it showed 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();
+ if (left !== props.sessionId) void closePrompt(left);
}, [props.sessionId]);
+ useEffect(() => () => void closePrompt(shownSession.current), []);
- const visible = Boolean(prompt) && prompt?.sessionId === props.sessionId && !props.turnRunning;
+ const visible = prompt !== null && prompt.sessionId === props.sessionId && !props.turnRunning && prompt.messageId === lastAnswerId(props.messages);
// Typing a new prompt (the draft changing after the prompt showed) puts it away.
const draftAtShow = useRef<string | null>(null);
useEffect(() => {
@@ -140,10 +188,11 @@ export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
draftAtShow.current = props.draft;
return;
}
- if (props.draft !== draftAtShow.current && props.draft.trim()) void closePrompt();
- }, [visible, props.draft]);
+ if (props.draft !== draftAtShow.current && props.draft.trim()) void closePrompt(props.sessionId);
+ }, [visible, props.draft, props.sessionId]);
if (!visible || !prompt) return null;
+ const done = () => latest.current.onDone?.();
return (
<FeedbackTurnPromptView
prompt={prompt}
@@ -151,9 +200,12 @@ export function FeedbackTurnPrompt(props: FeedbackTurnPromptProps) {
onPulse={ratePulse}
onToggleReason={toggleTurnReason}
onComment={setPromptComment}
- onSend={() => void sendPrompt()}
- onSkip={() => void sendPrompt({ skip: true })}
- onDismiss={() => void closePrompt()}
+ onSend={() => void sendPrompt().then((result) => { if (!useFeedbackStore.getState().prompt && result) done(); })}
+ onSkip={() => void sendPrompt({ skip: true }).then((result) => { if (!useFeedbackStore.getState().prompt && result) done(); })}
+ onDismiss={() => {
+ void closePrompt(props.sessionId);
+ done();
+ }}
/>
);
}
@@ -170,9 +222,11 @@ export type FeedbackTurnPromptViewProps = {
};
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";
+const chipClass = "h-7 px-2.5 text-[12px] text-muted-foreground aria-pressed:border-foreground/25 aria-pressed:text-foreground";
function CommentRow(props: { prompt: TurnPrompt; placeholder: string; onComment: (text: string) => void; onSend: () => void; onSkip: () => void; testId: string }) {
+ // The pulse is about OmniRush, not this chat: it carries no chat id.
+ const note = props.prompt.kind === "pulse" ? null : RATING_NOTE;
return (
<>
<div className="flex w-full max-w-xl items-center gap-2">
@@ -198,7 +252,7 @@ function CommentRow(props: { prompt: TurnPrompt; placeholder: string; onComment:
{props.prompt.error ? (
<p role="alert" className="text-[12px] leading-4 text-destructive" data-testid="feedback-error">{props.prompt.error}</p>
) : null}
- <p className="text-[11px] leading-4 text-muted-foreground/80" data-testid="feedback-note">{RATING_NOTE}</p>
+ {note ? <p className="text-[11px] leading-4 text-muted-foreground/80" data-testid="feedback-note">{note}</p> : null}
</>
);
}
@@ -217,7 +271,7 @@ export function FeedbackTurnPromptView(props: FeedbackTurnPromptViewProps) {
variant="ghost"
size="icon-xs"
aria-label="Dismiss"
- title="Dismiss (Esc)"
+ title="Dismiss"
onClick={props.onDismiss}
className="text-muted-foreground/70 hover:text-foreground"
data-testid="feedback-dismiss"
@@ -270,30 +324,37 @@ export function FeedbackTurnPromptView(props: FeedbackTurnPromptViewProps) {
<>
<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">
+ <Button variant="ghost" size="icon-xs" className={thumbClass} aria-label="Good answer" title={`Good answer. ${RATING_NOTE}`} 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">
+ <Button variant="ghost" size="icon-xs" className={thumbClass} aria-label="Bad answer" title={`Bad answer. ${RATING_NOTE}`} 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?">
+ <ToggleGroup
+ multiple
+ aria-label="What went wrong?"
+ variant="outline"
+ size="sm"
+ spacing={1.5}
+ value={prompt.reasons}
+ onValueChange={(value) => {
+ // The one reason pressed or released.
+ const next = value.filter((id): id is TurnReasonId => TURN_REASONS.some((r) => r.id === id));
+ const changed = TURN_REASONS.find((r) => next.includes(r.id) !== prompt.reasons.includes(r.id));
+ if (changed) props.onToggleReason(changed.id);
+ }}
+ className="flex-wrap"
+ >
{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}`}
- >
+ <ToggleGroupItem key={reason.id} value={reason.id} className={chipClass} data-testid={`feedback-reason-${reason.id}`}>
{reason.label}
- </button>
+ </ToggleGroupItem>
))}
- </div>
+ </ToggleGroup>
<CommentRow prompt={prompt} placeholder="Anything to add? (optional)" onComment={props.onComment} onSend={props.onSend} onSkip={props.onSkip} testId="feedback-comment" />
</>
) : prompt.stage === "up" ? (
@@ -365,7 +426,7 @@ export function FeedbackFormView(props: FeedbackFormViewProps) {
{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
+ Include this chat's id
</label>
) : null}
</div>
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 ca89c060..feb1481b 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
@@ -3408,6 +3408,9 @@ export function SessionSurface(props: SessionSurfaceProps) {
draft={draft}
modelId={sessionModel.selectedModel?.modelID ?? null}
effort={sessionModel.modelVariant ?? null}
+ queuedCount={queuedItems.length}
+ askable={!currentSnapshot?.session.parentID && !(currentSnapshot?.session.title ?? "").startsWith("Automation: ")}
+ onDone={() => composerShellRef.current?.querySelector<HTMLElement>("[contenteditable=true]")?.focus()}
/>
{admissionOutcomeUnresolved && queuedDrainState.phase.kind !== "admission_unknown" && renderedMessages.length > 0 ? (
<AdmissionOutcomeUnknownCard
diff --git a/apps/app/tests/in-app-feedback.test.tsx b/apps/app/tests/in-app-feedback.test.tsx
index 63786554..b70f1748 100644
--- a/apps/app/tests/in-app-feedback.test.tsx
+++ b/apps/app/tests/in-app-feedback.test.tsx
@@ -60,6 +60,20 @@ describe("in-app feedback: how the last turn ended", () => {
expect(lib.finishedTurn(messages)).toEqual({ outcome: "ok", toolCalls: 1, durationMs: 15_000, text: "Two files: a and b.", turn: 2, messageId: "a2" });
});
+ test("the agent asking the person a question is not a finished turn", () => {
+ const asks = [user("u1", "set it up"), assistant("a1", [toolPart, text("Which database should I use, Postgres or SQLite?")])];
+ expect(lib.finishedTurn(asks)).toBeNull();
+ });
+
+ test("after an automatic compaction: back to the real prompt (tools, duration, turn index)", () => {
+ const cont = { id: "c1", role: "user", parts: [{ type: "text", text: "Continue.", synthetic: true }], metadata: { opencode: { created: 30_000 } } } as unknown as UIMessage;
+ const compactReq = { ...user("cr", "compact"), metadata: { opencode: { created: 20_000, compaction: true } } } as UIMessage;
+ const summary = assistant("s1", [text("summary")], { created: 20_100, completed: 25_000, finish: "stop", compaction: true });
+ const messages = [user("u1", "first"), assistant("a1", [text("hi")]), user("u2", "build it", 10_000), assistant("a2", [toolPart], { created: 10_100, completed: 19_000, finish: "tool-calls" }), compactReq, summary, cont, assistant("a3", [toolPart, text("Built.")], { created: 30_100, completed: 50_000, finish: "stop" })];
+ expect(lib.finishedTurn(messages)).toEqual({ outcome: "ok", toolCalls: 2, durationMs: 40_000, text: "Built.", turn: 2, messageId: "a3" });
+ expect(lib.lastAnswerId(messages)).toBe("a3");
+ });
+
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();
@@ -88,6 +102,21 @@ describe("in-app feedback: after a 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("stale by the time the main process answers (typed, another answer, another session): dropped", async () => {
+ const main = fakeMain();
+ expect(await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null, stillCurrent: () => false })).toBeNull();
+ expect(lib.useFeedbackStore.getState().prompt).toBeNull();
+ expect(main.shown).toEqual([]);
+ });
+
+ test("a send that fails outright says so inline; the prompt stays", async () => {
+ fakeMain({ kind: "turn" }, { ok: false, error: "failed" });
+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });
+ lib.rateTurn("up");
+ await lib.sendPrompt();
+ expect(lib.useFeedbackStore.getState().prompt?.error).toBe("Couldn't send. Try again.");
+ });
+
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();
@@ -121,15 +150,20 @@ describe("in-app feedback: after a turn", () => {
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 () => {
+ test("a rating chosen and then left (next turn, typing, ×): the rating and the reasons picked, sent quietly, not the unsent comment", 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.setPromptComment("half typed");
+ lib.feedbackTurnStarted("ses_other");
+ await flush();
+ expect(lib.useFeedbackStore.getState().prompt?.sessionId).toBe("ses_1");
+ expect(main.submitted).toEqual([]);
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.started).toEqual([{ sessionId: "ses_other" }, { sessionId: "ses_1" }]);
+ expect(main.submitted[0]).toMatchObject({ rating: "down", categories: ["ui"], comment: null });
expect(main.toasts).toEqual([]);
expect(lib.useFeedbackStore.getState().prompt).toBeNull();
});
@@ -151,7 +185,7 @@ describe("in-app feedback: after a turn", () => {
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 }]);
+ expect(main.submitted).toEqual([{ kind: "pulse", rating: 9, categories: [], comment: "fast and handy", sessionId: null, turn: null, trigger: "pulse", modelId: "m", effort: null }]);
});
test("queued (offline / the server has none yet): the saved wording, never an error", async () => {
@@ -203,7 +237,7 @@ describe("in-app feedback: refusals (422 / 413)", () => {
const prompt = { sessionId: "ses_1", kind: "turn" as const, stage: "down" as const, turn: 2, messageId: "a2", modelId: null, effort: null, rating: "down" as const, reasons: [], comment: "x", error: "Couldn't send: comment: too long", sending: false };
const html = renderToStaticMarkup(<FeedbackTurnPromptView prompt={prompt} onRate={noop} onPulse={noop} onToggleReason={noop} onComment={noop} onSend={noop} onSkip={noop} onDismiss={noop} />);
expect(html).toContain("Couldn&#x27;t send: comment: too long");
- const dialog = { open: true, trigger: "menu" as const, sessionId: null, category: "bug" as const, text: "x", includeSession: null, sending: false, error: "That's too long to send" };
+ const dialog = { open: true, trigger: "menu" as const, sessionId: null, category: "bug" as const, text: "x", includeSession: null, sending: false, error: "That's too long to send", openId: 1 };
const form = renderToStaticMarkup(<FeedbackFormView dialog={dialog} onCategory={noop} onText={noop} onIncludeSession={noop} onSend={noop} onCancel={noop} />);
expect(form).toContain("That&#x27;s too long to send");
expect(form).toContain('role="alert"');
@@ -239,6 +273,25 @@ describe("in-app feedback: Send feedback", () => {
expect(main.toasts).toEqual([{ kind: "sent", title: "Thanks, sent." }]);
});
+ test("a late answer to an earlier opening leaves a reopened dialog alone", async () => {
+ let release: (v: unknown) => void = () => undefined;
+ lib.setFeedbackBridgeForTests({
+ offer: async () => null,
+ sessionStarted: async () => true,
+ shown: async () => ({ ok: true }),
+ submit: () => new Promise((resolve) => { release = resolve; }) as never,
+ });
+ lib.openFeedbackDialog({ trigger: "menu", sessionId: null });
+ lib.setDialogText("first");
+ const pending = lib.sendFeedbackDialog();
+ lib.closeFeedbackDialog();
+ lib.openFeedbackDialog({ trigger: "command", sessionId: null });
+ lib.setDialogText("second, being written");
+ release({ ok: true, sent: true, queued: false });
+ await pending;
+ expect(lib.useFeedbackStore.getState().dialog).toMatchObject({ open: true, trigger: "command", text: "second, being written" });
+ });
+
test("a refused input keeps the dialog open", async () => {
fakeMain(null, { ok: false, error: "comment" });
lib.openFeedbackDialog({ trigger: "menu" });
@@ -297,8 +350,10 @@ describe("in-app feedback: the views", () => {
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"/);
+ const chip = (id: string) => html.match(new RegExp(`<button[^>]*data-testid="feedback-reason-${id}"[^>]*>`))?.[0] ?? "";
+ expect(chip("slow")).toContain('aria-pressed="true"');
+ expect(chip("wrong")).toContain('aria-pressed="false"');
+ expect(html).toContain('data-slot="toggle-group"');
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"');
@@ -331,14 +386,14 @@ describe("in-app feedback: the views", () => {
});
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, error: null };
+ const dialog = { open: true, trigger: "menu" as const, sessionId: "ses_open", category: "bug" as const, text: "", includeSession: null, sending: false, error: null, openId: 1 };
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).toContain("Include this chat&#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.toContain("Include this chat");
expect(noSession).not.toMatch(/data-testid="feedback-dialog-send"[^>]*disabled=""/);
});
});
diff --git a/apps/desktop/electron/feedback-desktop.mjs b/apps/desktop/electron/feedback-desktop.mjs
index e38b4d38..bb322f20 100644
--- a/apps/desktop/electron/feedback-desktop.mjs
+++ b/apps/desktop/electron/feedback-desktop.mjs
@@ -85,7 +85,12 @@ function finite(value) {
* now?: () => number,
* random?: () => number,
* log?: (level: string, message: string, data?: object) => void,
+ * accountId?: (() => Promise<string | null>) | null,
* }} options
+ *
+ * `accountId()`: the signed-in account's id, null when signed out. Queued
+ * feedback is stamped with it and sent only under that account; the app
+ * never asks on its own while signed out.
*/
export function createDesktopFeedback({
request,
@@ -99,10 +104,20 @@ export function createDesktopFeedback({
now = Date.now,
random = Math.random,
log = () => undefined,
+ accountId = null,
}) {
const allowed = desktopFeedbackAllowed({ env, packaged, devMode });
- // (The shared module's options carry no JSDoc type of their own.)
- const service = createFeedback(/** @type {any} */ ({
+ /** The account last read (the shared module asks synchronously); read again before each offer, send and retry. */
+ let account = null;
+ async function readAccount() {
+ if (typeof accountId !== "function") return account;
+ account = await accountId().catch(() => null);
+ return account;
+ }
+ const retryEveryMs = desktopFeedbackRetryMs({ env, packaged });
+ let accountTimer = null;
+ /** @type {import("./feedback/feedback.mjs").FeedbackOptions} */
+ const options = {
request,
stateFile: path.join(userDataPath, STATE_FILE),
client: "desktop",
@@ -112,7 +127,8 @@ export function createDesktopFeedback({
now,
random,
log,
- retryEveryMs: desktopFeedbackRetryMs({ env, packaged }),
+ retryEveryMs,
+ ...(typeof accountId === "function" ? { account: () => account } : {}),
onEvent: (name, properties) => {
try {
emit?.(name, properties);
@@ -120,13 +136,26 @@ export function createDesktopFeedback({
/* analytics never in the way */
}
},
- }));
+ };
+ const service = createFeedback(options);
return {
service,
allowed,
- start: () => service.start(),
- stop: () => service.stop(),
+ async start() {
+ await readAccount();
+ service.start();
+ // The queue's own retries see a sign-in or sign-out within one interval.
+ if (!accountTimer && typeof accountId === "function") {
+ accountTimer = setInterval(() => void readAccount(), Math.min(retryEveryMs, 60_000));
+ accountTimer.unref?.();
+ }
+ },
+ stop() {
+ if (accountTimer) clearInterval(accountTimer);
+ accountTimer = null;
+ return service.stop();
+ },
/** IPC omnirushFeedbackPolicy: the policy in force (off when not allowed). */
policy: () => service.policy(),
/** IPC omnirushFeedbackStatus. */
@@ -141,9 +170,10 @@ export function createDesktopFeedback({
* 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) {
+ async offer(input) {
const sessionId = typeof input?.sessionId === "string" && SESSION_RE.test(input.sessionId) ? input.sessionId : null;
if (!sessionId) return null;
+ await readAccount();
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 {
@@ -165,6 +195,7 @@ export function createDesktopFeedback({
*/
async submit(input) {
const value = input && typeof input === "object" ? input : {};
+ await readAccount();
try {
return await /** @type {any} */ (service.submit)({
kind: value.kind,
diff --git a/apps/desktop/electron/feedback-desktop.test.mjs b/apps/desktop/electron/feedback-desktop.test.mjs
index 4cac5cc8..adb08ebb 100644
--- a/apps/desktop/electron/feedback-desktop.test.mjs
+++ b/apps/desktop/electron/feedback-desktop.test.mjs
@@ -13,6 +13,7 @@ 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";
+import { buildNukeManifest } from "./nuke.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const T0 = Date.parse("2026-10-19T09:00:00");
@@ -27,9 +28,9 @@ function tmp() {
/**
* 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]
+ * @param {{ policy?: any, submit?: any, env?: Record<string, string>, packaged?: boolean, devMode?: boolean, userDataPath?: string, now?: () => number, accountId?: () => Promise<string | null> }} [options]
*/
-function desktop({ policy = ON, submit = 201, env = { OMNIRUSH_FEEDBACK: "1" }, packaged = false, devMode = false, userDataPath = tmp(), now = () => T0 } = {}) {
+function desktop({ policy = ON, submit = 201, env = { OMNIRUSH_FEEDBACK: "1" }, packaged = false, devMode = false, userDataPath = tmp(), now = () => T0, accountId = undefined } = {}) {
const calls = [];
const events = [];
/** @type {{ policy: any, submit: any }} */
@@ -55,6 +56,7 @@ function desktop({ policy = ON, submit = 201, env = { OMNIRUSH_FEEDBACK: "1" },
emit: (name, properties) => events.push({ name, properties }),
now,
random: () => 0,
+ ...(accountId ? { accountId } : {}),
});
return { d, calls, events, server, userDataPath };
}
@@ -91,22 +93,22 @@ test("offer: an eligible turn gets the prompt, once per session and once a day",
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");
+ assert.deepEqual(await d.offer({ sessionId: "ses_a", ...OK_TURN }), { kind: "turn" });
+ assert.equal(await d.offer({ sessionId: "ses_a", ...OK_TURN }), null, "once per session");
+ assert.equal(await 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");
+ assert.deepEqual(await 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+");
+ assert.equal(await d.offer({ sessionId: "ses_1", outcome: "ok", toolCalls: 0, durationMs: 5_000 }), null, "no tool, short");
+ assert.equal(await 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(await d.offer({ sessionId: `ses_${outcome}`, ...OK_TURN, outcome }), null, outcome);
+ assert.equal(await d.offer({ sessionId: "bad id!", ...OK_TURN }), null, "a bad session id");
+ assert.deepEqual(await 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 () => {
@@ -119,7 +121,7 @@ test("offer: disabled, 404 or unreachable policy, OMNIRUSH_FEEDBACK=0 or a dev b
])) {
const { d, calls } = desktop(opts);
await d.service.refreshPolicy({ force: true });
- assert.equal(d.offer({ sessionId: "ses_x", ...OK_TURN }), null, label);
+ assert.equal(await 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`);
}
@@ -130,7 +132,7 @@ test("pulse: after pulse_after_sessions sessions, instead of the turn prompt", a
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" });
+ assert.deepEqual(await d.offer({ sessionId: "ses_p2", ...OK_TURN }), { kind: "pulse" });
});
test("shown and submitted: analytics labels only, never the comment", async () => {
@@ -170,14 +172,14 @@ test("submit: a 404 queues it in feedback.json and stops the prompts; a later 20
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");
+ assert.equal(await 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");
+ assert.deepEqual(await 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 () => {
@@ -209,10 +211,46 @@ test("submit: a 429 waits for its Retry-After", async () => {
assert.equal(saved.spool[0].next_at, T0 + 7_200_000);
});
+test("accounts: no offers signed out; queued feedback goes only under the account it was written under", async () => {
+ let who = /** @type {string | null} */ (null);
+ const { d, calls } = desktop({ accountId: async () => who });
+ await d.service.refreshPolicy({ force: true });
+ assert.equal(await d.offer({ sessionId: "ses_out", ...OK_TURN }), null, "signed out: never asks on its own");
+ assert.deepEqual(await d.submit({ kind: "general", categories: ["idea"], comment: "written signed out", trigger: "menu" }), { ok: true, sent: false, queued: true, reason: "signed_out" });
+ who = "acct-a";
+ assert.deepEqual(await d.offer({ sessionId: "ses_a1", ...OK_TURN }), { kind: "turn" }, "signed in: asks");
+ calls.length = 0;
+ await d.service.flush({ force: true });
+ assert.equal(calls.filter((c) => c.path === "/feedback").length, 0, "the one written signed out is never sent");
+ assert.deepEqual(await d.submit({ kind: "general", categories: ["bug"], comment: "from A", trigger: "menu" }), { ok: true, sent: true, queued: false });
+});
+
+test("accounts: an entry queued under A is not sent while B is signed in, and goes once A is back", async () => {
+ let who = /** @type {string | null} */ ("acct-a");
+ const { d, calls, server } = desktop({ submit: "offline", accountId: async () => who });
+ assert.deepEqual(await d.submit({ kind: "general", categories: ["bug"], comment: "A's note", trigger: "menu" }), { ok: true, sent: false, queued: true, reason: "offline" });
+ server.submit = 201;
+ who = "acct-b";
+ await d.submit({ kind: "general", categories: ["idea"], comment: "B's note", trigger: "menu" });
+ calls.length = 0;
+ await d.service.flush({ force: true });
+ assert.ok(calls.every((c) => c.path !== "/feedback" || /** @type {any} */ (c.body).comment !== "A's note"), "A's entry not sent under B");
+ who = "acct-a";
+ await d.submit({ kind: "general", categories: ["praise"], comment: "A again", trigger: "menu" });
+ await d.service.flush({ force: true });
+ assert.ok(calls.some((c) => c.path === "/feedback" && /** @type {any} */ (c.body).comment === "A's note"), "sent once A is back");
+});
+
+test("Reset app data (nuke) removes the whole data folder, feedback.json with it", () => {
+ const userDataPath = "/home/alice/.config/ai.omnirush.desktop";
+ const manifest = buildNukeManifest({ env: {}, homedir: "/home/alice", platform: "linux", userDataPath });
+ assert.ok(manifest.deletePaths.includes(userDataPath));
+});
+
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 });
+ await 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"]);
});
@@ -243,6 +281,7 @@ test("account store: feedbackRequest posts feedback to the account server with t
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("/device/me")) return new Response(JSON.stringify({ id: "3F2504E0-4F89-11D3-9A0C-0305E82C3301", email: "[email protected]", status: "active" }), { status: 200, headers: { "content-type": "application/json" } });
if (u.pathname.endsWith("/feedback") && JSON.parse(String(init.body)).comment === "bad") {
return new Response(JSON.stringify({ detail: "invalid_feedback", errors: { comment: "too long" } }), { status: 422, headers: { "content-type": "application/json" } });
}
@@ -289,6 +328,7 @@ test("account store: feedbackRequest posts feedback to the account server with t
now += 2 * 60_000;
await d.service.flush();
assert.equal(d.status().queued, 0, "the signed-out one went too, at its retry");
+ assert.equal(await store.accountId(), "3f2504e0-4f89-11d3-9a0c-0305e82c3301", "the account from /device/me");
const refused = await store.feedbackRequest("/feedback", { method: "POST", body: { kind: "general", comment: "bad" } });
assert.deepEqual(refused, { status: 422, data: { detail: "invalid_feedback", errors: { comment: "too long" } }, retryAfter: null }, "a 422's body is read");
const limited = await store.feedbackRequest("/feedback", { method: "POST", body: { kind: "general", comment: "limit" } });
diff --git a/apps/desktop/electron/feedback/PARITY.sha256 b/apps/desktop/electron/feedback/PARITY.sha256
index cbee1549..f78c57ef 100644
--- a/apps/desktop/electron/feedback/PARITY.sha256
+++ b/apps/desktop/electron/feedback/PARITY.sha256
@@ -1,3 +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.
-df0b9db1a8e4aab13325a443a570bd38f89f340b78df98ff32b90f8b488013e9 feedback.mjs
+8756de52f755719c7d09565ea811d9c3ce7723e99ca59470a7e762860fda1d2c feedback.mjs
diff --git a/apps/desktop/electron/feedback/feedback.mjs b/apps/desktop/electron/feedback/feedback.mjs
index cbccc257..a4010cd9 100644
--- a/apps/desktop/electron/feedback/feedback.mjs
+++ b/apps/desktop/electron/feedback/feedback.mjs
@@ -28,6 +28,12 @@
// A 2xx or a 4xx that is final (400, 413, 422: the person is told) removes
// it; a 429 waits for its Retry-After (the server's day ends at 00:00 UTC).
//
+// Accounts: with `account` (the signed-in account's id, null when signed
+// out), every queued entry is stamped with the account it was written under
+// and sent only while that account is signed in; one written while no
+// account was known is never sent (it goes after 7 days). Signed out, the
+// app does not ask on its own.
+//
// 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.
@@ -141,6 +147,7 @@ export const TURN_OUTCOMES = Object.freeze(["ok", "refused", "limit", "error", "
/**
* 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.
+ * @param {{ outcome?: string, toolCalls?: number, durationMs?: number }} [turn]
*/
export function turnEligible({ outcome, toolCalls = 0, durationMs = 0 } = {}) {
if (outcome !== "ok") return false;
@@ -400,6 +407,22 @@ export function writeState(file, state) {
* @typedef {(pathAndQuery: string, init: { method?: string, body?: unknown, timeoutMs: number }) => Promise<{ status: number, data: unknown, retryAfter?: number | null } | null>} FeedbackRequest
*/
+/**
+ * @typedef {object} FeedbackOptions
+ * @property {FeedbackRequest | null} [request]
+ * @property {string} [stateFile]
+ * @property {"cli" | "desktop" | "web"} [client]
+ * @property {string} [version]
+ * @property {string} [os]
+ * @property {boolean} [allowed]
+ * @property {() => number} [now]
+ * @property {() => number} [random]
+ * @property {((name: string, properties: Record<string, unknown>) => void) | null} [onEvent]
+ * @property {(level: string, message: string, data?: object) => void} [log]
+ * @property {number} [retryEveryMs]
+ * @property {(() => string | null | undefined) | null} [account]
+ */
+
/**
* The app's feedback. `request(pathAndQuery, { method, body, timeoutMs })`
* is the app's authorized call; it resolves { status, data }, or null when
@@ -407,6 +430,9 @@ export function writeState(file, state) {
* 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.
+ * `account()`: the signed-in account's id or null (queued entries go only
+ * under the account they were written under).
+ * @param {FeedbackOptions} options
*/
export function createFeedback({
request,
@@ -420,8 +446,19 @@ export function createFeedback({
onEvent = null,
log = () => undefined,
retryEveryMs = 5 * 60_000,
+ account = null,
} = {}) {
const ctx = { client, appVersion: version, os };
+ /** The signed-in account (a string), null when signed out; undefined without `account`. */
+ const currentAccount = () => {
+ if (typeof account !== "function") return undefined;
+ try {
+ const id = account();
+ return typeof id === "string" && id ? id : null;
+ } catch {
+ return null;
+ }
+ };
let fetching = null;
let flushing = null;
let timer = null;
@@ -511,7 +548,7 @@ export function createFeedback({
*/
function offerAfterTurn(turn = {}) {
const sessionId = typeof turn.sessionId === "string" && SESSION_RE.test(turn.sessionId) ? turn.sessionId : null;
- if (!allowed || !sessionId || !turnEligible(turn)) return null;
+ if (!allowed || !sessionId || !turnEligible(turn) || currentAccount() === null) return null;
return mutate((s) => {
const p = policy(s);
if (!p.enabled || p.maxPerDay < 1) return null;
@@ -550,6 +587,8 @@ export function createFeedback({
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 };
+ const owner = currentAccount();
+ if (owner !== undefined) entry.account = owner;
mutate((s) => {
s.spool = [...s.spool, entry].slice(-SPOOL_MAX);
});
@@ -559,7 +598,9 @@ export function createFeedback({
const refused = outcome.refused[entry.id];
if (refused) return { ok: false, error: refused.status === 413 ? "too_large" : "invalid", errors: refused.errors };
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" };
+ if (sent) return { ok: true, sent: true, queued: false };
+ const queued = outcome.kept.includes(entry.id) || read().spool.some((e) => e.id === entry.id);
+ return { ok: true, sent: false, queued, reason: outcome.reasons[entry.id] ?? (owner === null ? "signed_out" : "offline") };
}
/** Send what is queued and due (or just `only`; `force`: also what waits for its retry, the person asked). */
@@ -572,10 +613,13 @@ export function createFeedback({
const result = { sent: [], kept: [], reasons: {}, refused: {} };
if (typeof request !== "function") return result;
const at = now();
+ const me = currentAccount();
+ // Another account's entry (or one written signed out) is not this account's to send.
+ const mine = (e) => me === undefined || (typeof me === "string" && e.account === me);
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));
+ const picked = s.spool.filter((e) => (only ? e.id === only : true) && mine(e) && (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 }));
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 3b236283..f3094a18 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -1423,17 +1423,17 @@ const desktopPlacements = createDesktopPlacements({
// policy turns it on. Its two analytics events go to the window's analytics.
const desktopFeedback = createDesktopFeedback({
request: (pathAndQuery, init) => omnirushAccountStore.feedbackRequest(pathAndQuery, init),
+ accountId: () => omnirushAccountStore.accountId(),
userDataPath: app.getPath("userData"),
version: app.getVersion(),
packaged: app.isPackaged,
devMode: isDevMode,
+ // Only the app window (never a browser panel or a preview window).
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 */
- }
+ try {
+ if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) mainWindow.webContents.send(FEEDBACK_EVENT_CHANNEL, { name, properties });
+ } catch {
+ /* closing */
}
},
});
@@ -3500,7 +3500,7 @@ or use: pnpm dev:worktree`);
const win = await createMainWindow();
// In the background: the window never waits for it.
desktopPlacements.start();
- desktopFeedback.start();
+ void 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 1500acfa..73cb09a7 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -672,6 +672,8 @@ export function createDesktopOmniRushAccountStore({
* server-driven sign-out lands afterwards.
*/
async function save(credentials) {
+ // A new or renewed sign-in: the account is read again (accountId).
+ knownAccountId = null;
const normalized = validCredentials(credentials);
if (!normalized) throw new Error("Invalid OmniRush account credential bundle");
if (clearInFlight) {
@@ -988,6 +990,30 @@ export function createDesktopOmniRushAccountStore({
* expired while the app was idle, so a second one is allowed before the
* session counts as gone.
*/
+ /** The signed-in account's id (from /device/me), remembered until the sign-in changes. */
+ let knownAccountId = null;
+
+ /**
+ * The signed-in account's opaque id, or null when signed out or unknown
+ * (feedback-desktop.mjs: queued feedback goes only under its account).
+ * @returns {Promise<string | null>}
+ */
+ async function accountId() {
+ const credentials = await load().catch(() => null);
+ if (!credentials) {
+ knownAccountId = null;
+ return null;
+ }
+ if (knownAccountId) return knownAccountId;
+ try {
+ const profile = await fetchProfile(credentials, 1);
+ knownAccountId = profile?.accountId ?? null;
+ } catch {
+ return null;
+ }
+ return knownAccountId;
+ }
+
async function fetchProfile(credentials, refreshesLeft = 2, sessionId = null) {
const profileUrl = controlPlaneBase(credentials.gatewayUrl);
profileUrl.pathname += "/device/me";
@@ -1427,6 +1453,7 @@ export function createDesktopOmniRushAccountStore({
* @returns {Promise<SignOutOutcome>}
*/
async function clear({ revokeRemote = true } = {}) {
+ knownAccountId = null;
// Claim the gate first (synchronously, so no persist slips in), then wait
// for a rotation still in flight: signing out under it would revoke a
// retired token (the live session survives) or let its persist land
@@ -1476,5 +1503,6 @@ export function createDesktopOmniRushAccountStore({
buildathonTagSession,
placementsRequest,
feedbackRequest,
+ accountId,
};
}