mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(browser): deliver install events and retain extension menu items
This commit is contained in:
parent
4c8bbe07e4
commit
5377a7d174
6 changed files with 112 additions and 30 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { addItem, chooseItem, menuTarget, removeItem, shownItems, updateItem, type MenuItem } from "./context-menus"
|
||||
import { Schema } from "effect"
|
||||
import { addItem, chooseItem, MenuArchive, menuTarget, removeItem, restoredMenus, shownItems, updateItem, type MenuItem } from "./context-menus"
|
||||
|
||||
const params = {
|
||||
linkURL: "",
|
||||
|
|
@ -11,6 +12,13 @@ const params = {
|
|||
frameURL: "",
|
||||
}
|
||||
|
||||
test("menu definitions and choices survive a cold start, but do not carry into a new version", () => {
|
||||
const created = addItem([], { id: "selected", type: "checkbox", contexts: ["selection"], checked: true })
|
||||
const saved = Schema.decodeUnknownSync(Schema.fromJsonString(MenuArchive))(JSON.stringify({ version: "1", items: created }))
|
||||
expect(restoredMenus(saved, "1")).toMatchObject([{ id: "selected", checked: true, contexts: ["selection"] }])
|
||||
expect(restoredMenus(saved, "2")).toEqual([])
|
||||
})
|
||||
|
||||
test("items keep their tree, reject duplicate ids and unknown parents, and go with their parent", () => {
|
||||
const items = [
|
||||
{ id: "root", title: "Root", contexts: ["all"] },
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Schema } from "effect"
|
||||
import { extensionLabel } from "./label"
|
||||
import type { ContextMenuParams, Extension, MenuItemConstructorOptions } from "electron"
|
||||
import type { Storage } from "@opencode/plugin/gui/main"
|
||||
import { method, none, optional, type ApiModule, type Emit } from "./api"
|
||||
import { matchesHost } from "./match-pattern"
|
||||
import type { Manifests } from "./manifest"
|
||||
|
|
@ -24,17 +25,20 @@ const Properties = Schema.Struct({
|
|||
type Properties = typeof Properties.Type
|
||||
|
||||
/** One item an extension added, by its id. Patterns limit it to pages and links that match them. */
|
||||
export type MenuItem = {
|
||||
readonly id: string | number
|
||||
readonly title: string
|
||||
readonly type: "normal" | "checkbox" | "radio" | "separator"
|
||||
readonly contexts: readonly string[]
|
||||
readonly parentId: string | number | undefined
|
||||
readonly checked: boolean
|
||||
readonly enabled: boolean
|
||||
readonly visible: boolean
|
||||
readonly documentUrlPatterns: readonly string[] | undefined
|
||||
readonly targetUrlPatterns: readonly string[] | undefined
|
||||
const MenuItem = Schema.Struct({
|
||||
id: Id, title: Schema.String, type: Schema.Literals(["normal", "checkbox", "radio", "separator"]),
|
||||
contexts: Schema.Array(Schema.String), parentId: Schema.optional(Id), checked: Schema.Boolean,
|
||||
enabled: Schema.Boolean, visible: Schema.Boolean, documentUrlPatterns: Schema.optional(Schema.Array(Schema.String)),
|
||||
targetUrlPatterns: Schema.optional(Schema.Array(Schema.String)),
|
||||
})
|
||||
|
||||
export type MenuItem = typeof MenuItem.Type
|
||||
|
||||
export const MenuArchive = Schema.Struct({ version: Schema.String, items: Schema.Array(MenuItem).check(Schema.isMaxLength(256)) })
|
||||
|
||||
/** A worker may stop between any two events. Its definitions belong to the installed version, not the worker. */
|
||||
export function restoredMenus(archive: typeof MenuArchive.Type, version: string) {
|
||||
return archive.version === version ? archive.items : []
|
||||
}
|
||||
|
||||
/** What was right-clicked, as the context names `contextMenus` items match. */
|
||||
|
|
@ -183,11 +187,19 @@ export function createContextMenus(input: {
|
|||
emit: Emit
|
||||
extensions: () => readonly Extension[]
|
||||
manifest: Manifests
|
||||
storage: Storage
|
||||
}) {
|
||||
const menus = new Map<string, readonly MenuItem[]>()
|
||||
const store = (id: string) => input.storage.store(`extension-menus.${id}`, { schema: MenuArchive, initial: { version: "", items: [] } })
|
||||
|
||||
const change = (extension: string, next: (items: readonly MenuItem[]) => readonly MenuItem[]) => {
|
||||
menus.set(extension, next(menus.get(extension) ?? []))
|
||||
const change = (extension: Extension, next: (items: readonly MenuItem[]) => readonly MenuItem[]) => {
|
||||
const saved = store(extension.id)
|
||||
const current = restoredMenus(saved.value, extension.version)
|
||||
const items = next(current)
|
||||
|
||||
if (current === items) return
|
||||
|
||||
if (items.length > 256 || Buffer.byteLength(JSON.stringify(items)) > 256 * 1024) throw new Error("Context menu storage limit exceeded.")
|
||||
saved.set({ version: extension.version, items })
|
||||
}
|
||||
|
||||
const clicked = (extension: Extension, tab: PaneTab, item: MenuItem, params: ContextMenuParams) => {
|
||||
|
|
@ -195,7 +207,7 @@ export function createContextMenus(input: {
|
|||
const choice = item.type === "checkbox" || item.type === "radio"
|
||||
// The tab that was right-clicked, with its address only for an extension that may read it.
|
||||
const snapshot = input.tabs.snapshot(tab.contents.id)
|
||||
change(extension.id, (items) => chooseItem(items, item))
|
||||
change(extension, (items) => chooseItem(items, item))
|
||||
|
||||
const info = {
|
||||
menuItemId: item.id,
|
||||
|
|
@ -225,7 +237,8 @@ export function createContextMenus(input: {
|
|||
const target = menuTarget(params)
|
||||
|
||||
return input.extensions().flatMap((extension): MenuItemConstructorOptions[] => {
|
||||
const items = menus.get(extension.id) ?? []
|
||||
if (!input.manifest(extension).permissions.includes("contextMenus")) return []
|
||||
const items = restoredMenus(store(extension.id).value, extension.version)
|
||||
|
||||
const build = (item: MenuItem): MenuItemConstructorOptions => {
|
||||
const children = shownItems(items, target, item.id)
|
||||
|
|
@ -283,19 +296,30 @@ export function createContextMenus(input: {
|
|||
],
|
||||
methods: {
|
||||
"contextMenus.create": method(Schema.Tuple([Properties]), (context, [properties]) =>
|
||||
change(context.extension.id, (items) => addItem(items, properties)),
|
||||
change(context.extension, (items) => addItem(items, properties)),
|
||||
),
|
||||
"contextMenus.update": method(Schema.Tuple([Id, Properties]), (context, [id, properties]) =>
|
||||
change(context.extension.id, (items) => updateItem(items, id, properties)),
|
||||
change(context.extension, (items) => updateItem(items, id, properties)),
|
||||
),
|
||||
"contextMenus.remove": method(Schema.Tuple([Id]), (context, [id]) =>
|
||||
change(context.extension.id, (items) => removeItem(items, id)),
|
||||
change(context.extension, (items) => removeItem(items, id)),
|
||||
),
|
||||
"contextMenus.removeAll": method(none, (context) => void menus.delete(context.extension.id)),
|
||||
"contextMenus.removeAll": method(none, (context) => change(context.extension, () => [])),
|
||||
},
|
||||
// An extension turned off and on again creates its items again at start.
|
||||
forget: (extension) => void menus.delete(extension),
|
||||
}
|
||||
|
||||
return { module, template }
|
||||
return {
|
||||
module,
|
||||
template,
|
||||
remove: (id: string) => input.storage.remove(`extension-menus.${id}`),
|
||||
// Reinstalling even the same version runs onInstalled again. Let it register the same IDs; a failed swap
|
||||
// must return the previous extension's approved menu tree along with its files.
|
||||
reset(id: string) {
|
||||
const saved = store(id)
|
||||
const previous = saved.value
|
||||
saved.set({ version: "", items: [] })
|
||||
|
||||
return () => saved.set(previous)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@ export async function createExtensionHost(input: {
|
|||
// Listeners by event, then by extension.
|
||||
const subscribers = new Map<string, Map<string, Subscriber[]>>()
|
||||
const workers = new Map<number, ServiceWorkerMain>()
|
||||
|
||||
type Install = { reason: "install" } | { reason: "update"; previousVersion: string }
|
||||
|
||||
const installs = new Map<string, Promise<Install | undefined>>()
|
||||
const file = path.join(input.directory, "extension-preload.js")
|
||||
|
||||
// The modules already listen (to cookies, tabs); a host that cannot start lets them go again.
|
||||
|
|
@ -84,6 +88,14 @@ export async function createExtensionHost(input: {
|
|||
|
||||
const subscribe = (extension: Extension | undefined, name: string, subscriber: Subscriber) => {
|
||||
if (!extension || !allowed(input.manifest(extension), namespaceOf(namespaces, name))) return
|
||||
|
||||
if (name === "runtime.onInstalled") {
|
||||
const pending = installs.get(extension.id)
|
||||
installs.delete(extension.id)
|
||||
|
||||
return pending
|
||||
}
|
||||
|
||||
const byExtension = subscribers.get(name) ?? new Map<string, Subscriber[]>()
|
||||
const list = byExtension.get(extension.id) ?? []
|
||||
|
||||
|
|
@ -95,6 +107,7 @@ export async function createExtensionHost(input: {
|
|||
|
||||
if (!same) byExtension.set(extension.id, [...list, subscriber])
|
||||
subscribers.set(name, byExtension)
|
||||
|
||||
}
|
||||
|
||||
const frameContext = (event: Electron.IpcMainInvokeEvent | Electron.IpcMainEvent) => {
|
||||
|
|
@ -120,8 +133,8 @@ export async function createExtensionHost(input: {
|
|||
contents.ipc.handle("browser-extension:subscribe", (event, name: string) => {
|
||||
const context = frameContext(event)
|
||||
|
||||
if (context)
|
||||
subscribe(context.extension, name, {
|
||||
if (context && (name !== "runtime.onInstalled" || (contents.getType() === "backgroundPage" && !context.frame.parent)))
|
||||
return subscribe(context.extension, name, {
|
||||
kind: "frame",
|
||||
process: context.frame.processId,
|
||||
routing: context.frame.routingId,
|
||||
|
|
@ -210,8 +223,21 @@ export async function createExtensionHost(input: {
|
|||
|
||||
return {
|
||||
emit,
|
||||
// Only an approved install arms this event, never a startup load. Registration and load completion can race.
|
||||
prepareInstall(id: string, previousVersion: string | undefined) {
|
||||
const pending = Promise.withResolvers<Install | undefined>()
|
||||
installs.set(id, pending.promise)
|
||||
const info: Install = previousVersion === undefined ? { reason: "install" } : { reason: "update", previousVersion }
|
||||
|
||||
return (success: boolean) => {
|
||||
pending.resolve(success ? info : undefined)
|
||||
|
||||
if (!success) installs.delete(id)
|
||||
}
|
||||
},
|
||||
/** Forgets an extension's listeners, as when it is removed or turned off. */
|
||||
forget(extension: string) {
|
||||
installs.delete(extension)
|
||||
subscribers.forEach((byExtension) => byExtension.delete(extension))
|
||||
input.modules.forEach((module) => module.forget?.(extension))
|
||||
},
|
||||
|
|
@ -233,6 +259,7 @@ export async function createExtensionHost(input: {
|
|||
})
|
||||
workers.clear()
|
||||
subscribers.clear()
|
||||
installs.clear()
|
||||
input.modules.forEach((module) => module.dispose?.())
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ export async function createExtensionApis(input: {
|
|||
const extensions = () => input.session.extensions.getAllExtensions()
|
||||
const manifest = createManifests()
|
||||
const tabs = createExtensionTabs({ emit, extensions, manifest })
|
||||
const menus = createContextMenus({ tabs, emit, extensions, manifest })
|
||||
const menus = createContextMenus({ tabs, emit, extensions, manifest, storage: input.storage })
|
||||
const popups = createPopups({ partition: input.partition, tabs })
|
||||
|
||||
const actions = createActions({
|
||||
|
|
@ -58,6 +58,7 @@ export async function createExtensionApis(input: {
|
|||
log: input.log,
|
||||
manifest,
|
||||
modules: [
|
||||
{ namespaces: [{ path: "runtime", methods: [], events: ["onInstalled"] }], methods: {} },
|
||||
tabs.module,
|
||||
actions.module,
|
||||
createWebNavigation({ tabs, emit }),
|
||||
|
|
@ -75,6 +76,8 @@ export async function createExtensionApis(input: {
|
|||
return {
|
||||
tabs,
|
||||
menu: menus.template,
|
||||
prepareInstall: host.prepareInstall,
|
||||
resetMenus: menus.reset,
|
||||
/** The toolbar button state the extensions menu shows, for extensions that have a button. */
|
||||
action: actions.view,
|
||||
/**
|
||||
|
|
@ -95,6 +98,7 @@ export async function createExtensionApis(input: {
|
|||
},
|
||||
/** Deletes what an extension kept in this app, as when the user removes it. */
|
||||
uninstall(id: string) {
|
||||
menus.remove(id)
|
||||
storageSync.remove(id)
|
||||
},
|
||||
dispose() {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,10 @@ if (href.startsWith("chrome-extension://")) {
|
|||
|
||||
const bridge = {
|
||||
invoke: (name, args) => request("browser-extension:call", [name, args]),
|
||||
subscribe: (name) => void request("browser-extension:subscribe", [name]).catch(() => undefined),
|
||||
subscribe: (name) => void request("browser-extension:subscribe", [name]).then((install) => {
|
||||
// The reply works while a worker is still starting; a pushed event can be dropped before it is running.
|
||||
if (name === "runtime.onInstalled" && install) receiver.dispatch?.(name, [install])
|
||||
}).catch(() => undefined),
|
||||
listen: (dispatch) => {
|
||||
receiver.dispatch = dispatch
|
||||
},
|
||||
|
|
|
|||
|
|
@ -309,9 +309,15 @@ export async function createBrowserProfile(input: {
|
|||
|
||||
const folder = record.directory
|
||||
const previous = stored.value.find((item) => item.id === record.id)
|
||||
const previousVersion = previous && details.get(previous.id)?.version
|
||||
|
||||
// Chromium keeps the loaded copy's files open, and Windows moves no open file.
|
||||
if (previous && session.extensions.getExtension(previous.id)) session.extensions.removeExtension(previous.id)
|
||||
if (previous) {
|
||||
apis.forget(previous.id)
|
||||
|
||||
if (session.extensions.getExtension(previous.id)) session.extensions.removeExtension(previous.id)
|
||||
}
|
||||
|
||||
const swapped = await swapIn(staging, folder)
|
||||
|
||||
if (!swapped) {
|
||||
|
|
@ -322,15 +328,25 @@ export async function createBrowserProfile(input: {
|
|||
return { type: "failed", reason: "manifest" }
|
||||
}
|
||||
|
||||
const result = await add(record)
|
||||
const restoreMenus = previous && apis.resetMenus(previous.id)
|
||||
const finishInstall = apis.prepareInstall(record.id, previousVersion)
|
||||
|
||||
const result = await add(record).catch((cause: unknown) => {
|
||||
finishInstall(false)
|
||||
throw cause
|
||||
})
|
||||
|
||||
finishInstall(result.type === "installed")
|
||||
|
||||
if (result.type === "installed") {
|
||||
|
||||
if (swapped.backup) void rm(swapped.backup, { recursive: true, force: true }).catch(() => undefined)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// The new copy did not load: it goes, and the previous one, if any, comes back as it was.
|
||||
restoreMenus?.()
|
||||
await rm(folder, { recursive: true, force: true }).catch(() => undefined)
|
||||
|
||||
if (swapped.backup) await rename(swapped.backup, folder).catch(() => undefined)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue