Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
82 changes: 56 additions & 26 deletions packages/opencode/src/worktree/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { errorMessage } from "../util/error"
import { BusEvent } from "@/bus/bus-event"
import { GlobalBus } from "@/bus/global"
import { Git } from "@/git"
import { Effect, Layer, Path, Scope, Context, Stream, Semaphore } from "effect"
import { Deferred, Effect, Layer, Path, Scope, Context, Stream, Semaphore } from "effect"
import { ensureWorktreesIgnored, restoreWorktreesIgnored } from "./gitignore-guard"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import { NodePath } from "@effect/platform-node"
Expand Down Expand Up @@ -446,10 +446,7 @@ export namespace Worktree {
},
})

yield* runStartScripts(info.directory, { projectID, extra }).pipe(
Effect.catchCause((cause) => Effect.sync(() => log.error("worktree start task failed", { cause }))),
Effect.forkIn(scope),
)
yield* launchStartScripts(info.directory, { projectID, extra })
})

const createFromInfo = Effect.fn("Worktree.createFromInfo")(function* (info: Info, startCommand?: string) {
Expand Down Expand Up @@ -608,28 +605,42 @@ export namespace Worktree {
return result
})

const signalStartLaunch = (launch: Deferred.Deferred<void> | undefined) => {
if (!launch) return Effect.void
return Deferred.succeed(launch, undefined).pipe(Effect.ignore)
}

const runStartCommand = Effect.fnUntraced(
function* (directory: string, cmd: string) {
const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]]
const handle = yield* spawner.spawn(
ChildProcess.make(shell, args, { cwd: directory, extendEnv: true, stdin: "ignore" }),
function* (directory: string, cmd: string, launch?: Deferred.Deferred<void>) {
return yield* Effect.gen(function* () {
const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]]
const handle = yield* spawner.spawn(
ChildProcess.make(shell, args, { cwd: directory, extendEnv: true, stdin: "ignore" }),
)
yield* signalStartLaunch(launch)
// Drain stdout, capture stderr for error reporting
const [, stderr] = yield* Effect.all(
[Stream.runDrain(handle.stdout), Stream.mkString(Stream.decodeText(handle.stderr))],
{ concurrency: 2 },
).pipe(Effect.orDie)
const code = yield* handle.exitCode
return { code, stderr }
}).pipe(
Effect.scoped,
Effect.catch(() => signalStartLaunch(launch).pipe(Effect.as({ code: 1, stderr: "" }))),
)
// Drain stdout, capture stderr for error reporting
const [, stderr] = yield* Effect.all(
[Stream.runDrain(handle.stdout), Stream.mkString(Stream.decodeText(handle.stderr))],
{ concurrency: 2 },
).pipe(Effect.orDie)
const code = yield* handle.exitCode
return { code, stderr }
},
Effect.scoped,
Effect.catch(() => Effect.succeed({ code: 1, stderr: "" })),
)

const runStartScript = Effect.fnUntraced(function* (directory: string, cmd: string, kind: string) {
const runStartScript = Effect.fnUntraced(function* (
directory: string,
cmd: string,
kind: string,
launch?: Deferred.Deferred<void>,
) {
const text = cmd.trim()
if (!text) return true
const result = yield* runStartCommand(directory, text)
const result = yield* runStartCommand(directory, text, launch)
if (result.code === 0) return true
log.error("worktree start command failed", { kind, directory, message: result.stderr })
return false
Expand All @@ -638,18 +649,40 @@ export namespace Worktree {
const runStartScripts = Effect.fnUntraced(function* (
directory: string,
input: { projectID: ProjectID; extra?: string },
launch?: Deferred.Deferred<void>,
) {
const row = yield* Effect.sync(() =>
Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, input.projectID)).get()),
)
const project = row ? Project.fromRow(row) : undefined
const startup = project?.commands?.start?.trim() ?? ""
const ok = yield* runStartScript(directory, startup, "project")
const extra = input.extra?.trim() ?? ""
if (!startup && !extra) {
yield* signalStartLaunch(launch)
return true
}
const ok = yield* runStartScript(directory, startup, "project", startup ? launch : undefined)
if (!ok) return false
yield* runStartScript(directory, input.extra ?? "", "worktree")
yield* runStartScript(directory, extra, "worktree", startup ? undefined : launch)
return true
})

const launchStartScripts = Effect.fnUntraced(function* (
directory: string,
input: { projectID: ProjectID; extra?: string },
) {
const launch = yield* Deferred.make<void>()
yield* runStartScripts(directory, input, launch).pipe(
Effect.catchCause((cause) =>
signalStartLaunch(launch).pipe(
Effect.andThen(Effect.sync(() => log.error("worktree start task failed", { cause }))),
),
),
Effect.forkIn(scope),
)
return yield* Deferred.await(launch)
})

const prune = Effect.fnUntraced(function* (root: string, entries: string[]) {
const base = yield* canonical(root)
yield* Effect.forEach(
Expand Down Expand Up @@ -766,10 +799,7 @@ export namespace Worktree {
yield* upsertRegistry(Info.parse({ ...registered, branch }))
}

yield* runStartScripts(worktreePath, { projectID: Instance.project.id }).pipe(
Effect.catchCause((cause) => Effect.sync(() => log.error("worktree start task failed", { cause }))),
Effect.forkIn(scope),
)
yield* launchStartScripts(worktreePath, { projectID: Instance.project.id })

return true
})
Expand Down
84 changes: 84 additions & 0 deletions packages/opencode/test/project/worktree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,79 @@ import { $ } from "bun"
import { afterEach, describe, expect, test } from "bun:test"

const wintest = process.platform !== "win32" ? test : test.skip
import { AppFileSystem } from "@opencode-ai/core/filesystem"
import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner"
import { NodePath } from "@effect/platform-node"
import { Effect, Layer, Stream } from "effect"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import fs from "fs/promises"
import path from "path"
import { Git } from "../../src/git"
import { Instance } from "../../src/project/instance"
import { Project } from "../../src/project/project"
import { ProjectTable } from "../../src/project/project.sql"
import { Database, eq } from "../../src/storage/db"
import { Worktree } from "../../src/worktree"
import { tmpdir } from "../fixture/fixture"

const encoder = new TextEncoder()

function withInstance(directory: string, fn: () => Promise<any>) {
return Instance.provide({ directory, fn })
}

function startCommandSpawnProbe(probe: { spawned: boolean; release?: () => void }) {
return Layer.effect(
ChildProcessSpawner.ChildProcessSpawner,
Effect.gen(function* () {
const real = yield* ChildProcessSpawner.ChildProcessSpawner
return ChildProcessSpawner.make(
Effect.fnUntraced(function* (command) {
const std = ChildProcess.isStandardCommand(command) ? command : undefined
const text = std ? [std.command, ...std.args].join(" ") : ""
if (text.includes("start-spawn-probe")) {
probe.spawned = true
let released = false
let finish: (code: ChildProcessSpawner.ExitCode) => void = () => undefined
const exit = new Promise<ChildProcessSpawner.ExitCode>((resolve) => {
finish = resolve
})
probe.release = () => {
if (released) return
released = true
finish(ChildProcessSpawner.ExitCode(0))
}
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(0),
exitCode: Effect.promise(() => exit),
isRunning: Effect.sync(() => !released),
kill: () => Effect.sync(() => probe.release?.()),
stdin: { [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") } as any,
stdout: Stream.empty,
stderr: Stream.make(encoder.encode("")),
all: Stream.empty,
getInputFd: () => ({ [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") }) as any,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
})
}
return yield* real.spawn(command)
}),
)
}),
).pipe(Layer.provide(CrossSpawnSpawner.defaultLayer))
}

function worktreeLayerWithStartCommandProbe(probe: { spawned: boolean; release?: () => void }) {
return Worktree.layer.pipe(
Layer.provide(Git.defaultLayer),
Layer.provide(Project.defaultLayer),
Layer.provide(startCommandSpawnProbe(probe)),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(NodePath.layer),
)
}

function normalize(input: string) {
return input.replace(/\\/g, "/").toLowerCase()
}
Expand Down Expand Up @@ -264,6 +324,30 @@ describe("Worktree", () => {
})
})

test("returns only after the project start command has spawned", async () => {
await using tmp = await tmpdir({ git: true })
const probe = { spawned: false, release: undefined as (() => void) | undefined }

await withInstance(tmp.path, async () => {
const info = await Worktree.createReady({ name: "reset-start-spawn-probe" })
await Project.update({
projectID: Instance.project.id,
commands: {
start: "start-spawn-probe",
},
})

const layer = worktreeLayerWithStartCommandProbe(probe)
await Effect.runPromise(
Worktree.Service.use((svc) => svc.reset({ directory: info.directory })).pipe(Effect.provide(layer)),
)

expect(probe.spawned).toBe(true)
probe.release?.()
await Worktree.remove({ directory: info.directory })
})
})

test("refreshes registry branch metadata from the attached worktree", async () => {
await using tmp = await tmpdir({ git: true })

Expand Down
Loading