Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: stricter quality checklist rules

ogsamrat46b1273075c8
diff --git a/apps/app/src/app/lib/good-session.ts b/apps/app/src/app/lib/good-session.ts
index 100c8916..0f02f41b 100644
--- a/apps/app/src/app/lib/good-session.ts
+++ b/apps/app/src/app/lib/good-session.ts
@@ -1,31 +1,45 @@
-// "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:
+// "Good session ★": the live checklist and the don't-quit-mid-turn guard.
//
-// 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)
+// A Good session is one the server's strict check passes (omnirush-backend:
+// session_repro.py REASONS and WorkSize.floor, the Session QC V2 gate, Session
+// QC V3's blocking checks and quality_rewards.STRICT_SPINS_TEXT). The rules
+// below mirror the parts of that check a turn can see as it runs. They never
+// show a check as passed where the server's check fails; the filled ★ comes
+// only from the server's verdict, after upload.
+//
+// code WorkSize.floor's code part: 2+ project code files and 30+ lines
+// changed, or 5+ files and 150+ lines (session_qc.is_code_path,
+// session_repro._written_lines)
+// ran a build or test run (session_qc.BUILD_TEST, WorkSize.test_runs)
// 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)
+// home_folder, shell writes outside it), with no personal or
+// outside service (V3 remote_service, local_database, remote_git,
+// docker, public_web, private_web, external_browser,
+// local_service) and no machine-specific program (V3
+// host_only_program)
// 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.
+//
+// The rules (everything from "Code files" to "The don't-quit-mid-turn guard")
+// are the same, line for line, as the CLI's
+// assets/extensions/omnirush/good-session-lib.js; only the types differ. The
+// desktop's own part is `messageFacts` (the transcript as tool calls).
import type { UIMessage } from "ai";
export const GOOD_SESSION_LABEL = "Good session ★";
+/** All local checks pass; the server decides after upload. */
+export const GOOD_SESSION_ON_TRACK = "On track for a Good session ★ (final check after upload)";
/** The four steps the rewards panel and the checklist's link show. */
-export const GOOD_SESSION_GUIDE: readonly string[] = [
+export const GOOD_SESSION_GUIDE: readonly string[] = Object.freeze([
"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";
@@ -34,20 +48,22 @@ 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_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";
export const TURN_GUARD_QUIT = "Quit anyway";
+export const NUDGE_TITLE = `Not a ${GOOD_SESSION_LABEL} yet`;
+
/**
- * Server texts still say "replay-ready ★" (STRICT_SPINS_TEXT, notices,
- * hints): users read "Good session ★" everywhere.
+ * Server texts that still say "replay-ready ★" (older servers): 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
+ return String(text)
.replace(/\breplay[- ]ready ★ sessions\b/gi, "Good sessions ★")
.replace(/\breplay[- ]ready ★ session\b/gi, "Good session ★")
.replace(/\breplay[- ]ready ★/gi, GOOD_SESSION_LABEL)
@@ -91,8 +107,8 @@ const SCRATCH_PREFIXES = ["/tmp/", "/var/tmp/", "/private/tmp/", "/var/folders/"
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();
+function normPath(value: unknown): string {
+ let norm = String(value).replace(/\\/g, "/").toLowerCase();
while (norm.startsWith("./")) norm = norm.slice(2);
return norm;
}
@@ -111,8 +127,8 @@ function notProject(norm: string): boolean {
}
/** Whether a changed file counts as project code (session_qc.is_code_path). */
-export function isCodePath(path: string): boolean {
- const norm = normPath(path.trim());
+export function isCodePath(value: unknown): boolean {
+ const norm = normPath(String(value ?? "").trim());
if (!norm || notProject(norm)) return false;
const folders = norm.split("/").slice(0, -1);
const name = norm.slice(norm.lastIndexOf("/") + 1);
@@ -125,9 +141,28 @@ export function isCodePath(path: string): boolean {
return !NON_CODE_EXTENSIONS.has(name.slice(name.lastIndexOf(".")));
}
-// --- Commands (session_qc.BUILD_TEST, session_qc_v2._runs) --------------------
+/** WorkSize.floor's code part: files and lines (the build/test part is the `ran` check). */
+export const FLOOR_FILES = 2;
+export const FLOOR_LINES = 30;
+export const FLOOR_ALONE_FILES = 5;
+export const FLOOR_ALONE_LINES = 150;
+
+/** Lines an edit put in (session_repro._written_lines; apply_patch: its added lines). */
+export function writtenLines(input: unknown): number {
+ const value = record(input);
+ for (const key of ["content", "newString", "new_string", "new_str"]) {
+ if (typeof value[key] === "string") return (value[key] as string).split("\n").length;
+ }
+ if (Array.isArray(value.edits)) {
+ return value.edits.reduce((total: number, edit: unknown) => total + writtenLines(edit), 0);
+ }
+ const patch = str(value.patchText) || str(value.patch) || str(value.input);
+ return patch.split("\n").filter((line) => line.startsWith("+") && !line.startsWith("+++")).length;
+}
+
+// --- Commands (session_qc.BUILD_TEST, session_qc_v2._runs, V3) ----------------
-/** A build, a test run or a linter/type check (session_qc.BUILD_TEST). */
+/** A build, a test run or a linter/type check (session_qc.BUILD_TEST): what WorkSize.test_runs counts. */
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|`
@@ -138,26 +173,13 @@ const BUILD_TEST = new RegExp(
+ 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"]);
+const WRAPPERS = new Set(["sudo", "time", "nice", "env", "exec", "command", "timeout", "npx", "bunx", "pnpx"]);
/** The commands of a shell line, each as its words (V2 `_split`/`_words`). */
-export function commandSegments(command: string): string[][] {
- return command
- .split(/\n|&&|\|\||;|\||\(|\)|`|\$\(/)
+export function commandSegments(command: unknown): string[][] {
+ return String(command ?? "")
+ .split(/\n|&&|\|\||;|\||\(|\)|`|\$\(|&/)
.map((segment) => {
const words = segment.trim().split(/\s+/).filter(Boolean);
while (words.length) {
@@ -165,6 +187,7 @@ export function commandSegments(command: string): string[][] {
if (ENV_ASSIGN.test(first)) { words.shift(); continue; }
if (WRAPPERS.has(first)) {
words.shift();
+ while (/^-/.test(words[0] ?? "")) words.shift();
if (first === "timeout" && /^\d/.test(words[0] ?? "")) words.shift();
continue;
}
@@ -175,12 +198,9 @@ export function commandSegments(command: string): string[][] {
.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);
- });
+/** Whether a shell line builds or tests (session_qc.BUILD_TEST, the only runs WorkSize counts). */
+export function ranSomething(command: unknown): boolean {
+ return commandSegments(command).some((words) => BUILD_TEST.test(words.join(" ")));
}
const REMOTE_PROGRAMS = new Set([
@@ -188,152 +208,205 @@ const REMOTE_PROGRAMS = new Set([
"supabase", "wrangler", "flyctl", "fly", "heroku", "railway", "kubectl", "helm", "terraform",
"doctl", "ngrok", "cloudflared", "gsutil", "eas",
]);
+/** Programs only the user's machine has (V3 HOST_PROGRAMS, plus the desktop openers). */
+const HOST_PROGRAMS = new Set([
+ "osascript", "xcodebuild", "xcrun", "sips", "qlmanage", "pbcopy", "pbpaste", "defaults", "launchctl",
+ "safaridriver", "system_profiler", "ioreg", "diskutil", "powershell", "powershell.exe", "pwsh", "cmd",
+ "cmd.exe", "wsl", "wsl.exe", "adb", "fastboot", "nvidia-smi", "systemctl", "journalctl", "networksetup",
+ "java_home", "nix", "nix-shell", "nix-build", "nix-env", "flutter", "dart", "swift", "swiftc",
+ "open", "xdg-open", "start", "explorer.exe", "notify-send", "xclip", "xsel",
+]);
const DB_CLIENTS = new Set(["psql", "pgcli", "mysql", "mariadb", "mycli", "mongosh", "mongo", "redis-cli"]);
const DOCKER_PROGRAMS = new Set(["docker", "docker-compose", "podman"]);
+const FETCHERS = new Set(["curl", "wget", "http", "https", "httpie", "xh", "aria2c", "fetch"]);
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;
+const URL_ARG = /^['"]?(https?:\/\/[^\s'"]+|(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:\d+)?(\/[^\s'"]*)?)/i;
+/** A server on this machine (V3 LOCAL_URL). */
+const LOCAL_URL = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[\w.-]+\.localhost)(:\d+)?(\/|$|\?|#)|^(file|about|data):/i;
+/** A command that starts a local server, so later calls to localhost reach it (V3 SERVER_START). */
+const SERVER_START = new RegExp(
+ String.raw`\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|preview|watch)\b|`
+ + String.raw`\bnpx\s+(vite(?!\s+build)|serve|http-server|live-server|nodemon)\b|`
+ + String.raw`\bvite(\s+(dev|serve|preview)\b|\s+--|\s*$)|`
+ + String.raw`\b(nodemon|live-server|http-server)\s|\bnext\s+(dev|start)\b|`
+ + String.raw`\bpython3?\s+-m\s+(http\.server|uvicorn|flask|streamlit|gunicorn)\b|`
+ + String.raw`\b(uvicorn|gunicorn|hypercorn|daphne)\s|\bflask\s+run\b|`
+ + String.raw`manage\.py\s+runserver|\brails\s+s(erver)?\b|\bphp\s+-S\b|`
+ + String.raw`\bstreamlit\s+run\b|\b(go|cargo)\s+run\b|\bdeno\s+(run|task)\b|`
+ + String.raw`\b(hugo|jekyll)\s+serve|\bexpo\s+start\b|\bwrangler\s+dev\b|`
+ + String.raw`\b(vercel|netlify)\s+dev\b|\bollama\s+serve\b|\bredis-server\b|`
+ + String.raw`\bmongod\b|\bpg_ctl\s+start\b|\bdocker(-compose|\s+compose)?\s+(up|run)\b|`
+ + String.raw`\bnode\s+\S*(server|app|index|main)\S*\.(c|m)?[jt]s\b`,
+ "i",
+);
+
+/** Whether a shell line starts a local server (V3 SERVER_START). */
+export function startsServer(command: unknown): boolean {
+ return SERVER_START.test(String(command ?? ""));
+}
+
+/** The web addresses a shell line fetches with curl, wget and the like. */
+export function fetchedUrls(command: unknown): string[] {
+ const urls: string[] = [];
+ for (const words of commandSegments(command)) {
+ const program = (words[0] ?? "").replace(/^.*\//, "").toLowerCase();
+ if (!FETCHERS.has(program)) continue;
+ for (const word of words.slice(1)) {
+ const match = URL_ARG.exec(word);
+ if (match) urls.push(match[1]!);
+ }
+ }
+ return urls;
+}
-/** 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, " ");
+/**
+ * What takes a shell line outside the project (V3 remote_service,
+ * local_database, remote_git, docker, public_web, host_only_program), as a
+ * short name, or null. Calls to this machine (`curl localhost:3000`) are
+ * judged by the checklist, which knows whether the session started a server.
+ */
+export function personalService(command: unknown, { dbBuilt = false }: { dbBuilt?: boolean } = {}): string | null {
+ const bare = String(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;
+ if (DB_CLIENTS.has(program) && !dbBuilt) return program;
+ if (HOST_PROGRAMS.has(program)) return `${program}, a program only your machine has`;
}
+ const remote = fetchedUrls(command).find((url) => !LOCAL_URL.test(url));
+ if (remote) return `the web (${remote.slice(0, 60)})`;
return null;
}
+/** The files a shell line writes or removes: redirects, tee, cp/mv targets, rm/mkdir/touch arguments. */
+export function shellWrites(command: unknown): string[] {
+ const text = String(command ?? "");
+ const out: string[] = [];
+ for (const match of text.matchAll(/(?:^|[^<>&\d])\d?>>?\s*(['"]?)([^\s'";&|<>)]+)\1/g)) {
+ if (!match[2]!.startsWith("&")) out.push(match[2]!);
+ }
+ for (const words of commandSegments(text.replace(/\d?>>?\s*\S+/g, " "))) {
+ const program = (words[0] ?? "").replace(/^.*\//, "").toLowerCase();
+ const args = words.slice(1).filter((word) => !word.startsWith("-")).map((word) => word.replace(/^['"]|['"]$/g, ""));
+ if (program === "tee" || program === "rm" || program === "rmdir" || program === "mkdir" || program === "touch" || program === "chmod") {
+ out.push(...(program === "chmod" ? args.slice(1) : args));
+ } else if ((program === "cp" || program === "mv" || program === "ln" || program === "install" || program === "rsync") && args.length >= 2) {
+ out.push(args.at(-1)!);
+ if (program === "mv") out.push(...args.slice(0, -1));
+ }
+ }
+ return out;
+}
+
// --- Folders ---------------------------------------------------------------
const HOME_FOLDER = /^(\/home\/[^/]+|\/users\/[^/]+|\/root|[a-z]:\/users\/[^/]+|~)\/?$/;
+const HOME_PREFIX = /^(\/home\/[^/]+|\/users\/[^/]+|\/root|[a-z]:\/users\/[^/]+)(\/|$)/;
-function folderKey(path: string): string {
- return normPath(path.trim()).replace(/\/+$/, "");
+function folderKey(value: unknown): string {
+ return normPath(String(value ?? "").trim()).replace(/\/+$/, "");
}
/** The project folder is the home folder itself (V3 home_folder). */
-export function isHomeFolder(root: string): boolean {
+export function isHomeFolder(root: unknown): boolean {
return HOME_FOLDER.test(folderKey(root));
}
function isAbsolute(norm: string): boolean {
- return norm.startsWith("/") || norm.startsWith("~") || WINDOWS_DRIVE.test(norm);
+ return norm.startsWith("/") || norm.startsWith("~") || norm.startsWith("$home") || WINDOWS_DRIVE.test(norm);
+}
+
+function resolveDots(value: string): string {
+ const out: string[] = [];
+ for (const segment of value.split("/")) {
+ if (segment === "..") {
+ if (out.length > 1) out.pop();
+ } else if (segment !== "." && (segment || out.length === 0)) {
+ out.push(segment);
+ }
+ }
+ return out.join("/");
}
/** 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);
+export function outsideProject(file: unknown, root: unknown): boolean {
+ let norm = folderKey(file);
const base = folderKey(root);
if (!norm || !base) return false;
+ if (/^(~|\$home|\$\{home\})(\/|$)/.test(norm)) {
+ // `~/x`: under the home folder the project folder sits in, when it sits in one.
+ const home = HOME_PREFIX.exec(base)?.[1];
+ if (!home) return true;
+ norm = norm.replace(/^(~|\$home|\$\{home\})/, home);
+ }
if (!isAbsolute(norm)) {
// Relative to the project folder: only `..` can leave it.
if (!norm.split("/").includes("..")) return false;
norm = resolveDots(`${base}/${norm}`);
+ } else {
+ norm = resolveDots(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;
-};
+// --- Tool calls -------------------------------------------------------------------
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 WEB_TOOLS = new Set(["webfetch", "web_fetch", "websearch", "web_search"]);
+const BROWSER_TOOL = /^browser_|^(playwright|puppeteer|chrome)[_-]/;
const PATCH_FILE = /^\*\*\* (?:Add|Update|Delete) File: (.+)$|^\*\*\* Move to: (.+)$/gm;
-type ToolCall = { tool: string; input: Record<string, unknown>; state: string; failed: boolean; notRun: boolean };
-
/** A call the engine or the user refused, so nothing ran (bad arguments, an unknown tool, a denied permission). */
const NOT_RUN = /invalid arguments|no tool named|unknown tool|tool .{0,40}not (found|available)|permission .{0,20}(denied|rejected)|user (rejected|denied|dismissed)/i;
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
+function record(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
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;
- const failed = record.state === "output-error";
- calls.push({
- tool: tool.toLowerCase().replace(/^.*[.:]/, ""),
- input: isRecord(record.input) ? record.input : {},
- state: str(record.state),
- failed,
- notRun: failed && NOT_RUN.test(str(record.errorText)),
- });
- }
- return calls;
+export type ToolCall = { tool: string; input: Record<string, unknown>; failed: boolean; notRun: boolean; unfinished: boolean };
+
+/**
+ * One tool call, from either engine: { tool, input, failed, errorText,
+ * unfinished }. `failed`: the call ended in an error; `errorText`: what the
+ * error said (a refusal counts for nothing); `unfinished`: it never ended.
+ */
+export function toolCall({ tool, input, failed = false, errorText = "", unfinished = false }: {
+ tool?: unknown; input?: unknown; failed?: boolean; errorText?: unknown; unfinished?: boolean;
+} = {}): ToolCall {
+ const isFailed = Boolean(failed);
+ return {
+ tool: String(tool ?? "").toLowerCase().replace(/^.*[.:]/, ""),
+ input: record(input),
+ failed: isFailed,
+ notRun: isFailed && NOT_RUN.test(str(errorText)),
+ unfinished: Boolean(unfinished),
+ };
}
/** 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);
+export function editedPaths(input: unknown): string[] {
+ const value = record(input);
+ const direct = str(value.filePath) || str(value.file_path) || str(value.path) || str(value.file) || str(value.target_file);
if (direct) return [direct];
- const patch = str(input.patchText) || str(input.patch) || str(input.input);
+ const patch = str(value.patchText) || str(value.patch) || str(value.input);
const paths: string[] = [];
for (const match of patch.matchAll(PATCH_FILE)) {
- const path = (match[1] ?? match[2] ?? "").trim();
- if (path) paths.push(path);
+ const file = (match[1] ?? match[2] ?? "").trim();
+ if (file) paths.push(file);
}
return paths;
}
@@ -352,78 +425,148 @@ function shellFolders(command: string, input: Record<string, unknown>): string[]
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 toolUrl(input: Record<string, unknown>): string {
+ return str(input.url) || str(input.href) || str(input.uri);
}
-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 -----------------------------------------------------------
+
+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;
+};
+
+/** "incomplete": a check fails or the turn runs; "on-track": every local check passes; "good": the server says so. */
+export type GoodSessionVerdict = "incomplete" | "on-track" | "good";
+
+export type GoodSessionChecklist = {
+ checks: GoodSessionCheck[];
+ verdict: GoodSessionVerdict;
+ /** Every local check passes (the server still decides). */
+ onTrack: 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;
+ /** The work as WorkSize counts it. */
+ work: { codeFiles: number; lines: number; testRuns: number };
+};
+
+export type GoodSessionInput = {
+ /** toolCall()s, oldest first. */
+ calls?: readonly ToolCall[];
+ /** The project folder the session runs in. */
+ 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";
+ /** Native Windows (not WSL). */
+ nativeWindows?: boolean;
+ /** The server checked this session after upload and it is a Good session ★. */
+ serverGood?: boolean;
+};
+
+function plural(count: number, word: string): string {
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
}
-/** The checklist for a session, from its transcript. */
-export function goodSessionChecklist(input: GoodSessionInput): GoodSessionChecklist {
- let code = false;
- let ran = false;
+/** The checklist for a session, from its tool calls. */
+export function goodSessionChecklist({
+ calls = [], workspaceRoot = "", turnRunning = false, lastTurn = "cut", nativeWindows = false, serverGood = false,
+}: GoodSessionInput = {}): GoodSessionChecklist {
+ const codeFiles = new Map<string, number>();
+ let testRuns = 0;
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);
+ let serverStarted = false;
+ let localUnstarted: string | null = null;
+ const home = String(workspaceRoot).trim() ? isHomeFolder(workspaceRoot) : false;
const dbBuilt = calls.some((call) => SHELL_TOOLS.has(call.tool) && DB_SETUP.test(shellCommand(call.input)));
+ const local = (url: string) => {
+ if (!serverStarted) localUnstarted ??= url;
+ };
for (const call of calls) {
if (call.notRun) continue;
if (EDIT_TOOLS.has(call.tool)) {
- for (const path of editedPaths(call.input)) {
- if (outsideProject(path, input.workspaceRoot)) {
- outside ??= path;
+ const files = editedPaths(call.input);
+ for (const file of files) {
+ if (outsideProject(file, workspaceRoot)) {
+ outside ??= file;
continue;
}
- if (!call.failed && isCodePath(path)) code = true;
+ if (!call.failed && isCodePath(file)) {
+ const key = folderKey(file);
+ codeFiles.set(key, (codeFiles.get(key) ?? 0) + (files.length === 1 ? writtenLines(call.input) : 0));
+ }
+ }
+ if (!call.failed && files.length > 1) {
+ // A patch over several files: its added lines go to the first code file.
+ const first = files.map(folderKey).find((key) => codeFiles.has(key));
+ if (first) codeFiles.set(first, (codeFiles.get(first) ?? 0) + writtenLines(call.input));
}
} else if (SHELL_TOOLS.has(call.tool)) {
const command = shellCommand(call.input);
if (!command) continue;
- if (ranSomething(command)) ran = true;
+ if (ranSomething(command)) testRuns += 1;
service ??= personalService(command, { dbBuilt });
- for (const folder of shellFolders(command, call.input)) {
- if (outsideProject(folder, input.workspaceRoot)) outside ??= folder;
+ for (const url of fetchedUrls(command)) if (LOCAL_URL.test(url)) local(url);
+ if (startsServer(command)) serverStarted = true;
+ for (const folder of [...shellFolders(command, call.input), ...shellWrites(command)]) {
+ if (outsideProject(folder, workspaceRoot)) outside ??= folder;
}
+ } else if (WEB_TOOLS.has(call.tool) || BROWSER_TOOL.test(call.tool)) {
+ const url = toolUrl(call.input);
+ if (url && LOCAL_URL.test(url)) local(url);
+ else if (url || WEB_TOOLS.has(call.tool)) service ??= `the web (${(url || call.tool).slice(0, 60)})`;
}
}
- const finished = lastTurnState(input.messages, input.turnRunning);
+ const fileCount = codeFiles.size;
+ const lines = [...codeFiles.values()].reduce((total, count) => total + count, 0);
+ const code = (fileCount >= FLOOR_FILES && lines >= FLOOR_LINES) || (fileCount >= FLOOR_ALONE_FILES && lines >= FLOOR_ALONE_LINES);
+ 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 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.",
+ label: `code changed${code ? "" : codeShort}`,
+ hint: code
+ ? `${plural(fileCount, "code file")} and ${plural(lines, "line")} changed.`
+ : fileCount === 0
+ ? "Build or change real code in the project."
+ : `Build or change more real code: ${FLOOR_FILES}+ code files and ${FLOOR_LINES}+ lines.`,
},
{
id: "ran",
- state: ran ? "pass" : "fail",
+ state: testRuns > 0 ? "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.",
+ hint: testRuns > 0 ? "The agent ran a build or the tests." : "Ask the agent to build it or run its tests.",
},
{
id: "project",
- state: home || outside || service ? "fail" : "pass",
+ state: home || outside || service || localUnstarted ? "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.",
+ ? `Uses ${service}: keep the work inside the project.`
+ : localUnstarted
+ ? `Calls ${localUnstarted} without starting that server in the session: start it in the session.`
+ : "The work stays inside the project folder.",
},
{
id: "finished",
@@ -436,12 +579,13 @@ export function goodSessionChecklist(input: GoodSessionInput): GoodSessionCheckl
: "The last turn stopped before it finished: send a follow-up and let it finish.",
},
];
- if (input.nativeWindows) {
+ if (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) };
+ const onTrack = checks.every((check) => check.state === "pass");
+ const verdict: GoodSessionVerdict = onTrack ? (serverGood ? "good" : "on-track") : "incomplete";
+ return { checks, verdict, onTrack, missing, text: checklistText(checks, verdict), work: { codeFiles: fileCount, lines, testRuns } };
}
function mark(check: GoodSessionCheck): string {
@@ -449,43 +593,123 @@ function mark(check: GoodSessionCheck): string {
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 checklist's heading: the filled ★ only on the server's word. */
+export function checklistHeading(verdict: GoodSessionVerdict): string {
+ return verdict === "good" ? GOOD_SESSION_LABEL : verdict === "on-track" ? GOOD_SESSION_ON_TRACK : "Good session";
+}
+
+/** "Good session: code changed ✓ · ran/tested ✗ · in project ✓ · finish your turn". */
+export function checklistText(checks: readonly GoodSessionCheck[], verdict: GoodSessionVerdict = "incomplete"): string {
+ return `${checklistHeading(verdict)}: ${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;
+export function goodSessionNudge(checklist: Pick<GoodSessionChecklist, "missing"> | null | undefined): { 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(" "),
- };
+ return { title: NUDGE_TITLE, 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;
+/** When to nudge: once per session, on the turn that just ended (running → not running), and only when something is missing. */
+export function shouldNudge({ wasRunning, running, checklist, alreadyNudged }: {
+ wasRunning: boolean; running: boolean; checklist: Pick<GoodSessionChecklist, "missing"> | null | undefined; alreadyNudged: boolean;
}): boolean {
- return input.wasRunning && !input.running && !input.alreadyNudged && input.checklist.missing.length > 0;
+ return Boolean(wasRunning && !running && !alreadyNudged && (checklist?.missing?.length ?? 0) > 0);
}
// --- The don't-quit-mid-turn guard --------------------------------------------
-export type TurnGuardAction = "close" | "quit" | "switch" | "delete";
+export type QuitGuard = {
+ readonly state: "idle" | "asking" | "waiting";
+ request(input?: { running?: boolean; interactive?: boolean; hangup?: boolean }): "quit" | "ask";
+ answer(wait: boolean): "wait" | "quit";
+ turnEnded(): boolean;
+};
-/** 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;
+/**
+ * `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.
+ */
+export function createQuitGuard(): QuitGuard {
+ let state: "idle" | "asking" | "waiting" = "idle";
+ return {
+ get state() {
+ return state;
+ },
+ request({ running = false, interactive = true, hangup = false } = {}) {
+ if (!interactive || hangup || !running) return "quit";
+ if (state === "idle") {
+ state = "asking";
+ return "ask";
+ }
+ return "quit";
+ },
+ answer(wait) {
+ if (state !== "asking") return wait ? "wait" : "quit";
+ if (wait) {
+ state = "waiting";
+ return "wait";
+ }
+ return "quit";
+ },
+ turnEnded() {
+ const was = state;
+ state = "idle";
+ return was === "waiting" || was === "asking";
+ },
+ };
+}
+
+// --- The desktop's transcript -------------------------------------------------
+
+function sessionErrorOf(message: UIMessage): boolean {
+ return message.parts.some((part) => {
+ const metadata = record((part as { providerMetadata?: unknown }).providerMetadata);
+ return record(metadata.opencode).sessionError !== undefined;
+ });
+}
+
+function messageCalls(message: UIMessage): ToolCall[] {
+ const calls: ToolCall[] = [];
+ for (const part of message.parts) {
+ const value = part as unknown as Record<string, unknown>;
+ let tool = "";
+ if (part.type === "dynamic-tool") tool = str(value.toolName);
+ else if (part.type.startsWith("tool-")) tool = part.type.slice(5);
+ else continue;
+ calls.push(toolCall({
+ tool,
+ input: value.input,
+ failed: value.state === "output-error",
+ errorText: value.errorText,
+ unfinished: value.state === "input-streaming" || value.state === "input-available",
+ }));
+ }
+ 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" } {
+ const calls: ToolCall[] = [];
+ let lastCalls: ToolCall[] = [];
+ for (const message of messages) {
+ if (message.role !== "assistant") continue;
+ lastCalls = messageCalls(message);
+ calls.push(...lastCalls);
}
+ const last = messages.at(-1);
+ const lastTurn = last && last.role === "assistant" && !sessionErrorOf(last) && !lastCalls.some((call) => call.unfinished) ? "pass" : "cut";
+ return { calls, lastTurn };
+}
+
+/** Whether leaving (closing, quitting, switching or deleting) is about a session whose turn runs. */
+export function leavingRunningTurn(input: { action: "close" | "quit" | "switch" | "delete"; 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;
}
@@ -494,9 +718,10 @@ export function needsTurnGuard(input: { action: TurnGuardAction; turnRunning: bo
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 {
+export function localDay(now: Date | number = Date.now()): string {
+ const at = new Date(now);
const pad = (value: number) => String(value).padStart(2, "0");
- return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`;
}
export function showWslBanner(input: { nativeWindows: boolean; dismissedDay: string | null; now?: Date }): boolean {
diff --git a/apps/app/src/react-app/domains/quality/good-session.tsx b/apps/app/src/react-app/domains/quality/good-session.tsx
index 8132596f..56d21a5e 100644
--- a/apps/app/src/react-app/domains/quality/good-session.tsx
+++ b/apps/app/src/react-app/domains/quality/good-session.tsx
@@ -19,11 +19,10 @@ 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 { omnirushQualityDetails, 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,
@@ -32,14 +31,17 @@ import {
WSL_BANNER_DISMISSED_KEY,
WSL_BANNER_TEXT,
WSL_GUIDE_URL,
+ checklistHeading,
+ checklistText,
goodSessionChecklist,
goodSessionNudge,
+ messageFacts,
localDay,
shouldNudge,
showWslBanner,
type GoodSessionCheck,
} from "../../../app/lib/good-session";
-import { readPref, writePref } from "../../../app/lib/quality";
+import { readPref, useAccountQuality, writePref } from "../../../app/lib/quality";
import { isDesktopRuntime, isWindowsPlatform } from "../../../app/utils";
import { hasLiveSessionActivity, useSessionActivityStore } from "../session/status/session-activity-store";
@@ -105,19 +107,59 @@ export type GoodSessionChecklistBarProps = {
turnRunning: boolean;
};
+const SERVER_VERDICT_REFRESH_MS = 5 * 60_000;
+
+/**
+ * The server's verdict on this session (GET /me/quality: `client_grade`),
+ * once the local checks pass and no turn runs. Sessions are checked about
+ * once an hour after upload, so this is usually false during the session.
+ */
+function useServerGood(sessionId: string, ask: boolean): boolean {
+ const quality = useAccountQuality();
+ const [good, setGood] = useState<{ sessionId: string; good: boolean }>({ sessionId, good: false });
+ const lastRead = useRef<{ sessionId: string; at: number } | null>(null);
+ useEffect(() => {
+ if (!ask || !quality) return;
+ const last = lastRead.current;
+ if (last && last.sessionId === sessionId && Date.now() - last.at < SERVER_VERDICT_REFRESH_MS) return;
+ lastRead.current = { sessionId, at: Date.now() };
+ let cancelled = false;
+ void omnirushQualityDetails()
+ .then((details) => {
+ if (cancelled) return;
+ const session = details?.sessions.find((entry) => entry.sessionId === sessionId);
+ setGood({ sessionId, good: session?.clientGrade === true });
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [ask, quality, sessionId]);
+ return good.sessionId === sessionId && good.good;
+}
+
/**
* 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.
+ * ran/tested ✗ · in project ✓ · finish your turn". When every local check
+ * passes it reads "On track for a Good session ★ (final check after
+ * upload)" with an outlined star; the star fills only on the server's
+ * verdict. 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,
+ const facts = useMemo(() => messageFacts(props.messages), [props.messages]);
+ const local = useMemo(() => goodSessionChecklist({
+ ...facts,
workspaceRoot: props.workspaceRoot,
turnRunning: props.turnRunning,
nativeWindows,
- }), [nativeWindows, props.messages, props.turnRunning, props.workspaceRoot]);
+ }), [facts, nativeWindows, props.turnRunning, props.workspaceRoot]);
+ const serverGood = useServerGood(props.sessionId, local.onTrack);
+ const checklist = useMemo(
+ () => (serverGood && local.onTrack ? { ...local, verdict: "good" as const, text: checklistText(local.checks, "good") } : local),
+ [local, serverGood],
+ );
const hasPrompt = props.messages.some((message) => message.role === "user");
// The nudge: on the running → done edge of this session's turn.
@@ -135,16 +177,22 @@ export function GoodSessionChecklistBar(props: GoodSessionChecklistBarProps) {
}, [checklist, hasPrompt, props.sessionId, props.turnRunning]);
if (!hasPrompt) return null;
+ const verdict = checklist.verdict;
return (
- <div className="px-4 max-lg:px-3 lg:px-8" data-testid="good-session-checklist" data-good={checklist.good ? "" : undefined}>
+ <div className="px-4 max-lg:px-3 lg:px-8" data-testid="good-session-checklist" data-verdict={verdict}>
<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>
+ <Star
+ data-testid="good-session-star"
+ data-filled={verdict === "good" ? "" : undefined}
+ className={cn("size-3 shrink-0", verdict === "good" ? "fill-current text-foreground" : verdict === "on-track" ? "text-foreground" : "text-muted-foreground")}
+ aria-hidden="true"
+ />
+ <span className="whitespace-nowrap font-medium text-foreground">{checklistHeading(verdict)}:</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}
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.tsx
index f7d37de1..cd0ec5c5 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,7 +102,7 @@ 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 { createQuitGuard, leavingRunningTurn } from "@/app/lib/good-session";
import { TurnGuardDialog } from "@/react-app/domains/quality/good-session";
import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";
import {
@@ -1181,15 +1181,30 @@ export function SessionPage(props: SessionPageProps) {
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));
+ // Leaving a session whose turn runs (switching away, deleting it) asks
+ // first; a second request, after "Wait for it", goes ahead. The guard
+ // re-arms when no turn runs any more (the CLI's createQuitGuard).
+ const leaveGuard = useRef(createQuitGuard());
+ const anyTurnRunning = Object.values(props.sidebar.sessionStatusById).some(
+ (status) => status === "thinking" || status === "responding" || status === "compacting" || status === "waiting",
+ );
+ useEffect(() => {
+ if (!anyTurnRunning) leaveGuard.current.turnEnded();
+ }, [anyTurnRunning]);
+ const guardLeave = useCallback((running: boolean, proceed: () => void) => {
+ if (leaveGuard.current.request({ running }) === "ask") {
+ setTurnGuardProceed(() => proceed);
return;
}
- openSessionTab(workspaceId, sessionId);
- }, [openSessionTab, props.sidebar.selectedSessionId, sessionTurnRunning]);
+ proceed();
+ }, []);
+
+ // The sidebar's switch.
+ const guardedOpenSessionTab = useCallback((workspaceId: string, sessionId: string) => {
+ const currentSessionId = props.sidebar.selectedSessionId ?? null;
+ const running = leavingRunningTurn({ action: "switch", turnRunning: sessionTurnRunning(currentSessionId), currentSessionId, targetSessionId: sessionId });
+ guardLeave(running, () => openSessionTab(workspaceId, sessionId));
+ }, [guardLeave, openSessionTab, props.sidebar.selectedSessionId, sessionTurnRunning]);
const closeSecondaryWorkbenchPane = useCallback(() => {
setWorkbenchSplit(null);
@@ -1427,11 +1442,7 @@ export function SessionPage(props: SessionPageProps) {
setSessionActionId(sessionId);
setDeleteOpen(true);
};
- if (needsTurnGuard({ action: "delete", turnRunning: sessionTurnRunning(sessionId) })) {
- setTurnGuardProceed(() => openDelete);
- return;
- }
- openDelete();
+ guardLeave(leavingRunningTurn({ action: "delete", turnRunning: sessionTurnRunning(sessionId) }), openDelete);
} : undefined}
onArchiveSession={props.onArchiveSession ? (sessionId, archived) => {
void props.onArchiveSession?.(sessionId, archived);
@@ -2076,9 +2087,13 @@ export function SessionPage(props: SessionPageProps) {
<TurnGuardDialog
open={turnGuardProceed !== null}
- onWait={() => setTurnGuardProceed(null)}
+ onWait={() => {
+ leaveGuard.current.answer(true);
+ setTurnGuardProceed(null);
+ }}
onQuit={() => {
const proceed = turnGuardProceed;
+ leaveGuard.current.answer(false);
setTurnGuardProceed(null);
proceed?.();
}}
diff --git a/apps/app/tests/good-session.test.tsx b/apps/app/tests/good-session.test.tsx
index 1c91d06c..8084b880 100644
--- a/apps/app/tests/good-session.test.tsx
+++ b/apps/app/tests/good-session.test.tsx
@@ -4,32 +4,40 @@ import { renderToStaticMarkup } from "react-dom/server";
import {
GOOD_SESSION_GUIDE,
+ GOOD_SESSION_ON_TRACK,
TURN_GUARD_MESSAGE,
TURN_GUARD_QUIT,
TURN_GUARD_WAIT,
checklistText,
+ createQuitGuard,
+ fetchedUrls,
goodSessionChecklist,
goodSessionNudge,
goodSessionWording,
isCodePath,
isHomeFolder,
+ leavingRunningTurn,
localDay,
- needsTurnGuard,
+ messageFacts,
outsideProject,
personalService,
ranSomething,
+ shellWrites,
shouldNudge,
showWslBanner,
+ startsServer,
+ writtenLines,
} from "../src/app/lib/good-session";
import { GoodSessionGuide } from "../src/react-app/domains/quality/good-session";
const ROOT = "/home/dev/projects/todo-api";
+const BODY = Array.from({ length: 20 }, (_, i) => `export const v${i} = ${i};`).join("\n");
let seq = 0;
-function tool(toolName: string, input: Record<string, unknown>, state: "output-available" | "output-error" | "input-streaming" = "output-available") {
+function tool(toolName: string, input: Record<string, unknown>, state: "output-available" | "output-error" | "input-streaming" = "output-available", errorText = "failed") {
seq += 1;
return state === "output-error"
- ? { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input, errorText: "failed" }
+ ? { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input, errorText }
: state === "input-streaming"
? { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input }
: { type: "dynamic-tool", toolName, toolCallId: `c${seq}`, state, input, output: "ok" };
@@ -44,16 +52,23 @@ function transcript(...assistantParts: unknown[][]): UIMessage[] {
return messages;
}
-function states(messages: UIMessage[], options: { turnRunning?: boolean; nativeWindows?: boolean; root?: string } = {}) {
+function states(messages: UIMessage[], options: { turnRunning?: boolean; nativeWindows?: boolean; root?: string; serverGood?: boolean } = {}) {
const result = goodSessionChecklist({
- messages,
+ ...messageFacts(messages),
workspaceRoot: options.root ?? ROOT,
turnRunning: options.turnRunning ?? false,
nativeWindows: options.nativeWindows ?? false,
+ serverGood: options.serverGood ?? false,
});
return { result, by: Object.fromEntries(result.checks.map((check) => [check.id, check.state])) };
}
+/** Two real code files (40 lines): above WorkSize.floor's code part. */
+const realWork = () => [
+ tool("write", { filePath: `${ROOT}/src/server.ts`, content: BODY }),
+ tool("write", { filePath: "src/routes.ts", content: BODY }),
+];
+
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`]) {
@@ -63,33 +78,69 @@ describe("code files mirror session_qc.is_code_path", () => {
expect(isCodePath(path)).toBe(false);
}
});
+
+ test("written lines like session_repro._written_lines; patches count added lines", () => {
+ expect(writtenLines({ content: "a\nb\nc" })).toBe(3);
+ expect(writtenLines({ newString: "x" })).toBe(1);
+ expect(writtenLines({ edits: [{ newString: "a\nb" }, { newString: "c" }] })).toBe(3);
+ expect(writtenLines({ patchText: "*** Update File: a.py\n@@\n-a\n+b\n+c\n" })).toBe(2);
+ });
});
-describe("commands mirror session_qc.BUILD_TEST, plus running the program", () => {
- test("builds, tests and program runs count, reads do not", () => {
+describe("ran/tested is session_qc.BUILD_TEST only (WorkSize.test_runs)", () => {
+ test("builds and tests count", () => {
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",
+ "make", "npx tsc --noEmit", "tsc -p .", "FOO=1 npm run build", "bun test", "timeout 20 node --test", "npx vitest run",
]) {
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"]) {
+ });
+
+ test("running the program, formatters and reads do not", () => {
+ for (const command of [
+ "ls -la", "cat package.json", "git status", "npm install", "node server.js", "python main.py", "./target/release/todo",
+ "npm run dev", "npx prettier --write .", "bash run.sh", "go run .",
+ ]) {
expect(ranSomething(command)).toBe(false);
}
});
+});
- test("personal services: remote programs, databases it did not build, docker, remote git", () => {
+describe("outside services and machine-specific programs", () => {
+ test("remote programs, databases it did not build, docker, remote git, host-only programs, the web", () => {
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("osascript -e 'beep'")).toContain("osascript");
+ expect(personalService("open index.html")).toContain("open");
+ expect(personalService("xdg-open http://localhost:3000")).toContain("xdg-open");
+ expect(personalService("curl -s https://api.github.com/repos/x/y")).toContain("the web");
+ expect(personalService("wget http://example.com/data.json")).toContain("the web");
+ expect(personalService("curl localhost:3000/health")).toBeNull();
expect(personalService("docker --version")).toBeNull();
expect(personalService("rg 'git push' src")).toBeNull();
expect(personalService("npm test")).toBeNull();
});
+
+ test("fetched addresses and server starts (V3 SERVER_START)", () => {
+ expect(fetchedUrls("curl -sf http://127.0.0.1:8000/ && echo ok")).toEqual(["http://127.0.0.1:8000/"]);
+ expect(fetchedUrls("curl localhost:3000")).toEqual(["localhost:3000"]);
+ expect(startsServer("npm run dev &")).toBe(true);
+ expect(startsServer("python3 -m http.server 8000")).toBe(true);
+ expect(startsServer("npm test")).toBe(false);
+ });
+
+ test("shell writes: redirects, tee, cp/mv, rm", () => {
+ expect(shellWrites("echo hi > ~/.bashrc")).toEqual(["~/.bashrc"]);
+ expect(shellWrites("npm test 2>&1 | tee /home/dev/log.txt")).toContain("/home/dev/log.txt");
+ expect(shellWrites("cp dist/app /usr/local/bin/app")).toContain("/usr/local/bin/app");
+ expect(shellWrites("rm -rf /etc/x")).toContain("/etc/x");
+ expect(shellWrites("npm test > /dev/null 2>&1")).toEqual(["/dev/null"]);
+ });
});
describe("folders", () => {
@@ -103,8 +154,13 @@ describe("folders", () => {
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("/dev/null", 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);
+ expect(outsideProject("~/.bashrc", ROOT)).toBe(true);
+ expect(outsideProject("~/projects/todo-api/src/a.ts", ROOT)).toBe(false);
+ expect(outsideProject("$HOME/.zshrc", ROOT)).toBe(true);
+ expect(outsideProject(`${ROOT}/../secret`, ROOT)).toBe(true);
});
});
@@ -113,44 +169,62 @@ describe("the live checklist", () => {
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);
+ expect(result.text).toBe("Good session: code changed (0 of 2 files) ✗ · ran/tested ✗ · in project ✓ · finish your turn");
+ expect(result.verdict).toBe("incomplete");
});
- 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 });
+ test("real code changed, not tested yet, turn still running: the spec's example line", () => {
+ const { result } = states(transcript(realWork()), { 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" })],
- ));
+ test("every local check passes: on track, with an outlined star; the filled ★ only from the server", () => {
+ const messages = transcript(realWork(), [tool("bash", { command: "npm test", description: "run tests" })]);
+ const { result, by } = states(messages);
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(result.verdict).toBe("on-track");
+ expect(result.onTrack).toBe(true);
+ expect(result.text).toBe(`${GOOD_SESSION_ON_TRACK}: code changed ✓ · ran/tested ✓ · in project ✓ · turn finished ✓`);
+ expect(result.text.startsWith("Good session ★")).toBe(false);
expect(goodSessionNudge(result)).toBeNull();
+ const confirmed = states(messages, { serverGood: true }).result;
+ expect(confirmed.verdict).toBe("good");
+ expect(confirmed.text).toBe("Good session ★: code changed ✓ · ran/tested ✓ · in project ✓ · turn finished ✓");
+ // The server's word never overrides a failing local check.
+ expect(states(transcript(realWork()), { serverGood: true }).result.verdict).toBe("incomplete");
+ });
+
+ test("the work-size floor: 2+ code files and 30+ lines (or 5 files and 150 lines)", () => {
+ const one = states(transcript([tool("write", { filePath: "src/a.ts", content: BODY }), tool("bash", { command: "npm test" })]));
+ expect(one.by.code).toBe("fail");
+ expect(one.result.checks[0]!.label).toBe("code changed (1 of 2 files)");
+ const small = states(transcript([tool("write", { filePath: "src/a.ts", content: "a\nb" }), tool("write", { filePath: "src/b.ts", content: "c" })]));
+ expect(small.result.checks[0]!.label).toBe("code changed (3 of 30 lines)");
+ expect(small.result.work).toEqual({ codeFiles: 2, lines: 3, testRuns: 0 });
});
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");
+ const patchText = `*** Begin Patch\n*** Update File: src/app.py\n@@\n${BODY.split("\n").map((l) => `+${l}`).join("\n")}\n*** Add File: src/util.py\n+x = 1\n*** End Patch`;
+ const { result } = states(transcript([tool("apply_patch", { patchText })]));
+ expect(result.work.codeFiles).toBe(2);
+ expect(result.work.lines).toBe(21);
+ expect(states(transcript([tool("apply_patch", { patchText: "*** Begin Patch\n*** Add File: docs/notes.md\n+x\n*** End Patch" })])).result.work.codeFiles).toBe(0);
});
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");
+ expect(states(transcript([tool("edit", { filePath: "src/a.ts", newString: BODY }, "output-error")])).result.work.codeFiles).toBe(0);
+ expect(states(transcript([tool("write", { filePath: "README.md", content: BODY })])).result.work.codeFiles).toBe(0);
+ });
+
+ test("a failing test run still counts as a run", () => {
+ expect(states(transcript([tool("bash", { command: "pytest" }, "output-error")])).by.ran).toBe("pass");
});
test("calls the engine refused never ran: bad arguments, unknown tool, denied permission", () => {
- const refused = (toolName: string, input: Record<string, unknown>, errorText: string) =>
- ({ type: "dynamic-tool", toolName, toolCallId: `r${toolName}`, state: "output-error", input, errorText });
const messages = transcript([
- refused("write", { content: "x" }, 'Invalid arguments for tool "write": - path: Missing key'),
- refused("bash", { command: "npm test" }, 'No tool named "bash" is currently available.'),
- refused("bash", { command: "cd /etc && make" }, "The user rejected permission to use this specific tool call."),
+ tool("write", { content: BODY }, "output-error", 'Invalid arguments for tool "write": - path: Missing key'),
+ tool("bash", { command: "npm test" }, "output-error", 'No tool named "bash" is currently available.'),
+ tool("bash", { command: "cd /etc && make" }, "output-error", "The user rejected permission to use this specific tool call."),
]);
const { by } = states(messages);
expect(by.code).toBe("fail");
@@ -159,24 +233,32 @@ describe("the live checklist", () => {
});
test("the v2 engine's shell tool and path key", () => {
- const { result } = states(transcript([tool("write", { path: "src/a.ts", content: "x" }), tool("shell", { command: "npm test" })]));
- expect(result.good).toBe(true);
+ const { result } = states(transcript([
+ tool("write", { path: "src/a.ts", content: BODY }), tool("write", { path: "src/b.ts", content: BODY }), tool("shell", { command: "npm test" }),
+ ]));
+ expect(result.verdict).toBe("on-track");
});
- 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'", () => {
+ test("work outside the project, in the home folder or on an outside 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");
+ expect(states(transcript([tool("websearch", { query: "express docs" })])).by.project).toBe("fail");
+ expect(states(transcript([tool("browser_navigate", { url: "https://github.com" })])).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("localhost: fine once the session started the server, not before", () => {
+ const started = states(transcript([tool("bash", { command: "npm run dev &" }), tool("bash", { command: "curl localhost:3000" }), tool("webfetch", { url: "http://localhost:3000" })]));
+ expect(started.by.project).toBe("pass");
+ const unstarted = states(transcript([tool("bash", { command: "curl -s http://localhost:3000/api" })]));
+ expect(unstarted.by.project).toBe("fail");
+ expect(unstarted.result.checks[2]!.hint).toContain("without starting that server");
+ });
+
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"] });
@@ -184,22 +266,20 @@ describe("the live checklist", () => {
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");
+ expect(states(unanswered).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 messages = transcript([...realWork(), 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.verdict).toBe("incomplete");
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);
+ expect(states(transcript([...realWork(), tool("bash", { command: "go test ./..." })])).result.verdict).toBe("on-track");
});
test("tool names from either engine: dynamic-tool parts and typed tool-* parts", () => {
@@ -209,22 +289,42 @@ describe("the live checklist", () => {
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" },
+ { 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" },
] as UIMessage["parts"],
},
];
- expect(states(messages).result.good).toBe(true);
+ expect(states(messages).result.verdict).toBe("on-track");
});
});
+describe("the judge's eight sessions the server rejects: never a ✓ on the failing item, never the ★ label", () => {
+ const one = (command: string, extra: unknown[] = []) => transcript([tool("write", { filePath: "main.py", content: BODY }), ...extra, tool("bash", { command })]);
+ const cases: Array<[string, UIMessage[], "code" | "ran" | "project"]> = [
+ ["1-line edit + python main.py", transcript([tool("edit", { filePath: "main.py", oldString: "a", newString: "b" }), tool("bash", { command: "python main.py" })]), "code"],
+ ["write + webfetch + node --test", one("node --test", [tool("webfetch", { url: "https://docs.python.org/3/" })]), "project"],
+ ["write + curl to an API + pytest", one("curl https://api.github.com/repos/a/b && pytest"), "project"],
+ ["write + curl localhost (never started) + pytest", one("curl localhost:3000 && pytest"), "project"],
+ ["write + npx prettier", one("npx prettier --write ."), "ran"],
+ ["write + osascript; make", one("osascript -e 'display notification \"x\"'; make"), "project"],
+ ["write + echo > ~/.bashrc; make", one("echo hi > ~/.bashrc; make"), "project"],
+ ["write + npm install lodash && npm test", one("npm install lodash && npm test"), "code"],
+ ];
+ for (const [name, messages, failing] of cases) {
+ test(name, () => {
+ const { result, by } = states(messages);
+ expect(by[failing]).toBe("fail");
+ expect(result.verdict).not.toBe("good");
+ expect(result.verdict).toBe("incomplete");
+ expect(result.text.startsWith("Good session ★")).toBe(false);
+ expect(result.text.startsWith("On track")).toBe(false);
+ });
+ }
+});
+
describe("the nudge", () => {
- const missing = goodSessionChecklist({
- messages: transcript([tool("write", { filePath: "src/a.ts" })]),
- workspaceRoot: ROOT,
- turnRunning: false,
- nativeWindows: false,
- });
+ const missing = goodSessionChecklist({ ...messageFacts(transcript([tool("write", { filePath: "src/a.ts" })])), workspaceRoot: ROOT });
test("once, when a turn ends with something missing", () => {
expect(shouldNudge({ wasRunning: true, running: false, checklist: missing, alreadyNudged: false })).toBe(true);
@@ -236,19 +336,30 @@ describe("the nudge", () => {
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");
+ expect(nudge?.body).toContain("run 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);
+describe("the don't-leave-mid-turn guard", () => {
+ test("leaving a running turn: quit, close, delete; switching only to another session", () => {
+ expect(leavingRunningTurn({ action: "quit", turnRunning: true })).toBe(true);
+ expect(leavingRunningTurn({ action: "close", turnRunning: true })).toBe(true);
+ expect(leavingRunningTurn({ action: "delete", turnRunning: true })).toBe(true);
+ expect(leavingRunningTurn({ action: "quit", turnRunning: false })).toBe(false);
+ expect(leavingRunningTurn({ action: "switch", turnRunning: true, currentSessionId: "a", targetSessionId: "b" })).toBe(true);
+ expect(leavingRunningTurn({ action: "switch", turnRunning: true, currentSessionId: "a", targetSessionId: "a" })).toBe(false);
+ });
+
+ test("createQuitGuard: asks once; a second request (after Wait for it) goes ahead; the turn ending re-arms", () => {
+ const guard = createQuitGuard();
+ expect(guard.request({ running: false })).toBe("quit");
+ expect(guard.request({ running: true })).toBe("ask");
+ expect(guard.answer(true)).toBe("wait");
+ expect(guard.request({ running: true })).toBe("quit");
+ expect(guard.turnEnded()).toBe(true);
+ expect(guard.request({ running: true })).toBe("ask");
+ expect(guard.answer(false)).toBe("quit");
+ expect(guard.request({ running: true })).toBe("quit");
});
test("the dialog says the spec's words", () => {
@@ -267,7 +378,7 @@ describe("wording, the guide and the WSL banner", () => {
});
test("the guide has the four steps and the WSL tip", () => {
- expect(GOOD_SESSION_GUIDE).toEqual([
+ expect([...GOOD_SESSION_GUIDE]).toEqual([
"Work inside your project folder.",
"Build or change real code.",
"Run it or its tests.",