diff --git a/packages/app/component-tests/extension-host.fixture.tsx b/packages/app/component-tests/extension-host.fixture.tsx index 215cb980e3a..4922952f6df 100644 --- a/packages/app/component-tests/extension-host.fixture.tsx +++ b/packages/app/component-tests/extension-host.fixture.tsx @@ -34,6 +34,8 @@ import { Persist, persisted } from "@/runtime/persistence/storage" import { ServerScope } from "@/runtime/server/scope" import { ExtensionHostProvider, useExtensionHost, type HostApiFactories } from "../src/runtime/extension/host" import { createHostApis } from "../src/runtime/extension/host-apis" +import { createInstalled } from "../src/runtime/extension/installed" +import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge" import { createRegion, RegionContent } from "../src/runtime/extension/panels" import { ExtensionSlot } from "../src/runtime/extension/render" import { persistedHandle } from "../src/runtime/extension/stores" @@ -199,6 +201,7 @@ export function mountExtensionHost() { export function mountExtensions(input: { definitions: readonly Definition[] disabled?: readonly string[] + bridge?: Parameters[0] stored?: Readonly> /** Shows the production developer settings page for status-label contracts. */ settings?: boolean @@ -242,10 +245,24 @@ export function mountExtensions(input: { }) function MountedHost() { + const installed = input.bridge ? createInstalled(input.bridge) : undefined + + const disabledState = createMemo(() => { + if (!installed) return disabled() + + const state = installed.enableState() + + if (!state) return undefined + + return new Set( + input.definitions.flatMap((definition) => (extensionEnabled(definition, state) ? [] : [definition.id])), + ) + }) + return ( diff --git a/packages/app/component-tests/extension-host.spec.ts b/packages/app/component-tests/extension-host.spec.ts index 27920dd6e1e..c867482b16d 100644 --- a/packages/app/component-tests/extension-host.spec.ts +++ b/packages/app/component-tests/extension-host.spec.ts @@ -9,6 +9,7 @@ import type { SessionRef, SessionScreen, } from "@opencode/gui-extensions/sdk" +import type { Bridge, BridgeMessage, EnableState, Installed } from "@opencode/gui-extensions/sdk/bridge" import { expect, sourceURL, story } from "../../storybook/playwright/story" const fixture = sourceURL(new URL("./extension-host.fixture.tsx", import.meta.url)) @@ -895,3 +896,158 @@ story("declared global stores load before setup, so setup reads the stored value expect(result).toEqual({ held: { status: "loading", seen: [] }, seen: [true] }) }) + +story("startup enable state does not wait for the manager, and live updates beat older replies", async ({ page }) => { + const result = await page.evaluate(async (fixture) => { + const { Contract, mountExtensions, until } = await import(fixture) + const Provider: Contract = Contract.define("disabled.value") + const Dependent: Contract = Contract.define("dependent.value") + const observed = { read: (): Live => ({ status: "pending" }) } + const initial = Promise.withResolvers() + const reply = Promise.withResolvers() + const listeners = new Set<(message: BridgeMessage) => void>() + const setups: string[] = [] + + const list = (disabled: readonly string[]): Installed[] => + ["dependent", "enabled", "disabled"].map((id) => ({ + id, + name: id, + version: "1", + builtin: true, + enabled: !disabled.includes(id), + })) + + const bridge: Bridge = { + packaged: false, + call: async () => undefined, + subscribe: async () => ({ available: false }), + on: (listener) => { + listeners.add(listener) + + return () => void listeners.delete(listener) + }, + embed() {}, + capture: async () => undefined, + runMenubarItem() {}, + configure() {}, + manager: { + initial: initial.promise, + list: () => reply.promise, + enable: async () => {}, + disable: async () => {}, + reload: async () => {}, + install: async () => {}, + remove: async () => {}, + source: async () => "", + asset: () => "", + }, + } + + const host = mountExtensions({ + bridge, + // The consumer comes first; the provider's old-id setting arrives asynchronously from the preload. + definitions: [ + { + id: "dependent", + requires: { provider: Provider }, + provides: { value: Dependent }, + renderer: async () => ({ + default: (ctx: Context) => { + setups.push("dependent") + ctx.provide(Dependent, 2) + }, + }), + }, + { + id: "enabled", + uses: { value: Dependent }, + renderer: async () => ({ + default: (ctx: Context & { uses: { value: () => Live } }) => { + setups.push("enabled") + observed.read = ctx.uses.value + }, + }), + }, + { + id: "disabled", + legacy: ["previous"], + provides: { value: Provider }, + renderer: async () => ({ + default: (ctx: Context) => { + setups.push("disabled") + ctx.provide(Provider, 1) + }, + }), + }, + ], + }) + + await new Promise((resolve) => setTimeout(resolve, 50)) + const before = [...setups] + initial.resolve([{ id: "previous", enabled: false }]) + await until(() => host.ready()) + + const started = { + setups: [...setups], + status: host.status("disabled"), + dependent: host.status("dependent"), + live: observed.read(), + } + + const unknown: { ready: boolean; setups: string[]; status?: string }[] = [] + + // A failed startup reply must not temporarily activate the disabled extension while list() waits. + for (const failure of ["unknown", "rejected"]) { + const initial = failure === "unknown" ? Promise.resolve(undefined) : Promise.reject(new Error("snapshot failed")) + const reply = Promise.withResolvers() + + const failed = mountExtensions({ + bridge: { ...bridge, manager: { ...bridge.manager, initial, list: () => reply.promise } }, + definitions: [{ id: "disabled", renderer: async () => ({ default: () => void setups.push("wrongly enabled") }) }], + }) + + await new Promise((resolve) => setTimeout(resolve, 50)) + const blocked = { ready: failed.ready(), setups: [...setups] } + + reply.resolve(list(["disabled"])) + await until(() => failed.ready()) + unknown.push({ ...blocked, status: failed.status("disabled") }) + failed.unmount() + } + + listeners.forEach((listener) => listener({ type: "extensions", list: list(["enabled"]) })) + await until( + () => + host.status("disabled") === "active" && + host.status("enabled") === "disabled" && + host.status("dependent") === "active", + ) + reply.resolve(list(["disabled"])) + await new Promise((resolve) => setTimeout(resolve, 50)) + + const updated = { + setups: [...setups], + status: [host.status("enabled"), host.status("disabled"), host.status("dependent")], + } + + host.unmount() + + return { before, started, unknown, updated, listeners: listeners.size } + }, fixture) + + expect(result).toEqual({ + before: [], + started: { + setups: ["enabled"], + status: "disabled", + dependent: "blocked", + live: { status: "inactive", reason: "blocked" }, + }, + unknown: [ + { ready: false, setups: ["enabled"], status: "disabled" }, + { ready: false, setups: ["enabled"], status: "disabled" }, + ], + updated: { setups: ["enabled", "disabled", "dependent"], status: ["disabled", "active", "active"] }, + listeners: 0, + }) +}) diff --git a/packages/app/src/runtime/extension/installed.ts b/packages/app/src/runtime/extension/installed.ts index 5514035c839..d135b1ab7b0 100644 --- a/packages/app/src/runtime/extension/installed.ts +++ b/packages/app/src/runtime/extension/installed.ts @@ -1,19 +1,24 @@ -import { createResource, onCleanup } from "solid-js" +import { createMemo, createResource, onCleanup } from "solid-js" import { createStore, reconcile } from "solid-js/store" import type { Bridge, Installed } from "@opencode/gui-extensions/sdk/bridge" -/** The extensions main reports to this window: the initial list, then every list it pushes. */ +/** Saved enable preferences and manager metadata; activation and blocked-dependency status belong to the host. */ export function createInstalled(bridge: Bridge | undefined) { - const [state, setState] = createStore({ list: [] as Installed[] }) + const [state, setState] = createStore<{ list?: readonly Installed[] }>({}) // A pushed list is newer than the initial reply, so a reply that arrives after one is dropped. const pushed = { count: 0 } - const [loaded] = createResource(async () => { - if (!bridge) return true + const [initial] = createResource(async () => (bridge ? bridge.manager.initial?.catch(() => undefined) : [])) + + // Metadata still loads for settings and failure reporting. Activation can use known preload rows before it arrives. + createResource(async () => { + if (!bridge) return + const seen = pushed.count const list = await bridge.manager.list() + if (pushed.count === seen) setState("list", reconcile([...list])) - return true }) + if (bridge) onCleanup( bridge.on((message) => { @@ -22,5 +27,9 @@ export function createInstalled(bridge: Bridge | undefined) { setState("list", reconcile([...message.list])) }), ) - return { loaded, list: () => state.list } + + return { + enableState: createMemo(() => state.list ?? initial.latest), + list: () => state.list ?? [], + } } diff --git a/packages/app/src/runtime/extension/root.tsx b/packages/app/src/runtime/extension/root.tsx index 7f0b9c0d7ab..d07caf1b117 100644 --- a/packages/app/src/runtime/extension/root.tsx +++ b/packages/app/src/runtime/extension/root.tsx @@ -1,4 +1,5 @@ import { createMemo, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js" +import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge" import type { Definition } from "@opencode/gui-extensions/sdk" import { builtins } from "./builtins" import { createInstalled } from "./installed" @@ -35,12 +36,6 @@ export function ExtensionRoot(props: ParentProps) { onCleanup(ipcs.dispose) const installed = createInstalled(bridge) - const disabled = createMemo(() => { - if (!installed.loaded()) return undefined - - return new Set(installed.list().flatMap((item) => (item.enabled ? [] : [item.id]))) - }) - const os = platform.platform === "desktop" ? platform.os : undefined // Built-ins only: installed `.ocdx` archives run their main entry until that format ships renderer bundles. @@ -48,6 +43,15 @@ export function ExtensionRoot(props: ParentProps) { (definition: Definition) => !definition.os || (!!os && definition.os.includes(os)), ) + // Only enable preferences cross this boundary; the host derives blocked status from live hard dependencies. + const disabled = createMemo(() => { + const state = installed.enableState() + + if (!state) return undefined + + return new Set(definitions.flatMap((definition) => (extensionEnabled(definition, state) ? [] : [definition.id]))) + }) + const failed = (id: string) => installed.list().some((item) => item.id === id && item.error !== undefined) return ( diff --git a/packages/app/src/runtime/platform/platform.tsx b/packages/app/src/runtime/platform/platform.tsx index f6edac52cd6..1bf530d0320 100644 --- a/packages/app/src/runtime/platform/platform.tsx +++ b/packages/app/src/runtime/platform/platform.tsx @@ -7,7 +7,9 @@ import type { DraftStore } from "@/runtime/persistence/drafts" import type { Bridge } from "@opencode/gui-extensions/sdk/bridge" type PickerPaths = string | string[] | null + type OpenDirectoryPickerOptions = { title?: string; multiple?: boolean } + type OpenAttachmentPickerOptions = { title?: string multiple?: boolean @@ -15,8 +17,11 @@ type OpenAttachmentPickerOptions = { extensions?: string[] defaultPath?: string } + type SaveFilePickerOptions = { title?: string; defaultPath?: string } + type PlatformName = "web" | "desktop" + type DesktopOS = "macos" | "windows" | "linux" export type FatalRendererErrorLog = { @@ -53,9 +58,9 @@ type PlatformBase = { notify(title: string, description?: string, onClick?: () => void): Promise /** Open a native attachment picker and read selected files sequentially (desktop only) */ - openAttachmentPickerDialog?( + openAttachmentPickerDialog?( opts: OpenAttachmentPickerOptions, - onFile: (file: File) => Promise, + onFile: (file: File) => Promise, ): Promise /** Resolve the native source path for a desktop File. */ diff --git a/packages/app/test-browser/extension-installed.test.ts b/packages/app/test-browser/extension-installed.test.ts index 8e4cdc4edc0..5fd6de33595 100644 --- a/packages/app/test-browser/extension-installed.test.ts +++ b/packages/app/test-browser/extension-installed.test.ts @@ -40,8 +40,8 @@ test("a list main pushes while the initial list is pending wins over the older r listeners.forEach((listener) => listener({ type: "extensions", list: [{ ...extension, enabled: false }] })) reply.resolve([{ ...extension, enabled: true }]) await Bun.sleep(0) - expect({ loaded: root.installed.loaded(), enabled: root.installed.list().map((item) => item.enabled) }).toEqual({ - loaded: true, + expect({ known: root.installed.enableState() !== undefined, enabled: root.installed.list().map((item) => item.enabled) }).toEqual({ + known: true, enabled: [false], }) root.dispose() diff --git a/packages/desktop/src/main/extension/enable-state.ts b/packages/desktop/src/main/extension/enable-state.ts new file mode 100644 index 00000000000..791b825c3fc --- /dev/null +++ b/packages/desktop/src/main/extension/enable-state.ts @@ -0,0 +1,12 @@ +import type { DatabaseSync } from "node:sqlite" +import type { EnableState } from "@opencode/gui-extensions/sdk/bridge" + +/** Explicit settings only: both startup readers and the manager resolve absent rows through the same SDK rule. */ +export function readEnableState(db: DatabaseSync): readonly EnableState[] { + return db.prepare("SELECT id, enabled FROM extension").all().map((row) => { + // SAFETY: extension.id is TEXT PRIMARY KEY; extension.enabled is INTEGER NOT NULL in every journaled schema. + const id = row.id as string + + return { id, enabled: row.enabled === 1 } + }) +} diff --git a/packages/desktop/src/main/extension/host.ts b/packages/desktop/src/main/extension/host.ts index 00b35c4e5c4..bb976f7a1ac 100644 --- a/packages/desktop/src/main/extension/host.ts +++ b/packages/desktop/src/main/extension/host.ts @@ -128,6 +128,7 @@ export function createHost(input: { const manager = createManager( input.db, (id) => id.startsWith("opencode") || definitions.some((definition) => definition.id === id), + definitions, ) const embeds = createEmbeds() diff --git a/packages/desktop/src/main/extension/manager.test.ts b/packages/desktop/src/main/extension/manager.test.ts new file mode 100644 index 00000000000..67db5895e41 --- /dev/null +++ b/packages/desktop/src/main/extension/manager.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from "bun:test" +import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge" +import details from "../../../../gui-extensions/src/details/index" +import context from "../../../../gui-extensions/src/context/index" +import { openDatabase } from "../storage/database" +import { extension } from "../storage/schema" +import { readEnableState } from "./enable-state" +import { createManager } from "./manager" + +test.each([ + { name: "no setting", rows: [], expected: true }, + { name: "an old disabled setting", rows: [{ id: "older", enabled: false }], expected: false }, + { name: "an old enabled setting", rows: [{ id: "older", enabled: true }], expected: true }, + { + name: "the newest old setting", + rows: [{ id: "older", enabled: false }, { id: "previous", enabled: true }], + expected: true, + }, + { + name: "the current enabled setting", + rows: [{ id: "previous", enabled: false }, { id: "current", enabled: true }], + expected: true, + }, + { + name: "the current disabled setting", + rows: [{ id: "previous", enabled: true }, { id: "current", enabled: false }], + expected: false, + }, +])("both hosts resolve $name from real database rows, and a new setting wins", (input) => { + const database = openDatabase(":memory:") + const definition = { id: "current", legacy: ["previous", "older"] } + const manager = createManager(database.db, () => false, [definition]) + input.rows.forEach((row) => database.db.insert(extension).values(row).run()) + + expect(manager.enabled(definition.id)).toBe(input.expected) + expect(extensionEnabled(definition, readEnableState(database.db.$client))).toBe(input.expected) + + const before = database.db.select().from(extension).all() + + manager.setEnabled(definition.id, !input.expected) + expect(manager.enabled(definition.id)).toBe(!input.expected) + expect(extensionEnabled(definition, readEnableState(database.db.$client))).toBe(!input.expected) + expect(database.db.select().from(extension).all().filter((row) => row.id !== definition.id)).toEqual( + before.filter((row) => row.id !== definition.id), + ) + database.close() +}) + +test.each([details, context])("$id preserves disabled state from its shipping legacy declaration", (definition) => { + const database = openDatabase(":memory:") + const manager = createManager(database.db, () => false, [definition]) + database.db.insert(extension).values({ id: definition.legacy[0], enabled: false }).run() + + expect(manager.enabled(definition.id)).toBe(false) + expect(extensionEnabled(definition, readEnableState(database.db.$client))).toBe(false) + database.close() +}) diff --git a/packages/desktop/src/main/extension/manager.ts b/packages/desktop/src/main/extension/manager.ts index c4671e935b3..e6d01f28202 100644 --- a/packages/desktop/src/main/extension/manager.ts +++ b/packages/desktop/src/main/extension/manager.ts @@ -1,19 +1,20 @@ import { randomUUID } from "node:crypto" import { and, eq, isNotNull } from "drizzle-orm" -import { net } from "electron" -import { Option } from "effect" +import { Option, Predicate } from "effect" +import type { Definition } from "@opencode/gui-extensions/sdk/main" +import { extensionEnabled } from "@opencode/gui-extensions/sdk/bridge" import type { Database } from "../storage/database" import { extension, extensionFile } from "../storage/schema" import { ExtensionError } from "./error" import { decodeManifest } from "./manifest" +import { readEnableState } from "./enable-state" /** * Enable state and installed archives, committed together in the desktop database. Archive installs are groundwork for * `.ocdx` extensions: an installed archive runs its main entry only, the renderer loads built-ins until that format * ships renderer bundles, and packaged builds refuse the manager until installs have a trust model. */ -export function createManager(db: Database, reserved: (id: string) => boolean) { - const row = (id: string) => db.select().from(extension).where(eq(extension.id, id)).get() +export function createManager(db: Database, reserved: (id: string) => boolean, definitions: readonly Definition[]) { return { /** Every installed archive. A manifest that no longer decodes is reported, not dropped. */ installed() { @@ -29,9 +30,12 @@ export function createManager(db: Database, reserved: (id: string) => boolean) { manifest: Option.getOrUndefined(decodeManifest(item.manifest)), })) }, - /** Extensions without a row keep the default: enabled. */ + /** The current id wins, then declared legacy ids newest first; no setting means enabled. */ enabled(id: string) { - return row(id)?.enabled ?? true + return extensionEnabled( + definitions.find((definition) => definition.id === id) ?? { id }, + readEnableState(db.$client), + ) }, setEnabled(id: string, enabled: boolean) { db.insert(extension).values({ id, enabled }).onConflictDoUpdate({ target: extension.id, set: { enabled } }).run() @@ -49,9 +53,11 @@ export function createManager(db: Database, reserved: (id: string) => boolean) { }, async install(source: Uint8Array | string) { const { readArchive } = await import("./archive") - const archive = await readArchive(typeof source === "string" ? await download(source) : source) + const archive = await readArchive(Predicate.isString(source) ? await download(source) : source) const id = archive.manifest.id + if (reserved(id)) throw new ExtensionError("reserved") + const values = { enabled: true, manifest: JSON.stringify(archive.manifest), revision: randomUUID() } db.transaction((tx) => { tx.delete(extensionFile).where(eq(extensionFile.extension_id, id)).run() @@ -63,6 +69,7 @@ export function createManager(db: Database, reserved: (id: string) => boolean) { tx.insert(extensionFile).values({ extension_id: id, path: file.path, data: file.data }).run(), ) }) + return archive.manifest }, remove(id: string) { @@ -76,27 +83,43 @@ export function createManager(db: Database, reserved: (id: string) => boolean) { async function download(url: string) { const { archiveLimit } = await import("./archive") + if (!URL.canParse(url) || !["http:", "https:"].includes(new URL(url).protocol)) throw new ExtensionError("url") - const response = await net.fetch(url).catch((error: unknown) => { + + const { net } = await import("electron") + + const response = await net.fetch(url).catch((error) => { throw new ExtensionError("download", { cause: error }) }) + if (!response.ok || !response.body) throw new ExtensionError("download", { message: String(response.status) }) + if (Number(response.headers.get("content-length")) > archiveLimit) { await response.body.cancel() + throw new ExtensionError("tooLarge") } + const reader = response.body.getReader() const chunks: Uint8Array[] = [] + const pump = async (size: number): Promise => { const next = await reader.read() + if (next.done) return size + if (size + next.value.byteLength > archiveLimit) { await reader.cancel() + throw new ExtensionError("tooLarge") } + chunks.push(next.value) + return pump(size + next.value.byteLength) } + await pump(0) + return Buffer.concat(chunks) } diff --git a/packages/desktop/src/main/storage/database.test.ts b/packages/desktop/src/main/storage/database.test.ts index 9cf93547305..64313112434 100644 --- a/packages/desktop/src/main/storage/database.test.ts +++ b/packages/desktop/src/main/storage/database.test.ts @@ -10,6 +10,7 @@ const tables = (db: ReturnType) => db .all<{ name: string }>(sql`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) .map((row) => row.name) + const expected = ["blob", "document", "extension", "extension_file", "migration", "state"] describe("database", () => { @@ -32,17 +33,32 @@ describe("database", () => { expect(migrate(db)).toEqual([]) }) + test("a failed migration rolls back the journal without losing existing data", () => { + const native = new DatabaseSync(":memory:") + native.exec("CREATE TABLE state (value TEXT); INSERT INTO state VALUES ('kept')") + const db = drizzle({ client: native }) + + expect(() => migrate(db)).toThrow() + expect(db.all(sql`SELECT id FROM migration`)).toEqual([]) + expect(db.all(sql`SELECT value FROM state`)).toEqual([{ value: "kept" }]) + native.close() + }) + test("rendered registry matches the drizzle-kit output on disk", async () => { const directory = path.join(import.meta.dirname, "migration") + const ids = (await Array.fromAsync(new Bun.Glob("*/migration.sql").scan({ cwd: directory }))) .map((file) => path.dirname(file)) .sort() + expect(migrations.map((migration) => migration.id)).toEqual(ids) + for (const migration of migrations) { const source = (await Bun.file(path.join(directory, migration.id, "migration.sql")).text()).replaceAll( "\r\n", "\n", ) + for (const statement of migration.statements) expect(source).toContain(statement) } }) diff --git a/packages/desktop/src/main/storage/database.ts b/packages/desktop/src/main/storage/database.ts index 02f270746f0..8d11d15f990 100644 --- a/packages/desktop/src/main/storage/database.ts +++ b/packages/desktop/src/main/storage/database.ts @@ -1,17 +1,9 @@ import { DatabaseSync } from "node:sqlite" -import { sql } from "drizzle-orm" import { drizzle } from "drizzle-orm/node-sqlite" -import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core" -import { migrations } from "./migration.gen" +import { migrateDatabase } from "./migration" export type Database = ReturnType -// Owned by the runner rather than schema.ts so drizzle-kit never tries to migrate the journal itself. -const journal = sqliteTable("migration", { - id: text().primaryKey(), - time_completed: integer().notNull(), -}) - export function openDatabase(filename: string) { const native = new DatabaseSync(filename) // WAL keeps readers off the writer. NORMAL fsyncs at checkpoints only, which survives an app @@ -19,30 +11,10 @@ export function openDatabase(filename: string) { native.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA temp_store=MEMORY") const db = drizzle({ client: native }) migrate(db) + return { db, close: () => native.close() } } export function migrate(db: Database) { - db.run(sql`CREATE TABLE IF NOT EXISTS ${journal} (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`) - const applied = new Set( - db - .select({ id: journal.id }) - .from(journal) - .all() - .map((row) => row.id), - ) - // drafts.sqlite predates the journal: its tables were created by hand, so the migration that - // would create them is recorded as applied instead of run. - const legacy = - applied.size === 0 && - db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'document'`) !== undefined - const pending = migrations.filter((migration) => !applied.has(migration.id)) - if (pending.length === 0) return [] - db.transaction((tx) => { - pending.forEach((migration, index) => { - if (!(legacy && index === 0)) migration.statements.forEach((statement) => tx.run(sql.raw(statement))) - tx.insert(journal).values({ id: migration.id, time_completed: Date.now() }).run() - }) - }) - return pending.map((migration) => migration.id) + return migrateDatabase(db.$client) } diff --git a/packages/desktop/src/main/storage/index.ts b/packages/desktop/src/main/storage/index.ts index 05a5ce3fc01..b32c5e194c2 100644 --- a/packages/desktop/src/main/storage/index.ts +++ b/packages/desktop/src/main/storage/index.ts @@ -8,6 +8,7 @@ import { setStorageSnapshotProvider } from "./snapshot" import { createDraftStore } from "./drafts" import { importLegacyStores } from "./legacy" import { createStateStore } from "./state" +import { readEnableState } from "../extension/enable-state" export type Interface = ReturnType @@ -19,9 +20,11 @@ export const layer = Layer.effect( const path = yield* Path.Path const runFork = Effect.runForkWith(yield* Effect.context()) const userData = app.getPath("userData") + const storage = make(path.join(userData, "drafts.sqlite"), (error) => runFork(Effect.logError("storage flush failed", { error })), ) + yield* importLegacyStores(storage.db, userData).pipe( Effect.tap((result) => result.removed.length === 0 @@ -30,10 +33,10 @@ export const layer = Layer.effect( ), Effect.catch((error) => Effect.logWarning("failed to import legacy store files", { error })), ) - const wire = (_event: Electron.Event, win: BrowserWindow) => win.on("session-end", storage.flush) + const wire = (_event: Electron.Event | undefined, win: BrowserWindow) => win.on("session-end", storage.flush) app.on("before-quit", storage.flush) app.on("browser-window-created", wire) - BrowserWindow.getAllWindows().forEach((win) => wire({} as Electron.Event, win)) + BrowserWindow.getAllWindows().forEach((win) => wire(undefined, win)) yield* Effect.addFinalizer(() => Effect.sync(() => { app.off("before-quit", storage.flush) @@ -42,17 +45,24 @@ export const layer = Layer.effect( storage.close() }), ) - setStorageSnapshotProvider((names) => Object.fromEntries(names.map((name) => [name, storage.state.items(name)]))) + setStorageSnapshotProvider((names) => ({ + storage: Object.fromEntries(names.map((name) => [name, storage.state.items(name)])), + extensions: readEnableState(storage.db.$client), + })) marks.storage = Date.now() + return Service.of(storage) }), ) // The file keeps its historical name; renaming it would mean moving the drafts it already holds. +// SAFETY: this observer only reports caught write failures; it never interprets them as stored values. +// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above export function make(filename: string, onError?: (error: unknown) => void) { const database = openDatabase(filename) const state = createStateStore(database.db, { onError }) const drafts = createDraftStore(database.db, { onError }) + return { db: database.db, state, diff --git a/packages/desktop/src/main/storage/migration.ts b/packages/desktop/src/main/storage/migration.ts new file mode 100644 index 00000000000..ae7eb7f27a5 --- /dev/null +++ b/packages/desktop/src/main/storage/migration.ts @@ -0,0 +1,33 @@ +import type { DatabaseSync } from "node:sqlite" +import { migrations } from "./migration.gen" + +/** The desktop journal, usable by the early preload read without loading Drizzle or Effect. */ +export function migrateDatabase(db: DatabaseSync) { + db.exec("CREATE TABLE IF NOT EXISTS migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)") + + const applied = new Set(db.prepare("SELECT id FROM migration").all().map((row) => row.id)) + + // drafts.sqlite predates the journal: adopt its existing draft tables instead of creating them again. + const legacy = + applied.size === 0 && + db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'document'").get() !== undefined + + const pending = migrations.filter((migration) => !applied.has(migration.id)) + + if (pending.length === 0) return [] + db.exec("BEGIN") + + try { + const record = db.prepare("INSERT INTO migration (id, time_completed) VALUES (?, ?)") + pending.forEach((migration, index) => { + if (!(legacy && index === 0)) migration.statements.forEach((statement) => db.exec(statement)) + record.run(migration.id, Date.now()) + }) + db.exec("COMMIT") + } catch (error) { + db.exec("ROLLBACK") + throw error + } + + return pending.map((migration) => migration.id) +} diff --git a/packages/desktop/src/main/storage/snapshot.ts b/packages/desktop/src/main/storage/snapshot.ts index 629e9b74d07..d46bea1bd22 100644 --- a/packages/desktop/src/main/storage/snapshot.ts +++ b/packages/desktop/src/main/storage/snapshot.ts @@ -1,56 +1,29 @@ -import { existsSync, readdirSync } from "node:fs" -import path from "node:path" -import { DatabaseSync } from "node:sqlite" import { app, ipcMain } from "electron" -import { StorageSnapshotChannel, type StorageSnapshot } from "../../shared/ipc-transport" +import { WindowSnapshotChannel, type WindowSnapshot } from "../../shared/ipc-transport" import { isRendererUrl } from "../windows/scheme" +import { readWindowSnapshot } from "./window-snapshot" // A window's preload asks for the namespaces its shell reads before the page runs, so the first // render is the hydrated one. Until the storage layer is up (the first window asks before it exists) // the answer comes from the database file; the layer takes over so later windows see queued writes. -type Provider = (names: ReadonlyArray) => StorageSnapshot +type Provider = (names: ReadonlyArray) => WindowSnapshot -let provider: Provider = readFromDisk +let provider: Provider = (names) => readWindowSnapshot(app.getPath("userData"), names) export function setStorageSnapshotProvider(next: Provider) { provider = next } export function registerStorageSnapshotHandler() { - ipcMain.handle(StorageSnapshotChannel, (event, names: unknown): StorageSnapshot => { - if (!isRendererUrl(event.senderFrame?.url)) return {} - if (!Array.isArray(names)) return {} - return provider(names.filter((name): name is string => typeof name === "string")) + // SAFETY: Electron delivers untrusted IPC arguments; accept only an array whose every element is a string here. + // oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above + ipcMain.handle(WindowSnapshotChannel, (event, names: unknown): WindowSnapshot => { + if (!isRendererUrl(event.senderFrame?.url)) return { storage: {} } + + // SAFETY: this dependency-free boundary check establishes the complete array-of-strings contract. + // oxlint-disable-next-line anti-slop/no-runtime-typeof -- see SAFETY above + if (!Array.isArray(names) || !names.every((name) => typeof name === "string")) return { storage: {} } + + return provider(names) }) } - -// Nothing has been written in this process yet, so every namespace is at revision 0, as the -// storage layer would report before its first update. Legacy electron-store files still waiting -// to be imported would make the database stale for this launch, so the renderer asks the layer then. -function readFromDisk(names: ReadonlyArray): StorageSnapshot { - const userData = app.getPath("userData") - const file = path.join(userData, "drafts.sqlite") - if (!existsSync(file)) return {} - if (readdirSync(userData).some((name) => name === "default.dat" || /^opencode\..+\.dat$/.test(name))) return {} - try { - const db = new DatabaseSync(file) - try { - const rows = db.prepare("SELECT key, value FROM state WHERE name = ?") - return Object.fromEntries( - names.map((name) => [ - name, - { - items: Object.fromEntries( - (rows.all(name) as { key: string; value: string }[]).map((row) => [row.key, row.value]), - ), - revision: 0, - }, - ]), - ) - } finally { - db.close() - } - } catch { - return {} - } -} diff --git a/packages/desktop/src/main/storage/window-snapshot.test.ts b/packages/desktop/src/main/storage/window-snapshot.test.ts new file mode 100644 index 00000000000..9ed1e335e6c --- /dev/null +++ b/packages/desktop/src/main/storage/window-snapshot.test.ts @@ -0,0 +1,41 @@ +import { afterEach, expect, test } from "bun:test" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" +import { DatabaseSync } from "node:sqlite" +import { readWindowSnapshot } from "./window-snapshot" +import { migrateDatabase } from "./migration" + +const roots: string[] = [] + +// Bun's node:sqlite shim can retain file handles on Windows after close; only these owned test directories are removed. +afterEach(() => Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }).catch(() => undefined)))) + +test.each(["missing", "unreadable"])("a $s database distinguishes default enable state from unknown", async (input) => { + const root = await mkdtemp(path.join(tmpdir(), "opencode-window-snapshot-")) + roots.push(root) + + if (input === "unreadable") await Bun.write(path.join(root, "drafts.sqlite"), "not a SQLite database") + + expect(readWindowSnapshot(root, ["shell"])).toEqual( + input === "missing" ? { storage: {}, extensions: [] } : { storage: {} }, + ) +}) + +test.each([false, true])("the early snapshot keeps explicit rows even with legacy files: %s", async (legacy) => { + const root = await mkdtemp(path.join(tmpdir(), "opencode-window-snapshot-")) + roots.push(root) + const db = new DatabaseSync(path.join(root, "drafts.sqlite")) + migrateDatabase(db) + db.prepare("INSERT INTO state (name, key, value, updated_at) VALUES (?, ?, ?, 0)").run("shell", "theme", "dark") + db.prepare("INSERT INTO extension (id, enabled) VALUES (?, ?)").run("previous", 0) + db.prepare("INSERT INTO extension (id, enabled) VALUES (?, ?)").run("current", 1) + db.close() + + if (legacy) await Bun.write(path.join(root, "default.dat"), "{}") + + expect(readWindowSnapshot(root, ["shell"])).toEqual({ + storage: legacy ? {} : { shell: { items: { theme: "dark" }, revision: 0 } }, + extensions: [{ id: "previous", enabled: false }, { id: "current", enabled: true }], + }) +}) diff --git a/packages/desktop/src/main/storage/window-snapshot.ts b/packages/desktop/src/main/storage/window-snapshot.ts new file mode 100644 index 00000000000..d3552ba443f --- /dev/null +++ b/packages/desktop/src/main/storage/window-snapshot.ts @@ -0,0 +1,47 @@ +import { existsSync, readdirSync } from "node:fs" +import path from "node:path" +import { DatabaseSync } from "node:sqlite" +import type { WindowSnapshot } from "../../shared/ipc-transport" +import { migrateDatabase } from "./migration" +import { readEnableState } from "../extension/enable-state" + +// Before the storage layer exists, nothing has been written in this process and every namespace is at revision 0. +// Legacy electron-store files can make storage stale, but explicit extension settings still come from SQLite. +export function readWindowSnapshot(userData: string, names: readonly string[]): WindowSnapshot { + const file = path.join(userData, "drafts.sqlite") + + if (!existsSync(file)) return { storage: {}, extensions: [] } + + try { + const legacy = readdirSync(userData).some((name) => name === "default.dat" || /^opencode\..+\.dat$/.test(name)) + const db = new DatabaseSync(file) + + try { + migrateDatabase(db) + + const rows = db.prepare("SELECT key, value FROM state WHERE name = ?") + + return { + storage: legacy + ? {} + : Object.fromEntries( + names.map((name) => [ + name, + { + // SAFETY: the journaled state table declares both selected columns TEXT NOT NULL. + items: Object.fromEntries( + (rows.all(name) as { key: string; value: string }[]).map((row) => [row.key, row.value]), + ), + revision: 0, + }, + ]), + ), + extensions: readEnableState(db), + } + } finally { + db.close() + } + } catch { + return { storage: {} } + } +} diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts index 9bc1da769f1..57ffce01a2d 100644 --- a/packages/desktop/src/preload/index.ts +++ b/packages/desktop/src/preload/index.ts @@ -2,28 +2,31 @@ import { contextBridge, ipcRenderer, webUtils } from "electron" import { DragCancelEvent, IpcTransportPort, - StorageSnapshotChannel, + WindowSnapshotChannel, storageSnapshotNames, - type StorageSnapshot, + type WindowSnapshot, } from "../shared/ipc-transport" import { windowBootstrapFromArguments } from "../shared/window-bootstrap" ipcRenderer.on(IpcTransportPort, (event) => { const port = event.ports[0] + if (port) window.postMessage(IpcTransportPort, "*", [port]) }) ipcRenderer.on(DragCancelEvent, () => window.dispatchEvent(new Event(DragCancelEvent))) const bootstrap = windowBootstrapFromArguments(process.argv) + // Asked before the page runs, so the stores the shell reads are hydrated on the first render. -const storageSnapshot: Promise = ipcRenderer - .invoke(StorageSnapshotChannel, storageSnapshotNames(bootstrap.id)) - .catch(() => ({})) +const snapshot: Promise = ipcRenderer + .invoke(WindowSnapshotChannel, storageSnapshotNames(bootstrap.id)) + .catch(() => ({ storage: {} })) contextBridge.exposeInMainWorld("electron", { windowID: bootstrap.id, bootstrap, - storageSnapshot, + storageSnapshot: snapshot.then((snapshot) => snapshot.storage), + extensions: snapshot.then((snapshot) => snapshot.extensions), getPathForFile: (file: File) => webUtils.getPathForFile(file), }) diff --git a/packages/desktop/src/preload/types.ts b/packages/desktop/src/preload/types.ts index 4d60ef346ec..c6ac36b98e1 100644 --- a/packages/desktop/src/preload/types.ts +++ b/packages/desktop/src/preload/types.ts @@ -1,9 +1,10 @@ -import type { StorageSnapshot } from "../shared/ipc-transport" +import type { StorageSnapshot, WindowSnapshot } from "../shared/ipc-transport" import type { WindowBootstrap } from "../shared/window-bootstrap" export type ElectronNative = { windowID: string bootstrap: WindowBootstrap storageSnapshot: Promise + extensions: Promise getPathForFile(file: File): string } diff --git a/packages/desktop/src/renderer/extensions.ts b/packages/desktop/src/renderer/extensions.ts index 43a18c63365..2393bb509c5 100644 --- a/packages/desktop/src/renderer/extensions.ts +++ b/packages/desktop/src/renderer/extensions.ts @@ -63,6 +63,7 @@ export function createExtensionBridge(): Bridge { runMenubarItem: (id) => send("ExtensionMenubarItem", { id }), configure: (servers) => send("ExtensionConfigure", { servers }), manager: { + initial: window.electron.extensions, list: () => invoke("ExtensionList"), enable: (id) => manage(invoke("ExtensionEnable", { id })), disable: (id) => manage(invoke("ExtensionDisable", { id })), diff --git a/packages/desktop/src/renderer/platform/index.ts b/packages/desktop/src/renderer/platform/index.ts index 52dda647679..94d4636fa79 100644 --- a/packages/desktop/src/renderer/platform/index.ts +++ b/packages/desktop/src/renderer/platform/index.ts @@ -16,6 +16,7 @@ export type DesktopWindowState = { export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWindowState): Platform { const os = desktopOS() + return { platform: "desktop", os, @@ -30,11 +31,14 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind notify: createDesktopNotify(api), fetch: (input, init) => { if (input instanceof Request) return fetch(input) + return fetch(input, init) }, getDefaultServer: async () => { const url = await api.getDefaultServerUrl().catch(() => null) + if (!url) return null + return ServerConnection.Key.make(url) }, setDefaultServer: async (url) => { @@ -46,6 +50,7 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind setPinchZoomEnabled, onDragCancel: (callback) => { window.addEventListener(DragCancelEvent, callback) + return () => window.removeEventListener(DragCancelEvent, callback) }, runDesktopMenuAction: createDesktopMenuAction(api), @@ -58,7 +63,10 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind function desktopOS() { if (navigator.userAgent.includes("Mac")) return "macos" + if (navigator.userAgent.includes("Windows")) return "windows" + if (navigator.userAgent.includes("Linux")) return "linux" + return undefined } diff --git a/packages/desktop/src/shared/ipc-transport.ts b/packages/desktop/src/shared/ipc-transport.ts index fb60a732216..b47c5b45752 100644 --- a/packages/desktop/src/shared/ipc-transport.ts +++ b/packages/desktop/src/shared/ipc-transport.ts @@ -1,20 +1,35 @@ +import type { EnableState } from "@opencode/gui-extensions/sdk/bridge" + export const IpcTransportPort = "desktop-rpc-port" + export const DragCancelEvent = "opencode:drag-cancel" -export const StorageSnapshotChannel = "desktop-storage-snapshot" + +export const WindowSnapshotChannel = "desktop-window-snapshot" // The main process decodes RPC payloads with the JSON codec, and JSON has no undefined: an // optional field the caller left as `undefined` decodes only when its key is absent. Structured // clone keeps the key, so drop such fields the way JSON.stringify would, leaving bytes untouched. +// SAFETY: transport normalization preserves encoded payloads except undefined keys; the RPC codec validates the result. +/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-runtime-typeof -- see SAFETY above */ export function omitUndefined(value: unknown): unknown { if (Array.isArray(value)) return value.map(omitUndefined) + if (typeof value !== "object" || value === null || value instanceof Uint8Array) return value + return Object.fromEntries( Object.entries(value).flatMap(([key, item]) => (item === undefined ? [] : [[key, omitUndefined(item)]])), ) } +/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-runtime-typeof */ export type StorageSnapshot = Record; revision: number }> +/** The preload's existing startup reply; missing enable state is unknown, not an all-enabled setting. */ +export type WindowSnapshot = { + storage: StorageSnapshot + extensions?: readonly EnableState[] +} + // The namespaces a window reads while its shell mounts. The preload asks for them before the page // runs so the first render already has them; mirrors windowStorage() in // packages/app/src/runtime/persistence/storage.ts. diff --git a/packages/gui-extensions/AGENTS.md b/packages/gui-extensions/AGENTS.md index 0c19752974d..d5a61b8e2e4 100644 --- a/packages/gui-extensions/AGENTS.md +++ b/packages/gui-extensions/AGENTS.md @@ -4,7 +4,7 @@ Built-in features of the desktop and web app, each behind the SDK in `src/sdk/`. ## Structure -- One folder per extension: `index.ts` (`Extension.define({ id, os?, provides?, uses?, requires?, stores?, i18n })`), `contract.ts`, `renderer.tsx`, an optional `main.ts`, and `i18n/.ts`. +- One folder per extension: `index.ts` (`Extension.define({ id, legacy?, os?, provides?, uses?, requires?, stores?, i18n })`), `contract.ts`, `renderer.tsx`, an optional `main.ts`, and `i18n/.ts`. - `src/renderer.ts` and `src/main.ts` are the only files that list the built-ins, each through `Extension.compose`. Main never imports window code. `src/builtins.typecheck.ts` fails the typecheck when a window `uses` or `requires` an Ipc that no main entry provides. - Every extension here ships. Do not add an extension, fixture or wrapper only to document or demonstrate the SDK; the guide shows shipping code. - Another extension may import only your `contract.ts` (tokens and schemas, no runtime code). Declare what other extensions provide in `uses` (or `requires`). Your own tokens, your Ipc included, go in `provides` only: the window reads each as `ctx.uses.` too, and a key that names one token in `provides` and another in `uses` fails to compile. To declare an Ipc without loading its schemas at startup, use `Ipc.ref("id")` and `ctx.uses.name.load(Token)` from the chunk that loads them; never put a reference in `requires`. @@ -48,7 +48,8 @@ An instance lives from `setup` until it is disabled, reloaded, removed, or its w - Desktop storage loads over IPC; web storage is synchronous, so a read before load passes every web e2e test and still breaks desktop. Declare stores (`Store.global`, `Store.session`): a global store is loaded before setup, a session store's `value` is undefined until it loads, and `update` waits for the load. `Storage.store`, for keys only known at runtime, returns the same `Persisted`; derive nothing from it, such as a request, before `value` is defined. - Declare main-process state known up front with `Store.main`; the main entry reads it as `ctx.stores.name` (`MainSetup`), always loaded. Each process's `ctx.stores` holds only its own stores. Main's `ctx.storage.store` is for keys only known at runtime. -- Stored keys live in your extension id's namespace (`extension..`). Moving a stored value goes through `from` (and `from.sessions` for one session's slice of an app key); a list names older homes newest first, for example your earlier id's namespace, then the app key before it. A `pick` returns undefined when the older key holds none of its fields, never an object of undefined fields, or the next home is never read. In main, an older home is `{ settings: key, file? }` or `{ state: [namespace, key] }`. Keep the old field readable until every user has migrated; never drop user data. When you rename an extension, map its command ids in the keybind rename map and its panel keys in `Panel.legacy` too. +- Stored keys live in your extension id's namespace (`extension..`). Move values through `from` (and `from.sessions` for one session's slice of an app key), with older homes newest first. A `pick` returns undefined when the old key holds none of its fields, never an object of undefined fields. Main's older homes are `{ settings: key, file? }` or `{ state: [namespace, key] }`. Keep old fields readable until every user has migrated; never drop user data. +- When you rename an extension, list earlier ids newest first in `Definition.legacy` for enable state, migrate command ids in the keybind rename map, and map panel keys in `Panel.legacy`. - `update` mutates a deep-mutable draft and returns nothing or `undefined`; a returned replacement fails to compile and throws at runtime in both processes. `set` replaces the value. Plain readonly `Schema.Struct` fields work without `mutableKey`. Window `update` and `set` wait for load and apply in call order with each other, including runtime-key stores; main writes reach disk at once. Do not batch main writes yourself. - `Storage.remove(key, { from })` takes the store's `from`, so the older key is never imported again and the key reads as `initial`. diff --git a/packages/gui-extensions/README.md b/packages/gui-extensions/README.md index a30c4fef1a3..6118b023ff4 100644 --- a/packages/gui-extensions/README.md +++ b/packages/gui-extensions/README.md @@ -38,6 +38,7 @@ Unit tests of logic that carries a contract sit beside the code as `*.test.ts`, | Field | What it declares | In the context | | ---------- | ----------------------------------------------------------------------------- | ------------------------------------------------- | | `id` | Prefix of every id: commands, panel keys, stored keys, contract and Ipc ids | `ctx.id` | +| `legacy` | Earlier extension ids, newest first; preserves desktop enable state after a rename | | | `os` | The operating systems it runs on; omit it to run everywhere, the web included | | | `provides` | Contracts from the window entry, Ipcs from the main entry | `ctx.provide(token, impl)`, and `ctx.uses.name()` | | `uses` | Optional dependencies other extensions provide; it works while one is missing | `ctx.uses.name()` is `Live` | @@ -396,7 +397,17 @@ servers: Store.main(Schema.Array(SshConfig), [], { settings: "ssh.servers" }), - `from` imports an older value once, while the store holds none. A list names older homes, newest first. With `pick`, the older key stays for its other owners; a pick returns undefined when that key holds none of its fields, never an object of undefined fields, so the next home is read. - `update(mutate)` edits a deep-mutable draft and must return nothing or `undefined`. Returning the next value is a compile error and throws at runtime in both processes; use `set(next)` to replace the complete value, including main primitives and lists. Plain `Schema.Struct` fields work without `mutableKey`. Window calls wait for load and apply in call order with each other; main writes reach disk immediately. Runtime-key stores have the same contract. - `Storage.remove(key, { from })` reads as `initial` again and never imports `from` again. -- Renaming an extension moves three things: stored keys (`from`), command ids (the keybind rename map in `packages/app/src/settings/keybinds/migration.ts`), and panel keys (`Panel.legacy`). Never drop user data. +- Renaming an extension moves four things: enable state (`Definition.legacy`), stored keys (`from`), command ids (the keybind rename map in `packages/app/src/settings/keybinds/migration.ts`), and panel keys (`Panel.legacy`). Never drop user data. + +Declare earlier ids newest first, for example `Extension.define({ id: "details", legacy: ["summary"] })`. The current id's explicit enable setting always wins. Without one, the first earlier id with a setting wins; with no setting at all, the extension is enabled. Both desktop hosts use this rule. Old rows stay intact, and enable/disable changes write only under the current id. A failed startup snapshot is unknown, so the window waits for the manager list rather than running disabled extensions. + +The enable preference is separate from activation: an enabled extension with an unavailable hard dependency is `blocked`. The window publishes disabled providers before starting enabled entries, so consumers settle as blocked regardless of declaration order. + + + +```ts +legacy: ["summary"], +``` ## Runtime rules diff --git a/packages/gui-extensions/src/context/index.ts b/packages/gui-extensions/src/context/index.ts index def86e05c92..eb844b8015c 100644 --- a/packages/gui-extensions/src/context/index.ts +++ b/packages/gui-extensions/src/context/index.ts @@ -3,6 +3,7 @@ import en from "./i18n/en" export default Extension.define({ id: "context", + legacy: ["usage"], i18n: { en, am: () => import("./i18n/am"), diff --git a/packages/gui-extensions/src/details/index.ts b/packages/gui-extensions/src/details/index.ts index af778ea20ae..223dda494f3 100644 --- a/packages/gui-extensions/src/details/index.ts +++ b/packages/gui-extensions/src/details/index.ts @@ -7,6 +7,7 @@ const Prefs = Schema.Struct({ projectExpanded: Schema.Boolean, serverExpanded: S export default Extension.define({ id: "details", + legacy: ["summary"], uses: { changes: Changes }, stores: { // Stored under the extension's earlier id `summary`, and before extensions in the app settings. diff --git a/packages/gui-extensions/src/sdk/bridge.ts b/packages/gui-extensions/src/sdk/bridge.ts index b21c365e9d1..8ceddd14c33 100644 --- a/packages/gui-extensions/src/sdk/bridge.ts +++ b/packages/gui-extensions/src/sdk/bridge.ts @@ -4,6 +4,32 @@ * Payloads are structured-clone values already encoded with the Ipc's schemas. The `ipc` fields name an Ipc by id. */ +import type { Definition } from "./core" + +/** One explicit desktop enable-state row. An absent row means there is no setting under that id. */ +export interface EnableState { + /** The extension id the user saved a setting under, including ids from before a rename. */ + readonly id: string + /** The saved setting: true enables the extension; false disables it. */ + readonly enabled: boolean +} + +/** + * Resolves desktop enable state without changing stored rows. The current id wins, then legacy ids newest first; + * no matching row means enabled. Both hosts use this rule, including a window's preload snapshot. + * + * @param definition - The current id and its optional earlier ids. + * @param state - Explicit saved rows, or the manager's resolved list. + * @returns Whether the extension is enabled. + */ +export function extensionEnabled(definition: Pick, state: readonly EnableState[]) { + const row = [definition.id, ...(definition.legacy ?? [])] + .map((id) => state.find((item) => item.id === id)) + .find((item) => item !== undefined) + + return row?.enabled ?? true +} + /** Where an embed sits in its window, as the renderer measured it. */ export interface BridgeLayout { /** The embed should be on screen. */ @@ -186,6 +212,12 @@ export interface Bridge { ): void /** The extension manager. */ readonly manager: { + /** + * Explicit enable-state rows from the existing preload startup reply, including earlier ids. Undefined (or an + * omitted promise) means unknown: activation waits for `list()` or a live list, never assumes all are enabled. + * An empty list is authoritative: no saved settings. A rejected promise also falls back to the manager list. + */ + readonly initial?: Promise /** The installed extensions, built-ins included. */ list(): Promise /** diff --git a/packages/gui-extensions/src/sdk/core.ts b/packages/gui-extensions/src/sdk/core.ts index 811281e2c2f..5e9e301b6c0 100644 --- a/packages/gui-extensions/src/sdk/core.ts +++ b/packages/gui-extensions/src/sdk/core.ts @@ -85,6 +85,19 @@ export interface Definition { * all of those; migrate them as the guide describes. */ readonly id: string + /** + * Earlier extension ids, newest first, used to preserve desktop enable state after a rename. The current id's + * explicit setting wins; otherwise the first earlier id with a setting wins. Omit this for a new extension. + * With no setting under any id, the extension is enabled. Old rows stay intact; changes write under the current id. + * Stored keys, commands and panels still need their own migrations (`from`, the keybind map and `Panel.legacy`). + * This restores the enable preference only; hard dependencies still gate activation and can leave it blocked. + * + * @example + * ```ts + * Extension.define({ id: "details", legacy: ["summary"] }) + * ``` + */ + readonly legacy?: readonly string[] /** * The operating systems the extension runs on. Omit it to run everywhere, the web included. An extension that lists * any OS does not run on the web, where no OS is known. diff --git a/script/sdk-docs.ts b/script/sdk-docs.ts index ccbfc9c6d8d..5447700885f 100644 --- a/script/sdk-docs.ts +++ b/script/sdk-docs.ts @@ -5,8 +5,8 @@ // a member of an exported object such as `Store.global` has no doc comment; // - a documented function or method leaves a parameter without `@param`, or names one it does not have. // It also fails when a code block of the guide (`packages/gui-extensions/README.md`) marked `` (a -// whole file of a shipping extension) or `` (the first declaration, object property or call -// statement named `name` in that file, with the comments directly above it) differs from that source, or when the +// whole file of a shipping extension) or `` (a top-level declaration or call named `name`, +// else the first nested match, with the comments directly above it) differs from that source, or when the // guide or the package's AGENTS.md names a `ctx.` no context declares. // Usage: bun script/sdk-docs.ts import path from "node:path" @@ -256,8 +256,8 @@ async function read(file: string) { } /** - * The file's lines, or, for a name, the lines of the first declaration, object property or call statement it names, - * with the comment lines directly above it, dedented. + * The file's lines, or, for a name, the lines of its top-level match (else the first nested match), with the comment + * lines directly above it, dedented. */ function excerpt(file: string, text: string, name: string | undefined) { const lines = text.replace(/\n$/, "").split("\n") @@ -278,10 +278,22 @@ function excerpt(file: string, text: string, name: string | undefined) { return picked.map((line) => line.slice(indent)) } -/** The first node, in source order, that declares `name`, is an object property named `name`, or calls `name`. */ +/** Top-level matches win; otherwise find the first nested declaration, property or call in source order. */ function named(node: ts.Node, name: string): ts.Node | undefined { + if (ts.isSourceFile(node)) { + const top = node.statements.find((statement) => matches(statement, name)) + + if (top) return top + } + + if (matches(node, name)) return node + + return ts.forEachChild(node, (child) => named(child, name)) +} + +function matches(node: ts.Node, name: string) { if (ts.isVariableStatement(node)) { - if (node.declarationList.declarations.some((declaration) => declaration.name.getText() === name)) return node + return node.declarationList.declarations.some((declaration) => declaration.name.getText() === name) } if ( @@ -293,16 +305,16 @@ function named(node: ts.Node, name: string): ts.Node | undefined { ts.isMethodDeclaration(node)) && node.name?.getText() === name ) - return node + return true if ( ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && node.expression.expression.getText() === name ) - return node + return true - return ts.forEachChild(node, (child) => named(child, name)) + return false } function parse(file: string, text: string) {