Initial import: opencode Chrome extension + native host (browser MCP bridge)
This commit is contained in:
commit
ee5b79570c
41 files changed
+6845
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>Connect opencode?</title><link rel="stylesheet" href="ui.css"></head>
|
||||
<body>
|
||||
<h1>Use this browser for opencode?</h1>
|
||||
<p>An opencode session asked to choose a browser for automation. Connect to let it control tabs in this browser.</p>
|
||||
<label for="name">Name this browser</label>
|
||||
<input id="name" maxlength="80">
|
||||
<div class="row"><button id="no">Not this one</button><button id="yes" class="primary">Connect</button></div>
|
||||
<script src="connect.js"></script>
|
||||
</body></html>
|
||||
@@ -0,0 +1,13 @@
|
||||
const params = new URLSearchParams(location.search);
|
||||
const requestId = params.get("request");
|
||||
const nameInput = document.getElementById("name");
|
||||
nameInput.value = params.get("name") || "";
|
||||
|
||||
async function answer(accepted) {
|
||||
await chrome.runtime.sendMessage({ type: "connect_answer", requestId, accepted, name: nameInput.value.trim() });
|
||||
window.close();
|
||||
}
|
||||
|
||||
document.getElementById("yes").addEventListener("click", () => answer(true));
|
||||
document.getElementById("no").addEventListener("click", () => answer(false));
|
||||
nameInput.addEventListener("keydown", (e) => e.key === "Enter" && answer(true));
|
||||
@@ -0,0 +1,599 @@
|
||||
// Content script: accessibility tree (read_page), element refs, natural
|
||||
// language element search (find), form filling, page text, and point/ref
|
||||
// geometry for the background worker. Runs in the extension's isolated world.
|
||||
|
||||
(function () {
|
||||
if (window.__ocbContentLoaded) return;
|
||||
window.__ocbContentLoaded = true;
|
||||
|
||||
// --- Element refs ---
|
||||
// Stable per page: an element keeps its ref across calls, held weakly so a
|
||||
// removed element can be garbage collected.
|
||||
let refCounter = 0;
|
||||
const elementMap = {}; // ref -> WeakRef<Element>
|
||||
const reverseMap = new WeakMap(); // Element -> ref
|
||||
|
||||
function getOrAssignRef(el) {
|
||||
const existing = reverseMap.get(el);
|
||||
if (existing && elementMap[existing]?.deref() === el) return existing;
|
||||
const ref = `ref_${++refCounter}`;
|
||||
elementMap[ref] = new WeakRef(el);
|
||||
reverseMap.set(el, ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
function resolveRef(ref) {
|
||||
const el = elementMap[ref]?.deref();
|
||||
if (!el) {
|
||||
delete elementMap[ref];
|
||||
return null;
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
// --- Roles and names ---
|
||||
// Matches what the official extension prints: HTML-derived roles (no
|
||||
// separate searchbox/spinbutton/slider), "generic" for everything without
|
||||
// one, and names in its order (placeholder before <label for>, the value
|
||||
// after both).
|
||||
const TAG_TO_ROLE = {
|
||||
a: "link", button: "button", textarea: "textbox", select: "combobox", img: "image",
|
||||
h1: "heading", h2: "heading", h3: "heading", h4: "heading", h5: "heading", h6: "heading",
|
||||
nav: "navigation", main: "main", header: "banner", footer: "contentinfo", aside: "complementary",
|
||||
section: "region", article: "article", form: "form", label: "label", ul: "list", ol: "list",
|
||||
li: "listitem", table: "table", dialog: "dialog"
|
||||
};
|
||||
const INPUT_ROLES = { checkbox: "checkbox", radio: "radio", button: "button", submit: "button", reset: "button", image: "button", file: "button" };
|
||||
const SKIP_TAGS = new Set(["script", "style", "noscript", "template", "head", "meta", "link", "br", "title", "ocb-agent-overlay"]);
|
||||
const INTERACTIVE_ROLES = new Set([
|
||||
"button", "link", "textbox", "searchbox", "checkbox", "radio", "tab", "menuitem", "menuitemcheckbox",
|
||||
"menuitemradio", "switch", "combobox", "slider", "spinbutton", "option", "treeitem", "listbox"
|
||||
]);
|
||||
|
||||
function getRole(el) {
|
||||
const explicit = el.getAttribute("role");
|
||||
if (explicit && explicit.trim()) return explicit.trim().split(/\s+/)[0];
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag === "input") return INPUT_ROLES[str(el.type).toLowerCase()] || "textbox";
|
||||
if (tag === "a" && !el.hasAttribute("href")) return "generic";
|
||||
return TAG_TO_ROLE[tag] || "generic";
|
||||
}
|
||||
|
||||
const str = (v) => (typeof v === "string" ? v : "");
|
||||
const clean = (s) => String(s || "").replace(/\s+/g, " ").trim();
|
||||
const cap = (s) => (s.length > 100 ? s.slice(0, 100) + "..." : s);
|
||||
|
||||
function directText(el) {
|
||||
let t = "";
|
||||
for (const n of el.childNodes) if (n.nodeType === 3) t += n.textContent;
|
||||
return clean(t);
|
||||
}
|
||||
|
||||
function getAccessibleName(el, role = getRole(el)) {
|
||||
const aria = el.getAttribute("aria-label");
|
||||
if (aria && aria.trim()) return cap(clean(aria));
|
||||
const labelledBy = el.getAttribute("aria-labelledby");
|
||||
if (labelledBy) {
|
||||
const t = labelledBy.split(/\s+/).map((id) => clean(document.getElementById(id)?.textContent)).filter(Boolean).join(" ");
|
||||
if (t) return cap(t);
|
||||
}
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (tag === "select") {
|
||||
const o = el.options[el.selectedIndex] || el.options[0];
|
||||
return o ? cap(clean(o.textContent)) : "";
|
||||
}
|
||||
if (tag === "input" || tag === "textarea") {
|
||||
const type = str(el.type).toLowerCase();
|
||||
if (type === "file") return "";
|
||||
if (str(el.placeholder).trim()) return cap(clean(el.placeholder));
|
||||
if (el.id) {
|
||||
const label = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
||||
if (label && clean(label.textContent)) return cap(clean(label.textContent));
|
||||
}
|
||||
if (str(el.title).trim()) return cap(clean(el.title));
|
||||
if (el.value) return type === "password" ? "[value redacted]" : cap(clean(el.value));
|
||||
return "";
|
||||
}
|
||||
if (tag === "img") return cap(clean(str(el.alt) || str(el.title)));
|
||||
if (role === "link" && str(el.title).trim()) return cap(clean(el.title));
|
||||
if (["link", "button", "heading", "option"].includes(role)) {
|
||||
const t = clean(el.textContent);
|
||||
if (t) return cap(t);
|
||||
} else {
|
||||
const t = directText(el);
|
||||
if (t) return cap(t);
|
||||
}
|
||||
return cap(clean(str(el.title)));
|
||||
}
|
||||
|
||||
function isInteractive(el) {
|
||||
return INTERACTIVE_ROLES.has(getRole(el));
|
||||
}
|
||||
|
||||
function isVisible(el) {
|
||||
const style = getComputedStyle(el);
|
||||
if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
|
||||
if (parseFloat(style.opacity) === 0) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width === 0 && r.height === 0 && style.overflow !== "visible") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function inViewport(el) {
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
|
||||
}
|
||||
|
||||
// --- read_page ---
|
||||
const q = (v) => String(v).replace(/"/g, '\\"');
|
||||
|
||||
function describeLine(el, role, name) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
let line = role;
|
||||
if (name) line += ` "${q(name)}"`;
|
||||
line += ` [${getOrAssignRef(el)}]`;
|
||||
if (tag === "a" && el.hasAttribute("href")) line += ` href="${q(el.getAttribute("href"))}"`;
|
||||
if (["input", "button"].includes(tag) && el.hasAttribute("type")) line += ` type="${q(el.getAttribute("type"))}"`;
|
||||
if (["input", "textarea"].includes(tag) && el.hasAttribute("placeholder")) line += ` placeholder="${q(el.getAttribute("placeholder"))}"`;
|
||||
return line;
|
||||
}
|
||||
|
||||
function optionLines(select, indent) {
|
||||
return Array.from(select.options).map((o) => {
|
||||
let line = `${indent}option "${q(clean(o.textContent))}"`;
|
||||
if (o.selected) line += " (selected)";
|
||||
if (o.hasAttribute("value")) line += ` value="${q(o.getAttribute("value"))}"`;
|
||||
return line;
|
||||
});
|
||||
}
|
||||
|
||||
function generateAccessibilityTree(options = {}) {
|
||||
const filter = options.filter === "interactive" ? "interactive" : "all";
|
||||
const maxDepth = Number(options.depth) > 0 ? Number(options.depth) : 15;
|
||||
const maxChars = Number(options.max_chars) > 0 ? Number(options.max_chars) : 50000;
|
||||
const lines = [];
|
||||
|
||||
function children(el) {
|
||||
const out = [...(el.shadowRoot?.children || []), ...el.children];
|
||||
if (el.tagName === "IFRAME") {
|
||||
try {
|
||||
if (el.contentDocument?.body) out.push(...el.contentDocument.body.children);
|
||||
} catch {}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function walk(el, depth, indent) {
|
||||
if (!el || el.nodeType !== 1 || depth > maxDepth) return;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (SKIP_TAGS.has(tag) || (tag === "input" && str(el.type).toLowerCase() === "hidden")) return;
|
||||
const role = getRole(el);
|
||||
if (filter === "interactive") {
|
||||
if (INTERACTIVE_ROLES.has(role) && isVisible(el) && inViewport(el)) {
|
||||
lines.push(describeLine(el, role, getAccessibleName(el, role)));
|
||||
if (tag === "select") lines.push(...optionLines(el, " "));
|
||||
}
|
||||
if (tag !== "select") for (const c of children(el)) walk(c, depth + 1, indent);
|
||||
return;
|
||||
}
|
||||
const name = getAccessibleName(el, role);
|
||||
const shown = role !== "generic" || !!name;
|
||||
if (shown) lines.push(indent + describeLine(el, role, name));
|
||||
const next = shown ? indent + " " : indent;
|
||||
if (tag === "select") {
|
||||
lines.push(...optionLines(el, next));
|
||||
if (el.multiple) return;
|
||||
}
|
||||
for (const c of children(el)) walk(c, depth + 1, next);
|
||||
}
|
||||
|
||||
if (options.ref_id) {
|
||||
const root = resolveRef(options.ref_id);
|
||||
if (!root) return { error: `No element found with reference: "${options.ref_id}". The element may have been removed from the page.` };
|
||||
walk(root, 1, "");
|
||||
} else {
|
||||
for (const c of (document.body || document.documentElement).children) walk(c, 1, "");
|
||||
}
|
||||
|
||||
const full = lines.join("\n");
|
||||
if (full.length <= maxChars) return { tree: full };
|
||||
// Cut at a line boundary and say how much was left out.
|
||||
let cut = full.lastIndexOf("\n", maxChars);
|
||||
if (cut <= 0) cut = maxChars;
|
||||
return {
|
||||
tree:
|
||||
full.slice(0, cut) +
|
||||
`\n\n[Output truncated: showing ${cut} of ${full.length} characters. Pass a larger max_chars, ` +
|
||||
`or use depth/ref_id (or filter: "interactive") to focus on part of the page.]`
|
||||
};
|
||||
}
|
||||
|
||||
// --- get_page_text ---
|
||||
function getPageText() {
|
||||
const candidates = ["article", "main", '[role="main"]', '[itemprop="articleBody"]', '[class*="article-body"]', '[class*="post-content"]', '[class*="entry-content"]', "#content", ".content"];
|
||||
let source = null;
|
||||
for (const sel of candidates) {
|
||||
const el = document.querySelector(sel);
|
||||
if (el && clean(el.innerText || "").length > 200) {
|
||||
source = el;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!source) source = document.body;
|
||||
const text = (source.innerText || source.textContent || "")
|
||||
.replace(/[ \t]+\n/g, "\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
return { title: document.title || "", url: location.href, sourceTag: source.tagName.toLowerCase(), text: text.slice(0, 200000) };
|
||||
}
|
||||
|
||||
// --- find ---
|
||||
const STOP = new Set(["the", "a", "an", "of", "on", "in", "to", "for", "with", "and", "or", "that", "which", "is", "this", "page", "element", "containing", "contains", "named", "called", "labeled", "labelled", "text", "says", "saying", "at", "top", "bottom", "near"]);
|
||||
const ROLE_WORDS = {
|
||||
button: ["button"], btn: ["button"], link: ["link"], links: ["link"],
|
||||
input: ["textbox", "searchbox", "combobox", "spinbutton"], field: ["textbox", "searchbox", "combobox", "spinbutton"],
|
||||
textbox: ["textbox", "searchbox"], textarea: ["textbox"], box: ["textbox", "searchbox", "combobox", "checkbox"],
|
||||
bar: ["textbox", "searchbox", "navigation", "toolbar"], checkbox: ["checkbox", "switch"], toggle: ["switch", "checkbox", "button"],
|
||||
switch: ["switch", "checkbox"], radio: ["radio"], dropdown: ["combobox", "listbox", "button"], select: ["combobox", "listbox"],
|
||||
menu: ["menu", "menubar", "menuitem", "button", "navigation"], tab: ["tab"], tabs: ["tab", "tablist"],
|
||||
image: ["image"], img: ["image"], icon: ["image", "button", "link"], logo: ["image", "link"], picture: ["image"], photo: ["image"],
|
||||
heading: ["heading"], header: ["heading", "banner"], title: ["heading"], dialog: ["dialog"], modal: ["dialog"],
|
||||
popup: ["dialog", "menu"], slider: ["slider"], list: ["list", "listbox"], item: ["listitem", "option", "menuitem"],
|
||||
option: ["option"], row: ["row"], table: ["table"], form: ["form"], navigation: ["navigation"], nav: ["navigation"],
|
||||
video: ["video"], searchbar: ["searchbox", "textbox"]
|
||||
};
|
||||
|
||||
function tokens(s) {
|
||||
return String(s || "")
|
||||
.toLowerCase()
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
||||
.split(/[^\p{L}\p{N}]+/u)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function collectAll(root, out = []) {
|
||||
for (const el of root.querySelectorAll("*")) {
|
||||
out.push(el);
|
||||
if (el.shadowRoot) collectAll(el.shadowRoot, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function findElements(query) {
|
||||
// Refs are handed out in page order, as the official extension's find
|
||||
// does (it reads the whole tree first, starting with <body>).
|
||||
if (document.body) getOrAssignRef(document.body);
|
||||
generateAccessibilityTree({ filter: "all" });
|
||||
const qTokens = tokens(query);
|
||||
const roleHints = new Set();
|
||||
const content = [];
|
||||
for (const t of qTokens) {
|
||||
if (ROLE_WORDS[t]) ROLE_WORDS[t].forEach((r) => roleHints.add(r));
|
||||
if (!STOP.has(t)) content.push(t);
|
||||
}
|
||||
// Words that only name a role ("button") shouldn't also have to appear in
|
||||
// the element's text, but they count when they do ("Search" button).
|
||||
const contentOnly = content.filter((t) => !ROLE_WORDS[t]);
|
||||
const phrase = clean(String(query).toLowerCase());
|
||||
const scored = [];
|
||||
|
||||
for (const el of collectAll(document)) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (["script", "style", "noscript", "template", "head", "meta", "link", "html", "body", "br"].includes(tag)) continue;
|
||||
// Hidden file inputs are the usual kind (a styled button opens them),
|
||||
// and file_upload needs their ref, so they stay findable.
|
||||
const hiddenFileInput = tag === "input" && str(el.type).toLowerCase() === "file";
|
||||
if (!hiddenFileInput && !isVisible(el)) continue;
|
||||
const role = getRole(el);
|
||||
const name = getAccessibleName(el, role);
|
||||
const interactive = isInteractive(el);
|
||||
// Text is only a fair signal for small elements: a big container
|
||||
// "contains" everything below it and would always win.
|
||||
const rawText = clean(el.innerText || "");
|
||||
const ownText = rawText.length <= 160 ? rawText : "";
|
||||
const fields = {
|
||||
name: tokens(name),
|
||||
hint: tokens([str(el.placeholder), el.getAttribute("aria-label"), str(el.title), str(el.alt), el.getAttribute("aria-placeholder")].join(" ")),
|
||||
attrs: tokens([el.id, typeof el.className === "string" ? el.className : "", el.getAttribute("name"), el.getAttribute("data-testid"), str(el.type), tag].join(" ")),
|
||||
text: tokens(ownText),
|
||||
value: tokens(tag === "input" || tag === "textarea" ? str(el.value) : "")
|
||||
};
|
||||
let score = 0;
|
||||
let matched = 0;
|
||||
for (const t of content) {
|
||||
const hit = (arr) => arr.some((w) => w === t || (t.length > 3 && w.startsWith(t)) || (w.length > 3 && t.startsWith(w)));
|
||||
let s = 0;
|
||||
if (hit(fields.name)) s = 3;
|
||||
else if (hit(fields.hint)) s = 2.5;
|
||||
else if (hit(fields.text)) s = 2;
|
||||
else if (hit(fields.value)) s = 1.5;
|
||||
else if (hit(fields.attrs)) s = 1;
|
||||
if (s) matched++;
|
||||
score += s;
|
||||
}
|
||||
const roleMatch = roleHints.size > 0 && (roleHints.has(role) || (roleHints.has("textbox") && ["input", "textarea"].includes(tag)));
|
||||
if (contentOnly.length && !contentOnly.some((t) => [...fields.name, ...fields.hint, ...fields.text, ...fields.value, ...fields.attrs].some((w) => w === t || (t.length > 3 && w.startsWith(t)) || (w.length > 3 && t.startsWith(w))))) continue;
|
||||
if (!matched && !roleMatch) continue;
|
||||
if (roleMatch) score += 3;
|
||||
else if (roleHints.size) score -= 1.5;
|
||||
if (interactive) score += 1;
|
||||
if (phrase.length > 2 && (name.toLowerCase().includes(phrase) || ownText.toLowerCase().includes(phrase))) score += 3;
|
||||
if (content.length) score *= 0.5 + 0.5 * (matched / content.length);
|
||||
if (score <= 0.5) continue;
|
||||
scored.push({ el, score, role, name, text: ownText });
|
||||
}
|
||||
|
||||
// A match whose best signal came from text is usually also matched by
|
||||
// its wrapper; keep the innermost one.
|
||||
scored.sort((a, b) => b.score - a.score);
|
||||
// Nested matches: a wrapper whose visible text is the same as its
|
||||
// child's is the same thing on screen, and the child is the precise
|
||||
// target (the wrapper's centre can be empty space). Otherwise keep the
|
||||
// better-scoring one unless the two score about the same.
|
||||
const kept = [];
|
||||
for (const s of scored) {
|
||||
const i = kept.findIndex((k) => k.el.contains(s.el) || s.el.contains(k.el));
|
||||
if (i === -1) {
|
||||
kept.push(s);
|
||||
continue;
|
||||
}
|
||||
const k = kept[i];
|
||||
const inner = k.el.contains(s.el) ? s : k;
|
||||
const outer = inner === s ? k : s;
|
||||
if (inner.text && inner.text === outer.text) {
|
||||
kept[i] = { ...inner, score: Math.max(k.score, s.score) };
|
||||
} else if (Math.abs(k.score - s.score) >= 1.5) {
|
||||
kept.push(s);
|
||||
}
|
||||
}
|
||||
kept.sort((a, b) => b.score - a.score);
|
||||
// A <label> adds nothing when the control it labels is already listed.
|
||||
for (let i = kept.length - 1; i >= 0; i--) {
|
||||
const ctrl = kept[i].el.tagName === "LABEL" && kept[i].el.control;
|
||||
if (ctrl && kept.some((k) => k.el === ctrl)) kept.splice(i, 1);
|
||||
}
|
||||
const total = kept.length;
|
||||
const results = kept.slice(0, 20).map(({ el, role, name }) => ({
|
||||
ref: getOrAssignRef(el),
|
||||
role,
|
||||
name,
|
||||
type: el.tagName === "INPUT" ? str(el.type).toLowerCase() : null,
|
||||
label: el.labels?.[0] ? clean(el.labels[0].textContent) : null
|
||||
}));
|
||||
return { results, total };
|
||||
}
|
||||
|
||||
// --- form_input ---
|
||||
function findInputInside(el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
if (["input", "textarea", "select"].includes(tag) || el.isContentEditable) return el;
|
||||
const root = el.shadowRoot || el;
|
||||
const inner = root.querySelector("input, textarea, select, [contenteditable='true']");
|
||||
if (inner) return inner;
|
||||
for (const child of root.querySelectorAll("*")) {
|
||||
const deep = child.shadowRoot?.querySelector("input, textarea, select");
|
||||
if (deep) return deep;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Messages follow the official extension's wording.
|
||||
function setFormValue(ref, value) {
|
||||
const el = resolveRef(ref);
|
||||
if (!el) return { error: `No element found with reference: "${ref}". The element may have been removed from the page.` };
|
||||
try {
|
||||
el.scrollIntoView({ block: "center", behavior: "instant" });
|
||||
} catch {}
|
||||
const target = el.tagName === "BUTTON" ? el : findInputInside(el) || el;
|
||||
const tag = target.tagName.toLowerCase();
|
||||
const type = str(target.type).toLowerCase();
|
||||
const fire = () => {
|
||||
target.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
|
||||
target.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
|
||||
};
|
||||
|
||||
if (tag === "select") {
|
||||
const want = String(value);
|
||||
const opts = Array.from(target.options);
|
||||
const opt = opts.find((o) => o.value === want) || opts.find((o) => clean(o.textContent) === want) ||
|
||||
opts.find((o) => clean(o.textContent).toLowerCase() === want.toLowerCase());
|
||||
if (!opt) {
|
||||
return { error: `Option "${want}" not found. Available options: ${opts.map((o) => `"${clean(o.textContent)}" (value: "${o.value}")`).join(", ")}` };
|
||||
}
|
||||
const previous = target.value;
|
||||
target.value = opt.value;
|
||||
fire();
|
||||
return { message: `Selected option "${opt.value}" in dropdown (previous: "${previous}")` };
|
||||
}
|
||||
if (tag === "input" && type === "checkbox") {
|
||||
const previous = target.checked;
|
||||
const shouldCheck = typeof value === "boolean" ? value : String(value).toLowerCase() === "true";
|
||||
if (target.checked !== shouldCheck) target.click();
|
||||
return { message: `Checkbox ${target.checked ? "checked" : "unchecked"} (previous: ${previous})` };
|
||||
}
|
||||
if (tag === "input" && type === "radio") {
|
||||
const shouldCheck = typeof value === "boolean" ? value : String(value).toLowerCase() !== "false";
|
||||
if (shouldCheck && !target.checked) target.click();
|
||||
return { message: "ok" };
|
||||
}
|
||||
if (tag === "input" && type === "file") return { error: `Element type "INPUT" (file) is not a supported form input; use file_upload` };
|
||||
if (tag === "input" || tag === "textarea") {
|
||||
const previous = target.value;
|
||||
target.focus();
|
||||
const proto = tag === "textarea" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
||||
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
|
||||
if (setter) setter.call(target, String(value));
|
||||
else target.value = String(value);
|
||||
fire();
|
||||
if (type === "range") return { message: "ok" };
|
||||
return { message: `Set ${tag === "textarea" ? "textarea" : type || "text"} value to "${target.value}" (previous: "${previous}")` };
|
||||
}
|
||||
if (target.isContentEditable) {
|
||||
const previous = target.textContent;
|
||||
target.focus();
|
||||
target.textContent = String(value);
|
||||
fire();
|
||||
return { message: `Set contenteditable value to "${target.textContent}" (previous: "${previous}")` };
|
||||
}
|
||||
return { error: `Element type "${target.tagName}" is not a supported form input` };
|
||||
}
|
||||
|
||||
// --- geometry ---
|
||||
function describeBrief(el) {
|
||||
const id = el.id ? `#${el.id}` : "";
|
||||
const cls = typeof el.className === "string" && el.className.trim() ? "." + el.className.trim().split(/\s+/)[0] : "";
|
||||
const t = clean(el.textContent || "").slice(0, 40);
|
||||
return `<${el.tagName.toLowerCase()}${id}${cls}>${t ? ` "${t}"` : ""}`;
|
||||
}
|
||||
|
||||
// Centre of a ref'd element, scrolled into view first (a person scrolls
|
||||
// before clicking, and an off-screen point can't be clicked at all).
|
||||
function getRefCoordinates(ref, scroll = true) {
|
||||
const el = resolveRef(ref);
|
||||
if (!el) return null;
|
||||
if (scroll) {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.left < 0 || r.top < 0 || r.right > innerWidth || r.bottom > innerHeight) {
|
||||
try {
|
||||
el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
|
||||
} catch {
|
||||
el.scrollIntoView(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
const r = el.getBoundingClientRect();
|
||||
const x = Math.round(r.x + r.width / 2);
|
||||
const y = Math.round(r.y + r.height / 2);
|
||||
const reachable = x >= 0 && y >= 0 && x < innerWidth && y < innerHeight;
|
||||
let covering = null;
|
||||
if (reachable) {
|
||||
const at = document.elementFromPoint(x, y);
|
||||
if (at && at !== el && !el.contains(at) && !at.contains(el)) covering = describeBrief(at);
|
||||
}
|
||||
return { x, y, reachable, covering };
|
||||
}
|
||||
|
||||
// --- agent overlay ---
|
||||
// Same look as the official extension's: a pulsing orange glow around the
|
||||
// viewport and an orange "phantom" cursor that glides to where the agent
|
||||
// acts. Unlike the official one it is not touched for screenshots (that
|
||||
// made the glow blink). Closed shadow root: page CSS can't touch it, and
|
||||
// pointer-events:none keeps it out of input and hit tests.
|
||||
const GLOW = "217, 119, 87";
|
||||
const CURSOR_MS = 180;
|
||||
const ARROW = "M0 0 L0 18 L4.5 14 L7.5 21.5 L11 20 L8 13 L14 13 Z";
|
||||
let overlayHost = null;
|
||||
let overlayParts = null;
|
||||
let cursorPos = null;
|
||||
|
||||
function ensureOverlay() {
|
||||
if (overlayHost?.isConnected) return overlayParts;
|
||||
overlayHost = document.createElement("ocb-agent-overlay");
|
||||
overlayHost.style.cssText = "all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483646;";
|
||||
const root = overlayHost.attachShadow({ mode: "closed" });
|
||||
root.innerHTML = `
|
||||
<style>
|
||||
@keyframes pulse { 0%, 100% { opacity: .6; } 50% { opacity: 1; } }
|
||||
.glow { position: fixed; inset: 0; pointer-events: none; opacity: 0; transition: opacity .3s ease-in-out; }
|
||||
.glow-inner { position: absolute; inset: 0; will-change: opacity; animation: pulse 2s ease-in-out infinite;
|
||||
box-shadow: rgba(${GLOW}, .7) 0 0 15px inset, rgba(${GLOW}, .5) 0 0 25px inset, rgba(${GLOW}, .2) 0 0 35px inset; }
|
||||
@media (prefers-reduced-motion: reduce) { .glow-inner { animation: none; } }
|
||||
.cursor { position: fixed; top: 0; left: 0; pointer-events: none; will-change: transform;
|
||||
transition: transform ${CURSOR_MS}ms cubic-bezier(.2, 0, 0, 1); }
|
||||
.cursor svg { position: absolute; top: 0; left: 0; overflow: visible; }
|
||||
.styled { filter: drop-shadow(rgba(${GLOW}, .9) 0 0 4px) drop-shadow(rgba(${GLOW}, .45) 0 0 10px); }
|
||||
</style>
|
||||
<div>
|
||||
<div class="glow"><div class="glow-inner"></div></div>
|
||||
<div class="cursor" aria-hidden="true">
|
||||
<svg class="styled" width="20" height="26" viewBox="0 0 20 26">
|
||||
<path d="${ARROW}" stroke="#D97757" stroke-width="3" stroke-linejoin="round" fill="#D97757"/>
|
||||
<path d="${ARROW}" fill="#FAF9F5"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>`;
|
||||
overlayParts = { glow: root.querySelector(".glow"), cursor: root.querySelector(".cursor") };
|
||||
(document.documentElement || document.body).appendChild(overlayHost);
|
||||
// A new page starts with the cursor in the middle of the viewport.
|
||||
cursorPos ??= { x: Math.round(innerWidth / 2), y: Math.round(innerHeight / 2) };
|
||||
placeCursor(cursorPos.x, cursorPos.y, false);
|
||||
return overlayParts;
|
||||
}
|
||||
|
||||
function placeCursor(x, y, animate) {
|
||||
const { cursor } = overlayParts;
|
||||
cursor.style.transition = animate ? "" : "none";
|
||||
cursor.style.transform = `translate3d(${x}px, ${y}px, 0)`;
|
||||
cursorPos = { x, y };
|
||||
}
|
||||
|
||||
const overlay = {
|
||||
// The agent is working in this tab: glow on, cursor shown. It stays until
|
||||
// the session ends.
|
||||
active() {
|
||||
const p = ensureOverlay();
|
||||
p.glow.style.opacity = "1";
|
||||
return { ok: true };
|
||||
},
|
||||
off() {
|
||||
overlayHost?.remove();
|
||||
overlayHost = null;
|
||||
overlayParts = null;
|
||||
return { ok: true };
|
||||
},
|
||||
// Glide the cursor to (x, y) and resolve once it has arrived, so the
|
||||
// input the worker dispatches next lands as the cursor gets there.
|
||||
async move(m) {
|
||||
const p = overlay.active() && overlayParts;
|
||||
const dist = Math.hypot(m.x - cursorPos.x, m.y - cursorPos.y);
|
||||
placeCursor(m.x, m.y, true);
|
||||
if (dist > 1) await new Promise((r) => setTimeout(r, CURSOR_MS));
|
||||
return { ok: !!p };
|
||||
}
|
||||
};
|
||||
|
||||
// --- messages ---
|
||||
const handlers = {
|
||||
overlay: (m) => (overlay[m.op] ? overlay[m.op](m) : { ok: false }),
|
||||
readPage: (m) => generateAccessibilityTree(m.options || {}),
|
||||
getPageText: () => getPageText(),
|
||||
find: (m) => findElements(m.query || ""),
|
||||
setFormValue: (m) => setFormValue(m.ref, m.value),
|
||||
refCoordinates: (m) => getRefCoordinates(m.ref, m.scroll !== false),
|
||||
scrollToRef: (m) => {
|
||||
const el = resolveRef(m.ref);
|
||||
if (!el) return { ok: false };
|
||||
el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
|
||||
return { ok: true, desc: describeBrief(el) };
|
||||
},
|
||||
// Stamp a DOM attribute on a ref'd element so the worker can find it via
|
||||
// CDP (which runs in the main world and can't see this world's refs).
|
||||
markElement: (m) => {
|
||||
const el = resolveRef(m.ref);
|
||||
if (!el) return { ok: false };
|
||||
document.querySelectorAll("[data-ocb-target]").forEach((e) => e.removeAttribute("data-ocb-target"));
|
||||
el.setAttribute("data-ocb-target", "1");
|
||||
return {
|
||||
ok: true,
|
||||
tag: el.tagName.toLowerCase(),
|
||||
isFileInput: el.tagName.toLowerCase() === "input" && str(el.type).toLowerCase() === "file"
|
||||
};
|
||||
},
|
||||
unmarkElement: () => {
|
||||
document.querySelectorAll("[data-ocb-target]").forEach((e) => e.removeAttribute("data-ocb-target"));
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
|
||||
const h = msg && msg.__ocb && handlers[msg.type];
|
||||
if (!h) return false;
|
||||
Promise.resolve()
|
||||
.then(() => h(msg))
|
||||
.then(
|
||||
(result) => sendResponse({ result }),
|
||||
(e) => sendResponse({ error: String(e && e.message) })
|
||||
);
|
||||
return true;
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,124 @@
|
||||
// Turns recorded frames into an animated GIF with the overlays gif_creator
|
||||
// describes: orange click circles, red drag arrows, black action labels, an
|
||||
// orange progress bar and a small watermark.
|
||||
|
||||
import { GIFEncoder, quantize, applyPalette } from "./vendor/gifenc.js";
|
||||
|
||||
const MAX_WIDTH = 800;
|
||||
const ORANGE = "#f97316";
|
||||
|
||||
function drawLabel(ctx, text, w, h) {
|
||||
ctx.font = "600 14px -apple-system, Segoe UI, Roboto, sans-serif";
|
||||
const pad = 8;
|
||||
const t = text.length > 90 ? text.slice(0, 87) + "…" : text;
|
||||
const tw = Math.min(ctx.measureText(t).width, w - 2 * pad - 16);
|
||||
ctx.fillStyle = "rgba(0,0,0,0.78)";
|
||||
ctx.fillRect(8, h - 44, tw + 2 * pad, 28);
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(t, 8 + pad, h - 30, w - 2 * pad - 16);
|
||||
}
|
||||
|
||||
function drawClick(ctx, x, y) {
|
||||
ctx.strokeStyle = ORANGE;
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, 14, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = "rgba(249,115,22,0.35)";
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, 6, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
function drawArrow(ctx, sx, sy, ex, ey) {
|
||||
ctx.strokeStyle = "#ef4444";
|
||||
ctx.fillStyle = "#ef4444";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(sx, sy);
|
||||
ctx.lineTo(ex, ey);
|
||||
ctx.stroke();
|
||||
const a = Math.atan2(ey - sy, ex - sx);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(ex, ey);
|
||||
ctx.lineTo(ex - 14 * Math.cos(a - 0.4), ey - 14 * Math.sin(a - 0.4));
|
||||
ctx.lineTo(ex - 14 * Math.cos(a + 0.4), ey - 14 * Math.sin(a + 0.4));
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
function drawWatermark(ctx, w) {
|
||||
ctx.font = "600 12px -apple-system, Segoe UI, Roboto, sans-serif";
|
||||
const text = "opencode";
|
||||
const tw = ctx.measureText(text).width;
|
||||
ctx.fillStyle = "rgba(0,0,0,0.45)";
|
||||
ctx.fillRect(w - tw - 20, 8, tw + 12, 20);
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(text, w - tw - 14, 18);
|
||||
}
|
||||
|
||||
async function decode(frame) {
|
||||
const blob = await (await fetch(`data:image/jpeg;base64,${frame.data}`)).blob();
|
||||
return createImageBitmap(blob);
|
||||
}
|
||||
|
||||
/**
|
||||
* frames: [{data (base64 jpeg), w, h (CSS px the image covers), action}]
|
||||
* Returns the GIF as a Uint8Array.
|
||||
*/
|
||||
export async function encodeGif(frames, options = {}) {
|
||||
const opt = {
|
||||
showClickIndicators: true,
|
||||
showDragPaths: true,
|
||||
showActionLabels: true,
|
||||
showProgressBar: true,
|
||||
showWatermark: true,
|
||||
quality: 10,
|
||||
...options
|
||||
};
|
||||
// quality 1 (best) .. 30 (smallest): fewer palette colours as it rises.
|
||||
const q = Math.min(30, Math.max(1, Number(opt.quality) || 10));
|
||||
const colors = Math.max(32, Math.round(256 - (q - 1) * (224 / 29)));
|
||||
|
||||
const first = await decode(frames[0]);
|
||||
const scale = Math.min(1, MAX_WIDTH / first.width);
|
||||
const W = Math.round(first.width * scale);
|
||||
const H = Math.round(first.height * scale);
|
||||
first.close();
|
||||
|
||||
const canvas = new OffscreenCanvas(W, H);
|
||||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
const gif = GIFEncoder();
|
||||
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const f = frames[i];
|
||||
const bmp = await decode(f);
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.drawImage(bmp, 0, 0, W, H);
|
||||
// Action coordinates are CSS px; the frame image covers f.w x f.h CSS px.
|
||||
const k = W / (f.w || bmp.width);
|
||||
bmp.close();
|
||||
const a = f.action || {};
|
||||
if (opt.showClickIndicators && a.kind === "click" && a.x != null) drawClick(ctx, a.x * k, a.y * k);
|
||||
if (opt.showDragPaths && a.kind === "drag") drawArrow(ctx, a.sx * k, a.sy * k, a.x * k, a.y * k);
|
||||
if (opt.showActionLabels && a.label) drawLabel(ctx, a.label, W, H);
|
||||
if (opt.showProgressBar) {
|
||||
ctx.fillStyle = "rgba(0,0,0,0.25)";
|
||||
ctx.fillRect(0, H - 6, W, 6);
|
||||
ctx.fillStyle = ORANGE;
|
||||
ctx.fillRect(0, H - 6, (W * (i + 1)) / frames.length, 6);
|
||||
}
|
||||
if (opt.showWatermark) drawWatermark(ctx, W);
|
||||
|
||||
const { data } = ctx.getImageData(0, 0, W, H);
|
||||
const palette = quantize(data, colors);
|
||||
const index = applyPalette(data, palette);
|
||||
const isLast = i === frames.length - 1;
|
||||
gif.writeFrame(index, W, H, { palette, delay: isLast ? 2500 : a.kind === "screenshot" ? 900 : 1200, repeat: 0 });
|
||||
}
|
||||
gif.finish();
|
||||
return gif.bytes();
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 174 B |
Binary file not shown.
|
After Width: | Height: | Size: 386 B |
@@ -0,0 +1,174 @@
|
||||
// Key identities for CDP Input.dispatchKeyEvent.
|
||||
//
|
||||
// Pages read `key`, `code` and `keyCode`, so each key is described the way a
|
||||
// real US keyboard reports it. Characters with no key identity (emoji, CJK)
|
||||
// return null and are inserted as text only.
|
||||
|
||||
const SHIFTED = new Set('~!@#$%^&*()_+{}|:"<>?'.split(""));
|
||||
|
||||
const CODE_PUNCT = {
|
||||
" ": "Space", "-": "Minus", "_": "Minus", "=": "Equal", "+": "Equal",
|
||||
"[": "BracketLeft", "{": "BracketLeft", "]": "BracketRight", "}": "BracketRight",
|
||||
"\\": "Backslash", "|": "Backslash", ";": "Semicolon", ":": "Semicolon",
|
||||
"'": "Quote", '"': "Quote", ",": "Comma", "<": "Comma", ".": "Period",
|
||||
">": "Period", "/": "Slash", "?": "Slash", "`": "Backquote", "~": "Backquote",
|
||||
"!": "Digit1", "@": "Digit2", "#": "Digit3", "$": "Digit4", "%": "Digit5",
|
||||
"^": "Digit6", "&": "Digit7", "*": "Digit8", "(": "Digit9", ")": "Digit0"
|
||||
};
|
||||
|
||||
const PUNCT_KEYCODE = {
|
||||
Space: 32, Minus: 189, Equal: 187, BracketLeft: 219, BracketRight: 221, Backslash: 220,
|
||||
Semicolon: 186, Quote: 222, Comma: 188, Period: 190, Slash: 191, Backquote: 192,
|
||||
Digit0: 48, Digit1: 49, Digit2: 50, Digit3: 51, Digit4: 52, Digit5: 53, Digit6: 54,
|
||||
Digit7: 55, Digit8: 56, Digit9: 57
|
||||
};
|
||||
|
||||
/** {code, keyCode, shift} for a single printable character, or null. */
|
||||
export function charDescriptor(ch) {
|
||||
if (!ch || ch.length !== 1) return null;
|
||||
const upper = ch.toUpperCase();
|
||||
if (ch >= "a" && ch <= "z") return { code: `Key${upper}`, keyCode: upper.charCodeAt(0), shift: false };
|
||||
if (ch >= "A" && ch <= "Z") return { code: `Key${upper}`, keyCode: upper.charCodeAt(0), shift: true };
|
||||
if (ch >= "0" && ch <= "9") return { code: `Digit${ch}`, keyCode: ch.charCodeAt(0), shift: false };
|
||||
const code = CODE_PUNCT[ch];
|
||||
if (code) return { code, keyCode: PUNCT_KEYCODE[code] || 0, shift: SHIFTED.has(ch) };
|
||||
return null;
|
||||
}
|
||||
|
||||
// Named, non-printing keys: key -> [code, keyCode, text]
|
||||
const NAMED = {
|
||||
Enter: ["Enter", 13, "\r"],
|
||||
Tab: ["Tab", 9, "\t"],
|
||||
Escape: ["Escape", 27],
|
||||
Backspace: ["Backspace", 8],
|
||||
Delete: ["Delete", 46],
|
||||
Insert: ["Insert", 45],
|
||||
ArrowUp: ["ArrowUp", 38],
|
||||
ArrowDown: ["ArrowDown", 40],
|
||||
ArrowLeft: ["ArrowLeft", 37],
|
||||
ArrowRight: ["ArrowRight", 39],
|
||||
Home: ["Home", 36],
|
||||
End: ["End", 35],
|
||||
PageUp: ["PageUp", 33],
|
||||
PageDown: ["PageDown", 34],
|
||||
" ": ["Space", 32, " "],
|
||||
CapsLock: ["CapsLock", 20],
|
||||
ContextMenu: ["ContextMenu", 93]
|
||||
};
|
||||
for (let i = 1; i <= 12; i++) NAMED[`F${i}`] = [`F${i}`, 111 + i];
|
||||
|
||||
const ALIASES = {
|
||||
enter: "Enter", return: "Enter", tab: "Tab", escape: "Escape", esc: "Escape",
|
||||
backspace: "Backspace", delete: "Delete", del: "Delete", insert: "Insert",
|
||||
space: " ", spacebar: " ",
|
||||
arrowup: "ArrowUp", arrowdown: "ArrowDown", arrowleft: "ArrowLeft", arrowright: "ArrowRight",
|
||||
up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight",
|
||||
home: "Home", end: "End", pageup: "PageUp", pagedown: "PageDown", page_up: "PageUp", page_down: "PageDown",
|
||||
capslock: "CapsLock", contextmenu: "ContextMenu", menu: "ContextMenu"
|
||||
};
|
||||
|
||||
// CDP modifier bits.
|
||||
export const MOD = { alt: 1, ctrl: 2, meta: 4, shift: 8 };
|
||||
|
||||
function modifierBit(part) {
|
||||
switch (part) {
|
||||
case "ctrl": case "control": return MOD.ctrl;
|
||||
case "alt": case "option": case "opt": return MOD.alt;
|
||||
case "shift": return MOD.shift;
|
||||
case "cmd": case "command": case "meta": case "super": case "win": case "windows": return MOD.meta;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseModifiers(str) {
|
||||
if (!str) return 0;
|
||||
return String(str)
|
||||
.split("+")
|
||||
.map((p) => p.trim().toLowerCase())
|
||||
.reduce((m, p) => m | modifierBit(p), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one combo such as "cmd+shift+z", "Return" or "a" into the key event
|
||||
* fields. Returns null for something that is not a key.
|
||||
*/
|
||||
export function parseCombo(combo) {
|
||||
const parts = String(combo).split("+");
|
||||
// "ctrl++" / "+" mean the plus key itself.
|
||||
if (combo.endsWith("++")) parts.splice(parts.length - 2, 2, "+");
|
||||
else if (combo === "+") parts.splice(0, parts.length, "+");
|
||||
if (parts.length === 1 && modifierBit(parts[0].trim().toLowerCase())) {
|
||||
// A bare modifier press, e.g. "shift".
|
||||
const map = {
|
||||
[MOD.ctrl]: ["Control", "ControlLeft", 17],
|
||||
[MOD.alt]: ["Alt", "AltLeft", 18],
|
||||
[MOD.shift]: ["Shift", "ShiftLeft", 16],
|
||||
[MOD.meta]: ["Meta", "MetaLeft", 91]
|
||||
};
|
||||
const m = map[modifierBit(parts[0].trim().toLowerCase())];
|
||||
return { key: m[0], code: m[1], keyCode: m[2], modifiers: 0, text: undefined };
|
||||
}
|
||||
let modifiers = 0;
|
||||
let keyName = null;
|
||||
for (const raw of parts) {
|
||||
const p = raw.trim();
|
||||
const bit = modifierBit(p.toLowerCase());
|
||||
if (bit) modifiers |= bit;
|
||||
else keyName = p;
|
||||
}
|
||||
if (keyName === null) return null;
|
||||
const alias = ALIASES[keyName.toLowerCase()];
|
||||
const named = NAMED[alias || keyName] || (alias === undefined && NAMED[keyName]);
|
||||
if (named) {
|
||||
const key = alias || keyName;
|
||||
return { key: key === " " ? " " : key, code: named[0], keyCode: named[1], modifiers, text: modifiers & ~MOD.shift ? undefined : named[2] };
|
||||
}
|
||||
if (keyName.length === 1) {
|
||||
const d = charDescriptor(keyName);
|
||||
let key = keyName;
|
||||
// With shift held, letters report upper case, as a real keyboard does.
|
||||
if (modifiers & MOD.shift && key.length === 1) key = key.toUpperCase();
|
||||
const mods = modifiers | (d && d.shift ? MOD.shift : 0);
|
||||
return {
|
||||
key,
|
||||
code: d ? d.code : "",
|
||||
keyCode: d ? d.keyCode : key.toUpperCase().charCodeAt(0),
|
||||
modifiers: mods,
|
||||
// Only unmodified (or shift-only) presses produce text.
|
||||
text: modifiers & ~MOD.shift ? undefined : key
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// macOS does not run editing shortcuts from synthetic key events; Chrome only
|
||||
// applies them when the event carries the matching editing command. Without
|
||||
// this, cmd+a / cmd+c / cmd+v do nothing in text fields on a Mac.
|
||||
const MAC_COMMANDS = {
|
||||
[`${MOD.meta}:KeyA`]: ["selectAll"],
|
||||
[`${MOD.meta}:KeyC`]: ["copy"],
|
||||
[`${MOD.meta}:KeyX`]: ["cut"],
|
||||
[`${MOD.meta}:KeyV`]: ["paste"],
|
||||
[`${MOD.meta}:KeyZ`]: ["undo"],
|
||||
[`${MOD.meta | MOD.shift}:KeyZ`]: ["redo"],
|
||||
[`${MOD.meta}:ArrowLeft`]: ["moveToBeginningOfLine"],
|
||||
[`${MOD.meta}:ArrowRight`]: ["moveToEndOfLine"],
|
||||
[`${MOD.meta}:ArrowUp`]: ["moveToBeginningOfDocument"],
|
||||
[`${MOD.meta}:ArrowDown`]: ["moveToEndOfDocument"],
|
||||
[`${MOD.meta | MOD.shift}:ArrowLeft`]: ["moveToBeginningOfLineAndModifySelection"],
|
||||
[`${MOD.meta | MOD.shift}:ArrowRight`]: ["moveToEndOfLineAndModifySelection"],
|
||||
[`${MOD.alt}:ArrowLeft`]: ["moveWordLeft"],
|
||||
[`${MOD.alt}:ArrowRight`]: ["moveWordRight"],
|
||||
[`${MOD.alt}:Backspace`]: ["deleteWordBackward"],
|
||||
[`${MOD.meta}:Backspace`]: ["deleteToBeginningOfLine"]
|
||||
};
|
||||
|
||||
export function macEditingCommands(parsed) {
|
||||
return MAC_COMMANDS[`${parsed.modifiers}:${parsed.code}`];
|
||||
}
|
||||
|
||||
/** Page-zoom shortcuts, which the tool contract says to reject. */
|
||||
export function isZoomShortcut(parsed) {
|
||||
if (!(parsed.modifiers & (MOD.ctrl | MOD.meta))) return false;
|
||||
return ["Equal", "Minus", "Digit0"].includes(parsed.code) || ["=", "+", "-", "0"].includes(parsed.key);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "opencode",
|
||||
"version": "1.0.0",
|
||||
"description": "Lets opencode drive this browser: the Claude in Chrome tool set over MCP.",
|
||||
"minimum_chrome_version": "116",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyYRQZXAQPkTDwkGanqG6NAXHlAqQDfBSqhvqbHJ9y1DvazG3o9kgKp9q0dxGd45TRYpBGj2NHlQCpyuvcz7L3O6lifwuKHcnQT5NTC0z7qgfsxo7aGfEAJbueqhi0yNLF9jEdk8RTwdPAVWxhpVss+Lu5BSOXDMsiU/r16E9pPUACqwKUkGeHx/9WR2SMRMLzPgGXOXAtre6h8+bVpu9YnDX4qOvhahQe3sZDfNaMH4hJTy3aGWph0nyiIIOYlhlzBu5N8btbcwLjouHikRE9wBfoOIGWtfLWP9PYde355hF8/2i+c4kzaAoGub2w4dhBv1HOkfFw6CEu4RJGxhR3QIDAQAB",
|
||||
"permissions": [
|
||||
"tabs",
|
||||
"tabGroups",
|
||||
"debugger",
|
||||
"scripting",
|
||||
"nativeMessaging",
|
||||
"storage",
|
||||
"alarms",
|
||||
"downloads"
|
||||
],
|
||||
"host_permissions": ["<all_urls>"],
|
||||
"background": {
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"action": {
|
||||
"default_title": "opencode",
|
||||
"default_popup": "popup.html"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["<all_urls>"],
|
||||
"js": ["content.js"],
|
||||
"run_at": "document_idle",
|
||||
"all_frames": false
|
||||
}
|
||||
],
|
||||
"icons": {
|
||||
"16": "icons/icon16.png",
|
||||
"48": "icons/icon48.png",
|
||||
"128": "icons/icon128.png"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>opencode</title><link rel="stylesheet" href="ui.css"><style>body{width:320px}</style></head>
|
||||
<body>
|
||||
<h1>opencode</h1>
|
||||
<div class="status"><span id="dot" class="dot"></span><span id="state">Checking…</span></div>
|
||||
<label for="name">This browser's name (shown to opencode)</label>
|
||||
<input id="name" maxlength="80">
|
||||
<div class="row"><button id="save" class="primary">Save name</button></div>
|
||||
<p class="muted" style="margin-top:12px">Device ID <code id="device"></code><br>Extension ID <code id="ext"></code> · v<span id="ver"></span></p>
|
||||
<script src="popup.js"></script>
|
||||
</body></html>
|
||||
@@ -0,0 +1,22 @@
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
async function refresh() {
|
||||
const s = await chrome.runtime.sendMessage({ type: "status" });
|
||||
$("dot").classList.toggle("on", s.connected);
|
||||
$("state").textContent = s.connected
|
||||
? "Connected to the native host"
|
||||
: `Not connected${s.error ? ` (${s.error})` : ""} — run install.sh`;
|
||||
if (document.activeElement !== $("name")) $("name").value = s.identity.name;
|
||||
$("device").textContent = s.identity.deviceId;
|
||||
$("ext").textContent = s.extensionId;
|
||||
$("ver").textContent = s.version;
|
||||
}
|
||||
|
||||
$("save").addEventListener("click", async () => {
|
||||
await chrome.runtime.sendMessage({ type: "rename", name: $("name").value.trim() });
|
||||
$("save").textContent = "Saved";
|
||||
setTimeout(() => ($("save").textContent = "Save name"), 1200);
|
||||
});
|
||||
|
||||
refresh();
|
||||
setInterval(refresh, 1500);
|
||||
@@ -0,0 +1,16 @@
|
||||
:root { color-scheme: light dark; --bg: #fff; --fg: #1b1b1f; --muted: #6b6b76; --line: #e3e3e8; --accent: #2563eb; --ok: #15803d; --bad: #b91c1c; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg: #1c1c21; --fg: #ececf1; --muted: #9a9aa6; --line: #33333b; --accent: #60a5fa; --ok: #4ade80; --bad: #f87171; } }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; padding: 16px; font: 13px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif; background: var(--bg); color: var(--fg); }
|
||||
h1 { font-size: 15px; margin: 0 0 10px; }
|
||||
p { margin: 0 0 10px; }
|
||||
.muted { color: var(--muted); font-size: 12px; }
|
||||
.status { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--bad); flex: none; }
|
||||
.dot.on { background: var(--ok); }
|
||||
label { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
|
||||
input { width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: var(--fg); font: inherit; }
|
||||
.row { display: flex; gap: 8px; margin-top: 12px; }
|
||||
button { flex: 1; padding: 8px 10px; border-radius: 6px; border: 1px solid var(--line); background: transparent; color: var(--fg); font: inherit; cursor: pointer; }
|
||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
|
||||
code { font: 11px ui-monospace, Menlo, monospace; word-break: break-all; }
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2017 Matt DesLauriers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||
OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
var X={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function F(t=256){let e=0,s=new Uint8Array(t);return{get buffer(){return s.buffer},reset(){e=0},bytesView(){return s.subarray(0,e)},bytes(){return s.slice(0,e)},writeByte(r){n(e+1),s[e]=r,e++},writeBytes(r,o=0,i=r.length){n(e+i);for(let c=0;c<i;c++)s[e++]=r[c+o]},writeBytesView(r,o=0,i=r.byteLength){n(e+i),s.set(r.subarray(o,o+i),e),e+=i}};function n(r){var o=s.length;if(o>=r)return;var i=1024*1024;r=Math.max(r,o*(o<i?2:1.125)>>>0),o!=0&&(r=Math.max(r,256));let c=s;s=new Uint8Array(r),e>0&&s.set(c.subarray(0,e),0)}}var O=12,J=5003,lt=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function at(t,e,s,n,r=F(512),o=new Uint8Array(256),i=new Int32Array(J),c=new Int32Array(J)){let x=i.length,a=Math.max(2,n);o.fill(0),c.fill(0),i.fill(-1);let l=0,f=0,g=a+1,h=g,b=!1,w=h,_=(1<<w)-1,u=1<<g-1,k=u+1,B=u+2,p=0,A=s[0],z=0;for(let y=x;y<65536;y*=2)++z;z=8-z,r.writeByte(a),I(u);let d=s.length;for(let y=1;y<d;y++){t:{let m=s[y],v=(m<<O)+A,M=m<<z^A;if(i[M]===v){A=c[M];break t}let V=M===0?1:x-M;for(;i[M]>=0;)if(M-=V,M<0&&(M+=x),i[M]===v){A=c[M];break t}I(A),A=m,B<1<<O?(c[M]=B++,i[M]=v):(i.fill(-1),B=u+2,b=!0,I(u))}}return I(A),I(k),r.writeByte(0),r.bytesView();function I(y){for(l&=lt[f],f>0?l|=y<<f:l=y,f+=w;f>=8;)o[p++]=l&255,p>=254&&(r.writeByte(p),r.writeBytesView(o,0,p),p=0),l>>=8,f-=8;if((B>_||b)&&(b?(w=h,_=(1<<w)-1,b=!1):(++w,_=w===O?1<<w:(1<<w)-1)),y==k){for(;f>0;)o[p++]=l&255,p>=254&&(r.writeByte(p),r.writeBytesView(o,0,p),p=0),l>>=8,f-=8;p>0&&(r.writeByte(p),r.writeBytesView(o,0,p),p=0)}}}var $=at;function D(t,e,s){return t<<8&63488|e<<2&992|s>>3}function G(t,e,s,n){return t>>4|e&240|(s&240)<<4|(n&240)<<8}function j(t,e,s){return t>>4<<8|e&240|s>>4}function R(t,e,s){return t<e?e:t>s?s:t}function T(t){return t*t}function tt(t,e,s){var n=0,r=1e100;let o=t[e],i=o.cnt,c=o.ac,x=o.rc,a=o.gc,l=o.bc;for(var f=o.fw;f!=0;f=t[f].fw){let h=t[f],b=h.cnt,w=i*b/(i+b);if(!(w>=r)){var g=0;s&&(g+=w*T(h.ac-c),g>=r)||(g+=w*T(h.rc-x),!(g>=r)&&(g+=w*T(h.gc-a),!(g>=r)&&(g+=w*T(h.bc-l),!(g>=r)&&(r=g,n=f))))}}o.err=r,o.nn=n}function Q(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function ut(t,e){let s=e==="rgb444"?4096:65536,n=new Array(s),r=t.length;if(e==="rgba4444")for(let o=0;o<r;++o){let i=t[o],c=i>>24&255,x=i>>16&255,a=i>>8&255,l=i&255,f=G(l,a,x,c),g=f in n?n[f]:n[f]=Q();g.rc+=l,g.gc+=a,g.bc+=x,g.ac+=c,g.cnt++}else if(e==="rgb444")for(let o=0;o<r;++o){let i=t[o],c=i>>16&255,x=i>>8&255,a=i&255,l=j(a,x,c),f=l in n?n[l]:n[l]=Q();f.rc+=a,f.gc+=x,f.bc+=c,f.cnt++}else for(let o=0;o<r;++o){let i=t[o],c=i>>16&255,x=i>>8&255,a=i&255,l=D(a,x,c),f=l in n?n[l]:n[l]=Q();f.rc+=a,f.gc+=x,f.bc+=c,f.cnt++}return n}function H(t,e,s={}){let{format:n="rgb565",clearAlpha:r=!0,clearAlphaColor:o=0,clearAlphaThreshold:i=0,oneBitAlpha:c=!1}=s;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let x=new Uint32Array(t.buffer),a=s.useSqrt!==!1,l=n==="rgba4444",f=ut(x,n),g=f.length,h=g-1,b=new Uint32Array(g+1);for(var w=0,u=0;u<g;++u){let C=f[u];if(C!=null){var _=1/C.cnt;l&&(C.ac*=_),C.rc*=_,C.gc*=_,C.bc*=_,f[w++]=C}}T(e)/w<.022&&(a=!1);for(var u=0;u<w-1;++u)f[u].fw=u+1,f[u+1].bk=u,a&&(f[u].cnt=Math.sqrt(f[u].cnt));a&&(f[u].cnt=Math.sqrt(f[u].cnt));var k,B,p;for(u=0;u<w;++u){tt(f,u,!1);var A=f[u].err;for(B=++b[0];B>1&&(p=B>>1,!(f[k=b[p]].err<=A));B=p)b[B]=k;b[B]=u}var z=w-e;for(u=0;u<z;){for(var d;;){var I=b[1];if(d=f[I],d.tm>=d.mtm&&f[d.nn].mtm<=d.tm)break;d.mtm==h?I=b[1]=b[b[0]--]:(tt(f,I,!1),d.tm=u);var A=f[I].err;for(B=1;(p=B+B)<=b[0]&&(p<b[0]&&f[b[p]].err>f[b[p+1]].err&&p++,!(A<=f[k=b[p]].err));B=p)b[B]=k;b[B]=I}var y=f[d.nn],m=d.cnt,v=y.cnt,_=1/(m+v);l&&(d.ac=_*(m*d.ac+v*y.ac)),d.rc=_*(m*d.rc+v*y.rc),d.gc=_*(m*d.gc+v*y.gc),d.bc=_*(m*d.bc+v*y.bc),d.cnt+=y.cnt,d.mtm=++u,f[y.bk].fw=y.fw,f[y.fw].bk=y.bk,y.mtm=h}let M=[];var V=0;for(u=0;;++V){let L=R(Math.round(f[u].rc),0,255),C=R(Math.round(f[u].gc),0,255),Y=R(Math.round(f[u].bc),0,255),E=255;if(l){if(E=R(Math.round(f[u].ac),0,255),c){let st=typeof c=="number"?c:127;E=E<=st?0:255}r&&E<=i&&(L=C=Y=o,E=0)}let K=l?[L,C,Y,E]:[L,C,Y];if(xt(M,K)||M.push(K),(u=f[u].fw)==0)break}return M}function xt(t,e){for(let s=0;s<t.length;s++){let n=t[s],r=n[0]===e[0]&&n[1]===e[1]&&n[2]===e[2],o=n.length>=4&&e.length>=4?n[3]===e[3]:!0;if(r&&o)return!0}return!1}function U(t,e){var s=0,n;for(n=0;n<t.length;n++){let r=t[n]-e[n];s+=r*r}return s}function P(t,e){Line truncated
|
||||
Reference in new issue
Block a user