import { Show, createEffect, createMemo, on, onMount, type JSX } from "solid-js" import { createStore } from "solid-js/store" import type { ModelSelection } from "@/providers/models/selection" import { STORY_MODEL, emptySessionDocument, pendingAndQueuedDocument } from "@opencode/session-ui/storybook" import { Composer } from "./composer" import type { ComposerModel } from "./model" import { createComposerEditor } from "./editor/interaction" import type { ComposerHistory, ComposerPersistedState, ComposerSuggestion } from "./types" import { buildPromptRequest } from "./request" import { promptLength } from "./prompt-parts" import { SessionPreview } from "@/session/story-model" import { Skill } from "@opencode/schema/skill" import { resolveSessionComposerSelection } from "@/session/composer/selection" const pixel = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==" const selectedModel = { id: STORY_MODEL.id, providerID: STORY_MODEL.providerID, api: { id: STORY_MODEL.id, url: "https://api.anthropic.com", npm: "@ai-sdk/anthropic" }, name: "Claude Sonnet 4", family: "claude-sonnet", capabilities: { temperature: true, reasoning: true, attachment: true, toolcall: true, input: { text: true, audio: false, image: true, video: false, pdf: true }, output: { text: true, audio: false, image: false, video: false, pdf: false }, interleaved: true, }, cost: { input: 3, output: 15, cache: { read: 0.3, write: 3.75 } }, limit: { context: 200_000, output: 64_000 }, status: "active", options: {}, headers: {}, release_date: "2025-05-22", variants: { balanced: {}, high: {} }, provider: { id: STORY_MODEL.providerID, name: "Anthropic", source: "custom", env: [], options: {}, models: {}, }, latest: true, } satisfies NonNullable> function ComposerStory(props: { prompt?: ComposerPersistedState["prompt"] comments?: ComposerPersistedState["context"]["items"] working?: boolean stopping?: boolean sending?: boolean suggestions?: "command" | "context" | "none" failure?: boolean label?: string inspectRequest?: boolean continueOnStop?: boolean longLabels?: boolean alternate?: "none" | "queue" | "steer" manySuggestions?: boolean history?: boolean many?: boolean /** File search waits for the story's "Return files" button, like a slow server. */ fileSearch?: boolean suggestionBoundary?: () => HTMLElement | undefined }) { const [fileSearch, setFileSearch] = createStore<{ pending?: string }>({}) let returnFiles: (() => void) | undefined const [draft, setDraft] = createStore({ prompt: props.prompt ?? [{ type: "text", content: "", start: 0, end: 0 }], cursor: props.prompt ? promptLength(props.prompt) : 0, model: { providerID: STORY_MODEL.providerID, modelID: STORY_MODEL.id, variant: STORY_MODEL.variant }, context: { items: props.comments ?? [] }, }) const [story, setStory] = createStore({ activity: props.label ?? "Ready", variant: STORY_MODEL.variant, }) const modelOption = createMemo(() => ({ ...selectedModel, name: props.longLabels ? "Claude Sonnet with an unusually long model name" : selectedModel.name, })) const modelSelection = { ready: Object.assign(() => true, { promise: undefined }), key: () => ({ providerID: modelOption().provider.id, modelID: modelOption().id }), current: () => modelOption(), recent: () => [modelOption()], favorite: { list: () => [], toggle() {} }, list: () => [modelOption()], cycle() {}, set() {}, visible: () => true, setVisibility() {}, variant: { configured: () => STORY_MODEL.variant, current: () => story.variant, list: () => ["balanced", "high"], set: (variant: string | undefined) => setStory("variant", variant ?? "balanced"), cycle() {}, }, } satisfies ModelSelection const commands: ComposerSuggestion[] = [ { id: "command.test", kind: "command", label: "/test", trigger: "test", title: "Run tests" }, { id: "command.review", kind: "command", label: "/review", trigger: "review", title: "Review changes" }, ...(props.manySuggestions ? Array.from({ length: 12 }, (_, index) => ({ id: `command.example-${index}`, kind: "command" as const, label: `/example-${index}`, trigger: `example-${index}`, title: `Run example ${index}`, })) : []), ] const context: ComposerSuggestion[] = [ { id: "file:src/app.tsx", kind: "file", label: "src/app.tsx", path: "src/app.tsx", mention: { type: "file", path: "src/app.tsx", content: "@src/app.tsx", start: 0, end: 0 }, }, { id: "agent:review", kind: "agent", label: "@review", mention: { type: "agent", name: "review", content: "@review", start: 0, end: 0 }, }, { id: "skill:effect", kind: "skill", label: "@effect", description: "Build Effect applications", mention: { type: "skill", id: Skill.ID.make("effect"), name: Skill.Name.make("Effect"), content: "@effect", start: 0, end: 0, }, }, ] const editor = createComposerEditor({ store: [draft, setDraft], commands: () => commands, context: () => context, searchContextFiles: (query, signal) => { if (!props.fileSearch) return [] return new Promise((resolve) => { returnFiles = () => resolve(query.includes("z") ? [] : storyFiles(query)) setFileSearch("pending", query) signal?.addEventListener("abort", () => setFileSearch("pending", undefined), { once: true }) }) }, get history(): ComposerHistory | undefined { if (!props.history && !props.many) return undefined return { entries: (mode) => mode === "shell" ? [{ prompt: text("bun typecheck") }] : [ { prompt: text("Explain the latest changes") }, { prompt: [ ...text("Review the composer layout\nKeep keyboard navigation accessible"), { type: "path", id: "history-layout", filename: "layout.png", mime: "image/png", path: "C:/shots/layout.png", }, ], metadata: "review", }, { prompt: text("Run the focused tests") }, ...(props.many ? Array.from({ length: 16 }, (_, index) => ({ prompt: text(`Earlier prompt ${index + 1}`) })) : []), ], add() {}, capture: () => (draft.context.items.some((item) => item.key === "history-comment") ? "review" : undefined), restore: (metadata) => setDraft( "context", "items", metadata === "review" ? [ { type: "file", key: "history-comment", path: "src/composer.tsx", selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, comment: "Keep the search separate from the draft", }, ] : [], ), } }, readImage: async () => pixel, view: { placeholder: () => "Ask anything, / for commands, @ for context...", agent: { options: () => [ { id: "build", label: props.longLabels ? "Build agent with an unusually long name" : "build" }, { id: "review", label: "review" }, ], current: () => "build", onSelect: (agent) => setStory("activity", `Selected ${agent}`), }, variant: { options: () => [ { id: "default", label: "default" }, { id: "balanced", label: props.longLabels ? "Balanced reasoning with an extended label" : "balanced" }, { id: "high", label: "high" }, ], current: () => story.variant, onSelect: (variant) => setStory("variant", variant), }, submit: { stopping: () => !!props.stopping, working: () => !!props.working, busy: () => !!props.sending, get queue() { const alternate = props.alternate if (!alternate || alternate === "none") return undefined return { count: () => 0, delivery: () => (alternate === "queue" ? "steer" : "queue"), alternate: () => alternate, editing: () => undefined, confirmEdit() {}, undoing: () => false, cancelEdit() {}, editFirst: () => false, first() {}, steerFirst() {}, } }, onSubmit: () => { const value = draft.prompt.map((part) => ("content" in part ? part.content : `[${part.filename}]`)).join("") const request = props.inspectRequest ? buildPromptRequest({ prompt: draft.prompt, context: draft.context.items, images: [], text: value, sessionDirectory: "C:/repo", }) : undefined setDraft("prompt", [{ type: "text", content: "", start: 0, end: 0 }]) setDraft("cursor", 0) if (props.failure) { setDraft("prompt", props.prompt ?? [{ type: "text", content: "", start: 0, end: 0 }]) setStory("activity", "Submission failed; draft restored") return } setStory( "activity", request ? JSON.stringify({ files: request.files, agents: request.agents, skills: request.skills }) : `Submitted: ${value}`, ) }, onStop: () => setStory("activity", props.continueOnStop ? "POST /interrupt · resume: true" : "Stop requested"), }, }, }) const model = { ...editor, model: { selection: modelSelection, paid: true, loading: false }, } satisfies ComposerModel const suggest = (kind: typeof props.suggestions) => { if (kind === "command") return model.openCommands() if (kind === "context") return model.openContext() model.dispatch({ type: "popover.close" }) } onMount(() => { if (props.suggestions === "command" || props.suggestions === "context") suggest(props.suggestions) }) // The Lab keeps this story mounted across states that differ only in args, so the composer follows them // in place and its own transitions play. The prompt is compared by value: the lab updates its args store in place. // One effect, so the prompt lands before the suggestions open on it: an empty draft opens them inline, typing the // trigger, so a change of either starts over from the state's prompt. createEffect( on( () => [JSON.stringify(props.prompt ?? null), props.suggestions] as const, ([json, kind]) => { const prompt: ComposerPersistedState["prompt"] = JSON.parse(json) ?? text("") setDraft({ prompt, cursor: promptLength(prompt) }) suggest(kind) }, { defer: true }, ), ) createEffect( on( () => props.label, (label) => setStory("activity", label ?? "Ready"), { defer: true }, ), ) return (
{story.activity}
) } const text = (content: string): ComposerPersistedState["prompt"] => [ { type: "text", content, start: 0, end: content.length }, ] const storyFiles = (query: string): ComposerSuggestion[] => ["plan.md", "notes.md", "capture.ts", "corpus.ts", "cursor.png", "claude.png"].map((name) => { const path = `${query}/${name}` return { id: `file:${path}`, kind: "file", label: path, path, mention: { type: "file", path, content: `@${path}`, start: 0, end: 0 }, } }) type FlowArgs = { prompt?: ComposerPersistedState["prompt"] working: boolean stopping: boolean failure: boolean sending: boolean label: string suggestions: "command" | "context" | "none" alternate: "none" | "queue" | "steer" many: boolean } export default { title: "OpenCode/Composer/Flow", component: Composer, parameters: { layout: "centered" }, // States that only change the composer's props share this render, so moving between them keeps one composer. args: { working: false, stopping: false, failure: false, sending: false, label: "Ready", suggestions: "none", alternate: "none", many: false, }, argTypes: { suggestions: { control: "select", options: ["none", "command", "context"] }, alternate: { control: "select", options: ["none", "queue", "steer"] }, }, render: (args: FlowArgs) => , } export const EmptyDraft = {} export const PromptHistory = { args: { many: false }, render: (args: FlowArgs) => (
), } export const TextDraft = { args: { prompt: text("Explain this change") } } export const MultilineDraft = { args: { prompt: text("Review the implementation\nThen run the focused tests") } } export const MixedAttachments = { render: (args: FlowArgs) => ( ), } export const BrowserElementComment = { render: (args: FlowArgs) => ( form > button.btn.primary")', comment: "Match the secondary button height", commentID: "save", }, { type: "file", key: "comment:src/app.tsx", path: "src/app.tsx", selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, comment: "Keep the normal flow flat", }, ]} /> ), } export const ModelAndVariant = { args: { prompt: text("Compare both variants") } } export const SlashSuggestions = { args: { suggestions: "command" } } export const ContextSuggestions = { args: { suggestions: "context" } } export const SlowFileSearch = { render: (args: FlowArgs) => } function ConstrainedCommandSuggestionsStory(props: FlowArgs) { let boundary: HTMLDivElement | undefined return (
boundary} />
) } export const ConstrainedCommandSuggestions = { args: { suggestions: "command" }, render: (args: FlowArgs) => , } export const DetachedCommandSuggestionBoundary = { args: { suggestions: "command" }, render: (args: FlowArgs) => { const detached = document.createElement("div") return detached} /> }, } export const RunningAndStopping = { args: { working: true, stopping: true, label: "Session is running" } } export const SteeringFollowUp = { args: { prompt: text("Use this correction at the next boundary"), working: true } } export const FailedSubmissionRestoration = { args: { prompt: text("Preserve this draft on failure"), failure: true } } export const Sending = { args: { prompt: text("Run the focused tests"), sending: true } } export const NewSessionFirstPrompt = { args: { prompt: text("Create the Session and implement the change"), label: "New Session draft" }, } export const ActiveSessionFollowUp = { args: { prompt: text("Now add focused coverage"), label: "Active Session follow-up" }, } export const RightToLeft = { globals: { direction: "rtl" }, args: { prompt: text("راجع src/app.tsx ثم شغّل bun test") }, } export const NarrowLayout = { parameters: { viewport: { defaultViewport: "mobile1" } }, args: { prompt: text("Verify the narrow Composer") }, render: (args: FlowArgs) => (
), } export const ToolbarOverflow = { args: { alternate: "queue", working: true, prompt: text("Keep all controls reachable when the toolbar overflows") }, render: (args: FlowArgs) => (
), } export const DemoFirstClassSkillIDs = { name: "Demo: First-class skill IDs", args: { suggestions: "context", label: "Select a skill from the context menu" }, render: (args: FlowArgs) => ( ), } export const DemoStructuredCustomCommand = { name: "Demo: Structured custom command", render: (args: FlowArgs) => ( ), } export const DemoPendingInboxHydration = { name: "Demo: Pending inbox hydration", render: () => , } export const DemoServerOwnedExecutionStatus = { name: "Demo: Server-owned execution status", render: () => , } export const DemoDurableSelectionPrecedence = { name: "Demo: Durable selection precedence", args: { label: "Composer is ready", prompt: text("Continue with the resolved Session selection") }, render: (args: FlowArgs) => , } export const DemoContinueOnStop = { name: "Demo: Continue on Stop", args: { working: true, stopping: true, label: "Session execution is running" }, render: (args: FlowArgs) => ( ), } function DemoFrame(props: { title: string; description: string; children: JSX.Element }) { return (

{props.title}

{props.description}

{props.children}
) } function PendingInboxDemo() { const [store, setStore] = createStore({ hydrated: false }) return (
} >
) } function ServerStatusDemo() { const [store, setStore] = createStore({ running: false, activity: "Idle from server projection" }) const document = createMemo(() => ({ ...emptySessionDocument, status: store.running ? ({ type: "busy" } as const) : ({ type: "idle" } as const), })) return (
{store.activity}
) } function SelectionPrecedenceDemo(props: FlowArgs) { const [store, setStore] = createStore({ durable: true }) const selection = createMemo(() => resolveSessionComposerSelection( store.durable ? { agent: "build", model: { id: "claude-sonnet-4", providerID: "anthropic" } } : undefined, { agent: "review", model: { modelID: "gpt-5", providerID: "openai" } }, ), ) return (
SessionInfo.model {store.durable ? "anthropic/claude-sonnet-4" : "Unavailable"} Last message metadata openai/gpt-5 Resolved selection {selection().model ? `${selection().model?.providerID}/${selection().model?.modelID}` : "Unavailable"}
) }