A desktop coding agent with free access to frontier models.
TypeScript
feat: quality checklist and quit guard
ogsamrat152eede783cc
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex a3d42f92..ae87e910 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -338,6 +338,8 @@ declare global {platform?: "darwin" | "linux" | "windows";version?: string;evalFatalBootstrapFailure?: string | null;+ /** Test hook (OMNIRUSH_E2E_FORCE_WIN32=1): act as native Windows. */+ forceNativeWindows?: boolean;};};}diff --git a/apps/app/src/app/lib/good-session.ts b/apps/app/src/app/lib/good-session.tsnew file mode 100644index 00000000..8359c555--- /dev/null+++ b/apps/app/src/app/lib/good-session.ts@@ -0,0 +1,498 @@+// "Good session ★": the live checklist the session view shows, worked out+// locally from the session's own tool events. The server's strict check has+// the final say (omnirush-backend: session_repro.py, the Session QC V2 gate+// and quality_rewards.STRICT_SPINS_TEXT); these rules mirror the parts of it+// a turn can see as it runs:+//+// code at least one project code file changed (session_qc.is_code_path)+// ran the agent ran something: a build, the tests or the program+// (session_qc.BUILD_TEST, plus running the program itself)+// project the work stays inside the project folder (V3 outside_path,+// home_folder), with no personal services (V3 remote_service,+// local_database, remote_git, docker)+// finished the last turn finished (V3 unrecorded_turn, V2 `finished`)+// windows not native Windows (V3 windows_host); WSL is fine+//+// Sub-agents and many turns are not required.++import type { UIMessage } from "ai";++export const GOOD_SESSION_LABEL = "Good session ★";++/** The four steps the rewards panel and the checklist's link show. */+export const GOOD_SESSION_GUIDE: readonly string[] = [+ "Work inside your project folder.",+ "Build or change real code.",+ "Run it or its tests.",+ "Let the last turn finish.",+];+export const GOOD_SESSION_WSL_TIP = "On Windows? Use WSL.";+export const GOOD_SESSION_GUIDE_LINK = "How to make a Good session";++/** The console's WSL guide (omnirush-console app/console/wsl, lib/wsl-guide). */+export const WSL_GUIDE_URL = "https://omnirush.ai/console/wsl";+export const WSL_BANNER_TEXT = "Sessions from native Windows don't count as Good sessions. Switch to WSL";++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_MESSAGE = `${TURN_GUARD_TITLE} ${TURN_GUARD_DETAIL}`;+export const TURN_GUARD_WAIT = "Wait for it";+export const TURN_GUARD_QUIT = "Quit anyway";++/**+ * Server texts still say "replay-ready ★" (STRICT_SPINS_TEXT, notices,+ * hints): users read "Good session ★" everywhere.+ */+export function goodSessionWording(text: string): string;+export function goodSessionWording(text: string | null | undefined): string | null | undefined;+export function goodSessionWording(text: string | null | undefined): string | null | undefined {+ if (!text) return text;+ return text+ .replace(/\breplay[- ]ready ★ sessions\b/gi, "Good sessions ★")+ .replace(/\breplay[- ]ready ★ session\b/gi, "Good session ★")+ .replace(/\breplay[- ]ready ★/gi, GOOD_SESSION_LABEL)+ .replace(/★ ?replay[- ]ready sessions\b/gi, "★ Good sessions")+ .replace(/\breplay[- ]ready sessions\b/gi, "Good sessions")+ .replace(/\breplay[- ]ready session\b/gi, "Good session")+ .replace(/\breplay[- ]ready\b/gi, "Good session");+}++// --- Code files (session_qc.is_code_path) -----------------------------------++const NON_CODE_EXTENSIONS = new Set([+ ".md", ".markdown", ".txt", ".rst", ".adoc", ".org", ".rtf", ".doc", ".docx", ".pdf",+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".bmp", ".tif", ".tiff", ".avif", ".heic",+ ".ttf", ".otf", ".woff", ".woff2", ".eot", ".mp3", ".wav", ".mp4", ".mov", ".log", ".csv",+ ".tsv", ".jsonl", ".xlsx", ".pptx", ".sqlite", ".sqlite3", ".db", ".bin", ".zip", ".tar",+ ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".whl",+]);+const INTERNAL_DIRS = [+ "__agent__/", ".omnirush/", ".opencode/", ".pi/", ".godot/", ".git/", "node_modules/", ".venv/",+ "venv/", "__pycache__/", ".idea/", ".vscode/", ".next/", ".nuxt/", ".svelte-kit/", ".turbo/",+ ".cache/", ".parcel-cache/", "coverage/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/",+ ".gradle/", "cmake-build-",+];+const BUILD_OUTPUT_DIRS = new Set(["dist", "build", "out", "target"]);+const SOURCE_DIRS = new Set(["src", "app", "lib", "main", "java", "kotlin"]);+const GENERATED_FILES = new Set(["package-lock.json", "npm-shrinkwrap.json", "packages.lock.json", "pnpm-lock.yaml", "go.sum"]);+const GENERATED_SUFFIXES = [+ ".lock", ".lockb", ".tsbuildinfo", ".sst", ".map", ".min.js", ".min.css", ".pyc", ".pyo", ".o",+ ".obj", ".a", ".class", ".jar", ".so", ".dll", ".dylib", ".exe", ".wasm",+];+const CODE_FILENAMES = new Set([+ "dockerfile", "containerfile", "makefile", "gnumakefile", "justfile", "gemfile", "rakefile",+ "podfile", "brewfile", "jenkinsfile", "procfile", "vagrantfile", "build", "workspace",+ "cmakelists.txt", "package.json", "cargo.toml", "go.mod", "pyproject.toml",+]);+const REQUIREMENTS_FILE = /^requirements[\w.-]*\.(txt|in)$/;+const SCRIPT_DIRS = new Set(["bin", "scripts"]);+const AGENT_NOTES = new Set(["swarm.md", "plan.json", "readme"]);+const SCRATCH_PREFIXES = ["/tmp/", "/var/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/", "/dev/"];+const WINDOWS_SCRATCH = /^[a-z]:\/windows\/temp\/|\/appdata\/local\/temp\//;+const WINDOWS_DRIVE = /^[a-z]:\//;++function normPath(path: string): string {+ let norm = path.replace(/\\/g, "/").toLowerCase();+ while (norm.startsWith("./")) norm = norm.slice(2);+ return norm;+}++function isScratch(norm: string): boolean {+ return SCRATCH_PREFIXES.some((prefix) => norm.startsWith(prefix)) || WINDOWS_SCRATCH.test(norm);+}++function notProject(norm: string): boolean {+ if (isScratch(norm)) return true;+ if (INTERNAL_DIRS.some((dir) => norm.startsWith(dir) || norm.includes(`/${dir}`))) return true;+ const folders = norm.split("/").slice(0, -1);+ const absolute = norm.startsWith("/") || norm.startsWith("~/") || WINDOWS_DRIVE.test(norm);+ return folders.some((folder, index) => BUILD_OUTPUT_DIRS.has(folder)+ && ((!absolute && index === 0) || (absolute && index > 0 && !SOURCE_DIRS.has(folders[index - 1] ?? ""))));+}++/** Whether a changed file counts as project code (session_qc.is_code_path). */+export function isCodePath(path: string): boolean {+ const norm = normPath(path.trim());+ if (!norm || notProject(norm)) return false;+ const folders = norm.split("/").slice(0, -1);+ const name = norm.slice(norm.lastIndexOf("/") + 1);+ if (!name) return false;+ if (GENERATED_FILES.has(name) || GENERATED_SUFFIXES.some((suffix) => name.endsWith(suffix))) return false;+ if (CODE_FILENAMES.has(name) || REQUIREMENTS_FILE.test(name)) return true;+ if (folders.at(-1) === "requirements" && name.endsWith(".txt")) return true;+ if (AGENT_NOTES.has(name)) return false;+ if (!name.includes(".")) return folders.some((folder) => SCRIPT_DIRS.has(folder));+ return !NON_CODE_EXTENSIONS.has(name.slice(name.lastIndexOf(".")));+}++// --- Commands (session_qc.BUILD_TEST, session_qc_v2._runs) --------------------++/** A build, a test run or a linter/type check (session_qc.BUILD_TEST). */+const BUILD_TEST = new RegExp(+ String.raw`^(pytest|unittest|tox|nox|npm (run )?(test|build|lint)|`+ + String.raw`yarn (test|build)|pnpm (test|build)|bun test|jest|vitest|mocha|`+ + String.raw`go (test|build|vet)|cargo (test|build|check|clippy)|make\b|cmake|`+ + String.raw`mvn|gradle|dotnet (test|build)|tsc\b|eslint|ruff|mypy|flake8|`+ + String.raw`black --check|gcc|g\+\+|clang|javac|rustc|`+ + String.raw`python3? -m (pytest|unittest|py_compile)|node --test|php(unit)?|`+ + String.raw`rspec)`,+ "i",+);+/** Running the program itself: a script, a dev server, the built binary. */+const PROGRAM_RUN = new RegExp(+ String.raw`^(`+ + String.raw`(node|deno|bun|tsx|ts-node)( run)? [^-\s]\S*|`+ + String.raw`python[\d.]* (-m \S+|[^-\s]\S*\.py\b)|uv run|poetry run|`+ + String.raw`(npm|pnpm|yarn|bun) (run )?(start|dev|serve|preview|test|build)\b|npm run \S+|npx \S+|`+ + String.raw`go run|cargo run|dotnet run|swift run|mvn exec|gradle run|\./gradlew|`+ + String.raw`(bash|sh|zsh) [^-\s]\S*\.sh\b|ruby \S+\.rb\b|php \S+\.php\b|perl \S+\.pl\b|java (-jar )?\S+|`+ + String.raw`uvicorn|gunicorn|flask run|rails (s|server|test)\b|rake\b|bundle exec|`+ + String.raw`\.{1,2}/\S+|(\S+/)?(bin|build|target|dist|out)/\S+`+ + String.raw`)`,+ "i",+);+const ENV_ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=\S*$/;+const WRAPPERS = new Set(["sudo", "time", "nice", "env", "exec", "command", "timeout"]);++/** The commands of a shell line, each as its words (V2 `_split`/`_words`). */+export function commandSegments(command: string): string[][] {+ return command+ .split(/\n|&&|\|\||;|\||\(|\)|`|\$\(/)+ .map((segment) => {+ const words = segment.trim().split(/\s+/).filter(Boolean);+ while (words.length) {+ const first = words[0]!;+ if (ENV_ASSIGN.test(first)) { words.shift(); continue; }+ if (WRAPPERS.has(first)) {+ words.shift();+ if (first === "timeout" && /^\d/.test(words[0] ?? "")) words.shift();+ continue;+ }+ break;+ }+ return words;+ })+ .filter((words) => words.length > 0);+}++/** Whether a shell line builds, tests or runs the program. */+export function ranSomething(command: string): boolean {+ return commandSegments(command).some((words) => {+ const line = words.join(" ");+ return BUILD_TEST.test(line) || PROGRAM_RUN.test(line);+ });+}++const REMOTE_PROGRAMS = new Set([+ "gh", "glab", "ssh", "scp", "sftp", "aws", "gcloud", "az", "vercel", "netlify", "firebase",+ "supabase", "wrangler", "flyctl", "fly", "heroku", "railway", "kubectl", "helm", "terraform",+ "doctl", "ngrok", "cloudflared", "gsutil", "eas",+]);+const DB_CLIENTS = new Set(["psql", "pgcli", "mysql", "mariadb", "mycli", "mongosh", "mongo", "redis-cli"]);+const DOCKER_PROGRAMS = new Set(["docker", "docker-compose", "podman"]);+const PROBE_ARGS = new Set(["--help", "--version", "--dry-run", "--dryrun", "-h", "-v"]);+const GIT_REMOTE = /\bgit\s+(-C\s+\S+\s+)?(clone|fetch|pull|push|ls-remote)\b/;+const DB_SETUP = /createdb|create\s+database|initdb|\bmigrate\b|db:migrate|db\s+push|alembic\s+upgrade|drizzle-kit\s+(push|migrate)|\bseed\b|db:seed/i;+const QUOTED = /'[^']*'|"[^"]*"/g;++/** The personal service a shell line uses (V3 remote_service, local_database, remote_git, docker), or null. */+export function personalService(command: string, options: { dbBuilt?: boolean } = {}): string | null {+ const bare = command.replace(QUOTED, " ");+ if (GIT_REMOTE.test(bare)) return "a remote git repository";+ for (const words of commandSegments(bare)) {+ const program = (words[0] ?? "").replace(/^.*\//, "").toLowerCase();+ if (words.slice(1).some((word) => PROBE_ARGS.has(word))) continue;+ if (REMOTE_PROGRAMS.has(program)) return program;+ if (DOCKER_PROGRAMS.has(program)) return "docker";+ if (DB_CLIENTS.has(program) && !options.dbBuilt) return program;+ }+ return null;+}++// --- Folders ---------------------------------------------------------------++const HOME_FOLDER = /^(\/home\/[^/]+|\/users\/[^/]+|\/root|[a-z]:\/users\/[^/]+|~)\/?$/;++function folderKey(path: string): string {+ return normPath(path.trim()).replace(/\/+$/, "");+}++/** The project folder is the home folder itself (V3 home_folder). */+export function isHomeFolder(root: string): boolean {+ return HOME_FOLDER.test(folderKey(root));+}++function isAbsolute(norm: string): boolean {+ return norm.startsWith("/") || norm.startsWith("~") || WINDOWS_DRIVE.test(norm);+}++/** Whether a path the agent changed or worked in is outside the project folder (scratch folders are fine). */+export function outsideProject(path: string, root: string): boolean {+ let norm = folderKey(path);+ const base = folderKey(root);+ if (!norm || !base) return false;+ if (!isAbsolute(norm)) {+ // Relative to the project folder: only `..` can leave it.+ if (!norm.split("/").includes("..")) return false;+ norm = resolveDots(`${base}/${norm}`);+ }+ if (isScratch(`${norm}/`)) return false;+ return norm !== base && !norm.startsWith(`${base}/`);+}++function resolveDots(path: string): string {+ const out: string[] = [];+ for (const segment of path.split("/")) {+ if (segment === "..") {+ if (out.length > 1) out.pop();+ } else if (segment !== "." && (segment || out.length === 0)) {+ out.push(segment);+ }+ }+ return out.join("/");+}++// --- The checklist -----------------------------------------------------------++export type GoodSessionCheckId = "code" | "ran" | "project" | "finished" | "windows";+export type GoodSessionCheckState = "pass" | "fail" | "pending";++export type GoodSessionCheck = {+ id: GoodSessionCheckId;+ state: GoodSessionCheckState;+ /** "code changed", "ran/tested", "in project", "finish your turn". */+ label: string;+ /** Why it fails, or what to do next. */+ hint: string;+};++export type GoodSessionChecklist = {+ checks: GoodSessionCheck[];+ /** Every check passes: the session can earn a Good session ★. */+ good: boolean;+ /** The checks that still fail, without the running turn. */+ missing: GoodSessionCheck[];+ /** "Good session: code changed ✓ · ran/tested ✗ · in project ✓ · finish your turn". */+ text: string;+};++export type GoodSessionInput = {+ messages: readonly UIMessage[];+ /** The project folder the session runs in. */+ workspaceRoot: string;+ /** A turn is running (busy, retrying, waiting on a question or a permission). */+ turnRunning: boolean;+ /** Native Windows (not WSL). */+ nativeWindows: boolean;+};++const EDIT_TOOLS = new Set([+ "edit", "write", "patch", "multiedit", "apply_patch", "str_replace", "str_replace_editor", "create", "notebookedit",+]);+const SHELL_TOOLS = new Set(["bash", "shell", "run", "exec", "terminal", "execute", "bash_output"]);+const PATCH_FILE = /^\*\*\* (?:Add|Update|Delete) File: (.+)$|^\*\*\* Move to: (.+)$/gm;++type ToolCall = { tool: string; input: Record<string, unknown>; state: string; failed: boolean };++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function str(value: unknown): string {+ return typeof value === "string" ? value : "";+}++function toolCalls(message: UIMessage): ToolCall[] {+ const calls: ToolCall[] = [];+ for (const part of message.parts) {+ const record = part as unknown as Record<string, unknown>;+ let tool = "";+ if (part.type === "dynamic-tool") tool = str(record.toolName);+ else if (part.type.startsWith("tool-")) tool = part.type.slice(5);+ else continue;+ calls.push({+ tool: tool.toLowerCase().replace(/^.*[.:]/, ""),+ input: isRecord(record.input) ? record.input : {},+ state: str(record.state),+ failed: record.state === "output-error",+ });+ }+ return calls;+}++/** The files an edit tool changed: its path field, or the files its patch names. */+export function editedPaths(input: Record<string, unknown>): string[] {+ const direct = str(input.filePath) || str(input.file_path) || str(input.path) || str(input.file) || str(input.target_file);+ if (direct) return [direct];+ const patch = str(input.patchText) || str(input.patch) || str(input.input);+ const paths: string[] = [];+ for (const match of patch.matchAll(PATCH_FILE)) {+ const path = (match[1] ?? match[2] ?? "").trim();+ if (path) paths.push(path);+ }+ return paths;+}++function shellCommand(input: Record<string, unknown>): string {+ const command = input.command ?? input.cmd ?? input.script;+ if (Array.isArray(command)) return command.filter((word) => typeof word === "string").join(" ");+ return str(command);+}++function shellFolders(command: string, input: Record<string, unknown>): string[] {+ const folders = [str(input.workdir), str(input.cwd), str(input.directory)].filter(Boolean);+ for (const words of commandSegments(command.replace(QUOTED, (quoted) => quoted.slice(1, -1).replace(/\s/g, "\u0000")))) {+ if ((words[0] === "cd" || words[0] === "pushd") && words[1]) folders.push(words[1].replace(/\u0000/g, " "));+ }+ return folders;+}++function sessionErrorOf(message: UIMessage): boolean {+ return message.parts.some((part) => {+ const metadata = (part as { providerMetadata?: unknown }).providerMetadata;+ return isRecord(metadata) && isRecord(metadata.opencode) && metadata.opencode.sessionError !== undefined;+ });+}++function lastTurnState(messages: readonly UIMessage[], turnRunning: boolean): GoodSessionCheckState | "cut" {+ if (turnRunning) return "pending";+ const last = messages.at(-1);+ if (!last || last.role !== "assistant") return "cut";+ if (sessionErrorOf(last)) return "cut";+ const unfinished = toolCalls(last).some((call) => call.state === "input-streaming" || call.state === "input-available");+ return unfinished ? "cut" : "pass";+}++/** The checklist for a session, from its transcript. */+export function goodSessionChecklist(input: GoodSessionInput): GoodSessionChecklist {+ let code = false;+ let ran = false;+ let outside: string | null = null;+ let service: string | null = null;+ const home = input.workspaceRoot.trim() ? isHomeFolder(input.workspaceRoot) : false;+ const calls = input.messages.filter((message) => message.role === "assistant").flatMap(toolCalls);+ const dbBuilt = calls.some((call) => SHELL_TOOLS.has(call.tool) && DB_SETUP.test(shellCommand(call.input)));++ for (const call of calls) {+ if (EDIT_TOOLS.has(call.tool)) {+ for (const path of editedPaths(call.input)) {+ if (outsideProject(path, input.workspaceRoot)) {+ outside ??= path;+ continue;+ }+ if (!call.failed && isCodePath(path)) code = true;+ }+ } else if (SHELL_TOOLS.has(call.tool)) {+ const command = shellCommand(call.input);+ if (!command) continue;+ if (ranSomething(command)) ran = true;+ service ??= personalService(command, { dbBuilt });+ for (const folder of shellFolders(command, call.input)) {+ if (outsideProject(folder, input.workspaceRoot)) outside ??= folder;+ }+ }+ }++ const finished = lastTurnState(input.messages, input.turnRunning);+ const checks: GoodSessionCheck[] = [+ {+ id: "code",+ state: code ? "pass" : "fail",+ label: "code changed",+ hint: code ? "A project code file changed." : "Build or change real code in the project.",+ },+ {+ id: "ran",+ state: ran ? "pass" : "fail",+ label: "ran/tested",+ hint: ran ? "The agent ran a build, the tests or the program." : "Ask the agent to run it or its tests.",+ },+ {+ id: "project",+ state: home || outside || service ? "fail" : "pass",+ label: "in project",+ hint: home+ ? "The session runs in your home folder: open a project folder instead."+ : outside+ ? `Work outside the project folder: ${outside}`+ : service+ ? `Uses a personal service (${service}): keep the work inside the project.`+ : "The work stays inside the project folder.",+ },+ {+ id: "finished",+ state: finished === "cut" ? "fail" : finished,+ label: finished === "pending" ? "finish your turn" : finished === "pass" ? "turn finished" : "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.",+ },+ ];+ if (input.nativeWindows) {+ checks.push({ id: "windows", state: "fail", label: "native Windows", hint: "Sessions from native Windows don't count: use WSL." });+ }+ const missing = checks.filter((check) => check.state === "fail");+ const good = checks.every((check) => check.state === "pass");+ return { checks, good, missing, text: checklistText(checks, good) };+}++function mark(check: GoodSessionCheck): string {+ if (check.state === "pending") return check.label;+ return `${check.label} ${check.state === "pass" ? "✓" : "✗"}`;+}++export function checklistText(checks: readonly GoodSessionCheck[], good = checks.every((check) => check.state === "pass")): string {+ return `${good ? GOOD_SESSION_LABEL : "Good session"}: ${checks.map(mark).join(" · ")}`;+}++/** The one gentle nudge after a turn ends with something missing, or null. */+export function goodSessionNudge(checklist: GoodSessionChecklist): { title: string; body: string } | null {+ const missing = checklist.missing;+ if (!missing.length) return null;+ return {+ title: `Not a ${GOOD_SESSION_LABEL} yet`,+ body: missing.map((check) => check.hint).join(" "),+ };+}++/**+ * When to nudge: once per session, on the turn that just ended (running →+ * not running), and only when something is missing.+ */+export function shouldNudge(input: {+ wasRunning: boolean;+ running: boolean;+ checklist: GoodSessionChecklist;+ alreadyNudged: boolean;+}): boolean {+ return input.wasRunning && !input.running && !input.alreadyNudged && input.checklist.missing.length > 0;+}++// --- The don't-quit-mid-turn guard --------------------------------------------++export type TurnGuardAction = "close" | "quit" | "switch" | "delete";++/** Whether leaving (closing, quitting, switching or deleting) needs the confirm first. */+export function needsTurnGuard(input: { action: TurnGuardAction; turnRunning: boolean; targetSessionId?: string | null; currentSessionId?: string | null }): boolean {+ if (!input.turnRunning) return false;+ if (input.action === "switch") {+ return Boolean(input.currentSessionId) && input.targetSessionId !== input.currentSessionId;+ }+ return true;+}++// --- Native Windows ------------------------------------------------------------++export const WSL_BANNER_DISMISSED_KEY = "omnirush.goodSession.wslBannerDismissedDay.v1";++/** The local day ("2026-10-06"): a dismissed banner comes back the next day. */+export function localDay(now: Date = new Date()): string {+ const pad = (value: number) => String(value).padStart(2, "0");+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;+}++export function showWslBanner(input: { nativeWindows: boolean; dismissedDay: string | null; now?: Date }): boolean {+ return input.nativeWindows && input.dismissedDay !== localDay(input.now);+}diff --git a/apps/app/src/app/lib/quality.ts b/apps/app/src/app/lib/quality.tsindex 4e5c7cfe..615e41a6 100644--- a/apps/app/src/app/lib/quality.ts+++ b/apps/app/src/app/lib/quality.ts@@ -16,6 +16,7 @@ import type {OmniRushWheelSegment,} from "@omnirush/types/desktop-ipc";+import { GOOD_SESSION_LABEL, goodSessionWording } from "./good-session";import { compactTokenCount } from "./omnirush-usage";export type AccountQuality = OmniRushAccountQuality;@@ -58,7 +59,7 @@ export function qualityBadgeTitle(quality: AccountQuality): string {if (quality.tokensMultiplier < 1) parts.push(`tokens ×${quality.tokensMultiplier}`);if (quality.preview) parts.push("preview: spins pay 0 tokens");const head = parts.join(" · ");- return quality.nextTierHint ? `${head}\n${quality.nextTierHint}` : head;+ return quality.nextTierHint ? `${head}\n${goodSessionWording(quality.nextTierHint)}` : head;}/** Whether the spin button can spin now: spins left, and not all of them held back by a resting wheel. */@@ -242,9 +243,9 @@ export function nearMissText(spin: QualitySpin, jackpotTokens?: number | null):}/** The star, explained wherever it shows. */-export const CLIENT_GRADE_NOTE = "★ Replay-ready sessions earn +2 spins on a richer wheel.";+export const CLIENT_GRADE_NOTE = "★ Good sessions earn +2 spins on a richer wheel.";/** What users read for a client-grade session or spin (internal fields keep `client`). */-export const REPLAY_READY_LABEL = "Replay-ready ★";+export const GOOD_SESSION_STAR_LABEL = GOOD_SESSION_LABEL;/*** The prize shown `progress` (0..1) into the count-up: an ease-out that neverdiff --git a/apps/app/src/react-app/domains/quality/good-session.tsx b/apps/app/src/react-app/domains/quality/good-session.tsxnew file mode 100644index 00000000..f7a5e997--- /dev/null+++ b/apps/app/src/react-app/domains/quality/good-session.tsx@@ -0,0 +1,260 @@+/** @jsxImportSource react */+import { useEffect, useMemo, useRef, useState } from "react";+import type { UIMessage } from "ai";+import { AlertTriangle, Star, X } from "lucide-react";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { toast } from "@/components/ui/sonner";+import { cn } from "@/lib/utils";++import { openDesktopUrl } from "../../../app/lib/desktop";+import {+ GOOD_SESSION_GUIDE,+ GOOD_SESSION_GUIDE_LINK,+ GOOD_SESSION_LABEL,+ GOOD_SESSION_WSL_TIP,+ TURN_GUARD_DETAIL,+ TURN_GUARD_QUIT,+ TURN_GUARD_TITLE,+ TURN_GUARD_WAIT,+ WSL_BANNER_DISMISSED_KEY,+ WSL_BANNER_TEXT,+ WSL_GUIDE_URL,+ goodSessionChecklist,+ goodSessionNudge,+ localDay,+ shouldNudge,+ showWslBanner,+ type GoodSessionCheck,+} from "../../../app/lib/good-session";+import { readPref, writePref } from "../../../app/lib/quality";+import { isDesktopRuntime, isWindowsPlatform } from "../../../app/utils";+import { hasLiveSessionActivity, useSessionActivityStore } from "../session/status/session-activity-store";++/** Native Windows (the app itself; there is no WSL desktop build). The e2e hook forces it on Linux. */+export function isNativeWindowsHost(): boolean {+ if (typeof window !== "undefined" && window.__OMNIRUSH_ELECTRON__?.meta?.forceNativeWindows === true) return true;+ return isWindowsPlatform();+}++/** The four steps, plus the WSL tip. */+export function GoodSessionGuide({ className }: { className?: string }) {+ return (+ <div className={cn("text-xs", className)} data-testid="good-session-guide">+ <p className="font-medium text-foreground">{GOOD_SESSION_GUIDE_LINK}</p>+ <ol className="mt-1 list-decimal space-y-0.5 ps-4 leading-5 text-muted-foreground marker:text-muted-foreground/60">+ {GOOD_SESSION_GUIDE.map((step) => <li key={step}>{step}</li>)}+ </ol>+ <p className="mt-1 leading-5 text-muted-foreground" data-testid="good-session-wsl-tip">{GOOD_SESSION_WSL_TIP}</p>+ </div>+ );+}++function CheckMark({ check }: { check: GoodSessionCheck }) {+ return (+ <span+ title={check.hint}+ data-check={check.id}+ data-state={check.state}+ className={cn(+ "whitespace-nowrap",+ check.state === "pass" && "text-foreground",+ check.state === "fail" && "text-amber-11",+ )}+ >+ {check.label}+ {check.state === "pending" ? null : <span aria-hidden="true">{check.state === "pass" ? " ✓" : " ✗"}</span>}+ </span>+ );+}++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 [];+ }+}++function rememberNudged(sessionId: string) {+ const ids = nudgedSessions().filter((id) => id !== sessionId);+ ids.push(sessionId);+ writePref(NUDGED_STORAGE_KEY, JSON.stringify(ids.slice(-NUDGED_KEEP)));+}++export type GoodSessionChecklistBarProps = {+ sessionId: string;+ messages: readonly UIMessage[];+ workspaceRoot: string;+ turnRunning: boolean;+};++/**+ * The live checklist over the composer: "Good session: code changed ✓ ·+ * ran/tested ✗ · in project ✓ · finish your turn". One gentle nudge per+ * session when a turn ends with something missing.+ */+export function GoodSessionChecklistBar(props: GoodSessionChecklistBarProps) {+ const nativeWindows = useMemo(() => isNativeWindowsHost(), []);+ const checklist = useMemo(() => goodSessionChecklist({+ messages: props.messages,+ workspaceRoot: props.workspaceRoot,+ turnRunning: props.turnRunning,+ nativeWindows,+ }), [nativeWindows, props.messages, props.turnRunning, props.workspaceRoot]);+ const hasPrompt = props.messages.some((message) => message.role === "user");++ // 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 });+ useEffect(() => {+ const previous = wasRunning.current;+ wasRunning.current = { sessionId: props.sessionId, running: props.turnRunning };+ if (previous.sessionId !== props.sessionId) return;+ const alreadyNudged = nudgedSessions().includes(props.sessionId);+ if (!shouldNudge({ wasRunning: previous.running, running: props.turnRunning, checklist, alreadyNudged })) return;+ const nudge = goodSessionNudge(checklist);+ if (!nudge) return;+ rememberNudged(props.sessionId);+ toast(nudge.title, { id: `good-session-nudge:${props.sessionId}`, description: nudge.body, duration: 12_000 });+ }, [checklist, props.sessionId, props.turnRunning]);++ if (!hasPrompt) return null;+ return (+ <div className="px-4 max-lg:px-3 lg:px-8" data-testid="good-session-checklist" data-good={checklist.good ? "" : undefined}>+ <div className="mx-auto flex max-w-[800px] items-center gap-2 pb-1.5">+ <div+ className="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"+ aria-label={checklist.text}+ role="status"+ >+ <Star className={cn("size-3 shrink-0", checklist.good ? "fill-current text-foreground" : "text-muted-foreground")} aria-hidden="true" />+ <span className="whitespace-nowrap font-medium text-foreground">{checklist.good ? GOOD_SESSION_LABEL : "Good session"}:</span>+ {checklist.checks.map((check, index) => (+ <span key={check.id} className="inline-flex items-center gap-1.5">+ {index > 0 ? <span aria-hidden="true" className="text-muted-foreground/60">·</span> : null}+ <CheckMark check={check} />+ </span>+ ))}+ </div>+ <Popover>+ <PopoverTrigger+ render={(+ <button+ type="button"+ data-testid="good-session-guide-link"+ className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground underline-offset-2 transition hover:text-foreground hover:underline"+ />+ )}+ >+ {GOOD_SESSION_GUIDE_LINK}+ </PopoverTrigger>+ <PopoverContent side="top" align="end" className="w-72 gap-2 rounded-2xl p-3">+ <GoodSessionGuide />+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+}++/** "Sessions from native Windows don't count as Good sessions. Switch to WSL": dismissible, back the next day. */+export function WslBanner({ className }: { className?: string }) {+ const nativeWindows = useMemo(() => isNativeWindowsHost(), []);+ const [dismissedDay, setDismissedDay] = useState(() => readPref(WSL_BANNER_DISMISSED_KEY));+ // Comes back on the next day even when the app stays open.+ const [now, setNow] = useState(() => new Date());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(new Date()), 60 * 60_000);+ return () => window.clearInterval(timer);+ }, []);+ if (!showWslBanner({ nativeWindows, dismissedDay, now })) return null;+ const dismiss = () => {+ const day = localDay();+ writePref(WSL_BANNER_DISMISSED_KEY, day);+ setDismissedDay(day);+ };+ return (+ <div className={cn("px-4 max-lg:px-3 lg:px-8", className)}>+ <div+ role="status"+ data-testid="good-session-wsl-banner"+ className="mx-auto mb-2 flex max-w-[800px] items-center gap-2 rounded-lg border border-amber-7/40 bg-amber-2/30 px-3 py-2 text-xs text-amber-11"+ >+ <AlertTriangle className="size-3.5 shrink-0" aria-hidden="true" />+ <span className="min-w-0 flex-1">+ {WSL_BANNER_TEXT}{" "}+ <button+ type="button"+ data-testid="good-session-wsl-link"+ className="font-medium underline underline-offset-2 hover:text-amber-12"+ onClick={() => void openDesktopUrl(WSL_GUIDE_URL).catch(() => undefined)}+ >+ Open the WSL guide+ </button>+ </span>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label="Dismiss"+ data-testid="good-session-wsl-dismiss"+ onClick={dismiss}+ className="-me-1 text-amber-11 hover:text-amber-12"+ >+ <X />+ </Button>+ </div>+ </div>+ );+}++/** The confirm before switching or deleting a session whose turn is running. */+export function TurnGuardDialog(props: { open: boolean; onWait: () => void; onQuit: () => void }) {+ return (+ <AlertDialog open={props.open} onOpenChange={(open) => { if (!open) props.onWait(); }}>+ <AlertDialogContent data-testid="turn-guard-dialog">+ <AlertDialogHeader>+ <AlertDialogMedia className="bg-amber-3/50 text-amber-11">+ <AlertTriangle />+ </AlertDialogMedia>+ <AlertDialogTitle>{TURN_GUARD_TITLE}</AlertDialogTitle>+ <AlertDialogDescription>{TURN_GUARD_DETAIL}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogAction variant="outline" data-testid="turn-guard-quit" onClick={props.onQuit}>+ {TURN_GUARD_QUIT}+ </AlertDialogAction>+ <AlertDialogCancel variant="default" autoFocus data-testid="turn-guard-wait">+ {TURN_GUARD_WAIT}+ </AlertDialogCancel>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++/** Tells the desktop shell whether any turn is running, so closing or quitting asks first. */+export function TurnRunningSync() {+ const running = useSessionActivityStore((store) => hasLiveSessionActivity(store.statusesByWorkspaceId));+ useEffect(() => {+ if (!isDesktopRuntime()) return;+ void Promise.resolve(window.__OMNIRUSH_ELECTRON__?.invokeDesktop?.("__setTurnRunning", running)).catch(() => undefined);+ }, [running]);+ return null;+}diff --git a/apps/app/src/react-app/domains/quality/quality-notice.tsx b/apps/app/src/react-app/domains/quality/quality-notice.tsxindex 9e8f5240..4a64a440 100644--- a/apps/app/src/react-app/domains/quality/quality-notice.tsx+++ b/apps/app/src/react-app/domains/quality/quality-notice.tsx@@ -9,7 +9,7 @@ import { cn } from "@/lib/utils";import { omnirushAccountStatus, omnirushQualityDetails } from "../../../app/lib/desktop";import {CLIENT_GRADE_NOTE,- REPLAY_READY_LABEL,+ GOOD_SESSION_STAR_LABEL,canSpinNow,isCoachingNotice,qualityTierLabel,@@ -23,6 +23,8 @@ import type { OmniRushQualitySession } from "@omnirush/types/desktop-ipc";import { BiggestWinTicker, NextSpinHint, QualityTierBadge, StreakLine } from "./quality-parts";import { QualitySpinDialog } from "./quality-spin-dialog";import { useQualityPopups } from "./use-quality-popups";+import { GoodSessionGuide } from "./good-session";+import { goodSessionWording } from "../../../app/lib/good-session";/** Used only when the server sends no `fail_labels` entry for a code. */const FALLBACK_FAIL_LABELS: Record<string, string> = {@@ -69,12 +71,12 @@ export function SessionReasons({ reasons }: { reasons: QualitySessionReasons | n<span className="shrink-0 font-medium text-foreground">+{session.spins} spin{session.spins === 1 ? "" : "s"}</span>) : null}</div>- {session.why ? <div className="mt-0.5 text-xs leading-5 text-foreground">{session.why}</div> : null}+ {session.why ? <div className="mt-0.5 text-xs leading-5 text-foreground">{goodSessionWording(session.why)}</div> : null}{workSummary(session.work) ? <div className="mt-0.5 text-[11px] text-muted-foreground">{workSummary(session.work)}</div> : null}{session.fails.length || session.reproducible === "pass" || session.clientGrade ? (<div className="mt-1.5 flex flex-wrap gap-1">{session.clientGrade ? (- <Badge variant="secondary" data-testid="quality-client-grade" className="h-4 px-1.5 text-[10px] font-normal text-muted-foreground">{REPLAY_READY_LABEL}</Badge>+ <Badge variant="secondary" data-testid="quality-client-grade" className="h-4 px-1.5 text-[10px] font-normal text-muted-foreground">{GOOD_SESSION_STAR_LABEL}</Badge>) : session.reproducible === "pass" ? (<Badge variant="secondary" data-testid="quality-reproducible" className="h-4 px-1.5 text-[10px] font-normal text-muted-foreground">Reproducible ✓</Badge>) : null}@@ -116,8 +118,8 @@ export function QualityNoticeCard(props: QualityNoticeCardProps) {const coaching = isCoachingNotice(notice, quality);const [whyOpen, setWhyOpen] = useState(false);const [sessions, setSessions] = useState<QualitySessionReasons | null>(null);- const title = notice?.title ?? `Quality: ${qualityTierLabel(quality.tier)}`;- const body = notice?.body || (notice ? "" : quality.nextTierHint ?? "");+ const title = goodSessionWording(notice?.title ?? `Quality: ${qualityTierLabel(quality.tier)}`);+ const body = goodSessionWording(notice?.body || (notice ? "" : quality.nextTierHint ?? ""));const spinnable = canSpinNow(quality);const Icon = coaching ? Lightbulb : Gift;@@ -168,13 +170,15 @@ export function QualityNoticeCard(props: QualityNoticeCardProps) {<div data-testid="quality-notice-tips"><p className="text-xs font-medium text-foreground">{coaching ? "How to earn spins" : "Tips"}</p><ul className="mt-1 list-disc space-y-1 ps-4 text-xs leading-5 text-muted-foreground marker:text-muted-foreground/60">- {quality.tips.map((tip) => <li key={tip}>{tip}</li>)}+ {quality.tips.map((tip) => <li key={tip}>{goodSessionWording(tip)}</li>)}</ul></div>) : coaching ? (<p className="text-xs font-medium text-foreground">How to earn spins</p>) : null}+ <GoodSessionGuide className="rounded-lg border border-border px-3 py-2" />+{coaching ? (<div><button@@ -226,7 +230,7 @@ export function QualityNudge(props: { text: string; onDismiss: () => void }) {className={cn("fixed bottom-4 right-4 z-[64] flex max-w-[360px] items-start gap-3 p-4 text-sm", TOAST_SURFACE)}><Gift className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden="true" />- <span className="flex-1 text-muted-foreground">{props.text}</span>+ <span className="flex-1 text-muted-foreground">{goodSessionWording(props.text)}</span><Button type="button" variant="ghost" size="icon-xs" onClick={props.onDismiss} aria-label="Dismiss" className="-me-1 -mt-0.5 text-muted-foreground"><X /></Button>diff --git a/apps/app/src/react-app/domains/quality/quality-parts.tsx b/apps/app/src/react-app/domains/quality/quality-parts.tsxindex 8cc1e470..6cdce0a3 100644--- a/apps/app/src/react-app/domains/quality/quality-parts.tsx+++ b/apps/app/src/react-app/domains/quality/quality-parts.tsx@@ -3,6 +3,7 @@ import { Badge } from "@/components/ui/badge";import { cn } from "@/lib/utils";import { compactTokenCount } from "../../../app/lib/omnirush-usage";+import { goodSessionWording } from "../../../app/lib/good-session";import { qualityBadgeText, qualityBadgeTitle, type AccountQuality } from "../../../app/lib/quality";/** The tier, as a small neutral badge. Dashed in preview (spins pay nothing). */@@ -67,7 +68,7 @@ export function spinRowTitle(quality: AccountQuality): string {const ready = quality.spinsAvailable;const stars = Math.min(ready, quality.clientSpinsAvailable ?? 0);return ready > 0- ? `${ready} spin${ready === 1 ? "" : "s"} ready${stars > 0 ? `, ${stars} replay-ready ★ on the richer wheel` : ""}`+ ? `${ready} spin${ready === 1 ? "" : "s"} ready${stars > 0 ? `, ${stars} Good session ★ on the richer wheel` : ""}`: "No spins yet: good sessions earn spins.";}@@ -85,7 +86,7 @@ export function SpinCounts({ quality }: { quality: AccountQuality }) {<Badgevariant="secondary"data-testid="quality-client-spins"- title={`${stars} replay-ready ★`}+ title={`${stars} Good session${stars === 1 ? "" : "s"} ★`}className="h-4 px-1.5 text-[10px] font-normal text-muted-foreground tabular-nums">★{shortCount(stars)}@@ -95,12 +96,12 @@ export function SpinCounts({ quality }: { quality: AccountQuality }) {);}-/** "4-day streak · +1 spin per replay-ready ★ session · 7 days: +2". */+/** "4-day streak · +1 spin per Good session ★ · 7 days: +2". */export function streakText(quality: Pick<AccountQuality, "streakDays" | "streakMultiplier" | "streakNext">): string | null {if (quality.streakDays <= 0 && !quality.streakNext) return null;const parts: string[] = [];parts.push(quality.streakDays > 0 ? `${quality.streakDays}-day streak` : "No streak yet");- if (quality.streakMultiplier > 0) parts.push(`+${quality.streakMultiplier} spin${quality.streakMultiplier === 1 ? "" : "s"} per replay-ready ★ session`);+ if (quality.streakMultiplier > 0) parts.push(`+${quality.streakMultiplier} spin${quality.streakMultiplier === 1 ? "" : "s"} per Good session ★`);if (quality.streakNext) parts.push(`${quality.streakNext.days} days: +${quality.streakNext.bonusSpins}`);return parts.join(" · ");}@@ -133,7 +134,7 @@ export function NextSpinHint({ quality, className }: { quality: AccountQuality;<ProgressRing progress={hint.progress} className="mt-px text-muted-foreground" /><div className="min-w-0"><div className="font-medium text-foreground">Next spin · {Math.round(hint.progress * 100)}%</div>- <div className="mt-0.5 leading-5 text-muted-foreground">{hint.text}</div>+ <div className="mt-0.5 leading-5 text-muted-foreground">{goodSessionWording(hint.text)}</div></div></div>);diff --git a/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx b/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsxindex b7ca3429..321399ec 100644--- a/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx+++ b/apps/app/src/react-app/domains/quality/quality-spin-dialog.tsx@@ -12,7 +12,7 @@ import { omnirushAccountStatus, omnirushQualityDetails, omnirushQualitySpin, omnimport { compactTokenCount } from "../../../app/lib/omnirush-usage";import {CLIENT_GRADE_NOTE,- REPLAY_READY_LABEL,+ GOOD_SESSION_STAR_LABEL,countUpValue,DEFAULT_WHEEL_SEGMENTS,SOUND_STORAGE_KEY,@@ -84,7 +84,7 @@ function recentSpinLabel(spin: OmniRushQualitySpinRecord): string {return spin.status === "ready" ? "ready" : spin.status;}-/** The last spins (newest first) as one muted line, ★ on the replay-ready ones. */+/** The last spins (newest first) as one muted line, ★ on the Good session ones. */export function RecentSpins({ spins }: { spins: OmniRushQualitySpinRecord[] }) {const shown = spins.slice(0, 10);if (!shown.length) return null;@@ -95,8 +95,8 @@ export function RecentSpins({ spins }: { spins: OmniRushQualitySpinRecord[] }) {{shown.map((spin, index) => (<likey={spin.id}- data-replay-ready={spin.clientGrade ? "" : undefined}- title={spin.clientGrade ? REPLAY_READY_LABEL : spin.status}+ data-good-session={spin.clientGrade ? "" : undefined}+ title={spin.clientGrade ? GOOD_SESSION_STAR_LABEL : spin.status}className="tabular-nums">{spin.clientGrade ? "★ " : ""}@@ -251,11 +251,11 @@ export function QualitySpinPanel(props: QualitySpinPanelProps) {const celebrate = result?.celebrate ?? "none";const busy = phase === "requesting" || phase === "spinning" || (phase === "result" && !settled);const canSpin = !busy && spinsLeft > 0 && !(phase !== "result" && resting);- // Before a spin: the wheel the next spin uses (the richer one while replay-ready spins are+ // Before a spin: the wheel the next spin uses (the richer one while Good session ★ spins are// waiting). From the answer on: the wheel the server actually used.const nextIsReplayReady = !result && quality.clientSpinsAvailable > 0 && clientSegments.length > 0;const shownSegments = result ? segments : nextIsReplayReady ? clientSegments : segments;- const replayWheel = result ? (result.clientGrade ? "Replay-ready ★ wheel" : null) : nextIsReplayReady ? "Replay-ready ★ wheel (next spin)" : null;+ const replayWheel = result ? (result.clientGrade ? "Good session ★ wheel" : null) : nextIsReplayReady ? "Good session ★ wheel (next spin)" : null;const resultLine = result? [result.preview || result.capped ? spinPayoutText(result) : result.potBalance !== null ? `Pot: ${compactTokenCount(result.potBalance)} tokens` : "Added to your pot",@@ -274,7 +274,7 @@ export function QualitySpinPanel(props: QualitySpinPanelProps) {<Description>{spinsLeft} spin{spinsLeft === 1 ? "" : "s"} ready{!result && quality.clientSpinsAvailable > 0 ? (- <span data-testid="quality-dialog-client-spins"> · ★{quality.clientSpinsAvailable} replay-ready</span>+ <span data-testid="quality-dialog-client-spins"> · ★{quality.clientSpinsAvailable} Good session</span>) : null}</Description></div>@@ -326,7 +326,7 @@ export function QualitySpinPanel(props: QualitySpinPanelProps) {</span>{settled && celebrate === "jackpot" ? <Badge variant="secondary" className="font-normal">Jackpot</Badge> : null}{settled && result.clientGrade ? (- <Badge variant="secondary" className="font-normal text-muted-foreground">{REPLAY_READY_LABEL}</Badge>+ <Badge variant="secondary" className="font-normal text-muted-foreground">{GOOD_SESSION_STAR_LABEL}</Badge>) : settled && result.reproducible ? (<Badge variant="secondary" className="font-normal text-muted-foreground">Reproducible</Badge>) : null}@@ -366,7 +366,7 @@ export function QualitySpinPanel(props: QualitySpinPanelProps) {{busy ? "Spinning" : settled ? `Spin again (${spinsLeft} left)` : spinsLeft > 1 ? `Spin (${spinsLeft} ready)` : "Spin"}</Button>) : (- <p className="text-sm text-muted-foreground">No spins left. Replay-ready ★ sessions earn more.</p>+ <p className="text-sm text-muted-foreground">No spins left. Good sessions ★ earn more.</p>)}</DialogFooter></>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 2c4c7862..f7d37de1 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,6 +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 { needsTurnGuard } from "@/app/lib/good-session";+import { TurnGuardDialog } from "@/react-app/domains/quality/good-session";import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";import {availableNarrowPane,@@ -509,6 +511,8 @@ export function SessionPage(props: SessionPageProps) {const [renameTitle, setRenameTitle] = useState("");const [renameBusy, setRenameBusy] = useState(false);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 [deleteBusy, setDeleteBusy] = useState(false);const [sessionActionId, setSessionActionId] = useState<string | null>(null);const workbenchPrimary = useWorkbenchStore((state) => state.primary);@@ -1172,6 +1176,21 @@ export function SessionPage(props: SessionPageProps) {props.sidebar.onOpenSession(workspaceId, sessionId);}, [focusWorkbenchPane, omniRushbenchTab, props.sidebar]);+ const sessionTurnRunning = useCallback((sessionId: string | null | undefined) => {+ const status = sessionId ? props.sidebar.sessionStatusById[sessionId] : undefined;+ return status === "thinking" || status === "responding" || status === "compacting" || status === "waiting";+ }, [props.sidebar.sessionStatusById]);++ // The sidebar's switch: leaving a session whose turn runs asks first.+ const guardedOpenSessionTab = useCallback((workspaceId: string, sessionId: string) => {+ const currentSessionId = props.sidebar.selectedSessionId ?? null;+ if (needsTurnGuard({ action: "switch", turnRunning: sessionTurnRunning(currentSessionId), currentSessionId, targetSessionId: sessionId })) {+ setTurnGuardProceed(() => () => openSessionTab(workspaceId, sessionId));+ return;+ }+ openSessionTab(workspaceId, sessionId);+ }, [openSessionTab, props.sidebar.selectedSessionId, sessionTurnRunning]);+const closeSecondaryWorkbenchPane = useCallback(() => {setWorkbenchSplit(null);}, [setWorkbenchSplit]);@@ -1398,14 +1417,21 @@ export function SessionPage(props: SessionPageProps) {workspaceConnectionStateById={props.sidebar.workspaceConnectionStateById}newTaskDisabled={props.sidebar.newTaskDisabled}onSelectWorkspace={props.sidebar.onSelectWorkspace}- onOpenSession={openSessionTab}+ onOpenSession={guardedOpenSessionTab}onPrefetchSession={props.sidebar.onPrefetchSession}onCreateTaskInWorkspace={props.sidebar.onCreateTaskInWorkspace}onCreateSplitTaskInWorkspace={props.sidebar.onCreateSplitTaskInWorkspace}onOpenRenameSession={props.onRenameSession ? openRenameModal : undefined}onOpenDeleteSession={props.onDeleteSession ? (sessionId) => {- setSessionActionId(sessionId);- setDeleteOpen(true);+ const openDelete = () => {+ setSessionActionId(sessionId);+ setDeleteOpen(true);+ };+ if (needsTurnGuard({ action: "delete", turnRunning: sessionTurnRunning(sessionId) })) {+ setTurnGuardProceed(() => openDelete);+ return;+ }+ openDelete();} : undefined}onArchiveSession={props.onArchiveSession ? (sessionId, archived) => {void props.onArchiveSession?.(sessionId, archived);@@ -2048,6 +2074,16 @@ export function SessionPage(props: SessionPageProps) {/>) : null}+ <TurnGuardDialog+ open={turnGuardProceed !== null}+ onWait={() => setTurnGuardProceed(null)}+ onQuit={() => {+ const proceed = turnGuardProceed;+ setTurnGuardProceed(null);+ proceed?.();+ }}+ />+{props.onDeleteSession ? (<ConfirmModalopen={deleteOpen}diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsxindex c90c51e4..403ceb20 100644--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx@@ -42,6 +42,7 @@ import { omnirushAccountStatus, type WorkspaceInfo } from "../../../../app/lib/dimport { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";import { isDesktopRuntime } from "../../../../app/lib/runtime-env";import { refreshAccountStatus, setQualitySessionId, useAccountStatusStore, useQualityUiStore, type AccountQuality } from "../../../../app/lib/quality";+import { goodSessionWording } from "../../../../app/lib/good-session";import { ProgressRing, QualityTierBadge, SpinCounts, spinRowTitle } from "../../quality/quality-parts";import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";import { NotificationBell } from "../../../shell/notification-center";@@ -1011,7 +1012,7 @@ function QualitySpinRow({ quality }: { quality: AccountQuality }) {<buttontype="button"onClick={openPanel}- title={hint?.text ?? quality.nextTierHint ?? "Quality rewards"}+ title={goodSessionWording(hint?.text ?? quality.nextTierHint ?? "Quality rewards")}aria-label={`Next spin ${progress}`}data-testid="quality-footer-next"className="absolute inset-e-1 top-1.5 flex h-5 items-center gap-1 rounded-md px-1 text-[11px] text-muted-foreground tabular-nums transition hover:bg-sidebar-accent hover:text-foreground group-data-[collapsible=icon]:hidden"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 7adfeb11..b9767329 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,6 +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 { 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 {@@ -3293,6 +3294,13 @@ export function SessionSurface(props: SessionSurfaceProps) {{attachment.name}{sending ? " · Uploading…" : ""}</div>)))}+ <WslBanner />+ <GoodSessionChecklistBar+ sessionId={props.sessionId}+ messages={renderedMessages}+ workspaceRoot={props.workspaceRoot}+ turnRunning={chatStreaming || (effectiveActivityStatus !== "idle" && effectiveActivityStatus !== "error")}+ /><ReactSessionComposerrunModeControl={<WorkspaceRunModeMenu client={props.client} workspaceId={props.workspaceId} busy={chatStreaming || preparingCloudTools || Boolean(props.activePermission || props.activeQuestion)} />}fullPermissionsControl={<FullPermissionsToggle client={props.client} workspaceId={props.workspaceId} />}diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsxindex d873f44c..4f04120b 100644--- a/apps/app/src/react-app/shell/app-root.tsx+++ b/apps/app/src/react-app/shell/app-root.tsx@@ -47,6 +47,7 @@ import { SessionRoute } from "./session-route";import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";import { UpdateGate } from "./update-gate";import { QualityRewards } from "../domains/quality/quality-notice";+import { TurnRunningSync } from "../domains/quality/good-session";import { SettingsRoute } from "./settings-route";import { ShellConfigProvider } from "./shell-config";import { WelcomeRoute } from "./welcome-route";@@ -512,6 +513,7 @@ export function AppRoot() {<LoadingOverlay /><CloudWorkspaceOverlay />{isDesktopRuntime() ? <QualityRewards /> : null}+ {isDesktopRuntime() ? <TurnRunningSync /> : null}</CloudWorkspaceStatusProvider></OmniRushWebAccessGate></DenSigninGate>diff --git a/apps/app/tests/good-session.test.tsx b/apps/app/tests/good-session.test.tsxnew file mode 100644index 00000000..8f37f914--- /dev/null+++ b/apps/app/tests/good-session.test.tsx@@ -0,0 +1,278 @@+import { describe, expect, test } from "bun:test";+import type { UIMessage } from "ai";+import { renderToStaticMarkup } from "react-dom/server";++import {+ GOOD_SESSION_GUIDE,+ TURN_GUARD_MESSAGE,+ TURN_GUARD_QUIT,+ TURN_GUARD_WAIT,+ checklistText,+ goodSessionChecklist,+ goodSessionNudge,+ goodSessionWording,+ isCodePath,+ isHomeFolder,+ localDay,+ needsTurnGuard,+ outsideProject,+ personalService,+ ranSomething,+ shouldNudge,+ showWslBanner,+} from "../src/app/lib/good-session";+import { GoodSessionGuide } from "../src/react-app/domains/quality/good-session";++const ROOT = "/home/dev/projects/todo-api";++let seq = 0;+function tool(toolName: string, input: Record<string, unknown>, state: "output-available" | "output-error" | "input-streaming" = "output-available") {+ seq += 1;+ return state === "output-error"+ ? { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input, errorText: "failed" }+ : state === "input-streaming"+ ? { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input }+ : { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input, output: "ok" };+}++function transcript(...assistantParts: unknown[][]): UIMessage[] {+ const messages: UIMessage[] = [];+ assistantParts.forEach((parts, index) => {+ messages.push({ id: `u${index}`, role: "user", parts: [{ type: "text", text: "build the API" }] });+ messages.push({ id: `a${index}`, role: "assistant", parts: [...parts, { type: "text", text: "Done." }] as UIMessage["parts"] });+ });+ return messages;+}++function states(messages: UIMessage[], options: { turnRunning?: boolean; nativeWindows?: boolean; root?: string } = {}) {+ const result = goodSessionChecklist({+ messages,+ workspaceRoot: options.root ?? ROOT,+ turnRunning: options.turnRunning ?? false,+ nativeWindows: options.nativeWindows ?? false,+ });+ return { result, by: Object.fromEntries(result.checks.map((check) => [check.id, check.state])) };+}++describe("code files mirror session_qc.is_code_path", () => {+ test("source, manifests and build files count; docs, lockfiles, caches and build output do not", () => {+ for (const path of ["src/app.ts", "main.py", "Dockerfile", "package.json", "requirements-dev.txt", "scripts/deploy", "src/build/x.ts", `${ROOT}/lib/db.go`]) {+ expect(isCodePath(path)).toBe(true);+ }+ for (const path of ["README.md", "notes.txt", "pnpm-lock.yaml", "Cargo.lock", "node_modules/x/index.js", "dist/app.js", ".opencode/plan.md", "/tmp/scratch.py", "bin", "logo.png", "README"]) {+ expect(isCodePath(path)).toBe(false);+ }+ });+});++describe("commands mirror session_qc.BUILD_TEST, plus running the program", () => {+ test("builds, tests and program runs count, reads do not", () => {+ for (const command of [+ "npm test", "pnpm build", "cd api && pytest -q", "python3 -m pytest tests", "go test ./...", "cargo build --release",+ "make", "npx tsc --noEmit", "tsc -p .", "node server.js", "python app.py", "./target/release/todo", "FOO=1 npm run dev",+ "bun test", "bash run.sh", "timeout 20 node index.mjs",+ ]) {+ expect(ranSomething(command)).toBe(true);+ }+ for (const command of ["ls -la", "cat package.json", "git status", "rg TODO src", "npm install", "echo hi > a.txt", "mkdir -p src"]) {+ expect(ranSomething(command)).toBe(false);+ }+ });++ test("personal services: remote programs, databases it did not build, docker, remote git", () => {+ expect(personalService("gh pr create")).toBe("gh");+ expect(personalService("ssh deploy@host 'ls'")).toBe("ssh");+ expect(personalService("docker compose up -d")).toBe("docker");+ expect(personalService("git push origin main")).toBe("a remote git repository");+ expect(personalService("psql -c 'select 1'")).toBe("psql");+ expect(personalService("psql -c 'select 1'", { dbBuilt: true })).toBeNull();+ expect(personalService("docker --version")).toBeNull();+ expect(personalService("rg 'git push' src")).toBeNull();+ expect(personalService("npm test")).toBeNull();+ });+});++describe("folders", () => {+ test("home folder and paths outside the project", () => {+ expect(isHomeFolder("/home/dev")).toBe(true);+ expect(isHomeFolder("/Users/dev/")).toBe(true);+ expect(isHomeFolder("C:\\Users\\dev")).toBe(true);+ expect(isHomeFolder(ROOT)).toBe(false);+ expect(outsideProject(`${ROOT}/src/a.ts`, ROOT)).toBe(false);+ expect(outsideProject("src/a.ts", ROOT)).toBe(false);+ expect(outsideProject("/home/dev/other/a.ts", ROOT)).toBe(true);+ expect(outsideProject("../other/a.ts", ROOT)).toBe(true);+ expect(outsideProject("/tmp/scratch", ROOT)).toBe(false);+ expect(outsideProject("/home/dev/projects/todo-api-old/a.ts", ROOT)).toBe(true);+ expect(outsideProject("C:\\work\\app\\src\\a.ts", "C:\\work\\app")).toBe(false);+ });+});++describe("the live checklist", () => {+ test("a fresh session: nothing yet, and the running turn reads 'finish your turn'", () => {+ const messages: UIMessage[] = [{ id: "u", role: "user", parts: [{ type: "text", text: "build it" }] }];+ const { result, by } = states(messages, { turnRunning: true });+ expect(by).toEqual({ code: "fail", ran: "fail", project: "pass", finished: "pending" });+ expect(result.text).toBe("Good session: code changed ✗ · ran/tested ✗ · in project ✓ · finish your turn");+ expect(result.good).toBe(false);+ });++ test("code changed, not run yet, turn still running: the spec's example line", () => {+ const { result } = states(transcript([tool("write", { filePath: `${ROOT}/src/server.ts`, content: "x" })]), { turnRunning: true });+ expect(result.text).toBe("Good session: code changed ✓ · ran/tested ✗ · in project ✓ · finish your turn");+ });++ test("a complete session passes every check and earns the star", () => {+ const { result, by } = states(transcript(+ [tool("edit", { filePath: `${ROOT}/src/server.ts`, oldString: "a", newString: "b" })],+ [tool("bash", { command: "npm test", description: "run tests" })],+ ));+ expect(by).toEqual({ code: "pass", ran: "pass", project: "pass", finished: "pass" });+ expect(result.good).toBe(true);+ expect(result.text).toBe("Good session ★: code changed ✓ · ran/tested ✓ · in project ✓ · turn finished ✓");+ expect(goodSessionNudge(result)).toBeNull();+ });++ test("apply_patch names its files in the patch text", () => {+ const patchText = "*** Begin Patch\n*** Update File: src/app.py\n@@\n-a\n+b\n*** End Patch";+ expect(states(transcript([tool("apply_patch", { patchText })])).by.code).toBe("pass");+ expect(states(transcript([tool("apply_patch", { patchText: "*** Begin Patch\n*** Add File: docs/notes.md\n+x\n*** End Patch" })])).by.code).toBe("fail");+ });++ test("a failed edit or a docs-only change does not count as code", () => {+ expect(states(transcript([tool("edit", { filePath: "src/a.ts" }, "output-error")])).by.code).toBe("fail");+ expect(states(transcript([tool("write", { filePath: "README.md" })])).by.code).toBe("fail");+ });++ test("a failing test run still counts as running something", () => {+ expect(states(transcript([tool("bash", { command: "pytest" }, "output-error")])).by.ran).toBe("pass");+ });++ test("work outside the project, in the home folder or on a personal service fails 'in project'", () => {+ expect(states(transcript([tool("write", { filePath: "/home/dev/.bashrc", content: "x" })])).by.project).toBe("fail");+ expect(states(transcript([tool("bash", { command: "cd /home/dev/other && npm test" })])).by.project).toBe("fail");+ expect(states(transcript([tool("bash", { command: "ls", workdir: "/srv/data" })])).by.project).toBe("fail");+ expect(states(transcript([tool("bash", { command: "git push" })])).by.project).toBe("fail");+ expect(states(transcript([tool("write", { filePath: "/home/dev/a.py" })]), { root: "/home/dev" }).by.project).toBe("fail");+ // Reading outside is fine (the server restores files read in full), and so is scratch space.+ expect(states(transcript([tool("read", { filePath: "/etc/hosts" }), tool("write", { filePath: "/tmp/x.py" })])).by.project).toBe("pass");+ });++ test("the last turn: an error, a tool cut mid-call or no answer fails it", () => {+ const errored = transcript([tool("bash", { command: "npm test" })]);+ errored.push({ id: "err", role: "assistant", parts: [{ type: "text", text: "Stopped", providerMetadata: { opencode: { sessionError: { title: "Stopped" } } } }] as UIMessage["parts"] });+ expect(states(errored).by.finished).toBe("fail");+ const cut: UIMessage[] = [{ id: "u", role: "user", parts: [{ type: "text", text: "go" }] }, { id: "a", role: "assistant", parts: [tool("bash", { command: "npm test" }, "input-streaming")] as UIMessage["parts"] }];+ expect(states(cut).by.finished).toBe("fail");+ const unanswered: UIMessage[] = [{ id: "u", role: "user", parts: [{ type: "text", text: "go" }] }];+ const { result } = states(unanswered);+ expect(result.checks.find((check) => check.id === "finished")?.label).toBe("last turn cut off");+ });++ test("native Windows adds a failing check; WSL (Linux) does not", () => {+ const messages = transcript([tool("write", { filePath: "src/a.ts" }), tool("bash", { command: "npm test" })]);+ const windows = states(messages, { nativeWindows: true });+ expect(windows.by.windows).toBe("fail");+ expect(windows.result.good).toBe(false);+ expect(windows.result.text).toContain("native Windows ✗");+ expect(states(messages).by.windows).toBeUndefined();+ });++ test("sub-agents and many turns are not required", () => {+ const { result } = states(transcript([tool("write", { filePath: "main.go" }), tool("bash", { command: "go run ." })]));+ expect(result.good).toBe(true);+ });++ test("tool names from either engine: dynamic-tool parts and typed tool-* parts", () => {+ const messages: UIMessage[] = [+ { id: "u", role: "user", parts: [{ type: "text", text: "go" }] },+ {+ id: "a",+ role: "assistant",+ parts: [+ { type: "tool-write", toolCallId: "1", state: "output-available", input: { filePath: "src/a.rs" }, output: "ok" },+ { type: "tool-bash", toolCallId: "2", state: "output-available", input: { command: "cargo test" }, output: "ok" },+ ] as UIMessage["parts"],+ },+ ];+ expect(states(messages).result.good).toBe(true);+ });+});++describe("the nudge", () => {+ const missing = goodSessionChecklist({+ messages: transcript([tool("write", { filePath: "src/a.ts" })]),+ workspaceRoot: ROOT,+ turnRunning: false,+ nativeWindows: false,+ });++ test("once, when a turn ends with something missing", () => {+ expect(shouldNudge({ wasRunning: true, running: false, checklist: missing, alreadyNudged: false })).toBe(true);+ expect(shouldNudge({ wasRunning: true, running: false, checklist: missing, alreadyNudged: true })).toBe(false);+ expect(shouldNudge({ wasRunning: false, running: false, checklist: missing, alreadyNudged: false })).toBe(false);+ expect(shouldNudge({ wasRunning: true, running: true, checklist: missing, alreadyNudged: false })).toBe(false);+ });++ test("says what is missing, gently", () => {+ const nudge = goodSessionNudge(missing);+ expect(nudge?.title).toBe("Not a Good session ★ yet");+ expect(nudge?.body).toContain("run it or its tests");+ });+});++describe("the don't-quit-mid-turn guard", () => {+ test("asks only while a turn runs, and only when switching to another session", () => {+ expect(needsTurnGuard({ action: "quit", turnRunning: true })).toBe(true);+ expect(needsTurnGuard({ action: "close", turnRunning: true })).toBe(true);+ expect(needsTurnGuard({ action: "delete", turnRunning: true })).toBe(true);+ expect(needsTurnGuard({ action: "quit", turnRunning: false })).toBe(false);+ expect(needsTurnGuard({ action: "switch", turnRunning: true, currentSessionId: "a", targetSessionId: "b" })).toBe(true);+ expect(needsTurnGuard({ action: "switch", turnRunning: true, currentSessionId: "a", targetSessionId: "a" })).toBe(false);+ expect(needsTurnGuard({ action: "switch", turnRunning: false, currentSessionId: "a", targetSessionId: "b" })).toBe(false);+ });++ 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"]);+ });+});++describe("wording, the guide and the WSL banner", () => {+ test("server texts read Good session ★", () => {+ expect(goodSessionWording("Only replay-ready ★ sessions earn spins: a complete project")).toBe("Only Good sessions ★ earn spins: a complete project");+ expect(goodSessionWording("+1 spin per replay-ready ★ session")).toBe("+1 spin per Good session ★");+ expect(goodSessionWording("★ Replay-ready sessions earn +2 spins")).toBe("★ Good sessions earn +2 spins");+ expect(goodSessionWording("Replay-ready ★")).toBe("Good session ★");+ expect(goodSessionWording(null)).toBeNull();+ });++ test("the guide has the four steps and the WSL tip", () => {+ expect(GOOD_SESSION_GUIDE).toEqual([+ "Work inside your project folder.",+ "Build or change real code.",+ "Run it or its tests.",+ "Let the last turn finish.",+ ]);+ const html = renderToStaticMarkup(<GoodSessionGuide />);+ expect(html).toContain("How to make a Good session");+ expect(html).toContain("On Windows? Use WSL.");+ expect(html.match(/<li>/g)?.length).toBe(4);+ });++ test("the WSL banner: native Windows only, dismissed for the day, back the next day", () => {+ const now = new Date(2026, 9, 6, 15, 0);+ expect(localDay(now)).toBe("2026-10-06");+ expect(showWslBanner({ nativeWindows: true, dismissedDay: null, now })).toBe(true);+ expect(showWslBanner({ nativeWindows: true, dismissedDay: "2026-10-06", now })).toBe(false);+ expect(showWslBanner({ nativeWindows: true, dismissedDay: "2026-10-06", now: new Date(2026, 9, 7, 9, 0) })).toBe(true);+ expect(showWslBanner({ nativeWindows: false, dismissedDay: null, now })).toBe(false);+ });++ test("checklistText marks pending checks without a tick", () => {+ expect(checklistText([+ { id: "code", state: "pass", label: "code changed", hint: "" },+ { id: "finished", state: "pending", label: "finish your turn", hint: "" },+ ])).toBe("Good session: code changed ✓ · finish your turn");+ });+});diff --git a/apps/app/tests/quality.test.tsx b/apps/app/tests/quality.test.tsxindex 9a2a6012..1b0e563c 100644--- a/apps/app/tests/quality.test.tsx+++ b/apps/app/tests/quality.test.tsx@@ -168,7 +168,7 @@ describe("notice: once per id", () => {});test("streak text", () => {- expect(streakText(quality)).toBe("4-day streak · +1 spin per reproducible session · 7 days: +2");+ expect(streakText(quality)).toBe("4-day streak · +1 spin per Good session ★ · 7 days: +2");expect(streakText({ streakDays: 0, streakMultiplier: 0, streakNext: null })).toBeNull();});});@@ -285,11 +285,11 @@ describe("revision: fail labels, jackpot, open session", () => {expect(html).toContain("Started in your home folder");expect(html).toContain("3 code files · 120 lines · no tests");expect(html).toContain("Reproducible ✓");- expect(html).not.toContain("Replay-ready ★");+ expect(html).not.toContain("Good session ★");expect(html).toContain("+2 spins on a richer wheel");});- test("the sidebar row shows the ready count, and a ★ count only for replay-ready spins", () => {+ test("the sidebar row shows the ready count, and a ★ count only for Good session spins", () => {const plain = renderToStaticMarkup(<SpinCounts quality={quality} />);expect(plain).toContain("2 ready");expect(plain).not.toContain("quality-client-spins");@@ -299,7 +299,7 @@ describe("revision: fail labels, jackpot, open session", () => {expect(renderToStaticMarkup(<SpinCounts quality={{ ...quality, spinsAvailable: 0 }} />)).toBe("");});- test("a replay-ready session shows the star instead of the check", () => {+ test("a Good session shows the star instead of the check", () => {const html = renderToStaticMarkup(<SessionReasonsreasons={{@@ -311,7 +311,7 @@ describe("revision: fail labels, jackpot, open session", () => {}}/>,);- expect(html).toContain("Replay-ready ★");+ expect(html).toContain("Good session ★");expect(html).not.toContain("Reproducible ✓");});@@ -337,7 +337,7 @@ describe("revision: fail labels, jackpot, open session", () => {});});-describe("replay-ready wording, history and the count-up", () => {+describe("Good session wording, history and the count-up", () => {test("users never read the word client", () => {const starred = { ...quality, clientSpinsAvailable: 2, tier: "coaching" as const };const notice = { id: "c-1", kind: "tier-coaching", title: "Here is how to get spins", body: "" };@@ -362,18 +362,19 @@ describe("replay-ready wording, history and the count-up", () => {const text = html.replace(/<[^>]*>/g, " ");expect(text.toLowerCase()).not.toContain("client");expect(text).toContain("old app version");- expect(text).toContain("Replay-ready ★");- expect(text).toContain("Replay-ready sessions earn +2 spins on a richer wheel.");+ expect(text).toContain("Good session ★");+ expect(text).toContain("Good sessions earn +2 spins on a richer wheel.");+ expect(text.toLowerCase()).not.toContain("replay-ready");});- test("recent spins: the last 10, ★ on replay-ready ones", () => {+ test("recent spins: the last 10, ★ on Good session ones", () => {const spins = Array.from({ length: 12 }, (_, index) => ({id: `s${index}`, status: "spun" as const, reason: null, reproducible: true, clientGrade: index % 2 === 0, sessionId: null,earnedAt: null, expiresAt: null, spunAt: null, prizeTokens: 500_000, paidTokens: 500_000,}));const html = renderToStaticMarkup(<RecentSpins spins={spins} />);expect(html.match(/<li /g)?.length).toBe(10);- expect(html.match(/data-replay-ready/g)?.length).toBe(5);+ expect(html.match(/data-good-session/g)?.length).toBe(5);expect(html).toContain("★ 500K");expect(renderToStaticMarkup(<RecentSpins spins={[]} />)).toBe("");});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 1af6e063..c67c64be 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -93,6 +93,7 @@ import {setOmniRushSentrySession,} from "./sentry.mjs";import { installStdioErrorHandlers } from "./stdio-errors.mjs";+import { createTurnGuard } from "./turn-guard.mjs";import {createRendererCrashRecovery,installSocketTypeOfServiceGuard,@@ -1103,6 +1104,11 @@ const IDLE_ROUTER_INFO = Object.freeze({let mainWindow = null;const pendingDeepLinks = [];+const turnGuard = createTurnGuard({+ showMessageBox: (win, options) => (win ? dialog.showMessageBox(win, options) : dialog.showMessageBox(options)),+ getWindow: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null),+ appName: APP_NAME,+});browserPanel = createBrowserPanel({remoteDebugPort,@@ -2543,6 +2549,9 @@ const desktopCommandHandlers = {"__setApplicationMenuVisible": async (event, ...args) => {return applicationMenu.setVisible(args[0]);},+ "__setTurnRunning": async (event, ...args) => {+ return turnGuard.setTurnRunning(args[0] === true);+ },};if (isDevMode) {@@ -2721,9 +2730,19 @@ async function createMainWindow() {flushPendingDeepLinks();});+ // A turn still running: ask before the window goes (turn-guard.mjs).+ turnGuard.reset();+ mainWindow.on("close", (event) => {+ const win = mainWindow;+ turnGuard.guardClose(event, () => {+ if (win && !win.isDestroyed()) win.close();+ });+ });+mainWindow.on("closed", () => {browserPanel.destroy();mainWindow = null;+ turnGuard.setTurnRunning(false);});const recoverRendererCrash = createRendererCrashRecovery({@@ -2945,6 +2964,7 @@ or use: pnpm dev:worktree`);} else {app.on("before-quit", (event) => {if (runtimeDisposedForQuit) return;+ if (!turnGuard.guardQuit(event, () => app.quit())) return;event.preventDefault();if (runtimeDisposeInProgress) return;showShutdownScreen();diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex 7635f6dd..d12c429c 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -293,6 +293,8 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {platform: normalizePlatform(process.platform),version: process.versions.electron,evalFatalBootstrapFailure: process.env.OMNIRUSH_EVAL_FATAL_DESKTOP_BOOTSTRAP_FAILURE ?? null,+ // Test hook: e2e runs on Linux show the native-Windows notice.+ forceNativeWindows: process.env.OMNIRUSH_E2E_FORCE_WIN32 === "1",},});diff --git a/apps/desktop/electron/turn-guard.mjs b/apps/desktop/electron/turn-guard.mjsnew file mode 100644index 00000000..b59c7b15--- /dev/null+++ b/apps/desktop/electron/turn-guard.mjs@@ -0,0 +1,88 @@+// The don't-quit-mid-turn 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);+// "Quit anyway" goes ahead.++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"]);+const QUIT_ANYWAY = 1;++/**+ * @param {{+ * showMessageBox: (window: import("electron").BrowserWindow | null, options: import("electron").MessageBoxOptions) => Promise<{ response: number }>,+ * getWindow: () => import("electron").BrowserWindow | null,+ * appName?: string,+ * }} deps+ */+export function createTurnGuard(deps) {+ let turnRunning = false;+ let quitConfirmed = false;+ /** @type {Promise<boolean> | null} */+ let asking = null;++ async function confirmLeave() {+ if (!turnRunning || quitConfirmed) return true;+ // A second close or quit while the dialog is open waits for the same answer.+ asking ??= 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: 0,+ cancelId: 0,+ noLink: true,+ })+ .then((result) => result.response === QUIT_ANYWAY)+ .catch(() => true)+ .finally(() => {+ asking = null;+ });+ return asking;+ }++ return {+ setTurnRunning(value) {+ turnRunning = value === true;+ return turnRunning;+ },+ isTurnRunning() {+ return turnRunning;+ },+ /**+ * `before-quit`: returns true when the quit may go on now. Otherwise it+ * has prevented the event and quits again (`quit`) once the user picks+ * "Quit anyway".+ */+ guardQuit(event, quit) {+ if (!turnRunning || quitConfirmed) return true;+ event.preventDefault();+ void confirmLeave().then((leave) => {+ if (!leave) return;+ quitConfirmed = true;+ quit();+ });+ return false;+ },+ /**+ * The window's `close`: the same question; "Quit anyway" closes it+ * (`close`), which quits the app where closing the last window does.+ */+ guardClose(event, close) {+ if (!turnRunning || quitConfirmed) return true;+ event.preventDefault();+ void confirmLeave().then((leave) => {+ if (!leave) return;+ quitConfirmed = true;+ close();+ });+ return false;+ },+ /** A window opened again (macOS keeps the app running): ask next time too. */+ reset() {+ quitConfirmed = false;+ },+ };+}diff --git a/apps/desktop/electron/turn-guard.test.mjs b/apps/desktop/electron/turn-guard.test.mjsnew file mode 100644index 00000000..9b37fbf7--- /dev/null+++ b/apps/desktop/electron/turn-guard.test.mjs@@ -0,0 +1,110 @@+import assert from "node:assert/strict";+import test from "node:test";++import { TURN_GUARD_BUTTONS, TURN_GUARD_DETAIL, TURN_GUARD_TITLE, createTurnGuard } from "./turn-guard.mjs";++function fakeEvent() {+ return { prevented: false, preventDefault() { this.prevented = true; } };+}++function setup(responses) {+ const asked = [];+ const guard = createTurnGuard({+ getWindow: () => /** @type {any} */ ("win"),+ showMessageBox: async (win, options) => {+ asked.push({ win, options });+ return { response: responses.shift() ?? 0 };+ },+ });+ return { guard, asked };+}++const settle = () => new Promise((resolve) => setImmediate(resolve));++test("no turn running: quit and close go ahead without asking", () => {+ const { guard, asked } = setup([]);+ const event = fakeEvent();+ assert.equal(guard.guardQuit(event, () => assert.fail("no re-quit")), true);+ assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("no re-close")), true);+ assert.equal(event.prevented, false);+ assert.equal(asked.length, 0);+});++test("a turn running: quitting asks, with Wait for it as the default", async () => {+ const { guard, asked } = setup([0]);+ guard.setTurnRunning(true);+ const event = fakeEvent();+ let quits = 0;+ assert.equal(guard.guardQuit(event, () => { quits += 1; }), false);+ assert.equal(event.prevented, true);+ await settle();+ assert.equal(asked.length, 1);+ const { options } = asked[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.equal(options.defaultId, 0);+ assert.equal(options.cancelId, 0);+ assert.equal(quits, 0, "Wait for it keeps the app open");+});++test("Quit anyway quits, and the second before-quit goes through", async () => {+ const { guard, asked } = setup([1]);+ guard.setTurnRunning(true);+ let quits = 0;+ guard.guardQuit(fakeEvent(), () => { quits += 1; });+ await settle();+ assert.equal(quits, 1);+ const again = fakeEvent();+ assert.equal(guard.guardQuit(again, () => assert.fail("asked twice")), true);+ assert.equal(again.prevented, false);+ assert.equal(asked.length, 1);+});++test("closing the window asks the same; Quit anyway closes it and the quit that follows is not asked again", async () => {+ const { guard, asked } = setup([1]);+ guard.setTurnRunning(true);+ let closes = 0;+ const event = fakeEvent();+ assert.equal(guard.guardClose(event, () => { closes += 1; }), false);+ assert.equal(event.prevented, true);+ await settle();+ assert.equal(closes, 1);+ assert.equal(guard.guardQuit(fakeEvent(), () => assert.fail("asked twice")), true);+ assert.equal(asked.length, 1);+});++test("a close and a quit while the dialog is open share one dialog", async () => {+ const { guard, asked } = setup([0]);+ guard.setTurnRunning(true);+ guard.guardClose(fakeEvent(), () => assert.fail("waited"));+ guard.guardQuit(fakeEvent(), () => assert.fail("waited"));+ await settle();+ assert.equal(asked.length, 1);+});++test("the turn finishing while asked: later quits go through; a reopened window asks again", async () => {+ const { guard, asked } = setup([1, 0]);+ guard.setTurnRunning(true);+ guard.guardClose(fakeEvent(), () => undefined);+ await settle();+ guard.reset();+ assert.equal(guard.guardClose(fakeEvent(), () => assert.fail("waited")), false);+ await settle();+ assert.equal(asked.length, 2);+ guard.setTurnRunning(false);+ assert.equal(guard.guardQuit(fakeEvent(), () => undefined), true);+});++test("only a strict true marks a turn running", () => {+ const { guard } = setup([]);+ assert.equal(guard.setTurnRunning("yes"), false);+ assert.equal(guard.setTurnRunning(true), true);+ assert.equal(guard.isTurnRunning(), true);+});++test("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"]);+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex f0562ecb..718f035c 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/turn-guard.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 90f48f87..087f698b 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -871,6 +871,7 @@ export type DesktopCommandMap = {__setZoomFactor: { args: [factor: number]; result: boolean };__setNativeTheme: { args: [theme: string]; result: unknown };__setApplicationMenuVisible: { args: [visible: boolean]; result: unknown };+ __setTurnRunning: { args: [running: boolean]; result: unknown };};export type DesktopCommandName = keyof DesktopCommandMap;