refactor(gui-extensions): tighten the SDK surface (#53078)

This commit is contained in:
Luke Parker 2026-10-04 16:59:43 +10:00 • committed by GitHub
parent 453dd2ad01
commit 5589ca43f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 1736 additions and 823 deletions

View file

@ -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<typeof createHostApis> }
/** 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<Record<string, Json>>
/** Shows the production developer settings page for status-label contracts. */
settings?: boolean
}) {
const held = Promise.withResolvers<void>()
const [disabled, setDisabled] = createSignal<ReadonlySet<string>>(new Set(input.disabled ?? []))
@ -248,6 +260,9 @@ export function mountExtensions(input: {
return (
<Show when={host.ready()}>
<Show when={input.settings}>
<GuiExtensionsSettings />
</Show>
<ExtensionSlot at="window.bottom" input={{}} />
</Show>
)
@ -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,
}}
/>
<RegionContent
region={region}
view={view()}
screen={screen}
frame={{
shown: () => true,
present: () => true,
@ -429,7 +445,7 @@ export function mountSessionRegion(input: { definitions: readonly Definition[];
<RealHost
definitions={input.definitions}
captured={captured}
mounted={standIn({ current: view, screen: () => screen })}
mounted={standIn({ current: () => (routed() ? view() : undefined), screen: () => screen })}
>
<Region />
</RealHost>
@ -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],

View file

@ -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<void>()
const resume = Promise.withResolvers<void>()
const done = Promise.withResolvers<void>()
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<Record<keyof typeof mounts, { readonly session: { readonly id: string } }>> = {}
const inputs: Partial<
Record<keyof typeof mounts, { readonly session: { readonly id: string }; readonly screen: SessionScreen }>
> = {}
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<number, "root.value"> = Contract.define("root.value")
const Branch: Contract<number, "branch.value"> = Contract.define("branch.value")
const observed = { read: (): Live<number> => ({ 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<number> } }) => {
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<void>()
const done = Promise.withResolvers<void>()
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" },
})
})
})

View file

@ -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)

View file

@ -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<keyof HostApis, "links" | "dialogs">]: HostApiFactory<HostApis[K]>
}
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<string, Absent>
@ -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<D>` of this definition.
const setup = module.default as (ctx: InstanceContext) => void | Promise<void>
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<T>(point: Point<T>, 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<Messages> {
const english = catalog?.en ?? {}

View file

@ -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<Reply>()

View file

@ -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<IpcSpec["state"]>
@ -112,15 +112,16 @@ export function createIpcClients(bridge: Bridge | undefined) {
const create = (connected: Bridge, token: Ipc): IpcClient<IpcSpec> => {
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, {

View file

@ -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: {
<MobilePanel
entry={entry}
view={props.session}
screen={props.screen}
sidebar={props.sidebar}
visible={store.drawer === entry.key}
open={() => props.region.openFor(entry.extension)}

View file

@ -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<readonly BackgroundTask[]>) => setBackground(() => tasks) }
return {
screen,
view: mounted,
bindBackground: (tasks: Accessor<readonly BackgroundTask[]>) => setBackground(() => tasks),
}
}

View file

@ -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<MountedSession>; tabs: Tabs }) {
export function createRegion(input: {
region: Panel["region"]
view: Accessor<MountedSession>
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<Mo
const prefix = `${item.extension}:`
const open = stored().flatMap((key) => (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<Mo
if (!item?.value.normalize) return key
return panelKey(item.extension, item.value.normalize(key.slice(item.extension.length + 1), input.view()))
return panelKey(
item.extension,
item.value.normalize(
panelInput(input.view, input.screen, {
id: key.slice(item.extension.length + 1),
}),
),
)
}
// remap reads the stored tabs and writes nothing once every key is canonical, so this settles in one rerun.
@ -164,12 +188,13 @@ export function createRegion(input: { region: Panel["region"]; view: Accessor<Mo
if (value && strip().some((entry) => entry.key === value && (desktop() || !entry.tab.transient))) return value
return strip()
.filter((entry) => entry.tab.fallback !== undefined)
.reduce<RegionEntry | undefined>(
(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<Mo
on(active, (key, _, restored: boolean = true) => {
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<Mo
const entry = byKey().get(key)
input.tabs().close(key)
if (entry) entry.provider.close?.(entry.tab, input.view())
if (entry)
entry.provider.close?.(
panelInput(input.view, input.screen, {
tab: entry.tab,
}),
)
},
}
}
@ -220,6 +256,7 @@ export type Region = ReturnType<typeof createRegion>
export function RegionContent(props: {
region: Region
view: MountedSession
screen: SessionScreen
frame: Omit<PanelFrame, "visible" | "open"> & { shown: Accessor<boolean> }
}) {
const groups = createMemo(() =>
@ -273,14 +310,13 @@ export function RegionContent(props: {
>
<Contribution extension={extension}>
{() =>
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
},
}),
)
}
</Contribution>
</PanelContext.Provider>
@ -310,14 +346,13 @@ export function RegionContent(props: {
>
<Contribution extension={extension}>
{() =>
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
},
}),
)
}
</Contribution>
</PanelContext.Provider>
@ -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<T extends object>(view: Accessor<MountedSession>, 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: {
>
<Contribution extension={extension}>
{() =>
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
},
}),
)
}
</Contribution>
</PanelContext.Provider>
@ -497,6 +545,7 @@ export function DockRegion(props: {
export function MobilePanel(props: {
entry: RegionEntry
view: MountedSession
screen: SessionScreen
sidebar: PanelSidebar
visible: boolean
open: Accessor<readonly string[]>
@ -515,14 +564,13 @@ export function MobilePanel(props: {
>
<Contribution extension={props.entry.extension}>
{() =>
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
},
}),
)
}
</Contribution>
</PanelContext.Provider>

View file

@ -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")
}

View file

@ -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
},
}}
/>
<Show when={tabsVisible()}>
@ -229,6 +234,7 @@ export function SideRegion(props: {
<RegionContent
region={props.region}
view={props.view}
screen={props.screen}
frame={{
shown: tabsOpen,
present: tabsVisible,
@ -264,6 +270,9 @@ export function SideRegion(props: {
get session() {
return props.view
},
get screen() {
return props.screen
},
}}
/>
</div>

View file

@ -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<T> = Parameters<Persisted<T>["update"]>[0]
/** One older key persistence imports a store's value from. */
type CopyFrom = NonNullable<Exclude<Parameters<typeof persisted>[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<T extends object>(input: {
readonly store: T
@ -75,42 +72,45 @@ export function persistedHandle<T extends object>(input: {
readonly init: Promise<unknown> | undefined
}) {
const [loaded, setLoaded] = createSignal(!input.init)
const queue: Mutation<T>[] = []
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<T>) =>
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<T> = {
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<T>)
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<T>(handle: Persisted<T>) {
* changes made before then wait and apply in order. Call it inside an owner, which ends the hand-over.
*/
export function deferredHandle<T>(store: Accessor<Persisted<T> | undefined>): Persisted<T> {
const queue: Mutation<T>[] = []
const queue: ((current: Persisted<T>) => 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<T>(store: Accessor<Persisted<T> | 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))
},
}
}

View file

@ -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",

View file

@ -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 (
<SessionStatePanel>
<DataProvider
@ -93,6 +94,7 @@ function PreparingSession(props: { sessionID: string; pending: PendingSession })
function TargetSessionSettingsCommand() {
useSettingsCommand()
return null
}
@ -115,11 +117,13 @@ function ResolvedTargetSessionRoute() {
const server = useServer()
const tabs = useTabs()
const data = useData()
const current = createSessionResolution(
() => 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 <SessionScreen session={session} />
return <SessionScreenView session={session} />
}
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
}

View file

@ -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 (
<ExtensionLinks session={mounted.view()}>
<SessionScreenContent session={props.session} view={mounted.view} bindBackground={mounted.bindBackground} />
<SessionScreenContent
session={props.session}
screen={mounted.screen}
view={mounted.view}
bindBackground={mounted.bindBackground}
/>
</ExtensionLinks>
)
}
@ -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<MountedSession>
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: {
<Show when={session.identity.sessionKey()} keyed>
{(_key) => (
<MobileViewTabs
screen={props.screen}
views={mobile}
region={region}
current={mobileView()}
@ -288,7 +303,15 @@ function SessionScreenContent(props: {
<div class="relative flex-1 min-h-0 overflow-hidden">
<Show when={!isDesktop() && store.mobileDockCached}>
<div class="absolute inset-0" classList={{ invisible: mobileView() !== dockView()?.key }}>
<DockRegion view={props.view()} sidebar={sidebar} fill embedded present contentHeight="100%" />
<DockRegion
view={props.view()}
screen={props.screen}
sidebar={sidebar}
fill
embedded
present
contentHeight="100%"
/>
</div>
</Show>
<Switch>
@ -298,6 +321,7 @@ function SessionScreenContent(props: {
<Match when={!isDesktop() && session.identity.params.id ? mobileEntry() : undefined}>
{(entry) => (
<MobilePanel
screen={props.screen}
entry={entry()}
view={props.view()}
sidebar={sidebar}
@ -428,6 +452,7 @@ function SessionScreenContent(props: {
}}
>
<SideRegion
screen={props.screen}
view={props.view()}
region={region}
sidebar={sidebar}
@ -484,6 +509,7 @@ function SessionScreenContent(props: {
>
<div data-slot="side-terminal-panel-clip" class="size-full overflow-clip rounded-[10px]">
<DockRegion
screen={props.screen}
view={props.view()}
sidebar={sidebar}
fill
@ -531,6 +557,7 @@ function SessionScreenContent(props: {
</div>
</Show>
<DockRegion
screen={props.screen}
view={props.view()}
sidebar={sidebar}
stacked={isDesktop()}

View file

@ -10,7 +10,7 @@ import { InlineInput } from "@opencode/ui/inline-input"
import { Keybind } from "@opencode/ui/keybind"
import { Menu } from "@opencode/ui/menu"
import { TextShimmer } from "@opencode/ui/text-shimmer"
import type { BackgroundTask, MountedSession } from "@opencode/gui-extensions/sdk"
import type { BackgroundTask, MountedSession, SessionScreen } from "@opencode/gui-extensions/sdk"
import { ExtensionSlot } from "@/runtime/extension/render"
import { useLanguage } from "@/runtime/i18n/language"
import { useServer } from "@/runtime/server/current"
@ -60,6 +60,7 @@ type MessageTimelineProps = {
active?: boolean
session: TimelineSessionSource
view: MountedSession
screen: SessionScreen
background: SessionBackground
actions?: SessionUserActions
scroll: { overflow: boolean; jump: boolean }
@ -554,6 +555,9 @@ function MessageTimelineView(
get session() {
return props.view
},
get screen() {
return props.screen
},
get active() {
return props.active !== false
},

View file

@ -25,10 +25,10 @@ const first = { status: "active", value: "first", generation: 1 } as const
const second = { status: "active", value: "second", generation: 2 } as const
const Items = Schema.Struct({ items: Schema.mutable(Schema.Array(Schema.String)) })
const Items = Schema.Struct({ items: Schema.Array(Schema.String) })
const Noted = Schema.Struct({
items: Schema.mutable(Schema.Array(Schema.String)),
items: Schema.Array(Schema.String),
note: Schema.optional(Schema.String),
})
@ -251,6 +251,7 @@ describe("extension primitives", () => {
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<void>()
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,

View file

@ -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) {

View file

@ -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<typeof open>) => opened.store.update(() => ["a"]), expected: ["a"] },
{
name: "update",
write: (opened: ReturnType<typeof open>) =>
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<typeof open>) => {
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<typeof open>) => {
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<typeof open>) => {
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<typeof open>) =>
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<typeof open>) => {
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 }>([

View file

@ -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<typeof options.initial>)
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),

View file

@ -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.<key>` 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<typeof Token>("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<typeof definition>()` 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<typeof definition>`), 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.<id>.<key>`). 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.

View file

@ -68,6 +68,11 @@ Setup receives one context. Components read the same object with `useExtension<t
- No host API throws before the app interface mounts: reads return their documented defaults (`ctx.layout.ready()` is false), and writes such as `ctx.layout.open` wait, then apply in call order. A dialog `ctx.dialogs.open` opens meanwhile shows after the interface's first render.
- Points and contracts are tokens: `ctx.add(Command, …)`, `ctx.provide(FileTree, …)`.
- Reading a token you did not declare is a compile error. A key that names one token in `provides` and another in `uses` is one too.
- Bind each contract component with `bindExtension` during the provider's setup so `useExtension` reads the provider's context, not the consumer's. Props retain their getters. Leave data methods such as `Changes.diffs()` unwrapped.
```tsx
ctx.provide(FileTree, { Tree: bindExtension((props) => <Tree {...props} />) })
```
```ts
const setup: Setup<typeof definition> = (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) => <View session={props.session} tab={props.tab} />,
render: (props) => <View session={props.session} screen={props.screen} tab={props.tab} />,
})
// 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<typeof definition>` sees the declarations |
| `Extension.compose(...definitions)` | A process's list; fails to compile on a missing or duplicate provider |
| `Point.define<T>(id)` | A place your extension renders and others contribute to |
| `Contract.define<T, Id>(id)` | An in-process API one extension provides to others |
| `Ipc.define(spec)` / `Ipc.ref<typeof T>(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<typeof definition>` sees the declarations |
| `Extension.compose(...definitions)` | A process's list; rejects repeated extension ids and missing or duplicate providers |
| `Point.define<T>(id)` | A place your extension renders and others contribute to |
| `Contract.define<T, Id>(id)` | An in-process API one extension provides to others |
| `Ipc.define(spec)` / `Ipc.ref<typeof T>(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<string | undefined>(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:
<!-- source: src/pairing/page.tsx#local -->
```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 `<id>.<name>`.
- Define it in `contract.ts`. Its id is your extension id, or `<id>.<name>`. 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<typeof renderer, typeof main>` 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<T>`, 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.<id>.<name>` in the window, the store's name under `extension.<id>` 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<typeof definition> = (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)

View file

@ -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<MountedSession>; tabs: Accessor<StripTabs> }): {
createRegion(input: {
region: "side"
view: Accessor<MountedSession>
screen: SessionScreen
tabs: Accessor<StripTabs>
}): {
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<T>) => 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<T>)
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,

View file

@ -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)),
}
}

View file

@ -13,7 +13,7 @@ export function createRefs(reserved: Persisted<number, number>) {
return () => {
if (state.next >= state.end) {
state.end = state.next + block
reserved.update(() => state.end)
reserved.set(state.end)
}
return `e${++state.next}`

View file

@ -148,19 +148,19 @@ const setup: Setup<typeof definition> = (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<typeof definition> = (ctx) => {
)}
</Show>
),
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),
})
}

View file

@ -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) {

View file

@ -49,7 +49,7 @@ const setup: Setup<typeof Btw> = (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) => (
<Suspense>
<SessionBtwPanel btw={btw} session={props.session} />

View file

@ -18,7 +18,7 @@ const setup: Setup<typeof definition> = (ctx) => {
draggable: false,
closable: "compact",
first: true,
fallback: 2,
fallback: true,
label: (state) => (
<div class="flex items-center gap-2">
<SessionContextUsage session={state.session} variant="indicator" />
@ -41,7 +41,7 @@ const setup: Setup<typeof definition> = (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()

View file

@ -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",

View file

@ -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<DetailsPanelProps>
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")),
),
)

View file

@ -38,7 +38,13 @@ const setup: Setup<typeof Details> = (ctx) => {
at: "session.header",
order: 20,
render: (input) => (
<DetailsHeader session={input.session} active={input.active} panel={DetailsPanel} disclosure={disclosure} />
<DetailsHeader
session={input.session}
screen={input.screen}
active={input.active}
panel={DetailsPanel}
disclosure={disclosure}
/>
),
})
@ -76,7 +82,7 @@ const setup: Setup<typeof Details> = (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 (

View file

@ -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))
})

View file

@ -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

View file

@ -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<string, ChangeKind>

View file

@ -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",

View file

@ -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<typeof File> = (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>("handoff", { initial: { sessions: {} } })
const preference = desktop ? ctx.stores.app : undefined
@ -194,7 +191,7 @@ const setup: Setup<typeof File> = (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<typeof File> = (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<typeof File> = (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 (
<Show when={ctx.screen.current()}>
{(screen) => (
<FileProvider>
<Suspense>
<Show
when={panel.placement() === "mobile"}
fallback={<FileBrowser tab={() => props.tab} session={props.session} screen={screen()} />}
>
<MobileFiles session={props.session} screen={screen()} />
</Show>
</Suspense>
</FileProvider>
)}
</Show>
<FileProvider>
<Suspense>
<Show
when={panel.placement() === "mobile"}
fallback={<FileBrowser tab={() => props.tab} session={props.session} screen={props.screen} />}
>
<MobileFiles session={props.session} screen={props.screen} />
</Show>
</Suspense>
</FileProvider>
)
},
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<typeof File> = (ctx) => {
ctx.add(Slot, {
at: "session.panel.end",
render: (input) => (
<Show when={ctx.screen.current()}>
{(screen) => (
<FileProvider>
<Suspense>
<OpenInAppButton session={input.session} screen={screen()} />
</Suspense>
</FileProvider>
)}
</Show>
<FileProvider>
<Suspense>
<OpenInAppButton session={input.session} screen={input.screen} />
</Suspense>
</FileProvider>
),
})
}
@ -324,63 +305,47 @@ const setup: Setup<typeof File> = (ctx) => {
ctx.add(Slot, {
at: "session.panel.sidebar",
render: (input) => (
<Show when={ctx.screen.current()}>
{(screen) => (
<FileProvider>
<Suspense>
<Sidebar session={input.session} screen={screen()} />
</Suspense>
</FileProvider>
)}
</Show>
<FileProvider>
<Suspense>
<Sidebar session={input.session} screen={input.screen} />
</Suspense>
</FileProvider>
),
})
// 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) => (
<ExtensionContext.Provider value={context}>
<Show when={ctx.screen.current()}>
{(screen) => (
<FileProvider>
<Suspense>
<Tree
session={props.session}
screen={screen()}
allowed={props.allowed}
kinds={props.kinds}
draggable={false}
active={props.active}
onFileClick={(node) => props.onFileClick(node.path)}
/>
</Suspense>
</FileProvider>
)}
</Show>
</ExtensionContext.Provider>
),
List: (props) => (
<ExtensionContext.Provider value={context}>
<Show when={ctx.screen.current()}>
{(screen) => (
<FileProvider>
<Suspense>
<List
session={props.session}
screen={screen()}
files={props.files}
kinds={props.kinds}
active={props.active}
highlighted={props.highlighted}
onFileClick={(path) => props.onFileClick(path)}
/>
</Suspense>
</FileProvider>
)}
</Show>
</ExtensionContext.Provider>
),
Tree: bindExtension((props) => (
<FileProvider>
<Suspense>
<Tree
session={props.session}
screen={props.screen}
allowed={props.allowed}
kinds={props.kinds}
draggable={false}
active={props.active}
onFileClick={(node) => props.onFileClick(node.path)}
/>
</Suspense>
</FileProvider>
)),
List: bindExtension((props) => (
<FileProvider>
<Suspense>
<List
session={props.session}
screen={props.screen}
files={props.files}
kinds={props.kinds}
active={props.active}
highlighted={props.highlighted}
onFileClick={(path) => props.onFileClick(path)}
/>
</Suspense>
</FileProvider>
)),
})
/**
@ -461,9 +426,7 @@ const setup: Setup<typeof File> = (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<string | undefined>(
(previous) => (sessions.current() ? ctx.screen.current()?.file.root : undefined) ?? previous,
)
const root = createMemo<string | undefined>((previous) => ctx.screen.current()?.file.root ?? previous)
const moved = createMemo(on(root, () => ({}), { defer: true }))

View file

@ -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.

View file

@ -20,7 +20,7 @@ const setup: MainSetup<typeof definition> = (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)

View file

@ -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.

View file

@ -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
}

View file

@ -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",

View file

@ -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.
<ReviewPanelSidebar
screen={props.screen}
session={props.session}
title={props.title}
state={props.state}
@ -243,6 +244,7 @@ function ReviewPanel(props: ReviewPanelProps) {
}
function ReviewPanelSidebar(props: {
screen: SessionScreen
session: MountedSession
title?: JSX.Element
state: ReviewPanelState
@ -315,6 +317,7 @@ function ReviewPanelSidebar(props: {
{(views) => (
<Dynamic
component={views().Tree}
screen={props.screen}
session={props.session}
allowed={props.filteredFiles}
kinds={props.kinds}
@ -333,6 +336,7 @@ function ReviewPanelSidebar(props: {
{(views) => (
<Dynamic
component={views().List}
screen={props.screen}
session={props.session}
files={props.filteredFiles}
kinds={props.kinds}

View file

@ -56,12 +56,8 @@ const setup: Setup<typeof Review> = (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<typeof Review> = (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<typeof Review> = (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<typeof Review> = (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 (
<Show when={entry()?.model} keyed>
<Show when={model()} keyed>
{(model) => {
createKeyed(frame.visible, () => onCleanup(watch(props.session, "panel")))
createKeyed(frame.visible, () => onCleanup(watch(props.screen, "panel")))
return (
<Show
@ -265,7 +267,7 @@ const setup: Setup<typeof Review> = (ctx) => {
if (!layout.side.opened(session)) layout.side.toggle(session)
},
watch: (session, source) => watch(session, source),
watch,
onReveal(listener) {
reveals.add(listener)

View file

@ -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<Composition<[typeof PaneProvider, typeof Consumer]>, { 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<typeof Consumer> = (ctx) => {
// @ts-expect-error a session has no composer: read `ctx.screen.current()?.composer`
void session?.composer
equal<ReturnType<typeof ctx.screen.current>, 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<ReturnType<Setup<typeof Consumer>>, undefined>(true)
// @ts-expect-error an async window setup returns a Promise, not undefined
export const asyncSetup: Setup<typeof Consumer> = async () => {}
// @ts-expect-error a window setup cannot return an object either
export const returningSetup: Setup<typeof Consumer> = () => ({ open: true })
equal<ReturnType<MainSetup<typeof Consumer>>, void | Promise<void>>(true)
equal<PanelProps["screen"], SessionScreen>(true)
equal<Parameters<Panel["list"]>[0]["session"], MountedSession>(true)
equal<Parameters<Panel["list"]>[0]["screen"], SessionScreen>(true)
equal<Parameters<NonNullable<Panel["focus"]>>[0]["restored"], boolean>(true)
equal<Parameters<NonNullable<Panel["normalize"]>>[0]["screen"], SessionScreen>(true)
equal<Parameters<NonNullable<Panel["close"]>>[0], PanelProps>(true)
equal<SlotMap["session.header"]["screen"], SessionScreen>(true)
equal<SlotMap["session.panel.end"]["screen"], SessionScreen>(true)
equal<SlotMap["session.panel.sidebar"]["screen"], SessionScreen>(true)
equal<SlotMap["window.bottom"]["screen"], never>(true)
equal<PanelTab["fallback"], boolean | undefined>(true)
export const ineligible: PanelTab = { id: "details", title: "Details", fallback: false }
equal<Extract<Live<never>, { 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<typeof NoInput.spec>, 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<typeof Nested> = (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<typeof TreeProvider> = (ctx) => {

View file

@ -294,7 +294,12 @@ export interface SetupContext<D> extends Omit<Context, "provide"> {
/**
* A window entry: the default export of `renderer.tsx`. `Setup<typeof Definition>` 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<D> extends Omit<Context, "provide"> {
* export default setup
* ```
*/
export type Setup<D extends Definition> = (ctx: SetupContext<D>) => void | Promise<void>
export type Setup<D extends Definition> = (ctx: SetupContext<D>) => undefined

View file

@ -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<void>
@ -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<typeof Definition>` (`@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> = 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<S extends IpcSpec> = {
readonly [Name in keyof S["methods"]]: (
input: TypeOf<S["methods"][Name]["input"]>,
options?: {
/** Aborts the call: main's `Caller.signal` aborts, and the promise rejects. */
readonly signal?: AbortSignal
},
) => Promise<TypeOf<S["methods"][Name]["output"]>>
readonly [Name in keyof S["methods"]]: S["methods"][Name] extends { readonly input: Codec }
? (
/** The argument decoded by this method's input schema. */
input: TypeOf<S["methods"][Name]["input"]>,
/** Optional per-call cancellation. */
options?: IpcCallOptions,
) => Promise<TypeOf<S["methods"][Name]["output"]>>
: (
/** Optional per-call cancellation; no input placeholder is accepted. */
options?: IpcCallOptions,
) => Promise<TypeOf<S["methods"][Name]["output"]>>
} & {
/**
* 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<S extends IpcSpec> = {
): 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> =
T extends Ipc<infer S>
@ -315,7 +325,8 @@ export type TokenValue<T> =
* - `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<T> =
* 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<T, V = T | undefined> {
@ -690,15 +703,30 @@ export interface Persisted<T, V = T | undefined> {
/** 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<T>,
) => 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> = T extends object ? { -readonly [K in keyof T]: Mutable<T[K]> } : T
/** The tokens a definition declares under `K`; `{}` when it declares none. */
export type Declared<D, K extends "provides" | "uses" | "requires"> = D extends { readonly [P in K]?: infer M }
? M extends Tokens
@ -735,6 +763,12 @@ export interface Duplicate<Id extends string> {
readonly [problem]: Id
}
/** `Extension.compose`'s error: two definitions use the same extension id. */
export interface DuplicateExtension<Id extends string> {
/** 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<Id extends string> {
/** The Ipc's id. */
@ -784,8 +818,21 @@ type DuplicateIds<Ds extends readonly unknown[]> = {
[I in keyof Ds]: Literal<Ids<Ds[I], "provides">> & Ids<Others<Ds, I>, "provides">
}[number]
type ExtensionId<D> = D extends { readonly id: infer Id } ? Literal<Id> : never
type DuplicateExtensions<Ds extends readonly unknown[]> = {
[I in keyof Ds]: ExtensionId<Ds[I]> & ExtensionId<Others<Ds, I>>
}[number]
/** Compile errors for a composition; `unknown` when it is valid. */
export type Composition<Ds extends readonly unknown[]> = [MissingIds<Ds>] extends [never]
export type Composition<Ds extends readonly unknown[]> = [DuplicateExtensions<Ds>] extends [never]
? ProvidersCheck<Ds>
: {
/** Two definitions share this extension id. */
readonly "duplicate extension": DuplicateExtension<DuplicateExtensions<Ds>>
}
type ProvidersCheck<Ds extends readonly unknown[]> = [MissingIds<Ds>] extends [never]
? [DuplicateIds<Ds>] 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.

View file

@ -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
}

View file

@ -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<S extends Schema.ConstraintCodec<unknown, unknown>>(
@ -251,7 +250,7 @@ export interface MainContext<D = never> extends BaseContext {
* @example
* ```ts
* const count = ctx.stores.count
* count.update((value) => value + 1)
* count.set(count.value + 1)
* ```
*/
readonly stores: MainStores<D>
@ -362,7 +361,7 @@ export interface MainContext<D = never> extends BaseContext {
* ```ts
* const setup: MainSetup<typeof definition> = (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
* ```

View file

@ -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<string, never>
/** 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<MenuItem>("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) => <View session={props.session} />,
* })
* ```

View file

@ -141,7 +141,7 @@ export function createKeyed<S extends KeyedSource>(
*
* @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 ?? []
* ```
*/

View file

@ -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<D extends Definition = never>() {
return context as [D] extends [never] ? Context : SetupContext<D>
}
/**
* 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) => <Tree {...props} />) })
* ```
*/
export function bindExtension<P extends object>(component: Component<P>): Component<P> {
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. */

View file

@ -28,7 +28,7 @@ const setup: MainSetup<typeof definition> = 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)),
)

View file

@ -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<typeof importGhostty> }
const workspaceKey = (server: string, directory: string) => `${server}\0${directory}`
const trimTerminal = (pty: LocalPTY) => {
const trimTerminal = (pty: Mutable<LocalPTY>) => {
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) {

View file

@ -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<S extends Schema.ConstraintCodec<unknown, unknown>>(schema: S, value: () => S["Type"]) {
const defaulted = Schema.withDecodingDefaultType<S>(Effect.sync(value))(schema)
return Schema.catchDecoding<typeof defaulted>(() => Effect.sync(() => Option.some(value())))(defaulted)
}
function optional<S extends Schema.ConstraintCodec<unknown, unknown>>(schema: S) {
const field = Schema.optional(schema)
return Schema.catchDecoding<typeof field>(() => Effect.succeed(Option.none()))(field)
}
function struct<const Fields extends Schema.Struct.Fields>(fields: Fields) {
return Schema.Struct(fields).mapFields(Struct.map(Schema.mutableKey))
return Schema.catchDecoding<typeof field>(() => Effect.succeed(Option.none()))(field)
}
// Recover individual entries rather than discarding the whole collection.
function array<S extends Schema.ConstraintCodec<unknown, unknown>>(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<S extends Schema.ConstraintCodec<unknown, unknown>>(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<string>()
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,

View file

@ -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",

View file

@ -38,8 +38,8 @@ const setup: MainSetup<typeof definition> = 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)),

View file

@ -21,7 +21,7 @@ const setup: Setup<typeof definition> = (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") })
}

View file

@ -44,7 +44,7 @@ const setup: MainSetup<typeof definition> = (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")

View file

@ -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<unknown, undefined>
}
type ReviewDiff = ((PresentationFileDiff & { file: string }) | FileDiffInfo) & {
preloaded?: PreloadMultiFileDiffResult<unknown, undefined>
}
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<HTMLDivElement, Event>
@ -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<string, HTMLElement>()
const nodes = new Map<string, HTMLDivElement>()
const [store, setStore] = createStore({
open: [] as string[],
visible: {} as Record<string, boolean>,
force: {} as Record<string, boolean>,
selection: null as SessionReviewSelection | null,
commenting: null as SessionReviewSelection | null,
opened: null as SessionReviewFocus | null,
const [store, setStore] = createStore<{
open: string[]
visible: Record<string, boolean | undefined>
force: Record<string, boolean | undefined>
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<string, SessionReviewComment[]>()
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<HTMLDivElement, Event> = (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<HTMLDivElement, Event>)(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),

View file

@ -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",

View file

@ -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<typeof Root> {}
export interface AccordionProps extends Omit<ComponentProps<typeof Root>, "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<typeof Item> {}
export interface AccordionHeaderProps extends ComponentProps<typeof Header> {}
export interface AccordionTriggerProps extends ComponentProps<typeof Trigger> {}
export interface AccordionContentProps extends ComponentProps<typeof Content> {}
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 (
<Root
{...rest}
value={split.value as string[] | undefined}
data-component="accordion"
classList={{
...split.classList,
@ -24,6 +34,7 @@ function AccordionRoot(props: AccordionProps) {
function AccordionItem(props: AccordionItemProps) {
const [split, rest] = splitProps(props, ["class", "classList"])
return (
<Item
{...rest}
@ -38,6 +49,7 @@ function AccordionItem(props: AccordionItemProps) {
function AccordionHeader(props: ParentProps<AccordionHeaderProps>) {
const [split, rest] = splitProps(props, ["class", "classList", "children"])
return (
<Header
{...rest}
@ -54,6 +66,7 @@ function AccordionHeader(props: ParentProps<AccordionHeaderProps>) {
function AccordionTrigger(props: ParentProps<AccordionTriggerProps>) {
const [split, rest] = splitProps(props, ["class", "classList", "children"])
return (
<Trigger
{...rest}
@ -70,6 +83,7 @@ function AccordionTrigger(props: ParentProps<AccordionTriggerProps>) {
function AccordionContent(props: ParentProps<AccordionContentProps>) {
const [split, rest] = splitProps(props, ["class", "classList", "children"])
return (
<Content
{...rest}

View file

@ -0,0 +1,269 @@
import { additionalIcons, additionalIconViewBox } from "./icon/additional-icons"
// Consumers center the SVG viewport, so each icon must center its artwork within its viewBox.
const icons = {
lock: {
viewBox: "0 0 16 16",
body: `<rect x="3.5" y="7" width="9" height="7" rx="1" stroke="currentColor"/><path d="M5 7V5a3 3 0 0 1 6 0v2M8 10v1" stroke="currentColor" stroke-linecap="round"/>`,
},
globe: {
viewBox: "0 0 16 16",
body: `<circle cx="8" cy="8" r="6" stroke="currentColor"/><ellipse cx="8" cy="8" rx="2.5" ry="6" stroke="currentColor"/><path d="M2 8h12" stroke="currentColor"/>`,
},
"select-element": {
viewBox: "0 0 16 16",
body: `<path d="M12.5 6.5V2.5C12.5 1.94772 12.0523 1.5 11.5 1.5H2.5C1.94772 1.5 1.5 1.94772 1.5 2.5V11.5C1.5 12.0523 1.94772 12.5 2.5 12.5H6.5" stroke="currentColor" stroke-linecap="round"/><path d="M7.5 7.5L14.5 10.1L11.1 11.1L10.1 14.5L7.5 7.5Z" stroke="currentColor" stroke-linejoin="round"/>`,
},
flask: {
viewBox: "0 0 16 16",
body: `<path d="M5.5 2H10.5M6 2V6L2.5 12C2 13 2.5 14 3.5 14H12.5C13.5 14 14 13 13.5 12L10 6V2M4.25 9H11.75" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"/>`,
},
edit: {
viewBox: "0 0 16 16",
body: `<path d="M13.5556 8.21529V13.5556H2.44446L2.44446 2.44445H7.78474M6.00002 8.16216V10H7.83786L14 3.83784L12.1622 2L6.00002 8.16216Z" stroke="currentColor"/>`,
},
"folder-add-left": {
viewBox: "0 0 16 16",
body: `<path d="M7.5 13.3333H1.5V2H6.83333L8.83333 4H14.8333V6M10.1667 11.3333H15.5M12.8333 8.66667V14" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
folder: {
viewBox: "0 0 16 16",
body: `<path d="M1.33337 2V13.3333H14.6667V4H8.66671L6.66671 2H1.33337Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
branch: {
viewBox: "0 0 16 16",
body: `<path d="M5.118 5.686V10.314M5.118 5.686C5.97 5.686 6.661 4.995 6.661 4.143C6.661 3.291 5.97 2.6 5.118 2.6C4.266 2.6 3.575 3.291 3.575 4.143C3.575 4.995 4.266 5.686 5.118 5.686ZM5.118 10.314C4.266 10.314 3.575 11.005 3.575 11.857C3.575 12.709 4.266 13.4 5.118 13.4C5.97 13.4 6.661 12.709 6.661 11.857M5.118 10.314C5.97 10.314 6.661 11.005 6.661 11.857M10.882 5.686C11.734 5.686 12.425 4.995 12.425 4.143C12.425 3.291 11.734 2.6 10.882 2.6C10.03 2.6 9.339 3.291 9.339 4.143C9.339 4.995 10.03 5.686 10.882 5.686ZM10.882 5.686V9.457C10.882 10.783 9.807 11.857 8.482 11.857H6.661" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>`,
},
"branch-out": {
viewBox: "0 0 16 16",
body: `<path d="M10.4225 3.35355L12.9024 5.83344L10.4225 8.31333" stroke="currentColor"/><path d="M1 12.2852H4.23042C4.89912 12.2852 5.52359 11.951 5.89452 11.3946L9.00783 6.72462C8.37877 6.16823 10.0032 5.83402 10.6719 5.83402H12.9024" stroke="currentColor"/><path d="M8.5 12.2852H14" stroke="currentColor" stroke-linejoin="round"/>`,
},
"grid-plus": {
viewBox: "0 0 16 16",
body: `<path d="M13.9948 11.668H9.32812M11.6641 9.33203V13.9987M6.66667 9.33203V13.9987H2V9.33203H6.66667ZM6.66667 2V6.66667H2V2H6.66667ZM13.9948 2V6.66667H9.32812V2H13.9948Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
help: {
viewBox: "0 0 16 16",
body: `<path d="M6.33345 6.33349V5.00015H9.66679V7.00015L8.00015 8.00015V9.66679M8.27485 11.6819H7.71897M14.4446 8.00011C14.4446 11.5593 11.5593 14.4446 8.00011 14.4446C4.44094 14.4446 1.55566 11.5593 1.55566 8.00011C1.55566 4.44094 4.44094 1.55566 8.00011 1.55566C11.5593 1.55566 14.4446 4.44094 14.4446 8.00011Z" stroke="currentColor" stroke-linecap="square"/>`,
},
info: {
viewBox: "0 0 16 16",
body: `<g transform="translate(2 2)"><path d="M12 12H0V0H12V12ZM1 1V11H11V1H1ZM6.5791 4.81641V9.37207H5.5791V5.81641H4.46777V4.81641H6.5791ZM6.85645 2.62891V3.62891H5.30078V2.62891H6.85645Z" fill="currentColor"/></g>`,
},
"circle-exclamation": {
viewBox: "0 0 16 16",
body: `<path d="M8.75 11.75H7.25V10.25H8.75V11.75Z" fill="currentColor"/><path d="M8.75 9.25H7.25V4.25H8.75V9.25Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M8 1C9.93286 1 11.684 1.7836 12.9502 3.0498C14.2164 4.31601 15 6.06714 15 8C15 11.866 11.866 15 8 15C6.06714 15 4.31601 14.2164 3.0498 12.9502C1.7836 11.684 1 9.93286 1 8C1 4.13401 4.13401 1 8 1ZM8 2C4.68629 2 2 4.68629 2 8C2 9.65699 2.67148 11.1559 3.75781 12.2422C4.84415 13.3285 6.34301 14 8 14C11.3137 14 14 11.3137 14 8C14 6.34301 13.3285 4.84415 12.2422 3.75781C11.1559 2.67148 9.65699 2 8 2Z" fill="currentColor"/>`,
},
"circle-xmark": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M1.33334 8.00016C1.33334 4.31826 4.31811 1.3335 8.00001 1.3335C11.6819 1.3335 14.6667 4.31826 14.6667 8.00016C14.6667 11.6821 11.6819 14.6668 8.00001 14.6668C4.31811 14.6668 1.33334 11.6821 1.33334 8.00016ZM6.00001 5.29306L5.2929 6.00016L7.2929 8.00016L5.2929 10.0002L6.00001 10.7073L8.00001 8.70727L10 10.7073L10.7071 10.0002L8.70712 8.00016L10.7071 6.00016L10 5.29306L8.00001 7.29306L6.00001 5.29306Z" fill="currentColor"/>`,
},
"sidebar-right": {
viewBox: "0 0 20 20",
body: `<path d="M2.91536 2.91406H2.36536V2.36406H2.91536V2.91406ZM2.91536 17.0807V17.6307H2.36536V17.0807H2.91536ZM17.082 17.0807H17.632V17.6307H17.082V17.0807ZM17.082 2.91406V2.36406H17.632V2.91406H17.082ZM6.9987 2.91406H6.4487V2.36406H6.9987V2.91406ZM6.9987 17.0807V17.6307H6.4487V17.0807H6.9987ZM2.91536 2.91406H3.46536V17.0807H2.91536H2.36536V2.91406H2.91536ZM2.91536 17.0807V16.5307H17.082V17.0807V17.6307H2.91536V17.0807ZM17.082 17.0807H16.532V2.91406H17.082H17.632V17.0807H17.082ZM17.082 2.91406V3.46406H2.91536V2.91406V2.36406H17.082V2.91406ZM6.9987 2.91406H7.5487V17.0807H6.9987H6.4487V2.91406H6.9987ZM17.082 17.0807L17.082 17.6307L6.9987 17.6307V17.0807V16.5307L17.082 16.5307L17.082 17.0807ZM6.9987 2.91406V2.36406H17.082V2.91406V3.46406H6.9987V2.91406Z" fill="currentColor"/>`,
},
status: {
viewBox: "0 0 20 20",
body: `<path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>`,
},
"status-active": {
viewBox: "0 0 20 20",
body: `<path d="M18 2H2V10H18V2Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 18H18V10H2V18Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>`,
},
"magnifying-glass": {
viewBox: "0 0 16 16",
body: `<path d="M14 14L10.3454 10.3454M6.88889 11.7778C9.58889 11.7778 11.7778 9.58889 11.7778 6.88889C11.7778 4.18889 9.58889 2 6.88889 2C4.18889 2 2 4.18889 2 6.88889C2 9.58889 4.18889 11.7778 6.88889 11.7778Z" stroke="currentColor"/>`,
},
menu: {
viewBox: "0 0 16 16",
body: `<path d="M2 8H14M2 4.664H14M2 11.336H14" stroke="currentColor"/>`,
},
plus: {
viewBox: "0 0 16 16",
body: `<path d="M8 2.88867V13.1109" stroke="currentColor" stroke-linejoin="round"/><path d="M2.88867 8H13.1109" stroke="currentColor" stroke-linejoin="round"/>`,
},
"settings-gear": {
viewBox: "0 0 16 16",
body: `<path d="M7.99998 1.3335L14 4.66683V11.3335L7.99998 14.6668L2 11.3335V4.66683L7.99998 1.3335Z" stroke="currentColor"/><path d="M9.99998 8.00016C9.99998 9.10476 9.10458 10.0002 7.99998 10.0002C6.89538 10.0002 5.99998 9.10476 5.99998 8.00016C5.99998 6.89556 6.89538 6.00016 7.99998 6.00016C9.10458 6.00016 9.99998 6.89556 9.99998 8.00016Z" stroke="currentColor"/>`,
},
"chevron-down": {
viewBox: "0 0 16 16",
body: `<path d="M5 6.5L8 9.5L11 6.5" stroke="currentColor"/>`,
},
collapse: {
viewBox: "0 0 16 16",
body: `<path d="M8 1V6M11 3L8 6L5 3" stroke="currentColor"/><path d="M8 15V10M11 13L8 10L5 13" stroke="currentColor"/><path d="M4 8H6" stroke="currentColor"/><path d="M7 8H9" stroke="currentColor"/><path d="M10 8H12" stroke="currentColor"/>`,
},
check: {
viewBox: "0 0 16 16",
body: `<path d="M3.53613 8.17857L6.39328 11.75L12.4647 4.25" stroke="currentColor"/>`,
},
monitor: {
viewBox: "0 0 16 16",
body: `<path d="M4.05559 9.38889H0.500007C0.500007 9.38889 0.500017 8.59298 0.500017 7.61112V2.27778C0.500017 1.29594 0.500102 0.5 0.500102 0.5H13.3889C13.3889 0.5 13.3889 1.29594 13.3889 2.27778V7.61112C13.3889 8.59298 13.3889 9.38889 13.3889 9.38889H9.83336M4.05559 9.38889V11.6111H6.94448H9.83336V9.38889M4.05559 9.38889H9.83336" transform="translate(1.05556 1.94444)" stroke="currentColor"/>`,
},
"workspace-new": {
viewBox: "0 0 16 16",
body: `<path d="M2 10.7578V14.0011H5.24324M13.9991 5.24324V2H10.7559M13.9991 10.7578V14.0011H10.7559M2 5.24324V2H5.24324" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M8 4.5V11.5M4.5 8H11.5" stroke="currentColor" stroke-linejoin="round"/>`,
},
"workspace-isolated": {
viewBox: "0 0 16 16",
body: `<path d="M10.5 10.5V5.5H5.5V10.5H10.5Z" fill="currentColor"/><rect x="2.5" y="2.5" width="11" height="11" stroke="currentColor"/>`,
},
workspace: {
viewBox: "0 0 16 16",
body: `<path d="M2 10.668V14.0013H10.6667M13.9974 10.6667V2H2.66406M13.9974 10.668V14.0013H10.6641M2 10V2H5.33333" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M10.6693 10.6654V5.33203H5.33594V10.6654H10.6693Z" fill="currentColor"/>`,
},
"outline-worktree": {
viewBox: "0 0 16 16",
body: `<path d="M12 3.11133L14.3885 5.49977L12 7.88822M14.5 5.49972H10.058L5.13456 11.8139M14.5 11.6606L8.5 11.6606M5.50012 11.6597H1.5" stroke="currentColor"/>`,
},
"outline-trash": {
viewBox: "0 0 16 16",
body: `<path d="M2.44434 4.22224H13.5554M5.99994 4.22224V2.44446C5.99994 1.95557 5.99992 1.55557 5.99992 1.55557H9.99989C9.99989 1.55557 9.99994 1.95557 9.99994 2.44446V4.22224M6.55545 7.77779L6.7485 11.7778M9.44437 7.77779L9.2513 11.7778M12.1756 6.88891L11.8666 12.7556C11.8168 13.7068 11.7748 14.4445 11.7748 14.4445H4.22511C4.22511 14.4445 4.18392 13.7067 4.13414 12.7556L3.82509 6.88891" stroke="currentColor"/>`,
},
close: {
viewBox: "0 0 20 20",
body: `<path d="M14.4446 5.55566L5.55566 14.4446M5.55566 5.55566L14.4446 14.4446" stroke="currentColor" stroke-linejoin="round"/>`,
},
"xmark-small": {
viewBox: "0 0 16 16",
body: `<path d="M4.25 11.75L11.75 4.25M11.75 11.75L4.25 4.25" stroke="currentColor"/>`,
},
"outline-xmark": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M4.99487 5.70186L7.29297 7.99995L4.99487 10.2981L5.70198 11.0052L8.00008 8.70706L10.2982 11.0052L11.0053 10.2981L8.70718 7.99995L11.0053 5.70186L10.2982 4.99475L8.00008 7.29285L5.70198 4.99475L4.99487 5.70186Z" fill="currentColor"/>`,
},
"outline-chevron-down": {
viewBox: "0 0 16 16",
body: `<path d="M5 6.5L8 9.5L11 6.5" stroke="currentColor"/>`,
},
"outline-dots": {
viewBox: "0 0 16 16",
body: `<path d="M2.5 7.5H3.5V8.5H2.5V7.5Z" stroke="currentColor"/><path d="M7.5 7.5H8.5V8.5H7.5V7.5Z" stroke="currentColor"/><path d="M12.5 7.5H13.5V8.5H12.5V7.5Z" stroke="currentColor"/>`,
},
expand: {
viewBox: "0 0 16 16",
body: `<path d="M8.25 6.17773V1.17773M11.25 4.17773L8.25 1.17773L5.25 4.17773" stroke="currentColor"/><path d="M8.25 9.17773V14.1777M11.25 11.1777L8.25 14.1777L5.25 11.1777" stroke="currentColor"/><path d="M4.25 7.67773H12.25" stroke="currentColor"/>`,
},
filetree: {
viewBox: "0 0 16 16",
body: `<path d="M2.5 1.5V12.2484H6.75M2.5 4.74838H6.75" stroke="currentColor"/><rect x="8.5" y="3.2168" width="6" height="3" fill="none" stroke="currentColor"/><rect x="8.5" y="10.75" width="6" height="3" fill="none" stroke="currentColor"/>`,
},
split: {
viewBox: "0 0 16 16",
body: `<path d="M1 14H15L15 2H1V14Z" stroke="currentColor"/><rect x="3" y="4" width="4" height="8" fill="currentColor" fill-opacity="0.5"/><rect x="9" y="4" width="4" height="8" fill="currentColor" fill-opacity="0.5"/>`,
},
unified: {
viewBox: "0 0 16 16",
body: `<path d="M3.00001 4.00045L12.9998 4L13 6.99955L3 7L3.00001 4.00045Z" fill="currentColor" fill-opacity="0.5"/><path d="M3.0001 9H13L12.9999 12H3L3.0001 9Z" fill="currentColor" fill-opacity="0.5"/><path d="M1 14H15L15 2H1V14Z" stroke="currentColor"/>`,
},
review: {
viewBox: "0 0 20 20",
body: `<path d="M7 14.5H13M7 7.99512H10.0049M10.0049 7.99512H13M10.0049 7.99512V5M10.0049 7.99512V11M18 18V2L2 2L2 18H18Z" stroke="currentColor"/>`,
},
"window-analytics": {
viewBox: "0 0 16 16",
body: `<path d="M14.5 9.8333V13.5H1.5V2.5H7.1667M9.5 2.5V7.5H14.5V2.5H9.5Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
"graduation-cap": {
viewBox: "0 0 16 16",
body: `<path d="M12.3327 7.50065V11.0007L7.99935 13.6673L3.66602 11.0007V7.50065M14.3327 9.83398V6.16732M7.99935 2.33398L1.66602 6.00065L7.99935 10.0007L14.3327 6.00065L7.99935 2.33398Z" stroke="currentColor" stroke-linecap="square"/>`,
},
"code-slash": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0812 2.10803L6.55974 14.0809L5.92016 13.8928L9.44161 1.91992L10.0812 2.10803ZM4.13793 4.97275L1.44666 8.00045L4.13793 11.0281L3.63966 11.471L0.554688 8.00045L3.63966 4.52984L4.13793 4.97275ZM12.3617 4.52984L15.4467 8.00045L12.3617 11.471L11.8634 11.0281L14.5547 8.00045L11.8634 4.97275L12.3617 4.52984Z" fill="currentColor"/>`,
},
trash: {
viewBox: "0 0 20 20",
body: `<path d="M4.58342 17.9134L4.58369 17.4134L4.22787 17.5384L4.22766 18.0384H4.58342V17.9134ZM15.4167 17.9134V18.0384H15.7725L15.7723 17.5384L15.4167 17.9134ZM2.08342 3.95508V3.45508H1.58342V3.95508H2.08342V4.45508V3.95508ZM17.9167 4.45508V4.95508H18.4167V4.45508H17.9167V3.95508V4.45508ZM4.16677 4.58008L3.66701 4.5996L4.22816 17.5379L4.72792 17.4934L5.22767 17.4489L4.66652 4.54055L4.16677 4.58008ZM4.58342 18.0384V17.9134H15.4167V18.0384V18.5384H4.58342V18.0384ZM15.4167 17.9134L15.8332 17.5379L16.2498 4.5996L15.7501 4.58008L15.2503 4.56055L14.8337 17.4989L15.4167 17.9134ZM15.8334 4.58008V4.08008H4.16677V4.58008V5.08008H15.8334V4.58008ZM2.08342 4.45508V4.95508H4.16677V4.58008V4.08008H2.08342V4.45508ZM15.8334 4.58008V5.08008H17.9167V4.45508V3.95508H15.8334V4.58008ZM6.83951 4.35149L7.432 4.55047C7.79251 3.47701 8.80699 2.70508 10.0001 2.70508V2.20508V1.70508C8.25392 1.70508 6.77335 2.83539 6.24702 4.15251L6.83951 4.35149ZM10.0001 2.20508V2.70508C11.1932 2.70508 12.2077 3.47701 12.5682 4.55047L13.1607 4.35149L13.7532 4.15251C13.2269 2.83539 11.7463 1.70508 10.0001 1.70508V2.20508Z" fill="currentColor"/>`,
},
"outline-sliders": {
viewBox: "0 0 16 16",
body: `<path d="M11.7779 4.66675H14.4446M11.7779 4.66675C11.7779 5.77132 10.8825 6.66675 9.77789 6.66675C8.67332 6.66675 7.77789 5.77132 7.77789 4.66675M11.7779 4.66675C11.7779 3.56218 10.8825 2.66675 9.77789 2.66675C8.67332 2.66675 7.77789 3.56218 7.77789 4.66675M1.55566 4.66675H7.77789M4.22233 11.3334H1.55566M4.22233 11.3334C4.22233 12.438 5.11776 13.3334 6.22233 13.3334C7.3269 13.3334 8.22233 12.438 8.22233 11.3334M4.22233 11.3334C4.22233 10.2288 5.11776 9.33341 6.22233 9.33341C7.3269 9.33341 8.22233 10.2288 8.22233 11.3334M14.4446 11.3334H8.22233" stroke="currentColor"/>`,
},
"outline-copy": {
viewBox: "0 0 16 16",
body: `<path d="M4.14908 11.0081H1.76282V1.51758H9.1038V2.55588M14.2225 4.99681H6.75397V14.4873H14.2225V4.99681Z" stroke="currentColor"/>`,
},
"arrow-up-right": {
viewBox: "0 0 16 16",
body: `<path d="M11 9.56V5H6.44M11 5L5 11" stroke="currentColor"/>`,
},
"outline-square-arrow": {
viewBox: "0 0 16 16",
body: `<path d="M13.5555 6.66656V2.44434H9.33326M13.5555 2.44434L7.99993 7.99989M13.5555 9.33324V13.5555C13.5555 13.5555 12.7599 13.5555 11.7777 13.5555H2.44438C2.44438 13.5555 2.44438 12.7599 2.44438 11.7777V4.22213C2.44438 3.2399 2.44434 2.44435 2.44434 2.44435H6.66661" stroke="currentColor"/>`,
},
"outline-arrow-to-corner-top-right": {
viewBox: "0 0 16 16",
body: `<path d="M2 8.5V2H14V14H8M5 5.66667H10.3333V11M3.66797 12.333L9.94292 6.05806" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-hexagonal-warning": {
viewBox: "0 0 16 16",
body: `<path d="M10.6667 1.33325H5.33272L1.33334 5.33325L1.33342 10.6917L5.3327 14.691L10.6667 14.6909L14.6911 10.6917V5.33255L10.6667 1.33325Z" stroke="currentColor"/><path d="M8 10.6667H8.00667" stroke="currentColor" stroke-linecap="square"/><path d="M8 7.99992V5.33325" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-share": {
viewBox: "0 0 16 16",
body: `<path d="M13.5554 10.4445V13.5556C13.5554 13.5556 12.7599 13.5556 11.7777 13.5556H4.22211C3.23989 13.5556 2.44434 13.5556 2.44434 13.5556V10.4445M4.88878 5.55557L7.99989 2.44446L11.111 5.55557M7.99989 2.44446L7.99989 9.11112" stroke="currentColor"/>`,
},
"outline-eye": {
viewBox: "0 0 20 20",
body: `<path d="M2.5 10s3.33-5.42 7.5-5.42S17.5 10 17.5 10s-3.33 5.42-7.5 5.42S2.5 10 2.5 10Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/><circle cx="10" cy="10" r="2.5" stroke="currentColor"/>`,
},
"outline-eye-slash": {
viewBox: "0 0 20 20",
body: `<path d="M2.5 10s3.33-5.42 7.5-5.42S17.5 10 17.5 10s-3.33 5.42-7.5 5.42S2.5 10 2.5 10Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/><circle cx="10" cy="10" r="2.5" stroke="currentColor"/><path d="M3 3 17 17" stroke="currentColor" stroke-linecap="round"/>`,
},
refresh: {
viewBox: "0 0 20 20",
body: `<path d="M16.25 7.5A6.5 6.5 0 1 0 16.5 11M16.25 3.5v4h-4" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>`,
},
reset: {
viewBox: "0 0 20 20",
body: `<path d="M5.83333 4.16406L2.5 7.4974L5.83333 10.8307M3.33333 7.4974H17.9167V15.4141H10" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-reset": {
viewBox: "0 0 20 20",
body: `<path d="M5.83333 4.16406L2.5 7.4974L5.83333 10.8307M3.33333 7.4974H17.9167V15.4141H10" stroke="currentColor" stroke-linecap="square"/>`,
},
"fill-triangle-down": {
viewBox: "0 0 16 16",
body: `<path d="M5.37624 6.75194C5.18184 6.41861 5.42224 6 5.80814 6H10.1921C10.578 6 10.8184 6.41861 10.624 6.75194L8.43203 10.5096C8.23909 10.8404 7.76119 10.8404 7.56825 10.5096L5.37624 6.75194Z" fill="currentColor"/>`,
},
archive: {
viewBox: "0 0 16 16",
body: `<path d="M13.1112 13.5555V14.0555H13.6112V13.5555H13.1112ZM2.889 13.5555H2.389L2.389 14.0555H2.889V13.5555ZM3.38901 5.55546L3.38901 5.05546L2.38901 5.05546L2.38901 5.55546L2.88901 5.55546L3.38901 5.55546ZM14.4446 2.44434H14.9446V1.94434L14.4446 1.94434L14.4446 2.44434ZM14.4446 5.55545L14.4446 6.05545L14.9446 6.05545V5.55545H14.4446ZM1.55566 5.55546L1.05566 5.55545L1.05566 6.05546L1.55566 6.05546L1.55566 5.55546ZM1.5557 2.44436L1.5557 1.94436L1.05571 1.94436L1.0557 2.44435L1.5557 2.44436ZM13.1112 5.55546H12.6112V13.5555H13.1112H13.6112V5.55546H13.1112ZM2.889 13.5555H3.389L3.38901 5.55546L2.88901 5.55546L2.38901 5.55546L2.389 13.5555H2.889ZM14.4446 2.44434H13.9446V5.55545H14.4446H14.9446V2.44434H14.4446ZM1.55566 5.55546L2.05566 5.55547L2.0557 2.44436L1.5557 2.44436L1.0557 2.44435L1.05566 5.55545L1.55566 5.55546ZM6.22234 8.22213V8.72213H9.7779V8.22213V7.72213H6.22234V8.22213ZM13.1112 13.5555V13.0555H2.889V13.5555V14.0555H13.1112V13.5555ZM1.5557 2.44436L1.5557 2.94436L14.4446 2.94434L14.4446 2.44434L14.4446 1.94434L1.5557 1.94436L1.5557 2.44436ZM14.4446 5.55545L14.4446 5.05545L1.55566 5.05546L1.55566 5.55546L1.55566 6.05546L14.4446 6.05545L14.4446 5.55545Z" fill="currentColor"/>`,
},
}
/** 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) }
}

View file

@ -1,3 +1,4 @@
/** Additional UI artwork, independent of a renderer. */
export const additionalIcons = {
"align-right": `<path d="M12.292 6.04167L16.2503 9.99998L12.292 13.9583M2.91699 9.99998H15.6253M17.0837 3.75V16.25" stroke="currentColor" stroke-linecap="square"/>`,
"arrow-up": `<path fill-rule="evenodd" clip-rule="evenodd" d="M9.99991 2.24121L16.0921 8.33343L15.2083 9.21731L10.6249 4.63397V17.5001H9.37492V4.63398L4.7916 9.21731L3.90771 8.33343L9.99991 2.24121Z" fill="currentColor"/>`,

View file

@ -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: `<rect x="3.5" y="7" width="9" height="7" rx="1" stroke="currentColor"/><path d="M5 7V5a3 3 0 0 1 6 0v2M8 10v1" stroke="currentColor" stroke-linecap="round"/>`,
},
globe: {
viewBox: "0 0 16 16",
body: `<circle cx="8" cy="8" r="6" stroke="currentColor"/><ellipse cx="8" cy="8" rx="2.5" ry="6" stroke="currentColor"/><path d="M2 8h12" stroke="currentColor"/>`,
},
"select-element": {
viewBox: "0 0 16 16",
body: `<path d="M12.5 6.5V2.5C12.5 1.94772 12.0523 1.5 11.5 1.5H2.5C1.94772 1.5 1.5 1.94772 1.5 2.5V11.5C1.5 12.0523 1.94772 12.5 2.5 12.5H6.5" stroke="currentColor" stroke-linecap="round"/><path d="M7.5 7.5L14.5 10.1L11.1 11.1L10.1 14.5L7.5 7.5Z" stroke="currentColor" stroke-linejoin="round"/>`,
},
flask: {
viewBox: "0 0 16 16",
body: `<path d="M5.5 2H10.5M6 2V6L2.5 12C2 13 2.5 14 3.5 14H12.5C13.5 14 14 13 13.5 12L10 6V2M4.25 9H11.75" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"/>`,
},
edit: {
viewBox: "0 0 16 16",
body: `<path d="M13.5556 8.21529V13.5556H2.44446L2.44446 2.44445H7.78474M6.00002 8.16216V10H7.83786L14 3.83784L12.1622 2L6.00002 8.16216Z" stroke="currentColor"/>`,
},
"folder-add-left": {
viewBox: "0 0 16 16",
body: `<path d="M7.5 13.3333H1.5V2H6.83333L8.83333 4H14.8333V6M10.1667 11.3333H15.5M12.8333 8.66667V14" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
folder: {
viewBox: "0 0 16 16",
body: `<path d="M1.33337 2V13.3333H14.6667V4H8.66671L6.66671 2H1.33337Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
branch: {
viewBox: "0 0 16 16",
body: `<path d="M5.118 5.686V10.314M5.118 5.686C5.97 5.686 6.661 4.995 6.661 4.143C6.661 3.291 5.97 2.6 5.118 2.6C4.266 2.6 3.575 3.291 3.575 4.143C3.575 4.995 4.266 5.686 5.118 5.686ZM5.118 10.314C4.266 10.314 3.575 11.005 3.575 11.857C3.575 12.709 4.266 13.4 5.118 13.4C5.97 13.4 6.661 12.709 6.661 11.857M5.118 10.314C5.97 10.314 6.661 11.005 6.661 11.857M10.882 5.686C11.734 5.686 12.425 4.995 12.425 4.143C12.425 3.291 11.734 2.6 10.882 2.6C10.03 2.6 9.339 3.291 9.339 4.143C9.339 4.995 10.03 5.686 10.882 5.686ZM10.882 5.686V9.457C10.882 10.783 9.807 11.857 8.482 11.857H6.661" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>`,
},
"branch-out": {
viewBox: "0 0 16 16",
body: `<path d="M10.4225 3.35355L12.9024 5.83344L10.4225 8.31333" stroke="currentColor"/><path d="M1 12.2852H4.23042C4.89912 12.2852 5.52359 11.951 5.89452 11.3946L9.00783 6.72462C8.37877 6.16823 10.0032 5.83402 10.6719 5.83402H12.9024" stroke="currentColor"/><path d="M8.5 12.2852H14" stroke="currentColor" stroke-linejoin="round"/>`,
},
"grid-plus": {
viewBox: "0 0 16 16",
body: `<path d="M13.9948 11.668H9.32812M11.6641 9.33203V13.9987M6.66667 9.33203V13.9987H2V9.33203H6.66667ZM6.66667 2V6.66667H2V2H6.66667ZM13.9948 2V6.66667H9.32812V2H13.9948Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
help: {
viewBox: "0 0 16 16",
body: `<path d="M6.33345 6.33349V5.00015H9.66679V7.00015L8.00015 8.00015V9.66679M8.27485 11.6819H7.71897M14.4446 8.00011C14.4446 11.5593 11.5593 14.4446 8.00011 14.4446C4.44094 14.4446 1.55566 11.5593 1.55566 8.00011C1.55566 4.44094 4.44094 1.55566 8.00011 1.55566C11.5593 1.55566 14.4446 4.44094 14.4446 8.00011Z" stroke="currentColor" stroke-linecap="square"/>`,
},
info: {
viewBox: "0 0 16 16",
body: `<g transform="translate(2 2)"><path d="M12 12H0V0H12V12ZM1 1V11H11V1H1ZM6.5791 4.81641V9.37207H5.5791V5.81641H4.46777V4.81641H6.5791ZM6.85645 2.62891V3.62891H5.30078V2.62891H6.85645Z" fill="currentColor"/></g>`,
},
"circle-exclamation": {
viewBox: "0 0 16 16",
body: `<path d="M8.75 11.75H7.25V10.25H8.75V11.75Z" fill="currentColor"/><path d="M8.75 9.25H7.25V4.25H8.75V9.25Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M8 1C9.93286 1 11.684 1.7836 12.9502 3.0498C14.2164 4.31601 15 6.06714 15 8C15 11.866 11.866 15 8 15C6.06714 15 4.31601 14.2164 3.0498 12.9502C1.7836 11.684 1 9.93286 1 8C1 4.13401 4.13401 1 8 1ZM8 2C4.68629 2 2 4.68629 2 8C2 9.65699 2.67148 11.1559 3.75781 12.2422C4.84415 13.3285 6.34301 14 8 14C11.3137 14 14 11.3137 14 8C14 6.34301 13.3285 4.84415 12.2422 3.75781C11.1559 2.67148 9.65699 2 8 2Z" fill="currentColor"/>`,
},
"circle-xmark": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M1.33334 8.00016C1.33334 4.31826 4.31811 1.3335 8.00001 1.3335C11.6819 1.3335 14.6667 4.31826 14.6667 8.00016C14.6667 11.6821 11.6819 14.6668 8.00001 14.6668C4.31811 14.6668 1.33334 11.6821 1.33334 8.00016ZM6.00001 5.29306L5.2929 6.00016L7.2929 8.00016L5.2929 10.0002L6.00001 10.7073L8.00001 8.70727L10 10.7073L10.7071 10.0002L8.70712 8.00016L10.7071 6.00016L10 5.29306L8.00001 7.29306L6.00001 5.29306Z" fill="currentColor"/>`,
},
"sidebar-right": {
viewBox: "0 0 20 20",
body: `<path d="M2.91536 2.91406H2.36536V2.36406H2.91536V2.91406ZM2.91536 17.0807V17.6307H2.36536V17.0807H2.91536ZM17.082 17.0807H17.632V17.6307H17.082V17.0807ZM17.082 2.91406V2.36406H17.632V2.91406H17.082ZM6.9987 2.91406H6.4487V2.36406H6.9987V2.91406ZM6.9987 17.0807V17.6307H6.4487V17.0807H6.9987ZM2.91536 2.91406H3.46536V17.0807H2.91536H2.36536V2.91406H2.91536ZM2.91536 17.0807V16.5307H17.082V17.0807V17.6307H2.91536V17.0807ZM17.082 17.0807H16.532V2.91406H17.082H17.632V17.0807H17.082ZM17.082 2.91406V3.46406H2.91536V2.91406V2.36406H17.082V2.91406ZM6.9987 2.91406H7.5487V17.0807H6.9987H6.4487V2.91406H6.9987ZM17.082 17.0807L17.082 17.6307L6.9987 17.6307V17.0807V16.5307L17.082 16.5307L17.082 17.0807ZM6.9987 2.91406V2.36406H17.082V2.91406V3.46406H6.9987V2.91406Z" fill="currentColor"/>`,
},
status: {
viewBox: "0 0 20 20",
body: `<path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>`,
},
"status-active": {
viewBox: "0 0 20 20",
body: `<path d="M18 2H2V10H18V2Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 18H18V10H2V18Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>`,
},
"magnifying-glass": {
viewBox: "0 0 16 16",
body: `<path d="M14 14L10.3454 10.3454M6.88889 11.7778C9.58889 11.7778 11.7778 9.58889 11.7778 6.88889C11.7778 4.18889 9.58889 2 6.88889 2C4.18889 2 2 4.18889 2 6.88889C2 9.58889 4.18889 11.7778 6.88889 11.7778Z" stroke="currentColor"/>`,
},
menu: {
viewBox: "0 0 16 16",
body: `<path d="M2 8H14M2 4.664H14M2 11.336H14" stroke="currentColor"/>`,
},
plus: {
viewBox: "0 0 16 16",
body: `<path d="M8 2.88867V13.1109" stroke="currentColor" stroke-linejoin="round"/><path d="M2.88867 8H13.1109" stroke="currentColor" stroke-linejoin="round"/>`,
},
"settings-gear": {
viewBox: "0 0 16 16",
body: `<path d="M7.99998 1.3335L14 4.66683V11.3335L7.99998 14.6668L2 11.3335V4.66683L7.99998 1.3335Z" stroke="currentColor"/><path d="M9.99998 8.00016C9.99998 9.10476 9.10458 10.0002 7.99998 10.0002C6.89538 10.0002 5.99998 9.10476 5.99998 8.00016C5.99998 6.89556 6.89538 6.00016 7.99998 6.00016C9.10458 6.00016 9.99998 6.89556 9.99998 8.00016Z" stroke="currentColor"/>`,
},
"chevron-down": {
viewBox: "0 0 16 16",
body: `<path d="M5 6.5L8 9.5L11 6.5" stroke="currentColor"/>`,
},
collapse: {
viewBox: "0 0 16 16",
body: `<path d="M8 1V6M11 3L8 6L5 3" stroke="currentColor"/><path d="M8 15V10M11 13L8 10L5 13" stroke="currentColor"/><path d="M4 8H6" stroke="currentColor"/><path d="M7 8H9" stroke="currentColor"/><path d="M10 8H12" stroke="currentColor"/>`,
},
check: {
viewBox: "0 0 16 16",
body: `<path d="M3.53613 8.17857L6.39328 11.75L12.4647 4.25" stroke="currentColor"/>`,
},
monitor: {
viewBox: "0 0 16 16",
body: `<path d="M4.05559 9.38889H0.500007C0.500007 9.38889 0.500017 8.59298 0.500017 7.61112V2.27778C0.500017 1.29594 0.500102 0.5 0.500102 0.5H13.3889C13.3889 0.5 13.3889 1.29594 13.3889 2.27778V7.61112C13.3889 8.59298 13.3889 9.38889 13.3889 9.38889H9.83336M4.05559 9.38889V11.6111H6.94448H9.83336V9.38889M4.05559 9.38889H9.83336" transform="translate(1.05556 1.94444)" stroke="currentColor"/>`,
},
"workspace-new": {
viewBox: "0 0 16 16",
body: `<path d="M2 10.7578V14.0011H5.24324M13.9991 5.24324V2H10.7559M13.9991 10.7578V14.0011H10.7559M2 5.24324V2H5.24324" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M8 4.5V11.5M4.5 8H11.5" stroke="currentColor" stroke-linejoin="round"/>`,
},
"workspace-isolated": {
viewBox: "0 0 16 16",
body: `<path d="M10.5 10.5V5.5H5.5V10.5H10.5Z" fill="currentColor"/><rect x="2.5" y="2.5" width="11" height="11" stroke="currentColor"/>`,
},
workspace: {
viewBox: "0 0 16 16",
body: `<path d="M2 10.668V14.0013H10.6667M13.9974 10.6667V2H2.66406M13.9974 10.668V14.0013H10.6641M2 10V2H5.33333" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M10.6693 10.6654V5.33203H5.33594V10.6654H10.6693Z" fill="currentColor"/>`,
},
"outline-worktree": {
viewBox: "0 0 16 16",
body: `<path d="M12 3.11133L14.3885 5.49977L12 7.88822M14.5 5.49972H10.058L5.13456 11.8139M14.5 11.6606L8.5 11.6606M5.50012 11.6597H1.5" stroke="currentColor"/>`,
},
"outline-trash": {
viewBox: "0 0 16 16",
body: `<path d="M2.44434 4.22224H13.5554M5.99994 4.22224V2.44446C5.99994 1.95557 5.99992 1.55557 5.99992 1.55557H9.99989C9.99989 1.55557 9.99994 1.95557 9.99994 2.44446V4.22224M6.55545 7.77779L6.7485 11.7778M9.44437 7.77779L9.2513 11.7778M12.1756 6.88891L11.8666 12.7556C11.8168 13.7068 11.7748 14.4445 11.7748 14.4445H4.22511C4.22511 14.4445 4.18392 13.7067 4.13414 12.7556L3.82509 6.88891" stroke="currentColor"/>`,
},
close: {
viewBox: "0 0 20 20",
body: `<path d="M14.4446 5.55566L5.55566 14.4446M5.55566 5.55566L14.4446 14.4446" stroke="currentColor" stroke-linejoin="round"/>`,
},
"xmark-small": {
viewBox: "0 0 16 16",
body: `<path d="M4.25 11.75L11.75 4.25M11.75 11.75L4.25 4.25" stroke="currentColor"/>`,
},
"outline-xmark": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M4.99487 5.70186L7.29297 7.99995L4.99487 10.2981L5.70198 11.0052L8.00008 8.70706L10.2982 11.0052L11.0053 10.2981L8.70718 7.99995L11.0053 5.70186L10.2982 4.99475L8.00008 7.29285L5.70198 4.99475L4.99487 5.70186Z" fill="currentColor"/>`,
},
"outline-chevron-down": {
viewBox: "0 0 16 16",
body: `<path d="M5 6.5L8 9.5L11 6.5" stroke="currentColor"/>`,
},
"outline-dots": {
viewBox: "0 0 16 16",
body: `<path d="M2.5 7.5H3.5V8.5H2.5V7.5Z" stroke="currentColor"/><path d="M7.5 7.5H8.5V8.5H7.5V7.5Z" stroke="currentColor"/><path d="M12.5 7.5H13.5V8.5H12.5V7.5Z" stroke="currentColor"/>`,
},
expand: {
viewBox: "0 0 16 16",
body: `<path d="M8.25 6.17773V1.17773M11.25 4.17773L8.25 1.17773L5.25 4.17773" stroke="currentColor"/><path d="M8.25 9.17773V14.1777M11.25 11.1777L8.25 14.1777L5.25 11.1777" stroke="currentColor"/><path d="M4.25 7.67773H12.25" stroke="currentColor"/>`,
},
filetree: {
viewBox: "0 0 16 16",
body: `<path d="M2.5 1.5V12.2484H6.75M2.5 4.74838H6.75" stroke="currentColor"/><rect x="8.5" y="3.2168" width="6" height="3" fill="none" stroke="currentColor"/><rect x="8.5" y="10.75" width="6" height="3" fill="none" stroke="currentColor"/>`,
},
split: {
viewBox: "0 0 16 16",
body: `<path d="M1 14H15L15 2H1V14Z" stroke="currentColor"/><rect x="3" y="4" width="4" height="8" fill="currentColor" fill-opacity="0.5"/><rect x="9" y="4" width="4" height="8" fill="currentColor" fill-opacity="0.5"/>`,
},
unified: {
viewBox: "0 0 16 16",
body: `<path d="M3.00001 4.00045L12.9998 4L13 6.99955L3 7L3.00001 4.00045Z" fill="currentColor" fill-opacity="0.5"/><path d="M3.0001 9H13L12.9999 12H3L3.0001 9Z" fill="currentColor" fill-opacity="0.5"/><path d="M1 14H15L15 2H1V14Z" stroke="currentColor"/>`,
},
review: {
viewBox: "0 0 20 20",
body: `<path d="M7 14.5H13M7 7.99512H10.0049M10.0049 7.99512H13M10.0049 7.99512V5M10.0049 7.99512V11M18 18V2L2 2L2 18H18Z" stroke="currentColor"/>`,
},
"window-analytics": {
viewBox: "0 0 16 16",
body: `<path d="M14.5 9.8333V13.5H1.5V2.5H7.1667M9.5 2.5V7.5H14.5V2.5H9.5Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>`,
},
"graduation-cap": {
viewBox: "0 0 16 16",
body: `<path d="M12.3327 7.50065V11.0007L7.99935 13.6673L3.66602 11.0007V7.50065M14.3327 9.83398V6.16732M7.99935 2.33398L1.66602 6.00065L7.99935 10.0007L14.3327 6.00065L7.99935 2.33398Z" stroke="currentColor" stroke-linecap="square"/>`,
},
"code-slash": {
viewBox: "0 0 16 16",
body: `<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0812 2.10803L6.55974 14.0809L5.92016 13.8928L9.44161 1.91992L10.0812 2.10803ZM4.13793 4.97275L1.44666 8.00045L4.13793 11.0281L3.63966 11.471L0.554688 8.00045L3.63966 4.52984L4.13793 4.97275ZM12.3617 4.52984L15.4467 8.00045L12.3617 11.471L11.8634 11.0281L14.5547 8.00045L11.8634 4.97275L12.3617 4.52984Z" fill="currentColor"/>`,
},
trash: {
viewBox: "0 0 20 20",
body: `<path d="M4.58342 17.9134L4.58369 17.4134L4.22787 17.5384L4.22766 18.0384H4.58342V17.9134ZM15.4167 17.9134V18.0384H15.7725L15.7723 17.5384L15.4167 17.9134ZM2.08342 3.95508V3.45508H1.58342V3.95508H2.08342V4.45508V3.95508ZM17.9167 4.45508V4.95508H18.4167V4.45508H17.9167V3.95508V4.45508ZM4.16677 4.58008L3.66701 4.5996L4.22816 17.5379L4.72792 17.4934L5.22767 17.4489L4.66652 4.54055L4.16677 4.58008ZM4.58342 18.0384V17.9134H15.4167V18.0384V18.5384H4.58342V18.0384ZM15.4167 17.9134L15.8332 17.5379L16.2498 4.5996L15.7501 4.58008L15.2503 4.56055L14.8337 17.4989L15.4167 17.9134ZM15.8334 4.58008V4.08008H4.16677V4.58008V5.08008H15.8334V4.58008ZM2.08342 4.45508V4.95508H4.16677V4.58008V4.08008H2.08342V4.45508ZM15.8334 4.58008V5.08008H17.9167V4.45508V3.95508H15.8334V4.58008ZM6.83951 4.35149L7.432 4.55047C7.79251 3.47701 8.80699 2.70508 10.0001 2.70508V2.20508V1.70508C8.25392 1.70508 6.77335 2.83539 6.24702 4.15251L6.83951 4.35149ZM10.0001 2.20508V2.70508C11.1932 2.70508 12.2077 3.47701 12.5682 4.55047L13.1607 4.35149L13.7532 4.15251C13.2269 2.83539 11.7463 1.70508 10.0001 1.70508V2.20508Z" fill="currentColor"/>`,
},
"outline-sliders": {
viewBox: "0 0 16 16",
body: `<path d="M11.7779 4.66675H14.4446M11.7779 4.66675C11.7779 5.77132 10.8825 6.66675 9.77789 6.66675C8.67332 6.66675 7.77789 5.77132 7.77789 4.66675M11.7779 4.66675C11.7779 3.56218 10.8825 2.66675 9.77789 2.66675C8.67332 2.66675 7.77789 3.56218 7.77789 4.66675M1.55566 4.66675H7.77789M4.22233 11.3334H1.55566M4.22233 11.3334C4.22233 12.438 5.11776 13.3334 6.22233 13.3334C7.3269 13.3334 8.22233 12.438 8.22233 11.3334M4.22233 11.3334C4.22233 10.2288 5.11776 9.33341 6.22233 9.33341C7.3269 9.33341 8.22233 10.2288 8.22233 11.3334M14.4446 11.3334H8.22233" stroke="currentColor"/>`,
},
"outline-copy": {
viewBox: "0 0 16 16",
body: `<path d="M4.14908 11.0081H1.76282V1.51758H9.1038V2.55588M14.2225 4.99681H6.75397V14.4873H14.2225V4.99681Z" stroke="currentColor"/>`,
},
"arrow-up-right": {
viewBox: "0 0 16 16",
body: `<path d="M11 9.56V5H6.44M11 5L5 11" stroke="currentColor"/>`,
},
"outline-square-arrow": {
viewBox: "0 0 16 16",
body: `<path d="M13.5555 6.66656V2.44434H9.33326M13.5555 2.44434L7.99993 7.99989M13.5555 9.33324V13.5555C13.5555 13.5555 12.7599 13.5555 11.7777 13.5555H2.44438C2.44438 13.5555 2.44438 12.7599 2.44438 11.7777V4.22213C2.44438 3.2399 2.44434 2.44435 2.44434 2.44435H6.66661" stroke="currentColor"/>`,
},
"outline-arrow-to-corner-top-right": {
viewBox: "0 0 16 16",
body: `<path d="M2 8.5V2H14V14H8M5 5.66667H10.3333V11M3.66797 12.333L9.94292 6.05806" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-hexagonal-warning": {
viewBox: "0 0 16 16",
body: `<path d="M10.6667 1.33325H5.33272L1.33334 5.33325L1.33342 10.6917L5.3327 14.691L10.6667 14.6909L14.6911 10.6917V5.33255L10.6667 1.33325Z" stroke="currentColor"/><path d="M8 10.6667H8.00667" stroke="currentColor" stroke-linecap="square"/><path d="M8 7.99992V5.33325" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-share": {
viewBox: "0 0 16 16",
body: `<path d="M13.5554 10.4445V13.5556C13.5554 13.5556 12.7599 13.5556 11.7777 13.5556H4.22211C3.23989 13.5556 2.44434 13.5556 2.44434 13.5556V10.4445M4.88878 5.55557L7.99989 2.44446L11.111 5.55557M7.99989 2.44446L7.99989 9.11112" stroke="currentColor"/>`,
},
"outline-eye": {
viewBox: "0 0 20 20",
body: `<path d="M2.5 10s3.33-5.42 7.5-5.42S17.5 10 17.5 10s-3.33 5.42-7.5 5.42S2.5 10 2.5 10Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/><circle cx="10" cy="10" r="2.5" stroke="currentColor"/>`,
},
"outline-eye-slash": {
viewBox: "0 0 20 20",
body: `<path d="M2.5 10s3.33-5.42 7.5-5.42S17.5 10 17.5 10s-3.33 5.42-7.5 5.42S2.5 10 2.5 10Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/><circle cx="10" cy="10" r="2.5" stroke="currentColor"/><path d="M3 3 17 17" stroke="currentColor" stroke-linecap="round"/>`,
},
refresh: {
viewBox: "0 0 20 20",
body: `<path d="M16.25 7.5A6.5 6.5 0 1 0 16.5 11M16.25 3.5v4h-4" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>`,
},
reset: {
viewBox: "0 0 20 20",
body: `<path d="M5.83333 4.16406L2.5 7.4974L5.83333 10.8307M3.33333 7.4974H17.9167V15.4141H10" stroke="currentColor" stroke-linecap="square"/>`,
},
"outline-reset": {
viewBox: "0 0 20 20",
body: `<path d="M5.83333 4.16406L2.5 7.4974L5.83333 10.8307M3.33333 7.4974H17.9167V15.4141H10" stroke="currentColor" stroke-linecap="square"/>`,
},
"fill-triangle-down": {
viewBox: "0 0 16 16",
body: `<path d="M5.37624 6.75194C5.18184 6.41861 5.42224 6 5.80814 6H10.1921C10.578 6 10.8184 6.41861 10.624 6.75194L8.43203 10.5096C8.23909 10.8404 7.76119 10.8404 7.56825 10.5096L5.37624 6.75194Z" fill="currentColor"/>`,
},
archive: {
viewBox: "0 0 16 16",
body: `<path d="M13.1112 13.5555V14.0555H13.6112V13.5555H13.1112ZM2.889 13.5555H2.389L2.389 14.0555H2.889V13.5555ZM3.38901 5.55546L3.38901 5.05546L2.38901 5.05546L2.38901 5.55546L2.88901 5.55546L3.38901 5.55546ZM14.4446 2.44434H14.9446V1.94434L14.4446 1.94434L14.4446 2.44434ZM14.4446 5.55545L14.4446 6.05545L14.9446 6.05545V5.55545H14.4446ZM1.55566 5.55546L1.05566 5.55545L1.05566 6.05546L1.55566 6.05546L1.55566 5.55546ZM1.5557 2.44436L1.5557 1.94436L1.05571 1.94436L1.0557 2.44435L1.5557 2.44436ZM13.1112 5.55546H12.6112V13.5555H13.1112H13.6112V5.55546H13.1112ZM2.889 13.5555H3.389L3.38901 5.55546L2.88901 5.55546L2.38901 5.55546L2.389 13.5555H2.889ZM14.4446 2.44434H13.9446V5.55545H14.4446H14.9446V2.44434H14.4446ZM1.55566 5.55546L2.05566 5.55547L2.0557 2.44436L1.5557 2.44436L1.0557 2.44435L1.05566 5.55545L1.55566 5.55546ZM6.22234 8.22213V8.72213H9.7779V8.22213V7.72213H6.22234V8.22213ZM13.1112 13.5555V13.0555H2.889V13.5555V14.0555H13.1112V13.5555ZM1.5557 2.44436L1.5557 2.94436L14.4446 2.94434L14.4446 2.44434L14.4446 1.94434L1.5557 1.94436L1.5557 2.44436ZM14.4446 5.55545L14.4446 5.05545L1.55566 5.05546L1.55566 5.55546L1.55566 6.05546L14.4446 6.05545L14.4446 5.55545Z" fill="currentColor"/>`,
},
}
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<IconName>([...Object.keys(additionalIcons), ...Object.keys(icons)] as IconName[]))
return iconNames()
.map((name) => `<symbol id="${symbol(name)}" viewBox="${getIcon(name).viewBox}">${getIcon(name).body}</symbol>`)
.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)