diff --git a/Sources/BrowserBridge/BrowserProfileDiscovery.swift b/Sources/BrowserBridge/BrowserProfileDiscovery.swift index 865c587..88f3ef3 100644 --- a/Sources/BrowserBridge/BrowserProfileDiscovery.swift +++ b/Sources/BrowserBridge/BrowserProfileDiscovery.swift @@ -10,6 +10,7 @@ enum BrowserProfileDiscovery { struct Identity: Sendable, Equatable { let browser: String let profile: String + let directory: String } private struct LocalState: Decodable { @@ -74,39 +75,72 @@ enum BrowserProfileDiscovery { let matched = knownBrowsers.first { parentPath.contains($0.matchToken) } let browserName = matched?.displayName ?? "Chrome" guard let rel = matched?.userDataRelativePath else { - return Identity(browser: browserName, profile: "Default") + return Identity(browser: browserName, profile: "Default", directory: "Default") } let userData = home.appending(path: rel, directoryHint: .isDirectory) - let profileDir = detectProfileDirectory(userData: userData) - let label = resolveProfileLabel(userData: userData, directory: profileDir) - return Identity(browser: browserName, profile: label) + let profileDir = + detectProfileDirectory(userData: userData) ?? detectExtensionProfileDirectory(userData: userData) + let resolved = resolveProfile(userData: userData, directory: profileDir) + return Identity(browser: browserName, profile: resolved.label, directory: resolved.directory) } /// Reads Chrome's `Local State` to turn a directory name like `Profile 1` into its human name. - static func resolveProfileLabel(userData: URL, directory: String?) -> String { + static func resolveProfile(userData: URL, directory: String?) -> (label: String, directory: String) { let localStateURL = userData.appending(path: "Local State") + let fallbackDir = directory ?? "Default" let decoded: LocalState do { let data = try Data(contentsOf: localStateURL) decoded = try JSONDecoder().decode(LocalState.self, from: data) } catch { - return directory ?? "Default" + return (fallbackDir, fallbackDir) } guard let cache = decoded.profile?.infoCache else { - return directory ?? "Default" + return (fallbackDir, fallbackDir) } let key = directory ?? decoded.profile?.lastUsed ?? "Default" - guard let entry = cache[key] else { return key } + guard let entry = cache[key] else { return (key, key) } let name = entry.name?.trimmingCharacters(in: .whitespacesAndNewlines) let gaia = entry.gaiaName?.trimmingCharacters(in: .whitespacesAndNewlines) - if let name, !name.isEmpty, let gaia, !gaia.isEmpty, !name.contains("—"), - name.lowercased() != gaia.lowercased() - { - return "\(name) — \(gaia)" + if let name, !name.isEmpty, let gaia, !gaia.isEmpty, !name.contains("—") { + let lowerName = name.lowercased() + let gaiaWords = gaia.lowercased().split(separator: " ").map(String.init) + let overlaps = + lowerName == gaia.lowercased() || gaiaWords.contains { $0.count >= 3 && lowerName.contains($0) } + if !overlaps { + return ("\(name) — \(gaia)", key) + } + } + if let name, !name.isEmpty { return (name, key) } + if let gaia, !gaia.isEmpty { return (gaia, key) } + return (key, key) + } + + /// Finds profile directories in `userData` where Front Desk's extension is installed. When + /// only one profile has the extension, this identifies it unambiguously even if Chrome's + /// `last_used` points at another profile. + private static func detectExtensionProfileDirectory(userData: URL) -> String? { + let fm = FileManager.default + let entries: [URL] + do { + entries = try fm.contentsOfDirectory( + at: userData, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles]) + } catch { + return nil + } + let extID = BrowserIdentity.extensionID + var matches: [String] = [] + for entry in entries { + let name = entry.lastPathComponent + guard name == "Default" || name.hasPrefix("Profile ") else { continue } + let prefs = entry.appending(path: "Preferences") + guard let data = fm.contents(atPath: prefs.path(percentEncoded: false)), + let text = String(data: data, encoding: .utf8), + text.contains(extID) + else { continue } + matches.append(name) } - if let name, !name.isEmpty { return name } - if let gaia, !gaia.isEmpty { return gaia } - return key + return matches.count == 1 ? matches[0] : nil } /// Attempts to infer the profile directory from the current working directory or environment. diff --git a/Sources/BrowserBridge/main.swift b/Sources/BrowserBridge/main.swift index b3d0f6f..a717568 100644 --- a/Sources/BrowserBridge/main.swift +++ b/Sources/BrowserBridge/main.swift @@ -146,6 +146,7 @@ enum BrowserBridgeMain { } dict["browser"] = .string(identity.browser) dict["profile"] = .string(identity.profile) + dict["profileDirectory"] = .string(identity.directory) return try WireCoding.encodeLine(JSONValue.object(dict)) } catch { var line = frame diff --git a/Sources/Host/Browser/BrowserDesk+Actions.swift b/Sources/Host/Browser/BrowserDesk+Actions.swift index c001a5a..a5e7a67 100644 --- a/Sources/Host/Browser/BrowserDesk+Actions.swift +++ b/Sources/Host/Browser/BrowserDesk+Actions.swift @@ -94,19 +94,21 @@ extension BrowserDesk { updateTabs(for: key, from: value) } } - let profiles = connectedProfiles() - let lines = profiles.map { p in - let uploads = p.fileAccessAllowed ? "uploads:ready" : "uploads:enable-file-urls" - return "\(p.browser) — \(p.profile) (\(p.tabCount) tabs, \(uploads))" + let orderedLinks = links.values.sorted { ($0.browser, $0.profile) < ($1.browser, $1.profile) } + let lines = orderedLinks.map { link in + let uploads = link.fileAccessAllowed ? "uploads:ready" : "uploads:enable-file-urls" + return "\(link.slug) \(link.browser) — \(link.profile) (\(link.tabs.count) tabs, \(uploads))" } let data = JSONValue.array( - profiles.map { p in + orderedLinks.map { link in .object([ - "id": .string(p.id), - "browser": .string(p.browser), - "profile": .string(p.profile), - "fileAccessAllowed": .bool(p.fileAccessAllowed), - "tabCount": .number(Double(p.tabCount)), + "id": .string(link.slug), + "key": .string(link.key), + "browser": .string(link.browser), + "profile": .string(link.profile), + "profileDirectory": .string(link.directory), + "fileAccessAllowed": .bool(link.fileAccessAllowed), + "tabCount": .number(Double(link.tabs.count)), ]) }) return BrowserReply(output: lines.joined(separator: "\n"), data: data) diff --git a/Sources/Host/Browser/BrowserDesk.swift b/Sources/Host/Browser/BrowserDesk.swift index a5d5ee1..0009f84 100644 --- a/Sources/Host/Browser/BrowserDesk.swift +++ b/Sources/Host/Browser/BrowserDesk.swift @@ -52,9 +52,14 @@ actor BrowserDesk { let descriptor: Descriptor var browser: String = "Chrome" var profile: String = "Default" + var directory: String = "Default" var fileAccessAllowed = false var tabs: [BrowserTabInfo] = [] + var slug: String { + "\(browser.lowercased()):\(directory)" + } + init(key: String, descriptor: Descriptor) { self.key = key self.descriptor = descriptor @@ -193,6 +198,7 @@ actor BrowserDesk { guard let link = links[profileKey] else { return } if case .string(let browser) = dict["browser"], !browser.isEmpty { link.browser = browser } if case .string(let profile) = dict["profile"], !profile.isEmpty { link.profile = profile } + if case .string(let dir) = dict["profileDirectory"], !dir.isEmpty { link.directory = dir } if case .bool(let allowed) = dict["fileAccessAllowed"] { link.fileAccessAllowed = allowed } updateTabs(for: profileKey, from: decoded) Log.ui.info( @@ -293,10 +299,15 @@ actor BrowserDesk { guard let filter, !filter.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return Array(links.keys) } - let needle = filter.lowercased() + let needle = filter.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let exact = links.values.filter { + $0.slug.lowercased() == needle || $0.directory.lowercased() == needle + || $0.profile.lowercased() == needle || $0.key.lowercased() == needle + } + if !exact.isEmpty { return exact.map(\.key) } return links.values.filter { - $0.profile.lowercased().contains(needle) || $0.browser.lowercased().contains(needle) - || $0.key.lowercased() == needle + $0.slug.lowercased().contains(needle) || $0.directory.lowercased().contains(needle) + || $0.profile.lowercased().contains(needle) || $0.browser.lowercased().contains(needle) }.map(\.key) } diff --git a/Sources/Script/Prelude.swift b/Sources/Script/Prelude.swift index 7653113..1399be6 100644 --- a/Sources/Script/Prelude.swift +++ b/Sources/Script/Prelude.swift @@ -125,7 +125,7 @@ enum Prelude { function makeTab(tabId) { const on = (method, ...args) => call(null, 'browser.' + method, [tabId, ...args]); - const tab = { tabId }; + const tab = { tabId, id: String(tabId) }; const methods = { state: (options) => printedText(on('state', options)), find: (words) => on('find', words).text, @@ -144,6 +144,7 @@ enum Prelude { drag: (from, to) => printedText(on('drag', from, to)), upload: (target, files) => printedText(on('upload', target, files)), goto: (url) => printedText(on('goto', url)), + navigate: (url) => printedText(on('goto', url)), back: () => printedText(on('back')), forward: () => printedText(on('forward')), reload: () => printedText(on('reload')), @@ -154,17 +155,33 @@ enum Prelude { close: () => { on('close'); }, detach: () => { on('detach'); }, }; + // Compatibility aliases for the browser tab handle. + methods.getAXState = (options) => methods.state(options?.disableDiffing ? { ...options, full: true } : options); + methods.getScreenshot = methods.screenshot; + methods.setValue = methods.set; + methods.typeText = (first, second) => { + if (second === undefined) return methods.type(first); + if (first !== null && first !== undefined) methods.click(first); + return methods.type(second); + }; + methods.pressKey = (first, second) => { + if (second === undefined) return methods.key(first); + if (first !== null && first !== undefined) methods.click(first); + return methods.key(second); + }; for (const name of Object.keys(methods)) Object.defineProperty(tab, name, { value: methods[name] }); return Object.freeze(tab); } function openOrSelectTab(target, options) { - const answer = typeof target === 'number' - ? call(null, 'browser.selectTab', [target, options]) + const numeric = typeof target === 'number' ? target + : (typeof target === 'string' && /^\d+$/.test(target.trim()) ? Number(target.trim()) : null); + const answer = numeric !== null + ? call(null, 'browser.selectTab', [numeric, options]) : call(null, 'browser.openTab', [target, options]); if (answer.printed && answer.text) printedTexts.add(answer.text); const match = typeof answer.text === 'string' ? answer.text.match(/^Tab (\d+):/) : null; - const resolvedId = typeof target === 'number' ? target : (match ? Number(match[1]) : null); + const resolvedId = numeric !== null ? numeric : (match ? Number(match[1]) : null); return makeTab(resolvedId); } @@ -174,6 +191,7 @@ enum Prelude { browsers: () => call(null, 'browser.browsers', []).data || [], tabs: (profile) => call(null, 'browser.tabs', profile ? [profile] : []).data || [], tab: (target, options) => openOrSelectTab(target, options), + newTab: (url, options) => openOrSelectTab(url, options), end: () => { call(null, 'end', []); }, }; computer.getApp = computer.app; @@ -183,6 +201,7 @@ enum Prelude { computer.getTab = computer.tab; const cua = { + getState: () => ({ apps: computer.apps(), browsers: computer.browsers() }), getApp: (name, options) => { const app = makeApp(call(null, 'app', [name, options]).app, true); if (options?.emit !== false) printedValues.add(app); @@ -199,8 +218,24 @@ enum Prelude { return apps; }, listBrowsers: computer.browsers, - listTabs: computer.tabs, - getTab: computer.tab, + listTabs: (options) => computer.tabs(typeof options === 'string' ? options : options?.browser), + getBrowser: (options) => { + const list = computer.browsers(); + const wanted = (typeof options === 'string' ? options : (options?.id || options?.profile || '')).toLowerCase(); + const found = wanted + ? list.find((b) => String(b.id || '').toLowerCase().includes(wanted) || String(b.profile || '').toLowerCase().includes(wanted) || String(b.browser || '').toLowerCase().includes(wanted)) + : list[0]; + return { browserId: found?.id || wanted || 'chrome', documentation: () => 'Front Desk Chrome tab bridge. Use cua.createBrowserTab(browserId, url, { visible: false }) for background tabs.' }; + }, + createBrowserTab: (browserId, url, options) => openOrSelectTab(url || 'about:blank', { + profile: browserId, + foreground: options?.visible === true, + emit: options?.emit, + }), + getTab: (ref, options) => openOrSelectTab(typeof ref === 'object' && ref !== null ? (ref.url || ref.id) : ref, { + profile: options?.browser || options?.profile, + emit: options?.emit, + }), }; // JavaScriptCore contexts have no atob, and older macOS has no Uint8Array.fromBase64. diff --git a/Sources/Script/ScriptArguments+Browser.swift b/Sources/Script/ScriptArguments+Browser.swift index f8a9ffe..e228a09 100644 --- a/Sources/Script/ScriptArguments+Browser.swift +++ b/Sources/Script/ScriptArguments+Browser.swift @@ -178,6 +178,9 @@ extension ScriptArguments { private static func parseBrowserTarget(_ value: JSONValue?) -> Target? { guard let value else { return nil } if let n = value.numberValue { return .element(id: ElementID(Int(n))) } + if let s = value.stringValue, let n = Int(s.trimmingCharacters(in: .whitespaces)) { + return .element(id: ElementID(n)) + } if let obj = dict(value), let n = obj["id"]?.numberValue { return .element(id: ElementID(Int(n))) } if let pt = parseBrowserPoint(value) { return .point(at: pt) } return nil diff --git a/Sources/computer/BrowserCommand.swift b/Sources/computer/BrowserCommand.swift index 9603c02..1f4ef34 100644 --- a/Sources/computer/BrowserCommand.swift +++ b/Sources/computer/BrowserCommand.swift @@ -4,6 +4,12 @@ import Foundation import Wire +/// One step inside a multi-line browser heredoc batch. +enum BrowserBatchStep: Equatable { + case browser(BrowserAction) + case end +} + /// Parses and executes `computer browsers`, `computer tabs`, and `computer tab ...` commands. struct BrowserCommand { let output: Output @@ -38,6 +44,124 @@ struct BrowserCommand { } } + /// Executes a multi-line browser heredoc batch over one persistent host connection, stopping + /// at the first error and printing the final step's output. + static func runBatch( + output: Output, shell: AgentShell, deadline: Deadline, session: SessionKey?, steps: [BrowserBatchStep] + ) async -> Int32 { + guard let app = AppInstall.enclosingThisExecutable() else { return output.fail(HostClient.notInsideApp) } + let connection: HostConnection + switch await HostClient(app: app, deadline: deadline, shell: shell).connect() { + case .success(let connected): connection = connected + case .failure(let problem): return output.fail(problem) + } + var lastBrowserReply: BrowserReply? + var lastEndReply: EndReply? + for step in steps { + switch step { + case .browser(let action): + let request = BrowserRequest( + session: session?.rawValue, + shell: shell, + deadline: deadline.earlier(by: Timing.replyGrace), + action: action) + switch connection.call(.browser(request), expecting: BrowserReply.self, deadline: deadline) { + case .failure(let problem): + return output.fail(problem) + case .success(let reply): + if let problem = reply.problem { + return output.fail(problem) + } + lastBrowserReply = reply + lastEndReply = nil + } + case .end: + switch connection.call(.end(EndRequest(session: session)), expecting: EndReply.self, deadline: deadline) + { + case .failure(let problem): + return output.fail(problem) + case .success(let reply): + lastEndReply = reply + } + } + } + if let lastEndReply, lastBrowserReply == nil || output.json { + output.result(lastEndReply, text: lastEndReply.output) + } else if let lastBrowserReply, output.json || !lastBrowserReply.output.isEmpty { + output.result(lastBrowserReply, text: lastBrowserReply.output) + } else if let lastEndReply, !lastEndReply.output.isEmpty { + output.result(lastEndReply, text: lastEndReply.output) + } + return 0 + } + + static func isBrowserBatch(_ batch: String) -> Bool { + let lines = + batch + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty && !$0.hasPrefix("#") } + guard let first = lines.first else { return false } + let verb = first.split(whereSeparator: \.isWhitespace).first.map(String.init) + return verb == "tab" || verb == "tabs" || verb == "browsers" + } + + static func parseBatch(_ batch: String) -> Result<[BrowserBatchStep], Problem> { + let lines = + batch + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty && !$0.hasPrefix("#") } + guard !lines.isEmpty else { + return .failure(CommandParser.invalid("The batch is empty, so nothing ran.")) + } + var steps: [BrowserBatchStep] = [] + for line in lines { + let tokens = tokenizeLine(line) + guard let verb = tokens.first else { continue } + if verb == "end" { + guard tokens.count == 1 else { + return .failure(CommandParser.invalid("`end` takes no arguments, so nothing ran.")) + } + steps.append(.end) + continue + } + switch parse(verb: verb, args: Array(tokens.dropFirst())) { + case .failure(let problem): return .failure(problem) + case .success(let action): steps.append(.browser(action)) + } + } + return .success(steps) + } + + private static func tokenizeLine(_ line: String) -> [String] { + var tokens: [String] = [] + var current = "" + var quote: Character? + var escaping = false + for ch in line { + if escaping { + current.append(ch) + escaping = false + } else if ch == "\\", quote != "'" { + escaping = true + } else if let q = quote { + if ch == q { quote = nil } else { current.append(ch) } + } else if ch == "\"" || ch == "'" { + quote = ch + } else if ch.isWhitespace { + if !current.isEmpty { + tokens.append(current) + current = "" + } + } else { + current.append(ch) + } + } + if !current.isEmpty { tokens.append(current) } + return tokens + } + /// Parses `browsers`, `tabs`, or `tab ...` CLI arguments into a typed `BrowserAction`. static func parse(verb: String, args: [String]) -> Result { switch verb { diff --git a/Sources/computer/Invocation.swift b/Sources/computer/Invocation.swift index e91a8f3..570c37b 100644 --- a/Sources/computer/Invocation.swift +++ b/Sources/computer/Invocation.swift @@ -23,6 +23,8 @@ struct Invocation: Equatable { case forget /// `browsers`, `tabs`, or `tab ...`. case browser(BrowserAction) + /// Multi-line heredoc batch of browser commands (`tab ...`, optional `end`). + case browserBatch([BrowserBatchStep]) } /// `computer` alone (with nothing on stdin) and `--help` print help. For `js`, `stdin` is the code @@ -52,6 +54,9 @@ struct Invocation: Equatable { if help { return .success(Invocation(command: .help, json: json)) } guard let verb = words.first else { guard let batch else { return .success(Invocation(command: .help, json: json)) } + if BrowserCommand.isBrowserBatch(batch) { + return BrowserCommand.parseBatch(batch).map { Invocation(command: .browserBatch($0), json: json) } + } return CommandParser.parseBatch(batch).map { Invocation(command: .run($0), json: json) } } switch verb { diff --git a/Sources/computer/MCPTools.swift b/Sources/computer/MCPTools.swift index fc898cd..a2fc05b 100644 --- a/Sources/computer/MCPTools.swift +++ b/Sources/computer/MCPTools.swift @@ -8,13 +8,16 @@ enum MCPTools { tool( "js", """ - Operate Mac apps in a persistent JavaScript session. Start with cua.getApp(name) or cua.listApps(). - Batch known actions, then read app.getAXState() and verify the result. Prefer IDs from the latest tree. - Use app.getScreenshot() for pixels. Do not sleep. Reads emit by default. Silence them with {emit:false} - or write your own text with nodeRepl.write(value). + Operate Mac apps and background Chrome tabs in a persistent JavaScript session. + Apps: cua.getApp(name) or cua.listApps(). Batch known actions, then read app.getAXState() and verify. + Browser tabs (true background tabs across signed-in Chrome profiles, zero focus steal): + computer.browsers(), computer.tabs(), computer.newTab(url, {profile}), computer.tab(tabId). + Tab methods: state/getAXState, find(words), click(id|[x,y]), set/setValue(id, text), + type/typeText(text), key/pressKey(keys), upload(id, path), goto(url), screenshot/getScreenshot(), + eval(expr), close(). - Actions: click(id or [x,y], options?), typeText(text), pressKey(key), setValue(id, text), - selectText(id, text, options?), scroll(id or [x,y], direction, pages?), performSecondaryAction(id, action). + Prefer IDs from the latest tree. Use screenshot() for pixels. Do not sleep. Reads emit by default; + silence them with {emit:false} or write text with nodeRepl.write(value). """, properties: [ "code": .object([ diff --git a/Sources/computer/main.swift b/Sources/computer/main.swift index f039e05..c93f88a 100644 --- a/Sources/computer/main.swift +++ b/Sources/computer/main.swift @@ -56,5 +56,9 @@ case .success(let invocation): exit( await BrowserCommand(output: output, shell: shell, deadline: deadline, session: session, action: action) .run()) + case .browserBatch(let steps): + exit( + await BrowserCommand.runBatch( + output: output, shell: shell, deadline: deadline, session: session, steps: steps)) } } diff --git a/Tests/Transcripts/mcp/code-mode.jsonl b/Tests/Transcripts/mcp/code-mode.jsonl index 0034cdf..62ec05b 100644 --- a/Tests/Transcripts/mcp/code-mode.jsonl +++ b/Tests/Transcripts/mcp/code-mode.jsonl @@ -2,7 +2,7 @@ {"reply":{"id":1,"jsonrpc":"2.0","result":{"capabilities":{"tools":{}},"protocolVersion":"2025-03-26","serverInfo":{"name":"front_desk","version":"0.1.1"}}}} {"request":{"jsonrpc":"2.0","method":"notifications/initialized"}} {"request":{"id":"list","jsonrpc":"2.0","method":"tools/list"}} -{"reply":{"id":"list","jsonrpc":"2.0","result":{"tools":[{"description":"Operate Mac apps in a persistent JavaScript session. Start with cua.getApp(name) or cua.listApps().\nBatch known actions, then read app.getAXState() and verify the result. Prefer IDs from the latest tree.\nUse app.getScreenshot() for pixels. Do not sleep. Reads emit by default. Silence them with {emit:false}\nor write your own text with nodeRepl.write(value).\n\nActions: click(id or [x,y], options?), typeText(text), pressKey(key), setValue(id, text),\nselectText(id, text, options?), scroll(id or [x,y], direction, pages?), performSecondaryAction(id, action).","inputSchema":{"additionalProperties":false,"properties":{"code":{"maxLength":100000,"type":"string"},"timeout_ms":{"default":30000,"maximum":55000,"minimum":1,"type":"integer"},"title":{"description":"Short description of the step.","type":"string"}},"required":["code"],"type":"object"},"name":"js"},{"description":"Clear this session’s JavaScript variables. Use when you need a fresh context.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"js_reset"}]}}} +{"reply":{"id":"list","jsonrpc":"2.0","result":{"tools":[{"description":"Operate Mac apps and background Chrome tabs in a persistent JavaScript session.\nApps: cua.getApp(name) or cua.listApps(). Batch known actions, then read app.getAXState() and verify.\nBrowser tabs (true background tabs across signed-in Chrome profiles, zero focus steal):\ncomputer.browsers(), computer.tabs(), computer.newTab(url, {profile}), computer.tab(tabId).\nTab methods: state/getAXState, find(words), click(id|[x,y]), set/setValue(id, text),\ntype/typeText(text), key/pressKey(keys), upload(id, path), goto(url), screenshot/getScreenshot(),\neval(expr), close().\n\nPrefer IDs from the latest tree. Use screenshot() for pixels. Do not sleep. Reads emit by default;\nsilence them with {emit:false} or write text with nodeRepl.write(value).","inputSchema":{"additionalProperties":false,"properties":{"code":{"maxLength":100000,"type":"string"},"timeout_ms":{"default":30000,"maximum":55000,"minimum":1,"type":"integer"},"title":{"description":"Short description of the step.","type":"string"}},"required":["code"],"type":"object"},"name":"js"},{"description":"Clear this session’s JavaScript variables. Use when you need a fresh context.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"js_reset"}]}}} {"request":{"id":3,"jsonrpc":"2.0","method":"tools/call","params":{"arguments":{"code":"const app = await cua.getApp(\"Contacts\"); const number = 40;"},"name":"js"}}} {"reply":{"id":3,"jsonrpc":"2.0","result":{"content":[{"text":"\nContacts\n- Fill a field with set.\n\nWindow \"New Contact\" in Contacts.\n0 standard window New Contact\n\t1 text field (settable) Placeholder: First\n\t2 text field (settable) Placeholder: Last\n\t3 text entry area Description: Note\n\t4 button Done","type":"text"}],"isError":false}}} {"request":{"id":4,"jsonrpc":"2.0","method":"tools/call","params":{"arguments":{"code":"app.click(1); await app.setValue(1, \"Ana\"); app.typeText(3, \"hello\"); app.pressKey(3, \"Tab\"); nodeRepl.write(number + 2); await app.getAXState();","timeout_ms":20000,"title":"Fill first name"},"name":"js"}}} diff --git a/Tests/computerTests/BrowserCommandTests.swift b/Tests/computerTests/BrowserCommandTests.swift index 0ec7f1f..40107aa 100644 --- a/Tests/computerTests/BrowserCommandTests.swift +++ b/Tests/computerTests/BrowserCommandTests.swift @@ -40,4 +40,29 @@ struct BrowserCommandTests { try Invocation.parse(["tab", "webmcp", "search", "{\"q\":\"ok\"}"]).get().command == .browser(.webmcpCall(tabID: nil, tool: "search", inputJSON: "{\"q\":\"ok\"}"))) } + + @Test("parses multi-line browser heredoc batches including end") + func parsesBrowserBatch() throws { + let batch = """ + # Upload and submit in one batch + tab 42 upload 100009 /tmp/report.txt + tab 42 set 100010 "Draft Q4 plan" + tab 42 click 100011 + tab 42 close + end + """ + let parsed = try Invocation.parse([], batch: batch).get() + #expect( + parsed.command + == .browserBatch([ + .browser(.upload(tabID: 42, target: .element(id: ElementID(100_009)), files: ["/tmp/report.txt"])), + .browser(.set(tabID: 42, id: ElementID(100_010), text: "Draft Q4 plan")), + .browser( + .click( + tabID: 42, target: .element(id: ElementID(100_011)), + options: Click(button: .left, count: 1, modifiers: []))), + .browser(.close(tabID: 42)), + .end, + ])) + } } diff --git a/resources/skill/SKILL.md b/resources/skill/SKILL.md index fbf7810..d52d866 100644 --- a/resources/skill/SKILL.md +++ b/resources/skill/SKILL.md @@ -101,16 +101,18 @@ When Chrome has the Front Desk extension connected, work directly in real backgr all signed-in profiles without touching the user's active tab, window, or mouse: - `computer browsers` lists connected profiles (`chrome:Profile 1`, `chrome:Default`, …). -- `computer tabs [--profile ]` lists open tabs with their IDs (`:`). +- `computer tabs [--profile ]` lists open tabs with their IDs (``). - `computer tab new [--profile ]` opens a new background tab and prints its accessibility tree. - `computer tab state [--full]`, `click `, `set `, `type `, - `key `, `scroll [pages]`, `navigate `, `upload `, + `key `, `scroll [pages]`, `goto `, `upload `, `screenshot`, `eval `, `webmcp [tool] [json]`, `close`. +- Batch multiple `tab ...` commands in a single `computer <<'EOF'` heredoc (or in `computer js`) + for speed. - Tabs return compact accessibility diffs (`~` changed, `+` added, `Removed IDs`) just like native apps. Actions on banking, password-manager, or Chrome internal pages are refused unless allowed. -- In `computer js`, use `computer.browsers()`, `computer.tabs()`, `computer.newTab(url)` and - `computer.tab(id)` (`state`, `find`, `elements`, `click`, `set`, `type`, `key`, `scroll`, - `navigate`, `upload`, `screenshot`, `eval`, `webmcp`, `close`). +- In `computer js`, use `computer.browsers()`, `computer.tabs()`, `computer.newTab(url, {profile})` + and `computer.tab(id)` (`state`, `find`, `click`, `set`, `type`, `key`, `scroll`, + `goto`, `upload`, `screenshot`, `eval`, `webmcp`, `close`). ## Code mode: `computer js`