A desktop coding agent with free access to frontier models.
TypeScript
feat: server checklist and finish guard
ogsamratd87b41909a1c
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 54adcf2c..d7b0a68b 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -784,6 +784,7 @@ const {omnirushAccountStatus,omnirushQualityDetails,omnirushQualitySpins,+ omnirushSessionStatus,omnirushQualitySpin,omnirushAccountConnect,omnirushAccountSignOut,@@ -847,6 +848,7 @@ export {omnirushAccountStatus,omnirushQualityDetails,omnirushQualitySpins,+ omnirushSessionStatus,omnirushQualitySpin,omnirushAccountConnect,omnirushAccountSignOut,diff --git a/apps/app/src/app/lib/good-session.ts b/apps/app/src/app/lib/good-session.tsindex 7781b31e..b0b3f64e 100644--- a/apps/app/src/app/lib/good-session.ts+++ b/apps/app/src/app/lib/good-session.ts@@ -31,6 +31,7 @@// desktop's own part is `messageFacts` (the transcript as tool calls).import type { UIMessage } from "ai";+import type { OmniRushSessionStatus } from "@omnirush/types/desktop-ipc";export const GOOD_SESSION_LABEL = "Good session ★";/** All local checks pass; the server decides after upload. */@@ -53,11 +54,29 @@ export const WSL_BANNER_TEXT = "Sessions from native Windows don't count as Goodexport const TURN_GUARD_TITLE = "A turn is still running.";export const TURN_GUARD_DETAIL = `Quit now and this session won't count as a ${GOOD_SESSION_LABEL}.`;export const TURN_GUARD_MESSAGE = `${TURN_GUARD_TITLE} ${TURN_GUARD_DETAIL}`;-export const TURN_GUARD_WAIT = "Wait for it";+/** Keeps the app open and lets the running turn finish. */+export const TURN_GUARD_WAIT = "Finish it";export const TURN_GUARD_QUIT = "Quit anyway";export const NUDGE_TITLE = `Not a ${GOOD_SESSION_LABEL} yet`;+/** The finish guard (M4b): no turn runs, but the last one needs finishing. */+export type FinishGuardKind = "awaiting" | "cut";+export const FINISH_GUARD_TITLE = "This session is one step from counting.";+export const FINISH_GUARD_DETAIL: Readonly<Record<FinishGuardKind, string>> = Object.freeze({+ awaiting: "The agent asked you a question. Answer it (or tell it to go ahead) and let the turn finish, or this session won't pass the quality check.",+ cut: "The last turn stopped before it finished. Send \"continue\" and let it finish, or this session won't pass the quality check.",+});+export const FINISH_GUARD_FINISH = "Finish it";+export const FINISH_GUARD_QUIT = "Quit anyway";+/** What "Finish it" puts in the composer (editable, not sent). */+export const FINISH_GUARD_PROMPT: Readonly<Record<FinishGuardKind, string>> = Object.freeze({+ awaiting: "Go ahead.",+ cut: "Continue and finish the task.",+});+/** The desktop's "Finish it" ({ sessionId, kind }), from the native dialog (turn-guard.mjs) or the in-app one. */+export const FINISH_GUARD_EVENT = "omnirush:finish-guard:finish";+/*** Server texts that still say "replay-ready ★" (older servers): users read* "Good session ★" everywhere.@@ -454,10 +473,12 @@ function toolUrl(input: Record<string, unknown>): string {// --- The checklist -----------------------------------------------------------export type GoodSessionCheckId = "code" | "ran" | "project" | "finished" | "windows";-export type GoodSessionCheckState = "pass" | "fail" | "pending";+/** "warn" comes from the server only. */+export type GoodSessionCheckState = "pass" | "fail" | "warn" | "pending";export type GoodSessionCheck = {- id: GoodSessionCheckId;+ /** A GoodSessionCheckId locally; the server's ids may grow. */+ id: string;state: GoodSessionCheckState;/** "code changed", "ran/tested", "in project", "finish your turn". */label: string;@@ -488,8 +509,12 @@ export type GoodSessionInput = {workspaceRoot?: string;/** A turn is running (busy, retrying, waiting on a question or a permission). */turnRunning?: boolean;- /** "pass": the last message is an answer with no session error and no unfinished tool call. */- lastTurn?: "pass" | "cut";+ /**+ * "pass": the last turn ended on an answer (no error, no unfinished tool,+ * text after the last tool call, a good finish reason); "awaiting": that+ * answer asks the user something; "cut": anything else.+ */+ lastTurn?: LastTurn;/** Native Windows (not WSL). */nativeWindows?: boolean;/** Remote workspaces do not necessarily have a local project folder. */@@ -561,7 +586,7 @@ export function goodSessionChecklist({const codeShort = fileCount < FLOOR_FILES? ` (${fileCount} of ${FLOOR_FILES} files)`: lines < FLOOR_LINES ? ` (${lines} of ${FLOOR_LINES} lines)` : "";- const finished = turnRunning ? "pending" : lastTurn === "pass" ? "pass" : "cut";+ const finished = turnRunning ? "pending" : lastTurn;const noRoot = !isRemoteWorkspace && unknownRoot && calls.some((call) => !call.notRun);const checks: GoodSessionCheck[] = [{@@ -598,13 +623,17 @@ export function goodSessionChecklist({},{id: "finished",- state: finished === "cut" ? "fail" : finished,- label: finished === "pending" ? "finish your turn" : finished === "pass" ? "turn finished" : "last turn cut off",+ state: finished === "pending" || finished === "pass" ? finished : "fail",+ label: finished === "pending"+ ? "finish your turn"+ : finished === "pass" ? "turn finished" : finished === "awaiting" ? "answer the agent" : "last turn cut off",hint: finished === "pending"? "Let the turn finish: quitting or stopping now cuts it off.": finished === "pass"? "The last turn finished."- : "The last turn stopped before it finished: send a follow-up and let it finish.",+ : finished === "awaiting"+ ? "The agent asked you a question: answer it (or tell it to go ahead) and let the turn finish."+ : "The last turn stopped before it finished: send a follow-up and let it finish.",},];if (nativeWindows) {@@ -618,7 +647,7 @@ export function goodSessionChecklist({function mark(check: GoodSessionCheck): string {if (check.state === "pending") return check.label;- return `${check.label} ${check.state === "pass" ? "✓" : "✗"}`;+ return `${check.label} ${check.state === "pass" ? "✓" : check.state === "warn" ? "!" : "✗"}`;}/** The checklist's heading: the filled ★ only on the server's word. */@@ -645,60 +674,159 @@ export function shouldNudge({ wasRunning, running, checklist, alreadyNudged }: {return Boolean(wasRunning && !running && !alreadyNudged && (checklist?.missing?.length ?? 0) > 0);}-// --- The don't-quit-mid-turn guard --------------------------------------------+// --- The don't-quit-mid-turn guard and the finish guard ---------------------------export type QuitGuard = {readonly state: "idle" | "asking" | "waiting";- request(input?: { running?: boolean; interactive?: boolean; hangup?: boolean }): "quit" | "ask";+ request(input?: { running?: boolean; interactive?: boolean; hangup?: boolean; finish?: string | null }): "quit" | "ask" | "finish";answer(wait: boolean): "wait" | "quit";+ askedAbout(finish: string): boolean;turnEnded(): boolean;};/**- * `request({ running, interactive, hangup })` answers "quit" (go ahead) or- * "ask" (show TURN_GUARD_MESSAGE with "Wait for it" / "Quit anyway"). The- * first quit request while a turn runs asks; a second one, whatever the- * answer, quits. `answer(wait)` takes the user's choice; `turnEnded()`- * re-arms the guard for the next turn and says whether the user was waiting.- * Headless runs and a closed terminal (hangup) never ask.+ * `request({ running, interactive, hangup, finish })` answers "quit" (go+ * ahead), "ask" (a turn runs: TURN_GUARD_MESSAGE with "Wait for it" / "Quit+ * anyway") or "finish" (`finish`, a "<session>:<state>" key: the finish+ * guard's "Finish it" / "Quit anyway"). The first quit request while a turn+ * runs asks; a second one, whatever the answer, quits. Each finish key asks+ * once, ever. `answer(wait)` takes the user's choice; `turnEnded()` re-arms+ * the running-turn question for the next turn and says whether the user was+ * waiting. Headless runs and a closed terminal (hangup) never ask.*/export function createQuitGuard(): QuitGuard {let state: "idle" | "asking" | "waiting" = "idle";+ let askingFinish = false;+ const asked = new Set<string>();return {get state() {return state;},- request({ running = false, interactive = true, hangup = false } = {}) {- if (!interactive || hangup || !running) return "quit";- if (state === "idle") {+ request({ running = false, interactive = true, hangup = false, finish = null } = {}) {+ if (!interactive || hangup) return "quit";+ if (running) {+ if (state === "idle") {+ state = "asking";+ askingFinish = false;+ return "ask";+ }+ return "quit";+ }+ if (finish && state !== "asking" && !asked.has(finish)) {+ asked.add(finish);state = "asking";- return "ask";+ askingFinish = true;+ return "finish";}return "quit";},answer(wait) {if (state !== "asking") return wait ? "wait" : "quit";+ if (askingFinish) {+ // Asked once for this state: the next request quits, and a new turn asks as usual.+ askingFinish = false;+ state = "idle";+ return wait ? "wait" : "quit";+ }if (wait) {state = "waiting";return "wait";}return "quit";},+ askedAbout(finish) {+ return asked.has(finish);+ },turnEnded() {const was = state;state = "idle";+ askingFinish = false;return was === "waiting" || was === "asking";},};}+// --- How the last turn ended (session_qc._completion) ------------------------------++/** An answer that asks the user something (session_qc.AWAITING_USER, on the last 400 characters). */+const AWAITING_USER = /(would you like|do you want|should i|shall i|let me know|which (one|option)|can you (confirm|clarify|provide)|please (confirm|clarify|provide))[^.]*\?\s*$/i;+const MENU_ITEM = /^[ \t]*(?:\*\*)?\(?\d{1,2}[.)]/;+const MENU_ITEM_MORE = /^(?:[ \t]+\S|[ \t]*[-*+] )/;+const MENU_CHOICE = /\b(options?|pick|choose|which one|which of|prefer|should i)\b/i;+/** Finish reasons of a turn that did not finish (session_qc.BAD_FINISH). */+export const BAD_FINISH: ReadonlySet<string> = new Set(["length", "error", "tool-calls", "content-filter", "abort", "aborted"]);++/**+ * Whether an answer ends on a numbered list for the user to choose from+ * (session_qc._ends_on_menu): the list is the answer's last block, and the+ * line that leads into it is a question or asks the user to choose, or its+ * last line asks which option. A summary of what was done is not a menu.+ */+export function endsOnMenu(text: string): boolean {+ const lines = text.split(/\r\n|\r|\n/).filter((line) => line.trim());+ let index = lines.length - 1;+ let items = 0;+ while (index >= 0 && (MENU_ITEM.test(lines[index]!) || MENU_ITEM_MORE.test(lines[index]!))) {+ if (MENU_ITEM.test(lines[index]!)) items += 1;+ index -= 1;+ }+ if (items < 2) return false;+ const lead = index >= 0 ? lines[index]!.trim() : "";+ const last = lines.at(-1)!.trim();+ return lead.endsWith("?")+ || (lead.endsWith(":") && MENU_CHOICE.test(lead))+ || (last.endsWith("?") && MENU_CHOICE.test(last));+}++/** Whether a final answer waits on the user: a question (AWAITING_USER) or a menu. */+export function awaitsUser(text: string): boolean {+ const tail = text.trim().slice(-600);+ return AWAITING_USER.test(tail.slice(-400)) || endsOnMenu(tail);+}++export type LastTurn = "pass" | "cut" | "awaiting";+/**+ * How the last turn ended. "stopped" (the Stop button, or the app closed+ * mid-turn) and "gateway" (an omnirush.ai gateway error) are excused: the+ * checklist still reads "last turn cut off", but the finish guard stays out+ * of it. "none": no answer in the last turn yet.+ */+export type LastTurnEnd = LastTurn | "stopped" | "gateway" | "none";++/** What the checklist's `finished` shows for an ending. */+export function lastTurnOf(ended: LastTurnEnd): LastTurn {+ return ended === "pass" || ended === "awaiting" ? ended : "cut";+}+// --- The desktop's transcript --------------------------------------------------function sessionErrorOf(message: UIMessage): boolean {- return message.parts.some((part) => {+function sessionErrorOf(message: UIMessage): Record<string, unknown> | null {+ for (const part of message.parts) {const metadata = record((part as { providerMetadata?: unknown }).providerMetadata);- return record(metadata.opencode).sessionError !== undefined;- });+ const opencode = record(metadata.opencode);+ if (opencode.sessionError !== undefined) return record(opencode.sessionError);+ }+ return null;+}++/**+ * The gateway refusing on purpose: out of tokens for the day, the Windows+ * cut-off, the session cap, an app update required. Its messages start with+ * "omnirush.ai: " (and usually end on a console link); retrying cannot help.+ */+const REFUSAL = /(^|Message: )omnirush\.ai:|daily_grant_exhausted|windows_cutoff|session_quality_cap|update_required|client update required/im;++/**+ * How a turn that ended on an error ended. The engine's MessageAbortedError+ * is the Stop button; an APIError is the gateway (session_qc._interruption).+ * `retryable`: a gateway or stream error worth one automatic "continue"+ * (never a stop or a refusal).+ */+function errorEnding(error: Record<string, unknown>): { ended: LastTurnEnd; retryable: boolean } {+ if (error.kind === "aborted") return { ended: "stopped", retryable: false };+ const refusal = REFUSAL.test(`${str(error.title)}\n${str(error.technicalDetails)}`) || Boolean(str(record(error.action).link));+ if (/^Error type: APIError$/m.test(str(error.technicalDetails))) return { ended: "gateway", retryable: !refusal };+ return { ended: "cut", retryable: !refusal && (error.kind === "provider-timeout" || error.kind === "provider-incomplete") };}function messageCalls(message: UIMessage): ToolCall[] {@@ -720,18 +848,197 @@ function messageCalls(message: UIMessage): ToolCall[] {return calls;}-/** The desktop transcript as the checklist reads it: { calls, lastTurn } (the CLI's sessionFacts). */-export function messageFacts(messages: readonly UIMessage[]): { calls: ToolCall[]; lastTurn: "pass" | "cut" } {+function messageOpencode(message: UIMessage): Record<string, unknown> {+ return record(record(message.metadata).opencode);+}++/** How the last turn (the messages after the last prompt) ended (session_qc._completion). */+type TurnEnding = { ended: LastTurnEnd; endedAt: number | null; retryable: boolean };++function lastTurnEnd(messages: readonly UIMessage[]): TurnEnding {+ let start = messages.length;+ while (start > 0 && messages[start - 1]!.role !== "user") start -= 1;+ const turn = messages.slice(start).filter((message) => message.role === "assistant");+ const last = turn.at(-1);+ if (!last) return { ended: "none", endedAt: null, retryable: false };+ const completed = messageOpencode(last).completed;+ const endedAt = typeof completed === "number" ? completed : null;+ const error = sessionErrorOf(last);+ if (error) return { ...errorEnding(error), endedAt };+ let finalText = "";+ let afterLastTool = true;+ let unfinished = false;+ let finish = "";+ for (const message of turn) {+ const reason = messageOpencode(message).finish;+ if (typeof reason === "string" && reason) finish = reason;+ for (const part of message.parts) {+ const value = part as unknown as Record<string, unknown>;+ if (part.type === "dynamic-tool" || part.type.startsWith("tool-")) {+ afterLastTool = false;+ finalText = "";+ if (value.state === "input-streaming" || value.state === "input-available") unfinished = true;+ } else if (part.type === "text" && str(value.text).trim()) {+ afterLastTool = true;+ finalText = str(value.text);+ }+ }+ }+ const reason = finish.toLowerCase();+ if (unfinished || BAD_FINISH.has(reason) || !finalText.trim() || !afterLastTool) {+ // A tool chain cut mid-call, or a stream that ended on an error or between tool calls.+ return { ended: "cut", endedAt, retryable: unfinished || reason === "tool-calls" || reason === "error" };+ }+ return { ended: awaitsUser(finalText) ? "awaiting" : "pass", endedAt, retryable: false };+}++/**+ * The desktop transcript as the checklist reads it: { calls, lastTurn } (the+ * CLI's sessionFacts), plus how the last turn ended (`ended`), when+ * (`endedAt`, ms; null when unknown) and whether one automatic "continue"+ * could help (`retryable`), for the finish guard and the auto-retry.+ */+export function messageFacts(messages: readonly UIMessage[]): { calls: ToolCall[]; lastTurn: LastTurn } & TurnEnding {const calls: ToolCall[] = [];- let lastCalls: ToolCall[] = [];for (const message of messages) {if (message.role !== "assistant") continue;- lastCalls = messageCalls(message);- calls.push(...lastCalls);+ calls.push(...messageCalls(message));+ }+ const ending = lastTurnEnd(messages);+ return { calls, lastTurn: lastTurnOf(ending.ended), ...ending };+}++// --- The server's checklist (GET /me/sessions/{id}/status) ---------------------------++export type GoodSessionTone = "amber" | "red";++/** The checklist the bar shows, with the server's own words when it answered. */+export type ShownChecklist = GoodSessionChecklist & {+ source: "server" | "local";+ /** The server's headline, or null. */+ message: string | null;+ messageTone: GoodSessionTone | null;+ /** The server's reasons, in order. */+ reasons: string[];+ /** The escalation line (warn → surcharge → cap), or null. */+ dock: { tone: GoodSessionTone; message: string; link: string | null } | null;+};++function localShown(local: GoodSessionChecklist): ShownChecklist {+ return { ...local, source: "local", message: null, messageTone: null, reasons: [], dock: null };+}++/** Whether the server block is missing or says nothing yet: the local checklist shows then, exactly as without it. */+export function serverStatusUsable(status: OmniRushSessionStatus | null | undefined): status is OmniRushSessionStatus {+ if (!status) return false;+ return !(status.status === "unknown" && status.checklist.length === 0);+}++/**+ * The bar's checklist: the server's `checklist[]`, `message`, `reasons` and+ * `dock` when it answered for this session; otherwise the local checklist,+ * unchanged. An answer with no checklist items keeps the local items under+ * the server's message. The filled ★ comes from the server's `usable`+ * verdict (or, without a server block, from /me/quality's client grade).+ */+export function shownChecklist({ local, server, sessionId, serverGood = false }: {+ local: GoodSessionChecklist;+ server: OmniRushSessionStatus | null | undefined;+ sessionId: string;+ serverGood?: boolean;+}): ShownChecklist {+ if (!serverStatusUsable(server) || server.sessionId !== sessionId) {+ if (!serverGood || !local.onTrack) return localShown(local);+ return localShown({ ...local, verdict: "good", text: checklistText(local.checks, "good") });}- const last = messages.at(-1);- const lastTurn = last && last.role === "assistant" && !sessionErrorOf(last) && !lastCalls.some((call) => call.unfinished) ? "pass" : "cut";- return { calls, lastTurn };+ const checks: GoodSessionCheck[] = server.checklist.length+ ? server.checklist.map((item) => ({ id: item.id, state: item.state, label: goodSessionWording(item.label), hint: goodSessionWording(item.hint) }))+ : local.checks;+ const onTrack = checks.every((check) => check.state === "pass");+ const verdict: GoodSessionVerdict = server.verdict?.state === "usable" ? "good" : onTrack ? "on-track" : "incomplete";+ const dock = server.dock;+ const dockTone: GoodSessionTone = dock && (dock.stage === "surcharge" || dock.stage === "cap" || dock.capped || server.status === "failing") ? "red" : "amber";+ return {+ checks,+ verdict,+ onTrack,+ missing: checks.filter((check) => check.state === "fail"),+ text: checklistText(checks, verdict),+ work: local.work,+ source: "server",+ message: server.message ? goodSessionWording(server.message) : null,+ messageTone: server.status === "failing" ? "red" : server.status === "at_risk" ? "amber" : null,+ reasons: server.reasons.map((reason) => reason.message),+ dock: dock?.message && (dock.stage !== "none" || dock.capped)+ ? { tone: dockTone, message: dock.message, link: dock.link }+ : null,+ };+}++/** Milliseconds to the next status read: the server's `poll_seconds`, at least 30 s; 60 s when it named none. */+export function sessionStatusPollMs(status: Pick<OmniRushSessionStatus, "pollSeconds"> | null | undefined): number {+ const seconds = status?.pollSeconds;+ return Math.max(30, typeof seconds === "number" && seconds > 0 ? seconds : 60) * 1000;+}++/**+ * Whether quitting should ask the finish guard, and with which words. Arms+ * when no turn runs and the last turn was cut off or waits on the user; an+ * excused ending (stopped, gateway error) never arms. The server arms it+ * too when its `finished` item is the one step left (fail or pending, every+ * other item passing or warning) and it judged after the last turn ended.+ */+export function finishGuardKind({ turnRunning, ended, endedAt = null, server = null }: {+ turnRunning: boolean;+ ended: LastTurnEnd;+ endedAt?: number | null;+ server?: OmniRushSessionStatus | null;+}): FinishGuardKind | null {+ if (turnRunning || ended === "stopped" || ended === "gateway" || ended === "none") return null;+ // The server's kill switch (`client.finish_guard: false`).+ if (serverStatusUsable(server) && server.client?.finishGuard === false) return null;+ if (ended === "awaiting" || ended === "cut") return ended;+ if (!serverStatusUsable(server)) return null;+ const finished = server.checklist.find((item) => item.id === "finished");+ if (!finished || (finished.state !== "fail" && finished.state !== "pending")) return null;+ if (!server.checklist.every((item) => item === finished || item.state === "pass" || item.state === "warn")) return null;+ // The local transcript says it finished: only a verdict newer than that turn overrides it.+ const judgedAt = server.evaluatedAt ? Date.parse(server.evaluatedAt) : Number.NaN;+ if (endedAt === null || !Number.isFinite(judgedAt) || judgedAt < endedAt) return null;+ return /\b(question|answer|reply|waiting)\b/i.test(`${finished.label} ${finished.hint}`) ? "awaiting" : "cut";+}++/**+ * The message to send on its own after a turn ended on a gateway, stream or+ * tool-chain error, or null. Only when the server turned it on for this+ * session (`client.auto_retry`; never offline), at most `max` times in a+ * row, never after the user pressed Stop and never on a refusal.+ */+export function autoRetryMessage({ turnRunning, ended, retryable, userStopped, retriesInARow, server }: {+ turnRunning: boolean;+ ended: LastTurnEnd;+ retryable: boolean;+ userStopped: boolean;+ retriesInARow: number;+ server: OmniRushSessionStatus | null | undefined;+}): string | null {+ const retry = server?.client?.autoRetry;+ if (!retry?.enabled || !retry.message || retriesInARow >= retry.max) return null;+ if (turnRunning || userStopped || !retryable || (ended !== "cut" && ended !== "gateway")) return null;+ return retry.message;+}++/** The `depth` item's hint for the one-time "one more turn" nudge, or null (off: `client.one_more_turn: false`). */+export function oneMoreTurnHint(server: OmniRushSessionStatus | null | undefined): string | null {+ if (!serverStatusUsable(server) || server.client?.oneMoreTurn === false) return null;+ const depth = server.checklist.find((item) => item.id === "depth");+ if (!depth || (depth.state !== "warn" && depth.state !== "fail") || !depth.hint) return null;+ return goodSessionWording(depth.hint);+}++/** The key the guard asks once for: one session, one state. */+export function finishGuardKey(sessionId: string, kind: FinishGuardKind): string {+ return `${sessionId}:${kind}`;}/** Whether ending or deleting a session is about a session whose turn runs. */diff --git a/apps/app/src/react-app/domains/quality/good-session.tsx b/apps/app/src/react-app/domains/quality/good-session.tsxindex 40fb9ffd..db5fde8f 100644--- a/apps/app/src/react-app/domains/quality/good-session.tsx+++ b/apps/app/src/react-app/domains/quality/good-session.tsx@@ -1,6 +1,7 @@/** @jsxImportSource react */import { useEffect, useMemo, useRef, useState } from "react";import type { UIMessage } from "ai";+import type { OmniRushSessionStatus } from "@omnirush/types/desktop-ipc";import { AlertTriangle, CircleCheck, CircleX, Star, X } from "lucide-react";import {@@ -19,11 +20,18 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popoverimport { toast } from "@/components/ui/sonner";import { cn } from "@/lib/utils";-import { omnirushQualityDetails, openDesktopUrl } from "../../../app/lib/desktop";+import { omnirushQualityDetails, omnirushSessionStatus, openDesktopUrl } from "../../../app/lib/desktop";import {+ FINISH_GUARD_DETAIL,+ FINISH_GUARD_EVENT,+ FINISH_GUARD_FINISH,+ FINISH_GUARD_PROMPT,+ FINISH_GUARD_QUIT,+ FINISH_GUARD_TITLE,GOOD_SESSION_GUIDE,GOOD_SESSION_GUIDE_LINK,GOOD_SESSION_WSL_TIP,+ NUDGE_TITLE,TURN_GUARD_DETAIL,TURN_GUARD_QUIT,TURN_GUARD_TITLE,@@ -31,16 +39,23 @@ import {WSL_BANNER_DISMISSED_KEY,WSL_BANNER_TEXT,WSL_GUIDE_URL,+ autoRetryMessage,checklistHeading,- checklistText,+ finishGuardKind,goodSessionChecklist,goodSessionNudge,messageFacts,localDay,+ oneMoreTurnHint,+ serverStatusUsable,+ sessionStatusPollMs,shouldNudge,+ shownChecklist,showWslBanner,windowsNotCounted,+ type FinishGuardKind,type GoodSessionCheck,+ type GoodSessionTone,} from "../../../app/lib/good-session";import { readPref, useAccountQuality, writePref } from "../../../app/lib/quality";import { isDesktopRuntime, isWindowsPlatform } from "../../../app/utils";@@ -76,12 +91,14 @@ function CheckMark({ check }: { check: GoodSessionCheck }) {className={cn("inline-flex items-center gap-1 whitespace-nowrap",check.state === "pass" && "text-foreground",- check.state === "fail" && "text-amber-11",+ (check.state === "fail" || check.state === "warn") && "text-amber-11",)}>{check.label}{check.state === "pending" ? null : check.state === "pass" ? (<CircleCheck className="size-3.5 shrink-0" strokeWidth={2.5} aria-hidden="true" />+ ) : check.state === "warn" ? (+ <AlertTriangle className="size-3.5 shrink-0" strokeWidth={2.5} aria-hidden="true" />) : (<CircleX className="size-3.5 shrink-0" strokeWidth={2.5} aria-hidden="true" />)}@@ -93,18 +110,11 @@ const NUDGED_STORAGE_KEY = "omnirush.goodSession.nudged.v1";const NUDGED_KEEP = 200;function nudgedSessions(): string[] {- try {- const parsed = JSON.parse(readPref(NUDGED_STORAGE_KEY) ?? "[]");- return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];- } catch {- return [];- }+ return rememberedSessions(NUDGED_STORAGE_KEY);}function rememberNudged(sessionId: string) {- const ids = nudgedSessions().filter((id) => id !== sessionId);- ids.push(sessionId);- writePref(NUDGED_STORAGE_KEY, JSON.stringify(ids.slice(-NUDGED_KEEP)));+ rememberSession(NUDGED_STORAGE_KEY, sessionId);}export type GoodSessionChecklistBarProps = {@@ -113,6 +123,92 @@ export type GoodSessionChecklistBarProps = {workspaceRoot: string;isRemoteWorkspace: boolean;turnRunning: boolean;+ /** "Finish it": put the reply in the composer and focus it (never sends). */+ onFinishIt?: (prompt: string) => void;+ /** Send a prompt on its own (the server's auto-retry). */+ onAutoRetry?: (prompt: string) => void;+};++/** How long a turn's end settles before an auto-retry is judged (late Stop or error events land first). */+const AUTO_RETRY_SETTLE_MS = 4_000;+/** Sessions whose running turn the user stopped (the Stop button); cleared when a turn starts. */+const userStops = new Set<string>();+/** Automatic retries in a row per session; reset when a turn finishes. */+const autoRetries = new Map<string, number>();++/** The Stop button: no auto-retry follows this turn. */+export function noteUserStop(sessionId: string) {+ userStops.add(sessionId);+}++const ONE_MORE_TURN_STORAGE_KEY = "omnirush.goodSession.oneMoreTurn.v1";++function rememberedSessions(key: string): string[] {+ try {+ const parsed = JSON.parse(readPref(key) ?? "[]");+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];+ } catch {+ return [];+ }+}++function rememberSession(key: string, sessionId: string) {+ const ids = rememberedSessions(key).filter((id) => id !== sessionId);+ ids.push(sessionId);+ writePref(key, JSON.stringify(ids.slice(-NUDGED_KEEP)));+}++/** The open sessions' finish states, for the in-app delete guard (the native quit guard gets them over IPC). */+const finishStates = new Map<string, FinishGuardKind>();++export function finishGuardFor(sessionId: string): FinishGuardKind | null {+ return finishStates.get(sessionId) ?? null;+}++function reportFinishState(sessionId: string, kind: FinishGuardKind | null) {+ if (kind) finishStates.set(sessionId, kind);+ else finishStates.delete(sessionId);+ if (!isDesktopRuntime()) return;+ void Promise.resolve(window.__OMNIRUSH_ELECTRON__?.invokeDesktop?.("__setFinishState", { sessionId, kind })).catch(() => undefined);+}++/** "Finish it" for a session: its checklist bar fills the composer. */+export function requestFinishIt(sessionId: string, kind: FinishGuardKind) {+ window.dispatchEvent(new CustomEvent(FINISH_GUARD_EVENT, { detail: { sessionId, kind } }));+}++/**+ * The server's live status for the open session (GET+ * /me/sessions/{id}/status, 3 s), re-read every `poll_seconds` (30 s or+ * more, 60 s by default) and when a turn starts or ends. Null while it is+ * unknown, the request failed or outside the desktop: the bar then shows+ * the local checklist.+ */+function useServerSessionStatus(sessionId: string, active: boolean, turnRunning: boolean): OmniRushSessionStatus | null {+ const [read, setRead] = useState<{ sessionId: string; status: OmniRushSessionStatus | null }>({ sessionId, status: null });+ useEffect(() => {+ if (!active || !isDesktopRuntime()) return;+ let cancelled = false;+ let timer: number | undefined;+ const poll = async () => {+ const status = await omnirushSessionStatus({ sessionId }).catch(() => null);+ if (cancelled) return;+ setRead({ sessionId, status });+ timer = window.setTimeout(() => void poll(), sessionStatusPollMs(status));+ };+ void poll();+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [active, sessionId, turnRunning]);+ return read.sessionId === sessionId ? read.status : null;+}++const TONE_TEXT: Record<GoodSessionTone, string> = { amber: "text-amber-11", red: "text-red-11" };+const TONE_BOX: Record<GoodSessionTone, string> = {+ amber: "border-amber-7/40 bg-amber-2/30 text-amber-11",+ red: "border-red-7/40 bg-red-2/30 text-red-11",};const SERVER_VERDICT_REFRESH_MS = 5 * 60_000;@@ -165,12 +261,83 @@ export function GoodSessionChecklistBar(props: GoodSessionChecklistBarProps) {turnRunning: props.turnRunning,nativeWindows: windowsNotCounted({ nativeWindows, windowsCounts }),}), [facts, nativeWindows, props.isRemoteWorkspace, props.turnRunning, props.workspaceRoot, windowsCounts]);- const serverGood = useServerGood(props.sessionId, local.onTrack);+ const hasPrompt = props.messages.some((message) => message.role === "user");+ const server = useServerSessionStatus(props.sessionId, hasPrompt, props.turnRunning);+ // /me/quality's client grade only while the server says nothing about this session.+ const serverGood = useServerGood(props.sessionId, local.onTrack && !serverStatusUsable(server));const checklist = useMemo(- () => (serverGood && local.onTrack ? { ...local, verdict: "good" as const, text: checklistText(local.checks, "good") } : local),- [local, serverGood],+ () => shownChecklist({ local, server, sessionId: props.sessionId, serverGood }),+ [local, props.sessionId, server, serverGood],);- const hasPrompt = props.messages.some((message) => message.role === "user");++ // The finish guard: the desktop asks before quitting, closing or deleting while this is set.+ const finishKind = hasPrompt+ ? finishGuardKind({ turnRunning: props.turnRunning, ended: facts.ended, endedAt: facts.endedAt, server })+ : null;+ useEffect(() => {+ const sessionId = props.sessionId;+ reportFinishState(sessionId, finishKind);+ return () => reportFinishState(sessionId, null);+ }, [finishKind, props.sessionId]);+ // The server's auto-retry: on this session's running → done edge, after+ // the end settles, judged on the latest transcript.+ const latest = useRef({ facts, server, turnRunning: props.turnRunning, onAutoRetry: props.onAutoRetry });+ latest.current = { facts, server, turnRunning: props.turnRunning, onAutoRetry: props.onAutoRetry };+ const retryEdge = useRef<{ sessionId: string; running: boolean }>({ sessionId: props.sessionId, running: props.turnRunning });+ useEffect(() => {+ const previous = retryEdge.current;+ const sessionId = props.sessionId;+ retryEdge.current = { sessionId, running: props.turnRunning };+ if (props.turnRunning) {+ if (!previous.running) userStops.delete(sessionId);+ return;+ }+ if (previous.sessionId !== sessionId || !previous.running) return;+ const timer = window.setTimeout(() => {+ const now = latest.current;+ if (now.facts.ended === "pass" || now.facts.ended === "awaiting") {+ autoRetries.delete(sessionId);+ return;+ }+ const retriesInARow = autoRetries.get(sessionId) ?? 0;+ if (!now.onAutoRetry) return;+ const message = autoRetryMessage({+ turnRunning: now.turnRunning,+ ended: now.facts.ended,+ retryable: now.facts.retryable,+ userStopped: userStops.has(sessionId),+ retriesInARow,+ server: now.server,+ });+ if (!message) return;+ autoRetries.set(sessionId, retriesInARow + 1);+ now.onAutoRetry(message);+ }, AUTO_RETRY_SETTLE_MS);+ return () => window.clearTimeout(timer);+ }, [props.sessionId, props.turnRunning]);++ // One more turn would make it count (the server's `depth` item): once per session.+ const depthHint = props.turnRunning ? null : oneMoreTurnHint(server);+ useEffect(() => {+ if (!depthHint || rememberedSessions(ONE_MORE_TURN_STORAGE_KEY).includes(props.sessionId)) return;+ rememberSession(ONE_MORE_TURN_STORAGE_KEY, props.sessionId);+ toast(NUDGE_TITLE, { id: `good-session-depth:${props.sessionId}`, description: depthHint, duration: 12_000 });+ }, [depthHint, props.sessionId]);++ const onFinishIt = props.onFinishIt;+ useEffect(() => {+ if (!onFinishIt) return;+ const sessionId = props.sessionId;+ const listener = (event: Event) => {+ if (!(event instanceof CustomEvent)) return;+ const detail: unknown = event.detail;+ if (!detail || typeof detail !== "object" || !("sessionId" in detail) || !("kind" in detail)) return;+ if (detail.sessionId !== sessionId || (detail.kind !== "awaiting" && detail.kind !== "cut")) return;+ onFinishIt(FINISH_GUARD_PROMPT[detail.kind]);+ };+ window.addEventListener(FINISH_GUARD_EVENT, listener);+ return () => window.removeEventListener(FINISH_GUARD_EVENT, listener);+ }, [onFinishIt, props.sessionId]);// The nudge: on the running → done edge of this session's turn.const wasRunning = useRef<{ sessionId: string; running: boolean }>({ sessionId: props.sessionId, running: props.turnRunning });@@ -188,8 +355,39 @@ export function GoodSessionChecklistBar(props: GoodSessionChecklistBarProps) {if (!hasPrompt) return null;const verdict = checklist.verdict;+ const dock = checklist.dock;+ const dockLink = dock?.link;return (- <div className="px-4 max-lg:px-3 lg:px-8" data-testid="good-session-checklist" data-verdict={verdict}>+ <div className="px-4 max-lg:px-3 lg:px-8" data-testid="good-session-checklist" data-verdict={verdict} data-source={checklist.source}>+ {dock ? (+ <div+ role="status"+ data-testid="good-session-dock"+ data-tone={dock.tone}+ className={cn("mx-auto mb-1.5 flex max-w-[800px] items-center gap-2 rounded-lg border px-3 py-1.5 text-xs", TONE_BOX[dock.tone])}+ >+ <AlertTriangle className="size-3.5 shrink-0" aria-hidden="true" />+ <span className="min-w-0 flex-1">{dock.message}</span>+ {dockLink ? (+ <button+ type="button"+ data-testid="good-session-dock-link"+ className="shrink-0 font-medium underline underline-offset-2"+ onClick={() => void openDesktopUrl(dockLink).catch(() => undefined)}+ >+ Details+ </button>+ ) : null}+ </div>+ ) : null}+ {checklist.message || checklist.reasons.length ? (+ <div className="mx-auto max-w-[800px] pb-1 text-[11px] leading-4 text-muted-foreground" data-testid="good-session-server-message">+ {checklist.message ? (+ <p className={cn("font-medium", checklist.messageTone ? TONE_TEXT[checklist.messageTone] : "text-foreground")}>{checklist.message}</p>+ ) : null}+ {checklist.reasons.map((reason) => <p key={reason} className="text-amber-11">{reason}</p>)}+ </div>+ ) : null}<div className="mx-auto flex max-w-[800px] items-center gap-2 pb-1.5"><divclassName="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 rounded-full border border-border bg-popover/60 px-2.5 py-1 text-[11px] leading-4 text-muted-foreground"@@ -286,6 +484,31 @@ export function WslBanner({ className }: { className?: string }) {);}+/** The finish guard in the app (deleting the session): "Finish it" (the default) or "Quit anyway". */+export function FinishGuardDialog(props: { kind: FinishGuardKind | null; onFinish: () => void; onQuit: () => void }) {+ return (+ <AlertDialog open={props.kind !== null} onOpenChange={(open) => { if (!open) props.onFinish(); }}>+ <AlertDialogContent data-testid="finish-guard-dialog">+ <AlertDialogHeader>+ <AlertDialogMedia className="bg-amber-3/50 text-amber-11">+ <AlertTriangle />+ </AlertDialogMedia>+ <AlertDialogTitle>{FINISH_GUARD_TITLE}</AlertDialogTitle>+ <AlertDialogDescription>{props.kind ? FINISH_GUARD_DETAIL[props.kind] : null}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogAction variant="outline" data-testid="finish-guard-quit" onClick={props.onQuit}>+ {FINISH_GUARD_QUIT}+ </AlertDialogAction>+ <AlertDialogCancel variant="default" autoFocus data-testid="finish-guard-finish">+ {FINISH_GUARD_FINISH}+ </AlertDialogCancel>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}+/** The confirm before switching or deleting a session whose turn is running. */export function TurnGuardDialog(props: { open: boolean; onWait: () => void; onQuit: () => void }) {return (diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex d1c2eaa1..af5b427f 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -102,8 +102,8 @@ import { isSameWorkbenchSession } from "./workbench-store";import { ReactSessionRuntime } from "../sync/runtime-sync";import { useSessionInteractions } from "../sync/use-session-interactions";import { createClient } from "@/app/lib/opencode";-import { createQuitGuard, leavingRunningTurn } from "@/app/lib/good-session";-import { TurnGuardDialog } from "@/react-app/domains/quality/good-session";+import { createQuitGuard, finishGuardKey, leavingRunningTurn, type FinishGuardKind } from "@/app/lib/good-session";+import { FinishGuardDialog, TurnGuardDialog, finishGuardFor, requestFinishIt } from "@/react-app/domains/quality/good-session";import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";import {availableNarrowPane,@@ -513,6 +513,7 @@ export function SessionPage(props: SessionPageProps) {const [deleteOpen, setDeleteOpen] = useState(false);// The don't-leave-mid-turn confirm: what to do on "Quit anyway".const [turnGuardProceed, setTurnGuardProceed] = useState<(() => void) | null>(null);+ const [finishGuard, setFinishGuard] = useState<{ sessionId: string; kind: FinishGuardKind; proceed: () => void } | null>(null);const [deleteBusy, setDeleteBusy] = useState(false);const [sessionActionId, setSessionActionId] = useState<string | null>(null);const workbenchPrimary = useWorkbenchStore((state) => state.primary);@@ -1194,11 +1195,19 @@ export function SessionPage(props: SessionPageProps) {useEffect(() => {leaveGuard.current.turnEnded();}, [runningTurns]);- const guardLeave = useCallback((running: boolean, proceed: () => void) => {- if (leaveGuard.current.request({ running }) === "ask") {+ // No turn runs but its last one needs finishing (cut off, or waiting on+ // the user): the finish guard asks once per session and state.+ const guardLeave = useCallback((running: boolean, proceed: () => void, sessionId?: string) => {+ const kind = !running && sessionId ? finishGuardFor(sessionId) : null;+ const verdict = leaveGuard.current.request({ running, finish: kind && sessionId ? finishGuardKey(sessionId, kind) : null });+ if (verdict === "ask") {setTurnGuardProceed(() => proceed);return;}+ if (verdict === "finish" && kind && sessionId) {+ setFinishGuard({ sessionId, kind, proceed });+ return;+ }proceed();}, []);@@ -1438,7 +1447,7 @@ export function SessionPage(props: SessionPageProps) {setSessionActionId(sessionId);setDeleteOpen(true);};- guardLeave(leavingRunningTurn({ action: "delete", turnRunning: sessionTurnRunning(sessionId) }), openDelete);+ guardLeave(leavingRunningTurn({ action: "delete", turnRunning: sessionTurnRunning(sessionId) }), openDelete, sessionId);} : undefined}onArchiveSession={props.onArchiveSession ? (sessionId, archived) => {void props.onArchiveSession?.(sessionId, archived);@@ -2095,6 +2104,22 @@ export function SessionPage(props: SessionPageProps) {}}/>+ <FinishGuardDialog+ kind={finishGuard?.kind ?? null}+ onFinish={() => {+ const guard = finishGuard;+ leaveGuard.current.answer(true);+ setFinishGuard(null);+ if (guard) requestFinishIt(guard.sessionId, guard.kind);+ }}+ onQuit={() => {+ const guard = finishGuard;+ leaveGuard.current.answer(false);+ setFinishGuard(null);+ guard?.proceed();+ }}+ />+{props.onDeleteSession ? (<ConfirmModalopen={deleteOpen}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.tsxindex ae68150f..d826a8ce 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@@ -98,7 +98,7 @@ import { getSessionActivityStatusLabel, useSessionActivityStore, type SessionActimport { PermissionApprovalPanel } from "@/react-app/domains/session/chat/permission-approval-modal";import { QuestionPanel } from "@/react-app/domains/session/modals/question-modal";import { QueuedMessagesPanel } from "@/react-app/domains/session/modals/queued-messages-panel";-import { GoodSessionChecklistBar, WslBanner } from "@/react-app/domains/quality/good-session";+import { GoodSessionChecklistBar, WslBanner, noteUserStop } from "@/react-app/domains/quality/good-session";import { deriveOpenTargets, sameOpenTargets, selectAutoOpenTarget, type OpenTarget } from "@/react-app/domains/session/artifacts/open-target";import { usePanelTabStore } from "@/react-app/domains/session/panel/panel-tab-store";import {@@ -2321,6 +2321,8 @@ export function SessionSurface(props: SessionSurfaceProps) {const handleAbort = useCallback(async () => {const phase = getQueuedDrainState(props.sessionId).phase;if (!chatStreaming && phase.kind !== "sending" && phase.kind !== "admission_unknown") return;+ // A stopped turn is the user's call: no automatic retry follows it.+ noteUserStop(props.sessionId);setError(null);// Stop means stop: drop queued follow-ups before aborting, otherwise the// queue-drain effect below re-prompts the agent the moment the abort@@ -2868,6 +2870,9 @@ export function SessionSurface(props: SessionSurfaceProps) {}});}, [props.sessionId, sendDraft]);+ const handleAutoRetry = useCallback((prompt: string) => {+ void handleResumeInterrupted(prompt);+ }, [handleResumeInterrupted]);const handleResumeUnknownOutcome = useCallback(() => {void handleResumeInterrupted(interruptedTaskRecoveryPrompt);}, [handleResumeInterrupted]);@@ -3332,6 +3337,8 @@ export function SessionSurface(props: SessionSurfaceProps) {workspaceRoot={props.workspaceRoot}isRemoteWorkspace={props.isRemoteWorkspace}turnRunning={chatStreaming || (effectiveActivityStatus !== "idle" && effectiveActivityStatus !== "error")}+ onFinishIt={handleMessageListSetPrompt}+ onAutoRetry={handleAutoRetry}/><ReactSessionComposerrunModeControl={<WorkspaceRunModeMenu client={props.client} workspaceId={props.workspaceId} busy={chatStreaming || preparingCloudTools || Boolean(props.activePermission || props.activeQuestion)} />}diff --git a/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts b/apps/app/src/react-app/domains/session/sync/usechat-adapter.tsindex 03accd97..18a5df65 100644--- a/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts+++ b/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts@@ -146,11 +146,13 @@ export function snapshotToUIMessages(snapshot: OmniRushSessionSnapshot): UIMessaconst created = message.info.time?.created;const time = message.info.time;const completed = time && "completed" in time ? time.completed : undefined;+ // The engine's finish reason ("stop", "length", "tool-calls", ...): the Good session checklist reads it.+ const finish = message.info.role === "assistant" ? message.info.finish : undefined;const uiMessage = {id: message.info.id,role: message.info.role,...(typeof created === "number"- ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}) } } }+ ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}), ...(finish ? { finish } : {}) } } }: {}),parts: message.parts.flatMap<UIMessage["parts"][number]>((part) => {if (part.type === "text") {diff --git a/apps/app/tests/good-session.test.tsx b/apps/app/tests/good-session.test.tsxindex f1168a91..477f2469 100644--- a/apps/app/tests/good-session.test.tsx+++ b/apps/app/tests/good-session.test.tsx@@ -1,15 +1,24 @@import { describe, expect, test } from "bun:test";import type { UIMessage } from "ai";+import type { OmniRushSessionStatus } from "@omnirush/types/desktop-ipc";import { renderToStaticMarkup } from "react-dom/server";import {+ FINISH_GUARD_DETAIL,+ FINISH_GUARD_PROMPT,+ FINISH_GUARD_TITLE,GOOD_SESSION_GUIDE,GOOD_SESSION_ON_TRACK,TURN_GUARD_MESSAGE,TURN_GUARD_QUIT,TURN_GUARD_WAIT,+ autoRetryMessage,+ awaitsUser,checklistText,createQuitGuard,+ endsOnMenu,+ finishGuardKey,+ finishGuardKind,fetchedUrls,goodSessionChecklist,goodSessionNudge,@@ -19,17 +28,21 @@ import {leavingRunningTurn,localDay,messageFacts,+ oneMoreTurnHint,outsideProject,personalService,ranSomething,+ sessionStatusPollMs,shellWrites,shouldNudge,+ shownChecklist,showWslBanner,startsServer,windowsNotCounted,writtenLines,} from "../src/app/lib/good-session";import { GoodSessionGuide } from "../src/react-app/domains/quality/good-session";+import { CODING_STARTER_CARDS } from "../src/components/chat/task-suggestions";const ROOT = "/home/dev/projects/todo-api";const BODY = Array.from({ length: 20 }, (_, i) => `export const v${i} = ${i};`).join("\n");@@ -315,6 +328,7 @@ describe("the live checklist", () => {{ type: "tool-write", toolCallId: "1", state: "output-available", input: { filePath: "src/a.rs", content: BODY }, output: "ok" },{ type: "tool-write", toolCallId: "2", state: "output-available", input: { filePath: "src/b.rs", content: BODY }, output: "ok" },{ type: "tool-bash", toolCallId: "3", state: "output-available", input: { command: "cargo test" }, output: "ok" },+ { type: "text", text: "Done." },] as UIMessage["parts"],},];@@ -391,7 +405,7 @@ describe("the don't-leave-mid-turn guard", () => {test("the dialog says the spec's words", () => {expect(TURN_GUARD_MESSAGE).toBe("A turn is still running. Quit now and this session won't count as a Good session ★.");- expect([TURN_GUARD_WAIT, TURN_GUARD_QUIT]).toEqual(["Wait for it", "Quit anyway"]);+ expect([TURN_GUARD_WAIT, TURN_GUARD_QUIT]).toEqual(["Finish it", "Quit anyway"]);});});@@ -440,3 +454,277 @@ describe("wording, the guide and the WSL banner", () => {])).toBe("Good session: code changed ✓ · finish your turn");});});++// --- The server's checklist, the finish guard and the auto-retry --------------------++function serverStatus(overrides: Partial<OmniRushSessionStatus> = {}): OmniRushSessionStatus {+ return {+ sessionId: "ses_1",+ status: "on_track",+ reasons: [],+ message: null,+ dock: null,+ verdict: null,+ checklist: [+ { id: "project", state: "pass", label: "in a project", hint: "The work stays in the project." },+ { id: "code", state: "pass", label: "code changed (3 files, 120 lines)", hint: "" },+ { id: "depth", state: "warn", label: "1 of 2 turns", hint: "One more turn would make this count: send a follow-up." },+ { id: "brand_new", state: "pending", label: "a new check", hint: "" },+ ],+ evaluatedAt: "2026-10-10T13:00:00Z",+ client: null,+ pollSeconds: 60,+ ...overrides,+ };+}++function assistant(id: string, parts: unknown[], opencode: Record<string, unknown> = {}): UIMessage {+ return { id, role: "assistant", metadata: { opencode }, parts: parts as UIMessage["parts"] };+}++function prompt(id = "u"): UIMessage {+ return { id, role: "user", parts: [{ type: "text", text: "fix the parser" }] };+}++function errorMessage(sessionError: Record<string, unknown>): UIMessage {+ return { id: "err", role: "assistant", parts: [{ type: "text", text: String(sessionError.title ?? "error"), providerMetadata: { opencode: { sessionError } } }] as UIMessage["parts"] };+}++const local = goodSessionChecklist({ ...messageFacts(transcript(realWork())), workspaceRoot: ROOT });++describe("the server's checklist", () => {+ test("renders the server's items in order with its words, unknown ids generically, warn as its own state", () => {+ const shown = shownChecklist({ local, server: serverStatus(), sessionId: "ses_1" });+ expect(shown.source).toBe("server");+ expect(shown.checks.map((check) => [check.id, check.state, check.label])).toEqual([+ ["project", "pass", "in a project"],+ ["code", "pass", "code changed (3 files, 120 lines)"],+ ["depth", "warn", "1 of 2 turns"],+ ["brand_new", "pending", "a new check"],+ ]);+ expect(shown.verdict).toBe("incomplete");+ expect(shown.text).toBe("Good session: in a project ✓ · code changed (3 files, 120 lines) ✓ · 1 of 2 turns ! · a new check");+ expect(shown.missing).toEqual([]);+ });++ test("message, reasons and the dock: amber for warn/at_risk, red for failing, surcharge and cap", () => {+ const atRisk = shownChecklist({+ local,+ sessionId: "ses_1",+ server: serverStatus({+ status: "at_risk",+ message: "Open a project folder.",+ reasons: [{ code: "generic_folder", message: "This runs in your Downloads folder: open a project folder." }],+ dock: { mode: "warn", stage: "warn", weight: 1, sessionTokens: 1, surchargeTokens: 0, capAtTokens: null, capped: false, message: "Heads up: this session may be charged more.", link: null },+ }),+ });+ expect(atRisk.message).toBe("Open a project folder.");+ expect(atRisk.messageTone).toBe("amber");+ expect(atRisk.reasons).toEqual(["This runs in your Downloads folder: open a project folder."]);+ expect(atRisk.dock).toEqual({ tone: "amber", message: "Heads up: this session may be charged more.", link: null });+ for (const stage of ["surcharge", "cap"] as const) {+ const shown = shownChecklist({+ local,+ sessionId: "ses_1",+ server: serverStatus({ status: "failing", dock: { mode: "enforce", stage, weight: 1.5, sessionTokens: 1, surchargeTokens: 1, capAtTokens: 2, capped: stage === "cap", message: "Using tokens at 1.5x.", link: "https://omnirush.ai/console/sessions" } }),+ });+ expect(shown.dock).toEqual({ tone: "red", message: "Using tokens at 1.5x.", link: "https://omnirush.ai/console/sessions" });+ expect(shown.messageTone).toBe("red");+ }+ const quiet = shownChecklist({ local, sessionId: "ses_1", server: serverStatus({ dock: { mode: "observe", stage: "none", weight: 1, sessionTokens: 1, surchargeTokens: 0, capAtTokens: null, capped: false, message: "observing", link: null } }) });+ expect(quiet.dock).toBeNull();+ });++ test("the filled ★ comes from the server's usable verdict", () => {+ const passing = serverStatus({ checklist: [{ id: "code", state: "pass", label: "code changed", hint: "" }] });+ expect(shownChecklist({ local, sessionId: "ses_1", server: passing }).verdict).toBe("on-track");+ expect(shownChecklist({ local, sessionId: "ses_1", server: { ...passing, verdict: { state: "usable", reasons: [], rewardWeight: 2 } } }).verdict).toBe("good");+ });++ test("falls back to the local checklist exactly when the block is null, unknown and empty, for another session, or the read failed", () => {+ for (const server of [null, undefined, serverStatus({ status: "unknown", checklist: [] }), serverStatus({ sessionId: "ses_other" })]) {+ const shown = shownChecklist({ local, server, sessionId: "ses_1" });+ expect(shown.source).toBe("local");+ expect(shown.checks).toEqual(local.checks);+ expect(shown.text).toBe(local.text);+ expect(shown.verdict).toBe(local.verdict);+ expect(shown.message).toBeNull();+ expect(shown.dock).toBeNull();+ }+ // Without a server block, /me/quality's client grade still fills the ★ once the local checks pass.+ const onTrack = goodSessionChecklist({ ...messageFacts(transcript([...realWork(), tool("bash", { command: "npm test" })])), workspaceRoot: ROOT });+ expect(shownChecklist({ local: onTrack, server: null, sessionId: "ses_1", serverGood: true }).verdict).toBe("good");+ });++ test("an answer with a message but no items keeps the local items under the server's words", () => {+ const shown = shownChecklist({ local, sessionId: "ses_1", server: serverStatus({ status: "at_risk", checklist: [], message: "Run the tests." }) });+ expect(shown.source).toBe("server");+ expect(shown.checks).toEqual(local.checks);+ expect(shown.message).toBe("Run the tests.");+ });++ test("polls at the server's pace: 30 s at least, 60 s when it names none or the read failed", () => {+ expect(sessionStatusPollMs(null)).toBe(60_000);+ expect(sessionStatusPollMs({ pollSeconds: 10 })).toBe(30_000);+ expect(sessionStatusPollMs({ pollSeconds: 90 })).toBe(90_000);+ });+});++describe("how the last turn ended (session_qc._completion)", () => {+ test("questions and menus wait on the user; a summary list does not", () => {+ expect(awaitsUser("I fixed the parser. Would you like me to add tests for the edge cases?")).toBe(true);+ expect(awaitsUser("Done. Let me know if you want anything else changed?")).toBe(true);+ expect(awaitsUser("Fixed it. Let me know if you need anything else.")).toBe(false);+ expect(endsOnMenu("Which option should I take?\n1. Rewrite the lexer\n2. Patch the tokenizer")).toBe(true);+ expect(endsOnMenu("Pick one of these options:\n1. Rewrite\n2. Patch")).toBe(true);+ expect(endsOnMenu("I made the following changes:\n1. Rewrote the lexer\n2. Added tests")).toBe(false);+ expect(endsOnMenu("Next?\n1. Only one item")).toBe(false);+ });++ test("a finished answer passes; a question is awaiting, with its own checklist words", () => {+ expect(messageFacts([prompt(), assistant("a", [tool("bash", { command: "npm test" }), { type: "text", text: "All tests pass." }], { finish: "stop" })]).ended).toBe("pass");+ const asking = [prompt(), assistant("a", [{ type: "text", text: "Shall I also update the docs?" }], { finish: "stop" })];+ const facts = messageFacts(asking);+ expect(facts.ended).toBe("awaiting");+ expect(facts.lastTurn).toBe("awaiting");+ const finished = goodSessionChecklist({ ...facts, workspaceRoot: ROOT }).checks.find((check) => check.id === "finished")!;+ expect([finished.state, finished.label]).toEqual(["fail", "answer the agent"]);+ });++ test("cut off: a bad finish reason, an unfinished tool, or no answer after the last tool call", () => {+ for (const finish of ["length", "error", "tool-calls", "content-filter", "aborted"]) {+ expect(messageFacts([prompt(), assistant("a", [{ type: "text", text: "Half done" }], { finish })]).ended).toBe("cut");+ }+ expect(messageFacts([prompt(), assistant("a", [tool("bash", { command: "npm test" }, "input-streaming")])]).ended).toBe("cut");+ expect(messageFacts([prompt(), assistant("a", [{ type: "text", text: "Running the tests" }, tool("bash", { command: "npm test" })])]).ended).toBe("cut");+ // The answer may sit in a later message of the same turn.+ expect(messageFacts([prompt(), assistant("a1", [tool("bash", { command: "npm test" })], { finish: "tool-calls" }), assistant("a2", [{ type: "text", text: "Done." }], { finish: "stop" })]).ended).toBe("pass");+ });++ test("the Stop button and gateway errors are excused; other errors cut; no answer yet is none", () => {+ expect(messageFacts([prompt(), errorMessage({ kind: "aborted", title: "Task interrupted", technicalDetails: "Error type: MessageAbortedError" })]).ended).toBe("stopped");+ expect(messageFacts([prompt(), errorMessage({ kind: "generic", title: "Bad gateway", technicalDetails: "Error type: APIError\nStatus: 502" })]).ended).toBe("gateway");+ expect(messageFacts([prompt(), errorMessage({ kind: "generic", title: "Context too long", technicalDetails: "Error type: ContextOverflowError" })]).ended).toBe("cut");+ expect(messageFacts([prompt()]).ended).toBe("none");+ expect(messageFacts([]).ended).toBe("none");+ });++ test("retryable: gateway, stream and tool-chain errors; never a stop or a refusal", () => {+ const retryable = (messages: UIMessage[]) => messageFacts(messages).retryable;+ expect(retryable([prompt(), errorMessage({ kind: "generic", title: "Bad gateway", technicalDetails: "Error type: APIError\nStatus: 502" })])).toBe(true);+ expect(retryable([prompt(), errorMessage({ kind: "provider-incomplete", title: "The model response was interrupted", technicalDetails: "Error type: UnknownError" })])).toBe(true);+ expect(retryable([prompt(), assistant("a", [tool("bash", { command: "npm test" }, "input-streaming")])])).toBe(true);+ expect(retryable([prompt(), errorMessage({ kind: "aborted", title: "Task interrupted", technicalDetails: "Error type: MessageAbortedError" })])).toBe(false);+ for (const refusal of [+ "Message: omnirush.ai: you've used today's tokens: https://omnirush.ai/console/account",+ "Message: Daily limit\nResponse: {\"detail\":\"daily_grant_exhausted\"}",+ "Message: refused\nResponse: {\"detail\":\"windows_cutoff\"}",+ "Message: paused\nResponse: {\"detail\":\"session_quality_cap\"}",+ "Message: update\nCode: update_required",+ ]) {+ expect(retryable([prompt(), errorMessage({ kind: "generic", title: "Refused", technicalDetails: `Error type: APIError\n${refusal}` })])).toBe(false);+ }+ expect(retryable([prompt(), assistant("a", [{ type: "text", text: "Half done" }], { finish: "length" })])).toBe(false);+ });+});++describe("the finish guard", () => {+ test("arms on cut and awaiting when no turn runs; never on a stop, a gateway error, a running turn or a fresh session", () => {+ expect(finishGuardKind({ turnRunning: false, ended: "cut" })).toBe("cut");+ expect(finishGuardKind({ turnRunning: false, ended: "awaiting" })).toBe("awaiting");+ expect(finishGuardKind({ turnRunning: true, ended: "cut" })).toBeNull();+ for (const ended of ["stopped", "gateway", "none", "pass"] as const) {+ expect(finishGuardKind({ turnRunning: false, ended })).toBeNull();+ }+ });++ test("the server arms it when finished is the one step left and it judged after the turn ended", () => {+ const server = serverStatus({+ evaluatedAt: "2026-10-10T13:00:00Z",+ checklist: [+ { id: "code", state: "pass", label: "code changed", hint: "" },+ { id: "depth", state: "warn", label: "1 of 2 turns", hint: "" },+ { id: "finished", state: "fail", label: "last turn cut off", hint: "Send a follow-up and let it finish." },+ ],+ });+ const before = Date.parse("2026-10-10T12:59:00Z");+ expect(finishGuardKind({ turnRunning: false, ended: "pass", endedAt: before, server })).toBe("cut");+ expect(finishGuardKind({ turnRunning: false, ended: "pass", endedAt: Date.parse("2026-10-10T13:01:00Z"), server })).toBeNull();+ expect(finishGuardKind({ turnRunning: false, ended: "pass", endedAt: null, server })).toBeNull();+ const awaiting = { ...server, checklist: server.checklist.map((item) => item.id === "finished" ? { ...item, state: "pending" as const, hint: "Answer the agent's question." } : item) };+ expect(finishGuardKind({ turnRunning: false, ended: "pass", endedAt: before, server: awaiting })).toBe("awaiting");+ const notNext = { ...server, checklist: [...server.checklist, { id: "ran", state: "fail" as const, label: "ran/tested", hint: "" }] };+ expect(finishGuardKind({ turnRunning: false, ended: "pass", endedAt: before, server: notNext })).toBeNull();+ });++ test("the server's kill switch (client.finish_guard: false) turns the new states off", () => {+ const off = serverStatus({ client: { autoRetry: null, finishGuard: false, oneMoreTurn: true } });+ expect(finishGuardKind({ turnRunning: false, ended: "cut", server: off })).toBeNull();+ expect(finishGuardKind({ turnRunning: false, ended: "awaiting", server: off })).toBeNull();+ expect(finishGuardKind({ turnRunning: false, ended: "cut", server: null })).toBe("cut");+ });++ test("asks once per session and state", () => {+ const guard = createQuitGuard();+ expect(guard.request({ finish: finishGuardKey("ses_1", "cut") })).toBe("finish");+ expect(guard.answer(true)).toBe("wait");+ expect(guard.request({ finish: finishGuardKey("ses_1", "cut") })).toBe("quit");+ expect(guard.request({ finish: finishGuardKey("ses_1", "awaiting") })).toBe("finish");+ expect(guard.answer(false)).toBe("quit");+ expect(guard.request({ finish: finishGuardKey("ses_2", "cut") })).toBe("finish");+ expect(guard.answer(true)).toBe("wait");+ // A running turn still asks its own question afterwards.+ expect(guard.request({ running: true })).toBe("ask");+ });++ test("the spec's words and the composer text", () => {+ expect(FINISH_GUARD_TITLE).toBe("This session is one step from counting.");+ expect(FINISH_GUARD_DETAIL.awaiting).toBe("The agent asked you a question. Answer it (or tell it to go ahead) and let the turn finish, or this session won't pass the quality check.");+ expect(FINISH_GUARD_DETAIL.cut).toBe("The last turn stopped before it finished. Send \"continue\" and let it finish, or this session won't pass the quality check.");+ expect(FINISH_GUARD_PROMPT).toEqual({ awaiting: "Go ahead.", cut: "Continue and finish the task." });+ });+});++describe("the server's auto-retry and one-more-turn nudge", () => {+ const on = serverStatus({ client: { autoRetry: { enabled: true, max: 1, message: "Continue." }, finishGuard: true, oneMoreTurn: true } });+ const base = { turnRunning: false, ended: "gateway" as const, retryable: true, userStopped: false, retriesInARow: 0, server: on };++ test("fires once after a gateway, stream or tool-chain error", () => {+ expect(autoRetryMessage(base)).toBe("Continue.");+ expect(autoRetryMessage({ ...base, ended: "cut" })).toBe("Continue.");+ expect(autoRetryMessage({ ...base, retriesInARow: 1 })).toBeNull();+ expect(autoRetryMessage({ ...base, turnRunning: true })).toBeNull();+ });++ test("never after the Stop button or on a refusal", () => {+ expect(autoRetryMessage({ ...base, userStopped: true })).toBeNull();+ expect(autoRetryMessage({ ...base, ended: "stopped", retryable: false })).toBeNull();+ expect(autoRetryMessage({ ...base, retryable: false })).toBeNull();+ expect(autoRetryMessage({ ...base, ended: "pass", retryable: false })).toBeNull();+ });++ test("off when the block or its client switches are absent, or the server turned it off", () => {+ expect(autoRetryMessage({ ...base, server: null })).toBeNull();+ expect(autoRetryMessage({ ...base, server: serverStatus() })).toBeNull();+ expect(autoRetryMessage({ ...base, server: serverStatus({ client: { autoRetry: null, finishGuard: true, oneMoreTurn: true } }) })).toBeNull();+ expect(autoRetryMessage({ ...base, server: serverStatus({ client: { autoRetry: { enabled: false, max: 1, message: "Continue." }, finishGuard: true, oneMoreTurn: true } }) })).toBeNull();+ expect(autoRetryMessage({ ...base, server: serverStatus({ client: { autoRetry: { enabled: true, max: 1, message: null }, finishGuard: true, oneMoreTurn: true } }) })).toBeNull();+ });++ test("one more turn: the depth item's hint, unless the server turned it off", () => {+ expect(oneMoreTurnHint(serverStatus())).toBe("One more turn would make this count: send a follow-up.");+ expect(oneMoreTurnHint(serverStatus({ client: { autoRetry: null, finishGuard: true, oneMoreTurn: false } }))).toBeNull();+ expect(oneMoreTurnHint(serverStatus({ checklist: [{ id: "depth", state: "pass", label: "2 turns", hint: "ok" }] }))).toBeNull();+ expect(oneMoreTurnHint(null)).toBeNull();+ });+});++describe("coding starter cards", () => {+ test("six task templates, inserted for the user to fill in", () => {+ expect(CODING_STARTER_CARDS.map((card) => card.title)).toEqual([+ "Fix a hard bug", "Make it faster", "Fix the build", "Refactor or migrate", "Build a real feature", "Systems work",+ ]);+ expect(CODING_STARTER_CARDS[0]!.prompt).toBe("There's a bug in this project: {describe the symptom}. Reproduce it with a failing test or command first, find the root cause, fix it, and run the tests until they pass.");+ expect(CODING_STARTER_CARDS.every((card) => card.prompt.includes("this project"))).toBe(true);+ });+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex b66fecbb..35bbf542 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -2176,6 +2176,11 @@ const desktopCommandHandlers = {"omnirushQualitySpins": async (event) => {return omnirushAccountStore.qualitySpinTotals();},+ // The server's live checklist for the open session; null: the app shows its own.+ "omnirushSessionStatus": async (event, ...args) => {+ const input = args[0] && typeof args[0] === "object" ? args[0] : {};+ return omnirushAccountStore.sessionStatus({ sessionId: input.sessionId });+ },"omnirushQualitySpin": async (event, ...args) => {const input = args[0] && typeof args[0] === "object" ? args[0] : {};return omnirushAccountStore.spinQuality({ idempotencyKey: typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined });@@ -2559,6 +2564,9 @@ const desktopCommandHandlers = {"__setTurnRunning": async (event, ...args) => {return turnGuard.setTurnRunning(args[0] === true);},+ "__setFinishState": async (event, ...args) => {+ return turnGuard.setFinishState(args[0]);+ },};if (isDevMode) {diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex 69b1cbfc..521e67d2 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -13,7 +13,7 @@ import {writePlaintextCredentialFile,} from "./plaintext-credential-file.mjs";import { CLIENT_HEADER, guiClientHeaderValue, parseClientUpdate } from "./update-gate.mjs";-import { parseAccountQuality, parseFailLabels, parseQualitySessions, parseSpinHistory, profileSessionId, parseSpinResult, parseWheelSegments, spinIdempotencyKey, spinRefusal } from "./quality.mjs";+import { parseAccountQuality, parseFailLabels, parseQualitySessions, parseSessionStatus, parseSpinHistory, profileSessionId, parseSpinResult, parseWheelSegments, spinIdempotencyKey, spinRefusal } from "./quality.mjs";const execFileAsync = promisify(execFile);@@ -45,6 +45,8 @@ const MAX_KEYCHAIN_DELETES = 8;*/const SERVER_ROTATION_GRACE_MS = 120_000;const REFRESH_TIMEOUT_MS = 20_000;+/** A session's live status: past this the app shows its own checklist (the server contract's 3 s). */+const SESSION_STATUS_TIMEOUT_MS = 3_000;/*** A refresh token that may already have been rotated (the answer was lost)* is sent again only while that attempt, timeout included, ends inside the@@ -1150,7 +1152,7 @@ export function createDesktopOmniRushAccountStore({url.pathname += pathname;const headers = new Headers(init.headers);headers.set("Authorization", `Bearer ${current.accessToken}`);- const response = await send(url, { ...init, headers, signal: AbortSignal.timeout(20_000) });+ const response = await send(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(20_000) });if (response.status === 401 && refreshesLeft > 0) {const refreshed = await refresh(current.accessToken);if (!refreshed) return response;@@ -1185,6 +1187,26 @@ export function createDesktopOmniRushAccountStore({}}+ /**+ * The server's live status for one session (GET /me/sessions/{id}/status),+ * within 3 s. Null while signed out, offline, slow or on a bad answer: the+ * app then shows its own checklist.+ */+ async function sessionStatus(input = {}) {+ const sessionId = profileSessionId(input.sessionId);+ if (!sessionId) return null;+ try {+ const response = await sendAuthorized(`/me/sessions/${encodeURIComponent(sessionId)}/status`, {+ method: "GET",+ signal: AbortSignal.timeout(SESSION_STATUS_TIMEOUT_MS),+ });+ if (!response?.ok) return null;+ return parseSessionStatus(await response.json());+ } catch {+ return null;+ }+ }+/** GET /me/quality/spins: totals and the last 10 spins; null when unavailable. */async function qualitySpinTotals() {try {@@ -1262,5 +1284,5 @@ export function createDesktopOmniRushAccountStore({}}- return { load, save, refresh, authorize, status, clear, qualityDetails, qualitySpinTotals, spinQuality };+ return { load, save, refresh, authorize, status, clear, qualityDetails, qualitySpinTotals, spinQuality, sessionStatus };}diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex d12c429c..9cd8e045 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -6,6 +6,7 @@ const NATIVE_MENU_TOGGLE_SIDEBAR_EVENT = "omnirush:native-menu:toggle-sidebar";const NATIVE_MENU_CHECK_UPDATES_EVENT = "omnirush:native-menu:check-updates";const NATIVE_MENU_ZOOM_EVENT = "omnirush:native-menu:zoom";const AUTOMATION_RUNNER_CREDENTIAL_REJECTED_EVENT = "omnirush:automation-runner:credential-rejected";+const FINISH_GUARD_EVENT = "omnirush:finish-guard:finish";function normalizePlatform(value) {if (value === "darwin" || value === "linux") return value;@@ -332,6 +333,12 @@ ipcRenderer.on(NATIVE_MENU_CHECK_UPDATES_EVENT, () => {window.dispatchEvent(new Event(NATIVE_MENU_CHECK_UPDATES_EVENT));});+// The finish guard's "Finish it" (turn-guard.mjs): the open session fills its composer.+ipcRenderer.on(FINISH_GUARD_EVENT, (_event, detail) => {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new CustomEvent(FINISH_GUARD_EVENT, { detail }));+});+ipcRenderer.on(NATIVE_MENU_ZOOM_EVENT, (_event, action) => {if (typeof window === "undefined") return;window.dispatchEvent(new CustomEvent(NATIVE_MENU_ZOOM_EVENT, { detail: action }));diff --git a/apps/desktop/electron/quality.mjs b/apps/desktop/electron/quality.mjsindex 2d7c42c9..d43394f6 100644--- a/apps/desktop/electron/quality.mjs+++ b/apps/desktop/electron/quality.mjs@@ -289,3 +289,103 @@ export function spinIdempotencyKey(value) {const key = text(value);return key && key.length <= 64 && /^[0-9A-Za-z._:-]+$/.test(key) ? key : globalThis.crypto.randomUUID();}++const SESSION_STATUSES = ["on_track", "at_risk", "failing", "unknown"];+const CHECK_STATES = ["pass", "fail", "warn", "pending"];+const DOCK_MODES = ["off", "observe", "warn", "enforce"];+const DOCK_STAGES = ["none", "warn", "surcharge", "cap"];+const VERDICT_STATES = ["pending", "usable", "not_usable"];+/** The fastest the app re-asks for a session's status, and its pace when the server names none. */+export const SESSION_STATUS_MIN_POLL_SECONDS = 30;+export const SESSION_STATUS_DEFAULT_POLL_SECONDS = 60;++function oneOf(value, allowed, fallback) {+ return allowed.includes(value) ? value : fallback;+}++function nonNegative(value) {+ const number = Number(value);+ return Number.isFinite(number) && number >= 0 ? number : 0;+}++function parseDock(value) {+ if (!value || typeof value !== "object") return null;+ const weight = Number(value.weight);+ const capAt = Number(value.cap_at_tokens);+ return {+ mode: oneOf(value.mode, DOCK_MODES, "off"),+ stage: oneOf(value.stage, DOCK_STAGES, "none"),+ weight: Number.isFinite(weight) && weight > 0 ? weight : 1,+ sessionTokens: nonNegative(value.session_tokens),+ surchargeTokens: nonNegative(value.surcharge_tokens),+ capAtTokens: value.cap_at_tokens === null || value.cap_at_tokens === undefined || !Number.isFinite(capAt) ? null : capAt,+ capped: value.capped === true,+ message: text(value.message),+ link: text(value.link),+ };+}++function parseVerdict(value) {+ if (!value || typeof value !== "object") return null;+ const weight = Number(value.reward_weight);+ return {+ state: oneOf(value.state, VERDICT_STATES, "pending"),+ reasons: Array.isArray(value.reasons) ? value.reasons.map(text).filter((reason) => reason !== null) : [],+ rewardWeight: Number.isFinite(weight) ? weight : null,+ };+}++/**+ * The block's `client` switches (contract revision 2); null when absent:+ * no auto-retry, the finish guard and the one-more-turn nudge on.+ */+function parseClientSwitches(value) {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const retry = value.auto_retry && typeof value.auto_retry === "object" ? value.auto_retry : null;+ const max = Number(retry?.max);+ return {+ autoRetry: retry+ ? {+ enabled: retry.enabled === true,+ max: Number.isFinite(max) && max > 0 ? Math.min(3, Math.floor(max)) : 1,+ message: text(retry.message),+ }+ : null,+ finishGuard: value.finish_guard !== false,+ oneMoreTurn: value.one_more_turn !== false,+ };+}++/**+ * The server's status block for one session (GET /me/sessions/{id}/status,+ * or `session_status` on /device/me); null when it is missing or malformed.+ * Labels, hints and messages are the server's words, kept as given.+ */+export function parseSessionStatus(value) {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const sessionId = text(value.session_id);+ if (!sessionId) return null;+ const poll = Number(value.poll_seconds);+ return {+ sessionId,+ status: oneOf(value.status, SESSION_STATUSES, "unknown"),+ reasons: Array.isArray(value.reasons)+ ? value.reasons+ .filter((reason) => reason && typeof reason === "object" && text(reason.message))+ .map((reason) => ({ code: text(reason.code) ?? "", message: text(reason.message) }))+ : [],+ message: text(value.message),+ dock: parseDock(value.dock),+ verdict: parseVerdict(value.verdict),+ checklist: Array.isArray(value.checklist)+ ? value.checklist+ .filter((item) => item && typeof item === "object" && text(item.id) && text(item.label))+ .map((item) => ({ id: text(item.id), state: oneOf(item.state, CHECK_STATES, "pending"), label: text(item.label), hint: text(item.hint) ?? "" }))+ : [],+ evaluatedAt: isoTime(value.evaluated_at),+ client: parseClientSwitches(value.client),+ pollSeconds: Number.isFinite(poll) && poll > 0+ ? Math.max(SESSION_STATUS_MIN_POLL_SECONDS, Math.floor(poll))+ : SESSION_STATUS_DEFAULT_POLL_SECONDS,+ };+}diff --git a/apps/desktop/electron/quality.test.mjs b/apps/desktop/electron/quality.test.mjsindex 1c0b00b9..a79e25e7 100644--- a/apps/desktop/electron/quality.test.mjs+++ b/apps/desktop/electron/quality.test.mjs@@ -5,7 +5,7 @@ import path from "node:path";import test from "node:test";import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";-import { parseAccountQuality, parseSpinHistory, parseSpinResult, spinIdempotencyKey, spinRefusal } from "./quality.mjs";+import { parseAccountQuality, parseSessionStatus, parseSpinHistory, parseSpinResult, spinIdempotencyKey, spinRefusal } from "./quality.mjs";const GATEWAY = "http://localhost:8090/omnirush/v1";const SEGMENTS = [@@ -283,3 +283,83 @@ test("spins history: totals and the last 10 spins, each marked when replay-readyassert.equal(history.recent[2].clientGrade, false);assert.equal(parseSpinHistory(null), null);});++const SESSION_STATUS = {+ session_id: "ses_abc",+ status: "at_risk",+ reasons: [{ code: "no_code", message: "No code has changed yet after 31 tool calls." }, { code: "x" }],+ message: "One step left.",+ dock: { mode: "warn", stage: "surcharge", weight: 1.5, session_tokens: 5400000, surcharge_tokens: 300000, cap_at_tokens: null, capped: false, message: "Using tokens at 1.5x.", link: "https://omnirush.ai/console/sessions" },+ verdict: { state: "pending", reasons: ["finished"], reward_weight: 2 },+ checklist: [+ { id: "project", state: "pass", label: "in a project", hint: "ok" },+ { id: "depth", state: "warn", label: "1 of 2 turns", hint: "One more turn would make this count: send a follow-up." },+ { id: "brand_new", state: "sideways", label: "new item" },+ { id: "", state: "pass", label: "no id" },+ ],+ evaluated_at: "2026-10-10T13:00:00Z",+ poll_seconds: 60,+ client: { auto_retry: { enabled: true, max: 1, message: "Continue." }, finish_guard: false },+};++test("session status: the server block, its words kept, unknown states pending, unknown ids kept", () => {+ const status = parseSessionStatus(SESSION_STATUS);+ assert.equal(status.status, "at_risk");+ assert.deepEqual(status.reasons, [{ code: "no_code", message: "No code has changed yet after 31 tool calls." }]);+ assert.deepEqual(status.checklist.map((item) => [item.id, item.state, item.label]), [+ ["project", "pass", "in a project"], ["depth", "warn", "1 of 2 turns"], ["brand_new", "pending", "new item"],+ ]);+ assert.equal(status.dock.stage, "surcharge");+ assert.equal(status.dock.weight, 1.5);+ assert.equal(status.dock.capAtTokens, null);+ assert.equal(status.verdict.rewardWeight, 2);+ assert.deepEqual(status.client, { autoRetry: { enabled: true, max: 1, message: "Continue." }, finishGuard: false, oneMoreTurn: true });+ assert.equal(status.pollSeconds, 60);+});++test("session status: poll at least every 30 s, 60 s by default; no client block on older servers", () => {+ assert.equal(parseSessionStatus({ ...SESSION_STATUS, poll_seconds: 5 }).pollSeconds, 30);+ assert.equal(parseSessionStatus({ ...SESSION_STATUS, poll_seconds: undefined }).pollSeconds, 60);+ assert.equal(parseSessionStatus({ ...SESSION_STATUS, poll_seconds: 120 }).pollSeconds, 120);+ assert.equal(parseSessionStatus({ ...SESSION_STATUS, client: undefined }).client, null);+ assert.equal(parseSessionStatus({ session_id: "ses_x" }).status, "unknown");+ assert.deepEqual(parseSessionStatus({ session_id: "ses_x" }).checklist, []);+ assert.equal(parseSessionStatus(null), null);+ assert.equal(parseSessionStatus({ status: "on_track" }), null);+});++test("session status: GET /me/sessions/{id}/status with the device credential; null on errors, bad ids or signed out", async () => {+ const seen = [];+ const store = await signedInStore(async (url, init) => {+ seen.push({ path: new URL(url).pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal instanceof AbortSignal });+ return Response.json(SESSION_STATUS);+ });+ const status = await store.sessionStatus({ sessionId: "ses_abc" });+ assert.equal(status.sessionId, "ses_abc");+ assert.deepEqual(seen, [{ path: "/omnirush/me/sessions/ses_abc/status", authorization: "Bearer access-1", signal: true }]);+ assert.equal(await store.sessionStatus({ sessionId: "../me" }), null);+ assert.equal(await store.sessionStatus({}), null);+ assert.equal(seen.length, 1, "bad ids never reach the server");++ const failing = await signedInStore(async () => new Response("down", { status: 503 }));+ assert.equal(await failing.sessionStatus({ sessionId: "ses_abc" }), null);+ const offline = await signedInStore(async () => { throw new TypeError("fetch failed"); });+ assert.equal(await offline.sessionStatus({ sessionId: "ses_abc" }), null);+ const timedOut = await signedInStore(async () => { throw new DOMException("The operation timed out.", "TimeoutError"); });+ assert.equal(await timedOut.sessionStatus({ sessionId: "ses_abc" }), null);+ const garbage = await signedInStore(async () => new Response("not json", { status: 200 }));+ assert.equal(await garbage.sessionStatus({ sessionId: "ses_abc" }), null);++ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-quality-"));+ let calls = 0;+ const signedOut = createDesktopOmniRushAccountStore({+ filePath: path.join(directory, "account.bin"),+ loadSafeStorage: () => testStorage(),+ platform: /** @type {NodeJS.Platform} */ ("linux"),+ env: { OMNIRUSH_DEV_MODE: "1" },+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },+ fetchImpl: async () => { calls += 1; return Response.json(SESSION_STATUS); },+ });+ assert.equal(await signedOut.sessionStatus({ sessionId: "ses_abc" }), null);+ assert.equal(calls, 0);+});diff --git a/apps/desktop/electron/turn-guard.mjs b/apps/desktop/electron/turn-guard.mjsindex 6b65e4bf..74d4b8e8 100644--- a/apps/desktop/electron/turn-guard.mjs+++ b/apps/desktop/electron/turn-guard.mjs@@ -1,9 +1,9 @@-// The don't-quit-mid-turn guard. The renderer reports whether a turn is+// The don't-quit-mid-turn guard and the finish guard. The renderer reports whether a turn is// running (`__setTurnRunning`); closing the window or quitting the app while// one runs asks first, because a cut-off last turn keeps the session from-// counting as a Good session ★. "Wait for it" is the default (and Escape);+// counting as a Good session ★. "Finish it" is the default (and Escape);// "Quit anyway" goes ahead. A second close or quit request, while the dialog-// is up or after "Wait for it" in the same turn, quits without asking; the+// is up or after "Finish it" in the same turn, quits without asking; the// guard re-arms when the turn ends. OS shutdown, updater installs and// relaunches call `allowQuit()` first and are never asked.//@@ -12,42 +12,89 @@export const TURN_GUARD_TITLE = "A turn is still running.";export const TURN_GUARD_DETAIL = "Quit now and this session won't count as a Good session ★.";-export const TURN_GUARD_BUTTONS = Object.freeze(["Wait for it", "Quit anyway"]);+// "Finish it" keeps the app open and lets the running turn finish.+export const TURN_GUARD_BUTTONS = Object.freeze(["Finish it", "Quit anyway"]);const WAIT = 0;+// The finish guard: no turn runs, but the last one was cut off ("cut") or+// ends on a question to the user ("awaiting"). Asked once per session and+// state; "Finish it" (the default) puts the reply in the composer.+export const FINISH_GUARD_TITLE = "This session is one step from counting.";+export const FINISH_GUARD_DETAIL = Object.freeze({+ awaiting: "The agent asked you a question. Answer it (or tell it to go ahead) and let the turn finish, or this session won't pass the quality check.",+ cut: "The last turn stopped before it finished. Send \"continue\" and let it finish, or this session won't pass the quality check.",+});+export const FINISH_GUARD_BUTTONS = Object.freeze(["Finish it", "Quit anyway"]);+/** Main → renderer: the user picked "Finish it" ({ sessionId, kind }). */+export const FINISH_GUARD_EVENT = "omnirush:finish-guard:finish";+const FINISH = 0;++/** `{ sessionId, kind }` from the renderer, or null when it names no session or no known state. */+export function finishState(value) {+ if (!value || typeof value !== "object") return null;+ const sessionId = typeof value.sessionId === "string" ? value.sessionId.trim() : "";+ if (!sessionId) return null;+ return { sessionId, kind: value.kind === "awaiting" || value.kind === "cut" ? value.kind : null };+}+/**- * `request({ running, interactive, hangup })` answers "quit" (go ahead) or- * "ask" (show TURN_GUARD_MESSAGE with "Wait for it" / "Quit anyway"). The+ * `request({ running, interactive, hangup, finish })` answers "quit" (go+ * ahead), "ask" (a turn runs: "Wait for it" / "Quit anyway") or "finish"+ * (`finish`, a "<session>:<state>" key: "Finish it" / "Quit anyway"). The* first quit request while a turn runs asks; a second one, whatever the- * answer, quits. `answer(wait)` takes the user's choice; `turnEnded()`- * re-arms the guard for the next turn and says whether the user was waiting.- * Headless runs and a closed terminal (hangup) never ask.+ * answer, quits. Each finish key asks once, ever. `answer(wait)` takes the+ * user's choice; `turnEnded()` re-arms the running-turn question for the+ * next turn and says whether the user was waiting. Headless runs and a+ * closed terminal (hangup) never ask.*/export function createQuitGuard() {let state = "idle"; // idle | asking | waiting+ let askingFinish = false;+ const asked = new Set();return {get state() {return state;},- request({ running = false, interactive = true, hangup = false } = {}) {- if (!interactive || hangup || !running) return "quit";- if (state === "idle") {+ request({ running = false, interactive = true, hangup = false, finish = null } = {}) {+ if (!interactive || hangup) return "quit";+ if (running) {+ if (state === "idle") {+ state = "asking";+ askingFinish = false;+ return "ask";+ }+ return "quit";+ }+ if (finish && state !== "asking" && !asked.has(finish)) {+ asked.add(finish);state = "asking";- return "ask";+ askingFinish = true;+ return "finish";}return "quit";},answer(wait) {if (state !== "asking") return wait ? "wait" : "quit";+ if (askingFinish) {+ // Asked once for this state: the next request quits, and a new turn asks as usual.+ askingFinish = false;+ state = "idle";+ return wait ? "wait" : "quit";+ }if (wait) {state = "waiting";return "wait";}return "quit";},+ /** Whether the finish key was asked about already. */+ askedAbout(finish) {+ return asked.has(finish);+ },turnEnded() {const was = state;state = "idle";+ askingFinish = false;return was === "waiting" || was === "asking";},};@@ -58,11 +105,21 @@ export function createQuitGuard() {* showMessageBox: (window: import("electron").BrowserWindow | null, options: import("electron").MessageBoxOptions) => Promise<{ response: number }>,* getWindow: () => import("electron").BrowserWindow | null,* appName?: string,+ * onFinish?: (detail: { sessionId: string, kind: "awaiting" | "cut" }) => void,* }} deps*/export function createTurnGuard(deps) {const guard = createQuitGuard();let turnRunning = false;+ /** Open sessions whose last turn needs finishing: sessionId → "awaiting" | "cut". */+ const finishing = new Map();+ const onFinish = deps.onFinish ?? ((detail) => {+ const win = deps.getWindow();+ if (!win || win.isDestroyed?.()) return;+ win.show?.();+ win.focus?.();+ win.webContents?.send(FINISH_GUARD_EVENT, detail);+ });let allowed = false;/** @type {AbortController | null} */let open = null;@@ -79,34 +136,50 @@ export function createTurnGuard(deps) {* it has prevented the event and calls `proceed` once the user picks* "Quit anyway".*/+ /** The first open session whose finish state was not asked about yet. */+ function nextFinish() {+ for (const [sessionId, kind] of finishing) {+ const key = `${sessionId}:${kind}`;+ if (!guard.askedAbout(key)) return { sessionId, kind, key };+ }+ return null;+ }+function decide(event, proceed) {if (allowed) return true;- if (guard.request({ running: turnRunning }) === "quit") {+ const finish = turnRunning ? null : nextFinish();+ const verdict = guard.request({ running: turnRunning, finish: finish?.key ?? null });+ if (verdict === "quit") {// The second request: it quits, and the open dialog goes with it.closeDialog();return true;}event.preventDefault();+ const asking = verdict === "finish" && finish ? finish : null;const controller = new AbortController();open = controller;void deps.showMessageBox(deps.getWindow() ?? null, {type: "warning",title: deps.appName ?? "OmniRush.ai",- message: TURN_GUARD_TITLE,- detail: TURN_GUARD_DETAIL,- buttons: [...TURN_GUARD_BUTTONS],- defaultId: WAIT,- cancelId: WAIT,+ message: asking ? FINISH_GUARD_TITLE : TURN_GUARD_TITLE,+ detail: asking ? FINISH_GUARD_DETAIL[asking.kind] : TURN_GUARD_DETAIL,+ buttons: asking ? [...FINISH_GUARD_BUTTONS] : [...TURN_GUARD_BUTTONS],+ defaultId: asking ? FINISH : WAIT,+ cancelId: asking ? FINISH : WAIT,noLink: true,signal: controller.signal,})- .then((result) => result.response === WAIT)+ .then((result) => result.response === (asking ? FINISH : WAIT)).catch(() => false).then((wait) => {// Closed by a second request, which already went ahead.if (controller.signal.aborted) return;open = null;- if (guard.answer(wait) === "quit") proceed();+ if (guard.answer(wait) === "quit") {+ proceed();+ return;+ }+ if (asking) onFinish({ sessionId: asking.sessionId, kind: asking.kind });});return false;}@@ -123,6 +196,14 @@ export function createTurnGuard(deps) {isTurnRunning() {return turnRunning;},+ /** The renderer: an open session's last turn needs finishing (`kind`), or no longer does (`kind: null`). */+ setFinishState(value) {+ const next = finishState(value);+ if (!next) return false;+ if (next.kind) finishing.set(next.sessionId, next.kind);+ else finishing.delete(next.sessionId);+ return true;+ },/** `before-quit`: true when the quit may go on now; `quit` quits again after "Quit anyway". */guardQuit(event, quit) {return decide(event, quit);diff --git a/apps/desktop/electron/turn-guard.test.mjs b/apps/desktop/electron/turn-guard.test.mjsindex fdc30cfa..8e661948 100644--- a/apps/desktop/electron/turn-guard.test.mjs+++ b/apps/desktop/electron/turn-guard.test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { TURN_GUARD_BUTTONS, TURN_GUARD_DETAIL, TURN_GUARD_TITLE, createQuitGuard, createTurnGuard } from "./turn-guard.mjs";+import { FINISH_GUARD_BUTTONS, FINISH_GUARD_DETAIL, FINISH_GUARD_EVENT, FINISH_GUARD_TITLE, TURN_GUARD_BUTTONS, TURN_GUARD_DETAIL, TURN_GUARD_TITLE, createQuitGuard, createTurnGuard, finishState } from "./turn-guard.mjs";function fakeEvent() {return { prevented: false, preventDefault() { this.prevented = true; } };@@ -35,7 +35,7 @@ test("no turn running: quit and close go ahead without asking", () => {assert.equal(dialogs.length, 0);});-test("a turn running: the first quit asks, with Wait for it as the default", async () => {+test("a turn running: the first quit asks, with Finish it as the default", async () => {const { guard, dialogs } = setup();guard.setTurnRunning(true);const event = fakeEvent();@@ -46,12 +46,12 @@ test("a turn running: the first quit asks, with Wait for it as the default", asyconst { options } = dialogs[0];assert.equal(options.message, "A turn is still running.");assert.equal(options.detail, "Quit now and this session won't count as a Good session ★.");- assert.deepEqual(options.buttons, ["Wait for it", "Quit anyway"]);+ assert.deepEqual(options.buttons, ["Finish it", "Quit anyway"]);assert.equal(options.defaultId, 0);assert.equal(options.cancelId, 0);dialogs[0].answer(0);await settle();- assert.equal(quits, 0, "Wait for it keeps the app open");+ assert.equal(quits, 0, "Finish it keeps the app open");});test("quit, Wait for it, quit again: the second quit quits without asking", async () => {@@ -164,5 +164,131 @@ test("createQuitGuard: idle → asking → waiting; any second request quits; tutest("constants", () => {assert.equal(TURN_GUARD_TITLE, "A turn is still running.");assert.match(TURN_GUARD_DETAIL, /Good session ★/);- assert.deepEqual([...TURN_GUARD_BUTTONS], ["Wait for it", "Quit anyway"]);+ assert.deepEqual([...TURN_GUARD_BUTTONS], ["Finish it", "Quit anyway"]);+});++/** A guard whose "Finish it" the test sees (`finishes`). */+function setupFinish() {+ const dialogs = [];+ const finishes = [];+ const guard = createTurnGuard({+ getWindow: () => /** @type {any} */ ("win"),+ onFinish: (detail) => finishes.push(detail),+ showMessageBox: (win, options) => new Promise((resolve) => {+ const dialog = { win, options, answer: (response) => resolve({ response }) };+ options.signal?.addEventListener("abort", () => resolve({ response: options.cancelId }));+ dialogs.push(dialog);+ }),+ });+ return { guard, dialogs, finishes };+}++test("finish guard: a cut-off last turn asks with the spec's words; Finish it keeps the app open and fills the composer", async () => {+ const { guard, dialogs, finishes } = setupFinish();+ assert.equal(guard.setFinishState({ sessionId: "ses_a", kind: "cut" }), true);+ const event = fakeEvent();+ let quits = 0;+ assert.equal(guard.guardQuit(event, () => { quits += 1; }), false);+ assert.equal(event.prevented, true);+ const { options } = dialogs[0];+ assert.equal(options.message, "This session is one step from counting.");+ assert.equal(options.detail, "The last turn stopped before it finished. Send \"continue\" and let it finish, or this session won't pass the quality check.");+ assert.deepEqual(options.buttons, ["Finish it", "Quit anyway"]);+ assert.equal(options.defaultId, 0);+ assert.equal(options.cancelId, 0);+ dialogs[0].answer(0);+ await settle();+ assert.equal(quits, 0);+ assert.deepEqual(finishes, [{ sessionId: "ses_a", kind: "cut" }]);+});++test("finish guard: asks once per session and state; a new state asks again; Quit anyway quits", async () => {+ const { guard, dialogs, finishes } = setupFinish();+ guard.setFinishState({ sessionId: "ses_a", kind: "awaiting" });+ guard.guardClose(fakeEvent(), () => assert.fail("finished"));+ assert.equal(dialogs[0].options.detail, FINISH_GUARD_DETAIL.awaiting);+ dialogs[0].answer(0);+ await settle();+ // Same session, same state: no second question.+ assert.equal(guard.guardQuit(fakeEvent(), () => assert.fail("no re-quit")), true);+ assert.equal(dialogs.length, 1);+ // The state changes to cut: asked once more.+ guard.setFinishState({ sessionId: "ses_a", kind: "cut" });+ let quits = 0;+ assert.equal(guard.guardQuit(fakeEvent(), () => { quits += 1; }), false);+ dialogs[1].answer(1);+ await settle();+ assert.equal(quits, 1, "Quit anyway quits");+ assert.equal(finishes.length, 1);+});++test("finish guard: a running turn asks the running question first; a cleared state never asks", async () => {+ const { guard, dialogs } = setupFinish();+ guard.setFinishState({ sessionId: "ses_a", kind: "cut" });+ guard.setTurnRunning(true);+ guard.guardQuit(fakeEvent(), () => {});+ assert.equal(dialogs[0].options.message, TURN_GUARD_TITLE);+ dialogs[0].answer(0);+ await settle();+ guard.setTurnRunning(false);+ guard.setFinishState({ sessionId: "ses_a", kind: null });+ assert.equal(guard.guardQuit(fakeEvent(), () => {}), true);+ assert.equal(dialogs.length, 1);+});++test("finish guard: a second request while its dialog is up quits; allowQuit never asks", async () => {+ const { guard, dialogs } = setupFinish();+ guard.setFinishState({ sessionId: "ses_b", kind: "awaiting" });+ guard.guardQuit(fakeEvent(), () => assert.fail("closed by the second request"));+ assert.equal(guard.guardQuit(fakeEvent(), () => {}), true);+ await settle();+ const other = setupFinish();+ other.guard.setFinishState({ sessionId: "ses_c", kind: "cut" });+ other.guard.allowQuit();+ assert.equal(other.guard.guardQuit(fakeEvent(), () => {}), true);+ assert.equal(other.dialogs.length, 0);+ assert.equal(dialogs.length, 1);+});++test("finishState: only a session id and a known state", () => {+ assert.equal(finishState(null), null);+ assert.equal(finishState({ kind: "cut" }), null);+ assert.deepEqual(finishState({ sessionId: " ses_a ", kind: "cut" }), { sessionId: "ses_a", kind: "cut" });+ assert.deepEqual(finishState({ sessionId: "ses_a", kind: "running" }), { sessionId: "ses_a", kind: null });+ assert.equal(FINISH_GUARD_TITLE, "This session is one step from counting.");+ assert.deepEqual([...FINISH_GUARD_BUTTONS], ["Finish it", "Quit anyway"]);+});++test("createQuitGuard finish keys: once each, and a later running turn still asks", () => {+ const quit = createQuitGuard();+ assert.equal(quit.request({ finish: "ses_a:cut" }), "finish");+ assert.equal(quit.request({ finish: "ses_a:cut" }), "quit", "a second request while asking");+ assert.equal(quit.answer(true), "wait");+ assert.equal(quit.state, "idle");+ assert.equal(quit.askedAbout("ses_a:cut"), true);+ assert.equal(quit.request({ finish: "ses_a:cut" }), "quit");+ assert.equal(quit.request({ running: true, finish: "ses_a:awaiting" }), "ask", "the running question wins");+ assert.equal(quit.answer(true), "wait");+ quit.turnEnded();+ assert.equal(quit.request({ finish: "ses_a:awaiting" }), "finish");+ assert.equal(quit.answer(false), "quit");+ assert.equal(quit.request({ finish: null }), "quit");+});++test("finish guard: by default, Finish it shows the window and tells the renderer", async () => {+ const sent = [];+ const win = { focused: false, isDestroyed: () => false, show() {}, focus() { this.focused = true; }, webContents: { send: (channel, detail) => sent.push([channel, detail]) } };+ /** @type {Array<(value: { response: number }) => void>} */+ const answers = [];+ const guard = createTurnGuard({+ getWindow: () => /** @type {any} */ (win),+ showMessageBox: () => new Promise((resolve) => answers.push(resolve)),+ });+ guard.setFinishState({ sessionId: "ses_a", kind: "awaiting" });+ guard.guardClose(fakeEvent(), () => assert.fail("finished"));+ answers[0]({ response: 0 });+ await settle();+ assert.equal(win.focused, true);+ assert.deepEqual(sent, [[FINISH_GUARD_EVENT, { sessionId: "ses_a", kind: "awaiting" }]]);+ assert.equal(FINISH_GUARD_EVENT, "omnirush:finish-guard:finish");});diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 60eb634d..41dbaf0f 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -280,6 +280,48 @@ export type OmniRushQualityDetails = {failLabels: Record<string, string>;};+/**+ * The server's live status for one session (GET /me/sessions/{id}/status).+ * Labels, hints and messages are server text, shown as given. Null from the+ * desktop: the app falls back to its own checklist.+ */+export type OmniRushSessionStatus = {+ sessionId: string;+ status: "on_track" | "at_risk" | "failing" | "unknown";+ reasons: { code: string; message: string }[];+ /** The headline above the checklist. */+ message: string | null;+ dock: {+ mode: "off" | "observe" | "warn" | "enforce";+ stage: "none" | "warn" | "surcharge" | "cap";+ weight: number;+ sessionTokens: number;+ surchargeTokens: number;+ capAtTokens: number | null;+ capped: boolean;+ message: string | null;+ link: string | null;+ } | null;+ verdict: { state: "pending" | "usable" | "not_usable"; reasons: string[]; rewardWeight: number | null } | null;+ /** In order; ids may grow. */+ checklist: { id: string; state: "pass" | "fail" | "warn" | "pending"; label: string; hint: string }[];+ evaluatedAt: string | null;+ /**+ * Server switches for the client; null on older servers (no auto-retry,+ * finish guard and one-more-turn nudge on).+ */+ client: {+ /** Send `message` once after a turn ends on a gateway, stream or tool-chain error (at most `max` in a row). */+ autoRetry: { enabled: boolean; max: number; message: string | null } | null;+ /** false: the finish guard's cut/awaiting states are off. */+ finishGuard: boolean;+ /** false: no one-more-turn nudge from the `depth` item. */+ oneMoreTurn: boolean;+ } | null;+ /** How often to re-ask while the session is active: 30 or more. */+ pollSeconds: number;+};+export type OmniRushQualitySpinRecord = {id: string;status: "ready" | "spun" | "expired" | "forfeit";@@ -775,6 +817,7 @@ export type DesktopCommandMap = {};omnirushQualityDetails: { args: []; result: OmniRushQualityDetails | null };omnirushQualitySpins: { args: []; result: OmniRushQualitySpinTotals | null };+ omnirushSessionStatus: { args: [input: { sessionId: string }]; result: OmniRushSessionStatus | null };omnirushQualitySpin: {args: [input: { idempotencyKey: string }];result: OmniRushQualitySpinOutcome;@@ -874,6 +917,7 @@ export type DesktopCommandMap = {__setNativeTheme: { args: [theme: string]; result: unknown };__setApplicationMenuVisible: { args: [visible: boolean]; result: unknown };__setTurnRunning: { args: [running: boolean]; result: unknown };+ __setFinishState: { args: [state: { sessionId: string; kind: "awaiting" | "cut" | null }]; result: unknown };};export type DesktopCommandName = keyof DesktopCommandMap;