Compare commits

..

5 Commits

Author SHA1 Message Date
Kit Langton 2a8ee9c965 refactor(tui): fade long session branch details 2026-08-08 20:50:04 -04:00
Kit Langton d0bec49ec2 fix(tui): keep session branch metadata subdued 2026-08-08 20:43:05 -04:00
Kit Langton 433fb4711f feat(tui): show session branches in vertical tabs 2026-08-08 20:39:42 -04:00
opencode-agent[bot] e8f215bfbc chore: generate 2026-08-09 00:29:22 +00:00
opencode-agent[bot] 445af9ce70 docs: fix install command rendering (#41340)
Co-authored-by: Kit Langton <7587245+kitlangton@users.noreply.github.com>
2026-08-08 20:28:07 -04:00
26 changed files with 254 additions and 591 deletions
+16 -47
View File
@@ -150,54 +150,24 @@ export interface Page {
readonly render: (input: { readonly data?: Record<string, any> }) => JSX.Element
}
/**
* The host UI's extensible regions. Each region publishes an input (reactive
* props passed to every claim render) and a part vocabulary: the stable ids
* of host furniture that placements may anchor to. Part ids are documented
* API — coarse, few, and kept stable across host refactors.
*/
export interface RegionMap {
readonly app: { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "home.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "prompt.footer": {
readonly input: { readonly sessionID?: string; readonly mode: "normal" | "shell" }
readonly part: "status" | "file"
export interface SlotMap {
readonly app: Readonly<Record<string, never>>
readonly "home.footer": Readonly<Record<string, never>>
readonly "prompt.footer.end": {
readonly sessionID?: string
readonly mode: "normal" | "shell"
}
readonly "session.composer.top": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.content": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "session.composer.top": {
readonly sessionID: string
}
readonly "sidebar.content": {
readonly sessionID: string
}
readonly "sidebar.footer": Readonly<Record<string, never>>
}
export type RegionName = keyof RegionMap
/**
* Where a claim lands in a region's structure. Exactly one of:
* - `at`: the region's edge — `"end"` is the ceremony-free default position
* - `before` / `after`: adjacent to a host part, wherever the host keeps it
* - `replace`: take over one part — or the whole region by naming it.
* Replace is takeover: anything anchored inside the replaced subtree is
* suppressed and recorded, never silently dropped. At the same target the
* last-enabled claim wins; an ancestor takeover beats a descendant one
* regardless of order.
* A placement aimed at a part the host no longer publishes degrades to the
* region's end (after end-edge claims) rather than disappearing.
*
* The `?: never` fields make the variants mutually exclusive: a claim with
* two placement keys is a type error, not a silent priority pick.
*/
export type RegionPlacement<Name extends RegionName = RegionName> =
| { readonly at: "start" | "end"; readonly before?: never; readonly after?: never; readonly replace?: never }
| { readonly before: RegionMap[Name]["part"]; readonly at?: never; readonly after?: never; readonly replace?: never }
| { readonly after: RegionMap[Name]["part"]; readonly at?: never; readonly before?: never; readonly replace?: never }
| {
readonly replace: RegionMap[Name]["part"] | Name
readonly at?: never
readonly before?: never
readonly after?: never
}
export type RegionClaim<Name extends RegionName = RegionName> = RegionPlacement<Name> & {
readonly render: (input: RegionMap[Name]["input"]) => JSX.Element
}
export type SlotName = keyof SlotMap
export type Slot<Name extends SlotName = SlotName> = (props: SlotMap[Name]) => JSX.Element
export interface App {
readonly version: string
@@ -424,8 +394,7 @@ export interface UI {
/** Closes an open tab, or the active tab when omitted, and returns false when no tab matched. */
close(sessionID?: string): boolean
}
/** Claims a place in a region's structure; see RegionPlacement. */
readonly slot: <Name extends RegionName>(region: Name, claim: RegionClaim<Name>) => () => void
readonly slot: <Name extends SlotName>(name: Name, render: Slot<Name>) => () => void
}
export interface Context {
+2 -2
View File
@@ -87,7 +87,7 @@ import { PromptRefProvider, usePromptRef } from "./context/prompt"
import { Config, ConfigProvider, useConfig } from "./config"
import { PluginProvider, usePlugin, type PackageResolver } from "./plugin/context"
import { tuiPluginDirectories } from "./plugin/discovery"
import { PluginRoute, Region } from "./plugin/render"
import { PluginRoute, PluginSlot } from "./plugin/render"
import { CommandPaletteDialog } from "./component/command-palette"
import { COMMAND_PALETTE_COMMAND, Keymap, type KeymapCommand } from "./context/keymap"
@@ -1225,7 +1225,7 @@ function App(props: { pair?: DialogPairCredentials }) {
</Match>
</Switch>
</box>
<Region name="app" input={{}} />
<PluginSlot name="app" input={{}} mode="all" />
</Show>
</box>
</box>
+70 -87
View File
@@ -53,7 +53,7 @@ import { useData } from "../../context/data"
import { useLocation } from "../../context/location"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { abbreviateHome } from "../../runtime"
import { Region } from "../../plugin/render"
import { PluginSlot } from "../../plugin/render"
import type { SessionPending } from "@opencode-ai/schema/session-pending"
export type PromptProps = {
@@ -1631,93 +1631,76 @@ export function Prompt(props: PromptProps) {
/>
</box>
<box width="100%" flexDirection="row" justifyContent="space-between" gap={2}>
<Region
name="prompt.footer"
input={{ sessionID: props.sessionID, mode: store.mode }}
parts={[
{
id: "status",
render: () => (
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show
when={config.animations ?? true}
fallback={<text fg={theme.text.subdued}>[]</text>}
>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg:
store.interrupt > 0
? theme.background.action.primary.default
: theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show when={config.animations ?? true} fallback={<text fg={theme.text.subdued}>[]</text>}>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
),
},
{
id: "file",
render: () => (
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
),
},
]}
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg: store.interrupt > 0 ? theme.background.action.primary.default : theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
</box>
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
<PluginSlot
name="prompt.footer.end"
input={{ sessionID: props.sessionID, mode: store.mode }}
mode="replace"
/>
</box>
</box>
+18 -3
View File
@@ -10,6 +10,7 @@ import {
moveSessionTab,
NEW_SESSION_TAB_TITLE,
sessionTabComplete,
sessionTabDetail,
sessionTabShortcutLabel,
seedSessionTabMotion,
sessionTabOverflowWidth,
@@ -148,10 +149,15 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
const visibleTitleParts = createMemo(() => Locale.graphemes(visibleTitle()))
const titleFades = createMemo(() => stringWidth(title()) >= titleWidth() && titleWidth() > FADE_WIDTH)
const detail = createMemo(() => {
if (tab === NEW_SESSION_TAB) return Locale.takeWidth("Start a new session", titleWidth())
if (tab === NEW_SESSION_TAB) return "Start a new session"
const value = session()
return Locale.takeWidth(projectName(project(), value?.location.directory) ?? "", titleWidth())
const projectLabel = projectName(project(), value?.location.directory) ?? ""
const vcs = value ? data.location.vcs.info(value.location) : undefined
return sessionTabDetail(projectLabel, vcs?.branch.current, vcs?.branch.default)
})
const visibleDetail = createMemo(() => Locale.takeWidth(detail(), titleWidth()))
const visibleDetailParts = createMemo(() => Locale.graphemes(visibleDetail()))
const detailFades = createMemo(() => stringWidth(detail()) >= titleWidth() && titleWidth() > FADE_WIDTH)
const background = createMemo(() => {
if (selected()) return theme.background.action.primary.selected
if (hovered() === tab.sessionID || dragging() === tab.sessionID)
@@ -184,6 +190,11 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
const detailPulseColor = createMemo(() => tint(pulseBackground(), theme.text.default, 0.13))
const detailGlowColor = createMemo(() => tint(pulseBackground(), glowHue(), 0.25))
const detailColor = createMemo(() => tint(theme.text.subdued, pulseBackground(), 0.35))
const detailTextColor = (index: number) => {
if (!detailFades() || index < visibleDetailParts().length - FADE_WIDTH) return detailColor()
const position = index - (visibleDetailParts().length - FADE_WIDTH)
return tint(detailColor(), pulseBackground(), 0.2 + 0.72 * (position / Math.max(1, FADE_WIDTH - 1)))
}
const glows = () => status().glows
const previous = createMemo(() => items()[index() - 1])
const previousStatus = createMemo(() => {
@@ -360,7 +371,11 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
/>
<box zIndex={1} width="100%" flexDirection="row" paddingLeft={numberWidth() + 1} paddingRight={2}>
<text fg={detailColor()} wrapMode="none" selectable={false}>
{detail()}
<Show when={detailFades()} fallback={visibleDetail()}>
<For each={visibleDetailParts()}>
{(character, index) => <span style={{ fg: detailTextColor(index()) }}>{character}</span>}
</For>
</Show>
</text>
</box>
</box>
@@ -13,6 +13,16 @@ export function sessionTabShortcutLabel(index: number) {
return "·"
}
export function sessionTabBranch(current: string | undefined, defaultBranch: string | undefined) {
if (!current || current === defaultBranch) return undefined
return current
}
export function sessionTabDetail(project: string, current: string | undefined, defaultBranch: string | undefined) {
const branch = sessionTabBranch(current, defaultBranch)
return branch && project ? `${project}:${branch}` : (branch ?? project)
}
export type SessionTabHistory = {
entries: readonly string[]
index: number
+15 -4
View File
@@ -157,9 +157,9 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
})
})
// Load lightweight session metadata concurrently so persisted tabs can resolve their project
// labels immediately. Delay the heavier per-tab data so the visible session keeps the first
// connection slots and switches still render from a warm cache.
// Load lightweight session and location metadata concurrently so persisted tabs can resolve
// their project and branch labels. Delay the heavier per-tab data so the visible session keeps
// the first connection slots and switches still render from a warm cache.
const openTabSessions = createMemo(() =>
state()
.tabs.map((tab) => tab.sessionID)
@@ -171,8 +171,19 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
if (client.connection.status() !== "connected") return
const sessionIDs = openTabSessions()
if (sessionIDs === "") return
void Promise.allSettled(sessionIDs.split("\n").map((sessionID) => data.session.sync(sessionID)))
let stale = false
void (async () => {
await Promise.allSettled(sessionIDs.split("\n").map((sessionID) => data.session.sync(sessionID)))
if (stale) return
const locations = new Map(
sessionIDs
.split("\n")
.map((sessionID) => data.session.get(sessionID)?.location)
.filter((location) => location !== undefined)
.map((location) => [`${location.directory}\n${location.workspaceID ?? ""}`, location]),
)
await Promise.allSettled(Array.from(locations.values(), (location) => data.location.vcs.sync(location)))
})()
const timer = setTimeout(async () => {
const sessions = state()
.tabs.map((tab) => tab.sessionID)
@@ -62,8 +62,6 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.home-footer",
setup(context) {
// Root takeover: an external plugin replacing home.footer wins (last-
// enabled) and this builtin shows as suppressed, not silently gone.
context.ui.slot("home.footer", { replace: "home.footer", render: () => <View context={context} /> })
context.ui.slot("home.footer", () => <View context={context} />)
},
})
@@ -85,9 +85,8 @@ export function PromptFooter(props: { context: Plugin.Context; sessionID?: strin
export default Plugin.define({
id: "opencode.prompt-footer",
setup(context) {
context.ui.slot("prompt.footer", {
at: "end",
render: (props) => <PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />,
})
context.ui.slot("prompt.footer.end", (props) => (
<PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />
))
},
})
@@ -44,9 +44,6 @@ export function SidebarContext(props: { context: Plugin.Context; sessionID: stri
export default Plugin.define({
id: "internal:sidebar-context",
setup(context) {
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <SidebarContext context={context} sessionID={props.sessionID} />,
})
context.ui.slot("sidebar.content", (props) => <SidebarContext context={context} sessionID={props.sessionID} />)
},
})
@@ -19,6 +19,6 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.sidebar-footer",
setup(context) {
context.ui.slot("sidebar.footer", { replace: "sidebar.footer", render: () => <View context={context} /> })
context.ui.slot("sidebar.footer", () => <View context={context} />)
},
})
@@ -73,9 +73,6 @@ function View(props: { context: Plugin.Context; sessionID: string }) {
export default Plugin.define({
id: "internal:sidebar-mcp",
setup(context) {
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <View context={context} sessionID={props.sessionID} />,
})
context.ui.slot("sidebar.content", (props) => <View context={context} sessionID={props.sessionID} />)
},
})
@@ -1090,6 +1090,6 @@ export default Plugin.define({
name: ROUTE,
render: () => <DiffViewer context={context} />,
})
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
context.ui.slot("app", () => <Commands context={context} />)
},
})
@@ -85,6 +85,6 @@ function Commands(props: { context: Plugin.Context }) {
export default Plugin.define({
id,
setup(context) {
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
context.ui.slot("app", () => <Commands context={context} />)
},
})
@@ -137,6 +137,6 @@ export default Plugin.define({
return <StorybookIndex context={context} />
},
})
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
context.ui.slot("app", () => <Commands context={context} />)
},
})
+8 -47
View File
@@ -1,26 +1,6 @@
import { PluginContextProvider } from "@opencode-ai/plugin/tui"
import type { JSX } from "solid-js"
import type {
Context,
Dialog,
Page,
RegionClaim,
RegionMap,
RegionName,
Toast,
} from "@opencode-ai/plugin/tui/context"
import type { Placement } from "./structure"
// Region inputs erased to their union: the registry stores one render shape
// regardless of which region a claim targets.
export type RegionRender = (input: RegionMap[RegionName]["input"]) => JSX.Element
// A registered claim as stored by the plugin provider's registry.
export type SlotClaim = {
readonly region: RegionName
readonly placement: Placement
readonly render: RegionRender
}
import type { Context, Dialog, Page, Slot, SlotMap, Toast } from "@opencode-ai/plugin/tui/context"
import { infoStringToFiletype, type MarkdownCodeBlockRenderer } from "@opentui/core"
import { useRenderer } from "@opentui/solid"
import { useClient } from "../context/client"
@@ -49,14 +29,12 @@ export type Dispose = () => Promise<void>
export type Registry = {
has(kind: "routes" | "slots" | "markdown", name: string): boolean
set(kind: "routes", name: string, page: Page): void
set(kind: "slots", name: string, claim: SlotClaim): void
set(kind: "slots", name: string, slot: Slot): void
set(kind: "markdown", name: string, render: MarkdownCodeBlockRenderer): void
remove(kind: "routes" | "slots" | "markdown", name: string): void
active(): boolean
}
// The host services a plugin context adapts. Collected once by the provider
// (hooks must run during component setup) and shared by every activation.
export function usePluginHost() {
@@ -92,7 +70,6 @@ export function createPluginContext(input: {
}): Context {
const host = input.host
let context: Context
let claims = 0
// Every dialog and registered render is wrapped so plugin components can
// reach their own context through usePlugin().
const provide = (render: () => JSX.Element) => (
@@ -207,28 +184,12 @@ export function createPluginContext(input: {
return true
},
},
slot(name: RegionName, value: RegionClaim) {
// Keys are counter-suffixed so one plugin may claim several places
// in the same region; order within the plugin is registration order.
const key = `${name}#${claims++}`
// Rebuilt field-by-field rather than rest-spread so malformed input
// from untyped plugins normalizes to exactly one placement key — a
// claim carrying two keys would match twice in the resolver.
const placement: Placement =
value.at !== undefined
? { at: value.at }
: value.before !== undefined
? { before: value.before }
: value.after !== undefined
? { after: value.after }
: { replace: value.replace }
input.registry.set("slots", key, {
region: name,
placement,
// The registration map erases the region-specific input type.
render: (slotInput) => provide(() => (value.render as RegionRender)(slotInput)),
})
return registration("slots", key)
slot(name, render) {
if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
// The registration map erases the slot-specific input type.
input.registry.set("slots", name, ((slotInput: SlotMap[typeof name]) =>
provide(() => render(slotInput))) as Slot)
return registration("slots", name)
},
},
}
+22 -29
View File
@@ -14,16 +14,15 @@ import {
import path from "path"
import { stat } from "fs/promises"
import { fileURLToPath, pathToFileURL } from "url"
import type { Page } from "@opencode-ai/plugin/tui/context"
import type { Claim } from "./structure"
import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
import type { Page, Slot, SlotName } from "@opencode-ai/plugin/tui/context"
import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
import { isDeepEqual } from "remeda"
import "#runtime-plugin-support"
import { useConfig } from "../config"
import { useTuiLifecycle } from "../context/runtime"
import { errorMessage } from "../util/error"
import { builtins } from "./builtins"
import { createPluginContext, usePluginHost, type Dispose, type RegionRender, type SlotClaim } from "./api"
import { createPluginContext, usePluginHost, type Dispose } from "./api"
import { createSourceWatcher } from "./watch"
import { discoverTuiPlugins, freshSpecifier, localSource } from "./discovery"
@@ -47,7 +46,9 @@ type Value = {
readonly list: () => ReadonlyArray<State>
readonly registered: () => ReadonlyArray<RegisteredPlugin>
readonly route: (id: string, name: string) => Page["render"] | undefined
readonly claims: (region: string) => ReadonlyArray<Claim<RegionRender>>
readonly slot: <Name extends SlotName>(
name: Name,
) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
readonly markdown: () => MarkdownOptions["renderNode"]
readonly activate: (id: string) => Promise<boolean>
readonly deactivate: (id: string) => Promise<boolean>
@@ -61,7 +62,7 @@ type Registration = {
options?: Readonly<Record<string, any>>
active: boolean
routes: Record<string, Page>
slots: Record<string, SlotClaim>
slots: Record<string, Slot>
markdown: Record<string, MarkdownCodeBlockRenderer>
cleanups: Dispose[]
}
@@ -118,7 +119,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
owned,
registry: {
has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | SlotClaim | MarkdownCodeBlockRenderer) =>
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | Slot | MarkdownCodeBlockRenderer) =>
setStore("registrations", id, kind, name, () => value),
remove: (kind, name) =>
setStore(
@@ -386,7 +387,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
host.toast.show({ variant: "error", title: "Plugin", message: `${state.target}: ${state.error}` })
setStore("states", reconcileStore(states))
}
const slotItems = new WeakMap<RegionRender, Claim<RegionRender>>()
const slotItems = new WeakMap<Slot, { readonly id: string; readonly render: Slot }>()
createEffect(
on(
() => JSON.stringify(config.data.plugins ?? []),
@@ -435,27 +436,19 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
active: plugin.active,
})),
route: (id, name) => store.registrations[id]?.routes[name]?.render,
// Claims come back in enable order: registration-store key order
// across plugins (generations preserve key positions in place), then
// registration order within one plugin. The resolver's last-wins
// rules depend on it.
claims: (region) =>
Object.entries(store.registrations).flatMap(([id, registration]) =>
Object.entries(registration.active ? registration.slots : {}).flatMap(([key, slot]) => {
if (slot.region !== region) return []
// <For> diffs rows by reference; a stable claim per render
// function keeps untouched plugins' slot rows (and their
// state) alive across other plugins' reloads.
const cached = slotItems.get(slot.render)
if (cached) return [cached]
// Placements are immutable once registered; unwrap the store
// proxy so the resolver's `in` checks hit plain objects
// instead of subscribing tracked scopes to every key probe.
const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
slotItems.set(slot.render, item)
return [item]
}),
),
slot: (name) =>
Object.entries(store.registrations).flatMap(([id, registration]) => {
const render = registration.active ? registration.slots[name] : undefined
if (!render) return []
// <For> diffs rows by reference; a stable wrapper per render
// function keeps untouched plugins' slot rows (and their state)
// alive across other plugins' reloads.
const cached = slotItems.get(render)
if (cached) return [cached]
const item = { id, render }
slotItems.set(render, item)
return [item]
}),
markdown,
// Manual dialog toggles join the same chain as reconciles so a
// toggle mid-reload cannot mix registrations across generations.
+22 -62
View File
@@ -9,9 +9,7 @@ import {
type JSX,
type ParentProps,
} from "solid-js"
import type { RegionMap, RegionName } from "@opencode-ai/plugin/tui/context"
import type { RegionRender } from "./api"
import { resolveStructure, type Entry, type Part } from "./structure"
import type { SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
import { useRoute } from "../context/route"
import { useToast } from "../ui/toast"
import { errorMessage } from "../util/error"
@@ -66,69 +64,31 @@ export function PluginRoute(props: { readonly fallback: (id: string, name: strin
)
}
type HostRender = () => JSX.Element
// One extensible area of the host UI: the host's parts plus every active
// plugin claim, resolved into one ordered child list. Placement policy —
// takeover suppression, last-enabled-wins, missing-anchor degradation —
// lives in resolveStructure; this component only renders the result.
export function Region<Name extends RegionName>(props: {
export function PluginSlot<Name extends SlotName>(props: {
readonly name: Name
readonly input: RegionMap[Name]["input"]
readonly parts?: ReadonlyArray<Part<HostRender, RegionMap[Name]["part"]>>
readonly input: SlotMap[Name]
readonly mode: "all" | "replace"
}) {
const plugins = usePlugin()
// resolveStructure builds fresh entry objects each run, but <For> diffs
// rows by reference: cache entries so untouched rows (and the plugin
// state inside them) survive unrelated claim changes. Part entries key on
// their documented-stable id — render-function identity would break if
// the compiled parts prop ever rebuilt its closures. Claim entries key on
// the render function (weakly, so hot-reloaded generations collect).
const partEntries = new Map<string, Entry<HostRender, RegionRender>>()
const claimEntries = new WeakMap<RegionRender, Entry<HostRender, RegionRender>>()
const entries = createMemo(
() =>
resolveStructure<HostRender, RegionRender>({
region: props.name,
parts: props.parts ?? [],
claims: plugins.claims(props.name),
}).entries.map((entry) => {
if (entry.kind === "part") {
const cached = partEntries.get(entry.id)
if (cached) return cached
partEntries.set(entry.id, entry)
return entry
}
const cached = claimEntries.get(entry.claim.render)
if (cached) return cached
claimEntries.set(entry.claim.render, entry)
return entry
}),
[] as ReadonlyArray<Entry<HostRender, RegionRender>>,
// Rows are reference-stable, so an elementwise comparison makes a claim
// change in some other region a complete no-op for this one.
{ equals: (a, b) => a.length === b.length && a.every((entry, index) => entry === b[index]) },
)
const renderers = createMemo(() => {
const items = plugins.slot(props.name)
if (props.mode === "replace") return items.slice(-1)
return items
})
return (
<For each={entries()}>
{(entry) =>
// A row's entry object is cached, so its kind never changes within
// the row's lifetime — a plain branch is safe here.
entry.kind === "part" ? (
entry.render()
) : (
<PluginBoundary id={entry.claim.plugin} where={`region ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(entry.claim.render, mergeProps(() => props.input) as RegionMap[RegionName]["input"])
}
</PluginBoundary>
)
}
<For each={renderers()}>
{(item) => (
<PluginBoundary id={item.id} where={`slot ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare item.render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(item.render, mergeProps(() => props.input) as SlotMap[Name])
}
</PluginBoundary>
)}
</For>
)
}
-125
View File
@@ -1,125 +0,0 @@
// Pure resolution of a region's structure: the host's part tree plus plugin
// claims in, an ordered render list plus suppressions out. No solid, no I/O —
// every policy rule (takeover, hierarchy-beats-timeline, last-enabled-wins,
// missing-anchor degradation) is testable as a data transform.
// Mirrors the public RegionPlacement type (plugin package) with part ids
// erased to strings so the resolver stays independent of the region map.
// Keep the two unions' variants in sync.
export type Placement =
| { readonly at: "start" | "end" }
| { readonly before: string }
| { readonly after: string }
| { readonly replace: string }
// One plugin's registered slot, in enable order within the claims array.
export type Claim<Render> = {
readonly key: string
readonly plugin: string
readonly placement: Placement
readonly render: Render
}
// Host furniture: a leaf renders, a container groups — never both. Part ids
// are the stable anchor vocabulary and must be unique within a region.
export type Part<Render, Id extends string = string> =
| { readonly id: Id; readonly render: Render; readonly parts?: never }
| { readonly id: Id; readonly parts: ReadonlyArray<Part<Render, Id>>; readonly render?: never }
export type Entry<PartRender, ClaimRender> =
| { readonly kind: "part"; readonly id: string; readonly render: PartRender }
| { readonly kind: "claim"; readonly claim: Claim<ClaimRender> }
export function resolveStructure<PartRender extends {}, ClaimRender>(input: {
readonly region: string
readonly parts: ReadonlyArray<Part<PartRender>>
readonly claims: ReadonlyArray<Claim<ClaimRender>>
}): {
readonly entries: ReadonlyArray<Entry<PartRender, ClaimRender>>
readonly suppressed: ReadonlyArray<{ readonly claim: Claim<ClaimRender>; readonly by: Claim<ClaimRender> }>
readonly degraded: ReadonlyArray<Claim<ClaimRender>>
} {
// Root takeover: the region's content is the winning claim, full stop.
// Every other claim — including edge-anchored ones — is suppressed, so a
// theme can never be silently decorated by chips it didn't plan for.
const takeover = input.claims
.filter((claim) => "replace" in claim.placement && claim.placement.replace === input.region)
.at(-1)
if (takeover)
return {
entries: [{ kind: "claim", claim: takeover }],
suppressed: input.claims.filter((claim) => claim !== takeover).map((claim) => ({ claim, by: takeover })),
degraded: [],
}
const known = new Set<string>()
const register = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
known.add(part.id)
if (part.parts !== undefined) register(part.parts)
}
}
register(input.parts)
const entries: Entry<PartRender, ClaimRender>[] = []
const suppressed: { claim: Claim<ClaimRender>; by: Claim<ClaimRender> }[] = []
// A container takeover orphans everything anchored to (or replacing) the
// parts inside it. Recorded so the host can surface it (plugins dialog,
// in a follow-up) — never silently dropped.
const suppressSubtree = (parts: ReadonlyArray<Part<PartRender>>, by: Claim<ClaimRender>) => {
for (const part of parts) {
for (const claim of input.claims) if (anchor(claim.placement) === part.id) suppressed.push({ claim, by })
if (part.parts !== undefined) suppressSubtree(part.parts, by)
}
}
const walk = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
for (const claim of input.claims)
if ("before" in claim.placement && claim.placement.before === part.id) entries.push({ kind: "claim", claim })
// Replacing keeps the part's position: before/after anchors on the
// replaced id stay valid, only the content (and subtree) changes hands.
const replacers = input.claims.filter(
(claim) => "replace" in claim.placement && claim.placement.replace === part.id,
)
const winner = replacers.at(-1)
if (winner) {
for (const loser of replacers.slice(0, -1)) suppressed.push({ claim: loser, by: winner })
entries.push({ kind: "claim", claim: winner })
// Hierarchy beats timeline: claims into the subtree lose to the
// container's winner no matter when they were enabled.
if (part.parts !== undefined) suppressSubtree(part.parts, winner)
}
if (!winner && part.parts !== undefined) walk(part.parts)
if (!winner && part.render !== undefined) entries.push({ kind: "part", id: part.id, render: part.render })
for (const claim of input.claims)
if ("after" in claim.placement && claim.placement.after === part.id) entries.push({ kind: "claim", claim })
}
}
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "start") entries.push({ kind: "claim", claim })
walk(input.parts)
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "end") entries.push({ kind: "claim", claim })
// A claim aimed at a part the host no longer publishes degrades to the
// region's end rather than vanishing: an anchor rename must never silently
// cost a plugin its render. Degraded claims land after end-edge claims,
// in enable order.
const degraded = input.claims.filter((claim) => {
const id = anchor(claim.placement)
return id !== undefined && !known.has(id)
})
for (const claim of degraded) entries.push({ kind: "claim", claim })
return { entries, suppressed, degraded }
}
function anchor(placement: Placement) {
if ("before" in placement) return placement.before
if ("after" in placement) return placement.after
if ("replace" in placement) return placement.replace
return undefined
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { useEditorContext } from "../context/editor"
import { useData } from "../context/data"
import { useLocation } from "../context/location"
import { FormPrompt } from "./session/form"
import { Region } from "../plugin/render"
import { PluginSlot } from "../plugin/render"
import { useTerminalDimensions } from "@opentui/solid"
let once = false
@@ -91,7 +91,7 @@ export function Home() {
<box flexGrow={1} minHeight={0} />
</box>
<box width="100%" flexShrink={0}>
<Region name="home.footer" input={{}} />
<PluginSlot name="home.footer" input={{}} mode="replace" />
</box>
<Show when={forms()[0]?.id} keyed>
{(_) => {
+2 -2
View File
@@ -82,7 +82,7 @@ import { collapseToolOutput } from "../../util/collapse-tool-output"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { usePathFormatter } from "../../context/path-format"
import { useLocation } from "../../context/location"
import { Region } from "../../plugin/render"
import { PluginSlot } from "../../plugin/render"
import { usePlugin } from "../../plugin/context"
import {
cacheReuseDrop,
@@ -1072,7 +1072,7 @@ export function Session() {
<Show when={!composer.open && !disabled() && queuedPrompts().length > 0}>
<QueuedPromptDock prompts={queuedPrompts()} onOpen={openQueuedPrompts} />
</Show>
<Region name="session.composer.top" input={{ sessionID: route.sessionID }} />
<PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
<Composer
sessionID={route.sessionID}
open={composer.open || (!!session()?.parentID && forms().length === 0)}
+3 -3
View File
@@ -2,7 +2,7 @@ import { useData } from "../../context/data"
import { createMemo, Show } from "solid-js"
import { useTheme } from "../../context/theme"
import { useConfig } from "../../config"
import { Region } from "../../plugin/render"
import { PluginSlot } from "../../plugin/render"
import { withTimestampedFallback } from "@opencode-ai/util/session-title-fallback"
import { getScrollAcceleration } from "../../util/scroll"
@@ -52,12 +52,12 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
<text fg={theme.text.subdued}>{session()!.location.workspaceID}</text>
</Show>
</box>
<Region name="sidebar.content" input={{ sessionID: props.sessionID }} />
<PluginSlot name="sidebar.content" input={{ sessionID: props.sessionID }} mode="all" />
</box>
</scrollbox>
<box flexShrink={0} gap={1} paddingTop={1}>
<Region name="sidebar.footer" input={{}} />
<PluginSlot name="sidebar.footer" input={{}} mode="replace" />
</box>
</box>
</Show>
@@ -8,8 +8,8 @@ import type {
KeymapCommand,
KeymapLayer,
Page,
RegionClaim,
Route,
Slot,
} from "@opencode-ai/plugin/tui/context"
import { ThemeProvider, useThemes } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
@@ -142,7 +142,7 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
const commands = new Map<string, KeymapCommand>()
let current = initialRoute ?? startRoute
let renderDiff: Page["render"] | undefined
let renderCommands: RegionClaim<"app">["render"] | undefined
let renderCommands: Slot | undefined
let vcsDiffInput: unknown
const config = createTuiResolvedConfig()
const transport = createFetch((url) => {
@@ -199,8 +199,8 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
},
current: () => current,
},
slot(_name: string, claim: RegionClaim<"app">) {
renderCommands = claim.render
slot(_name: string, render: Slot) {
renderCommands = render
return () => {}
},
},
@@ -11,11 +11,25 @@ import {
reopenSessionTab,
seedSessionTabMotion,
sessionTabComplete,
sessionTabBranch,
sessionTabDetail,
sessionTabOverflowWidth,
sessionTabShortcutLabel,
} from "../../src/context/session-tabs-model"
describe("session tabs", () => {
test("shows only non-default session branches", () => {
expect(sessionTabBranch("main", "main")).toBeUndefined()
expect(sessionTabBranch("feature/sidebar", "main")).toBe("feature/sidebar")
expect(sessionTabBranch("feature/sidebar", undefined)).toBe("feature/sidebar")
expect(sessionTabBranch(undefined, "main")).toBeUndefined()
})
test("separates the project and branch with a colon", () => {
expect(sessionTabDetail("opencode", "feature/sidebar", "main")).toBe("opencode:feature/sidebar")
expect(sessionTabDetail("opencode", "main", "main")).toBe("opencode")
})
test("labels direct shortcut tabs and marks unbound tabs with a dot", () => {
expect(Array.from({ length: 12 }, (_, index) => sessionTabShortcutLabel(index))).toEqual([
"1",
@@ -27,7 +27,14 @@ async function wait(fn: () => boolean | Promise<boolean>, timeout = 2_000) {
async function renderSessionTabs(
initialSessionID: string,
options?: { state?: string; title?: string; home?: boolean; persisted?: string[]; sessionGate?: Promise<void> },
options?: {
state?: string
title?: string
home?: boolean
persisted?: string[]
sessionGate?: Promise<void>
sessionDirectories?: Record<string, string>
},
) {
const temporary = options?.state ? undefined : await tmpdir()
const state = options?.state ?? temporary!.path
@@ -44,7 +51,16 @@ async function renderSessionTabs(
}
const events = createEventStream()
const sessions: string[] = []
const vcsLocations: string[] = []
const calls = createFetch(async (url) => {
if (url.pathname === "/api/vcs") {
const requested = url.searchParams.get("location[directory]") ?? directory
vcsLocations.push(requested)
return json({
location: { directory: requested },
data: { branch: { current: "main", default: "main" } },
})
}
const sessionID = url.pathname.match(/^\/api\/session\/([^/]+)$/)?.[1]
if (!sessionID) return undefined
sessions.push(sessionID)
@@ -54,7 +70,7 @@ async function renderSessionTabs(
id: sessionID,
title: sessionID === initialSessionID ? options?.title : undefined,
projectID: "project",
location: { directory },
location: { directory: options?.sessionDirectories?.[sessionID] ?? directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 0, updated: 0 },
@@ -104,6 +120,7 @@ async function renderSessionTabs(
route,
data,
sessions,
vcsLocations,
state,
emit: (event: OpenCodeEvent) => events.emit({ ...event, location: { directory } }),
async destroy() {
@@ -134,6 +151,21 @@ test("loads persisted tab metadata concurrently on connect", async () => {
}
})
test("loads VCS metadata for each persisted tab location", async () => {
const other = `${directory}/other-worktree`
const setup = await renderSessionTabs("first", {
home: true,
persisted: ["first", "second"],
sessionDirectories: { second: other },
})
try {
await wait(() => setup.vcsLocations.includes(other))
} finally {
await setup.destroy()
}
})
test("stores session tabs for the current working directory by default", async () => {
const setup = await renderSessionTabs("first")
+2 -5
View File
@@ -140,11 +140,8 @@ import { appendFile } from "node:fs/promises"
export default {
id: "test.crash",
setup: async (context: any) => {
context.ui.slot("home.footer", {
replace: "home.footer",
render: () => {
throw new Error("boom")
},
context.ui.slot("home.footer", () => {
throw new Error("boom")
})
await appendFile(${JSON.stringify(markerCrash)}, "setup\\n")
},
-148
View File
@@ -1,148 +0,0 @@
import { expect, test } from "bun:test"
import type { RegionClaim } from "@opencode-ai/plugin/tui/context"
import { resolveStructure, type Claim, type Part, type Placement } from "../src/plugin/structure"
// Type-level canaries, checked by `bun typecheck`: the placement sum and the
// part union are exclusive — nonsense shapes must not compile.
export const canaries = () => {
const claims: RegionClaim<"prompt.footer">[] = []
claims.push({ at: "end", render: () => null })
// @ts-expect-error two placement keys cannot coexist
claims.push({ at: "end", before: "status", render: () => null })
// @ts-expect-error replace does not combine with an anchor
claims.push({ replace: "status", after: "file", render: () => null })
// @ts-expect-error a part is a leaf or a container, never both
const hybrid: Part<string> = { id: "x", render: "x", parts: [] }
return { claims, hybrid }
}
// The resolver is generic over render types; strings make ordering
// assertions read as layouts.
function claim(plugin: string, placement: Placement, render?: string): Claim<string> {
return { key: `${plugin}/${render ?? JSON.stringify(placement)}`, plugin, placement, render: render ?? plugin }
}
function layout(result: ReturnType<typeof resolveStructure<string, string>>) {
return result.entries.map((entry) => (entry.kind === "part" ? entry.id : entry.claim.render))
}
const footer: Part<string>[] = [
{ id: "status", render: "status" },
{ id: "file", render: "file" },
]
const tree: Part<string>[] = [
{ id: "left", parts: [{ id: "mode", render: "mode" }] },
{
id: "right",
parts: [
{ id: "directory", render: "directory" },
{ id: "model", render: "model" },
{ id: "tokens", render: "tokens" },
],
},
]
test("no claims renders the host parts in order", () => {
const result = resolveStructure<string, string>({ region: "prompt.footer", parts: footer, claims: [] })
expect(layout(result)).toEqual(["status", "file"])
expect(result.suppressed).toEqual([])
expect(result.degraded).toEqual([])
})
test("edge claims land at the region's edges, several in enable order", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [
claim("a", { at: "end" }, "a1"),
claim("b", { at: "start" }, "b1"),
claim("a", { at: "end" }, "a2"),
],
})
expect(layout(result)).toEqual(["b1", "status", "file", "a1", "a2"])
})
test("before and after anchor to a part, wherever the host keeps it", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "status" }, "chip"), claim("b", { before: "status" }, "vim")],
})
expect(layout(result)).toEqual(["vim", "status", "chip", "file"])
})
test("a missing anchor degrades to the end instead of disappearing", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "tokens" }, "chip")],
})
expect(layout(result)).toEqual(["status", "file", "chip"])
expect(result.degraded.map((item) => item.render)).toEqual(["chip"])
})
test("replacing a part swaps content but keeps the position and its anchors", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { replace: "status" }, "fancy-status"), claim("b", { after: "status" }, "chip")],
})
expect(layout(result)).toEqual(["fancy-status", "chip", "file"])
expect(result.suppressed).toEqual([])
})
test("same target: the last-enabled claim wins and the loser is recorded", () => {
const first = claim("a", { replace: "status" }, "first")
const second = claim("b", { replace: "status" }, "second")
const result = resolveStructure({ region: "prompt.footer", parts: footer, claims: [first, second] })
expect(layout(result)).toEqual(["second", "file"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("container takeover suppresses everything anchored in the subtree", () => {
const takeover = claim("theme", { replace: "right" }, "my-right")
const chip = claim("pr", { after: "model" }, "chip")
const inner = claim("x", { replace: "tokens" }, "cost")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [takeover, chip, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([
{ claim: chip, by: takeover },
{ claim: inner, by: takeover },
])
})
test("hierarchy beats timeline: an ancestor takeover wins over a later descendant claim", () => {
// The descendant replace was enabled after the container takeover; the
// container still wins because its target contains the descendant's.
const inner = claim("x", { replace: "model" }, "swap-model")
const outer = claim("theme", { replace: "right" }, "my-right")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [outer, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([{ claim: inner, by: outer }])
})
test("root takeover: nothing original survives, all other claims suppressed", () => {
const theme = claim("powerline", { replace: "prompt.footer" }, "powerline")
const chip = claim("pr", { at: "end" }, "chip")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [chip, theme] })
expect(layout(result)).toEqual(["powerline"])
expect(result.suppressed).toEqual([{ claim: chip, by: theme }])
})
test("root takeover at the same node: last enabled wins", () => {
const first = claim("a", { replace: "home.footer" }, "first")
const second = claim("b", { replace: "home.footer" }, "second")
const result = resolveStructure<string, string>({ region: "home.footer", parts: [], claims: [first, second] })
expect(layout(result)).toEqual(["second"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("containers flatten in order and anchors on a container wrap its whole span", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: tree,
claims: [claim("a", { before: "right" }, "divider"), claim("b", { after: "right" }, "clock")],
})
expect(layout(result)).toEqual(["mode", "divider", "directory", "model", "tokens", "clock"])
})