diff --git a/packages/app/component-tests/extension-host.fixture.tsx b/packages/app/component-tests/extension-host.fixture.tsx index 0d7b31a303a..215cb980e3a 100644 --- a/packages/app/component-tests/extension-host.fixture.tsx +++ b/packages/app/component-tests/extension-host.fixture.tsx @@ -16,7 +16,16 @@ import { type StoreOptions, type Workspaces, } from "@opencode/gui-extensions/sdk" -import { createMemo, createSignal, getOwner, onCleanup, runWithOwner, Show, type ParentProps } from "solid-js" +import { + createComponent, + createMemo, + createSignal, + getOwner, + onCleanup, + runWithOwner, + Show, + type ParentProps, +} from "solid-js" import { createStore, produce } from "solid-js/store" import { Schema } from "effect" import { render } from "solid-js/web" @@ -29,8 +38,9 @@ import { createRegion, RegionContent } from "../src/runtime/extension/panels" import { ExtensionSlot } from "../src/runtime/extension/render" import { persistedHandle } from "../src/runtime/extension/stores" import { LanguageProvider } from "../src/runtime/i18n/language" +import { GuiExtensionsSettings } from "../src/runtime/extension/settings-page-dev" -export { Contract, createKeyed, Panel, Slot, Store } from "@opencode/gui-extensions/sdk" +export { bindExtension, useExtension, Contract, createKeyed, Panel, Slot, Store } from "@opencode/gui-extensions/sdk" export { Schema } @@ -45,7 +55,7 @@ type Captured = { apis?: ReturnType } /** A value the fixture's storage holds as JSON. */ type Json = string | number | boolean | null | readonly Json[] | { readonly [key: string]: Json } -export { createMemo, createSignal, getOwner, onCleanup, runWithOwner } +export { createComponent, createMemo, createSignal, getOwner, onCleanup, runWithOwner } const layout: Layout = { narrow: () => false, @@ -190,6 +200,8 @@ export function mountExtensions(input: { definitions: readonly Definition[] disabled?: readonly string[] stored?: Readonly> + /** Shows the production developer settings page for status-label contracts. */ + settings?: boolean }) { const held = Promise.withResolvers() const [disabled, setDisabled] = createSignal>(new Set(input.disabled ?? [])) @@ -248,6 +260,9 @@ export function mountExtensions(input: { return ( + + + ) @@ -362,15 +377,13 @@ export function mountSessionRegion(input: { definitions: readonly Definition[]; } const [view, setView] = createSignal(object("a")) + const [routed, setRouted] = createSignal(true) const route = { - get session() { - return view() - }, composer: { attach: () => void attached.push(view().id), update() {}, detach() {} }, } - // SAFETY: the test's extension reads only `session` and `composer.attach` of the screen. + // SAFETY: the test's extension reads only `composer.attach` of the screen. // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above const screen = route as unknown as SessionScreen @@ -385,6 +398,7 @@ export function mountSessionRegion(input: { definitions: readonly Definition[]; const region = createRegion({ region: "side", view, + screen, tabs: () => ({ all, active: () => input.active, @@ -403,11 +417,13 @@ export function mountSessionRegion(input: { definitions: readonly Definition[]; get session() { return view() }, + screen, }} /> true, present: () => true, @@ -429,7 +445,7 @@ export function mountSessionRegion(input: { definitions: readonly Definition[]; screen })} + mounted={standIn({ current: () => (routed() ? view() : undefined), screen: () => screen })} > @@ -444,6 +460,8 @@ export function mountSessionRegion(input: { definitions: readonly Definition[]; container, /** Routes a session: the screen creates a new session object for it. */ route: (id: string) => setView(object(id)), + /** The route leaves while its old screen has not unmounted yet. */ + leave: () => setRouted(false), /** The session each composer attachment reached, in order. */ attached, status: (id: string) => hosts[0]?.state.status[id], diff --git a/packages/app/component-tests/extension-host.spec.ts b/packages/app/component-tests/extension-host.spec.ts index ba48e031e8a..27920dd6e1e 100644 --- a/packages/app/component-tests/extension-host.spec.ts +++ b/packages/app/component-tests/extension-host.spec.ts @@ -1,5 +1,14 @@ -import type { Owner } from "solid-js" -import type { Context, Contract, DialogHandle, Dialogs, SessionRef } from "@opencode/gui-extensions/sdk" +import type { Component, Owner } from "solid-js" +import type { + Context, + Contract, + DialogHandle, + Dialogs, + Live, + PanelTab, + SessionRef, + SessionScreen, +} from "@opencode/gui-extensions/sdk" import { expect, sourceURL, story } from "../../storybook/playwright/story" const fixture = sourceURL(new URL("./extension-host.fixture.tsx", import.meta.url)) @@ -33,29 +42,32 @@ story("an extension that finishes loading after the host unmounts is never set u expect(setups).toBe(0) }) -story("an async setup that resolves after the host unmounts releases everything it registers", async ({ page }) => { +story("async work from synchronous setup cannot register after the host unmounts", async ({ page }) => { const result = await page.evaluate(async (fixture) => { const { mountExtensionHost, onCleanup } = await import(fixture) const host = mountExtensionHost() const started = Promise.withResolvers() const resume = Promise.withResolvers() + const done = Promise.withResolvers() const cleaned: string[] = [] const point = { kind: "point" as const, id: "fixture-point" } const resumed = { aborted: false } - host.load(async (ctx: Context) => { + host.load((ctx: Context) => { ctx.add(point, "before") onCleanup(() => void cleaned.push("owner")) started.resolve() - await resume.promise - // After an await there is no owner: the signal tells the setup it outlived its instance. - resumed.aborted = ctx.signal.aborted - ctx.add(point, "after") + void resume.promise.then(() => { + // A promise callback has no owner; the signal says the work outlived the instance. + resumed.aborted = ctx.signal.aborted + ctx.add(point, "after") + done.resolve() + }) }) await started.promise const before = host.entries(point.id) host.unmount() resume.resolve() - await new Promise((resolve) => setTimeout(resolve, 100)) + await done.promise return { before, after: host.entries(point.id), cleaned, aborted: resumed.aborted } }, fixture) @@ -183,17 +195,23 @@ story( const result = await page.evaluate(async (fixture) => { const { mountSessionRegion, until, Panel, Slot } = await import(fixture) const mounts = { single: 0, grouped: 0, slot: 0 } - const inputs: Partial> = {} + + const inputs: Partial< + Record + > = {} + const kept: Kept = {} const node = () => document.createElement("p") // One render of each kind the host has: a selected tab, a group that stays mounted, and a slot. - const render = (kind: keyof typeof mounts) => (input: { readonly session: { readonly id: string } }) => { - mounts[kind]++ - inputs[kind] = input + const render = + (kind: keyof typeof mounts) => + (input: { readonly session: { readonly id: string }; readonly screen: SessionScreen }) => { + mounts[kind]++ + inputs[kind] = input - return node() - } + return node() + } const host = mountSessionRegion({ active: "single:main", @@ -230,9 +248,13 @@ story( const seen = () => ({ mounts: { ...mounts }, sessions: [inputs.single?.session.id, inputs.grouped?.session.id, inputs.slot?.session.id], + screens: [inputs.single?.screen === screen, inputs.grouped?.screen === screen, inputs.slot?.screen === screen], kept: session?.id, fresh: kept.ctx?.sessions.current() !== session, - screen: { same: kept.ctx?.screen.current() === screen, session: screen?.session?.id }, + screen: { + same: kept.ctx?.screen.current() === screen, + aligned: !!kept.ctx?.screen.current() === !!kept.ctx?.sessions.current(), + }, }) const steps = [seen()] @@ -242,21 +264,28 @@ story( screen?.composer.attach({ type: "file", path: "notes.md" }) host.route("a") steps.push(seen()) + host.leave() + const home = seen() host.unmount() - return { steps, attached: host.attached } + return { steps, home, attached: host.attached } }, fixture) const step = (id: string, fresh: boolean) => ({ mounts: { single: 1, grouped: 1, slot: 1 }, sessions: [id, id, id], + screens: [true, true, true], kept: "a", fresh, - screen: { same: true, session: id }, + screen: { same: true, aligned: true }, }) // Routing A again makes a new object for the new visit; the kept one still names A. - expect(result).toEqual({ steps: [step("a", false), step("b", true), step("a", true)], attached: ["b"] }) + expect(result).toEqual({ + steps: [step("a", false), step("b", true), step("a", true)], + home: { ...step("a", true), screen: { same: false, aligned: true } }, + attached: ["b"], + }) }, ) @@ -295,7 +324,9 @@ story( scope: { server: "local" }, }) - prefs.update((draft) => ({ count: draft.count + 1 })) + prefs.update((draft) => { + draft.count++ + }) reads.state = createMemo(() => ctx.layout.state("fixture:main", session)) reads.font = createMemo(() => ctx.appearance.font("mono")) reads.prefs = prefs @@ -340,6 +371,84 @@ story( }, ) +// Selection follows opt-in tier order, not the strip's pinned-first order. Unrelated regular tabs never opt in. +const tiers: readonly { name: string; tabs: readonly PanelTab[]; active?: string; expected: string }[] = [ + { + name: "regular tabs, in stored order", + tabs: [ + { id: "details", title: "Details" }, + { id: "review", title: "Review", pinned: true, fallback: true }, + { id: "context", title: "Context", first: true, fallback: true }, + { id: "file-one", title: "File one", fallback: true }, + { id: "file-two", title: "File two", fallback: true }, + ], + expected: "file-one", + }, + { + name: "first tabs before pinned tabs", + tabs: [ + { id: "details", title: "Details" }, + { id: "review", title: "Review", pinned: true, fallback: true }, + { id: "context", title: "Context", first: true, fallback: true }, + ], + expected: "context", + }, + { + name: "pinned tabs when no other tier opts in", + tabs: [ + { id: "details", title: "Details" }, + { id: "review", title: "Review", pinned: true, fallback: true }, + ], + expected: "review", + }, + { + name: "no implicit fallback", + tabs: [{ id: "details", title: "Details", fallback: false }], + expected: "", + }, + { + name: "a stored selection wins without opting in", + tabs: [ + { id: "details", title: "Details" }, + { id: "file", title: "File", fallback: true }, + ], + active: "details:main", + expected: "details", + }, +] + +tiers.forEach((row) => { + story(`panel fallback: ${row.name}`, async ({ page }) => { + const selected = await page.evaluate( + async (input) => { + const { mountSessionRegion, Panel, until } = await import(input.fixture) + + const host = mountSessionRegion({ + active: input.row.active ?? "gone:main", + definitions: input.row.tabs.map((tab) => ({ + id: tab.id, + renderer: async () => ({ + default: (ctx: Context) => { + const item = { ...tab, id: "main" } + ctx.add(Panel, { id: "main", region: "side", list: () => [item], render: () => ctx.id }) + }, + }), + })), + }) + + await until(() => input.row.tabs.every((tab) => host.status(tab.id) === "active")) + const result = host.container.textContent + host.unmount() + + return result + }, + { fixture, row }, + ) + + expect(selected).toBe(row.expected) + }) +}) + story("an extension reloaded while disabled starts when it is enabled again", async ({ page }) => { const result = await page.evaluate(async (fixture) => { const { mountExtensionHost } = await import(fixture) @@ -495,11 +604,27 @@ story("an extension that requires a contract starts once it is active and restar ] // Hard contracts gate startup: a consumer whose provider is disabled settles the gate without starting. - const gated = mountExtensions({ definitions, disabled: ["provider"] }) + const gated = mountExtensions({ definitions: [definitions[1], definitions[0]], disabled: ["provider"] }) await until(() => gated.ready()) const blocked = { status: gated.status("consumer"), log: [...log] } gated.unmount() + const failed = mountExtensions({ + definitions: [ + { + ...definitions[0], + renderer: async () => { + throw new Error("provider failed") + }, + }, + definitions[1], + ], + }) + + await until(() => failed.ready()) + const failedProvider = { status: failed.status("consumer"), log: [...log] } + failed.unmount() + const host = mountExtensions({ definitions }) await new Promise((resolve) => setTimeout(resolve, 50)) const waiting = { status: host.status("consumer"), log: [...log] } @@ -509,17 +634,232 @@ story("an extension that requires a contract starts once it is active and restar await until(() => log.length === 3) host.disable(["provider"]) await until(() => log.length === 4) - const outcome = { blocked, waiting, log, after: host.status("consumer") } + const outcome = { blocked, failedProvider, waiting, log, after: host.status("consumer") } host.unmount() return outcome }, fixture) expect(result).toEqual({ - blocked: { status: "loading", log: [] }, + blocked: { status: "blocked", log: [] }, + failedProvider: { status: "blocked", log: [] }, waiting: { status: "loading", log: [] }, log: ["setup 1", "cleanup 1", "setup 2", "cleanup 2"], - after: "loading", + after: "blocked", + }) +}) + +story("a contract component reads its provider context and preserves reactive props", async ({ page }) => { + const result = await page.evaluate(async (fixture) => { + const { bindExtension, createComponent, createSignal, Contract, mountExtensions, Slot, until, useExtension } = + await import(fixture) + + const View: Contract<{ View: Component<{ readonly label: string }> }, "provider.view"> = + Contract.define("provider.view") + + const observed = { context: "", read: () => "", change: () => {}, mounts: 0 } + + const host = mountExtensions({ + definitions: [ + { + id: "provider", + provides: { view: View }, + renderer: async () => ({ + default: (ctx: Context) => { + ctx.provide(View, { + View: bindExtension((props: { readonly label: string }) => { + observed.context = useExtension().id + observed.read = () => props.label + observed.mounts++ + + return document.createTextNode(observed.context) + }), + }) + }, + }), + }, + { + id: "consumer", + requires: { view: View }, + renderer: async () => ({ + default: (ctx: Context & { requires: { view: { View: Component<{ readonly label: string }> } } }) => { + const [label, setLabel] = createSignal("before") + observed.change = () => setLabel("after") + ctx.add(Slot, { + at: "window.bottom", + render: () => + createComponent(ctx.requires.view.View, { + get label() { + return label() + }, + }), + }) + }, + }), + }, + ], + }) + + await until(() => host.container.textContent === "provider") + const before = observed.read() + observed.change() + const outcome = { context: observed.context, mounts: observed.mounts, before, after: observed.read() } + host.unmount() + + return outcome + }, fixture) + + expect(result).toEqual({ context: "provider", mounts: 1, before: "before", after: "after" }) +}) + +story("developer settings show a blocked hard dependency instead of loading forever", async ({ page }, info) => { + await page.evaluate(async (fixture) => { + const { Contract, mountExtensions, until } = await import(fixture) + const Tree = Contract.define("provider.tree") + + const host = mountExtensions({ + settings: true, + disabled: ["provider"], + definitions: [ + { id: "provider", provides: { tree: Tree }, renderer: async () => ({ default: () => {} }) }, + { id: "consumer", requires: { tree: Tree }, renderer: async () => ({ default: () => {} }) }, + ], + }) + + await until(() => !!host.container.textContent?.includes("consumer")) + }, fixture) + const settings = page.getByRole("region", { name: "Extensions", exact: true }) + await settings.screenshot({ path: info.outputPath("requires-status.png") }) + await expect(settings.getByText("Blocked", { exact: true })).toBeVisible() + await expect(settings.getByText("Loading", { exact: true })).toHaveCount(0) +}) + +story("blocked chains expose their own reason and recover regardless of definition order", async ({ page }) => { + const result = await page.evaluate(async (fixture) => { + const { Contract, mountExtensions, until } = await import(fixture) + const Root: Contract = Contract.define("root.value") + const Branch: Contract = Contract.define("branch.value") + const observed = { read: (): Live => ({ status: "pending" }), starts: 0 } + + const host = mountExtensions({ + disabled: ["root"], + definitions: [ + { + id: "leaf", + requires: { branch: Branch }, + renderer: async () => ({ + default: () => { + observed.starts++ + }, + }), + }, + { + id: "observer", + uses: { branch: Branch }, + renderer: async () => ({ + default: (ctx: Context & { uses: { branch: () => Live } }) => { + observed.read = ctx.uses.branch + }, + }), + }, + { + id: "branch", + requires: { root: Root }, + provides: { branch: Branch }, + renderer: async () => ({ default: (ctx: Context) => void ctx.provide(Branch, 2) }), + }, + { + id: "root", + provides: { root: Root }, + renderer: async () => ({ default: (ctx: Context) => void ctx.provide(Root, 1) }), + }, + ], + }) + + await until(() => host.ready()) + + const blocked = { + branch: host.status("branch"), + leaf: host.status("leaf"), + live: observed.read(), + starts: observed.starts, + } + + host.disable([]) + await until(() => host.status("leaf") === "active") + const recovered = { live: observed.read(), starts: observed.starts } + host.unmount() + + return { blocked, recovered } + }, fixture) + + expect(result).toEqual({ + blocked: { branch: "blocked", leaf: "blocked", live: { status: "inactive", reason: "blocked" }, starts: 0 }, + recovered: { live: { status: "active", value: 2, generation: 1 }, starts: 1 }, + }) +}) + +const invalidSetups = ["promise", "thenable"] + +invalidSetups.forEach((kind) => { + story(`window setup rejects a returned ${kind}`, async ({ page }) => { + const result = await page.evaluate( + async (input) => { + const { mountExtensions, until } = await import(input.fixture) + const resume = Promise.withResolvers() + const done = Promise.withResolvers() + const point = { kind: "point" as const, id: "invalid-setup" } + const observed = { aborted: false } + + const host = mountExtensions({ + definitions: [ + { + id: "invalid", + renderer: async () => ({ + default: (ctx: Context) => { + ctx.add(point, "before") + + if (input.kind === "thenable") + return { + then(resolve: () => void) { + resolve() + }, + } + + return resume.promise.then(() => { + observed.aborted = ctx.signal.aborted + ctx.add(point, "after") + done.resolve() + }) + }, + }), + }, + ], + }) + + await until(() => host.ready()) + + const failed = { + status: host.status("invalid"), + error: host.failure("invalid")?.error.includes("Window setup must be synchronous"), + entries: host.entries(point.id), + } + + resume.resolve() + + if (input.kind === "promise") await done.promise + const after = { entries: host.entries(point.id), aborted: observed.aborted } + host.unmount() + + return { failed, after } + }, + { fixture, kind }, + ) + + expect(result).toEqual({ + failed: { status: "failed", error: true, entries: 0 }, + after: { entries: 0, aborted: kind === "promise" }, + }) }) }) diff --git a/packages/app/src/runtime/extension/host-apis.tsx b/packages/app/src/runtime/extension/host-apis.tsx index b71dc4742c3..5d90d76bc58 100644 --- a/packages/app/src/runtime/extension/host-apis.tsx +++ b/packages/app/src/runtime/extension/host-apis.tsx @@ -282,7 +282,13 @@ export function createHostApis() { list: () => current()?.sessions() ?? [], current: () => current()?.current(), }), - screen: () => ({ current: () => current()?.screen() }), + screen: () => ({ + current: () => { + const attached = current() + + return attached?.current() ? attached.screen() : undefined + }, + }), // Before the interface mounts, reads return what an empty layout holds and writes wait for it. layout: (extension) => ({ narrow, @@ -545,8 +551,9 @@ export function createExtensionAttachment(apis: HostApis) { // The side tabs a mounted session lists right now, plus `adding` as if it were stored; unmounted sessions have none. const listed = (session: SessionRef, value: string, adding?: string) => { const view = mountedSession(session) + const currentScreen = screen() - if (!view) return [] + if (!view || !currentScreen) return [] const all = layout.panel.state(value).all const stored = adding && !all.includes(adding) ? [...all, adding] : all @@ -558,7 +565,15 @@ export function createExtensionAttachment(apis: HostApis) { const prefix = `${item.extension}:` const open = stored.flatMap((key) => (key.startsWith(prefix) ? [key.slice(prefix.length)] : [])) - return item.value.list(view, open).map((tab) => ({ key: `${prefix}${tab.id}`, tab })) + return item.value + .list({ + get session() { + return mountedSession(session) ?? view + }, + screen: currentScreen, + open, + }) + .map((tab) => ({ key: `${prefix}${tab.id}`, tab })) }), ) } @@ -620,8 +635,9 @@ export function createExtensionAttachment(apis: HostApis) { const tab = listed(session, value).find((entry) => entry.key === key)?.tab layout.panel.close(value, key) const view = mountedSession(session) + const currentScreen = screen() - if (view && tab) item?.value.close?.(tab, view) + if (view && tab && currentScreen) item?.value.close?.({ tab, session: view, screen: currentScreen }) } // The routed session's side region, which knows the fallback selection the stored state lacks. @@ -803,7 +819,7 @@ export function createExtensionAttachment(apis: HostApis) { if (session) selectMobile(session, view) }, }, - /** A session screen started rendering: `Screen.current` returns it until it unmounts. */ + /** A screen started rendering: `Screen.current` returns it only while its session matches the route. */ screen(value: SessionScreen) { setScreen(() => value) diff --git a/packages/app/src/runtime/extension/host.tsx b/packages/app/src/runtime/extension/host.tsx index 2f5424aea91..169e2312c43 100644 --- a/packages/app/src/runtime/extension/host.tsx +++ b/packages/app/src/runtime/extension/host.tsx @@ -20,6 +20,7 @@ import { type ParentProps, } from "solid-js" import { createStore } from "solid-js/store" +import { Predicate } from "effect" import { resolveTemplate } from "@solid-primitives/i18n" import { useDialog } from "@opencode/ui/context/dialog" import { pluralCategory } from "@opencode/ui/context/i18n" @@ -86,7 +87,7 @@ export type HostApiFactories = { readonly [K in Exclude]: HostApiFactory } -export type ExtensionStatus = "loading" | "active" | "failed" | "disabled" +export type ExtensionStatus = "loading" | "active" | "failed" | "disabled" | "blocked" /** The last error an extension raised: in its setup or an effect, or while one of its contributions rendered. */ export type ExtensionFailure = { readonly phase: "setup" | "render"; readonly error: string } @@ -110,6 +111,7 @@ const pending: Absent = { status: "pending" } const inactive = { disabled: { status: "inactive", reason: "disabled" }, failed: { status: "inactive", reason: "failed" }, + blocked: { status: "inactive", reason: "blocked" }, restarting: { status: "inactive", reason: "restarting" }, } as const satisfies Record @@ -190,6 +192,9 @@ function createHost(input: HostInput) { if (main ? input.failed?.(extension) : state.status[extension] === "failed") return inactive.failed + // A blocked provider cannot offer its own contracts either, so hard-dependency chains settle as unavailable. + if (!main && state.status[extension] === "blocked") return inactive.blocked + // A renderer provider that is up but does not provide the token (e.g. on this platform) is not coming. if (!main && state.status[extension] === "active") return inactive.disabled @@ -383,7 +388,13 @@ function createHost(input: HostInput) { // enable watcher skip it later. Before the list loads nothing activates; the watcher starts each entry then. if (!load || input.disabled()?.has(definition.id) !== false) return - setState("status", definition.id, "loading") + const unavailable = Object.values(definition.requires ?? {}).some((token) => { + const provider = untrack(() => providerState(token)) + + return blocked(provider) + }) + + setState("status", definition.id, unavailable ? "blocked" : "loading") // Waits for its hard contracts; the requirement watcher starts it once they are active. if (!satisfied(definition)) return @@ -432,13 +443,26 @@ function createHost(input: HostInput) { } // SAFETY: the host context implements the parameter of every `Setup` of this definition. - const setup = module.default as (ctx: InstanceContext) => void | Promise + const setup = module.default as (ctx: InstanceContext) => void const start = () => void Promise.try(() => // Errors from the extension's own effects, at setup or later, fail the extension and nothing else. catchError( - () => untrack(() => setup(instance.context)), + () => + untrack(() => { + const returned = setup(instance.context) + + if (!Predicate.isPromiseLike(returned)) return + + // Do not await invalid setup, but consume its eventual rejection after the instance is aborted. + void Promise.resolve(returned).catch((cause: unknown) => + console.error(`[extension] ${definition.id}`, cause), + ) + throw new Error( + "Window setup must be synchronous. Start async work with createKeyed or createLatest.", + ) + }), (cause) => queueMicrotask(() => crash(cause)), ), ).then(() => { @@ -479,7 +503,7 @@ function createHost(input: HostInput) { void Promise.try(fn).catch((cause: unknown) => console.error(`[extension] ${extension}`, cause)) const own = (fn: Cleanup): Cleanup => { - // Work that outlives the extension, e.g. after an await in setup, is released as soon as it registers. + // Work that outlives the extension, e.g. a promise callback, is released as soon as it registers. if (controller.signal.aborted) { release(fn) @@ -593,7 +617,7 @@ function createHost(input: HostInput) { add(point: Point, item: T | (() => T | undefined)) { if (late()) return () => {} - // Work after an await in setup has no owner; fall back to the extension root. + // Promise callbacks may have no owner; fall back to the extension root. const read = // SAFETY: a function item is the SDK's reactive form; points take no function values. // oxlint-disable-next-line anti-slop/no-runtime-typeof -- see SAFETY above @@ -774,40 +798,17 @@ function createHost(input: HostInput) { const status = state.status[definition.id] - if (status === "active" || status === "failed" || status === "disabled") return true + if (status === "active" || status === "failed" || status === "disabled" || status === "blocked") return true return Object.values(definition.requires ?? {}).some((token) => { const provider = providerState(token) - return provider.status === "inactive" && provider.reason !== "restarting" + return blocked(provider) }) })), false, ) - createMemo(() => { - const disabled = input.disabled() - - if (!disabled) return - - untrack(() => - batch(() => - input.definitions.forEach((definition) => { - if (disabled.has(definition.id)) { - deactivate(definition.id) - setState("status", definition.id, "disabled") - - return - } - - if (instances.has(definition.id) || state.status[definition.id] === "loading") return - - void activate(latest(definition)) - }), - ), - ) - }) - // `requires` gating: an extension starts once every hard contract is active and restarts with a new generation of // any of them. Activation is never ordered by the graph; only these extensions wait, and only for their contracts. input.definitions.forEach((definition) => { @@ -818,33 +819,59 @@ function createHost(input: HostInput) { const key = createMemo(() => { const providers = tokens.map(providerState) - return providers.every((provider) => provider.status === "active") - ? providers.map((provider) => (provider.status === "active" ? provider.generation : 0)).join(",") - : undefined + if (providers.every((provider) => provider.status === "active")) + return providers.map((provider) => (provider.status === "active" ? provider.generation : 0)).join(",") + + return providers.some(blocked) ? "blocked" : undefined }) createRenderEffect( - on( - key, - (value) => - untrack(() => - batch(() => { - const id = definition.id + on(key, (value) => + untrack(() => + batch(() => { + const id = definition.id - deactivate(id) + deactivate(id) - if (input.disabled()?.has(id) !== false) return + if (input.disabled()?.has(id) !== false) return - if (value === undefined) return setState("status", id, "loading") + if (value === undefined) return setState("status", id, "loading") - void activate(latest(definition)) - }), - ), - { defer: true }, + if (value === "blocked") return setState("status", id, "blocked") + + void activate(latest(definition)) + }), + ), ), ) }) + // Establish requirement watchers before activation, including their initial state. Publish every disabled status + // before starting enabled entries, so declaration order cannot leave a hard-dependency chain loading forever. + createMemo(() => { + const disabled = input.disabled() + + if (!disabled) return + + untrack(() => + batch(() => { + input.definitions + .filter((definition) => disabled.has(definition.id)) + .forEach((definition) => { + deactivate(definition.id) + setState("status", definition.id, "disabled") + }) + input.definitions + .filter((definition) => !disabled.has(definition.id)) + .forEach((definition) => { + if (instances.has(definition.id) || state.status[definition.id] === "loading") return + + void activate(latest(definition)) + }) + }), + ) + }) + onCleanup(() => { lifetime.disposed = true loads.clear() @@ -888,6 +915,11 @@ function windowStores(definition: Definition) { ) } +/** A hard dependency that is not coming until its provider or configuration changes. */ +function blocked(provider: Provider) { + return provider.status === "inactive" && provider.reason !== "restarting" +} + /** English merged under the locale's messages. A catalog that fails to load leaves English. */ async function loadMessages(catalog: Catalog | undefined, locale: string): Promise { const english = catalog?.en ?? {} diff --git a/packages/app/src/runtime/extension/ipc.test.ts b/packages/app/src/runtime/extension/ipc.test.ts index 46768a6acb6..0f77fc58fb2 100644 --- a/packages/app/src/runtime/extension/ipc.test.ts +++ b/packages/app/src/runtime/extension/ipc.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test" -import type { Ipc } from "@opencode/gui-extensions/sdk" +import { Ipc } from "@opencode/gui-extensions/sdk" +import { Schema } from "effect" import type { Bridge, BridgeMessage } from "@opencode/gui-extensions/sdk/bridge" import { createIpcClients } from "./ipc" @@ -39,6 +40,38 @@ test.each<[string, BridgeMessage, Reply, { available: boolean; state: unknown }] ipcs.dispose() }) +test("no-input methods pass their first argument's abort signal to the bridge", async () => { + const bridge = fakeBridge() + const controller = new AbortController() + const calls: { method: string; input?: unknown; signal?: AbortSignal }[] = [] + + const methods = Ipc.define({ + id: "fixture", + methods: { info: { output: Schema.String }, echo: { input: Schema.String, output: Schema.String } }, + }) + + const ipcs = createIpcClients({ + ...bridge.value, + call: async (request, signal) => { + calls.push({ method: request.method, input: request.input, signal }) + + return "reply" + }, + }) + + ipcs.typed(methods) + bridge.emit({ type: "available", ipc: "fixture", available: true }) + const client = ipcs.typed(methods) + + expect(await client?.info({ signal: controller.signal })).toBe("reply") + expect(await client?.echo("input", { signal: controller.signal })).toBe("reply") + expect(calls).toEqual([ + { method: "info", input: null, signal: controller.signal }, + { method: "echo", input: "input", signal: controller.signal }, + ]) + ipcs.dispose() +}) + function fakeBridge() { const listeners = new Set<(message: BridgeMessage) => void>() const pending = Promise.withResolvers() diff --git a/packages/app/src/runtime/extension/ipc.ts b/packages/app/src/runtime/extension/ipc.ts index 536c95dbc99..915f27d42ca 100644 --- a/packages/app/src/runtime/extension/ipc.ts +++ b/packages/app/src/runtime/extension/ipc.ts @@ -1,7 +1,7 @@ import { batch } from "solid-js" import { createStore, reconcile } from "solid-js/store" import { Schema } from "effect" -import type { Ipc, IpcClient, IpcSpec } from "@opencode/gui-extensions/sdk" +import type { Ipc, IpcCallOptions, IpcClient, IpcSpec } from "@opencode/gui-extensions/sdk" import type { Bridge } from "@opencode/gui-extensions/sdk/bridge" type Codec = NonNullable @@ -112,15 +112,16 @@ export function createIpcClients(bridge: Bridge | undefined) { const create = (connected: Bridge, token: Ipc): IpcClient => { const methods = Object.fromEntries( - Object.entries(token.spec.methods).map(([name, method]) => [ - name, - async (input: Decoded, options?: { signal?: AbortSignal }) => { + Object.entries(token.spec.methods).map(([name, method]) => { + const call = async (input: Decoded, options?: IpcCallOptions) => { const encoded = method.input ? Schema.encodeUnknownSync(method.input)(input) : null const output = await connected.call({ ipc: token.id, method: name, input: encoded }, options?.signal) return method.output ? Schema.decodeUnknownSync(method.output)(output) : undefined - }, - ]), + } + + return [name, method.input ? call : (options?: IpcCallOptions) => call(undefined, options)] + }), ) const client = Object.assign(methods, { diff --git a/packages/app/src/runtime/extension/mobile.tsx b/packages/app/src/runtime/extension/mobile.tsx index 3910e60d68f..567c142f7f8 100644 --- a/packages/app/src/runtime/extension/mobile.tsx +++ b/packages/app/src/runtime/extension/mobile.tsx @@ -10,6 +10,7 @@ import { type PanelSidebar, type PanelTab, type MountedSession, + type SessionScreen, } from "@opencode/gui-extensions/sdk" import { useLanguage } from "@/runtime/i18n/language" import { useExtensionHost } from "./host" @@ -62,6 +63,7 @@ export function MobileViewTabs(props: { region: Region current: string session: MountedSession + screen: SessionScreen sidebar: PanelSidebar onSelect: (key: string) => void }): JSX.Element { @@ -173,6 +175,7 @@ export function MobileViewTabs(props: { props.region.openFor(entry.extension)} diff --git a/packages/app/src/runtime/extension/mounted-session.ts b/packages/app/src/runtime/extension/mounted-session.ts index e519f23d2b7..a76628bebb2 100644 --- a/packages/app/src/runtime/extension/mounted-session.ts +++ b/packages/app/src/runtime/extension/mounted-session.ts @@ -1,6 +1,7 @@ import { - createEffect, + batch, createMemo, + createEffect, createRenderEffect, createRoot, createSignal, @@ -207,17 +208,11 @@ export function createMountedSession(session: SessionModel) { // One object while this screen is mounted, whichever session it routes: its models follow the route. const screen: SessionScreen = Object.freeze({ - get session() { - return attachment.current() - }, file: files, comment, composer: composerRef, }) - // Before the screen's regions render, so every contribution they show reads it. - onCleanup(attachment.screen(screen)) - const owner = getOwner() const root: ObjectRoot = {} @@ -248,8 +243,18 @@ export function createMountedSession(session: SessionModel) { // The session's declared stores start loading now, before its regions read them. createRenderEffect(on(mounted, (view) => attachment.preload(view))) - // Registered once: `Sessions.current` follows the screen's object from here on. - createEffect(() => onCleanup(attachment.mount(mounted))) + // Publish both after render, with the original session-mount timing. Renders receive their own screen directly; + // only global observers need this attachment. One batch prevents exposing a view on another screen. + createEffect(() => + batch(() => { + onCleanup(attachment.screen(screen)) + onCleanup(attachment.mount(mounted)) + }), + ) - return { view: mounted, bindBackground: (tasks: Accessor) => setBackground(() => tasks) } + return { + screen, + view: mounted, + bindBackground: (tasks: Accessor) => setBackground(() => tasks), + } } diff --git a/packages/app/src/runtime/extension/panels.tsx b/packages/app/src/runtime/extension/panels.tsx index 547327fc069..051dd960989 100644 --- a/packages/app/src/runtime/extension/panels.tsx +++ b/packages/app/src/runtime/extension/panels.tsx @@ -1,4 +1,15 @@ -import { createEffect, createMemo, For, on, onCleanup, onMount, Show, type Accessor, type JSX } from "solid-js" +import { + createEffect, + createMemo, + For, + mergeProps, + on, + onCleanup, + onMount, + Show, + type Accessor, + type JSX, +} from "solid-js" import { createStore } from "solid-js/store" import { Schema } from "effect" import { makeEventListener } from "@solid-primitives/event-listener" @@ -16,6 +27,7 @@ import { type PanelSidebar, type PanelTab, type MountedSession, + type SessionScreen, } from "@opencode/gui-extensions/sdk" import { same } from "@/runtime/persistence/equality" import { Persist, persisted } from "@/runtime/persistence/storage" @@ -83,7 +95,12 @@ export function createPanelSidebar(): PanelSidebar { * Every panel extensions offer in one region of the routed session, merged with the stored strip. `view` returns the * routed session's object, a new one per routed session. */ -export function createRegion(input: { region: Panel["region"]; view: Accessor; tabs: Tabs }) { +export function createRegion(input: { + region: Panel["region"] + view: Accessor + screen: SessionScreen + tabs: Tabs +}) { const host = useExtensionHost() const stored = () => input.tabs().all() const providers = createMemo(() => host.items(Panel).filter((item) => item.value.region === input.region)) @@ -93,7 +110,7 @@ export function createRegion(input: { region: Panel["region"]; view: Accessor (key.startsWith(prefix) ? [key.slice(prefix.length)] : [])) - return item.value.list(input.view(), open).map( + return item.value.list(panelInput(input.view, input.screen, { open })).map( (tab): RegionEntry => ({ key: panelKey(item.extension, tab.id), extension: item.extension, @@ -123,7 +140,14 @@ export function createRegion(input: { region: Panel["region"]; view: Accessor entry.key === value && (desktop() || !entry.tab.transient))) return value - return strip() - .filter((entry) => entry.tab.fallback !== undefined) - .reduce( - (best, entry) => (!best || entry.tab.fallback! > best.tab.fallback! ? entry : best), - undefined, - )?.key + const eligible = strip().filter((entry) => entry.tab.fallback && (desktop() || !entry.tab.transient)) + + return [ + ...eligible.filter((entry) => !entry.tab.pinned && !entry.tab.first), + ...eligible.filter((entry) => !entry.tab.pinned && entry.tab.first), + ...eligible.filter((entry) => entry.tab.pinned), + ][0]?.key }) // The effect's own value marks its first run: the selection the region mounts with, stored or fallback. @@ -177,7 +202,13 @@ export function createRegion(input: { region: Panel["region"]; view: Accessor { const entry = key ? byKey().get(key) : undefined - if (entry) entry.provider.focus?.(entry.tab, input.view(), { restored }) + if (entry) + entry.provider.focus?.( + panelInput(input.view, input.screen, { + tab: entry.tab, + restored, + }), + ) return false }), @@ -209,7 +240,12 @@ export function createRegion(input: { region: Panel["region"]; view: Accessor export function RegionContent(props: { region: Region view: MountedSession + screen: SessionScreen frame: Omit & { shown: Accessor } }) { const groups = createMemo(() => @@ -273,14 +310,13 @@ export function RegionContent(props: { > {() => - member()!.provider.render({ - get tab() { - return member()!.tab - }, - get session() { - return props.view - }, - }) + member()!.provider.render( + panelInput(() => props.view, props.screen, { + get tab() { + return member()!.tab + }, + }), + ) } @@ -310,14 +346,13 @@ export function RegionContent(props: { > {() => - entry()!.provider.render({ - get tab() { - return entry()!.tab - }, - get session() { - return props.view - }, - }) + entry()!.provider.render( + panelInput(() => props.view, props.screen, { + get tab() { + return entry()!.tab + }, + }), + ) } @@ -335,9 +370,23 @@ function groupKey(entry: RegionEntry) { return `${entry.extension}/${entry.tab.group ?? entry.key}` } +/** Keeps session and tab getters live while the owning screen stays constant. Spreading would snapshot getters. */ +function panelInput(view: Accessor, screen: SessionScreen, fields: T) { + return mergeProps( + { + get session() { + return view() + }, + screen, + }, + fields, + ) +} + /** The dock region: host frame, sizing, and resize around the dock panel an extension renders. */ export function DockRegion(props: { view: MountedSession + screen: SessionScreen sidebar: PanelSidebar stacked?: boolean fill?: boolean @@ -362,7 +411,7 @@ export function DockRegion(props: { .items(Panel) .filter((item) => item.value.region === "dock") .flatMap((item) => - item.value.list(props.view, []).map( + item.value.list(panelInput(() => props.view, props.screen, { open: [] })).map( (tab): RegionEntry => ({ key: panelKey(item.extension, tab.id), extension: item.extension, @@ -475,14 +524,13 @@ export function DockRegion(props: { > {() => - entry()!.provider.render({ - get tab() { - return entry()!.tab - }, - get session() { - return props.view - }, - }) + entry()!.provider.render( + panelInput(() => props.view, props.screen, { + get tab() { + return entry()!.tab + }, + }), + ) } @@ -497,6 +545,7 @@ export function DockRegion(props: { export function MobilePanel(props: { entry: RegionEntry view: MountedSession + screen: SessionScreen sidebar: PanelSidebar visible: boolean open: Accessor @@ -515,14 +564,13 @@ export function MobilePanel(props: { > {() => - props.entry.provider.render({ - get tab() { - return props.entry.tab - }, - get session() { - return props.view - }, - }) + props.entry.provider.render( + panelInput(() => props.view, props.screen, { + get tab() { + return props.entry.tab + }, + }), + ) } diff --git a/packages/app/src/runtime/extension/settings-page-dev.tsx b/packages/app/src/runtime/extension/settings-page-dev.tsx index 2531a935942..46dbf692be1 100644 --- a/packages/app/src/runtime/extension/settings-page-dev.tsx +++ b/packages/app/src/runtime/extension/settings-page-dev.tsx @@ -36,6 +36,8 @@ export function GuiExtensionsSettings() { if (value === "disabled") return language.t("settings.guiExtensions.status.disabled") + if (value === "blocked") return language.t("settings.guiExtensions.status.blocked") + return language.t("settings.guiExtensions.status.loading") } diff --git a/packages/app/src/runtime/extension/side-region.tsx b/packages/app/src/runtime/extension/side-region.tsx index c4f2d8cc34d..309e89db73d 100644 --- a/packages/app/src/runtime/extension/side-region.tsx +++ b/packages/app/src/runtime/extension/side-region.tsx @@ -18,6 +18,7 @@ import { SessionReviewV2SidebarToggle } from "@opencode/session-ui/v2/session-re import { MenuItem, type MountedSession, + type SessionScreen, type PanelSidebar, type SessionPanelMenuItem, } from "@opencode/gui-extensions/sdk" @@ -37,6 +38,7 @@ const FILE_TREE_WIDTH_MIN = 240 /** The side region: the tab strip with its "+" menu, the selected panel, and the inner sidebar. */ export function SideRegion(props: { view: MountedSession + screen: SessionScreen region: Region sidebar: PanelSidebar fileTree: boolean @@ -206,6 +208,9 @@ export function SideRegion(props: { get session() { return props.view }, + get screen() { + return props.screen + }, }} /> @@ -229,6 +234,7 @@ export function SideRegion(props: { diff --git a/packages/app/src/runtime/extension/stores.ts b/packages/app/src/runtime/extension/stores.ts index 98629acf159..d17c0b6d27f 100644 --- a/packages/app/src/runtime/extension/stores.ts +++ b/packages/app/src/runtime/extension/stores.ts @@ -11,12 +11,10 @@ import { } from "solid-js" import { produce, reconcile, type SetStoreFunction } from "solid-js/store" import { Predicate } from "effect" -import type { Persisted, SessionRef, StoreFrom } from "@opencode/gui-extensions/sdk" +import type { Mutable, Persisted, SessionRef, StoreFrom } from "@opencode/gui-extensions/sdk" import { Persist, type persisted } from "@/runtime/persistence/storage" import type { SessionStateKey } from "@/runtime/server/scope" -type Mutation = Parameters["update"]>[0] - /** One older key persistence imports a store's value from. */ type CopyFrom = NonNullable[0], string>["copyFrom"]>[number] @@ -64,8 +62,7 @@ function sessionCopy(from: StoreFrom, session: SessionStateKey): CopyFrom | unde } /** - * What `Storage.store` returns: a `Persisted` whose `update` waits until the stored value has loaded, then applies in - * call order. + * What `Storage.store` returns: a `Persisted` whose `update` and `set` wait for load, then apply in call order. */ export function persistedHandle(input: { readonly store: T @@ -75,42 +72,45 @@ export function persistedHandle(input: { readonly init: Promise | undefined }) { const [loaded, setLoaded] = createSignal(!input.init) - const queue: Mutation[] = [] + const queue: (() => void)[] = [] - // A mutation edits the draft in place, or returns the next value, which replaces the stored one entirely. - const apply = (mutation: Mutation) => - batch(() => { - const replaced: T[] = [] + const write = (apply: () => void) => { + if (untrack(loaded)) return apply() - input.set( - produce((draft) => { - const next = mutation(draft) - - if (next) replaced.push(next) - }), - ) - replaced.forEach((next) => input.set(reconcile(next))) - }) + queue.push(apply) + } // Registered after the store's own hydration on the same read, so queued changes apply over the stored value. const load = input.init?.then(() => batch(() => { - queue.splice(0).forEach(apply) + queue.splice(0).forEach((apply) => apply()) setLoaded(true) }), ) - void load?.catch(() => undefined) + // Runtime-key stores have no setup awaiter: a failed queued mutation must still report its contract error. + void load?.catch((cause: unknown) => console.error("[extension storage] Load or queued write failed", cause)) const handle: Persisted = { get value() { return loaded() ? input.store : undefined }, ready: loaded, - update(mutation) { - if (untrack(loaded)) return apply(mutation) + update(mutate) { + write(() => + input.set( + produce((draft) => { + // SAFETY: Solid's produce draft is writable recursively; schema readonly fields constrain readers, not drafts. + const returned = mutate(draft as Mutable) - queue.push(mutation) + if (returned !== undefined) + throw new Error("Persisted.update must not return a value. Use set(next) to replace the value.") + }), + ), + ) + }, + set(next) { + write(() => input.set(reconcile(next))) }, } @@ -129,13 +129,13 @@ export function whenLoaded(handle: Persisted) { * changes made before then wait and apply in order. Call it inside an owner, which ends the hand-over. */ export function deferredHandle(store: Accessor | undefined>): Persisted { - const queue: Mutation[] = [] + const queue: ((current: Persisted) => void)[] = [] // Hands changes made before the store opened to it, which applies them once it has loaded. createRenderEffect(() => { const current = store() - if (current && queue.length > 0) untrack(() => queue.splice(0).forEach((mutation) => current.update(mutation))) + if (current && queue.length > 0) untrack(() => queue.splice(0).forEach((apply) => apply(current))) }) return { @@ -143,11 +143,17 @@ export function deferredHandle(store: Accessor | undefined>): Pe return store()?.value }, ready: () => store()?.ready() ?? false, - update(mutation) { + update(mutate) { const current = untrack(store) - if (current) return current.update(mutation) - queue.push(mutation) + if (current) return current.update(mutate) + queue.push((opened) => opened.update(mutate)) + }, + set(next) { + const current = untrack(store) + + if (current) return current.set(next) + queue.push((opened) => opened.set(next)) }, } } diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index c0a6f7b301c..fbb3e6994f9 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -628,6 +628,7 @@ export const dict = { "settings.guiExtensions.status.active": "Active", "settings.guiExtensions.status.failed": "Failed", "settings.guiExtensions.status.disabled": "Disabled", + "settings.guiExtensions.status.blocked": "Blocked", "settings.tab.about": "About", "settings.about.version": "Version {{version}}", "settings.about.devVersion": "development", diff --git a/packages/app/src/session/route.tsx b/packages/app/src/session/route.tsx index 0c46de18f78..e0aaddb4441 100644 --- a/packages/app/src/session/route.tsx +++ b/packages/app/src/session/route.tsx @@ -24,7 +24,7 @@ import { SessionIdentityHeader } from "./session-identity-header" import { IncompatibleServerPanel } from "./incompatible-server-panel" import { SessionErrorFallback } from "./route-error" import { createSessionResolution } from "./session-resolution" -import { SessionScreen } from "./screen" +import { SessionScreenView } from "./screen" import { PreparingComposer } from "./preparing-composer" export function TargetSessionRouteContent() { @@ -52,6 +52,7 @@ export function TargetSessionRouteContent() { function PreparingSession(props: { sessionID: string; pending: PendingSession }) { const language = useLanguage() const providers = useProviders(() => props.pending.draft.directory) + return ( params.id, () => data.session, { children: true, connected: () => server.ctx.sdk.connection.status() === "connected" }, ) + const directory = createMemo(() => current()?.location.directory) return ( @@ -178,16 +182,20 @@ function TargetSessionPage() { function SessionPage() { const session = useSessionModel() - return + + return } function MarkSessionNotificationsViewed(props: { sessionID: () => string | undefined }) { const notification = useNotification() createEffect(() => { const sessionID = props.sessionID() + if (!notification.ready() || !sessionID) return + if (notification.session.unseenCount(sessionID) === 0) return notification.session.markViewed(sessionID) }) + return null } diff --git a/packages/app/src/session/screen.tsx b/packages/app/src/session/screen.tsx index a0dadf655c4..63d697639ae 100644 --- a/packages/app/src/session/screen.tsx +++ b/packages/app/src/session/screen.tsx @@ -12,7 +12,7 @@ import { } from "solid-js" import { createStore } from "solid-js/store" import { ResizeHandle } from "@opencode/ui/resize-handle" -import { Slot, type BackgroundTask, type MountedSession } from "@opencode/gui-extensions/sdk" +import { Slot, type BackgroundTask, type MountedSession, type SessionScreen } from "@opencode/gui-extensions/sdk" import { MessageTimeline } from "@/session/timeline/message-timeline" import { ComposerDropzone } from "@/composer/dropzone" import type { SessionModel } from "@/session/model" @@ -37,13 +37,18 @@ import { SessionReviewToggle } from "./header/session-header-actions" import { createAnimatedPresence } from "@/runtime/animated-presence" import { createTimelineCache } from "./timeline/cache" -export function SessionScreen(props: { session: SessionModel }) { +export function SessionScreenView(props: { session: SessionModel }) { // The timeline cache captures its owner when created, so link handling must be provided above it. const mounted = createMountedSession(props.session) return ( - + ) } @@ -52,6 +57,7 @@ function SessionScreenContent(props: { session: SessionModel /** One object per routed session; renders receive each through a reactive prop instead of remounting. */ view: Accessor + screen: SessionScreen bindBackground: (tasks: () => readonly BackgroundTask[]) => void }) { const session = props.session @@ -59,7 +65,14 @@ function SessionScreenContent(props: { const attachment = useExtensionAttachment() const isDesktop = session.isDesktop const sidebar = createPanelSidebar() - const region = createRegion({ region: "side", view: props.view, tabs: session.layout.tabs }) + + const region = createRegion({ + region: "side", + view: props.view, + screen: props.screen, + tabs: session.layout.tabs, + }) + onCleanup(attachment.region(region)) const mobile = createMobileViews() @@ -229,6 +242,7 @@ function SessionScreenContent(props: { hideHeader={!isDesktop()} session={source} view={own()} + screen={props.screen} background={composer.requests.background} actions={composer.actions.timeline} scroll={timeline.scroll} @@ -269,6 +283,7 @@ function SessionScreenContent(props: { {(_key) => (
- +
@@ -298,6 +321,7 @@ function SessionScreenContent(props: { {(entry) => (
{ test.each([ { name: "while the storage read is held", location: { directory: "/repo" } }, { name: "while the session location is unknown", location: undefined }, + { name: "while held with an invalid returned replacement", location: { directory: "/repo" }, invalid: true }, ])("store writes made $name apply in order over the stored value", async (row) => { const held = Promise.withResolvers() const key = `extension-store-${crypto.randomUUID()}` @@ -299,6 +300,18 @@ describe("extension primitives", () => { } }) + if ("invalid" in row) { + // @ts-expect-error JavaScript extensions can return an invalid replacement before hydration too + root.handle.update(() => ({ items: ["wrong"] })) + held.resolve() + await expect(Promise.all(opened.map(whenLoaded))).rejects.toThrow("Use set") + root.dispose() + + return + } + + root.handle.update((draft) => void draft.items.push("discarded")) + root.handle.set({ items: ["replacement"] }) root.handle.update((draft) => void draft.items.push("first")) root.handle.update((draft) => void draft.items.push("second")) @@ -309,7 +322,7 @@ describe("extension primitives", () => { await Promise.all(opened.map(whenLoaded)) expect({ before, after: root.handle.value?.items, ready: root.handle.ready() }).toEqual({ before: { value: undefined, ready: false }, - after: ["stored", "first", "second"], + after: ["replacement", "first", "second"], ready: true, }) root.dispose() @@ -318,11 +331,24 @@ describe("extension primitives", () => { test.each([ { name: "an edit to the draft", - mutation: (draft: (typeof Noted)["Type"]) => void draft.items.push("b"), + write: (handle: Persisted<(typeof Noted)["Type"]>) => handle.update((draft) => void draft.items.push("b")), expected: { items: ["a", "b"], note: "kept" }, }, - { name: "a returned value", mutation: () => ({ items: ["b"] }), expected: { items: ["b"] } }, - ])("store update: $name becomes the whole stored value", (row) => { + { + name: "set replaces", + write: (handle: Persisted<(typeof Noted)["Type"]>) => handle.set({ items: ["b"] }), + expected: { items: ["b"] }, + }, + { + name: "update rejects a returned replacement", + write: (handle: Persisted<(typeof Noted)["Type"]>) => + expect(() => { + // @ts-expect-error JavaScript extensions can still return a replacement at runtime + handle.update(() => ({ items: ["wrong"] })) + }).toThrow("Use set"), + expected: { items: ["a"], note: "kept" }, + }, + ])("store writes: $name becomes the whole stored value", (row) => { const key = `extension-update-${crypto.randomUUID()}` localStorage.setItem(`opencode.global.dat:${key}`, JSON.stringify({ items: ["a"], note: "kept" })) @@ -333,7 +359,7 @@ describe("extension primitives", () => { return { dispose, handle: persistedHandle({ store: pair[0], set: pair[1], init: pair[3].promise }) } }) - root.handle.update(row.mutation) + row.write(root.handle) flushPersisted() expect({ value: root.handle.value, diff --git a/packages/desktop/src/main/extension/host.ts b/packages/desktop/src/main/extension/host.ts index 547d33285c1..00b35c4e5c4 100644 --- a/packages/desktop/src/main/extension/host.ts +++ b/packages/desktop/src/main/extension/host.ts @@ -600,14 +600,20 @@ export function createHost(input: { const ids = [...local.map((definition) => definition.id), ...manager.installed().map((item) => item.id)] await Promise.all(ids.map((id) => lifecycle.activate(id))) }, - /** Activates the extension an Ipc belongs to ahead of `start`. Ipc ids start with their extension's id. */ + /** Activates the declared provider ahead of `start`, falling back to the Ipc id's extension prefix. */ demand(ipc: string) { if (ipcs.has(ipc)) return - const id = [...local.map((definition) => definition.id), ...manager.installed().map((item) => item.id)].find( - (id) => ipc === id || ipc.startsWith(`${id}.`), + const declared = local.find((definition) => + Object.values(definition.provides ?? {}).some((token) => token.id === ipc), ) + const id = + declared?.id ?? + [...local.map((definition) => definition.id), ...manager.installed().map((item) => item.id)].find( + (id) => ipc === id || ipc.startsWith(`${id}.`), + ) + if (id) void lifecycle.activate(id) }, snapshot(ipc: string, window: number) { diff --git a/packages/desktop/src/main/extension/storage.test.ts b/packages/desktop/src/main/extension/storage.test.ts index 6d602be34b4..cc6cb6941c9 100644 --- a/packages/desktop/src/main/extension/storage.test.ts +++ b/packages/desktop/src/main/extension/storage.test.ts @@ -56,14 +56,21 @@ type Seed = { describe("main extension storage", () => { // A crash right after saving keeps the value: another connection reads it without any flush. test.each([ - { name: "update", write: (opened: ReturnType) => opened.store.update(() => ["a"]), expected: ["a"] }, + { + name: "update", + write: (opened: ReturnType) => + opened.store.update((draft) => { + draft.push("a") + }), + expected: ["a"], + }, { // The open store holds what was stored, not the caller's list, which changes afterwards. - name: "a returned list", + name: "set copies a list", write: (opened: ReturnType) => { const list = ["a"] - opened.store.update(() => list) + opened.store.set(list) list.push("b") }, expected: ["a"], @@ -71,7 +78,7 @@ describe("main extension storage", () => { { name: "remove", write: (opened: ReturnType) => { - opened.store.update(() => ["a"]) + opened.store.set(["a"]) opened.storage.remove("servers") }, expected: [], @@ -81,10 +88,32 @@ describe("main extension storage", () => { name: "an update through another store on the key", write: (opened: ReturnType) => { expect(opened.store.value).toEqual([]) - opened.storage.store("servers", { schema: Schema.Array(Schema.String), initial: [] }).update(() => ["a"]) + opened.storage.store("servers", { schema: Schema.Array(Schema.String), initial: [] }).set(["a"]) }, expected: ["a"], }, + { + name: "update rejects a returned replacement", + write: (opened: ReturnType) => + expect(() => { + // @ts-expect-error JavaScript extensions can still return a replacement at runtime + opened.store.update(() => ["wrong"]) + }).toThrow("Use set"), + expected: [], + }, + { + name: "set and update retain call order", + write: (opened: ReturnType) => { + opened.store.update((draft) => { + draft.push("before") + }) + opened.store.set(["replaced"]) + opened.store.update((draft) => { + draft.push("after") + }) + }, + expected: ["replaced", "after"], + }, ])("$name reaches the database before it returns, and the open store reads it", async (row) => { const root = await directory() const file = path.join(root, "drafts.sqlite") @@ -106,6 +135,21 @@ describe("main extension storage", () => { reader.close() }) + test.each([7, null])("set persists the primitive %p immediately", async (next) => { + const root = await directory() + const file = path.join(root, "state.sqlite") + const writer = openDatabase(file) + const reader = openDatabase(file) + const settings = settingsIn(root) + const options = { schema: Schema.NullOr(Schema.Finite), initial: 0 } + const store = createStorage(createStateStore(writer.db), settings, "example").store("value", options) + store.set(next) + + expect(createStorage(createStateStore(reader.db), settings, "example").store("value", options).value).toBe(next) + writer.close() + reader.close() + }) + // The built-ins moved their main state into declared stores: each older home imports into the same row, byte for // byte (an unknown field included), and `remove` with the same `from` deletes every home it names. test.each<{ name: string; from: MainStoreFrom | readonly MainStoreFrom[]; seed: Seed; id: string; row: string }>([ diff --git a/packages/desktop/src/main/extension/storage.ts b/packages/desktop/src/main/extension/storage.ts index 995893201e5..6a9afd06c2c 100644 --- a/packages/desktop/src/main/extension/storage.ts +++ b/packages/desktop/src/main/extension/storage.ts @@ -1,4 +1,4 @@ -import type { MainStoreFrom, Storage } from "@opencode/gui-extensions/sdk/main" +import type { MainStoreFrom, Mutable, Storage } from "@opencode/gui-extensions/sdk/main" import { Option, Schema } from "effect" import type { StateStore } from "../storage/state" import type { SettingsStore } from "../storage/store" @@ -109,14 +109,19 @@ export function createStorage(state: StateStore, settings: SettingsFiles, id: st return current() }, ready: () => true, - // The draft is a decoded copy, so a mutation never touches the cached value until it is written. A returned - // value replaces the draft. - update(mutation) { + // The draft is a decoded copy, so mutation cannot touch the cache before the write. Schema readonly fields + // are type-level only; the decoded JSON's objects and arrays are writable. + update(mutate) { const draft = Schema.decodeSync(codec)(Schema.encodeSync(codec)(current())) - const next = mutation(draft) + // SAFETY: the codec above creates a writable copy of the stored JSON, including its nested fields. + const returned = mutate(draft as Mutable) - write(next === undefined ? draft : next) + if (returned !== undefined) + throw new Error("Persisted.update must not return a value. Use set(next) to replace the value.") + + write(draft) }, + set: write, } }, remove: (key, options) => remove(key, options?.from), diff --git a/packages/gui-extensions/AGENTS.md b/packages/gui-extensions/AGENTS.md index 0e8d114054e..0c19752974d 100644 --- a/packages/gui-extensions/AGENTS.md +++ b/packages/gui-extensions/AGENTS.md @@ -8,7 +8,9 @@ Built-in features of the desktop and web app, each behind the SDK in `src/sdk/`. - `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`. -- Use `requires` only where the extension is meaningless without the contract. Graceful degradation is `uses`. +- Use `requires` only where the extension is meaningless without the contract. Graceful degradation is `uses`. `Extension.compose` rejects duplicate extension ids, and duplicate or missing providers. +- A contract that returns components binds each with `bindExtension` in the provider's setup, so `useExtension` inside reads the provider's context, not the consumer's. Do not wrap data methods such as `Changes.diffs`. +- SDK icon fields take an `IconName` from `@opencode/ui/icons/catalog`, the dependency-free icon catalog. - The APIs the host always provides are context properties (`ctx.layout`, `ctx.sessions`, `ctx.storage`, `ctx.desktop`, …; in main `ctx.storage`, `ctx.windows`, `ctx.serverEndpoints`, …). `useExtension()` returns the same context in components. Points and contracts stay tokens: `ctx.add(Point, item)`, `ctx.provide(Contract, impl)`; main provides Ipcs with `ctx.provide(Ipc, impl)`. - Never import `@opencode/app`, `@opencode/desktop`, or `@/` paths. Import CSS with `?inline` and contribute it through `ctx.add(Style, css)`. No module-level state: keep state inside `setup`. `bun run lint` enforces these rules. - `bun run lint:changed` must pass before you finish: every file you add or edit has no oxlint problem at all, including the warn-level anti-slop rules (`unknown` parameters and returns, unchecked type assertions, widened types, unsafe dictionaries, missing spacing). Touching a file means leaving the whole file clean, older warnings included. Fix the code; suppress only with a `SAFETY:` comment that states a real checked invariant. @@ -30,14 +32,14 @@ Built-in features of the desktop and web app, each behind the SDK in `src/sdk/`. An instance lives from `setup` until it is disabled, reloaded, removed, or its window closes. A reload can land at any `await`, so code that outlives a tick must prove it still belongs to the live instance. - Everything registered through `ctx` (contributions, contracts, Ipc listeners, dialogs, embeds) is withdrawn with the current owner (a component, a `createKeyed` run), else with the instance. `ctx.dialogs.open` returns a handle whose `close()` closes that dialog alone. Anything else you start (timers, DOM listeners, subscriptions) needs teardown: in the window, Solid's `onCleanup` (setup runs under the extension's root owner); in main, `ctx.scope.addFinalizer`, which runs at once when the instance is already gone. `setup` returns nothing. -- `setup` may be async. After every `await`, return if the signal aborted (`ctx.signal` in the window, `ctx.scope.signal` in main) before touching state or contributing; there is no owner after an `await`, so window teardown that starts later listens to `ctx.signal`. Pass the signal, or one derived from it, to Ipc calls and long work. +- Window `setup` is synchronous: an async one fails to compile, and the host fails it at runtime. Put async work in `createKeyed` or `createLatest`, with `ctx.signal` or a signal derived from it. Only main `setup` may be async. After every `await`, return if the signal aborted (`ctx.signal` in window work, `ctx.scope.signal` in main) before touching state or contributing; there is no owner after an `await`, so window teardown that starts later listens to `ctx.signal`. Pass the signal to Ipc calls and long work. Methods without an input schema take options only, e.g. `pairing.info({ signal })`. - Never keep a value from a shorter lifetime in a longer one. Read a server's `client`, `data` and `url` from its live `ServerRef` each time: a restarted or re-authenticated server gets a new controller under the same id. Keep per-session state in a session-scoped store, or in a map keyed by `session.key` that you prune. -- Each routed session gets its own frozen `MountedSession`, and a new one when it moves to another directory (same `key` and `visit`, new `directory`). A render receives the next one through `props.session` (panels), `input.session` (slots) or `state.session` (tab labels) without remounting. Read those getters where you use them; never copy the object into a variable or key a cache by it, which would rebuild on every switch. A `MountedSession` has no actions that follow the route: the workspace files, comments and composer belong to the session screen, `ctx.screen.current()`, one object while it routes A, B and A again. Read it where you act or render, never once in setup, and key per-screen caches (such as tab objects) by it. It is undefined on Home and on a draft, where no session screen is mounted; on a mounted screen, its `session` is undefined whenever `ctx.sessions.current()` is (during the screen's first render, and while the route has left it), so check both. +- Each routed session gets its own frozen `MountedSession`, and a new one when it moves to another directory (same `key` and `visit`, new `directory`). A render receives the next one through `props.session` (panels), `input.session` (slots) or `state.session` (tab labels) without remounting. Read those getters where you use them; never copy the object into a variable or key a cache by it, which would rebuild on every switch. A `MountedSession` has no actions that follow the route: the workspace files, comments and composer belong to the session screen, one object while it routes A, B and A again. Panel callbacks take one named input with a non-null, constant `screen`; every `session.*` slot gets it too, but `window.bottom` does not. Render `tab` and `session` fields are live getters; lifecycle callbacks keep their event's tab and call metadata. Key per-screen caches by the screen. Commands and link handlers read `ctx.screen.current()` where they act, never once in setup. It is defined exactly when `ctx.sessions.current()` is: from just after the screen's first render until the route leaves it, so never on Home or a draft. Renders and render effects use their inputs, not these accessors; pass the owning screen on, as `Changes.watch(screen, source)` takes it. - Main: `ctx.lifecycle.restart(handoff, { keep: ctx.scope })` keeps the extension that owns `ctx.scope` (the caller by default) active until the handoff settles; when it rejects, return to a state the user can retry from. ## Failure is part of the contract -- A `uses` dependency is a `Live` accessor: `pending` while the provider loads, `inactive` while it is disabled, failed, or restarting. Every Ipc is `inactive` on the web. Every user action branches on it and still answers: offer the action only while it can answer (register it in a `createKeyed` run), or show an unavailable state (as WSL's "WSL unavailable" does). Never a silent `return` or an endless spinner. +- A `uses` dependency is a `Live` accessor: `pending` while the provider loads, `inactive` while it is disabled, failed, blocked by a hard dependency, or restarting. A hard dependency whose provider is disabled or failed leaves its consumer `blocked` (also the `Live` reason down the chain), and re-enabling the provider resumes it. Every Ipc is `inactive` on the web. Every user action branches on it and still answers: offer the action only while it can answer (register it in a `createKeyed` run), or show an unavailable state (as WSL's "WSL unavailable" does). Never a silent `return` or an endless spinner. - An Ipc that goes away is a suspension, not a failure: keep what the user had (for example the browser's tab inventory) and resume when it returns, without a retry timer. - An Ipc call can reject while the event that explains it is still in flight; events and call replies travel on different channels. When main reports an outcome as an event, let the event decide, and treat a rejection as final only for errors main throws before any event (validation, missing endpoint). - The host orders Ipc state for you: an event always wins over an older snapshot. Do not re-fetch state to fix ordering. @@ -47,13 +49,13 @@ 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. -- `update` edits the draft, or returns the next value, which replaces the stored one in both processes; returning is how main writes a number, `null` or a new list. Main writes reach disk at once; do not batch them yourself. +- `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`. ## Panels and layout -- `Panel.focus(tab, view, { restored })`: `restored` is true only for the selection the side region mounts with (for example after a reload). Run side effects that express user intent, such as switching the file tree's tab, only when it is false. -- The host selects a fallback tab while the stored one is not listed. If you will restore a tab, keep listing its stored id, with `hidden: true` while its content is not known yet, so the fallback never runs. +- `Panel.focus(input)`: `input.restored` is true only for the selection the side region mounts with (for example after a reload). Run side effects that express user intent, such as switching the file tree's tab, only when it is false. All panel callbacks take one named input; read its getters and do not destructure. +- The host selects the first tab with `fallback: true` in regular, `first`, then pinned tier order while the stored selection is missing or cannot be selected. False or omission opts out. If you will restore a tab, keep listing its stored id, with `hidden: true` while its content is not known yet, so the fallback never runs. - Map keys stored before extensions, or under your extension's earlier id, with `Panel.legacy`. A `transient` panel's stored keys are dropped once it stops listing them. - A `PanelTab.transient` tab is a launcher (e.g. "Open file"): the next preview replaces it, and narrow screens neither store nor select it. `closable` only styles the close button; set both when you want both. - `Layout.stored(session)` returns your stored tab ids. Layout reads return nothing while `session.location` is undefined (for example after a server re-authenticates); writes made meanwhile wait and apply in order once it is known. diff --git a/packages/gui-extensions/README.md b/packages/gui-extensions/README.md index 1213a2155cf..a30c4fef1a3 100644 --- a/packages/gui-extensions/README.md +++ b/packages/gui-extensions/README.md @@ -68,6 +68,11 @@ Setup receives one context. Components read the same object with `useExtension ) }) +``` ```ts const setup: Setup = (ctx) => { @@ -84,6 +89,8 @@ stateDiagram-v2 [*] --> loading: enabled loading --> active: setup settled loading --> failed: setup threw + loading --> blocked: requires provider disabled or failed + blocked --> loading: provider returns active --> failed: an effect threw active --> loading: reload, or a requires provider restarted active --> disabled: disabled @@ -97,7 +104,7 @@ stateDiagram-v2 - A registration ends with the current Solid owner: a component, a `createKeyed` run, or else the extension. - Teardown of other work: `onCleanup` in the window, `ctx.scope.addFinalizer` in main. Setup returns nothing. -- Setup may be async. After each `await` there is no owner. Return if `ctx.signal.aborted` (main: `ctx.scope.signal`). +- Window setup is synchronous: its `undefined` return type rejects async functions, and the host fails thenable-returning JavaScript setups instead of waiting for them. Put async work in `createKeyed` or `createLatest`, with `ctx.signal` or a signal derived from it. Only main setup may be async. After each `await` there is no owner; return if the signal aborted before registering or changing state. Late registrations remain safe: the host releases them when the owner or instance ended. The updater listens to its main side's `check` event once per generation of that side. When main restarts, the run ends and its listener goes with it: @@ -124,20 +131,18 @@ flowchart LR - A session that moves to another directory gets a new object too, with the new `directory` and the same `key` and `visit`. Key per-session state by `key`. - Renders stay mounted. The host hands them the next object through a reactive getter, so read `props.session` (panels), `input.session` (slots) or `state.session` (tab labels) where you use it, and never copy it into a variable. - The workspace files, line comments and composer follow the route, so they belong to the session screen. An action through it targets the session routed at that moment. Read it inside a render or a handler, not once in setup. Key per-screen state, such as cached tab objects, by the screen; key per-session state by `session.key`. -- The screen and its session are two different checks: - -| Read | Defined | Undefined | -| ------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ctx.screen.current()` | While a session screen is mounted: one object from its first render until it unmounts | On Home, on a draft (`/new-session` renders the new-session page, not a session screen), and before the app interface mounts | -| `ctx.screen.current()?.session` | While that screen routes a session: the same object as `ctx.sessions.current()` | Whenever `ctx.sessions.current()` is: during the screen's first render, before it registers the routed session, and while the route has left the screen for Home or a draft that has not replaced it yet | +- `ctx.screen.current()` and `ctx.sessions.current()` are published together in one batched effect after the screen's first render, with v2's original session-mount timing. Renders already receive their owning screen and session directly. Both public accessors are undefined during the first render, on Home, on a draft, before the interface mounts and once the route leaves the mounted screen. The screen has no `session` property. +- All panel callbacks take one named input: `list({ session, screen, open })`, `render({ tab, session, screen })`, `focus({ tab, session, screen, restored })`, `close({ tab, session, screen })`, `normalize({ id, session, screen })`. Session fields are getters; the screen is the constant owning screen. Render tab fields are live getters too; lifecycle callbacks receive their event's tab. Stored ids and `restored` describe that call. Do not destructure live getters. Every `session.*` slot gets a non-null `screen`; `window.bottom` does not. +- Render effects can run before public publication too: change-list views call `Changes.watch(input.screen, source)`, not `ctx.screen.current()`, so their first demand is never lost. +- `fallback: true` opts a tab into selection when the stored selection is missing or cannot be selected; false or omission opts out. The host takes the first eligible regular tab, then a `first` tab, then a pinned tab, preserving order within each tier. Closing a tab still selects its neighbour. ```ts ctx.add(Panel, { id: "main", region: "side", - list: (_session, open) => (open.includes("main") ? [tab] : []), + list: (input) => (input.open.includes("main") ? [tab] : []), // Runs once; `props.session` returns B's object after a switch to B, without a remount. - render: (props) => , + render: (props) => , }) // The composer follows the route, so it belongs to the screen: the file reaches the session routed when this runs. @@ -153,27 +158,25 @@ ctx.add(Command, { ## Primitives -| Primitive | Use it for | -| ------------------------------------------------ | ----------------------------------------------------------------------------- | -| `Extension.define(definition)` | The manifest, typed so `Setup` sees the declarations | -| `Extension.compose(...definitions)` | A process's list; fails to compile on a missing or duplicate provider | -| `Point.define(id)` | A place your extension renders and others contribute to | -| `Contract.define(id)` | An in-process API one extension provides to others | -| `Ipc.define(spec)` / `Ipc.ref(id)` | The main ↔ window contract, or a reference to it that loads no schemas | -| `Store.global` / `Store.session` / `Store.main` | Declared window state the host loads before you read it, and main state | -| `createKeyed(source, fn, { otherwise, equals })` | Side effects per provider generation or per value; the only sanctioned effect | -| `createLatest(source, fetch)` | Async data that never suspends and drops stale replies | -| `createVisitState(initial)` | State that resets each time the user routes back to the session | -| `useExtension` / `usePanel` / `useDrawer` | The context, the panel frame, and the narrow-screen drawer in components | -| `onIdle(fn)` | Preloading a lazy chunk while the app is idle | -| `Scope` (main) | `ctx.scope`: `signal`, `addFinalizer`, `fork`, `close` | +| Primitive | Use it for | +| ------------------------------------------------ | ----------------------------------------------------------------------------------- | +| `Extension.define(definition)` | The manifest, typed so `Setup` sees the declarations | +| `Extension.compose(...definitions)` | A process's list; rejects repeated extension ids and missing or duplicate providers | +| `Point.define(id)` | A place your extension renders and others contribute to | +| `Contract.define(id)` | An in-process API one extension provides to others | +| `Ipc.define(spec)` / `Ipc.ref(id)` | The main ↔ window contract, or a reference to it that loads no schemas | +| `Store.global` / `Store.session` / `Store.main` | Declared window state the host loads before you read it, and main state | +| `createKeyed(source, fn, { otherwise, equals })` | Side effects per provider generation or per value; the only sanctioned effect | +| `createLatest(source, fetch)` | Async data that never suspends and drops stale replies | +| `createVisitState(initial)` | State that resets each time the user routes back to the session | +| `useExtension` / `usePanel` / `useDrawer` | The context, the panel frame, and the narrow-screen drawer in components | +| `bindExtension(component)` | One contract component under its provider's context; data methods stay plain | +| `onIdle(fn)` | Preloading a lazy chunk while the app is idle | +| `Scope` (main) | `ctx.scope`: `signal`, `addFinalizer`, `fork`, `close` | [Lifetimes](#lifetimes) shows `createKeyed` in the updater. ```ts -// Async data: `latest` stays while a new request runs; a stale reply is dropped. -const info = createLatest(ctx.uses.pairing, (pairing, signal) => pairing.info(undefined, { signal })) - // Forget a selection when the user goes Home and back. const [selected, setSelected] = createVisitState(undefined) @@ -182,10 +185,23 @@ const Page = lazy(() => import("./page")) onCleanup(onIdle(() => void Page.preload())) ``` +Pairing's shipping page uses a query, not `createLatest`. It passes the query's abort signal directly to the no-input Ipc method; options are the only argument: + + + +```tsx +const local = useQuery(() => ({ + queryKey: [ctx.id, "local"], + queryFn: (input) => props.client.info({ signal: input.signal }), +})) +``` + ## Catalog Each line links to the file whose TSDoc covers every field. +SDK icon fields use `IconName` from `@opencode/ui/icons/catalog`, a dependency-free module with no Solid or CSS imports. The UI renderer reads that same catalog: there is no copied name list or dependency on a UI component's props, and no artwork in the general-purpose util package. + ### Points | Point | Process | What an item is | @@ -251,7 +267,7 @@ sequenceDiagram M-->>W: emit("check", null, window): the app menu asks this window to check ``` -- Define it in `contract.ts`. Its id is your extension id, or `.`. +- Define it in `contract.ts`. Its id is your extension id, or `.`. A method without an input schema takes only optional call options: `pairing.info({ signal })`, never an `undefined` placeholder. - Your own Ipc goes in `provides` only: the main entry provides it, and the window entry reads it as `ctx.uses.name`. Another extension's Ipc goes in `uses`. - On the web there is no main process: the Ipc is always `inactive`. - `IpcsProvided` fails to compile when a window provides, uses or requires an Ipc that no main entry provides. [`src/builtins.typecheck.ts`](src/builtins.typecheck.ts) checks the built-ins. @@ -273,13 +289,14 @@ A reference cannot go in `requires`: setup would wait for a `load` that only set `ctx.uses.name()` returns `Live`, one object per provider transition. -| Status | When | What the user must see | -| -------------------------- | ------------------------------------------------------------------------ | ----------------------------------------- | -| `pending` | The provider has not started, e.g. main is not up yet | A loading state, or nothing to click | -| `active` | `value` is the contract or client; `generation` counts restarts | The feature | -| `inactive`, `"restarting"` | It was active and comes back | Keep what the user had; resume after | -| `inactive`, `"disabled"` | Turned off, not composed, or not on this platform (every Ipc on the web) | An unavailable state, never a dead button | -| `inactive`, `"failed"` | Its setup threw | An unavailable state | +| Status | When | What the user must see | +| -------------------------- | ------------------------------------------------------------------------ | -------------------------------------------- | +| `pending` | The provider has not started, e.g. main is not up yet | A loading state, or nothing to click | +| `active` | `value` is the contract or client; `generation` counts restarts | The feature | +| `inactive`, `"restarting"` | It was active and comes back | Keep what the user had; resume after | +| `inactive`, `"disabled"` | Turned off, not composed, or not on this platform (every Ipc on the web) | An unavailable state, never a dead button | +| `inactive`, `"failed"` | Its setup threw | An unavailable state | +| `inactive`, `"blocked"` | A hard dependency is disabled, failed or itself blocked | An unavailable state; resume when it returns | - Offer an action only while it can answer, or let it answer with an unavailable state. Never a silent `return`, never an endless spinner. - `createKeyed` runs once per active generation. What the run registers ends with that generation. `otherwise` runs while there is none. @@ -297,7 +314,7 @@ const act = (name: "check" | "install") => { if (live.status === "active") return void import("./actions").then((module) => module[name](ctx, live.value)) - // Not loaded yet, or gone (disabled, failed, restarting): nothing can check or install. + // Not loaded yet, or gone (disabled, failed, blocked, restarting): nothing can check or install. showToast({ title: ctx.t("common.requestFailed") }) } ``` @@ -377,7 +394,7 @@ servers: Store.main(Schema.Array(SshConfig), [], { settings: "ssh.servers" }), - Keys live in your namespace: `extension..` in the window, the store's name under `extension.` in main. - `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(fn)` edits the draft, or returns the next value, which replaces the stored one, in both processes. In the window it waits for the load, then applies in call order. +- `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. @@ -394,18 +411,18 @@ servers: Store.main(Schema.Array(SshConfig), [], { settings: "ssh.servers" }), ## Testing -| Gate | Where | Catches | -| -------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Composition compile checks | [`sdk/compose.typecheck.ts`](src/sdk/compose.typecheck.ts), [`builtins.typecheck.ts`](src/builtins.typecheck.ts) | A missing `requires` provider, two providers of one token, a window Ipc no main entry provides, a key naming two tokens, a store read in the wrong process | -| Point compile checks | [`sdk/points.typecheck.ts`](src/sdk/points.typecheck.ts) | A `MenuItem` field its menu ignores | -| Graph matrix | `packages/app/component-tests/extension-graph.spec.ts` | A `requires` cycle; a consumer that fails when one optional provider is disabled | -| Keeper suites | `packages/app/e2e/regression/` | What the user sees, per product area | -| Unit tests | `*.test.ts` beside the code | Pure logic with a contract: paths, migrations, protocols | -| Lint gate | `bun run lint` (oxlint, ast-grep, `script/sdk-docs.ts`); `bun run lint:changed` | Raw effects, app imports, module state, undocumented SDK, a guide block that differs from its shipping source | +| Gate | Where | Catches | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| Composition compile checks | [`sdk/compose.typecheck.ts`](src/sdk/compose.typecheck.ts), [`builtins.typecheck.ts`](src/builtins.typecheck.ts) | Duplicate extension ids, missing or duplicate providers, wrong-process stores, readonly drafts, panel and slot inputs, no-input Ipc options | +| Point compile checks | [`sdk/points.typecheck.ts`](src/sdk/points.typecheck.ts) | A `MenuItem` field its menu ignores | +| Graph matrix | `packages/app/component-tests/extension-graph.spec.ts` | A `requires` cycle; a consumer that fails when one optional provider is disabled | +| Keeper suites | `packages/app/e2e/regression/` | What the user sees, per product area | +| Unit tests | `*.test.ts` beside the code | Pure logic with a contract: paths, migrations, protocols | +| Lint gate | `bun run lint` (oxlint, ast-grep, `script/sdk-docs.ts`); `bun run lint:changed` | Raw effects, app imports, module state, undocumented SDK, a guide block that differs from its shipping source | - Test a main entry through its `Ipc` contract with real inputs, not Electron mocks. - The hosts own their contracts: main storage in `packages/desktop/src/main/extension/storage.test.ts`, the real window host in `packages/app/component-tests/extension-host.spec.ts`. An extension does not test them again. -- Drive the race the user hits: a reload during async setup, a store that loads late, an Ipc that goes away and returns. +- Drive the race the user hits: a reload during async work, a store that loads late, an Ipc that goes away and returns. ## Build your first extension @@ -483,7 +500,7 @@ const setup: MainSetup = (ctx) => { if (enabled && blocker.id === undefined) blocker.id = powerSaveBlocker.start("prevent-display-sleep") if (!enabled) release() - stored.update(() => enabled) + stored.set(enabled) } if (stored.value) keepScreenActive(true) diff --git a/packages/gui-extensions/src/browser/panel.fixture.tsx b/packages/gui-extensions/src/browser/panel.fixture.tsx index 07a59b6512f..1fcc99346f4 100644 --- a/packages/gui-extensions/src/browser/panel.fixture.tsx +++ b/packages/gui-extensions/src/browser/panel.fixture.tsx @@ -11,7 +11,7 @@ import { type ParentComponent, type ParentProps, } from "solid-js" -import { createStore, produce } from "solid-js/store" +import { createStore, produce, reconcile } from "solid-js/store" import { Portal, render } from "solid-js/web" import type { Bridge, BridgeLayout } from "../sdk/bridge" import { @@ -29,11 +29,13 @@ import { type Layout, type Locale, type MountedSession, + type Mutable, type PanelFrame, type PanelTab, type Router, type Servers, type SessionRef, + type SessionScreen, type Storage, type Workspaces, } from "../sdk" @@ -394,7 +396,12 @@ type RegionHost = { }> > useExtensionHost(): { ready(): boolean } - createRegion(input: { region: "side"; view: Accessor; tabs: Accessor }): { + createRegion(input: { + region: "side" + view: Accessor + screen: SessionScreen + tabs: Accessor + }): { keys(): readonly string[] active(): string | undefined entry(key: string): { readonly tab: PanelTab } | undefined @@ -511,12 +518,10 @@ export function mountBrowserRegion(input: RegionHost) { const view = () => views.get(store.session) ?? fallback // One screen object while the strip mounts, whichever session it routes. - const screen = { - get session() { - return view() - }, - file, - } + // SAFETY: this fixture draws tab triggers only. Its file model implements the list, normalize and focus paths; + // comment, composer and file-view operations are never invoked here. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + const screen = { file } as unknown as SessionScreen const layout = (extension: string): Layout => ({ narrow: () => false, @@ -550,17 +555,29 @@ export function mountBrowserRegion(input: RegionHost) { if (key === "file:tree") setTree(() => value) - return [value, (mutation: (draft: T) => void) => set(produce(mutation))] as const + return { + memory: [value, (mutation: (draft: T) => void) => set(produce(mutation))] as const, + store: { + value, + ready: () => true, + update: (mutate: (draft: Mutable) => undefined) => + set( + produce((draft) => { + // SAFETY: keep uses Solid's writable produce draft; readonly schema fields apply only to readers. + const returned = mutate(draft as Mutable) + + if (returned !== undefined) throw new Error("Use set(next) to replace the value.") + }), + ), + set: (next: T) => set(reconcile(next)), + }, + } } // Loaded at once. const storage = (extension: string): Storage => ({ - store: (key, options) => { - const [value, update] = keep(`${extension}:${key}`, options.initial) - - return { value, ready: () => true, update } - }, - memory: (key, options) => keep(`${extension}:${key}`, options.initial), + store: (key, options) => keep(`${extension}:${key}`, options.initial).store, + memory: (key, options) => keep(`${extension}:${key}`, options.initial).memory, remove() {}, }) @@ -639,6 +656,7 @@ export function mountBrowserRegion(input: RegionHost) { const region = input.createRegion({ region: "side", view, + screen, tabs: () => ({ all: () => strip(view().key).all, active: () => strip(view().key).active, diff --git a/packages/gui-extensions/src/browser/refs.test.ts b/packages/gui-extensions/src/browser/refs.test.ts index 03ed79a07fd..5fec4be585d 100644 --- a/packages/gui-extensions/src/browser/refs.test.ts +++ b/packages/gui-extensions/src/browser/refs.test.ts @@ -20,13 +20,8 @@ test("element refs stay unique when the pane's main entry reloads over the same return read() }, ready: () => true, - // Like the host's: a mutation that returns a value replaces the stored one. - update: (mutation: (draft: number) => number | void) => { - const current = read() - const next = mutation(current) - - values.stored = Schema.encodeUnknownSync(declared.schema)(next === undefined ? current : next) - }, + update: (mutate: (draft: number) => void) => mutate(read()), + set: (next: number) => void (values.stored = Schema.encodeUnknownSync(declared.schema)(next)), } } diff --git a/packages/gui-extensions/src/browser/refs.ts b/packages/gui-extensions/src/browser/refs.ts index ff13f81a3e6..57797123d7a 100644 --- a/packages/gui-extensions/src/browser/refs.ts +++ b/packages/gui-extensions/src/browser/refs.ts @@ -13,7 +13,7 @@ export function createRefs(reserved: Persisted) { return () => { if (state.next >= state.end) { state.end = state.next + block - reserved.update(() => state.end) + reserved.set(state.end) } return `e${++state.next}` diff --git a/packages/gui-extensions/src/browser/renderer.tsx b/packages/gui-extensions/src/browser/renderer.tsx index 6c8f2f7fdec..634815c5d59 100644 --- a/packages/gui-extensions/src/browser/renderer.tsx +++ b/packages/gui-extensions/src/browser/renderer.tsx @@ -148,19 +148,19 @@ const setup: Setup = (ctx) => { ctx.add(Panel, { id: "main", region: "side", - list(session, open) { + list(input) { // While the model loads, the stored tabs hold the strip and its selection, as before the first inventory. - const ids = model()?.tabs(session, open) ?? open + const ids = model()?.tabs(input.session, input.open) ?? input.open if (ids.length === 0) { - tabs.delete(session.key) + tabs.delete(input.session.key) return [] } - const previous = tabs.get(session.key) - const next = new Map(ids.map((id) => [id, previous?.get(id) ?? create(session.key, id)])) - tabs.set(session.key, next) + const previous = tabs.get(input.session.key) + const next = new Map(ids.map((id) => [id, previous?.get(id) ?? create(input.session.key, id)])) + tabs.set(input.session.key, next) return [...next.values()] }, @@ -176,8 +176,8 @@ const setup: Setup = (ctx) => { )} ), - close: (tab, session) => model()?.closeTab(session, tab.id), - focus: (tab, session) => model()?.focusTab(session, tab.id), + close: (input) => model()?.closeTab(input.session, input.tab.id), + focus: (input) => model()?.focusTab(input.session, input.tab.id), }) } diff --git a/packages/gui-extensions/src/browser/restore.ts b/packages/gui-extensions/src/browser/restore.ts index df436953110..c6156203ec6 100644 --- a/packages/gui-extensions/src/browser/restore.ts +++ b/packages/gui-extensions/src/browser/restore.ts @@ -34,7 +34,7 @@ export function createBrowserRestoreStore(storage: Storage) { const target = store(key) const value = { tabs: state.tabs.map((tab) => ({ id: tab.id, url: tab.url })), focusedTabID: state.focusedTabID } - if (JSON.stringify(target.value) !== JSON.stringify(value)) target.update(() => value) + if (JSON.stringify(target.value) !== JSON.stringify(value)) target.set(value) }, // Also drops the unimported desktop row, as the pane's own close always did. remove(key: string) { diff --git a/packages/gui-extensions/src/btw/renderer.tsx b/packages/gui-extensions/src/btw/renderer.tsx index c2eb5f1e61c..ac34537bfe8 100644 --- a/packages/gui-extensions/src/btw/renderer.tsx +++ b/packages/gui-extensions/src/btw/renderer.tsx @@ -49,7 +49,7 @@ const setup: Setup = (ctx) => { // Layouts saved before extensions store the tab as "btw"; as a panel key it leaves like any unlisted transient tab. legacy: { btw: "main" }, // The answer lives only in this window's memory, so the tab lists while its session has one. - list: (session, open) => (open.includes("main") && btw.has(session) ? [tab] : []), + list: (input) => (input.open.includes("main") && btw.has(input.session) ? [tab] : []), render: (props) => ( diff --git a/packages/gui-extensions/src/context/renderer.tsx b/packages/gui-extensions/src/context/renderer.tsx index a35dfbf18da..59db34e63a1 100644 --- a/packages/gui-extensions/src/context/renderer.tsx +++ b/packages/gui-extensions/src/context/renderer.tsx @@ -18,7 +18,7 @@ const setup: Setup = (ctx) => { draggable: false, closable: "compact", first: true, - fallback: 2, + fallback: true, label: (state) => (
@@ -41,7 +41,7 @@ const setup: Setup = (ctx) => { // Stored before extensions as "context", then under the extension's earlier id `usage`. legacy: { context: "main", "usage:context": "main" }, mobile: { title: ctx.t("mobile.title"), order: 10, kind: "menu" }, - list: (_session, open) => (open.includes("main") ? [tab] : []), + list: (input) => (input.open.includes("main") ? [tab] : []), render: (props) => { const panel = usePanel() diff --git a/packages/gui-extensions/src/details/index.ts b/packages/gui-extensions/src/details/index.ts index 3ba5a3d7961..af778ea20ae 100644 --- a/packages/gui-extensions/src/details/index.ts +++ b/packages/gui-extensions/src/details/index.ts @@ -1,11 +1,9 @@ -import { Schema, Struct } from "effect" +import { Schema } from "effect" import { Changes } from "../review/contract" import { Extension, Store } from "../sdk" import en from "./i18n/en" -const Prefs = Schema.Struct({ projectExpanded: Schema.Boolean, serverExpanded: Schema.Boolean }).mapFields( - Struct.map(Schema.mutableKey), -) +const Prefs = Schema.Struct({ projectExpanded: Schema.Boolean, serverExpanded: Schema.Boolean }) export default Extension.define({ id: "details", diff --git a/packages/gui-extensions/src/details/popover.tsx b/packages/gui-extensions/src/details/popover.tsx index 2904149f4dd..eaebd68766e 100644 --- a/packages/gui-extensions/src/details/popover.tsx +++ b/packages/gui-extensions/src/details/popover.tsx @@ -5,13 +5,14 @@ import { Keybind } from "@opencode/ui/keybind" import { Tooltip } from "@opencode/ui/tooltip" import { createMemo, onCleanup, Show, Suspense, type Component, type ParentProps } from "solid-js" import { createStore } from "solid-js/store" -import { Command, createKeyed, createVisitState, useExtension, type MountedSession } from "../sdk" +import { Command, createKeyed, createVisitState, useExtension, type MountedSession, type SessionScreen } from "../sdk" import type Details from "./index" import type { Disclosure, DetailsPanelProps } from "./panel" /** The session details button of one timeline header. Cached timelines each keep their own. */ export function DetailsHeader(props: { session: MountedSession + screen: SessionScreen active: boolean panel: Component disclosure: Disclosure @@ -42,8 +43,8 @@ export function DetailsHeader(props: { // The changes row loads the session directory's changes only while the details show. createKeyed(changes, (service) => createKeyed( - () => open() && props.session, - (session) => onCleanup(service.watch(session, "details")), + () => open() && props.screen, + (screen) => onCleanup(service.watch(screen, "details")), ), ) diff --git a/packages/gui-extensions/src/details/renderer.tsx b/packages/gui-extensions/src/details/renderer.tsx index bda4f21f43b..e21d56fe39f 100644 --- a/packages/gui-extensions/src/details/renderer.tsx +++ b/packages/gui-extensions/src/details/renderer.tsx @@ -38,7 +38,13 @@ const setup: Setup = (ctx) => { at: "session.header", order: 20, render: (input) => ( - + ), }) @@ -76,7 +82,7 @@ const setup: Setup = (ctx) => { // The changes row loads the session directory's changes only while the drawer shows. createKeyed(changes, (service) => - createKeyed(frame.visible, () => onCleanup(service.watch(props.session, "details"))), + createKeyed(frame.visible, () => onCleanup(service.watch(props.screen, "details"))), ) return ( diff --git a/packages/gui-extensions/src/file/apps.ts b/packages/gui-extensions/src/file/apps.ts index 46221c349a8..d14e908f285 100644 --- a/packages/gui-extensions/src/file/apps.ts +++ b/packages/gui-extensions/src/file/apps.ts @@ -1,4 +1,4 @@ -import { Schema, Struct } from "effect" +import { Schema } from "effect" const OPEN_APPS = [ "vscode", @@ -21,4 +21,4 @@ export type OpenApp = (typeof OPEN_APPS)[number] export const OpenAppPreferences = Schema.Struct({ app: Schema.Literals(OPEN_APPS), -}).mapFields(Struct.map(Schema.mutableKey)) +}) diff --git a/packages/gui-extensions/src/file/browser.tsx b/packages/gui-extensions/src/file/browser.tsx index ff5810a66ac..073b2816947 100644 --- a/packages/gui-extensions/src/file/browser.tsx +++ b/packages/gui-extensions/src/file/browser.tsx @@ -212,7 +212,7 @@ export default function FileBrowser(props: { // Change markers in the tree load while a file tab shows, as the side panel did. createKeyed( () => (panel.visible() && !placeholder() ? changes() : undefined), - (service) => onCleanup(service.watch(props.session, "files")), + (service) => onCleanup(service.watch(props.screen, "files")), ) // Keep each file tab's last selection for the moment before a session's file view state loads. The handoff diff --git a/packages/gui-extensions/src/file/contract.ts b/packages/gui-extensions/src/file/contract.ts index dd005f9d7e2..ef4c3bab211 100644 --- a/packages/gui-extensions/src/file/contract.ts +++ b/packages/gui-extensions/src/file/contract.ts @@ -1,8 +1,10 @@ import type { JSX } from "solid-js" import type { ChangeKind } from "../review/contract" -import { Contract, type MountedSession } from "../sdk" +import { Contract, type MountedSession, type SessionScreen } from "../sdk" export interface FileTreeProps { + /** The session screen that owns the rendered files. */ + readonly screen: SessionScreen readonly session: MountedSession /** The files to show, as a tree of only these paths. */ readonly allowed: readonly string[] @@ -12,6 +14,8 @@ export interface FileTreeProps { } export interface FileListProps { + /** The session screen that owns the rendered files. */ + readonly screen: SessionScreen readonly session: MountedSession readonly files: readonly string[] readonly kinds?: ReadonlyMap diff --git a/packages/gui-extensions/src/file/index.ts b/packages/gui-extensions/src/file/index.ts index 3030b053621..128375a1cb5 100644 --- a/packages/gui-extensions/src/file/index.ts +++ b/packages/gui-extensions/src/file/index.ts @@ -1,4 +1,4 @@ -import { Schema, Struct } from "effect" +import { Schema } from "effect" import { Browser } from "../browser/contract" import { Changes } from "../review/contract" import { Extension, Store } from "../sdk" @@ -6,7 +6,7 @@ import { OpenAppPreferences } from "./apps" import { FileTree } from "./contract" import en from "./i18n/en" -const TreeState = Schema.Struct({ tab: Schema.Literals(["changes", "all"]) }).mapFields(Struct.map(Schema.mutableKey)) +const TreeState = Schema.Struct({ tab: Schema.Literals(["changes", "all"]) }) export default Extension.define({ id: "file", diff --git a/packages/gui-extensions/src/file/renderer.tsx b/packages/gui-extensions/src/file/renderer.tsx index 51b8e15b479..5e62664a0f4 100644 --- a/packages/gui-extensions/src/file/renderer.tsx +++ b/packages/gui-extensions/src/file/renderer.tsx @@ -3,13 +3,12 @@ import { Icon } from "@opencode/ui/icon" import { encodeFilePath, getFilename } from "@opencode/util/path" import { createKeyed, - ExtensionContext, + bindExtension, LinkHandler, MenuItem, Panel, Slot, Style, - useExtension, usePanel, type Files, type LineRange, @@ -46,8 +45,6 @@ const setup: Setup = (ctx) => { const layout = ctx.layout const storage = ctx.storage const desktop = ctx.desktop - // The extension's context as other extensions' views receive it. - const context = useExtension() const tree = ctx.stores.tree const [handoff, setHandoff] = storage.memory("handoff", { initial: { sessions: {} } }) const preference = desktop ? ctx.stores.app : undefined @@ -194,7 +191,7 @@ const setup: Setup = (ctx) => { }, group: GROUP, // A gone selection falls back to the first file tab. - fallback: 3, + fallback: true, dom: { panel: TABPANEL }, } } @@ -205,11 +202,10 @@ const setup: Setup = (ctx) => { legacy: { "open-file": OPEN }, // Older builds stored some files as absolute paths; one file is one tab once the workspace root is known. // Resolves the stored URL once and encodes the result, so an encoded name such as a%23b.txt stays one file. - normalize: (id) => { - const files = ctx.screen.current()?.file - - return isFileTab(id) && files?.ready() ? `//${encodeFilePath(fileTabPath(files, id))}` : id - }, + normalize: (input) => + isFileTab(input.id) && input.screen.file.ready() + ? `//${encodeFilePath(fileTabPath(input.screen.file, input.id))}` + : input.id, mobile: { get title() { return ctx.t("mobile.title") @@ -217,62 +213,51 @@ const setup: Setup = (ctx) => { order: 20, kind: "tab", }, - // The host lists tabs while the session screen renders, which `ctx.screen` returns from its first render. - list(_session, stored) { - const screen = ctx.screen.current() - - return stored.flatMap((id) => { + list(input) { + return input.open.flatMap((id) => { if (id === OPEN) return [launcher] - if (!isFileTab(id) || !screen) return [] + if (!isFileTab(id)) return [] - const cache = tabsOf(screen) + const cache = tabsOf(input.screen) const existing = cache.get(id) if (existing) return [existing] - const created = fileTab(screen.file, id) + const created = fileTab(input.screen.file, id) cache.set(id, created) return [created] }) }, - close(tab) { - const screen = ctx.screen.current() - - if (screen) tabs.get(screen)?.delete(tab.id) + close(input) { + tabs.get(input.screen)?.delete(input.tab.id) }, render: (props) => { const panel = usePanel() return ( - - {(screen) => ( - - - props.tab} session={props.session} screen={screen()} />} - > - - - - - )} - + + + props.tab} session={props.session} screen={props.screen} />} + > + + + + ) }, - focus(tab, _session, change) { - const screen = ctx.screen.current() + focus(input) { + if (!isFileTab(input.tab.id)) return - if (!isFileTab(tab.id) || !screen) return - - focused.set(screen, tab.id) - void screen.file.sync(fileTabPath(screen.file, tab.id)) + focused.set(input.screen, input.tab.id) + void input.screen.file.sync(fileTabPath(input.screen.file, input.tab.id)) // A restored file tab keeps the tree tab the user left, e.g. Changes across a reload. - if (!change.restored && tree.value.tab === "changes") shared.tree.setTab("all") + if (!input.restored && tree.value.tab === "changes") shared.tree.setTab("all") }, }) @@ -308,15 +293,11 @@ const setup: Setup = (ctx) => { ctx.add(Slot, { at: "session.panel.end", render: (input) => ( - - {(screen) => ( - - - - - - )} - + + + + + ), }) } @@ -324,63 +305,47 @@ const setup: Setup = (ctx) => { ctx.add(Slot, { at: "session.panel.sidebar", render: (input) => ( - - {(screen) => ( - - - - - - )} - + + + + + ), }) // The review panel lists its changed files with the browser's tree; it renders under this extension, on the // session screen's file model. ctx.provide(FileTree, { - Tree: (props) => ( - - - {(screen) => ( - - - props.onFileClick(node.path)} - /> - - - )} - - - ), - List: (props) => ( - - - {(screen) => ( - - - props.onFileClick(path)} - /> - - - )} - - - ), + Tree: bindExtension((props) => ( + + + props.onFileClick(node.path)} + /> + + + )), + List: bindExtension((props) => ( + + + props.onFileClick(path)} + /> + + + )), }) /** @@ -461,9 +426,7 @@ const setup: Setup = (ctx) => { createKeyed(ctx.uses.changes, (changes) => onCleanup(changes.onReveal(() => shared.tree.setTab("changes")))) // A new workspace directory drops loaded files; reload the selected file tab. - const root = createMemo( - (previous) => (sessions.current() ? ctx.screen.current()?.file.root : undefined) ?? previous, - ) + const root = createMemo((previous) => ctx.screen.current()?.file.root ?? previous) const moved = createMemo(on(root, () => ({}), { defer: true })) diff --git a/packages/gui-extensions/src/file/sidebar.tsx b/packages/gui-extensions/src/file/sidebar.tsx index 0c54a280c95..55a7ca56b46 100644 --- a/packages/gui-extensions/src/file/sidebar.tsx +++ b/packages/gui-extensions/src/file/sidebar.tsx @@ -14,7 +14,7 @@ export default function FileSidebar(props: { session: MountedSession; screen: Se const changes = () => current(shared.changes()) // The host mounts this only while the tree is open, which is when its changes should stay loaded. - createKeyed(shared.changes, (service) => onCleanup(service.watch(props.session, "tree"))) + createKeyed(shared.changes, (service) => onCleanup(service.watch(props.screen, "tree"))) // Lists the root again when the directory, the tree tab or the connection changes, and whenever the root // listing is unloaded: the workspace's tree resets to a new root entry. Loading that listing is the same key. diff --git a/packages/gui-extensions/src/pairing/main.ts b/packages/gui-extensions/src/pairing/main.ts index 0e555b7cf89..19846197325 100644 --- a/packages/gui-extensions/src/pairing/main.ts +++ b/packages/gui-extensions/src/pairing/main.ts @@ -20,7 +20,7 @@ const setup: MainSetup = (ctx) => { if (enabled && blocker.id === undefined) blocker.id = powerSaveBlocker.start("prevent-display-sleep") if (!enabled) release() - stored.update(() => enabled) + stored.set(enabled) } if (stored.value) keepScreenActive(true) diff --git a/packages/gui-extensions/src/pairing/page.tsx b/packages/gui-extensions/src/pairing/page.tsx index 6cf8dcff4e6..c30a0d807f2 100644 --- a/packages/gui-extensions/src/pairing/page.tsx +++ b/packages/gui-extensions/src/pairing/page.tsx @@ -30,7 +30,7 @@ function SettingsPairing(props: { client: Client }) { const local = useQuery(() => ({ queryKey: [ctx.id, "local"], - queryFn: () => props.client.info(), + queryFn: (input) => props.client.info({ signal: input.signal }), })) // Reading pending query data would suspend the entire settings surface. diff --git a/packages/gui-extensions/src/review/contract.ts b/packages/gui-extensions/src/review/contract.ts index 2291f1610c2..09686aa7905 100644 --- a/packages/gui-extensions/src/review/contract.ts +++ b/packages/gui-extensions/src/review/contract.ts @@ -1,5 +1,5 @@ import type { FileDiffInfo } from "@opencode/client/promise" -import { Contract, type SessionRef, type MountedSession } from "../sdk" +import { Contract, type SessionRef, type SessionScreen } from "../sdk" export type ChangeKind = "add" | "del" | "mix" @@ -26,8 +26,11 @@ export interface Changes { * Keeps the changes of the view the caller renders loaded while it shows them, across the view's session * switches. A `tree` is a persistent change list: opening the side region refreshes the changes it shows. * `details` loads `details(session)`. + * + * @param screen - The owning screen from the panel or session-slot input, available even before publication. + * @param source - The view's demand: a tree, file markers or session details. */ - watch(session: MountedSession, source: "tree" | "files" | "details"): () => void + watch(screen: SessionScreen, source: "tree" | "files" | "details"): () => void /** Runs when review reveals a change (e.g. from a composer comment), so change lists can show theirs. */ onReveal(listener: () => void): () => void } diff --git a/packages/gui-extensions/src/review/index.ts b/packages/gui-extensions/src/review/index.ts index f2f37534096..58cf2d2cda4 100644 --- a/packages/gui-extensions/src/review/index.ts +++ b/packages/gui-extensions/src/review/index.ts @@ -1,24 +1,20 @@ -import { Schema, Struct } from "effect" +import { Schema } from "effect" import { FileTree } from "../file/contract" import { Extension, Store } from "../sdk" import { Changes } from "./contract" import en from "./i18n/en" -const DiffState = Schema.Struct({ diffStyle: Schema.Literals(["unified", "split"]) }).mapFields( - Struct.map(Schema.mutableKey), -) +const DiffState = Schema.Struct({ diffStyle: Schema.Literals(["unified", "split"]) }) -const PanelState = Schema.Struct({ expandMode: Schema.Literals(["expand", "collapse"]) }).mapFields( - Struct.map(Schema.mutableKey), -) +const PanelState = Schema.Struct({ expandMode: Schema.Literals(["expand", "collapse"]) }) -const MobileDiff = Schema.Struct({ wrap: Schema.Boolean }).mapFields(Struct.map(Schema.mutableKey)) +const MobileDiff = Schema.Struct({ wrap: Schema.Boolean }) const SessionState = Schema.Struct({ mode: Schema.optional(Schema.Literals(["git", "branch", "turn"])), file: Schema.optional(Schema.String), - open: Schema.mutable(Schema.Array(Schema.String)), -}).mapFields(Struct.map(Schema.mutableKey)) + open: Schema.Array(Schema.String), +}) export default Extension.define({ id: "review", diff --git a/packages/gui-extensions/src/review/panel.tsx b/packages/gui-extensions/src/review/panel.tsx index 9fdba82e9ee..ae3852dbad5 100644 --- a/packages/gui-extensions/src/review/panel.tsx +++ b/packages/gui-extensions/src/review/panel.tsx @@ -192,6 +192,7 @@ function ReviewPanel(props: ReviewPanelProps) { // Always mounted: the sidebar header hosts the changes-mode dropdown, // which must stay reachable when the current mode has zero diffs. ( ( = (ctx) => { return created } - // Views of the screen watch while they render, which is when `ctx.screen` returns it. - const watch = (_session: MountedSession, source: keyof Demand) => { - const screen = ctx.screen.current() - - if (!screen) return () => {} - + // Views receive their screen before the public attachment is published, so initial render effects can watch it. + const watch = (screen: SessionScreen, source: keyof Demand) => { const set = demand(screen)[1] set(source, (count) => count + 1) @@ -74,7 +70,7 @@ const setup: Setup = (ctx) => { const [entry, setEntry] = createSignal<{ screen: SessionScreen; model: ReviewModel; dispose: () => void }>() createKeyed( - () => (sessions.current() ? ctx.screen.current() : undefined), + ctx.screen.current, (screen) => { const current = untrack(entry) const initial = untrack(sessions.current) @@ -129,7 +125,7 @@ const setup: Setup = (ctx) => { get tabbable() { return !(count() > 0 || layout.sidebar.opened()) }, - fallback: 1, + fallback: true, dom: { tab: "session-side-panel-review-tab", panel: "session-side-panel-review-tabpanel" }, } @@ -155,15 +151,21 @@ const setup: Setup = (ctx) => { order: 10, kind: "tab", }, - list: (session) => (!layout.narrow() && session.project ? [tab] : []), + list: (input) => (!layout.narrow() && input.session.project ? [tab] : []), render: (props) => { const frame = usePanel() - // The screen's model: the render belongs to the routed session, so it never waits for a key to match. + // A server switch mounts a new screen before the owned model effect runs. Never render the old screen's model. + const model = () => { + const current = entry() + + return current?.screen === props.screen ? current.model : undefined + } + return ( - + {(model) => { - createKeyed(frame.visible, () => onCleanup(watch(props.session, "panel"))) + createKeyed(frame.visible, () => onCleanup(watch(props.screen, "panel"))) return ( = (ctx) => { if (!layout.side.opened(session)) layout.side.toggle(session) }, - watch: (session, source) => watch(session, source), + watch, onReveal(listener) { reveals.add(listener) diff --git a/packages/gui-extensions/src/sdk/compose.typecheck.ts b/packages/gui-extensions/src/sdk/compose.typecheck.ts index bef6736db04..70c2d72bda7 100644 --- a/packages/gui-extensions/src/sdk/compose.typecheck.ts +++ b/packages/gui-extensions/src/sdk/compose.typecheck.ts @@ -4,6 +4,7 @@ import type { Accessor } from "solid-js" import { Schema } from "effect" import { Extension, + bindExtension, Ipc, Contract, Store, @@ -12,12 +13,19 @@ import { type DefinitionCheck, type Desktop, type Duplicate, + type DuplicateExtension, type IpcClient, type Live, type Missing, type MissingMain, type IpcsProvided, type SessionScreen, + type MountedSession, + type Panel, + type PanelProps, + type PanelTab, + type SlotMap, + type IconName, type Setup, } from "./index" import type { MainSetup } from "./main" @@ -58,6 +66,17 @@ equal, { readonly "missing p true, ) +// Extension identities must be unique even when the definitions provide nothing. +const SameId = Extension.define({ id: "tree" }) + +// @ts-expect-error two definitions share the extension id tree +Extension.compose(TreeProvider, SameId) + +equal< + Composition<[typeof TreeProvider, typeof SameId]>, + { readonly "duplicate extension": DuplicateExtension<"tree"> } +>(true) + // Two providers of one token. const Second = Extension.define({ id: "second", provides: { tree: Tree } }) @@ -128,6 +147,89 @@ export const setup: Setup = (ctx) => { // @ts-expect-error a session has no composer: read `ctx.screen.current()?.composer` void session?.composer equal, SessionScreen | undefined>(true) + // @ts-expect-error the screen has no duplicate session accessor + void ctx.screen.current()?.session + ctx.stores.view.update((draft) => { + draft.open = true + }) + ctx.stores.view.set({ open: false }) + // @ts-expect-error update only mutates; replacement values go through set + ctx.stores.view.update(() => ({ open: true })) + // @ts-expect-error replacement values match the schema + ctx.stores.view.set({ open: "wrong" }) +} + +equal>, undefined>(true) + +// @ts-expect-error an async window setup returns a Promise, not undefined +export const asyncSetup: Setup = async () => {} + +// @ts-expect-error a window setup cannot return an object either +export const returningSetup: Setup = () => ({ open: true }) + +equal>, void | Promise>(true) + +equal(true) + +equal[0]["session"], MountedSession>(true) + +equal[0]["screen"], SessionScreen>(true) + +equal>[0]["restored"], boolean>(true) + +equal>[0]["screen"], SessionScreen>(true) + +equal>[0], PanelProps>(true) + +equal(true) + +equal(true) + +equal(true) + +equal(true) + +equal(true) + +export const ineligible: PanelTab = { id: "details", title: "Details", fallback: false } + +equal, { status: "inactive" }>["reason"], "disabled" | "failed" | "blocked" | "restarting">(true) + +// @ts-expect-error only known artwork names belong to SDK icon fields +export const unknownIcon: IconName = "not-an-icon" + +export const bound = bindExtension((props: { readonly label: string }) => props.label) + +// @ts-expect-error bound components preserve the original props +bound({ wrong: "field" }) + +const NoInput = Ipc.define({ id: "fixture.no-input", methods: { info: { output: Schema.String } } }) + +export function noInput(client: IpcClient, signal: AbortSignal) { + void client.info() + void client.info({ signal }) + // @ts-expect-error no input placeholder before call options + void client.info(undefined, { signal }) + // @ts-expect-error strictly typed call options + void client.info({ signal: "wrong" }) +} + +const Nested = Extension.define({ + id: "nested", + stores: { + prefs: Store.global(Schema.Struct({ items: Schema.Array(Schema.Struct({ shown: Schema.Boolean })) }), { + items: [], + }), + }, +}) + +export const nested: Setup = (ctx) => { + ctx.stores.prefs.update((draft) => { + draft.items.push({ shown: true }) + draft.items[0].shown = false + }) + // @ts-expect-error stored values stay readonly outside update + ctx.stores.prefs.value.items.push({ shown: true }) } export const provider: Setup = (ctx) => { diff --git a/packages/gui-extensions/src/sdk/context.ts b/packages/gui-extensions/src/sdk/context.ts index fe6a16cfe50..e551d308df6 100644 --- a/packages/gui-extensions/src/sdk/context.ts +++ b/packages/gui-extensions/src/sdk/context.ts @@ -294,7 +294,12 @@ export interface SetupContext extends Omit { /** * A window entry: the default export of `renderer.tsx`. `Setup` types the context from the - * definition's declarations. It may be async; return nothing. + * definition's declarations. Runs synchronously under the extension's Solid owner; return nothing. Put async work + * in `createKeyed` or `createLatest`, and pass `ctx.signal` or a signal derived from it. + * The `undefined` return type rejects async functions and replacement values, while accepting a block with no + * return. The host also rejects thenables from JavaScript entries and aborts their late work. + * + * @param ctx - The extension's declared APIs, dependencies and stores, under its Solid owner. * * @example * ```ts @@ -304,4 +309,4 @@ export interface SetupContext extends Omit { * export default setup * ``` */ -export type Setup = (ctx: SetupContext) => void | Promise +export type Setup = (ctx: SetupContext) => undefined diff --git a/packages/gui-extensions/src/sdk/core.ts b/packages/gui-extensions/src/sdk/core.ts index 4a1df739fb3..811281e2c2f 100644 --- a/packages/gui-extensions/src/sdk/core.ts +++ b/packages/gui-extensions/src/sdk/core.ts @@ -44,8 +44,8 @@ export type Catalog = { } /** - * What an entry's setup returns. Teardown is not returned: a window entry uses Solid's `onCleanup` (setup runs under - * the extension's root owner) and `ctx.signal`; a main entry uses `ctx.scope.addFinalizer` and `ctx.scope.signal`. + * What a main entry's setup returns. Teardown is not returned: main uses `ctx.scope.addFinalizer` and + * `ctx.scope.signal`. Window setup is synchronous and returns nothing. */ type Result = void | Promise @@ -100,7 +100,7 @@ export interface Definition { readonly provides?: Tokens /** * Optional dependencies that other extensions provide. Each is a `Live` accessor in `ctx.uses`: pending while its - * provider loads, inactive while it is disabled, failed or restarting. The extension must keep working while one is + * provider loads, inactive while it is disabled, failed, blocked or restarting. The extension must keep working while one is * inactive. Your own tokens need no entry: `provides` already puts them in `ctx.uses`. A key that names one token in * `provides` and another here fails to compile (`Conflict<"key">`). */ @@ -120,7 +120,7 @@ export interface Definition { /** The window entry; its default export is a `Setup` (`@opencode/gui-extensions/sdk`). */ readonly renderer?: () => Promise<{ /** The window setup. */ - readonly default: (ctx: never) => Result + readonly default: (ctx: never) => void }> /** The main entry; its default export is a `MainSetup` (`@opencode/gui-extensions/sdk/main`). */ readonly main?: () => Promise<{ @@ -267,17 +267,21 @@ type TypeOf = C extends Codec ? C["Type"] : void * * @example * ```ts - * const info = await pairing.info(undefined, { signal: ctx.signal }) + * const info = await pairing.info({ signal: ctx.signal }) * ``` */ export type IpcClient = { - readonly [Name in keyof S["methods"]]: ( - input: TypeOf, - options?: { - /** Aborts the call: main's `Caller.signal` aborts, and the promise rejects. */ - readonly signal?: AbortSignal - }, - ) => Promise> + readonly [Name in keyof S["methods"]]: S["methods"][Name] extends { readonly input: Codec } + ? ( + /** The argument decoded by this method's input schema. */ + input: TypeOf, + /** Optional per-call cancellation. */ + options?: IpcCallOptions, + ) => Promise> + : ( + /** Optional per-call cancellation; no input placeholder is accepted. */ + options?: IpcCallOptions, + ) => Promise> } & { /** * This window's state, as main's `IpcImpl.state` last pushed it. Undefined until the first snapshot arrives and @@ -298,6 +302,12 @@ export type IpcClient = { ): Cleanup } +/** Options for any Ipc method. A method without an input schema takes these as its only argument. */ +export interface IpcCallOptions { + /** Aborts the call: main's `Caller.signal` aborts, and the promise rejects. */ + readonly signal?: AbortSignal +} + /** The value a token gives its users: the contract itself, or the client of an Ipc. */ export type TokenValue = T extends Ipc @@ -315,7 +325,8 @@ export type TokenValue = * - `active`: `value` is the contract or Ipc client. `generation` counts activations: a provider that restarts comes * back with a new one. * - `inactive`: the provider is gone, and `reason` says why: `disabled` (turned off, absent, or not on this platform, - * such as every Ipc on the web), `failed` (its setup threw), or `restarting` (it was active before and is coming back). + * such as every Ipc on the web), `failed` (its setup threw), `blocked` (a hard dependency is unavailable), or + * `restarting` (it was active before and is coming back). * * @example * ```ts @@ -343,9 +354,10 @@ export type Live = * Why the provider is gone. * - `disabled`: turned off, not composed, or not on this platform. * - `failed`: its setup threw. + * - `blocked`: a hard dependency is disabled, failed or itself blocked. * - `restarting`: it was active before and is coming back. */ - readonly reason: "disabled" | "failed" | "restarting" + readonly reason: "disabled" | "failed" | "blocked" | "restarting" } const live = Symbol.for("opencode.extension.live") @@ -681,7 +693,8 @@ export const Store = { * @example * ```ts * const prefs = ctx.stores.prefs - * prefs.update((draft) => ({ shown: !draft.shown })) + * prefs.update((draft) => { draft.shown = !draft.shown }) + * prefs.set({ shown: true }) * ``` */ export interface Persisted { @@ -690,15 +703,30 @@ export interface Persisted { /** The stored value has loaded. Always true in main. Reactive in the window. */ ready(): boolean /** - * Changes the stored value. In the window it waits until the value has loaded, then applies in call order; in main - * it writes at once. The mutation edits `draft` in place, or returns the next value, which replaces the stored one; - * return nothing after editing the draft. + * Mutates a deep-mutable draft, even when the schema's fields are readonly. Return nothing or `undefined`; + * returning a replacement is a compile error and throws at runtime. Use `set` to replace the value. In the + * window it waits for load and applies in call order with `set`; in main it writes at once. * - * @param mutation - Receives a draft of the current value. + * @param mutate - Edits a draft of the current value in place. */ - update(mutation: (draft: T) => T | void): void + update( + mutate: ( + /** A deep-mutable copy of the current value; edit it in place. */ + draft: Mutable, + ) => undefined, + ): void + /** + * Replaces the stored value. In the window it waits for load and applies in call order with `update`; in main it + * writes at once. Use this for primitives or to replace an object or collection. + * + * @param next - The complete next value, typed by the store's schema. + */ + set(next: T): void } +/** A stored value's writable draft, recursively removing readonly fields and collection entries. */ +export type Mutable = T extends object ? { -readonly [K in keyof T]: Mutable } : T + /** The tokens a definition declares under `K`; `{}` when it declares none. */ export type Declared = D extends { readonly [P in K]?: infer M } ? M extends Tokens @@ -735,6 +763,12 @@ export interface Duplicate { readonly [problem]: Id } +/** `Extension.compose`'s error: two definitions use the same extension id. */ +export interface DuplicateExtension { + /** The repeated extension id. */ + readonly [problem]: Id +} + /** `IpcsProvided`'s error: a window `provides`, `uses` or `requires` of an Ipc that no main entry provides. */ export interface MissingMain { /** The Ipc's id. */ @@ -784,8 +818,21 @@ type DuplicateIds = { [I in keyof Ds]: Literal> & Ids, "provides"> }[number] +type ExtensionId = D extends { readonly id: infer Id } ? Literal : never + +type DuplicateExtensions = { + [I in keyof Ds]: ExtensionId & ExtensionId> +}[number] + /** Compile errors for a composition; `unknown` when it is valid. */ -export type Composition = [MissingIds] extends [never] +export type Composition = [DuplicateExtensions] extends [never] + ? ProvidersCheck + : { + /** Two definitions share this extension id. */ + readonly "duplicate extension": DuplicateExtension> + } + +type ProvidersCheck = [MissingIds] extends [never] ? [DuplicateIds] extends [never] ? unknown : { @@ -846,7 +893,8 @@ export const Extension = { definition, /** * Returns the definitions as they are. Fails to compile, naming the token id, when a `requires` token has no - * provider in the composition (`Missing<"id">`), or when two extensions provide the same token (`Duplicate<"id">`). + * provider in the composition (`Missing<"id">`), when two extensions provide the same token (`Duplicate<"id">`), + * or when two definitions share an extension id (`DuplicateExtension<"id">`). * * @param definitions - Every extension of one process, each with its entry. * @returns The same definitions, as an array. diff --git a/packages/gui-extensions/src/sdk/host-apis.ts b/packages/gui-extensions/src/sdk/host-apis.ts index f8aeab6508d..272363faf4b 100644 --- a/packages/gui-extensions/src/sdk/host-apis.ts +++ b/packages/gui-extensions/src/sdk/host-apis.ts @@ -576,12 +576,6 @@ export interface MountedSession extends SessionRef { * views that render inside it; a `MountedSession` you keep never acts on another session. */ export interface SessionScreen { - /** - * The routed session, the object `Sessions.current` returns, and undefined whenever that is: until the screen has - * mounted, and while the route leaves for Home or a draft. Reactive. Inside a render, read `props.session` or - * `input.session` instead. - */ - readonly session: MountedSession | undefined /** The routed workspace's files. */ readonly file: Files /** The line comments of the routed session's next prompt. */ @@ -590,12 +584,13 @@ export interface SessionScreen { readonly composer: Composer } -/** The session screen, while one is mounted. */ +/** The session screen, while it routes the mounted session. */ export interface Screen { /** * The mounted session screen: the same object for as long as it stays mounted, whichever session it routes. Defined - * from the screen's first render, so every panel, slot and tab of the screen can read it; undefined on Home, on a - * draft and before the app interface mounts. Reactive. + * exactly when `Sessions.current()` is, after the screen's first render; undefined on Home, on a draft, + * while the route has left the mounted screen, and before the app interface mounts. Panel callbacks and session + * slots receive a non-null screen directly. Reactive. */ current(): SessionScreen | undefined } @@ -606,7 +601,9 @@ export interface Sessions { list(): readonly SessionRef[] /** * The routed, mounted session: a new object each time a session is routed. Undefined on Home, on a draft, and - * before the app interface mounts. Reactive. + * before the app interface mounts and during the screen's first render. Defined exactly when `Screen.current()` + * is, after that first render. Panel and session-slot inputs are available during render directly. + * Reactive. */ current(): MountedSession | undefined } diff --git a/packages/gui-extensions/src/sdk/main.ts b/packages/gui-extensions/src/sdk/main.ts index 1fc2ee2016f..f3c4e657980 100644 --- a/packages/gui-extensions/src/sdk/main.ts +++ b/packages/gui-extensions/src/sdk/main.ts @@ -90,8 +90,7 @@ export interface Storage { * The window's `Persisted` shape, read and written synchronously: `value` is always defined and `ready()` always * true. Values are stored as the schema's canonical JSON; the schema must not need services. A stored value that * fails to decode reads as `initial`. Each write reaches the database before it returns. `update` changes a copy of - * the value; a mutation may also return the next value, which replaces it, so a number, `null` or a new list is - * written that way. + * the value through a deep-mutable draft; `set` replaces it, including a number, `null` or a new list. * * @param key - The store's key in your namespace. * @param options - The store's options. @@ -99,7 +98,7 @@ export interface Storage { * @example * ```ts * const tabs = ctx.storage.store(`restore:${session}`, { schema: Tabs, initial: [] }) - * tabs.update(() => next) + * tabs.set(next) * ``` */ store>( @@ -251,7 +250,7 @@ export interface MainContext extends BaseContext { * @example * ```ts * const count = ctx.stores.count - * count.update((value) => value + 1) + * count.set(count.value + 1) * ``` */ readonly stores: MainStores @@ -362,7 +361,7 @@ export interface MainContext extends BaseContext { * ```ts * const setup: MainSetup = (ctx) => { * const stored = ctx.stores.keepScreenActive // a declared main store, always loaded - * ctx.provide(Pairing, { info, code, screenActive, setScreenActive: (enabled) => stored.update(() => enabled) }) + * ctx.provide(Pairing, { info, code, screenActive, setScreenActive: (enabled) => stored.set(enabled) }) * } * export default setup * ``` diff --git a/packages/gui-extensions/src/sdk/points.ts b/packages/gui-extensions/src/sdk/points.ts index 5f69ea3dbdf..a6eb1e934c0 100644 --- a/packages/gui-extensions/src/sdk/points.ts +++ b/packages/gui-extensions/src/sdk/points.ts @@ -1,10 +1,10 @@ -import type { IconProps } from "@opencode/ui/icon" import type { JSX } from "solid-js" +import type { IconName } from "@opencode/ui/icons/catalog" import { Point } from "./core" -import type { SessionRef, MountedSession } from "./host-apis" +import type { SessionRef, MountedSession, SessionScreen } from "./host-apis" -/** The name of an icon in `@opencode/ui/icon`. */ -export type IconName = IconProps["name"] +/** The name of a shared icon; derived from the dependency-free UI artwork catalog, not a component's props. */ +export type { IconName } /** * A command in the palette, with an optional keybind and slash command. The host publishes it as @@ -168,8 +168,8 @@ export interface PanelTab { * closing it selects the first remaining tab. */ readonly first?: boolean - /** Selected when the stored selection is gone. The highest value wins, then strip order. */ - readonly fallback?: number + /** Opts into fallback selection: first eligible regular tab, then a `first` tab, then a pinned tab. Defaults to false. */ + readonly fallback?: boolean /** Tabs in one group share one render that stays mounted while any member is listed. */ readonly group?: string /** Struck through, e.g. a file that no longer exists. */ @@ -213,15 +213,17 @@ export interface MobileView { } /** - * What `Panel.render` receives. Both fields are reactive getters: read `props.tab` and `props.session` where you use - * them, and do not destructure. When another session is routed, `session` returns its object and the render stays - * mounted. + * What `Panel.render` receives. `tab` and `session` are reactive getters; `screen` is the constant owning screen. + * Read the getters where you use them and do not destructure. On a session switch the render stays mounted and + * receives the next session. In `focus` and `close`, `tab` is the event's tab, not the render's changing selection. */ export interface PanelProps { /** The tab, as `list` currently returns it. */ readonly tab: PanelTab /** The routed session. */ readonly session: MountedSession + /** The session screen that owns this panel's files, comments and composer; always present. */ + readonly screen: SessionScreen } /** A panel: the tabs an extension shows in a session's side region, or its dock. */ @@ -248,10 +250,16 @@ export interface Panel { * The canonical form of one of this panel's stored tab ids, when one tab can be stored more than one way (e.g. * the same file as an absolute and a relative path). The host rewrites stored ids and drops duplicates. Reactive. * - * @param id - A stored tab id. - * @param session - The routed session. + * @param input - The stored id, session getter and constant owning screen. Do not destructure the session. */ - normalize?(id: string, session: MountedSession): string + normalize?(input: { + /** A stored tab id. */ + readonly id: string + /** The routed session. */ + readonly session: MountedSession + /** The session screen; always present. */ + readonly screen: SessionScreen + }): string /** * A narrow-screen view of this panel. The render sees `usePanel().placement() === "mobile"` and receives a tab with * the panel's `id` and the view's `title`. @@ -261,38 +269,40 @@ export interface Panel { * Reactive, and runs again when another session is routed. `open` holds this extension's tab ids stored in the * strip. List those that still apply, plus any `pinned` tab. The host renders triggers, restore, and selection from * this data. Cache tab objects by something that outlives one session object (the tab id, `session.key`, or the - * screen `ctx.screen.current()` returns), so a session switch does not render their labels again. + * screen passed as `input.screen`), so a session switch does not render their labels again. Read the getters; + * do not destructure. * - * @param session - The routed session. - * @param open - This extension's stored tab ids, in strip order. + * @param input - A session getter, the constant owning screen and this call's stored tab ids. */ - list(session: MountedSession, open: readonly string[]): readonly PanelTab[] + list(input: { + /** The routed session. */ + readonly session: MountedSession + /** The session screen; always present. */ + readonly screen: SessionScreen + /** This extension's stored tab ids, in strip order. */ + readonly open: readonly string[] + }): readonly PanelTab[] /** * Renders a tab's content once; its own reactivity updates it, also when another session is routed. A render that * throws renders nothing and records the error. * - * @param props - The tab and the routed session, as reactive getters. + * @param props - The tab and session as reactive getters, and the constant owning screen. */ render(props: PanelProps): JSX.Element /** * Runs after the host removes the tab from the strip. * - * @param tab - The removed tab. - * @param session - The routed session. + * @param input - The removed tab, routed session and owning screen. Read the getters; do not destructure. */ - close?(tab: PanelTab, session: MountedSession): void + close?(input: PanelProps): void /** * Runs when the tab becomes selected. `restored` is true for the selection the side region mounts with, e.g. the * tab selected before a reload, and false for every later selection change. * - * @param tab - The selected tab. - * @param session - The routed session. - * @param change - How the selection came about. + * @param input - The selected tab, routed session, owning screen and selection origin. Do not destructure. */ focus?( - tab: PanelTab, - session: MountedSession, - change: { + input: PanelProps & { /** The selection the side region mounted with, not a user's choice. */ readonly restored: boolean }, @@ -542,6 +552,8 @@ export interface SlotMap { readonly "window.bottom": Record /** The timeline title row. Cached timelines stay mounted while hidden; `active` is false then. */ readonly "session.header": { + /** The timeline's owning session screen; always present, also while the timeline is cached. */ + readonly screen: SessionScreen /** The timeline's session: its latest object, kept while the timeline is hidden. */ readonly session: MountedSession /** The timeline is the one on screen. */ @@ -549,11 +561,15 @@ export interface SlotMap { } /** The actions at the end of the side region's tab strip. */ readonly "session.panel.end": { + /** The owning session screen; always present. */ + readonly screen: SessionScreen /** The routed session; a new object when another session is routed. */ readonly session: MountedSession } /** The side region's inner sidebar, shown while it is open. */ readonly "session.panel.sidebar": { + /** The owning session screen; always present. */ + readonly screen: SessionScreen /** The routed session; a new object when another session is routed. */ readonly session: MountedSession } @@ -567,8 +583,9 @@ export type Slot = { /** Slot contents render in ascending order. Defaults to 0. */ readonly order?: number /** - * Renders the content once; its own reactivity updates it. The input's fields are reactive getters, so read - * `input.session` where you use it: another routed session arrives through it without a remount. A render that + * Renders the content once; its own reactivity updates it. Session and active fields are reactive getters, so read + * `input.session` where you use it: another routed session arrives through it without a remount. `screen` on a + * session slot is its constant owning screen, available during the first render. A render that * throws renders nothing and records the error. * * @param input - The slot's input. @@ -612,7 +629,7 @@ export const MenuItem = Point.define("menu-item") * ctx.add(Panel, { * id: "main", * region: "side", - * list: (session, open) => (open.includes("main") ? [tab] : []), + * list: (input) => (input.open.includes("main") ? [tab] : []), * render: (props) => , * }) * ``` diff --git a/packages/gui-extensions/src/sdk/reactive.ts b/packages/gui-extensions/src/sdk/reactive.ts index 1e215324282..a346dfa6eb1 100644 --- a/packages/gui-extensions/src/sdk/reactive.ts +++ b/packages/gui-extensions/src/sdk/reactive.ts @@ -141,7 +141,7 @@ export function createKeyed( * * @example * ```ts - * const info = createLatest(ctx.uses.pairing, (pairing, signal) => pairing.info(undefined, { signal })) + * const info = createLatest(ctx.uses.pairing, (pairing, signal) => pairing.info({ signal })) * const urls = () => info.latest?.urls ?? [] * ``` */ diff --git a/packages/gui-extensions/src/sdk/solid.ts b/packages/gui-extensions/src/sdk/solid.ts index 787ec0f1b3c..574a96dfeb4 100644 --- a/packages/gui-extensions/src/sdk/solid.ts +++ b/packages/gui-extensions/src/sdk/solid.ts @@ -1,4 +1,4 @@ -import { createContext, useContext, type Accessor } from "solid-js" +import { createComponent, createContext, useContext, type Accessor, type Component } from "solid-js" import type { Context, SetupContext } from "./context" import type { Definition } from "./core" @@ -16,7 +16,8 @@ export const LifetimeContext = createContext<{ /** * The extension's context inside a contribution: the same object setup receives. Pass the definition for the typed - * declarations. Throws outside an extension contribution. + * declarations. Throws outside an extension contribution. A component returned by a contract must be bound with + * `bindExtension` in the provider's setup; otherwise it reads the consuming extension's context. * * @example * ```ts @@ -35,6 +36,31 @@ export function useExtension() { return context as [D] extends [never] ? Context : SetupContext } +/** + * Binds one contract component to the providing extension's context. Call during setup, then provide the returned + * component: `useExtension` inside it reads the provider, not the extension that renders it. Props retain their + * reactive getters. Data methods need no wrapper. Throws outside an extension's owner. + * + * @param component - One component the contract exposes. + * @returns The component under the providing extension's context. + * + * @example + * ```ts + * ctx.provide(FileTree, { Tree: bindExtension((props) => ) }) + * ``` + */ +export function bindExtension

(component: Component

): Component

{ + const context = useExtension() + + return (props) => + createComponent(ExtensionContext.Provider, { + value: context, + get children() { + return createComponent(component, props) + }, + }) +} + /** The inner sidebar preference every side panel shares, as `PanelFrame.sidebar`. */ export interface PanelSidebar { /** The inner sidebar is open. Reactive. */ diff --git a/packages/gui-extensions/src/ssh/main.ts b/packages/gui-extensions/src/ssh/main.ts index 86863f0e34d..4be32c648fa 100644 --- a/packages/gui-extensions/src/ssh/main.ts +++ b/packages/gui-extensions/src/ssh/main.ts @@ -28,7 +28,7 @@ const setup: MainSetup = async (ctx) => { binary: cli.binary ?? cli.command[0] ?? "opencode", command: cli.command, configs: saved.value, - save: (configs) => Effect.try({ try: () => saved.update(() => configs), catch: SshFailure.from }), + save: (configs) => Effect.try({ try: () => saved.set(configs), catch: SshFailure.from }), }).pipe(Scope.provide(scope)), ) diff --git a/packages/gui-extensions/src/terminal/model.ts b/packages/gui-extensions/src/terminal/model.ts index 8091b3f4b0c..8ba5f356e88 100644 --- a/packages/gui-extensions/src/terminal/model.ts +++ b/packages/gui-extensions/src/terminal/model.ts @@ -1,6 +1,6 @@ import { batch, createMemo, createRoot, getOwner, onCleanup, untrack } from "solid-js" import { createStore } from "solid-js/store" -import { createKeyed, type Storage, type ServerRef, type MountedSession, type Sessions } from "../sdk" +import { createKeyed, type Mutable, type Storage, type ServerRef, type MountedSession, type Sessions } from "../sdk" import { MAX_TERMINAL_SESSIONS, numberFromTitle, TerminalState, type LocalPTY } from "./state" import { defaultTitle } from "./title" @@ -29,7 +29,7 @@ type Ghostty = { shared?: ReturnType } const workspaceKey = (server: string, directory: string) => `${server}\0${directory}` -const trimTerminal = (pty: LocalPTY) => { +const trimTerminal = (pty: Mutable) => { if (!pty.buffer && pty.cursor === undefined && pty.scrollY === undefined) return pty.buffer = undefined @@ -307,10 +307,7 @@ function createWorkspace(input: { storage: Storage; server: ServerRef; directory all, active, clear() { - stored.update((draft) => { - draft.active = undefined - draft.all = [] - }) + stored.set({ active: undefined, all: [] }) }, new() { const nextNumber = pickNextTerminalNumber() @@ -360,10 +357,14 @@ function createWorkspace(input: { storage: Storage; server: ServerRef; directory if (index === -1) return - stored.update((draft) => trimTerminal(draft.all[index])) + stored.update((draft) => { + trimTerminal(draft.all[index]) + }) }, trimAll() { - stored.update((draft) => draft.all.forEach(trimTerminal)) + stored.update((draft) => { + draft.all.forEach(trimTerminal) + }) }, clone, open(id: string) { diff --git a/packages/gui-extensions/src/terminal/state.ts b/packages/gui-extensions/src/terminal/state.ts index a3b2e0954a1..fa50d397de7 100644 --- a/packages/gui-extensions/src/terminal/state.ts +++ b/packages/gui-extensions/src/terminal/state.ts @@ -1,28 +1,27 @@ -import { Effect, Option, Schema, SchemaGetter, Struct } from "effect" +import { Effect, Option, Schema, SchemaGetter } from "effect" import { titleNumber } from "./title" // Same recovery rules as the host's persistence schema helpers, so stored terminals decode as before. function fallback>(schema: S, value: () => S["Type"]) { const defaulted = Schema.withDecodingDefaultType(Effect.sync(value))(schema) + return Schema.catchDecoding(() => Effect.sync(() => Option.some(value())))(defaulted) } function optional>(schema: S) { const field = Schema.optional(schema) - return Schema.catchDecoding(() => Effect.succeed(Option.none()))(field) -} -function struct(fields: Fields) { - return Schema.Struct(fields).mapFields(Struct.map(Schema.mutableKey)) + return Schema.catchDecoding(() => Effect.succeed(Option.none()))(field) } // Recover individual entries rather than discarding the whole collection. function array>(schema: S) { const decode = Schema.decodeUnknownOption(schema) const encode = Schema.encodeSync(schema) + return fallback( Schema.Array(Schema.Unknown).pipe( - Schema.decodeTo(Schema.mutable(Schema.Array(Schema.toType(schema))), { + Schema.decodeTo(Schema.Array(Schema.toType(schema)), { decode: SchemaGetter.transform((items) => items.flatMap((item) => Option.toArray(decode(item)))), encode: SchemaGetter.transform((items) => items.map((item) => encode(item))), }), @@ -31,7 +30,7 @@ function array>(schema: S) { ) } -const PTY = struct({ +const PTY = Schema.Struct({ id: Schema.NonEmptyString, title: fallback(Schema.String, () => ""), titleNumber: fallback(Schema.Finite, () => 0), @@ -50,7 +49,7 @@ export function numberFromTitle(title: string) { return titleNumber(title, MAX_TERMINAL_SESSIONS) } -const State = struct({ +const State = Schema.Struct({ active: optional(Schema.String), all: array(PTY), }) @@ -59,11 +58,14 @@ export const TerminalState = State.pipe( Schema.decodeTo(Schema.toType(State), { decode: SchemaGetter.transform((value) => { const seen = new Set() + const all = value.all.flatMap((pty) => { if (seen.has(pty.id)) return [] seen.add(pty.id) + return [{ ...pty, titleNumber: pty.titleNumber > 0 ? pty.titleNumber : (numberFromTitle(pty.title) ?? 0) }] }) + return { active: value.active && seen.has(value.active) ? value.active : all[0]?.id, all, diff --git a/packages/gui-extensions/src/updater/index.ts b/packages/gui-extensions/src/updater/index.ts index cc7b358c2cb..cb8dc099fa3 100644 --- a/packages/gui-extensions/src/updater/index.ts +++ b/packages/gui-extensions/src/updater/index.ts @@ -1,11 +1,11 @@ -import { Schema, Struct } from "effect" +import { Schema } from "effect" import { Extension, Store } from "../sdk" import { Updater } from "./contract" import en from "./i18n/en" -const ReleaseNotes = Schema.Struct({ enabled: Schema.Boolean }).mapFields(Struct.map(Schema.mutableKey)) +const ReleaseNotes = Schema.Struct({ enabled: Schema.Boolean }) -const Seen = Schema.Struct({ version: Schema.optional(Schema.String) }).mapFields(Struct.map(Schema.mutableKey)) +const Seen = Schema.Struct({ version: Schema.optional(Schema.String) }) export default Extension.define({ id: "updater", diff --git a/packages/gui-extensions/src/updater/main.ts b/packages/gui-extensions/src/updater/main.ts index 8c42c15032a..355dc5e560b 100644 --- a/packages/gui-extensions/src/updater/main.ts +++ b/packages/gui-extensions/src/updater/main.ts @@ -38,8 +38,8 @@ const setup: MainSetup = async (ctx) => { }), persistence: { get: Effect.sync(() => ready.value ?? undefined), - set: (value) => Effect.sync(() => ready.update(() => value)), - clear: Effect.sync(() => ready.update(() => null)), + set: (value) => Effect.sync(() => ready.set(value)), + clear: Effect.sync(() => ready.set(null)), }, changed: () => publish.changed(), }).pipe(Scope.provide(scope)), diff --git a/packages/gui-extensions/src/updater/renderer.tsx b/packages/gui-extensions/src/updater/renderer.tsx index 9fe7e8da62f..039f85438bf 100644 --- a/packages/gui-extensions/src/updater/renderer.tsx +++ b/packages/gui-extensions/src/updater/renderer.tsx @@ -21,7 +21,7 @@ const setup: Setup = (ctx) => { if (live.status === "active") return void import("./actions").then((module) => module[name](ctx, live.value)) - // Not loaded yet, or gone (disabled, failed, restarting): nothing can check or install. + // Not loaded yet, or gone (disabled, failed, blocked, restarting): nothing can check or install. showToast({ title: ctx.t("common.requestFailed") }) } diff --git a/packages/gui-extensions/src/wsl/main.ts b/packages/gui-extensions/src/wsl/main.ts index 6bcbc5f5dea..484bd6249c0 100644 --- a/packages/gui-extensions/src/wsl/main.ts +++ b/packages/gui-extensions/src/wsl/main.ts @@ -44,7 +44,7 @@ const setup: MainSetup = (ctx) => { return [{ id: Option.isSome(id) ? id.value.id : wslServerIdForDistro(distro), distro }] }), - writeServers: (servers) => saved.update(() => ({ servers })), + writeServers: (servers) => saved.set({ servers }), installCli: local ? async (distro) => { const { buildLocalWslCli } = await import("./local") diff --git a/packages/session-ui/src/components/session-review.tsx b/packages/session-ui/src/components/session-review.tsx index 95906712609..7fe0234ff9c 100644 --- a/packages/session-ui/src/components/session-review.tsx +++ b/packages/session-ui/src/components/session-review.tsx @@ -15,6 +15,7 @@ import { getDirectory, getFilename } from "@opencode/util/path" import { checksum } from "@opencode/util/encode" import { createEffect, createMemo, For, Match, onCleanup, Show, Switch, untrack, type JSX } from "solid-js" import { createStore } from "solid-js/store" +import { Predicate } from "effect" import type { FileDiffInfo } from "@opencode/client/promise" import type { PresentationFileContent, PresentationFileDiff } from "../file-presentation" import { PreloadMultiFileDiffResult } from "@pierre/diffs/ssr" @@ -27,6 +28,7 @@ import type { LineCommentEditorProps } from "./line-comment" import { normalize, text, type ViewDiff } from "./session-diff" const MAX_DIFF_CHANGED_LINES = 500 + const REVIEW_MOUNT_MARGIN = 300 export type SessionReviewDiffStyle = "unified" | "split" @@ -66,30 +68,11 @@ export type SessionReviewFocus = { file: string; id: string } type RawReviewDiff = (PresentationFileDiff | FileDiffInfo) & { preloaded?: PreloadMultiFileDiffResult } + type ReviewDiff = ((PresentationFileDiff & { file: string }) | FileDiffInfo) & { preloaded?: PreloadMultiFileDiffResult } -function diff(value: unknown): value is ReviewDiff { - if (!value || typeof value !== "object" || Array.isArray(value)) return false - if (!("file" in value) || typeof value.file !== "string") return false - if (!("additions" in value) || typeof value.additions !== "number") return false - if (!("deletions" in value) || typeof value.deletions !== "number") return false - if ("patch" in value && value.patch !== undefined && typeof value.patch !== "string") return false - if ("before" in value && value.before !== undefined && typeof value.before !== "string") return false - if ("after" in value && value.after !== undefined && typeof value.after !== "string") return false - if (!("status" in value) || value.status === undefined) return true - return value.status === "added" || value.status === "deleted" || value.status === "modified" -} - -function list(value: unknown): ReviewDiff[] { - if (Array.isArray(value) && value.every(diff)) return value - if (Array.isArray(value)) return value.filter(diff) - if (diff(value)) return [value] - if (!value || typeof value !== "object") return [] - return Object.values(value).filter(diff) -} - export interface SessionReviewProps { title?: JSX.Element empty?: JSX.Element @@ -108,7 +91,7 @@ export interface SessionReviewProps { focusedComment?: SessionReviewFocus | null onFocusedCommentChange?: (focus: SessionReviewFocus | null) => void focusedFile?: string - open?: string[] + open?: readonly string[] onOpenChange?: (open: string[]) => void scrollRef?: (el: HTMLDivElement) => void onScroll?: JSX.EventHandlerUnion @@ -151,7 +134,9 @@ function ReviewCommentMenu(props: { function diffId(file: string): string | undefined { const sum = checksum(file) + if (!sum) return + return `session-review-diff-${sum}` } @@ -168,40 +153,62 @@ export const SessionReview = (props: SessionReviewProps) => { const fileComponent = useFileComponent() const anchors = new Map() const nodes = new Map() - const [store, setStore] = createStore({ - open: [] as string[], - visible: {} as Record, - force: {} as Record, - selection: null as SessionReviewSelection | null, - commenting: null as SessionReviewSelection | null, - opened: null as SessionReviewFocus | null, + + const [store, setStore] = createStore<{ + open: string[] + visible: Record + force: Record + selection: SessionReviewSelection | null + commenting: SessionReviewSelection | null + opened: SessionReviewFocus | null + }>({ + open: [], + visible: {}, + force: {}, + selection: null, + commenting: null, + opened: null, }) + const selection = () => store.selection const commenting = () => store.commenting const opened = () => store.opened const open = () => props.open ?? store.open + const itemsMap = createMemo(() => - Object.fromEntries(list(props.diffs).map((diff) => [diff.file, { ...normalize(diff), preloaded: diff.preloaded }])), + Object.fromEntries( + props.diffs + .filter((diff): diff is ReviewDiff => diff.file !== undefined) + .map((diff) => [diff.file, { ...normalize(diff), preloaded: diff.preloaded }]), + ), ) + const files = createMemo(() => props.diffs.map((diff) => diff.file!)) + const grouped = createMemo(() => { const next = new Map() + for (const comment of props.comments ?? []) { const list = next.get(comment.file) + if (list) { list.push(comment) continue } + next.set(comment.file, [comment]) } + return next }) + const diffStyle = () => props.diffStyle ?? (props.split ? "split" : "unified") const hasDiffs = () => files().length > 0 const syncVisible = () => { frame = undefined + if (!scroll) return const root = scroll.getBoundingClientRect() @@ -213,6 +220,7 @@ export const SessionReview = (props: SessionReviewProps) => { for (const [file, el] of nodes) { if (!openSet.has(file)) continue const rect = el.getBoundingClientRect() + if (rect.bottom < top || rect.top > bottom) continue next[file] = true } @@ -220,6 +228,7 @@ export const SessionReview = (props: SessionReviewProps) => { const prev = untrack(() => store.visible) const prevKeys = Object.keys(prev) const nextKeys = Object.keys(next) + if (prevKeys.length === nextKeys.length && nextKeys.every((file) => prev[file])) return setStore("visible", next) } @@ -239,13 +248,12 @@ export const SessionReview = (props: SessionReviewProps) => { const handleScroll: JSX.EventHandler = (event) => { queue() const next = props.onScroll + if (!next) return - if (Array.isArray(next)) { - const [fn, data] = next as [(data: unknown, event: Event) => void, unknown] - fn(data, event) - return - } - ;(next as JSX.EventHandler)(event) + + if (Predicate.isFunction(next)) return next(event) + + next[0](next[1], event) } onCleanup(() => { @@ -261,6 +269,7 @@ export const SessionReview = (props: SessionReviewProps) => { const handleChange = (next: string[]) => { props.onOpenChange?.(next) + if (props.open === undefined) setStore("open", next) queue() } @@ -277,6 +286,7 @@ export const SessionReview = (props: SessionReviewProps) => { const selectionPreview = (diff: ViewDiff, range: SelectedLineRange) => { const side = selectionSide(range) const contents = text(diff, side) + if (contents.length === 0) return undefined return previewSelectedLines(contents, range) @@ -284,6 +294,7 @@ export const SessionReview = (props: SessionReviewProps) => { createEffect(() => { const focus = props.focusedComment + if (!focus) return untrack(() => { @@ -293,9 +304,11 @@ export const SessionReview = (props: SessionReviewProps) => { setStore("opened", focus) const comment = (props.comments ?? []).find((c) => c.file === focus.file && c.id === focus.id) + if (comment) setStore("selection", { file: comment.file, range: cloneSelectedLineRange(comment.selection) }) const current = open() + if (!current.includes(focus.file)) { handleChange([...current, focus.file]) } @@ -304,17 +317,21 @@ export const SessionReview = (props: SessionReviewProps) => { if (token !== focusToken) return const root = scroll + if (!root) return const wrapper = anchors.get(focus.file) const anchor = wrapper?.querySelector(`[data-comment-id="${focus.id}"]`) + const ready = anchor instanceof HTMLElement && anchor.style.pointerEvents !== "none" && anchor.style.opacity !== "0" const target = ready ? anchor : wrapper + if (!target) { if (attempt >= 120) return requestAnimationFrame(() => scrollTo(attempt + 1)) + return } @@ -325,6 +342,7 @@ export const SessionReview = (props: SessionReviewProps) => { root.scrollTop = Math.max(0, next) if (ready) return + if (attempt >= 120) return requestAnimationFrame(() => scrollTo(attempt + 1)) } @@ -419,25 +437,33 @@ export const SessionReview = (props: SessionReviewProps) => { const tooLarge = createMemo(() => { if (!expanded()) return false + if (force()) return false + if (mediaKind()) return false + return changedLines() > MAX_DIFF_CHANGED_LINES }) const isAdded = () => diff().status === "added" || (beforeText().length === 0 && afterText().length > 0) + const isDeleted = () => diff().status === "deleted" || (afterText().length === 0 && beforeText().length > 0) const selectedLines = createMemo(() => { const current = selection() + if (!current || current.file !== file) return null + return current.range }) const draftRange = createMemo(() => { const current = commenting() + if (!current || current.file !== file) return null + return current.range }) @@ -449,7 +475,9 @@ export const SessionReview = (props: SessionReviewProps) => { state: { opened: () => { const current = opened() + if (!current || current.file !== file) return null + return current.id }, setOpened: (id) => setStore("opened", id ? { file, id } : null), diff --git a/packages/ui/package.json b/packages/ui/package.json index 6a780d6dd72..af19b302660 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -46,6 +46,7 @@ "./field": "./src/forms/field/field.tsx", "./file-tree.css": "./src/styles/file-tree.css", "./icon": "./src/icons/icon/icon.tsx", + "./icons/catalog": "./src/icons/catalog.ts", "./icon-button": "./src/actions/icon-button/icon-button.tsx", "./inline-input": "./src/forms/inline-input/inline-input.tsx", "./keybind": "./src/data-display/keybind/keybind.tsx", diff --git a/packages/ui/src/data-display/accordion/accordion.tsx b/packages/ui/src/data-display/accordion/accordion.tsx index 7c32d9d7f4c..44fbb577dd3 100644 --- a/packages/ui/src/data-display/accordion/accordion.tsx +++ b/packages/ui/src/data-display/accordion/accordion.tsx @@ -2,17 +2,27 @@ import { Content, Header, Item, Root, Trigger } from "@kobalte/core/accordion" import { splitProps } from "solid-js" import type { ComponentProps, ParentProps } from "solid-js" -export interface AccordionProps extends ComponentProps {} +export interface AccordionProps extends Omit, "value"> { + /** Controlled expanded items. Kobalte reads this iterable into its own selection; it never mutates this array. */ + value?: readonly string[] +} + export interface AccordionItemProps extends ComponentProps {} + export interface AccordionHeaderProps extends ComponentProps {} + export interface AccordionTriggerProps extends ComponentProps {} + export interface AccordionContentProps extends ComponentProps {} function AccordionRoot(props: AccordionProps) { - const [split, rest] = splitProps(props, ["class", "classList"]) + const [split, rest] = splitProps(props, ["class", "classList", "value"]) + + // SAFETY: Kobalte's createMultipleSelectionState copies selectedKeys into a Selection before changing it. return ( ) { const [split, rest] = splitProps(props, ["class", "classList", "children"]) + return (

) { function AccordionTrigger(props: ParentProps) { const [split, rest] = splitProps(props, ["class", "classList", "children"]) + return ( ) { function AccordionContent(props: ParentProps) { const [split, rest] = splitProps(props, ["class", "classList", "children"]) + return ( `, + }, + globe: { + viewBox: "0 0 16 16", + body: ``, + }, + "select-element": { + viewBox: "0 0 16 16", + body: ``, + }, + flask: { + viewBox: "0 0 16 16", + body: ``, + }, + edit: { + viewBox: "0 0 16 16", + body: ``, + }, + "folder-add-left": { + viewBox: "0 0 16 16", + body: ``, + }, + folder: { + viewBox: "0 0 16 16", + body: ``, + }, + branch: { + viewBox: "0 0 16 16", + body: ``, + }, + "branch-out": { + viewBox: "0 0 16 16", + body: ``, + }, + "grid-plus": { + viewBox: "0 0 16 16", + body: ``, + }, + help: { + viewBox: "0 0 16 16", + body: ``, + }, + info: { + viewBox: "0 0 16 16", + body: ``, + }, + "circle-exclamation": { + viewBox: "0 0 16 16", + body: ``, + }, + "circle-xmark": { + viewBox: "0 0 16 16", + body: ``, + }, + "sidebar-right": { + viewBox: "0 0 20 20", + body: ``, + }, + status: { + viewBox: "0 0 20 20", + body: ``, + }, + "status-active": { + viewBox: "0 0 20 20", + body: ``, + }, + "magnifying-glass": { + viewBox: "0 0 16 16", + body: ``, + }, + menu: { + viewBox: "0 0 16 16", + body: ``, + }, + plus: { + viewBox: "0 0 16 16", + body: ``, + }, + "settings-gear": { + viewBox: "0 0 16 16", + body: ``, + }, + "chevron-down": { + viewBox: "0 0 16 16", + body: ``, + }, + collapse: { + viewBox: "0 0 16 16", + body: ``, + }, + check: { + viewBox: "0 0 16 16", + body: ``, + }, + monitor: { + viewBox: "0 0 16 16", + body: ``, + }, + "workspace-new": { + viewBox: "0 0 16 16", + body: ``, + }, + "workspace-isolated": { + viewBox: "0 0 16 16", + body: ``, + }, + workspace: { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-worktree": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-trash": { + viewBox: "0 0 16 16", + body: ``, + }, + close: { + viewBox: "0 0 20 20", + body: ``, + }, + "xmark-small": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-xmark": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-chevron-down": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-dots": { + viewBox: "0 0 16 16", + body: ``, + }, + expand: { + viewBox: "0 0 16 16", + body: ``, + }, + filetree: { + viewBox: "0 0 16 16", + body: ``, + }, + split: { + viewBox: "0 0 16 16", + body: ``, + }, + unified: { + viewBox: "0 0 16 16", + body: ``, + }, + review: { + viewBox: "0 0 20 20", + body: ``, + }, + "window-analytics": { + viewBox: "0 0 16 16", + body: ``, + }, + "graduation-cap": { + viewBox: "0 0 16 16", + body: ``, + }, + "code-slash": { + viewBox: "0 0 16 16", + body: ``, + }, + trash: { + viewBox: "0 0 20 20", + body: ``, + }, + "outline-sliders": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-copy": { + viewBox: "0 0 16 16", + body: ``, + }, + "arrow-up-right": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-square-arrow": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-arrow-to-corner-top-right": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-hexagonal-warning": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-share": { + viewBox: "0 0 16 16", + body: ``, + }, + "outline-eye": { + viewBox: "0 0 20 20", + body: ``, + }, + "outline-eye-slash": { + viewBox: "0 0 20 20", + body: ``, + }, + refresh: { + viewBox: "0 0 20 20", + body: ``, + }, + reset: { + viewBox: "0 0 20 20", + body: ``, + }, + "outline-reset": { + viewBox: "0 0 20 20", + body: ``, + }, + "fill-triangle-down": { + viewBox: "0 0 16 16", + body: ``, + }, + archive: { + viewBox: "0 0 16 16", + body: ``, + }, +} + +/** Icon names derived from the shared artwork, with no UI or runtime dependencies. */ +export type IconName = keyof typeof icons | keyof typeof additionalIcons + +/** The artwork catalog's names, in sprite order. */ +export function iconNames() { + // SAFETY: every key comes from one of the two artwork records that define IconName. + return Array.from(new Set([...Object.keys(additionalIcons), ...Object.keys(icons)])) as IconName[] +} + +/** + * Narrows a name against the shared artwork catalog. + * @param name - A name supplied by a caller, including names unknown to this build. + */ +export function isIconName(name: string): name is IconName { + return Object.hasOwn(icons, name) || Object.hasOwn(additionalIcons, name) +} + +/** + * The SVG body and viewport for a known catalog name, with primary artwork taking precedence. + * @param name - A name validated by the type or by `isIconName`. + */ +export function getIcon(name: IconName) { + // SAFETY: IconName is the union of both catalogs' keys; an absent primary entry falls back to additional artwork. + const icon = icons[name as keyof typeof icons] + + if (icon) return icon + // SAFETY: the primary lookup ruled out its entries, so the remaining name belongs to additionalIcons. + const key = name as keyof typeof additionalIcons + + return { body: additionalIcons[key], viewBox: additionalIconViewBox(key) } +} diff --git a/packages/ui/src/icons/icon/additional-icons.ts b/packages/ui/src/icons/icon/additional-icons.ts index 1391ac64420..edcbf5442bb 100644 --- a/packages/ui/src/icons/icon/additional-icons.ts +++ b/packages/ui/src/icons/icon/additional-icons.ts @@ -1,3 +1,4 @@ +/** Additional UI artwork, independent of a renderer. */ export const additionalIcons = { "align-right": ``, "arrow-up": ``, diff --git a/packages/ui/src/icons/icon/icon.tsx b/packages/ui/src/icons/icon/icon.tsx index 9b7d6ad44d1..1a4f265f9a7 100644 --- a/packages/ui/src/icons/icon/icon.tsx +++ b/packages/ui/src/icons/icon/icon.tsx @@ -1,270 +1,30 @@ import { onMount, type ComponentProps, splitProps } from "solid-js" -import { additionalIcons, additionalIconViewBox } from "./additional-icons" +import { iconNames, isIconName, getIcon, type IconName } from "../catalog" import "./icon.css" -// Consumers center the SVG viewport, so each icon must center its artwork within its viewBox. -const icons = { - lock: { - viewBox: "0 0 16 16", - body: ``, - }, - globe: { - viewBox: "0 0 16 16", - body: ``, - }, - "select-element": { - viewBox: "0 0 16 16", - body: ``, - }, - flask: { - viewBox: "0 0 16 16", - body: ``, - }, - edit: { - viewBox: "0 0 16 16", - body: ``, - }, - "folder-add-left": { - viewBox: "0 0 16 16", - body: ``, - }, - folder: { - viewBox: "0 0 16 16", - body: ``, - }, - branch: { - viewBox: "0 0 16 16", - body: ``, - }, - "branch-out": { - viewBox: "0 0 16 16", - body: ``, - }, - "grid-plus": { - viewBox: "0 0 16 16", - body: ``, - }, - help: { - viewBox: "0 0 16 16", - body: ``, - }, - info: { - viewBox: "0 0 16 16", - body: ``, - }, - "circle-exclamation": { - viewBox: "0 0 16 16", - body: ``, - }, - "circle-xmark": { - viewBox: "0 0 16 16", - body: ``, - }, - "sidebar-right": { - viewBox: "0 0 20 20", - body: ``, - }, - status: { - viewBox: "0 0 20 20", - body: ``, - }, - "status-active": { - viewBox: "0 0 20 20", - body: ``, - }, - "magnifying-glass": { - viewBox: "0 0 16 16", - body: ``, - }, - menu: { - viewBox: "0 0 16 16", - body: ``, - }, - plus: { - viewBox: "0 0 16 16", - body: ``, - }, - "settings-gear": { - viewBox: "0 0 16 16", - body: ``, - }, - "chevron-down": { - viewBox: "0 0 16 16", - body: ``, - }, - collapse: { - viewBox: "0 0 16 16", - body: ``, - }, - check: { - viewBox: "0 0 16 16", - body: ``, - }, - monitor: { - viewBox: "0 0 16 16", - body: ``, - }, - "workspace-new": { - viewBox: "0 0 16 16", - body: ``, - }, - "workspace-isolated": { - viewBox: "0 0 16 16", - body: ``, - }, - workspace: { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-worktree": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-trash": { - viewBox: "0 0 16 16", - body: ``, - }, - close: { - viewBox: "0 0 20 20", - body: ``, - }, - "xmark-small": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-xmark": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-chevron-down": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-dots": { - viewBox: "0 0 16 16", - body: ``, - }, - expand: { - viewBox: "0 0 16 16", - body: ``, - }, - filetree: { - viewBox: "0 0 16 16", - body: ``, - }, - split: { - viewBox: "0 0 16 16", - body: ``, - }, - unified: { - viewBox: "0 0 16 16", - body: ``, - }, - review: { - viewBox: "0 0 20 20", - body: ``, - }, - "window-analytics": { - viewBox: "0 0 16 16", - body: ``, - }, - "graduation-cap": { - viewBox: "0 0 16 16", - body: ``, - }, - "code-slash": { - viewBox: "0 0 16 16", - body: ``, - }, - trash: { - viewBox: "0 0 20 20", - body: ``, - }, - "outline-sliders": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-copy": { - viewBox: "0 0 16 16", - body: ``, - }, - "arrow-up-right": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-square-arrow": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-arrow-to-corner-top-right": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-hexagonal-warning": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-share": { - viewBox: "0 0 16 16", - body: ``, - }, - "outline-eye": { - viewBox: "0 0 20 20", - body: ``, - }, - "outline-eye-slash": { - viewBox: "0 0 20 20", - body: ``, - }, - refresh: { - viewBox: "0 0 20 20", - body: ``, - }, - reset: { - viewBox: "0 0 20 20", - body: ``, - }, - "outline-reset": { - viewBox: "0 0 20 20", - body: ``, - }, - "fill-triangle-down": { - viewBox: "0 0 16 16", - body: ``, - }, - archive: { - viewBox: "0 0 16 16", - body: ``, - }, -} - -type IconName = keyof typeof icons | keyof typeof additionalIcons - const spriteID = "opencode-v2-icon-sprite" + const symbol = (name: IconName) => `opencode-v2-icon-${name}` + let spriteInserted = false -function getIcon(name: IconName) { - const icon = icons[name as keyof typeof icons] - if (icon) return icon - const body = additionalIcons[name as keyof typeof additionalIcons] - return { body, viewBox: additionalIconViewBox(name as keyof typeof additionalIcons) } -} - function spriteContent() { - return Array.from(new Set([...Object.keys(additionalIcons), ...Object.keys(icons)] as IconName[])) + return iconNames() .map((name) => `${getIcon(name).body}`) .join("") } function ensureSprite() { if (spriteInserted) return + if (typeof document === "undefined") return // Hot reload preserves the DOM sprite, but its symbols may be from an older module. const existing = document.getElementById(spriteID) + if (existing) { existing.innerHTML = spriteContent() spriteInserted = true + return } @@ -287,11 +47,11 @@ export interface IconProps extends ComponentProps<"svg"> { export function Icon(props: IconProps) { const [split, rest] = splitProps(props, ["name", "size"]) + const iconName = (): IconName => { - if (icons[split.name as keyof typeof icons]) return split.name as keyof typeof icons - if (additionalIcons[split.name as keyof typeof additionalIcons]) return split.name as keyof typeof additionalIcons - return "plus" + return isIconName(split.name) ? split.name : "plus" } + const icon = () => getIcon(iconName()) const pixelSize = split.size === "small" ? 14 : split.size === "large" ? 20 : 16 onMount(ensureSprite)