fix(app): drive plugin GUI loading, New tabs, deferred menus and composer writes through state machines (#61987)

This commit is contained in:
Luke Parker
2026-11-05 00:54:02 -06:00
committed by GitHub
Unverified
parent 00c25e81cd
commit 4f6a84cf02
15 changed files with 1721 additions and 251 deletions
@@ -96,6 +96,52 @@ test("new tab selection and closing stay in the focused pane", async ({ page })
await expect(sideTabs.nth(0)).toHaveAttribute("aria-selected", "true")
})
test("closing another pane's tab keeps the side pane's New tab", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/OtherPaneClose"
const key = `local\u0000${base64Encode(directory)}/ses_otherpaneclose`
await openSession(page, {
name: "OtherPaneClose",
fileList: () => [],
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
seed: {
panes: { ses_otherpaneclose: { review: true } },
storage: {
"opencode.global.dat:layout": {
sessionTabs: {
// The side pane selects nothing of its own, so it shows its fallback tab while the split pane is active.
[key]: {
all: ["review:changes", "file://README.md", "file://notes.md"],
active: "file://notes.md",
panes: { "file://notes.md": "split" },
selected: { split: "file://notes.md" },
},
},
},
},
},
})
const side = page.locator('[data-pane-content="side"]')
const split = page.locator('[data-pane-content="split"]')
const sideNewTab = side.getByRole("tab", { name: "New tab", exact: true })
await expect(side.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true")
await side.getByRole("button", { name: "Add tab", exact: true }).click()
await expect(sideNewTab).toHaveAttribute("aria-selected", "true")
// The selection falls back to the side pane's first tab, which is already listed there: no launcher opened it.
await split.getByRole("tab", { name: "notes.md", exact: true }).hover()
await split
.locator('div[data-value="file://notes.md"]')
.getByRole("button", { name: "Close tab", exact: true })
.click()
await expect(split).toHaveCount(0)
await expect(sideNewTab).toHaveCount(1)
await expect(sideNewTab).toHaveAttribute("aria-selected", "true")
})
test("closing the last New tab closes the side region, and only a New tab lists the launchers", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
await openSession(page, { name: "LastNewTab", seed: { panes: { ses_lastnewtab: { review: true } } } })
@@ -1,4 +1,4 @@
import { For, Show, createMemo, createUniqueId, type JSX } from "solid-js"
import { For, Show, createMemo, createSignal, createUniqueId, onCleanup, untrack, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { FileIcon } from "@opencode/ui/file-icon"
import { Icon } from "@opencode/ui/icon"
@@ -17,6 +17,14 @@ import {
type ClosedSideTab,
type ClosedTabsModifier,
} from "./closed-tabs"
import {
createDeferredMenuState,
selectDeferredMenuHover,
selectDeferredMenuOpen,
transitionDeferredMenu,
type DeferredMenuEffect,
type DeferredMenuEvent,
} from "./deferred-menu-machine"
const MENU_LIMIT = 10
@@ -143,6 +151,68 @@ function ClosedTabsItems(props: { entries: readonly ClosedSideTab[]; onReopen: (
)
}
/**
* Drives `deferred-menu-machine.ts` for a menu whose chosen item runs once the closing menu has returned focus to its
* trigger, and the tab strip has passed it on to the selected tab. Releasing that focus first lets the item move it
* where its tab needs it, e.g. into a new terminal, without the strip taking it back for the tab it remembers.
*/
export function createDeferredMenu<T>(options: { onChoose: (choice: T) => void; onNewTab?: () => void }) {
const [state, setState] = createSignal(createDeferredMenuState<T>())
// Events an effect raises synchronously wait behind that effect.
const queue: DeferredMenuEvent<T>[] = []
let timer: ReturnType<typeof setTimeout> | undefined
const dispatch = (event: DeferredMenuEvent<T>) => {
queue.push(event)
if (queue.length === 1) untrack(drain)
}
const drain = () => {
const event = queue[0]
if (!event) return
try {
const next = transitionDeferredMenu(untrack(state), event)
setState(() => next.state)
next.effects.forEach((effect) =>
Promise.try(() => run(effect)).catch((cause: unknown) => console.error("[plugin] menu choice failed", cause)),
)
} finally {
queue.shift()
}
drain()
}
const run = (effect: DeferredMenuEffect<T>) => {
if (effect.type === "open.new-tab") return options.onNewTab?.()
if (effect.type === "timer.start") {
clearTimeout(timer)
timer = setTimeout(() => dispatch({ type: "timer.fired", attempt: effect.attempt }), effect.delay)
return
}
if (effect.type === "timer.stop") {
clearTimeout(timer)
timer = undefined
return
}
if (document.activeElement instanceof HTMLElement) document.activeElement.blur()
options.onChoose(effect.choice)
}
onCleanup(() => dispatch({ type: "disposed" }))
return { state, dispatch }
}
const MODIFIER_LABEL = {
mac: { alt: "⌥", shift: "⇧", ctrl: "⌃", meta: "⌘" },
other: { alt: "Alt", shift: "Shift", ctrl: "Ctrl", meta: "Win" },
@@ -163,13 +233,12 @@ export function NewTabButton(props: {
const global = closedTabsSwap() === "global"
const held = createModifierHeld(modifier)
const label = MODIFIER_LABEL[/(Mac|iPhone|iPad)/.test(navigator.platform) ? "mac" : "other"][modifier]
const [state, setState] = createStore({ hover: false, open: false })
const available = () => props.entries.length > 0
const swapped = () => state.open || (available() && held() && (global || state.hover))
// What the press that is opening the menu asked for, read when Kobalte reports the open.
let intent: "menu" | "new" = "new"
// A chosen entry reopens once the closing menu has returned focus, as the "+" menu does.
let chosen: string | undefined
const menu = createDeferredMenu<string>({ onChoose: (key) => props.onReopen(key), onNewTab: () => props.onNewTab() })
const swapped = () =>
selectDeferredMenuOpen(menu.state()) || (available() && held() && (global || selectDeferredMenuHover(menu.state())))
return (
<Tooltip
@@ -193,13 +262,10 @@ export function NewTabButton(props: {
modal={false}
placement="bottom-start"
gutter={4}
open={state.open}
onOpenChange={(open) => {
if (!open) return setState("open", false)
if (intent === "menu" && available()) return setState("open", true)
props.onNewTab()
}}
open={selectDeferredMenuOpen(menu.state())}
onOpenChange={(open) =>
menu.dispatch({ type: "open.change", open, available: available(), defaultIntent: "new" })
}
>
<Menu.Trigger
as={IconButton}
@@ -210,38 +276,31 @@ export function NewTabButton(props: {
size="large"
aria-label={swapped() ? language.t("home.recentlyClosed") : language.t("session.tab.add")}
aria-haspopup="menu"
onPointerEnter={() => setState("hover", true)}
onPointerLeave={() => setState("hover", false)}
onPointerEnter={() => menu.dispatch({ type: "hover", hover: true })}
onPointerLeave={() => menu.dispatch({ type: "hover", hover: false })}
onPointerDown={(event: PointerEvent) => {
// The tablist redirects focus entering it to the selected tab, which counts as focus-outside and closes
// the menu.
event.preventDefault()
intent = swapped() || hasModifier(event, modifier) ? "menu" : "new"
menu.dispatch({ type: "arm", intent: swapped() || hasModifier(event, modifier) ? "menu" : "new" })
}}
onKeyDown={(event: KeyboardEvent) => {
intent = event.key === "ArrowDown" || event.key === "ArrowUp" || swapped() ? "menu" : "new"
// Only a key that activates the trigger arms it; a modifier pressed alone opens nothing.
if (!["Enter", " ", "ArrowDown", "ArrowUp"].includes(event.key)) return menu.dispatch({ type: "disarm" })
menu.dispatch({
type: "arm",
intent: event.key === "ArrowDown" || event.key === "ArrowUp" || swapped() ? "menu" : "new",
})
}}
onBlur={() => menu.dispatch({ type: "disarm" })}
onContextMenu={(event: MouseEvent) => {
if (!available()) return
event.preventDefault()
setState("open", true)
if (available()) event.preventDefault()
menu.dispatch({ type: "context.menu", available: available() })
}}
/>
<Menu.Portal>
<Menu.Content
class="min-w-64"
onCloseAutoFocus={() => {
const key = chosen
if (!key) return
chosen = undefined
setTimeout(() => {
if (document.activeElement instanceof HTMLElement) document.activeElement.blur()
props.onReopen(key)
})
}}
>
<ClosedTabsItems entries={props.entries} onReopen={(key) => (chosen = key)} />
<Menu.Content class="min-w-64" onCloseAutoFocus={() => menu.dispatch({ type: "close.autofocus" })}>
<ClosedTabsItems entries={props.entries} onReopen={(choice) => menu.dispatch({ type: "select", choice })} />
</Menu.Content>
</Menu.Portal>
</Menu>
@@ -0,0 +1,151 @@
import { describe, expect, test } from "bun:test"
import { createComposerWriteState, transitionComposerWrite, type ComposerWriteEvent } from "./composer-write-machine"
type Draft = { readonly name: string; readonly log: string[] }
/**
* Drives the machine as `mounted-session.ts` does: effects run in order, and an event an effect raises waits behind
* the effects already running, so a write a queued write makes queues behind the writes already waiting.
*/
function harness() {
const machine = { state: createComposerWriteState<Draft>() }
const queue: ComposerWriteEvent<Draft>[] = []
const observed: string[] = []
const logged: unknown[] = []
const dispatch = (event: ComposerWriteEvent<Draft>) => {
queue.push(event)
if (queue.length > 1) return
while (queue[0]) {
const next = transitionComposerWrite(machine.state, queue[0])
machine.state = next.state
next.effects.forEach((effect) => {
if (effect.type === "apply") return effect.write(effect.target)
if (effect.type === "drain") return dispatch({ type: "drain.next", target: effect.target })
if (effect.type === "observe") return void observed.push(effect.target.name)
logged.push(effect.cause)
})
queue.shift()
}
}
const loading = Promise.resolve()
const write = (draft: Draft, label: string, options: { pending?: boolean; then?: () => void } = {}) =>
dispatch({
type: "write",
target: draft,
load: options.pending ? loading : undefined,
write: (target) => {
target.log.push(label)
options.then?.()
},
})
return { machine, dispatch, write, observed, logged }
}
const draft = (name: string): Draft => ({ name, log: [] })
describe("composer write machine", () => {
test("a write to a loaded draft applies at once", () => {
const run = harness()
const a = draft("a")
run.write(a, "insert")
expect(a.log).toEqual(["insert"])
expect(run.observed).toEqual([])
})
test("writes before the draft loads wait for it, in call order", () => {
const run = harness()
const a = draft("a")
run.write(a, "one", { pending: true })
run.write(a, "two", { pending: true })
// The draft loaded but its `loaded` event has not arrived: the write still waits its turn.
run.write(a, "three")
expect(a.log).toEqual([])
expect(run.observed).toEqual(["a"])
run.dispatch({ type: "loaded", target: a })
expect(a.log).toEqual(["one", "two", "three"])
expect(run.machine.state).toEqual({ status: "active", entries: [] })
})
test("a draft that fails to load is never overwritten by the writes that waited for it", () => {
const run = harness()
const a = draft("a")
const cause = new Error("storage unavailable")
run.write(a, "insert", { pending: true })
run.dispatch({ type: "failed", target: a, cause })
run.dispatch({ type: "loaded", target: a })
expect(a.log).toEqual([])
expect(run.logged).toEqual([cause])
})
test("a loading draft never holds back or releases another session's writes", () => {
const run = harness()
const a = draft("a")
const b = draft("b")
run.write(a, "a1", { pending: true })
run.write(b, "b-ready")
expect(b.log).toEqual(["b-ready"])
run.dispatch({ type: "failed", target: a, cause: new Error("a") })
run.write(b, "b-pending", { pending: true })
// B's own load has not settled, whatever happened to A.
expect(b.log).toEqual(["b-ready"])
run.dispatch({ type: "loaded", target: b })
expect(b.log).toEqual(["b-ready", "b-pending"])
})
test("a write a waiting write makes runs after the writes already waiting", () => {
const run = harness()
const a = draft("a")
run.write(a, "attach", { pending: true, then: () => run.write(a, "nested") })
run.write(a, "focus", { pending: true })
run.dispatch({ type: "loaded", target: a })
expect(a.log).toEqual(["attach", "focus", "nested"])
})
test("disposal ignores a late load and later writes", () => {
const run = harness()
const a = draft("a")
run.write(a, "insert", { pending: true })
run.dispatch({ type: "disposed" })
run.dispatch({ type: "loaded", target: a })
run.write(a, "late")
expect(a.log).toEqual([])
expect(run.machine.state).toEqual({ status: "disposed" })
})
test("an event for a target with nothing waiting keeps the same state", () => {
const state = createComposerWriteState<Draft>()
const a = draft("a")
expect(transitionComposerWrite(state, { type: "loaded", target: a }).state).toBe(state)
expect(transitionComposerWrite(state, { type: "drain.next", target: a }).state).toBe(state)
expect(transitionComposerWrite(state, { type: "failed", target: a, cause: undefined }).state).toBe(state)
})
})
@@ -0,0 +1,111 @@
export type ComposerWrite<T> = (target: T) => void
/**
* A routed session's draft that plugin writes wait for. Writes queue in call order, including a write a queued write
* makes, which runs after the ones already waiting.
*/
export type ComposerTargetEntry<T> =
/** The draft is still loading from storage. */
| { readonly status: "loading"; readonly target: T; readonly queue: readonly ComposerWrite<T>[] }
/** The draft loaded and its waiting writes run one at a time. */
| { readonly status: "draining"; readonly target: T; readonly queue: readonly ComposerWrite<T>[] }
export type ComposerWriteState<T> =
| { readonly status: "active"; readonly entries: readonly ComposerTargetEntry<T>[] }
| { readonly status: "disposed" }
export type ComposerWriteEvent<T> =
/** `load`: the target's draft load while it is still loading; a loaded draft takes the write at once. */
| {
readonly type: "write"
readonly target: T
readonly load: Promise<unknown> | undefined
readonly write: ComposerWrite<T>
}
| { readonly type: "loaded"; readonly target: T }
/** Runs the target's next waiting write, or ends its drain. */
| { readonly type: "drain.next"; readonly target: T }
| { readonly type: "failed"; readonly target: T; readonly cause: unknown }
| { readonly type: "disposed" }
export type ComposerWriteEffect<T> =
| { readonly type: "observe"; readonly target: T; readonly load: Promise<unknown> }
| { readonly type: "apply"; readonly target: T; readonly write: ComposerWrite<T> }
| { readonly type: "drain"; readonly target: T }
| { readonly type: "log"; readonly cause: unknown }
export type ComposerWriteTransition<T> = {
readonly state: ComposerWriteState<T>
readonly effects: readonly ComposerWriteEffect<T>[]
}
export function createComposerWriteState<T>(): ComposerWriteState<T> {
return { status: "active", entries: [] }
}
export function transitionComposerWrite<T>(
state: ComposerWriteState<T>,
event: ComposerWriteEvent<T>,
): ComposerWriteTransition<T> {
if (state.status === "disposed") return { state, effects: [] }
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [] }
const entry = state.entries.find((item) => item.target === event.target)
if (event.type === "write") {
if (entry) return { state: replace(state, { ...entry, queue: [...entry.queue, event.write] }), effects: [] }
if (!event.load) return { state, effects: [{ type: "apply", target: event.target, write: event.write }] }
return {
state: {
status: "active",
entries: [...state.entries, { status: "loading", target: event.target, queue: [event.write] }],
},
effects: [{ type: "observe", target: event.target, load: event.load }],
}
}
if (event.type === "loaded") {
if (entry?.status !== "loading") return { state, effects: [] }
return {
state: replace(state, { status: "draining", target: entry.target, queue: entry.queue }),
effects: [{ type: "drain", target: entry.target }],
}
}
// A draft that failed to load stays on disk untouched: writes made before the load settled are dropped rather than
// replace it with an edited empty draft. Later writes apply as the user's own edits do.
if (event.type === "failed") {
if (entry?.status !== "loading") return { state, effects: [] }
return { state: remove(state, entry.target), effects: [{ type: "log", cause: event.cause }] }
}
if (entry?.status !== "draining") return { state, effects: [] }
const [head, ...rest] = entry.queue
if (!head) return { state: remove(state, entry.target), effects: [] }
return {
state: replace(state, { status: "draining", target: entry.target, queue: rest }),
effects: [
{ type: "apply", target: entry.target, write: head },
{ type: "drain", target: entry.target },
],
}
}
function replace<T>(state: Extract<ComposerWriteState<T>, { status: "active" }>, entry: ComposerTargetEntry<T>) {
return {
status: "active" as const,
entries: state.entries.map((item) => (item.target === entry.target ? entry : item)),
}
}
function remove<T>(state: Extract<ComposerWriteState<T>, { status: "active" }>, target: T) {
return { status: "active" as const, entries: state.entries.filter((item) => item.target !== target) }
}
@@ -0,0 +1,127 @@
import { describe, expect, test } from "bun:test"
import {
createDeferredMenuState,
DEFERRED_MENU_FALLBACK_MS,
selectDeferredMenuOpen,
transitionDeferredMenu,
type DeferredMenuEffect,
type DeferredMenuEvent,
type DeferredMenuState,
} from "./deferred-menu-machine"
function run(events: DeferredMenuEvent<string>[], state: DeferredMenuState<string> = createDeferredMenuState()) {
return events.reduce<{ state: DeferredMenuState<string>; effects: DeferredMenuEffect<string>[] }>(
(current, event) => {
const next = transitionDeferredMenu(current.state, event)
return { state: next.state, effects: [...current.effects, ...next.effects] }
},
{ state, effects: [] },
)
}
// What Kobalte reports when the "+" asks to open, as `NewTabButton` dispatches it.
const press: DeferredMenuEvent<string> = { type: "open.change", open: true, available: true, defaultIntent: "new" }
const close: DeferredMenuEvent<string> = { type: "open.change", open: false, available: true, defaultIntent: "new" }
const ran = (effects: readonly DeferredMenuEffect<string>[]) =>
effects.flatMap((effect) => (effect.type === "run.choice" ? [effect.choice] : []))
describe("deferred menu machine", () => {
test.each([
["a modifier pressed alone", [{ type: "arm", intent: "menu" }, { type: "disarm" }]],
[
"a press dragged off the trigger",
[
{ type: "hover", hover: true },
{ type: "arm", intent: "menu" },
{ type: "hover", hover: false },
],
],
["a menu opened and closed", [{ type: "arm", intent: "menu" }, press, close]],
] satisfies [string, DeferredMenuEvent<string>[]][])("after %s, a plain activation opens a new tab", (_, events) => {
const result = run([...events, press])
expect(result.effects.at(-1)).toEqual({ type: "open.new-tab" })
expect(selectDeferredMenuOpen(result.state)).toBe(false)
})
test("a press that asks for the menu opens it while it lists something", () => {
expect(selectDeferredMenuOpen(run([{ type: "arm", intent: "menu" }, press]).state)).toBe(true)
const empty = run([
{ type: "arm", intent: "menu" },
{ ...press, available: false },
])
expect(empty.effects).toEqual([{ type: "open.new-tab" }])
})
test("the menu stays shown after a choice until it reports its own close", () => {
const chosen = run([{ type: "arm", intent: "menu" }, press, { type: "select", choice: "a" }])
expect(selectDeferredMenuOpen(chosen.state)).toBe(true)
expect(selectDeferredMenuOpen(run([close], chosen.state).state)).toBe(false)
})
test("a chosen item runs once focus returns", () => {
const result = run([
{ type: "arm", intent: "menu" },
press,
{ type: "select", choice: "a" },
close,
{ type: "close.autofocus" },
])
expect(result.effects).toEqual([
{ type: "timer.start", attempt: 1, delay: DEFERRED_MENU_FALLBACK_MS },
{ type: "timer.start", attempt: 1, delay: 0 },
])
const fired = run(
[
{ type: "timer.fired", attempt: 1 },
{ type: "timer.fired", attempt: 1 },
],
result.state,
)
expect(ran(fired.effects)).toEqual(["a"])
})
test("a chosen item still runs when focus never returns, and a later Escape runs nothing", () => {
const chosen = run([{ type: "arm", intent: "menu" }, press, { type: "select", choice: "a" }, close])
const fallback = run([{ type: "timer.fired", attempt: 1 }], chosen.state)
expect(ran(fallback.effects)).toEqual(["a"])
const escaped = run([{ type: "arm", intent: "menu" }, press, close, { type: "close.autofocus" }], fallback.state)
expect(ran(escaped.effects)).toEqual([])
expect(escaped.effects.filter((effect) => effect.type === "timer.start")).toEqual([])
})
test("reopening before the choice ran runs it at once", () => {
const chosen = run([{ type: "arm", intent: "menu" }, press, { type: "select", choice: "a" }])
const reopened = run(
[
{ type: "context.menu", available: true },
{ type: "timer.fired", attempt: 1 },
],
chosen.state,
)
expect(reopened.effects).toEqual([{ type: "timer.stop" }, { type: "run.choice", choice: "a" }])
expect(selectDeferredMenuOpen(reopened.state)).toBe(true)
})
test("disposal stops the timer and drops the choice", () => {
const chosen = run([{ type: "arm", intent: "menu" }, press, { type: "select", choice: "a" }])
const disposed = run([{ type: "disposed" }, { type: "timer.fired", attempt: 1 }], chosen.state)
expect(disposed.effects).toEqual([{ type: "timer.stop" }])
expect(disposed.state).toEqual({ status: "disposed" })
})
})
@@ -0,0 +1,163 @@
/** How long a chosen item waits for the closing menu to return focus before it runs anyway. */
export const DEFERRED_MENU_FALLBACK_MS = 50
/** What a press on a dual trigger asks for: its menu, or the trigger's own action (a new tab). */
export type DeferredMenuIntent = "menu" | "new"
/**
* A menu whose chosen item runs only once the closing menu has returned focus to its trigger, so the item can move
* focus where it needs it without the trigger or tab strip taking it back.
*/
export type DeferredMenuState<T> =
/** `armed`: what the press under way asked for, read when the menu reports it opens; cleared once read. */
| {
readonly status: "closed"
readonly attempt: number
readonly hover: boolean
readonly armed: DeferredMenuIntent | undefined
}
| { readonly status: "open"; readonly attempt: number; readonly hover: boolean }
/**
* An item was chosen and runs once focus returns, or after the fallback. `attempt` names its timer; `shown`: the menu
* has not reported its own close yet.
*/
| {
readonly status: "closing"
readonly attempt: number
readonly hover: boolean
readonly shown: boolean
readonly choice: T
}
| { readonly status: "disposed" }
export type DeferredMenuEvent<T> =
| { readonly type: "hover"; readonly hover: boolean }
| { readonly type: "arm"; readonly intent: DeferredMenuIntent }
| { readonly type: "disarm" }
/** `available`: the menu has something to list. */
| { readonly type: "context.menu"; readonly available: boolean }
/** The menu asks to open or close; an open with nothing armed does `defaultIntent`. */
| {
readonly type: "open.change"
readonly open: boolean
readonly available: boolean
readonly defaultIntent: DeferredMenuIntent
}
| { readonly type: "select"; readonly choice: T }
/** The closing menu returned focus to its trigger. */
| { readonly type: "close.autofocus" }
| { readonly type: "timer.fired"; readonly attempt: number }
| { readonly type: "disposed" }
export type DeferredMenuEffect<T> =
| { readonly type: "open.new-tab" }
| { readonly type: "timer.start"; readonly attempt: number; readonly delay: number }
| { readonly type: "timer.stop" }
| { readonly type: "run.choice"; readonly choice: T }
export type DeferredMenuTransition<T> = {
readonly state: DeferredMenuState<T>
readonly effects: readonly DeferredMenuEffect<T>[]
}
export function createDeferredMenuState<T>(): DeferredMenuState<T> {
return { status: "closed", attempt: 0, hover: false, armed: undefined }
}
export function transitionDeferredMenu<T>(
state: DeferredMenuState<T>,
event: DeferredMenuEvent<T>,
): DeferredMenuTransition<T> {
if (state.status === "disposed") return { state, effects: [] }
if (event.type === "disposed")
return { state: { status: "disposed" }, effects: state.status === "closing" ? [{ type: "timer.stop" }] : [] }
if (event.type === "hover") {
if (state.status !== "closed")
return { state: state.hover === event.hover ? state : { ...state, hover: event.hover }, effects: [] }
// A press that leaves the trigger is abandoned.
const armed = event.hover ? state.armed : undefined
if (state.hover === event.hover && state.armed === armed) return { state, effects: [] }
return { state: { ...state, hover: event.hover, armed }, effects: [] }
}
if (state.status === "closed") return closed(state, event)
if (state.status === "open") {
if (event.type === "open.change" && !event.open)
return { state: closedState(state.attempt, state.hover), effects: [] }
if (event.type === "select") return choose(state.attempt, state.hover, event.choice)
return { state, effects: [] }
}
if (event.type === "select") return choose(state.attempt, state.hover, event.choice)
if (event.type === "open.change" && !event.open)
return { state: state.shown ? { ...state, shown: false } : state, effects: [] }
if (event.type === "close.autofocus")
return { state, effects: [{ type: "timer.start", attempt: state.attempt, delay: 0 }] }
if (event.type === "timer.fired" && event.attempt === state.attempt)
return { state: closedState(state.attempt, state.hover), effects: [{ type: "run.choice", choice: state.choice }] }
// Reopened before the choice ran: run it now rather than lose it.
if ((event.type === "context.menu" || (event.type === "open.change" && event.open)) && event.available)
return {
state: { status: "open", attempt: state.attempt + 1, hover: state.hover },
effects: [{ type: "timer.stop" }, { type: "run.choice", choice: state.choice }],
}
return { state, effects: [] }
}
/** The menu shows: open, or closing until it reports its own close. */
export function selectDeferredMenuOpen<T>(state: DeferredMenuState<T>) {
return state.status === "open" || (state.status === "closing" && state.shown)
}
export function selectDeferredMenuHover<T>(state: DeferredMenuState<T>) {
return state.status !== "disposed" && state.hover
}
function closed<T>(
state: Extract<DeferredMenuState<T>, { status: "closed" }>,
event: DeferredMenuEvent<T>,
): DeferredMenuTransition<T> {
if (event.type === "arm")
return { state: state.armed === event.intent ? state : { ...state, armed: event.intent }, effects: [] }
if (
event.type === "disarm" ||
(event.type === "open.change" && !event.open) ||
(event.type === "context.menu" && !event.available)
)
return { state: state.armed === undefined ? state : { ...state, armed: undefined }, effects: [] }
if (event.type === "context.menu")
return { state: { status: "open", attempt: state.attempt, hover: state.hover }, effects: [] }
if (event.type !== "open.change") return { state, effects: [] }
if ((state.armed ?? event.defaultIntent) === "menu" && event.available)
return { state: { status: "open", attempt: state.attempt, hover: state.hover }, effects: [] }
return { state: closedState(state.attempt, state.hover), effects: [{ type: "open.new-tab" }] }
}
function choose<T>(attempt: number, hover: boolean, choice: T): DeferredMenuTransition<T> {
return {
state: { status: "closing", attempt: attempt + 1, hover, shown: true, choice },
effects: [{ type: "timer.start", attempt: attempt + 1, delay: DEFERRED_MENU_FALLBACK_MS }],
}
}
function closedState<T>(attempt: number, hover: boolean): DeferredMenuState<T> {
return { status: "closed", attempt, hover, armed: undefined }
}
@@ -34,6 +34,12 @@ import { useFile } from "@/workspaces/files/model"
import { useWorkspaceLocation } from "@/workspaces/location"
import { pathKey } from "@/workspaces/path-key"
import { usePluginAttachment } from "./host-apis"
import {
createComposerWriteState,
transitionComposerWrite,
type ComposerWriteEffect,
type ComposerWriteEvent,
} from "./composer-write-machine"
const noTasks: readonly BackgroundTask[] = []
@@ -156,29 +162,64 @@ export function createMountedSession(session: SessionModel) {
}
// A write before the routed session's draft loads would replace the stored draft, so it waits for the load and then
// applies to that session. Later writes queue behind it to keep call order.
let writes: Promise<void> | undefined
// applies to that session (`composer-write-machine.ts`). Later writes to that session queue behind it to keep call
// order; other sessions' drafts do not wait for it.
const writes = { state: createComposerWriteState<ComposerStateValue>() }
// Events an effect raises synchronously, such as a write a queued write makes, wait behind that effect.
const queue: ComposerWriteEvent<ComposerStateValue>[] = []
const write = (apply: (draft: ComposerStateValue) => void) => {
const target = composer.capture()
const dispatchWrite = (event: ComposerWriteEvent<ComposerStateValue>) => {
queue.push(event)
if (!writes && composer.ready()) return apply(target)
const loaded = composer.ready() ? undefined : composer.ready.promise
if (queue.length === 1) untrack(drainWrites)
}
const next = Promise.resolve(writes)
.then(() => loaded)
.catch(() => undefined)
.then(() => apply(target))
const drainWrites = () => {
const event = queue[0]
writes = next
if (!event) return
const settle = () => {
if (writes === next) writes = undefined
try {
const next = transitionComposerWrite(writes.state, event)
writes.state = next.state
next.effects.forEach((effect) =>
Promise.try(() => runWrite(effect)).catch((cause: unknown) =>
console.error("[plugin] Composer write failed", cause),
),
)
} finally {
queue.shift()
}
void next.then(settle, settle)
drainWrites()
}
const runWrite = (effect: ComposerWriteEffect<ComposerStateValue>) => {
if (effect.type === "apply") return effect.write(effect.target)
if (effect.type === "drain") return dispatchWrite({ type: "drain.next", target: effect.target })
if (effect.type === "observe")
return void effect.load.then(
// One batch, so the waiting writes land as one change.
() => batch(() => dispatchWrite({ type: "loaded", target: effect.target })),
(cause: unknown) => dispatchWrite({ type: "failed", target: effect.target, cause }),
)
console.error("[plugin] Composer draft load failed", effect.cause)
}
onCleanup(() => dispatchWrite({ type: "disposed" }))
const write = (apply: (draft: ComposerStateValue) => void) =>
dispatchWrite({
type: "write",
target: composer.capture(),
load: composer.ready() ? undefined : composer.ready.promise,
write: apply,
})
// A subagent's session has no composer, so its draft is never sent.
const edit = (apply: (draft: ReturnType<typeof createComposerEditorActions>) => void) => {
if (!session.data.isChild()) write((target) => apply(createComposerEditorActions(target.store)))
@@ -233,9 +274,12 @@ export function createMountedSession(session: SessionModel) {
focus(commentID, options) {
if (commentID === undefined) return prompt()?.focus()
const item = composer.context.items().find((entry) => entry.type === "quote" && entry.commentID === commentID)
// Behind the writes still waiting, so it finds a quote an `attach` just before it added.
write((draft) => {
const item = draft.context.items().find((entry) => entry.type === "quote" && entry.commentID === commentID)
if (item) composer.capture().quoteComment.set(item.key, options?.anchor)
if (item) draft.quoteComment.set(item.key, options?.anchor)
})
},
update: (id, patch) => write((draft) => draft.context.updateComment(id, patch)),
detach: (id) => write((draft) => draft.context.removeComment(id)),
@@ -0,0 +1,196 @@
import { describe, expect, test } from "bun:test"
import type { SessionPane } from "@/shell/state/session-tabs"
import {
createNewTabsState,
selectHasNewTabs,
selectPaneNewTabs,
selectShownNewTab,
transitionNewTabs,
type NewTabsEvent,
type NewTabsState,
type PaneTabSnapshot,
type RegionTabSnapshot,
} from "./new-tab-machine"
type Region = {
session?: string
sideOpen?: boolean
regionActive?: string
side?: PaneTabSnapshot
split?: PaneTabSnapshot
bottom?: PaneTabSnapshot
}
const none: PaneTabSnapshot = { active: undefined, keys: [] }
function snapshot(region: Region): RegionTabSnapshot {
const panes = { side: region.side ?? none, split: region.split ?? none, bottom: region.bottom ?? none }
return {
session: region.session ?? "s1",
empty: Object.values(panes).every((pane) => pane.keys.length === 0),
regionActive: region.regionActive,
sideOpen: region.sideOpen ?? false,
panes,
}
}
const sync = (region: Region): NewTabsEvent => ({ type: "sync", snapshot: snapshot(region) })
function run(events: NewTabsEvent[], state: NewTabsState = createNewTabsState()) {
return events.reduce(
(current, event) => {
const next = transitionNewTabs(current.state, event)
return { state: next.state, emptied: current.emptied + next.effects.length }
},
{ state, emptied: 0 },
)
}
function shown(state: NewTabsState, region: Region, pane: SessionPane) {
return selectShownNewTab(state, pane, snapshot(region).panes[pane].active)
}
describe("new tab machine", () => {
test("closing a tab in another pane keeps the side pane's New tab", () => {
// The side pane falls back to README while the split pane's terminal holds the region's selection.
const before: Region = {
regionActive: "term:1",
side: { active: "file://README.md", keys: ["review:changes", "file://README.md"] },
split: { active: "term:1", keys: ["term:1"] },
}
// Closing the terminal moves the region's selection to the first tab, which the side pane now shows.
const after: Region = {
regionActive: "review:changes",
side: { active: "review:changes", keys: ["review:changes", "file://README.md"] },
}
const result = run([sync(before), { type: "open", pane: "side" }, sync(after)])
expect(selectPaneNewTabs(result.state, "side")).toEqual(["new:1"])
expect(shown(result.state, after, "side")).toBe("new:1")
})
test("a launcher that replaces the preview tab in place replaces the New tab", () => {
const before: Region = { regionActive: "file://foo.ts", side: { active: "file://foo.ts", keys: ["file://foo.ts"] } }
const after: Region = { regionActive: "file://bar.ts", side: { active: "file://bar.ts", keys: ["file://bar.ts"] } }
const result = run([sync(before), { type: "open", pane: "side" }, sync(after)])
expect(selectPaneNewTabs(result.state, "side")).toEqual([])
expect(result.state.panes.side.chosen).toBeUndefined()
})
test("a launcher that selects an already listed tab replaces the New tab", () => {
const before: Region = { regionActive: "a", side: { active: "a", keys: ["a", "b"] } }
const after: Region = { regionActive: "b", side: { active: "b", keys: ["a", "b"] } }
const result = run([sync(before), { type: "open", pane: "side" }, { type: "open", pane: "side" }, sync(after)])
// Only the shown one goes; the other New tab stays, and nothing is chosen.
expect(result.state.panes.side).toEqual({ ids: ["new:1"], chosen: undefined })
expect(shown(result.state, after, "side")).toBeUndefined()
})
test("closing the pane's selected tab falls back and keeps the New tab", () => {
const before: Region = { regionActive: "a", side: { active: "a", keys: ["a", "b"] } }
const after: Region = { regionActive: "b", side: { active: "b", keys: ["b"] } }
const result = run([sync(before), { type: "open", pane: "side" }, sync(after)])
expect(shown(result.state, after, "side")).toBe("new:1")
})
test("selecting a strip tab shows it over the New tab, which stays", () => {
const before: Region = { regionActive: "a", side: { active: "a", keys: ["a", "b"] } }
const after: Region = { regionActive: "b", side: { active: "b", keys: ["a", "b"] } }
const result = run([
sync(before),
{ type: "open", pane: "side" },
{ type: "select.tab", pane: "side" },
sync(after),
])
expect(result.state.panes.side).toEqual({ ids: ["new:1"], chosen: undefined })
})
test("a split pane that loses its last tab takes its New tabs and choice with it", () => {
const open: Region = { regionActive: "t", side: none, split: { active: "t", keys: ["t"] } }
const closed: Region = { side: { active: "a", keys: ["a"] } }
const result = run([sync(open), { type: "open", pane: "split" }, sync(closed)])
expect(result.state.panes.split).toEqual({ ids: [], chosen: undefined })
})
test("another session starts without the previous session's New tabs", () => {
const region: Region = { side: { active: "a", keys: ["a"] }, regionActive: "a" }
const result = run([sync(region), { type: "open", pane: "side" }, sync({ ...region, session: "s2" })])
expect(result.state.panes.side).toEqual({ ids: [], chosen: undefined })
})
test("selecting a New tab that is not listed changes nothing", () => {
const state = run([sync({ side: { active: "a", keys: ["a"] } })]).state
const next = transitionNewTabs(state, { type: "select.new", pane: "side", id: "new:9" })
expect(next.state).toBe(state)
})
test("opening an empty side region opens one New tab per opening", () => {
const empty: Region = { sideOpen: true }
const opened = run([sync({}), sync(empty)])
expect(selectPaneNewTabs(opened.state, "side")).toEqual(["new:1"])
// Closing it inside the same opening does not bring it back.
const dismissed = run([{ type: "dismiss", id: "new:1", empty: true }, sync(empty)], opened.state)
expect(dismissed.emptied).toBe(1)
expect(selectHasNewTabs(dismissed.state)).toBe(false)
// The next opening shows one again.
const reopened = run([sync({}), sync(empty)], dismissed.state)
expect(selectPaneNewTabs(reopened.state, "side")).toEqual(["new:2"])
})
test("an opening keeps a New tab left from an earlier one rather than adding another", () => {
const result = run([sync({}), { type: "open", pane: "side" }, sync({ sideOpen: true })])
expect(selectPaneNewTabs(result.state, "side")).toEqual(["new:1"])
})
test("routing into an open, empty side region opens a New tab for that session", () => {
const result = run([sync({ sideOpen: true }), sync({ sideOpen: true, session: "s2" })])
expect(selectPaneNewTabs(result.state, "side")).toEqual(["new:2"])
})
test("closing the shown New tab shows the one after it, else the one before", () => {
const region: Region = { side: { active: "a", keys: ["a"] }, regionActive: "a" }
const three = run([
sync(region),
{ type: "open", pane: "side" },
{ type: "open", pane: "side" },
{ type: "open", pane: "side" },
{ type: "select.new", pane: "side", id: "new:2" },
])
const middle = run([{ type: "dismiss", id: "new:2", empty: false }], three.state)
expect(middle.state.panes.side).toEqual({ ids: ["new:1", "new:3"], chosen: "new:3" })
const last = run([{ type: "dismiss", id: "new:3", empty: false }], middle.state)
expect(last.state.panes.side).toEqual({ ids: ["new:1"], chosen: "new:1" })
expect(last.emptied).toBe(0)
})
test("a sync that changes nothing returns the same state", () => {
const region: Region = { side: { active: "a", keys: ["a"] }, regionActive: "a" }
const state = run([sync(region)]).state
expect(transitionNewTabs(state, sync(region)).state).toBe(state)
})
})
@@ -0,0 +1,223 @@
import { SESSION_PANES, type SessionPane } from "@/shell/state/session-tabs"
/** A pane's drawn tabs and the tab it selects. */
export type PaneTabSnapshot = {
readonly active: string | undefined
readonly keys: readonly string[]
}
/** What the region shows, read each time it changes. */
export type RegionTabSnapshot = {
/** The routed session's key. */
readonly session: string
/** The strip holds no tab, hidden ones included. */
readonly empty: boolean
/** The tab the region selects, in any pane. */
readonly regionActive: string | undefined
/** The side region is open on screen, after the layout loaded. */
readonly sideOpen: boolean
readonly panes: Readonly<Record<SessionPane, PaneTabSnapshot>>
}
/** A pane's New tabs, in strip order, and the one it shows over its selected tab. */
export type PaneNewTabs = {
readonly ids: readonly string[]
/** Always `undefined` or an element of `ids`. */
readonly chosen: string | undefined
}
/**
* The host's New tab views, each listing the launchers in a pane until the user closes it or a tab opened from it
* replaces it. They belong to the session they opened in.
*/
export type NewTabsState = {
readonly serial: number
readonly session: string
/** The current session is in an open-and-empty span of the side region, which opened its New tab once. */
readonly openedEmpty: boolean
readonly panes: Readonly<Record<SessionPane, PaneNewTabs>>
/** The region as the last `sync` saw it, which the next one compares against. */
readonly snapshot: RegionTabSnapshot | undefined
}
export type NewTabsEvent =
| { readonly type: "sync"; readonly snapshot: RegionTabSnapshot }
| { readonly type: "open"; readonly pane: SessionPane }
| { readonly type: "select.new"; readonly pane: SessionPane; readonly id: string }
/** The user selects a tab of the pane, which shows over its New tabs. */
| { readonly type: "select.tab"; readonly pane: SessionPane }
/** `empty`: the strip holds no tab, so closing the last New tab empties the region. */
| { readonly type: "dismiss"; readonly id: string; readonly empty: boolean }
/** The last New tab of a strip with no tabs closed: the region closes, as closing its last tab does. */
export type NewTabsEffect = { readonly type: "emptied" }
export type NewTabsTransition = {
readonly state: NewTabsState
readonly effects: readonly NewTabsEffect[]
}
export function createNewTabsState(): NewTabsState {
return { serial: 0, session: "", openedEmpty: false, panes: emptyPanes(), snapshot: undefined }
}
export function transitionNewTabs(state: NewTabsState, event: NewTabsEvent): NewTabsTransition {
if (event.type === "sync") return { state: sync(state, event.snapshot), effects: [] }
if (event.type === "open") return { state: open(state, event.pane), effects: [] }
if (event.type === "select.new") {
const pane = state.panes[event.pane]
if (!pane.ids.includes(event.id) || pane.chosen === event.id) return { state, effects: [] }
return { state: withPane(state, event.pane, { ids: pane.ids, chosen: event.id }), effects: [] }
}
if (event.type === "select.tab") {
const pane = state.panes[event.pane]
if (pane.chosen === undefined) return { state, effects: [] }
return { state: withPane(state, event.pane, { ids: pane.ids, chosen: undefined }), effects: [] }
}
const owner = SESSION_PANES.find((pane) => state.panes[pane].ids.includes(event.id))
if (!owner) return { state, effects: [] }
// Closing the shown New tab shows the one after it, else the one before, as a browser does.
const pane = state.panes[owner]
const index = pane.ids.indexOf(event.id)
const chosen = pane.chosen === event.id ? (pane.ids[index + 1] ?? pane.ids[index - 1]) : pane.chosen
const next = withPane(state, owner, { ids: pane.ids.filter((id) => id !== event.id), chosen })
return { state: next, effects: event.empty && !selectHasNewTabs(next) ? [{ type: "emptied" }] : [] }
}
/** The New tabs a pane lists, in strip order. */
export function selectPaneNewTabs(state: NewTabsState, pane: SessionPane) {
return state.panes[pane].ids
}
/** The New tab a pane shows: the chosen one, else the newest while the pane selects no tab. */
export function selectShownNewTab(state: NewTabsState, pane: SessionPane, paneActive: string | undefined) {
return shown(state.panes[pane], paneActive)
}
export function selectHasNewTabs(state: NewTabsState) {
return SESSION_PANES.some((pane) => state.panes[pane].ids.length > 0)
}
function sync(state: NewTabsState, snapshot: RegionTabSnapshot): NewTabsState {
// Another session starts with none, and opens one when it routes into an open, empty side region.
if (snapshot.session !== state.session) {
const reset = { ...state, session: snapshot.session, panes: emptyPanes(), snapshot }
const openedEmpty = snapshot.sideOpen && snapshot.empty
return openedEmpty ? open({ ...reset, openedEmpty }, "side") : { ...reset, openedEmpty }
}
const previous = state.snapshot
const listed = new Set(SESSION_PANES.flatMap((pane) => snapshot.panes[pane].keys))
const syncPane = (pane: SessionPane): PaneNewTabs => {
const current = state.panes[pane]
const next = snapshot.panes[pane]
// A split or bottom pane closes with its last tab, and its New tabs go with it.
if (pane !== "side" && next.keys.length === 0)
return current.ids.length === 0 ? current : { ids: [], chosen: undefined }
if (!previous) return current
const before = previous.panes[pane]
const replaced = shown(current, before.active)
if (!replaced || !replacedBy(before, next, previous.regionActive, listed)) return current
return { ids: current.ids.filter((id) => id !== replaced), chosen: undefined }
}
const panes = { side: syncPane("side"), split: syncPane("split"), bottom: syncPane("bottom") }
const changed = SESSION_PANES.some((pane) => panes[pane] !== state.panes[pane])
const synced: NewTabsState = {
...state,
panes: changed ? panes : state.panes,
snapshot: previous && sameSnapshot(previous, snapshot) ? previous : snapshot,
}
// Opening the side region with no tabs shows a New tab, once per opening. One left from an earlier opening shows
// again rather than being joined by another.
const want = snapshot.sideOpen && snapshot.empty
const opened = want && !state.openedEmpty
const result =
opened && selectShownNewTab(synced, "side", snapshot.panes.side.active) === undefined
? open({ ...synced, openedEmpty: true }, "side")
: { ...synced, openedEmpty: want }
if (result.panes === state.panes && result.openedEmpty === state.openedEmpty && result.snapshot === previous)
return state
return result
}
/**
* A tab that selects itself while a New tab shows replaces that New tab, as one a launcher in it opens does: a tab new
* to the pane, or a listed tab while the tab the pane and region selected stay listed. A pane falling back to another
* tab after its own or the region's selected tab closed or moved away keeps it.
*/
function replacedBy(
before: PaneTabSnapshot,
next: PaneTabSnapshot,
regionActive: string | undefined,
listed: ReadonlySet<string>,
) {
if (next.active === undefined || next.active === before.active) return false
if (!before.keys.includes(next.active)) return true
return (
(before.active === undefined || next.keys.includes(before.active)) &&
(regionActive === undefined || listed.has(regionActive))
)
}
function open(state: NewTabsState, pane: SessionPane): NewTabsState {
const serial = state.serial + 1
const id = `new:${serial}`
return { ...withPane(state, pane, { ids: [...state.panes[pane].ids, id], chosen: id }), serial }
}
function shown(pane: PaneNewTabs, paneActive: string | undefined) {
return pane.chosen ?? (paneActive === undefined ? pane.ids.at(-1) : undefined)
}
function withPane(state: NewTabsState, pane: SessionPane, value: PaneNewTabs): NewTabsState {
return { ...state, panes: { ...state.panes, [pane]: value } }
}
function emptyPanes(): Record<SessionPane, PaneNewTabs> {
return {
side: { ids: [], chosen: undefined },
split: { ids: [], chosen: undefined },
bottom: { ids: [], chosen: undefined },
}
}
function sameSnapshot(a: RegionTabSnapshot, b: RegionTabSnapshot) {
return (
a.session === b.session &&
a.empty === b.empty &&
a.regionActive === b.regionActive &&
a.sideOpen === b.sideOpen &&
SESSION_PANES.every(
(pane) =>
a.panes[pane].active === b.panes[pane].active &&
a.panes[pane].keys.length === b.panes[pane].keys.length &&
a.panes[pane].keys.every((key, index) => key === b.panes[pane].keys[index]),
)
)
}
+56 -84
View File
@@ -2,15 +2,17 @@ import {
batch,
createEffect,
createMemo,
createRenderEffect,
createSignal,
For,
mergeProps,
on,
onCleanup,
Show,
untrack,
type Accessor,
type JSX,
} from "solid-js"
import { createStore } from "solid-js/store"
import { Schema } from "effect"
import { createMediaQuery } from "@solid-primitives/media"
import {
@@ -30,6 +32,13 @@ import { Contribution } from "./render"
import { usePluginAttachment } from "./attachment"
import { legacyKeys, panelKey } from "./panel-keys"
import { closedEntry, createSideFocus, type ClosedTabs } from "./closed-tabs"
import {
createNewTabsState,
selectPaneNewTabs,
selectShownNewTab,
transitionNewTabs,
type NewTabsEvent,
} from "./new-tab-machine"
type Tabs = Accessor<{
tabs(): SessionTabs
@@ -320,62 +329,6 @@ export function createRegion(input: {
return entry ? paneOf(entry) : "side"
})
// The host's new tab views, each listing the launchers in a pane until the user closes it or a tab selected from it
// replaces it. They belong to the session they opened in. A split or bottom pane closes with its last tab, and its
// New tabs go with it.
type NewTab = { id: string; pane: SessionPane; session: string }
const [state, setState] = createStore<{
adding: NewTab[]
// The New tab each pane shows over its selected tab; none shows the selected tab.
chosen: Partial<Record<SessionPane, string>>
}>({ adding: [], chosen: {} })
let serial = 0
const live = (value: NewTab) =>
value.session === input.view().key && (value.pane === "side" || panes[value.pane].keys().length > 0)
const newTabs = (pane: SessionPane) => state.adding.filter((value) => value.pane === pane && live(value))
// A pane with no tab of its own shows its newest New tab.
const shownNewTab = (pane: SessionPane) => {
const list = newTabs(pane)
const chosen = list.find((value) => value.id === state.chosen[pane])
if (chosen) return chosen
if (panes[pane].active() !== undefined) return undefined
return list.at(-1)
}
createEffect(() => {
if (state.adding.some((value) => !live(value))) setState("adding", (list) => list.filter(live))
})
// A tab that selects itself while a New tab shows replaces that New tab, as one a launcher in it opens does. The other
// New tabs stay. Selecting a tab in the strip unchooses the New tab first, and the pane falling back to another tab
// after its selected tab closes or moves away keeps it.
for (const pane of ["side", "split", "bottom"] as const) {
createEffect(
on(
() => ({
key: panes[pane].active(),
keys: panes[pane].keys(),
chosen: state.chosen[pane],
shown: shownNewTab(pane)?.id,
}),
(next, prev) => {
if (!prev?.shown || !next.key || next.key === prev.key || next.chosen !== prev.chosen) return
if (prev.key && !next.keys.includes(prev.key)) return
setState("adding", (list) => list.filter((value) => value.id !== prev.shown))
},
),
)
}
const empty = createMemo(() => strip().length === 0)
// Focus leaves before the close starts, back to where it was; otherwise the panel hands it to its toggle.
@@ -393,22 +346,43 @@ export function createRegion(input: {
input.onEmptied?.()
}
// Closing the shown New tab shows the New tab after it, else the one before, as a browser does. Closing the last New
// tab of a strip with no tabs closes the region, as closing its last tab does.
const dismissNewTab = (id: string) =>
batch(() => {
const closing = state.adding.find((value) => value.id === id)
// The host's New tab views (`new-tab-machine.ts`). The side region reports whether it is open on screen.
const [newTabsState, setNewTabsState] = createSignal(createNewTabsState())
const [sideOpen, setSideOpen] = createSignal(false)
if (closing && state.chosen[closing.pane] === id) {
const list = newTabs(closing.pane)
const index = list.findIndex((value) => value.id === id)
setState("chosen", closing.pane, (list[index + 1] ?? list[index - 1])?.id)
}
const dispatchNewTabs = (event: NewTabsEvent) => {
const next = transitionNewTabs(untrack(newTabsState), event)
setState("adding", (list) => list.filter((value) => value.id !== id))
setNewTabsState(next.state)
if (empty() && !state.adding.some(live)) emptied()
})
if (next.effects.length > 0) emptied()
}
// Feeds the machine the region's tabs each time they change: a tab that selects itself replaces the New tab its pane
// shows, a split or bottom pane takes its New tabs when it closes, and an open, empty side region opens one.
createRenderEffect(() =>
dispatchNewTabs({
type: "sync",
snapshot: {
session: input.view().key,
empty: empty(),
regionActive: active(),
sideOpen: sideOpen(),
panes: {
side: { active: panes.side.active(), keys: panes.side.keys() },
split: { active: panes.split.active(), keys: panes.split.keys() },
bottom: { active: panes.bottom.active(), keys: panes.bottom.keys() },
},
},
}),
)
const newTabs = (pane: SessionPane) => selectPaneNewTabs(newTabsState(), pane)
const shownNewTab = (pane: SessionPane) => selectShownNewTab(newTabsState(), pane, panes[pane].active())
// Closing the last New tab of a strip with no tabs closes the region, as closing its last tab does.
const dismissNewTab = (id: string) => batch(() => dispatchNewTabs({ type: "dismiss", id, empty: untrack(empty) }))
return {
/** Whether a key event belongs to the side region rather than the session around it. */
@@ -434,37 +408,34 @@ export function createRegion(input: {
/** Selects a tab and shows it over the New tab its pane showed, which stays in the strip. */
select(key: string) {
batch(() => {
setState("chosen", paneOfKey(key), undefined)
dispatchNewTabs({ type: "select.tab", pane: paneOfKey(key) })
input.tabs().setActive(key)
})
},
/** The live new tab views of a pane, in strip order. */
/** The new tab views of a pane, by id in strip order. */
newTabs,
/** The new tab view a pane shows: the chosen one, else the newest while the pane selects no tab. */
/** The id of the new tab view a pane shows: the chosen one, else the newest while the pane selects no tab. */
shownNewTab,
newTab: (pane: SessionPane) => shownNewTab(pane) !== undefined,
selectNewTab(pane: SessionPane, id: string) {
setState("chosen", pane, id)
dispatchNewTabs({ type: "select.new", pane, id })
},
/** Adds a new tab view in a pane, by default the one holding the selected tab, and shows it. */
openNewTab(pane: SessionPane = activePane()) {
const id = `new:${++serial}`
batch(() => {
setState("adding", (list) => [...list, { id, pane, session: input.view().key }])
setState("chosen", pane, id)
})
dispatchNewTabs({ type: "open", pane })
},
dismissNewTab,
/** Closes the shown new tab view in the given or active pane; returns whether one was showing. */
closeNewTab(pane: SessionPane = activePane()) {
const value = shownNewTab(pane)
const id = shownNewTab(pane)
if (!value) return false
dismissNewTab(value.id)
if (!id) return false
dismissNewTab(id)
return true
},
/** The side region reports whether it is open on screen, which opens a New tab in an empty one. */
syncSideOpen: (open: boolean) => void setSideOpen(open),
/** Opens or closes the side region for the user. Opening moves focus into it once it lands; closing gives focus back. */
toggle() {
const side = input.side()
@@ -502,7 +473,8 @@ export function createRegion(input: {
batch(() => {
input.tabs().close(key)
if (last && !state.adding.some(live)) emptied()
// The strip is empty now, so a split or bottom pane closed and only the side pane's New tabs remain.
if (last && selectPaneNewTabs(untrack(newTabsState), "side").length === 0) emptied()
})
if (entry)
@@ -0,0 +1,186 @@
import { describe, expect, test } from "bun:test"
import type { BridgePluginGui, BridgePluginGuis } from "@opencode/plugin/gui/host"
import {
createPluginGuiState,
transitionPluginGui,
type LoadedPluginGui,
type PluginGuiEffect,
type PluginGuiEvent,
type PluginGuiState,
} from "./plugin-gui-machine"
const gui = (id: string, revision: string): BridgePluginGui => ({ id, revision, code: "", options: {} })
const guis = (plugins: BridgePluginGui[], reserved: string[] = []): BridgePluginGuis => ({ plugins, reserved })
const evaluated = (plugin: BridgePluginGui): LoadedPluginGui => ({
id: plugin.id,
revision: plugin.revision,
options: plugin.options,
definition: { id: plugin.id },
})
function run(events: PluginGuiEvent[], state: PluginGuiState = createPluginGuiState().state) {
return events.reduce<{ state: PluginGuiState; effects: PluginGuiEffect[] }>(
(current, event) => {
const next = transitionPluginGui(current.state, event)
return { state: next.state, effects: [...current.effects, ...next.effects] }
},
{ state, effects: [] },
)
}
function published(effects: readonly PluginGuiEffect[]) {
return effects.flatMap((effect) =>
effect.type === "publish" ? [effect.plugins.map((plugin) => `${plugin.id}@${plugin.revision}`)] : [],
)
}
describe("plugin GUI machine", () => {
test("starts the first request with its timeout", () => {
expect(createPluginGuiState()).toEqual({
state: { status: "awaiting", attempt: 1 },
effects: [
{ type: "fetch.initial", attempt: 1 },
{ type: "timer.start", attempt: 1 },
],
})
})
test("a rejected first request settles with no plugins, and a later push recovers", () => {
const failed = run([{ type: "initial.failed", attempt: 1, cause: new Error("ipc") }])
expect(failed.state.status).toBe("failed")
expect(failed.effects).toContainEqual({ type: "timer.stop" })
expect(published(failed.effects)).toEqual([[]])
const acme = gui("acme", "r1")
const pushed = transitionPluginGui(failed.state, { type: "pushed", guis: guis([acme]) })
expect(pushed.state).toMatchObject({ status: "evaluating", settled: true })
const loaded = transitionPluginGui(pushed.state, {
type: "evaluated",
attempt: pushed.state.status === "evaluating" ? pushed.state.attempt : 0,
loaded: [evaluated(acme)],
})
expect(published(loaded.effects)).toEqual([["acme@r1"]])
})
test("a first request main never answers times out and settles", () => {
const timedOut = run([{ type: "timeout", attempt: 1 }])
expect(timedOut.state.status).toBe("failed")
expect(published(timedOut.effects)).toEqual([[]])
// The reply that finally arrives still loads.
const late = transitionPluginGui(timedOut.state, {
type: "initial.resolved",
attempt: 1,
guis: guis([gui("acme", "r1")]),
})
expect(late.state.status).toBe("evaluating")
})
test("a push before the first reply wins, and the late reply is ignored", () => {
const pushed = run([{ type: "pushed", guis: guis([], ["file"]) }])
expect(pushed.effects).toEqual([{ type: "timer.stop" }, { type: "publish", plugins: [], reserved: ["file"] }])
const late = transitionPluginGui(pushed.state, {
type: "initial.resolved",
attempt: 1,
guis: guis([gui("acme", "r1")]),
})
expect(late.state).toBe(pushed.state)
expect(late.effects).toEqual([])
})
test("a slow evaluation of an older push never lands over a newer one", () => {
const r1 = gui("acme", "r1")
const r2 = gui("acme", "r2")
const first = run([{ type: "initial.resolved", attempt: 1, guis: guis([r1]) }])
const second = transitionPluginGui(first.state, { type: "pushed", guis: guis([r2]) })
const fast = transitionPluginGui(second.state, { type: "evaluated", attempt: 3, loaded: [evaluated(r2)] })
expect(published(fast.effects)).toEqual([["acme@r2"]])
const slow = transitionPluginGui(fast.state, { type: "evaluated", attempt: 2, loaded: [evaluated(r1)] })
expect(slow.state).toBe(fast.state)
expect(slow.effects).toEqual([])
expect(fast.state.status === "loaded" && fast.state.cache.get("acme")?.revision).toBe("r2")
})
test("a removed plugin is not brought back by a slower evaluation", () => {
const r1 = gui("acme", "r1")
const first = run([{ type: "initial.resolved", attempt: 1, guis: guis([r1]) }])
const removed = transitionPluginGui(first.state, { type: "pushed", guis: guis([]) })
expect(published(removed.effects)).toEqual([[]])
const slow = transitionPluginGui(removed.state, { type: "evaluated", attempt: 2, loaded: [evaluated(r1)] })
expect(slow.state).toBe(removed.state)
expect(removed.state.status === "loaded" && removed.state.cache.size).toBe(0)
})
test("an unchanged revision publishes the cached definition without evaluating", () => {
const acme = gui("acme", "r1")
const definition = evaluated(acme)
const loaded = run([
{ type: "initial.resolved", attempt: 1, guis: guis([acme]) },
{ type: "evaluated", attempt: 2, loaded: [definition] },
])
const again = transitionPluginGui(loaded.state, { type: "pushed", guis: guis([acme], ["x"]) })
expect(again.effects).toEqual([{ type: "publish", plugins: [definition], reserved: ["x"] }])
})
test("a first evaluation that fails settles empty, keeping the reserved ids", () => {
const failed = run([
{ type: "initial.resolved", attempt: 1, guis: guis([gui("acme", "r1")], ["file"]) },
{ type: "evaluate.failed", attempt: 2, cause: new Error("chunk") },
])
expect(failed.state.status).toBe("failed")
expect(failed.effects).toContainEqual({ type: "publish", plugins: [], reserved: ["file"] })
})
test("a reload that fails keeps the plugins that already run", () => {
const r1 = gui("acme", "r1")
const loaded = run([
{ type: "initial.resolved", attempt: 1, guis: guis([r1]) },
{ type: "evaluated", attempt: 2, loaded: [evaluated(r1)] },
])
const reload = run(
[
{ type: "pushed", guis: guis([gui("acme", "r2")]) },
{ type: "evaluate.failed", attempt: 3, cause: new Error("chunk") },
],
loaded.state,
)
expect(reload.state.status === "loaded" && reload.state.cache.get("acme")?.revision).toBe("r1")
expect(published(reload.effects)).toEqual([])
})
test("disposal stops the timer and ignores late results", () => {
const disposed = transitionPluginGui(createPluginGuiState().state, { type: "disposed" })
expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "timer.stop" }] })
const late = transitionPluginGui(disposed.state, { type: "initial.resolved", attempt: 1, guis: guis([]) })
expect(late.state).toBe(disposed.state)
expect(late.effects).toEqual([])
})
})
@@ -0,0 +1,178 @@
import type { PluginOptions } from "@opencode/plugin/gui"
import type { BridgePluginGui, BridgePluginGuis, Entry } from "@opencode/plugin/gui/host"
/** How long main may take to answer the first request before the window settles with no plugin GUIs. */
export const PLUGIN_GUI_INITIAL_TIMEOUT_MS = 10_000
/** A plugin's `./gui-experimental` bundle as this window evaluated it, at one revision. */
export type LoadedPluginGui = {
readonly id: string
readonly revision: string
readonly definition: Entry
readonly options: PluginOptions
}
type Cache = ReadonlyMap<string, LoadedPluginGui>
const EMPTY: Cache = new Map()
/**
* The plugin GUIs this window runs. `attempt` names the request or evaluation whose result counts; a push starts a new
* one, so a slower result of an older list never lands.
*/
export type PluginGuiState =
/** Waiting for main's first list, by reply or push. */
| { readonly status: "awaiting"; readonly attempt: number }
/** Evaluating the bundles of `target` that `cache` does not hold at their revision. */
| {
readonly status: "evaluating"
readonly attempt: number
/** An earlier list or failure already published, so the window has settled. */
readonly settled: boolean
readonly target: BridgePluginGuis
readonly cache: Cache
}
/** Published; `cache` holds each running plugin at its revision, so an unchanged one keeps its definition. */
| { readonly status: "loaded"; readonly attempt: number; readonly cache: Cache }
/** The first list never came or did not evaluate: published empty so themes settle, until main pushes again. */
| { readonly status: "failed"; readonly attempt: number }
| { readonly status: "disposed" }
export type PluginGuiEvent =
| { readonly type: "initial.resolved"; readonly attempt: number; readonly guis: BridgePluginGuis }
| { readonly type: "initial.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "timeout"; readonly attempt: number }
| { readonly type: "pushed"; readonly guis: BridgePluginGuis }
| { readonly type: "evaluated"; readonly attempt: number; readonly loaded: readonly LoadedPluginGui[] }
| { readonly type: "evaluate.failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "disposed" }
export type PluginGuiEffect =
| { readonly type: "fetch.initial"; readonly attempt: number }
| { readonly type: "timer.start"; readonly attempt: number }
| { readonly type: "timer.stop" }
| { readonly type: "evaluate"; readonly attempt: number; readonly plugins: readonly BridgePluginGui[] }
| { readonly type: "publish"; readonly plugins: readonly LoadedPluginGui[]; readonly reserved: readonly string[] }
| { readonly type: "log"; readonly cause: unknown }
export type PluginGuiTransition = {
readonly state: PluginGuiState
readonly effects: readonly PluginGuiEffect[]
}
const TIMER_STOP: PluginGuiEffect = { type: "timer.stop" }
/** Asks main for its list, bounded by a timeout. */
export function createPluginGuiState(): PluginGuiTransition {
return {
state: { status: "awaiting", attempt: 1 },
effects: [
{ type: "fetch.initial", attempt: 1 },
{ type: "timer.start", attempt: 1 },
],
}
}
export function transitionPluginGui(state: PluginGuiState, event: PluginGuiEvent): PluginGuiTransition {
if (state.status === "disposed") return { state, effects: [] }
if (event.type === "disposed")
return { state: { status: "disposed" }, effects: state.status === "awaiting" ? [TIMER_STOP] : [] }
if (state.status === "awaiting") {
if (event.type === "pushed") return receive(state.attempt + 1, false, EMPTY, event.guis, true)
if (event.type !== "initial.resolved" && event.type !== "initial.failed" && event.type !== "timeout")
return { state, effects: [] }
if (event.attempt !== state.attempt) return { state, effects: [] }
if (event.type === "initial.resolved") return receive(state.attempt + 1, false, EMPTY, event.guis, true)
return {
state: { status: "failed", attempt: state.attempt },
effects: [
TIMER_STOP,
{ type: "publish", plugins: [], reserved: [] },
{ type: "log", cause: event.type === "timeout" ? new Error("Main did not list plugin GUIs") : event.cause },
],
}
}
if (event.type === "pushed") {
if (state.status === "evaluating") return receive(state.attempt + 1, state.settled, state.cache, event.guis, false)
return receive(state.attempt + 1, true, state.status === "loaded" ? state.cache : EMPTY, event.guis, false)
}
// A first reply slower than the timeout still loads, unless main pushed a newer list since.
if (state.status === "failed" && event.type === "initial.resolved" && event.attempt === state.attempt)
return receive(state.attempt + 1, true, EMPTY, event.guis, false)
if (state.status !== "evaluating") return { state, effects: [] }
if (event.type === "evaluated" && event.attempt === state.attempt) {
const fresh = toCache(event.loaded)
const plugins = state.target.plugins.flatMap((plugin) => {
const loaded = fresh.get(plugin.id) ?? state.cache.get(plugin.id)
return loaded ? [loaded] : []
})
return {
state: { status: "loaded", attempt: state.attempt, cache: toCache(plugins) },
effects: [{ type: "publish", plugins, reserved: state.target.reserved }],
}
}
if (event.type !== "evaluate.failed" || event.attempt !== state.attempt) return { state, effects: [] }
// After a reload fails, the plugins that already run keep running.
if (state.settled)
return {
state: { status: "loaded", attempt: state.attempt, cache: state.cache },
effects: [{ type: "log", cause: event.cause }],
}
return {
state: { status: "failed", attempt: state.attempt },
effects: [
{ type: "publish", plugins: [], reserved: state.target.reserved },
{ type: "log", cause: event.cause },
],
}
}
/** Publishes a list whose every revision is cached, or evaluates the bundles that are new to this window. */
function receive(
attempt: number,
settled: boolean,
cache: Cache,
guis: BridgePluginGuis,
stopTimer: boolean,
): PluginGuiTransition {
const stop = stopTimer ? [TIMER_STOP] : []
const missing = guis.plugins.filter((plugin) => cache.get(plugin.id)?.revision !== plugin.revision)
if (missing.length > 0)
return {
state: { status: "evaluating", attempt, settled, target: guis, cache },
effects: [...stop, { type: "evaluate", attempt, plugins: missing }],
}
const plugins = guis.plugins.flatMap((plugin) => {
const loaded = cache.get(plugin.id)
return loaded ? [loaded] : []
})
return {
state: { status: "loaded", attempt, cache: toCache(plugins) },
effects: [...stop, { type: "publish", plugins, reserved: guis.reserved }],
}
}
function toCache(plugins: readonly LoadedPluginGui[]): Cache {
return new Map(plugins.map((plugin) => [plugin.id, plugin]))
}
+87 -53
View File
@@ -1,18 +1,18 @@
import { createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js"
import { createMemo, onCleanup, untrack } from "solid-js"
import type { PluginOptions } from "@opencode/plugin/gui"
import type { Bridge, BridgePluginGui, BridgePluginGuis, Entry } from "@opencode/plugin/gui/host"
import type { Bridge, BridgePluginGui, Entry } from "@opencode/plugin/gui/host"
import type { OpenCodeClient } from "@opencode/client/promise"
import { useGlobal } from "@/runtime/server/runtime"
import { ServerConnection } from "@/runtime/server/registry"
import { pluginDefinition } from "./module"
/** A plugin's `./gui-experimental` bundle as this window evaluated it, at one revision. */
type Loaded = {
readonly id: string
readonly revision: string
readonly definition: Entry
readonly options: PluginOptions
}
import {
createPluginGuiState,
PLUGIN_GUI_INITIAL_TIMEOUT_MS,
transitionPluginGui,
type LoadedPluginGui,
type PluginGuiEffect,
type PluginGuiEvent,
} from "./plugin-gui-machine"
/** A plugin's GUI as the plugin host runs it: its definition, options, and the client of the server that runs it. */
export type PluginGui = {
@@ -43,61 +43,95 @@ export function PluginGuiLoader(props: {
return conn ? global.serverCtx(ServerConnection.key(conn)) : undefined
})
// One evaluation per plugin revision, so an unchanged plugin keeps its definition and the host does not reload it.
const cache = new Map<string, Loaded>()
const [guis, setGuis] = createSignal<BridgePluginGuis>()
// The server that runs the plugin, read each time: it is a new client after that server restarts.
const client = () => controller()?.sdk.api
const initial = createPluginGuiState()
const machine = { state: initial.state }
// Events an effect raises synchronously wait behind that effect.
const queue: PluginGuiEvent[] = []
let timer: ReturnType<typeof setTimeout> | undefined
const dispatch = (event: PluginGuiEvent) => {
queue.push(event)
if (queue.length === 1) untrack(drain)
}
const drain = () => {
const event = queue[0]
if (!event) return
try {
const next = transitionPluginGui(machine.state, event)
machine.state = next.state
next.effects.forEach((effect) =>
Promise.try(() => run(effect)).catch((cause: unknown) =>
console.error("[plugin] plugin GUI effect failed", cause),
),
)
} finally {
queue.shift()
}
drain()
}
const run = (effect: PluginGuiEffect) => {
if (effect.type === "fetch.initial")
return void Promise.try(() => props.bridge.pluginGuis()).then(
(guis) => dispatch({ type: "initial.resolved", attempt: effect.attempt, guis }),
(cause: unknown) => dispatch({ type: "initial.failed", attempt: effect.attempt, cause }),
)
if (effect.type === "timer.start") {
clearTimeout(timer)
timer = setTimeout(() => dispatch({ type: "timeout", attempt: effect.attempt }), PLUGIN_GUI_INITIAL_TIMEOUT_MS)
return
}
if (effect.type === "timer.stop") {
clearTimeout(timer)
timer = undefined
return
}
if (effect.type === "evaluate")
return void Promise.all(effect.plugins.map(evaluate)).then(
(loaded) => dispatch({ type: "evaluated", attempt: effect.attempt, loaded }),
(cause: unknown) => dispatch({ type: "evaluate.failed", attempt: effect.attempt, cause }),
)
if (effect.type === "publish")
return props.onChange(
effect.plugins.map((plugin) => ({ definition: plugin.definition, options: plugin.options, client })),
effect.reserved,
)
console.error("[plugin] failed to load plugin GUIs", effect.cause)
}
onCleanup(
props.bridge.on((message) => {
if (message.type === "pluginGuis") setGuis({ plugins: message.plugins, reserved: message.reserved })
if (message.type === "pluginGuis")
dispatch({ type: "pushed", guis: { plugins: message.plugins, reserved: message.reserved } })
}),
)
// A change main pushed while this request was in flight is newer than its reply.
void props.bridge.pluginGuis().then(
(initial) => setGuis((current) => current ?? initial),
() => undefined,
)
const [found] = createResource(guis, async (input) => {
const plugins = await Promise.all(input.plugins.map((plugin) => load(plugin, cache)))
const ids = new Set(plugins.map((plugin) => plugin.id))
cache.forEach((_, id) => {
if (!ids.has(id)) cache.delete(id)
})
return { plugins, reserved: input.reserved }
})
// Syncs the loaded plugins out to the plugin host.
createEffect(() => {
const latest = found.latest
if (!latest) return
// The server that runs the plugin, read each time: it is a new client after that server restarts.
const client = () => controller()?.sdk.api
props.onChange(
latest.plugins.map((plugin) => ({ definition: plugin.definition, options: plugin.options, client })),
latest.reserved,
)
})
onCleanup(() => dispatch({ type: "disposed" }))
initial.effects.forEach(run)
return null
}
/** Evaluates a plugin's bundle when its revision is new to this window. */
async function load(plugin: BridgePluginGui, cache: Map<string, Loaded>): Promise<Loaded> {
const cached = cache.get(plugin.id)
if (cached?.revision === plugin.revision) return cached
const next = {
/** Evaluates a plugin's bundle at the revision main sent. */
async function evaluate(plugin: BridgePluginGui): Promise<LoadedPluginGui> {
return {
id: plugin.id,
revision: plugin.revision,
options: plugin.options,
definition: await pluginDefinition(plugin.id, plugin.code),
}
cache.set(plugin.id, next)
return next
}
+14 -16
View File
@@ -1,4 +1,4 @@
import { batch, createMemo, createSignal, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js"
import { createMemo, createSignal, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js"
import { runsOn, type Bridge, type Entry } from "@opencode/plugin/gui/host"
import { builtins } from "./builtins"
import { PluginGuiLoader, type PluginGui } from "./plugins"
@@ -52,16 +52,18 @@ export function PluginRoot(props: ParentProps) {
const localBuiltins = builtins.filter((definition) => runsOn(definition, os))
// The GUIs of the plugins on the app's own server, as main sends them; undefined until main first sends them. The web
// runs built-ins only.
const [plugins, setPlugins] = createSignal<readonly PluginGui[] | undefined>(bridge ? undefined : [])
// Plugins whose GUI cannot load because a built-in claims the id, as main reports them; Extensions › Plugins shows
// them.
const [reserved, setReserved] = createSignal<readonly string[]>([])
// The GUIs of the plugins on the app's own server, as main sends them, and the plugins whose GUI cannot load because a
// built-in claims the id, which Extensions › Plugins shows. Settled once the loader first publishes, even empty after
// a failure. The web runs built-ins only.
const [loaded, setLoaded] = createSignal<{
settled: boolean
plugins: readonly PluginGui[]
reserved: readonly string[]
}>({ settled: !bridge, plugins: [], reserved: [] })
// The same definitions in the same order are no change, so a refetch that found nothing new restarts nothing.
const definitions = createMemo<readonly Entry[]>(
() => [...localBuiltins, ...(plugins() ?? []).map((plugin) => plugin.definition)],
() => [...localBuiltins, ...loaded().plugins.map((plugin) => plugin.definition)],
[],
{
equals: (a, b) => a.length === b.length && a.every((definition, index) => definition === b[index]),
@@ -76,12 +78,8 @@ export function PluginRoot(props: ParentProps) {
value={
bridge && {
bridge,
set: (next, ids) =>
batch(() => {
setPlugins(next)
setReserved(ids)
}),
reserved,
set: (plugins, reserved) => setLoaded({ settled: true, plugins, reserved }),
reserved: () => loaded().reserved,
}
}
>
@@ -93,12 +91,12 @@ export function PluginRoot(props: ParentProps) {
apis={apis.apis}
whenMounted={apis.whenMounted}
ipc={bridge ? (token) => ipcs.client(token) : undefined}
plugin={(id) => plugins()?.find((plugin) => plugin.definition.id === id)}
plugin={(id) => loaded().plugins.find((plugin) => plugin.definition.id === id)}
generation={ipcs.generation}
ipcFailed={ipcs.failed}
>
<PluginStyles />
<PluginThemes loaded={() => plugins() !== undefined} />
<PluginThemes loaded={() => loaded().settled} />
{PluginHotReload && (
<Suspense>
<PluginHotReload />
+30 -48
View File
@@ -1,14 +1,4 @@
import {
For,
Show,
createEffect,
createMemo,
createSignal,
on,
onCleanup,
type Accessor,
type JSX,
} from "solid-js"
import { For, Show, createMemo, createRenderEffect, createSignal, onCleanup, type Accessor, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { createMediaQuery } from "@solid-primitives/media"
import { createEventListener } from "@solid-primitives/event-listener"
@@ -40,7 +30,8 @@ import { RegionContent, type Region, type RegionPane } from "./panels"
import { PluginSlot } from "./render"
import { createTabStripScroll } from "./tab-strip-scroll"
import { closedTabsModifier, type ClosedSideTab } from "./closed-tabs"
import { ClosedTabsSection, NewTabButton } from "./closed-tabs-view"
import { ClosedTabsSection, createDeferredMenu, NewTabButton } from "./closed-tabs-view"
import { selectDeferredMenuOpen } from "./deferred-menu-machine"
import type { PaneDrag } from "./pane-drag"
const PANE_HEIGHT_MIN = 120
@@ -72,14 +63,9 @@ export function SideRegion(props: {
const contentMounted = createMemo<boolean>((mounted) => mounted || tabsVisible(), false)
const panelWidth = createMemo(() => (tabsVisible() ? "auto" : "0px"))
// Opening the side region with no tabs shows a new tab view, once per opening and session. Keyed by the session, not
// the item, whose object changes with every routed session. A view left from an earlier opening is shown again
// rather than joined by another.
const starting = createMemo(() =>
tabsOpen() && layout.ready() && props.region.empty() ? props.view.key : undefined,
)
createEffect(on(starting, (key) => key && !props.region.newTab("side") && props.region.openNewTab("side")))
// Opening the side region with no tabs shows a new tab view, once per opening and session (`new-tab-machine.ts`).
createRenderEffect(() => props.region.syncSideOpen(tabsOpen() && layout.ready()))
onCleanup(() => props.region.syncSideOpen(false))
// The split pane shows while it holds tabs; when the side pane has none, New tabs included, the split pane takes the
// whole height.
@@ -252,7 +238,7 @@ export function PaneTabs(props: {
return (
<Tabs
data-pane-content={props.pane.id}
value={current()?.id ?? props.pane.active() ?? "empty"}
value={current() ?? props.pane.active() ?? "empty"}
onChange={(value) => {
// Kobalte selects the first tab while triggers register, including while the "+" click is still dispatching.
// Only input on a tab selects one; the region owns fallback selection.
@@ -264,8 +250,7 @@ export function PaneTabs(props: {
)
return
if (props.region.newTabs(props.pane.id).some((entry) => entry.id === value))
return props.region.selectNewTab(props.pane.id, value)
if (props.region.newTabs(props.pane.id).includes(value)) return props.region.selectNewTab(props.pane.id, value)
props.region.select(value)
}}
>
@@ -311,11 +296,11 @@ export function PaneTabs(props: {
)}
</For>
<For each={props.region.newTabs(props.pane.id)}>
{(entry) => (
{(id) => (
<Tabs.Trigger
value={entry.id}
value={id}
class="group"
onMiddleClick={() => props.region.dismissNewTab(entry.id)}
onMiddleClick={() => props.region.dismissNewTab(id)}
closeButton={
<IconButton
size="small"
@@ -327,7 +312,7 @@ export function PaneTabs(props: {
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
props.region.dismissNewTab(entry.id)
props.region.dismissNewTab(id)
}}
icon={<Icon name="xmark-small" />}
aria-label={language.t("common.closeTab")}
@@ -434,8 +419,8 @@ export function PaneTabs(props: {
</div>
<Show when={current()}>
{(entry) => (
<Tabs.Content value={entry().id} class="flex flex-col h-full overflow-hidden contain-strict">
{(id) => (
<Tabs.Content value={id()} class="flex flex-col h-full overflow-hidden contain-strict">
<Launchers items={launchers()} onChoose={target} closed={closed} />
</Tabs.Content>
)}
@@ -510,14 +495,23 @@ function AddMenu(props: { items: readonly SessionPanelMenuEntry[]; onChoose: (ke
const command = useCommand()
const keys = createMemo(() => props.items.map((entry) => entry.key), [], { equals: same })
const byKey = createMemo(() => new Map(props.items.map((entry) => [entry.key, entry.item])))
// A chosen item runs once the closing menu has returned focus to "+", and the tab strip has passed it on to the
// selected tab. Releasing that focus first lets the item move it where its tab needs it, e.g. into a new terminal,
// without the strip taking it back for the tab it remembers.
let chosen: SessionPanelMenuEntry | undefined
const menu = createDeferredMenu<SessionPanelMenuEntry>({
onChoose: (entry) => {
props.onChoose(entry.key)
entry.item.run() },
})
return (
<Tooltip value={language.t("session.tab.add")} placement="bottom" class="flex items-center">
<Menu appearance="standard" modal={false} placement="bottom-start" gutter={4}>
<Menu
appearance="standard"
modal={false}
placement="bottom-start"
gutter={4}
open={selectDeferredMenuOpen(menu.state())}
onOpenChange={(open) => menu.dispatch({ type: "open.change", open, available: true, defaultIntent: "menu" })}
>
<Menu.Trigger
as={IconButton}
icon={<Icon name="plus" />}
@@ -529,19 +523,7 @@ function AddMenu(props: { items: readonly SessionPanelMenuEntry[]; onChoose: (ke
onPointerDown={(event: PointerEvent) => event.preventDefault()}
/>
<Menu.Portal>
<Menu.Content
onCloseAutoFocus={() => {
const entry = chosen
if (!entry) return
chosen = undefined
setTimeout(() => {
if (document.activeElement instanceof HTMLElement) document.activeElement.blur()
props.onChoose(entry.key)
entry.item.run()
})
}}
>
<Menu.Content onCloseAutoFocus={() => menu.dispatch({ type: "close.autofocus" })}>
<For each={keys()}>
{(key) => (
<Show when={byKey().get(key)}>
@@ -555,7 +537,7 @@ function AddMenu(props: { items: readonly SessionPanelMenuEntry[]; onChoose: (ke
return (
<Menu.Item
class="!gap-6"
onSelect={() => (chosen = { key, item: item() })}
onSelect={() => menu.dispatch({ type: "select", choice: { key, item: item() } })}
shortcut={
<Show when={keybind().length > 0}>
<Keybind keys={keybind()} variant="neutral" />