Bläddra i källkod

feat(tui): region structure for plugin slot placement

Kit Langton 2 dagar sedan
förälder
incheckning
f4241c49b4

+ 59 - 1
packages/plugin/src/tui/context.ts

@@ -169,6 +169,55 @@ export interface SlotMap {
 export type SlotName = keyof SlotMap
 export type Slot<Name extends SlotName = SlotName> = (props: SlotMap[Name]) => 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"
+  }
+  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 }
+}
+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 interface App {
   readonly version: string
   readonly channel: string
@@ -394,7 +443,16 @@ export interface UI {
     /** Closes an open tab, or the active tab when omitted, and returns false when no tab matched. */
     close(sessionID?: string): boolean
   }
-  readonly slot: <Name extends SlotName>(name: Name, render: Slot<Name>) => () => void
+  readonly slot: {
+    /**
+     * @deprecated Position-encoded slot names are the legacy surface; use
+     * the region + placement form. `slot("prompt.footer.end", render)` is
+     * `slot("prompt.footer", { at: "end", render })`.
+     */
+    <Name extends SlotName>(name: Name, render: Slot<Name>): () => void
+    /** Claims a place in a region's structure; see RegionPlacement. */
+    <Name extends RegionName>(region: Name, claim: RegionClaim<Name>): () => void
+  }
 }
 
 export interface Context {

+ 2 - 2
packages/tui/src/app.tsx

@@ -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, PluginSlot } from "./plugin/render"
+import { PluginRoute, Region } from "./plugin/render"
 import { CommandPaletteDialog } from "./component/command-palette"
 import { COMMAND_PALETTE_COMMAND, Keymap, type KeymapCommand } from "./context/keymap"
 
@@ -1233,7 +1233,7 @@ function App(props: { pair?: DialogPairCredentials }) {
                 </Match>
               </Switch>
             </box>
-            <PluginSlot name="app" input={{}} mode="all" />
+            <Region name="app" input={{}} />
           </Show>
         </box>
       </box>

+ 87 - 70
packages/tui/src/component/prompt/index.tsx

@@ -52,7 +52,7 @@ import { useData } from "../../context/data"
 import { useLocation } from "../../context/location"
 import { Keymap, type KeymapCommand } from "../../context/keymap"
 import { abbreviateHome } from "../../runtime"
-import { PluginSlot } from "../../plugin/render"
+import { Region } from "../../plugin/render"
 import type { SessionPending } from "@opencode-ai/schema/session-pending"
 
 export type PromptProps = {
@@ -1592,76 +1592,93 @@ export function Prompt(props: PromptProps) {
           />
         </box>
         <box width="100%" flexDirection="row" justifyContent="space-between" gap={2}>
-          <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>
-          <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"
+          <Region
+            name="prompt.footer"
             input={{ sessionID: props.sessionID, mode: store.mode }}
-            mode="replace"
+            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>
+                ),
+              },
+              {
+                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>
+                ),
+              },
+            ]}
           />
         </box>
       </box>

+ 75 - 8
packages/tui/src/plugin/api.tsx

@@ -1,6 +1,24 @@
 import { PluginContextProvider } from "@opencode-ai/plugin/tui"
 import type { JSX } from "solid-js"
-import type { Context, Dialog, Page, Slot, SlotMap, Toast } from "@opencode-ai/plugin/tui/context"
+import type {
+  Context,
+  Dialog,
+  Page,
+  RegionClaim,
+  RegionName,
+  Slot,
+  SlotMap,
+  SlotName,
+  Toast,
+} from "@opencode-ai/plugin/tui/context"
+import type { Placement } from "./structure"
+
+// A registered claim as stored by the plugin provider's registry.
+export type SlotClaim = {
+  readonly region: RegionName
+  readonly placement: Placement
+  readonly render: Slot
+}
 import { infoStringToFiletype, type MarkdownCodeBlockRenderer } from "@opentui/core"
 import { useRenderer } from "@opentui/solid"
 import { useClient } from "../context/client"
@@ -29,12 +47,27 @@ 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, slot: Slot): void
+  set(kind: "slots", name: string, claim: SlotClaim): void
   set(kind: "markdown", name: string, render: MarkdownCodeBlockRenderer): void
   remove(kind: "routes" | "slots" | "markdown", name: string): void
   active(): boolean
 }
 
+// Position-encoded legacy slot names map onto the region model. Append
+// slots become end-edge claims. Host-declared "replace" slots on partless
+// regions become root takeovers, reproducing their old last-registrant-wins
+// semantics exactly. One deliberate change: "prompt.footer.end" was also
+// last-registrant-wins, but maps to an end-edge claim — chips from several
+// plugins now coexist instead of silently shadowing each other.
+const legacySlots: Record<SlotName, { readonly region: RegionName; readonly placement: Placement }> = {
+  app: { region: "app", placement: { at: "end" } },
+  "home.footer": { region: "home.footer", placement: { replace: "home.footer" } },
+  "prompt.footer.end": { region: "prompt.footer", placement: { at: "end" } },
+  "session.composer.top": { region: "session.composer.top", placement: { at: "end" } },
+  "sidebar.content": { region: "sidebar.content", placement: { at: "end" } },
+  "sidebar.footer": { region: "sidebar.footer", placement: { replace: "sidebar.footer" } },
+}
+
 // 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() {
@@ -70,6 +103,7 @@ 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) => (
@@ -184,12 +218,45 @@ export function createPluginContext(input: {
           return true
         },
       },
-      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)
+      slot(name: SlotName | RegionName, value: Slot | RegionClaim) {
+        // Legacy form: position-encoded name plus a bare render function.
+        if (typeof value === "function") {
+          if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
+          const mapped = legacySlots[name as SlotName]
+          // Reachable only from untyped plugin code; fail with the name
+          // instead of a property access on undefined.
+          if (!mapped) throw new Error(`Unknown slot: ${name}`)
+          input.registry.set("slots", name, {
+            region: mapped.region,
+            placement: mapped.placement,
+            // The registration map erases the slot-specific input type.
+            render: ((slotInput: SlotMap[SlotName]) => provide(() => value(slotInput))) as Slot,
+          })
+          return registration("slots", name)
+        }
+        // Region form: a placement plus render. 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, {
+          // The overloads correlate the second argument's shape with the
+          // name: an object value implies a region name.
+          region: name as RegionName,
+          placement,
+          render: ((slotInput: SlotMap[SlotName]) => provide(() => value.render(slotInput))) as Slot,
+        })
+        return registration("slots", key)
       },
     },
   }

+ 29 - 22
packages/tui/src/plugin/context.tsx

@@ -14,15 +14,16 @@ import {
 import path from "path"
 import { stat } from "fs/promises"
 import { fileURLToPath, pathToFileURL } from "url"
-import type { Page, Slot, SlotName } from "@opencode-ai/plugin/tui/context"
-import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
+import type { Page, Slot } from "@opencode-ai/plugin/tui/context"
+import type { Claim } from "./structure"
+import { createStore, produce, reconcile as reconcileStore, unwrap } 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 } from "./api"
+import { createPluginContext, usePluginHost, type Dispose, type SlotClaim } from "./api"
 import { createSourceWatcher } from "./watch"
 import { discoverTuiPlugins, freshSpecifier, localSource } from "./discovery"
 
@@ -46,9 +47,7 @@ type Value = {
   readonly list: () => ReadonlyArray<State>
   readonly registered: () => ReadonlyArray<RegisteredPlugin>
   readonly route: (id: string, name: string) => Page["render"] | undefined
-  readonly slot: <Name extends SlotName>(
-    name: Name,
-  ) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
+  readonly claims: (region: string) => ReadonlyArray<Claim<Slot>>
   readonly markdown: () => MarkdownOptions["renderNode"]
   readonly activate: (id: string) => Promise<boolean>
   readonly deactivate: (id: string) => Promise<boolean>
@@ -62,7 +61,7 @@ type Registration = {
   options?: Readonly<Record<string, any>>
   active: boolean
   routes: Record<string, Page>
-  slots: Record<string, Slot>
+  slots: Record<string, SlotClaim>
   markdown: Record<string, MarkdownCodeBlockRenderer>
   cleanups: Dispose[]
 }
@@ -119,7 +118,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 | Slot | MarkdownCodeBlockRenderer) =>
+        set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | SlotClaim | MarkdownCodeBlockRenderer) =>
           setStore("registrations", id, kind, name, () => value),
         remove: (kind, name) =>
           setStore(
@@ -387,7 +386,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<Slot, { readonly id: string; readonly render: Slot }>()
+  const slotItems = new WeakMap<Slot, Claim<Slot>>()
   createEffect(
     on(
       () => JSON.stringify(config.data.plugins ?? []),
@@ -436,19 +435,27 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
             active: plugin.active,
           })),
         route: (id, name) => store.registrations[id]?.routes[name]?.render,
-        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]
-          }),
+        // 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]
+            }),
+          ),
         markdown,
         // Manual dialog toggles join the same chain as reconciles so a
         // toggle mid-reload cannot mix registrations across generations.

+ 61 - 22
packages/tui/src/plugin/render.tsx

@@ -1,5 +1,6 @@
 import { createComponent, createMemo, ErrorBoundary, For, mergeProps, onMount, Show, type JSX, type ParentProps } from "solid-js"
-import type { SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
+import type { RegionMap, RegionName, Slot, SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
+import { resolveStructure, type Entry, type Part } from "./structure"
 import { useRoute } from "../context/route"
 import { useToast } from "../ui/toast"
 import { errorMessage } from "../util/error"
@@ -54,31 +55,69 @@ export function PluginRoute(props: { readonly fallback: (id: string, name: strin
   )
 }
 
-export function PluginSlot<Name extends SlotName>(props: {
+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: {
   readonly name: Name
-  readonly input: SlotMap[Name]
-  readonly mode: "all" | "replace"
+  readonly input: RegionMap[Name]["input"]
+  readonly parts?: ReadonlyArray<Part<HostRender, RegionMap[Name]["part"]>>
 }) {
   const plugins = usePlugin()
-  const renderers = createMemo(() => {
-    const items = plugins.slot(props.name)
-    if (props.mode === "replace") return items.slice(-1)
-    return items
-  })
+  // 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, Slot>>()
+  const claimEntries = new WeakMap<Slot, Entry<HostRender, Slot>>()
+  const entries = createMemo(
+    () =>
+      resolveStructure<HostRender, Slot>({
+        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, Slot>>,
+    // 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]) },
+  )
   return (
-    <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 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 SlotMap[SlotName])
+            }
+          </PluginBoundary>
+        )
+      }
     </For>
   )
 }

+ 125 - 0
packages/tui/src/plugin/structure.ts

@@ -0,0 +1,125 @@
+// 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
packages/tui/src/routes/home.tsx

@@ -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 { PluginSlot } from "../plugin/render"
+import { Region } 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}>
-        <PluginSlot name="home.footer" input={{}} mode="replace" />
+        <Region name="home.footer" input={{}} />
       </box>
       <Show when={forms()[0]?.id} keyed>
         {(_) => {

+ 2 - 2
packages/tui/src/routes/session/index.tsx

@@ -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 { PluginSlot } from "../../plugin/render"
+import { Region } 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>
-              <PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
+              <Region name="session.composer.top" input={{ sessionID: route.sessionID }} />
               <Composer
                 sessionID={route.sessionID}
                 open={composer.open || (!!session()?.parentID && forms().length === 0)}

+ 3 - 3
packages/tui/src/routes/session/sidebar.tsx

@@ -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 { PluginSlot } from "../../plugin/render"
+import { Region } 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>
-            <PluginSlot name="sidebar.content" input={{ sessionID: props.sessionID }} mode="all" />
+            <Region name="sidebar.content" input={{ sessionID: props.sessionID }} />
           </box>
         </scrollbox>
 
         <box flexShrink={0} gap={1} paddingTop={1}>
-          <PluginSlot name="sidebar.footer" input={{}} mode="replace" />
+          <Region name="sidebar.footer" input={{}} />
         </box>
       </box>
     </Show>

+ 148 - 0
packages/tui/test/plugin-structure.test.ts

@@ -0,0 +1,148 @@
+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"])
+})