Compare commits

..

1 Commits

Author SHA1 Message Date
Dustin Deus fda66bfd40 fix(core): request default OpenAI reasoning summaries 2026-07-13 10:12:06 +00:00
55 changed files with 1222 additions and 847 deletions
+245
View File
@@ -0,0 +1,245 @@
# OpenCode Session Runtime
OpenCode sessions preserve durable conversational history while assembling the runtime context an agent needs to act correctly in its current environment.
## Language
**Model Context**:
The complete model-visible input assembled for one **Step**, including system instructions, **Session History**, tool definitions, and step-local additions. **Instructions** are one component of Model Context, not a synonym for it.
_Avoid_: System Context
**Instructions**:
The opaque algebra of independently refreshable typed instruction sources that render the durable instruction baseline and chronological updates shown to the model.
_Avoid_: Model Context, System Context
**Session History**:
The projected chronological conversation selected for a **Step** after applying the active compaction boundary and interleaving derived **Instruction Updates** from the current **Instruction Epoch**.
_Avoid_: Session Context
**Instruction Source**:
One independently read typed value within **Instructions**, represented by a stable namespaced key, canonical JSON codec, pure first/changed renderers, and an optional removal renderer.
_Avoid_: Prompt fragment
**InstructionEntry**:
One API-managed, durable, per-Session instruction value. Its slash-free client key maps to the `api/<key>` **Instruction Source** key. Entries deliberately render to the model as mechanism-neutral `<context>` blocks: the model sees session context, not how it was attached.
**InstructionDiscovery**:
The Location-scoped service that observes ambient global and upward-project `AGENTS.md` files as one ordered aggregate **Instruction Source**.
**Instruction State**:
The Session-owned projection cache of one instruction log fold: epoch start, values at that start, current values, and the last folded sequence. It is rebuilt from durable events and never authors model-visible facts.
**Instruction Update**:
A durable `session.instructions.updated` value delta admitted at a **Safe Step Boundary**. Its model-visible System text is rendered from stored values at request assembly and is never persisted verbatim.
_Avoid_: Correction, stored prose, raw text diff
**Initial Instructions**:
The deterministic instruction text rendered from values at the current **Instruction Epoch** start and sent as provider-cache prefix state until completed compaction moves the epoch or Session movement or committed revert resets it.
_Avoid_: Live system prompt
**Instruction Epoch**:
The span between completed compactions. Its start is the last `session.compaction.ended` sequence, or the initial complete instruction delta when no prior epoch exists.
**Instruction Values**:
The key-to-hash map produced by folding instruction deltas in durable sequence order. Hash bodies live once in the content-addressed instruction blob store.
**Unavailable Instruction Source**:
An expected temporary inability to read an **Instruction Source** value; the runtime retains its prior effective value and emits no update, while an unavailable source blocks the initial complete delta.
**Safe Step Boundary**:
The point during Step preparation, after prior tool settlement and before durable input promotion, where instruction changes may be admitted chronologically.
**Admitted Prompt**:
A durable user input accepted into the Session inbox but not yet included in **Session History**.
**Prompt Promotion**:
The durable transition that removes an **Admitted Prompt** from pending input and appends its user message to **Session History**.
**Step**:
One logical LLM call spanning pre-flight instruction synchronization, input promotion, request build, and compaction check; the provider stream; and tool settlement.
_Avoid_: provider turn, turn (unqualified)
**Physical Attempt**:
One actual provider request on the wire in service of a **Step**; most Steps have one Physical Attempt, while overflow-triggered compaction recovery may give one Step two.
**Assistant Turn**:
A reserved name for the not-yet-modeled unit containing all **Steps** from prompt promotion until the assistant yields the floor; do not reify it until something durable needs it.
**Settlement**:
The terminal transition for a unit of work: Step and tool settlement are durable, while drain and execution settlement are coordinator-observed.
**Execution**:
One session-scoped coordinator busy period from first wake until idle. An Execution is process-local coordination rather than a durable domain entity.
**Session Drain**:
One process-local execution span that promotes eligible input and runs required **Steps** until no immediate continuation remains. A Session Drain has no durable identity or transcript boundary.
**Model Tool Output**:
The bounded projection of a Core-executed tool result persisted in Session history and replayed to the model. A tool may shape this projection semantically, but the Tool Registry enforces the final size limit.
**Managed Tool Output File**:
A temporary file created under OpenCode's shared tool-output directory to retain complete output that was too large for Session history.
**Model Request Options**:
Provider-semantic model settings selected from the Catalog and active Session variant before the LLM protocol adapter encodes them for a provider request.
_Avoid_: Request body, wire options
**Generation Controls**:
Provider-neutral sampling and output controls, partitioned from provider semantics and compatibility wire fields when model metadata enters the Catalog.
**Native Continuation Metadata**:
Opaque protocol-shaped data attached to assistant content and required to continue that content natively with a compatible model, such as a reasoning signature or provider-hosted item identifier.
**PTY Environment**:
The host-supplied environment overlay applied by the server when creating a PTY, observed for the request Location and resolved PTY working directory.
**OpenCode Client**:
The generated Promise and Effect APIs derived from the public `HttpApi`; **Embedded OpenCode** shares the Effect API through an in-memory `HttpClient` against the same router and handlers.
_Avoid_: Remote client
**SDK Contract IR**:
The runtime-neutral compiled representation of the authoritative `HttpApi`, preserving encoded and decoded type projections plus transport metadata so independent SDK emitters can choose their public value model and runtime interpreter.
**Embedded OpenCode**:
A scoped in-process host that structurally extends the **OpenCode Client**, supplies an in-memory HTTP transport, and exposes additional same-process capabilities directly.
_Avoid_: Local implementation
**Page**:
A bounded ordered result containing `items` and opaque `previous` and `next` cursor links for navigating the same query in either direction.
_Avoid_: Response envelope
## Relationships
- **Instructions** is an opaque carrier composed from zero or more **Instruction Sources**.
- **Model Context** is broader than **Instructions**. For each **Step**, the runner assembles the selected agent or provider system text, **Initial Instructions**, **Session History**, available tools, and step-local additions into one model request.
- **Session History** persists conversational messages. The runner derives model-facing **Instruction Update** messages from value deltas and interleaves them by durable sequence; **Initial Instructions** remain separate provider-request state.
- The runner explicitly loads and combines instruction built-ins, **InstructionDiscovery**, selected-agent skill guidance, reference guidance, MCP guidance, and **InstructionEntry** values. There is no instruction registry.
- `Instructions.combine(...)` preserves caller order and rejects duplicate stable namespaced source keys. The runner loads its producers concurrently, then combines them in its fixed declared order.
- Each **Instruction Source** read returns one coherent typed value, explicit removal, or temporary unavailability. `Instructions.make(...)` hides the value type so differently typed sources compose uniformly; its canonical codec defines storage and hash equivalence, while pure renderers produce first, changed, and optional removal text.
- `Instructions.read(...)` reads every composed source concurrently and exactly once at the boundary. `Instructions.diff(...)` compares encoded-value hashes with current **Instruction Values** and returns one delta plus new blob bodies.
- `Instructions.renderInitial(...)` renders values at the **Instruction Epoch** start. `Instructions.renderUpdate(...)` renders one hydrated delta against the values immediately before it.
- A changed **Instruction Source** contributes its hash to one **Instruction Update**; explicit removal contributes the `"removed"` sentinel.
- An **Instruction Update** persists only its value delta. Rendered text is derived during request assembly and excluded from compaction summaries.
- The instruction blob insert, durable delta, and **Instruction State** advance commit atomically.
- Changes from multiple **Instruction Sources** admitted at one safe boundary combine into one **Instruction Update**.
- Instruction changes are sampled and admitted lazily at a **Safe Step Boundary**, never pushed asynchronously when their source changes.
- At a **Safe Step Boundary**, prior tool results are already settled; instruction preparation completes before newly admitted user input promotes.
- An **Admitted Prompt** is replayable pending input, not yet model-visible **Session History**.
- **Prompt Promotion** atomically consumes the pending inbox entry and appends its model-visible user message.
- Steering prompts promote at the next **Safe Step Boundary** while the current **Session Drain** still requires continuation. Promoting any newly admitted user input resets the selected agent's step allowance; multiple prompts promoted at one boundary reset it once.
- A queued prompt does not promote while the current **Session Drain** requires continuation. The runner promotes one queued prompt when the Session would otherwise become idle, then reevaluates continuation before promoting another.
- A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, physical attempts, and tool state rather than inventing an enclosing execution identity.
- An **Execution** contains one or more **Session Drains**; a **Session Drain** contains one reserved assistant-turn span at a time; that span contains **Steps**; and each **Step** contains one or more **Physical Attempts** plus any tool calls it requires.
- A **Step** record covers only the model-visible span from first assistant output through tool settlement; pre-flight leaves no record, and one Step settles at most one record.
- The first **Step** admits one complete delta and renders **Initial Instructions** without narrating that delta in history; an unavailable initial source blocks the Step instead of persisting incomplete values.
- Instruction preparation precedes durable input promotion on every Step so an unavailable first baseline leaves pending input untouched and later updates enter history before newly promoted input.
- Completed compaction moves the **Instruction Epoch** to the exact `session.compaction.ended` sequence and copies current hashes to the epoch's initial values. Earlier updates leave active model history while durable deltas remain.
- A newly composed **Instruction Source** absent from current **Instruction Values** emits its first rendering once at the next **Safe Step Boundary**.
- **Unavailable Instruction Source** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text.
- **InstructionDiscovery** observes ambient instructions as one ordered aggregate **Instruction Source**.
- Ambient discovery reads global and upward-project `AGENTS.md` files and honors `OPENCODE_DISABLE_PROJECT_CONFIG` for project files.
- After a successful internal file or directory read, nearby `AGENTS.md` files toward the Location root are injected once per Session as durable synthetic instruction messages.
- **InstructionEntry** stores API-managed per-Session JSON values. Each entry contributes one `api/<key>` **Instruction Source**, so adding, replacing, or removing an entry is reconciled at the next **Safe Step Boundary**.
- Location-scoped instruction producers naturally re-resolve when a moved Session next runs in its destination Location.
- Moving a Session clears its **Instruction State**, so the destination must admit a complete delta before another prompt can promote. Committed revert does the same; replay derives both resets from their durable events.
- Selected-agent available-skill guidance is an **Instruction Source** composed explicitly by the runner. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool.
- The selected agent and model are sampled when a **Step** starts. Changes admitted after that boundary apply to the next Step and do not restart the current Step.
- An agent switch that changes selected-agent guidance produces an **Instruction Update** while preserving the current baseline.
- Local tool authorization and pending permission requests retain the effective agent of the **Step** that issued the call; a later agent switch cannot change that call's policy.
- Instruction source changes never wake idle Sessions; the next naturally scheduled **Safe Step Boundary** loads and compares current values lazily.
- Once admitted, an **Instruction Update** remains durable even if the following **Physical Attempt** fails and is replayed unchanged on retry.
- **Instruction Updates** remain durable value history but are not `session_message` rows. Clients display changed keys rather than model-facing prose.
- The date **Instruction Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later.
- **Initial Instructions** are recomputed deterministically from durable values for every request; rendered bytes are not stored.
- A model/provider switch preserves current **Instruction Values**, the **Instruction Epoch**, and chronological conversation history; the new selection applies to the next **Step**.
- **Native Continuation Metadata** remains in durable history. Step projection includes it only for a successful exact originating provider/model match; failed Steps and incompatible models omit opaque metadata, while non-empty visible reasoning lowers to ordinary assistant text after a model switch. This conservative relation may widen only when recorded provider tests establish compatibility.
- **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding.
- **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing.
- The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`.
- Networked and **Embedded OpenCode** use the same **OpenCode Client** and preserve the full HTTP encoding, routing, middleware, and decoding boundary; only the `HttpClient` transport differs.
- The Effect-native network constructor obtains `HttpClient.HttpClient` from its environment so callers own transport selection, recording, tracing, retries, and tests. Convenience runtimes may provide a fetch transport separately.
- Creating **Embedded OpenCode** is scoped. Closing its owning Scope releases the in-process server resources, database resources, registrations, and fibers.
- **Embedded OpenCode** exposes shared client capabilities and embedded-only capabilities on one object; consumers do not navigate through a nested `.client` property.
- The beta **OpenCode Client** currently uses plural consumer-facing capability groups such as `sessions`; whether the stable Session namespace should instead be singular `session` must be settled before stabilization. Internal server identifiers do not implicitly define public client names.
- Server's concrete `HttpApi` is authoritative for shared **OpenCode Client** capabilities. Codegen compiles its Session group directly; the Effect runtime uses an equivalent Protocol-only projection so generated artifacts remain independent of Core and Server.
- SDK generation reflects the public `HttpApi` once into an **SDK Contract IR**. Promise and Effect emitters share endpoint structure and transport metadata without being required to expose identical public values: an emitter may select encoded wire types, decoded domain types, compile-time brands, runtime validation, and its own execution abstraction independently.
- The first Effect emitter is the rich projection: it exposes decoded Effect-native values, preserves brands and schema transformations, performs runtime schema decoding, and delegates transport interpretation to `HttpApiClient`. Lighter wire-shaped Effect output remains possible through another emitter policy rather than constraining the shared IR.
- The rich Effect emitter regenerates private executable schemas when the **SDK Contract IR** proves that their transport semantics can be reproduced exactly. Contracts with authoritative custom transformations use the import-based Effect emitter against a Protocol-only client projection whose generated transport output is tested against Server's concrete API; the Promise emitter still derives zero-Effect structural wire types from the same IR.
- `@opencode-ai/protocol` owns Session endpoint construction and middleware placement. Server supplies concrete middleware keys to produce the authoritative build-time API; the client projection supplies transport-only keys without importing Core or Server at runtime.
- The first Promise emitter targets the same clean domain-oriented method organization rather than Hey API source compatibility. It returns unwrapped values directly, rejects declared and infrastructure failures, and begins with minimal client-level transport configuration; result wrappers, interceptors, and legacy generated signatures are outside the initial surface.
- The first Promise emitter parses response syntax and trusts its generated structural types; it does not perform runtime structural validation. Malformed payload syntax fails, while a syntactically valid shape mismatch is not detected at the SDK boundary. Standalone validator generation remains an optional future emitter policy.
- Declared Promise-client failures retain their tagged structural wire values and have generated type guards. Consumers do not depend on generated `Error` subclass identity, preserving discrimination across package copies and realms while remaining structurally aligned with Effect domain errors.
- Promise-client infrastructure failures use one generated `ClientError` class with a structured reason such as transport failure, unexpected status, unsupported content type, or malformed response. Promise methods reject with either a tagged declared domain failure or `ClientError`, matching the Effect client's conceptual domain/infrastructure error division.
- Promise methods accept a separate optional per-call transport-options argument containing `AbortSignal` and header overrides. Cancellation and transport metadata do not enter the domain input object; broader interceptor and response-mode APIs remain deferred.
- Promise streaming methods return a lazy `AsyncIterable` directly rather than a Promise-wrapped stream object. Iteration opens the connection, `AbortSignal` cancels it, and ending iteration closes the underlying request; the Effect emitter analogously returns `Stream` directly.
- Promise SSE connection establishment, declared HTTP failures, and infrastructure failures occur during `AsyncIterable` iteration, beginning with its first `next()` call, rather than during synchronous method construction.
- Neither generated streaming runtime automatically reconnects after disconnection. Promise `AsyncIterable` and Effect `Stream` fail explicitly; live consumers refresh and resubscribe, while durable sequence-based resume remains explicit composition above the generated client.
- Promise client construction is synchronous and network-free. It requires `baseUrl`, defaults to `globalThis.fetch`, accepts client-level headers, and merges them with per-call header overrides.
- Effect client construction accepts an explicit `baseUrl` and obtains `HttpClient.HttpClient` from the Effect environment. It does not install fetch or duplicate per-call transport policy; callers transform/provide the client for headers, tracing, retries, recording, and tests, while fiber interruption owns cancellation.
- Promise and Effect emitters each own their generated public type modules. The **SDK Contract IR**, not a physically shared generated type package, is the common source; this permits zero-Effect wire types and rich decoded Effect types to evolve independently.
- Promise and Effect network clients ship from `@opencode-ai/client` behind isolated root and `/effect` exports. The root has no runtime path to Effect; `/effect` imports only Effect, Schema, and Protocol.
- The Effect-native scoped host belongs to `@opencode-ai/sdk-next`, which will assume the existing `@opencode-ai/sdk` name after legacy consumers migrate. Client remains network-only and SDK depends one-way on Client.
- SDK executes Server's assembled `HttpRouter` in memory. It opens no listener and performs no network I/O, while preserving Server routing, middleware, codecs, handlers, and errors.
- The Effect Client and SDK re-export their decoded datatype facade from Schema so callers do not depend on internal package locations or Core's versioned names.
- A capability intended for both networked and **Embedded OpenCode** belongs in the authoritative public `HttpApi`; embedded-only same-process capabilities extend **Embedded OpenCode** separately.
- `sessions.log({ sessionID, after, follow })` is the public durable Session event stream. It verifies the Session, replays durable events after the optional aggregate sequence, optionally continues with newly committed durable events, excludes live-only fragments, and is transported as SSE in both networked and embedded modes.
- `events.subscribe()` is a distinct public instance-wide live stream for Session and non-Session activity. It has no replay guarantee and includes connection, heartbeat, and instance-disposal lifecycle events; consumers recover from disconnection by refreshing authoritative state.
- A Session ID is not an optional filter on `events.subscribe()`: instance-wide live events and durable Session events have different schemas, replay guarantees, cursors, lifecycle events, and failure behavior.
- The initial common OpenCode Client does not expose server-global event aggregation. `events.subscribe()` is bounded to the connected OpenCode instance or workspace; any future cross-instance administrative stream requires a separately designed API.
- `events.subscribe()` does not automatically reconnect after transport loss. The live-only stream fails with `ClientError`; consumers refresh authoritative state before explicitly opening a new subscription because events missed during disconnection cannot be replayed.
- `sessions.log({ sessionID, after, follow })` returns the generated HTTP client's cold durable event stream and does not build reconnection policy into the endpoint or client constructor. Transport loss fails the stream with `ClientError`. Callers may compose an explicit resuming stream above it by retaining the last observed durable sequence and opening a new subscription with `after`; any reusable resume helper remains a separate API design question.
- The stable `sessions.list(...)` design returns a **Page** in both networked and **Embedded OpenCode**; embedded execution does not define a separate unbounded array-returning list operation. The beta client currently preserves the existing HTTP `{ data, cursor }` envelope until emitter-level Page projection is implemented.
- Session list cursors are opaque branded values carrying continuation query and ordering state. Consumers pass them back unchanged and do not inspect storage anchors or encoded filter fields.
- A Session list continuation accepts only its opaque cursor. Scope, filters, ordering, and page size are fixed by the initial query and carried by that cursor.
- `sessions.messages(...)` returns a **Page** and uses the same cursor discipline as `sessions.list(...)`: the initial request supplies `sessionID`, ordering, and page size; continuation supplies `sessionID` plus only an opaque branded message cursor carrying ordering, page size, direction, and message anchor. Using a cursor with another Session is invalid.
- `sessions.message({ sessionID, messageID })` is a required resource lookup. An unknown Session fails with `SessionNotFoundError`; a known Session with an absent or differently owned message fails with `MessageNotFoundError` without disclosing cross-Session ownership. Absence is not represented as `undefined` across the public HTTP boundary.
- `sessions.interrupt({ sessionID })` first verifies that the durable Session exists, failing with `SessionNotFoundError` otherwise. For a known Session, interruption is idempotent: idle, already-settled, or locally unowned execution is a no-op.
- `sessions.active()` snapshots the current process's foreground Session drain registry as a record of Session IDs to `{ type: "running" }`. Missing IDs are inactive; background subagents and tasks do not make their parent Session active, and process restart clears the registry.
- `sessions.context({ sessionID })` preserves the existing message-only operation. It returns projected **Session History**; it does not include or represent the complete **Model Context**, whose agent system text, **Initial Instructions**, tools, and step-local additions remain separate.
- **Open question**: Should a future, separately named operation expose complete **Model Context**, including the instruction baseline, applied instruction metadata, tools, and step-local additions?
- `sessions.prompt(...)` exposes `resume?: boolean`. Omitting it preserves durable admission followed by an advisory execution wake; `resume: false` requests durable admit-only behavior.
- The public operation remains `sessions.prompt(...)`; `SessionPending.admit` is the internal primitive, while the public `Admission` result and `resume` option express its durable admission semantics.
- `sessions.create(...)` accepts an optional `location`. Omission resolves through the connected OpenCode instance's default or current location; an explicit value selects a known location. Networked and embedded transports use the same handler semantics.
- `sessions.switchAgent({ sessionID, agent })` is part of the common client alongside `sessions.switchModel(...)`. It affects subsequent Session activity and fails with `SessionNotFoundError` for an unknown Session.
- The **Embedded OpenCode** Layer delegates to the same scoped creation path; it does not define a second implementation.
- A **PTY Environment** adapter observes plugins in the request Location while passing the resolved PTY working directory to the hook; standalone servers use an empty adapter.
- An **Instruction Update** lowers to the provider's native chronological instruction role when supported and to a wrapped chronological fallback otherwise.
- When the aggregate discovered instruction set changes, its **Instruction Update** includes the complete current ordered set and supersedes the prior aggregate value; when no discovered instructions remain, the message states that previously loaded instructions no longer apply.
- Ambient project instruction discovery honors `OPENCODE_DISABLE_PROJECT_CONFIG`; global instructions remain eligible.
- Oversized textual **Model Tool Output** retains a bounded preview in Session history while its complete text moves to managed tool-output storage. Arbitrary structured-result size is a separate concern.
- One tool settlement receives one aggregate textual limit, using the configured maximum lines or UTF-8 bytes, whichever is reached first. The limit is provider-independent; token pressure belongs to context assembly and compaction.
- Generic truncation preserves the beginning and end of textual output. Tools may apply a more meaningful strategy before the Tool Registry enforces the final limit.
- A truncated **Model Tool Output** identifies its complete text in the bounded model-visible preview. The Tool Registry also supplies managed paths as internal metadata to tool hooks; Session events do not expose a typed `outputPaths` field.
- A **Managed Tool Output File** is temporary and may expire after its retention period. The bounded **Model Tool Output**, not the file, is the durable replayable record.
- Failure to retain a **Managed Tool Output File** fails settlement operationally. The Session never publishes a successful result whose complete output was lost during generic bounding.
- Once a tool operation succeeds, bounding its **Model Tool Output** and publishing its one durable settlement form an interruption-safe completion region. Raw oversized success is never published before a later correction.
- When a structured-only result would exceed the **Model Tool Output** limit, its validated structured value remains unchanged for Session consumers while model replay uses a bounded textual JSON preview and optional managed output path.
- Existing tool-managed output paths survive generic bounding. A fallback file retains exactly the complete projected text received by the Tool Registry and never claims to reconstruct output already discarded by tool-specific shaping.
- **Managed Tool Output Files** use globally unique names in one shared flat directory. They receive no special filesystem authority; each tool applies its ordinary external-path policy.
- Provider-executed tool results remain provider-native transcript facts outside generic Tool Registry bounding. Their context control requires provider-aware pruning or compaction because some providers require exact structured round-trip payloads.
## Client contract architecture
Semantic values that mean the same thing internally and publicly live in the lightweight Schema leaf. Core consumes Schema for domain behavior; Protocol composes Schema values into paths, payloads, envelopes, errors, cursors, and streams; Server imports both, hosts Protocol's exact groups, and owns protocol/domain adaptation. The root Promise client remains zero-Effect, `/effect` depends on Effect plus Schema and Protocol, and `@opencode-ai/sdk-next` composes the scoped in-process host above Client, Core, and Server.
Shared public records are plain objects declared with `Schema.Struct`. A same-name inferred interface gives object records readable TypeScript signatures without constructors, prototypes, or nominal identity; unions retain explicit type aliases.
Before stabilizing the client API:
- Keep additional public schemas in Schema and additional network groups in Protocol; neither package may transitively load databases, Drizzle, Session execution, providers, watchers, native modules, or WASM.
- Keep concrete Location middleware keys in Server while Protocol owns their placement. Client projections may supply transport-only keys, but must prove generated equivalence with Server's concrete API.
- Project the existing list response envelope to the stable client **Page** shape and enforce separate initial-query and cursor-continuation inputs without changing the hosted V2 wire contract.
- Settle the stable consumer namespace (`session` versus the current beta `sessions`) and use an explicit codegen annotation if the consumer name should differ from the server group identifier.
- Preserve V2 route paths, operation IDs, codecs, errors, middleware behavior, and OpenAPI output while making this change.
- Preserve browser-safe `@opencode-ai/client` and `@opencode-ai/client/effect` bundles through import-boundary tests.
- Define embedded-host placement before supporting multiple hosts over one database. Hosts that share durable Session storage must also share process-local Session execution coordination, or each host must receive isolated storage explicitly.
- Keep an embedded request scope alive until any streamed response body finishes. The initial non-streaming Session surface does not exercise this lifetime boundary; Session and instance event streams must do so before joining the embedded client.
## Example dialogue
> **Dev:** "The date changed while the session was active. Should the **Instruction Update** say what the old date was?"
> **Domain expert:** "No. Emit the newly effective date so the agent can act on the current instructions."
## Flagged ambiguities
- Legacy `experimental.chat.system.transform` can mutate assembled system text arbitrarily, but V2 plugins do not yet expose an equivalent hook. Decide separately whether to port it, model dynamic uses as explicit **Instruction Sources**, or narrow its semantics.
+2
View File
@@ -627,6 +627,7 @@ export class RunFooter implements FooterApi {
this.themes.splice(index, 1)
theme.block.syntax?.destroy()
theme.block.subtleSyntax?.destroy()
}
public close(): void {
@@ -1022,6 +1023,7 @@ export class RunFooter implements FooterApi {
void resolveRunTheme(this.renderer).then((theme) => {
if (this.isGone) {
theme.block.syntax?.destroy()
theme.block.subtleSyntax?.destroy()
return
}
+5 -1
View File
@@ -6,7 +6,11 @@ function syntax(style?: SyntaxStyle): SyntaxStyle {
return style ?? SyntaxStyle.fromTheme([])
}
export function entrySyntax(theme: RunTheme): SyntaxStyle {
export function entrySyntax(commit: StreamCommit, theme: RunTheme): SyntaxStyle {
if (commit.kind === "reasoning") {
return syntax(theme.block.subtleSyntax ?? theme.block.syntax)
}
return syntax(theme.block.syntax)
}
+3 -3
View File
@@ -143,7 +143,7 @@ export class RunScrollbackStream {
}
active.renderable.fg = entryColor(active.commit, theme)
active.renderable.syntaxStyle = entrySyntax(theme)
active.renderable.syntaxStyle = entrySyntax(active.commit, theme)
}
private createEntry(commit: StreamCommit, body: ActiveBody): ActiveEntry {
@@ -165,7 +165,7 @@ export class RunScrollbackStream {
? new CodeRenderable(surface.renderContext, {
content: "",
filetype: body.filetype,
syntaxStyle: entrySyntax(this.theme),
syntaxStyle: entrySyntax(commit, this.theme),
width: "100%",
wrapMode: "word",
drawUnstyledText: false,
@@ -175,7 +175,7 @@ export class RunScrollbackStream {
})
: new MarkdownRenderable(surface.renderContext, {
content: "",
syntaxStyle: entrySyntax(this.theme),
syntaxStyle: entrySyntax(commit, this.theme),
width: "100%",
streaming: true,
internalBlockMode: "top-level",
+1 -1
View File
@@ -84,7 +84,7 @@ export function RunEntryContent(props: {
const theme = createMemo(() => props.theme ?? RUN_THEME_FALLBACK)
const body = createMemo(() => props.body ?? entryBody(props.commit))
const style = createMemo(() => entryLook(props.commit, theme().entry))
const syntax = createMemo(() => entrySyntax(theme()))
const syntax = createMemo(() => entrySyntax(props.commit, theme()))
const color = createMemo(() => entryColor(props.commit, theme()))
const suppressBackgrounds = createMemo(() => props.opts?.suppressBackgrounds === true)
const diffBg = (color: ColorInput) => (suppressBackgrounds() ? transparent : color)
+44 -1
View File
@@ -47,6 +47,7 @@ export type RunBlockTheme = {
text: ColorInput
muted: ColorInput
syntax?: SyntaxStyle
subtleSyntax?: SyntaxStyle
diffAdded: ColorInput
diffRemoved: ColorInput
diffAddedBg: ColorInput
@@ -171,10 +172,42 @@ function tint(base: RGBA, overlay: RGBA, value: number): RGBA {
)
}
function blend(color: RGBA, bg: RGBA): RGBA {
if (color.a >= 1) {
return color
}
return RGBA.fromValues(
bg.r + (color.r - bg.r) * color.a,
bg.g + (color.g - bg.g) * color.a,
bg.b + (color.b - bg.b) * color.a,
1,
)
}
function chroma(color: RGBA) {
return Math.max(color.r, color.g, color.b) - Math.min(color.r, color.g, color.b)
}
function opaqueSyntaxStyle(style: SyntaxStyle | undefined, bg: RGBA): SyntaxStyle | undefined {
if (!style) {
return undefined
}
return SyntaxStyle.fromStyles(
Object.fromEntries(
[...style.getAllStyles()].map(([name, value]) => [
name,
{
...value,
fg: value.fg ? blend(value.fg, bg) : value.fg,
bg: value.bg ? blend(value.bg, bg) : value.bg,
},
]),
),
)
}
function indexedPalette(colors: TerminalColors, size: number = Math.max(colors.palette.length, 16)): RGBA[] {
return Array.from({ length: size }, (_, index) => {
const value = colors.palette[index]
@@ -469,7 +502,10 @@ function map(
scrollbackTheme: TuiThemeCurrent,
splash: RunSplashTheme,
syntax?: SyntaxStyle,
subtleSyntax?: SyntaxStyle,
): RunTheme {
const opaqueSubtleSyntax = opaqueSyntaxStyle(subtleSyntax, scrollbackTheme.background)
subtleSyntax?.destroy()
const footerBackground = alpha(footerTheme.background, 1)
const footerMode = mode(footerBackground)
const shade = fade(footerTheme.backgroundMenu, footerTheme.background, 0.12, 0.56, 0.72)
@@ -530,6 +566,7 @@ function map(
text: scrollbackTheme.text,
muted: scrollbackTheme.textMuted,
syntax,
subtleSyntax: opaqueSubtleSyntax,
diffAdded: scrollbackTheme.diffAdded,
diffRemoved: scrollbackTheme.diffRemoved,
diffAddedBg: transparent,
@@ -640,7 +677,13 @@ export async function resolveRunTheme(renderer: CliRenderer): Promise<RunTheme>
_hasSelectedListItemText: true,
}
const syntax = shared.generateSyntax(syntaxTheme)
return map(footerTheme, scrollbackTheme, splashTheme(scrollbackTheme, indexed), syntax)
return map(
footerTheme,
scrollbackTheme,
splashTheme(scrollbackTheme, indexed),
syntax,
shared.generateSubtleSyntax(syntaxTheme),
)
} catch {
return RUN_THEME_FALLBACK
}
+4 -23
View File
@@ -35,23 +35,9 @@ test("migrates tui and kv config into cli.json", async () => {
path.join(directory, "kv.json"),
JSON.stringify({
theme_mode_lock: "light",
attention_sound_pack: "custom.pack",
diff_wrap_mode: "none",
diff_viewer_show_file_tree: false,
diff_viewer_single_patch: true,
diff_viewer_view: "split",
terminal_title_enabled: false,
file_context_enabled: false,
paste_summary_enabled: false,
sidebar: "hide",
scrollbar_visible: true,
thinking_mode: "show",
exploration_grouping: false,
tips_hidden: true,
dismissed_getting_started: true,
animations_enabled: false,
skipped_version: "9.9.9",
which_key_layout: "overlay",
}),
)
@@ -70,17 +56,12 @@ test("migrates tui and kv config into cli.json", async () => {
plugins: [{ package: "example", options: { mode: "safe" } }, "-disabled"],
leader: { timeout: 500 },
scroll: { speed: 2, acceleration: true },
attention: { sound_pack: "custom.pack" },
diffs: { wrap: "none", tree: false, single: true, view: "split" },
terminal: { title: false },
prompt: { editor: false, paste: "full" },
session: { sidebar: "hide", scrollbar: true, thinking: "show", grouping: "none" },
hints: { tips: false, onboarding: false },
animations: false,
diffs: { view: "unified" },
prompt: { paste: "full" },
session: { grouping: "none" },
hints: { tips: false },
mouse: false,
})
expect(config).not.toHaveProperty("skipped_version")
expect(config).not.toHaveProperty("which_key")
expect((await Bun.file(path.join(directory, "cli.json")).json()).keybinds).toEqual({ leader: "ctrl+o" })
expect(await Bun.file(path.join(directory, "cli.json")).exists()).toBe(true)
expect(await Bun.file(path.join(directory, "tui.json")).exists()).toBe(true)
+1 -2
View File
@@ -543,8 +543,7 @@ const layer = Layer.effect(
needsContinuation = result.needsContinuation
step = result.step + 1
if (needsContinuation) {
yield* runPendingCompaction(input.sessionID)
promotion = "steer"
promotion = (yield* SessionPending.compaction(db, input.sessionID)) ? undefined : "steer"
continue
}
yield* runPendingCompaction(input.sessionID)
+5 -6
View File
@@ -2,6 +2,7 @@ export * as SessionRunnerModel from "./model"
import { makeLocationNode } from "../../effect/app-node"
import { Model } from "@opencode-ai/llm"
import { OpenAI } from "@opencode-ai/llm/providers"
// ast-grep-ignore: no-star-import
import * as AnthropicMessages from "@opencode-ai/llm/protocols/anthropic-messages"
// ast-grep-ignore: no-star-import
@@ -191,20 +192,18 @@ export const fromCatalogModel = (
const packageName = ProviderV2.packageName(resolved.package)
const key = apiKey(resolved, credential)
if (
OpenAICodex.isChatGPT(credential) &&
!ProviderV2.isAISDK(resolved.package) &&
isNativeOpenAI(resolved.package)
) {
if (OpenAICodex.isChatGPT(credential) && !ProviderV2.isAISDK(resolved.package) && isNativeOpenAI(resolved.package)) {
return Effect.succeed(codexModel(resolved, credential, key))
}
if (ProviderV2.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
if (OpenAICodex.isChatGPT(credential)) return Effect.succeed(codexModel(resolved, credential, key))
const id = resolved.modelID ?? resolved.id
return Effect.succeed(
withDefaults(resolved, OpenAIResponses.route)
.with(OpenAI.OpenAIProviderOptions.withOpenAIOptions(id, {}))
.with({ auth: key === undefined ? Auth.none : Auth.bearer(key) })
.model({ id: resolved.modelID ?? resolved.id }),
.model({ id }),
)
}
if (ProviderV2.isAISDK(resolved.package) && packageName === "@ai-sdk/anthropic") {
@@ -64,6 +64,20 @@ describe("SessionRunnerModel", () => {
}),
)
it.effect("requests OpenAI reasoning summaries for default reasoning models", () =>
Effect.gen(function* () {
const resolved = yield* SessionRunnerModel.fromCatalogModel(
model(ProviderV2.aisdk("@ai-sdk/openai"), {
modelID: "gpt-5.2",
settings: { baseURL: "https://openai.example/v1" },
}),
)
const prepared = yield* LLMClient.prepare(LLM.request({ model: resolved, prompt: "Hello" }))
expect(prepared.body).toMatchObject({ reasoning: { summary: "auto" } })
}),
)
it.effect("keeps catalog apiKey credentials out of provider JSON", () =>
Effect.gen(function* () {
const resolved = yield* SessionRunnerModel.fromCatalogModel(
+2 -2
View File
@@ -1614,14 +1614,14 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("runs one durable compaction barrier after tool settlement and before later inputs", () =>
it.effect("runs one durable compaction barrier before later steer and queued prompts", () =>
Effect.gen(function* () {
const session = yield* setup
currentModel = recoveryModel
streamGate = yield* Deferred.make<void>()
streamStarted = yield* Deferred.make<void>()
responses = [
reply.tool("call-active", "echo", { text: "active" }),
reply.text("Active complete", "text-active"),
[LLMEvent.textDelta({ id: "summary", text: "durable summary" })],
reply.text("Steer complete", "text-steer"),
reply.text("Queue complete", "text-queue"),
+5 -14
View File
@@ -1,21 +1,12 @@
---
title: "SDK"
description: "Embed OpenCode directly in your application."
description: "Embed an OpenCode host in an Effect application."
---
We're working on a general-purpose SDK for embedding OpenCode directly inside
your application. The regular SDK is coming soon.
An Effect-native version is available now for applications built with Effect.
Its current documentation is below. For other applications, run OpenCode as a
server and use the [TypeScript client](/build/client) in the meantime.
## Effect
`@opencode-ai/sdk-next` hosts OpenCode in-process. Unlike the
[network client](/build/client), it assembles the OpenCode server and routes API
calls through its HTTP router in memory. It opens no HTTP listener and adds no
network hop between the client and server.
`@opencode-ai/sdk-next` is the Effect-native SDK for applications that need to
host OpenCode in-process. Unlike the [network client](/build/client), it assembles the
OpenCode server and routes API calls through its HTTP router in memory. It opens
no HTTP listener and adds no network hop between the client and server.
<Warning>
The V2 SDK is beta and currently private to the OpenCode workspace. It is not
+1
View File
@@ -7,6 +7,7 @@ import * as OpenAIResponses from "../protocols/openai-responses"
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
export type { OpenAIOptionsInput, OpenAIResponseIncludable } from "./openai-options"
export * as OpenAIProviderOptions from "./openai-options"
export const id = ProviderID.make("openai")
@@ -136,14 +136,14 @@ test("theme swaps restyle active reasoning without resetting the stream", async
...RUN_THEME_FALLBACK,
block: {
...RUN_THEME_FALLBACK.block,
syntax: previousSyntax,
subtleSyntax: previousSyntax,
},
}
const next = {
...RUN_THEME_FALLBACK,
block: {
...RUN_THEME_FALLBACK.block,
syntax: nextSyntax,
subtleSyntax: nextSyntax,
},
}
const out = await setup({ theme: previous, onThemeRelease: (theme) => released.push(theme) })
@@ -67,7 +67,9 @@ test("returns syntax styles and indexed splash colors", async () => {
try {
expect(theme.block.syntax).toBeDefined()
expect(theme.block.subtleSyntax).toBeDefined()
expect([...theme.block.syntax!.getAllStyles()].length).toBeGreaterThan(0)
expect([...theme.block.subtleSyntax!.getAllStyles()].length).toBeGreaterThan(0)
expectIndexed(theme.splash.left)
expectIndexed(theme.splash.right)
expectIndexed(theme.splash.leftShadow)
@@ -80,6 +82,7 @@ test("returns syntax styles and indexed splash colors", async () => {
expect(expectRgba(theme.footer.statusAccent).toInts()).not.toEqual(expectRgba(theme.footer.status).toInts())
} finally {
theme.block.syntax?.destroy()
theme.block.subtleSyntax?.destroy()
}
})
@@ -100,6 +103,7 @@ test("keeps footer surfaces exact while scrollback stays palette matched", async
expectIndexed(theme.block.warning)
} finally {
theme.block.syntax?.destroy()
theme.block.subtleSyntax?.destroy()
}
})
@@ -115,7 +119,9 @@ test("uses refreshed background brightness when cached renderer mode is stale",
expect(expectRgba(stale.footer.surface).toInts()).toEqual(expectRgba(light.footer.surface).toInts())
} finally {
stale.block.syntax?.destroy()
stale.block.subtleSyntax?.destroy()
light.block.syntax?.destroy()
light.block.subtleSyntax?.destroy()
}
})
@@ -132,7 +138,9 @@ test("keeps renderer mode when refreshed default background is unavailable", asy
expect(expectRgba(light.footer.surface).toInts()).not.toEqual(expectRgba(dark.footer.surface).toInts())
} finally {
light.block.syntax?.destroy()
light.block.subtleSyntax?.destroy()
dark.block.syntax?.destroy()
dark.block.subtleSyntax?.destroy()
}
})
-3
View File
@@ -358,7 +358,6 @@ export type TuiTheme = {
readonly ready: boolean
}
/** @deprecated Persistent TUI KV storage is not supported in V2. */
export type TuiKV = {
get: <Value = unknown>(key: string, fallback?: Value) => Value
set: (key: string, value: unknown) => void
@@ -435,7 +434,6 @@ type TuiConfigView = {
sidebar?: "auto" | "hide"
scrollbar?: boolean
thinking?: "show" | "hide"
markdown?: "source" | "rendered"
grouping?: "auto" | "none"
}
hints?: { tips?: boolean; onboarding?: boolean }
@@ -630,7 +628,6 @@ export type TuiPluginApi = {
dialog: TuiDialogStack
}
readonly tuiConfig: Frozen<TuiConfigView>
/** @deprecated Persistent TUI KV storage is not supported in V2. */
kv: TuiKV
state: TuiState
theme: TuiTheme
+2
View File
@@ -19,10 +19,12 @@
"./context/args": "./src/context/args.tsx",
"./context/epilogue": "./src/context/epilogue.tsx",
"./context/exit": "./src/context/exit.tsx",
"./context/kv": "./src/context/kv.tsx",
"./context/log": "./src/context/log.tsx",
"./context/project": "./src/context/project.tsx",
"./context/runtime": "./src/context/runtime.tsx",
"./context/sdk": "./src/context/sdk.tsx",
"./context/sync": "./src/context/sync.tsx",
"./context/theme": "./src/context/theme.tsx",
"./context/editor": "./src/context/editor.ts",
"./context/clipboard": "./src/context/clipboard.tsx",
+115 -101
View File
@@ -44,6 +44,7 @@ import { useEvent } from "./context/event"
import { SDKProvider, useSDK } from "./context/sdk"
import { StartupLoading } from "./component/startup-loading"
import { Reconnecting } from "./component/reconnecting"
import { SyncProvider, useSync } from "./context/sync"
import { DataProvider, useData } from "./context/data"
import { LocationProvider } from "./context/location"
import { LocalProvider, useLocal } from "./context/local"
@@ -70,6 +71,7 @@ import { DialogAlert } from "./ui/dialog-alert"
import { DialogConfirm } from "./ui/dialog-confirm"
import { ToastProvider, useToast } from "./ui/toast"
import { isDefaultTitle } from "./util/session"
import { KVProvider, useKV } from "./context/kv"
import * as Model from "./util/model"
import { ArgsProvider, useArgs, type Args } from "./context/args"
import open from "open"
@@ -179,6 +181,23 @@ function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error)
}
function isVersionGreater(left: string, right: string) {
const parse = (value: string) => {
const [core, prerelease] = value.replace(/^v/, "").split("-", 2)
return { core: core.split(".").map((part) => Number.parseInt(part, 10) || 0), prerelease }
}
const a = parse(left)
const b = parse(right)
for (let index = 0; index < Math.max(a.core.length, b.core.length); index++) {
const difference = (a.core[index] ?? 0) - (b.core[index] ?? 0)
if (difference) return difference > 0
}
if (a.prerelease === b.prerelease) return false
if (!a.prerelease) return true
if (!b.prerelease) return false
return a.prerelease.localeCompare(b.prerelease, undefined, { numeric: true }) > 0
}
export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
const log = input.log ?? (() => {})
const global = yield* Global.Service
@@ -324,63 +343,67 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
service={input.config}
options={{ terminalSuspend: process.platform !== "win32" }}
>
<ToastProvider>
<RouteProvider
initialRoute={
input.args.continue
? {
type: "session",
sessionID: "dummy",
}
: undefined
}
>
<PluginRuntimeProvider value={pluginRuntime}>
<SDKProvider
client={createOpencodeClient({ ...options, directory })}
api={api}
reconnect={reconnect}
reload={input.server.reload}
>
<PermissionProvider>
<ProjectProvider>
<DataProvider>
<ThemeProvider mode={mode}>
<LocalProvider>
<PromptStashProvider>
<DialogProvider>
<FrecencyProvider>
<PromptHistoryProvider>
<PromptRefProvider>
<EditorContextProvider>
<LocationProvider>
<App
pluginHost={input.pluginHost}
pair={
input.server.endpoint.auth
? input.server.endpoint.auth
: {
username: "opencode",
password: "",
}
}
/>
</LocationProvider>
</EditorContextProvider>
</PromptRefProvider>
</PromptHistoryProvider>
</FrecencyProvider>
</DialogProvider>
</PromptStashProvider>
</LocalProvider>
</ThemeProvider>
</DataProvider>
</ProjectProvider>
</PermissionProvider>
</SDKProvider>
</PluginRuntimeProvider>
</RouteProvider>
</ToastProvider>
<KVProvider>
<ToastProvider>
<RouteProvider
initialRoute={
input.args.continue
? {
type: "session",
sessionID: "dummy",
}
: undefined
}
>
<PluginRuntimeProvider value={pluginRuntime}>
<SDKProvider
client={createOpencodeClient({ ...options, directory })}
api={api}
reconnect={reconnect}
reload={input.server.reload}
>
<PermissionProvider>
<ProjectProvider>
<SyncProvider>
<DataProvider>
<ThemeProvider mode={mode}>
<LocalProvider>
<PromptStashProvider>
<DialogProvider>
<FrecencyProvider>
<PromptHistoryProvider>
<PromptRefProvider>
<EditorContextProvider>
<LocationProvider>
<App
pluginHost={input.pluginHost}
pair={
input.server.endpoint.auth
? input.server.endpoint.auth
: {
username: "opencode",
password: "",
}
}
/>
</LocationProvider>
</EditorContextProvider>
</PromptRefProvider>
</PromptHistoryProvider>
</FrecencyProvider>
</DialogProvider>
</PromptStashProvider>
</LocalProvider>
</ThemeProvider>
</DataProvider>
</SyncProvider>
</ProjectProvider>
</PermissionProvider>
</SDKProvider>
</PluginRuntimeProvider>
</RouteProvider>
</ToastProvider>
</KVProvider>
</ConfigProvider>
</ArgsProvider>
</OpencodeKeymapProvider>
@@ -417,16 +440,17 @@ function App(props: {
}) {
const log = useLog({ component: "app" })
const startup = useTuiStartup()
const configState = useConfig()
const config = configState.data
const config = useConfig().data
const route = useRoute()
const dimensions = useTerminalDimensions()
const renderer = useRenderer()
const dialog = useDialog()
const local = useLocal()
const kv = useKV()
const keymap = useOpencodeKeymap()
const event = useEvent()
const sdk = useSDK()
const sync = useSync()
const toast = useToast()
const themeState = useTheme()
const { theme, mode, setMode, locked, lock, unlock } = themeState
@@ -435,7 +459,7 @@ function App(props: {
const exit = useExit()
const promptRef = usePromptRef()
const pluginRuntime = usePluginRuntime()
const attention = createTuiAttention({ renderer, config, update: configState.update })
const attention = createTuiAttention({ renderer, config, kv })
const clipboard = useClipboard()
// Toast once when an MCP server enters a failed or needs-auth state so the user knows to act,
@@ -472,11 +496,12 @@ function App(props: {
tuiConfig: config,
dialog,
keymap,
kv,
route,
routes: pluginRuntime.routes,
event,
sdk,
project,
sync,
data,
theme: themeState,
toast,
@@ -524,8 +549,8 @@ function App(props: {
renderer.clearSelection()
}
const terminalTitleEnabled = () => config.terminal?.title ?? true
const pasteSummaryEnabled = () => config.prompt?.paste !== "full"
const [terminalTitleEnabled, setTerminalTitleEnabled] = kv.signal("terminal_title_enabled", true)
const [pasteSummaryEnabled, setPasteSummaryEnabled] = kv.signal("paste_summary_enabled", true)
createEffect(() => {
renderer.useMouse = !Flag.OPENCODE_DISABLE_MOUSE && config.mouse
@@ -855,7 +880,6 @@ function App(props: {
{
name: "theme.switch_mode",
title: mode() === "dark" ? "Switch to light mode" : "Switch to dark mode",
hidden: true,
run: () => {
setMode(mode() === "dark" ? "light" : "dark")
dialog.clear()
@@ -865,7 +889,6 @@ function App(props: {
{
name: "theme.mode.lock",
title: locked() ? "Unlock theme mode" : "Lock theme mode",
hidden: true,
run: () => {
if (locked()) unlock()
else lock()
@@ -933,57 +956,41 @@ function App(props: {
name: "terminal.title.toggle",
title: terminalTitleEnabled() ? "Disable terminal title" : "Enable terminal title",
category: "System",
hidden: true,
run: () => {
const next = !terminalTitleEnabled()
if (!next) renderer.setTerminalTitle("")
void configState
.update((draft) => {
draft.terminal = { ...draft.terminal, title: next }
})
.catch(toast.error)
setTerminalTitleEnabled((prev) => {
const next = !prev
kv.set("terminal_title_enabled", next)
if (!next) renderer.setTerminalTitle("")
return next
})
dialog.clear()
},
},
{
name: "app.toggle.animations",
title: (config.animations ?? true) ? "Disable animations" : "Enable animations",
title: kv.get("animations_enabled", true) ? "Disable animations" : "Enable animations",
category: "System",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.animations = !(config.animations ?? true)
})
.catch(toast.error)
kv.set("animations_enabled", !kv.get("animations_enabled", true))
dialog.clear()
},
},
{
name: "app.toggle.file_context",
title: (config.prompt?.editor ?? true) ? "Disable file context" : "Enable file context",
title: kv.get("file_context_enabled", true) ? "Disable file context" : "Enable file context",
category: "System",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.prompt = { ...draft.prompt, editor: !(config.prompt?.editor ?? true) }
})
.catch(toast.error)
kv.set("file_context_enabled", !kv.get("file_context_enabled", true))
dialog.clear()
},
},
{
name: "app.toggle.diffwrap",
title: (config.diffs?.wrap ?? "word") === "word" ? "Disable diff wrapping" : "Enable diff wrapping",
title: kv.get("diff_wrap_mode", "word") === "word" ? "Disable diff wrapping" : "Enable diff wrapping",
category: "System",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.diffs = { ...draft.diffs, wrap: (config.diffs?.wrap ?? "word") === "word" ? "none" : "word" }
})
.catch(toast.error)
const current = kv.get("diff_wrap_mode", "word")
kv.set("diff_wrap_mode", current === "word" ? "none" : "word")
dialog.clear()
},
},
@@ -991,13 +998,12 @@ function App(props: {
name: "app.toggle.paste_summary",
title: pasteSummaryEnabled() ? "Disable paste summary" : "Enable paste summary",
category: "System",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.prompt = { ...draft.prompt, paste: pasteSummaryEnabled() ? "full" : "compact" }
})
.catch(toast.error)
setPasteSummaryEnabled((prev) => {
const next = !prev
kv.set("paste_summary_enabled", next)
return next
})
dialog.clear()
},
},
@@ -1095,13 +1101,21 @@ function App(props: {
event.on("installation.update-available", async (evt) => {
const version = evt.data.version
const skipped = kv.get("skipped_version")
if (skipped && !isVersionGreater(version, skipped)) return
const choice = await DialogConfirm.show(
dialog,
`Update Available`,
`A new release v${version} is available. Would you like to update now?`,
"later",
"skip",
)
if (choice === false) {
kv.set("skipped_version", version)
return
}
if (choice !== true) return
toast.show({
+5 -10
View File
@@ -38,8 +38,9 @@ type TuiAttentionHost = TuiAttention & {
dispose(): void
}
const DEFAULT_TITLE = "OpenCode"
const DEFAULT_TITLE = "opencode"
const DEFAULT_PACK_ID = "opencode.default"
const KV_SOUND_PACK = "attention_sound_pack"
const TITLE_LIMIT = 80
const MESSAGE_LIMIT = 240
const BUILTIN_PACK: RegisteredSoundPack = {
@@ -113,8 +114,6 @@ function focusSkip(when: TuiAttentionWhen, focus: FocusState) {
export function createTuiAttention(input: {
renderer: AttentionRenderer
config: Pick<Config.Resolved, "attention">
update?: Config.Interface["update"]
/** @deprecated Ignored. Sound-pack persistence uses CLI config. */
kv?: TuiKV
audio?: Pick<typeof TuiAudio, "loadSoundFile" | "play">
}): TuiAttentionHost {
@@ -135,7 +134,8 @@ export function createTuiAttention(input: {
input.renderer.on("blur", onBlur)
function configuredPackID() {
return activePackID ?? input.config.attention.sound_pack
const stored = input.kv?.get<string | undefined>(KV_SOUND_PACK, undefined)
return activePackID ?? stored ?? input.config.attention.sound_pack
}
function currentPack() {
@@ -234,12 +234,7 @@ export function createTuiAttention(input: {
const pack = packs.get(id)
if (!pack) return false
activePackID = pack.id
if (options?.persist)
void input
.update?.((draft) => {
draft.attention = { ...draft.attention, sound_pack: pack.id }
})
.catch(() => {})
if (options?.persist) input.kv?.set(KV_SOUND_PACK, pack.id)
return true
},
current() {
+159 -37
View File
@@ -1,12 +1,17 @@
import { createMemo, createSignal } from "solid-js"
import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core"
import { useTerminalDimensions } from "@opentui/solid"
import { createMemo, createSignal, For, onMount, Show } from "solid-js"
import { useConfig } from "../config"
import { useTheme } from "../context/theme"
import { DialogSelect } from "../ui/dialog-select"
import { useBindings } from "../keymap"
import { useDialog } from "../ui/dialog"
import { useToast } from "../ui/toast"
type Setting = {
title: string
category: string
description: string
detail?: string
path: string[]
default: unknown
values?: readonly unknown[]
@@ -21,12 +26,18 @@ const settings: Setting[] = [
{
title: "Theme",
category: "Appearance",
description: "Interface color theme",
detail:
"Choose the color theme used throughout OpenCode. Custom themes discovered from your config directory appear here alongside the built-in themes.",
path: ["theme", "name"],
default: "opencode",
},
{
title: "Color mode",
category: "Appearance",
description: "Terminal color preference",
detail:
"Choose how OpenCode selects its colors. System follows your terminal preference, while dark and light keep the interface in a fixed mode.",
path: ["theme", "mode"],
default: "system",
values: ["system", "dark", "light"],
@@ -34,6 +45,7 @@ const settings: Setting[] = [
{
title: "Animations",
category: "Appearance",
description: "Interface motion",
path: ["animations"],
default: true,
values: [false, true],
@@ -42,6 +54,7 @@ const settings: Setting[] = [
{
title: "Tips",
category: "Appearance",
description: "Home screen hints",
path: ["hints", "tips"],
default: true,
values: [false, true],
@@ -50,6 +63,7 @@ const settings: Setting[] = [
{
title: "Onboarding",
category: "Appearance",
description: "Getting-started guidance",
path: ["hints", "onboarding"],
default: true,
values: [false, true],
@@ -58,6 +72,7 @@ const settings: Setting[] = [
{
title: "Sidebar",
category: "Session",
description: "Session sidebar visibility",
path: ["session", "sidebar"],
default: "auto",
values: ["hide", "auto"],
@@ -65,6 +80,7 @@ const settings: Setting[] = [
{
title: "Scrollbar",
category: "Session",
description: "Transcript scrollbar",
path: ["session", "scrollbar"],
default: false,
values: [false, true],
@@ -73,20 +89,15 @@ const settings: Setting[] = [
{
title: "Thinking",
category: "Session",
description: "Model reasoning by default",
path: ["session", "thinking"],
default: "hide",
values: ["hide", "show"],
},
{
title: "Markdown",
category: "Session",
path: ["session", "markdown"],
default: "rendered",
values: ["source", "rendered"],
},
{
title: "Grouping",
category: "Session",
description: "Related transcript items",
path: ["session", "grouping"],
default: "auto",
values: ["none", "auto"],
@@ -94,6 +105,7 @@ const settings: Setting[] = [
{
title: "Layout",
category: "Diffs",
description: "Diff presentation",
path: ["diffs", "view"],
default: "auto",
values: ["auto", "split", "unified"],
@@ -101,6 +113,7 @@ const settings: Setting[] = [
{
title: "Wrapping",
category: "Diffs",
description: "Long diff lines",
path: ["diffs", "wrap"],
default: "word",
values: ["none", "word"],
@@ -108,6 +121,7 @@ const settings: Setting[] = [
{
title: "File tree",
category: "Diffs",
description: "Diff file navigation",
path: ["diffs", "tree"],
default: true,
values: [false, true],
@@ -116,6 +130,7 @@ const settings: Setting[] = [
{
title: "Single patch",
category: "Diffs",
description: "Only the selected patch",
path: ["diffs", "single"],
default: false,
values: [false, true],
@@ -124,6 +139,7 @@ const settings: Setting[] = [
{
title: "Scroll speed",
category: "Input",
description: "Distance per input tick",
path: ["scroll", "speed"],
default: 3,
step: 0.25,
@@ -134,6 +150,7 @@ const settings: Setting[] = [
{
title: "Acceleration",
category: "Input",
description: "Repeated scrolling",
path: ["scroll", "acceleration"],
default: false,
values: [false, true],
@@ -142,6 +159,7 @@ const settings: Setting[] = [
{
title: "Mouse",
category: "Input",
description: "Terminal mouse capture",
path: ["mouse"],
default: true,
values: [false, true],
@@ -150,6 +168,7 @@ const settings: Setting[] = [
{
title: "Editor context",
category: "Input",
description: "Active selection in prompts",
path: ["prompt", "editor"],
default: true,
values: [false, true],
@@ -158,6 +177,7 @@ const settings: Setting[] = [
{
title: "Large pastes",
category: "Input",
description: "Paste display style",
path: ["prompt", "paste"],
default: "compact",
values: ["compact", "full"],
@@ -165,6 +185,7 @@ const settings: Setting[] = [
{
title: "Leader timeout",
category: "Input",
description: "Wait after leader key",
path: ["leader", "timeout"],
default: 2000,
step: 250,
@@ -175,6 +196,7 @@ const settings: Setting[] = [
{
title: "Attention",
category: "Alerts",
description: "Alerts when input is needed",
path: ["attention", "enabled"],
default: false,
values: [false, true],
@@ -183,6 +205,7 @@ const settings: Setting[] = [
{
title: "Notifications",
category: "Alerts",
description: "System notifications",
path: ["attention", "notifications"],
default: true,
values: [false, true],
@@ -191,6 +214,7 @@ const settings: Setting[] = [
{
title: "Sounds",
category: "Alerts",
description: "Attention sounds",
path: ["attention", "sound"],
default: true,
values: [false, true],
@@ -199,6 +223,7 @@ const settings: Setting[] = [
{
title: "Volume",
category: "Alerts",
description: "Attention sound level",
path: ["attention", "volume"],
default: 0.4,
step: 0.1,
@@ -209,6 +234,7 @@ const settings: Setting[] = [
{
title: "Window title",
category: "Terminal",
description: "Update terminal title",
path: ["terminal", "title"],
default: true,
values: [false, true],
@@ -218,10 +244,18 @@ const settings: Setting[] = [
export function DialogConfig() {
const config = useConfig()
const dialog = useDialog()
const toast = useToast()
const themeState = useTheme()
const { theme } = themeState
const dimensions = useTerminalDimensions()
const [selected, setSelected] = createSignal(0)
const [saving, setSaving] = createSignal(false)
let scroll: ScrollBoxRenderable | undefined
onMount(() => {
dialog.setSize("xlarge")
dialog.setCentered(true)
})
const value = (setting: Setting) => {
const current = setting.path.reduce<unknown>((result, key) => {
@@ -241,18 +275,34 @@ export function DialogConfig() {
const index = setting.values?.indexOf(current)
return index === undefined || index < 0 ? String(current) : (setting.labels?.[index] ?? String(current))
}
const options = createMemo(() =>
const rows = createMemo(() =>
settings.map((setting, index) => ({
title: setting.title,
category: setting.category,
footer: display(setting),
value: index,
setting,
index,
heading: index === 0 || settings[index - 1].category !== setting.category,
})),
)
const split = createMemo(() => dimensions().width >= 110)
const height = createMemo(() => Math.max(8, Math.min(36, dimensions().height - 12)))
async function change(direction: number, index = selected()) {
function move(direction: number) {
const next = (selected() + direction + settings.length) % settings.length
setSelected(next)
queueMicrotask(() => {
if (!scroll) return
const row =
next +
settings.slice(0, next + 1).filter((setting, index) => {
return index === 0 || settings[index - 1].category !== setting.category
}).length
if (row < scroll.scrollTop) scroll.scrollTo(row)
if (row >= scroll.scrollTop + scroll.viewport.height) scroll.scrollTo(row - scroll.viewport.height + 1)
})
}
async function change(direction: number) {
if (saving()) return
const setting = settings[index]
const setting = settings[selected()]
const current = value(setting)
const choices = values(setting)
const next = choices
@@ -272,27 +322,99 @@ export function DialogConfig() {
.finally(() => setSaving(false))
}
useBindings(() => ({
bindings: [
{
key: "up",
desc: "Previous setting",
group: "Settings",
cmd: () => move(-1),
},
{
key: "down",
desc: "Next setting",
group: "Settings",
cmd: () => move(1),
},
{ key: "left", desc: "Previous value", group: "Settings", cmd: () => void change(-1) },
{ key: "right", desc: "Next value", group: "Settings", cmd: () => void change(1) },
{ key: "return", desc: "Next value", group: "Settings", cmd: () => void change(1) },
],
}))
return (
<DialogSelect
title="Settings"
options={options()}
onMove={(option) => setSelected(option.value)}
onSelect={(option) => void change(1, option.value)}
footerHints={[{ title: "←/→", label: "change" }]}
bindings={[
{
key: "left",
desc: "Previous value",
group: "Settings",
cmd: () => void change(-1),
},
{
key: "right",
desc: "Next value",
group: "Settings",
cmd: () => void change(1),
},
]}
/>
<box flexDirection="row" height={height() + 1}>
<box width={split() ? "54%" : "100%"} paddingLeft={4} paddingRight={split() ? 3 : 4} paddingBottom={1}>
<text fg={theme.text} attributes={TextAttributes.BOLD} paddingBottom={1}>
Settings
</text>
<scrollbox
ref={(element: ScrollBoxRenderable) => (scroll = element)}
flexGrow={1}
scrollbarOptions={{ visible: false }}
>
<For each={rows()}>
{(row) => (
<>
<Show when={row.heading}>
<box paddingTop={row.index === 0 ? 0 : 1}>
<text fg={theme.primary} attributes={TextAttributes.BOLD}>
{row.setting.category}
</text>
</box>
</Show>
<box flexDirection="row" height={1}>
<text
width={25}
fg={row.index === selected() ? theme.text : theme.textMuted}
attributes={row.index === selected() ? TextAttributes.BOLD : undefined}
>
{row.setting.title}
</text>
<box flexGrow={1} flexDirection="row" justifyContent="flex-end">
<box flexDirection="row">
<text fg={theme.textMuted}>{row.index === selected() ? " " : " "}</text>
<text
fg={row.index === selected() ? theme.primary : theme.textMuted}
attributes={row.index === selected() ? TextAttributes.BOLD : undefined}
>
{display(row.setting)}
</text>
<text fg={theme.textMuted}>{row.index === selected() ? " " : " "}</text>
</box>
</box>
</box>
</>
)}
</For>
</scrollbox>
</box>
<Show when={split()}>
<box
position="relative"
top={-1}
width="46%"
height={height() + 2}
paddingTop={1}
paddingLeft={2}
paddingRight={2}
backgroundColor={theme.backgroundElement}
>
<box flexDirection="row" justifyContent="space-between">
<text fg={theme.primary} attributes={TextAttributes.BOLD}>
{settings[selected()].title}
</text>
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
esc
</text>
</box>
<box paddingTop={1}>
<text fg={theme.text} wrapMode="word">
{settings[selected()].detail ?? settings[selected()].description}
</text>
</box>
</box>
</Show>
</box>
)
}
@@ -132,7 +132,6 @@ export function DialogModel(props: { providerID?: string }) {
{
command: "model.dialog.provider",
title: connected() ? "Connect integration" : "View all integrations",
selection: "none",
onTrigger() {
dialog.replace(() => (
<DialogIntegration
@@ -155,7 +154,6 @@ export function DialogModel(props: { providerID?: string }) {
skipFilter={true}
title={title()}
current={local.model.current()}
focusCurrent={false}
/>
)
}
@@ -345,7 +345,6 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
{
command: "dialog.move_session.new",
title: "new",
selection: "none",
onTrigger: () => void create(),
},
{
@@ -361,7 +360,6 @@ export function DialogMoveSession(props: DialogMoveSessionProps) {
{
command: "dialog.move_session.refresh",
title: "refresh",
selection: "none",
onTrigger: () => void refetch(),
},
]
@@ -108,7 +108,7 @@ export function ErrorComponent(props: { error: Error; reset: () => void; mode?:
{/* Headline */}
<box flexDirection="column" alignItems="center" flexShrink={0}>
<text attributes={TextAttributes.BOLD} fg={colors.text}>
OpenCode crashed
opencode crashed
</text>
<Show when={showSubtext()}>
<text fg={colors.muted}>An unexpected error stopped the session.</text>
@@ -192,7 +192,7 @@ export function ErrorComponent(props: { error: Error; reset: () => void; mode?:
? "Report copied — paste it into a new GitHub issue."
: "Copy the report and open a GitHub issue to help us fix this."}
</text>
<text fg={colors.muted}>OpenCode {InstallationVersion}</text>
<text fg={colors.muted}>opencode {InstallationVersion}</text>
</box>
</Show>
</box>
@@ -211,7 +211,7 @@ function buildIssueURL(message: string, stack: string) {
url.searchParams.set("terminal", describeTerminal())
url.searchParams.set(
"reproduce",
"Reported automatically from the OpenCode crash screen. If you can, describe what you were doing when it crashed.",
"Reported automatically from the opencode crash screen. If you can, describe what you were doing when it crashed.",
)
// Budget the stack against the fully URL-encoded length (not the raw length) so
@@ -220,7 +220,7 @@ function buildIssueURL(message: string, stack: string) {
// so measuring url.toString() is both correct and safe on any input.
const MAX_URL_LENGTH = 6000
const marker = "\n... (truncated)"
const head = `The OpenCode TUI crashed with an unexpected error.\n\n**Error:** ${message}\n\n**Stack trace:**\n`
const head = `The opencode TUI crashed with an unexpected error.\n\n**Error:** ${message}\n\n**Stack trace:**\n`
const setBody = (body: string) => url.searchParams.set("description", head + "```\n" + body + "\n```")
setBody(stack)
+17 -40
View File
@@ -43,6 +43,7 @@ import { useDialog } from "../../ui/dialog"
import { DialogIntegration } from "../dialog-integration"
import { useConnected } from "../use-connected"
import { useToast } from "../../ui/toast"
import { useKV } from "../../context/kv"
import { createFadeIn } from "../../util/signal"
import { DialogSkill } from "../dialog-skill"
import { useArgs } from "../../context/args"
@@ -53,7 +54,6 @@ import { readLocalAttachment } from "./local-attachment"
import { useData } from "../../context/data"
import { useLocation } from "../../context/location"
import { contextUsage } from "../../util/session"
import { SessionMessage } from "@opencode-ai/core/session/message"
registerOpencodeSpinner()
@@ -177,10 +177,11 @@ export function Prompt(props: PromptProps) {
const exit = useExit()
const dimensions = useTerminalDimensions()
const { theme, syntax } = useTheme()
const animationsEnabled = createMemo(() => config.animations ?? true)
const kv = useKV()
const animationsEnabled = createMemo(() => kv.get("animations_enabled", true))
const list = createMemo(() => props.placeholders?.normal ?? [])
const shell = createMemo(() => props.placeholders?.shell ?? [])
const fileContextEnabled = createMemo(() => config.prompt?.editor ?? true)
const fileContextEnabled = createMemo(() => kv.get("file_context_enabled", true))
const [dismissedEditorSelectionKey, setDismissedEditorSelectionKey] = createSignal<string>()
const editorContext = createMemo(() => {
const selection = fileContextEnabled() ? editor.selection() : undefined
@@ -1004,10 +1005,8 @@ export function Prompt(props: PromptProps) {
// Capture mode before it gets reset
const currentMode = store.mode
const submittedPrompt = structuredClone(unwrap(store.prompt))
const editorSelection = editorContext()
const pendingEditorSelection = editorSelection && editor.labelState() === "pending" ? editorSelection : undefined
let cleared = false
if (store.mode === "shell") {
move.startSubmit()
@@ -1100,53 +1099,31 @@ export function Prompt(props: PromptProps) {
return false
}
}
const messageID = SessionMessage.ID.create()
data.session.message.optimistic.add(sessionID, {
id: messageID,
type: "user",
text: inputText,
time: { created: Date.now() },
})
history.append({
...submittedPrompt,
mode: currentMode,
})
input.extmarks.clear()
setStore("prompt", emptyPrompt())
setStore("extmarkToPart", new Map())
props.onSubmit?.()
input.clear()
cleared = true
const error = await sdk.api.session
.prompt({
sessionID,
id: messageID,
text: inputText,
files: submittedPrompt.files,
agents: submittedPrompt.agents,
files: store.prompt.files,
agents: store.prompt.agents,
})
.then(
() => undefined,
(error) => error,
)
if (error) {
data.session.message.optimistic.remove(sessionID, messageID)
toast.show({ title: "Failed to send prompt", message: errorMessage(error), variant: "error" })
return false
}
if (pendingEditorSelection) editor.markSelectionSent()
}
if (!cleared) {
history.append({
...submittedPrompt,
mode: currentMode,
})
input.extmarks.clear()
setStore("prompt", emptyPrompt())
setStore("extmarkToPart", new Map())
props.onSubmit?.()
}
history.append({
...store.prompt,
mode: currentMode,
})
input.extmarks.clear()
setStore("prompt", emptyPrompt())
setStore("extmarkToPart", new Map())
props.onSubmit?.()
// temporary hack to make sure the message is sent
if (!props.sessionID) {
@@ -1158,7 +1135,7 @@ export function Prompt(props: PromptProps) {
})
}, 50)
}
if (!cleared) input.clear()
input.clear()
if (finishMoveProgress) move.finishSubmit()
return true
}
@@ -1214,7 +1191,7 @@ export function Prompt(props: PromptProps) {
const lineCount = (pastedContent.match(/\n/g)?.length ?? 0) + 1
if (
(lineCount >= 3 || pastedContent.length > 150) &&
config.prompt?.paste !== "full"
kv.get("paste_summary_enabled", true)
) {
pasteText(pastedContent, `[Pasted ~${lineCount} lines]`)
return
@@ -1518,7 +1495,7 @@ export function Prompt(props: PromptProps) {
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show when={config.animations ?? true} fallback={<text fg={theme.textMuted}>[]</text>}>
<Show when={kv.get("animations_enabled", true)} fallback={<text fg={theme.textMuted}>[]</text>}>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
+3 -3
View File
@@ -1,6 +1,6 @@
import { Show } from "solid-js"
import { useTheme } from "../context/theme"
import { useConfig } from "../config"
import { useKV } from "../context/kv"
import type { JSX } from "@opentui/solid"
import type { RGBA } from "@opentui/core"
import { registerOpencodeSpinner } from "./register-spinner"
@@ -11,10 +11,10 @@ export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦",
export function Spinner(props: { children?: JSX.Element; color?: RGBA }) {
const { theme } = useTheme()
const config = useConfig().data
const kv = useKV()
const color = () => props.color ?? theme.textMuted
return (
<Show when={config.animations ?? true} fallback={<text fg={color()}> {props.children}</text>}>
<Show when={kv.get("animations_enabled", true)} fallback={<text fg={color()}> {props.children}</text>}>
<box flexDirection="row" gap={1}>
<spinner frames={SPINNER_FRAMES} interval={80} color={color()} />
<Show when={props.children}>
-3
View File
@@ -118,9 +118,6 @@ export const Info = Schema.Struct({
grouping: Schema.optional(Schema.Literals(["auto", "none"])).annotate({
description: "Group related transcript items automatically or render each item separately",
}),
markdown: Schema.optional(Schema.Literals(["source", "rendered"])).annotate({
description: "Show Markdown syntax markers or conceal them in rendered transcript content",
}),
}),
).annotate({ description: "Session transcript presentation settings" }),
hints: Schema.optional(
+5 -27
View File
@@ -384,7 +384,9 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
event.data.inputID,
])
message.update(event.data.sessionID, (draft, index) => {
const item: SessionMessageInfo =
message.append(
draft,
index,
event.data.input.type === "user"
? {
id: event.data.inputID,
@@ -397,10 +399,8 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
type: "synthetic",
...event.data.input.data,
time: { created: event.created },
}
const position = index.get(event.data.inputID)
if (position === undefined) return message.append(draft, index, item)
draft[position] = item
},
)
})
break
case "session.instructions.updated":
@@ -928,28 +928,6 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
const position = messageIndex.get(sessionID)?.get(messageID)
return position === undefined ? undefined : messages?.[position]
},
optimistic: {
add(sessionID: string, item: Extract<SessionMessageInfo, { type: "user" }>) {
if (!store.session.input[sessionID]?.includes(item.id))
setStore("session", "input", sessionID, [...(store.session.input[sessionID] ?? []), item.id])
message.update(sessionID, (draft, index) => message.append(draft, index, item))
},
remove(sessionID: string, messageID: string) {
setStore(
"session",
"input",
sessionID,
(store.session.input[sessionID] ?? []).filter((id) => id !== messageID),
)
message.update(sessionID, (draft, index) => {
const position = index.get(messageID)
if (position === undefined) return
draft.splice(position, 1)
index.clear()
draft.forEach((item, itemIndex) => index.set(item.id, itemIndex))
})
},
},
async refresh(sessionID: string) {
const messages = (await sdk.api.message.list({ sessionID, limit: 200, order: "desc" })).data.toReversed()
messageIndex.set(sessionID, new Map(messages.map((message, index) => [message.id, index])))
+107
View File
@@ -0,0 +1,107 @@
import { createEffect, createSignal, type Setter } from "solid-js"
import { createStore, unwrap } from "solid-js/store"
import { createSimpleContext } from "./helper"
import { Flock } from "@opencode-ai/core/util/flock"
import { Global } from "@opencode-ai/core/global"
import { readJson, writeJsonAtomic } from "../util/persistence"
import { useTuiPaths } from "./runtime"
import path from "path"
import { useConfigOptional, type Config } from "../config"
export const { use: useKV, provider: KVProvider } = createSimpleContext({
name: "KV",
init: (props: { config?: Config.Info }) => {
const config = props.config ?? useConfigOptional()?.data
const paths = useTuiPaths()
void Global.Path.state
const file = path.join(paths.state, "kv.json")
const lock = `tui-kv:${file}`
const [ready, setReady] = createSignal(false)
const [store, setStore] = createStore<Record<string, any>>()
// Queue same-process writes so rapid updates persist in order.
let write = Promise.resolve()
Flock.withLock(lock, () => readJson<Record<string, unknown>>(file))
.then((x) => {
const values: Record<string, any> = { ...x }
Object.entries(configValues(config ?? {})).forEach(([key, value]) => {
if (value === undefined) delete values[key]
else values[key] = value
})
setStore(values)
})
.catch((error) => {
console.error("Failed to read KV state", { error })
})
.finally(() => {
setReady(true)
})
createEffect(() => {
if (!ready() || !config) return
Object.entries(configValues(config)).forEach(([key, value]) => {
if (value === undefined) setStore(key, undefined)
else setStore(key, value)
})
})
const result = {
get ready() {
return ready()
},
get store() {
return store
},
signal<T>(name: string, defaultValue: T) {
if (store[name] === undefined) setStore(name, defaultValue)
return [
function () {
return result.get(name)
},
function setter(next: Setter<T>) {
result.set(name, next)
},
] as const
},
get(key: string, defaultValue?: any) {
return store[key] ?? defaultValue
},
set(key: string, value: any) {
setStore(key, value)
const snapshot = structuredClone(unwrap(store))
write = write
.then(() => Flock.withLock(lock, () => writeJsonAtomic(file, snapshot)))
.catch((error) => {
console.error("Failed to write KV state", { error })
})
},
}
return result
},
})
function configValues(config: Config.Info) {
const values: Record<string, any> = {}
if (config.theme?.name !== undefined) values.theme = config.theme.name
if (config.theme?.mode !== undefined) {
values.theme_mode_lock = config.theme.mode === "system" ? undefined : config.theme.mode
values.theme_mode = undefined
}
if (config.attention?.sound_pack !== undefined) values.attention_sound_pack = config.attention.sound_pack
if (config.diffs?.wrap !== undefined) values.diff_wrap_mode = config.diffs.wrap
if (config.diffs?.tree !== undefined) values.diff_viewer_show_file_tree = config.diffs.tree
if (config.diffs?.single !== undefined) values.diff_viewer_single_patch = config.diffs.single
if (config.diffs?.view !== undefined)
values.diff_viewer_view = config.diffs.view === "auto" ? undefined : config.diffs.view
if (config.terminal?.title !== undefined) values.terminal_title_enabled = config.terminal.title
if (config.prompt?.editor !== undefined) values.file_context_enabled = config.prompt.editor
if (config.prompt?.paste !== undefined) values.paste_summary_enabled = config.prompt.paste === "compact"
if (config.session?.sidebar !== undefined) values.sidebar = config.session.sidebar
if (config.session?.scrollbar !== undefined) values.scrollbar_visible = config.session.scrollbar
if (config.session?.thinking !== undefined) values.thinking_mode = config.session.thinking
if (config.session?.grouping !== undefined) values.exploration_grouping = config.session.grouping === "auto"
if (config.hints?.tips !== undefined) values.tips_hidden = !config.hints.tips
if (config.hints?.onboarding !== undefined) values.dismissed_getting_started = !config.hints.onboarding
if (config.animations !== undefined) values.animations_enabled = config.animations
return values
}
+94
View File
@@ -0,0 +1,94 @@
import type {
Agent,
Command,
Config,
FormatterStatus,
LspStatus,
McpResource,
McpStatus,
Message,
Part,
PermissionRequest,
Provider,
QuestionRequest,
Session,
FileDiffInfo,
VcsInfo,
} from "@opencode-ai/sdk/v2"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "./helper"
import { useProject } from "./project"
export const {
context: SyncContext,
use: useSync,
provider: SyncProvider,
} = createSimpleContext({
name: "Sync",
init: () => {
const project = useProject()
const [store, setStore] = createStore<{
status: "loading" | "partial" | "complete"
provider: Provider[]
agent: Agent[]
command: Command[]
permission: Record<string, PermissionRequest[]>
question: Record<string, QuestionRequest[]>
config: Config
session: Session[]
session_diff: Record<string, FileDiffInfo[]>
message: Record<string, Message[]>
part: Record<string, Part[]>
lsp: LspStatus[]
mcp: Record<string, McpStatus>
mcp_resource: Record<string, McpResource>
formatter: FormatterStatus[]
vcs: VcsInfo | undefined
}>({
status: "complete",
provider: [],
agent: [],
command: [],
permission: {},
question: {},
config: {},
session: [],
session_diff: {},
message: {},
part: {},
lsp: [],
mcp: {},
mcp_resource: {},
formatter: [],
vcs: undefined,
})
return {
data: store,
set: setStore,
get status() {
return store.status
},
get ready() {
return true
},
get path() {
return project.instance.path()
},
session: {
get(_sessionID: string) {
return undefined as Session | undefined
},
query() {
return {} as { scope?: "project"; path?: string }
},
async refresh() {},
status(_sessionID: string) {
return "idle" as const
},
async sync(_sessionID: string) {},
},
async bootstrap(_input: { fatal?: boolean } = {}) {},
}
},
})
+27 -25
View File
@@ -4,6 +4,7 @@ import {
DEFAULT_THEMES,
addTheme,
allThemes,
generateSubtleSyntax,
generateSyntax,
generateSystem,
hasTheme,
@@ -21,6 +22,7 @@ import {
import { createEffect, createMemo, onCleanup, onMount } from "solid-js"
import { createStore, produce } from "solid-js/store"
import { createSimpleContext } from "./helper"
import { useKV } from "./kv"
import { useConfig } from "../config"
import { Global } from "@opencode-ai/core/global"
import { Glob } from "@opencode-ai/core/util/glob"
@@ -62,6 +64,7 @@ export {
DEFAULT_THEMES,
addTheme,
allThemes,
generateSubtleSyntax,
generateSyntax,
generateSystem,
hasTheme,
@@ -73,6 +76,7 @@ export {
upsertTheme,
type Theme,
type ThemeJson,
type SyntaxStyleOverrides,
} from "../theme"
const THEME_REFRESH_DELAYS = [250, 1000] as const
@@ -99,8 +103,8 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
name: "Theme",
init: (props: { mode: "dark" | "light"; source?: ThemeSource }) => {
const renderer = useRenderer()
const configState = useConfig()
const config = configState.data
const config = useConfig().data
const kv = useKV()
const themes = props.source ?? themeSource
const pick = (value: unknown) => {
if (value === "dark" || value === "light") return value
@@ -109,11 +113,12 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
setStore(
produce((draft) => {
const lock = pick(config.theme?.mode)
const lock = pick(kv.get("theme_mode_lock"))
const mode = lock ?? pick(renderer.themeMode) ?? props.mode
if (!lock && pick(kv.get("theme_mode")) !== undefined) kv.set("theme_mode", undefined)
draft.mode = mode
draft.lock = lock
const active = config.theme?.name ?? "opencode"
const active = config.theme?.name ?? kv.get("theme", "opencode")
draft.active = typeof active === "string" ? active : "opencode"
draft.ready = false
}),
@@ -127,10 +132,10 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
createEffect(() => {
const mode = config.theme?.mode
if (mode === "dark" || mode === "light") {
pin(mode, false)
pin(mode)
return
}
if (mode === "system" && store.lock !== undefined) free(false)
if (mode === "system" && store.lock !== undefined) free()
})
function syncCustomThemes() {
@@ -204,31 +209,23 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
}
function apply(mode: "dark" | "light") {
if (store.lock !== undefined) kv.set("theme_mode", mode)
if (store.mode === mode) return
setStore("mode", mode)
refreshSystemTheme(mode)
}
function pin(mode: "dark" | "light" = store.mode, persist = true) {
function pin(mode: "dark" | "light" = store.mode) {
setStore("lock", mode)
kv.set("theme_mode_lock", mode)
apply(mode)
if (!persist) return
void configState
.update((draft) => {
draft.theme = { ...draft.theme, mode }
})
.catch(() => {})
}
function free(persist = true) {
function free() {
setStore("lock", undefined)
kv.set("theme_mode_lock", undefined)
kv.set("theme_mode", undefined)
refreshSystemTheme(renderer.themeMode ?? store.mode)
if (!persist) return
void configState
.update((draft) => {
draft.theme = { ...draft.theme, mode: "system" }
})
.catch(() => {})
}
const handle = (mode: "dark" | "light") => {
@@ -268,12 +265,20 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
const values = createMemo(() => {
const active = store.themes[store.active]
if (active) return resolveTheme(active, store.mode)
const saved = kv.get("theme")
if (typeof saved === "string") {
const theme = store.themes[saved]
if (theme) return resolveTheme(theme, store.mode)
}
return resolveTheme(store.themes.opencode, store.mode)
})
createEffect(() => renderer.setBackgroundColor(values().background))
const syntax = createSyntaxStyleMemo(() => generateSyntax(values()))
const subtleSyntax = createSyntaxStyleMemo(() => generateSubtleSyntax(values()))
return {
theme: new Proxy(values(), {
@@ -288,6 +293,7 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
all: allThemes,
has: hasTheme,
syntax,
subtleSyntax,
mode: () => store.mode,
locked: () => store.lock !== undefined,
lock: () => pin(store.mode),
@@ -296,11 +302,7 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
set(theme: string) {
if (!hasTheme(theme)) return false
setStore("active", theme)
void configState
.update((draft) => {
draft.theme = { ...draft.theme, name: theme }
})
.catch(() => {})
kv.set("theme", theme)
return true
},
get ready() {
+47
View File
@@ -1,3 +1,6 @@
import { createMemo, type Setter } from "solid-js"
import { useKV } from "./kv"
export type ThinkingMode = "show" | "hide"
const MODES: readonly ThinkingMode[] = ["show", "hide"] as const
@@ -13,8 +16,52 @@ export function reasoningSummary(text: string) {
return { title: match[1].trim(), body: content.slice(match[0].length).trimEnd() }
}
export function isThinkingMode(value: unknown): value is ThinkingMode {
return typeof value === "string" && (MODES as readonly string[]).includes(value)
}
// Cycle order matches the slash command: show → hide → show.
export function nextThinkingMode(current: ThinkingMode): ThinkingMode {
const idx = MODES.indexOf(current)
return MODES[(idx + 1) % MODES.length] ?? "show"
}
export function useThinkingMode() {
const kv = useKV()
// Capture pre-state before `kv.signal` seeds a default, so we can detect
// first-time users with a legacy `thinking_visibility` boolean and migrate.
// The KVProvider only renders children once kv.ready, so reads here are safe.
const hadStored = kv.get("thinking_mode") !== undefined
const legacy = kv.get("thinking_visibility")
const [stored, setStored] = kv.signal<ThinkingMode>("thinking_mode", "hide")
// The kv signal exposes its setter typed as `Setter<T>` which carries Solid's
// overload set; passing an updater fn through a property access loses the
// bivariance trick the existing `setX((prev) => ...)` callsites rely on.
// Wrap it in a sane shape so consumers can just call `set(next)` or pass
// an updater.
const set = (next: ThinkingMode | ((prev: ThinkingMode) => ThinkingMode)) => {
if (typeof next === "function") setStored(next as Setter<ThinkingMode>)
else setStored(() => next)
}
// Preserve previous experience for users who had explicitly toggled the
// legacy `thinking_visibility` boolean. First-time users (no legacy key)
// get the new "hide" default (collapsed thinking).
if (!hadStored) {
if (legacy === true) set("show")
else if (legacy === false) set("hide")
}
if ((stored() as string) === "minimal") set("hide")
const mode = createMemo<ThinkingMode>(() => {
const value = stored()
return isThinkingMode(value) ? value : "hide"
})
return {
mode,
set,
}
}
+2 -10
View File
@@ -5,12 +5,10 @@ import { Tips } from "./tips-view"
import { useBindings } from "../../keymap"
import { useData } from "../../context/data"
import { hasConnectedProvider } from "../../util/connected-provider"
import { useConfig } from "../../config"
const id = "internal:home-tips"
function View(props: { api: TuiPluginApi; hidden: boolean; show: boolean; connected: boolean }) {
const config = useConfig()
useBindings(() => ({
commands: [
{
@@ -18,13 +16,8 @@ function View(props: { api: TuiPluginApi; hidden: boolean; show: boolean; connec
title: props.hidden ? "Show tips" : "Hide tips",
category: "System",
namespace: "palette",
hidden: true,
run() {
void config
.update((draft) => {
draft.hints = { ...draft.hints, tips: props.hidden }
})
.catch(() => {})
props.api.kv.set("tips_hidden", !props.api.kv.get("tips_hidden", false))
props.api.ui.dialog.clear()
},
},
@@ -47,8 +40,7 @@ const tui: TuiPlugin = async (api) => {
slots: {
home_bottom() {
const data = useData()
const config = useConfig().data
const hidden = createMemo(() => !(config.hints?.tips ?? true))
const hidden = createMemo(() => api.kv.get("tips_hidden", false))
const first = createMemo(() => api.state.session.count() === 0)
const connected = createMemo(() => hasConnectedProvider(data.location.integration.list() ?? []))
const show = createMemo(() => (!first() || !connected()) && !hidden())
@@ -4,20 +4,18 @@ import { createMemo, Show } from "solid-js"
import { abbreviateHome } from "../../runtime"
import { useTuiPaths } from "../../context/runtime"
import { FilePath } from "../../ui/file-path"
import { useConfig } from "../../config"
const id = "internal:sidebar-footer"
function View(props: { api: TuiPluginApi; directory: string }) {
const paths = useTuiPaths()
const config = useConfig()
const theme = () => props.api.theme.current
const has = createMemo(() =>
props.api.state.provider.some(
(item) => item.id !== "opencode" || Object.values(item.models).some((model) => model.cost?.input !== 0),
),
)
const done = createMemo(() => !(config.data.hints?.onboarding ?? true))
const done = createMemo(() => props.api.kv.get("dismissed_getting_started", false))
const show = createMemo(() => !has() && !done())
const location = createMemo(() => {
const branch = props.directory === props.api.state.path.directory ? props.api.state.vcs?.branch : undefined
@@ -46,16 +44,7 @@ function View(props: { api: TuiPluginApi; directory: string }) {
<text fg={theme().text}>
<b>Getting started</b>
</text>
<text
fg={theme().textMuted}
onMouseDown={() =>
void config
.update((draft) => {
draft.hints = { ...draft.hints, onboarding: false }
})
.catch(() => {})
}
>
<text fg={theme().textMuted} onMouseDown={() => props.api.kv.set("dismissed_getting_started", true)}>
</text>
</box>
@@ -19,7 +19,6 @@ import { DiffViewerFileTree } from "./diff-viewer-file-tree"
import { Panel, PanelGroup, Separator } from "./diff-viewer-ui"
import { DialogSelect } from "../../ui/dialog-select"
import { getScrollAcceleration } from "../../util/scroll"
import { useConfig } from "../../config"
import {
allExpandedFileTreeDirectories,
buildFileTree,
@@ -42,6 +41,9 @@ const MIN_SPLIT_WIDTH = 100
const FILE_TREE_WIDTH = 32
const PLAIN_TEXT_FILETYPE = "opencode-plain-text"
const VCS_DIFF_CONTEXT_LINES = 12
const KV_SHOW_FILE_TREE = "diff_viewer_show_file_tree"
const KV_SINGLE_PATCH = "diff_viewer_single_patch"
const KV_VIEW = "diff_viewer_view"
type DiffMode = "working" | "branch" | "last-turn"
type DiffViewerFocus = "patches" | "files"
type DiffView = "split" | "unified"
@@ -90,7 +92,6 @@ function diffSourceLabel(mode: DiffMode) {
function DiffViewer(props: { api: TuiPluginApi }) {
const dimensions = useTerminalDimensions()
const sdk = useSDK()
const config = useConfig()
const themeState = useTheme()
const theme = () => props.api.theme.current
const params = () =>
@@ -134,9 +135,11 @@ function DiffViewer(props: { api: TuiPluginApi }) {
})
const files = createMemo(() => diff() ?? [])
const [focus, setFocus] = createSignal<DiffViewerFocus>("patches")
const [fileTreeEnabled, setFileTreeEnabled] = createSignal(config.data.diffs?.tree ?? true)
const [fileTreeEnabled, setFileTreeEnabled] = createSignal(
props.api.kv.get<boolean>(KV_SHOW_FILE_TREE, true) !== false,
)
const showFileTree = createMemo(() => showDiffViewerFileTree(fileTreeEnabled(), files().length))
const [singlePatch, setSinglePatch] = createSignal(config.data.diffs?.single ?? false)
const [singlePatch, setSinglePatch] = createSignal(props.api.kv.get<boolean>(KV_SINGLE_PATCH, false) === true)
const patchPaneWidth = createMemo(() => dimensions().width - (showFileTree() ? 33 : 0) - 4)
const patchLeftBorder = createMemo<BorderSides[]>(() => (showFileTree() ? ["left"] : []))
const splitAvailable = createMemo(() => patchPaneWidth() >= MIN_SPLIT_WIDTH)
@@ -145,7 +148,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
if (props.api.tuiConfig.diffs?.view === "split") return "split"
return splitAvailable() ? "split" : "unified"
})
const [viewOverride, setViewOverride] = createSignal<DiffView | undefined>(storedView(config.data.diffs?.view))
const [viewOverride, setViewOverride] = createSignal<DiffView | undefined>(storedView(props.api.kv.get(KV_VIEW)))
const view = createMemo(() => (splitAvailable() ? (viewOverride() ?? defaultView()) : "unified"))
const fileTree = createMemo(() => buildFileTree(files()))
const [expandedFileNodes, setExpandedFileNodes] = createSignal<ReadonlySet<number>>(new Set())
@@ -620,33 +623,23 @@ function DiffViewer(props: { api: TuiPluginApi }) {
name: "diff.toggle_file_tree",
title: "Toggle diff viewer file tree",
category: "VCS",
hidden: true,
run() {
const next = !fileTreeEnabled()
if (!next) setFocus("patches")
setFileTreeEnabled(next)
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, tree: next }
})
.catch(() => {})
props.api.kv.set(KV_SHOW_FILE_TREE, next)
},
},
{
name: "diff.single_patch",
title: "Toggle single patch view",
category: "VCS",
hidden: true,
run() {
setSelectedHunk(undefined)
if (!singlePatch()) {
ensureHighlightedPatchFile()
setSinglePatch(true)
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, single: true }
})
.catch(() => {})
props.api.kv.set(KV_SINGLE_PATCH, true)
scrollSinglePatchToTop()
return
}
@@ -660,11 +653,7 @@ function DiffViewer(props: { api: TuiPluginApi }) {
)
if (fileIndex !== undefined) selectPatchFile(fileIndex)
setSinglePatch(false)
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, single: false }
})
.catch(() => {})
props.api.kv.set(KV_SINGLE_PATCH, false)
if (fileIndex !== undefined) scrollToPatchFileIndexAfterRender(fileIndex)
},
},
@@ -680,17 +669,12 @@ function DiffViewer(props: { api: TuiPluginApi }) {
name: "diff.toggle_view",
title: "Toggle diff viewer split or unified view",
category: "VCS",
hidden: true,
run() {
if (!splitAvailable()) return
setSelectedHunk(undefined)
const next = view() === "split" ? "unified" : "split"
setViewOverride(next)
void config
.update((draft) => {
draft.diffs = { ...draft.diffs, view: next }
})
.catch(() => {})
props.api.kv.set(KV_VIEW, next)
},
},
{
@@ -217,7 +217,6 @@ function View(props: { api: TuiPluginApi }) {
{
title: "install",
command: "dialog.plugins.install",
selection: "none",
hidden: lock(),
onTrigger: () => {
showInstall(props.api)
@@ -22,6 +22,8 @@ const command = {
} as const
const LAYER_PRIORITY = 900
const KV_LAYOUT = "which_key_layout"
const KV_PENDING_PREVIEW = "which_key_pending_preview"
const toggleCommands = [command.toggle, command.toggleLayout, command.togglePending] as const
const scrollCommands = [
command.scrollUp,
@@ -529,8 +531,8 @@ function WhichKeyPanel(props: {
const tui: TuiPlugin = async (api) => {
const [pinned, setPinned] = createSignal(false)
const [mode, setMode] = createSignal(layout("dock"))
const [pendingPreview, setPendingPreview] = createSignal(false)
const [mode, setMode] = createSignal(layout(api.kv.get(KV_LAYOUT, "dock")))
const [pendingPreview, setPendingPreview] = createSignal(api.kv.get(KV_PENDING_PREVIEW, false))
api.keymap.registerLayer({
priority: LAYER_PRIORITY,
@@ -552,6 +554,7 @@ const tui: TuiPlugin = async (api) => {
run() {
setMode((value) => {
const next = value === "dock" ? "overlay" : "dock"
api.kv.set(KV_LAYOUT, next)
return next
})
},
@@ -563,6 +566,7 @@ const tui: TuiPlugin = async (api) => {
category: "System",
run() {
setPendingPreview((value) => {
api.kv.set(KV_PENDING_PREVIEW, !value)
return !value
})
},
+37 -26
View File
@@ -3,11 +3,12 @@ import type { Config } from "../config"
import type { useEvent } from "../context/event"
import type { useRoute } from "../context/route"
import type { useSDK } from "../context/sdk"
import type { useSync } from "../context/sync"
import type { useData } from "../context/data"
import type { useProject } from "../context/project"
import type { useTheme } from "../context/theme"
import { Dialog as DialogUI, type useDialog } from "../ui/dialog"
import type { useOpencodeKeymap } from "../keymap"
import type { useKV } from "../context/kv"
import { DialogAlert } from "../ui/dialog-alert"
import { DialogConfirm } from "../ui/dialog-confirm"
import { DialogPrompt } from "../ui/dialog-prompt"
@@ -25,11 +26,12 @@ type Input = {
tuiConfig: Config.Resolved
dialog: ReturnType<typeof useDialog>
keymap: ReturnType<typeof useOpencodeKeymap>
kv: ReturnType<typeof useKV>
route: ReturnType<typeof useRoute>
routes: PluginRoutes
event: ReturnType<typeof useEvent>
sdk: ReturnType<typeof useSDK>
project: ReturnType<typeof useProject>
sync: ReturnType<typeof useSync>
data: ReturnType<typeof useData>
theme: ReturnType<typeof useTheme>
toast: ReturnType<typeof useToast>
@@ -95,51 +97,57 @@ function mapOptionCb<Value>(cb?: (item: TuiDialogSelectOption<Value>) => void) {
return (item: SelectOption<Value>) => cb(pickOption(item))
}
function stateApi(project: ReturnType<typeof useProject>, data: ReturnType<typeof useData>): TuiPluginApi["state"] {
function stateApi(sync: ReturnType<typeof useSync>, data: ReturnType<typeof useData>): TuiPluginApi["state"] {
return {
get ready() {
return true
},
get config() {
return {}
return sync.data.config
},
get provider() {
return []
return sync.data.provider
},
get path() {
return project.instance.path()
return sync.path
},
get vcs() {
return undefined
if (!sync.data.vcs) return
return {
branch: sync.data.vcs.branch,
default_branch: sync.data.vcs.default_branch,
}
},
session: {
count() {
return data.session.list().length
},
get(_sessionID) {
return undefined
get(sessionID) {
return sync.session.get(sessionID)
},
diff(_sessionID) {
return []
diff(sessionID) {
return (sync.data.session_diff[sessionID] ?? []).flatMap((item) =>
item.file === undefined ? [] : [{ ...item, file: item.file }],
)
},
messages(_sessionID) {
return []
messages(sessionID) {
return sync.data.message[sessionID] ?? []
},
status(sessionID) {
return data.session.status(sessionID) === "running" ? { type: "busy" } : { type: "idle" }
},
permission(_sessionID) {
return []
permission(sessionID) {
return sync.data.permission[sessionID] ?? []
},
question(_sessionID) {
return []
question(sessionID) {
return sync.data.question[sessionID] ?? []
},
},
part(_messageID) {
return []
part(messageID) {
return sync.data.part[messageID] ?? []
},
lsp() {
return []
return sync.data.lsp.map((item) => ({ id: item.id, root: item.root, status: item.status }))
},
mcp() {
return (data.location.mcp.server.list() ?? [])
@@ -284,14 +292,17 @@ export function createTuiApiAdapters(input: Input): Omit<TuiPluginApi, "lifecycl
return input.tuiConfig
},
kv: {
get(_key, fallback) {
if (fallback === undefined) throw new Error("Persistent TUI KV storage is not supported")
return fallback
get(key, fallback) {
return input.kv.get(key, fallback)
},
set(key, value) {
input.kv.set(key, value)
},
get ready() {
return input.kv.ready
},
set() {},
ready: true,
},
state: stateApi(input.project, input.data),
state: stateApi(input.sync, input.data),
get client() {
return input.sdk.client
},
+33 -40
View File
@@ -23,7 +23,7 @@ import { useData } from "../../context/data"
import { SplitBorder } from "../../ui/border"
import { useTuiPaths, useTuiTerminalEnvironment } from "../../context/runtime"
import { Spinner, SPINNER_FRAMES } from "../../component/spinner"
import { useTheme } from "../../context/theme"
import { createSyntaxStyleMemo, generateSubtleSyntax, useTheme } from "../../context/theme"
import { BoxRenderable, ScrollBoxRenderable, addDefaultParsers, TextAttributes, RGBA } from "@opentui/core"
import { Prompt, type PromptRef } from "../../component/prompt"
import type {
@@ -54,6 +54,7 @@ import { filetype } from "../../util/filetype"
import parsers from "../../parsers-config"
import { errorMessage } from "../../util/error"
import { Toast, useToast } from "../../ui/toast"
import { useKV } from "../../context/kv.tsx"
import stripAnsi from "strip-ansi"
import { usePromptRef } from "../../context/prompt"
import { useEpilogue } from "../../context/epilogue"
@@ -65,7 +66,7 @@ import { DialogExportResult } from "../../ui/dialog-export-result"
import { sessionEpilogue } from "../../util/presentation"
import { useConfig } from "../../config"
import { useClipboard } from "../../context/clipboard"
import { nextThinkingMode, reasoningSummary, type ThinkingMode } from "../../context/thinking"
import { nextThinkingMode, reasoningSummary, useThinkingMode, type ThinkingMode } from "../../context/thinking"
import { getScrollAcceleration } from "../../util/scroll"
import { collapseToolOutput } from "../../util/collapse-tool-output"
import { usePluginRuntime } from "../../plugin/runtime"
@@ -121,7 +122,6 @@ const context = createContext<{
sessionID: string
thinkingMode: () => ThinkingMode
showThinking: () => boolean
markdownMode: () => "source" | "rendered"
groupExploration: () => boolean
diffWrapMode: () => "word" | "none"
models: () => ModelInfo[]
@@ -147,8 +147,8 @@ export function Session() {
const data = useData()
const project = useProject()
const paths = useTuiPaths()
const configState = useConfig()
const config = configState.data
const config = useConfig().data
const kv = useKV()
const { theme } = useTheme()
const promptRef = usePromptRef()
const session = createMemo(() => data.session.get(route.sessionID))
@@ -194,14 +194,15 @@ export function Session() {
})
const dimensions = useTerminalDimensions()
const sidebar = createMemo(() => config.session?.sidebar ?? "auto")
const [sidebar, setSidebar] = kv.signal<"auto" | "hide">("sidebar", "auto")
const [sidebarOpen, setSidebarOpen] = createSignal(false)
const thinkingMode = createMemo<ThinkingMode>(() => config.session?.thinking ?? "hide")
const thinking = useThinkingMode()
const thinkingMode = thinking.mode
const showThinking = createMemo(() => true)
const showScrollbar = createMemo(() => config.session?.scrollbar ?? false)
const markdownMode = createMemo(() => config.session?.markdown ?? "rendered")
const diffWrapMode = createMemo(() => config.diffs?.wrap ?? "word")
const groupExploration = createMemo(() => config.session?.grouping !== "none")
const [showScrollbar, setShowScrollbar] = kv.signal("scrollbar_visible", false)
const [diffWrapMode] = kv.signal<"word" | "none">("diff_wrap_mode", "word")
const [_animationsEnabled, _setAnimationsEnabled] = kv.signal("animations_enabled", true)
const [groupExploration, setGroupExploration] = kv.signal("exploration_grouping", true)
const wide = createMemo(() => dimensions().width > 120)
const sidebarVisible = createMemo(() => {
@@ -461,11 +462,7 @@ export function Session() {
run: () => {
batch(() => {
const isVisible = sidebarVisible()
void configState
.update((draft) => {
draft.session = { ...draft.session, sidebar: isVisible ? "hide" : "auto" }
})
.catch(toast.error)
setSidebar(() => (isVisible ? "hide" : "auto"))
setSidebarOpen(!isVisible)
})
dialog.clear()
@@ -479,17 +476,12 @@ export function Session() {
})(),
value: "session.toggle.thinking",
category: "Session",
hidden: true,
slash: {
name: "thinking",
aliases: ["toggle-thinking"],
},
run: () => {
void configState
.update((draft) => {
draft.session = { ...draft.session, thinking: nextThinkingMode(thinkingMode()) }
})
.catch(toast.error)
thinking.set(nextThinkingMode(thinkingMode()))
dialog.clear()
},
},
@@ -497,13 +489,8 @@ export function Session() {
title: "Toggle session scrollbar",
value: "session.toggle.scrollbar",
category: "Session",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.session = { ...draft.session, scrollbar: !showScrollbar() }
})
.catch(toast.error)
setShowScrollbar((prev) => !prev)
dialog.clear()
},
},
@@ -511,13 +498,8 @@ export function Session() {
title: groupExploration() ? "Show tool calls individually" : "Group related tool calls",
value: "session.toggle.exploration_grouping",
category: "Session",
hidden: true,
run: () => {
void configState
.update((draft) => {
draft.session = { ...draft.session, grouping: groupExploration() ? "none" : "auto" }
})
.catch(toast.error)
setGroupExploration((prev) => !prev)
dialog.clear()
},
},
@@ -873,7 +855,6 @@ export function Session() {
sessionID: route.sessionID,
thinkingMode,
showThinking,
markdownMode,
groupExploration,
diffWrapMode,
models,
@@ -1306,6 +1287,7 @@ function SessionSkillMessage(props: { message: Extract<SessionMessageInfo, { typ
function CompactionMessage(props: { message: Extract<SessionMessageInfo, { type: "compaction" }> }) {
const ctx = use()
const kv = useKV()
const { theme, syntax } = useTheme()
const status = () => props.message.status
const text = () => (props.message.status === "failed" ? props.message.error.message : props.message.summary)
@@ -1318,7 +1300,7 @@ function CompactionMessage(props: { message: Extract<SessionMessageInfo, { type:
<box flexDirection="row" gap={1} paddingLeft={1} paddingRight={1}>
<Switch>
<Match when={status() === "running"}>
<Show when={ctx.config.animations ?? true} fallback={<text fg={color()}></text>}>
<Show when={kv.get("animations_enabled", true)} fallback={<text fg={color()}></text>}>
<spinner frames={SPINNER_FRAMES} interval={80} color={color()} />
</Show>
</Match>
@@ -1338,7 +1320,7 @@ function CompactionMessage(props: { message: Extract<SessionMessageInfo, { type:
internalBlockMode="top-level"
content={content()}
tableOptions={{ style: "grid" }}
conceal={ctx.markdownMode() === "rendered"}
conceal={false}
fg={theme.markdownText}
bg={theme.background}
/>
@@ -1716,7 +1698,7 @@ function ReasoningPart(props: {
part: SessionMessageAssistantReasoning
message: SessionMessageAssistant
}) {
const { theme, syntax } = useTheme()
const { theme } = useTheme()
const ctx = use()
// Collapsed by default in hide mode: a single line throughout, so the
// layout never shifts. Click to open the full markdown block, click to close.
@@ -1736,6 +1718,8 @@ function ReasoningPart(props: {
return end === undefined ? 0 : Math.max(0, end - start)
})
const summary = createMemo(() => reasoningSummary(content()))
const syntax = createSyntaxStyleMemo(() => generateSubtleSyntax(theme))
const toggle = () => {
if (!inMinimal()) return
setExpanded((prev) => !prev)
@@ -1761,7 +1745,7 @@ function ReasoningPart(props: {
streaming={true}
syntaxStyle={syntax()}
content={summary().body}
conceal={ctx.markdownMode() === "rendered"}
conceal={false}
fg={theme.textMuted}
/>
</box>
@@ -1827,7 +1811,7 @@ function TextPart(props: { last: boolean; part: SessionMessageAssistantText }) {
internalBlockMode="top-level"
content={props.part.text.trim()}
tableOptions={{ style: "grid" }}
conceal={ctx.markdownMode() === "rendered"}
conceal={false}
fg={theme.markdownText}
bg={theme.background}
/>
@@ -2396,6 +2380,10 @@ function Subagent(props: ToolProps) {
)
}
export function formatSubagentToolcalls(count: number) {
return `${count} toolcall${count === 1 ? "" : "s"}`
}
export function formatSubagentTitle(agent: string, description: string, background: boolean) {
return `${agent} Subagent — ${description}${background ? " [background]" : ""}`
}
@@ -2404,6 +2392,11 @@ export function formatSubagentRetry(attempt: number, message: string) {
return `Retrying (attempt ${attempt}) · ${message}`
}
export function formatCompletedSubagentDetail(toolcalls: number, duration: string) {
if (toolcalls === 0) return duration
return `${formatSubagentToolcalls(toolcalls)} · ${duration}`
}
type ExecuteCall = { tool: string; status: "running" | "completed" | "error"; input?: Record<string, unknown> }
function executeCalls(value: unknown): ExecuteCall[] {
+1 -3
View File
@@ -177,9 +177,7 @@ export function createSessionRows(sessionID: Accessor<string>) {
}
const queuedStart = (rows: SessionRow[]) => {
const index = rows.findIndex(
(row) => row.type === "compaction-queued" || (row.type === "message" && isPending(row.messageID)),
)
const index = rows.findIndex((row) => row.type === "message" && isPending(row.messageID))
return index === -1 ? rows.length : index
}
+27
View File
@@ -90,6 +90,7 @@ export type Theme = {
_hasSelectedListItemText: boolean
}
type ThemeColor = Exclude<keyof Theme, "thinkingOpacity" | "_hasSelectedListItemText">
export type SyntaxStyleOverrides = Record<string, { italic?: boolean }>
export function selectedForeground(theme: Theme, bg?: RGBA): RGBA {
// If theme explicitly defines selectedListItemText, use it
@@ -556,6 +557,32 @@ export function generateSyntax(theme: Theme) {
return SyntaxStyle.fromTheme(getSyntaxRules(theme))
}
export function generateSubtleSyntax(theme: Theme, overrides?: SyntaxStyleOverrides) {
const rules = getSyntaxRules(theme)
return SyntaxStyle.fromTheme(
rules.map((rule) => {
const override = rule.scope.reduce((acc, scope) => ({ ...acc, ...overrides?.[scope] }), {})
if (rule.style.foreground) {
const fg = rule.style.foreground
return {
...rule,
style: {
...rule.style,
...override,
foreground: RGBA.fromInts(
Math.round(fg.r * 255),
Math.round(fg.g * 255),
Math.round(fg.b * 255),
Math.round(theme.thinkingOpacity * 255),
),
},
}
}
return rule
}),
)
}
function getSyntaxRules(theme: Theme) {
return [
{
+25 -40
View File
@@ -36,7 +36,14 @@ export interface DialogSelectProps<T> {
renderFilter?: boolean
locked?: boolean
preserveSelection?: boolean
actions?: DialogSelectAction<T>[]
actions?: {
command: string
title: string
side?: "left" | "right"
hidden?: boolean
disabled?: boolean | ((option: DialogSelectOption<T> | undefined) => boolean)
onTrigger: (option: DialogSelectOption<T>) => void
}[]
footerHints?: {
title: string
label: string
@@ -44,27 +51,8 @@ export interface DialogSelectProps<T> {
}[]
bindings?: readonly Binding<Renderable, KeyEvent>[]
current?: T
focusCurrent?: boolean
}
type DialogSelectActionBase<T> = {
command: string
title: string
side?: "left" | "right"
hidden?: boolean
disabled?: boolean | ((option: DialogSelectOption<T> | undefined) => boolean)
}
type DialogSelectAction<T> =
| (DialogSelectActionBase<T> & {
selection?: "required"
onTrigger: (option: DialogSelectOption<T>) => void
})
| (DialogSelectActionBase<T> & {
selection: "none"
onTrigger: () => void
})
export interface DialogSelectOption<T = any> {
title: string
titleView?: JSX.Element
@@ -116,7 +104,6 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
on(
() => props.current,
(current) => {
if (props.focusCurrent === false) return
if (current) {
const currentIndex = flat().findIndex((opt) => isDeepEqual(opt.value, current))
if (currentIndex >= 0) {
@@ -233,11 +220,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
on(
() => props.options,
() => {
if (!props.preserveSelection) {
const next = Math.min(store.selected, flat().length - 1)
if (next >= 0 && next !== store.selected) setStore("selected", next)
return
}
if (!props.preserveSelection) return
if (resetSelection && store.filter.length > 0) {
const option = flat()[0]
if (!option) return
@@ -246,7 +229,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
return
}
if (!selection) {
if (props.focusCurrent !== false && props.current !== undefined) {
if (props.current !== undefined) {
const index = flat().findIndex((option) => isDeepEqual(option.value, props.current))
if (index >= 0) {
setStore("selected", index)
@@ -296,7 +279,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
setTimeout(() => {
if (filter.length > 0) {
moveTo(0, true, false)
} else if (current && props.focusCurrent !== false) {
} else if (current) {
const currentIndex = flat().findIndex((opt) => isDeepEqual(opt.value, current))
if (currentIndex >= 0) {
moveTo(currentIndex, true)
@@ -365,7 +348,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
setStore("input", "keyboard")
const index = focusedAction()
if (index !== undefined) {
trigger(actionItems()[index])
triggerAction(actionItems()[index])
return
}
const option = selected()
@@ -456,7 +439,14 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
name: item.command,
title: item.title,
category: "Dialog",
run: () => trigger(item),
run() {
if (props.locked) return
if (isActionDisabled(item)) return
setStore("input", "keyboard")
const option = selected()
if (!option) return
item.onTrigger(option)
},
})),
],
bindings: [
@@ -512,13 +502,10 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
const left = createMemo(() => visibleActions().filter((item) => item.side !== "right"))
const right = createMemo(() => visibleActions().filter((item) => item.side === "right"))
function trigger(item: Action | undefined) {
if (props.locked || !item || isActionDisabled(item)) return
function triggerAction(item: VisibleAction | undefined) {
if (props.locked) return
if (!item || !isActionItem(item) || isActionDisabled(item)) return
setStore("input", "keyboard")
if (item.selection === "none") {
item.onTrigger()
return
}
const option = selected()
if (!option) return
item.onTrigger(option)
@@ -529,9 +516,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
}
function isActionDisabled(item: Action) {
const option = selected()
if (item.selection !== "none" && !option) return true
return typeof item.disabled === "function" ? item.disabled(option) : item.disabled
return typeof item.disabled === "function" ? item.disabled(selected()) : item.disabled
}
function isActionFocused(item: VisibleAction) {
@@ -558,7 +543,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
<box
flexDirection="row"
backgroundColor={active() ? theme.primary : RGBA.fromInts(0, 0, 0, 0)}
onMouseUp={() => trigger(item)}
onMouseUp={() => triggerAction(item)}
>
<text
fg={disabled() ? theme.textMuted : active() ? fg : theme.text}
-1
View File
@@ -90,7 +90,6 @@ function init() {
let focus: Renderable | null
function refocus() {
setTimeout(() => {
if (store.stack.length > 0) return
if (!focus) return
if (focus.isDestroyed) return
function find(item: Renderable) {
@@ -0,0 +1,70 @@
/** @jsxImportSource @opentui/solid */
import { testRender } from "@opentui/solid"
import { onMount } from "solid-js"
import { ArgsProvider } from "../../../../src/context/args"
import { KVProvider, useKV } from "../../../../src/context/kv"
import { ProjectProvider, useProject } from "../../../../src/context/project"
import { SDKProvider } from "../../../../src/context/sdk"
import { SyncProvider, useSync } from "../../../../src/context/sync"
import { PermissionProvider } from "../../../../src/context/permission"
import { ExitProvider } from "../../../../src/context/exit"
import { createApi, createClient, createEventStream, createFetch, type FetchHandler } from "../../../fixture/tui-sdk"
import { TestTuiContexts } from "../../../fixture/tui-environment"
export { createEventStream, createFetch, directory, json, worktree } from "../../../fixture/tui-sdk"
export async function wait(fn: () => boolean, timeout = 2000) {
const start = Date.now()
while (!fn()) {
if (Date.now() - start > timeout) throw new Error("timed out waiting for condition")
await Bun.sleep(10)
}
}
type Ctx = { kv: ReturnType<typeof useKV>; project: ReturnType<typeof useProject>; sync: ReturnType<typeof useSync> }
export async function mount(override?: FetchHandler, state?: string) {
const events = createEventStream()
const calls = createFetch(override, events)
let sync!: ReturnType<typeof useSync>
let project!: ReturnType<typeof useProject>
let kv!: ReturnType<typeof useKV>
let done!: () => void
const ready = new Promise<void>((resolve) => {
done = resolve
})
function Probe() {
const ctx: Ctx = { kv: useKV(), project: useProject(), sync: useSync() }
onMount(() => {
sync = ctx.sync
project = ctx.project
kv = ctx.kv
done()
})
return <box />
}
const app = await testRender(() => (
<TestTuiContexts paths={state ? { state } : undefined}>
<ArgsProvider>
<KVProvider>
<SDKProvider client={createClient(calls.fetch)} api={createApi(calls.fetch)}>
<PermissionProvider>
<ProjectProvider>
<ExitProvider exit={() => {}}>
<SyncProvider>
<Probe />
</SyncProvider>
</ExitProvider>
</ProjectProvider>
</PermissionProvider>
</SDKProvider>
</KVProvider>
</ArgsProvider>
</TestTuiContexts>
))
await ready
await wait(() => sync.status === "complete")
return { app, emit: events.emit, kv, project, sync, session: calls.session }
}
@@ -0,0 +1,24 @@
/** @jsxImportSource @opentui/solid */
import { expect, test } from "bun:test"
import { mount } from "./sync-fixture"
test("legacy sync is an inert compatibility context", async () => {
const { app, session, sync } = await mount()
try {
expect(sync.status).toBe("complete")
expect(sync.ready).toBe(true)
expect(sync.data.session).toEqual([])
expect(sync.data.message).toEqual({})
expect(sync.data.provider).toEqual([])
expect(sync.session.get("ses_test")).toBeUndefined()
await sync.bootstrap()
await sync.session.refresh()
await sync.session.sync("ses_test")
expect(session).toEqual([])
} finally {
app.renderer.destroy()
}
})
-84
View File
@@ -653,75 +653,6 @@ test("completes exploration when a queued prompt is promoted", async () => {
}
})
test("shows optimistic prompts immediately and reconciles admission", async () => {
const events = createEventStream()
const sessionID = "session-optimistic"
const calls = createFetch((url) => {
if (url.pathname === `/api/session/${sessionID}/message`) return json({ data: [], cursor: {} })
}, events)
let data!: ReturnType<typeof useData>
function Probe() {
data = useData()
return <box />
}
const app = await testRender(() => (
<TestTuiContexts>
<SDKProvider client={createClient(calls.fetch)} api={createApi(calls.fetch)}>
<ProjectProvider>
<DataProvider>
<Probe />
</DataProvider>
</ProjectProvider>
</SDKProvider>
</TestTuiContexts>
))
try {
const messageID = SessionMessage.ID.create()
data.session.message.optimistic.add(sessionID, {
id: messageID,
type: "user",
text: "Steer now",
time: { created: 1 },
})
const optimistic = data.session.message.get(sessionID, messageID)
expect(optimistic?.type).toBe("user")
expect(optimistic?.type === "user" ? optimistic.text : undefined).toBe("Steer now")
expect(data.session.input.has(sessionID, messageID)).toBe(true)
emitEvent(events, {
id: EventV2.ID.create(),
created: 2,
type: "session.input.admitted",
durable: durable(sessionID),
data: {
sessionID,
inputID: messageID,
input: { type: "user", data: { text: "Steer now", metadata: { admitted: true } }, delivery: "steer" },
},
})
await wait(() => data.session.message.get(sessionID, messageID)?.metadata?.admitted === true)
expect(data.session.message.list(sessionID)).toHaveLength(1)
const failedID = SessionMessage.ID.create()
data.session.message.optimistic.add(sessionID, {
id: failedID,
type: "user",
text: "Fails",
time: { created: 3 },
})
data.session.message.optimistic.remove(sessionID, failedID)
expect(data.session.message.get(sessionID, failedID)).toBeUndefined()
expect(data.session.input.has(sessionID, failedID)).toBe(false)
} finally {
app.renderer.destroy()
}
})
test("removes committed revert messages from local state", async () => {
const events = createEventStream()
const sessionID = "session-revert"
@@ -1271,21 +1202,6 @@ test("restores queued compaction from durable pending input", async () => {
{ type: "compaction-queued", inputID: "message-compaction-later" },
])
emitEvent(events, {
id: "evt_text_ended",
created: 2,
type: "session.text.ended",
durable: durable(sessionID, 5),
data: {
sessionID,
assistantMessageID: "message-assistant",
ordinal: 0,
text: "Active output",
},
})
await wait(() => rows.some((row) => row.type === "part"))
expect(rows.map((row) => row.type)).toEqual(["part", "compaction-queued", "compaction-queued"])
emitEvent(events, {
id: "evt_compaction_started",
created: 2,
@@ -26,10 +26,12 @@ async function mountPrompt(input: {
}) {
const state = path.join(input.root, "state")
await mkdir(state, { recursive: true })
await Bun.write(path.join(state, "kv.json"), "{}")
const [
{ DialogProvider },
{ DialogPrompt },
{ KVProvider },
{ ThemeProvider },
{ ConfigProvider },
{ ToastProvider },
@@ -37,6 +39,7 @@ async function mountPrompt(input: {
] = await Promise.all([
import("../../../src/ui/dialog"),
import("../../../src/ui/dialog-prompt"),
import("../../../src/context/kv"),
import("../../../src/context/theme"),
import("../../../src/config"),
import("../../../src/ui/toast"),
@@ -64,13 +67,15 @@ async function mountPrompt(input: {
>
<OpencodeKeymapProvider keymap={keymap}>
<ConfigProvider config={resolvedConfig}>
<ThemeProvider mode="dark">
<ToastProvider>
<DialogProvider>
<DialogPrompt title="Rename Session" value="draft" onConfirm={input.onConfirm} />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
<KVProvider>
<ThemeProvider mode="dark">
<ToastProvider>
<DialogProvider>
<DialogPrompt title="Rename Session" value="draft" onConfirm={input.onConfirm} />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</KVProvider>
</ConfigProvider>
</OpencodeKeymapProvider>
</TestTuiContexts>
@@ -1,264 +0,0 @@
/** @jsxImportSource @opentui/solid */
import { InputRenderable } from "@opentui/core"
import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
import { testRender, useRenderer } from "@opentui/solid"
import { expect, test } from "bun:test"
import { mkdir } from "node:fs/promises"
import path from "node:path"
import { createSignal, onCleanup, onMount } from "solid-js"
import type { DialogSelectOption } from "../../../src/ui/dialog-select"
import { tmpdir } from "../../fixture/fixture"
import { TestTuiContexts } from "../../fixture/tui-environment"
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
async function renderSelect(
root: string,
options: DialogSelectOption<string>[],
onGlobal: () => void,
onRow: (option: DialogSelectOption<string>) => void,
) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
const config = createTuiResolvedConfig()
const [
{ ConfigProvider },
{ ThemeProvider },
{ OpencodeKeymapProvider, registerOpencodeKeymap },
{ DialogProvider },
{ DialogSelect },
{ ToastProvider },
] = await Promise.all([
import("../../../src/config"),
import("../../../src/context/theme"),
import("../../../src/keymap"),
import("../../../src/ui/dialog"),
import("../../../src/ui/dialog-select"),
import("../../../src/ui/toast"),
])
function Harness() {
const renderer = useRenderer()
const keymap = createDefaultOpenTuiKeymap(renderer)
const off = registerOpencodeKeymap(keymap, renderer, config)
onCleanup(off)
return (
<TestTuiContexts directory={root} paths={{ home: root, state, worktree: root }}>
<OpencodeKeymapProvider keymap={keymap}>
<ConfigProvider config={config}>
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({}) }}>
<ToastProvider>
<DialogProvider>
<DialogSelect
title="Items"
options={options}
actions={[
{
command: "dialog.move_session.delete",
title: "delete",
onTrigger: onRow,
},
{
command: "dialog.move_session.new",
title: "new",
selection: "none",
onTrigger: onGlobal,
},
]}
/>
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</ConfigProvider>
</OpencodeKeymapProvider>
</TestTuiContexts>
)
}
const app = await testRender(() => <Harness />, { width: 80, height: 20, kittyKeyboard: true })
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Items"))
await app.waitFor(() => app.renderer.currentFocusedEditor instanceof InputRenderable)
return app
}
async function mountSelect(root: string, initial: DialogSelectOption<string>[]) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
const config = createTuiResolvedConfig()
const [
{ ConfigProvider },
{ ThemeProvider },
{ OpencodeKeymapProvider, registerOpencodeKeymap },
{ DialogProvider, useDialog },
{ DialogSelect },
{ ToastProvider },
] = await Promise.all([
import("../../../src/config"),
import("../../../src/context/theme"),
import("../../../src/keymap"),
import("../../../src/ui/dialog"),
import("../../../src/ui/dialog-select"),
import("../../../src/ui/toast"),
])
const selected: string[] = []
const moved: string[] = []
let replaceOptions!: (options: DialogSelectOption<string>[]) => void
function Harness() {
const renderer = useRenderer()
const keymap = createDefaultOpenTuiKeymap(renderer)
const off = registerOpencodeKeymap(keymap, renderer, config)
const [options, setOptions] = createSignal(initial)
replaceOptions = setOptions
onCleanup(off)
function Fixture() {
const dialog = useDialog()
onMount(() =>
dialog.replace(() => (
<DialogSelect
title="Mutable options"
options={options()}
onMove={(option) => moved.push(option.value)}
onSelect={(option) => selected.push(option.value)}
/>
)),
)
return null
}
return (
<TestTuiContexts directory={root} paths={{ home: root, state, worktree: root }}>
<OpencodeKeymapProvider keymap={keymap}>
<ConfigProvider config={config}>
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({}) }}>
<ToastProvider>
<DialogProvider>
<Fixture />
</DialogProvider>
</ToastProvider>
</ThemeProvider>
</ConfigProvider>
</OpencodeKeymapProvider>
</TestTuiContexts>
)
}
const app = await testRender(() => <Harness />, { width: 80, height: 24, kittyKeyboard: true })
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Mutable options"))
await app.waitFor(() => app.renderer.currentFocusedEditor instanceof InputRenderable)
return { app, moved, replaceOptions, selected }
}
test("dialog actions run without options while row actions still require a selection", async () => {
await using tmp = await tmpdir()
let global = 0
const rows: string[] = []
const app = await renderSelect(
tmp.path,
[],
() => global++,
(option) => rows.push(option.value),
)
try {
app.mockInput.pressKey("m", { ctrl: true })
app.mockInput.pressKey("d", { ctrl: true })
expect(global).toBe(1)
expect(rows).toEqual([])
} finally {
app.renderer.destroy()
}
})
test("footer actions run when filtering leaves no selected row", async () => {
await using tmp = await tmpdir()
let global = 0
const rows: string[] = []
const app = await renderSelect(
tmp.path,
[{ title: "Alpha", value: "alpha" }],
() => global++,
(option) => rows.push(option.value),
)
try {
for (const key of "missing") app.mockInput.pressKey(key)
await app.waitForFrame((frame) => frame.includes("No results found"))
app.mockInput.pressKey("d", { ctrl: true })
app.mockInput.pressTab()
app.mockInput.pressEnter()
expect(global).toBe(1)
expect(rows).toEqual([])
} finally {
app.renderer.destroy()
}
})
test("row actions receive the selected option", async () => {
await using tmp = await tmpdir()
const rows: string[] = []
const app = await renderSelect(
tmp.path,
[{ title: "Alpha", value: "alpha" }],
() => {},
(option) => rows.push(option.value),
)
try {
app.mockInput.pressKey("d", { ctrl: true })
expect(rows).toEqual(["alpha"])
} finally {
app.renderer.destroy()
}
})
test("selects the new final option immediately after removing the selected final option", async () => {
await using tmp = await tmpdir()
const options = ["first", "second", "third"].map((value) => ({ title: value, value }))
const select = await mountSelect(tmp.path, options)
try {
select.app.mockInput.pressArrow("down")
await select.app.waitFor(() => select.moved.at(-1) === "second")
select.app.mockInput.pressArrow("down")
await select.app.waitFor(() => select.moved.at(-1) === "third")
select.replaceOptions(options.slice(0, -1))
await select.app.waitForFrame((frame) => !frame.includes("third"))
select.app.mockInput.pressEnter()
await select.app.waitFor(() => select.selected.length === 1)
expect(select.selected).toEqual(["second"])
} finally {
select.app.renderer.destroy()
}
})
test("selects a repopulated option after removing the only option", async () => {
await using tmp = await tmpdir()
const select = await mountSelect(tmp.path, [{ title: "only", value: "only" }])
try {
select.replaceOptions([])
await select.app.waitForFrame((frame) => frame.includes("No results found"))
select.app.mockInput.pressEnter()
expect(select.selected).toEqual([])
select.replaceOptions([{ title: "replacement", value: "replacement" }])
await select.app.waitForFrame((frame) => frame.includes("replacement"))
select.app.mockInput.pressEnter()
await select.app.waitFor(() => select.selected.length === 1)
expect(select.selected).toEqual(["replacement"])
} finally {
select.app.renderer.destroy()
}
})
@@ -4,6 +4,7 @@ import { RGBA } from "@opentui/core"
import { testRender } from "@opentui/solid"
import type { JSX } from "solid-js"
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
import { KVProvider } from "../../../src/context/kv"
import { ThemeProvider } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
import { DiffViewerFileTree } from "../../../src/feature-plugins/system/diff-viewer-file-tree"
@@ -181,7 +182,9 @@ function withTheme(component: () => JSX.Element) {
return (
<TestTuiContexts>
<ConfigProvider config={createTuiResolvedConfig()}>
<ThemeProvider mode="dark">{component()}</ThemeProvider>
<KVProvider>
<ThemeProvider mode="dark">{component()}</ThemeProvider>
</KVProvider>
</ConfigProvider>
</TestTuiContexts>
)
@@ -5,6 +5,7 @@ import { DiffRenderable, type Renderable, ScrollBoxRenderable } from "@opentui/c
import { testRender, useRenderer } from "@opentui/solid"
import type { TuiPluginApi, TuiPluginMeta, TuiRouteCurrent, TuiRouteDefinition } from "@opencode-ai/plugin/tui"
import type { Session } from "@opencode-ai/sdk/v2"
import { KVProvider } from "../../../src/context/kv"
import { ThemeProvider } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
import { SDKProvider } from "../../../src/context/sdk"
@@ -173,9 +174,11 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
<SDKProvider client={createClient(transport.fetch)} api={createApi(transport.fetch)}>
<OpencodeKeymapProvider keymap={keymap}>
<ConfigProvider config={config}>
<ThemeProvider mode="dark">
{renderDiff?.({ params: "params" in current ? current.params : undefined })}
</ThemeProvider>
<KVProvider>
<ThemeProvider mode="dark">
{renderDiff?.({ params: "params" in current ? current.params : undefined })}
</ThemeProvider>
</KVProvider>
</ConfigProvider>
</OpencodeKeymapProvider>
</SDKProvider>
+9 -5
View File
@@ -7,6 +7,7 @@ import path from "node:path"
import { onCleanup } from "solid-js"
import { ClipboardProvider } from "../../../src/context/clipboard"
import type { FormWithLocation } from "../../../src/context/data"
import { KVProvider } from "../../../src/context/kv"
import { SDKProvider } from "../../../src/context/sdk"
import { ThemeProvider } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
@@ -20,6 +21,7 @@ import { createApi, createClient, createEventStream, createFetch } from "../../f
async function mountForm(root: string, width = 80) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
await Bun.write(path.join(state, "kv.json"), "{}")
const replies: unknown[] = []
const copied: string[] = []
@@ -76,11 +78,13 @@ async function mountForm(root: string, width = 80) {
<OpencodeKeymapProvider keymap={keymap}>
<ConfigProvider config={config}>
<SDKProvider client={createClient(transport.fetch)} api={createApi(transport.fetch)}>
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({}) }}>
<ToastProvider>
<FormPrompt form={form} />
</ToastProvider>
</ThemeProvider>
<KVProvider>
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({}) }}>
<ToastProvider>
<FormPrompt form={form} />
</ToastProvider>
</ThemeProvider>
</KVProvider>
</SDKProvider>
</ConfigProvider>
</OpencodeKeymapProvider>
@@ -2,8 +2,10 @@ import { afterEach, describe, expect, test } from "bun:test"
import { For } from "solid-js"
import { testRender, type JSX } from "@opentui/solid"
import {
formatCompletedSubagentDetail,
formatSubagentRetry,
formatSubagentTitle,
formatSubagentToolcalls,
InlineToolRow,
parseApplyPatchFiles,
parseDiagnostics,
@@ -180,6 +182,13 @@ describe("TUI inline tool wrapping", () => {
).toEqual([{ message: "valid", range: { start: { line: 2, character: 3 } } }])
})
test("formats completed subagent toolcall details", () => {
expect(formatCompletedSubagentDetail(0, "501ms")).toBe("501ms")
expect(formatCompletedSubagentDetail(1, "501ms")).toBe("1 toolcall · 501ms")
expect(formatCompletedSubagentDetail(2, "501ms")).toBe("2 toolcalls · 501ms")
expect(formatSubagentToolcalls(0)).toBe("0 toolcalls")
})
test("keeps background state attached to the subagent identity", () => {
expect(formatSubagentTitle("Explore", "Inspect renderer", false)).toBe("Explore Subagent — Inspect renderer")
expect(formatSubagentTitle("Explore", "Inspect renderer", true)).toBe(
@@ -198,4 +207,5 @@ describe("TUI inline tool wrapping", () => {
test("snapshots expanded tool errors under the tool text", async () => {
expect(await renderFrame(() => <Fixture errorExpanded />, { width: 72, height: 12 })).toMatchSnapshot()
})
})
+10
View File
@@ -11,6 +11,7 @@ type Opts = {
}
export function createTuiPluginApi(opts: Opts = {}) {
const values = new Map<string, unknown>()
const color = RGBA.fromInts(200, 200, 200)
const dialog = { clear() {}, replace() {}, setSize() {}, size: "medium" as const, depth: 0, open: false }
return {
@@ -18,6 +19,15 @@ export function createTuiPluginApi(opts: Opts = {}) {
client: opts.client,
event: opts.event,
keymap: opts.keymap,
kv: {
get(name: string, fallback?: unknown) {
return values.has(name) ? values.get(name) : fallback
},
set(name: string, value: unknown) {
values.set(name, value)
},
ready: true,
},
state: { session: { get: () => undefined, ...opts.state?.session } },
theme: { current: new Proxy({}, { get: () => color }) },
tuiConfig: createTuiResolvedConfig(),
-1
View File
@@ -8,7 +8,6 @@
"dev": "vite dev --host 0.0.0.0 --port 3000",
"build": "vite build",
"preview": "vite preview --host 0.0.0.0",
"pretypecheck": "fumadocs-mdx",
"typecheck": "tsgo --noEmit"
},
"dependencies": {
+5
View File
@@ -7,6 +7,11 @@ export function baseOptions(): BaseLayoutProps {
url: "/",
},
links: [
{
text: "Docs",
url: "/docs",
active: "nested-url",
},
{
text: "GitHub",
url: "https://github.com/anomalyco/opencode",
-6
View File
@@ -23,12 +23,6 @@ body {
margin: 0;
}
/* Fumadocs 16.11 stretches top layout tabs across the main grid row. */
#nd-docs-layout > div:has(> a[href="/docs/build"], > a[href="/docs/api"]) {
align-self: start;
height: 3rem;
}
.home {
min-height: 100vh;
display: grid;