Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ OpenCode plugin modules are target-specific. This package exports separate modul
{
"exports": {
"./server": "./dist/server.js",
"./tui": "./src/tui.tsx"
"./tui": "./src/tui.ts"
}
}
```
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@
"import": "./dist/server.js"
},
"./tui": {
"import": "./src/tui.tsx"
"import": "./src/tui.ts"
}
},
"files": [
"dist",
"src/tui.tsx",
"src/tui.ts",
"LICENSE",
"README.md"
],
Expand Down
102 changes: 43 additions & 59 deletions src/tui.tsx → src/tui.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @jsxImportSource @opentui/solid */
import type { TuiCommand, TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui"
import { createMemo, createSignal, onCleanup, Show } from "solid-js"
import { createElement, insert, setProp } from "@opentui/solid"
import { createSignal, onCleanup } from "solid-js"

type GoalCheckpoint = {
summary: string
Expand Down Expand Up @@ -63,6 +63,7 @@ type GoalSessionState = {
goal: GoalSnapshot | null
messageIndex: number
}
type ElementChild = string | number | boolean | null | undefined | object | (() => string)

type ModernTuiApi = TuiPluginApi & {
keymap?: {
Expand All @@ -82,6 +83,21 @@ type ModernTuiApi = TuiPluginApi & {

const goalCache = new Map<string, GoalSnapshot>()

function element(tag: string, props: Record<string, unknown>, children: ElementChild[] = []) {
const node = createElement(tag)
for (const [key, value] of Object.entries(props)) if (value !== undefined) setProp(node, key, value)
for (const child of children) if (child !== null && child !== undefined && child !== false) insert(node, child)
return node
}

function text(props: Record<string, unknown>, children: ElementChild[]) {
return element("text", props, children)
}

function box(props: Record<string, unknown>, children: ElementChild[] = []) {
return element("box", props, children)
}

function goalSnapshotKey(sessionID: string) {
return `goal-mode.snapshot.${sessionID}`
}
Expand Down Expand Up @@ -332,63 +348,31 @@ function formatGoal(goal: GoalSnapshot | null) {
return lines.join("\n")
}

function GoalSidebar(props: { api: TuiPluginApi; sessionID: string }) {
const theme = () => props.api.theme.current
function GoalSidebar(api: TuiPluginApi, sessionID: string) {
const theme = api.theme.current
const state = goalStateFromSession(api, sessionID)
const goal = state.goal
if (!goal) return null
if (goal.status === "complete" || goal.status === "unmet") {
const elapsed = liveTimeUsedSeconds(goal)
return text({ fg: goal.status === "complete" ? theme.primary : theme.textMuted }, [`${goal.status === "complete" ? "Goal achieved" : "Goal unmet"} (${formatDurationBadge(elapsed)})`])
}
const [nowSeconds, setNowSeconds] = createSignal(currentEpochSeconds())
const timer = setInterval(() => setNowSeconds(currentEpochSeconds()), 1000)
onCleanup(() => clearInterval(timer))
const state = createMemo(() => {
props.api.state.session.messages(props.sessionID)
return goalStateFromSession(props.api, props.sessionID)
})
const goal = createMemo(() => state().goal)
const elapsed = createMemo(() => {
const value = goal()
return value ? liveTimeUsedSeconds(value, nowSeconds()) : 0
})
const objective = createMemo(() => goal()?.objective ?? "")

return (
<Show when={goal()}>
{(value: () => GoalSnapshot) => (
<Show
when={value().status === "complete" || value().status === "unmet"}
fallback={
<box>
<text fg={theme().text}>
<b>Goal</b>
</text>
<text fg={theme().textMuted}>Status: {value().status}</text>
<text fg={theme().textMuted}>Time: {formatDuration(elapsed())}</text>
<text fg={theme().textMuted}>
Tokens: {value().tokensUsed}
<Show when={value().tokenBudget}>{(budget: () => number) => <>/{budget()}</>}</Show>
</text>
<text fg={theme().textMuted}>
Auto-continues: {value().autoTurns}
<Show when={value().maxAutoTurns}>{(budget: () => number) => <>/{budget()}</>}</Show>
</text>
<Show when={value().lastCheckpoint}>
{(checkpoint: () => GoalCheckpoint) => <text fg={theme().textMuted}>Checkpoint: {checkpoint().summary}</text>}
</Show>
<Show when={value().stopReason}>
{(reason: () => string) => <text fg={theme().textMuted}>Stop: {reason()}</text>}
</Show>
<Show when={value().lastStatus}>
{(status: () => string) => <text fg={theme().textMuted}>{status()}</text>}
</Show>
<text fg={theme().textMuted}>{objective()}</text>
</box>
}
>
<text fg={value().status === "complete" ? theme().primary : theme().textMuted}>
<b>{value().status === "complete" ? "Goal achieved" : "Goal unmet"}</b> (
{formatDurationBadge(elapsed())})
</text>
</Show>
)}
</Show>
)
if (goal.status === "active") {
const timer = setInterval(() => setNowSeconds(currentEpochSeconds()), 1000)
onCleanup(() => clearInterval(timer))
}
return box({}, [
text({ fg: theme.text }, ["Goal"]),
text({ fg: theme.textMuted }, [`Status: ${goal.status}`]),
text({ fg: theme.textMuted }, [() => `Time: ${formatDuration(liveTimeUsedSeconds(goal, nowSeconds()))}`]),
text({ fg: theme.textMuted }, [`Tokens: ${goal.tokensUsed}${goal.tokenBudget == null ? "" : `/${goal.tokenBudget}`}`]),
text({ fg: theme.textMuted }, [`Auto-continues: ${goal.autoTurns}${goal.maxAutoTurns == null ? "" : `/${goal.maxAutoTurns}`}`]),
...(goal.lastCheckpoint ? [text({ fg: theme.textMuted }, [`Checkpoint: ${goal.lastCheckpoint.summary}`])] : []),
...(goal.stopReason ? [text({ fg: theme.textMuted }, [`Stop: ${goal.stopReason}`])] : []),
...(goal.lastStatus ? [text({ fg: theme.textMuted }, [goal.lastStatus])] : []),
text({ fg: theme.textMuted }, [goal.objective]),
])
}

function registerGoalCommand(api: TuiPluginApi, command: TuiCommand) {
Expand Down Expand Up @@ -417,7 +401,7 @@ const tui: TuiPlugin = async (api) => {
order: 125,
slots: {
sidebar_content(_ctx, props) {
return <GoalSidebar api={api} sessionID={props.session_id} />
return GoalSidebar(api, props.session_id)
},
},
})
Expand Down
88 changes: 86 additions & 2 deletions test/tui.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test } from "bun:test"
import plugin, { formatDuration, goalStateFromSession, liveTimeUsedSeconds } from "../src/tui.tsx"
import { expect, setSystemTime, spyOn, test } from "bun:test"
import { testRender } from "@opentui/solid"
import plugin, { formatDuration, goalStateFromSession, liveTimeUsedSeconds } from "../src/tui.ts"

function goal(overrides: Partial<Parameters<typeof liveTimeUsedSeconds>[0]> = {}): Parameters<typeof liveTimeUsedSeconds>[0] {
return {
Expand Down Expand Up @@ -115,6 +116,89 @@ test("live goal time advances from the authoritative snapshot sample time", () =
expect(liveTimeUsedSeconds(goal({ sampledAt: undefined }), 130)).toBe(10)
})

test("active goal sidebar advances visible elapsed time after a timer tick", async () => {
const intervalCallbacks: (() => void)[] = []
const timer = 1 as unknown as ReturnType<typeof setInterval>
const setIntervalSpy = spyOn(globalThis, "setInterval").mockImplementation(((callback: unknown, delay?: number) => {
if (delay === 1000 && typeof callback === "function") {
intervalCallbacks.push(() => callback())
return timer
}
throw new Error(`Unexpected interval delay: ${delay}`)
}) as unknown as typeof setInterval)
const clearIntervalSpy = spyOn(globalThis, "clearInterval").mockImplementation(() => {})
let sidebar: ((ctx: unknown, props: { session_id: string }) => unknown) | undefined
const snapshot = goal()
const api = {
slots: {
register(input: { slots: { sidebar_content: (ctx: unknown, props: { session_id: string }) => unknown } }) {
sidebar = input.slots.sidebar_content
return "slot-id"
},
},
command: {
register() {
return () => {}
},
},
route: { current: { name: "session", params: { sessionID: "session" } } },
ui: {
toast() {},
dialog: {
setSize() {},
replace() {},
clear() {},
},
},
theme: {
current: {
text: "#ffffff",
textMuted: "#888888",
primary: "#00ff00",
},
},
state: {
session: {
messages() {
return [{ id: "active" }]
},
},
part() {
return [{ type: "tool", tool: "create_goal", state: { status: "completed", output: JSON.stringify({ goal: snapshot }) } }]
},
},
kv: {
get(_key: string, fallback: unknown) {
return fallback
},
set() {},
},
}

setSystemTime(new Date(100_000))
await plugin.tui(api as never, undefined, undefined as never)
const setup = await testRender(() => sidebar?.({}, { session_id: "session" }) as never, { width: 80, height: 20 })
let destroyed = false
try {
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("Time: 0:10")

setSystemTime(new Date(105_000))
for (const callback of intervalCallbacks) callback()
await setup.flush()

expect(setup.captureCharFrame()).toContain("Time: 0:15")
setup.renderer.destroy()
destroyed = true
expect(clearIntervalSpy).toHaveBeenCalledWith(timer)
} finally {
if (!destroyed) setup.renderer.destroy()
clearIntervalSpy.mockRestore()
setIntervalSpy.mockRestore()
setSystemTime()
}
})

test("formats goal durations for display", () => {
expect(formatDuration(0)).toBe("0:00")
expect(formatDuration(65)).toBe("1:05")
Expand Down