A desktop coding agent with free access to frontier models.
TypeScript
fix: show refused feedback inline
Samrat Talukdar9db38057a5ea
diff --git a/apps/app/src/app/lib/in-app-feedback.ts b/apps/app/src/app/lib/in-app-feedback.tsindex d8c9468b..4b73efc9 100644--- a/apps/app/src/app/lib/in-app-feedback.ts+++ b/apps/app/src/app/lib/in-app-feedback.ts@@ -54,6 +54,7 @@ export const SENT_TOAST = "Thanks, sent.";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";/** 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";@@ -148,6 +149,9 @@ export type TurnPrompt = {rating: "up" | "down" | number | null;reasons: TurnReasonId[];comment: string;+ /** The server refused the last Send (shown inline; the prompt stays). */+ error: string | null;+ sending: boolean;};export type FeedbackDialogState = {@@ -160,6 +164,8 @@ export type FeedbackDialogState = {/** null: the default for the category (on for Bug); true/false: the person's own choice. */includeSession: boolean | null;sending: boolean;+ /** The server refused the last Send (shown inline; the text stays). */+ error: string | null;};type FeedbackState = {@@ -167,7 +173,7 @@ type FeedbackState = {dialog: FeedbackDialogState;};-const closedDialog: FeedbackDialogState = { open: false, trigger: "menu", sessionId: null, category: "bug", text: "", includeSession: null, sending: false };+const closedDialog: FeedbackDialogState = { open: false, trigger: "menu", sessionId: null, category: "bug", text: "", includeSession: null, sending: false, error: null };export const useFeedbackStore = create<FeedbackState>(() => ({ prompt: null, dialog: closedDialog }));@@ -209,6 +215,19 @@ export function setFeedbackBridgeForTests(next: Bridge | null): void {useFeedbackStore.setState({ prompt: null, dialog: closedDialog });}+/**+ * Why the server refused a send, for the person to fix: a 422 names its+ * fields ("Couldn't send: comment: too long"), a 413 is too long. Null when+ * it was sent or kept for later.+ */+export function refusalText(result: OmniRushFeedbackResult): string | null {+ if (result.ok) return null;+ if (result.error === "too_large") return TOO_LARGE_ERROR;+ if (result.error !== "invalid") return null;+ const fields = Object.entries(result.errors ?? {}).filter(([, why]) => typeof why === "string").map(([field, why]) => `${field}: ${why}`);+ return fields.length ? `Couldn't send: ${fields.join("; ")}` : "Couldn't send: the server did not accept it";+}+/** 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;@@ -271,6 +290,8 @@ export async function offerFeedbackAfterTurn(input: {rating: null,reasons: [],comment: "",+ error: null,+ sending: false,},});void bridge.shown({ kind: offer.kind }).catch(() => undefined);@@ -312,16 +333,33 @@ export function toggleTurnReason(id: TurnReasonId) {}export function setPromptComment(comment: string) {- setPrompt({ comment: comment.slice(0, COMMENT_MAX) });+ setPrompt({ comment: comment.slice(0, COMMENT_MAX), error: null });}-/** Send, or Skip (the rating alone, without reasons or comment). Without a rating the prompt just goes. */+/**+ * Send, or Skip (the rating alone, without reasons or comment). Without a+ * rating the prompt just goes. A refusal (422 / 413) keeps the prompt open+ * with its reason, so the comment can be fixed.+ */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;+ if (!prompt || prompt.rating === null) {+ useFeedbackStore.setState({ prompt: null });+ return null;+ }+ if (prompt.sending) return null;const input = skip ? { ...promptInput(prompt), categories: [], comment: null } : promptInput(prompt);- return send(input);+ setPrompt({ sending: true, error: null });+ const result = await send(input, { toast: false });+ const refused = refusalText(result);+ const current = useFeedbackStore.getState().prompt;+ if (refused && current?.sessionId === prompt.sessionId && current.messageId === prompt.messageId) {+ setPrompt({ sending: false, error: refused });+ return result;+ }+ if (current?.sessionId === prompt.sessionId && current.messageId === prompt.messageId) useFeedbackStore.setState({ prompt: null });+ notify(result);+ return result;}/**@@ -332,7 +370,8 @@ export async function sendPrompt({ skip = false } = {}): Promise<OmniRushFeedbacexport function closePrompt(): Promise<OmniRushFeedbackResult | null> {const prompt = useFeedbackStore.getState().prompt;useFeedbackStore.setState({ prompt: null });- if (!prompt || prompt.rating === null) return Promise.resolve(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 });}@@ -366,7 +405,7 @@ export function setDialogCategory(category: GeneralCategoryId) {}export function setDialogText(text: string) {- setDialog({ text });+ setDialog({ text, error: null });}export function setDialogIncludeSession(include: boolean) {@@ -390,7 +429,7 @@ export async function sendFeedbackDialog(): Promise<OmniRushFeedbackResult | nuleffort: null,});if (result.ok) useFeedbackStore.setState({ dialog: closedDialog });- else setDialog({ sending: false });+ else setDialog({ sending: false, error: refusalText(result) ?? "Couldn't send. Try again." });return result;}diff --git a/apps/app/src/react-app/domains/feedback/feedback.tsx b/apps/app/src/react-app/domains/feedback/feedback.tsxindex 2d834be1..e821b8f5 100644--- a/apps/app/src/react-app/domains/feedback/feedback.tsx+++ b/apps/app/src/react-app/domains/feedback/feedback.tsx@@ -192,9 +192,12 @@ function CommentRow(props: { prompt: TurnPrompt; placeholder: string; onComment: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>+ <Button size="sm" className="h-8" onClick={props.onSend} disabled={props.prompt.sending} data-testid="feedback-send">Send</Button>+ <Button size="sm" variant="ghost" className="h-8 text-muted-foreground" onClick={props.onSkip} disabled={props.prompt.sending} data-testid="feedback-skip">Skip</Button></div>+ {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></>);@@ -356,6 +359,9 @@ export function FeedbackFormView(props: FeedbackFormViewProps) {className="min-h-24"data-testid="feedback-text"/>+ {dialog.error ? (+ <p role="alert" className="text-[13px] text-destructive" data-testid="feedback-dialog-error">{dialog.error}</p>+ ) : null}{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)} />diff --git a/apps/app/tests/in-app-feedback.test.tsx b/apps/app/tests/in-app-feedback.test.tsxindex 9883e21d..63786554 100644--- a/apps/app/tests/in-app-feedback.test.tsx+++ b/apps/app/tests/in-app-feedback.test.tsx@@ -163,6 +163,53 @@ describe("in-app feedback: after a turn", () => {});});+describe("in-app feedback: refusals (422 / 413)", () => {+ test("the words: the fields a 422 names, a 413 too long, nothing for sent or queued", () => {+ expect(lib.refusalText({ ok: false, error: "invalid", errors: { comment: "too long", turn: "must be an integer" } })).toBe("Couldn't send: comment: too long; turn: must be an integer");+ expect(lib.refusalText({ ok: false, error: "invalid", errors: null })).toBe("Couldn't send: the server did not accept it");+ expect(lib.refusalText({ ok: false, error: "too_large" })).toBe("That's too long to send");+ expect(lib.refusalText({ ok: true, sent: true, queued: false })).toBeNull();+ expect(lib.refusalText({ ok: true, sent: false, queued: true, reason: "offline" })).toBeNull();+ });++ test("the follow-up: a 422 keeps the prompt open with its reason and the comment; no toast", async () => {+ const main = fakeMain({ kind: "turn" }, { ok: false, error: "invalid", errors: { comment: "too long" } });+ await lib.offerFeedbackAfterTurn({ sessionId: "ses_1", turn: TURN, fallbackDurationMs: 0, modelId: null, effort: null });+ lib.rateTurn("down");+ lib.setPromptComment("way too much");+ await lib.sendPrompt();+ expect(main.submitted).toHaveLength(1);+ expect(lib.useFeedbackStore.getState().prompt).toMatchObject({ rating: "down", comment: "way too much", error: "Couldn't send: comment: too long", sending: false });+ expect(main.toasts).toEqual([]);+ lib.setPromptComment("shorter");+ expect(lib.useFeedbackStore.getState().prompt?.error).toBeNull();+ });++ test("the dialog: a 422 or 413 keeps it open with the text and the reason", async () => {+ fakeMain(null, { ok: false, error: "invalid", errors: { comment: "too long" } });+ lib.openFeedbackDialog({ trigger: "menu", sessionId: null });+ lib.setDialogText("a long note");+ await lib.sendFeedbackDialog();+ expect(lib.useFeedbackStore.getState().dialog).toMatchObject({ open: true, text: "a long note", error: "Couldn't send: comment: too long", sending: false });+ fakeMain(null, { ok: false, error: "too_large" });+ lib.openFeedbackDialog({ trigger: "menu", sessionId: null });+ lib.setDialogText("huge");+ await lib.sendFeedbackDialog();+ expect(lib.useFeedbackStore.getState().dialog.error).toBe("That's too long to send");+ });++ test("the views show the reason", () => {+ const noop = () => undefined;+ 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'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 form = renderToStaticMarkup(<FeedbackFormView dialog={dialog} onCategory={noop} onText={noop} onIncludeSession={noop} onSend={noop} onCancel={noop} />);+ expect(form).toContain("That's too long to send");+ expect(form).toContain('role="alert"');+ });+});+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();@@ -229,7 +276,7 @@ describe("in-app feedback: analytics", () => {});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 base = { sessionId: "ses_1", kind: "turn" as const, stage: "rate" as const, turn: 2, messageId: "a2", modelId: null, effort: null, rating: null, reasons: [], comment: "", error: null, sending: false };const noop = () => undefined;const handlers = { onRate: noop, onPulse: noop, onToggleReason: noop, onComment: noop, onSend: noop, onSkip: noop, onDismiss: noop };@@ -284,7 +331,7 @@ 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 };+ const dialog = { open: true, trigger: "menu" as const, sessionId: "ses_open", category: "bug" as const, text: "", includeSession: null, sending: false, error: null };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}"`);diff --git a/apps/desktop/electron/feedback-desktop.test.mjs b/apps/desktop/electron/feedback-desktop.test.mjsindex a066d8d7..4cac5cc8 100644--- a/apps/desktop/electron/feedback-desktop.test.mjs+++ b/apps/desktop/electron/feedback-desktop.test.mjs@@ -1,6 +1,6 @@// 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+// the account store's feedbackRequest). The CLI covers the same rules with its// own launcher.import assert from "node:assert/strict";import { createHash } from "node:crypto";@@ -41,7 +41,8 @@ function desktop({ policy = ON, submit = 201, env = { OMNIRUSH_FEEDBACK: "1" },if (p === "/feedback") {if (server.submit === "offline") throw new Error("ECONNREFUSED");if (server.submit === "signed_out") return null;- return { status: server.submit, data: null };+ if (typeof server.submit === "object") return server.submit;+ return { status: server.submit, data: server.submit === 201 ? { ok: true } : null, retryAfter: null };}return { status: 404, data: null };},@@ -188,6 +189,26 @@ test("submit: offline, signed out and 429 are kept for later with their reason",}});+test("submit: a 422 names the wrong fields and a 413 is too large; neither is queued", async () => {+ const { d, server } = desktop({ submit: { status: 422, data: { detail: "invalid_feedback", errors: { comment: "too long" } }, retryAfter: null } });+ const r = await d.submit({ kind: "general", categories: ["bug"], comment: "x", trigger: "menu" });+ assert.deepEqual(r, { ok: false, error: "invalid", errors: { comment: "too long" } });+ assert.equal(d.status().queued, 0, "not kept: the person is told");+ server.submit = { status: 413, data: { detail: "feedback_too_large" }, retryAfter: null };+ const big = await d.submit({ kind: "general", categories: ["bug"], comment: "y", trigger: "menu" });+ assert.equal(big.ok, false);+ assert.equal(/** @type {any} */ (big).error, "too_large");+ assert.equal(d.status().queued, 0);+});++test("submit: a 429 waits for its Retry-After", async () => {+ const { d, userDataPath } = desktop({ submit: { status: 429, data: { detail: "feedback_rate_limited" }, retryAfter: 7_200 } });+ const r = await d.submit({ kind: "turn", rating: "up", sessionId: "ses_r", turn: 1, trigger: "sampled" });+ assert.deepEqual(r, { ok: true, sent: false, queued: true, reason: "rate_limited" });+ const saved = JSON.parse(fs.readFileSync(path.join(userDataPath, "feedback.json"), "utf8"));+ assert.equal(saved.spool[0].next_at, T0 + 7_200_000);+});+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 });@@ -201,7 +222,7 @@ test("wiring: main.mjs handlers, the preload's event channel, the bridge and thefor (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, /omnirushAccountStore\.feedbackRequest\(pathAndQuery, init\)/);assert.match(main, /desktopFeedback\.start\(\)/);assert.match(main, /desktopFeedback\.stop\(\)/);const preload = fs.readFileSync(path.join(here, "preload.mjs"), "utf8");@@ -212,7 +233,7 @@ test("wiring: main.mjs handlers, the preload's event channel, the bridge and theassert.ok(renderer.includes(`"${EVENT_CHANNEL}"`));});-test("account store: clientRequest posts feedback to the account server with the device credential (renewed on a 401)", async () => {+test("account store: feedbackRequest 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));@@ -222,6 +243,12 @@ test("account store: clientRequest posts feedback to the account server with theif (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") && 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" } });+ }+ if (u.pathname.endsWith("/feedback") && JSON.parse(String(init.body)).comment === "limit") {+ return new Response(JSON.stringify({ detail: "feedback_rate_limited" }), { status: 429, headers: { "content-type": "application/json", "retry-after": "5400" } });+ }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" } });};@@ -243,7 +270,7 @@ test("account store: clientRequest posts feedback to the account server with the});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 d = createDesktopFeedback({ request: (p, init) => store.feedbackRequest(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");@@ -262,4 +289,9 @@ test("account store: clientRequest posts feedback to the account server with thenow += 2 * 60_000;await d.service.flush();assert.equal(d.status().queued, 0, "the signed-out one went too, at its retry");+ 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" } });+ assert.deepEqual(limited, { status: 429, data: { detail: "feedback_rate_limited" }, retryAfter: 5400 }, "Retry-After in seconds");+ assert.deepEqual(await d.submit({ kind: "general", categories: ["bug"], comment: "bad", trigger: "menu" }), { ok: false, error: "invalid", errors: { comment: "too long" } });});diff --git a/apps/desktop/electron/feedback/PARITY.sha256 b/apps/desktop/electron/feedback/PARITY.sha256index 95126e4a..cbee1549 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.-667c049238433b39be32d54796ae78b585e9478660521ef9ec734dc9c4a38e88 feedback.mjs+df0b9db1a8e4aab13325a443a570bd38f89f340b78df98ff32b90f8b488013e9 feedback.mjsdiff --git a/apps/desktop/electron/feedback/feedback.mjs b/apps/desktop/electron/feedback/feedback.mjsindex caa04c80..cbccc257 100644--- a/apps/desktop/electron/feedback/feedback.mjs+++ b/apps/desktop/electron/feedback/feedback.mjs@@ -25,7 +25,8 @@// 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.+// 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).//// Nothing here touches sessions, prompts, the model, files or uploads, and// the comment never goes to analytics (analyticsProperties). Node builtins@@ -92,7 +93,13 @@ 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}$/;+/** The server's rule for `session_id`: ses_… or the CLI's session UUID. */+const PAYLOAD_SESSION_RE = /^(?:ses_[A-Za-z0-9_]{1,124}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;+const LABEL_RE = /^[A-Za-z0-9._:/@+-]+$/;+/** The server's longest app_version, os, model_id, effort. */+export const FIELD_MAX = Object.freeze({ app_version: 64, os: 64, model_id: 128, effort: 32 });+/** After a 429: its Retry-After, at most this long. */+const MAX_RETRY_AFTER_MS = 26 * 3_600_000;// --- policy -----------------------------------------------------------------@@ -156,19 +163,24 @@ export function looksLikeRefusal(text) {// eslint-disable-next-line no-control-regexconst 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. */+/** The comment as sent: trimmed, at most COMMENT_MAX UTF-16 units (the server counts JavaScript's .length, a pair is never cut); 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();+ if (text.length <= COMMENT_MAX) return text;+ let cut = text.slice(0, COMMENT_MAX);+ // Never half a surrogate pair at the end.+ if (/[\ud800-\udbff]$/.test(cut)) cut = cut.slice(0, -1);+ return cut.trimEnd();}-function label(value) {- return typeof value === "string" && LABEL_RE.test(value.trim()) ? value.trim() : null;+function label(value, max = 64) {+ if (typeof value !== "string") return null;+ const v = value.trim();+ return v && v.length <= max && LABEL_RE.test(v) ? v : null;}/** "0-10 pulse" bucket: promoter (9-10), passive (7-8), detractor (0-6). */@@ -201,7 +213,7 @@ export function buildPayload(input = {}, ctx = {}) {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 sessionId = typeof input.sessionId === "string" && PAYLOAD_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 {@@ -214,10 +226,10 @@ export function buildPayload(input = {}, ctx = {}) {turn: sessionId ? turn : null,trigger,client,- app_version: label(ctx.appVersion) ?? "0",+ app_version: label(ctx.appVersion, FIELD_MAX.app_version) ?? "0",os: ["win", "mac", "linux"].includes(ctx.os) ? ctx.os : osName(),- model_id: label(input.modelId),- effort: label(input.effort),+ model_id: label(input.modelId, FIELD_MAX.model_id),+ effort: label(input.effort, FIELD_MAX.effort),},};}@@ -385,7 +397,7 @@ export function writeState(file, state) {// --- the app's feedback -----------------------------------------------------/**- * @typedef {(pathAndQuery: string, init: { method?: string, body?: unknown, timeoutMs: number }) => Promise<{ status: number, data: unknown } | null>} FeedbackRequest+ * @typedef {(pathAndQuery: string, init: { method?: string, body?: unknown, timeoutMs: number }) => Promise<{ status: number, data: unknown, retryAfter?: number | null } | null>} FeedbackRequest*//**@@ -529,7 +541,9 @@ export function createFeedback({/*** Send one feedback (queued first). Resolves { ok: true, sent, queued,- * reason? } or { ok: false, error } when the input cannot be sent.+ * reason? } or { ok: false, error, errors? } when it cannot be sent (the+ * input, or the server refused it: error "invalid" with its 422 `errors`+ * by field, or "too_large" for a 413; not queued).* `reason` when queued: offline | signed_out | unavailable | rate_limited.*/async function submit(input = {}) {@@ -542,6 +556,8 @@ export function createFeedback({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 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" };}@@ -550,10 +566,10 @@ export function createFeedback({async function flush({ only = null, force = false } = {}) {if (flushing) {await flushing.catch(() => undefined);- if (!only) return { sent: [], kept: [], reasons: {} };+ if (!only) return { sent: [], kept: [], reasons: {}, refused: {} };}const run = (async () => {- const result = { sent: [], kept: [], reasons: {} };+ const result = { sent: [], kept: [], reasons: {}, refused: {} };if (typeof request !== "function") return result;const at = now();const due = mutate((s) => {@@ -581,7 +597,12 @@ export function createFeedback({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 });+ if (final) {+ log("warn", "feedback: the server refused one", { status });+ const errors = answer?.data && typeof answer.data === "object" && answer.data.errors && typeof answer.data.errors === "object" ? answer.data.errors : null;+ result.refused[entry.id] = { status, errors };+ }+ const retryAfterMs = Number.isFinite(answer?.retryAfter) && answer.retryAfter > 0 ? Math.min(MAX_RETRY_AFTER_MS, answer.retryAfter * 1_000) : null;mutate((s) => {if (done || final) {s.spool = s.spool.filter((e) => e.id !== entry.id);@@ -594,7 +615,7 @@ export function createFeedback({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);+ kept.next_at = now() + (status === 429 ? retryAfterMs ?? RATE_LIMIT_RETRY_MS : status === 404 ? Math.min(RATE_LIMIT_RETRY_MS, backoff) : backoff);});if (done) {result.sent.push(entry.id);diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex ed37315f..3b236283 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -1422,7 +1422,7 @@ const desktopPlacements = createDesktopPlacements({// 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),+ request: (pathAndQuery, init) => omnirushAccountStore.feedbackRequest(pathAndQuery, init),userDataPath: app.getPath("userData"),version: app.getVersion(),packaged: app.isPackaged,diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex 86e6ff81..1500acfa 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -1322,8 +1322,7 @@ export function createDesktopOmniRushAccountStore({}/**- * One sponsored-placements or feedback call (placements-desktop.mjs,- * feedback-desktop.mjs as `clientRequest`): `pathAndQuery`+ * One sponsored-placements call (placements-desktop.mjs): `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.@@ -1343,6 +1342,30 @@ export function createDesktopOmniRushAccountStore({return { status: response.status, data };}+ /**+ * One in-app feedback call (feedback-desktop.mjs): like placementsRequest,+ * but `data` is the JSON of any answer (a 422 names its wrong fields) and+ * `retryAfter` the Retry-After seconds (a 429 lasts until 00:00 UTC), or+ * null. Resolves null while signed out; throws on network errors and+ * timeouts.+ * @param {string} pathAndQuery+ * @param {{ method?: string, body?: unknown, timeoutMs?: number }} [init]+ * @returns {Promise<{ status: number, data: any, retryAfter: number | null } | null>}+ */+ async function feedbackRequest(pathAndQuery, { method = "GET", body = undefined, timeoutMs = 2_000 } = {}) {+ const [pathname, query = ""] = String(pathAndQuery).split("?");+ const response = await sendAuthorized(`${pathname}`, {+ method,+ ...(body !== undefined ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}),+ signal: AbortSignal.timeout(timeoutMs),+ }, 1, undefined, query);+ if (!response) return null;+ const data = await response.json().catch(() => null);+ const header = response.headers.get("retry-after");+ const seconds = header !== null && header.trim() !== "" ? Number(header) : NaN;+ return { status: response.status, data, retryAfter: Number.isFinite(seconds) && seconds >= 0 ? seconds : null };+ }+/*** Join the event from the app (POST /me/buildathon/join; only offered when* the promo says `join: true`). The answer is the enrolled status.@@ -1452,7 +1475,6 @@ export function createDesktopOmniRushAccountStore({buildathonJoin,buildathonTagSession,placementsRequest,- /** The same call for the other small client endpoints (feedback-desktop.mjs). */- clientRequest: placementsRequest,+ feedbackRequest,};}diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 2c396faa..94c630cb 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -439,10 +439,15 @@ export type OmniRushFeedbackInput = {modelId: string | null;effort: string | null;};-/** queued: kept in feedback.json and sent later (offline, signed out, the server has none yet, rate limited). */+/**+ * queued: kept in feedback.json and sent later (offline, signed out, the+ * server has none yet, rate limited). ok false: not sent and not kept: the+ * input ("comment", "kind", "rating"), or the server refused it ("invalid":+ * a 422 with its wrong fields in `errors`; "too_large": a 413).+ */export type OmniRushFeedbackResult =| { ok: true; sent: boolean; queued: boolean; reason?: "offline" | "signed_out" | "unavailable" | "rate_limited" }- | { ok: false; error: string };+ | { ok: false; error: string; errors?: Record<string, string> | null };export type OmniRushFeedbackStatus = { policy: OmniRushFeedbackPolicy; queued: number; unavailable: boolean; allowed: boolean };export type OmniRushSessionStatus = {