Compare commits

..
Author SHA1 Message Date
Claude 5015bf18d4 refactor: destroy Snapshot facade
Remove the seven async facade exports (init, track, patch, restore,
revert, diff, diffFull) and the dedicated makeRuntime wrapper from
snapshot/index.ts. Bootstrap now runs svc.init() through BootstrapRuntime
(with Snapshot.defaultLayer added to BootstrapLayer so the service is
resolvable), the debug CLI commands and the three affected test files
(snapshot, revert-compact, project-init-git) call
AppRuntime.runPromise(Snapshot.Service.use(...)) directly.

https://claude.ai/code/session_01VKXRMreuM8EX2g8WRZPNpm
2026-04-11 14:17:39 +00:00
opencode-agent[bot] 27190635ea chore: update nix node_modules hashes 2026-04-11 04:45:55 +00:00
opencode-agent[bot] 2e340d976f chore: generate 2026-04-11 03:53:48 +00:00
Kit LangtonandGitHub fe4dfb9f6f refactor(git): remove runtime facade wrappers (#21982) 2026-04-10 23:52:48 -04:00
Kit LangtonandGitHub 5e3dc80999 refactor: collapse command facade (#21981) 2026-04-10 23:52:12 -04:00
Kit LangtonandGitHub d84cc33742 refactor(plugin): return Effect from ToolContext.ask (#21986) 2026-04-10 23:50:50 -04:00
opencode-agent[bot] c92c462148 chore: update nix node_modules hashes 2026-04-11 03:39:49 +00:00
Kit LangtonandGitHub 9ca06e0336 docs(effect): mark SessionTodo migrated (#21987) 2026-04-10 23:35:50 -04:00
opencode-agent[bot] 3b523b32f5 chore: generate 2026-04-11 03:28:30 +00:00
Kit LangtonandGitHub ba3600a515 refactor(session): remove dead updatePartDelta facade (#21985) 2026-04-10 23:27:30 -04:00
Kit LangtonandGitHub 03ce2e5288 refactor(installation): drop facade runtime wrappers (#21984) 2026-04-10 23:26:16 -04:00
Kit LangtonandGitHub 87e23abb10 refactor: remove ProviderAuth facade (#21983) 2026-04-10 23:25:43 -04:00
opencode-agent[bot] 2868000c20 chore: generate 2026-04-11 03:19:50 +00:00
Kit LangtonandGitHub f38f415bf0 refactor: collapse Format facade (#21980) 2026-04-10 23:18:54 -04:00
Kit LangtonandGitHub 4341ab838e refactor(tool): use Session.Service directly in TaskTool (#21975) 2026-04-10 23:18:30 -04:00
Kit LangtonandGitHub cd004cf0b2 refactor(session): eliminate Effect.promise roundtrips for sync MessageV2.stream (#21973) 2026-04-10 23:18:13 -04:00
opencode-agent[bot] 19ae8c88b0 chore: generate 2026-04-11 03:13:03 +00:00
Kit LangtonandGitHub 3dd09147c2 refactor(tool): Tool.Context.metadata returns Effect (#21972) 2026-04-10 23:12:04 -04:00
47 changed files with 560 additions and 610 deletions
+1
View File
@@ -450,6 +450,7 @@
"version": "1.4.3",
"dependencies": {
"@opencode-ai/sdk": "workspace:*",
"effect": "catalog:",
"zod": "catalog:",
},
"devDependencies": {
+4 -4
View File
@@ -1,8 +1,8 @@
{
"nodeModules": {
"x86_64-linux": "sha256-285KZ7rZLRoc6XqCZRHc25NE+mmpGh/BVeMpv8aPQtQ=",
"aarch64-linux": "sha256-qIwmY4TP4CI7R7G6A5OMYRrorVNXjkg25tTtVpIHm2o=",
"aarch64-darwin": "sha256-RwvnZQhdYZ0u7h7evyfxuPLHHX9eO/jXTAxIFc8B+IE=",
"x86_64-darwin": "sha256-vVj40al+TEeMpbe5XG2GmJEpN+eQAvtr9W0T98l5PBE="
"x86_64-linux": "sha256-gFbo3B6TFAmin2marXlwUyfchTX6ogsaUFEzBIl4zaI=",
"aarch64-linux": "sha256-HUKL7zBVtb1KPaoAgfSfAzjDoAPRUe2WNFHDrsoqEF8=",
"aarch64-darwin": "sha256-qWPRkuVA3nDEEaVZ0Ex4sYsFFarSRJSyOn+KJm1D3U0=",
"x86_64-darwin": "sha256-FxhOYMXkxjn/9xQPeVX/gfQT/KjHT4wIBqzVDZuYlos="
}
}
+3 -1
View File
@@ -223,7 +223,7 @@ Fully migrated (single namespace, InstanceState where needed, flattened facade):
Still open:
- [ ] `SessionTodo``session/todo.ts`
- [x] `SessionTodo``session/todo.ts`
- [ ] `SyncEvent``sync/index.ts`
- [ ] `Workspace``control-plane/workspace.ts`
@@ -336,6 +336,8 @@ For each service, the migration is roughly:
### Migration log
- `Snapshot` — facade destroyed 2026-04-11. Removed the `makeRuntime(...)` wrapper and the seven async exports (`init`, `track`, `patch`, `restore`, `revert`, `diff`, `diffFull`); `project/bootstrap.ts` now runs `svc.init()` through `BootstrapRuntime`, the debug CLI commands use `AppRuntime.runPromise(Snapshot.Service.use(...))`, and the snapshot/revert-compact/project-init-git tests were rewritten to the same pattern. `Snapshot.defaultLayer` was added to `BootstrapLayer` so bootstrap can resolve the service without pulling in `AppRuntime`.
- `SessionStatus` — migrated 2026-04-11. Replaced the last route and retry-policy callers with `AppRuntime.runPromise(SessionStatus.Service.use(...))` and removed the `makeRuntime(...)` facade.
- `ShareNext` — migrated 2026-04-11. Swapped remaining async callers to `AppRuntime.runPromise(ShareNext.Service.use(...))`, removed the `makeRuntime(...)` facade, and kept instance bootstrap on the shared app runtime.
- `SessionTodo` — migrated 2026-04-10. Already matched the target service shape in `session/todo.ts`: single namespace, traced Effect methods, and no `makeRuntime(...)` facade remained; checklist updated to reflect the completed migration.
- `Storage` — migrated 2026-04-10. One production caller (`Session.diff`) and all storage.test.ts tests converted to effectful style. Facades and `makeRuntime` removed.
+1 -1
View File
@@ -158,7 +158,7 @@ async function createToolContext(agent: Agent.Info) {
agent: agent.name,
abort: new AbortController().signal,
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask(req: Omit<Permission.Request, "id" | "sessionID" | "tool">) {
return Effect.sync(() => {
for (const pattern of req.patterns) {
@@ -1,3 +1,4 @@
import { AppRuntime } from "@/effect/app-runtime"
import { Snapshot } from "../../../snapshot"
import { bootstrap } from "../../bootstrap"
import { cmd } from "../cmd"
@@ -14,7 +15,7 @@ const TrackCommand = cmd({
describe: "track current snapshot state",
async handler() {
await bootstrap(process.cwd(), async () => {
console.log(await Snapshot.track())
console.log(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track())))
})
},
})
@@ -30,7 +31,7 @@ const PatchCommand = cmd({
}),
async handler(args) {
await bootstrap(process.cwd(), async () => {
console.log(await Snapshot.patch(args.hash))
console.log(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(args.hash))))
})
},
})
@@ -46,7 +47,7 @@ const DiffCommand = cmd({
}),
async handler(args) {
await bootstrap(process.cwd(), async () => {
console.log(await Snapshot.diff(args.hash))
console.log(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diff(args.hash))))
})
},
})
+8 -4
View File
@@ -29,6 +29,7 @@ import { Provider } from "../../provider/provider"
import { Bus } from "../../bus"
import { MessageV2 } from "../../session/message-v2"
import { SessionPrompt } from "@/session/prompt"
import { AppRuntime } from "@/effect/app-runtime"
import { Git } from "@/git"
import { setTimeout as sleep } from "node:timers/promises"
import { Process } from "@/util/process"
@@ -258,7 +259,9 @@ export const GithubInstallCommand = cmd({
}
// Get repo info
const info = (await Git.run(["remote", "get-url", "origin"], { cwd: Instance.worktree })).text().trim()
const info = await AppRuntime.runPromise(
Git.Service.use((git) => git.run(["remote", "get-url", "origin"], { cwd: Instance.worktree })),
).then((x) => x.text().trim())
const parsed = parseGitHubRemote(info)
if (!parsed) {
prompts.log.error(`Could not find git repository. Please run this command from a git repository.`)
@@ -497,20 +500,21 @@ export const GithubRunCommand = cmd({
: "issue"
: undefined
const gitText = async (args: string[]) => {
const result = await Git.run(args, { cwd: Instance.worktree })
const result = await AppRuntime.runPromise(Git.Service.use((git) => git.run(args, { cwd: Instance.worktree })))
if (result.exitCode !== 0) {
throw new Process.RunFailedError(["git", ...args], result.exitCode, result.stdout, result.stderr)
}
return result.text().trim()
}
const gitRun = async (args: string[]) => {
const result = await Git.run(args, { cwd: Instance.worktree })
const result = await AppRuntime.runPromise(Git.Service.use((git) => git.run(args, { cwd: Instance.worktree })))
if (result.exitCode !== 0) {
throw new Process.RunFailedError(["git", ...args], result.exitCode, result.stdout, result.stderr)
}
return result
}
const gitStatus = (args: string[]) => Git.run(args, { cwd: Instance.worktree })
const gitStatus = (args: string[]) =>
AppRuntime.runPromise(Git.Service.use((git) => git.run(args, { cwd: Instance.worktree })))
const commitChanges = async (summary: string, actor?: string) => {
const args = ["commit", "-m", summary]
if (actor) args.push("-m", `Co-authored-by: ${actor} <${actor}@users.noreply.github.com>`)
+18 -7
View File
@@ -1,5 +1,6 @@
import { UI } from "../ui"
import { cmd } from "./cmd"
import { AppRuntime } from "@/effect/app-runtime"
import { Git } from "@/git"
import { Instance } from "@/project/instance"
import { Process } from "@/util/process"
@@ -67,19 +68,29 @@ export const PrCommand = cmd({
const remoteName = forkOwner
// Check if remote already exists
const remotes = (await Git.run(["remote"], { cwd: Instance.worktree })).text().trim()
const remotes = await AppRuntime.runPromise(
Git.Service.use((git) => git.run(["remote"], { cwd: Instance.worktree })),
).then((x) => x.text().trim())
if (!remotes.split("\n").includes(remoteName)) {
await Git.run(["remote", "add", remoteName, `https://github.com/${forkOwner}/${forkName}.git`], {
cwd: Instance.worktree,
})
await AppRuntime.runPromise(
Git.Service.use((git) =>
git.run(["remote", "add", remoteName, `https://github.com/${forkOwner}/${forkName}.git`], {
cwd: Instance.worktree,
}),
),
)
UI.println(`Added fork remote: ${remoteName}`)
}
// Set upstream to the fork so pushes go there
const headRefName = prInfo.headRefName
await Git.run(["branch", `--set-upstream-to=${remoteName}/${headRefName}`, localBranchName], {
cwd: Instance.worktree,
})
await AppRuntime.runPromise(
Git.Service.use((git) =>
git.run(["branch", `--set-upstream-to=${remoteName}/${headRefName}`, localBranchName], {
cwd: Instance.worktree,
}),
),
)
}
// Check for opencode session link in PR body
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Argv } from "yargs"
import { UI } from "../ui"
import * as prompts from "@clack/prompts"
import { AppRuntime } from "@/effect/app-runtime"
import { Installation } from "../../installation"
import { Global } from "../../global"
import fs from "fs/promises"
@@ -57,7 +58,7 @@ export const UninstallCommand = {
UI.empty()
prompts.intro("Uninstall OpenCode")
const method = await Installation.method()
const method = await AppRuntime.runPromise(Installation.Service.use((svc) => svc.method()))
prompts.log.info(`Installation method: ${method}`)
const targets = await collectRemovalTargets(args, method)
+8 -3
View File
@@ -1,6 +1,7 @@
import type { Argv } from "yargs"
import { UI } from "../ui"
import * as prompts from "@clack/prompts"
import { AppRuntime } from "@/effect/app-runtime"
import { Installation } from "../../installation"
export const UpgradeCommand = {
@@ -24,7 +25,7 @@ export const UpgradeCommand = {
UI.println(UI.logo(" "))
UI.empty()
prompts.intro("Upgrade")
const detectedMethod = await Installation.method()
const detectedMethod = await AppRuntime.runPromise(Installation.Service.use((svc) => svc.method()))
const method = (args.method as Installation.Method) ?? detectedMethod
if (method === "unknown") {
prompts.log.error(`opencode is installed to ${process.execPath} and may be managed by a package manager`)
@@ -42,7 +43,9 @@ export const UpgradeCommand = {
}
}
prompts.log.info("Using method: " + method)
const target = args.target ? args.target.replace(/^v/, "") : await Installation.latest()
const target = args.target
? args.target.replace(/^v/, "")
: await AppRuntime.runPromise(Installation.Service.use((svc) => svc.latest()))
if (Installation.VERSION === target) {
prompts.log.warn(`opencode upgrade skipped: ${target} is already installed`)
@@ -53,7 +56,9 @@ export const UpgradeCommand = {
prompts.log.info(`From ${Installation.VERSION}${target}`)
const spinner = prompts.spinner()
spinner.start("Upgrading...")
const err = await Installation.upgrade(method, target).catch((err) => err)
const err = await AppRuntime.runPromise(Installation.Service.use((svc) => svc.upgrade(method, target))).catch(
(err) => err,
)
if (err) {
spinner.stop("Upgrade failed", 1)
if (err instanceof Installation.UpgradeFailedError) {
+4 -3
View File
@@ -1,12 +1,13 @@
import { Bus } from "@/bus"
import { Config } from "@/config/config"
import { AppRuntime } from "@/effect/app-runtime"
import { Flag } from "@/flag/flag"
import { Installation } from "@/installation"
export async function upgrade() {
const config = await Config.getGlobal()
const method = await Installation.method()
const latest = await Installation.latest(method).catch(() => {})
const method = await AppRuntime.runPromise(Installation.Service.use((svc) => svc.method()))
const latest = await AppRuntime.runPromise(Installation.Service.use((svc) => svc.latest(method))).catch(() => {})
if (!latest) return
if (Flag.OPENCODE_ALWAYS_NOTIFY_UPDATE) {
@@ -25,7 +26,7 @@ export async function upgrade() {
}
if (method === "unknown") return
await Installation.upgrade(method, latest)
await AppRuntime.runPromise(Installation.Service.use((svc) => svc.upgrade(method, latest)))
.then(() => Bus.publish(Installation.Event.Updated, { version: latest }))
.catch(() => {})
}
-7
View File
@@ -1,6 +1,5 @@
import { BusEvent } from "@/bus/bus-event"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
import type { InstanceContext } from "@/project/instance"
import { SessionID, MessageID } from "@/session/schema"
import { Effect, Layer, Context } from "effect"
@@ -189,10 +188,4 @@ export namespace Command {
Layer.provide(MCP.defaultLayer),
Layer.provide(Skill.defaultLayer),
)
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function list() {
return runPromise((svc) => svc.list())
}
}
@@ -0,0 +1,10 @@
import { Layer, ManagedRuntime } from "effect"
import { memoMap } from "./run-service"
import { Format } from "@/format"
import { ShareNext } from "@/share/share-next"
import { Snapshot } from "@/snapshot"
export const BootstrapLayer = Layer.mergeAll(Format.defaultLayer, ShareNext.defaultLayer, Snapshot.defaultLayer)
export const BootstrapRuntime = ManagedRuntime.make(BootstrapLayer, { memoMap })
-15
View File
@@ -2,7 +2,6 @@ import { Effect, Layer, Context } from "effect"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
import path from "path"
import { mergeDeep } from "remeda"
import z from "zod"
@@ -193,18 +192,4 @@ export namespace Format {
Layer.provide(Config.defaultLayer),
Layer.provide(CrossSpawnSpawner.defaultLayer),
)
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function init() {
return runPromise((s) => s.init())
}
export async function status() {
return runPromise((s) => s.status())
}
export async function file(filepath: string) {
return runPromise((s) => s.file(filepath))
}
}
-11
View File
@@ -1,7 +1,6 @@
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
import { Effect, Layer, Context, Stream } from "effect"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import { makeRuntime } from "@/effect/run-service"
export namespace Git {
const cfg = [
@@ -258,14 +257,4 @@ export namespace Git {
)
export const defaultLayer = layer.pipe(Layer.provide(CrossSpawnSpawner.defaultLayer))
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function run(args: string[], opts: Options) {
return runPromise((git) => git.run(args, opts))
}
export async function defaultBranch(cwd: string) {
return runPromise((git) => git.defaultBranch(cwd))
}
}
@@ -1,7 +1,6 @@
import { Effect, Layer, Schema, Context, Stream } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
import { makeRuntime } from "@/effect/run-service"
import { withTransientReadRetry } from "@/util/effect-http-client"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import path from "path"
@@ -338,18 +337,4 @@ export namespace Installation {
Layer.provide(FetchHttpClient.layer),
Layer.provide(CrossSpawnSpawner.defaultLayer),
)
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function method(): Promise<Method> {
return runPromise((svc) => svc.method())
}
export async function latest(installMethod?: Method): Promise<string> {
return runPromise((svc) => svc.latest(installMethod))
}
export async function upgrade(m: Method, target: string): Promise<void> {
return runPromise((svc) => svc.upgrade(m, target))
}
}
+4 -4
View File
@@ -10,19 +10,19 @@ import { Bus } from "../bus"
import { Command } from "../command"
import { Instance } from "./instance"
import { Log } from "@/util/log"
import { AppRuntime } from "@/effect/app-runtime"
import { BootstrapRuntime } from "@/effect/bootstrap-runtime"
import { ShareNext } from "@/share/share-next"
export async function InstanceBootstrap() {
Log.Default.info("bootstrapping", { directory: Instance.directory })
await Plugin.init()
void AppRuntime.runPromise(ShareNext.Service.use((svc) => svc.init()))
Format.init()
void BootstrapRuntime.runPromise(ShareNext.Service.use((svc) => svc.init()))
void BootstrapRuntime.runPromise(Format.Service.use((svc) => svc.init()))
await LSP.init()
File.init()
FileWatcher.init()
Vcs.init()
Snapshot.init()
void BootstrapRuntime.runPromise(Snapshot.Service.use((svc) => svc.init()))
Bus.subscribe(Command.Event.Executed, async (payload) => {
if (payload.properties.name === Command.Default.INIT) {
-19
View File
@@ -2,7 +2,6 @@ import type { AuthOAuthResult, Hooks } from "@opencode-ai/plugin"
import { NamedError } from "@opencode-ai/util/error"
import { Auth } from "@/auth"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
import { Plugin } from "../plugin"
import { ProviderID } from "./schema"
import { Array as Arr, Effect, Layer, Record, Result, Context } from "effect"
@@ -232,22 +231,4 @@ export namespace ProviderAuth {
export const defaultLayer = Layer.suspend(() =>
layer.pipe(Layer.provide(Auth.defaultLayer), Layer.provide(Plugin.defaultLayer)),
)
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function methods() {
return runPromise((svc) => svc.methods())
}
export async function authorize(input: {
providerID: ProviderID
method: number
inputs?: Record<string, string>
}): Promise<Authorization | undefined> {
return runPromise((svc) => svc.authorize(input))
}
export async function callback(input: { providerID: ProviderID; method: number; code?: string }) {
return runPromise((svc) => svc.callback(input))
}
}
+3 -2
View File
@@ -30,6 +30,7 @@ import { ProviderRoutes } from "./routes/provider"
import { EventRoutes } from "./routes/event"
import { errorHandler } from "./middleware"
import { getMimeType } from "hono/utils/mime"
import { AppRuntime } from "@/effect/app-runtime"
const log = Log.create({ service: "server" })
@@ -190,7 +191,7 @@ export const InstanceRoutes = (upgrade: UpgradeWebSocket, app: Hono = new Hono()
},
}),
async (c) => {
const commands = await Command.list()
const commands = await AppRuntime.runPromise(Command.Service.use((svc) => svc.list()))
return c.json(commands)
},
)
@@ -277,7 +278,7 @@ export const InstanceRoutes = (upgrade: UpgradeWebSocket, app: Hono = new Hono()
},
}),
async (c) => {
return c.json(await Format.status())
return c.json(await AppRuntime.runPromise(Format.Service.use((svc) => svc.status())))
},
)
.all("/*", async (c) => {
+36 -18
View File
@@ -1,10 +1,12 @@
import { Hono, type Context } from "hono"
import { describeRoute, resolver, validator } from "hono-openapi"
import { streamSSE } from "hono/streaming"
import { Effect } from "effect"
import z from "zod"
import { BusEvent } from "@/bus/bus-event"
import { SyncEvent } from "@/sync"
import { GlobalBus } from "@/bus/global"
import { AppRuntime } from "@/effect/app-runtime"
import { AsyncQueue } from "@/util/queue"
import { Instance } from "../../project/instance"
import { Installation } from "@/installation"
@@ -290,25 +292,41 @@ export const GlobalRoutes = lazy(() =>
}),
),
async (c) => {
const method = await Installation.method()
if (method === "unknown") {
return c.json({ success: false, error: "Unknown installation method" }, 400)
const result = await AppRuntime.runPromise(
Installation.Service.use((svc) =>
Effect.gen(function* () {
const method = yield* svc.method()
if (method === "unknown") {
return { success: false as const, status: 400 as const, error: "Unknown installation method" }
}
const target = c.req.valid("json").target || (yield* svc.latest(method))
const result = yield* Effect.catch(
svc.upgrade(method, target).pipe(Effect.as({ success: true as const, version: target })),
(err) =>
Effect.succeed({
success: false as const,
status: 500 as const,
error: err instanceof Error ? err.message : String(err),
}),
)
if (!result.success) return result
return { ...result, status: 200 as const }
}),
),
)
if (!result.success) {
return c.json({ success: false, error: result.error }, result.status)
}
const target = c.req.valid("json").target || (await Installation.latest(method))
const result = await Installation.upgrade(method, target)
.then(() => ({ success: true as const, version: target }))
.catch((e) => ({ success: false as const, error: e instanceof Error ? e.message : String(e) }))
if (result.success) {
GlobalBus.emit("event", {
directory: "global",
payload: {
type: Installation.Event.Updated.type,
properties: { version: target },
},
})
return c.json(result)
}
return c.json(result, 500)
const target = result.version
GlobalBus.emit("event", {
directory: "global",
payload: {
type: Installation.Event.Updated.type,
properties: { version: target },
},
})
return c.json({ success: true, version: target })
},
),
)
+20 -11
View File
@@ -6,6 +6,7 @@ import { Provider } from "../../provider/provider"
import { ModelsDev } from "../../provider/models"
import { ProviderAuth } from "../../provider/auth"
import { ProviderID } from "../../provider/schema"
import { AppRuntime } from "../../effect/app-runtime"
import { mapValues } from "remeda"
import { errors } from "../error"
import { lazy } from "../../util/lazy"
@@ -81,7 +82,7 @@ export const ProviderRoutes = lazy(() =>
},
}),
async (c) => {
return c.json(await ProviderAuth.methods())
return c.json(await AppRuntime.runPromise(ProviderAuth.Service.use((svc) => svc.methods())))
},
)
.post(
@@ -118,11 +119,15 @@ export const ProviderRoutes = lazy(() =>
async (c) => {
const providerID = c.req.valid("param").providerID
const { method, inputs } = c.req.valid("json")
const result = await ProviderAuth.authorize({
providerID,
method,
inputs,
})
const result = await AppRuntime.runPromise(
ProviderAuth.Service.use((svc) =>
svc.authorize({
providerID,
method,
inputs,
}),
),
)
return c.json(result)
},
)
@@ -160,11 +165,15 @@ export const ProviderRoutes = lazy(() =>
async (c) => {
const providerID = c.req.valid("param").providerID
const { method, code } = c.req.valid("json")
await ProviderAuth.callback({
providerID,
method,
code,
})
await AppRuntime.runPromise(
ProviderAuth.Service.use((svc) =>
svc.callback({
providerID,
method,
code,
}),
),
)
return c.json(true)
},
),
+4 -21
View File
@@ -353,16 +353,10 @@ export namespace Session {
delta: string
}) => Effect.Effect<void>
/** Finds the first message matching the predicate, searching newest-first. */
readonly findMessage: {
<T extends MessageV2.WithParts>(
sessionID: SessionID,
predicate: (msg: MessageV2.WithParts) => msg is T,
): Effect.Effect<Option.Option<T>>
(
sessionID: SessionID,
predicate: (msg: MessageV2.WithParts) => boolean,
): Effect.Effect<Option.Option<MessageV2.WithParts>>
}
readonly findMessage: (
sessionID: SessionID,
predicate: (msg: MessageV2.WithParts) => boolean,
) => Effect.Effect<Option.Option<MessageV2.WithParts>>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Session") {}
@@ -856,15 +850,4 @@ export namespace Session {
MessageV2.Part.parse(part)
return runPromise((svc) => svc.updatePart(part))
}
export const updatePartDelta = fn(
z.object({
sessionID: SessionID.zod,
messageID: MessageID.zod,
partID: PartID.zod,
field: z.string(),
delta: z.string(),
}),
(input) => runPromise((svc) => svc.updatePartDelta(input)),
)
}
+24 -32
View File
@@ -364,21 +364,19 @@ NOTE: At any point in time through this workflow you should feel free to ask the
agent: input.agent.name,
messages: input.messages,
metadata: (val) =>
run.promise(
input.processor.updateToolCall(options.toolCallId, (match) => {
if (!["running", "pending"].includes(match.state.status)) return match
return {
...match,
state: {
title: val.title,
metadata: val.metadata,
status: "running",
input: args,
time: { start: Date.now() },
},
}
}),
),
input.processor.updateToolCall(options.toolCallId, (match) => {
if (!["running", "pending"].includes(match.state.status)) return match
return {
...match,
state: {
title: val.title,
metadata: val.metadata,
status: "running",
input: args,
time: { start: Date.now() },
},
}
}),
ask: (req) =>
permission
.ask({
@@ -592,17 +590,14 @@ NOTE: At any point in time through this workflow you should feel free to ask the
callID: part.callID,
extra: { bypassAgentCheck: true, promptOps },
messages: msgs,
metadata(val: { title?: string; metadata?: Record<string, any> }) {
return run.promise(
Effect.gen(function* () {
part = yield* sessions.updatePart({
...part,
type: "tool",
state: { ...part.state, ...val },
} satisfies MessageV2.ToolPart)
}),
)
},
metadata: (val: { title?: string; metadata?: Record<string, any> }) =>
Effect.gen(function* () {
part = yield* sessions.updatePart({
...part,
type: "tool",
state: { ...part.state, ...val },
} satisfies MessageV2.ToolPart)
}),
ask: (req: any) =>
permission
.ask({
@@ -907,11 +902,8 @@ NOTE: At any point in time through this workflow you should feel free to ask the
})
const lastModel = Effect.fnUntraced(function* (sessionID: SessionID) {
const match = yield* sessions.findMessage(
sessionID,
(m): m is MessageV2.WithParts & { info: MessageV2.User } => m.info.role === "user" && !!m.info.model,
)
if (Option.isSome(match)) return match.value.info.model
const match = yield* sessions.findMessage(sessionID, (m) => m.info.role === "user" && !!m.info.model)
if (Option.isSome(match) && match.value.info.role === "user") return match.value.info.model
return yield* provider.defaultModel()
})
@@ -1053,7 +1045,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
messageID: info.id,
extra: { bypassCwdCheck: true, ...extra },
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
})
.pipe(Effect.onInterrupt(() => Effect.sync(() => controller.abort())))
-31
View File
@@ -5,7 +5,6 @@ import path from "path"
import z from "zod"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
import { AppFileSystem } from "@/filesystem"
import { Hash } from "@/util/hash"
import { Config } from "../config/config"
@@ -690,34 +689,4 @@ export namespace Snapshot {
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Config.defaultLayer),
)
const { runPromise } = makeRuntime(Service, defaultLayer)
export async function init() {
return runPromise((svc) => svc.init())
}
export async function track() {
return runPromise((svc) => svc.track())
}
export async function patch(hash: string) {
return runPromise((svc) => svc.patch(hash))
}
export async function restore(snapshot: string) {
return runPromise((svc) => svc.restore(snapshot))
}
export async function revert(patches: Patch[]) {
return runPromise((svc) => svc.revert(patches))
}
export async function diff(hash: string) {
return runPromise((svc) => svc.diff(hash))
}
export async function diffFull(from: string, to: string) {
return runPromise((svc) => svc.diffFull(from, to))
}
}
+10 -12
View File
@@ -385,7 +385,7 @@ export const BashTool = Tool.define(
let expired = false
let aborted = false
ctx.metadata({
yield* ctx.metadata({
metadata: {
output: "",
description: input.description,
@@ -397,17 +397,15 @@ export const BashTool = Tool.define(
const handle = yield* spawner.spawn(cmd(input.shell, input.name, input.command, input.cwd, input.env))
yield* Effect.forkScoped(
Stream.runForEach(Stream.decodeText(handle.all), (chunk) =>
Effect.sync(() => {
output += chunk
ctx.metadata({
metadata: {
output: preview(output),
description: input.description,
},
})
}),
),
Stream.runForEach(Stream.decodeText(handle.all), (chunk) => {
output += chunk
return ctx.metadata({
metadata: {
output: preview(output),
description: input.description,
},
})
}),
)
const abort = Effect.callback<void>((resume) => {
+1 -1
View File
@@ -158,7 +158,7 @@ export const EditTool = Tool.define(
if (change.removed) filediff.deletions += change.count || 0
}
ctx.metadata({
yield* ctx.metadata({
metadata: {
diff,
filediff,
+1 -2
View File
@@ -30,7 +30,6 @@ import { Glob } from "../util/glob"
import path from "path"
import { pathToFileURL } from "url"
import { Effect, Layer, Context } from "effect"
import { EffectLogger } from "@/effect/logger"
import { FetchHttpClient, HttpClient } from "effect/unstable/http"
import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
@@ -137,7 +136,7 @@ export namespace ToolRegistry {
Effect.gen(function* () {
const pluginCtx: PluginToolContext = {
...toolCtx,
ask: (req) => Effect.runPromise(toolCtx.ask(req).pipe(Effect.provide(EffectLogger.layer))),
ask: (req) => toolCtx.ask(req),
directory: ctx.directory,
worktree: ctx.worktree,
}
+32 -36
View File
@@ -36,6 +36,7 @@ export const TaskTool = Tool.define(
Effect.gen(function* () {
const agent = yield* Agent.Service
const config = yield* Config.Service
const sessions = yield* Session.Service
const run = Effect.fn("TaskTool.execute")(function* (params: z.infer<typeof parameters>, ctx: Tool.Context) {
const cfg = yield* config.get()
@@ -62,44 +63,39 @@ export const TaskTool = Tool.define(
const taskID = params.task_id
const session = taskID
? yield* Effect.promise(() => {
const id = SessionID.make(taskID)
return Session.get(id).catch(() => undefined)
})
? yield* sessions.get(SessionID.make(taskID)).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
: undefined
const nextSession =
session ??
(yield* Effect.promise(() =>
Session.create({
parentID: ctx.sessionID,
title: params.description + ` (@${next.name} subagent)`,
permission: [
...(canTodo
? []
: [
{
permission: "todowrite" as const,
pattern: "*" as const,
action: "deny" as const,
},
]),
...(canTask
? []
: [
{
permission: id,
pattern: "*" as const,
action: "deny" as const,
},
]),
...(cfg.experimental?.primary_tools?.map((item) => ({
pattern: "*",
action: "allow" as const,
permission: item,
})) ?? []),
],
}),
))
(yield* sessions.create({
parentID: ctx.sessionID,
title: params.description + ` (@${next.name} subagent)`,
permission: [
...(canTodo
? []
: [
{
permission: "todowrite" as const,
pattern: "*" as const,
action: "deny" as const,
},
]),
...(canTask
? []
: [
{
permission: id,
pattern: "*" as const,
action: "deny" as const,
},
]),
...(cfg.experimental?.primary_tools?.map((item) => ({
pattern: "*",
action: "allow" as const,
permission: item,
})) ?? []),
],
}))
const msg = yield* Effect.sync(() => MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID }))
if (msg.info.role !== "assistant") return yield* Effect.fail(new Error("Not an assistant message"))
@@ -109,7 +105,7 @@ export const TaskTool = Tool.define(
providerID: msg.info.providerID,
}
ctx.metadata({
yield* ctx.metadata({
title: params.description,
metadata: {
sessionId: nextSession.id,
+1 -1
View File
@@ -22,7 +22,7 @@ export namespace Tool {
callID?: string
extra?: { [key: string]: any }
messages: MessageV2.WithParts[]
metadata(input: { title?: string; metadata?: M }): void
metadata(input: { title?: string; metadata?: M }): Effect.Effect<void>
ask(input: Omit<Permission.Request, "id" | "sessionID" | "tool">): Effect.Effect<void>
}
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test"
import path from "path"
import fs from "fs/promises"
import { Effect } from "effect"
import { tmpdir } from "../fixture/fixture"
import { Instance } from "../../src/project/instance"
import { ProviderAuth } from "../../src/provider/auth"
@@ -39,14 +40,18 @@ describe("plugin.auth-override", () => {
const methods = await Instance.provide({
directory: tmp.path,
fn: async () => {
return ProviderAuth.methods()
return Effect.runPromise(
ProviderAuth.Service.use((svc) => svc.methods()).pipe(Effect.provide(ProviderAuth.defaultLayer)),
)
},
})
const plainMethods = await Instance.provide({
directory: plain.path,
fn: async () => {
return ProviderAuth.methods()
return Effect.runPromise(
ProviderAuth.Service.use((svc) => svc.methods()).pipe(Effect.provide(ProviderAuth.defaultLayer)),
)
},
})
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test"
import path from "path"
import { GlobalBus } from "../../src/bus/global"
import { Snapshot } from "../../src/snapshot"
import { AppRuntime } from "../../src/effect/app-runtime"
import { InstanceBootstrap } from "../../src/project/bootstrap"
import { Instance } from "../../src/project/instance"
import { Server } from "../../src/server/server"
@@ -64,7 +65,7 @@ describe("project.initGit endpoint", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
expect(await Snapshot.track()).toBeTruthy()
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))).toBeTruthy()
},
})
} finally {
@@ -7,6 +7,7 @@ import { SessionRevert } from "../../src/session/revert"
import { SessionCompaction } from "../../src/session/compaction"
import { MessageV2 } from "../../src/session/message-v2"
import { Snapshot } from "../../src/snapshot"
import { AppRuntime } from "../../src/effect/app-runtime"
import { Log } from "../../src/util/log"
import { Instance } from "../../src/project/instance"
import { MessageID, PartID } from "../../src/session/schema"
@@ -460,12 +461,12 @@ describe("revert + compact workflow", () => {
const u = await user(sid)
await text(sid, u.id, `${file}:${next}`)
const a = await assistant(sid, u.id, tmp.path)
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
if (!before) throw new Error("expected snapshot")
await fs.writeFile(path.join(tmp.path, file), next)
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
if (!after) throw new Error("expected snapshot")
const patch = await Snapshot.patch(before)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before)))
await Session.updatePart({
id: PartID.ascending(),
messageID: a.id,
@@ -550,12 +551,12 @@ describe("revert + compact workflow", () => {
const u = await user(sid)
await text(sid, u.id, `a.txt:${next}`)
const a = await assistant(sid, u.id, tmp.path)
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
if (!before) throw new Error("expected snapshot")
await fs.writeFile(path.join(tmp.path, "a.txt"), next)
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
if (!after) throw new Error("expected snapshot")
const patch = await Snapshot.patch(before)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before)))
await Session.updatePart({
id: PartID.ascending(),
messageID: a.id,
+144 -139
View File
@@ -3,11 +3,12 @@ import { $ } from "bun"
import fs from "fs/promises"
import path from "path"
import { Snapshot } from "../../src/snapshot"
import { AppRuntime } from "../../src/effect/app-runtime"
import { Instance } from "../../src/project/instance"
import { Filesystem } from "../../src/util/filesystem"
import { tmpdir } from "../fixture/fixture"
// Git always outputs /-separated paths internally. Snapshot.patch() joins them
// Git always outputs /-separated paths internally. AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch())) joins them
// with path.join (which produces \ on Windows) then normalizes back to /.
// This helper does the same for expected values so assertions match cross-platform.
const fwd = (...parts: string[]) => path.join(...parts).replaceAll("\\", "/")
@@ -40,12 +41,12 @@ test("tracks deleted files correctly", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`rm ${tmp.path}/a.txt`.quiet()
expect((await Snapshot.patch(before!)).files).toContain(fwd(tmp.path, "a.txt"))
expect((await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files).toContain(fwd(tmp.path, "a.txt"))
},
})
})
@@ -55,12 +56,13 @@ test("revert should remove new files", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/new.txt`, "NEW")
await Snapshot.revert([await Snapshot.patch(before!)])
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -77,13 +79,14 @@ test("revert in subdirectory", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`mkdir -p ${tmp.path}/sub`.quiet()
await Filesystem.write(`${tmp.path}/sub/file.txt`, "SUB")
await Snapshot.revert([await Snapshot.patch(before!)])
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -102,7 +105,7 @@ test("multiple file operations", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`rm ${tmp.path}/a.txt`.quiet()
@@ -111,7 +114,8 @@ test("multiple file operations", async () => {
await Filesystem.write(`${tmp.path}/dir/d.txt`, "D")
await Filesystem.write(`${tmp.path}/b.txt`, "MODIFIED")
await Snapshot.revert([await Snapshot.patch(before!)])
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(await fs.readFile(`${tmp.path}/a.txt`, "utf-8")).toBe(tmp.extra.aContent)
expect(
@@ -132,12 +136,12 @@ test("empty directory handling", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`mkdir ${tmp.path}/empty`.quiet()
expect((await Snapshot.patch(before!)).files.length).toBe(0)
expect((await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files.length).toBe(0)
},
})
})
@@ -147,15 +151,15 @@ test("binary file handling", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/image.png`, new Uint8Array([0x89, 0x50, 0x4e, 0x47]))
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(fwd(tmp.path, "image.png"))
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
.access(`${tmp.path}/image.png`)
@@ -171,12 +175,12 @@ test("symlink handling", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await fs.symlink(`${tmp.path}/a.txt`, `${tmp.path}/link.txt`, "file")
expect((await Snapshot.patch(before!)).files).toContain(fwd(tmp.path, "link.txt"))
expect((await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files).toContain(fwd(tmp.path, "link.txt"))
},
})
})
@@ -186,12 +190,12 @@ test("file under size limit handling", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/large.txt`, "x".repeat(1024 * 1024))
expect((await Snapshot.patch(before!)).files).toContain(fwd(tmp.path, "large.txt"))
expect((await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files).toContain(fwd(tmp.path, "large.txt"))
},
})
})
@@ -201,14 +205,14 @@ test("large added files are skipped", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/huge.txt`, new Uint8Array(2 * 1024 * 1024 + 1))
expect((await Snapshot.patch(before!)).files).toEqual([])
expect(await Snapshot.diff(before!)).toBe("")
expect(await Snapshot.track()).toBe(before)
expect((await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files).toEqual([])
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diff(before!)))).toBe("")
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))).toBe(before)
},
})
})
@@ -218,13 +222,14 @@ test("nested directory revert", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`mkdir -p ${tmp.path}/level1/level2/level3`.quiet()
await Filesystem.write(`${tmp.path}/level1/level2/level3/deep.txt`, "DEEP")
await Snapshot.revert([await Snapshot.patch(before!)])
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -241,14 +246,14 @@ test("special characters in filenames", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/file with spaces.txt`, "SPACES")
await Filesystem.write(`${tmp.path}/file-with-dashes.txt`, "DASHES")
await Filesystem.write(`${tmp.path}/file_with_underscores.txt`, "UNDERSCORES")
const files = (await Snapshot.patch(before!)).files
const files = (await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))).files
expect(files).toContain(fwd(tmp.path, "file with spaces.txt"))
expect(files).toContain(fwd(tmp.path, "file-with-dashes.txt"))
expect(files).toContain(fwd(tmp.path, "file_with_underscores.txt"))
@@ -262,10 +267,10 @@ test("revert with empty patches", async () => {
directory: tmp.path,
fn: async () => {
// Should not crash with empty patches
expect(Snapshot.revert([])).resolves.toBeUndefined()
expect(AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([])))).resolves.toBeUndefined()
// Should not crash with patches that have empty file lists
expect(Snapshot.revert([{ hash: "dummy", files: [] }])).resolves.toBeUndefined()
expect(AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([{ hash: "dummy", files: [] }])))).resolves.toBeUndefined()
},
})
})
@@ -275,14 +280,14 @@ test("patch with invalid hash", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Create a change
await Filesystem.write(`${tmp.path}/test.txt`, "TEST")
// Try to patch with invalid hash - should handle gracefully
const patch = await Snapshot.patch("invalid-hash-12345")
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch("invalid-hash-12345")))
expect(patch.files).toEqual([])
expect(patch.hash).toBe("invalid-hash-12345")
},
@@ -294,18 +299,18 @@ test("revert non-existent file", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Try to revert a file that doesn't exist in the snapshot
// This should not crash
expect(
Snapshot.revert([
AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([
{
hash: before!,
files: [`${tmp.path}/nonexistent.txt`],
},
]),
]))),
).resolves.toBeUndefined()
},
})
@@ -316,7 +321,7 @@ test("unicode filenames", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const unicodeFiles = [
@@ -330,14 +335,14 @@ test("unicode filenames", async () => {
await Filesystem.write(file.path, file.content)
}
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files.length).toBe(4)
for (const file of unicodeFiles) {
expect(patch.files).toContain(file.path)
}
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
for (const file of unicodeFiles) {
expect(
@@ -362,17 +367,17 @@ test.skip("unicode filenames modification and restore", async () => {
await Filesystem.write(chineseFile, "original chinese")
await Filesystem.write(cyrillicFile, "original cyrillic")
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(chineseFile, "modified chinese")
await Filesystem.write(cyrillicFile, "modified cyrillic")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(chineseFile)
expect(patch.files).toContain(cyrillicFile)
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(await fs.readFile(chineseFile, "utf-8")).toBe("original chinese")
expect(await fs.readFile(cyrillicFile, "utf-8")).toBe("original cyrillic")
@@ -385,17 +390,17 @@ test("unicode filenames in subdirectories", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`mkdir -p "${tmp.path}/目录/подкаталог"`.quiet()
const deepFile = fwd(tmp.path, "目录", "подкаталог", "文件.txt")
await Filesystem.write(deepFile, "deep unicode content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(deepFile)
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
.access(deepFile)
@@ -411,7 +416,7 @@ test("very long filenames", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const longName = "a".repeat(200) + ".txt"
@@ -419,10 +424,10 @@ test("very long filenames", async () => {
await Filesystem.write(longFile, "long filename content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(longFile)
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
.access(longFile)
@@ -438,14 +443,14 @@ test("hidden files", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/.hidden`, "hidden content")
await Filesystem.write(`${tmp.path}/.gitignore`, "*.log")
await Filesystem.write(`${tmp.path}/.config`, "config content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(fwd(tmp.path, ".hidden"))
expect(patch.files).toContain(fwd(tmp.path, ".gitignore"))
expect(patch.files).toContain(fwd(tmp.path, ".config"))
@@ -458,7 +463,7 @@ test("nested symlinks", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`mkdir -p ${tmp.path}/sub/dir`.quiet()
@@ -466,7 +471,7 @@ test("nested symlinks", async () => {
await fs.symlink(`${tmp.path}/sub/dir/target.txt`, `${tmp.path}/sub/dir/link.txt`, "file")
await fs.symlink(`${tmp.path}/sub`, `${tmp.path}/sub-link`, "dir")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(fwd(tmp.path, "sub", "dir", "link.txt"))
expect(patch.files).toContain(fwd(tmp.path, "sub-link"))
},
@@ -478,7 +483,7 @@ test("file permissions and ownership changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Change permissions multiple times
@@ -486,7 +491,7 @@ test("file permissions and ownership changes", async () => {
await $`chmod 755 ${tmp.path}/a.txt`.quiet()
await $`chmod 644 ${tmp.path}/a.txt`.quiet()
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
// Note: git doesn't track permission changes on existing files by default
// Only tracks executable bit when files are first added
expect(patch.files.length).toBe(0)
@@ -499,13 +504,13 @@ test("circular symlinks", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Create circular symlink
await fs.symlink(`${tmp.path}/circular`, `${tmp.path}/circular`, "dir").catch(() => {})
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files.length).toBeGreaterThanOrEqual(0) // Should not crash
},
})
@@ -516,14 +521,14 @@ test("gitignore changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/.gitignore`, "*.ignored")
await Filesystem.write(`${tmp.path}/test.ignored`, "ignored content")
await Filesystem.write(`${tmp.path}/normal.txt`, "normal content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
// Should track gitignore itself
expect(patch.files).toContain(fwd(tmp.path, ".gitignore"))
@@ -540,7 +545,7 @@ test("git info exclude changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const file = `${tmp.path}/.git/info/exclude`
@@ -549,12 +554,12 @@ test("git info exclude changes", async () => {
await Bun.write(`${tmp.path}/ignored.txt`, "ignored content")
await Bun.write(`${tmp.path}/normal.txt`, "normal content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(fwd(tmp.path, "normal.txt"))
expect(patch.files).not.toContain(fwd(tmp.path, "ignored.txt"))
const after = await Snapshot.track()
const diffs = await Snapshot.diffFull(before!, after!)
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.some((x) => x.file === "normal.txt")).toBe(true)
expect(diffs.some((x) => x.file === "ignored.txt")).toBe(false)
},
@@ -574,7 +579,7 @@ test("git info exclude keeps global excludes", async () => {
const prev = process.env.GIT_CONFIG_GLOBAL
process.env.GIT_CONFIG_GLOBAL = config
try {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const file = `${tmp.path}/.git/info/exclude`
@@ -585,7 +590,7 @@ test("git info exclude keeps global excludes", async () => {
await Bun.write(`${tmp.path}/info.tmp`, "info content")
await Bun.write(`${tmp.path}/normal.txt`, "normal content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(fwd(tmp.path, "normal.txt"))
expect(patch.files).not.toContain(fwd(tmp.path, "global.tmp"))
expect(patch.files).not.toContain(fwd(tmp.path, "info.tmp"))
@@ -602,7 +607,7 @@ test("concurrent file operations during patch", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Start creating files
@@ -615,7 +620,7 @@ test("concurrent file operations during patch", async () => {
})()
// Get patch while files are being created
const patchPromise = Snapshot.patch(before!)
const patchPromise = AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await createPromise
const patch = await patchPromise
@@ -634,9 +639,9 @@ test("snapshot state isolation between projects", async () => {
await Instance.provide({
directory: tmp1.path,
fn: async () => {
const before1 = await Snapshot.track()
const before1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
await Filesystem.write(`${tmp1.path}/project1.txt`, "project1 content")
const patch1 = await Snapshot.patch(before1!)
const patch1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before1!)))
expect(patch1.files).toContain(fwd(tmp1.path, "project1.txt"))
},
})
@@ -644,9 +649,9 @@ test("snapshot state isolation between projects", async () => {
await Instance.provide({
directory: tmp2.path,
fn: async () => {
const before2 = await Snapshot.track()
const before2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
await Filesystem.write(`${tmp2.path}/project2.txt`, "project2 content")
const patch2 = await Snapshot.patch(before2!)
const patch2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before2!)))
expect(patch2.files).toContain(fwd(tmp2.path, "project2.txt"))
// Ensure project1 files don't appear in project2
@@ -664,20 +669,20 @@ test("patch detects changes in secondary worktree", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
expect(await Snapshot.track()).toBeTruthy()
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))).toBeTruthy()
},
})
await Instance.provide({
directory: worktreePath,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const worktreeFile = fwd(worktreePath, "worktree.txt")
await Filesystem.write(worktreeFile, "worktree content")
const patch = await Snapshot.patch(before!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
expect(patch.files).toContain(worktreeFile)
},
})
@@ -696,7 +701,7 @@ test("revert only removes files in invoking worktree", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
expect(await Snapshot.track()).toBeTruthy()
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))).toBeTruthy()
},
})
const primaryFile = `${tmp.path}/worktree.txt`
@@ -705,14 +710,14 @@ test("revert only removes files in invoking worktree", async () => {
await Instance.provide({
directory: worktreePath,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const worktreeFile = fwd(worktreePath, "worktree.txt")
await Filesystem.write(worktreeFile, "worktree content")
const patch = await Snapshot.patch(before!)
await Snapshot.revert([patch])
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(before!)))
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -740,14 +745,14 @@ test("diff reports worktree-only/shared edits and ignores primary-only", async (
await Instance.provide({
directory: tmp.path,
fn: async () => {
expect(await Snapshot.track()).toBeTruthy()
expect(await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))).toBeTruthy()
},
})
await Instance.provide({
directory: worktreePath,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${worktreePath}/worktree-only.txt`, "worktree diff content")
@@ -755,7 +760,7 @@ test("diff reports worktree-only/shared edits and ignores primary-only", async (
await Filesystem.write(`${tmp.path}/shared.txt`, "primary edit")
await Filesystem.write(`${tmp.path}/primary-only.txt`, "primary change")
const diff = await Snapshot.diff(before!)
const diff = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diff(before!)))
expect(diff).toContain("worktree-only.txt")
expect(diff).toContain("shared.txt")
expect(diff).not.toContain("primary-only.txt")
@@ -774,15 +779,15 @@ test("track with no changes returns same hash", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const hash1 = await Snapshot.track()
const hash1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(hash1).toBeTruthy()
// Track again with no changes
const hash2 = await Snapshot.track()
const hash2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(hash2).toBe(hash1!)
// Track again
const hash3 = await Snapshot.track()
const hash3 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(hash3).toBe(hash1!)
},
})
@@ -793,7 +798,7 @@ test("diff function with various changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Make various changes
@@ -801,7 +806,7 @@ test("diff function with various changes", async () => {
await Filesystem.write(`${tmp.path}/new.txt`, "new content")
await Filesystem.write(`${tmp.path}/b.txt`, "modified content")
const diff = await Snapshot.diff(before!)
const diff = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diff(before!)))
expect(diff).toContain("a.txt")
expect(diff).toContain("b.txt")
expect(diff).toContain("new.txt")
@@ -814,7 +819,7 @@ test("restore function", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
// Make changes
@@ -823,7 +828,7 @@ test("restore function", async () => {
await Filesystem.write(`${tmp.path}/b.txt`, "modified")
// Restore to original state
await Snapshot.restore(before!)
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.restore(before!)))
expect(
await fs
@@ -848,20 +853,20 @@ test("revert should not delete files that existed but were deleted in snapshot",
await Instance.provide({
directory: tmp.path,
fn: async () => {
const snapshot1 = await Snapshot.track()
const snapshot1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snapshot1).toBeTruthy()
await $`rm ${tmp.path}/a.txt`.quiet()
const snapshot2 = await Snapshot.track()
const snapshot2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snapshot2).toBeTruthy()
await Filesystem.write(`${tmp.path}/a.txt`, "recreated content")
const patch = await Snapshot.patch(snapshot2!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(snapshot2!)))
expect(patch.files).toContain(fwd(tmp.path, "a.txt"))
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -880,18 +885,18 @@ test("revert preserves file that existed in snapshot when deleted then recreated
fn: async () => {
await Filesystem.write(`${tmp.path}/existing.txt`, "original content")
const snapshot = await Snapshot.track()
const snapshot = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snapshot).toBeTruthy()
await $`rm ${tmp.path}/existing.txt`.quiet()
await Filesystem.write(`${tmp.path}/existing.txt`, "recreated")
await Filesystem.write(`${tmp.path}/newfile.txt`, "new")
const patch = await Snapshot.patch(snapshot!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(snapshot!)))
expect(patch.files).toContain(fwd(tmp.path, "existing.txt"))
expect(patch.files).toContain(fwd(tmp.path, "newfile.txt"))
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
expect(
await fs
@@ -919,7 +924,7 @@ test("diffFull sets status based on git change type", async () => {
await Filesystem.write(`${tmp.path}/trim.txt`, "line1\nline2\n")
await Filesystem.write(`${tmp.path}/delete.txt`, "gone")
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/grow.txt`, "one\ntwo\n")
@@ -927,10 +932,10 @@ test("diffFull sets status based on git change type", async () => {
await $`rm ${tmp.path}/delete.txt`.quiet()
await Filesystem.write(`${tmp.path}/added.txt`, "new")
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(4)
const added = diffs.find((d) => d.file === "added.txt")
@@ -961,15 +966,15 @@ test("diffFull with new file additions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/new.txt`, "new content")
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const newFileDiff = diffs[0]
@@ -999,7 +1004,7 @@ test("diffFull with a large interleaved mixed diff", async () => {
...bin.map((file, i) => Filesystem.write(file, new Uint8Array([0, i, 255, i % 251]))),
])
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Promise.all([
@@ -1009,10 +1014,10 @@ test("diffFull with a large interleaved mixed diff", async () => {
...del.map((file) => fs.rm(file)),
])
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs).toHaveLength(ids.length * 4)
const map = new Map(diffs.map((item) => [item.file, item]))
@@ -1054,17 +1059,17 @@ test("diffFull preserves git diff order across batch boundaries", async () => {
await $`mkdir -p ${tmp.path}/order`.quiet()
await Promise.all(ids.map((id) => Filesystem.write(`${tmp.path}/order/${id}.txt`, `before-${id}`)))
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Promise.all(ids.map((id) => Filesystem.write(`${tmp.path}/order/${id}.txt`, `after-${id}`)))
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const expected = ids.map((id) => `order/${id}.txt`)
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.map((item) => item.file)).toEqual(expected)
},
})
@@ -1075,15 +1080,15 @@ test("diffFull with file modifications", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/b.txt`, "modified content")
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const modifiedFileDiff = diffs[0]
@@ -1101,15 +1106,15 @@ test("diffFull with file deletions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await $`rm ${tmp.path}/a.txt`.quiet()
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const removedFileDiff = diffs[0]
@@ -1126,15 +1131,15 @@ test("diffFull with multiple line additions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/multi.txt`, "line1\nline2\nline3")
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const multiDiff = diffs[0]
@@ -1152,16 +1157,16 @@ test("diffFull with addition and deletion", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/added.txt`, "added content")
await $`rm ${tmp.path}/a.txt`.quiet()
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(2)
const addedFileDiff = diffs.find((d) => d.file === "added.txt")
@@ -1184,7 +1189,7 @@ test("diffFull with multiple additions and deletions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/multi1.txt`, "line1\nline2\nline3")
@@ -1192,10 +1197,10 @@ test("diffFull with multiple additions and deletions", async () => {
await $`rm ${tmp.path}/a.txt`.quiet()
await $`rm ${tmp.path}/b.txt`.quiet()
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(4)
const multi1Diff = diffs.find((d) => d.file === "multi1.txt")
@@ -1226,13 +1231,13 @@ test("diffFull with no changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(0)
},
})
@@ -1243,15 +1248,15 @@ test("diffFull with binary file changes", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/binary.bin`, new Uint8Array([0x00, 0x01, 0x02, 0x03]))
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const binaryDiff = diffs[0]
@@ -1267,15 +1272,15 @@ test("diffFull with whitespace changes", async () => {
directory: tmp.path,
fn: async () => {
await Filesystem.write(`${tmp.path}/whitespace.txt`, "line1\nline2")
const before = await Snapshot.track()
const before = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(before).toBeTruthy()
await Filesystem.write(`${tmp.path}/whitespace.txt`, "line1\n\nline2\n")
const after = await Snapshot.track()
const after = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(after).toBeTruthy()
const diffs = await Snapshot.diffFull(before!, after!)
const diffs = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.diffFull(before!, after!)))
expect(diffs.length).toBe(1)
const whitespaceDiff = diffs[0]
@@ -1292,26 +1297,26 @@ test("revert with overlapping files across patches uses first patch hash", async
fn: async () => {
// Write initial content and snapshot
await Filesystem.write(`${tmp.path}/shared.txt`, "v1")
const snap1 = await Snapshot.track()
const snap1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snap1).toBeTruthy()
// Modify and snapshot again
await Filesystem.write(`${tmp.path}/shared.txt`, "v2")
const snap2 = await Snapshot.track()
const snap2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snap2).toBeTruthy()
// Modify once more so both patches include shared.txt
await Filesystem.write(`${tmp.path}/shared.txt`, "v3")
const patch1 = await Snapshot.patch(snap1!)
const patch2 = await Snapshot.patch(snap2!)
const patch1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(snap1!)))
const patch2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(snap2!)))
// Both patches should include shared.txt
expect(patch1.files).toContain(fwd(tmp.path, "shared.txt"))
expect(patch2.files).toContain(fwd(tmp.path, "shared.txt"))
// Revert with patch1 first — should use snap1's hash (restoring "v1")
await Snapshot.revert([patch1, patch2])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch1, patch2])))
const content = await fs.readFile(`${tmp.path}/shared.txt`, "utf-8")
expect(content).toBe("v1")
@@ -1328,24 +1333,24 @@ test("revert preserves patch order when the same hash appears again", async () =
await Filesystem.write(`${tmp.path}/foo/bar`, "v1")
await Filesystem.write(`${tmp.path}/a.txt`, "v1")
const snap1 = await Snapshot.track()
const snap1 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snap1).toBeTruthy()
await $`rm -rf ${tmp.path}/foo`.quiet()
await Filesystem.write(`${tmp.path}/foo`, "v2")
await Filesystem.write(`${tmp.path}/a.txt`, "v2")
const snap2 = await Snapshot.track()
const snap2 = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snap2).toBeTruthy()
await $`rm -rf ${tmp.path}/foo`.quiet()
await Filesystem.write(`${tmp.path}/a.txt`, "v3")
await Snapshot.revert([
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([
{ hash: snap1!, files: [fwd(tmp.path, "a.txt")] },
{ hash: snap2!, files: [fwd(tmp.path, "foo")] },
{ hash: snap1!, files: [fwd(tmp.path, "foo", "bar")] },
])
])))
expect(await fs.readFile(`${tmp.path}/a.txt`, "utf-8")).toBe("v1")
expect((await fs.stat(`${tmp.path}/foo`)).isDirectory()).toBe(true)
@@ -1365,16 +1370,16 @@ test("revert handles large mixed batches across chunk boundaries", async () => {
await $`mkdir -p ${tmp.path}/batch ${tmp.path}/fresh`.quiet()
await Promise.all(base.map((file, i) => Filesystem.write(file, `base-${i}`)))
const snap = await Snapshot.track()
const snap = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.track()))
expect(snap).toBeTruthy()
await Promise.all(base.map((file, i) => Filesystem.write(file, `next-${i}`)))
await Promise.all(fresh.map((file, i) => Filesystem.write(file, `fresh-${i}`)))
const patch = await Snapshot.patch(snap!)
const patch = await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.patch(snap!)))
expect(patch.files.length).toBe(base.length + fresh.length)
await Snapshot.revert([patch])
await AppRuntime.runPromise(Snapshot.Service.use((svc) => svc.revert([patch])))
await Promise.all(
base.map(async (file, i) => {
@@ -22,7 +22,7 @@ const baseCtx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
}
type AskInput = {
+14 -12
View File
@@ -29,7 +29,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
@@ -982,13 +982,14 @@ describe("tool.bash abort", () => {
{
...ctx,
abort: controller.signal,
metadata: (input) => {
const output = (input.metadata as { output?: string })?.output
if (output && output.includes("before") && !controller.signal.aborted) {
collected.push(output)
controller.abort()
}
},
metadata: (input) =>
Effect.sync(() => {
const output = (input.metadata as { output?: string })?.output
if (output && output.includes("before") && !controller.signal.aborted) {
collected.push(output)
controller.abort()
}
}),
},
),
)
@@ -1074,10 +1075,11 @@ describe("tool.bash abort", () => {
},
{
...ctx,
metadata: (input) => {
const output = (input.metadata as { output?: string })?.output
if (output) updates.push(output)
},
metadata: (input) =>
Effect.sync(() => {
const output = (input.metadata as { output?: string })?.output
if (output) updates.push(output)
}),
},
),
)
+1 -1
View File
@@ -20,7 +20,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
@@ -16,7 +16,7 @@ const baseCtx: Omit<Tool.Context, "ask"> = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
}
const glob = (p: string) =>
+1 -1
View File
@@ -20,7 +20,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
+1 -1
View File
@@ -15,7 +15,7 @@ const ctx = {
agent: "test-agent",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
+1 -1
View File
@@ -29,7 +29,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
+1 -1
View File
@@ -19,7 +19,7 @@ const baseCtx: Omit<Tool.Context, "ask"> = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
}
afterEach(async () => {
+4 -4
View File
@@ -209,7 +209,7 @@ describe("tool.task", () => {
abort: new AbortController().signal,
extra: { promptOps },
messages: [],
metadata() {},
metadata: () => Effect.void,
ask: () => Effect.void,
},
)
@@ -247,7 +247,7 @@ describe("tool.task", () => {
abort: new AbortController().signal,
extra: { promptOps, ...extra },
messages: [],
metadata() {},
metadata: () => Effect.void,
ask: (input) =>
Effect.sync(() => {
calls.push(input)
@@ -296,7 +296,7 @@ describe("tool.task", () => {
abort: new AbortController().signal,
extra: { promptOps },
messages: [],
metadata() {},
metadata: () => Effect.void,
ask: () => Effect.void,
},
)
@@ -335,7 +335,7 @@ describe("tool.task", () => {
abort: new AbortController().signal,
extra: { promptOps },
messages: [],
metadata() {},
metadata: () => Effect.void,
ask: () => Effect.void,
},
)
+1 -1
View File
@@ -15,7 +15,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
+1 -1
View File
@@ -22,7 +22,7 @@ const ctx = {
agent: "build",
abort: AbortSignal.any([]),
messages: [],
metadata: () => {},
metadata: () => Effect.void,
ask: () => Effect.void,
}
+1
View File
@@ -18,6 +18,7 @@
],
"dependencies": {
"@opencode-ai/sdk": "workspace:*",
"effect": "catalog:",
"zod": "catalog:"
},
"peerDependencies": {
+2 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod"
import { Effect } from "effect"
export type ToolContext = {
sessionID: string
@@ -16,7 +17,7 @@ export type ToolContext = {
worktree: string
abort: AbortSignal
metadata(input: { title?: string; metadata?: { [key: string]: any } }): void
ask(input: AskInput): Promise<void>
ask(input: AskInput): Effect.Effect<void>
}
type AskInput = {
+50 -50
View File
@@ -316,6 +316,29 @@ export type EventCommandExecuted = {
}
}
export type EventWorkspaceReady = {
type: "workspace.ready"
properties: {
name: string
}
}
export type EventWorkspaceFailed = {
type: "workspace.failed"
properties: {
message: string
}
}
export type EventWorkspaceStatus = {
type: "workspace.status"
properties: {
workspaceID: string
status: "connected" | "connecting" | "disconnected" | "error"
error?: string
}
}
export type QuestionOption = {
/**
* Display text (1-5 words, concise)
@@ -387,29 +410,6 @@ export type EventQuestionRejected = {
}
}
export type Todo = {
/**
* Brief description of the task
*/
content: string
/**
* Current status of the task: pending, in_progress, completed, cancelled
*/
status: string
/**
* Priority level of the task: high, medium, low
*/
priority: string
}
export type EventTodoUpdated = {
type: "todo.updated"
properties: {
sessionID: string
todos: Array<Todo>
}
}
export type SessionStatus =
| {
type: "idle"
@@ -446,6 +446,29 @@ export type EventSessionCompacted = {
}
}
export type Todo = {
/**
* Brief description of the task
*/
content: string
/**
* Current status of the task: pending, in_progress, completed, cancelled
*/
status: string
/**
* Priority level of the task: high, medium, low
*/
priority: string
}
export type EventTodoUpdated = {
type: "todo.updated"
properties: {
sessionID: string
todos: Array<Todo>
}
}
export type EventWorktreeReady = {
type: "worktree.ready"
properties: {
@@ -500,29 +523,6 @@ export type EventPtyDeleted = {
}
}
export type EventWorkspaceReady = {
type: "workspace.ready"
properties: {
name: string
}
}
export type EventWorkspaceFailed = {
type: "workspace.failed"
properties: {
message: string
}
}
export type EventWorkspaceStatus = {
type: "workspace.status"
properties: {
workspaceID: string
status: "connected" | "connecting" | "disconnected" | "error"
error?: string
}
}
export type OutputFormatText = {
type: "text"
}
@@ -995,22 +995,22 @@ export type Event =
| EventMcpToolsChanged
| EventMcpBrowserOpenFailed
| EventCommandExecuted
| EventWorkspaceReady
| EventWorkspaceFailed
| EventWorkspaceStatus
| EventQuestionAsked
| EventQuestionReplied
| EventQuestionRejected
| EventTodoUpdated
| EventSessionStatus
| EventSessionIdle
| EventSessionCompacted
| EventTodoUpdated
| EventWorktreeReady
| EventWorktreeFailed
| EventPtyCreated
| EventPtyUpdated
| EventPtyExited
| EventPtyDeleted
| EventWorkspaceReady
| EventWorkspaceFailed
| EventWorkspaceStatus
| EventMessageUpdated
| EventMessageRemoved
| EventMessagePartUpdated
+121 -121
View File
@@ -7986,6 +7986,71 @@
},
"required": ["type", "properties"]
},
"Event.workspace.ready": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.ready"
},
"properties": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": ["name"]
}
},
"required": ["type", "properties"]
},
"Event.workspace.failed": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.failed"
},
"properties": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
},
"required": ["message"]
}
},
"required": ["type", "properties"]
},
"Event.workspace.status": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.status"
},
"properties": {
"type": "object",
"properties": {
"workspaceID": {
"type": "string",
"pattern": "^wrk.*"
},
"status": {
"type": "string",
"enum": ["connected", "connecting", "disconnected", "error"]
},
"error": {
"type": "string"
}
},
"required": ["workspaceID", "status"]
}
},
"required": ["type", "properties"]
},
"QuestionOption": {
"type": "object",
"properties": {
@@ -8136,50 +8201,6 @@
},
"required": ["type", "properties"]
},
"Todo": {
"type": "object",
"properties": {
"content": {
"description": "Brief description of the task",
"type": "string"
},
"status": {
"description": "Current status of the task: pending, in_progress, completed, cancelled",
"type": "string"
},
"priority": {
"description": "Priority level of the task: high, medium, low",
"type": "string"
}
},
"required": ["content", "status", "priority"]
},
"Event.todo.updated": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "todo.updated"
},
"properties": {
"type": "object",
"properties": {
"sessionID": {
"type": "string",
"pattern": "^ses.*"
},
"todos": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Todo"
}
}
},
"required": ["sessionID", "todos"]
}
},
"required": ["type", "properties"]
},
"SessionStatus": {
"anyOf": [
{
@@ -8286,6 +8307,50 @@
},
"required": ["type", "properties"]
},
"Todo": {
"type": "object",
"properties": {
"content": {
"description": "Brief description of the task",
"type": "string"
},
"status": {
"description": "Current status of the task: pending, in_progress, completed, cancelled",
"type": "string"
},
"priority": {
"description": "Priority level of the task: high, medium, low",
"type": "string"
}
},
"required": ["content", "status", "priority"]
},
"Event.todo.updated": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "todo.updated"
},
"properties": {
"type": "object",
"properties": {
"sessionID": {
"type": "string",
"pattern": "^ses.*"
},
"todos": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Todo"
}
}
},
"required": ["sessionID", "todos"]
}
},
"required": ["type", "properties"]
},
"Event.worktree.ready": {
"type": "object",
"properties": {
@@ -8440,71 +8505,6 @@
},
"required": ["type", "properties"]
},
"Event.workspace.ready": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.ready"
},
"properties": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": ["name"]
}
},
"required": ["type", "properties"]
},
"Event.workspace.failed": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.failed"
},
"properties": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
},
"required": ["message"]
}
},
"required": ["type", "properties"]
},
"Event.workspace.status": {
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "workspace.status"
},
"properties": {
"type": "object",
"properties": {
"workspaceID": {
"type": "string",
"pattern": "^wrk.*"
},
"status": {
"type": "string",
"enum": ["connected", "connecting", "disconnected", "error"]
},
"error": {
"type": "string"
}
},
"required": ["workspaceID", "status"]
}
},
"required": ["type", "properties"]
},
"OutputFormatText": {
"type": "object",
"properties": {
@@ -9937,6 +9937,15 @@
{
"$ref": "#/components/schemas/Event.command.executed"
},
{
"$ref": "#/components/schemas/Event.workspace.ready"
},
{
"$ref": "#/components/schemas/Event.workspace.failed"
},
{
"$ref": "#/components/schemas/Event.workspace.status"
},
{
"$ref": "#/components/schemas/Event.question.asked"
},
@@ -9946,9 +9955,6 @@
{
"$ref": "#/components/schemas/Event.question.rejected"
},
{
"$ref": "#/components/schemas/Event.todo.updated"
},
{
"$ref": "#/components/schemas/Event.session.status"
},
@@ -9958,6 +9964,9 @@
{
"$ref": "#/components/schemas/Event.session.compacted"
},
{
"$ref": "#/components/schemas/Event.todo.updated"
},
{
"$ref": "#/components/schemas/Event.worktree.ready"
},
@@ -9976,15 +9985,6 @@
{
"$ref": "#/components/schemas/Event.pty.deleted"
},
{
"$ref": "#/components/schemas/Event.workspace.ready"
},
{
"$ref": "#/components/schemas/Event.workspace.failed"
},
{
"$ref": "#/components/schemas/Event.workspace.status"
},
{
"$ref": "#/components/schemas/Event.message.updated"
},