Compare commits

..
Author SHA1 Message Date
Kit Langton 6ff4da5639 Merge branch 'dev' into kit/effectify-command 2026-03-20 15:14:01 -04:00
Kit LangtonandGitHub b6e94fd2a8 Merge branch 'dev' into kit/effectify-command 2026-03-20 09:17:34 -04:00
Kit LangtonandGitHub 3d5c041129 Merge branch 'dev' into kit/effectify-command 2026-03-19 21:16:40 -04:00
Kit LangtonandGitHub 3af557512b Merge branch 'dev' into kit/effectify-command 2026-03-19 19:27:53 -04:00
Kit Langton b53a95fd81 log errors in catchCause instead of silently swallowing 2026-03-19 16:23:07 -04:00
Kit Langton 8e11a46fe0 use forkScoped + Fiber.join for lazy init (match old Instance.state behavior) 2026-03-19 16:03:38 -04:00
Kit Langton 8ab4d84057 handle undefined command in session prompt 2026-03-19 15:17:00 -04:00
Kit Langton 4066247988 effectify Command service: migrate from Instance.state to Effect service pattern 2026-03-19 15:14:54 -04:00
Kit Langton b9de3ad370 fix(bus): tighten GlobalBus payload and BusEvent.define types
Constrain BusEvent.define to ZodObject instead of ZodType so TS knows
event properties are always a record. Type GlobalBus payload as
{ type: string; properties: Record<string, unknown> } instead of any.

Refactor watcher test to use Bus.subscribe instead of raw GlobalBus
listener, removing hand-rolled event types and unnecessary casts.
2026-03-19 15:12:21 -04:00
9 changed files with 466 additions and 515 deletions
+2 -2
View File
@@ -129,10 +129,10 @@ Still open and likely worth migrating:
- [ ] `Plugin` - [ ] `Plugin`
- [ ] `ToolRegistry` - [ ] `ToolRegistry`
- [ ] `Pty` - [ ] `Pty`
- [x] `Worktree` - [ ] `Worktree`
- [ ] `Installation` - [ ] `Installation`
- [ ] `Bus` - [ ] `Bus`
- [ ] `Command` - [x] `Command`
- [ ] `Config` - [ ] `Config`
- [ ] `Session` - [ ] `Session`
- [ ] `SessionProcessor` - [ ] `SessionProcessor`
+2 -2
View File
@@ -1,5 +1,5 @@
import z from "zod" import z from "zod"
import type { ZodType } from "zod" import type { ZodObject, ZodRawShape } from "zod"
import { Log } from "../util/log" import { Log } from "../util/log"
export namespace BusEvent { export namespace BusEvent {
@@ -9,7 +9,7 @@ export namespace BusEvent {
const registry = new Map<string, Definition>() const registry = new Map<string, Definition>()
export function define<Type extends string, Properties extends ZodType>(type: Type, properties: Properties) { export function define<Type extends string, Properties extends ZodObject<ZodRawShape>>(type: Type, properties: Properties) {
const result = { const result = {
type, type,
properties, properties,
+1 -1
View File
@@ -4,7 +4,7 @@ export const GlobalBus = new EventEmitter<{
event: [ event: [
{ {
directory?: string directory?: string
payload: any payload: { type: string; properties: Record<string, unknown> }
}, },
] ]
}>() }>()
+52 -18
View File
@@ -1,15 +1,18 @@
import { BusEvent } from "@/bus/bus-event" import { BusEvent } from "@/bus/bus-event"
import { InstanceContext } from "@/effect/instance-context"
import { runPromiseInstance } from "@/effect/runtime"
import { SessionID, MessageID } from "@/session/schema" import { SessionID, MessageID } from "@/session/schema"
import { Effect, Fiber, Layer, ServiceMap } from "effect"
import z from "zod" import z from "zod"
import { Config } from "../config/config" import { Config } from "../config/config"
import { Instance } from "../project/instance"
import { Identifier } from "../id/id"
import PROMPT_INITIALIZE from "./template/initialize.txt" import PROMPT_INITIALIZE from "./template/initialize.txt"
import PROMPT_REVIEW from "./template/review.txt" import PROMPT_REVIEW from "./template/review.txt"
import { MCP } from "../mcp" import { MCP } from "../mcp"
import { Skill } from "../skill" import { Skill } from "../skill"
import { Log } from "../util/log"
export namespace Command { export namespace Command {
const log = Log.create({ service: "command" })
export const Event = { export const Event = {
Executed: BusEvent.define( Executed: BusEvent.define(
"command.executed", "command.executed",
@@ -57,33 +60,46 @@ export namespace Command {
REVIEW: "review", REVIEW: "review",
} as const } as const
const state = Instance.state(async () => { export interface Interface {
readonly get: (name: string) => Effect.Effect<Info | undefined>
readonly list: () => Effect.Effect<Info[]>
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Command") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const instance = yield* InstanceContext
const commands: Record<string, Info> = {}
const load = Effect.fn("Command.load")(function* () {
yield* Effect.promise(async () => {
const cfg = await Config.get() const cfg = await Config.get()
const result: Record<string, Info> = { commands[Default.INIT] = {
[Default.INIT]: {
name: Default.INIT, name: Default.INIT,
description: "create/update AGENTS.md", description: "create/update AGENTS.md",
source: "command", source: "command",
get template() { get template() {
return PROMPT_INITIALIZE.replace("${path}", Instance.worktree) return PROMPT_INITIALIZE.replace("${path}", instance.worktree)
}, },
hints: hints(PROMPT_INITIALIZE), hints: hints(PROMPT_INITIALIZE),
}, }
[Default.REVIEW]: { commands[Default.REVIEW] = {
name: Default.REVIEW, name: Default.REVIEW,
description: "review changes [commit|branch|pr], defaults to uncommitted", description: "review changes [commit|branch|pr], defaults to uncommitted",
source: "command", source: "command",
get template() { get template() {
return PROMPT_REVIEW.replace("${path}", Instance.worktree) return PROMPT_REVIEW.replace("${path}", instance.worktree)
}, },
subtask: true, subtask: true,
hints: hints(PROMPT_REVIEW), hints: hints(PROMPT_REVIEW),
},
} }
for (const [name, command] of Object.entries(cfg.command ?? {})) { for (const [name, command] of Object.entries(cfg.command ?? {})) {
result[name] = { commands[name] = {
name, name,
agent: command.agent, agent: command.agent,
model: command.model, model: command.model,
@@ -97,7 +113,7 @@ export namespace Command {
} }
} }
for (const [name, prompt] of Object.entries(await MCP.prompts())) { for (const [name, prompt] of Object.entries(await MCP.prompts())) {
result[name] = { commands[name] = {
name, name,
source: "mcp", source: "mcp",
description: prompt.description, description: prompt.description,
@@ -126,8 +142,8 @@ export namespace Command {
// Add skills as invokable commands // Add skills as invokable commands
for (const skill of await Skill.all()) { for (const skill of await Skill.all()) {
// Skip if a command with this name already exists // Skip if a command with this name already exists
if (result[skill.name]) continue if (commands[skill.name]) continue
result[skill.name] = { commands[skill.name] = {
name: skill.name, name: skill.name,
description: skill.description, description: skill.description,
source: "skill", source: "skill",
@@ -137,15 +153,33 @@ export namespace Command {
hints: [], hints: [],
} }
} }
})
return result
}) })
const loadFiber = yield* load().pipe(
Effect.catchCause((cause) => Effect.sync(() => log.error("init failed", { cause }))),
Effect.forkScoped,
)
const get = Effect.fn("Command.get")(function* (name: string) {
yield* Fiber.join(loadFiber)
return commands[name]
})
const list = Effect.fn("Command.list")(function* () {
yield* Fiber.join(loadFiber)
return Object.values(commands)
})
return Service.of({ get, list })
}),
)
export async function get(name: string) { export async function get(name: string) {
return state().then((x) => x[name]) return runPromiseInstance(Service.use((svc) => svc.get(name)))
} }
export async function list() { export async function list() {
return state().then((x) => Object.values(x)) return runPromiseInstance(Service.use((svc) => svc.list()))
} }
} }
@@ -124,7 +124,7 @@ export namespace Workspace {
await parseSSE(res.body, stop, (event) => { await parseSSE(res.body, stop, (event) => {
GlobalBus.emit("event", { GlobalBus.emit("event", {
directory: space.id, directory: space.id,
payload: event, payload: event as { type: string; properties: Record<string, unknown> },
}) })
}) })
// Wait 250ms and retry if SSE connection fails // Wait 250ms and retry if SSE connection fails
+3 -3
View File
@@ -1,4 +1,5 @@
import { Effect, Layer, LayerMap, ServiceMap } from "effect" import { Effect, Layer, LayerMap, ServiceMap } from "effect"
import { Command } from "@/command"
import { File } from "@/file/service" import { File } from "@/file/service"
import { FileTime } from "@/file/time-service" import { FileTime } from "@/file/time-service"
import { FileWatcher } from "@/file/watcher" import { FileWatcher } from "@/file/watcher"
@@ -10,13 +11,13 @@ import { ProviderAuth } from "@/provider/auth-service"
import { Question } from "@/question/service" import { Question } from "@/question/service"
import { Skill } from "@/skill/service" import { Skill } from "@/skill/service"
import { Snapshot } from "@/snapshot/service" import { Snapshot } from "@/snapshot/service"
import { Worktree } from "@/worktree"
import { InstanceContext } from "./instance-context" import { InstanceContext } from "./instance-context"
import { registerDisposer } from "./instance-registry" import { registerDisposer } from "./instance-registry"
export { InstanceContext } from "./instance-context" export { InstanceContext } from "./instance-context"
export type InstanceServices = export type InstanceServices =
| Command.Service
| Question.Service | Question.Service
| Permission.Service | Permission.Service
| ProviderAuth.Service | ProviderAuth.Service
@@ -27,7 +28,6 @@ export type InstanceServices =
| File.Service | File.Service
| Skill.Service | Skill.Service
| Snapshot.Service | Snapshot.Service
| Worktree.Service
// NOTE: LayerMap only passes the key (directory string) to lookup, but we need // NOTE: LayerMap only passes the key (directory string) to lookup, but we need
// the full instance context (directory, worktree, project). We read from the // the full instance context (directory, worktree, project). We read from the
@@ -38,6 +38,7 @@ export type InstanceServices =
function lookup(_key: string) { function lookup(_key: string) {
const ctx = Layer.sync(InstanceContext, () => InstanceContext.of(Instance.current)) const ctx = Layer.sync(InstanceContext, () => InstanceContext.of(Instance.current))
return Layer.mergeAll( return Layer.mergeAll(
Command.layer,
Question.layer, Question.layer,
Permission.layer, Permission.layer,
ProviderAuth.defaultLayer, ProviderAuth.defaultLayer,
@@ -48,7 +49,6 @@ function lookup(_key: string) {
File.layer, File.layer,
Skill.defaultLayer, Skill.defaultLayer,
Snapshot.defaultLayer, Snapshot.defaultLayer,
Worktree.layer,
).pipe(Layer.provide(ctx)) ).pipe(Layer.provide(ctx))
} }
+3
View File
@@ -1782,6 +1782,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the
export async function command(input: CommandInput) { export async function command(input: CommandInput) {
log.info("command", input) log.info("command", input)
const command = await Command.get(input.command) const command = await Command.get(input.command)
if (!command) {
throw new NamedError.Unknown({ message: `Command not found: "${input.command}"` })
}
const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent()) const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent())
const raw = input.arguments.match(argsRegex) ?? [] const raw = input.arguments.match(argsRegex) ?? []
+42 -128
View File
@@ -4,17 +4,17 @@ import z from "zod"
import { NamedError } from "@opencode-ai/util/error" import { NamedError } from "@opencode-ai/util/error"
import { Global } from "../global" import { Global } from "../global"
import { Instance } from "../project/instance" import { Instance } from "../project/instance"
import { InstanceBootstrap } from "../project/bootstrap"
import { Project } from "../project/project" import { Project } from "../project/project"
import { Database, eq } from "../storage/db" import { Database, eq } from "../storage/db"
import { ProjectTable } from "../project/project.sql" import { ProjectTable } from "../project/project.sql"
import type { ProjectID } from "../project/schema" import type { ProjectID } from "../project/schema"
import { fn } from "../util/fn"
import { Log } from "../util/log" import { Log } from "../util/log"
import { Process } from "../util/process" import { Process } from "../util/process"
import { git } from "../util/git" import { git } from "../util/git"
import { BusEvent } from "@/bus/bus-event" import { BusEvent } from "@/bus/bus-event"
import { GlobalBus } from "@/bus/global" import { GlobalBus } from "@/bus/global"
import { InstanceContext } from "@/effect/instance-context"
import { Effect, Layer, ServiceMap } from "effect"
export namespace Worktree { export namespace Worktree {
const log = Log.create({ service: "worktree" }) const log = Log.create({ service: "worktree" })
@@ -267,7 +267,7 @@ export namespace Worktree {
return process.platform === "win32" ? normalized.toLowerCase() : normalized return process.platform === "win32" ? normalized.toLowerCase() : normalized
} }
async function candidateName(worktreeDir: string, root: string, base?: string) { async function candidate(root: string, base?: string) {
for (const attempt of Array.from({ length: 26 }, (_, i) => i)) { for (const attempt of Array.from({ length: 26 }, (_, i) => i)) {
const name = base ? (attempt === 0 ? base : `${base}-${randomName()}`) : randomName() const name = base ? (attempt === 0 ? base : `${base}-${randomName()}`) : randomName()
const branch = `opencode/${name}` const branch = `opencode/${name}`
@@ -277,7 +277,7 @@ export namespace Worktree {
const ref = `refs/heads/${branch}` const ref = `refs/heads/${branch}`
const branchCheck = await git(["show-ref", "--verify", "--quiet", ref], { const branchCheck = await git(["show-ref", "--verify", "--quiet", ref], {
cwd: worktreeDir, cwd: Instance.worktree,
}) })
if (branchCheck.exitCode === 0) continue if (branchCheck.exitCode === 0) continue
@@ -335,51 +335,29 @@ export namespace Worktree {
}, 0) }, 0)
} }
// --------------------------------------------------------------------------- export async function makeWorktreeInfo(name?: string): Promise<Info> {
// Effect service if (Instance.project.vcs !== "git") {
// ---------------------------------------------------------------------------
export interface Interface {
readonly makeWorktreeInfo: (name?: string) => Effect.Effect<Info>
readonly createFromInfo: (info: Info, startCommand?: string) => Effect.Effect<() => Promise<void>>
readonly create: (input?: CreateInput) => Effect.Effect<Info>
readonly remove: (input: RemoveInput) => Effect.Effect<boolean>
readonly reset: (input: ResetInput) => Effect.Effect<boolean>
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Worktree") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const instance = yield* InstanceContext
const makeWorktreeInfoEffect = Effect.fn("Worktree.makeWorktreeInfo")(function* (name?: string) {
return yield* Effect.promise(async () => {
if (instance.project.vcs !== "git") {
throw new NotGitError({ message: "Worktrees are only supported for git projects" }) throw new NotGitError({ message: "Worktrees are only supported for git projects" })
} }
const root = path.join(Global.Path.data, "worktree", instance.project.id) const root = path.join(Global.Path.data, "worktree", Instance.project.id)
await fs.mkdir(root, { recursive: true }) await fs.mkdir(root, { recursive: true })
const base = name ? slug(name) : "" const base = name ? slug(name) : ""
return candidateName(instance.worktree, root, base || undefined) return candidate(root, base || undefined)
}) }
})
const createFromInfoEffect = Effect.fn("Worktree.createFromInfo")(function* (info: Info, startCommand?: string) { export async function createFromInfo(info: Info, startCommand?: string) {
return yield* Effect.promise(async (): Promise<() => Promise<void>> => {
const created = await git(["worktree", "add", "--no-checkout", "-b", info.branch, info.directory], { const created = await git(["worktree", "add", "--no-checkout", "-b", info.branch, info.directory], {
cwd: instance.worktree, cwd: Instance.worktree,
}) })
if (created.exitCode !== 0) { if (created.exitCode !== 0) {
throw new CreateFailedError({ message: errorText(created) || "Failed to create git worktree" }) throw new CreateFailedError({ message: errorText(created) || "Failed to create git worktree" })
} }
await Project.addSandbox(instance.project.id, info.directory).catch(() => undefined) await Project.addSandbox(Instance.project.id, info.directory).catch(() => undefined)
const projectID = instance.project.id const projectID = Instance.project.id
const extra = startCommand?.trim() const extra = startCommand?.trim()
return () => { return () => {
@@ -402,10 +380,7 @@ export namespace Worktree {
const booted = await Instance.provide({ const booted = await Instance.provide({
directory: info.directory, directory: info.directory,
init: async () => { init: InstanceBootstrap,
const { InstanceBootstrap } = await import("../project/bootstrap")
return InstanceBootstrap()
},
fn: () => undefined, fn: () => undefined,
}) })
.then(() => true) .then(() => true)
@@ -443,13 +418,11 @@ export namespace Worktree {
log.error("worktree start task failed", { directory: info.directory, error }) log.error("worktree start task failed", { directory: info.directory, error })
}) })
} }
}) }
})
const createEffect = Effect.fn("Worktree.create")(function* (input?: CreateInput) { export const create = fn(CreateInput.optional(), async (input) => {
const parsed = input ? CreateInput.optional().parse(input) : undefined const info = await makeWorktreeInfo(input?.name)
const info = yield* makeWorktreeInfoEffect(parsed?.name) const bootstrap = await createFromInfo(info, input?.startCommand)
const bootstrap = yield* createFromInfoEffect(info, parsed?.startCommand)
// This is needed due to how worktrees currently work in the // This is needed due to how worktrees currently work in the
// desktop app // desktop app
setTimeout(() => { setTimeout(() => {
@@ -458,14 +431,12 @@ export namespace Worktree {
return info return info
}) })
const removeEffect = Effect.fn("Worktree.remove")(function* (input: RemoveInput) { export const remove = fn(RemoveInput, async (input) => {
return yield* Effect.promise(async () => { if (Instance.project.vcs !== "git") {
const parsed = RemoveInput.parse(input)
if (instance.project.vcs !== "git") {
throw new NotGitError({ message: "Worktrees are only supported for git projects" }) throw new NotGitError({ message: "Worktrees are only supported for git projects" })
} }
const directory = await canonical(parsed.directory) const directory = await canonical(input.directory)
const locate = async (stdout: Uint8Array | undefined) => { const locate = async (stdout: Uint8Array | undefined) => {
const lines = outputText(stdout) const lines = outputText(stdout)
.split("\n") .split("\n")
@@ -511,7 +482,7 @@ export namespace Worktree {
await git(["fsmonitor--daemon", "stop"], { cwd: target }) await git(["fsmonitor--daemon", "stop"], { cwd: target })
} }
const list = await git(["worktree", "list", "--porcelain"], { cwd: instance.worktree }) const list = await git(["worktree", "list", "--porcelain"], { cwd: Instance.worktree })
if (list.exitCode !== 0) { if (list.exitCode !== 0) {
throw new RemoveFailedError({ message: errorText(list) || "Failed to read git worktrees" }) throw new RemoveFailedError({ message: errorText(list) || "Failed to read git worktrees" })
} }
@@ -529,10 +500,10 @@ export namespace Worktree {
await stop(entry.path) await stop(entry.path)
const removed = await git(["worktree", "remove", "--force", entry.path], { const removed = await git(["worktree", "remove", "--force", entry.path], {
cwd: instance.worktree, cwd: Instance.worktree,
}) })
if (removed.exitCode !== 0) { if (removed.exitCode !== 0) {
const next = await git(["worktree", "list", "--porcelain"], { cwd: instance.worktree }) const next = await git(["worktree", "list", "--porcelain"], { cwd: Instance.worktree })
if (next.exitCode !== 0) { if (next.exitCode !== 0) {
throw new RemoveFailedError({ throw new RemoveFailedError({
message: errorText(removed) || errorText(next) || "Failed to remove git worktree", message: errorText(removed) || errorText(next) || "Failed to remove git worktree",
@@ -549,7 +520,7 @@ export namespace Worktree {
const branch = entry.branch?.replace(/^refs\/heads\//, "") const branch = entry.branch?.replace(/^refs\/heads\//, "")
if (branch) { if (branch) {
const deleted = await git(["branch", "-D", branch], { cwd: instance.worktree }) const deleted = await git(["branch", "-D", branch], { cwd: Instance.worktree })
if (deleted.exitCode !== 0) { if (deleted.exitCode !== 0) {
throw new RemoveFailedError({ message: errorText(deleted) || "Failed to delete worktree branch" }) throw new RemoveFailedError({ message: errorText(deleted) || "Failed to delete worktree branch" })
} }
@@ -557,22 +528,19 @@ export namespace Worktree {
return true return true
}) })
})
const resetEffect = Effect.fn("Worktree.reset")(function* (input: ResetInput) { export const reset = fn(ResetInput, async (input) => {
return yield* Effect.promise(async () => { if (Instance.project.vcs !== "git") {
const parsed = ResetInput.parse(input)
if (instance.project.vcs !== "git") {
throw new NotGitError({ message: "Worktrees are only supported for git projects" }) throw new NotGitError({ message: "Worktrees are only supported for git projects" })
} }
const directory = await canonical(parsed.directory) const directory = await canonical(input.directory)
const primary = await canonical(instance.worktree) const primary = await canonical(Instance.worktree)
if (directory === primary) { if (directory === primary) {
throw new ResetFailedError({ message: "Cannot reset the primary workspace" }) throw new ResetFailedError({ message: "Cannot reset the primary workspace" })
} }
const list = await git(["worktree", "list", "--porcelain"], { cwd: instance.worktree }) const list = await git(["worktree", "list", "--porcelain"], { cwd: Instance.worktree })
if (list.exitCode !== 0) { if (list.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(list) || "Failed to read git worktrees" }) throw new ResetFailedError({ message: errorText(list) || "Failed to read git worktrees" })
} }
@@ -605,7 +573,7 @@ export namespace Worktree {
throw new ResetFailedError({ message: "Worktree not found" }) throw new ResetFailedError({ message: "Worktree not found" })
} }
const remoteList = await git(["remote"], { cwd: instance.worktree }) const remoteList = await git(["remote"], { cwd: Instance.worktree })
if (remoteList.exitCode !== 0) { if (remoteList.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(remoteList) || "Failed to list git remotes" }) throw new ResetFailedError({ message: errorText(remoteList) || "Failed to list git remotes" })
} }
@@ -624,19 +592,18 @@ export namespace Worktree {
: "" : ""
const remoteHead = remote const remoteHead = remote
? await git(["symbolic-ref", `refs/remotes/${remote}/HEAD`], { cwd: instance.worktree }) ? await git(["symbolic-ref", `refs/remotes/${remote}/HEAD`], { cwd: Instance.worktree })
: { exitCode: 1, stdout: undefined, stderr: undefined } : { exitCode: 1, stdout: undefined, stderr: undefined }
const remoteRef = remoteHead.exitCode === 0 ? outputText(remoteHead.stdout) : "" const remoteRef = remoteHead.exitCode === 0 ? outputText(remoteHead.stdout) : ""
const remoteTarget = remoteRef ? remoteRef.replace(/^refs\/remotes\//, "") : "" const remoteTarget = remoteRef ? remoteRef.replace(/^refs\/remotes\//, "") : ""
const remoteBranch = const remoteBranch = remote && remoteTarget.startsWith(`${remote}/`) ? remoteTarget.slice(`${remote}/`.length) : ""
remote && remoteTarget.startsWith(`${remote}/`) ? remoteTarget.slice(`${remote}/`.length) : ""
const mainCheck = await git(["show-ref", "--verify", "--quiet", "refs/heads/main"], { const mainCheck = await git(["show-ref", "--verify", "--quiet", "refs/heads/main"], {
cwd: instance.worktree, cwd: Instance.worktree,
}) })
const masterCheck = await git(["show-ref", "--verify", "--quiet", "refs/heads/master"], { const masterCheck = await git(["show-ref", "--verify", "--quiet", "refs/heads/master"], {
cwd: instance.worktree, cwd: Instance.worktree,
}) })
const localBranch = mainCheck.exitCode === 0 ? "main" : masterCheck.exitCode === 0 ? "master" : "" const localBranch = mainCheck.exitCode === 0 ? "main" : masterCheck.exitCode === 0 ? "master" : ""
@@ -646,7 +613,7 @@ export namespace Worktree {
} }
if (remoteBranch) { if (remoteBranch) {
const fetch = await git(["fetch", remote, remoteBranch], { cwd: instance.worktree }) const fetch = await git(["fetch", remote, remoteBranch], { cwd: Instance.worktree })
if (fetch.exitCode !== 0) { if (fetch.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(fetch) || `Failed to fetch ${target}` }) throw new ResetFailedError({ message: errorText(fetch) || `Failed to fetch ${target}` })
} }
@@ -660,19 +627,15 @@ export namespace Worktree {
const resetToTarget = await git(["reset", "--hard", target], { cwd: worktreePath }) const resetToTarget = await git(["reset", "--hard", target], { cwd: worktreePath })
if (resetToTarget.exitCode !== 0) { if (resetToTarget.exitCode !== 0) {
throw new ResetFailedError({ throw new ResetFailedError({ message: errorText(resetToTarget) || "Failed to reset worktree to target" })
message: errorText(resetToTarget) || "Failed to reset worktree to target",
})
} }
const cleanResult = await sweep(worktreePath) const clean = await sweep(worktreePath)
if (cleanResult.exitCode !== 0) { if (clean.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(cleanResult) || "Failed to clean worktree" }) throw new ResetFailedError({ message: errorText(clean) || "Failed to clean worktree" })
} }
const update = await git(["submodule", "update", "--init", "--recursive", "--force"], { const update = await git(["submodule", "update", "--init", "--recursive", "--force"], { cwd: worktreePath })
cwd: worktreePath,
})
if (update.exitCode !== 0) { if (update.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(update) || "Failed to update submodules" }) throw new ResetFailedError({ message: errorText(update) || "Failed to update submodules" })
} }
@@ -701,58 +664,9 @@ export namespace Worktree {
throw new ResetFailedError({ message: `Worktree reset left local changes:\n${dirty}` }) throw new ResetFailedError({ message: `Worktree reset left local changes:\n${dirty}` })
} }
const projectID = instance.project.id const projectID = Instance.project.id
queueStartScripts(worktreePath, { projectID }) queueStartScripts(worktreePath, { projectID })
return true return true
}) })
})
return Service.of({
makeWorktreeInfo: makeWorktreeInfoEffect,
createFromInfo: createFromInfoEffect,
create: createEffect,
remove: removeEffect,
reset: resetEffect,
})
}),
).pipe(Layer.fresh)
async function run<A, E>(effect: Effect.Effect<A, E, Service>) {
const { runPromiseInstance } = await import("@/effect/runtime")
return runPromiseInstance(effect)
}
// ---------------------------------------------------------------------------
// Promise facades
// ---------------------------------------------------------------------------
export async function makeWorktreeInfo(name?: string): Promise<Info> {
return run(Service.use((svc) => svc.makeWorktreeInfo(name)))
}
export async function createFromInfo(info: Info, startCommand?: string) {
return run(Service.use((svc) => svc.createFromInfo(info, startCommand)))
}
export const create = Object.assign(
async (input?: CreateInput) => {
return run(Service.use((svc) => svc.create(input)))
},
{ schema: CreateInput.optional() },
)
export const remove = Object.assign(
async (input: RemoveInput) => {
return run(Service.use((svc) => svc.remove(input)))
},
{ schema: RemoveInput },
)
export const reset = Object.assign(
async (input: ResetInput) => {
return run(Service.use((svc) => svc.reset(input)))
},
{ schema: ResetInput },
)
} }
+7 -7
View File
@@ -16,7 +16,7 @@ const describeWatcher = FileWatcher.hasNativeBinding() && !process.env.CI ? desc
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
type BusUpdate = { directory?: string; payload: { type: string; properties: WatcherEvent } } type BusUpdate = { directory?: string; payload: { type: string; properties: Record<string, unknown> } }
type WatcherEvent = { file: string; event: "add" | "change" | "unlink" } type WatcherEvent = { file: string; event: "add" | "change" | "unlink" }
/** Run `body` with a live FileWatcher service. */ /** Run `body` with a live FileWatcher service. */
@@ -40,18 +40,18 @@ function listen(directory: string, check: (evt: WatcherEvent) => boolean, hit: (
if (done) return if (done) return
if (evt.directory !== directory) return if (evt.directory !== directory) return
if (evt.payload.type !== FileWatcher.Event.Updated.type) return if (evt.payload.type !== FileWatcher.Event.Updated.type) return
if (!check(evt.payload.properties)) return const props = evt.payload.properties as WatcherEvent
hit(evt.payload.properties) if (!check(props)) return
hit(props)
} }
function cleanup() { GlobalBus.on("event", on)
return () => {
if (done) return if (done) return
done = true done = true
GlobalBus.off("event", on) GlobalBus.off("event", on)
} }
GlobalBus.on("event", on)
return cleanup
} }
function wait(directory: string, check: (evt: WatcherEvent) => boolean) { function wait(directory: string, check: (evt: WatcherEvent) => boolean) {