mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 08:39:02 +03:00
refactor(client): share the persistent pty protocol (#60323)
This commit is contained in:
committed by
GitHub
Unverified
parent
83e3999996
commit
067b741783
@@ -1,5 +1,52 @@
|
||||
import { PersistentPty } from "@opencode/schema/persistent-pty"
|
||||
import { Schema } from "effect"
|
||||
import type { ExperimentalPersistentPtyConnectTokenInput, OpenCodeClient, PtyConnectTokenInput } from "../promise"
|
||||
|
||||
// Declares only the fields clients read, so servers can add or drop the rest without a client silently ignoring a
|
||||
// message it depends on.
|
||||
export const PersistentPtyMessage = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("attached"),
|
||||
inputProtocol: Schema.optional(Schema.Number),
|
||||
info: Schema.Struct({ size: PersistentPty.Info.fields.size }),
|
||||
role: Schema.optional(Schema.Literals(["controller", "observer"])),
|
||||
}),
|
||||
Schema.Struct({ type: Schema.Literal("replay_complete") }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("resized"),
|
||||
cols: Schema.Number,
|
||||
rows: Schema.Number,
|
||||
checkpoint: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("controller_changed"),
|
||||
attachmentID: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("exited"),
|
||||
exitCode: Schema.optional(Schema.NullOr(Schema.Number)),
|
||||
}),
|
||||
Schema.Struct({ type: Schema.Literal("title_changed"), title: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("foreground_process_changed"), process: Schema.NullOr(Schema.String) }),
|
||||
])
|
||||
export type PersistentPtyMessage = typeof PersistentPtyMessage.Type
|
||||
|
||||
const decodeMessage = Schema.decodeUnknownOption(Schema.fromJsonString(PersistentPtyMessage))
|
||||
|
||||
export function decodePersistentPtyMessage(text: string) {
|
||||
return decodeMessage(text)
|
||||
}
|
||||
|
||||
export function persistentPtyFrame(size: { cols: number; rows: number }, data?: Uint8Array) {
|
||||
const frame = new Uint8Array(5 + (data?.byteLength ?? 0))
|
||||
const view = new DataView(frame.buffer)
|
||||
frame[0] = data ? 1 : 0
|
||||
view.setUint16(1, size.cols)
|
||||
view.setUint16(3, size.rows)
|
||||
if (data) frame.set(data, 5)
|
||||
return frame
|
||||
}
|
||||
|
||||
export type PtyClientOptions = {
|
||||
readonly url: string
|
||||
readonly openSocket?: (url: URL) => WebSocket
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Option } from "effect"
|
||||
import { decodePersistentPtyMessage, persistentPtyFrame } from "../src/solid"
|
||||
|
||||
const info = {
|
||||
id: "pty_1",
|
||||
title: "zsh",
|
||||
command: "/bin/zsh",
|
||||
args: [],
|
||||
cwd: "/repo",
|
||||
status: "running",
|
||||
pid: 42,
|
||||
sessionID: "ses_1",
|
||||
foregroundProcess: null,
|
||||
size: { cols: 80, rows: 24 },
|
||||
output: { head: 0, tail: 128 },
|
||||
}
|
||||
|
||||
const decode = (value: object) => Option.getOrUndefined(decodePersistentPtyMessage(JSON.stringify(value)))
|
||||
|
||||
describe("decodePersistentPtyMessage", () => {
|
||||
test("decodes every message the server sends, keeping only the fields clients read", () => {
|
||||
const replay = { requestedOffset: 128, availableOffset: 0, endOffset: 256, truncated: false }
|
||||
|
||||
expect(
|
||||
[
|
||||
{ type: "attached", inputProtocol: 1, info, role: "controller", generation: 3, replay },
|
||||
{ type: "replay_complete", endOffset: 256 },
|
||||
{ type: "resized", cols: 100, rows: 30, generation: 4, checkpoint: "G2M=" },
|
||||
{ type: "controller_changed", attachmentID: "attachment-1", generation: 5 },
|
||||
{ type: "exited", exitCode: 0, finalOffset: 512 },
|
||||
{ type: "title_changed", title: "vim" },
|
||||
{ type: "foreground_process_changed", process: "vim" },
|
||||
{ type: "foreground_process_changed", process: null },
|
||||
].map(decode),
|
||||
).toEqual([
|
||||
{ type: "attached", inputProtocol: 1, info: { size: info.size }, role: "controller" },
|
||||
{ type: "replay_complete" },
|
||||
{ type: "resized", cols: 100, rows: 30, checkpoint: "G2M=" },
|
||||
{ type: "controller_changed", attachmentID: "attachment-1" },
|
||||
{ type: "exited", exitCode: 0 },
|
||||
{ type: "title_changed", title: "vim" },
|
||||
{ type: "foreground_process_changed", process: "vim" },
|
||||
{ type: "foreground_process_changed", process: null },
|
||||
])
|
||||
})
|
||||
|
||||
test("reads only the size from attached terminal info, whatever else the server version sends", () => {
|
||||
const attached = (terminal: object) => ({ type: "attached", inputProtocol: 1, info: terminal, role: "controller" })
|
||||
|
||||
expect(decode(attached(info))).toEqual(attached({ size: info.size }))
|
||||
expect(decode(attached({ ...info, userTitle: "build", sessionID: "dummy" }))).toEqual(attached({ size: info.size }))
|
||||
expect(decode(attached({ id: "pty_1" }))).toBeUndefined()
|
||||
})
|
||||
|
||||
test("decodes minimal messages and the fields JSON.stringify drops", () => {
|
||||
expect(decode({ type: "attached", info: { size: info.size } })).toEqual({
|
||||
type: "attached",
|
||||
info: { size: info.size },
|
||||
})
|
||||
expect(decode({ type: "replay_complete" })).toEqual({ type: "replay_complete" })
|
||||
expect(decode({ type: "controller_changed", generation: 5 })).toEqual({ type: "controller_changed" })
|
||||
expect(decode({ type: "controller_changed", attachmentID: null })).toEqual({
|
||||
type: "controller_changed",
|
||||
attachmentID: null,
|
||||
})
|
||||
expect(decode({ type: "exited", finalOffset: 512 })).toEqual({ type: "exited" })
|
||||
expect(decode({ type: "exited", exitCode: null })).toEqual({ type: "exited", exitCode: null })
|
||||
})
|
||||
|
||||
test("ignores fields it does not know", () => {
|
||||
expect(decode({ type: "title_changed", title: "vim", extra: true })).toEqual({
|
||||
type: "title_changed",
|
||||
title: "vim",
|
||||
})
|
||||
})
|
||||
|
||||
test("returns None for unknown message types", () => {
|
||||
expect(Option.isNone(decodePersistentPtyMessage(JSON.stringify({ type: "future_message", value: 1 })))).toBe(true)
|
||||
})
|
||||
|
||||
test("returns None for malformed input", () => {
|
||||
const inputs = [
|
||||
"",
|
||||
"not json",
|
||||
"null",
|
||||
"42",
|
||||
JSON.stringify({ endOffset: 1 }),
|
||||
JSON.stringify({ type: "resized", cols: "100", rows: 30, generation: 4, checkpoint: "" }),
|
||||
JSON.stringify({ type: "resized", cols: 100, rows: 30, generation: 4 }),
|
||||
JSON.stringify({ type: "attached", inputProtocol: 1, role: "controller", generation: 1 }),
|
||||
JSON.stringify({ type: "foreground_process_changed" }),
|
||||
]
|
||||
|
||||
expect(inputs.map((input) => Option.isNone(decodePersistentPtyMessage(input)))).toEqual(inputs.map(() => true))
|
||||
})
|
||||
})
|
||||
|
||||
describe("persistentPtyFrame", () => {
|
||||
test("encodes a size-only interaction frame", () => {
|
||||
expect(Array.from(persistentPtyFrame({ cols: 300, rows: 24 }))).toEqual([0, 1, 44, 0, 24])
|
||||
})
|
||||
|
||||
test("encodes an input frame with its data", () => {
|
||||
expect(Array.from(persistentPtyFrame({ cols: 80, rows: 513 }, new Uint8Array([104, 105])))).toEqual([
|
||||
1, 0, 80, 2, 1, 104, 105,
|
||||
])
|
||||
})
|
||||
|
||||
test("encodes empty input as an input frame", () => {
|
||||
expect(Array.from(persistentPtyFrame({ cols: 80, rows: 24 }, new Uint8Array()))).toEqual([1, 0, 80, 0, 24])
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
import { EmbeddedTerminalRenderable, type RGBA } from "@opentui/core"
|
||||
import { decodePersistentPtyMessage, persistentPtyFrame } from "@opencode/client/solid"
|
||||
import { rgbToOklch, type ResolvedThemeTokens } from "@opencode/theme/tui"
|
||||
import { extend, useRenderer } from "@opentui/solid"
|
||||
import { Option } from "effect"
|
||||
import { createEffect, createSignal, onCleanup, onMount, Show } from "solid-js"
|
||||
import { useClient } from "../context/client"
|
||||
import { Keymap } from "../context/keymap"
|
||||
@@ -77,7 +79,7 @@ export function TerminalPane(props: {
|
||||
return
|
||||
}
|
||||
if (!size) return
|
||||
send(interactionFrame(size))
|
||||
send(persistentPtyFrame(size))
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
@@ -89,7 +91,7 @@ export function TerminalPane(props: {
|
||||
pendingInput.push(data)
|
||||
return
|
||||
}
|
||||
if (size) send(interactionFrame(size, data))
|
||||
if (size) send(persistentPtyFrame(size, data))
|
||||
}
|
||||
|
||||
onCleanup(terminals.attachWriter(props.ptyID, sendInput))
|
||||
@@ -206,21 +208,14 @@ export function TerminalPane(props: {
|
||||
return
|
||||
}
|
||||
if (typeof event.data !== "string") return
|
||||
const message: unknown = JSON.parse(event.data)
|
||||
if (!message || typeof message !== "object" || !("type" in message)) return
|
||||
const decoded = decodePersistentPtyMessage(event.data)
|
||||
if (Option.isNone(decoded)) return
|
||||
const message = decoded.value
|
||||
if (message.type === "exited") {
|
||||
exited = true
|
||||
return
|
||||
}
|
||||
if (
|
||||
message.type === "resized" &&
|
||||
"cols" in message &&
|
||||
typeof message.cols === "number" &&
|
||||
"rows" in message &&
|
||||
typeof message.rows === "number" &&
|
||||
"checkpoint" in message &&
|
||||
typeof message.checkpoint === "string"
|
||||
) {
|
||||
if (message.type === "resized") {
|
||||
enqueue({
|
||||
type: "resize",
|
||||
size: { cols: message.cols, rows: message.rows },
|
||||
@@ -232,36 +227,20 @@ export function TerminalPane(props: {
|
||||
enqueue({ type: "ready" })
|
||||
return
|
||||
}
|
||||
if (
|
||||
message.type === "controller_changed" &&
|
||||
"attachmentID" in message &&
|
||||
(typeof message.attachmentID === "string" || message.attachmentID === undefined)
|
||||
) {
|
||||
if (message.type === "controller_changed") {
|
||||
const previous = controller
|
||||
controller = message.attachmentID === attachmentID
|
||||
if (controller && !previous && restored) interact()
|
||||
return
|
||||
}
|
||||
if (message.type !== "attached") return
|
||||
if (!("inputProtocol" in message) || message.inputProtocol !== 1) {
|
||||
if (message.inputProtocol !== 1) {
|
||||
setFailure("Persistent terminal server is out of date; restart OpenCode")
|
||||
next.close()
|
||||
return
|
||||
}
|
||||
if (
|
||||
"info" in message &&
|
||||
message.info &&
|
||||
typeof message.info === "object" &&
|
||||
"size" in message.info &&
|
||||
message.info.size &&
|
||||
typeof message.info.size === "object" &&
|
||||
"cols" in message.info.size &&
|
||||
typeof message.info.size.cols === "number" &&
|
||||
"rows" in message.info.size &&
|
||||
typeof message.info.size.rows === "number"
|
||||
)
|
||||
enqueue({ type: "resize", size: { cols: message.info.size.cols, rows: message.info.size.rows } })
|
||||
controller = "role" in message && message.role === "controller"
|
||||
enqueue({ type: "resize", size: { cols: message.info.size.cols, rows: message.info.size.rows } })
|
||||
controller = message.role === "controller"
|
||||
attached = true
|
||||
})
|
||||
next.addEventListener("error", () => {
|
||||
@@ -396,13 +375,3 @@ function hex(color: RGBA) {
|
||||
.map((value) => value.toString(16).padStart(2, "0"))
|
||||
.join("")}`
|
||||
}
|
||||
|
||||
function interactionFrame(size: { cols: number; rows: number }, data?: Uint8Array) {
|
||||
const frame = new Uint8Array(5 + (data?.byteLength ?? 0))
|
||||
const view = new DataView(frame.buffer)
|
||||
frame[0] = data ? 1 : 0
|
||||
view.setUint16(1, size.cols)
|
||||
view.setUint16(3, size.rows)
|
||||
if (data) frame.set(data, 5)
|
||||
return frame
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user