GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — Add Intent abstraction for two-way server (and plugin) → client UI interactions by the-vampiire · Pull Request #6549 · anomalyco/opencode Conversationfeat: Add Intent abstraction for server→client UI interactionsSummaryThis PR introduces a generic Intent abstraction that enables the server (tools, plugins, core) to request user input through the TUI. It provides composable UI primitives (form, confirm, select, multiselect, toast) following the existing Permission system's event-based pattern. Closes: #6330 (partial — progress intent deferred) UII have tested it out with an
They work with keyboard (arrows, space for multi-select, esc to cancel) or mouse input. MotivationCurrently, there's no standardized way for tools or plugins to request user input during execution. PRs #5958 and #5563 implemented
What's Included vs. Issue #6330
Why
|
| Issue #6330 Proposed | This PR | Rationale |
|---|---|---|
ui-intent module |
intent module |
Follows opencode's single-word convention |
/session/:id/ui-intent/:id |
/session/:id/intent/:id |
Shorter, consistent |
ui.intent.request event |
intent.updated event |
Matches Permission pattern |
ui.intent.response event |
intent.replied event |
Matches Permission pattern |
Standalone select and multiselect intents — Issue only proposed these as form fields. Added as top-level intents for simpler use cases.
Conditional fields — condition: { field, equals } on TextField enables the "select with Other option" pattern mentioned in the proposal.
cancelAll(sessionID) — Utility to cancel all pending intents when a session ends.
This PR implements TUI renderers only. Desktop and Web clients would need their own implementations of the intent dialog component. The core module and SDK are client-agnostic.
packages/opencode/src/intent/)types.ts — Zod schemas for 5 intent types:
form — Multi-field input form with conditional field visibilityconfirm — Yes/no dialog with info/warning/danger variantsselect — Single-choice selection (2-8 options)multiselect — Multi-choice selection with optional min/maxtoast — Non-blocking notificationindex.ts — State management and public API:
Intent.request() — Create pending intent, returns PromiseIntent.respond() — Submit user responseIntent.list() — List pending intentsIntent.cancelAll() — Cancel all intents for a sessionIntent.form(), Intent.confirm(), Intent.select(), Intent.multiselect(), Intent.toast()Intent.Event.Updated, Intent.Event.Repliedpackages/opencode/src/server/server.ts)POST /session/:sessionID/intent/:intentID — Submit response to pending intentGET /intent — List all pending intentspackages/opencode/src/cli/cmd/tui/)component/dialog-intent.tsx — Full dialog component with renderers for all intent types:
ConfirmDialog — Left/right arrow navigation, enter to confirmSelectDialog — Up/down navigation, enter to selectMultiSelectDialog — Space to toggle, enter to submitFormDialog — Tab between fields, enter to submitapp.tsx — Event subscription:
Intent.Event.UpdatedDialogIntent for blocking intentspackages/sdk/)Regenerated with:
client.intent.respond() — Submit intent responseclient.intent.list() — List pending intentspackages/plugin/src/index.ts)Added UIHelpers type and ui property to PluginInput:
export type UIHelpers = { form(ctx, input): Promise<Record<string, any>> confirm(ctx, input): Promise<boolean> select(ctx, input): Promise<string | undefined> multiselect(ctx, input): Promise<string[]> toast(ctx, input): Promise<void> } export type PluginInput = { // ... existing fields ui?: UIHelpers // Available when running with intent support }
packages/opencode/src/plugin/index.ts)UIHelpers implementation that wraps Intent module:
ui: { form: (ctx, input) => Intent.form({ ...ctx, ...input, source: "plugin", plugin: name }), // ... other helpers }
const plugin: Plugin = async ({ ui }) => ({ tool: { dangerous_operation: { description: "Does something dangerous", parameters: z.object({ path: z.string() }), async execute({ parameters, sessionID, messageID }) { if (ui) { const confirmed = await ui.confirm( { sessionID, messageID }, { title: "Confirm Operation", message: `This will modify ${parameters.path}. Continue?`, variant: "danger", } ) if (!confirmed) return { title: "Cancelled", output: "User cancelled" } } // proceed with operation... }, }, }, })
const result = await ui.form( { sessionID, messageID }, { title: "Configure Database", fields: [ { type: "select", id: "type", label: "Database Type", options: [ { value: "pg", label: "PostgreSQL" }, { value: "mysql", label: "MySQL" }, { value: "other", label: "Other" }, ], }, { type: "text", id: "custom_type", label: "Specify database", condition: { field: "type", equals: "other" }, // Only shown when "Other" selected }, ], } ) // result = { type: "pg" } or { type: "other", custom_type: "cockroachdb" }
8 unit tests covering:
bun test packages/opencode/test/intent/intent.test.tsSee MANUAL_TESTING.md for step-by-step TUI testing instructions.
Following Permission pattern — Uses the same event-based architecture with pending state and promise resolution
Composable primitives — Form fields use the same schemas as standalone intents, enabling composition
Non-blocking toast — Toast returns immediately and doesn't create pending state
Session-scoped cleanup — cancelAll() clears all pending intents when session ends
Schema limits — Options capped at 2-8 items, fields at 1-10 to prevent UI overload
Optional ui on PluginInput — Plugins must check if (ui) before using, as it may not be available in all contexts (headless mode, non-TUI clients)
Separate dialog-intent vs reusing dialog-select — Intentionally kept as separate components despite functional overlap. Analysis below.
Modal dialog vs inline input replacement — Chose modal overlay rather than replacing the input area (Claude Code style). Analysis below.
Claude Code replaces the input textarea with the question UI, keeping the user "in flow" with the conversation. We considered this but chose a modal dialog instead.
| Aspect | Modal Dialog (This PR) | Inline Replacement (Claude Code) |
|---|---|---|
| Context visibility | Obscures conversation | Conversation visible |
| User mental model | "I'm answering a question" | "I'm continuing the conversation" |
| Complex forms | ✅ Multiple fields, selects, conditions | ❌ Awkward for multi-field |
| Implementation | New component, self-contained | Modify input component state machine |
| Partial input handling | N/A (separate UI) | Must save/restore draft text |
| Escape behavior | Close modal, cancel intent | Unclear—restore input? Cancel? |
Consistent with existing UI — OpenCode already uses modals for:
Ctrl+K)Ctrl+P)Adding another modal is expected behavior. Inline replacement would be the outlier.
Supports all intent types — Modal naturally handles:
confirm — Yes/No buttonsselect — Option list with keyboard navmultiselect — Checkboxes with space to toggleform — Multiple fields with conditionsInline replacement works well for simple text input but becomes awkward for structured selection UI.
Clear escape hatch — Esc closes modal and cancels the intent. With inline replacement, the semantics are muddier—does Esc restore the previous input? Cancel the whole operation? Users would need to learn new behavior.
Implementation isolation — Modal is a new component (dialog-intent.tsx) with no coupling to the input system. Inline replacement would require:
Inline replacement could be offered as an optional UX mode in a future PR if users prefer the Claude Code style. This would be additive—the modal implementation provides a working baseline, and inline could be added as intent.display: "inline" | "modal" in config.
This keeps the current PR focused on the Intent API and plugin integration, deferring UX experimentation to a separate effort.
We considered three options for the TUI dialog implementation:
| Option | Description | Risk |
|---|---|---|
| 1. Keep separate | New dialog-intent.tsx with its own Select/MultiSelect |
Low |
| 2. Compose | dialog-intent uses DialogSelect internally |
Medium |
| 3. Extract primitives | Shared OptionList component both use |
High |
We chose Option 1. Here's why:
| Aspect | dialog-select |
dialog-intent |
|---|---|---|
| Purpose | General TUI selection | Intent API communication |
| Trigger | Direct TUI invocation | Agent Intent events |
| Search/Filter | ✅ Fuzzy search | ❌ None needed |
| Categories | ✅ Grouped options | ❌ Flat list |
| Intent Types | Select only | Confirm, Select, MultiSelect, Form |
| Form Fields | ❌ | ✅ With conditions |
Test coverage for TUI components: None
dialog-select.tsx → 0 tests (14 consumer components)
dialog-intent.tsx → 0 tests (new, 1 consumer)
Intent API → 8 tests (core module only)
DialogSelect consumers (14 files):
Option 3 would require:
If abstracting shared primitives is desired:
OptionList)This keeps the Intent PR focused, reviewable, and low-risk.
progress primitive — Needs design for streaming updates
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Documentation AddedAdded documentation for the Intent system to the website docs: New Files
Updated Files
Docs build successfully ✅ |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Overall this looks great. I'd love to see some version of this make it into the upstream!
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
- Add Intent namespace with form, confirm, select, multiselect, toast primitives - Add IntentInfo and IntentResponse schemas for request/response cycle - Add server endpoints: POST /session/:id/intent/:id, GET /intent - Add Bus events: intent.updated, intent.replied - Add convenience helpers: Intent.form(), Intent.confirm(), Intent.select(), etc. - Add timeout and cancellation support - Add unit tests covering all intent types and edge cases
- Add dialog-intent.tsx with confirm, select, multiselect, form renderers - Wire Intent.Event.Updated subscription in app.tsx - Toast intents use existing toast system - Fix Zod schema types to support optional fields with defaults - Add z.input<> types for function parameters
- Regenerate SDK with intent.respond() and intent.list() methods - Add UIHelpers type to PluginInput (form, confirm, select, multiselect, toast) - Wire up plugin loader to provide UI helpers via Intent module - Update dialog-intent component with improved field handling
… design documentation - Add evt.preventDefault() to all keyboard handlers to prevent event leaking - Change form submit from ctrl+enter to enter - Convert select/multiselect field renderers to vertical layout - Add keyboard navigation (up/down) to form field renderers - Add space to toggle for multiselect field renderer - Auto-focus text inputs when they become visible (conditional fields) - Support array values in condition checks for multiselect - Document design decision to keep dialog-intent separate from dialog-select
Co-locate type casts with Switch/Match guards following the pattern established in session/index.tsx (UserMessage/AssistantMessage). Child components now receive narrowed types directly, removing redundant inline type assertions.
Follow existing pattern (ProjectRoute, TuiRoute) by extracting intent endpoints to separate Hono instance. Fixes TypeScript type chain depth limit exceeded error. API change: /session/:sessionID/intent/:intentID -> /intent/:sessionID/:intentID
8fa8d96 to
93206b6
Compare
Critical fixes: - dialog-intent.tsx: Fix API URL from /session/x/intent/y to /intent/x/y (was calling wrong endpoint, would have failed at runtime) - intent.test.ts: Flatten test structure to match canonical next.test.ts (codebase uses flat test() calls, not nested describe blocks) Standard fixes: - server/intent.ts: Split hono-openapi imports per project.ts pattern (describeRoute, validator on line 2; resolver on line 3) Verified via systematic comparison against: - permission/index.ts, permission/next.ts (core module patterns) - server/project.ts (route patterns) - test/permission/next.test.ts (test patterns) All tests pass (8/8), typecheck clean, formatter produces no changes.
|
i spent some extra time with claude to develop an idiomatic contribution guide. we used it to do a thorough review and align the PR with the code base. then we revisited it based on the experience to refine it. its out of scope so i didnt commmit it, but if you think its helpful i can add it for other contributors (here or in another PR). idioatic contributor guide# Idiomatic Contribution Guide Mental ModelYou are a guest in someone else's home. The existing codebase represents years of decisions, trade-offs, and evolved conventions. Every pattern you encounter—whether you personally agree with it or not—is the canonical standard. Your contribution must blend seamlessly, as if a core maintainer wrote it themselves. Core Principles
ApproachPhase 1: Establish BaselineBefore writing any code:
Phase 2: Implement with ConformanceWhile writing code:
Phase 3: Validate ConformanceBefore submitting:
Pattern DiscoveryFinding Canonical ReferencesMinimum 2 references required — A single reference can be an exception to the codebase norm. Multiple references reveal the actual pattern. Why 2+ References MatterA single reference can mislead you into following an exception rather than the rule. Example from real PR:
After checking more references:
The first reference was the exception, not the rule. When References ConflictIf canonical references show different patterns:
Example: "NamedError.create() used in 17 files (34 instances) vs class extends Error in 3 files (5 instances) → followed dominant pattern" Pattern Categories to Match
Status ClassificationsWhen analyzing conformance, use only these statuses:
There is no "acceptable deviation" — Either validate via multiple references that your approach IS the pattern, or fix it. Ambiguity = unresolved work. If you're tempted to mark something "acceptable" or "minor," you haven't done enough research. Find more references until you can definitively say conformant or drift. Issue SeverityNot all drift is equal. Prioritize fixes by severity:
Fix all tiers, but prioritize critical issues first. A stylistic fix means nothing if the code doesn't work. When Deviation May Be JustifiedDeviation from pattern is acceptable ONLY when:
If you can't quantify why you're different, you're not different enough. Example justification:
ExamplesGood: Following Route Pattern// Canonical reference: src/server/project.ts export const ProjectRoute = new Hono() .get("/", describeRoute({...}), async (c) => {...}) .patch("/:id", describeRoute({...}), validator(...), async (c) => {...}) // Your contribution: src/server/intent.ts export const IntentRoute = new Hono() .get("/", describeRoute({...}), async (c) => {...}) .post("/:id", describeRoute({...}), validator(...), async (c) => {...}) Bad: Inventing New Patterns// Your contribution introduces different style const intentRouter = new Hono() // Wrong: different naming convention intentRouter.get(...) // Wrong: not chained export default intentRouter // Wrong: default export vs named Good: Type Narrowing at Match Site// Canonical reference: src/cli/cmd/tui/routes/session/index.tsx <Match when={message.role === "user"}> <UserMessage message={message as UserMessage} /> </Match> // Your contribution follows same pattern <Match when={intent.type === "confirm"}> <ConfirmDialog intent={intent as ConfirmIntent} /> </Match> Do
Don't
ChecklistBefore marking PR ready for review:
SummaryYour goal: Write code that a maintainer would write. Your measure of success: A reviewer cannot distinguish your contribution from existing code. Your mindset: Grateful guest, not opinionated visitor. Your method: Multiple references, quantified decisions, zero ambiguity. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@the-vampiire I was hoping your PR would find its way into the code. Is there a reason you've closed this PR? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@arsham based on latest release yesterday, they have the question tool added. @thdxr took a different direction with it: this PR was an abstract foundation for intents that question or any other tools / plugins could build on. it's been 2 weeks since the discussion and PR, i don't think this is how they want to handle it. less so because it would be a big refactor to integrate now. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.