Compare commits

..

2 Commits

Author SHA1 Message Date
Kit Langton
58a8d4dbf5 refactor(opencode): remove AppRuntime from tui file io 2026-04-15 12:40:11 -04:00
Kit Langton
d8070f7f23 refactor(opencode): move tui state io to AppFileSystem 2026-04-15 11:27:54 -04:00
11 changed files with 80 additions and 144 deletions

View File

@@ -1,10 +1,9 @@
import path from "path"
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
import { onMount } from "solid-js"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "../../context/helper"
import { appendFile, writeFile } from "fs/promises"
import { appendFile } from "fs/promises"
function calculateFrecency(entry?: { frequency: number; lastOpen: number }): number {
if (!entry) return 0
@@ -20,7 +19,9 @@ export const { use: useFrecency, provider: FrecencyProvider } = createSimpleCont
init: () => {
const frecencyPath = path.join(Global.Path.state, "frecency.jsonl")
onMount(async () => {
const text = await Filesystem.readText(frecencyPath).catch(() => "")
const text = await Bun.file(frecencyPath)
.text()
.catch(() => "")
const lines = text
.split("\n")
.filter(Boolean)
@@ -54,7 +55,7 @@ export const { use: useFrecency, provider: FrecencyProvider } = createSimpleCont
if (sorted.length > 0) {
const content = sorted.map((entry) => JSON.stringify(entry)).join("\n") + "\n"
writeFile(frecencyPath, content).catch(() => {})
void Bun.write(frecencyPath, content)
}
})
@@ -77,7 +78,7 @@ export const { use: useFrecency, provider: FrecencyProvider } = createSimpleCont
.slice(0, MAX_FRECENCY_ENTRIES)
setStore("data", Object.fromEntries(sorted))
const content = sorted.map(([path, entry]) => JSON.stringify({ path, ...entry })).join("\n") + "\n"
writeFile(frecencyPath, content).catch(() => {})
void Bun.write(frecencyPath, content)
}
}

View File

@@ -1,10 +1,9 @@
import path from "path"
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
import { onMount } from "solid-js"
import { createStore, produce, unwrap } from "solid-js/store"
import { createSimpleContext } from "../../context/helper"
import { appendFile, writeFile } from "fs/promises"
import { appendFile } from "fs/promises"
import type { AgentPart, FilePart, TextPart } from "@opencode-ai/sdk/v2"
export type PromptInfo = {
@@ -32,7 +31,9 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
init: () => {
const historyPath = path.join(Global.Path.state, "prompt-history.jsonl")
onMount(async () => {
const text = await Filesystem.readText(historyPath).catch(() => "")
const text = await Bun.file(historyPath)
.text()
.catch(() => "")
const lines = text
.split("\n")
.filter(Boolean)
@@ -51,7 +52,7 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
// Rewrite file with only valid entries to self-heal corruption
if (lines.length > 0) {
const content = lines.map((line) => JSON.stringify(line)).join("\n") + "\n"
writeFile(historyPath, content).catch(() => {})
void Bun.write(historyPath, content)
}
})
@@ -97,7 +98,7 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
if (trimmed) {
const content = store.history.map((line) => JSON.stringify(line)).join("\n") + "\n"
writeFile(historyPath, content).catch(() => {})
void Bun.write(historyPath, content)
return
}

View File

@@ -1,10 +1,9 @@
import path from "path"
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
import { onMount } from "solid-js"
import { createStore, produce, unwrap } from "solid-js/store"
import { createSimpleContext } from "../../context/helper"
import { appendFile, writeFile } from "fs/promises"
import { appendFile } from "fs/promises"
import type { PromptInfo } from "./history"
export type StashEntry = {
@@ -20,7 +19,9 @@ export const { use: usePromptStash, provider: PromptStashProvider } = createSimp
init: () => {
const stashPath = path.join(Global.Path.state, "prompt-stash.jsonl")
onMount(async () => {
const text = await Filesystem.readText(stashPath).catch(() => "")
const text = await Bun.file(stashPath)
.text()
.catch(() => "")
const lines = text
.split("\n")
.filter(Boolean)
@@ -39,7 +40,7 @@ export const { use: usePromptStash, provider: PromptStashProvider } = createSimp
// Rewrite file with only valid entries to self-heal corruption
if (lines.length > 0) {
const content = lines.map((line) => JSON.stringify(line)).join("\n") + "\n"
writeFile(stashPath, content).catch(() => {})
void Bun.write(stashPath, content)
}
})
@@ -66,7 +67,7 @@ export const { use: usePromptStash, provider: PromptStashProvider } = createSimp
if (trimmed) {
const content = store.entries.map((line) => JSON.stringify(line)).join("\n") + "\n"
writeFile(stashPath, content).catch(() => {})
void Bun.write(stashPath, content)
return
}
@@ -82,7 +83,7 @@ export const { use: usePromptStash, provider: PromptStashProvider } = createSimp
)
const content =
store.entries.length > 0 ? store.entries.map((line) => JSON.stringify(line)).join("\n") + "\n" : ""
writeFile(stashPath, content).catch(() => {})
void Bun.write(stashPath, content)
return entry
},
remove(index: number) {
@@ -94,7 +95,7 @@ export const { use: usePromptStash, provider: PromptStashProvider } = createSimp
)
const content =
store.entries.length > 0 ? store.entries.map((line) => JSON.stringify(line)).join("\n") + "\n" : ""
writeFile(stashPath, content).catch(() => {})
void Bun.write(stashPath, content)
},
}
},

View File

@@ -1,5 +1,4 @@
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
import { createSignal, type Setter } from "solid-js"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "./helper"
@@ -12,9 +11,10 @@ export const { use: useKV, provider: KVProvider } = createSimpleContext({
const [store, setStore] = createStore<Record<string, any>>()
const filePath = path.join(Global.Path.state, "kv.json")
Filesystem.readJson(filePath)
Bun.file(filePath)
.json()
.then((x) => {
setStore(x)
if (typeof x === "object" && x !== null) setStore(x as Record<string, any>)
})
.catch(() => {})
.finally(() => {
@@ -44,7 +44,7 @@ export const { use: useKV, provider: KVProvider } = createSimpleContext({
},
set(key: string, value: any) {
setStore(key, value)
Filesystem.writeJson(filePath, store)
void Bun.write(filePath, JSON.stringify(store, null, 2))
},
}
return result

View File

@@ -12,7 +12,6 @@ import { Provider } from "@/provider/provider"
import { useArgs } from "./args"
import { useSDK } from "./sdk"
import { RGBA } from "@opentui/core"
import { Filesystem } from "@/util/filesystem"
export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
name: "Local",
@@ -131,14 +130,22 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
return
}
state.pending = false
Filesystem.writeJson(filePath, {
recent: modelStore.recent,
favorite: modelStore.favorite,
variant: modelStore.variant,
})
void Bun.write(
filePath,
JSON.stringify(
{
recent: modelStore.recent,
favorite: modelStore.favorite,
variant: modelStore.variant,
},
null,
2,
),
)
}
Filesystem.readJson(filePath)
Bun.file(filePath)
.json()
.then((x: any) => {
if (Array.isArray(x.recent)) setModelStore("recent", x.recent)
if (Array.isArray(x.favorite)) setModelStore("favorite", x.favorite)

View File

@@ -1,6 +1,5 @@
import { CliRenderEvents, SyntaxStyle, RGBA, type TerminalColors } from "@opentui/core"
import path from "path"
import { existsSync } from "fs"
import { createEffect, createMemo, onCleanup, onMount } from "solid-js"
import { createSimpleContext } from "./helper"
import { Glob } from "@opencode-ai/shared/util/glob"
@@ -41,6 +40,7 @@ import { useKV } from "./kv"
import { useRenderer } from "@opentui/solid"
import { createStore, produce } from "solid-js/store"
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
import { useTuiConfig } from "./tui-config"
import { isRecord } from "@/util/record"
import type { TuiThemeCurrent } from "@opencode-ai/plugin/tui"
@@ -477,19 +477,15 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
})
async function getCustomThemes() {
const ups = (start: string) => {
const out: string[] = []
let dir = start
while (true) {
const next = path.join(dir, ".opencode")
if (existsSync(next)) out.push(next)
const parent = path.dirname(dir)
if (parent === dir) return out
dir = parent
}
}
const directories = [Global.Path.config, ...ups(process.cwd())]
const directories = [
Global.Path.config,
...(await Array.fromAsync(
Filesystem.up({
targets: [".opencode"],
start: process.cwd(),
}),
)),
]
const result: Record<string, ThemeJson> = {}
for (const dir of directories) {
@@ -500,7 +496,7 @@ async function getCustomThemes() {
symlink: true,
})) {
const name = path.basename(item, ".json")
result[name] = (await Bun.file(item).json()) as ThemeJson
result[name] = await Filesystem.readJson(item)
}
}
return result

View File

@@ -74,8 +74,8 @@ import { Editor } from "../../util/editor"
import stripAnsi from "strip-ansi"
import { usePromptRef } from "../../context/prompt"
import { useExit } from "../../context/exit"
import { Filesystem } from "@/util/filesystem"
import { Global } from "@/global"
import { AppFileSystem } from "@opencode-ai/shared/filesystem"
import { PermissionPrompt } from "./permission"
import { QuestionPrompt } from "./question"
import { DialogExportOptions } from "../../ui/dialog-export-options"
@@ -916,12 +916,12 @@ export function Session() {
const filename = options.filename.trim()
const filepath = path.join(exportDir, filename)
await Filesystem.write(filepath, transcript)
await Bun.write(filepath, transcript)
// Open with EDITOR if available
const result = await Editor.open({ value: transcript, renderer })
if (result !== undefined) {
await Filesystem.write(filepath, result)
await Bun.write(filepath, result)
}
toast.show({ message: `Session exported to ${filename}`, variant: "success" })
@@ -2236,7 +2236,7 @@ function Skill(props: ToolProps<typeof SkillTool>) {
function Diagnostics(props: { diagnostics?: Record<string, Record<string, any>[]>; filePath: string }) {
const { theme } = useTheme()
const errors = createMemo(() => {
const normalized = Filesystem.normalizePath(props.filePath)
const normalized = AppFileSystem.normalizePath(props.filePath)
const arr = props.diagnostics?.[normalized] ?? []
return arr.filter((x) => x.severity === 1).slice(0, 3)
})

View File

@@ -4,7 +4,6 @@ import { lazy } from "../../../../util/lazy.js"
import { tmpdir } from "os"
import path from "path"
import fs from "fs/promises"
import { Filesystem } from "../../../../util/filesystem"
import { Process } from "../../../../util/process"
import { which } from "../../../../util/which"
@@ -58,8 +57,7 @@ export namespace Clipboard {
],
{ nothrow: true },
)
const buffer = await Filesystem.readBytes(tmpfile)
return { data: buffer.toString("base64"), mime: "image/png" }
return { data: Buffer.from(await Bun.file(tmpfile).arrayBuffer()).toString("base64"), mime: "image/png" }
} catch {
} finally {
await fs.rm(tmpfile, { force: true }).catch(() => {})

View File

@@ -3,7 +3,6 @@ import { rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { CliRenderer } from "@opentui/core"
import { Filesystem } from "@/util/filesystem"
import { Process } from "@/util/process"
export namespace Editor {
@@ -14,7 +13,7 @@ export namespace Editor {
const filepath = join(tmpdir(), `${Date.now()}.md`)
await using _ = defer(async () => rm(filepath, { force: true }))
await Filesystem.write(filepath, opts.value)
await Bun.write(filepath, opts.value)
opts.renderer.suspend()
opts.renderer.currentRenderBuffer.clear()
try {
@@ -26,7 +25,7 @@ export namespace Editor {
shell: process.platform === "win32",
})
await proc.exited
const content = await Filesystem.readText(filepath)
const content = await Bun.file(filepath).text()
return content || undefined
} finally {
opts.renderer.currentRenderBuffer.clear()

View File

@@ -2,74 +2,30 @@ import path from "path"
import os from "os"
import z from "zod"
import { type ParseError as JsoncParseError, parse as parseJsonc, printParseErrorCode } from "jsonc-parser"
import { Effect } from "effect"
import { AppFileSystem } from "@opencode-ai/shared/filesystem"
import { NamedError } from "@opencode-ai/shared/util/error"
import { Filesystem } from "@/util/filesystem"
import { Flag } from "@/flag/flag"
import { Global } from "@/global"
import { AppRuntime } from "@/effect/app-runtime"
async function withFs<A>(fn: (fs: AppFileSystem.Interface) => Effect.Effect<A, AppFileSystem.Error>) {
return AppRuntime.runPromise(
Effect.gen(function* () {
const fs = yield* AppFileSystem.Service
return yield* fn(fs)
}),
)
}
function missing(err: unknown) {
if (typeof err !== "object" || err === null) return false
if ("code" in err && err.code === "ENOENT") return true
return (
"reason" in err &&
typeof err.reason === "object" &&
err.reason !== null &&
"_tag" in err.reason &&
err.reason._tag === "NotFound"
)
}
export namespace ConfigPaths {
export async function projectFiles(name: string, directory: string, worktree: string) {
return withFs(
Effect.fn("ConfigPaths.projectFiles")(function* (fs) {
const dirs = [directory]
let dir = directory
while (true) {
if (worktree === dir) break
const parent = path.dirname(dir)
if (parent === dir) break
dirs.push(parent)
dir = parent
}
const out: string[] = []
for (const dir of dirs.toReversed()) {
for (const target of [`${name}.json`, `${name}.jsonc`]) {
const file = path.join(dir, target)
if (yield* fs.existsSafe(file)) out.push(file)
}
}
return out
}),
)
return Filesystem.findUp([`${name}.json`, `${name}.jsonc`], directory, worktree, { rootFirst: true })
}
export async function directories(directory: string, worktree: string) {
return [
Global.Path.config,
...(!Flag.OPENCODE_DISABLE_PROJECT_CONFIG
? await withFs((fs) =>
fs.up({
? await Array.fromAsync(
Filesystem.up({
targets: [".opencode"],
start: directory,
stop: worktree,
}),
)
: []),
...(await withFs((fs) =>
fs.up({
...(await Array.fromAsync(
Filesystem.up({
targets: [".opencode"],
start: Global.Path.home,
stop: Global.Path.home,
@@ -102,8 +58,8 @@ export namespace ConfigPaths {
/** Read a config file, returning undefined for missing files and throwing JsonError for other failures. */
export async function readFile(filepath: string) {
return withFs((fs) => fs.readFileString(filepath)).catch((err: unknown) => {
if (missing(err)) return
return Filesystem.readText(filepath).catch((err: NodeJS.ErrnoException) => {
if (err.code === "ENOENT") return
throw new JsonError({ path: filepath }, { cause: err })
})
}
@@ -152,11 +108,11 @@ export namespace ConfigPaths {
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
const fileContent = (
await withFs((fs) => fs.readFileString(resolvedPath)).catch((error: unknown) => {
await Filesystem.readText(resolvedPath).catch((error: NodeJS.ErrnoException) => {
if (missing === "empty") return ""
const errMsg = `bad file reference: "${token}"`
if (missing(error)) {
if (error.code === "ENOENT") {
throw new InvalidError(
{
path: configSource,

View File

@@ -1,33 +1,10 @@
import { Effect } from "effect"
import { AppFileSystem } from "@opencode-ai/shared/filesystem"
import { Npm } from "../npm"
import { Instance } from "../project/instance"
import { Filesystem } from "../util/filesystem"
import { Process } from "../util/process"
import { which } from "../util/which"
import { AppRuntime } from "@/effect/app-runtime"
import { Flag } from "@/flag/flag"
async function withFs<A>(fn: (fs: AppFileSystem.Interface) => Effect.Effect<A, AppFileSystem.Error>) {
return AppRuntime.runPromise(
Effect.gen(function* () {
const fs = yield* AppFileSystem.Service
return yield* fn(fs)
}),
)
}
async function find(target: string) {
return withFs((fs) => fs.findUp(target, Instance.directory, Instance.worktree))
}
async function readJson<T>(file: string) {
return withFs((fs) => fs.readJson(file).pipe(Effect.map((json) => json as T)))
}
async function readText(file: string) {
return withFs((fs) => fs.readFileString(file))
}
export interface Info {
name: string
environment?: Record<string, string>
@@ -89,9 +66,9 @@ export const prettier: Info = {
".gql",
],
async enabled() {
const items = await find("package.json")
const items = await Filesystem.findUp("package.json", Instance.directory, Instance.worktree)
for (const item of items) {
const json = await readJson<{
const json = await Filesystem.readJson<{
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
}>(item)
@@ -112,9 +89,9 @@ export const oxfmt: Info = {
extensions: [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"],
async enabled() {
if (!Flag.OPENCODE_EXPERIMENTAL_OXFMT) return false
const items = await find("package.json")
const items = await Filesystem.findUp("package.json", Instance.directory, Instance.worktree)
for (const item of items) {
const json = await readJson<{
const json = await Filesystem.readJson<{
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
}>(item)
@@ -163,7 +140,7 @@ export const biome: Info = {
async enabled() {
const configs = ["biome.json", "biome.jsonc"]
for (const config of configs) {
const found = await find(config)
const found = await Filesystem.findUp(config, Instance.directory, Instance.worktree)
if (found.length > 0) {
const bin = await Npm.which("@biomejs/biome")
if (bin) return [bin, "format", "--write", "$FILE"]
@@ -187,7 +164,7 @@ export const clang: Info = {
name: "clang-format",
extensions: [".c", ".cc", ".cpp", ".cxx", ".c++", ".h", ".hh", ".hpp", ".hxx", ".h++", ".ino", ".C", ".H"],
async enabled() {
const items = await find(".clang-format")
const items = await Filesystem.findUp(".clang-format", Instance.directory, Instance.worktree)
if (items.length > 0) {
const match = which("clang-format")
if (match) return [match, "-i", "$FILE"]
@@ -213,10 +190,10 @@ export const ruff: Info = {
if (!which("ruff")) return false
const configs = ["pyproject.toml", "ruff.toml", ".ruff.toml"]
for (const config of configs) {
const found = await find(config)
const found = await Filesystem.findUp(config, Instance.directory, Instance.worktree)
if (found.length > 0) {
if (config === "pyproject.toml") {
const content = await readText(found[0])
const content = await Filesystem.readText(found[0])
if (content.includes("[tool.ruff]")) return ["ruff", "format", "$FILE"]
} else {
return ["ruff", "format", "$FILE"]
@@ -225,9 +202,9 @@ export const ruff: Info = {
}
const deps = ["requirements.txt", "pyproject.toml", "Pipfile"]
for (const dep of deps) {
const found = await find(dep)
const found = await Filesystem.findUp(dep, Instance.directory, Instance.worktree)
if (found.length > 0) {
const content = await readText(found[0])
const content = await Filesystem.readText(found[0])
if (content.includes("ruff")) return ["ruff", "format", "$FILE"]
}
}
@@ -311,7 +288,7 @@ export const ocamlformat: Info = {
extensions: [".ml", ".mli"],
async enabled() {
if (!which("ocamlformat")) return false
const items = await find(".ocamlformat")
const items = await Filesystem.findUp(".ocamlformat", Instance.directory, Instance.worktree)
if (items.length > 0) return ["ocamlformat", "-i", "$FILE"]
return false
},
@@ -381,9 +358,9 @@ export const pint: Info = {
name: "pint",
extensions: [".php"],
async enabled() {
const items = await find("composer.json")
const items = await Filesystem.findUp("composer.json", Instance.directory, Instance.worktree)
for (const item of items) {
const json = await readJson<{
const json = await Filesystem.readJson<{
require?: Record<string, string>
"require-dev"?: Record<string, string>
}>(item)