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
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"monaco-editor": "^0.52.0",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
11 changes: 11 additions & 0 deletions packages/app/src/context/file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,16 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
viewCache.clear()
})

const save = (file: string, content: string) => {
const normalized = path.normalize(file)
return sdk.client.file
.write({ path: normalized, content })
.then(() => {
// Reload the file to reflect changes
void load(normalized, { force: true })
})
}

return {
ready: () => view().ready(),
normalize: path.normalize,
Expand All @@ -267,6 +277,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
},
get,
load,
save,
scrollTop,
scrollLeft,
setScrollTop,
Expand Down
5 changes: 5 additions & 0 deletions packages/app/src/pages/session/file-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ export function FileTabContent(props: { tab: string }) {
contents: source,
cacheKey: cacheKey(),
}}
filePath={path()}
onSave={(content: string) => {
const p = path()
if (p) file.save(p, content)
}}
enableLineSelection
enableHoverUtility
selectedLines={activeSelection()}
Expand Down
8 changes: 8 additions & 0 deletions packages/app/vite.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ export default [
},
worker: {
format: "es",
rollupOptions: {
output: {
entryFileNames: "assets/[name]-[hash].js",
},
},
},
optimizeDeps: {
include: ["monaco-editor"],
},
}
},
Expand Down
14 changes: 13 additions & 1 deletion packages/opencode/src/file/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ export interface Interface {
readonly init: () => Effect.Effect<void>
readonly status: () => Effect.Effect<Info[]>
readonly read: (file: string) => Effect.Effect<Content>
readonly write: (file: string, content: string) => Effect.Effect<void>
readonly list: (dir?: string) => Effect.Effect<Node[]>
readonly search: (input: {
query: string
Expand Down Expand Up @@ -640,8 +641,19 @@ export const layer = Layer.effect(
return output
})

const write: Interface["write"] = Effect.fn("File.write")(function* (file: string, content: string) {
const ctx = yield* InstanceState.context
const full = path.join(ctx.directory, file)

if (!containsPath(full, ctx)) {
throw new Error("Access denied: path escapes project directory")
}

yield* appFs.writeWithDirs(full, content)
})

log.info("init")
return Service.of({ init, status, read, list, search })
return Service.of({ init, status, read, write, list, search })
}),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,23 @@ import {
WorkspaceRoutingQueryFields,
} from "../middleware/workspace-routing"
import { described } from "./metadata"
import { FileWatcher } from "@/file/watcher"
import { EventV2Bridge } from "@/event-v2-bridge"

export const FileQuery = Schema.Struct({
...WorkspaceRoutingQueryFields,
path: Schema.String,
})

export const FileWriteQuery = Schema.Struct({
...WorkspaceRoutingQueryFields,
})

export const FileWriteBody = Schema.Struct({
path: Schema.String,
content: Schema.String,
})

export const FindTextQuery = Schema.Struct({
...WorkspaceRoutingQueryFields,
pattern: Schema.String,
Expand Down Expand Up @@ -110,6 +121,17 @@ export const FileApi = HttpApi.make("file")
description: "Get the git status of all files in the project.",
}),
),
HttpApiEndpoint.put("write", "/file/content", {
query: FileWriteQuery,
payload: FileWriteBody,
success: described(Schema.Struct({ success: Schema.Boolean }), "Write result"),
}).annotateMerge(
Comment on lines +124 to +128
OpenApi.annotations({
identifier: "file.write",
summary: "Write file",
description: "Write content to a specified file.",
}),
),
)
.annotateMerge(
OpenApi.annotations({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as InstanceState from "@/effect/instance-state"
import { File } from "@/file"
import { Ripgrep } from "@/file/ripgrep"
import { FileWatcher } from "@/file/watcher"
import { EventV2Bridge } from "@/event-v2-bridge"
import { Effect } from "effect"
import { HttpApiBuilder } from "effect/unstable/httpapi"
import { InstanceHttpApi } from "../api"
Expand All @@ -9,6 +11,7 @@ export const fileHandlers = HttpApiBuilder.group(InstanceHttpApi, "file", (handl
Effect.gen(function* () {
const svc = yield* File.Service
const ripgrep = yield* Ripgrep.Service
const events = yield* EventV2Bridge.Service

const findText = Effect.fn("FileHttpApi.findText")(function* (ctx: { query: { pattern: string } }) {
return (yield* ripgrep
Expand Down Expand Up @@ -43,12 +46,26 @@ export const fileHandlers = HttpApiBuilder.group(InstanceHttpApi, "file", (handl
return yield* svc.status()
})

const write = Effect.fn("FileHttpApi.write")(function* (ctx: {
query: { directory?: string; workspace?: string }
payload: { path: string; content: string }
}) {
yield* svc.write(ctx.payload.path, ctx.payload.content)
yield* events.publish(File.Event.Edited, { file: ctx.payload.path })
yield* events.publish(FileWatcher.Event.Updated, {
file: ctx.payload.path,
event: "change",
})
return { success: true }
})

return handlers
.handle("findText", findText)
.handle("findFile", findFile)
.handle("findSymbol", findSymbol)
.handle("list", list)
.handle("content", content)
.handle("status", status)
.handle("write", write)
}),
)
41 changes: 41 additions & 0 deletions packages/sdk/js/src/v2/gen/sdk.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1624,6 +1624,47 @@ export class File extends HeyApiClient {
...params,
})
}

/**
* Write file
*
* Write content to a specified file.
*/
public write<ThrowOnError extends boolean = false>(
parameters: {
directory?: string
workspace?: string
path: string
content: string
},
Comment on lines +1633 to +1639
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
],
},
],
)
return (options?.client ?? this.client).put<
{ success: boolean },
never,
ThrowOnError
>({
url: "/file/content",
...options,
...params,
body: { path: parameters.path, content: parameters.content },
headers: {
"Content-Type": "application/json",
...options?.headers,
},
})
}
}

export class Instance extends HeyApiClient {
Expand Down
3 changes: 2 additions & 1 deletion packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"solid-js": "catalog:",
"solid-list": "catalog:",
"strip-ansi": "7.1.2",
"virtua": "catalog:"
"virtua": "catalog:",
"monaco-editor": "^0.52.0"
}
}
79 changes: 78 additions & 1 deletion packages/ui/src/components/file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { acquireVirtualizer, virtualMetrics } from "../pierre/virtualizer"
import { getWorkerPool } from "../pierre/worker"
import { FileMedia, type FileMediaOptions } from "./file-media"
import { FileSearchBar } from "./file-search"
import { MonacoEditor } from "./monaco-editor"

const VIRTUALIZE_BYTES = 500_000

Expand Down Expand Up @@ -81,6 +82,8 @@ export type TextFileProps<T = {}> = FileOptions<T> &
file: FileContents
annotations?: LineAnnotation<T>[]
preloadedDiff?: PreloadMultiFileDiffResult<T>
filePath?: string
onSave?: (content: string) => void
}

type DiffPreload<T> = PreloadMultiFileDiffResult<T> | PreloadFileDiffResult<T>
Expand Down Expand Up @@ -911,7 +914,81 @@ function TextViewer<T>(props: TextFileProps<T>) {
virtuals.cleanup()
})

return <ViewerShell mode="text" viewer={viewer} class={local.class} classList={local.classList} />
// Monaco edit overlay
const [editing, setEditing] = createSignal(false)
const editContent = () => {
const value = local.file.contents as unknown
if (typeof value === "string") return value
if (Array.isArray(value)) return value.join("\n")
if (value == null) return ""
return String(value)
}

return (
<div style={{ position: "relative", width: "100%", height: "100%" }}>
<ViewerShell mode="text" viewer={viewer} class={local.class} classList={local.classList} />
{props.filePath && props.onSave && (
<button
onClick={() => setEditing(true)}
style={{
position: "absolute",
top: "8px",
right: "8px",
"z-index": "10",
padding: "4px 12px",
"font-size": "12px",
"border-radius": "4px",
border: "1px solid var(--border-base)",
background: "var(--background-stronger)",
color: "var(--text-base)",
cursor: "pointer",
}}
>
Edit
</button>
)}
{editing() && props.filePath && props.onSave && (
<div
style={{
position: "absolute",
inset: "0",
"z-index": "20",
background: "var(--background-base)",
}}
onKeyDown={(e) => {
if (e.key === "Escape") setEditing(false)
}}
>
<button
onClick={() => setEditing(false)}
style={{
position: "absolute",
top: "8px",
right: "8px",
"z-index": "30",
padding: "4px 12px",
"font-size": "12px",
"border-radius": "4px",
border: "1px solid var(--border-base)",
background: "var(--background-stronger)",
color: "var(--text-base)",
cursor: "pointer",
}}
>
Close
</button>
<MonacoEditor
filePath={props.filePath}
content={editContent()}
onSave={(content) => {
props.onSave!(content)
setEditing(false)
}}
/>
</div>
)}
Comment on lines +950 to +989
</div>
)
}

// ---------------------------------------------------------------------------
Expand Down
Loading
Loading