Repository navigation
Conversation
Contributor
Author
|
Passes on this branch.
All 15 checks passed. All checks
Shared steps (clienttools_steps.py) (This branch)"""Shared paths for the Duck.ai client tools proofs (tools_all, tools_deny, tools_settings).
Setup these proofs assume, done by hand before the run (see the proof notes): Browser Tools dev screen with
aiChatBrowserTools and all seven tools on, devSkipPermissionPrompt and requestAccess off; a Custom Duck.ai URL
whose instance offers client tools and is signed in; synthetic tabs "Storage blocking test page"
(?ddgverify=bm) and "Download" (?ddgverify=deny) inside the first 50 regular tabs; a synthetic download-1.pdf.
"""
import json
import pathlib
import time
from prove import Error, verify
PROMPT_TITLE = "browserToolsPermissionsTitle"
ALLOW = "id:browserToolsPermissionsAllow"
DONT_ALLOW = "id:browserToolsPermissionsDontAllow"
SEND_BUTTONS = ("nativeInputSubmitButton", "nativeInputAskButton")
def source():
return pathlib.Path(__file__).read_text()
def to_browser(android):
for _ in range(6):
where = android.where()
if where == "BrowserActivity":
return
if where == "-":
android.launch()
continue
android.key("back")
time.sleep(1)
raise Error(f"couldn't get back to the browser, still on {android.where()}")
def menu(android):
"""The browser menu from the New Tab Page, a page, or a Duck.ai tab."""
for _ in range(2):
for button in ("inputModeWidgetNavMenu", "browserMenuImageView", "browserMenu"):
if android.visible(f"id:{button}"):
android.tap(f"id:{button}")
break
else:
android.scroll("down")
continue
if android.wait("id:settingsMenuItem", 5):
return
raise Error("the browser menu didn't open")
def chat_attached(android, timeout=30):
return android.poll(lambda: android.web_eval("location.host") or "", lambda h: h.endswith("duck.ai"), timeout)
def new_chat(android):
"""A new Duck.ai chat; stops with an error when the instance asks for sign-in instead."""
to_browser(android)
menu(android)
android.tap("id:newDuckChatMenuItem" if android.visible("id:newDuckChatMenuItem") else "id:duckAiNewChatMenuItem")
if not android.wait("id:duckAIHeader", 25):
raise Error("Duck.ai didn't open")
host = chat_attached(android)
if not host.endswith("duck.ai"):
raise Error(f"the chat page is {host}, not Duck.ai: the dev instance needs the company sign-in on the phone")
time.sleep(2)
def said_count(android):
return android.web_eval('document.body.innerText.split("Duck.ai said").length - 1') or 0
def ask(android, prompt):
"""Sends a prompt; returns how many replies the page had before it."""
before = said_count(android)
android.type("id:inputField", prompt)
button = android.poll(lambda: next((b for b in SEND_BUTTONS if android.visible(f"id:{b}")), None), bool, 10)
if not button:
raise Error("no send button appeared after typing")
android.tap(f"id:{button}")
return before
def wait_prompt(android, timeout=40):
"""The permission dialog's title when it shows within timeout, else None."""
if android.wait(f"id:{PROMPT_TITLE}", timeout):
return android.text(PROMPT_TITLE)
return None
def wait_reply(android, before, timeout=60):
"""Waits for the reply after `before` to finish streaming; returns the reply's text (lowercased)."""
last = '(() => { const t = document.body.innerText; return t.slice(t.lastIndexOf("Duck.ai said")); })()'
android.poll(lambda: said_count(android), lambda n: n > before, timeout)
deadline = time.monotonic() + timeout
previous = None
while time.monotonic() < deadline:
text = android.web_eval(last) or ""
streaming = android.visible("id:stopStreamingButton") or android.visible(f"id:{PROMPT_TITLE}")
if not streaming and text == previous and len(text) > len("Duck.ai said") + 5:
return text.lower()
previous = text
time.sleep(2)
return (previous or "").lower()
def switcher(android):
to_browser(android)
for _ in range(3):
button = next((b for b in ("inputModeWidgetNavTabs", "tabsImageView", "tabsMenu") if android.visible(f"id:{b}")), None)
if button:
android.tap(f"id:{button}")
break
android.scroll("down") # a scrolled page hides the toolbar
if android.poll(android.where, lambda w: w == "TabSwitcherActivity", 10) != "TabSwitcherActivity":
raise Error("the tab switcher didn't open")
time.sleep(1)
def switcher_top(android, swipes=20):
"""Scrolls the tab switcher to its first cards."""
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "500", "540", "2100", "80")
time.sleep(2)
def switcher_bottom(android, swipes=20):
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "2000", "540", "400", "80")
time.sleep(2)
def tab_count(android):
value = android.text("regularTabCount")
return int(value) if value and value.isdigit() else None
def nodes(android):
out = []
def walk(n):
if isinstance(n, dict):
out.append(n)
for v in n.values():
walk(v)
elif isinstance(n, list):
for v in n:
walk(v)
walk(json.loads(verify("layout").stdout))
return out
def back_to_chat(android):
"""The last card in the tab switcher is the chat this proof opened (new tabs append at the end)."""
if android.where() != "TabSwitcherActivity":
switcher(android)
switcher_bottom(android)
cards = [n for n in nodes(android) if n.get("text") in ("Duck.ai", "New Chat") and n.get("center")]
if not cards:
raise Error("no Duck.ai card at the end of the tab switcher")
x, y = cards[-1]["center"].strip("[]").split(",")
android._adb("shell", "input", "tap", x, y)
if not android.wait("id:duckAIHeader", 15) or not chat_attached(android).endswith("duck.ai"):
raise Error("tapping the last Duck.ai card didn't return to the chat")
time.sleep(1)
def settings(android):
to_browser(android)
menu(android)
android.tap("id:settingsMenuItem")
if android.poll(android.where, lambda w: w == "SettingsActivity", 10) != "SettingsActivity":
raise Error("Settings didn't open")
time.sleep(1)
def browser_access(android):
"""Settings > AI Features > Browser Access."""
settings(android)
# Settings reopens at its last scroll position, so look further down first, then back up.
for direction in ["up"] * 6 + ["down"] * 20:
if android.visible("id:includeDuckChatSetting"):
break
android.scroll(direction)
android.tap("id:includeDuckChatSetting")
if android.poll(android.where, lambda w: w == "DuckChatSettingsActivity", 10) != "DuckChatSettingsActivity":
raise Error("AI Features didn't open")
for _ in range(4):
if android.visible("id:duckAiBrowserAccess"):
break
android.scroll("up")
android.tap("id:duckAiBrowserAccess")
if android.poll(android.where, lambda w: w == "BrowserAccessSettingsActivity", 10) != "BrowserAccessSettingsActivity":
raise Error("Browser Access didn't open")
time.sleep(1)
def access_choice(android, tool_name):
"""On Browser Access: the choice shown under a tool's row ("Always Ask", ...)."""
lines = android.lines()
for i, line in enumerate(lines):
if line[:2] == ["primaryText", tool_name]:
return next((l[1] for l in lines[i + 1:i + 2] if l[0] == "secondaryText"), None)
return None
def set_access(android, tool_name, choice):
android.tap(f"text:{tool_name}")
if not android.wait("id:radioListDialogTitle", 5):
raise Error(f"{tool_name}'s choices didn't open")
android.tap(f"text:{choice}")
android.tap("text:Save")
time.sleep(1)
def bookmarks(android):
to_browser(android)
menu(android)
for _ in range(3):
if android.visible("id:bookmarksMenuItem"):
break
android.scroll("up")
android.tap("id:bookmarksMenuItem")
if android.poll(android.where, lambda w: w == "BookmarksActivity", 10) != "BookmarksActivity":
raise Error("Bookmarks didn't open")
time.sleep(1)Proof source"""readTabContent and searchHistory work end to end from a Duck.ai chat.
readTabContent reads a background tab's text from the page context the browser cached for it: with
androidBrowserConfig.storePageContext off nothing is cached and the tool replies unavailable; with it on, a page
loaded afterwards is read, its address comes back without query or fragment, and a second call in the same chat
runs without a prompt (the chat grant). searchHistory prompts once, finds the synthetic pages by title, returns
their addresses without query or fragment and a UTC visitedAt, and a date range in the past finds nothing.
Setup done before the run: Browser Tools dev screen with aiChatBrowserTools, listOpenTabs, readTabContent and
searchHistory on, devSkipPermissionPrompt and requestAccess off; a Custom Duck.ai URL whose instance offers client
tools and is signed in.
"""
import time
import clienttools_steps as s
from prove import Error
LIVE = ["Duck.ai chat (Custom Duck.ai URL dev instance)"]
UNCACHED_URL = "https://example.com/?ddgverify=read1#top"
CACHED_URL = "https://example.org/?ddgverify=read2#top"
READ_PROMPT = "Allow Duck.ai to read your open tabs?"
TABS_PROMPT = "Allow Duck.ai to see your open tabs?"
HISTORY_PROMPT = "Allow Duck.ai to search your history?"
def store_page_context(android, on):
"""Setup: sets androidBrowserConfig.storePageContext from the Feature Flag Inventory."""
s.settings(android)
for direction in ["down"] * 6 + ["up"] * 12:
if android.visible("text:Feature Flag Inventory"):
break
android.scroll(direction)
android.tap("text:Feature Flag Inventory")
if not android.wait("id:internal_edit_text", 10):
raise Error("Feature Flag Inventory didn't open")
android.type("id:internal_edit_text", "storePageContext")
time.sleep(2)
android.key("back") # hides the keyboard
time.sleep(1)
# Rows: androidBrowserConfig (parent), then storePageContext.
if android.checked("trailingSwitch", 2) != on:
android.tap("id:trailingSwitch", index=2)
time.sleep(1)
state = android.checked("trailingSwitch", 2)
if state != on:
raise Error(f"storePageContext is {state}, wanted {on}")
android.shot(f"rh-setup-storepagecontext-{'on' if on else 'off'}")
s.to_browser(android)
def allow_until_reply(android, before, expected_prompts):
"""Allows every prompt shown before the reply finishes; returns (titles seen, reply)."""
seen = []
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
title = s.wait_prompt(android, timeout=8)
if title:
seen.append(title)
android.shot(f"rh-prompt-{len(seen)}-{expected_prompts}")
android.tap(s.ALLOW)
continue
if s.said_count(android) > before and not android.visible("id:stopStreamingButton"):
break
return seen, s.wait_reply(android, before)
def open_page(android, url):
"""Opens url in a new tab; returns the page's own text, lowercased and with whitespace collapsed."""
android.open(url)
android.poll(lambda: android.web_eval("location.href") or "", lambda h: "ddgverify" in h, 20)
time.sleep(3) # page-finish collection of the page context
return " ".join((android.web_eval("document.body.innerText") or "").lower().split())
def quoted(reply):
"""The text inside the reply's first pair of quotes, or ''."""
for left, right in (("\u201c", "\u201d"), ('"', '"')):
start = reply.find(left)
end = reply.find(right, start + 1)
if start >= 0 and end > start:
return " ".join(reply[start + 1:end].split()).rstrip(".")
return ""
def run(android):
android.section("Shared steps (clienttools_steps.py)", "```python\n" + s.source().rstrip() + "\n```")
# readTabContent with nothing cached
store_page_context(android, on=False)
uncached_text = open_page(android, UNCACHED_URL)
s.new_chat(android)
android.shot("rh-01-fresh-chat")
before = s.ask(android, "Use listOpenTabs to find my tab whose address is on example.com, then use readTabContent "
"with that tabId and quote one sentence from it in double quotes. If the tool fails, say the error code.")
android.mark()
seen, reply = allow_until_reply(android, before, "uncached")
android.check("readTabContent prompt shown", READ_PROMPT in seen, str(seen))
android.expect_log("readTabContent replied unavailable with nothing cached",
r"Client tool readTabContent replied unavailable")
quote = quoted(reply)
android.check("the reply quotes no page text", not quote or quote not in uncached_text, reply[:300])
android.shot("rh-02-uncached-reply")
# readTabContent with the page cached
store_page_context(android, on=True)
page_text = open_page(android, CACHED_URL)
android.note(f"second view, the example.org page's own text (DevTools): {page_text[:200]}")
s.back_to_chat(android)
before = s.ask(android, "Use listOpenTabs to find my tab whose address is on example.org, then use readTabContent "
"with that tabId. Reply with the exact url field and one sentence of the content in double quotes.")
android.mark()
seen, reply = allow_until_reply(android, before, "cached")
android.check("readTabContent ran without a second prompt (chat grant)", READ_PROMPT not in seen, str(seen))
android.expect_log("readTabContent replied ok", r"Client tool readTabContent replied ok")
quote = quoted(reply)
android.check("the reply's quote is the page's own text", len(quote) > 15 and quote in page_text,
f"quote: {quote!r}")
android.check("the reply's url has no query or fragment",
"example.org" in reply and "ddgverify" not in reply and "#top" not in reply, reply[:400])
android.shot("rh-03-cached-reply")
# searchHistory
today = time.strftime("%Y-%m-%d", time.gmtime())
before = s.ask(android, "Use the searchHistory tool with query Example Domain. For each result reply with its "
"exact url and visitedAt fields, one per line.")
android.mark()
seen, reply = allow_until_reply(android, before, "history")
android.check("searchHistory prompt shown", HISTORY_PROMPT in seen, str(seen))
android.expect_log("searchHistory replied ok", r"Client tool searchHistory replied ok")
android.check("the reply lists both synthetic pages", "example.com" in reply and "example.org" in reply, reply[:500])
android.check("no url carries the query or fragment", "ddgverify" not in reply and "#top" not in reply, reply[:500])
android.check(f"visitedAt is today's UTC date ending in Z", f"{today}t" in reply and "z" in reply, reply[:500])
android.shot("rh-04-history-reply")
before = s.ask(android, "Use the searchHistory tool with query Example Domain, startDate 2020-01-01 and endDate "
"2020-01-02. How many results did it return? Answer with the number only.")
android.mark()
seen, reply = allow_until_reply(android, before, "history-range")
android.check("searchHistory ran without a second prompt (chat grant)", HISTORY_PROMPT not in seen, str(seen))
android.expect_log("searchHistory with a past range replied ok", r"Client tool searchHistory replied ok")
android.check("a 2020 range finds nothing", "0" in reply.replace("duck.ai said", ""), reply[:300])
android.shot("rh-05-history-range-reply")
android.unverified("readTabContent with no tabId in the contextual sheet reads the host page",
"not driven on device; covered by ReadTabContentClientToolTest")
android.unverified("searchHistory returns unavailable with history turned off",
"would change the user's history setting; covered by SearchHistoryClientToolTest")Rerun |
Searches local history by term and an optional UTC date range, per the v1 contract. Each query word is scored against the title, host and path; a page needs half the words, and results rank by words matched, word-start matches, days visited, then recency. Addresses are merged once their query and fragment are dropped, so each URL appears once at its latest visit in range. Returns unavailable when history is off. Moves the UTC timestamp formatting searchDownloads used into ClientToolOutput so both tools share it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reads a tab's text from the page context the browser cached for it, the same content-scope extraction the contextual sheet attaches. Background tabs have no live WebView on Android, so the cache is the one source that covers every tab. A tab with no cached context, or one cached for another address, returns unavailable, as do non-web, Duck.ai and non-attachable pages. Omitting tabId reads the chat's own tab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
malmstein
force-pushed
the
feature/david/last_batch_of_tools
branch
from
November 20, 2026 11:14
66c32ac to
d9c3f3a
Compare
Finds a word or phrase in a tab's cached page context, the same text readTabContent reads, and returns the match count with up to maxMatches snippets of at most 100 characters. matchIndexesReliable is always false: matches come from the extracted text rather than the live page, so they may not line up with highlighting. Moves the tab lookup and page-context read out of readTabContent into CachedTabPages, so both tools apply the same page rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
malmstein
marked this pull request as ready for review
November 20, 2026 13:05
There was a problem hiding this comment.
Claude Code Review
This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.
Tip: disable this comment in your organization's Code Review settings.
Contributor
Author
|
Passes on this branch.
All 15 checks passed. All checks
Shared steps (clienttools_steps.py) (This branch)"""Shared paths for the Duck.ai client tools proofs (tools_all, tools_deny, tools_settings).
Setup these proofs assume, done by hand before the run (see the proof notes): Browser Tools dev screen with
aiChatBrowserTools and all seven tools on, devSkipPermissionPrompt and requestAccess off; a Custom Duck.ai URL
whose instance offers client tools and is signed in; synthetic tabs "Storage blocking test page"
(?ddgverify=bm) and "Download" (?ddgverify=deny) inside the first 50 regular tabs; a synthetic download-1.pdf.
"""
import json
import pathlib
import time
from prove import Error, verify
PROMPT_TITLE = "browserToolsPermissionsTitle"
ALLOW = "id:browserToolsPermissionsAllow"
DONT_ALLOW = "id:browserToolsPermissionsDontAllow"
SEND_BUTTONS = ("nativeInputSubmitButton", "nativeInputAskButton")
def source():
return pathlib.Path(__file__).read_text()
def to_browser(android):
for _ in range(6):
where = android.where()
if where == "BrowserActivity":
return
if where == "-":
android.launch()
continue
android.key("back")
time.sleep(1)
raise Error(f"couldn't get back to the browser, still on {android.where()}")
def menu(android):
"""The browser menu from the New Tab Page, a page, or a Duck.ai tab."""
for _ in range(2):
for button in ("inputModeWidgetNavMenu", "browserMenuImageView", "browserMenu"):
if android.visible(f"id:{button}"):
android.tap(f"id:{button}")
break
else:
android.scroll("down")
continue
if android.wait("id:settingsMenuItem", 5):
return
raise Error("the browser menu didn't open")
def chat_attached(android, timeout=30):
return android.poll(lambda: android.web_eval("location.host") or "", lambda h: h.endswith("duck.ai"), timeout)
def new_chat(android):
"""A new Duck.ai chat; stops with an error when the instance asks for sign-in instead."""
to_browser(android)
menu(android)
android.tap("id:newDuckChatMenuItem" if android.visible("id:newDuckChatMenuItem") else "id:duckAiNewChatMenuItem")
if not android.wait("id:duckAIHeader", 25):
raise Error("Duck.ai didn't open")
host = chat_attached(android)
if not host.endswith("duck.ai"):
raise Error(f"the chat page is {host}, not Duck.ai: the dev instance needs the company sign-in on the phone")
time.sleep(2)
def said_count(android):
return android.web_eval('document.body.innerText.split("Duck.ai said").length - 1') or 0
def ask(android, prompt):
"""Sends a prompt; returns how many replies the page had before it."""
before = said_count(android)
android.type("id:inputField", prompt)
button = android.poll(lambda: next((b for b in SEND_BUTTONS if android.visible(f"id:{b}")), None), bool, 10)
if not button:
raise Error("no send button appeared after typing")
android.tap(f"id:{button}")
return before
def wait_prompt(android, timeout=40):
"""The permission dialog's title when it shows within timeout, else None."""
if android.wait(f"id:{PROMPT_TITLE}", timeout):
return android.text(PROMPT_TITLE)
return None
def wait_reply(android, before, timeout=60):
"""Waits for the reply after `before` to finish streaming; returns the reply's text (lowercased)."""
last = '(() => { const t = document.body.innerText; return t.slice(t.lastIndexOf("Duck.ai said")); })()'
android.poll(lambda: said_count(android), lambda n: n > before, timeout)
deadline = time.monotonic() + timeout
previous = None
while time.monotonic() < deadline:
text = android.web_eval(last) or ""
streaming = android.visible("id:stopStreamingButton") or android.visible(f"id:{PROMPT_TITLE}")
if not streaming and text == previous and len(text) > len("Duck.ai said") + 5:
return text.lower()
previous = text
time.sleep(2)
return (previous or "").lower()
def switcher(android):
to_browser(android)
for _ in range(3):
button = next((b for b in ("inputModeWidgetNavTabs", "tabsImageView", "tabsMenu") if android.visible(f"id:{b}")), None)
if button:
android.tap(f"id:{button}")
break
android.scroll("down") # a scrolled page hides the toolbar
if android.poll(android.where, lambda w: w == "TabSwitcherActivity", 10) != "TabSwitcherActivity":
raise Error("the tab switcher didn't open")
time.sleep(1)
def switcher_top(android, swipes=20):
"""Scrolls the tab switcher to its first cards."""
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "500", "540", "2100", "80")
time.sleep(2)
def switcher_bottom(android, swipes=20):
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "2000", "540", "400", "80")
time.sleep(2)
def tab_count(android):
value = android.text("regularTabCount")
return int(value) if value and value.isdigit() else None
def nodes(android):
out = []
def walk(n):
if isinstance(n, dict):
out.append(n)
for v in n.values():
walk(v)
elif isinstance(n, list):
for v in n:
walk(v)
walk(json.loads(verify("layout").stdout))
return out
def back_to_chat(android):
"""The last card in the tab switcher is the chat this proof opened (new tabs append at the end)."""
if android.where() != "TabSwitcherActivity":
switcher(android)
switcher_bottom(android)
cards = [n for n in nodes(android) if n.get("text") in ("Duck.ai", "New Chat") and n.get("center")]
if not cards:
raise Error("no Duck.ai card at the end of the tab switcher")
x, y = cards[-1]["center"].strip("[]").split(",")
android._adb("shell", "input", "tap", x, y)
if not android.wait("id:duckAIHeader", 15) or not chat_attached(android).endswith("duck.ai"):
raise Error("tapping the last Duck.ai card didn't return to the chat")
time.sleep(1)
def settings(android):
to_browser(android)
menu(android)
android.tap("id:settingsMenuItem")
if android.poll(android.where, lambda w: w == "SettingsActivity", 10) != "SettingsActivity":
raise Error("Settings didn't open")
time.sleep(1)
def browser_access(android):
"""Settings > AI Features > Browser Access."""
settings(android)
# Settings reopens at its last scroll position, so look further down first, then back up.
for direction in ["up"] * 6 + ["down"] * 20:
if android.visible("id:includeDuckChatSetting"):
break
android.scroll(direction)
android.tap("id:includeDuckChatSetting")
if android.poll(android.where, lambda w: w == "DuckChatSettingsActivity", 10) != "DuckChatSettingsActivity":
raise Error("AI Features didn't open")
for _ in range(4):
if android.visible("id:duckAiBrowserAccess"):
break
android.scroll("up")
android.tap("id:duckAiBrowserAccess")
if android.poll(android.where, lambda w: w == "BrowserAccessSettingsActivity", 10) != "BrowserAccessSettingsActivity":
raise Error("Browser Access didn't open")
time.sleep(1)
def access_choice(android, tool_name):
"""On Browser Access: the choice shown under a tool's row ("Always Ask", ...)."""
lines = android.lines()
for i, line in enumerate(lines):
if line[:2] == ["primaryText", tool_name]:
return next((l[1] for l in lines[i + 1:i + 2] if l[0] == "secondaryText"), None)
return None
def set_access(android, tool_name, choice):
android.tap(f"text:{tool_name}")
if not android.wait("id:radioListDialogTitle", 5):
raise Error(f"{tool_name}'s choices didn't open")
android.tap(f"text:{choice}")
android.tap("text:Save")
time.sleep(1)
def bookmarks(android):
to_browser(android)
menu(android)
for _ in range(3):
if android.visible("id:bookmarksMenuItem"):
break
android.scroll("up")
android.tap("id:bookmarksMenuItem")
if android.poll(android.where, lambda w: w == "BookmarksActivity", 10) != "BookmarksActivity":
raise Error("Bookmarks didn't open")
time.sleep(1)Proof source"""readTabContent and searchHistory work end to end from a Duck.ai chat.
readTabContent reads a background tab's text from the page context the browser cached for it: with
androidBrowserConfig.storePageContext off nothing is cached and the tool replies unavailable; with it on, a page
loaded afterwards is read, its address comes back without query or fragment, and a second call in the same chat
runs without a prompt (the chat grant). searchHistory prompts once, finds the synthetic pages by title, returns
their addresses without query or fragment and a UTC visitedAt, and a date range in the past finds nothing.
Setup done before the run: Browser Tools dev screen with aiChatBrowserTools, listOpenTabs, readTabContent and
searchHistory on, devSkipPermissionPrompt and requestAccess off; a Custom Duck.ai URL whose instance offers client
tools and is signed in.
"""
import time
import clienttools_steps as s
from prove import Error
LIVE = ["Duck.ai chat (Custom Duck.ai URL dev instance)"]
UNCACHED_URL = "https://example.com/?ddgverify=read1#top"
CACHED_URL = "https://example.org/?ddgverify=read2#top"
READ_PROMPT = "Allow Duck.ai to read your open tabs?"
TABS_PROMPT = "Allow Duck.ai to see your open tabs?"
HISTORY_PROMPT = "Allow Duck.ai to search your history?"
def store_page_context(android, on):
"""Setup: sets androidBrowserConfig.storePageContext from the Feature Flag Inventory."""
s.settings(android)
for direction in ["down"] * 6 + ["up"] * 12:
if android.visible("text:Feature Flag Inventory"):
break
android.scroll(direction)
android.tap("text:Feature Flag Inventory")
if not android.wait("id:internal_edit_text", 10):
raise Error("Feature Flag Inventory didn't open")
android.type("id:internal_edit_text", "storePageContext")
time.sleep(2)
android.key("back") # hides the keyboard
time.sleep(1)
# Rows: androidBrowserConfig (parent), then storePageContext.
if android.checked("trailingSwitch", 2) != on:
android.tap("id:trailingSwitch", index=2)
time.sleep(1)
state = android.checked("trailingSwitch", 2)
if state != on:
raise Error(f"storePageContext is {state}, wanted {on}")
android.shot(f"rh-setup-storepagecontext-{'on' if on else 'off'}")
s.to_browser(android)
def prompt_title(android):
"""The permission dialog's title, found by its text since the dialog has no resource ids."""
return next((t for t in (READ_PROMPT, TABS_PROMPT, HISTORY_PROMPT, "Allow Duck.ai to do the following:")
if android.visible(f"text:{t}")), None)
def allow_until_reply(android, before, label):
"""Allows every prompt shown before the reply finishes; returns (titles seen, reply)."""
seen = []
deadline = time.monotonic() + 120
quiet = 0
while time.monotonic() < deadline:
title = prompt_title(android)
if title:
quiet = 0
seen.append(title)
android.shot(f"rh-prompt-{len(seen)}-{label}")
android.tap("text:Allow in This Chat")
time.sleep(1)
continue
replied = s.said_count(android) > before and not android.visible("id:stopStreamingButton")
quiet = quiet + 1 if replied else 0
if quiet >= 3:
break
time.sleep(1)
return seen, s.wait_reply(android, before)
def open_page(android, url):
"""Opens url in a new tab; returns the page's own text, lowercased and with whitespace collapsed."""
android.open(url)
android.poll(lambda: android.web_eval("location.href") or "", lambda h: "ddgverify" in h, 20)
time.sleep(3) # page-finish collection of the page context
return " ".join((android.web_eval("document.body.innerText") or "").lower().split())
def quoted(reply):
"""The text inside the reply's first pair of quotes, or ''."""
for left, right in (("\u201c", "\u201d"), ('"', '"')):
start = reply.find(left)
end = reply.find(right, start + 1)
if start >= 0 and end > start:
return " ".join(reply[start + 1:end].split()).rstrip(".")
return ""
def run(android):
android.section("Shared steps (clienttools_steps.py)", "```python\n" + s.source().rstrip() + "\n```")
# readTabContent with nothing cached
store_page_context(android, on=False)
uncached_text = open_page(android, UNCACHED_URL)
s.new_chat(android)
android.shot("rh-01-fresh-chat")
before = s.ask(android, "Use listOpenTabs to find my tab whose address is on example.com, then use readTabContent "
"with that tabId and quote one sentence from it in double quotes. If the tool fails, say the error code.")
android.mark()
seen, reply = allow_until_reply(android, before, "uncached")
android.check("readTabContent prompt shown", READ_PROMPT in seen, str(seen))
android.expect_log("readTabContent replied unavailable with nothing cached",
r"Client tool readTabContent replied unavailable")
quote = quoted(reply)
android.check("the reply quotes no page text", not quote or quote not in uncached_text, reply[:300])
android.shot("rh-02-uncached-reply")
# readTabContent with the page cached
store_page_context(android, on=True)
page_text = open_page(android, CACHED_URL)
android.note(f"second view, the example.org page's own text (DevTools): {page_text[:200]}")
s.back_to_chat(android)
before = s.ask(android, "Use listOpenTabs to find my tab whose address is on example.org, then use readTabContent "
"with that tabId. Reply with the exact url field and one sentence of the content in double quotes.")
android.mark()
seen, reply = allow_until_reply(android, before, "cached")
android.check("readTabContent ran without a second prompt (chat grant)", READ_PROMPT not in seen, str(seen))
android.expect_log("readTabContent replied ok", r"Client tool readTabContent replied ok")
quote = quoted(reply)
android.check("the reply's quote is the page's own text", len(quote) > 15 and quote in page_text,
f"quote: {quote!r}")
android.check("the reply's url has no query or fragment",
"example.org" in reply and "ddgverify" not in reply and "#top" not in reply, reply[:400])
android.shot("rh-03-cached-reply")
# searchHistory
today = time.strftime("%Y-%m-%d", time.gmtime())
before = s.ask(android, "Use the searchHistory tool with query Example Domain. For each result reply with its "
"exact url and visitedAt fields, one per line.")
android.mark()
seen, reply = allow_until_reply(android, before, "history")
android.check("searchHistory prompt shown", HISTORY_PROMPT in seen, str(seen))
android.expect_log("searchHistory replied ok", r"Client tool searchHistory replied ok")
android.check("the reply lists both synthetic pages", "example.com" in reply and "example.org" in reply, reply[:500])
android.check("no url carries the query or fragment", "ddgverify" not in reply and "#top" not in reply, reply[:500])
android.check(f"visitedAt is today's UTC date ending in Z", f"{today}t" in reply and "z" in reply, reply[:500])
android.shot("rh-04-history-reply")
before = s.ask(android, "Use the searchHistory tool with query Example Domain, startDate 2020-01-01 and endDate "
"2020-01-02. How many results did it return? Answer with the number only.")
android.mark()
seen, reply = allow_until_reply(android, before, "history-range")
android.check("searchHistory ran without a second prompt (chat grant)", HISTORY_PROMPT not in seen, str(seen))
android.expect_log("searchHistory with a past range replied ok", r"Client tool searchHistory replied ok")
android.check("a 2020 range finds nothing", "0" in reply.replace("duck.ai said", ""), reply[:300])
android.shot("rh-05-history-range-reply")
android.unverified("readTabContent with no tabId in the contextual sheet reads the host page",
"not driven on device; covered by ReadTabContentClientToolTest")
android.unverified("searchHistory returns unavailable with history turned off",
"would change the user's history setting; covered by SearchHistoryClientToolTest")RerunPasses on this branch.
All 7 checks passed. All checks
Shared steps (clienttools_steps.py) (This branch)"""Shared paths for the Duck.ai client tools proofs (tools_all, tools_deny, tools_settings).
Setup these proofs assume, done by hand before the run (see the proof notes): Browser Tools dev screen with
aiChatBrowserTools and all seven tools on, devSkipPermissionPrompt and requestAccess off; a Custom Duck.ai URL
whose instance offers client tools and is signed in; synthetic tabs "Storage blocking test page"
(?ddgverify=bm) and "Download" (?ddgverify=deny) inside the first 50 regular tabs; a synthetic download-1.pdf.
"""
import json
import pathlib
import time
from prove import Error, verify
PROMPT_TITLE = "browserToolsPermissionsTitle"
ALLOW = "id:browserToolsPermissionsAllow"
DONT_ALLOW = "id:browserToolsPermissionsDontAllow"
SEND_BUTTONS = ("nativeInputSubmitButton", "nativeInputAskButton")
def source():
return pathlib.Path(__file__).read_text()
def to_browser(android):
for _ in range(6):
where = android.where()
if where == "BrowserActivity":
return
if where == "-":
android.launch()
continue
android.key("back")
time.sleep(1)
raise Error(f"couldn't get back to the browser, still on {android.where()}")
def menu(android):
"""The browser menu from the New Tab Page, a page, or a Duck.ai tab."""
for _ in range(2):
for button in ("inputModeWidgetNavMenu", "browserMenuImageView", "browserMenu"):
if android.visible(f"id:{button}"):
android.tap(f"id:{button}")
break
else:
android.scroll("down")
continue
if android.wait("id:settingsMenuItem", 5):
return
raise Error("the browser menu didn't open")
def chat_attached(android, timeout=30):
return android.poll(lambda: android.web_eval("location.host") or "", lambda h: h.endswith("duck.ai"), timeout)
def new_chat(android):
"""A new Duck.ai chat; stops with an error when the instance asks for sign-in instead."""
to_browser(android)
menu(android)
android.tap("id:newDuckChatMenuItem" if android.visible("id:newDuckChatMenuItem") else "id:duckAiNewChatMenuItem")
if not android.wait("id:duckAIHeader", 25):
raise Error("Duck.ai didn't open")
host = chat_attached(android)
if not host.endswith("duck.ai"):
raise Error(f"the chat page is {host}, not Duck.ai: the dev instance needs the company sign-in on the phone")
time.sleep(2)
def said_count(android):
return android.web_eval('document.body.innerText.split("Duck.ai said").length - 1') or 0
def ask(android, prompt):
"""Sends a prompt; returns how many replies the page had before it."""
before = said_count(android)
android.type("id:inputField", prompt)
button = android.poll(lambda: next((b for b in SEND_BUTTONS if android.visible(f"id:{b}")), None), bool, 10)
if not button:
raise Error("no send button appeared after typing")
android.tap(f"id:{button}")
return before
def wait_prompt(android, timeout=40):
"""The permission dialog's title when it shows within timeout, else None."""
if android.wait(f"id:{PROMPT_TITLE}", timeout):
return android.text(PROMPT_TITLE)
return None
def wait_reply(android, before, timeout=60):
"""Waits for the reply after `before` to finish streaming; returns the reply's text (lowercased)."""
last = '(() => { const t = document.body.innerText; return t.slice(t.lastIndexOf("Duck.ai said")); })()'
android.poll(lambda: said_count(android), lambda n: n > before, timeout)
deadline = time.monotonic() + timeout
previous = None
while time.monotonic() < deadline:
text = android.web_eval(last) or ""
streaming = android.visible("id:stopStreamingButton") or android.visible(f"id:{PROMPT_TITLE}")
if not streaming and text == previous and len(text) > len("Duck.ai said") + 5:
return text.lower()
previous = text
time.sleep(2)
return (previous or "").lower()
def switcher(android):
to_browser(android)
for _ in range(3):
button = next((b for b in ("inputModeWidgetNavTabs", "tabsImageView", "tabsMenu") if android.visible(f"id:{b}")), None)
if button:
android.tap(f"id:{button}")
break
android.scroll("down") # a scrolled page hides the toolbar
if android.poll(android.where, lambda w: w == "TabSwitcherActivity", 10) != "TabSwitcherActivity":
raise Error("the tab switcher didn't open")
time.sleep(1)
def switcher_top(android, swipes=20):
"""Scrolls the tab switcher to its first cards."""
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "500", "540", "2100", "80")
time.sleep(2)
def switcher_bottom(android, swipes=20):
for _ in range(swipes):
android._adb("shell", "input", "swipe", "540", "2000", "540", "400", "80")
time.sleep(2)
def tab_count(android):
value = android.text("regularTabCount")
return int(value) if value and value.isdigit() else None
def nodes(android):
out = []
def walk(n):
if isinstance(n, dict):
out.append(n)
for v in n.values():
walk(v)
elif isinstance(n, list):
for v in n:
walk(v)
walk(json.loads(verify("layout").stdout))
return out
def back_to_chat(android):
"""The last card in the tab switcher is the chat this proof opened (new tabs append at the end)."""
if android.where() != "TabSwitcherActivity":
switcher(android)
switcher_bottom(android)
cards = [n for n in nodes(android) if n.get("text") in ("Duck.ai", "New Chat") and n.get("center")]
if not cards:
raise Error("no Duck.ai card at the end of the tab switcher")
x, y = cards[-1]["center"].strip("[]").split(",")
android._adb("shell", "input", "tap", x, y)
if not android.wait("id:duckAIHeader", 15) or not chat_attached(android).endswith("duck.ai"):
raise Error("tapping the last Duck.ai card didn't return to the chat")
time.sleep(1)
def settings(android):
to_browser(android)
menu(android)
android.tap("id:settingsMenuItem")
if android.poll(android.where, lambda w: w == "SettingsActivity", 10) != "SettingsActivity":
raise Error("Settings didn't open")
time.sleep(1)
def browser_access(android):
"""Settings > AI Features > Browser Access."""
settings(android)
# Settings reopens at its last scroll position, so look further down first, then back up.
for direction in ["up"] * 6 + ["down"] * 20:
if android.visible("id:includeDuckChatSetting"):
break
android.scroll(direction)
android.tap("id:includeDuckChatSetting")
if android.poll(android.where, lambda w: w == "DuckChatSettingsActivity", 10) != "DuckChatSettingsActivity":
raise Error("AI Features didn't open")
for _ in range(4):
if android.visible("id:duckAiBrowserAccess"):
break
android.scroll("up")
android.tap("id:duckAiBrowserAccess")
if android.poll(android.where, lambda w: w == "BrowserAccessSettingsActivity", 10) != "BrowserAccessSettingsActivity":
raise Error("Browser Access didn't open")
time.sleep(1)
def access_choice(android, tool_name):
"""On Browser Access: the choice shown under a tool's row ("Always Ask", ...)."""
lines = android.lines()
for i, line in enumerate(lines):
if line[:2] == ["primaryText", tool_name]:
return next((l[1] for l in lines[i + 1:i + 2] if l[0] == "secondaryText"), None)
return None
def set_access(android, tool_name, choice):
android.tap(f"text:{tool_name}")
if not android.wait("id:radioListDialogTitle", 5):
raise Error(f"{tool_name}'s choices didn't open")
android.tap(f"text:{choice}")
android.tap("text:Save")
time.sleep(1)
def bookmarks(android):
to_browser(android)
menu(android)
for _ in range(3):
if android.visible("id:bookmarksMenuItem"):
break
android.scroll("up")
android.tap("id:bookmarksMenuItem")
if android.poll(android.where, lambda w: w == "BookmarksActivity", 10) != "BookmarksActivity":
raise Error("Bookmarks didn't open")
time.sleep(1)Proof source"""findInPage works end to end from a Duck.ai chat.
With androidBrowserConfig.storePageContext on, a page loaded afterwards is searched from its cached text: the first
call prompts once, the match count equals the occurrences in the page's own text, the snippet is the page's own
text, and a second search in the same chat runs without a prompt and finds nothing for an absent word.
Setup done before the run: Browser Tools dev screen with aiChatBrowserTools, listOpenTabs and findInPage on,
devSkipPermissionPrompt and requestAccess off; storePageContext on; a Custom Duck.ai URL whose instance offers
client tools and is signed in.
"""
import re
import time
import clienttools_steps as s
from tools_read_history import open_page, quoted
LIVE = ["Duck.ai chat (Custom Duck.ai URL dev instance)"]
PAGE_URL = "https://example.org/?ddgverify=find#top"
FIND_PROMPT = "Allow Duck.ai to search the text of your open tabs?"
BATCH_PROMPT = "Allow Duck.ai to do the following:"
TITLES = (FIND_PROMPT, BATCH_PROMPT, "Allow Duck.ai to see your open tabs?")
def prompt_title(android):
"""The title of the permission dialog on screen, found by its text since the dialog has no resource ids."""
return next((t for t in TITLES if android.visible(f"text:{t}")), None)
def allow_until_reply(android, before, label):
"""Allows every prompt before the reply ends, single-tool or batched (requestAccess); returns (prompts, reply).
A batched prompt is recorded as its title plus the tool names it lists."""
seen = []
deadline = time.monotonic() + 120
quiet = 0
while time.monotonic() < deadline:
title = prompt_title(android)
if title:
quiet = 0
if title == BATCH_PROMPT:
title += " " + str([n for n in ("Open Tabs", "Find in Page") if android.visible(f"text:{n}")])
seen.append(title)
android.shot(f"fip-prompt-{len(seen)}-{label}")
android.tap("text:Allow in This Chat")
time.sleep(1)
continue
replied = s.said_count(android) > before and not android.visible("id:stopStreamingButton")
quiet = quiet + 1 if replied else 0
if quiet >= 3:
break
time.sleep(1)
return seen, s.wait_reply(android, before)
def asked_for_find(seen):
return any(p == FIND_PROMPT or (p.startswith(BATCH_PROMPT) and "Find in Page" in p) for p in seen)
def run(android):
android.section("Shared steps (clienttools_steps.py)", "```python\n" + s.source().rstrip() + "\n```")
page_text = open_page(android, PAGE_URL)
# The cached extraction also keeps translations the page hides, so the word must not appear in them.
expected = page_text.count("monitoring")
android.note(f"second view, the page's own text (DevTools) has 'monitoring' {expected} times: {page_text[:160]}")
s.new_chat(android)
android.shot("fip-01-fresh-chat")
before = s.ask(android, "Use listOpenTabs to find my tab whose address is on example.org, then use findInPage with "
"that tabId and query monitoring. Reply with matchCount as 'count: N' and the first snippet "
"in double quotes.")
android.mark()
seen, reply = allow_until_reply(android, before, "find")
android.check("a prompt asks for findInPage (alone or batched)", asked_for_find(seen), str(seen))
android.expect_log("findInPage replied ok", r"Client tool findInPage replied ok")
count = re.search(r"count:\s*(\d+)", reply)
android.check("matchCount equals the occurrences in the page's own text",
count is not None and int(count.group(1)) == expected, f"reply count {count and count.group(1)}, page {expected}")
snippet = quoted(reply)
android.check("the snippet is the page's own text and contains the query",
"monitoring" in snippet and snippet.rstrip(".…") in page_text, f"snippet: {snippet!r}")
android.shot("fip-02-find-reply")
before = s.ask(android, "Use findInPage on the same tab with query zebraquokka. Reply with 'count: N' only.")
android.mark()
seen, reply = allow_until_reply(android, before, "find-absent")
android.check("the second search runs without a prompt (chat grant)", not asked_for_find(seen), str(seen))
android.expect_log("findInPage replied ok for an absent word", r"Client tool findInPage replied ok")
android.check("an absent word finds nothing", re.search(r"count:\s*0\b", reply) is not None, reply[:200])
android.shot("fip-03-absent-reply")
android.unverified("findInPage with storePageContext off replies unavailable",
"same CachedTabPages path the readTabContent proof covered on this device; unit tested")Rerun |
The client tools contract changed the requestAccess result from a
granted list to an access map with one level per requested capability:
default, always, chat, never or notGranted. The server validates results
strictly, so the old {"granted": [...]} reply made every continuation
after a requestAccess prompt fail with a 400.
Capabilities this build can't serve, and ones removed from the prompt,
report notGranted. Naming an ask-every-time tool (openTab, bookmarkTab)
now fails with invalid_arguments, as the contract requires.
Verified: clienttools unit tests pass (219). On device against a
Duck.ai instance with client tools, the continuation carries
{"access":{"listOpenTabs":"chat"}}, the server answers 200 and the
model lists the open tabs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Duck.ai's Change button sends openAIChatSettings with the section browserPermissions. The app ignored the section and always opened AI Settings, so the user had to find Browser Access themselves. That section now opens Browser Access directly and leaves the chat open, so Back returns to the conversation. Any other or missing section still opens AI Settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Task/Issue URL: https://app.asana.com/1/137249556945/project/1174433894299346/task/1220725305869255
Tech Design URL (if applicable):
API Proposals URL(s) (if applicable):
Description
Adds readTabContent, findInPage and searchHistory Duck.ai client tools, each behind its own aiChatBrowserTools sub-feature (off by default). Stacked on #10628.
readTabContent and findInPage read a tab's text from the page context the browser caches per tab, because background tabs have no live WebView on Android. That cache only fills while androidBrowserConfig.storePageContext is on, so with that flag at its default (off) both tools always reply unavailable.
Also replies to requestAccess with the access map the server now expects, {"access":{"":""}} with one level per requested tool (default, always, chat, never or notGranted), and rejects requestAccess naming an ask-every-time tool (openTab, bookmarkTab) as invalid_arguments. On-device evidence for all ten tools, including deny then regrant from Browser Access: https://artifacts.go.duckduckgo.com/view/auto/16ea006d-01ce-4d37-810e-e40a977b0e59/verify-android/evidence-report.md
Steps to test this PR
Setup
readTabContent
findInPage
searchHistory
requestAccess
Browser Access
UI changes
Three new rows in Browser Access and three new permission prompts. The strings are in donottranslate.xml until they go out for translation.
🤖 Generated with Claude Code