From 255d795de5ff3ef65e9a9ad8862c659d5f41ba47 Mon Sep 17 00:00:00 2001 From: tomi Date: Sat, 14 Nov 2026 07:36:02 +0100 Subject: [PATCH 1/5] feat(goal): audit persistent blockers with rollback-safe sidecar --- docs/AUTONOMOUS_GOAL_RECOVERY.md | 25 +++ src/agent_automation/goal_blocking.rs | 209 ++++++++++++++++++++++++++ src/agent_automation/mod.rs | 1 + src/agent_automation/store.rs | 17 +-- src/markdown_chat/mod.rs | 14 ++ src/tools/goal.rs | 14 +- 6 files changed, 270 insertions(+), 10 deletions(-) create mode 100644 docs/AUTONOMOUS_GOAL_RECOVERY.md create mode 100644 src/agent_automation/goal_blocking.rs diff --git a/docs/AUTONOMOUS_GOAL_RECOVERY.md b/docs/AUTONOMOUS_GOAL_RECOVERY.md new file mode 100644 index 00000000..8dd38172 --- /dev/null +++ b/docs/AUTONOMOUS_GOAL_RECOVERY.md @@ -0,0 +1,25 @@ +# Autonomous goal recovery: staged integration + +This branch adapts focused concepts from LeZergan upstream Codexify PRs #22 and #24 with rollback-safe storage. It is not a wholesale merge of either PR. + +## Opt-in persistent blocker audit + +After installing a compatible binary, set agentChat.automation.persistentGoalBlockers to true. The default is false. + +When enabled, goal_finish may mark a goal blocked only after the same reason persists across three distinct goal turns spanning at least 60 seconds. A rejection explains that constraint and requires continued lawful independent work. Real payment, invoicing, authorization and fulfillment gates remain intact. This grants no authorization to charge, spend, publish or accept contracts. + +The audit lives in a private goal-blocker-audit.json sidecar; the existing strict AutomationTaskState JSON schema is unchanged for binary rollback compatibility. A new goal revision or a fresh explicit activation resets the audit identity. + +Do not add the new setting to a live older Codexify configuration: older builds reject unknown keys. Enable only after a guarded compatible update. + +## Stop recovery + +The browser companion recognizes a stable Stop selector, a localized Stop button, and the explicit English End-turn control. A bounded native click waits for temporary disabled state. Existing real modal checks, account verification, message ownership and Send safeguards remain mandatory. + +## Parallel browser lanes + +The 4-page pool from PR #22 was inspected but deliberately NOT installed. This branch retains one browser action lane until measured tests establish safe isolation, HTTP 429 backoff, memory use and retries on the 16 GB Windows host. + +## Verification and release + +Check Rust formatting, Rust test targets, TypeScript, Stop-control unit tests, native Chrome Stop test, and full browser safety tests. Install only with a guarded quiet-fleet update, a known-good rollback, and a verification of real safe retry. This staging branch has not deployed any behavior by itself. \ No newline at end of file diff --git a/src/agent_automation/goal_blocking.rs b/src/agent_automation/goal_blocking.rs new file mode 100644 index 00000000..870904d6 --- /dev/null +++ b/src/agent_automation/goal_blocking.rs @@ -0,0 +1,209 @@ +//! Require persistent, independently revisited blockers before ending an autonomous goal. +//! Adapted from LeZergan/codexify PR #24, without unbounded retries. +//! A separate, private sidecar preserves rollback compatibility with older +//! strict AutomationTaskState schemas: the original state format is unchanged. +use super::{AgentAutomationStore, GoalStatus}; +use crate::project_bindings::ConversationIdentity; +use serde::{Deserialize, Serialize}; + +const BLOCKER_AUDIT_RECORD: &str = "goal-blocker-audit.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct BlockerAudit { + pub revision: u64, + pub reason: String, + pub attempts: u32, + pub last_turn: u64, + pub first_at_ms: u64, + pub activation_at_ms: u64, +} + +impl AgentAutomationStore { + fn blocker_audit_path( + &self, + task: &ConversationIdentity, + ) -> Result { + Ok(self.task_directory(task)?.join(BLOCKER_AUDIT_RECORD)) + } + + fn read_blocker_audit( + &self, + task: &ConversationIdentity, + ) -> Result, String> { + let path = self.blocker_audit_path(task)?; + super::store::read_private_record(&path)? + .map(|bytes| { + serde_json::from_slice(&bytes).map_err(|_| { + "Persistent goal blocker audit contains invalid JSON; file preserved".into() + }) + }) + .transpose() + } + + pub fn audit_goal_blocker( + &self, + task: &ConversationIdentity, + revision: u64, + reason: &str, + now: u64, + ) -> Result<(), String> { + if !self.persistent_goal_blockers { + return Ok(()); + } + let reason = reason.trim(); + if reason.is_empty() || reason.len() > 4096 { + return Err("A blocked goal requires a concrete reason of at most 4096 bytes".into()); + } + let path = self.blocker_audit_path(task)?; + // Reuse the task-state mutation lock, so concurrent goal_finish calls + // cannot each increment the same turn or overwrite each other's audit. + let deferred = self.mutate(task, |state| { + let goal = state.goal.as_ref().ok_or("No agent-chat goal is configured")?; + if goal.revision != revision { + return Err("The goal revision changed; read goal_read again".into()); + } + if goal.status != GoalStatus::Active { + return Ok(None); + } + let previous = self.read_blocker_audit(task)?; + let same = previous.as_ref().is_some_and(|audit| { + audit.revision == revision + && audit.reason == reason + && audit.activation_at_ms == goal.updated_at_ms + }); + let audit = if same { + let mut previous = previous.expect("a matching audit exists"); + if previous.last_turn != goal.turn_count { + previous.last_turn = goal.turn_count; + previous.attempts = previous.attempts.saturating_add(1); + } + previous + } else { + BlockerAudit { + revision, + reason: reason.into(), + attempts: 1, + last_turn: goal.turn_count, + first_at_ms: now, + activation_at_ms: goal.updated_at_ms, + } + }; + super::store::persist_private_record(&path, &audit)?; + Ok((audit.attempts < 3 || now.saturating_sub(audit.first_at_ms) < 60_000) + .then(|| format!( + "Goal remains active. Blocker audit {}/3: {}. Investigate alternate free-only work, record evidence in rollout_update, and revisit the exact blocker in a later goal turn. Repeated goal_finish calls within one turn do not count. Three distinct turns spanning at least 60 seconds are required to block this autonomous goal. This does not authorize payments, contracts, private data access, or restricted operations.", + audit.attempts.min(3), audit.reason + ))) + })?; + if let Some(message) = deferred { + return Err(message); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture_store( + enabled: bool, + ) -> ( + tempfile::TempDir, + AgentAutomationStore, + ConversationIdentity, + ) { + let root = tempfile::tempdir().unwrap(); + let mut config = crate::config::default_config(root.path().to_path_buf()); + config.markdown_chat.automation.persistent_goal_blockers = enabled; + let store = AgentAutomationStore::for_config(&config).unwrap(); + let task = ConversationIdentity::from_openai_session("revenue-blocker-check").unwrap(); + store + .set_goal(&task, "Work towards verified revenue", 1) + .unwrap(); + store.run_goal(&task, 1, 2).unwrap(); + (root, store, task) + } + + #[test] + fn first_blocker_requires_three_distinct_turns_and_one_minute() { + let (_root, store, task) = fixture_store(true); + let reason = "Payment setup requires owner approval; continue independent research."; + assert!(store.audit_goal_blocker(&task, 1, reason, 100).is_err()); + assert!(store.audit_goal_blocker(&task, 1, reason, 100_000).is_err()); + assert_eq!( + store.read_blocker_audit(&task).unwrap().unwrap().attempts, + 1 + ); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().turn_count = 2; + Ok(()) + }) + .unwrap(); + assert!(store.audit_goal_blocker(&task, 1, reason, 101_000).is_err()); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().turn_count = 3; + Ok(()) + }) + .unwrap(); + assert!(store.audit_goal_blocker(&task, 1, reason, 120_000).is_ok()); + } + + #[test] + fn changed_reason_and_new_revision_reset_the_sidecar_audit() { + let (_root, store, task) = fixture_store(true); + assert!( + store + .audit_goal_blocker(&task, 1, "payment gate", 1_000) + .is_err() + ); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().turn_count = 2; + Ok(()) + }) + .unwrap(); + assert!( + store + .audit_goal_blocker(&task, 1, "publication gate", 70_000) + .is_err() + ); + let audit = store.read_blocker_audit(&task).unwrap().unwrap(); + assert_eq!(audit.attempts, 1); + assert_eq!(audit.reason, "publication gate"); + let next = store.set_goal(&task, "New task revision", 90_000).unwrap(); + store.run_goal(&task, next.revision, 90_001).unwrap(); + assert!( + store + .audit_goal_blocker(&task, next.revision, "new review gate", 90_002) + .is_err() + ); + assert_eq!( + store.read_blocker_audit(&task).unwrap().unwrap().revision, + next.revision + ); + } + + #[test] + fn sidecar_does_not_change_original_goal_state_schema_or_default_policy() { + let (_root, store, task) = fixture_store(true); + assert!( + store + .audit_goal_blocker(&task, 1, "Needs legal approval", 100) + .is_err() + ); + let state = store.load(&task).unwrap(); + let encoded = serde_json::to_value(&state).unwrap(); + assert!(encoded.get("blockerAudit").is_none()); + assert!(store.read_blocker_audit(&task).unwrap().is_some()); + let (_root, disabled, task) = fixture_store(false); + assert!( + disabled + .audit_goal_blocker(&task, 1, "Needs legal approval", 100) + .is_ok() + ); + } +} diff --git a/src/agent_automation/mod.rs b/src/agent_automation/mod.rs index af69a5ac..e1a26ca4 100644 --- a/src/agent_automation/mod.rs +++ b/src/agent_automation/mod.rs @@ -1,4 +1,5 @@ mod companion; +mod goal_blocking; mod install; mod model_fallback; mod process; diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index a99942ec..cced04c6 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -420,7 +420,7 @@ impl AutomationTaskState { return false; }; let action = &self.action; - if goal.status != GoalStatus::Active + !(goal.status != GoalStatus::Active || action.goal_revision != Some(goal.revision) || action.id.is_none() || action.status == AutomationActionStatus::Idle @@ -437,11 +437,7 @@ impl AutomationTaskState { || action.kind == Some(AutomationActionKind::OfflineCombined) && action.status != AutomationActionStatus::Cancelled && action.send_accepted == Some(true) - && action.messages_fenced) - { - return false; - } - true + && action.messages_fenced)) } pub(crate) fn goal_retry_at_ms(&self) -> Option { @@ -851,6 +847,7 @@ pub struct AgentAutomationStore { pub(super) renewal_config: super::turn_renewal::TurnRenewalConfig, pub(super) settings_path: Option, automatic_retries: bool, + pub(super) persistent_goal_blockers: bool, retry_timings: RetryTimings, pub(super) usage_options: crate::usage_analytics::Options, } @@ -912,6 +909,7 @@ impl AgentAutomationStore { renewal_config: Default::default(), settings_path: None, automatic_retries: true, + persistent_goal_blockers: false, retry_timings: RetryTimings::default(), usage_options: Default::default(), }) @@ -923,6 +921,7 @@ impl AgentAutomationStore { self.renewal_config = config.markdown_chat.turn_renewal.clone(); self.settings_path = config.loaded_config_path.clone(); self.automatic_retries = config.markdown_chat.automation.automatic_retries; + self.persistent_goal_blockers = config.markdown_chat.automation.persistent_goal_blockers; self.retry_timings = config.markdown_chat.automation.retry_timings.clone(); self.usage_options = crate::usage_analytics::Options::from_config(config); self.notification_workspace = config @@ -1408,7 +1407,7 @@ impl AgentAutomationStore { completed_tool_call_count: None, }; state.goal = Some(goal.clone()); - state.goal_wake = GoalWakeState::default(); + state.goal_wake = GoalWakeState::default(); if state.action.goal_revision.is_some() { state.action = AutomationActionState::default(); } @@ -3763,7 +3762,7 @@ fn open_lock_file(path: &Path) -> Result { Ok(file) } -fn read_private_record(path: &Path) -> Result>, String> { +pub(super) fn read_private_record(path: &Path) -> Result>, String> { let metadata = match std::fs::symlink_metadata(path) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { @@ -3971,7 +3970,7 @@ fn persist_state(path: &Path, state: &AutomationTaskState) -> Result<(), String> persist_private_record(path, state) } -fn persist_private_record(path: &Path, record: &impl Serialize) -> Result<(), String> { +pub(super) fn persist_private_record(path: &Path, record: &impl Serialize) -> Result<(), String> { let parent = path .parent() .ok_or("Agent automation state has no parent directory")?; diff --git a/src/markdown_chat/mod.rs b/src/markdown_chat/mod.rs index 4a9360e4..a7166528 100644 --- a/src/markdown_chat/mod.rs +++ b/src/markdown_chat/mod.rs @@ -139,6 +139,8 @@ pub struct AgentAutomationConfig { pub max_queued_actions: usize, pub auto_approve_tool_calls: bool, pub automatic_retries: bool, + // Opt-in: require persistent evidence before marking an autonomous goal blocked. + pub persistent_goal_blockers: bool, pub new_conversation_on_load_rate_limit: bool, pub retry_timings: RetryTimings, pub chatgpt_project_url: Option, @@ -156,6 +158,7 @@ impl Default for AgentAutomationConfig { max_queued_actions: DEFAULT_AUTOMATION_MAX_QUEUED_ACTIONS, auto_approve_tool_calls: true, automatic_retries: true, + persistent_goal_blockers: false, new_conversation_on_load_rate_limit: false, retry_timings: RetryTimings::default(), chatgpt_project_url: None, @@ -688,6 +691,17 @@ pub(crate) async fn history_call( #[cfg(test)] mod tests { use super::*; + #[test] + fn persistent_goal_blockers_defaults_off_and_is_opt_in() { + let defaults = AgentAutomationConfig::default(); + assert!(!defaults.persistent_goal_blockers); + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"persistentGoalBlockers": true})).unwrap(); + assert!(config.persistent_goal_blockers); + assert_eq!(config.retry_timings, defaults.retry_timings); + config.validate().unwrap(); + } + #[test] fn retry_timings_default_and_partial_configuration() { let defaults = AgentAutomationConfig::default(); diff --git a/src/tools/goal.rs b/src/tools/goal.rs index 3af4f80c..6b5af81e 100644 --- a/src/tools/goal.rs +++ b/src/tools/goal.rs @@ -84,7 +84,7 @@ impl Tool for GoalTool { "Resume the exact current paused or blocked standalone agent-chat goal without changing its text, revision, elapsed time, or turn count. An already active goal remains active. A completed goal requires goal_set to create a new revision. Use a fresh requestId for each operation and reuse it only to retry identical arguments." } Self::Finish => { - "NON-TERMINAL TOOL. Mark the exact current goal revision completed or blocked and publish its report inline for the user. For completed, summary MUST describe work performed, results and verification; nextSteps MUST describe suggested follow-up (explicitly say none if none is needed). For blocked, reason MUST explain the concrete blocker and nextSteps MUST explain exactly what input, action or external change will unblock it. Never block merely for a timeout or rejected command. This finishes only the goal, NEVER the assistant turn: no normal ChatGPT final answer. After completed call turn_completed repeatedly to wait for requests; after blocked call chat_await repeatedly for the needed input, then goal_resume only once the blocker is resolved. Follow returned user input first. Do not stop because of elapsed time or an anticipated timeout." + "NON-TERMINAL TOOL. Mark the exact current goal revision completed or blocked and publish its report inline for the user. For completed, summary MUST describe work performed, results and verification; nextSteps MUST describe suggested follow-up (explicitly say none if none is needed). For blocked, reason MUST explain the concrete blocker and nextSteps MUST explain exactly what input, action or external change will unblock it. Never block merely for a timeout or rejected command. This finishes only the goal, NEVER the assistant turn: no normal ChatGPT final answer. After completed call turn_completed repeatedly to wait for requests; after blocked call chat_await repeatedly for the needed input, then goal_resume only once the blocker is resolved. Follow returned user input first. Do not stop because of elapsed time or an anticipated timeout. When persistent goal-blocker auditing is enabled, a blocked result requires the same concrete blocker across three distinct goal turns spanning at least 60 seconds; continue all authorized independent work without assuming payment approval." } } .into() @@ -367,6 +367,18 @@ impl Tool for GoalTool { Ok(summary) => summary.total_tool_calls, Err(error) => return ToolResult::error(error), }; + // Persistent, opt-in blocker auditing prevents a long-running + // goal from exiting on its first unsupported external dependency. + if let GoalFinish::Blocked { reason } = &finish + && let Err(error) = store.audit_goal_blocker( + task, + args.expected_revision, + reason, + crate::markdown_chat::now_ms(), + ) + { + return ToolResult::error(error); + } match store.finish_goal_with_tool_count( task, args.expected_revision, From fc1f0acd51d5e5a8533c4d323dd0a151897de5b7 Mon Sep 17 00:00:00 2001 From: tomi Date: Sat, 14 Nov 2026 07:36:03 +0100 Subject: [PATCH 2/5] fix(browser): recognize End turn and bounded disabled Stop controls --- browser-companion/src/chatgpt-driver.ts | 19 +++++++----- browser-companion/src/stop-controls.ts | 14 +++++++++ .../tests/pairing-submit.test.ts | 17 +++++++++++ browser-companion/tests/stop-controls.test.ts | 30 +++++++++++++++++++ 4 files changed, 72 insertions(+), 8 deletions(-) create mode 100644 browser-companion/src/stop-controls.ts create mode 100644 browser-companion/tests/stop-controls.test.ts diff --git a/browser-companion/src/chatgpt-driver.ts b/browser-companion/src/chatgpt-driver.ts index 50ab2572..2215e71d 100644 --- a/browser-companion/src/chatgpt-driver.ts +++ b/browser-companion/src/chatgpt-driver.ts @@ -7,6 +7,7 @@ import {openNewChat, createdChatUrl, assertNewChatDraft} from "./new-chat"; import { HealthAccountCache, readChatGptAccount, type ChatGptAccount } from "./account"; import { throwIfSessionAttention, throwIfConversationLimit, toolApprovalVisible } from "./browser-session"; import {navigatePage,recordConversationAvailable,conversationLoadAvailableAt} from "./navigation"; +import {stopControls} from "./stop-controls"; import type { BrowserDriver, DriverExecution, BrowserStepRunner, StopProgressStep } from "./browser-window"; import { activeComposer, composerText, insertExactPrompt, isPairingVerificationDraft, uniqueSendButton } from "./composer"; import { clearComposerState, connectorIsSelected, ConnectorMenuUnavailableError, SELECTED_CONNECTOR_SELECTOR, selectConnector, type SelectedConnector } from "./connector-selection"; @@ -56,7 +57,7 @@ export function responseCompletionReady(input: { } async function generationRunning(page: Page): Promise { - return page.locator(CHATGPT_STOP_BUTTON_SELECTOR).filter({ visible:true }).count() + return stopControls(page).count() .then(count => count > 0) .catch(() => false); } @@ -156,7 +157,7 @@ async function stopLingeringResponse( } }; let confirmationSubmitted = false; - const waitForStopped = async (stop:Locator) => { + const waitForStopped = async () => { let settleDeadline = Math.min(deadline,(lastStopRequestedAt||Date.now())+settleMs); while (!boundedSignal.aborted) { const dialogs = await visibleStopDialogs(page); @@ -200,7 +201,7 @@ async function stopLingeringResponse( } // Confirmation can remove its entire iframe. Re-scan on the next poll // instead of waiting on a detached locator and retrying Stop prematurely. - if (!count && !await stop.isVisible()) return; + if (!count && !await stopControls(page).count()) return; if (Date.now() >= settleDeadline) throw new Error("ChatGPT Stop has not completed"); await new Promise(resolve => setTimeout(resolve,50)); } @@ -210,19 +211,21 @@ async function stopLingeringResponse( for (let attempt = 0; attempt < 3 && !boundedSignal.aborted; attempt++) { await assertTarget(); if (boundedSignal.aborted) break; - const stop = page.locator(CHATGPT_STOP_BUTTON_SELECTOR).filter({ visible:true }); + const stop = stopControls(page); const count = await stop.count(); const dialogCount = (await visibleStopDialogs(page)).length; if (count === 0 && dialogCount === 0) {emit({type:"stop_progress",step:"complete"});return;} - if (count !== 1 && dialogCount === 0) { + if (count > 1 && dialogCount === 0) { throw new BrowserCompanionError("ChatGPT does not have one visible Stop control", "selector_drift"); } try { - if (dialogCount === 0 && await stop.isEnabled()) { - await stop.click({ timeout:timeout(750), signal:boundedSignal }); + if (dialogCount === 0 && count === 1) { + // React may temporarily render the Stop/End-turn control disabled. + // A bounded native click waits for it rather than spinning until timeout. + await stop.click({ timeout:timeout(8_000), signal:boundedSignal }); await requested((["initial","retry","recovery"] as const)[attempt]!); } - await waitForStopped(stop); + await waitForStopped(); emit({type:"stop_progress",step:"complete"}); return; } catch (error) { diff --git a/browser-companion/src/stop-controls.ts b/browser-companion/src/stop-controls.ts new file mode 100644 index 00000000..ea46e213 --- /dev/null +++ b/browser-companion/src/stop-controls.ts @@ -0,0 +1,14 @@ +//! Recognize genuine ChatGPT generation controls across current picker layouts. +//! Adapted from LeZergan/codexify PR #22; no invasive browser pooling. +import type {Page, Locator} from "patchright"; +import {CHATGPT_STOP_BUTTON_SELECTOR} from "./session"; +import {uiLabelPattern} from "./ui-localization"; + +export const END_TURN_CONTROL_NAME = /^End(?: this| current)? turn$/iu; + +export function stopControls(page: Page): Locator { + return page.locator(CHATGPT_STOP_BUTTON_SELECTOR) + .or(page.getByRole("button", {name:uiLabelPattern("stopControl")})) + .or(page.getByRole("button", {name:END_TURN_CONTROL_NAME})) + .filter({visible:true}); +} diff --git a/browser-companion/tests/pairing-submit.test.ts b/browser-companion/tests/pairing-submit.test.ts index 3d100f03..a629eeda 100644 --- a/browser-companion/tests/pairing-submit.test.ts +++ b/browser-companion/tests/pairing-submit.test.ts @@ -978,6 +978,23 @@ test.skipIf(!native)("offline messages and goals stop lingering generation befor } },25_000); +test.skipIf(!native)("offline goal waits for disabled End turn control, then stops exactly once before Send",async()=>{ + const driver=await fixture("",true,connector,31_000,true); + await page.evaluate(()=>{ + const button=document.querySelector("[data-fixture-stop]")!; + button.removeAttribute("data-testid"); + button.setAttribute("aria-label","End turn"); + button.textContent="End turn"; + button.disabled=true; + setTimeout(()=>{button.disabled=false;},650); + }); + const offline=offlineRequest(); + await executeFixture(driver,{request:offline,renderedPrompt:renderActionPrompt(offline.prompt),signal:AbortSignal.timeout(16_000),emit:()=>{}}); + expect(await page.locator("body").getAttribute("data-order")).toBe("stop,stopped,send,"); + expect(await page.locator("body").getAttribute("data-stops")).toBe("1"); + expect(await page.locator("body").getAttribute("data-sends")).toBe("1"); +},20_000); + test.skipIf(!native)("finished responses ignore non-modal ChatGPT popovers rather than treating them as Stop confirmation",async()=>{ for(const aria of [' aria-modal="false"',''] as const){ const driver=await fixture(); diff --git a/browser-companion/tests/stop-controls.test.ts b/browser-companion/tests/stop-controls.test.ts new file mode 100644 index 00000000..a18bedfb --- /dev/null +++ b/browser-companion/tests/stop-controls.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from "bun:test"; +import type { Locator, Page } from "patchright"; +import { stopControls, END_TURN_CONTROL_NAME } from "../src/stop-controls"; +import { CHATGPT_STOP_BUTTON_SELECTOR } from "../src/session"; + +test("Stop recovery uses the known selector, localized button and End turn fallback", () => { + const calls: string[] = []; + const locator = { + or(_other: Locator) { calls.push("or"); return locator; }, + filter(options: Record) { calls.push("visible="+options.visible); return locator; }, + } as unknown as Locator; + const page = { + locator(selector: string) { calls.push("selector="+selector); return locator; }, + getByRole(role: string, options: {name: RegExp}) { + calls.push("role="+role+" name="+options.name.source); return locator; + }, + } as unknown as Page; + expect(stopControls(page)).toBe(locator); + expect(calls).toContain("selector="+CHATGPT_STOP_BUTTON_SELECTOR); + expect(calls).toContain("role=button name="+END_TURN_CONTROL_NAME.source); + expect(calls).toContain("visible=true"); + expect(calls.filter(value => value === "or").length).toBe(2); +}); + +test("End turn fallback matches only explicit end-turn labels", () => { + for (const label of ["End turn", "End this turn", "End current turn"]) + expect(END_TURN_CONTROL_NAME.test(label)).toBe(true); + for (const label of ["Send", "Queue", "End session", "Delete conversation"]) + expect(END_TURN_CONTROL_NAME.test(label)).toBe(false); +}); \ No newline at end of file From e5559edcfa7bdd2831552677ed80469d1c4d3fd6 Mon Sep 17 00:00:00 2001 From: tomi Date: Sat, 14 Nov 2026 08:07:29 +0100 Subject: [PATCH 3/5] test(goal): isolate blocker policy and stabilize Windows Chrome fixtures --- .../tests/pairing-submit.test.ts | 12 +++--- docs/AUTONOMOUS_GOAL_RECOVERY.md | 9 +++- src/agent_automation/goal_blocking.rs | 15 ++++--- src/agent_automation/goal_blocking_policy.rs | 42 +++++++++++++++++++ 4 files changed, 66 insertions(+), 12 deletions(-) create mode 100644 src/agent_automation/goal_blocking_policy.rs diff --git a/browser-companion/tests/pairing-submit.test.ts b/browser-companion/tests/pairing-submit.test.ts index a629eeda..3f6cbd5c 100644 --- a/browser-companion/tests/pairing-submit.test.ts +++ b/browser-companion/tests/pairing-submit.test.ts @@ -249,7 +249,7 @@ async function installFixtureRoutes(){ afterAll(async () => { await context?.close(); if(browserContext!==context)await browserContext?.close(); - if (profile) await rm(profile,{recursive:true,force:true}); + if (profile) await rm(profile,{recursive:true,force:true,maxRetries:8,retryDelay:300}); }); const surface: SingleBrowserSurface = { @@ -989,11 +989,11 @@ test.skipIf(!native)("offline goal waits for disabled End turn control, then sto setTimeout(()=>{button.disabled=false;},650); }); const offline=offlineRequest(); - await executeFixture(driver,{request:offline,renderedPrompt:renderActionPrompt(offline.prompt),signal:AbortSignal.timeout(16_000),emit:()=>{}}); + await executeFixture(driver,{request:offline,renderedPrompt:renderActionPrompt(offline.prompt),signal:AbortSignal.timeout(28_000),emit:()=>{}}); expect(await page.locator("body").getAttribute("data-order")).toBe("stop,stopped,send,"); expect(await page.locator("body").getAttribute("data-stops")).toBe("1"); expect(await page.locator("body").getAttribute("data-sends")).toBe("1"); -},20_000); +},35_000); test.skipIf(!native)("finished responses ignore non-modal ChatGPT popovers rather than treating them as Stop confirmation",async()=>{ for(const aria of [' aria-modal="false"',''] as const){ @@ -1008,7 +1008,7 @@ test.skipIf(!native)("finished responses ignore non-modal ChatGPT popovers rathe expect(await page.locator('body').getAttribute('data-stops')).toBe('0'); expect(await page.locator('[data-testid="nonmodal-menu"]').count()).toBe(1); } -},18_000); +},45_000); test.skipIf(!native)("offline Stop confirms an optional localized dialog before sending once",async()=>{ const prompts:ExecuteActionRequest["prompt"][]=[ @@ -1027,7 +1027,7 @@ test.skipIf(!native)("offline Stop confirms an optional localized dialog before expect(await page.locator('[role="dialog"]').count()).toBe(0); expect(documentLoads).toBe(2); } -},30_000); +},process.platform==="win32"?70_000:30_000); test.skipIf(!native)("offline Stop resumes the captured already-open confirmation before sending",async()=>{ for(const scenario of [{frame:undefined,captured:true,draft:'Existing draft'},{frame:'srcdoc',captured:true,draft:''},{frame:undefined,captured:false,draft:''},{frame:'nested',captured:false,draft:''}] as const){ @@ -1061,7 +1061,7 @@ test.skipIf(!native)("offline Stop never confirms unrelated or ambiguous dialogs expect(await page.locator("body").getAttribute("data-stops")).toBe('preexisting' in scenario?"0":"1"); expect(documentLoads).toBe(2); } -},15_000); +},process.platform==="win32"?40_000:15_000); test.skipIf(!native)("late Stop dialog during message preparation is confirmed before touching the blocked editor",async()=>{ const driver=await fixture(); diff --git a/docs/AUTONOMOUS_GOAL_RECOVERY.md b/docs/AUTONOMOUS_GOAL_RECOVERY.md index 8dd38172..9c71ebf4 100644 --- a/docs/AUTONOMOUS_GOAL_RECOVERY.md +++ b/docs/AUTONOMOUS_GOAL_RECOVERY.md @@ -22,4 +22,11 @@ The 4-page pool from PR #22 was inspected but deliberately NOT installed. This b ## Verification and release -Check Rust formatting, Rust test targets, TypeScript, Stop-control unit tests, native Chrome Stop test, and full browser safety tests. Install only with a guarded quiet-fleet update, a known-good rollback, and a verification of real safe retry. This staging branch has not deployed any behavior by itself. \ No newline at end of file +Check Rust formatting, Rust test targets, TypeScript, Stop-control unit tests, native Chrome Stop test, and full browser safety tests. Install only with a guarded quiet-fleet update, a known-good rollback, and a verification of real safe retry. This staging branch has not deployed any behavior by itself. +## Windows native test runner + +Use Bun 1.4.0 (as specified in upstream CI) for the Patchright/Chrome native fixture tests. An isolated Windows probe showed that Bun 1.3.2 could launch Chrome but did not complete the Patchright connection; Node.js and Bun 1.4.0 completed the same launch quickly. The older runner therefore produces false test-startup failures. Do not weaken production browser timeouts to compensate. + +The multi-scenario Windows fixtures allow additional aggregate test time while preserving original Linux CI budgets and Codexify's actual per-action deadlines. Verify the End-turn wait, localized Stop approval, non-modal popover exclusion, and rejection of unrelated approval dialogs as independent safety cases. + +The Windows Codexify scheduled service requires elevated task-administration privileges for a guarded binary replacement. This branch is not installed merely by pushing commits; retain the original binary, companion and config as rollback inputs. \ No newline at end of file diff --git a/src/agent_automation/goal_blocking.rs b/src/agent_automation/goal_blocking.rs index 870904d6..77d126ea 100644 --- a/src/agent_automation/goal_blocking.rs +++ b/src/agent_automation/goal_blocking.rs @@ -6,6 +6,9 @@ use super::{AgentAutomationStore, GoalStatus}; use crate::project_bindings::ConversationIdentity; use serde::{Deserialize, Serialize}; +#[path = "goal_blocking_policy.rs"] +mod policy; + const BLOCKER_AUDIT_RECORD: &str = "goal-blocker-audit.json"; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -74,10 +77,12 @@ impl AgentAutomationStore { }); let audit = if same { let mut previous = previous.expect("a matching audit exists"); - if previous.last_turn != goal.turn_count { - previous.last_turn = goal.turn_count; - previous.attempts = previous.attempts.saturating_add(1); - } + previous.attempts = policy::next_attempts( + previous.attempts, + previous.last_turn, + goal.turn_count, + ); + previous.last_turn = goal.turn_count; previous } else { BlockerAudit { @@ -90,7 +95,7 @@ impl AgentAutomationStore { } }; super::store::persist_private_record(&path, &audit)?; - Ok((audit.attempts < 3 || now.saturating_sub(audit.first_at_ms) < 60_000) + Ok((!policy::sufficient(audit.attempts, audit.first_at_ms, now)) .then(|| format!( "Goal remains active. Blocker audit {}/3: {}. Investigate alternate free-only work, record evidence in rollout_update, and revisit the exact blocker in a later goal turn. Repeated goal_finish calls within one turn do not count. Three distinct turns spanning at least 60 seconds are required to block this autonomous goal. This does not authorize payments, contracts, private data access, or restricted operations.", audit.attempts.min(3), audit.reason diff --git a/src/agent_automation/goal_blocking_policy.rs b/src/agent_automation/goal_blocking_policy.rs new file mode 100644 index 00000000..b4cf15e9 --- /dev/null +++ b/src/agent_automation/goal_blocking_policy.rs @@ -0,0 +1,42 @@ +//! Dependency-free policy for persistent, repeated autonomous goal blockers. +//! This file can be tested with rustc --test without linking the main Codexify app. + +/// Repeated calls in the same accepted goal turn must not advance the audit. +pub(crate) fn next_attempts(attempts: u32, previous_turn: u64, current_turn: u64) -> u32 { + if previous_turn == current_turn { + attempts + } else { + attempts.saturating_add(1) + } +} + +/// Require three distinct turns and at least one real minute. +pub(crate) fn sufficient(attempts: u32, first_at_ms: u64, now_ms: u64) -> bool { + attempts >= 3 && now_ms.saturating_sub(first_at_ms) >= 60_000 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn repeated_calls_in_one_turn_do_not_count() { + assert_eq!(next_attempts(1, 7, 7), 1); + assert_eq!(next_attempts(2, 8, 8), 2); + assert_eq!(next_attempts(2, 8, 9), 3); + } + + #[test] + fn requires_three_distinct_turns_and_elapsed_time() { + assert!(!sufficient(1, 100, 100_000)); + assert!(!sufficient(2, 100, 100_000)); + assert!(!sufficient(3, 100, 60_099)); + assert!(sufficient(3, 100, 60_100)); + } + + #[test] + fn clock_rollback_and_overflow_are_safe() { + assert!(!sufficient(3, 90_000, 1_000)); + assert_eq!(next_attempts(u32::MAX, 1, 2), u32::MAX); + } +} From 33fad0ff9960f2b2a5cd98e2197f23481253c93f Mon Sep 17 00:00:00 2001 From: tomi Date: Sat, 14 Nov 2026 08:26:03 +0100 Subject: [PATCH 4/5] fix(browser,goal): prevent cooldown tab churn and terminal turn renewals --- browser-companion/src/chrome-surface.ts | 7 +++- browser-companion/src/navigation.ts | 8 ++++ .../tests/chrome-surface.test.ts | 18 ++++++++ docs/AUTONOMOUS_GOAL_RECOVERY.md | 7 ++++ src/agent_automation/goal_blocking.rs | 41 +++++++++++++++++++ src/agent_automation/store.rs | 3 ++ src/agent_automation/supervisor.rs | 10 ++++- src/agent_automation/turn_renewal.rs | 6 +++ 8 files changed, 97 insertions(+), 3 deletions(-) diff --git a/browser-companion/src/chrome-surface.ts b/browser-companion/src/chrome-surface.ts index e69d63df..44cdc63c 100644 --- a/browser-companion/src/chrome-surface.ts +++ b/browser-companion/src/chrome-surface.ts @@ -7,7 +7,7 @@ import type { SingleBrowserSurface } from "./chatgpt-driver"; import { BrowserCompanionError } from "./errors"; import { backgroundChromeArgs } from "./background-chrome"; import {prepareRequestBlockList,requestBlockListArgs,verifyRequestBlockList} from "./request-block-list"; -import {isChatGptPage,navigatePage,observeConversationLoadResponses} from "./navigation"; +import {assertConversationLoadSlot,isChatGptPage,navigatePage,observeConversationLoadResponses} from "./navigation"; import {installChatModeCompatibility} from "./chat-mode"; import {canonicalChatGptConversationUrl,validateChatGptConversationUrl} from "./protocol"; @@ -141,7 +141,10 @@ export class ChromeSingleWindowSurface implements SingleBrowserSurface { &&ChromeSingleWindowSurface.conversationKey(page.url())===key); if(matches.length>1)throw new BrowserCompanionError("Multiple tabs show the same ChatGPT conversation; select a unique target","external_interference"); if(matches.length===1){this.selectedPage=matches[0]!;return this.page();} - const previous=this.selectedPage; + const previous=await this.page(); + // A cooldown rejection must never flash a blank tab before closing it. + // Bypass remains available only for explicitly authorized manual Retry. + assertConversationLoadSlot(previous,url); const page=await this.newTab(); this.selectedPage=page; try { diff --git a/browser-companion/src/navigation.ts b/browser-companion/src/navigation.ts index 37d56f21..e8f08127 100644 --- a/browser-companion/src/navigation.ts +++ b/browser-companion/src/navigation.ts @@ -86,6 +86,14 @@ export function conversationLoadAvailableAt(page:Page,url:string):number|null { return at>Date.now()?at:null; } +// Preflight before creating a new Chrome tab. navigatePage still enforces +// the actual reservation while holding its serialized navigation budget. +export function assertConversationLoadSlot(page:Page,url:string):void { + if(cooldownBypass.getStore())return; + const availableAt=conversationLoadAvailableAt(page,url); + if(availableAt!==null)throw new ConversationCooldownError(Math.min(availableAt,Number.MAX_SAFE_INTEGER)); +} + export function recordConversationUnavailable(page:Page):void { const budget=navigationBudget(page.context()); // Repeated health checks of the same failure must not postpone recovery. diff --git a/browser-companion/tests/chrome-surface.test.ts b/browser-companion/tests/chrome-surface.test.ts index 3552f0b2..28db3d28 100644 --- a/browser-companion/tests/chrome-surface.test.ts +++ b/browser-companion/tests/chrome-surface.test.ts @@ -182,6 +182,24 @@ test("each conversation has a persistent tab and visiting another does not navig expect((b as unknown as FakePage).closed).toBeFalse(); }); +test("automatic cooldown preflight does not create and close flickering blank goal tabs",async()=>{ + const {surface,fake}=await createSurface(); + const first=await surface.selectConversation('https://chatgpt.com/c/first'); + expect(first.url()).toBe('https://chatgpt.com/c/first'); + const count=fake.createdTargets.length; + await expect(surface.selectConversation('https://chatgpt.com/c/second')) + .rejects.toMatchObject({code:"conversation_cooldown"}); + expect(fake.createdTargets).toHaveLength(count); + expect(await surface.page()).toBe(first); + expect(fake.tabs.filter(page=>!page.closed)).toHaveLength(2); + // Explicit manual Retry can bypass the local cooldown, with standard + // navigation and account checks still enforced by the driver. + const next=await withConversationCooldownBypass(true, + ()=>surface.selectConversation('https://chatgpt.com/c/second')); + expect(next.url()).toBe('https://chatgpt.com/c/second'); + expect(fake.createdTargets).toHaveLength(count+1); +}); + test("new-chat preparation reuses only its own draft tab, never another goal",async()=>{ const {surface,fake}=await createSurface(); const goal=await openGoal(surface,'https://chatgpt.com/c/revenue'); diff --git a/docs/AUTONOMOUS_GOAL_RECOVERY.md b/docs/AUTONOMOUS_GOAL_RECOVERY.md index 9c71ebf4..8545aeb0 100644 --- a/docs/AUTONOMOUS_GOAL_RECOVERY.md +++ b/docs/AUTONOMOUS_GOAL_RECOVERY.md @@ -16,6 +16,13 @@ Do not add the new setting to a live older Codexify configuration: older builds The browser companion recognizes a stable Stop selector, a localized Stop button, and the explicit English End-turn control. A bounded native click waits for temporary disabled state. Existing real modal checks, account verification, message ownership and Send safeguards remain mandatory. +## Terminal renewal and cooldown tab churn + +When a goal transitions to blocked or completed, its pending automatic turn-renewal state is cleared; the supervisor also retires stale handoffs for terminal goals. This prevents unnecessary continuation messages in ended revenue goals while preserving renewal for unrelated hourly worker chats. + +Selecting a previously unopened goal conversation now checks the shared ChatGPT navigation cooldown before creating a background tab. A cooldown rejection no longer causes a blank tab to appear and immediately close. The actual navigation reservation remains enforced in navigatePage; a manually authorized cooldown bypass retains its existing behavior. + +The managed ChatGPT Chrome for Testing window was temporarily minimized during investigation to stop visible focus interruptions, without closing the user's normal Chrome. ## Parallel browser lanes The 4-page pool from PR #22 was inspected but deliberately NOT installed. This branch retains one browser action lane until measured tests establish safe isolation, HTTP 429 backoff, memory use and retries on the 16 GB Windows host. diff --git a/src/agent_automation/goal_blocking.rs b/src/agent_automation/goal_blocking.rs index 77d126ea..792742c2 100644 --- a/src/agent_automation/goal_blocking.rs +++ b/src/agent_automation/goal_blocking.rs @@ -192,6 +192,47 @@ mod tests { ); } + #[test] + fn finishing_a_goal_retires_stale_automatic_turn_renewal_without_losing_goal_status() { + let (_root, store, task) = fixture_store(false); + store + .mutate(&task, |state| { + state.turn_renewal.send = Some(super::super::turn_renewal::TurnSend { + action_id: "renewal-send".into(), + at_ms: 5, + model: Some("gpt-6-sol".into()), + effort: Some("xhigh".into()), + pairing_generation: 1, + owner_generation: 1, + }); + state.turn_renewal.handoff = Some(super::super::turn_renewal::TurnHandoff { + id: "old-renewal".into(), + requested_at_ms: 6, + report_complete: true, + }); + Ok(()) + }) + .unwrap(); + assert!(!store.load(&task).unwrap().turn_renewal.is_empty()); + let finished = store + .finish_goal( + &task, + 1, + super::super::GoalFinish::Blocked { + reason: "Payment acceptance requires explicit owner approval".into(), + }, + 100, + ) + .unwrap(); + assert_eq!(finished.status, super::super::GoalStatus::Blocked); + let saved = store.load(&task).unwrap(); + assert!(saved.turn_renewal.is_empty()); + assert_eq!( + saved.goal.unwrap().status, + super::super::GoalStatus::Blocked + ); + } + #[test] fn sidecar_does_not_change_original_goal_state_schema_or_default_policy() { let (_root, store, task) = fixture_store(true); diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index cced04c6..99ff973b 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -1545,6 +1545,9 @@ impl AgentAutomationStore { goal.clone() }; state.goal_wake = GoalWakeState::default(); + // Completing or blocking a goal must retire its unsent automatic + // renewal. Do not continue a terminal commercial goal's chat. + state.turn_renewal = Default::default(); if state.action.goal_revision == Some(expected_revision) { state.action.status = AutomationActionStatus::Idle; state.action.automatic_retry_in_progress = false; diff --git a/src/agent_automation/supervisor.rs b/src/agent_automation/supervisor.rs index 68d847a1..fff322c8 100644 --- a/src/agent_automation/supervisor.rs +++ b/src/agent_automation/supervisor.rs @@ -1760,14 +1760,22 @@ impl AgentAutomationSupervisor { renewal_enabled, now_ms, ); + let terminal_goal = state.goal.as_ref().is_some_and(|goal| { + matches!( + goal.status, + super::GoalStatus::Blocked | super::GoalStatus::Completed + ) + }); let renewal_invalid = activity.agent_stop_requested + || terminal_goal || !renewal_enabled || state.turn_renewal.send.as_ref().is_some_and(|send| { send.owner_generation != task.owner_generation || send.pairing_generation != state.pairing.generation }); if renewal_invalid - && (state.turn_renewal.handoff.is_some() + && (terminal_goal && !state.turn_renewal.is_empty() + || state.turn_renewal.handoff.is_some() || activity.agent_stop_requested && state.turn_renewal.send.is_some()) { task.store.clear_turn_renewal(&task.task)?; diff --git a/src/agent_automation/turn_renewal.rs b/src/agent_automation/turn_renewal.rs index 574f3d3d..3de63a91 100644 --- a/src/agent_automation/turn_renewal.rs +++ b/src/agent_automation/turn_renewal.rs @@ -315,6 +315,12 @@ impl AgentAutomationStore { return Ok(None); } self.mutate(task, |state| { + // The renewal timer is turn-oriented, not goal-oriented. Prevent + // stale sends from renewing completed/blocked goal conversations. + if state.goal.as_ref().is_some_and(|goal| goal.status != super::GoalStatus::Active) { + state.turn_renewal = Default::default(); + return Ok(None); + } let Some(send) = &state.turn_renewal.send else {return Ok(None)}; let Some(minutes) = config.minutes(send.model.as_deref(), send.effort.as_deref()) else {return Ok(None)}; if send.pairing_generation != state.pairing.generation From 2fb171f0781127ce33eedb1b6da5911aca55b2de Mon Sep 17 00:00:00 2001 From: tomi Date: Sat, 14 Nov 2026 08:41:52 +0100 Subject: [PATCH 5/5] fix(browser): minimize managed Windows Chrome until explicitly revealed --- browser-companion/src/chrome-surface.ts | 22 +++++++++++++++++++ .../tests/chrome-surface.test.ts | 8 ++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/browser-companion/src/chrome-surface.ts b/browser-companion/src/chrome-surface.ts index 44cdc63c..93c066f6 100644 --- a/browser-companion/src/chrome-surface.ts +++ b/browser-companion/src/chrome-surface.ts @@ -100,6 +100,10 @@ export class ChromeSingleWindowSurface implements SingleBrowserSurface { const surface=new ChromeSingleWindowSurface(context,control); if(!isChatGptPage(control.url()))await surface.navigate(CHATGPT_HOME); else await control.evaluate(installChatModeCompatibility,undefined,undefined,false); + // The managed Windows browser is a background automation surface. Keep + // newly launched Chrome windows out of the user's foreground desktop. + // An explicit owner reveal() restores the window for interactive use. + await surface.minimizeManagedWindow(); return surface; } catch (error) { await context.close().catch(() => {}); @@ -175,6 +179,24 @@ export class ChromeSingleWindowSurface implements SingleBrowserSurface { return page; } + private async minimizeManagedWindow():Promise { + if(process.platform!=="win32")return; + let session:Awaited>|undefined; + try { + session=await this.context.newCDPSession(this.controlPage); + const window=await session.send("Browser.getWindowForTarget"); + if(window.bounds.windowState!=="minimized") + await session.send("Browser.setWindowBounds",{ + windowId:window.windowId,bounds:{windowState:"minimized"}, + }); + } catch { + // A desktop/window-manager that does not support minimizing must not + // break authenticated automation or silently close user goal tabs. + } finally { + await session?.detach().catch(()=>{}); + } + } + async reveal(): Promise { const page = await this.page(); const session = await this.context.newCDPSession(page); diff --git a/browser-companion/tests/chrome-surface.test.ts b/browser-companion/tests/chrome-surface.test.ts index 28db3d28..cf9af943 100644 --- a/browser-companion/tests/chrome-surface.test.ts +++ b/browser-companion/tests/chrome-surface.test.ts @@ -65,8 +65,8 @@ class FakeContext extends EventEmitter { } async newCDPSession() { return { - send:async (method: string) => { - if (method === "Browser.setWindowBounds") this.windowState = "normal"; + send:async (method: string, params?: {bounds?: {windowState?: string}}) => { + if (method === "Browser.setWindowBounds") this.windowState = params?.bounds?.windowState ?? "normal"; return { windowId:1, bounds:{ windowState:this.windowState } }; }, detach:async () => {}, @@ -123,10 +123,12 @@ test("startup creates a background page and only an explicit reveal restores foc const { surface, fake } = await createSurface([]); expect(fake.createdTargets).toEqual([{ url:"about:blank", newWindow:true, background:true }]); expect(fake.tabs[0]!.revealed).toBeFalse(); + if(process.platform==="win32")expect(fake.windowState).toBe("minimized"); await surface.beginAction(); await surface.endAction(); expect(fake.tabs[0]!.revealed).toBeFalse(); - expect(fake.windowState).toBe("normal"); + // Background goal actions do not restore the owner's Chrome window. + if(process.platform==="win32")expect(fake.windowState).toBe("minimized"); fake.windowState = "minimized"; await surface.reveal(); expect(fake.windowState).toBe("normal");