mirror of
https://github.com/anomalyco/opencode.git
synced 2026-12-02 14:33:37 +08:00
421 lines
18 KiB
TypeScript
421 lines
18 KiB
TypeScript
import { describe, expect, test } from "bun:test"
|
|
import { CodeModeTool } from "@opencode/core/codemode/tool"
|
|
import { Environment } from "@opencode/core/environment/index"
|
|
import { Permission } from "@opencode/core/permission"
|
|
import { AbsolutePath } from "@opencode/core/schema"
|
|
import { Tool } from "@opencode/core/tool"
|
|
import { Agent } from "@opencode/schema/agent"
|
|
import { Session } from "@opencode/schema/session"
|
|
import { SessionMessage } from "@opencode/schema/session-message"
|
|
import { Context, Effect, Layer } from "effect"
|
|
import path, { posix, win32 } from "node:path"
|
|
import { type CodeModeServiceOptions, codeModeServices } from "../fixture/codemode"
|
|
import { tmpdir } from "../fixture/tmpdir"
|
|
import { permissionService } from "../lib/permission"
|
|
import { noToolCalls } from "../lib/tool"
|
|
|
|
const context = {
|
|
sessionID: Session.ID.make("ses_codemode_machine_paths"),
|
|
agent: Agent.ID.make("build"),
|
|
messageID: SessionMessage.ID.make("msg_codemode_machine_paths"),
|
|
id: Tool.CallID.make("call_codemode_machine_paths"),
|
|
progress: () => Effect.void,
|
|
tool: noToolCalls,
|
|
}
|
|
|
|
const services = (directory: string, options?: CodeModeServiceOptions, permission?: Partial<Permission.Interface>) =>
|
|
codeModeServices(directory, permission, undefined, undefined, options)
|
|
|
|
const create = (
|
|
provided: Context.Context<CodeModeTool.Services>,
|
|
permission: Permission.Interface = permissionService({ assert: () => Effect.void }),
|
|
) =>
|
|
CodeModeTool.create(
|
|
{ tools: new Map() },
|
|
{ full: true, agents: false },
|
|
() => Effect.die("no tools"),
|
|
permission,
|
|
provided,
|
|
)
|
|
|
|
const run = async (
|
|
codeMode: ReturnType<typeof create>,
|
|
code: string,
|
|
cwd?: { readonly absolute: AbsolutePath; readonly environment: Environment.Interface },
|
|
) => {
|
|
const executed = codeMode.execute({ code }, context)
|
|
const effect = cwd ? Effect.provideService(executed, Environment.CurrentWorkingDirectory, cwd) : executed
|
|
const result = (await Effect.runPromise(effect)).output
|
|
if (result.error) throw new Error(result.output)
|
|
return JSON.parse(result.output)
|
|
}
|
|
|
|
/** In-memory files under Windows paths: the memory driver keys its nodes with POSIX separators. */
|
|
const windowsDriver = (): Environment.Driver => {
|
|
const memory = Environment.makeMemoryDriver()
|
|
const files = Environment.makeFiles(memory)
|
|
const at = (value: string) => win32.normalize(value).replaceAll("\\", "/")
|
|
return {
|
|
spawner: memory.spawner,
|
|
overrides: {
|
|
stat: (path) => files.stat(at(path)),
|
|
read: (path, range) => files.read(at(path), range),
|
|
list: (path) => files.list(at(path)),
|
|
write: (path, bytes) => files.write(at(path), bytes),
|
|
append: (path, bytes) => files.append(at(path), bytes),
|
|
remove: (path) => files.remove(at(path)),
|
|
mkdir: (path) => files.mkdir(at(path)),
|
|
move: (from, to) => files.move(at(from), at(to)),
|
|
},
|
|
}
|
|
}
|
|
|
|
const winEnvironment = (
|
|
id = Environment.ID.make("win"),
|
|
options?: { readonly local?: boolean; readonly home?: string },
|
|
) =>
|
|
Environment.make(id, windowsDriver(), {
|
|
local: options?.local ?? false,
|
|
path: win32,
|
|
shell: "pwsh",
|
|
...(options?.home === undefined ? {} : { home: Effect.succeed(options.home) }),
|
|
})
|
|
|
|
const posixEnvironment = (id = Environment.ID.make("pro"), home?: string) =>
|
|
Environment.make(id, Environment.makeMemoryDriver(), {
|
|
local: false,
|
|
path: posix,
|
|
shell: "sh",
|
|
...(home === undefined ? {} : { home: Effect.succeed(home) }),
|
|
})
|
|
|
|
const encode = (text: string) => new TextEncoder().encode(text)
|
|
|
|
describe("Code Mode path on a Windows-path environment", () => {
|
|
test("resolves against the Location environment's rules when no working directory is set", async () => {
|
|
const environment = winEnvironment()
|
|
const codeMode = create(services("C:/repo", { environment: Layer.succeed(Environment.Service, environment) }))
|
|
expect(
|
|
await run(codeMode, `return [path.resolve("a", "b"), path.relative("a", "c"), path.win32.join("a", "b")]`),
|
|
).toEqual(["C:\\repo\\a\\b", "..\\c", "a\\b"])
|
|
})
|
|
})
|
|
|
|
describe("Code Mode Bun.Glob on a Windows-path machine", () => {
|
|
test("scans by the machine's path rules and names absolute results with the machine", async () => {
|
|
await using temporary = await tmpdir()
|
|
const machine = winEnvironment()
|
|
await Effect.runPromise(
|
|
Effect.all([
|
|
machine.files.write(String.raw`C:\repo\src\a.ts`, encode("alpha")),
|
|
machine.files.write(String.raw`C:\repo\src\nested\b.ts`, encode("beta")),
|
|
]),
|
|
)
|
|
const codeMode = create(services(temporary.path, { machines: [machine] }))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const glob = new Bun.Glob("**/*.ts")
|
|
const relative = glob.scanSync({ cwd: "win:C:/repo" })
|
|
const absolute = glob.scanSync({ cwd: "win:C:/repo", absolute: true })
|
|
const contents = await Promise.all(absolute.map((file) => Bun.file(file).text()))
|
|
return { relative, absolute, contents }`,
|
|
),
|
|
).toEqual({
|
|
relative: [String.raw`src\a.ts`, String.raw`src\nested\b.ts`],
|
|
absolute: ["win:C:/repo/src/a.ts", "win:C:/repo/src/nested/b.ts"],
|
|
contents: ["alpha", "beta"],
|
|
})
|
|
})
|
|
|
|
test("scans a UNC share cwd and keeps its absolute results addressable", async () => {
|
|
await using temporary = await tmpdir()
|
|
const machine = winEnvironment()
|
|
const share = String.raw`\\server\share\repo`
|
|
const cwd = `win:${share}`
|
|
await Effect.runPromise(
|
|
Effect.all([
|
|
machine.files.write(String.raw`\\server\share\repo\src\a.ts`, encode("unc-a")),
|
|
machine.files.write(String.raw`\\server\share\repo\src\nested\b.ts`, encode("unc-b")),
|
|
]),
|
|
)
|
|
const codeMode = create(services(temporary.path, { machines: [machine] }))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const glob = new Bun.Glob("**/*.ts")
|
|
const relative = glob.scanSync({ cwd: ${JSON.stringify(cwd)} })
|
|
const absolute = glob.scanSync({ cwd: ${JSON.stringify(cwd)}, absolute: true })
|
|
const contents = await Promise.all(absolute.map((file) => Bun.file(file).text()))
|
|
return { relative, absolute, contents }`,
|
|
),
|
|
).toEqual({
|
|
relative: [String.raw`src\a.ts`, String.raw`src\nested\b.ts`],
|
|
absolute: [String.raw`win:\\server\share\repo\src\a.ts`, String.raw`win:\\server\share\repo\src\nested\b.ts`],
|
|
contents: ["unc-a", "unc-b"],
|
|
})
|
|
})
|
|
|
|
test("keeps an absolute pattern on the machine its cwd names", async () => {
|
|
await using temporary = await tmpdir()
|
|
const machine = winEnvironment()
|
|
await Effect.runPromise(machine.files.write(String.raw`C:\repo\src\a.ts`, encode("abs")))
|
|
const codeMode = create(services(temporary.path, { machines: [machine] }))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const glob = new Bun.Glob("C:/repo/**/*.ts")
|
|
return [glob.scanSync({ cwd: "win:C:/repo" }), glob.scanSync({ cwd: "win:C:/repo", absolute: true })]`,
|
|
),
|
|
).toEqual([[String.raw`C:\repo\src\a.ts`], ["win:C:/repo/src/a.ts"]])
|
|
})
|
|
|
|
test("scans drive-root wildcards without Machine.NotAbsolute", async () => {
|
|
await using temporary = await tmpdir()
|
|
const machine = winEnvironment()
|
|
await Effect.runPromise(
|
|
Effect.all([
|
|
machine.files.write(String.raw`C:\root.ts`, encode("root")),
|
|
machine.files.write(String.raw`C:\repo\src\a.ts`, encode("nested")),
|
|
]),
|
|
)
|
|
const assertions: Permission.AssertInput[] = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void assertions.push(input)) }
|
|
const codeMode = create(services(temporary.path, { machines: [machine] }, record), permissionService(record))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const top = new Bun.Glob("C:/*.ts")
|
|
const deep = new Bun.Glob("C:/**/*.ts")
|
|
const topAbs = top.scanSync({ cwd: "win:C:/repo", absolute: true })
|
|
return {
|
|
top: top.scanSync({ cwd: "win:C:/repo" }),
|
|
topAbs,
|
|
topText: await Bun.file(topAbs[0]).text(),
|
|
deep: deep.scanSync({ cwd: "win:C:/repo" }).sort(),
|
|
deepAbs: deep.scanSync({ cwd: "win:C:/repo", absolute: true }).sort(),
|
|
}`,
|
|
),
|
|
).toEqual({
|
|
top: [String.raw`C:\root.ts`],
|
|
topAbs: ["win:C:/root.ts"],
|
|
topText: "root",
|
|
deep: [String.raw`C:\repo\src\a.ts`, String.raw`C:\root.ts`],
|
|
deepAbs: ["win:C:/repo/src/a.ts", "win:C:/root.ts"],
|
|
})
|
|
expect(assertions.filter((item) => item.action === "read").map((item) => item.resources)).toContainEqual([
|
|
"win:C:/",
|
|
])
|
|
})
|
|
|
|
test("normalizes non-wildcard matches on Windows, round-trips Bun.file, and checks permission resources", async () => {
|
|
await using temporary = await tmpdir()
|
|
const machine = winEnvironment()
|
|
await Effect.runPromise(machine.files.write(String.raw`C:\repo\src\a.ts`, encode("exact")))
|
|
const assertions: Permission.AssertInput[] = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void assertions.push(input)) }
|
|
const codeMode = create(services(temporary.path, { machines: [machine] }, record), permissionService(record))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const glob = new Bun.Glob("src/a.ts")
|
|
const relative = glob.scanSync({ cwd: "win:C:/repo" })
|
|
const absolute = glob.scanSync({ cwd: "win:C:/repo", absolute: true })
|
|
return { relative, absolute, text: await Bun.file(absolute[0]).text() }`,
|
|
),
|
|
).toEqual({
|
|
relative: [String.raw`src\a.ts`],
|
|
absolute: ["win:C:/repo/src/a.ts"],
|
|
text: "exact",
|
|
})
|
|
expect(assertions.filter((item) => item.action === "read").map((item) => item.resources)).toEqual([
|
|
["win:C:/repo/src/a.ts"],
|
|
["win:C:/repo/src/a.ts"],
|
|
["win:C:/repo/src/a.ts"],
|
|
])
|
|
})
|
|
|
|
test("resolves environment-prefixed patterns across local and remote machines", async () => {
|
|
await using temporary = await tmpdir()
|
|
const win = winEnvironment()
|
|
const pro = posixEnvironment()
|
|
await Effect.runPromise(
|
|
Effect.all([
|
|
win.files.write(String.raw`C:\root.ts`, encode("win-root")),
|
|
win.files.write(String.raw`C:\repo\src\a.ts`, encode("win-a")),
|
|
win.files.write(String.raw`\\server\share\repo\src\u.ts`, encode("win-unc")),
|
|
pro.files.write("/work/repo/src/p.ts", encode("pro-p")),
|
|
]),
|
|
)
|
|
const assertions: Permission.AssertInput[] = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void assertions.push(input)) }
|
|
const codeMode = create(services(temporary.path, { machines: [win, pro] }, record), permissionService(record))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const winFromLocal = new Bun.Glob("win:C:/repo/**/*.ts").scanSync()
|
|
const winBackslashFromPro = new Bun.Glob(${JSON.stringify(String.raw`win:C:\repo\**\*.ts`)}).scanSync({ cwd: "pro:/work/repo" })
|
|
const winDriveRoot = new Bun.Glob("win:C:/*.ts").scanSync()
|
|
const winExact = new Bun.Glob("win:C:/repo/src/a.ts").scanSync()
|
|
const winUnc = new Bun.Glob(${JSON.stringify(String.raw`win:\\server\share\repo\**\*.ts`)}).scanSync()
|
|
const proFromLocal = new Bun.Glob("pro:/work/repo/**/*.ts").scanSync()
|
|
const proFromWin = new Bun.Glob("pro:/work/repo/**/*.ts").scanSync({ cwd: "win:C:/repo" })
|
|
const proFromWinAbs = new Bun.Glob("pro:/work/repo/**/*.ts").scanSync({ cwd: "win:C:/repo", absolute: true })
|
|
const texts = await Promise.all([
|
|
Bun.file(winFromLocal[0]).text(),
|
|
Bun.file(winUnc[0]).text(),
|
|
Bun.file(proFromWin[0]).text(),
|
|
])
|
|
return {
|
|
winFromLocal,
|
|
winBackslashFromPro,
|
|
winDriveRoot,
|
|
winExact,
|
|
winUnc,
|
|
proFromLocal,
|
|
proFromWin,
|
|
proFromWinAbs,
|
|
texts,
|
|
}`,
|
|
),
|
|
).toEqual({
|
|
winFromLocal: ["win:C:/repo/src/a.ts"],
|
|
winBackslashFromPro: ["win:C:/repo/src/a.ts"],
|
|
winDriveRoot: ["win:C:/root.ts"],
|
|
winExact: ["win:C:/repo/src/a.ts"],
|
|
winUnc: [String.raw`win:\\server\share\repo\src\u.ts`],
|
|
proFromLocal: ["pro:/work/repo/src/p.ts"],
|
|
proFromWin: ["pro:/work/repo/src/p.ts"],
|
|
proFromWinAbs: ["pro:/work/repo/src/p.ts"],
|
|
texts: ["win-a", "win-unc", "pro-p"],
|
|
})
|
|
const reads = assertions.filter((item) => item.action === "read").map((item) => item.resources)
|
|
expect(reads).toContainEqual(["win:C:/repo"])
|
|
expect(reads).toContainEqual(["win:C:/"])
|
|
expect(reads).toContainEqual(["pro:/work/repo"])
|
|
})
|
|
|
|
test("scans ~ patterns on Windows and POSIX machines even when home contains glob metacharacters", async () => {
|
|
await using temporary = await tmpdir()
|
|
const winHome = String.raw`C:\Users\alice@corp`
|
|
const proHome = "/home/alice[1]@corp"
|
|
const win = winEnvironment(Environment.ID.make("win"), { home: winHome })
|
|
const pro = posixEnvironment(Environment.ID.make("pro"), proHome)
|
|
await Effect.runPromise(
|
|
Effect.all([
|
|
win.files.write(String.raw`C:\Users\alice@corp\note.ts`, encode("win-top")),
|
|
win.files.write(String.raw`C:\Users\alice@corp\repo\src\a.ts`, encode("win-home")),
|
|
pro.files.write(`${proHome}/top.ts`, encode("pro-top")),
|
|
pro.files.write(`${proHome}/repo/src/p.ts`, encode("pro-home")),
|
|
]),
|
|
)
|
|
const assertions: Permission.AssertInput[] = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void assertions.push(input)) }
|
|
const codeMode = create(services(temporary.path, { machines: [win, pro] }, record), permissionService(record))
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const winSlash = new Bun.Glob("win:~/repo/**/*.ts").scanSync()
|
|
const winBackslash = new Bun.Glob(${JSON.stringify(String.raw`win:~\repo\**\*.ts`)}).scanSync()
|
|
const winTop = new Bun.Glob("win:~/*.ts").scanSync()
|
|
const winExact = new Bun.Glob("win:~/repo/src/a.ts").scanSync()
|
|
const proRepo = new Bun.Glob("pro:~/repo/**/*.ts").scanSync()
|
|
const proTop = new Bun.Glob("pro:~/*.ts").scanSync()
|
|
const proHomeDir = new Bun.Glob("pro:~").scanSync({ onlyFiles: false })
|
|
const texts = await Promise.all([
|
|
Bun.file(winSlash[0]).text(),
|
|
Bun.file(proRepo[0]).text(),
|
|
])
|
|
return { winSlash, winBackslash, winTop, winExact, proRepo, proTop, proHomeDir, texts }`,
|
|
),
|
|
).toEqual({
|
|
winSlash: ["win:C:/Users/alice@corp/repo/src/a.ts"],
|
|
winBackslash: ["win:C:/Users/alice@corp/repo/src/a.ts"],
|
|
winTop: ["win:C:/Users/alice@corp/note.ts"],
|
|
winExact: ["win:C:/Users/alice@corp/repo/src/a.ts"],
|
|
proRepo: [`pro:${proHome}/repo/src/p.ts`],
|
|
proTop: [`pro:${proHome}/top.ts`],
|
|
proHomeDir: [`pro:${proHome}`],
|
|
texts: ["win-home", "pro-home"],
|
|
})
|
|
const reads = assertions.filter((item) => item.action === "read").map((item) => item.resources)
|
|
expect(reads).toContainEqual(["win:C:/Users/alice@corp/repo"])
|
|
expect(reads).toContainEqual(["win:C:/Users/alice@corp"])
|
|
expect(reads).not.toContainEqual(["win:C:/Users"])
|
|
expect(reads).toContainEqual([`pro:${proHome}/repo`])
|
|
expect(reads).toContainEqual([`pro:${proHome}`])
|
|
expect(reads).not.toContainEqual(["pro:/home"])
|
|
await expect(
|
|
run(codeMode, `return new Bun.Glob(${JSON.stringify(String.raw`pro:~\repo\*.ts`)}).scanSync()`),
|
|
).rejects.toThrow("Machine paths are absolute or start with ~/")
|
|
})
|
|
|
|
test("scans environment-prefixed patterns even when cwd or CurrentWorkingDirectory is on an offline machine", async () => {
|
|
await using temporary = await tmpdir()
|
|
await Bun.write(`${temporary.path}/local.ts`, "local")
|
|
const pro = posixEnvironment()
|
|
const offline = Environment.unavailable(Environment.ID.make("offline"), new Error("offline"))
|
|
await Effect.runPromise(pro.files.write("/work/repo/src/p.ts", encode("pro-p")))
|
|
const codeMode = create(services(temporary.path, { machines: [pro, offline] }))
|
|
const localPattern = `local:${temporary.path.replaceAll("\\", "/")}/*.ts`
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`return {
|
|
pro: new Bun.Glob("pro:/work/repo/**/*.ts").scanSync({ cwd: "offline:/repo" }),
|
|
local: new Bun.Glob(${JSON.stringify(localPattern)}).scanSync({ cwd: "offline:/repo" }),
|
|
}`,
|
|
),
|
|
).toEqual({
|
|
pro: ["pro:/work/repo/src/p.ts"],
|
|
local: [`local:${temporary.path.replaceAll("\\", "/")}/local.ts`],
|
|
})
|
|
expect(
|
|
await run(codeMode, `return new Bun.Glob("pro:/work/repo/**/*.ts").scanSync()`, {
|
|
absolute: AbsolutePath.make("/repo"),
|
|
environment: offline,
|
|
}),
|
|
).toEqual(["pro:/work/repo/src/p.ts"])
|
|
await expect(run(codeMode, `return new Bun.Glob("**/*.ts").scanSync({ cwd: "offline:/repo" })`)).rejects.toThrow(
|
|
"offline",
|
|
)
|
|
})
|
|
|
|
test("does not route machine-prefixed patterns to registered peers when flags are disabled", async () => {
|
|
await using temporary = await tmpdir()
|
|
const pro = posixEnvironment()
|
|
await Effect.runPromise(pro.files.write("/work/repo/src/p.ts", encode("pro-p")))
|
|
const codeMode = create(services(temporary.path, { machines: [pro], flags: false }))
|
|
expect(await run(codeMode, `return new Bun.Glob("pro:/work/repo/**/*.ts").scanSync()`)).toEqual([])
|
|
})
|
|
|
|
test("fails when a pattern names an unknown machine prefix", async () => {
|
|
await using temporary = await tmpdir()
|
|
const pro = posixEnvironment()
|
|
const codeMode = create(services(temporary.path, { machines: [pro] }))
|
|
await expect(run(codeMode, `return new Bun.Glob("ghost:/work/repo/**/*.ts").scanSync()`)).rejects.toThrow(
|
|
'No machine named "ghost"',
|
|
)
|
|
})
|
|
|
|
test("preserves typed environment prefixes on non-machine Windows-rules environments", async () => {
|
|
const localWin = winEnvironment(Environment.localID, { local: true })
|
|
// A local environment resolves plain paths with host node:path (adding a drive letter on Windows).
|
|
const root = path.resolve("/repo").replaceAll("\\", "/")
|
|
await Effect.runPromise(localWin.files.write(`${root}/src/a.ts`, encode("local-win")))
|
|
const codeMode = create(
|
|
services(root, {
|
|
environment: Layer.succeed(Environment.Service, localWin),
|
|
flags: true,
|
|
}),
|
|
)
|
|
expect(
|
|
await run(
|
|
codeMode,
|
|
`const glob = new Bun.Glob("src/*.ts")
|
|
return [glob.scanSync({ cwd: "local:${root}" }), await Bun.file("local:${root}/src/a.ts").text()]`,
|
|
),
|
|
).toEqual([[String.raw`src\a.ts`], "local-win"])
|
|
})
|
|
})
|