Skip to content
Open
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
12 changes: 12 additions & 0 deletions packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export type PromptProps = {
visible?: boolean
disabled?: boolean
onSubmit?: () => void
onBeforeSubmit?: (text: string) => boolean
ref?: (ref: PromptRef) => void
hint?: JSX.Element
showPlaceholder?: boolean
Expand Down Expand Up @@ -587,6 +588,17 @@ export function Prompt(props: PromptProps) {
const currentMode = store.mode
const variant = local.model.variant.current()

// Allow external interception (e.g., /btw mode)
if (props.onBeforeSubmit?.(inputText)) {
history.append({ ...store.prompt, mode: currentMode })
input.extmarks.clear()
setStore("prompt", { input: "", parts: [] })
setStore("extmarkToPartIndex", new Map())
input.clear()
props.onSubmit?.()
return
}

if (store.mode === "shell") {
sdk.client.session.shell({
sessionID,
Expand Down
156 changes: 154 additions & 2 deletions packages/opencode/src/cli/cmd/tui/routes/session/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import { useCommandDialog } from "@tui/component/dialog-command"
import type { DialogContext } from "@tui/ui/dialog"
import { useKeybind } from "@tui/context/keybind"
import { Header } from "./header"
import { parsePatch } from "diff"
import { diffLines, parsePatch } from "diff"
import { useDialog } from "../../ui/dialog"
import { TodoItem } from "../../component/todo-item"
import { DialogMessage } from "./dialog-message"
Expand Down Expand Up @@ -81,9 +81,15 @@ import { DialogExportOptions } from "../../ui/dialog-export-options"
import { formatTranscript } from "../../util/transcript"
import { UI } from "@/cli/ui.ts"
import { useTuiConfig } from "../../context/tui-config"
import { Identifier } from "@/id/id"

addDefaultParsers(parsers.parsers)

type BtwState =
| { type: "waiting" }
| { type: "loading"; question: string; userMessageID: string }
| { type: "response"; question: string; responseMessageID: string }

class CustomSpeedScroll implements ScrollAcceleration {
constructor(private speed: number) {}

Expand Down Expand Up @@ -128,7 +134,8 @@ export function Session() {
.filter((x) => x.parentID === parentID || x.id === parentID)
.toSorted((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
})
const messages = createMemo(() => sync.data.message[route.sessionID] ?? [])
const messages = createMemo(() => (sync.data.message[route.sessionID] ?? []).filter((m) => !m.btw))
const [btwState, setBtwState] = createSignal<BtwState | null>(null)
const permissions = createMemo(() => {
if (session()?.parentID) return []
return children().flatMap((x) => sync.data.permission[x.id] ?? [])
Expand Down Expand Up @@ -259,6 +266,39 @@ export function Session() {
)
})

// Watch for btw response arriving via sync events
createEffect(() => {
const state = btwState()
if (!state || state.type !== "loading") return
const msgs = sync.data.message[route.sessionID] ?? []
const response = msgs.find(
(m): m is AssistantMessage =>
m.role === "assistant" &&
(m as AssistantMessage).parentID === state.userMessageID &&
m.btw === true &&
!!(m as AssistantMessage).finish &&
!["tool-calls", "unknown"].includes((m as AssistantMessage).finish!),
)
if (response) {
setBtwState({ type: "response", question: state.question, responseMessageID: response.id })
}
})

// Dismiss btw with esc (any state) or enter (response state)
useKeyboard((evt) => {
const state = btwState()
if (!state) return
if (evt.name === "escape") {
setBtwState(null)
evt.preventDefault()
evt.stopPropagation()
} else if (state.type === "response" && evt.name === "return") {
setBtwState(null)
evt.preventDefault()
evt.stopPropagation()
}
})

useKeyboard((evt) => {
if (!session()?.parentID) return
if (keybind.match("app_exit", evt)) {
Expand Down Expand Up @@ -319,6 +359,33 @@ export function Session() {
}, 50)
}

const btwBeforeSubmit = (text: string): boolean => {
const state = btwState()
if (!state || state.type !== "waiting") return false
const sessionID = session()?.id
if (!sessionID) {
setBtwState(null)
return false
}
const userMessageID = Identifier.ascending("message")
setBtwState({ type: "loading", question: text, userMessageID })
sdk.client.session
.promptAsync({
sessionID,
btw: true,
messageID: userMessageID,
parts: [{ type: "text", text }],
})
.catch((error) => {
toast.show({
message: error instanceof Error ? error.message : "Failed",
variant: "error",
})
setBtwState(null)
})
return true
}

const local = useLocal()

function moveFirstChild() {
Expand Down Expand Up @@ -616,6 +683,20 @@ export function Session() {
dialog.clear()
},
},
{
title: "Ask a quick question",
description: "Ask a quick question about your current work without adding to the conversation history.",
value: "session.btw",
keybind: "btw",
category: "Session",
slash: {
name: "btw",
},
onSelect: (dialog) => {
setBtwState({ type: "waiting" })
dialog.clear()
},
},
{
title: showDetails() ? "Hide tool details" : "Show tool details",
value: "session.toggle.actions",
Expand Down Expand Up @@ -1164,6 +1245,7 @@ export function Session() {
</Switch>
)}
</For>
<BtwSection state={btwState()} sync={sync} sessionID={route.sessionID} />
</scrollbox>
<box flexShrink={0}>
<Show when={permissions().length > 0}>
Expand All @@ -1183,6 +1265,7 @@ export function Session() {
}
}}
disabled={permissions().length > 0 || questions().length > 0}
onBeforeSubmit={btwBeforeSubmit}
onSubmit={() => {
toBottom()
}}
Expand Down Expand Up @@ -2279,3 +2362,72 @@ function filetype(input?: string) {
if (["typescriptreact", "javascriptreact", "javascript"].includes(language)) return "typescript"
return language
}

function BtwSection(props: { state: BtwState | null; sync: ReturnType<typeof useSync>; sessionID: string }) {
const { theme, syntax } = useTheme()

const responseText = createMemo(() => {
const state = props.state
if (!state || state.type !== "response") return null
const msgs = props.sync.data.message[props.sessionID] ?? []
const msg = msgs.find((m) => m.id === state.responseMessageID)
if (!msg) return null
const parts = props.sync.data.part[msg.id] ?? []
return parts
.filter((p): p is TextPart => p.type === "text" && !(p as TextPart).synthetic)
.map((p) => p.text)
.join("")
})

return (
<Show when={props.state}>
<box
marginTop={1}
border={["left"]}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.primary}
paddingLeft={2}
paddingTop={1}
paddingBottom={1}
flexShrink={0}
backgroundColor={theme.backgroundPanel}
>
<box flexDirection="row" gap={1}>
<text attributes={TextAttributes.BOLD} fg={theme.primary}>
/btw
</text>
<Show when={props.state!.type !== "waiting"}>
<text fg={theme.textMuted}>{(props.state as { type: "loading" | "response"; question: string }).question}</text>
</Show>
<Show when={props.state!.type === "waiting"}>
<text fg={theme.textMuted}>Type your question and press enter...</text>
</Show>
</box>
<Switch>
<Match when={props.state!.type === "loading"}>
<box flexDirection="row" gap={1} marginTop={1}>
<Spinner />
<text fg={theme.textMuted}>Thinking...</text>
</box>
</Match>
<Match when={props.state!.type === "response" && responseText()}>
<box marginTop={1}>
<code
filetype="markdown"
drawUnstyledText={false}
streaming={false}
syntaxStyle={syntax()}
content={responseText()!.trim()}
conceal={false}
fg={theme.text}
/>
</box>
<text fg={theme.textMuted} marginTop={1}>
enter/esc to close
</text>
</Match>
</Switch>
</box>
</Show>
)
}
14 changes: 14 additions & 0 deletions packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ export namespace MessageV2 {
system: z.string().optional(),
tools: z.record(z.string(), z.boolean()).optional(),
variant: z.string().optional(),
btw: z.boolean().optional(),
}).meta({
ref: "UserMessage",
})
Expand Down Expand Up @@ -438,6 +439,7 @@ export namespace MessageV2 {
structured: z.any().optional(),
variant: z.string().optional(),
finish: z.string().optional(),
btw: z.boolean().optional(),
}).meta({
ref: "AssistantMessage",
})
Expand Down Expand Up @@ -555,8 +557,20 @@ export namespace MessageV2 {
return { type: "json", value: output as never }
}

// Pre-compute which btw user messages already have a response, so we can
// skip completed btw exchanges while still including any pending btw question
const answeredBtwUserIDs = new Set<string>()
for (const msg of input) {
if (msg.info.role === "assistant" && msg.info.btw) {
answeredBtwUserIDs.add((msg.info as Assistant).parentID)
}
}

for (const msg of input) {
if (msg.parts.length === 0) continue
// Skip completed btw pairs; pending btw question passes through so the model can answer it
if (msg.info.btw && msg.info.role === "assistant") continue
if (msg.info.btw && msg.info.role === "user" && answeredBtwUserIDs.has(msg.info.id)) continue

if (msg.info.role === "user") {
const userMessage: UIMessage = {
Expand Down
Loading
Loading