refactor(core): consolidate pty service (#30537)
This commit is contained in:
27
packages/core/test/pty/info-schema.test.ts
Normal file
27
packages/core/test/pty/info-schema.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Schema } from "effect"
|
||||
import { Pty } from "@opencode-ai/core/pty"
|
||||
|
||||
const sample = (pid: number) => ({
|
||||
id: "pty_01J5Y5H0AH4Q4NXJ6P4C3P5V2K",
|
||||
title: "demo",
|
||||
command: "cmd.exe",
|
||||
args: [],
|
||||
cwd: "C:\\",
|
||||
status: "running",
|
||||
pid,
|
||||
})
|
||||
|
||||
describe("Pty.Info", () => {
|
||||
test("accepts pid 0 (Windows ConPTY assigns the pid asynchronously)", () => {
|
||||
expect(Schema.decodeUnknownSync(Pty.Info)(sample(0)).pid).toBe(0)
|
||||
})
|
||||
|
||||
test("accepts a positive pid", () => {
|
||||
expect(Schema.decodeUnknownSync(Pty.Info)(sample(48012)).pid).toBe(48012)
|
||||
})
|
||||
|
||||
test("rejects a negative pid", () => {
|
||||
expect(() => Schema.decodeUnknownSync(Pty.Info)(sample(-1))).toThrow()
|
||||
})
|
||||
})
|
||||
19
packages/core/test/pty/input.test.ts
Normal file
19
packages/core/test/pty/input.test.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { handlePtyInput } from "@opencode-ai/core/pty/input"
|
||||
import { it } from "../lib/effect"
|
||||
|
||||
describe("pty websocket input", () => {
|
||||
it.effect("does not forward invalid binary frames to the PTY handler", () =>
|
||||
Effect.gen(function* () {
|
||||
const messages: Array<string | ArrayBuffer> = []
|
||||
const handler = { onMessage: (message: string | ArrayBuffer) => messages.push(message) }
|
||||
|
||||
yield* handlePtyInput(handler, "ready")
|
||||
yield* handlePtyInput(handler, new Uint8Array([0xff, 0xfe, 0xfd]))
|
||||
yield* handlePtyInput(handler, new TextEncoder().encode("hello"))
|
||||
|
||||
expect(messages).toEqual(["ready", "hello"])
|
||||
}),
|
||||
)
|
||||
})
|
||||
110
packages/core/test/pty/pty-output-isolation.test.ts
Normal file
110
packages/core/test/pty/pty-output-isolation.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Duration, Effect, Layer, Queue } from "effect"
|
||||
import { EventV2 } from "@opencode-ai/core/event"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Pty } from "@opencode-ai/core/pty"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { location } from "../fixture/location"
|
||||
import { testEffect } from "../lib/effect"
|
||||
|
||||
type Socket = Parameters<Pty.Interface["connect"]>[1]
|
||||
|
||||
const locationLayer = Layer.succeed(
|
||||
Location.Service,
|
||||
Location.Service.of(location({ directory: AbsolutePath.make("/tmp") })),
|
||||
)
|
||||
const it = testEffect(Pty.layer.pipe(Layer.provideMerge(EventV2.defaultLayer), Layer.provideMerge(locationLayer)))
|
||||
const ptyTest = process.platform === "win32" ? it.live.skip : it.live
|
||||
|
||||
const createPty = Effect.fn("PtyOutputIsolationTest.createPty")(function* (command: string) {
|
||||
const pty = yield* Pty.Service
|
||||
return yield* Effect.acquireRelease(
|
||||
pty.create({ command, args: [], cwd: "/tmp", env: { TERM: "xterm-256color", OPENCODE_TERMINAL: "1" } }),
|
||||
(info) => pty.remove(info.id).pipe(Effect.ignore),
|
||||
)
|
||||
})
|
||||
|
||||
const decodeOutput = (data: string | Uint8Array | ArrayBuffer) =>
|
||||
typeof data === "string"
|
||||
? data
|
||||
: Buffer.from(data instanceof Uint8Array ? data : new Uint8Array(data)).toString("utf8")
|
||||
|
||||
const makeSocket = Effect.fn("PtyOutputIsolationTest.makeSocket")(function* (data: unknown) {
|
||||
const output = yield* Queue.unbounded<string>()
|
||||
const socket: Socket = {
|
||||
readyState: 1,
|
||||
data,
|
||||
send: (data) => Queue.offerUnsafe(output, decodeOutput(data)),
|
||||
close: () => {},
|
||||
}
|
||||
return { socket, output }
|
||||
})
|
||||
|
||||
const waitForOutput = (output: Queue.Queue<string>, text: string, duration: Duration.Input = "5 seconds") =>
|
||||
Effect.gen(function* () {
|
||||
let received = ""
|
||||
while (!received.includes(text)) received += yield* Queue.take(output)
|
||||
return received
|
||||
}).pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration,
|
||||
orElse: () => Effect.fail(new Error(`timeout waiting for output containing ${JSON.stringify(text)}`)),
|
||||
}),
|
||||
)
|
||||
|
||||
describe("pty output isolation", () => {
|
||||
ptyTest("does not leak output when websocket objects are reused", () =>
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
const a = yield* createPty("cat")
|
||||
const b = yield* createPty("cat")
|
||||
const shared = yield* makeSocket({ events: { connection: "a" } })
|
||||
const outB = yield* Queue.unbounded<string>()
|
||||
|
||||
yield* pty.connect(a.id, shared.socket)
|
||||
shared.socket.data = { events: { connection: "b" } }
|
||||
shared.socket.send = (data) => Queue.offerUnsafe(outB, decodeOutput(data))
|
||||
yield* pty.connect(b.id, shared.socket)
|
||||
yield* pty.write(a.id, "AAA\n")
|
||||
|
||||
const verify = yield* makeSocket({ events: { connection: "verify-a" } })
|
||||
yield* pty.connect(a.id, verify.socket)
|
||||
expect(yield* waitForOutput(verify.output, "AAA")).toContain("AAA")
|
||||
expect(yield* waitForOutput(outB, "AAA", "100 millis").pipe(Effect.option)).toMatchObject({ _tag: "None" })
|
||||
}),
|
||||
)
|
||||
|
||||
ptyTest("does not leak output when Bun recycles websocket objects before re-connect", () =>
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
const info = yield* createPty("cat")
|
||||
const first = yield* makeSocket({ events: { connection: "a" } })
|
||||
const recycled = yield* Queue.unbounded<string>()
|
||||
|
||||
yield* pty.connect(info.id, first.socket)
|
||||
first.socket.data = { events: { connection: "b" } }
|
||||
first.socket.send = (data) => Queue.offerUnsafe(recycled, decodeOutput(data))
|
||||
yield* pty.write(info.id, "AAA\n")
|
||||
|
||||
const verify = yield* makeSocket({ events: { connection: "verify" } })
|
||||
yield* pty.connect(info.id, verify.socket)
|
||||
expect(yield* waitForOutput(verify.output, "AAA")).toContain("AAA")
|
||||
expect(yield* waitForOutput(recycled, "AAA", "100 millis").pipe(Effect.option)).toMatchObject({ _tag: "None" })
|
||||
}),
|
||||
)
|
||||
|
||||
ptyTest("treats in-place socket data mutation as the same connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
const info = yield* createPty("cat")
|
||||
const data = { connId: 1 }
|
||||
const socket = yield* makeSocket(data)
|
||||
|
||||
yield* pty.connect(info.id, socket.socket)
|
||||
data.connId = 2
|
||||
yield* pty.write(info.id, "AAA\n")
|
||||
|
||||
expect(yield* waitForOutput(socket.output, "AAA")).toContain("AAA")
|
||||
}),
|
||||
)
|
||||
})
|
||||
91
packages/core/test/pty/pty-session.test.ts
Normal file
91
packages/core/test/pty/pty-session.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Cause, Effect, Exit, Layer, Queue } from "effect"
|
||||
import { EventV2 } from "@opencode-ai/core/event"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Pty } from "@opencode-ai/core/pty"
|
||||
import type { PtyID } from "@opencode-ai/core/pty/schema"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { location } from "../fixture/location"
|
||||
import { testEffect } from "../lib/effect"
|
||||
|
||||
type PtyEvent = { type: "created" | "exited" | "deleted"; id: PtyID }
|
||||
|
||||
const locationLayer = Layer.succeed(
|
||||
Location.Service,
|
||||
Location.Service.of(location({ directory: AbsolutePath.make("/tmp") })),
|
||||
)
|
||||
const it = testEffect(Pty.layer.pipe(Layer.provideMerge(EventV2.defaultLayer), Layer.provideMerge(locationLayer)))
|
||||
const ptyTest = process.platform === "win32" ? it.live.skip : it.live
|
||||
|
||||
const subscribePtyEvents = Effect.fn("PtySessionTest.subscribePtyEvents")(function* () {
|
||||
const source = yield* EventV2.Service
|
||||
const events = yield* Queue.unbounded<PtyEvent>()
|
||||
const unsubscribe = yield* source.listen((event) => {
|
||||
if (event.type === Pty.Event.Created.type)
|
||||
Queue.offerUnsafe(events, { type: "created", id: (event.data as typeof Pty.Event.Created.data.Type).info.id })
|
||||
if (event.type === Pty.Event.Exited.type)
|
||||
Queue.offerUnsafe(events, { type: "exited", id: (event.data as typeof Pty.Event.Exited.data.Type).id })
|
||||
if (event.type === Pty.Event.Deleted.type)
|
||||
Queue.offerUnsafe(events, { type: "deleted", id: (event.data as typeof Pty.Event.Deleted.data.Type).id })
|
||||
return Effect.void
|
||||
})
|
||||
yield* Effect.addFinalizer(() => unsubscribe)
|
||||
return events
|
||||
})
|
||||
|
||||
const createPty = Effect.fn("PtySessionTest.createPty")(function* (command: string, args: string[] = []) {
|
||||
const pty = yield* Pty.Service
|
||||
return yield* Effect.acquireRelease(
|
||||
pty.create({ command, args, cwd: "/tmp", env: { TERM: "xterm-256color", OPENCODE_TERMINAL: "1" } }),
|
||||
(info) => pty.remove(info.id).pipe(Effect.ignore),
|
||||
)
|
||||
})
|
||||
|
||||
const waitForEvents = (events: Queue.Queue<PtyEvent>, id: PtyID, count: number) =>
|
||||
Effect.gen(function* () {
|
||||
const picked: Array<PtyEvent["type"]> = []
|
||||
while (picked.length < count) {
|
||||
const evt = yield* Queue.take(events)
|
||||
if (evt.id === id) picked.push(evt.type)
|
||||
}
|
||||
return picked
|
||||
}).pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: "5 seconds",
|
||||
orElse: () => Effect.fail(new Error("timeout waiting for pty events")),
|
||||
}),
|
||||
)
|
||||
|
||||
describe("pty", () => {
|
||||
it.live("returns typed not found errors for missing sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
const id = "pty_missing" as PtyID
|
||||
let closed = false
|
||||
const socket = { readyState: 1, send: () => {}, close: () => void (closed = true) }
|
||||
|
||||
for (const result of [
|
||||
yield* pty.get(id).pipe(Effect.asVoid, Effect.exit),
|
||||
yield* pty.update(id, { title: "missing" }).pipe(Effect.asVoid, Effect.exit),
|
||||
yield* pty.remove(id).pipe(Effect.exit),
|
||||
yield* pty.resize(id, 80, 24).pipe(Effect.exit),
|
||||
yield* pty.write(id, "input").pipe(Effect.exit),
|
||||
yield* pty.connect(id, socket).pipe(Effect.asVoid, Effect.exit),
|
||||
]) {
|
||||
expect(Exit.isFailure(result)).toBe(true)
|
||||
if (Exit.isFailure(result))
|
||||
expect(Cause.squash(result.cause)).toMatchObject({ _tag: "Pty.NotFoundError", ptyID: id })
|
||||
}
|
||||
expect(closed).toBe(true)
|
||||
}),
|
||||
)
|
||||
|
||||
ptyTest("publishes created, exited, deleted in order for a short-lived process", () =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* subscribePtyEvents()
|
||||
const info = yield* createPty("/usr/bin/env", ["sh", "-c", "sleep 0.1"])
|
||||
|
||||
expect(yield* waitForEvents(events, info.id, 3)).toEqual(["created", "exited", "deleted"])
|
||||
}),
|
||||
)
|
||||
})
|
||||
59
packages/core/test/pty/ticket.test.ts
Normal file
59
packages/core/test/pty/ticket.test.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { PtyID } from "@opencode-ai/core/pty/schema"
|
||||
import { PtyTicket } from "@opencode-ai/core/pty/ticket"
|
||||
import { WorkspaceV2 } from "@opencode-ai/core/workspace"
|
||||
import { testEffect } from "../lib/effect"
|
||||
|
||||
const it = testEffect(PtyTicket.layer)
|
||||
const itExpiring = testEffect(Layer.effect(PtyTicket.Service, PtyTicket.make(5)))
|
||||
|
||||
describe("PTY websocket tickets", () => {
|
||||
it.live("consumes tickets once", () =>
|
||||
Effect.gen(function* () {
|
||||
const tickets = yield* PtyTicket.Service
|
||||
const scope = { ptyID: PtyID.ascending(), directory: "/tmp/a" }
|
||||
const issued = yield* tickets.issue(scope)
|
||||
|
||||
expect(yield* tickets.consume({ ...scope, ticket: issued.ticket })).toBe(true)
|
||||
expect(yield* tickets.consume({ ...scope, ticket: issued.ticket })).toBe(false)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("rejects tickets scoped to a different request", () =>
|
||||
Effect.gen(function* () {
|
||||
const tickets = yield* PtyTicket.Service
|
||||
const ptyID = PtyID.ascending()
|
||||
const issued = yield* tickets.issue({ ptyID, directory: "/tmp/a" })
|
||||
|
||||
expect(yield* tickets.consume({ ptyID, directory: "/tmp/b", ticket: issued.ticket })).toBe(false)
|
||||
expect(yield* tickets.consume({ ptyID, directory: "/tmp/a", ticket: issued.ticket })).toBe(true)
|
||||
}),
|
||||
)
|
||||
|
||||
itExpiring.live("rejects tickets after the TTL elapses", () =>
|
||||
Effect.gen(function* () {
|
||||
const tickets = yield* PtyTicket.Service
|
||||
const ptyID = PtyID.ascending()
|
||||
const issued = yield* tickets.issue({ ptyID })
|
||||
|
||||
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 25)))
|
||||
|
||||
expect(yield* tickets.consume({ ptyID, ticket: issued.ticket })).toBe(false)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("rejects tickets scoped to a different workspace", () =>
|
||||
Effect.gen(function* () {
|
||||
const tickets = yield* PtyTicket.Service
|
||||
const ptyID = PtyID.ascending()
|
||||
const workspaceID = WorkspaceV2.ID.ascending()
|
||||
const issued = yield* tickets.issue({ ptyID, workspaceID })
|
||||
|
||||
expect(yield* tickets.consume({ ptyID, workspaceID: WorkspaceV2.ID.ascending(), ticket: issued.ticket })).toBe(
|
||||
false,
|
||||
)
|
||||
expect(yield* tickets.consume({ ptyID, workspaceID, ticket: issued.ticket })).toBe(true)
|
||||
}),
|
||||
)
|
||||
})
|
||||
Reference in New Issue
Block a user