Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions browser-companion/src/chatgpt-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -56,7 +57,7 @@ export function responseCompletionReady(input: {
}

async function generationRunning(page: Page): Promise<boolean> {
return page.locator(CHATGPT_STOP_BUTTON_SELECTOR).filter({ visible:true }).count()
return stopControls(page).count()
.then(count => count > 0)
.catch(() => false);
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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));
}
Expand All @@ -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) {
Expand Down
29 changes: 27 additions & 2 deletions browser-companion/src/chrome-surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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(() => {});
Expand Down Expand Up @@ -141,7 +145,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 {
Expand Down Expand Up @@ -172,6 +179,24 @@ export class ChromeSingleWindowSurface implements SingleBrowserSurface {
return page;
}

private async minimizeManagedWindow():Promise<void> {
if(process.platform!=="win32")return;
let session:Awaited<ReturnType<BrowserContext["newCDPSession"]>>|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<void> {
const page = await this.page();
const session = await this.context.newCDPSession(page);
Expand Down
8 changes: 8 additions & 0 deletions browser-companion/src/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions browser-companion/src/stop-controls.ts
Original file line number Diff line number Diff line change
@@ -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});
}
26 changes: 23 additions & 3 deletions browser-companion/tests/chrome-surface.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {},
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -182,6 +184,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');
Expand Down
25 changes: 21 additions & 4 deletions browser-companion/tests/pairing-submit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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<HTMLButtonElement>("[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(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");
},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){
const driver=await fixture();
Expand All @@ -991,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"][]=[
Expand All @@ -1010,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){
Expand Down Expand Up @@ -1044,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();
Expand Down
30 changes: 30 additions & 0 deletions browser-companion/tests/stop-controls.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) { 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);
});
39 changes: 39 additions & 0 deletions docs/AUTONOMOUS_GOAL_RECOVERY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 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.

## 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.

## 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.
## 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.
Loading