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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/tui/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,10 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
name: "effort.list",
title: "Switch agent effort",
category: "Agent",
slashName: "agent-effort",
// Agent effort is a review-rigor dial, so it keeps its own `/effort`
// name: `/variants` (plural) stays the model thinking selector.
slashName: "effort",
slashAliases: ["agent-effort"],
run: () => {
dialog.replace(() => <DialogAgentEffort />)
},
Expand Down
42 changes: 27 additions & 15 deletions packages/tui/src/component/dialog-agent-effort.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useLocal } from "../context/local"
import { useTheme } from "../context/theme"
import { DialogSelect } from "../ui/dialog-select"
import { useDialog } from "../ui/dialog"
import type { Level } from "../util/agent-effort"
import { effortBadge, type Level } from "../util/agent-effort"

const ENTRIES: {
value: Level
Expand All @@ -20,7 +20,10 @@ const ENTRIES: {
{
value: "medium",
title: "Medium",
description: "up to 2 review passes · default",
// No "· default" here: on home the persisted selection decides the
// default now, so a static claim on one row would contradict it. The
// cursor and the footer carry that meaning instead.
description: "up to 2 review passes",
details: ["Independent review for code changes; only blocking findings force another pass, then an honest status"],
},
{
Expand All @@ -37,16 +40,27 @@ export function DialogAgentEffort() {
const { theme } = useTheme()

const options = createMemo(() =>
ENTRIES.map((entry) => ({
value: entry.value,
title: entry.title,
description: entry.description,
details: entry.details,
onSelect: () => {
dialog.clear()
local.effort.set(entry.value)
},
})),
ENTRIES.map((entry) => {
// Level names always stay visible; the hue only reinforces them (fast
// green, medium orange, thorough red). It is painted as a filled chip so
// it keeps its contrast on both the panel and a highlighted row.
const badge = effortBadge(entry.value, theme)
return {
value: entry.value,
title: entry.title,
titleView: (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Verify titleView span style props match renderer API

The <span style={{ fg: badge.fg, bg: badge.bg, bold: true }}> uses fg/bg/bold keys. Confirm this matches the @opentui/solid JSX style property expectations (vs color/backgroundColor/fontWeight). The test asserts the rendered colors, so it likely works, but worth a quick sanity check against other components.

<>
<span style={{ fg: badge.fg, bg: badge.bg, bold: true }}>{` ${entry.title} `}</span>
</>
),
description: entry.description,
details: entry.details,
onSelect: () => {
dialog.clear()
local.effort.set(entry.value)
},
}
}),
)

return (
Expand All @@ -57,9 +71,7 @@ export function DialogAgentEffort() {
flat={true}
footer={
<text fg={theme.textMuted}>
{local.effort.scoped()
? "Stored on this session · separate from model thinking"
: "Config default · open a session to change it"}
{local.effort.scoped() ? "Stored on this session" : "Default for new sessions"}
</text>
}
/>
Expand Down
18 changes: 16 additions & 2 deletions packages/tui/src/component/prompt/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { type AutocompleteRef, Autocomplete } from "./autocomplete"
import { useRenderer, useTerminalDimensions, type JSX } from "@opentui/solid"
import type { AssistantMessage, FilePart, UserMessage } from "@opencode-ai/sdk/v2"
import { Locale } from "../../util/locale"
import { effortColor } from "../../util/agent-effort"
import { errorMessage } from "../../util/error"
import { formatDuration } from "../../util/format"
import { useDialog } from "../../ui/dialog"
Expand Down Expand Up @@ -990,6 +991,10 @@ export function Prompt(props: PromptProps) {
if (move.pending() && !directory) return false
finishMoveProgress = Boolean(move.progress())

// A home default becomes the new session's persisted selection, so the
// server enforces the same level the composer shows. Undefined when the
// user never picked one, which leaves configuration in charge.
const effortMetadata = local.effort.newSessionMetadata()
const res = await sdk.client.session.create({
directory,
workspace: workspaceID,
Expand All @@ -999,6 +1004,7 @@ export function Prompt(props: PromptProps) {
id: selectedModel.modelID,
variant,
},
metadata: effortMetadata,
})

if (res.error) {
Expand All @@ -1014,6 +1020,7 @@ export function Prompt(props: PromptProps) {
}

sessionID = res.data.id
local.effort.seed(sessionID, effortMetadata)
}

const inputText = expandTrackedPastedText(
Expand Down Expand Up @@ -1459,10 +1466,17 @@ export function Prompt(props: PromptProps) {
</text>
<text fg={fadeColor(theme.textMuted, modelMetaAlpha())}>{currentProviderLabel()}</text>
{/* Agent effort is its own dial and shows even for
models without thinking variants. */}
models without thinking variants. Its hue (fast
green, medium orange, thorough red) is drawn
beside the always-visible level name. */}
<text fg={fadeColor(theme.textMuted, modelMetaAlpha())}>·</text>
<text>
<span style={{ fg: fadeColor(theme.info, modelMetaAlpha()), bold: true }}>
<span
style={{
fg: fadeColor(effortColor(local.effort.current(), theme), modelMetaAlpha()),
bold: true,
}}
>
{local.effort.current()}
</span>
</text>
Expand Down
92 changes: 84 additions & 8 deletions packages/tui/src/context/local.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { usePermission } from "./permission"
import { supportsVision } from "../util/model"
import {
coupledThinking,
defaultLevel,
effortRecord,
isRecord,
mergeEffortMetadata,
metadataLevel,
Expand Down Expand Up @@ -633,6 +635,61 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
const writes = new Map<string, Promise<void>>()
const [pendingVersion, setPendingVersion] = createSignal(0)

// Home default for new sessions, persisted for the TUI in the state
// directory. `stored` is the optimistic display value while `persisted`
// tracks what the file actually holds, so a failed write can roll the
// display back to a value that was really saved instead of reporting a
// selection that never landed.
const defaultFile = path.join(paths.state, "effort.json")
const [stored, setStored] = createSignal<Level | undefined>()
let persisted: Level | undefined
let touched = false
let defaultSequence = 0

let defaultWrites = readJson<unknown>(defaultFile)
.then((value) => {
const level = metadataLevel(value)
if (!level) throw new Error("Invalid agent effort default")
persisted = level

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: persisted = level is not guarded by touched, unlike setStored below it

If the initial readJson settles after a home selection's write has already succeeded (slow state directory, or a selection made immediately at startup), this line overwrites persisted with the stale on-disk value even though the file now holds the newer selection. The next failed write then rolls the label back through setStored(persisted) to a value that never landed — the exact failure mode the rollback logic exists to prevent. The setStored call a few lines below already guards with if (!touched); persisted needs the same guard:

Suggested change
persisted = level
if (!touched) persisted = level

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

// A selection made while the file was still loading wins over the
// file: the user's choice is newer than what was on disk.
if (!touched) setStored(level)
})
.catch((error) => {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return
toast.show({
variant: "warning",
message: `Failed to load the agent effort default: ${errorMessage(error)}`,
duration: 3000,
})
})

function persistDefault(level: Level) {
touched = true
setStored(level)
const attempt = ++defaultSequence
// Wait for the initial read before writing so it cannot replace a
// newer rollback baseline. Then persist rapid selections in order.
const write = defaultWrites.then(() => writeJsonAtomic(defaultFile, effortRecord(level)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: persistDefault error handling has a race with defaultWrites chain

defaultWrites = write.catch(() => {}) swallows the rejection, so the outer .then(success, error) receives a resolved promise (not the error). The error handler will never run because write.catch() returns a resolved promise. The toast and rollback logic in the error handler is dead code. Fix by not catching at the chain level:

Suggested change
const write = defaultWrites.then(() => writeJsonAtomic(defaultFile, effortRecord(level)))
const write = defaultWrites.then(() => writeJsonAtomic(defaultFile, effortRecord(level)))
defaultWrites = write
write.then(
() => {
persisted = level
},
(error) => {
if (attempt !== defaultSequence) return
setStored(persisted)
toast.show({
variant: "warning",
message: `Failed to save the agent effort default: ${errorMessage(error)}`,
duration: 3000,
})
},
)

defaultWrites = write.catch(() => {})
write.then(
() => {
persisted = level
},
(error) => {
// Only the newest selection owns the displayed default; an older
// failed write must not roll back a newer choice.
if (attempt !== defaultSequence) return
setStored(persisted)
toast.show({
variant: "warning",
message: `Failed to save the agent effort default: ${errorMessage(error)}`,
duration: 3000,
})
},
)
}

function activeSessionID() {
return route.data.type === "session" ? route.data.sessionID : undefined
}
Expand All @@ -658,26 +715,45 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
// write must be visible immediately, before the sync event that
// confirms it lands on the session row.
pendingVersion()
// Home has no session to override, so the persisted new-session
// default (then configuration) is what a new session would use.
if (!sessionID) return defaultLevel({ selected: stored(), config: sync.data.config })
return effortSelection({
override: sessionID ? pending.get(sessionID) : undefined,
override: pending.get(sessionID),
metadata: row?.metadata,
config: sync.data.config,
})
},
// Whether the selection is session-scoped right now. On the home
// route there is no session to persist into, so the configured
// default stays authoritative for new work.
// route the persisted default is authoritative for new work.
scoped() {
return activeSessionID() !== undefined
},
// Metadata a session created right now starts from, so the home
// default is stored on the session (and enforced by the server)
// rather than only being displayed. Undefined when the user never
// picked one, which leaves the configured default in charge.
newSessionMetadata() {
const level = stored()
return level ? effortRecord(level) : undefined
},
// Show a newly created session's inherited selection immediately:
// its row syncs a moment later, and reading through the same overlay
// as a session write keeps the label from flashing the old default.
seed(sessionID: string, metadata: Record<string, unknown> | undefined) {
if (!metadata) return
if (metadataLevel(sync.session.get(sessionID)?.metadata) === metadataLevel(metadata)) return
pending.set(sessionID, metadata)
setPendingVersion((version) => version + 1)
},
set(level: Level) {
const sessionID = activeSessionID()
if (!sessionID) {
toast.show({
variant: "info",
message: "Agent effort applies per session; open a session to change it.",
duration: 3000,
})
// Home selection: a failed default write rolls the value back and
// reports the failure, so the label never claims a level that is
// not actually persisted.
persistDefault(level)
model.variant.couple(level)
return
}
const row = sync.session.get(sessionID)
Expand Down
1 change: 1 addition & 0 deletions packages/tui/src/ui/help-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const HELP_SECTIONS: HelpSection[] = [
title: "System",
commands: [
{ command: "/variants", desc: "Switch model variants, when supported" },
{ command: "/effort", desc: "Agent effort: review rigor (fast, medium, thorough)" },
{ command: "/mcps", desc: "Toggle MCP servers" },
{ command: "/themes", desc: "Switch the terminal theme" },
{ command: "/status", desc: "View system status info" },
Expand Down
57 changes: 56 additions & 1 deletion packages/tui/src/util/agent-effort.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AgentEffort } from "@opencode-ai/schema/agent-effort"
import { RGBA } from "@opentui/core"

export type Level = AgentEffort.Level

Expand Down Expand Up @@ -74,14 +75,68 @@ export function resolveEffort(input: { metadata?: unknown; config?: unknown; fal
return metadataLevel(input.metadata) ?? configLevel(input.config) ?? AgentEffort.resolve(undefined, input.fallback)
}

/**
* The TUI-level default new sessions start from: the selection persisted on
* home, then the configured `agent.effort`, then the schema fallback. The
* caller validates whatever it read from disk, so `selected` is already a
* level or nothing.
*/
export function defaultLevel(input: { selected?: Level; config?: unknown }): Level {
return input.selected ?? configLevel(input.config) ?? AgentEffort.resolve(undefined)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: defaultLevel calls AgentEffort.resolve(undefined) without explicit fallback

The spec states the fallback chain is: persisted effort.json → agent.effort config → medium. Calling AgentEffort.resolve(undefined) relies on the schema's internal default which may not be "medium" or could change. Use an explicit fallback for clarity and safety:

Suggested change
return input.selected ?? configLevel(input.config) ?? AgentEffort.resolve(undefined)
return input.selected ?? configLevel(input.config) ?? AgentEffort.resolve(undefined, "medium")

}

/**
* A metadata record carrying exactly one persisted selection, used both for
* the session metadata write and for the TUI's persisted home default.
*/
export function effortRecord(level: Level): Record<string, unknown> {
return { [METADATA_KEY]: level }
}

/**
* `session.update` replaces the metadata record wholesale, so every effort
* write merges over the current record to preserve unrelated keys. A
* non-record base (missing/corrupted metadata) collapses to the single key.
*/
export function mergeEffortMetadata(current: unknown, level: Level): Record<string, unknown> {
const base = isRecord(current) ? current : {}
return { ...base, [METADATA_KEY]: level }
return { ...base, ...effortRecord(level) }
}

// Effort hues: fast is green, medium is orange, thorough is red. Each level
// keeps two variants so the hue stays legible on both dark and light surfaces
// (the level names are always rendered next to the color, so the levels never
// depend on color alone).
const TONES: Record<Level, { dark: string; light: string }> = {
fast: { dark: "#3fb950", light: "#116329" },
medium: { dark: "#f0883e", light: "#9a3412" },
thorough: { dark: "#f85149", light: "#b3121f" },
}

function luminance(color: RGBA) {
return 0.299 * color.r + 0.587 * color.g + 0.114 * color.b
}

/**
* The effort hue for a level, picked for the surface it is drawn on. A
* transparent surface means the terminal supplies the background, so the
* theme's text color stands in for it: readable light text implies a dark
* surface and therefore the bright hue variant.
*/
export function effortColor(level: Level, theme: { background: RGBA; text: RGBA }): RGBA {
const lightSurface =
theme.background.a === 0 ? luminance(theme.text) < 0.5 : luminance(theme.background) > 0.5
return RGBA.fromHex(TONES[level][lightSurface ? "light" : "dark"])
}

/**
* The level's hue as a filled indicator plus the ink that stays readable on
* it, for surfaces (like a highlighted selector row) where the surrounding
* colors are not ours to choose.
*/
export function effortBadge(level: Level, theme: { background: RGBA; text: RGBA }): { fg: RGBA; bg: RGBA } {
const bg = effortColor(level, theme)
return { bg, fg: luminance(bg) > 0.5 ? RGBA.fromInts(0, 0, 0) : RGBA.fromInts(255, 255, 255) }
}

/**
Expand Down
Loading
Loading