Compare commits

..

1 Commits

Author SHA1 Message Date
Kit Langton f4241c49b4 feat(tui): region structure for plugin slot placement 2026-08-07 22:51:10 -04:00
25 changed files with 813 additions and 729 deletions
+2 -14
View File
@@ -1,4 +1,4 @@
import { Cause, Context, Effect, Layer, Option, Schema } from "effect"
import { Cause, Context, Effect, Layer } from "effect"
import {
FetchHttpClient,
Headers,
@@ -198,20 +198,8 @@ const responseBody = (body: string | void, request: HttpClientRequest.HttpClient
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true }
}
const decodeProviderBody = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
message: Schema.optionalKey(Schema.String),
error: Schema.optionalKey(Schema.Struct({ message: Schema.optionalKey(Schema.String) })),
}),
),
)
const providerMessage = (status: number, body: { readonly body?: string }) => {
if (body.body && body.body.length <= 500) {
const decoded = Option.getOrUndefined(decodeProviderBody(body.body))
return `Provider request failed with HTTP ${status}: ${decoded?.error?.message ?? decoded?.message ?? body.body}`
}
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`
return `Provider request failed with HTTP ${status}`
}
+101
View File
@@ -0,0 +1,101 @@
export * as Account from "./account"
import { Schema } from "effect"
import type { HttpClientError } from "effect/unstable/http"
export const ID = Schema.String.pipe(Schema.brand("AccountID"))
export type ID = Schema.Schema.Type<typeof ID>
export const OrgID = Schema.String.pipe(Schema.brand("OrgID"))
export type OrgID = Schema.Schema.Type<typeof OrgID>
export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken"))
export type AccessToken = Schema.Schema.Type<typeof AccessToken>
export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken"))
export type RefreshToken = Schema.Schema.Type<typeof RefreshToken>
export const DeviceCode = Schema.String.pipe(Schema.brand("DeviceCode"))
export type DeviceCode = Schema.Schema.Type<typeof DeviceCode>
export const UserCode = Schema.String.pipe(Schema.brand("UserCode"))
export type UserCode = Schema.Schema.Type<typeof UserCode>
export class Info extends Schema.Class<Info>("Account")({
id: ID,
email: Schema.String,
url: Schema.String,
active_org_id: Schema.NullOr(OrgID),
}) {}
export class Org extends Schema.Class<Org>("Org")({
id: OrgID,
name: Schema.String,
}) {}
export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", {
method: Schema.String,
url: Schema.String,
description: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
}) {
static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError {
return new AccountTransportError({
method: error.request.method,
url: error.request.url,
description: error.description,
cause: error.cause,
})
}
override get message(): string {
return [
`Could not reach ${this.method} ${this.url}.`,
`This failed before the server returned an HTTP response.`,
this.description,
`Check your network, proxy, or VPN configuration and try again.`,
]
.filter(Boolean)
.join("\n")
}
}
export type AccountError = AccountRepoError | AccountServiceError | AccountTransportError
export class Login extends Schema.Class<Login>("Login")({
code: DeviceCode,
user: UserCode,
url: Schema.String,
server: Schema.String,
expiry: Schema.Duration,
interval: Schema.Duration,
}) {}
export class PollSuccess extends Schema.TaggedClass<PollSuccess>()("PollSuccess", {
email: Schema.String,
}) {}
export class PollPending extends Schema.TaggedClass<PollPending>()("PollPending", {}) {}
export class PollSlow extends Schema.TaggedClass<PollSlow>()("PollSlow", {}) {}
export class PollExpired extends Schema.TaggedClass<PollExpired>()("PollExpired", {}) {}
export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {}
export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
cause: Schema.Defect(),
}) {}
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
export type PollResult = Schema.Schema.Type<typeof PollResult>
+10 -7
View File
@@ -1,21 +1,24 @@
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
import { Account } from "../account"
import { Timestamps } from "../database/schema.sql"
export const AccountTable = sqliteTable("account", {
id: text().primaryKey(),
id: text().$type<Account.ID>().primaryKey(),
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
...Timestamps,
})
export const AccountStateTable = sqliteTable("account_state", {
id: integer().primaryKey(),
active_account_id: text().references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text(),
active_account_id: text()
.$type<Account.ID>()
.references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text().$type<Account.OrgID>(),
})
// LEGACY
@@ -24,8 +27,8 @@ export const ControlAccountTable = sqliteTable(
{
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
active: integer({ mode: "boolean" })
.notNull()
+2
View File
@@ -1,5 +1,6 @@
export * as PluginHooks from "./hooks"
import type { AISDKHooks } from "@opencode-ai/plugin/effect/aisdk"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import type { ShellHooks } from "@opencode-ai/plugin/effect/shell"
import type { ToolHooks } from "@opencode-ai/plugin/effect/tool"
@@ -8,6 +9,7 @@ import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { State } from "../state"
export interface Domains {
readonly aisdk: AISDKHooks
readonly session: SessionHooks
readonly shell: ShellHooks
readonly tool: ToolHooks
+15 -9
View File
@@ -3,6 +3,7 @@ export * as PatchTool from "./patch"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff"
import { createTwoFilesPatch, diffLines } from "diff"
import { Effect, Result, Schema } from "effect"
import path from "path"
import { Bom } from "@opencode-ai/util/bom"
@@ -14,7 +15,6 @@ import { Location } from "../../location"
import { Patch } from "@opencode-ai/util/patch"
import { Permission } from "../../permission"
import DESCRIPTION from "../patch.txt"
import { fileDiff } from "./file-diff"
export const name = "patch"
@@ -353,16 +353,22 @@ function errorMessage(error: unknown) {
function patchFile(change: Prepared, after = change.after): typeof FileDiff.Info.Type {
const target = (change.type === "update" ? change.moveTarget : undefined)?.resource ?? change.target.resource
const diff = fileDiff(
change.target.absolute,
change.before,
after,
change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
)
const patch = trimDiff(createTwoFilesPatch(change.target.absolute, change.target.absolute, change.before, after))
const counts =
change.type === "delete"
? { additions: 0, deletions: change.before.split("\n").length }
: diffLines(change.before, after).reduce(
(result, item) => ({
additions: result.additions + (item.added ? (item.count ?? 0) : 0),
deletions: result.deletions + (item.removed ? (item.count ?? 0) : 0),
}),
{ additions: 0, deletions: 0 },
)
return {
...diff,
file: target,
patch: trimDiff(diff.patch),
patch,
status: change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
...counts,
}
}
+2 -25
View File
@@ -215,7 +215,7 @@ describe("PatchTool", () => {
file: "remove.txt",
status: "deleted",
additions: 0,
deletions: 1,
deletions: 2,
patch: expect.stringContaining("-remove"),
},
],
@@ -248,29 +248,6 @@ describe("PatchTool", () => {
),
)
it.live("counts deleted lines with and without a trailing newline", () =>
withTempTool((directory, registry) =>
Effect.gen(function* () {
yield* Effect.promise(() =>
Promise.all([
fs.writeFile(path.join(directory, "trailing.txt"), "remove\n"),
fs.writeFile(path.join(directory, "unterminated.txt"), "remove"),
]),
)
const settled = yield* executeTool(
registry,
call("*** Begin Patch\n*** Delete File: trailing.txt\n*** Delete File: unterminated.txt\n*** End Patch"),
)
expect(settled.status).toBe("completed")
if (settled.status !== "completed") return
expect(settled.output.files).toMatchObject([
{ file: "trailing.txt", additions: 0, deletions: 1 },
{ file: "unterminated.txt", additions: 0, deletions: 1 },
])
}),
),
)
it.live("serializes concurrent patch transactions", () =>
withTempTool((directory, registry) => {
const target = path.join(directory, "concurrent.txt")
@@ -469,7 +446,7 @@ describe("PatchTool", () => {
{
file: "renamed/dir/name.txt",
status: "modified",
patch: expect.stringContaining(`Index: ${source}`),
patch: expect.stringContaining("-old content\n+new content"),
},
],
})
+14 -184
View File
@@ -198,13 +198,13 @@ describe("FlowchartDiagram", () => {
B --> A`)
expectDiagram(output).toEqualDiagram(`
╭───────────╮
│ │
│ │
▼ │
╭───╮ ╭─┴─╮
│ A ├──────▶│ B │
╰───╯ ╰───╯
╭──────────────
╭───╮ ╭─┴─╮
│ A ├─────────▶│ B │
╰───╯ ╰───╯
`)
})
@@ -599,7 +599,7 @@ flowchart LR
const output = renderFlowchartDiagram(content)
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "thick" }])
expect(output).toContain("━━━━━━▶")
expect(output).toContain("━━━━━━━━━▶")
})
test("parses and renders Mermaid dashed edges", () => {
@@ -611,7 +611,7 @@ flowchart LR
const output = renderFlowchartDiagram(content)
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "dashed" }])
expect(output).toContain("──────▶")
expect(output).toContain("─────────▶")
})
test("paints horizontal and vertical dashed routes with solid terminal cells", () => {
@@ -689,11 +689,11 @@ graph LR
`)
expectDiagram(output).toEqualDiagram(`
╭───────╮
╭────────╮ ╭─────╮ ├───────┤
│ Client ├──────▶│ API ├──────▶│ Cache │
╰────────╯ ╰─────╯ ├───────┤
╰───────╯
╭───────╮
╭────────╮ ╭─────╮ ├───────┤
│ Client ├─────────▶│ API ├─────────▶│ Cache │
╰────────╯ ╰─────╯ ├───────┤
╰───────╯
`)
})
@@ -1017,176 +1017,6 @@ flowchart LR
}
})
test("separates cross-dependent top-level subgraphs", () => {
const content = `flowchart TD
subgraph plugins["Plugins — one verb: attach"]
chip["pr-indicator<br/>attach(prompt.footer, { after: 'directory' })"]
theme["fancy-footer<br/>attach(prompt.footer, { replace: 'right' })"]
end
subgraph host["Host anatomy tree — published, stable part IDs"]
footer["prompt.footer"]
left["left"]
right["right<br/>(container)"]
dir["directory"]
model["model"]
tokens["tokens"]
footer --> left
footer --> right
right --> dir
right --> model
right --> tokens
end
chip -- "insert after" --> dir
theme == "takeover" ==> right
theme -. "suppresses guests<br/>in subtree" .-> chip`
const layout = layoutFlowchartDiagram(content)
const plugins = layout.subgraphBounds.get("plugins")!
const host = layout.subgraphBounds.get("host")!
const output = renderFlowchartDiagram(content)
const lines = output.split("\n")
expect(host.top).toBeGreaterThanOrEqual(plugins.top + plugins.height)
expect(lines.filter((line) => line.includes("Plugins — one verb: attach"))).toHaveLength(1)
expect(lines.filter((line) => line.includes("Host anatomy tree — published, stable part IDs"))).toHaveLength(1)
expect(lines.findIndex((line) => line.includes("Host anatomy tree"))).toBeGreaterThan(
lines.findIndex((line) => line.includes("Plugins — one verb")),
)
for (const route of layout.routes) {
for (let index = 1; index < route.points.length; index++) {
const from = route.points[index - 1]!
const to = route.points[index]!
expect(from.x === to.x || from.y === to.y).toBe(true)
}
}
})
test.each(["TD", "BT", "LR", "RL"] as const)(
"keeps parallel top-level subgraphs in the same rank for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph left [Left]
B[B]
end
subgraph right [Right]
C[C]
end
A --> B
A --> C`)
const source = layout.subgraphBounds.get("source")!
const left = layout.subgraphBounds.get("left")!
const right = layout.subgraphBounds.get("right")!
const leftNode = layout.bounds.get("B")!
const rightNode = layout.bounds.get("C")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof source) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
expect(horizontal ? leftNode.centerX : leftNode.centerY).toBe(horizontal ? rightNode.centerX : rightNode.centerY)
expect(Math.min(start(left), start(right))).toBeGreaterThanOrEqual(start(source) + size(source))
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"separates oversized parallel subgraph labels across %s diagrams",
(direction) => {
const horizontal = direction === "LR" || direction === "RL"
const label = horizontal ? "one<br/>two<br/>three<br/>four<br/>five" : "A very very wide downstream subgraph title"
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph left [${label}]
B[B]
end
subgraph right [Right]
C[C]
end
A --> B
A --> C`)
const left = layout.subgraphBounds.get("left")!
const right = layout.subgraphBounds.get("right")!
const overlap =
left.left < right.left + right.width &&
left.left + left.width > right.left &&
left.top < right.top + right.height &&
left.top + left.height > right.top
expect(overlap).toBe(false)
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"ranks nested order-only subgraph dependencies for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph first [First]
subgraph firstInner [First inner]
A[A]
end
end
subgraph second [Second]
subgraph secondInner [Second inner]
B[B]
end
end
firstInner ~~~ secondInner`)
const first = layout.subgraphBounds.get("first")!
const second = layout.subgraphBounds.get("second")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof first) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = horizontal ? first.width : first.height
expect(start(second)).toBeGreaterThanOrEqual(start(first) + size)
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"ranks cyclic top-level subgraphs as one downstream component for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph first [First]
B[B]
end
subgraph second [Second]
C[C]
end
A --> B
B --> C
C --> B`)
const source = layout.subgraphBounds.get("source")!
const first = layout.subgraphBounds.get("first")!
const second = layout.subgraphBounds.get("second")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof source) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
expect(Math.min(start(first), start(second))).toBeGreaterThanOrEqual(start(source) + size(source))
},
)
test("moves subgraph labels away from crossing routes", () => {
const output = renderFlowchartDiagram(`
flowchart TD
+31 -190
View File
@@ -27,7 +27,7 @@ import type {
export const DEFAULT_MIN_NODE_GAP = 5
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
export const DEFAULT_MIN_RANK_GAP = 7
export const DEFAULT_MIN_RANK_GAP = 10
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
export const COMPACT_MIN_RANK_GAP = 4
export const COMPACT_MIN_VERTICAL_RANK_GAP = 2
@@ -499,6 +499,10 @@ function edgeDirection(diagram: FlowchartDiagram, edge: FlowchartEdge): Flowchar
return diagram.direction
}
function hasLocalSubgraphDirection(diagram: FlowchartDiagram): boolean {
return (diagram.subgraphs ?? []).some((subgraph) => subgraph.direction && subgraph.direction !== diagram.direction)
}
function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string): Set<string> {
const nodeIds = new Set<string>()
for (const subgraph of diagram.subgraphs ?? []) {
@@ -511,200 +515,51 @@ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string):
return nodeIds
}
function rankGraphComponents(ids: readonly string[], outgoing: ReadonlyMap<string, ReadonlySet<string>>): Map<string, number> {
const reachable = new Map<string, Set<string>>()
for (const id of ids) {
const seen = new Set<string>()
const queue = [id]
for (let index = 0; index < queue.length; index++) {
const current = queue[index]!
if (seen.has(current)) continue
seen.add(current)
queue.push(...(outgoing.get(current) ?? []))
}
reachable.set(id, seen)
}
const componentById = new Map<string, number>()
const components: string[][] = []
for (const id of ids) {
if (componentById.has(id)) continue
const component = ids.filter(
(candidate) => !componentById.has(candidate) && reachable.get(id)!.has(candidate) && reachable.get(candidate)!.has(id),
)
const componentIndex = components.length
components.push(component)
for (const member of component) componentById.set(member, componentIndex)
}
const componentOutgoing = new Map(components.map((_, index) => [index, new Set<number>()]))
const incoming = new Map(components.map((_, index) => [index, 0]))
for (const [from, targets] of outgoing) {
const fromComponent = componentById.get(from)!
for (const to of targets) {
const toComponent = componentById.get(to)!
if (fromComponent === toComponent || componentOutgoing.get(fromComponent)!.has(toComponent)) continue
componentOutgoing.get(fromComponent)!.add(toComponent)
incoming.set(toComponent, incoming.get(toComponent)! + 1)
}
}
const componentRanks = new Map<number, number>()
const queue = components.map((_, index) => index).filter((index) => incoming.get(index) === 0)
for (const component of queue) componentRanks.set(component, 0)
for (let index = 0; index < queue.length; index++) {
const component = queue[index]!
for (const to of componentOutgoing.get(component)!) {
componentRanks.set(to, Math.max(componentRanks.get(to) ?? 0, componentRanks.get(component)! + 1))
incoming.set(to, incoming.get(to)! - 1)
if (incoming.get(to) === 0) queue.push(to)
}
}
return new Map(ids.map((id) => [id, componentRanks.get(componentById.get(id)!) ?? 0]))
}
function separateTopLevelItems(
function separateLocalSubgraphItems(
diagram: FlowchartDiagram,
nodeBounds: Map<string, FlowchartNodeBounds>,
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
gap: number,
): boolean {
const hasLocalDirection = (diagram.subgraphs ?? []).some(
(subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
)
): void {
if (!hasLocalSubgraphDirection(diagram)) return
const coveredNodeIds = new Set<string>()
const items: { id: string; bounds: FlowchartBounds; nodeIds: Set<string>; rank: number }[] = []
const itemByEndpoint = new Map<string, string>()
const subgraphs = diagram.subgraphs ?? []
const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
const topLevelSubgraphId = (id: string): string => {
let current = subgraphById.get(id)
while (current?.parentId) current = subgraphById.get(current.parentId)
return current?.id ?? id
}
for (const subgraph of subgraphs) {
const items: { bounds: FlowchartBounds; nodeIds: Set<string> }[] = []
for (const subgraph of diagram.subgraphs ?? []) {
if (subgraph.parentId) continue
const bounds = subgraphBounds.get(subgraph.id)
const nodeIds = collectSubgraphNodeIds(diagram, subgraph.id)
if (!bounds || nodeIds.size === 0) continue
items.push({ id: subgraph.id, bounds, nodeIds, rank: 0 })
itemByEndpoint.set(subgraph.id, subgraph.id)
for (const nodeId of nodeIds) {
coveredNodeIds.add(nodeId)
itemByEndpoint.set(nodeId, subgraph.id)
}
items.push({ bounds, nodeIds })
for (const nodeId of nodeIds) coveredNodeIds.add(nodeId)
}
for (const subgraph of subgraphs) itemByEndpoint.set(subgraph.id, topLevelSubgraphId(subgraph.id))
for (const node of diagram.nodes) {
if (coveredNodeIds.has(node.id)) continue
const bounds = nodeBounds.get(node.id)
if (!bounds) continue
items.push({ id: node.id, bounds, nodeIds: new Set([node.id]), rank: 0 })
itemByEndpoint.set(node.id, node.id)
if (bounds) items.push({ bounds, nodeIds: new Set([node.id]) })
}
if (items.length < 2) return false
const horizontal = isHorizontalDirection(diagram.direction)
const moveItem = (item: (typeof items)[number], dx: number, dy: number): void => {
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, dx, dy)
}
}
if (hasLocalDirection) {
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
let cursor: number | undefined
let moved = false
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
if (cursor === undefined) {
cursor = start + size + gap
continue
}
const shift = cursor - start
moved ||= shift !== 0
moveItem(item, horizontal ? shift : 0, horizontal ? 0 : shift)
cursor = start + shift + size + gap
}
return moved
}
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
const topLevelIds = new Set(subgraphs.filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id))
const rankedItems = items.filter((item) => topLevelIds.has(item.id))
if (rankedItems.length < 2) return false
const itemById = new Map(rankedItems.map((item) => [item.id, item]))
const outgoing = new Map(rankedItems.map((item) => [item.id, new Set<string>()]))
for (const edge of diagram.edges) {
const from = itemByEndpoint.get(edge.from)
const to = itemByEndpoint.get(edge.to)
if (!from || !to || from === to || !itemById.has(from) || !itemById.has(to) || outgoing.get(from)!.has(to)) continue
outgoing.get(from)!.add(to)
}
const ranks = rankGraphComponents(
rankedItems.map((item) => item.id),
outgoing,
)
for (const item of rankedItems) item.rank = ranks.get(item.id)!
const reversed = diagram.direction === "RL" || diagram.direction === "BT"
const primaryStart = (item: (typeof items)[number]): number => {
let cursor: number | undefined
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
return reversed ? -(start + size) : start
}
const itemsByRank = Map.groupBy(rankedItems, (item) => item.rank)
const rankKeys = [...itemsByRank.keys()].sort((a, b) => a - b)
let cursor: number | undefined
let moved = false
for (const rank of rankKeys) {
const rankItems = itemsByRank.get(rank)!
const start = Math.min(...rankItems.map(primaryStart))
const end = Math.max(
...rankItems.map((item) => primaryStart(item) + (horizontal ? item.bounds.width : item.bounds.height)),
)
if (cursor === undefined) {
cursor = end + gap
cursor = start + size + gap
continue
}
const shift = Math.max(0, cursor - start)
if (shift > 0) {
moved = true
for (const item of rankItems) {
const offset = reversed ? -shift : shift
moveItem(item, horizontal ? offset : 0, horizontal ? 0 : offset)
const shift = cursor - start
if (shift !== 0) {
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
}
}
cursor = end + shift + gap
cursor = start + shift + size + gap
}
for (const rank of rankKeys) {
const rankItems = itemsByRank
.get(rank)!
.toSorted((a, b) =>
horizontal ? a.bounds.top - b.bounds.top : a.bounds.left - b.bounds.left,
)
let crossCursor: number | undefined
for (const item of rankItems) {
const start = horizontal ? item.bounds.top : item.bounds.left
const size = horizontal ? item.bounds.height : item.bounds.width
if (crossCursor === undefined) {
crossCursor = start + size + gap
continue
}
const shift = Math.max(0, crossCursor - start)
if (shift > 0) {
moved = true
moveItem(item, horizontal ? 0 : shift, horizontal ? shift : 0)
}
crossCursor = start + shift + size + gap
}
}
return moved
}
function layoutSubgraphs(
@@ -759,27 +614,13 @@ function layoutFlowchartWithDirection(
const bounds = layoutRankedNodes(diagram, direction, sizes, minNodeGap, requestedMinRankGap)
layoutLocalSubgraphDirections(diagram, bounds, sizes, minNodeGap, requestedMinRankGap)
const subgraphs = diagram.subgraphs ?? []
let subgraphBounds = new Map<string, FlowchartSubgraphBounds>()
let routes: FlowchartEdgeRoute[]
if (subgraphs.length === 0) {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
} else {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
const moved = separateTopLevelItems(
diagram,
bounds,
subgraphBounds,
Math.max(1, Math.floor(requestedMinRankGap / 2)),
)
if (moved) {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
}
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
}
let routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
let subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
separateLocalSubgraphItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
const allBounds = [...bounds.values(), ...subgraphBounds.values(), ...routeRenderBounds(routes)]
const dx = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.left)))
const dy = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.top)))
-51
View File
@@ -1,51 +0,0 @@
import { describe, expect, test } from "bun:test"
import { RGBA } from "@opentui/core"
import { createOpenCodeDiagramPalette } from "./palette.js"
type Rgb = readonly [number, number, number]
const rgb = (value: Rgb) => RGBA.fromInts(...value)
describe("OpenCode diagram palette", () => {
test.each(
[
{
name: "dark theme",
text: [230, 232, 240],
subdued: [114, 120, 138],
secondary: [172, 176, 189],
muted: [149, 154, 169],
},
{
name: "light theme",
text: [32, 35, 43],
subdued: [119, 125, 138],
secondary: [76, 80, 91],
muted: [93, 98, 110],
},
] satisfies ReadonlyArray<{
name: string
text: Rgb
subdued: Rgb
secondary: Rgb
muted: Rgb
}>,
)("derives a controlled neutral ladder for a $name", ({ text, subdued, secondary, muted }) => {
const primary = rgb(text)
const info = RGBA.fromInts(40, 120, 220)
const background = RGBA.fromInts(10, 20, 30)
const palette = createOpenCodeDiagramPalette({
text: primary,
subdued: rgb(subdued),
info,
background,
})
expect(palette.text).toBe(primary)
expect(palette.primary).toBe(primary)
expect(palette.secondary.equals(rgb(secondary))).toBe(true)
expect(palette.muted.equals(rgb(muted))).toBe(true)
expect(palette.warning).toBe(info)
expect(palette.background).toBe(background)
})
})
-20
View File
@@ -1,20 +0,0 @@
import type { RGBA } from "@opentui/core"
import { blendColor } from "./core/color/style.js"
export interface OpenCodeDiagramPaletteInput {
readonly text: RGBA
readonly subdued: RGBA
readonly info: RGBA
readonly background: RGBA
}
export function createOpenCodeDiagramPalette(input: OpenCodeDiagramPaletteInput) {
return {
text: input.text,
primary: input.text,
secondary: blendColor(input.text, input.subdued, 0.5),
muted: blendColor(input.text, input.subdued, 0.7),
warning: input.info,
background: input.background,
}
}
+7 -6
View File
@@ -1,6 +1,5 @@
import { Plugin } from "@opencode-ai/plugin/tui"
import { createMermaidCodeBlockRenderer } from "./markdown.js"
import { createOpenCodeDiagramPalette } from "./palette.js"
export default Plugin.define({
id: "opencode.merman",
@@ -8,12 +7,14 @@ export default Plugin.define({
context.markdown.registerCodeBlockRenderer(
"mermaid",
createMermaidCodeBlockRenderer(context.renderer, () => ({
colors: createOpenCodeDiagramPalette({
text: context.theme.text.default,
subdued: context.theme.text.subdued,
info: context.theme.text.feedback.info.default,
colors: {
text: context.theme.markdown.text,
primary: context.theme.text.default,
secondary: context.theme.text.subdued,
muted: context.theme.border.default,
warning: context.theme.text.feedback.info.default,
background: context.theme.background.default,
}),
},
})),
)
},
+59 -1
View File
@@ -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 {
+11 -36
View File
@@ -13,30 +13,15 @@ trap 'rm -f -- "$pidfile"' EXIT
"$@"
`
// Modal's VM runtime accepts process-group signals without delivering them
// (kill(-pgid) returns 0 and nothing dies; direct-pid signals work), so the
// group is enumerated from /proc and each member is signalled directly. The
// second pass catches children forked between scan and signal.
const KILL = `
pidfile=$1
sig=$2
i=0
while [ ! -s "$pidfile" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
[ -s "$pidfile" ] || exit 47
target=$(cat "$pidfile")
pass=0
while [ "$pass" -lt 2 ]; do
for stat in /proc/[0-9]*/stat; do
[ -e "$stat" ] || continue
pid=\${stat#/proc/}
pid=\${pid%/stat}
set -- $(sed "s/.*) //" "$stat" 2>/dev/null)
if [ "\${3:-}" = "$target" ]; then
/bin/kill "-$sig" "$pid" 2>/dev/null || true
fi
done
pass=$((pass + 1))
done
while [ ! -s "$1" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
if [ -s "$1" ]; then
pid=$(cat "$1")
/bin/kill "-$2" "-$pid" 2>/dev/null || true
else
exit 47
fi
`
export interface ModalImageSpec {
@@ -69,15 +54,7 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
const app = await client.apps.fromName(options.app, { createIfMissing: true })
const imageSpec = options.image ?? ubuntuImage
const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
// with real device nodes, so workspaces can run Docker and other
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
const sandbox = await client.sandboxes.create(app, image, {
...options.sandbox,
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
})
const sandbox = await client.sandboxes.create(app, image, options.sandbox)
return {
driver: makeModalDriver(sandbox),
sandbox,
@@ -87,14 +64,12 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
/**
* Adapts Modal exec to the Environment driver. Files intentionally has no native
* overrides: exec latency dominates payload work (VM runtime floor measured
* ~285-535ms per exec, Aug 2026), so the derived exec defaults are the simplest
* implementation with no measured loss.
* overrides: Modal exec and filesystem tools share the same roughly 175ms floor,
* so the derived exec defaults are the simplest implementation with no measured loss.
*
* Modal cannot signal a ContainerProcess. Each command therefore starts a new
* process group and records its leader in a unique pid file; kill runs a second
* sandbox command that enumerates that group from /proc and signals each member
* directly (see KILL). Pid files are removed best-effort.
* sandbox command that signals that group. Pid files are removed best-effort.
*/
export const makeModalDriver = (sandbox: Sandbox): Driver => {
const spawn = Effect.fnUntraced(function* (command: Command) {
+11 -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, 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"
@@ -1154,6 +1154,15 @@ function App(props: { pair?: DialogPairCredentials }) {
}
})
event.on("session.execution.failed", (evt, { workspace }) => {
if (workspace !== (location.current?.workspaceID ?? data.location.default().workspaceID)) return
toast.show({
variant: "error",
message: evt.data.error.message,
duration: 5000,
})
})
// Suppress the full-screen overlay for transient startup and event-stream retry states.
// Initial connection gets a longer grace period; retries surface more quickly.
const [showReconnecting, setShowReconnecting] = createSignal(false)
@@ -1224,7 +1233,7 @@ function App(props: { pair?: DialogPairCredentials }) {
</Match>
</Switch>
</box>
<PluginSlot name="app" input={{}} mode="all" />
<Region name="app" input={{}} />
</Show>
</box>
</box>
+1 -14
View File
@@ -51,17 +51,6 @@ export function DialogOpen() {
.catch(() => [] as SessionInfo[]),
{ initialValue: [] },
)
const [matched] = createResource(
() => {
const value = filter().trim()
return /^ses_[0-9A-Za-z]{26}$/.test(value) ? value : undefined
},
(sessionID) =>
client.api.session
.get({ sessionID })
.then((session) => (session.id === sessionID ? session : undefined))
.catch(() => undefined),
)
const openTabs = createMemo(
() => new Set(sessionTabs.enabled() ? sessionTabs.tabs().map((tab) => tab.sessionID) : []),
@@ -71,8 +60,7 @@ export function DialogOpen() {
)
const sessions = createMemo(() => {
const seen = new Set<string>()
const match = matched()
return [...data.session.list(), ...fetched(), ...(match ? [match] : [])]
return [...data.session.list(), ...fetched()]
.filter((session) => {
if (session.parentID || seen.has(session.id)) return false
seen.add(session.id)
@@ -99,7 +87,6 @@ export function DialogOpen() {
data.session.family(session.id).some((id) => data.session.status(id) === "running")
return {
title: withTimestampedFallback(session),
searchText: session.id,
value: { type: "session", sessionID: session.id } as OpenTarget,
category: "Sessions",
footer: `${name ? `${Locale.truncate(name, 20)} · ` : ""}${timeAgo(session.time.updated)}`,
+87 -70
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
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 { 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>
{(_) => {
+17 -9
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 { 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)}
@@ -1631,13 +1631,21 @@ function AssistantFooter(props: { message: SessionMessageAssistant }) {
const interrupted = createMemo(() => props.message.error?.message === "Step interrupted")
return (
<>
<Show when={props.message.error && !interrupted() && !props.message.retry}>
<box paddingLeft={3}>
<text fg={theme.text.feedback.error.default}>Error: {errorMessage(props.message.error)}</text>
<Show when={props.message.error && !interrupted()}>
<box
border={["left"]}
paddingTop={1}
paddingBottom={1}
paddingLeft={2}
backgroundColor={theme.background.default}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.text.feedback.error.default}
>
<text fg={theme.text.subdued}>{errorMessage(props.message.error)}</text>
</box>
</Show>
<AssistantRetry retry={props.message.retry} />
<box paddingLeft={3} marginTop={props.message.retry || (props.message.error && !interrupted()) ? 1 : 0}>
<box paddingLeft={3} marginTop={props.message.error && !interrupted() ? 1 : 0}>
<text>
<span style={{ fg: props.message.error ? theme.text.subdued : local.agent.color(props.message.agent) }}>
{Locale.titlecase(props.message.agent)}
@@ -2037,9 +2045,9 @@ function AssistantRetry(props: { retry: SessionMessageAssistant["retry"] }) {
return (
<Show when={props.retry}>
{(retry) => (
<box paddingLeft={3}>
<text fg={theme.text.feedback.warning.default}>
Retry attempt {retry().attempt} scheduled: {retry().error.message}
<box paddingLeft={3} marginTop={1}>
<text fg={theme.text.subdued}>
Retry attempt {retry().attempt} scheduled: {retry().error.message} [{retry().error.type}]
</text>
</box>
)}
+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 { 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>
@@ -54,40 +54,6 @@ test("selecting an unhydrated session preserves its location", async () => {
}
})
test("finds and opens an exact session ID outside the recent list", async () => {
const sessionID = "ses_04a7a3d82ffeIphUJgd3SnEqiv"
const remote = { directory: "/tmp/opencode/archive", workspaceID: "ws_archive" }
const fixture = await renderOpen((url) => {
if (url.pathname === "/api/session") return json({ data: [], cursor: {} })
if (url.pathname !== `/api/session/${sessionID}`) return undefined
return json({
data: {
id: sessionID,
projectID: "proj_archive",
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
title: "TUI plugin slot API v2",
location: remote,
},
})
})
try {
await fixture.app.waitForFrame((frame) => frame.includes("Search sessions and projects"))
await fixture.app.mockInput.typeText(sessionID)
await fixture.app.waitForFrame((frame) => frame.includes("TUI plugin slot API v2"))
fixture.app.mockInput.pressEnter()
await fixture.app.waitFor(() => fixture.route.data.type === "session")
expect(fixture.route.data).toEqual({ type: "session", sessionID })
expect(fixture.location.ref).toEqual(remote)
} finally {
fixture.dispose()
}
})
test("shows the current project and opens its root", async () => {
const root = "/tmp/opencode/project"
const subfolder = `${root}/packages/tui`
+148
View File
@@ -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"])
})