Repository navigation
Conversation
…a Gemini web UI (CDP) The reverse-engineered API channel (main.ts) breaks when Google changes its web protocol (as it did in Oct 2026, with no upstream fix possible on our side). For TEXT generation this adds scripts/gemini-webui.ts, which drives the real gemini.google.com page over CDP instead, so it keeps working across protocol changes. - Text-only by design: no --model/--image/--reference; submits through the web UI, so the model selected in the page applies - Reuses the skill's existing conventions: same Chrome profile, consent gate, env vars, and path resolvers (gemini-webapi/utils/paths.ts); built on the existing baoyu-chrome-cdp package - no new dependencies - Headless by default; the HeadlessChrome UA token is bot-detected on gemini.google.com, so the driver presents the browser's own standard UA (version read from the browser itself via --version) - Session behavior is two-mode and described as observed: without a signed-in profile the web app runs anonymously (chats work but are not saved, so each call starts a new conversation and --sessionId only records the chat URL); with a signed-in profile the same --sessionId re-opens the saved conversation. A bind-check detects a dropped thread and self-heals by continuing on a fresh chat - Robust submission: chunked insertText with surrogate-pair guard, send-button click with Enter fallback, new-turn confirmation before answer polling (stable-4), session map written atomically (0600) - --json emits the same primary "text" field as main.ts --json, so downstream consumers can switch channels without changes - SKILL.md: net-new "Text Generation via Web UI" section + script table row; README.md / README.zh.md get matching notes Tested on macOS (real probes against gemini.google.com): CLI error paths, multi-file promptfiles, JSON output, emoji boundary handling, session map persistence, clean Chrome teardown. Windows/Linux reuse the same candidate tables and path resolvers as existing scripts. Version bump intentionally left to the release process.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64bc09fdb9
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| throw new Error('Prompt was not submitted (no new turn appeared).'); | ||
| } | ||
|
|
||
| const responsesBefore = await countElements('model-response'); |
There was a problem hiding this comment.
Capture the response baseline before sending
When Gemini creates the new <model-response> element before the one-second user-turn poll notices the submitted <user-query> (especially for a quick reply), this count already includes the response being awaited. The later all.length <= responsesBefore guard then ignores that response forever, so the command waits until the default 480-second timeout and reports that no response was captured even though the answer is visible.
Useful? React with 👍 / 👎.
| if (loc.includes('accounts.google') || loc.includes('ServiceLogin')) { | ||
| throw new Error( | ||
| 'NEED_LOGIN: not signed in. Run once with --show-window and sign in to your Google account in the window that opens.', | ||
| ); |
There was a problem hiding this comment.
Wait for login when showing the browser
When a fresh or expired profile is redirected to accounts.google.com, this branch throws immediately even if --show-window was supplied, and the finally block then kills the spawned browser. Consequently, the error's documented recovery of running once with --show-window cannot leave the window open long enough to complete login, so users in flows without anonymous access cannot establish the signed-in profile needed for multi-turn sessions.
Useful? React with 👍 / 👎.
| console.log(lastText); | ||
| } | ||
| } finally { | ||
| if (cdp) cdp.close(); |
There was a problem hiding this comment.
Close the reused tab before closing CDP
When findExistingChromeDebugPort succeeds, chrome is null and this closes the WebSocket before the following else if sends Target.closeTarget. That send is rejected and deliberately swallowed, so the fresh target opened for the invocation remains in the user's running browser and repeated calls accumulate abandoned Gemini tabs.
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| function saveSessionMap(file: string, update: Record<string, string>): void { | ||
| writeSessionMap(file, { ...loadSessionMap(file), ...update }); |
There was a problem hiding this comment.
Serialize writes to the shared session map
When two invocations with different --sessionId values complete concurrently, both can read the same old map here and then each replace the whole file with only its own merged update. The later write silently drops the other completed conversation's URL, so a subsequent continuation starts a fresh chat; use per-session files or an interprocess-safe read-modify-write strategy.
Useful? React with 👍 / 👎.
…driver - Locate our answer by turn index (Nth user-query pairs with the Nth model-response) instead of a baseline count sampled after submit; a fast reply that rendered before the poll could previously be swallowed by the baseline and run to the full timeout. - With --show-window, wait for sign-in on the accounts.google.com redirect instead of throwing (which killed the window mid-login). - Close the reused browser's tab before closing the CDP connection; the previous order failed the send silently and leaked the tab. - Store the conversation URL per session file instead of a shared JSON map, so concurrent runs with different session ids cannot clobber each other; the legacy shared map is still read for migration.
|
Pushed 3000347 addressing all four Codex findings:
Verified: @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 300034778e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| let userTurns = userTurnsBefore; | ||
| while (Date.now() < turnsDeadline) { | ||
| userTurns = await countElements('user-query'); | ||
| if (userTurns > userTurnsBefore) break; |
There was a problem hiding this comment.
Distinguish the submitted turn from loading history
The new turn-index logic fixes fast replies, but when a resumed conversation is still adding historical <user-query> nodes after userTurnsBefore is sampled, one of those nodes can satisfy this condition before the submitted node does. ourResponseIndex is then a historical index (and can shift again as earlier nodes are inserted), so the stable polls can return an old answer as this command's result; wait for history to settle or identify the submitted turn itself before choosing the response.
Useful? React with 👍 / 👎.
| if (cdp) cdp.close(); | ||
| if (chrome) { | ||
| // We spawned this browser: shut it down so the profile is released. | ||
| await gracefulKillChrome(chrome, port); |
There was a problem hiding this comment.
Serialize commands before shutting down their shared Chrome
When two invocations overlap on the same profile, the later one can discover and attach to the Chrome child spawned by the first via findExistingChromeDebugPort; when the first finishes here it kills the entire browser, closing the later invocation's tab and CDP connection while it is still waiting for an answer. The per-session store explicitly supports concurrent IDs, so browser ownership must be serialized or the owner must avoid shutting down a browser with active clients.
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| function sessionUrlFile(dataDir: string, id: string): string { | ||
| const safe = id.replace(/[^A-Za-z0-9._-]/g, '_'); |
There was a problem hiding this comment.
Preserve session IDs when deriving file names
For session IDs containing unsupported characters, this replacement is not injective (a/b and a?b both become a_b.json), and case-only IDs also collide on default macOS/Windows filesystems. Because loadSessionUrl trusts that file before consulting legacy data, one ID can resume and then overwrite another ID's Gemini conversation; use an injective encoding/hash or reject noncanonical IDs.
Useful? React with 👍 / 👎.
| process.on('SIGINT', () => killChromeAndExit(130)); | ||
| process.on('SIGTERM', () => killChromeAndExit(143)); |
There was a problem hiding this comment.
Clean up reused targets on termination signals
When findExistingChromeDebugPort reuses a browser, execution skips this block, so no SIGINT/SIGTERM handler is installed; Ctrl-C then terminates the process without running the asynchronous finally, leaving the fresh Target.createTarget tab open in the user's browser. The reordered cleanup fixes normal completion, but reused-browser signals still need to close targetId before exiting.
Useful? React with 👍 / 👎.
…ngs in webui driver - Sample the history baseline only after lazy-rendered <user-query> nodes settle, so the response index never lands on a historical turn (P1) - Serialize whole invocations on a profile lock file with stale-pid detection; a later run can no longer attach to a browser the earlier run shuts down, and the lock is always released in finally (P2) - Hash session ids into file names (sha256 hex) instead of character sanitization, which was not injective across separators or case (P2) - Install SIGINT/SIGTERM handlers even when attaching to an existing browser, and close our own tab before exiting on signals (P2)
|
Pushed 6ee8a39 addressing the second-round review findings:
Verified: tsc clean (only the pre-existing Bun global type note), live probe through the modified driver passes (lock acquired/released, response captured), local skill copy synced. @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ee8a3914a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const lockFile = path.join(dataDir, 'webui-invoke.lock'); | ||
| await acquireInvokeLock(lockFile, 10 * 60_000); |
There was a problem hiding this comment.
Place the lock at the shared-profile layer
When two processes share profileDir but have different GEMINI_WEB_DATA_DIR values, they acquire different locks here; moreover, main.ts --login uses the same profile without this lock (gemini-webapi/utils/load-browser-cookies.ts:182-190,238-248) and may spawn or attach to that Chrome and later shut it down. In either supported overlap the browser can still disappear mid-answer, so coordinate ownership with a lock keyed by the canonical profile and shared by every profile user.
Useful? React with 👍 / 👎.
| const deadline = Date.now() + (args.showWindow ? 300_000 : 60_000); | ||
| let hintShown = false; | ||
| while (Date.now() < deadline) { | ||
| if (await composerReady()) return; |
There was a problem hiding this comment.
Pause for sign-in in anonymous mode
When a signed-out profile is allowed to use Gemini anonymously, as the new documentation says, the anonymous page already has a composer, so this return fires before the accounts.google branch and --show-window immediately types and submits the prompt. The spawned window is then closed after the answer, leaving no reliable opportunity to perform the documented one-time sign-in; add an explicit login/wait path instead of treating an anonymous composer as completion.
Useful? React with 👍 / 👎.
| if (Number.isInteger(holderPid) && holderPid > 0 && !processExists(holderPid)) { | ||
| fs.rmSync(file, { force: true }); | ||
| continue; |
There was a problem hiding this comment.
Make stale-lock takeover atomic
When a holder has crashed and two invocations are waiting, both can read the dead PID before either removes the file; after one waiter unlinks it and creates its own lock, the other can execute this rmSync based on the stale read and delete the new owner's lock. Both then enter the browser section, recreating the attach/shutdown race this lock is meant to prevent, so stale takeover must verify ownership atomically or use an OS-backed lock.
Useful? React with 👍 / 👎.
- Profile-keyed lock in the shared temp dir (sha256 of the canonical profile dir), so overlapping profile users with different data dirs serialize; load-browser-cookies.ts acquires the same lock around its Chrome spawn/attach (new scripts/profile-lock.ts) (P2) - Stale-lock takeover is rename-based: the waiter atomically renames the stale file to a trash name, re-reads the pid inside it to confirm it moved the lock it read, and only then recreates — two concurrent waiters can no longer delete each other's fresh lock (P2) - Signed-out profiles pause for sign-in under --show-window before typing (the anonymous page has a composer, so the old composer check fired first and closed the window before the documented sign-in could happen); headless runs warn and continue anonymously, and GEMINI_WEBUI_ANONYMOUS=1 skips the wait (P2) Verified: tsc clean (no new errors vs baseline), lock probe passes (concurrent stale takeover serializes, no residue, symlink-keyed), live headless anonymous probe answers end-to-end.
|
Pushed 103ce62 addressing the third-round review findings:
Verified: tsc clean (no new errors vs baseline), lock probe passes, live headless probe passes. @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 103ce6250f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // account domain; a signed-in page shows the account avatar instead. | ||
| const signInLinkPresent = async (): Promise<boolean> => | ||
| Boolean( | ||
| await evalJs(`!!document.querySelector('a[href^="https://accounts.google.com/"]')`).catch(() => false), |
There was a problem hiding this comment.
Distinguish sign-in from other Accounts links
The new signInLinkPresent check treats every Accounts-domain anchor as the signed-out CTA, but the signed-in Google account avatar itself links to https://accounts.google.com/SignOutOptions...; a signed-in --show-window invocation therefore waits the full five minutes on every prompt. In the opposite direction, a normal same-tab click navigates to ServiceLogin where this page anchor disappears (and evaluation errors are coerced to false), so it can declare success before credentials are complete and then close on the missing composer. Match the actual sign-in CTA and finish only after returning to Gemini with the composer ready.
Useful? React with 👍 / 👎.
| // stays protected; if that fails, drop it and queue behind whoever | ||
| // holds the lock now. | ||
| try { | ||
| fs.renameSync(trash, file); |
There was a problem hiding this comment.
Avoid replacing a newer lock during stale recovery
The new restore branch still leaves a stale-takeover race with three waiters: after one waiter replaces the stale file with its live lock, a second waiter that read the old PID can move that live lock to trash, allowing a third waiter to create the now-absent lock and enter. On POSIX, this renameSync(trash, file) then replaces the third waiter's lock rather than failing, so the first and third processes overlap in the browser section; use an OS-backed lock or an ownership primitive that never removes a live lock pathname while validating it.
Useful? React with 👍 / 👎.
| const existingPort = await find_existing_chrome_debug_port(profileDir); | ||
| const reusing = existingPort !== null; | ||
| const port = existingPort ?? await get_free_port(); |
There was a problem hiding this comment.
Release the profile lock when browser setup fails
When Chrome discovery, port allocation, or launch_chrome throws before the try (most commonly because no executable is found), the lock acquired just above is never released. get_access_token catches the first cookie-load failure and retries at gemini-webapi/utils/get-access-token.ts:164; the same live PID then owns this lock, so a login with no usable cached cookies stalls for the full 10-minute lock timeout instead of reporting the Chrome error. Put all post-acquire setup under the releasing finally.
Useful? React with 👍 / 👎.
Problem
The reverse-engineered API channel (
scripts/main.ts) speaks a protocol Google can change at any time — and did in Oct 2026, which took text generation down for affected users with no client-side fix. Since the real gemini.google.com page always speaks the current protocol, this PR adds a CDP-based web-UI driver as a resilient path for text generation.Approach
New script
skills/baoyu-danger-gemini-web/scripts/gemini-webui.ts(~370 lines):baoyu-chrome-cdppackage — zero new dependencies). Image generation stays onmain.ts.--model(the model selected in the web page applies), no--image, no--reference. This is stated up front in code comments and SKILL.md so nobody expects parity with the API channel.resolveGeminiWebChromeProfileDir), consent gate, env vars (GEMINI_WEB_CHROME_PATH,--profile-dir, proxy vars) and path resolvers fromgemini-webapi/utils/paths.ts. It also reuses the same browser-candidate table asload-browser-cookies.ts.--promptfiles <files...>variadic semantics matchmain.ts(consumes all following non-flag values); stdin also accepted.--jsonemits the same primarytextfield asmain.ts --json, so downstream consumers can switch channels without changes ({ text, candidates: [], metadata: { via: "webui" }, sessionId }).Session behavior (described as observed, two modes)
--sessionIdre-opens the saved conversation URL (persisted atomically in<data-dir>/webui-sessions.json, mode 0600) for multi-turn continuation. A bind-check confirms the app actually rebound to the saved thread; if the thread is gone (deleted chat / dropped login), the driver proceeds on a fresh chat and re-maps the id instead of silently typing into the wrong conversation.--sessionIdonly records the chat URL. This is documented in code, SKILL.md and both READMEs;--show-windowlets the user sign in to unlock multi-turn.Bot detection
Headless by default. The
HeadlessChromeUA token is a known bot signal on gemini.google.com, so in headless mode the driver presents the platform-standard UA, with the version read from the installed browser itself (--version) rather than hardcoded.SKILL.md changes
Net-new only (nothing removed): one row in the Script Directory table and a new "Text Generation via Web UI" section (usage examples, headless/UA note, two-mode session behavior, truncation follow-up tip). README.md and README.zh.md get matching notes in the skill's section.
Testing
macOS (macOS 27.3.0 / Chrome stable), real probes against gemini.google.com:
--timeout, empty stdin on TTY,--help)--promptfiles a.md b.md --jsonreturns JSON with correct shape; emoji at chunk boundaries survives intact (surrogate-pair guard verified with emoji at index 1999); session map written with mode 0600; clean Chrome teardown (zero leftover processes); Ctrl-C kills the spawned headless browser--timeoutbounds the waitWindows/Linux: no platform-specific code beyond the shared candidate tables (same pattern as existing scripts) and
paths.tsresolvers, which already handle win32/XDG/WSL.Not touched
main.ts, thegemini-webapi/port, consent flow, packaging. Version bump left to the release process.Disclosure
This driver automates the user's own logged-in browser session on gemini.google.com (the same surface a human uses), as a fallback for the reverse-engineered API this skill already ships — it does not attack any additional Google endpoint. ToS gray zone is unchanged in kind; flagged for maintainer awareness.