Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/client/src/effect/api/api.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/client/src/effect/generated/client.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/client/src/promise/generated/client.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 22 additions & 1 deletion packages/client/src/promise/generated/types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 12 additions & 2 deletions packages/core/src/persistent-pty/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const WireTerminal = Schema.Struct({
id: Schema.Number,
pid: Schema.NullOr(Schema.Number),
title: Schema.String,
user_title: Schema.optional(Schema.NullOr(Schema.String)),
foreground_process: Schema.NullOr(Schema.String),
group_id: Session.ID,
command: Schema.Array(Schema.String),
Expand All @@ -37,6 +38,7 @@ const Registration = Schema.Struct({
protocol: Schema.Number,
socket: Schema.String,
token: Schema.String,
features: Schema.optional(Schema.Array(Schema.String)),
})
type Registration = typeof Registration.Type

Expand All @@ -46,6 +48,7 @@ export const WireResponse = Schema.Union([
instance_id: Schema.String,
pid: Schema.Number,
protocol: Schema.Number,
features: Schema.optional(Schema.Array(Schema.String)),
}),
Schema.Struct({ type: Schema.Literal("created"), terminal: WireTerminal }),
Schema.Struct({ type: Schema.Literal("terminals"), terminals: Schema.Array(WireTerminal) }),
Expand Down Expand Up @@ -141,6 +144,7 @@ export class DaemonError extends Data.TaggedError("PersistentPty.DaemonError")<{
export interface DaemonTransport {
readonly request: (value: object, start?: boolean) => Effect.Effect<WireResponse, DaemonError>
readonly requestIfRunning: (value: object) => Effect.Effect<WireResponse | undefined, DaemonError>
readonly supports: (feature: string) => Effect.Effect<boolean, DaemonError>
readonly shutdown: Effect.Effect<WireResponse | undefined, DaemonError>
readonly handoff: Effect.Effect<Handoff | null, DaemonError>
readonly subscribe: (
Expand Down Expand Up @@ -223,7 +227,8 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
response.protocol !== ProtocolVersion
)
return yield* Effect.fail(new DaemonError({ kind: "protocol", message: "opencode-pty registration mismatch" }))
return decoded
// Daemons older than the features list omit it; trust the live daemon's answer over the file.
return { ...decoded, features: response.features ?? [] }
})

const spawnDaemon = Effect.fn("PersistentPty.daemon.spawn")(function* () {
Expand Down Expand Up @@ -338,6 +343,11 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
Effect.catch((error) => (error.kind === "connect" ? Effect.succeed(undefined) : Effect.fail(error))),
)

const supports = Effect.fn("PersistentPty.daemon.supports")(function* (feature: string) {
const current = yield* connect(false)
return current.features?.includes(feature) ?? false
})

const shutdown = Effect.gen(function* () {
const response = yield* requestIfRunning({ op: "shutdown" })
registration = undefined
Expand Down Expand Up @@ -428,7 +438,7 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
)
}

return { request, requestIfRunning, shutdown, handoff, subscribe } satisfies DaemonTransport
return { request, requestIfRunning, supports, shutdown, handoff, subscribe } satisfies DaemonTransport
})

// Older releases kept registrations in purgeable temp directories. Renaming keeps the lock file's
Expand Down
32 changes: 31 additions & 1 deletion packages/core/src/persistent-pty/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ import { stat } from "node:fs/promises"
import path from "node:path"
import { Context, Effect, Layer, Schema, Stream } from "effect"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { Added, Handoff, PersistentPty, ReadLines, Removed, type ReadResult } from "@opencode/schema/persistent-pty"
import {
Added,
Handoff,
PersistentPty,
ReadLines,
Removed,
Updated,
type ReadResult,
} from "@opencode/schema/persistent-pty"
import { Session } from "@opencode/schema/session"
import { SessionEvent } from "@opencode/schema/session-event"
import { Bus } from "../bus.js"
Expand Down Expand Up @@ -64,6 +72,10 @@ export class InvalidCwdError extends Schema.TaggedError<InvalidCwdError>()("Pers
message: Schema.String,
}) {}

export class UnsupportedError extends Schema.TaggedError<UnsupportedError>()("PersistentPty.UnsupportedError", {
feature: Schema.String,
}) {}

export interface Interface {
readonly list: (sessionID?: Session.ID) => Effect.Effect<Info[], UnavailableError>
readonly get: (id: Pty.ID) => Effect.Effect<Info, NotFoundError | UnavailableError>
Expand Down Expand Up @@ -103,6 +115,10 @@ export interface Interface {
rows: number,
data: Uint8Array,
) => Effect.Effect<void, NotFoundError | UnavailableError>
readonly rename: (
id: Pty.ID,
title: string | null,
) => Effect.Effect<Info, NotFoundError | UnsupportedError | UnavailableError>
readonly snapshot: (id: Pty.ID) => Effect.Effect<Snapshot, NotFoundError | UnavailableError>
readonly read: (sessionID: Session.ID, lines?: number) => Effect.Effect<ReadResult | null, UnavailableError>
readonly remove: (id: Pty.ID) => Effect.Effect<void, NotFoundError | UnavailableError>
Expand Down Expand Up @@ -266,6 +282,18 @@ const makeLayer = (options: Options = {}) =>
return undefined
})

const rename = Effect.fn("PersistentPty.rename")(function* (id: Pty.ID, title: string | null) {
const terminal = yield* get(id)
// Daemons without the feature drop the connection on unknown requests.
if (!(yield* daemon.supports("rename").pipe(Effect.mapError(unavailable))))
return yield* new UnsupportedError({ feature: "rename" })
const response = yield* request(daemon, { op: "rename", id: fromID(id), title })
if (response.type !== "ok") return yield* unexpected(response)
const renamed = yield* get(id)
yield* bus.publish(Updated, { sessionID: terminal.sessionID, terminal: renamed })
return renamed
})

const snapshot = Effect.fn("PersistentPty.snapshot")(function* (id: Pty.ID) {
yield* get(id)
const response = yield* request(daemon, { op: "snapshot", id: fromID(id) })
Expand Down Expand Up @@ -404,6 +432,7 @@ const makeLayer = (options: Options = {}) =>
resize,
control,
input,
rename,
snapshot,
read,
remove,
Expand Down Expand Up @@ -449,6 +478,7 @@ function toInfo(value: WireTerminal): Info {
...(status === "exited" ? { exitCode: value.lifecycle.exit_code ?? undefined } : {}),
}),
sessionID: value.group_id,
userTitle: value.user_title ?? null,
foregroundProcess: value.foreground_process,
size: { cols: value.cols, rows: value.rows },
output: { head: value.output_head, tail: value.output_tail },
Expand Down
70 changes: 67 additions & 3 deletions packages/core/test/fixture/persistent-pty-daemon.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises"
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
import net from "node:net"
import os from "node:os"
import path from "node:path"
Expand Down Expand Up @@ -89,13 +89,77 @@ function frame(value: object) {
return output
}

export function writeRegistration(directory: string, socket: string, instance = "test", token = "test") {
export function writeRegistration(
directory: string,
socket: string,
instance = "test",
token = "test",
features?: string[],
) {
return writeFile(
path.join(directory, "service.json"),
JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token }),
JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token, features }),
)
}

// An in-process opencode-pty that a server adopts through a handoff, so no daemon is spawned. Without
// features it answers like a daemon that predates the features list.
export const fakeDaemon = Effect.fn(function* (features?: string[]) {
const base = yield* temporaryDirectory()
const root = path.join(base, "root")
const directory = path.join(root, "inherited")
const socket = path.join(base, "daemon.sock")
const terminals: Array<ReturnType<typeof terminal> & { user_title?: string | null }> = []
const failTerminate = new Set<string>()
const ops: string[] = []
let nextID = 1
yield* listen(socket, (connection, request) => {
ops.push(String(request.op))
if (request.op === "ping") return features ? { ...pong, features } : pong
if (request.op === "list") return { type: "terminals", terminals }
if (request.op === "create") {
const base = terminal(nextID++, String(request.group_id))
// A daemon that advertises features always serializes user_title.
const created = features ? { ...base, user_title: null } : base
terminals.push(created)
return { type: "created", terminal: created }
}
if (request.op === "control") return { type: "ok" }
if (request.op === "terminate") {
if (failTerminate.has(`pty_persistent_${request.id}`)) return { type: "error", message: "terminate failed" }
const index = terminals.findIndex((item) => item.id === request.id)
if (index === -1) return { type: "error", message: `terminal not found: ${String(request.id)}` }
terminals.splice(index, 1)
return { type: "ok" }
}
if (request.op === "rename" && features?.includes("rename")) {
const found = terminals.find((item) => item.id === request.id)
if (!found) return { type: "error", message: "terminal not found" }
found.user_title = typeof request.title === "string" && request.title !== "" ? request.title : null
found.title = found.user_title ?? "test"
return { type: "ok" }
}
// Old daemons cannot parse unknown requests and drop the connection.
if (request.op === "rename") {
connection.destroy()
return undefined
}
return { type: "error", message: `unexpected request: ${String(request.op)}` }
})
yield* Effect.promise(async () => {
await mkdir(directory, { recursive: true })
await writeRegistration(directory, socket, "test", "test", features)
})
return {
failTerminate,
ops,
options: {
root,
handoff: { directory, instanceID: "test", ticket: "ticket", expiresAt: Date.now() + 60_000 },
},
}
})

export function terminal(id: number, groupID = "ses_test") {
return {
id,
Expand Down
Loading
Loading