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
26 changes: 25 additions & 1 deletion browser_extension/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,34 @@ async function hello() {
// The browser shows that switch only to an extension that could want it:
// activeTab, in the manifest for that alone, makes this one such.
const fileAccess = await chrome.extension.isAllowedFileSchemeAccess().catch(() => null);
// The engine, which tells a browser that borrows another's name (Cent
// Browser says Google Chrome): its version is what differs.
const version = await chromiumVersion();
if (!connected) return;
send({
type: 'hello',
protocol: BRIDGE,
capabilities: CAPABILITIES,
browser: browserName(),
engine: version ? `Chromium ${version}` : 'Chromium',
version: chrome.runtime.getManifest().version,
fileAccess,
});
}

// The Chromium under the browser: the one in its user agent's full list,
// where it says, else its user agent's Chrome/…
async function chromiumVersion() {
try {
const { fullVersionList } = await navigator.userAgentData.getHighEntropyValues(['fullVersionList']);
const chromium = fullVersionList?.find((b) => b.brand === 'Chromium');
if (chromium?.version) return chromium.version;
} catch (error) {
// Not there, or not let: the user agent says.
}
return /(?:Chrome|Chromium)\/([\d.]+)/.exec(navigator.userAgent)?.[1] ?? null;
}

// The toolbar button's badge and title: recording, connected, or not.
function showState() {
chrome.action.setBadgeBackgroundColor({ color: '#c0392b' });
Expand Down Expand Up @@ -371,7 +388,14 @@ chrome.tabs.onCreated.addListener(async (tab) => {
// --- The tabs shared: the "BaoCode" group's, in any window.

async function groups() {
return chrome.tabGroups.query({ title: GROUP });
try {
return await chrome.tabGroups.query({ title: GROUP });
} catch (error) {
// No window open: a browser left running in the background. It has no
// group, and a window is made with the first tab asked for (createTab).
if (/No current window/i.test(String(error?.message))) return [];
throw error;
}
}

async function sharedTabs() {
Expand Down
2 changes: 1 addition & 1 deletion browser_extension/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_name__",
"version": "0.2.0",
"version": "0.2.1",
"description": "__MSG_description__",
"default_locale": "en",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw/z7XPTL8VYzRrKO5N7N14kL3MuvHD528smBkU6Odvd3L4/BHTaNmtwhOhEEE1q6DamfoekiwcgQWM2aoH32QAi1La7ZM7MXpFsQYkFQh8G7rbzrX5eronOSiPEeoeiXUNyNgnk4jxSAr0HKc7oiFzKtw7lAEXf83A0dFSbhNrLwRZIAqqA9s1qHNeglbG2j7UBf4C92NpdQXqJzs00MXb2gMh7IWIQwigL61nQtS2ZJKkWMTJJpE6TPiqGYiMEpBSjazUOcNzu28/X03iuPUVNgEzWbKe1DvqIOr7keI2QCnOlC2PkWIx2oNQnBZWgQsvffpdakemj7YC/MTIoyywIDAQAB",
Expand Down
116 changes: 115 additions & 1 deletion lib/browser/browser_bridge.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,39 @@ class BrowserBridge extends ChangeNotifier {
/// user's browsers, as Settings → Browser turns it on or off. Unset: on.
static const settingKey = 'browser.enabled';

/// settings.json's `browser.preferred`: the browser the agents use, by
/// the path of its executable ([BrowserConnection.executable]). Unset:
/// the last connected.
static const preferredKey = 'browser.preferred';

/// Sets [enabled] from [read] now and whenever [changes] notifies.
void follow(Listenable changes, Object? Function() read) {
void update() => enabled = read() != false;
update();
changes.addListener(update);
}

/// Sets [preferred] from [read] now and whenever [changes] notifies.
void followPreferred(Listenable changes, Object? Function() read) {
void update() => preferred = switch (read()) {
final String path when path.trim().isNotEmpty => path.trim(),
_ => null,
};
update();
changes.addListener(update);
}

/// The path of the browser chosen in Settings → Browser; null for none
/// chosen, where the last connected is used.
String? get preferred => _preferred;
String? _preferred;

set preferred(String? value) {
if (_preferred == value) return;
_preferred = value;
notifyListeners();
}

/// Where the host finds the app: the same folder for both, the user's
/// temporary one ([socketFolder] in a test).
static String get socketPath => p.join(_folder, 'baocode-browser.sock');
Expand Down Expand Up @@ -154,6 +180,38 @@ class BrowserBridge extends ChangeNotifier {
if (connection.browser != null && connection.compatible) connection,
];

/// The browser the agents use: [preferred]'s while it is connected, the
/// last connected otherwise (none chosen, or the one chosen closed);
/// null when none is.
BrowserConnection? get active {
final browsers = this.browsers;
if (browsers.isEmpty) return null;
if (chosen case final chosen?) return chosen;
return browsers.first;
}

/// The browser chosen in Settings → Browser ([preferred]), while it is
/// connected.
BrowserConnection? get chosen {
final path = _preferred;
if (path == null) return null;
for (final browser in browsers) {
if (_samePath(browser.executable, path)) return browser;
}
return null;
}

/// Whether [browser] is the one the agents use now.
bool isActive(BrowserConnection browser) => identical(active, browser);

/// Whether [a] and [b] name the same executable: the same path, whatever
/// the slashes or the case.
static bool _samePath(String? a, String? b) {
if (a == null || b == null || a.isEmpty || b.isEmpty) return false;
String plain(String path) => path.replaceAll('\\', '/').toLowerCase();
return plain(a) == plain(b);
}

/// The browsers whose extension is connected but speaks another
/// [protocol]: one of them, or BaoCode, has to be updated.
List<BrowserConnection> get mismatched => [
Expand Down Expand Up @@ -531,6 +589,54 @@ class BrowserConnection {
/// (its "Allow access to file URLs"): null for one from before it said.
bool? fileAccess;

/// The browser's executable, as its host said: the folder tells a browser
/// that borrows another's name (Cent Browser's extension says Google
/// Chrome). Null for one from before the host said.
String? executable;

/// The browser's engine and its version, as the extension said:
/// `Chromium 116.0.5845.188` under the browsers here.
String? engine;

/// The browser's name: its executable's where that says one (Cent
/// Browser's chrome.exe is not Chrome's), the extension's brand
/// otherwise.
String get displayName => _nameOf(executable) ?? browser ?? 'Browser';

/// The browsers whose executable says their name, which the extension
/// may not (Cent Browser's, Google Chrome's): a part of the path, and
/// the name.
static const _names = [
('centbrowser', 'Cent Browser'),
('brave', 'Brave'),
('vivaldi', 'Vivaldi'),
('microsoft edge', 'Microsoft Edge'),
('microsoft/edge', 'Microsoft Edge'),
('msedge', 'Microsoft Edge'),
('google chrome', 'Google Chrome'),
('google/chrome', 'Google Chrome'),
('google-chrome', 'Google Chrome'),
('chromium', 'Chromium'),
('arc.app', 'Arc'),
('opera', 'Opera'),
('qqbrowser', 'QQ Browser'),
('360se', '360 Browser'),
('360chrome', '360 Browser'),
('sogou', 'Sogou Explorer'),
('yandex', 'Yandex'),
('whale', 'Naver Whale'),
('ucbrowser', 'UC Browser'),
];

static String? _nameOf(String? path) {
if (path == null || path.isEmpty) return null;
final lower = path.replaceAll('\\', '/').toLowerCase();
for (final (part, name) in _names) {
if (lower.contains(part)) return name;
}
return null;
}

/// What to tell when [fileAccess] is false: only the user can turn it on.
static const fileAccessHelp =
'The browser does not let BaoCode\'s extension reach local files. Ask '
Expand Down Expand Up @@ -681,16 +787,24 @@ class BrowserConnection {
}
switch (message['type']) {
case 'hello' when message['origin'] != null:
// The host's: who started it.
// The host's: who started it, and the browser it runs in.
origin = message['origin'] as String?;
final allowed = BrowserBridge.extensionIds.any(
(id) => origin == 'chrome-extension://$id/',
);
if (!allowed) _close();
if (message['path'] case final String path
when path.trim().isNotEmpty) {
executable = path.trim();
}
case 'hello':
browser = message['browser'] as String? ?? 'Browser';
version = message['version'] as String?;
fileAccess = message['fileAccess'] as bool?;
if (message['engine'] case final String engine
when engine.trim().isNotEmpty) {
this.engine = engine.trim();
}
protocol = (message['protocol'] as num?)?.toInt() ?? 1;
capabilities = {
for (final capability in message['capabilities'] as List? ?? [])
Expand Down
6 changes: 3 additions & 3 deletions lib/browser/browser_history.dart
Original file line number Diff line number Diff line change
Expand Up @@ -662,11 +662,11 @@ final _historyTool = ClaudeSdkTool(
}
return true;
});
final browsers = BrowserBridge.instance.browsers;
final browser = BrowserBridge.instance.active;
BrowserTab? live(Object? tab) {
final id = int.tryParse('$tab');
if (id == null || browsers.isEmpty) return null;
final open = BrowserTab(browsers.first, id);
if (id == null || browser == null) return null;
final open = BrowserTab(browser, id);
return BrowserRecords.instance.watching(open) ? open : null;
}

Expand Down
21 changes: 11 additions & 10 deletions lib/browser/browser_tools.dart
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,10 @@ abstract final class BrowserTools {
}

static Future<void> _watch(int tabId) async {
final browsers = BrowserBridge.instance.browsers;
if (browsers.isEmpty) return;
final browser = BrowserBridge.instance.active;
if (browser == null) return;
try {
await BrowserRecords.instance.watch(BrowserTab(browsers.first, tabId));
await BrowserRecords.instance.watch(BrowserTab(browser, tabId));
} on Object {
// Not shared, or gone: the tool says so.
}
Expand Down Expand Up @@ -219,11 +219,11 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea
final browser = _browser();
final tabs = await browser.request('tabs.list') as List? ?? const [];
if (tabs.isEmpty) {
return 'No tab is shared with BaoCode in ${browser.browser}. '
return 'No tab is shared with BaoCode in ${browser.displayName}. '
'Open one with browser_open.';
}
return [
'${browser.browser}:',
'${browser.displayName}:',
for (final tab in tabs.cast<Map>()) _describeTab(tab),
].join('\n');
},
Expand Down Expand Up @@ -337,11 +337,12 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea
),
];

/// The browser to use: the last connected.
/// The browser to use: the one chosen in Settings → Browser, or the last
/// connected when none is (see [BrowserBridge.active]).
static BrowserConnection _browser() {
final bridge = BrowserBridge.instance;
final browsers = bridge.browsers;
if (browsers.isNotEmpty) return browsers.first;
final browser = bridge.active;
if (browser != null) return browser;
if (bridge.otherApp) {
throw StateError(
'Another BaoCode is connected to the browser: quit it first.',
Expand All @@ -350,10 +351,10 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea
if (bridge.mismatched case [final browser, ...]) {
throw StateError(
browser.protocol < BrowserBridge.protocol
? "BaoCode's extension in ${browser.browser} is too old for "
? "BaoCode's extension in ${browser.displayName} is too old for "
'this BaoCode: the user needs to update it (Settings → '
'Browser says how).'
: "BaoCode's extension in ${browser.browser} is newer than "
: "BaoCode's extension in ${browser.displayName} is newer than "
'this BaoCode: the user needs to update BaoCode.',
);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/browser_welcome.dart
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class _BrowserWelcomeState extends State<BrowserWelcome>
Widget _build(BuildContext context) {
final l10n = context.l10n;
final bridge = widget.bridge;
final connected = bridge.browsers.firstOrNull;
final connected = bridge.active;
final lines = [
(
const Icon(Codicons.lock, size: 15),
Expand All @@ -122,7 +122,7 @@ class _BrowserWelcomeState extends State<BrowserWelcome>
final String title;
final String text;
if (connected != null) {
title = l10n.browserWelcomeConnected(connected.browser ?? '');
title = l10n.browserWelcomeConnected(connected.displayName);
text = l10n.browserWelcomeTry;
} else if (!bridge.enabled) {
title = l10n.browserWelcomeInstallTitle;
Expand Down
6 changes: 6 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -7367,6 +7367,7 @@
"browserSettingsEnabled": "Let Agents Use the Browser",
"browserSettingsEnabledDescription": "When off, agents have no browser tools and the extension disconnects.",
"browserSettingsStatus": "Status",
"browserSettingsStatusDescription": "Agents use the browser marked In Use; choose another to switch.",
"browserSettingsNotInstalled": "No browser has connected yet",
"browserSettingsNotInstalledDescription": "Install the extension either way below, then open the browser: it connects automatically.",
"browserSettingsNotRunning": "No browser connected",
Expand All @@ -7379,6 +7380,11 @@
"@browserSettingsIncompatible": {"description": "A browser connected whose extension BaoCode cannot use: one too old, or newer than the app.", "placeholders": {"browser": {"type": "String"}}},
"browserSettingsExtensionVersion": "Extension {version}",
"@browserSettingsExtensionVersion": {"description": "The version of BaoCode's extension in a connected browser.", "placeholders": {"version": {"type": "String"}}},
"browserSettingsUse": "Use This Browser",
"browserSettingsUsing": "In Use",
"browserSettingsChosenMissing": "The browser chosen is not connected",
"browserSettingsChosenMissingDescription": "{path}: agents use {browser} until it connects again.",
"@browserSettingsChosenMissingDescription": {"description": "Under browserSettingsChosenMissing: the chosen browser's executable, and the connected one used meanwhile.", "placeholders": {"path": {"type": "String"}, "browser": {"type": "String"}}},
"browserSettingsExtensionOld": "The extension is out of date. From the store, it updates automatically, or click Update in chrome://extensions; installed manually, download the zip again, replace the folder's contents and click reload.",
"browserSettingsAppOld": "The extension is newer than this BaoCode. Update BaoCode.",
"browserSettingsNoFileAccess": "File access is off",
Expand Down
30 changes: 30 additions & 0 deletions lib/l10n/app_localizations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16747,6 +16747,12 @@ abstract class AppLocalizations {
/// **'Status'**
String get browserSettingsStatus;

/// No description provided for @browserSettingsStatusDescription.
///
/// In en, this message translates to:
/// **'Agents use the browser marked In Use; choose another to switch.'**
String get browserSettingsStatusDescription;

/// No description provided for @browserSettingsNotInstalled.
///
/// In en, this message translates to:
Expand Down Expand Up @@ -16801,6 +16807,30 @@ abstract class AppLocalizations {
/// **'Extension {version}'**
String browserSettingsExtensionVersion(String version);

/// No description provided for @browserSettingsUse.
///
/// In en, this message translates to:
/// **'Use This Browser'**
String get browserSettingsUse;

/// No description provided for @browserSettingsUsing.
///
/// In en, this message translates to:
/// **'In Use'**
String get browserSettingsUsing;

/// No description provided for @browserSettingsChosenMissing.
///
/// In en, this message translates to:
/// **'The browser chosen is not connected'**
String get browserSettingsChosenMissing;

/// Under browserSettingsChosenMissing: the chosen browser's executable, and the connected one used meanwhile.
///
/// In en, this message translates to:
/// **'{path}: agents use {browser} until it connects again.'**
String browserSettingsChosenMissingDescription(String path, String browser);

/// No description provided for @browserSettingsExtensionOld.
///
/// In en, this message translates to:
Expand Down
Loading
Loading