# One command that sets up Browser Workflow on Windows, for the AI apps on this computer: the # ChatGPT desktop app (Codex), the Claude desktop app, Claude Code and Antigravity. It is install.sh # for Windows: the same steps and the same results, written for PowerShell (Windows PowerShell 5.1 # and newer), and one thing more: the Claude desktop app. On a Mac that app installs the downloaded # file with a double-click; on Windows the file opens nothing, so this command sets it up instead. # # irm https://browser-workflow.web.app/install.ps1 | iex install (or update: see below) # $env:BW_REMOVE='1'; irm https://browser-workflow.web.app/install.ps1 | iex take everything out again # # Run again, it updates: with the newest version installed it says so and downloads nothing; with an # older one it shows both versions and asks before installing the new one (Enter is yes). With nobody # to ask it installs. $env:BW_UPDATE='yes' or 'no' answers ahead of the question. # # Install, and nothing else: # 1. looks for the AI apps. With none of them here it stops, and nothing is downloaded or changed # 2. ChatGPT app, Claude app, Antigravity: downloads the app from its GitHub releases into ~\.browser-workflow-app, # finds a Node.js to run it with (yours if it is 22 or newer; otherwise one is downloaded from # nodejs.org into ~\.browser-workflow-node, checked against the published checksum), and adds # Browser Workflow to their settings, after saving a copy of the file next to it: # ChatGPT desktop app ~\.codex\config.toml # Claude desktop app claude_desktop_config.json, in the folder it keeps its settings in # Antigravity ~\.gemini\config\mcp_config.json # The ChatGPT app and Antigravity each get a data folder of their own (~\.browser-workflow-chatgpt, # -antigravity), so they never share a link to an account. The Claude app uses ~\.browser-workflow, # as Claude Code does: they are one account. In the Claude app the address of the server is # added by the user (Settings, Connectors): that list is kept in their Claude account # The app is all an AI app gets: it has Browser Workflow's tools itself and asks the server for # an account of its own, so there is no address of the server to add, nothing to sign in to and # no computer to link. $env:BW_ALONE='0' before the command asks for the earlier way instead # (the address is added, then a sign-in and "Link this computer" in the AI app): for someone who # already has an account with a username # 3. Claude Code: installs the plugin browser-workflow (from the marketplace browser-workflow-bridge), # which brings both parts. Run again, it fetches the newest. The plugin was called # browser-workflow-bridge before: an install under that name is replaced # What is left is to quit the AI app, open it again and ask for a workflow. # # Remove takes out everything install and use put on this computer, for a clean start: the app's # files, the Node.js downloaded here, Browser Workflow's entries in those settings (also an address # added by hand), the data folders (the link to the account, the saved runs), the ChatGPT app's # sign-in to Browser Workflow (Windows Credential Manager), the copies of the settings files made # here, and the Claude Code plugin with its data. An account with no username is reachable only # through that sign-in: its workflows cannot be reached again afterwards. # # When something goes wrong it asks whether to send a report to Browser Workflow, and sends nothing # without a yes: what it printed, the version of Windows and which AI apps it found, with the user's # name taken out of folder names. An install that goes well sends nothing. BW_REPORT=yes or no # answers ahead of the question. # # It asks for no administrator rights and no password. It runs inside a block of its own and never # calls "exit", so the PowerShell window it was pasted in stays open and unchanged. # This file is plain ASCII on purpose: an older PowerShell may read a download in another encoding. & { $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' # the progress bar makes downloads many times slower try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } function Pick($value, $default) { if ($value) { $value } else { $default } } $server = Pick $env:BW_SERVER_URL 'https://browser-workflow-294054962898.us-central1.run.app' $release = Pick $env:BW_APP_URL 'https://github.com/chauvoluuhuong/browser-workflow-bridge/releases/latest/download/browser-workflow.mcpb' $nodeSite = Pick $env:BW_NODE_SITE 'https://nodejs.org/dist/latest-v22.x' $app = Join-Path $HOME '.browser-workflow-app' $ownNode = Join-Path $HOME '.browser-workflow-node' $codex = Pick $env:BW_CODEX_CONFIG (Join-Path (Join-Path $HOME '.codex') 'config.toml') $antigravity = Pick $env:BW_ANTIGRAVITY_CONFIG (Join-Path (Join-Path (Join-Path $HOME '.gemini') 'config') 'mcp_config.json') $plugin = 'browser-workflow@browser-workflow' # The plugin's name until 1.1.1: replaced on install, and taken out on remove. $oldPlugin = 'browser-workflow-bridge@browser-workflow' $remove = $env:BW_REMOVE -eq '1' # It is asked for once: the next command pasted in this window installs again. Remove-Item Env:BW_REMOVE -ErrorAction SilentlyContinue $ok = [string][char]0x2713 $bad = [string][char]0x2717 $hand = [char]::ConvertFromUtf32(0x1F449) $results = New-Object System.Collections.Generic.List[string] $global:LASTEXITCODE = 0 # What a report holds, if the user agrees to send one: the lines printed, and the step it stopped at. $version = '2026-10-14.2' $reportUrl = Pick $env:BW_REPORT_URL "$server/install-report" $printed = New-Object System.Collections.Generic.List[string] $step = 'starting' $problem = '' $isConsole = $false try { $isConsole = [Environment]::UserInteractive -and -not [Console]::IsOutputRedirected } catch {} $hasColor = -not $env:NO_COLOR -and -not $env:BW_KEEP_SIGNIN -and $isConsole function Say($text) { Write-Host $text; $printed.Add("$text") } function Fail($why) { throw "BW:$why" } # A program's output as text, and whether it ended well. Its error output never stops this script. function Run($exe, $arguments) { $before = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { $out = (& $exe @arguments 2>&1 | Out-String); return @{ Out = $out; Ok = ($LASTEXITCODE -eq 0) } } catch { return @{ Out = ''; Ok = $false } } finally { $ErrorActionPreference = $before } } function NewEnough($node) { try { if (-not $node -or -not (Test-Path $node)) { return $false } } catch { return $false } return (Run $node @('-p', "Number(process.versions.node.split('.')[0]) >= 22")).Out.Trim() -eq 'true' } function Download($url, $file) { Invoke-WebRequest -Uri $url -OutFile $file -UseBasicParsing } # Versions ("1.2.0"): the one a package.json or plugin.json names, and whether the first is older than the second. function VersionOf($file) { try { return "$((Get-Content $file -Raw | ConvertFrom-Json).version)" } catch { return '' } } function Older($a, $b) { $x = [regex]::Match("$a", '^\d+(\.\d+){0,3}').Value $y = [regex]::Match("$b", '^\d+(\.\d+){0,3}').Value if (-not $x -or -not $y) { return $false } if ($x -notmatch '\.') { $x += '.0' } if ($y -notmatch '\.') { $y += '.0' } return ([version]$x) -lt ([version]$y) } # The newest version of the app, from where its download is published; '' when it can't be told # (offline, or a download of one's own in BW_APP_URL). BW_LATEST_APP says it instead (tests). function LatestApp { if ($env:BW_LATEST_APP) { return $env:BW_LATEST_APP } if ($env:BW_APP_URL) { return '' } try { $r = [Net.HttpWebRequest]::Create('https://github.com/chauvoluuhuong/browser-workflow-bridge/releases/latest') $r.AllowAutoRedirect = $false; $r.Timeout = 10000; $r.UserAgent = 'browser-workflow-install' $res = $r.GetResponse(); $loc = $res.Headers['Location']; $res.Close() if ("$loc" -match '/tag/v?([^/]+)$') { return $Matches[1] } } catch { } return '' } # A newer version than the one installed: install it? Yes unless the answer is no; with nobody to ask, yes. function WantUpdate($what, $have, $newest) { $question = "${what}: version $newest is available (you have $have). Install it? [Y/n]" $answer = $env:BW_UPDATE if (-not $answer) { if (-not [Environment]::UserInteractive) { return $true } Write-Host '' try { $answer = Read-Host $question } catch { return $true } } $printed.Add("$question $(if ($answer) { $answer } else { 'yes' })") return ("$answer" -notmatch '^\s*n') } function Gone($path) { if (-not (Test-Path $path)) { return $false } Remove-Item $path -Recurse -Force -ErrorAction SilentlyContinue return -not (Test-Path $path) } # A copy of the app that an AI app started earlier is still running: it holds its folder, and it # writes its data folder back after it is deleted. function StopApp { try { Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($app) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } } catch { } } $tmp = Join-Path ([IO.Path]::GetTempPath()) ("browser-workflow-" + [Guid]::NewGuid().ToString('N')) try { New-Item -ItemType Directory -Path $tmp -Force | Out-Null # ---- which AI apps are here ----------------------------------------------------------------- $step = 'looking for the AI apps' $hasChatGPT = Test-Path (Split-Path $codex -Parent) if (-not $hasChatGPT -and $env:BW_CHATGPT_APPS -ne 'none') { # The ChatGPT app comes from the Microsoft Store: it is known by its package, not by a folder. try { if (Get-AppxPackage -ErrorAction SilentlyContinue 3>$null | Where-Object { $_.Name -match 'ChatGPT|OpenAI\.Codex' }) { $hasChatGPT = $true } } catch { } } $hasAntigravity = Test-Path $antigravity # The Claude desktop app keeps its settings in one of two folders: the second is where the one # installed as a Windows package really reads them. Both are written when both are there. $claudeApp = @() if ($env:BW_CLAUDE_APP_DIRS) { if ($env:BW_CLAUDE_APP_DIRS -ne 'none') { $claudeApp = @($env:BW_CLAUDE_APP_DIRS -split [IO.Path]::PathSeparator) } } else { if ($env:APPDATA) { $claudeApp += "$env:APPDATA\Claude" } if ($env:LOCALAPPDATA) { try { Get-ChildItem "$env:LOCALAPPDATA\Packages" -Directory -Filter '*Claude*' -ErrorAction SilentlyContinue | ForEach-Object { $claudeApp += (Join-Path $_.FullName 'LocalCache\Roaming\Claude') } } catch { } } } $claudeApp = @($claudeApp | Where-Object { try { $_ -and (Test-Path $_) } catch { $false } }) $hasClaudeApp = $claudeApp.Count -gt 0 $claude = $env:BW_CLAUDE if ($claude -eq 'none') { $claude = '' } elseif (-not $claude) { $found = Get-Command claude -ErrorAction SilentlyContinue | Select-Object -First 1; if ($found) { $claude = $found.Source } } $hasClaude = [bool]$claude $found = (@($(if ($hasChatGPT) { 'ChatGPT app' }), $(if ($hasClaudeApp) { 'Claude app' }), $(if ($hasAntigravity) { 'Antigravity' }), $(if ($hasClaude) { 'Claude Code' })) | Where-Object { $_ }) -join ', ' if (-not $remove -and -not ($hasChatGPT -or $hasClaudeApp -or $hasAntigravity -or $hasClaude)) { Fail 'no AI app that this command sets up was found on this computer (the ChatGPT desktop app, the Claude desktop app or Claude Code). Install one of them, open it once, and run this again. Nothing was downloaded or changed.' } # ---- a Node.js, 22 or newer: it runs the app, and it edits the settings files ----------------- $step = 'finding Node.js' $pathNode = '' $found = Get-Command node -ErrorAction SilentlyContinue | Select-Object -First 1 if ($found) { $pathNode = $found.Source } $node = '' foreach ($candidate in @($pathNode, (Join-Path $ownNode 'node.exe'), "$env:ProgramFiles\nodejs\node.exe")) { if (NewEnough $candidate) { $node = $candidate; break } } # None here: the ChatGPT app's own Node.js is inside a Store package whose folder changes with # every update, so one is downloaded for the app alone. It is not added to PATH. function GetNode { $arch = Pick $env:PROCESSOR_ARCHITEW6432 $env:PROCESSOR_ARCHITECTURE $kind = if ($arch -eq 'ARM64') { 'win-arm64' } elseif ($arch -eq 'AMD64') { 'win-x64' } else { '' } if (-not $kind) { return 'this computer runs a 32-bit Windows, which the app does not support' } try { $sums = (Invoke-WebRequest -Uri "$nodeSite/SHASUMS256.txt" -UseBasicParsing).Content if ($sums -is [byte[]]) { $sums = [Text.Encoding]::ASCII.GetString($sums) } $line = ($sums -split "`n") | Where-Object { $_ -match "^([0-9a-f]{64})\s+(node-v[0-9.]+-$kind\.zip)\s*$" } | Select-Object -First 1 if (-not $line) { return 'the list of Node.js downloads could not be read' } $null = $line -match "^([0-9a-f]{64})\s+(\S+)" $sum = $Matches[1]; $name = $Matches[2] $zip = Join-Path $tmp 'node.zip' Download "$nodeSite/$name" $zip } catch { return 'the download of Node.js failed. Check the internet connection and run this again' } if ((Get-FileHash $zip -Algorithm SHA256).Hash.ToLower() -ne $sum) { return 'the Node.js that was downloaded is not the one nodejs.org published' } try { Add-Type -AssemblyName System.IO.Compression.FileSystem $archive = [IO.Compression.ZipFile]::OpenRead($zip) try { $entry = $archive.Entries | Where-Object { $_.FullName -match '^[^/\\]+[/\\]node\.exe$' } | Select-Object -First 1 if (-not $entry) { return 'the Node.js download has no node.exe in it' } New-Item -ItemType Directory -Path $ownNode -Force | Out-Null [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $ownNode 'node.exe'), $true) } finally { $archive.Dispose() } } catch { return 'the Node.js download could not be opened' } if (-not (NewEnough (Join-Path $ownNode 'node.exe'))) { return 'the Node.js that was downloaded does not start on this computer' } return '' } $skipped = '' if (-not $node -and -not $remove -and ($hasChatGPT -or $hasClaudeApp -or $hasAntigravity)) { $step = 'downloading Node.js' Say 'Downloading Node.js, which runs the app (about 35 MB, once)...' $why = GetNode if (-not $why) { $node = Join-Path $ownNode 'node.exe' } elseif (-not $hasClaude) { Fail "$why. Nothing was changed." } else { $skipped = "The desktop apps (ChatGPT, Claude, Antigravity): skipped, $why"; $hasChatGPT = $false; $hasClaudeApp = $false; $hasAntigravity = $false } } # ---- the app's files (the desktop apps start them from this folder; Claude Code has its plugin) ---- function GetApp { $zip = Join-Path $tmp 'app.zip' try { Download $release $zip } catch { return 'the download failed. Check the internet connection and run this again' } $new = "$app.new" $null = Gone $new try { Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::ExtractToDirectory($zip, $new) } catch { $null = Gone $new; return 'the download could not be opened' } if (-not (Test-Path (Join-Path (Join-Path $new 'src') 'index.js'))) { $null = Gone $new; return 'the download is not the app (no src\index.js in it)' } $old = "$app.old" $null = Gone $old if (Test-Path $app) { try { Move-Item $app $old } catch { # A running copy holds the folder: it is stopped (the AI app starts the new one), and this is tried once more. StopApp; Start-Sleep -Seconds 1 try { Move-Item $app $old } catch { $null = Gone $new; return 'the app is in use. Quit the ChatGPT app completely and run this again' } } } Move-Item $new $app $null = Gone $old return '' } $getApp = $true if (-not $remove -and ($hasChatGPT -or $hasClaudeApp -or $hasAntigravity) -and (Test-Path (Join-Path (Join-Path $app 'src') 'index.js'))) { $step = 'looking for a newer version of the app' $have = VersionOf (Join-Path $app 'package.json') $newest = LatestApp if ($have -and $newest) { if (-not (Older $have $newest)) { $getApp = $false Say "The Browser Workflow app is up to date ($have)." } elseif (-not (WantUpdate 'The Browser Workflow app' $have $newest)) { $getApp = $false $results.Add("! The Browser Workflow app: kept version $have. Version $newest is there whenever you want it: run this command again") } } } if ($getApp -and -not $remove -and ($hasChatGPT -or $hasClaudeApp -or $hasAntigravity)) { $step = 'downloading the app' Say 'Downloading the Browser Workflow app...' $why = GetApp if ($why) { # Claude Code needs none of this: it still gets its plugin. if (-not $hasClaude) { Fail "$why. Nothing was changed." } $results.Add("$bad The desktop apps (ChatGPT, Claude, Antigravity): not installed, $why") $hasChatGPT = $false; $hasClaudeApp = $false; $hasAntigravity = $false } } if ($skipped) { $results.Add("! $skipped") } if ($remove) { StopApp; Start-Sleep -Seconds 1 } # ---- the Claude app has to be closed first ---------------------------------------------------- # It keeps its settings in memory and writes them back: what is changed in the file while it is # open is gone the next time it does (an entry added is lost, an entry removed comes back). So the # command waits here for it to be quit. BW_CLAUDE_APP_WAIT: how many seconds at most (for tests). # Claude Code is "claude.exe" too: the desktop app is told from it by where it is installed. function ClaudeAppOpen { if ($env:BW_CLAUDE_APP_OPEN) { return (Test-Path $env:BW_CLAUDE_APP_OPEN) } try { return [bool](Get-CimInstance Win32_Process -Filter "Name='claude.exe'" -ErrorAction Stop | Where-Object { $_.ExecutablePath -match 'AnthropicClaude|WindowsApps' }) } catch { return $false } } $claudeOpen = '' if ($claudeApp.Count -and ($remove -or $hasClaudeApp) -and (ClaudeAppOpen)) { $step = 'waiting for the Claude app to be quit' Say '' if ($hasColor) { Write-Host "$hand " -ForegroundColor Yellow -NoNewline Write-Host 'The Claude app is open: quit it completely now (right-click its icon next to the clock, then Quit) to continue.' $printed.Add('The Claude app is open: quit it completely now (right-click its icon next to the clock, then Quit) to continue.') } else { Say 'The Claude app is open: quit it completely now (right-click its icon next to the clock, then Quit) to continue.' } $limit = if ($env:BW_CLAUDE_APP_WAIT) { [int]$env:BW_CLAUDE_APP_WAIT } else { 300 } $waited = 0 while ((ClaudeAppOpen) -and $waited -lt $limit) { Start-Sleep -Seconds 2; $waited += 2 } if (ClaudeAppOpen) { $claudeOpen = 'Claude app: nothing was changed in it, because it is still open. Quit it completely and run this again' $claudeApp = @(); $hasClaudeApp = $false } else { Start-Sleep -Seconds 1 if ($hasColor) { Write-Host "$ok It is closed. Going on." -ForegroundColor Green $printed.Add('It is closed. Going on.') } else { Say 'It is closed. Going on.' } } } # ---- the desktop apps' settings, data and sign-in --------------------------------------------- $step = 'changing the settings of the AI apps' # The same program as in install.sh, with what differs on Windows: how a running app is found, # where the sign-in is kept, and paths that are written with doubled backslashes in a settings file. $settings = @' const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const { execFileSync } = require('node:child_process'); const { BW_NODE: node, BW_APP: app, BW_SERVER: server, BW_CODEX: codex, BW_ANTIGRAVITY: antigravity } = process.env; const remove = process.env.BW_REMOVE === '1'; // Alone: the app is the only thing the AI app gets. It has the tools itself and an account of its own, so no address of the // server is added, and there is nothing to sign in to or to link. BW_ALONE=0 asks for the earlier way: the address, a sign-in, a link. const alone = process.env.BW_ALONE !== '0'; const entry = path.join(app, 'src', 'index.js'); const home = os.homedir(); const ours = `${server}/mcp`; const OK = '\u2713'; const result = (mark, text) => fs.appendFileSync(process.env.BW_RESULTS, `${mark} ${text}\n`); const COPY = '.before-browser-workflow'; /** Our copies of a settings file: one is kept (what the file was before the last change); remove deletes them all. */ const copies = (file) => { try { return fs.readdirSync(path.dirname(file)).filter((n) => n.startsWith(path.basename(file) + COPY)).map((n) => path.join(path.dirname(file), n)); } catch { return []; } }; const save = (file, text) => { for (const c of copies(file)) fs.rmSync(c, { force: true }); if (fs.existsSync(file)) fs.copyFileSync(file, file + COPY); fs.mkdirSync(path.dirname(file), { recursive: true }); const tmp = `${file}.tmp-${process.pid}`; fs.writeFileSync(tmp, text); // Windows refuses to replace a file another program has open: it is then written in place. try { fs.renameSync(tmp, file); } catch { fs.writeFileSync(file, text); fs.rmSync(tmp, { force: true }); } }; const running = (names) => { try { const list = execFileSync('tasklist', ['/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true }).toLowerCase(); return names.some((n) => list.includes(`"${n.toLowerCase()}"`)); } catch { return false; } }; const gone = (dir) => { if (!fs.existsSync(dir)) return false; try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* still held: swept again at the end */ } return !fs.existsSync(dir); }; /** Whether a piece of a settings file names the app's folder: plain, or with its backslashes doubled as TOML and JSON write them. */ const namesApp = (text) => text.includes(app) || text.includes(JSON.stringify(app).slice(1, -1)); /** A TOML text without the tables `drop(name, body)` says yes to. A table runs from its "[header]" line to the next. */ function withoutTables(text, drop) { const lines = text.split('\n'), out = [], names = []; let skipping = false; for (let i = 0; i < lines.length; i++) { const header = /^\s*\[\[?([^\]]+)\]\]?\s*$/.exec(lines[i]); if (header) { let end = i + 1; while (end < lines.length && !/^\s*\[/.test(lines[end])) end++; skipping = drop(header[1].trim(), lines.slice(i, end).join('\n')); if (skipping) names.push(header[1].trim()); } if (!skipping) out.push(lines[i]); } return { text: out.join('\n').replace(/\n{3,}/g, '\n\n'), names }; } /** "mcp_servers.name" or "mcp_servers."name"" -> name; nothing for any other table, and for a table inside one. */ const serverName = (table) => /^mcp_servers\.("?)([^".]+)\1$/.exec(table)?.[2]; const inside = (table, names) => names.some((n) => table.startsWith(`mcp_servers.${n}.`) || table.startsWith(`mcp_servers."${n}".`)); /** The ChatGPT app's sign-in to Browser Workflow: in Windows Credential Manager, under "|...", or in a file. */ function forgetSignIn(names) { if (process.env.BW_KEEP_SIGNIN === '1') return 0; const service = 'Codex MCP Credentials'; const mine = (account) => names.some((n) => account.includes(`${n}|`)); let n = 0; try { // One line per saved sign-in holds "...target=": the word before it changes with the language of Windows. const list = execFileSync('cmdkey', ['/list'], { encoding: 'utf8', windowsHide: true }); for (const line of list.split(/\r?\n/)) { const target = /(\S*target=.*)$/.exec(line)?.[1]?.trim(); if (!target || !target.includes(service) || !mine(target.slice(target.indexOf('target=') + 7))) continue; try { execFileSync('cmdkey', [`/delete:${target}`], { stdio: 'ignore', windowsHide: true }); n++; } catch { /* left: said by the count */ } } } catch { /* no Credential Manager to reach */ } try { const file = path.join(path.dirname(codex), '.credentials.json'); if (fs.existsSync(file)) { const all = JSON.parse(fs.readFileSync(file, 'utf8')); const keys = Object.keys(all).filter((k) => mine(k) || JSON.stringify(all[k]).includes(ours)); if (keys.length) { for (const k of keys) delete all[k]; fs.writeFileSync(file, `${JSON.stringify(all, null, 2)}\n`); n += keys.length; } } } catch { /* not a file of sign-ins */ } return n; } // ---- ChatGPT desktop app: TOML tables ---- if (remove || process.env.BW_HAS_CHATGPT === '1') { const BEGIN = '# >>> Browser Workflow (added by its install command)'; const END = '# <<< Browser Workflow'; const before = (fs.existsSync(codex) ? fs.readFileSync(codex, 'utf8') : '').replace(/\r\n/g, '\n'); // The ChatGPT app rewrites this file and adds tables of its own between our two lines, so they only mark; tables are found by what they hold. const unmarked = before.split('\n').filter((l) => l.trim() !== BEGIN && l.trim() !== END).join('\n'); const open = running(['ChatGPT.exe', 'Codex.exe']); if (remove) { const names = []; const first = withoutTables(unmarked, (table, body) => { const name = serverName(table); if (name && (body.includes(ours) || namesApp(body))) { names.push(name); return true; } return false; }); const rest = withoutTables(first.text, (table) => inside(table, names)).text; const had = names.length > 0 || rest.trim() !== before.trim(); if (had) { save(codex, rest.replace(/\n*$/, '\n')); } for (const c of copies(codex)) fs.rmSync(c, { force: true }); const signIn = forgetSignIn([...new Set([...names, 'browser_workflow'])]); const data = gone(path.join(home, '.browser-workflow-chatgpt')); if (had || data || signIn) { result(OK, `ChatGPT app: removed${had ? ' from its settings' : ''}${data ? ', with its data folder' : ''}${signIn ? ', and its sign-in forgotten' : ''}${open ? '. It is open: quit it and open it again' : ''}`); } } else { // Ours to replace: the table that starts the app from our folder, and its env table. A "browser_workflow_app" that starts something else is someone's own. const own = /^\[mcp_servers\.browser_workflow_app\]/m.test(unmarked) && !withoutTables(unmarked, (table, body) => table === 'mcp_servers.browser_workflow_app' && namesApp(body)).names.length; if (own) result('!', 'ChatGPT app: it already has a "browser_workflow_app" entry of its own, left as it is'); else { let rest = withoutTables(unmarked, (table) => table === 'mcp_servers.browser_workflow_app' || table === 'mcp_servers.browser_workflow_app.env').text; const s = JSON.stringify; // Alone, an address of ours that is already there goes: the tools would show twice. if (alone) rest = withoutTables(rest, (table, body) => !!serverName(table) && body.includes(ours)).text; const hasServer = alone || rest.includes(ours); const lines = [ BEGIN, ...(hasServer ? [] : ['[mcp_servers.browser_workflow]', `url = ${s(ours)}`, '']), '[mcp_servers.browser_workflow_app]', `command = ${s(node)}`, `args = [${s(entry)}]`, '', '[mcp_servers.browser_workflow_app.env]', `BW_SERVER_URL = ${s(server)}`, `BW_DATA_DIR = ${s(path.join(home, '.browser-workflow-chatgpt'))}`, `BW_ALONE = ${s(alone ? '1' : '0')}`, END, ]; save(codex, `${rest.trim() ? `${rest.replace(/\n*$/, '\n')}\n` : ''}${lines.join('\n')}\n`); result(OK, `ChatGPT app: installed. ${open ? 'Quit it and open it again' : 'Open it'}. ${alone ? 'Then start a new chat: there is nothing to sign in to and nothing to link' : `${hasServer ? 'If it asks you to sign in to Browser Workflow' : 'Then sign in to Browser Workflow'}: Settings, Plugins, Browser Workflow, Authenticate, then Continue on the page that opens. Then start a new chat`}`); } } } // ---- Antigravity: a JSON file of servers ---- if (fs.existsSync(antigravity) && (remove || process.env.BW_HAS_ANTIGRAVITY === '1')) { const raw = fs.readFileSync(antigravity, 'utf8').replace(/^\uFEFF/, ''); let config; try { config = raw.trim() ? JSON.parse(raw) : {}; } catch { config = undefined; } if (!config) result('!', `Antigravity: ${antigravity} is not valid JSON, left as it is`); else { config.mcpServers ??= {}; const points = (v) => [v?.serverUrl, v?.url, v?.httpUrl].includes(ours); if (remove) { const names = Object.entries(config.mcpServers).filter(([, v]) => points(v) || (v?.args ?? []).some((a) => String(a).includes(app))).map(([k]) => k); for (const k of names) delete config.mcpServers[k]; if (names.length) save(antigravity, `${JSON.stringify(config, null, 2)}\n`); for (const c of copies(antigravity)) fs.rmSync(c, { force: true }); const data = gone(path.join(home, '.browser-workflow-antigravity')); if (names.length || data) result(OK, `Antigravity: removed${names.length ? ' from its settings' : ''}${data ? ', with its data folder' : ''}. Quit it and open it again`); } else { const had = 'browser-workflow-app' in config.mcpServers; if (alone) { for (const [k, v] of Object.entries(config.mcpServers)) if (points(v)) delete config.mcpServers[k]; } else if (!Object.values(config.mcpServers).some(points)) config.mcpServers['browser-workflow'] = { serverUrl: ours }; config.mcpServers['browser-workflow-app'] = { command: node, args: [entry], env: { BW_SERVER_URL: server, BW_DATA_DIR: path.join(home, '.browser-workflow-antigravity'), BW_ALONE: alone ? '1' : '0' } }; save(antigravity, `${JSON.stringify(config, null, 2)}\n`); result(OK, `Antigravity: ${had ? 'updated' : 'installed'}. Quit it and open it again, then start a new conversation`); } } } // ---- Claude desktop app: a JSON file of servers, in each folder it keeps its settings in ---- const claudeApp = (process.env.BW_CLAUDE_APP ?? '').split(path.delimiter).filter(Boolean); if (claudeApp.length && (remove || process.env.BW_HAS_CLAUDE_APP === '1')) { const NAME = 'Browser Workflow for Chrome'; // the name the extension has, so Claude sees the same tools either way let changed = 0, extension = false, theirs = false, replaced = false; // The extension's folder and settings go to ~/.browser-workflow-old-extension (nothing is deleted), and it comes off Claude's list. const putAwayExtension = (dir) => { const mine = (n) => /browser-workflow/i.test(n); const keep = path.join(home, '.browser-workflow-old-extension', String(Date.now())); const move = (from) => { if (!fs.existsSync(from)) return; fs.mkdirSync(keep, { recursive: true }); const to = path.join(keep, path.basename(from)); try { fs.renameSync(from, to); } catch { fs.cpSync(from, to, { recursive: true }); fs.rmSync(from, { recursive: true, force: true }); } }; const registry = path.join(dir, 'extensions-installations.json'); let reg; try { reg = JSON.parse(fs.readFileSync(registry, 'utf8').replace(/^\uFEFF/, '')); } catch { /* no list */ } const listed = reg?.extensions && typeof reg.extensions === 'object' ? Object.keys(reg.extensions).filter(mine) : []; let ids = []; try { ids = fs.readdirSync(path.join(dir, 'Claude Extensions')).filter(mine); } catch { /* no extensions */ } for (const id of ids) move(path.join(dir, 'Claude Extensions', id)); for (const id of new Set([...ids, ...listed])) move(path.join(dir, 'Claude Extensions Settings', `${id}.json`)); if (listed.length) { for (const id of listed) delete reg.extensions[id]; save(registry, `${JSON.stringify(reg, null, 2)}\n`); } }; for (const dir of claudeApp) { const file = path.join(dir, 'claude_desktop_config.json'); // Installed from the Download button it is an extension: the earlier way, as it was on the day of that file. It needs the // connector, and this command can't update it, so installing puts it away and adds the newest app instead (with both, every // tool would show twice). Claude is closed by now, so it does not write its list of extensions back. The data folder stays, // so the account the extension was linked to stays too. let asExtension = false; try { asExtension = fs.readdirSync(path.join(dir, 'Claude Extensions')).some((n) => /browser-workflow/i.test(n)); } catch { /* no extensions */ } if (asExtension && !remove) { putAwayExtension(dir); replaced = true; asExtension = false; } if (asExtension) extension = true; let config = {}; if (fs.existsSync(file)) { const raw = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''); try { config = raw.trim() ? JSON.parse(raw) : {}; } catch { config = undefined; } } if (!config || typeof config !== 'object' || Array.isArray(config)) { result('!', `Claude app: ${file} is not valid JSON, left as it is`); continue; } const servers = config.mcpServers && typeof config.mcpServers === 'object' ? config.mcpServers : {}; const mine = Object.entries(servers).filter(([, v]) => (v?.args ?? []).some((a) => String(a).includes(app))).map(([k]) => k); for (const k of mine) delete servers[k]; if (remove || asExtension) { if (mine.length) { config.mcpServers = servers; save(file, `${JSON.stringify(config, null, 2)}\n`); changed++; } if (remove) for (const c of copies(file)) fs.rmSync(c, { force: true }); } else if (NAME in servers) theirs = true; // an entry with our name that starts something else is someone's own else { config.mcpServers = { ...servers, [NAME]: { command: node, args: [entry], env: { BW_SERVER_URL: server, BW_ALONE: alone ? '1' : '0' } } }; save(file, `${JSON.stringify(config, null, 2)}\n`); changed++; } } // It is closed: the command waited for that before it came here. const again = 'Open it'; const byHand = 'Settings, Extensions, Advanced settings, Install Extension'; if (remove) { // ~\.browser-workflow is also the extension's and Claude Code's: it stays while the extension is there (Claude Code's part is below). const data = !extension && gone(path.join(home, '.browser-workflow')); if (changed || data) result(OK, `Claude app: removed${changed ? ' from its settings' : ''}${data ? ', with its data folder' : ''}`); if (extension) result('!', 'Claude app: Browser Workflow is also in it as an extension. Remove it there: Settings, Extensions, Browser Workflow, Uninstall'); } else if (extension) result(OK, `Claude app: it already has Browser Workflow, as an extension. To get the newest, download the file again and install it in Claude: ${byHand}`); else if (theirs) result('!', `Claude app: it already has a "${NAME}" entry of its own, left as it is`); else if (changed) result(OK, `Claude app: ${replaced ? 'the Browser Workflow extension was replaced by the newest app (the old one is in ~\.browser-workflow-old-extension)' : 'installed'}. ${again}, then start a new chat. ${alone ? 'There is nothing to sign in to and nothing to link. If Browser Workflow is already in Claude under Settings, Connectors, remove it there: the app has everything now' : `If Browser Workflow's address is not in Claude yet, add it first: Settings, Connectors, Add custom connector, ${ours}`}`); } if (remove && gone(app)) result(OK, 'The app\'s files: removed'); '@ if ($node -and ($remove -or $hasChatGPT -or $hasClaudeApp -or $hasAntigravity)) { $program = Join-Path $tmp 'settings.cjs' $resultsFile = Join-Path $tmp 'results.txt' $utf8 = New-Object System.Text.UTF8Encoding($false) [IO.File]::WriteAllText($program, $settings, $utf8) [IO.File]::WriteAllText($resultsFile, '', $utf8) $given = @{ BW_NODE = $node; BW_APP = $app; BW_SERVER = $server; BW_CODEX = $codex; BW_ANTIGRAVITY = $antigravity; BW_RESULTS = $resultsFile BW_REMOVE = $(if ($remove) { '1' } else { '0' }); BW_HAS_CHATGPT = $(if ($hasChatGPT) { '1' } else { '0' }); BW_HAS_ANTIGRAVITY = $(if ($hasAntigravity) { '1' } else { '0' }) BW_ALONE = $(if ($env:BW_ALONE -eq '0') { '0' } else { '1' }) BW_CLAUDE_APP = ($claudeApp -join [IO.Path]::PathSeparator); BW_HAS_CLAUDE_APP = $(if ($hasClaudeApp) { '1' } else { '0' }) } foreach ($k in $given.Keys) { Set-Item "Env:$k" $given[$k] } try { $ran = Run $node @($program) foreach ($line in [IO.File]::ReadAllLines($resultsFile, $utf8)) { if ($line) { $results.Add($line) } } if (-not $ran.Ok) { $results.Add("$bad The settings could not be changed: " + (($ran.Out.Trim() -split "`n") | Select-Object -Last 1)) } } finally { foreach ($k in $given.Keys) { Remove-Item "Env:$k" -ErrorAction SilentlyContinue } } } elseif ($remove) { # No Node.js to edit the settings files with: what is ours alone still goes. foreach ($d in @($app, (Join-Path $HOME '.browser-workflow-chatgpt'), (Join-Path $HOME '.browser-workflow-antigravity'))) { if (Gone $d) { $results.Add("$ok Removed $d") } } $left = $false foreach ($f in @($codex, $antigravity)) { if ((Test-Path $f) -and (Select-String -Path $f -Pattern 'browser-workflow' -SimpleMatch -Quiet)) { $left = $true } } if ($left) { $results.Add('! No Node.js 22 or newer was found to edit the settings with: remove Browser Workflow in the AI app itself (ChatGPT: Settings, Plugins)') } } if ($claudeOpen) { $results.Add("! $claudeOpen") } # ---- Claude Code: the plugin brings the server's address and the app --------------------------- $step = 'setting up Claude Code' if ($hasClaude) { $listed = (Run $claude @('plugin', 'list')).Out $hasNew = $listed -match (' ' + [regex]::Escape($plugin)) $hasOld = $listed -match (' ' + [regex]::Escape($oldPlugin)) if ($remove) { if ($hasNew -or $hasOld) { foreach ($p in @($plugin, $oldPlugin)) { $null = Run $claude @('plugin', 'uninstall', $p) } $null = Run $claude @('plugin', 'marketplace', 'remove', 'browser-workflow') foreach ($f in @('browser-workflow-bridge*', 'browser-workflow-browser-workflow*')) { Get-ChildItem (Join-Path $HOME '.claude\plugins\data') -Filter $f -ErrorAction SilentlyContinue | ForEach-Object { $null = Gone $_.FullName } } # ~\.browser-workflow is also the Claude desktop app's: it stays when that app has Browser Workflow installed. $desktop = $false if ($env:APPDATA) { $desktop = [bool](Get-ChildItem (Join-Path $env:APPDATA 'Claude\Claude Extensions') -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'browser-workflow' }) } if (-not $desktop) { $null = Gone (Join-Path $HOME '.browser-workflow'); $results.Add("$ok Claude Code: the plugin and its data removed") } else { $results.Add("$ok Claude Code: the plugin removed. The folder ~\.browser-workflow stays: the Claude desktop app uses it too") } } } elseif (-not (NewEnough $pathNode)) { $results.Add('! Claude Code: skipped. Its plugin needs Node.js 22 or newer on this computer: install it from https://nodejs.org and run this again') } else { Say 'Adding Browser Workflow to Claude Code...' $null = Run $claude @('plugin', 'marketplace', 'add', 'chauvoluuhuong/browser-workflow-bridge') # Added before, "add" succeeds and leaves Claude Code's copy of the plugin list as it was: "update" fetches the newest. $null = Run $claude @('plugin', 'marketplace', 'update', 'browser-workflow') $manual = "In Claude Code, type: /plugin marketplace add chauvoluuhuong/browser-workflow-bridge then: /plugin marketplace update browser-workflow then: /plugin install $plugin" # The version installed (under the plugin's line in the list), and the newest, in Claude Code's copy of the marketplace. $have = '' if ($listed -match ('(?m)>\s*' + [regex]::Escape($plugin) + '\s*\r?\n\s*Version:\s*(\S+)')) { $have = $Matches[1] } $newest = VersionOf (Join-Path $HOME '.claude\plugins\marketplaces\browser-workflow\.claude-plugin\plugin.json') if ($hasNew -and $have -and $newest -and -not (Older $have $newest)) { $results.Add("$ok Claude Code: up to date (version $have)") } elseif ($hasNew -and $have -and $newest -and -not (WantUpdate 'Browser Workflow in Claude Code' $have $newest)) { $results.Add("! Claude Code: kept version $have. Version $newest is there whenever you want it: run this command again") } elseif ($hasNew) { if ((Run $claude @('plugin', 'update', $plugin)).Ok) { $results.Add("$ok Claude Code: already installed, now the newest. Start a new session") } else { $results.Add("$bad Claude Code: the plugin could not be updated. $manual") } } elseif ((Run $claude @('plugin', 'install', $plugin)).Ok) { $results.Add("$ok Claude Code: installed. Start a new session and ask for a workflow. If it asks you to sign in: type /mcp, choose browser-workflow, then Authenticate") } else { $results.Add("$bad Claude Code: the plugin could not be installed. $manual") } # The plugin under its old name goes once the new one is in: both at once would start the app twice. if ($hasOld -and ((Run $claude @('plugin', 'list')).Out -match (' ' + [regex]::Escape($plugin)))) { $null = Run $claude @('plugin', 'uninstall', $oldPlugin) Get-ChildItem (Join-Path $HOME '.claude\plugins\data') -Filter 'browser-workflow-bridge*' -ErrorAction SilentlyContinue | ForEach-Object { $null = Gone $_.FullName } } } } if ($remove) { StopApp; Start-Sleep -Seconds 1 foreach ($d in @($app, (Join-Path $HOME '.browser-workflow-chatgpt'), (Join-Path $HOME '.browser-workflow-antigravity'))) { $null = Gone $d } # With the Claude app left as it is, the Node.js stays: running this again needs it to take the app out of Claude. if (-not $claudeOpen -and (Gone $ownNode)) { $results.Add("$ok The Node.js downloaded for the app: removed") } } # ---- what happened ---------------------------------------------------------------------------- $step = 'finishing' Say '' $done = [bool]($results | Where-Object { $_.StartsWith($ok) }) if ($results.Count -eq 0) { if ($remove) { Say 'Nothing of Browser Workflow was found on this computer.' } else { Say 'Nothing was installed.' } } else { foreach ($line in $results) { if ($hasColor) { if ($line.StartsWith($ok)) { $rest = $line.Substring($ok.Length + 1) $status = ($rest -split '\. ')[0] Write-Host "$ok " -ForegroundColor Green -NoNewline Write-Host $status } elseif ($line.StartsWith($bad)) { Write-Host "$bad " -ForegroundColor Red -NoNewline Write-Host ($line.Substring($bad.Length + 1)) } elseif ($line.StartsWith('!')) { Write-Host '! ' -ForegroundColor Yellow -NoNewline Write-Host ($line.Substring(2)) } else { Write-Host $line } } else { Write-Host $line } $printed.Add("$line") } if ($remove) { Say '' if ($claudeOpen) { if ($hasColor) { Write-Host "$hand " -ForegroundColor Yellow -NoNewline Write-Host 'Browser Workflow is off this computer, except in the Claude app: quit it completely and run the remove command again.' $printed.Add('Browser Workflow is off this computer, except in the Claude app: quit it completely and run the remove command again.') } else { Say 'Browser Workflow is off this computer, except in the Claude app: quit it completely and run the remove command again.' } } else { if ($hasColor) { Write-Host "$hand " -ForegroundColor Yellow -NoNewline Write-Host 'Browser Workflow has been removed. Restart your AI app (ChatGPT / Claude) to finish.' $printed.Add('Browser Workflow has been removed. Restart your AI app (ChatGPT / Claude) to finish.') } else { Say 'Browser Workflow is off this computer. To start again, run the install command.' } } } elseif ($done) { Say '' if ($hasColor) { Write-Host "$hand " -ForegroundColor Yellow -NoNewline Write-Host 'Restart your AI app (ChatGPT / Claude), then try asking:' Write-Host ' "Build a workflow to open google.com and search for iPhone"' $printed.Add('Restart your AI app (ChatGPT / Claude), then try asking: "Build a workflow to open google.com and search for iPhone"') } else { Say 'Restart your AI app (ChatGPT / Claude), then try asking:' Say ' "Build a workflow to open google.com and search for iPhone"' } } } $failed = @($results | Where-Object { $_.StartsWith($bad) }) if ($failed.Count -or (-not $remove -and -not $done)) { $global:LASTEXITCODE = 1 $problem = if ($failed.Count) { $failed[0] } else { 'nothing was installed' } } } catch { $global:LASTEXITCODE = 1 $why = "$($_.Exception.Message)" if ($why.StartsWith('BW:')) { $problem = $why.Substring(3); $text = "Browser Workflow was not installed: $problem" } else { $problem = "something unexpected happened: $why (line $($_.InvocationInfo.ScriptLineNumber))" $text = "Browser Workflow was not installed: something unexpected happened ($why). Nothing else was changed. Run this again, or report it: https://github.com/chauvoluuhuong/browser-workflow-bridge/issues" } Write-Host '' Write-Host $text -ForegroundColor Red $printed.Add($text) } finally { Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue } # ---- something went wrong: a report, only if the user says yes ---------------------------------- if ($problem) { try { $answer = $env:BW_REPORT if (-not $answer) { # Where there is nobody to ask, nothing is sent. if (-not [Environment]::UserInteractive) { return } Write-Host '' if ($hasColor) { Write-Host "$hand " -ForegroundColor Yellow -NoNewline try { $answer = Read-Host 'Would you like to send a report to Browser Workflow? [y/N]' } catch { return } } else { try { $answer = Read-Host 'Would you like to send a report to Browser Workflow? [y/N]' } catch { return } } } if ("$answer" -notmatch '^\s*y') { return } # A folder name is the one place the user's name shows: C:\Users\ becomes C:\Users\~. $clean = { param($t) [regex]::Replace("$t".Replace($HOME, '~'), '(?i)(:\\+Users\\+)[^\\\s"'']+', '${1}~') } $system = '' try { $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop; $system = "$($os.Caption) $($os.Version) $($env:PROCESSOR_ARCHITECTURE)" } catch { $system = [Environment]::OSVersion.VersionString } $report = @{ installer = 'windows'; version = $version; system = "$system, PowerShell $($PSVersionTable.PSVersion)" found = "$(if ($found) { $found } else { 'none' })$(if ($remove) { ' (removing)' })"; step = $step error = (& $clean $problem); log = (& $clean ($printed -join "`n")) } | ConvertTo-Json -Compress $sent = Invoke-RestMethod -Uri $reportUrl -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($report)) -TimeoutSec 10 if ($sent.id) { Write-Host "Sent, thank you. If you write to us about this, mention report $($sent.id)." } else { Write-Host 'The report could not be sent.' } } catch { Write-Host 'The report could not be sent.' } } }