Skip to content

Commit b12845f

Browse files
committed
feat(tui): paint an editable home prompt before the TUI loads
`opencode` used to show a blank terminal for seconds while it loaded the CLI, the server worker, plugins and providers, and keys typed meanwhile were echoed by the tty and lost or turned into stray Enters. The home screen with a working prompt is now on screen within about 100 ms. boot.ts, the new compiled entrypoint, calls InstantPrompt.start() before it imports the CLI. For the plain TUI (and `--mini`) it puts the tty in raw mode, reads tui.json with plain file I/O, paints the home screen from the startup cache, and hands stdin to a worker thread (instant/worker.ts). The main thread cannot service stdin while it evaluates the rest of the CLI, which takes 0.3-1.7 s; the worker reads and paints keys as they are typed. Just before the renderer claims the terminal, the TUI awaits handover(): the worker stops and returns the prompt state and unparsed bytes, which are unshifted onto stdin. A box on the renderer root (component/instant-screen.ts) keeps drawing the same frame, independent of the providers that render nothing until they load, and the renderer feeds keys back in until the home Prompt mounts and claim()s the text, caret and selection (placed through cell offsets, instant/caret.ts). The prompt is a real editor (instant/editor.ts): every input_* keybind, including tui.json overrides, word-wrap layout, click-to-caret, drag selection, paste and undo. Its actions are checked against opentui's own TextareaRenderable from every caret position (editor.test.ts). Enter while loading queues the submit with a white "still loading" notice; once the TUI has resolved the agent, model and variant it submits only if they match what the screen showed, otherwise a red "not submitted" notice asks for Enter again. Without the screen (`startup.instant_prompt: false`, `--mini`) the same capture runs invisibly (`startup.early_input`). A line feed in the first read is an Enter typed before raw mode (ICRNL) and is dropped. The startup cache (agent, model, variant, colors, shortcuts, branch, tips height per directory) is written beside the database the process would open, `<db>.tui-startup.json`, so a different OPENCODE_DB, data directory or channel never shares it; the loading path does not open SQLite. DatabaseLocation and GlobalPath split the path logic out of database.ts and global.ts for that. Layout numbers the screen depends on moved to constants-only modules read by both sides: layout.ts (home and prompt geometry, placeholders, spinner, notices) and config/keybind-definitions.ts (keybind defaults). Measured with opencode-idle-bench ttp, --pure, desktop at load ~27: typable 114 ms median (85-145) against 4778 ms (3830-5515) before. AI-Tool: opencode 1.18.34-vt-128-907b3bc518 AI-Model: anthropic/claude-opus-5-5 AI-Variant: high AI-Platform: linux AI-Harness: Vibeterm cfa71a2 AI-Session-ID: ses_eebf9a83fffeIQQwW9gVFo5jaO
1 parent 08f08f6 commit b12845f

41 files changed

Lines changed: 3137 additions & 300 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/core/src/database/database.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import { layer as sqliteLayer } from "#sqlite"
55
import { Context, Effect, Layer } from "effect"
66
import { Global } from "../global"
77
import { Flag } from "../flag/flag"
8-
import { isAbsolute, join } from "path"
98
import { DatabaseMigration } from "./migration"
9+
import { DatabaseLocation } from "./location"
1010
import { InstallationChannel } from "../installation/version"
1111
import { makeGlobalNode } from "../effect/app-node"
1212
import { SessionMaintenance } from "./session-maintenance"
@@ -43,17 +43,12 @@ export function layerFromPath(filename: string) {
4343
}
4444

4545
export function path() {
46-
if (Flag.OPENCODE_DB) {
47-
if (Flag.OPENCODE_DB === ":memory:" || isAbsolute(Flag.OPENCODE_DB)) return Flag.OPENCODE_DB
48-
return join(Global.Path.data, Flag.OPENCODE_DB)
49-
}
50-
if (
51-
["latest", "beta", "prod"].includes(InstallationChannel) ||
52-
process.env.OPENCODE_DISABLE_CHANNEL_DB === "1" ||
53-
process.env.OPENCODE_DISABLE_CHANNEL_DB === "true"
54-
)
55-
return join(Global.Path.data, "opencode.db")
56-
return join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`)
46+
return DatabaseLocation.resolve({
47+
data: Global.Path.data,
48+
db: Flag.OPENCODE_DB,
49+
channel: InstallationChannel,
50+
disableChannelDb: process.env.OPENCODE_DISABLE_CHANNEL_DB,
51+
})
5752
}
5853

5954
export const node = makeGlobalNode({ service: Service, layer: layerFromPath(path()), deps: [] })
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
export * as DatabaseLocation from "./location"
2+
3+
import { isAbsolute, join } from "path"
4+
5+
// Where the database file lives for a data directory, an OPENCODE_DB value and
6+
// a release channel. Kept apart from database.ts so callers that only need the
7+
// path, like the instant startup prompt's cache, do not load SQLite.
8+
export function resolve(input: { data: string; db?: string; channel: string; disableChannelDb?: string }) {
9+
if (input.db) {
10+
if (input.db === ":memory:" || isAbsolute(input.db)) return input.db
11+
return join(input.data, input.db)
12+
}
13+
if (
14+
["latest", "beta", "prod"].includes(input.channel) ||
15+
input.disableChannelDb === "1" ||
16+
input.disableChannelDb === "true"
17+
)
18+
return join(input.data, "opencode.db")
19+
return join(input.data, `opencode-${input.channel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`)
20+
}

‎packages/core/src/global-path.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
export * as GlobalPath from "./global-path"
2+
3+
import path from "path"
4+
import os from "os"
5+
import { xdgData, xdgCache, xdgConfig, xdgState } from "xdg-basedir"
6+
7+
// The directories opencode keeps its files in, without global.ts's side
8+
// effects (directory creation, flock setup, Effect services). The instant
9+
// startup prompt reads these before the rest of the CLI loads.
10+
const app = "opencode"
11+
const data = path.join(xdgData!, app)
12+
const cache = path.join(xdgCache!, app)
13+
const config = path.join(xdgConfig!, app)
14+
const state = path.join(xdgState!, app)
15+
const tmp = path.join(os.tmpdir(), app)
16+
17+
export const paths = {
18+
get home() {
19+
return process.env.OPENCODE_TEST_HOME ?? os.homedir()
20+
},
21+
data,
22+
bin: path.join(cache, "bin"),
23+
log: path.join(data, "log"),
24+
repos: path.join(data, "repos"),
25+
cache,
26+
config,
27+
state,
28+
tmp,
29+
}

‎packages/core/src/global.ts‎

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,13 @@
1-
import path from "path"
21
import fs from "fs/promises"
3-
import { xdgData, xdgCache, xdgConfig, xdgState } from "xdg-basedir"
4-
import os from "os"
52
import { Context, Effect, Layer } from "effect"
63
import { Flock } from "./util/flock"
74
import { Flag } from "./flag/flag"
85
import { makeGlobalNode } from "./effect/app-node"
6+
import { GlobalPath } from "./global-path"
97

10-
const app = "opencode"
11-
const data = path.join(xdgData!, app)
12-
const cache = path.join(xdgCache!, app)
13-
const config = path.join(xdgConfig!, app)
14-
const state = path.join(xdgState!, app)
15-
const tmp = path.join(os.tmpdir(), app)
8+
export const Path = GlobalPath.paths
169

17-
const paths = {
18-
get home() {
19-
return process.env.OPENCODE_TEST_HOME ?? os.homedir()
20-
},
21-
data,
22-
bin: path.join(cache, "bin"),
23-
log: path.join(data, "log"),
24-
repos: path.join(data, "repos"),
25-
cache,
26-
config,
27-
state,
28-
tmp,
29-
}
30-
31-
export const Path = paths
32-
33-
Flock.setGlobal({ state })
10+
Flock.setGlobal({ state: Path.state })
3411

3512
await Promise.all([
3613
fs.mkdir(Path.data, { recursive: true }),

‎packages/opencode/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"bench:test": "bun run script/bench-test-suite.ts",
1313
"profile:test": "bun run script/profile-test-files.ts",
1414
"build": "bun run script/build.ts",
15-
"dev": "bun run ./src/index.ts",
15+
"dev": "bun run ./src/boot.ts",
1616
"dev:temporary": "bun run ./src/temporary.ts"
1717
},
1818
"bin": {

‎packages/opencode/script/build.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ for (const item of targets) {
157157
await $`mkdir -p dist/${name}/bin`
158158

159159
const workerPath = "./src/cli/tui/worker.ts"
160+
const instantWorkerPath = "./src/cli/instant-worker.ts"
160161
const treeSitterWorkerPath = "opentui-tree-sitter-worker.js"
161162
const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
162163

@@ -184,8 +185,9 @@ for (const item of targets) {
184185
...(embeddedFileMap ? { "opencode-web-ui.gen.ts": embeddedFileMap } : {}),
185186
},
186187
entrypoints: [
187-
"./src/index.ts",
188+
"./src/boot.ts",
188189
workerPath,
190+
instantWorkerPath,
189191
treeSitterWorkerPath,
190192
...(embeddedFileMap ? ["opencode-web-ui.gen.ts"] : []),
191193
],
@@ -195,6 +197,7 @@ for (const item of targets) {
195197
OPENCODE_MODELS_DEV: generated.modelsData,
196198
OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + treeSitterWorkerPath,
197199
OPENCODE_WORKER_PATH: workerPath,
200+
OPENCODE_INSTANT_WORKER_PATH: JSON.stringify(instantWorkerPath),
198201
OPENCODE_CHANNEL: `'${Script.channel}'`,
199202
...(process.env.OPENCODE_INSTALL_METHOD
200203
? { OPENCODE_INSTALL_METHOD: JSON.stringify(process.env.OPENCODE_INSTALL_METHOD) }

‎packages/opencode/src/boot.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { InstantPrompt } from "@opencode-ai/tui/instant"
2+
3+
// Paint the instant startup prompt and start capturing keys before the rest of
4+
// the CLI is loaded; the dynamic import keeps that load out of this module.
5+
InstantPrompt.start()
6+
await import("./index")

‎packages/opencode/src/cli/cmd/run/footer.prompt.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import {
2424
pushPromptHistory,
2525
} from "./prompt.shared"
2626
import { OPENCODE_BASE_MODE, useBindings } from "@opencode-ai/tui/keymap"
27+
import { InstantPrompt } from "@opencode-ai/tui/instant"
28+
import { InstantCaret } from "@opencode-ai/tui/instant/caret"
2729
import { realignEditorPromptParts, resolveEditorSlashValue } from "./prompt.editor"
2830
import { FOOTER_MENU_ROWS, createFooterMenuState, type RunFooterMenuItem } from "./footer.menu"
2931
import type { RunFooterTheme } from "./theme"
@@ -706,12 +708,15 @@ export function createPromptState(input: PromptInput): PromptState {
706708
type = area.extmarks.registerType("run-direct-prompt-part")
707709
}
708710
area.on("line-info-change", scheduleRows)
711+
const early = InstantPrompt.claim()
712+
if (early?.text) draft = { text: early.text, parts: [] }
709713
queueMicrotask(() => {
710714
if (!area || area.isDestroyed || !input.prompt()) {
711715
return
712716
}
713717

714718
restore(draft)
719+
if (early?.text) InstantCaret.place(area, early.caret, early.selection)
715720
refresh()
716721
})
717722
}

‎packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
1414
import { Global } from "@opencode-ai/core/global"
1515
import { openEditor } from "@opencode-ai/tui/editor"
1616
import { registerOpencodeKeymap } from "@opencode-ai/tui/keymap"
17+
import { InstantPrompt } from "@opencode-ai/tui/instant"
1718
import { Session as SessionApi } from "@/session/session"
1819
import * as Locale from "@/util/locale"
1920
import { resolveInteractiveStdin } from "./runtime.stdin"
@@ -178,6 +179,7 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lif
178179
let unregisterKeymap: (() => void) | undefined
179180

180181
try {
182+
await InstantPrompt.handover()
181183
const renderer = await createCliRenderer({
182184
stdin: source.stdin,
183185
targetFps: 30,
@@ -193,6 +195,19 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lif
193195
consoleMode: "disabled",
194196
clearOnShutdown: false,
195197
})
198+
// Keys typed while the footer prompt loads keep going to the early input
199+
// capture until the prompt claims them.
200+
if (InstantPrompt.active()) {
201+
InstantPrompt.attach({
202+
render() {},
203+
exit() {
204+
renderer.destroy()
205+
process.exit(0)
206+
},
207+
ended: () => renderer.removeInputHandler(InstantPrompt.feed),
208+
})
209+
renderer.prependInputHandler(InstantPrompt.feed)
210+
}
196211
const theme = await resolveRunTheme(renderer)
197212
renderer.setBackgroundColor(theme.background)
198213
const keymap = createDefaultOpenTuiKeymap(renderer)

0 commit comments

Comments
 (0)