diff --git a/packages/core/src/persistent-pty/daemon.ts b/packages/core/src/persistent-pty/daemon.ts index 50d2284340c..526dc59c1a5 100644 --- a/packages/core/src/persistent-pty/daemon.ts +++ b/packages/core/src/persistent-pty/daemon.ts @@ -120,6 +120,15 @@ export type StreamEvent = | { readonly type: "title_changed"; readonly title: string } | { readonly type: "foreground_process_changed"; readonly process: string | null } +export type SubscribeInput = { + readonly cursor: number + readonly attachmentID: string + readonly role: Role + readonly takeover?: boolean + readonly onEvent: (event: StreamEvent) => void + readonly onEnd: () => void +} + export type DaemonAttachment = { readonly terminal: WireTerminal readonly role: Role @@ -149,14 +158,7 @@ export interface DaemonTransport { readonly handoff: Effect.Effect readonly subscribe: ( id: number, - input: { - readonly cursor: number - readonly attachmentID: string - readonly role: Role - readonly takeover?: boolean - readonly onEvent: (event: StreamEvent) => void - readonly onEnd: () => void - }, + input: SubscribeInput, ) => Effect.Effect } @@ -316,15 +318,21 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport" ) }) - const attempt = Effect.fn("PersistentPty.daemon.request-attempt")(function* (value: object, shouldStart: boolean) { - const current = yield* connect(shouldStart) - return yield* oneShot(current, value).pipe( - Effect.catch((error) => { - if (error.kind === "registration" && registration === current) registration = undefined - return Effect.fail(error) - }), - ) - }) + // Runs against the live registration and forgets it when the daemon rejects it as stale. + const withRegistration = (shouldStart: boolean, run: (current: Registration) => Effect.Effect) => + Effect.gen(function* () { + const current = yield* connect(shouldStart) + return yield* run(current).pipe( + Effect.catch((error) => { + if (error.kind === "registration" && registration === current) registration = undefined + return Effect.fail(error) + }), + ) + }) + + const attempt = Effect.fn("PersistentPty.daemon.request-attempt")((value: object, shouldStart: boolean) => + withRegistration(shouldStart, (current) => oneShot(current, value)), + ) const request = Effect.fn("PersistentPty.daemon.request")(function* (value: object, shouldStart = false) { return yield* attempt(value, shouldStart).pipe( @@ -392,20 +400,14 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport" const subscribe = Effect.fn("PersistentPty.daemon.subscribe")(function* ( terminalID: number, - input: Parameters[1], + input: SubscribeInput, ) { - const attempt = Effect.gen(function* () { - const current = yield* connect(false) - return yield* Effect.tryPromise({ + const attempt = withRegistration(false, (current) => + Effect.tryPromise({ try: () => subscribePromise(current, terminalID, input), catch: (cause) => (cause instanceof DaemonError ? cause : failure("connect", cause)), - }).pipe( - Effect.catch((error) => { - if (error.kind === "registration" && registration === current) registration = undefined - return Effect.fail(error) - }), - ) - }) + }), + ) return yield* attempt.pipe(Effect.catch((error) => (error.kind === "registration" ? attempt : Effect.fail(error)))) }) @@ -535,13 +537,7 @@ const oneShot = Effect.fn("PersistentPty.daemon.oneShot")(function* (registratio try: () => decode(first), catch: (cause) => failure("protocol", cause), }) - if (response.type === "error") - return yield* Effect.fail( - new DaemonError({ - kind: response.message === "authentication failed" ? "registration" : "protocol", - message: response.message, - }), - ) + if (response.type === "error") return yield* Effect.fail(responseError(response.message)) return response }), (socket) => Effect.sync(() => socket.destroy()), @@ -562,7 +558,7 @@ const oneShot = Effect.fn("PersistentPty.daemon.oneShot")(function* (registratio async function subscribePromise( registration: Registration, id: number, - input: Parameters[1], + input: SubscribeInput, ): Promise { const socket = net.createConnection(registration.socket) const frames = decoder(socket) @@ -587,11 +583,7 @@ async function subscribePromise( const initial = await frames.next() if (initial.done) throw new Error("opencode-pty closed before attachment") const response = decode(initial.value) - if (response.type === "error") - throw new DaemonError({ - kind: response.message === "authentication failed" ? "registration" : "protocol", - message: response.message, - }) + if (response.type === "error") throw responseError(response.message) if (response.type !== "attached") throw new Error(`unexpected opencode-pty response: ${response.type}`) let detached = false const pump = async () => { @@ -698,6 +690,10 @@ function decode(payload: Uint8Array) { return decodeWireResponse(Buffer.from(payload).toString("utf8")) } +function responseError(message: string) { + return new DaemonError({ kind: message === "authentication failed" ? "registration" : "protocol", message }) +} + function failure(kind: DaemonError["kind"], cause: unknown) { return new DaemonError({ kind, message: cause instanceof Error ? cause.message : String(cause) }) } diff --git a/packages/core/src/persistent-pty/index.ts b/packages/core/src/persistent-pty/index.ts index 22f38818ee6..1728996636d 100644 --- a/packages/core/src/persistent-pty/index.ts +++ b/packages/core/src/persistent-pty/index.ts @@ -21,9 +21,10 @@ import { Global } from "@opencode/util/global" import { ShellSelect } from "../shell/select.js" import { makeDaemonTransport, + type DaemonAttachment, type DaemonTransport, type Role, - type StreamEvent, + type SubscribeInput, type WireResponse, type WireTerminal, } from "./daemon.js" @@ -48,13 +49,7 @@ export type Attachment = { readonly info: Info readonly role: Role readonly generation: number - readonly replay: { - readonly requestedOffset: number - readonly availableOffset: number - readonly endOffset: number - readonly truncated: boolean - readonly data: Uint8Array - } + readonly replay: DaemonAttachment["replay"] readonly activate: () => void readonly detach: () => void } @@ -126,14 +121,7 @@ export interface Interface { readonly handoff: () => Effect.Effect readonly attach: ( id: Pty.ID, - input: { - readonly cursor: number - readonly attachmentID: string - readonly role: Role - readonly takeover?: boolean - readonly onEvent: (event: StreamEvent) => void - readonly onEnd: () => void - }, + input: SubscribeInput, ) => Effect.Effect } @@ -211,76 +199,42 @@ const makeLayer = (options: Options = {}) => return terminal }) - const write = Effect.fn("PersistentPty.write")(function* (id: Pty.ID, data: string, attachmentID?: string) { - yield* get(id) - const response = yield* request(daemon, { - op: "write", - id: fromID(id), - attachment_id: attachmentID ?? null, - data_base64: Buffer.from(data).toString("base64"), + // Sends a terminal command that answers "ok"; `select` marks the terminal as its session's current one. + const command = (id: Pty.ID, op: string, body: object, select: boolean) => + Effect.gen(function* () { + const terminal = yield* get(id) + const response = yield* request(daemon, { op, id: fromID(id), ...body }) + if (response.type !== "ok") return yield* unexpected(response) + if (select) current.set(terminal.sessionID, id) }) - if (response.type !== "ok") return yield* unexpected(response) - return undefined - }) - const resize = Effect.fn("PersistentPty.resize")(function* ( - id: Pty.ID, - cols: number, - rows: number, - attachmentID?: string, - ) { - const terminal = yield* get(id) - const response = yield* request(daemon, { - op: "resize", - id: fromID(id), - attachment_id: attachmentID ?? null, - cols, - rows, - }) - if (response.type !== "ok") return yield* unexpected(response) - current.set(terminal.sessionID, id) - return undefined - }) + const write = Effect.fn("PersistentPty.write")((id: Pty.ID, data: string, attachmentID?: string) => + command( + id, + "write", + { attachment_id: attachmentID ?? null, data_base64: Buffer.from(data).toString("base64") }, + false, + ), + ) - const control = Effect.fn("PersistentPty.control")(function* ( - id: Pty.ID, - attachmentID: string, - cols: number, - rows: number, - ) { - const terminal = yield* get(id) - const response = yield* request(daemon, { - op: "control", - id: fromID(id), - attachment_id: attachmentID, - cols, - rows, - }) - if (response.type !== "ok") return yield* unexpected(response) - current.set(terminal.sessionID, id) - return undefined - }) + const resize = Effect.fn("PersistentPty.resize")((id: Pty.ID, cols: number, rows: number, attachmentID?: string) => + command(id, "resize", { attachment_id: attachmentID ?? null, cols, rows }, true), + ) - const input = Effect.fn("PersistentPty.input")(function* ( - id: Pty.ID, - attachmentID: string, - cols: number, - rows: number, - data: Uint8Array, - ) { - const terminal = yield* get(id) - const response = yield* request(daemon, { - op: "input", - id: fromID(id), - attachment_id: attachmentID, - cols, - rows, - data_base64: Buffer.from(data).toString("base64"), - }) - if (response.type !== "ok") return yield* unexpected(response) - current.set(terminal.sessionID, id) - return undefined - }) + const control = Effect.fn("PersistentPty.control")( + (id: Pty.ID, attachmentID: string, cols: number, rows: number) => + command(id, "control", { attachment_id: attachmentID, cols, rows }, true), + ) + + const input = Effect.fn("PersistentPty.input")( + (id: Pty.ID, attachmentID: string, cols: number, rows: number, data: Uint8Array) => + command( + id, + "input", + { attachment_id: attachmentID, cols, rows, data_base64: Buffer.from(data).toString("base64") }, + true, + ), + ) const rename = Effect.fn("PersistentPty.rename")(function* (id: Pty.ID, title: string | null) { const terminal = yield* get(id) diff --git a/packages/core/src/pty.ts b/packages/core/src/pty.ts index 6d4ac6d628f..5af2f902f19 100644 --- a/packages/core/src/pty.ts +++ b/packages/core/src/pty.ts @@ -27,8 +27,8 @@ type Subscriber = { type Active = { info: Info process: Proc + // Retained output ending at cursor. buffer: string - bufferCursor: number cursor: number subscribers: Map listeners: Disp[] @@ -195,7 +195,6 @@ const layer = Layer.effect( info, process: proc, buffer: "", - bufferCursor: 0, cursor: 0, subscribers: new Map(), listeners: [], @@ -217,9 +216,7 @@ const layer = Layer.effect( } session.buffer += chunk if (session.buffer.length <= BUFFER_LIMIT) return - const excess = session.buffer.length - BUFFER_LIMIT - session.buffer = session.buffer.slice(excess) - session.bufferCursor += excess + session.buffer = session.buffer.slice(session.buffer.length - BUFFER_LIMIT) }), proc.onExit(({ exitCode }) => { if (session.info.status === "exited") return @@ -270,7 +267,6 @@ const layer = Layer.effect( pending: [], } session.subscribers.set(token, subscriber) - const start = session.bufferCursor const end = session.cursor const from = input.cursor === -1 @@ -278,14 +274,8 @@ const layer = Layer.effect( : input.cursor !== undefined && Number.isSafeInteger(input.cursor) ? Math.max(0, input.cursor) : 0 - const replay = (() => { - if (!session.buffer || from >= end) return "" - const offset = Math.max(0, from - start) - if (offset >= session.buffer.length) return "" - return session.buffer.slice(offset) - })() return { - replay, + replay: session.buffer.slice(Math.max(0, from - (end - session.buffer.length))), cursor: end, write: (data: string) => { if (session.info.status === "running") session.process.write(data)