mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
refactor(browser): satisfy the GUI lint rules in the prompt changes
Blank lines oxlint asks for; the prompts reset their input guard through createKeyed instead of a restricted createEffect; no typeof on Electron's dialog arguments; no conditional empty spread in the visit machine; the tests' stand-in pages and stores carry SAFETY notes with their lint exceptions.
This commit is contained in:
parent
c2e3397b68
commit
6bc2a7b647
12 changed files with 62 additions and 17 deletions
|
|
@ -13,13 +13,16 @@ export function activationAllowed(input: { readonly shownAt: number; readonly pr
|
|||
return input.pressedAt !== undefined && input.pressedAt >= input.shownAt && input.at - input.shownAt >= ACTIVATION_DELAY_MS
|
||||
}
|
||||
|
||||
/** When the prompt last appeared or changed, and when the last press on it began. */
|
||||
type Activation = { shownAt: number; pressedAt?: number }
|
||||
|
||||
/**
|
||||
* Guards the controls inside `root` marked `data-activation-guard`, and the submission of its forms: a click on one, or
|
||||
* a submit, that `activationAllowed` refuses is stopped before any handler of the control sees it. Call `changed` when
|
||||
* the prompt shows something new in the same place.
|
||||
*/
|
||||
export function guardActivation(root: HTMLElement) {
|
||||
const state: { shownAt: number; pressedAt?: number } = { shownAt: performance.now() }
|
||||
const state: Activation = { shownAt: performance.now() }
|
||||
|
||||
// A key held down since before the prompt repeats on it; only a press that starts on the prompt counts.
|
||||
const pressed = (event: PointerEvent | KeyboardEvent) => {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ const server = createServer((_request, response) => {
|
|||
void electron.app.whenReady().then(async () => {
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
|
||||
const address = server.address()
|
||||
const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`
|
||||
const origin = `http://127.0.0.1:${address instanceof Object ? address.port : 0}`
|
||||
const win = new electron.BrowserWindow({ show: false })
|
||||
const view = new electron.WebContentsView({ webPreferences: { sandbox: true, contextIsolation: true } })
|
||||
win.contentView.addChildView(view)
|
||||
|
|
@ -34,6 +34,7 @@ void electron.app.whenReady().then(async () => {
|
|||
framed: () => {},
|
||||
warn: (message) => warnings.push(message),
|
||||
})
|
||||
|
||||
// CDP's Page domain answers only once the page has a renderer.
|
||||
await contents.loadURL("about:blank")
|
||||
contents.debugger.attach("1.3")
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ test(
|
|||
})
|
||||
|
||||
if (!built.success) throw new AggregateError(built.logs, "The Electron fixture did not build.")
|
||||
|
||||
const child = Bun.spawn(
|
||||
[
|
||||
String(electron),
|
||||
|
|
@ -30,6 +31,7 @@ test(
|
|||
],
|
||||
{ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined, ELECTRON_ENABLE_LOGGING: undefined }, stdout: "pipe", stderr: "pipe" },
|
||||
)
|
||||
|
||||
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
|
||||
const line = stdout.split("\n").find((text) => text.startsWith("{"))
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { AGENT_PROMPT_WAIT_MS, createPagePrompts, takeDialogs } from "./page-pro
|
|||
import { createSitePermissions } from "./site-permissions"
|
||||
|
||||
beforeEach(() => jest.useFakeTimers())
|
||||
|
||||
afterEach(() => jest.useRealTimers())
|
||||
|
||||
describe("a tab's sign-in", () => {
|
||||
|
|
@ -134,7 +135,9 @@ describe("the takeover of a page's dialogs", () => {
|
|||
// An Electron without the internal listener, which then calls it with no callback.
|
||||
const contents = Object.assign(new EventEmitter(), { isDestroyed: () => false })
|
||||
const warnings: string[] = []
|
||||
|
||||
// SAFETY: the takeover reads only the events and `isDestroyed` of a page's contents.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
const dialogs = takeDialogs(contents as unknown as WebContents, {
|
||||
suppressed: () => false,
|
||||
opened: () => false,
|
||||
|
|
@ -152,6 +155,7 @@ describe("the takeover of a page's dialogs", () => {
|
|||
contents.on("-run-dialog", () => {})
|
||||
const answers: unknown[][] = []
|
||||
// SAFETY: as above.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
takeDialogs(contents as unknown as WebContents, { suppressed: () => false, opened: () => false, framed: () => {}, warn: () => {} })
|
||||
|
||||
contents.emit("-run-dialog", { dialogType: "confirm" }, (...args: unknown[]) => answers.push(args))
|
||||
|
|
@ -168,11 +172,13 @@ function page(origin: string, options: { agent?: boolean } = {}) {
|
|||
isDestroyed: () => false,
|
||||
isFocused: () => true,
|
||||
})
|
||||
|
||||
const views: (PromptView | null)[] = []
|
||||
const sites = createSitePermissions(memoryStorage(), () => {})
|
||||
|
||||
const prompts = createPagePrompts({
|
||||
// SAFETY: the prompts read only the members above of a page's contents, and its events.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
contents: contents as unknown as WebContents,
|
||||
scope: { kind: "profile" },
|
||||
sites,
|
||||
|
|
@ -220,11 +226,13 @@ function memoryStorage() {
|
|||
const values = new Map<string, unknown>()
|
||||
|
||||
// SAFETY: the site permissions read only `store` and its `value` and `set`.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
return {
|
||||
store: (key: string, options: { initial: unknown }) => ({
|
||||
get value() {
|
||||
return values.has(key) ? values.get(key) : options.initial
|
||||
},
|
||||
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
|
||||
set: (next: unknown) => values.set(key, next),
|
||||
}),
|
||||
} as unknown as Storage
|
||||
|
|
|
|||
|
|
@ -371,6 +371,7 @@ export function createPagePrompts(input: {
|
|||
details.requestingUrl === undefined || requestOrigin(details, contents) === originOf(requesting)
|
||||
? originOf(requesting)
|
||||
: "null"
|
||||
|
||||
const request = { origin, top: contents.mainFrame.origin, mainFrame: details.isMainFrame }
|
||||
|
||||
const agent = input.agentDriven()
|
||||
|
|
@ -543,7 +544,8 @@ export function takeDialogs(
|
|||
if (!callback) return input.warn("Electron's -run-dialog passed no callback; the dialog is left to CDP.")
|
||||
|
||||
if (input.suppressed()) return callback(false, "")
|
||||
const frame = info && typeof info === "object" && info.frame && !info.frame.isDestroyed() ? info.frame : undefined
|
||||
const details = dialogCallback(info) ? undefined : info
|
||||
const frame = details?.frame && !details.frame.isDestroyed() ? details.frame : undefined
|
||||
held.set(callback, frame ? { origin: frame.origin, main: frame.parent === null } : undefined)
|
||||
input.framed()
|
||||
// The page must never wait on a dialog nobody can see: one CDP never reported is dismissed.
|
||||
|
|
@ -577,8 +579,9 @@ export function takeDialogs(
|
|||
type DialogCallback = (success: boolean, text: string) => void
|
||||
|
||||
function dialogCallback(value: RunDialogInfo | DialogCallback | undefined): value is DialogCallback {
|
||||
return typeof value === "function"
|
||||
return value instanceof Function
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a top-level document Chromium's own `prompt` back. Electron replaces it in every main frame with one that
|
||||
* throws ("prompt() is not supported"); a frame Electron does not set up keeps the original, and calling it for this
|
||||
|
|
|
|||
|
|
@ -138,6 +138,7 @@ export function downloadOwner(download: AgentActivity & {
|
|||
|
||||
return agentCaused(download) ? "agent" : "user"
|
||||
}
|
||||
|
||||
/** Actions that only take a tab away from its document, which the agent may run on an extension page to leave it. */
|
||||
const leaving = ["navigate", "back", "forward", "stop"]
|
||||
|
||||
|
|
|
|||
|
|
@ -27,12 +27,16 @@ test("a load the page's beforeunload kept reports its error for the top frame in
|
|||
isDestroyed: () => false,
|
||||
getURL: () => "https://a.example/form",
|
||||
})
|
||||
|
||||
const emitted: [string, readonly Wire[]][] = []
|
||||
|
||||
// SAFETY: web navigation reads only `watch` and `get` of the tabs, and only the members above of a tab's contents.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
const tabs = {
|
||||
watch: (watch: (tab: { contents: typeof contents }) => (() => void) | void) => watch({ contents }) ?? (() => {}),
|
||||
get: () => undefined,
|
||||
} as unknown as ExtensionTabs
|
||||
|
||||
createWebNavigation({ tabs, emit: (event, args) => emitted.push([event, args]) })
|
||||
|
||||
contents.emit("did-fail-load", {}, -3, "ERR_ABORTED", "https://b.example/", true)
|
||||
|
|
|
|||
|
|
@ -103,6 +103,7 @@ describe("which prompt shows", () => {
|
|||
{ type: "requested", request: { ...signIn, navigation: true } },
|
||||
{ type: "requested", request: { ...signIn, key: "fetch", navigation: false } },
|
||||
])
|
||||
|
||||
const stopped = transitionPrompts(state, { type: "cleared", kinds: ["auth"], navigation: true })
|
||||
|
||||
expect(stopped.ended).toEqual([1])
|
||||
|
|
@ -134,6 +135,7 @@ describe("a tab's visit", () => {
|
|||
],
|
||||
start,
|
||||
)
|
||||
|
||||
const same = transitionVisit(visited, { type: "committed", origin: "https://bank.example" })
|
||||
const other = transitionVisit(visited, { type: "committed", origin: "https://news.example" })
|
||||
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ export function transitionPrompts(state: PromptState, event: PromptEvent): Promp
|
|||
return { state: { ...state, items: state.items.filter((item) => item.id !== event.id) }, ended: [] }
|
||||
case "cleared": {
|
||||
const kinds = event.kinds
|
||||
|
||||
const ended = state.items.filter(
|
||||
(item) => (!kinds || kinds.includes(item.kind)) && (!event.navigation || (item.kind === "auth" && item.navigation)),
|
||||
)
|
||||
|
|
@ -162,11 +163,11 @@ export const createVisit = (committed: string): Visit => ({ committed, bypass: f
|
|||
export function transitionVisit(state: Visit, event: VisitEvent): VisitTransition {
|
||||
switch (event.type) {
|
||||
case "started": {
|
||||
// A navigation the user started asks a site they dismissed again; one the page started does not.
|
||||
const user = !!state.intent
|
||||
const next = { ...state, pending: event.url, intent: undefined }
|
||||
|
||||
// A navigation the user started asks a site they dismissed again; one the page started does not.
|
||||
return {
|
||||
state: { ...state, pending: event.url, intent: undefined, ...(user ? { attempts: {}, dismissed: [] } : {}) },
|
||||
state: state.intent ? { ...next, attempts: {}, dismissed: [] } : next,
|
||||
clear: { kinds: ["auth", "leave"] },
|
||||
}
|
||||
}
|
||||
|
|
@ -237,6 +238,7 @@ export function promptSite(url: string, top: string, frame?: { readonly origin:
|
|||
|
||||
return { kind: "web" as const, host: promptHost(origin), embedded }
|
||||
}
|
||||
|
||||
/** Page-supplied text the pane shows as text: bounded, without controls that reorder or hide what follows. */
|
||||
export function promptText(text: string, max: number) {
|
||||
return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, "").slice(0, max)
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import { Icon } from "@opencode/ui/icon"
|
|||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
import { TextInput } from "@opencode/ui/text-input"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { createEffect, createSignal, createUniqueId, Match, on, onCleanup, onMount, Show, Switch, type JSX } from "solid-js"
|
||||
import { usePlugin } from "@opencode/plugin/gui"
|
||||
import { createSignal, createUniqueId, Match, onCleanup, onMount, Show, Switch, type JSX } from "solid-js"
|
||||
import { createKeyed, usePlugin } from "@opencode/plugin/gui"
|
||||
import { guardActivation } from "./activation-delay"
|
||||
import type definition from "./index"
|
||||
import { PROMPT_TEXT_MAX, SIGN_IN_TEXT_MAX, type PromptAnswer, type PromptSite, type PromptView } from "./ipc"
|
||||
|
|
@ -34,8 +34,16 @@ export function PromptDialog(props: {
|
|||
const title = createUniqueId()
|
||||
const description = createUniqueId()
|
||||
let box: HTMLDivElement | undefined
|
||||
// A page can open a dialog under a click or key press already in flight: its default answer waits for a new one,
|
||||
// from each dialog it shows on.
|
||||
let guard: ReturnType<typeof guardActivation> | undefined
|
||||
createKeyed(
|
||||
() => props.view.id,
|
||||
() => guard?.changed(),
|
||||
)
|
||||
const pageDialog = () => (props.view.ask.kind === "dialog" ? props.view.ask : undefined)
|
||||
const signIn = () => (props.view.ask.kind === "auth" ? props.view.ask : undefined)
|
||||
|
||||
// Only text that is there describes the dialog: an empty alert has none.
|
||||
const described = () => {
|
||||
const ask = props.view.ask
|
||||
|
|
@ -58,9 +66,7 @@ export function PromptDialog(props: {
|
|||
|
||||
onMount(() => {
|
||||
if (!box) return
|
||||
// A page can open a dialog under a click or key press already in flight: its default answer waits for a new one.
|
||||
const guard = guardActivation(box)
|
||||
createEffect(on(() => props.view.id, () => guard.changed(), { defer: true }))
|
||||
guard = guardActivation(box)
|
||||
onCleanup(guard.dispose)
|
||||
|
||||
if (!props.focus) return
|
||||
|
|
@ -392,15 +398,19 @@ export function PromptBar(props: { view: PromptView; answer: (answer: PromptAnsw
|
|||
const text = createUniqueId()
|
||||
let first: HTMLButtonElement | undefined
|
||||
let bar: HTMLElement | undefined
|
||||
// The bar appears where the page was: a click or key press already in flight, or a page's double-click target, must
|
||||
// not land on its answers, for each request it shows.
|
||||
let guard: ReturnType<typeof guardActivation> | undefined
|
||||
createKeyed(
|
||||
() => props.view.id,
|
||||
() => guard?.changed(),
|
||||
)
|
||||
|
||||
onMount(() => {
|
||||
if (props.focus) first?.focus({ preventScroll: true })
|
||||
|
||||
if (!bar) return
|
||||
// The bar appears where the page was: a click or key press already in flight, or a page's double-click target, must
|
||||
// not land on its answers.
|
||||
const guard = guardActivation(bar)
|
||||
createEffect(on(() => props.view.id, () => guard.changed(), { defer: true }))
|
||||
guard = guardActivation(bar)
|
||||
onCleanup(guard.dispose)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ describe("what a page's permission request gets before anyone is asked", () => {
|
|||
test("takes the asking frame's own origin, so a sandboxed or opaque document never borrows the page's", () => {
|
||||
// What Electron 44 passes, measured live: isMainFrame and requestingUrl only, for every non-media permission.
|
||||
const page = { url: "https://bank.example/probe", origin: "https://bank.example" }
|
||||
|
||||
const frames = [
|
||||
page,
|
||||
{ url: "https://bank.example/upload.html", origin: "null" },
|
||||
|
|
@ -72,6 +73,7 @@ describe("what a page's permission request gets before anyone is asked", () => {
|
|||
{ url: "blob:https://bank.example/0b6f", origin: "https://bank.example" },
|
||||
{ url: "data:text/html,x", origin: "null" },
|
||||
]
|
||||
|
||||
const asked = (requestingUrl: string, mainFrame = false) =>
|
||||
requesterOrigin({ mainFrame, requestingUrl, main: page, frames })
|
||||
|
||||
|
|
@ -159,15 +161,19 @@ describe("the decisions the user kept", () => {
|
|||
test("keeps one decision per site and feature, never a preview's, and changes only kept ones", () => {
|
||||
const values = new Map<string, unknown>()
|
||||
let changes = 0
|
||||
|
||||
// SAFETY: the site permissions read only `store` and its `value` and `set`.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
const storage = {
|
||||
store: (key: string, options: { initial: unknown }) => ({
|
||||
get value() {
|
||||
return values.has(key) ? values.get(key) : options.initial
|
||||
},
|
||||
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
|
||||
set: (next: unknown) => values.set(key, next),
|
||||
}),
|
||||
} as unknown as Storage
|
||||
|
||||
const sites = createSitePermissions(storage, () => changes++)
|
||||
const profile = { kind: "profile" } as const
|
||||
const server = { kind: "server", partition: "opencode-remote-a" } as const
|
||||
|
|
@ -192,4 +198,4 @@ describe("the decisions the user kept", () => {
|
|||
expect(sites.list()).toEqual([])
|
||||
expect(changes).toBe(4)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -133,6 +133,7 @@ export function siteAnswer(
|
|||
decided: { readonly kept: (kind: PermissionKind) => Setting | undefined; readonly visit: (kind: PermissionKind) => Setting | undefined },
|
||||
) {
|
||||
if (!request.kinds.length || !sameSite(request) || !trustworthy(request.origin)) return "block" as const
|
||||
|
||||
const decisions = request.kinds.map((kind) => {
|
||||
const kept = decided.kept(kind)
|
||||
const visit = decided.visit(kind)
|
||||
|
|
@ -154,6 +155,7 @@ export function siteAnswer(
|
|||
export function clipboardWrite(request: Omit<SiteRequest, "kinds">, agentDriven: boolean) {
|
||||
return !agentDriven && sameSite(request) && trustworthy(request.origin)
|
||||
}
|
||||
|
||||
/** This machine's own names, which reach another computer through a remote server's network. */
|
||||
function loopback(hostname: string) {
|
||||
return (
|
||||
|
|
@ -201,6 +203,7 @@ export function createSitePermissions(storage: Storage, changed: () => void) {
|
|||
write(stored.value.filter((item) => !same(item, decision))),
|
||||
}
|
||||
}
|
||||
|
||||
export type SitePermissions = ReturnType<typeof createSitePermissions>
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue