feat(app): demo session in the debug bar

This commit is contained in:
Kit Langton 2026-10-19 21:27:44 -07:00
parent 8c1a80b4e8
commit afce46e772
6 changed files with 570 additions and 4 deletions

View file

@ -196,6 +196,7 @@ export default function DebugBar(props: {
diagnostics?: boolean
inline?: boolean
motion?: { open: boolean; toggle: () => void }
demo?: { open: boolean; toggle: () => void }
}) {
const ctx = useExtension()
const router = ctx.router
@ -742,6 +743,16 @@ export default function DebugBar(props: {
</Show>
<Show when={props.motion}>
<div class="ms-auto flex items-center gap-[9px]">
<Show when={props.demo}>
<ToggleCell
active={!!props.demo?.open}
inline={props.inline}
label={ctx.t("demo.label")}
tip={ctx.t("demo.tip")}
value={ctx.t(props.demo?.open ? "focus.on" : "focus.off")}
onClick={() => props.demo?.toggle()}
/>
</Show>
<ToggleCell
active={globals().speed !== 1}
inline={props.inline}

View file

@ -0,0 +1,220 @@
import { createMemo, createSignal, For, onCleanup, Show } from "solid-js"
import { Portal } from "solid-js/web"
import { createKeyed, useExtension } from "../sdk"
// Drive's simulated provider (script/drive/demo-session.ts). The controls only act on a session that runs on it, so a
// demo prompt never reaches a real model or a real conversation.
const provider = "simulation"
type Action = (typeof actions)[number]
// Each action is a real prompt the scripted model recognises by its `[demo:<action> <speed>×]` tag.
const actions = [
"paragraph",
"code",
"shell",
"patch",
"turn",
"message",
"steer",
"burst",
"queue",
"subagent",
"background",
] as const
const prompts: Record<Action, string> = {
paragraph: "Describe the harbor at dawn",
code: "Show the lantern scheduler",
shell: "Run the tide checks",
patch: "Retime the North Mole lantern",
turn: "Check the lanterns against the tide tables",
message: "How is the harbor today?",
steer: "Also include the tide tables",
burst: "Read every harbor file",
queue: "Then repaint the pilot steps",
subagent: "Survey the breakwater in the background",
background: "Start the lantern preview",
}
// Auto-play's loop: each step waits for the session to settle; `then` lands while the step is still running.
const script: Array<{ action: Action; then?: { action: Action; after: number } }> = [
{ action: "paragraph" },
{ action: "shell" },
{ action: "code" },
{ action: "turn", then: { action: "steer", after: 1_200 } },
{ action: "patch" },
{ action: "burst" },
{ action: "paragraph", then: { action: "queue", after: 400 } },
{ action: "subagent" },
{ action: "background" },
{ action: "message" },
]
export default function Demo() {
const ctx = useExtension()
const [speed, setSpeed] = createSignal(1)
const [playing, setPlaying] = createSignal(false)
const target = createMemo(
() => {
const session = ctx.sessions.current()
if (!session?.location) return
return { id: session.id, location: session.location, server: session.server }
},
undefined,
{
equals: (a, b) =>
a?.id === b?.id && a?.server.data === b?.server.data && a?.location.directory === b?.location.directory,
},
)
const ready = createMemo(() => {
const current = target()
if (!current) return false
const model = current.server.data.session.get(current.id)?.model
const providers = current.server.data.location.provider.list(current.location)
return (model === undefined || model.providerID === provider) && !!providers?.some((item) => item.id === provider)
})
createKeyed(
target,
(current) => void current.server.data.location.provider.sync(current.location).catch(() => undefined),
)
const send = (action: Action) => {
const current = target()
if (!current || !ready()) return
return current.server.data.session
.prompt({
sessionID: current.id,
text: `[demo:${action} ${speed()}×] ${prompts[action]}`,
delivery: action === "queue" ? "queue" : "steer",
})
.catch(() => undefined)
}
const finish = () => {
const current = target()
if (current && ready())
void current.server.client.session.interrupt({ sessionID: current.id }).catch(() => undefined)
}
// Auto-play runs while it is on and the routed session can take demo prompts, and stops with either.
createKeyed(
() => playing() && ready() && target(),
(current) => {
const abort = new AbortController()
onCleanup(() => abort.abort())
void play(current, abort.signal)
},
)
async function play(current: NonNullable<ReturnType<typeof target>>, signal: AbortSignal) {
const idle = () =>
current.server.data.session.status(current.id) === "idle" &&
current.server.data.session.pending.list(current.id).length === 0
for (let step = 0; !signal.aborted; step = (step + 1) % script.length) {
const item = script[step]
void send(item.action)
await until(() => !idle(), 3_000, signal)
if (item.then) {
await wait(item.then.after / speed(), signal)
void send(item.then.action)
}
await until(idle, 60_000, signal)
await wait(900 / speed(), signal)
}
}
return (
<Portal>
<section
aria-label={ctx.t("demo.title")}
class="pointer-events-auto fixed bottom-10 left-3 z-50 flex w-[224px] flex-col gap-2 rounded-xl border border-border-base bg-surface-raised-stronger-non-alpha p-2.5 font-mono text-[11px] text-text-strong shadow-[var(--shadow-lg-border-base)]"
>
<span class="text-[10px] font-black uppercase tracking-[0.04em] opacity-70">{ctx.t("demo.title")}</span>
<label class="flex items-center gap-2 text-[10px] font-bold uppercase tabular-nums">
{ctx.t("demo.speed")}
<input
type="range"
min="0.25"
max="2"
step="0.25"
value={speed()}
class="min-w-0 flex-1"
onInput={(event) => setSpeed(Number(event.currentTarget.value))}
/>
<span class="w-10 text-end">{speed().toFixed(2)}×</span>
</label>
<Show when={!ready()}>
<p class="leading-text-tight opacity-70">{ctx.t("demo.unavailable")}</p>
</Show>
<div class="grid grid-cols-2 gap-1">
<For each={actions}>
{(action) => (
<DemoButton
disabled={!ready()}
label={ctx.t(`demo.action.${action}`)}
onClick={() => void send(action)}
/>
)}
</For>
<DemoButton disabled={!ready()} label={ctx.t("demo.action.finish")} onClick={finish} />
</div>
<DemoButton
active={playing()}
disabled={!ready()}
label={ctx.t(playing() ? "demo.autoplay.stop" : "demo.autoplay.start")}
onClick={() => setPlaying((value) => !value)}
/>
</section>
</Portal>
)
}
function DemoButton(props: { active?: boolean; disabled: boolean; label: string; onClick: () => void }) {
return (
<button
type="button"
aria-pressed={props.active}
disabled={props.disabled}
classList={{
"min-h-[24px] rounded px-1.5 py-1 text-[10px] font-bold uppercase leading-none hover:bg-surface-raised-base focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-border-focus disabled:pointer-events-none disabled:opacity-40": true,
"bg-surface-raised-base text-text-strong": !!props.active,
}}
onClick={props.onClick}
>
{props.label}
</button>
)
}
function wait(ms: number, signal: AbortSignal) {
return new Promise<void>((resolve) => {
const timer = setTimeout(done, ms)
signal.addEventListener("abort", done, { once: true })
function done() {
clearTimeout(timer)
signal.removeEventListener("abort", done)
resolve()
}
})
}
async function until(check: () => boolean, timeout: number, signal: AbortSignal) {
const deadline = Date.now() + timeout
while (!signal.aborted && !check() && Date.now() < deadline) await wait(100, signal)
}

View file

@ -35,6 +35,26 @@ export default {
"motion.label": "MOTION",
"motion.title": "Motion",
"motion.tip": "Tune animation springs live. Changes persist on this device.",
"demo.label": "DEMO",
"demo.title": "Demo session",
"demo.tip": "Drive the open session through scripted states on OpenCode Drive's simulated model.",
"demo.unavailable":
"Open a session on OpenCode Drive's simulated model to use these controls. Start one with script/drive/demo-session.ts.",
"demo.speed": "Speed",
"demo.action.paragraph": "Paragraph",
"demo.action.code": "Code block",
"demo.action.shell": "Shell",
"demo.action.patch": "Patch",
"demo.action.turn": "Long turn",
"demo.action.finish": "Finish turn",
"demo.action.message": "Message",
"demo.action.steer": "Steer",
"demo.action.burst": "Burst",
"demo.action.queue": "Queue",
"demo.action.subagent": "Subagent",
"demo.action.background": "Bg shell",
"demo.autoplay.start": "Auto-play",
"demo.autoplay.stop": "Stop auto-play",
"speed.label": "SPEED",
"speed.tip": "Global animation speed. Click to step through 0.5× and 0.25× back to 1×.",
"slow.label": "SLOW",

View file

@ -4,14 +4,16 @@ import type Debug from "./index"
const setup: Setup<typeof Debug> = (ctx) => {
const DebugBar = lazy(() => import("./bar"))
// Motion tuning lives only in the debug bar, on the dev server and in Beta. Both are fixed at build time, so other
// builds, prod included, drop the import and never contain knobs.
const motionTools = import.meta.env.DEV || import.meta.env.VITE_OPENCODE_CHANNEL === "beta"
const Motion = motionTools ? lazy(() => import("./motion")) : undefined
// Motion tuning and the demo session live only in the debug bar, on the dev server and in Beta. Both are fixed at
// build time, so other builds, prod included, drop the imports and never contain knobs.
const tools = import.meta.env.DEV || import.meta.env.VITE_OPENCODE_CHANNEL === "beta"
const Motion = tools ? lazy(() => import("./motion")) : undefined
const Demo = tools ? lazy(() => import("./demo")) : undefined
// Window-local; every window starts with the bar hidden.
const [visible, setVisible] = createSignal(false)
const [motion, setMotion] = createSignal(false)
const [demo, setDemo] = createSignal(false)
const toggle = () => {
setVisible((value) => !value)
@ -21,6 +23,10 @@ const setup: Setup<typeof Debug> = (ctx) => {
setMotion((value) => !value)
}
const toggleDemo = () => {
setDemo((value) => !value)
}
ctx.add(
Command,
(): Command => ({
@ -41,6 +47,7 @@ const setup: Setup<typeof Debug> = (ctx) => {
<DebugBar
diagnostics={import.meta.env.DEV}
motion={Motion ? { open: motion(), toggle: toggleMotion } : undefined}
demo={Demo ? { open: demo(), toggle: toggleDemo } : undefined}
inline
/>
</Suspense>
@ -53,6 +60,13 @@ const setup: Setup<typeof Debug> = (ctx) => {
</Suspense>
</Show>
)}
{Demo && (
<Show when={visible() && demo()}>
<Suspense>
<Demo />
</Suspense>
</Show>
)}
</>
),
})

View file

@ -0,0 +1,35 @@
# Demo session
`demo-session.ts` starts an isolated OpenCode server for the debug bar's Demo controls. Its simulated model answers
each `[demo:<action> <speed>×]` prompt with a scripted reply. Shell commands, patches, file reads and the background
subagent run for real inside the throwaway project, so the app renders them through the normal event path.
## Run
Use an `opencode-drive` installation on the module path and a dependency-installed checkout:
```sh
DEMO_STATE=/tmp/demo-session.json opencode-drive run script/drive/demo-session.ts
```
The script prints the session it created. `DEMO_STATE` optionally receives the server URL, its password and that
session ID, for a proxy or a client that opens it directly. Connect a dev or Beta build of the app to that server,
open the session, toggle the debug bar and press DEMO.
| Control | What the session does |
| ----------- | ------------------------------------------------------------------------ |
| Paragraph | Streams reasoning, then a paragraph |
| Code block | Streams a fenced TypeScript block line by line |
| Shell | Runs a real shell command whose output grows |
| Patch | Applies a real one-line patch, alternating between two values |
| Long turn | Thinks for a few seconds before answering |
| Finish turn | Interrupts the running turn |
| Message | Sends a user message that gets a short reply |
| Steer | Sends a prompt that steers a running turn |
| Burst | Reads five files in parallel, then streams one-character text deltas |
| Queue | Queues a prompt behind the running turn |
| Subagent | Starts a background subagent that reports back when it finishes |
| Bg shell | Starts a real background shell that keeps printing for about ten seconds |
| Auto-play | Loops a scripted mix of the above, including a steer and a queued prompt |
Speed scales the model's streaming delays and the shell scripts' pacing from 0.25× to 2×.

View file

@ -0,0 +1,266 @@
import { readFileSync } from "node:fs"
import { Effect, Stream } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
// Serves the debug bar's Demo controls: an isolated server whose simulated model answers each `[demo:<action> <speed>×]`
// prompt with a scripted reply. Shell, edit, read and subagent calls run for real inside the throwaway project.
// Run from the repository root with `opencode-drive run script/drive/demo-session.ts`; see demo-session.md.
const state = process.env.DEMO_STATE
const tides = [
"#!/bin/sh",
'delay=$(awk "BEGIN { print 0.22 / ${1:-1} }")',
"for station in Breakwater 'North Mole' 'Lantern Quay' 'Saltmarsh Gate' 'Pilot Steps' 'Fishery Slip' 'East Buoy' 'Harbor Mouth'; do",
' printf "✓ %-16s high water within 4 cm\\n" "$station"',
' sleep "$delay"',
"done",
'printf "\\n8 passed, 0 failed\\n"',
].join("\n")
const preview = [
"#!/bin/sh",
'delay=$(awk "BEGIN { print 0.9 / ${1:-1} }")',
'printf "Lantern preview starting on http://127.0.0.1:4173\\n"',
"for frame in 1 2 3 4 5 6 7 8 9 10 11 12; do",
' sleep "$delay"',
' printf "rebuilt beacon map (%s/12)\\n" "$frame"',
"done",
'printf "preview idle\\n"',
].join("\n")
const harbor = [
"export const lantern = {",
' name: "North Mole",',
" intervalMs: 4000,",
' color: "amber",',
"}",
"",
"export function nextFlash(at: number) {",
" return at + lantern.intervalMs",
"}",
"",
].join("\n")
const paragraph =
"The harbor wakes before the town does. Fishing boats slip their moorings while the lanterns along the North Mole " +
"are still turning, and the tide tables pinned inside the pilot's hut are already out of date by a few minutes. " +
"Most mornings the fog lifts in layers: first the masts, then the roofs of the net sheds, and finally the long " +
"breakwater, which always seems farther away than it is. By the time the bakery opens, the first catch is on ice."
const code = [
"Here is the scheduler that keeps the lanterns in phase:",
"",
"```ts",
"type Lantern = { name: string; intervalMs: number; offsetMs: number }",
"",
"export function schedule(lanterns: Lantern[], now: number) {",
" return lanterns",
" .map((lantern) => {",
" const elapsed = (now - lantern.offsetMs) % lantern.intervalMs",
" return { name: lantern.name, nextFlash: now + lantern.intervalMs - elapsed }",
" })",
" .toSorted((a, b) => a.nextFlash - b.nextFlash)",
"}",
"",
"export function inPhase(a: Lantern, b: Lantern) {",
" return a.intervalMs === b.intervalMs && a.offsetMs === b.offsetMs",
"}",
"```",
"",
"Each lantern keeps its own interval, so the sort decides which one flashes next.",
].join("\n")
export default OpenCodeDriver.use(
{
opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() },
tui: { viewport: { cols: 100, rows: 30 } },
llm: { requestTimeout: 3_600_000, settlementTimeout: 5_000 },
config: {
autoupdate: false,
username: "Demo",
agents: { surveyor: { mode: "subagent", description: "Surveys a part of the harbor" } },
},
project: {
git: true,
files: {
"README.md": "# Harbor\nLantern schedules and tide checks for a fictional harbor.\n",
"src/harbor.ts": harbor,
"src/tides.ts": "export const stations = ['Breakwater', 'North Mole', 'Lantern Quay']\n",
"src/fleet.ts": "export const boats = ['Gannet', 'Kittiwake', 'Shearwater']\n",
"docs/pilots.md": "# Pilot steps\nBoard at the pilot steps two hours before high water.\n",
"scripts/tides.sh": tides,
"scripts/preview.sh": preview,
},
},
},
({ llm, artifacts, directory }) =>
Effect.gen(function* () {
yield* llm.title(() => Effect.succeed("Timeline demo"))
yield* llm.serve((request) => {
const body = JSON.stringify(request.body)
if (body.includes("You are a subagent spawned")) return child(rate(body))
const turn = demoTurn(request.body)
if (!turn) return reply("Noted. The harbor log is up to date.", 1)
return respond(turn.action, turn.step, turn.speed, directory)
})
const session = yield* Effect.promise(() => createSession(artifacts, directory))
console.log(`Demo session ${session.id} in ${directory}`)
if (state)
yield* Effect.promise(() => Bun.write(state, JSON.stringify({ ...session.server, session: session.id })))
return yield* Effect.never
}),
)
function respond(action: string, step: number, speed: number, directory: string) {
const call = (name: string, input: Record<string, string | boolean>, index = 0) =>
Llm.toolCall({ index, id: `call_${crypto.randomUUID().replaceAll("-", "")}`, name, input })
const text = (value: string, chunk = 3) => Llm.text(value, { delay: 16 / speed, chunkSize: chunk })
const think = (value: string) => Llm.reasoning(value, { delay: 24 / speed, chunkSize: 4 })
const tools = (...outputs: Llm.Output[]) => Stream.make(...outputs, Llm.finish("tool-calls"))
switch (action) {
case "paragraph":
return Stream.make(think("Describing the morning harbor."), text(paragraph))
case "code":
return Stream.make(text(code, 6))
case "shell":
if (step === 0)
return tools(
text("Running the tide checks."),
call("shell", {
command: `sh scripts/tides.sh ${speed}`,
description: "Run tide checks",
workdir: directory,
}),
)
return Stream.make(text("All eight stations are within tolerance."))
case "patch":
if (step === 0)
return tools(text("Retiming the North Mole lantern."), call("patch", { patchText: patch(directory) }))
return Stream.make(text("The lantern interval is updated."))
case "turn":
return Stream.make(
think(
"Checking the tide tables against the lantern schedule. The North Mole runs on a four second interval, " +
"the Lantern Quay on six, so they line up every twelve seconds. High water is at 06:40, which means " +
"the pilot boat leaves at 04:40 and needs both lanterns in phase before then.",
),
Llm.pause(1_500 / speed),
text("Both lanterns are in phase before the pilot boat leaves."),
)
case "message":
return Stream.make(text("Sure. The harbor is quiet today."))
case "steer":
return Stream.make(text("Got it, I'll include the tide tables as well."))
case "burst":
if (step === 0)
return tools(
Llm.text("Reading the harbor files.", { delay: 4 / speed, chunkSize: 2 }),
...["README.md", "src/harbor.ts", "src/tides.ts", "src/fleet.ts", "docs/pilots.md"].map((file, index) =>
call("read", { path: `${directory}/${file}` }, index),
),
)
return Stream.make(
Llm.text(
"Five files: the lantern config, the tide stations, the fleet roster, the pilot notes and the readme.",
{ delay: 4 / speed, chunkSize: 1 },
),
)
case "queue":
return Stream.make(text("Next on the list: repaint the pilot steps before the spring tides."))
case "subagent":
if (step === 0)
return tools(
text("Sending a surveyor to the breakwater."),
call("subagent", {
agent: "surveyor",
description: "Survey the breakwater",
prompt: `[demo:child ${speed}×] Walk the breakwater and report any loose stones.`,
background: true,
}),
)
return Stream.make(text("The survey runs in the background. I'll report back when it lands."))
case "background":
if (step === 0)
return tools(
text("Starting the lantern preview."),
call("shell", {
command: `sh scripts/preview.sh ${speed}`,
description: "Lantern preview",
workdir: directory,
background: true,
}),
)
return Stream.make(text("The preview is starting in the background."))
}
return reply("Noted.", speed)
}
function child(speed: number) {
return Stream.make(
Llm.reasoning("Walking the breakwater from the harbor mouth.", { delay: 30 / speed, chunkSize: 3 }),
Llm.pause(1_200 / speed),
Llm.text(
"The breakwater is sound. Two capstones near the East Buoy have shifted a few centimetres and should be reset " +
"at the next low spring tide.",
{ delay: 40 / speed, chunkSize: 3 },
),
)
}
function reply(value: string, speed: number) {
return Stream.make(Llm.text(value, { delay: 16 / speed, chunkSize: 3 }))
}
// Toggles the lantern interval, so every press produces a real diff.
function patch(directory: string) {
const path = `${directory}/src/harbor.ts`
const [from, to] = readFileSync(path, "utf8").includes("intervalMs: 6000") ? [6000, 4000] : [4000, 6000]
return [
"*** Begin Patch",
`*** Update File: ${path}`,
"@@",
`- intervalMs: ${from},`,
`+ intervalMs: ${to},`,
"*** End Patch",
].join("\n")
}
function rate(body: string) {
const match = body.match(/\[demo:[a-z]+ ([\d.]+)×\]/)
return match ? Number(match[1]) || 1 : 1
}
// The newest user message picks the action; assistant messages after it count the steps already taken this turn.
function demoTurn(body: unknown) {
const messages = typeof body === "object" && body !== null && "messages" in body ? body.messages : undefined
if (!Array.isArray(messages)) return
const last = messages.findLastIndex((message) => message?.role === "user")
if (last < 0) return
const match = JSON.stringify(messages[last]).match(/\[demo:([a-z]+) ([\d.]+)×\]/)
if (!match) return
return {
action: match[1],
speed: Number(match[2]) || 1,
step: messages.slice(last + 1).filter((message) => message?.role === "assistant").length,
}
}
// Drive's SDK client trails the server protocol, so the session is created over plain HTTP with the isolated
// server's own registration.
async function createSession(artifacts: string, directory: string) {
const registration: { url: string; password?: string } = await Bun.file(
`${artifacts}/home/.local/state/opencode/service-local.json`,
).json()
const headers = {
"content-type": "application/json",
...(registration.password ? { authorization: `Basic ${btoa(`opencode:${registration.password}`)}` } : {}),
}
const response = await fetch(`${registration.url}/api/session`, {
method: "POST",
headers,
body: JSON.stringify({ title: "Timeline demo", location: { directory } }),
})
const created = (await response.json()) as { data: { id: string } }
return { id: created.data.id, server: registration }
}