Skip to content
Merged
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
1 change: 1 addition & 0 deletions changelog.d/fixes/13381-gemini-web-model-selection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(providers):** `gemini-web` now attempts to select and verify the requested Gemini UI mode (and Extended Thinking) before answering, and fails closed with a clear 400 instead of silently running the account default under a mismatched model label (#13381) — thanks @formilw
106 changes: 95 additions & 11 deletions open-sse/executors/gemini-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,20 @@ import { buildToolModeResponse } from "./chatgptWebTools.ts";
import {
checkGeminiWebUnsupportedControls,
GEMINI_WEB_UNSUPPORTED_CONTROL_CODE,
isForcingToolChoice,
requestsThinkingBudget,
} from "./gemini-web/capabilities.ts";
import {
describeModeSelectionFailure,
selectGeminiExtendedThinking,
selectGeminiModel,
} from "./gemini-web/modeSelection.ts";

// ─── Constants ──────────────────────────────────────────────────────────────

const GEMINI_URL = "https://gemini.google.com/app";
/** Response-label fallback when no `model` was requested at all (unchanged since pre-#13381). */
const DEFAULT_MODEL_ID = "gemini-2.5-pro";

// Re-exported for backward compatibility: some tests/callers import this classification helper
// from gemini-web.ts, its original home (#3516). The implementation now lives in
Expand Down Expand Up @@ -416,21 +425,28 @@ export class GeminiWebExecutor extends BaseExecutor {
const { model, body, stream, credentials, signal, log, onCredentialsRefreshed } = input;
const requestBody = body as GeminiRequestBody;

// #9356: fail fast on controls this provider cannot honor (reasoning_effort
// above "minimal", forced tool_choice). Runs before the credential check and
// before Playwright launches — the request is unservable no matter which
// cookie is used, and answering 200 with ordinary prose made agents believe
// their reasoning/tool requirements had been met. See ./gemini-web/capabilities.ts.
const violation = checkGeminiWebUnsupportedControls(body as Record<string, unknown>);
if (violation) {
// #9356: forced tool_choice is a guarantee gemini-web's prompt-emulation shim can
// never make — no UI control for it exists at all, on any account, so this still
// fails fast before the credential check and before Playwright launches. See
// ./gemini-web/capabilities.ts.
//
// `reasoning_effort` (Extended Thinking) is different (#13381 follow-up comment,
// 2026-09-11): eligible Gemini accounts DO expose a real Extended Thinking toggle
// in the UI, so a blanket "we can never do this" would be the same dishonesty this
// fix exists to remove. It is no longer rejected here — it is attempted, verified
// via read-back, and only THEN rejected if it cannot be confirmed. See the in-browser
// step below and ./gemini-web/modeSelection.ts.
const rawBody = body as Record<string, unknown>;
if (isForcingToolChoice(rawBody.tool_choice)) {
const violation = checkGeminiWebUnsupportedControls({ tool_choice: rawBody.tool_choice });
log?.warn?.(
"GEMINI-WEB",
`Rejected request: "${violation.param}" is not supported by this provider`
`Rejected request: "${violation!.param}" is not supported by this provider`
);
return {
response: new Response(
JSON.stringify(
buildErrorBody(400, violation.message, null, {
buildErrorBody(400, violation!.message, null, {
type: "invalid_request_error",
code: GEMINI_WEB_UNSUPPORTED_CONTROL_CODE,
})
Expand All @@ -442,6 +458,7 @@ export class GeminiWebExecutor extends BaseExecutor {
transformedBody: body,
};
}
const wantsExtendedThinking = requestsThinkingBudget(rawBody.reasoning_effort);

const cookie = resolveGeminiWebCookie(credentials);
if (!cookie) {
Expand Down Expand Up @@ -493,6 +510,11 @@ export class GeminiWebExecutor extends BaseExecutor {
};
}

// Resolved up front (#13381) — the pre-fix code only read `model` AFTER the
// response was already captured, purely to stamp it on the reply. It now also
// drives the in-browser mode-selection step below, before anything is typed.
const modelId = model || DEFAULT_MODEL_ID;

let browser: any = null;
let abortBrowser: (() => void) | null = null;
try {
Expand Down Expand Up @@ -549,6 +571,70 @@ export class GeminiWebExecutor extends BaseExecutor {
}
await page.waitForTimeout(3000);

// #13381 (Option B): verify the requested Gemini UI mode is actually active
// BEFORE anything is typed. `gemini-3.1-pro` is the mode gemini.google.com/app
// already opens to (no interaction attempted); every other advertised model is
// switched to and its active-mode indicator is read back — a confirmed match is
// required, or the request is rejected instead of silently running the account
// default under the requested model's label. See ./gemini-web/modeSelection.ts
// for why the selectors involved are UNVALIDATED and why that is safe here.
if (model) {
const modelSelection = await selectGeminiModel(page, modelId);
if (!modelSelection.confirmed) {
log?.warn?.(
"GEMINI-WEB",
`Rejected request: could not confirm Gemini UI mode for "${modelId}" ` +
`(${modelSelection.reason})`
);
return {
response: new Response(
JSON.stringify(
buildErrorBody(
400,
describeModeSelectionFailure(modelId, modelSelection.reason),
null,
{ type: "invalid_request_error", code: GEMINI_WEB_UNSUPPORTED_CONTROL_CODE }
)
),
{ status: 400, headers: { "Content-Type": "application/json" } }
),
url: GEMINI_URL,
headers: {},
transformedBody: body,
};
}
}

// Extended Thinking (#13381 follow-up, 2026-09-11): same detect-and-verify,
// fail-closed pattern as model selection above — attempted only when requested
// (`reasoning_effort` above "minimal"), never assumed available.
if (wantsExtendedThinking) {
const thinkingSelection = await selectGeminiExtendedThinking(page);
if (!thinkingSelection.confirmed) {
log?.warn?.(
"GEMINI-WEB",
`Rejected request: could not confirm Extended Thinking is available ` +
`(${thinkingSelection.reason})`
);
return {
response: new Response(
JSON.stringify(
buildErrorBody(
400,
describeModeSelectionFailure("Extended Thinking", thinkingSelection.reason),
null,
{ type: "invalid_request_error", code: GEMINI_WEB_UNSUPPORTED_CONTROL_CODE }
)
),
{ status: 400, headers: { "Content-Type": "application/json" } }
),
url: GEMINI_URL,
headers: {},
transformedBody: body,
};
}
}

// Type and send message
const inputEl = await page.waitForSelector(".ql-editor, [contenteditable='true']", {
timeout: 10000,
Expand Down Expand Up @@ -584,8 +670,6 @@ export class GeminiWebExecutor extends BaseExecutor {

await this.persistRotatedCookies(context, cookie, credentials, onCredentialsRefreshed, log);

const modelId = model || "gemini-2.5-pro";

if (hasTools) {
const cid = `chatcmpl-gwe-${crypto.randomUUID().slice(0, 12)}`;
const created = Math.floor(Date.now() / 1000);
Expand Down
214 changes: 214 additions & 0 deletions open-sse/executors/gemini-web/modeSelection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/**
* Per-model Gemini Web UI mode selection + verification (#13381, Option B).
*
* Before this module, `GeminiWebExecutor.execute()` read the `model` field
* only AFTER Gemini had already answered — purely to stamp the OpenAI-shaped
* response, never to influence what was actually typed/clicked in the
* browser (../gemini-web.ts). Every advertised `gweb/<model>` alias ran the
* identical automation, so the response `model` field was a caller-supplied
* label, not an observed fact.
*
* This module gives the executor a real selection step: for each advertised
* model (and for the Extended Thinking control, #13381 follow-up comment
* 2026-09-11), it tries the corresponding UI control, then READS BACK the
* active-mode indicator to confirm the switch actually took effect before
* the caller is allowed to proceed. `gemini-3.1-pro` is treated as the mode
* `gemini.google.com/app` already opens to (no interaction needed); every
* other advertised model requires a confirmed switch.
*
* ⚠️ SELECTOR SET IS UNVALIDATED. Every CSS selector below is a best-effort
* guess at Gemini's current DOM, not a value confirmed against a live
* account — this checkout has no live Gemini session and no way to inspect
* Google's current markup (which also changes without notice). That is fine
* BY DESIGN: `selectGeminiUiMode()` never trusts an unconfirmed guess. If a
* selector is wrong — the likely outcome until the mandatory live smoke in
* the PR is run and these values are corrected against the real DOM — the
* toggle/indicator lookup simply fails, the read-back does not confirm the
* requested mode, and the caller gets a clear 400
* (`unsupported_control_for_provider`) instead of a response silently
* labeled with a model/mode that never actually ran — the exact dishonesty
* #13381 reported. Update the selectors only after inspecting the real DOM
* on a live account, never from guesswork.
*/

/** Reasons `selectGeminiUiMode`/`selectGeminiModel` can fail closed. */
export type GeminiModeSelectionFailureReason =
"control_not_found" | "indicator_not_found" | "indicator_mismatch" | "unknown_model";

export interface GeminiWebModeDescriptor {
/** The advertised `gweb/<model>` id, or a synthetic label for non-model controls. */
readonly id: string;
/**
* true: this is the mode `gemini.google.com/app` already shows on load — no
* UI interaction is attempted, nothing to confirm.
*/
readonly isDefault: boolean;
/** UNVALIDATED — opens/activates the control for this mode. Ignored when `isDefault`. */
readonly toggleSelector?: string;
/** UNVALIDATED — element whose text proves which mode is now active. */
readonly activeIndicatorSelector?: string;
/** Text the active-mode indicator must contain once the switch is confirmed. */
readonly expectedIndicatorPattern?: RegExp;
}

/**
* Model -> Gemini UI mode map for the three `gweb/<model>` ids advertised by
* `open-sse/config/providers/registry/gemini/web/index.ts`. Keep the two
* catalogs in sync: an advertised model with no entry here fails closed as
* `unknown_model` (see `resolveGeminiModelMode`), which is the intended,
* honest behavior for a model this module cannot yet select.
*/
export const GEMINI_WEB_MODEL_MODES: Readonly<Record<string, GeminiWebModeDescriptor>> = {
"gemini-3.1-pro": { id: "gemini-3.1-pro", isDefault: true },
"gemini-3.7-flash": {
id: "gemini-3.7-flash",
isDefault: false,
toggleSelector:
'[data-test-id="bard-mode-menu-button"], button[aria-haspopup="menu"][aria-label*="model" i]',
activeIndicatorSelector:
'[data-test-id="bard-mode-menu-button"] .mode-title, [data-test-id="bard-mode-menu-button"]',
expectedIndicatorPattern: /\bflash\b(?!.*\blite\b)/i,
},
"gemini-3.1-flash-lite": {
id: "gemini-3.1-flash-lite",
isDefault: false,
toggleSelector:
'[data-test-id="bard-mode-menu-button"], button[aria-haspopup="menu"][aria-label*="model" i]',
activeIndicatorSelector:
'[data-test-id="bard-mode-menu-button"] .mode-title, [data-test-id="bard-mode-menu-button"]',
expectedIndicatorPattern: /flash.*\blite\b/i,
},
};

/** The Extended Thinking control (#13381 follow-up, 2026-09-11) — account-dependent, not a model. */
export const GEMINI_WEB_EXTENDED_THINKING_MODE: GeminiWebModeDescriptor = {
id: "extended-thinking",
isDefault: false,
toggleSelector:
'[data-test-id="deep-think-toggle"], button[aria-label*="extended thinking" i], ' +
'button[aria-label*="deep think" i]',
activeIndicatorSelector:
'[data-test-id="deep-think-toggle"][aria-pressed="true"], [data-test-id="deep-think-toggle"].is-active',
expectedIndicatorPattern: /thinking|deep think/i,
};

/** Minimal Playwright-shaped element the read-back needs — real `ElementHandle`s satisfy this. */
export interface GeminiAutomationElement {
click(): Promise<void>;
textContent?(): Promise<string | null>;
innerText?(): Promise<string>;
}

/** Minimal Playwright-shaped page the selection step needs — the real `Page` satisfies this. */
export interface GeminiAutomationPage {
waitForSelector(
selector: string,
opts?: { timeout?: number }
): Promise<GeminiAutomationElement | null>;
}

export interface GeminiModeSelectionResult {
confirmed: boolean;
reason?: GeminiModeSelectionFailureReason;
descriptor?: GeminiWebModeDescriptor;
}

async function readIndicatorText(el: GeminiAutomationElement): Promise<string | null> {
try {
if (typeof el.textContent === "function") {
const text = await el.textContent();
if (typeof text === "string") return text;
}
if (typeof el.innerText === "function") {
return await el.innerText();
}
} catch {
// Unreadable is treated the same as "did not confirm" below — never a pass.
}
return null;
}

/**
* Try to switch the live Gemini Web page to `descriptor`'s mode, then READ
* BACK the active-mode indicator before reporting success. A click landing
* is never itself treated as success — only a confirmed, pattern-matching
* indicator text is (#13381).
*/
export async function selectGeminiUiMode(
page: GeminiAutomationPage,
descriptor: GeminiWebModeDescriptor,
timeoutMs = 5000
): Promise<GeminiModeSelectionResult> {
if (descriptor.isDefault) return { confirmed: true, descriptor };

const { toggleSelector, activeIndicatorSelector, expectedIndicatorPattern } = descriptor;
if (!toggleSelector || !activeIndicatorSelector || !expectedIndicatorPattern) {
return { confirmed: false, reason: "control_not_found", descriptor };
}

const toggle = await page
.waitForSelector(toggleSelector, { timeout: timeoutMs })
.catch(() => null);
if (!toggle) return { confirmed: false, reason: "control_not_found", descriptor };

await toggle.click();

const indicator = await page
.waitForSelector(activeIndicatorSelector, { timeout: timeoutMs })
.catch(() => null);
if (!indicator) return { confirmed: false, reason: "indicator_not_found", descriptor };

const text = await readIndicatorText(indicator);
if (!text || !expectedIndicatorPattern.test(text)) {
return { confirmed: false, reason: "indicator_mismatch", descriptor };
}

return { confirmed: true, descriptor };
}

export function resolveGeminiModelMode(modelId: string): GeminiWebModeDescriptor | null {
return GEMINI_WEB_MODEL_MODES[modelId] ?? null;
}

/** Select + verify the requested advertised model's Gemini UI mode. */
export async function selectGeminiModel(
page: GeminiAutomationPage,
modelId: string,
timeoutMs?: number
): Promise<GeminiModeSelectionResult> {
const descriptor = resolveGeminiModelMode(modelId);
if (!descriptor) return { confirmed: false, reason: "unknown_model" };
return selectGeminiUiMode(page, descriptor, timeoutMs);
}

/** Select + verify the Extended Thinking control (#13381 follow-up). */
export async function selectGeminiExtendedThinking(
page: GeminiAutomationPage,
timeoutMs?: number
): Promise<GeminiModeSelectionResult> {
return selectGeminiUiMode(page, GEMINI_WEB_EXTENDED_THINKING_MODE, timeoutMs);
}

const REASON_DETAIL: Record<GeminiModeSelectionFailureReason, string> = {
unknown_model: "it is not one of the advertised, selectable gweb models",
control_not_found: "the Gemini UI control used to switch modes was not found",
indicator_not_found: "the active-mode indicator used to confirm the switch was not found",
indicator_mismatch: "the active-mode indicator did not confirm the switch after attempting it",
};

/**
* Client-facing explanation for a failed-closed selection, safe to put
* directly in a response body (no selector text, no stack trace).
*/
export function describeModeSelectionFailure(
controlLabel: string,
reason: GeminiModeSelectionFailureReason | undefined
): string {
const detail = (reason && REASON_DETAIL[reason]) || "the switch could not be verified";
return (
`Model provider "gemini-web" could not verify that "${controlLabel}" is actually active in ` +
`the Gemini web UI (${detail}). Rather than silently answering under a model/mode label that ` +
'may not be accurate, the request was rejected with "unsupported_control_for_provider" — ' +
"see #13381."
);
}
Loading
Loading