diff --git a/packages/core/src/file-mutation.ts b/packages/core/src/file-mutation.ts index 53d53e42fde..425208c4d92 100644 --- a/packages/core/src/file-mutation.ts +++ b/packages/core/src/file-mutation.ts @@ -28,6 +28,10 @@ export interface WriteResult { readonly existed: boolean } +export interface TextWriteResult extends WriteResult { + readonly bom: boolean +} + export interface Interface { /** Serialize a complete read/prepare/write mutation transaction by resolved path. */ readonly withLock: ( @@ -37,7 +41,7 @@ export interface Interface { /** Write text while retaining an existing UTF-8 BOM and emitting at most one BOM. */ readonly writeTextPreservingBom: ( input: TextWriteInput, - ) => Effect.Effect + ) => Effect.Effect } export class Service extends Context.Service()("@opencode/FileMutation") {} @@ -46,6 +50,11 @@ export const readText = Effect.fn("FileMutation.readText")(function* (files: Fil return Bom.decodeBytes((yield* files.read(target)).bytes) }) +export const readOptionalText = Effect.fn("FileMutation.readOptionalText")(function* (files: Files, target: string) { + const result = yield* files.read(target).pipe(Effect.catchTag("Environment.NotFound", () => Effect.undefined)) + return result ? Bom.decodeBytes(result.bytes) : undefined +}) + export const syncTextBom = Effect.fn("FileMutation.syncTextBom")(function* ( files: Files, target: string, @@ -108,11 +117,9 @@ const layer = Layer.effect( Effect.map((result) => result.bytes), Effect.catchTag("Environment.NotFound", () => Effect.undefined), ) - yield* environment.files.write( - input.target.absolute, - new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)), - ) - return writeResult(input.target, current !== undefined) + const bom = Boolean(current && Bom.has(current)) || next.bom + yield* environment.files.write(input.target.absolute, new TextEncoder().encode(Bom.join(next.text, bom))) + return { ...writeResult(input.target, current !== undefined), bom } }), ), ) diff --git a/packages/core/src/tool/plugin/write.ts b/packages/core/src/tool/plugin/write.ts index 147941ab9ff..3b264edb627 100644 --- a/packages/core/src/tool/plugin/write.ts +++ b/packages/core/src/tool/plugin/write.ts @@ -70,9 +70,7 @@ export const Plugin = { } const target = yield* access.resolve({ path: input.path, kind: "file" }) yield* access.authorizeExternal([target], context) - const current = yield* FileMutation.readText(environment.files, target.absolute).pipe( - Effect.catchTag("Environment.NotFound", () => Effect.undefined), - ) + const current = yield* FileMutation.readOptionalText(environment.files, target.absolute) const next = Bom.split(input.content) const preview = fileDiff(target.resource, current?.text ?? "", next.text, current ? "modified" : "added") yield* permission.assert({ @@ -84,12 +82,16 @@ export const Plugin = { agent: context.agent, source, }) - const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content }) - const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom + const written = yield* fileMutation.writeTextPreservingBom({ target, content: input.content }) if (yield* formatter.file(target.absolute)) { - yield* FileMutation.syncTextBom(environment.files, target.absolute, bom) + yield* FileMutation.syncTextBom(environment.files, target.absolute, written.bom) + } + return { + operation: written.operation, + target: written.target, + resource: written.resource, + existed: written.existed, } - return result }).pipe( Effect.map((output) => ({ output, content: toModelContent(output) })), Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })), diff --git a/packages/core/test/tool-write.test.ts b/packages/core/test/tool-write.test.ts index 4e5b6422585..1e964429b1c 100644 --- a/packages/core/test/tool-write.test.ts +++ b/packages/core/test/tool-write.test.ts @@ -1,7 +1,7 @@ import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { Effect, Layer } from "effect" +import { Effect, Exit, Layer, Tracer } from "effect" import { FileMutation } from "@opencode/core/file-mutation" import { Formatter } from "@opencode/core/formatter" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" @@ -32,11 +32,13 @@ const sessionID = Session.ID.make("ses_write_tool_test") const makeWriteFixture = () => { const fixture: { assertions: Permission.AssertInput[] + reads: Array<{ target: string; length?: number }> writes: string[] denyAction?: string formatFile: (target: string) => Effect.Effect } = { assertions: [], + reads: [], writes: [], formatFile: () => Effect.succeed(false), } @@ -82,6 +84,10 @@ const withTool = ( AppNodeBuilder.build(LayerNode.group([Tool.node, FileAccess.node, FileMutation.node, writeToolNode]), [ Environment.node.replace( transformEnvironmentFiles((files) => ({ + read: (target, options) => + Effect.sync(() => fixture.reads.push({ target, length: options?.length })).pipe( + Effect.andThen(files.read(target, options)), + ), write: (target, content) => Effect.sync(() => fixture.writes.push(target)).pipe(Effect.andThen(files.write(target, content))), })), @@ -399,4 +405,37 @@ describe("WriteTool", () => { ), ), ) + + it.live("creates a new unformatted file without span failures or post-write reads", () => { + const spans: Tracer.NativeSpan[] = [] + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options) + spans.push(span) + return span + }, + }) + return withTempDir((tmp) => { + const fixture = makeWriteFixture() + return withTool(tmp.path, fixture, (registry) => + Effect.gen(function* () { + const target = path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "fresh.txt") + const settled = yield* executeTool(registry, call({ path: "src/fresh.txt", content: "hello" })) + expect(settled.status).toBe("completed") + // Only the pre-write diff probe and the 3-byte BOM header check run; the written file is not re-read. + expect(fixture.reads).toEqual([ + { target, length: undefined }, + { target, length: 3 }, + ]) + const mutationSpans = spans.filter((span) => span.name.startsWith("FileMutation.")) + expect(mutationSpans.some((span) => span.name === "FileMutation.readOptionalText")).toBe(true) + for (const span of mutationSpans) { + if (span.status._tag === "Ended") { + expect(Exit.isFailure(span.status.exit)).toBe(false) + } + } + }), + ).pipe(Effect.provideService(Tracer.Tracer, tracer)) + }) + }) })