Skip to content

Commit 5c9c635

Browse files
feat(tui): add Ctrl+R prompt history search
- Add history_search keybind (ctrl+r) for reverse-i-search - Move session_rename to <leader>R to avoid conflict - Add search() method to history store with fuzzysort - Create DialogHistorySearch component Closes anomalyco#5062
1 parent 9adcf52 commit 5c9c635

5 files changed

Lines changed: 321 additions & 146 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Global } from "@/global"
33
import { onMount } from "solid-js"
44
import { createStore, produce } from "solid-js/store"
55
import { clone } from "remeda"
6+
import * as fuzzysort from "fuzzysort"
67
import { createSimpleContext } from "../../context/helper"
78
import { appendFile, writeFile } from "fs/promises"
89
import type { AgentPart, FilePart, TextPart } from "@opencode-ai/sdk/v2"
@@ -14,14 +15,14 @@ export type PromptInfo = {
1415
| Omit<FilePart, "id" | "messageID" | "sessionID">
1516
| Omit<AgentPart, "id" | "messageID" | "sessionID">
1617
| (Omit<TextPart, "id" | "messageID" | "sessionID"> & {
17-
source?: {
18-
text: {
19-
start: number
20-
end: number
21-
value: string
22-
}
18+
source?: {
19+
text: {
20+
start: number
21+
end: number
22+
value: string
2323
}
24-
})
24+
}
25+
})
2526
)[]
2627
}
2728

@@ -51,7 +52,7 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
5152
// Rewrite file with only valid entries to self-heal corruption
5253
if (lines.length > 0) {
5354
const content = lines.map((line) => JSON.stringify(line)).join("\n") + "\n"
54-
writeFile(historyFile.name!, content).catch(() => {})
55+
writeFile(historyFile.name!, content).catch(() => { })
5556
}
5657
})
5758

@@ -97,11 +98,18 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
9798

9899
if (trimmed) {
99100
const content = store.history.map((line) => JSON.stringify(line)).join("\n") + "\n"
100-
writeFile(historyFile.name!, content).catch(() => {})
101+
writeFile(historyFile.name!, content).catch(() => { })
101102
return
102103
}
103104

104-
appendFile(historyFile.name!, JSON.stringify(entry) + "\n").catch(() => {})
105+
appendFile(historyFile.name!, JSON.stringify(entry) + "\n").catch(() => { })
106+
},
107+
search(query: string): PromptInfo[] {
108+
const items = store.history.slice().reverse()
109+
if (!query.trim()) return items
110+
return fuzzysort
111+
.go(query, items, { key: "input" })
112+
.map((r) => r.obj) as PromptInfo[]
105113
},
106114
}
107115
},

‎packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { useToast } from "../../ui/toast"
3232
import { useKV } from "../../context/kv"
3333
import { useTextareaKeybindings } from "../textarea-keybindings"
3434
import { DialogSkill } from "../dialog-skill"
35+
import { DialogHistorySearch } from "../../ui/dialog-history-search"
3536

3637
export type PromptProps = {
3738
sessionID?: string
@@ -529,9 +530,9 @@ export function Prompt(props: PromptProps) {
529530
const sessionID = props.sessionID
530531
? props.sessionID
531532
: await (async () => {
532-
const sessionID = await sdk.client.session.create({}).then((x) => x.data!.id)
533-
return sessionID
534-
})()
533+
const sessionID = await sdk.client.session.create({}).then((x) => x.data!.id)
534+
return sessionID
535+
})()
535536
const messageID = Identifier.ascending("message")
536537
let inputText = store.prompt.input
537538

@@ -620,7 +621,7 @@ export function Prompt(props: PromptProps) {
620621
})),
621622
],
622623
})
623-
.catch(() => {})
624+
.catch(() => { })
624625
}
625626
history.append({
626627
...store.prompt,
@@ -885,6 +886,23 @@ export function Prompt(props: PromptProps) {
885886
if (keybind.match("history_previous", e) && input.visualCursor.visualRow === 0) input.cursorOffset = 0
886887
if (keybind.match("history_next", e) && input.visualCursor.visualRow === input.height - 1)
887888
input.cursorOffset = input.plainText.length
889+
890+
if (keybind.match("history_search", e)) {
891+
e.preventDefault()
892+
dialog.replace(() => (
893+
<DialogHistorySearch
894+
searchHistory={(query) => history.search(query)}
895+
onSelect={(item) => {
896+
input.setText(item.input)
897+
setStore("prompt", item)
898+
setStore("mode", item.mode ?? "normal")
899+
restoreExtmarksFromParts(item.parts)
900+
input.cursorOffset = input.plainText.length
901+
}}
902+
/>
903+
))
904+
return
905+
}
888906
}
889907
}}
890908
onSubmit={submit}
@@ -914,7 +932,7 @@ export function Prompt(props: PromptProps) {
914932
// Handle SVG as raw text content, not as base64 image
915933
if (file.type === "image/svg+xml") {
916934
event.preventDefault()
917-
const content = await file.text().catch(() => {})
935+
const content = await file.text().catch(() => { })
918936
if (content) {
919937
pasteText(content, `[SVG: ${file.name ?? "image"}]`)
920938
return
@@ -925,7 +943,7 @@ export function Prompt(props: PromptProps) {
925943
const content = await file
926944
.arrayBuffer()
927945
.then((buffer) => Buffer.from(buffer).toString("base64"))
928-
.catch(() => {})
946+
.catch(() => { })
929947
if (content) {
930948
await pasteImage({
931949
filename: file.name,
@@ -935,7 +953,7 @@ export function Prompt(props: PromptProps) {
935953
return
936954
}
937955
}
938-
} catch {}
956+
} catch { }
939957
}
940958

941959
const lineCount = (pastedContent.match(/\n/g)?.length ?? 0) + 1
@@ -1010,13 +1028,13 @@ export function Prompt(props: PromptProps) {
10101028
customBorderChars={
10111029
theme.backgroundElement.a !== 0
10121030
? {
1013-
...EmptyBorder,
1014-
horizontal: "▀",
1015-
}
1031+
...EmptyBorder,
1032+
horizontal: "▀",
1033+
}
10161034
: {
1017-
...EmptyBorder,
1018-
horizontal: " ",
1019-
}
1035+
...EmptyBorder,
1036+
horizontal: " ",
1037+
}
10201038
}
10211039
/>
10221040
</box>
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import { TextAttributes } from "@opentui/core"
2+
import { useTheme, selectedForeground } from "@tui/context/theme"
3+
import { createMemo, For, Show } from "solid-js"
4+
import { createStore } from "solid-js/store"
5+
import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
6+
import { useDialog } from "@tui/ui/dialog"
7+
import type { PromptInfo } from "@tui/component/prompt/history"
8+
import { Locale } from "@/util/locale"
9+
10+
export interface DialogHistorySearchProps {
11+
onSelect: (item: PromptInfo) => void
12+
searchHistory: (query: string) => PromptInfo[]
13+
}
14+
15+
export function DialogHistorySearch(props: DialogHistorySearchProps) {
16+
const dialog = useDialog()
17+
const { theme } = useTheme()
18+
const [store, setStore] = createStore({
19+
selected: 0,
20+
filter: "",
21+
})
22+
23+
const filtered = createMemo(() => props.searchHistory(store.filter))
24+
25+
const dimensions = useTerminalDimensions()
26+
const height = createMemo(() => Math.min(filtered().length, Math.floor(dimensions().height / 2) - 6))
27+
28+
const selected = createMemo(() => filtered()[store.selected])
29+
30+
function move(direction: number) {
31+
if (filtered().length === 0) return
32+
let next = store.selected + direction
33+
if (next < 0) next = filtered().length - 1
34+
if (next >= filtered().length) next = 0
35+
setStore("selected", next)
36+
}
37+
38+
useKeyboard((evt) => {
39+
if (evt.name === "up" || (evt.ctrl && evt.name === "p") || (evt.ctrl && evt.name === "r")) move(-1)
40+
if (evt.name === "down" || (evt.ctrl && evt.name === "n")) move(1)
41+
if (evt.name === "pageup") move(-10)
42+
if (evt.name === "pagedown") move(10)
43+
44+
if (evt.name === "return") {
45+
const item = selected()
46+
if (item) {
47+
evt.preventDefault()
48+
evt.stopPropagation()
49+
dialog.clear()
50+
props.onSelect(item)
51+
}
52+
}
53+
})
54+
55+
return (
56+
<box gap={1} paddingBottom={1}>
57+
<box paddingLeft={4} paddingRight={4}>
58+
<box flexDirection="row" justifyContent="space-between">
59+
<text fg={theme.text} attributes={TextAttributes.BOLD}>
60+
Search History
61+
</text>
62+
<text fg={theme.textMuted}>esc</text>
63+
</box>
64+
<box paddingTop={1}>
65+
<input
66+
onInput={(e) => {
67+
setStore("filter", e)
68+
setStore("selected", 0)
69+
}}
70+
focusedBackgroundColor={theme.backgroundPanel}
71+
cursorColor={theme.primary}
72+
focusedTextColor={theme.textMuted}
73+
ref={(r) => {
74+
setTimeout(() => {
75+
if (!r || r.isDestroyed) return
76+
r.focus()
77+
}, 1)
78+
}}
79+
placeholder="(reverse-i-search)"
80+
/>
81+
</box>
82+
</box>
83+
<Show
84+
when={filtered().length > 0}
85+
fallback={
86+
<box paddingLeft={4} paddingRight={4} paddingTop={1}>
87+
<text fg={theme.textMuted}>No history found</text>
88+
</box>
89+
}
90+
>
91+
<scrollbox
92+
paddingLeft={1}
93+
paddingRight={1}
94+
scrollbarOptions={{ visible: false }}
95+
maxHeight={height()}
96+
>
97+
<For each={filtered()}>
98+
{(item, index) => {
99+
const active = createMemo(() => index() === store.selected)
100+
const fg = selectedForeground(theme)
101+
return (
102+
<box
103+
flexDirection="row"
104+
backgroundColor={active() ? theme.primary : undefined}
105+
paddingLeft={3}
106+
paddingRight={3}
107+
onMouseUp={() => {
108+
dialog.clear()
109+
props.onSelect(item)
110+
}}
111+
onMouseOver={() => setStore("selected", index())}
112+
>
113+
<text
114+
flexGrow={1}
115+
fg={active() ? fg : theme.text}
116+
attributes={active() ? TextAttributes.BOLD : undefined}
117+
overflow="hidden"
118+
wrapMode="none"
119+
>
120+
{Locale.truncate(item.input.replace(/\n/g, " "), 70)}
121+
</text>
122+
</box>
123+
)
124+
}}
125+
</For>
126+
</scrollbox>
127+
</Show>
128+
<box paddingRight={2} paddingLeft={4} flexDirection="row" gap={2} flexShrink={0} paddingTop={1}>
129+
<text>
130+
<span style={{ fg: theme.text }}>
131+
<b>Select</b>{" "}
132+
</span>
133+
<span style={{ fg: theme.textMuted }}>Enter</span>
134+
</text>
135+
<text>
136+
<span style={{ fg: theme.text }}>
137+
<b>Next</b>{" "}
138+
</span>
139+
<span style={{ fg: theme.textMuted }}>Ctrl+R</span>
140+
</text>
141+
</box>
142+
</box>
143+
)
144+
}

‎packages/opencode/src/config/config.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,12 @@ export namespace Config {
122122
// Only scan project .opencode/ directories when project discovery is enabled
123123
...(!Flag.OPENCODE_DISABLE_PROJECT_CONFIG
124124
? await Array.fromAsync(
125-
Filesystem.up({
126-
targets: [".opencode"],
127-
start: Instance.directory,
128-
stop: Instance.worktree,
129-
}),
130-
)
125+
Filesystem.up({
126+
targets: [".opencode"],
127+
start: Instance.directory,
128+
stop: Instance.worktree,
129+
}),
130+
)
131131
: []),
132132
// Always scan ~/.opencode/ (user home directory)
133133
...(await Array.fromAsync(
@@ -767,7 +767,7 @@ export namespace Config {
767767
session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
768768
session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
769769
session_fork: z.string().optional().default("none").describe("Fork session from message"),
770-
session_rename: z.string().optional().default("ctrl+r").describe("Rename session"),
770+
session_rename: z.string().optional().default("<leader>R").describe("Rename session"),
771771
session_delete: z.string().optional().default("ctrl+d").describe("Delete session"),
772772
stash_delete: z.string().optional().default("ctrl+d").describe("Delete stash entry"),
773773
model_provider_list: z.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),
@@ -897,6 +897,7 @@ export namespace Config {
897897
.describe("Delete word backward in input"),
898898
history_previous: z.string().optional().default("up").describe("Previous history item"),
899899
history_next: z.string().optional().default("down").describe("Next history item"),
900+
history_search: z.string().optional().default("ctrl+r").describe("Search prompt history"),
900901
session_child_cycle: z.string().optional().default("<leader>right").describe("Next child session"),
901902
session_child_cycle_reverse: z.string().optional().default("<leader>left").describe("Previous child session"),
902903
session_parent: z.string().optional().default("<leader>up").describe("Go to parent session"),
@@ -1210,7 +1211,7 @@ export namespace Config {
12101211
await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
12111212
await fs.unlink(legacy)
12121213
})
1213-
.catch(() => {})
1214+
.catch(() => { })
12141215
}
12151216

12161217
return result
@@ -1301,15 +1302,15 @@ export namespace Config {
13011302
parsed.data.$schema = "https://opencode.ai/config.json"
13021303
// Write the $schema to the original text to preserve variables like {env:VAR}
13031304
const updated = original.replace(/^\s*\{/, '{\n "$schema": "https://opencode.ai/config.json",')
1304-
await Bun.write(configFilepath, updated).catch(() => {})
1305+
await Bun.write(configFilepath, updated).catch(() => { })
13051306
}
13061307
const data = parsed.data
13071308
if (data.plugin) {
13081309
for (let i = 0; i < data.plugin.length; i++) {
13091310
const plugin = data.plugin[i]
13101311
try {
13111312
data.plugin[i] = import.meta.resolve!(plugin, configFilepath)
1312-
} catch (err) {}
1313+
} catch (err) { }
13131314
}
13141315
}
13151316
return data

0 commit comments

Comments
 (0)