Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
58 changes: 54 additions & 4 deletions packages/core/src/persistent-pty/daemon.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process"
import { readFile } from "node:fs/promises"
import { mkdir, open, readFile, stat } from "node:fs/promises"
import net from "node:net"
import path from "node:path"
import { Cause, Data, Duration, Effect, Schema, Semaphore } from "effect"
Expand Down Expand Up @@ -269,22 +269,24 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"

const spawnDaemon = Effect.fn("PersistentPty.daemon.spawn")(function* () {
const executable = yield* Effect.tryPromise({ try: binary, catch: (cause) => failure("spawn", cause) })
// Without a log the daemon's own reports (a terminal it stopped waiting for, a job it could not use) are lost.
const log = yield* Effect.promise(() => openLog(root).catch(() => undefined))
const child = yield* Effect.tryPromise({
try: () =>
new Promise<ReturnType<typeof spawn>>((resolve, reject) => {
const child = spawn(executable, ["daemon", "--runtime-dir", root, "--name", id], {
detached: true,
windowsHide: true,
stdio: "ignore",
stdio: ["ignore", "ignore", log?.fd ?? "ignore"],
})
child.once("spawn", () => {
child.unref()
resolve(child)
})
child.once("error", reject)
}),
catch: (cause) => failure("spawn", cause),
})
catch: (cause) => failure("spawn", refusedSpawn(executable, cause) ?? cause),
}).pipe(Effect.ensuring(Effect.promise(() => log?.close() ?? Promise.resolve())))
return yield* Effect.gen(function* () {
const deadline = Date.now() + 5_000
let last: DaemonError | undefined
Expand Down Expand Up @@ -376,10 +378,38 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
withRegistration(shouldStart, (current) => oneShot(current, value)),
)

// The registration resets only when connecting fails, so a daemon that still takes connections but answers nothing
// would fail every later request the same way until the server restarts. When a reply goes missing and a ping on a
// fresh connection gets none either, give the daemon up: closing the owner connection stops it, and the next request
// starts a fresh one. Its terminals end with it. The request itself is not replayed, since it may have run.
const replaceUnresponsive = Effect.fn("PersistentPty.daemon.replaceUnresponsive")(function* (error: DaemonError) {
const current = registration
if (!current) return yield* Effect.fail(error)
const answers = yield* oneShot(current, { op: "ping" }).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
)
if (answers) return yield* Effect.fail(error)
yield* startup.withPermit(
Effect.sync(() => {
if (registration === current) abandon()
}),
)
yield* Effect.logWarning("Replacing an opencode-pty daemon that stopped responding", { pid: current.pid })
return yield* Effect.fail(
new DaemonError({
kind: "connect",
message: "opencode-pty stopped responding and was replaced",
pid: current.pid,
}),
)
})

const request = Effect.fn("PersistentPty.daemon.request")(function* (value: object, shouldStart = false) {
return yield* attempt(value, shouldStart).pipe(
Effect.catch((error) => {
if (error.kind === "registration") return attempt(value, shouldStart)
if (error.kind === "response") return replaceUnresponsive(error)
if (error.kind !== "connect") return Effect.fail(error)
registration = undefined
if (!shouldStart) return Effect.fail(error)
Expand Down Expand Up @@ -745,6 +775,26 @@ function responseError(message: string) {
return new DaemonError({ kind: message === "authentication failed" ? "registration" : "request", message })
}

// Windows refuses an unsigned program under Smart App Control or an application control policy, and libuv reports
// that only as an unknown error, which says nothing about the cause.
function refusedSpawn(executable: string, cause: unknown) {
if (process.platform !== "win32" || !(cause instanceof Error) || !("code" in cause) || cause.code !== "EUNKNOWN")
return
return `Windows refused to start ${executable}. Smart App Control or an application control policy (WDAC, AppLocker) usually causes this; a damaged file can too. (${cause.message})`
}

// One log for every daemon of this root, beside their runtime directories, which their sweep leaves alone. It starts
// over once it passes 1 MB.
async function openLog(root: string) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The log goes in root, next to the daemon's runtime directories. That breaks creates two persistent terminals for one session through the client API in packages/server/test/persistent-pty.test.ts: it reads fs.readdir(fixture.directory) and expects exactly one entry, the daemon directory, and now gets opencode-pty.log as well. It passes on the base and fails with this PR. Either update that test or move the log somewhere the runtime-root listing doesn't see. Separately, the 1 MB check only runs when a daemon is spawned, so a long-lived daemon can still grow the file without limit.

await mkdir(root, { recursive: true })
const file = path.join(root, "opencode-pty.log")
const size = await stat(file).then(
(info) => info.size,
() => 0,
)
return open(file, size > 1024 * 1024 ? "w" : "a")
}

function failure(kind: DaemonError["kind"], cause: unknown) {
return new DaemonError({ kind, message: cause instanceof Error ? cause.message : String(cause) })
}
61 changes: 61 additions & 0 deletions packages/core/test/persistent-pty-daemon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { mkdir, writeFile } from "node:fs/promises"
import net from "node:net"
import path from "node:path"
import { Effect, Fiber } from "effect"
import { TestClock } from "effect/testing"
import { makeDaemonTransport } from "../src/persistent-pty/daemon"
import { frame, listen, pong, temporaryDirectory, terminal, writeRegistration } from "./fixture/persistent-pty-daemon"
import { it } from "./lib/effect"
Expand Down Expand Up @@ -203,6 +204,66 @@ it.live("does not replay a dispatched mutating request when its response is lost
}),
)

it.effect("replaces a daemon that takes requests but no longer answers them", () =>
Effect.gen(function* () {
const { root, directory } = yield* TestClock.withLive(temporaryRuntime())
const socketPath = path.join(directory, "daemon.sock")
const seen: string[] = []
let answering = true
yield* TestClock.withLive(
listen(socketPath, (_socket, request) => {
seen.push(String(request.op))
if (!answering) return undefined
if (request.op === "ping") return pong
return { type: "processes", processes: [] }
}),
)
yield* Effect.promise(() => writeRegistration(directory, socketPath))
const daemon = yield* makeDaemonTransport(root, "daemon")
yield* TestClock.withLive(daemon.request({ op: "list" }))
answering = false

const waitFor = (op: string, count: number) =>
TestClock.withLive(
Effect.gen(function* () {
const deadline = Date.now() + 10_000
while (seen.filter((value) => value === op).length < count && Date.now() < deadline) yield* Effect.sleep(5)
}),
)
const pings = seen.filter((value) => value === "ping").length
const pending = yield* daemon
.request({ op: "list" })
.pipe(Effect.flip, Effect.forkChild({ startImmediately: true }))
yield* waitFor("list", 2)
yield* TestClock.adjust("5 seconds")
yield* waitFor("ping", pings + 1)
yield* TestClock.adjust("5 seconds")
const error = yield* Fiber.join(pending)

expect(error).toMatchObject({ kind: "connect", message: "opencode-pty stopped responding and was replaced" })
// The registration was given up: nothing is running for the next request that must not start a daemon.
expect(yield* TestClock.withLive(daemon.requestIfRunning({ op: "list" }))).toBeUndefined()
expect(seen.filter((value) => value === "list")).toHaveLength(2)
}),
)

// Windows reports an executable it refuses to start, blocked by policy or not a valid program, as EUNKNOWN.
const windows = process.platform === "win32" ? it.live : it.live.skip

windows("names the likely cause when Windows refuses to start the daemon", () =>
Effect.gen(function* () {
const { root } = yield* temporaryRuntime()
const binary = path.join(root, "opencode-pty.exe")
yield* Effect.promise(() => writeFile(binary, "not a program"))
const daemon = yield* makeDaemonTransport(root, "daemon", () => Promise.resolve(binary))

const error = yield* Effect.flip(daemon.request({ op: "list" }, true))
expect(error.kind).toBe("spawn")
expect(error.message).toContain(`Windows refused to start ${binary}`)
expect(error.message).toContain("Smart App Control")
}),
)

it.live("rejects incompatible daemons without replacing or killing them", () =>
Effect.gen(function* () {
const { root, directory } = yield* temporaryRuntime()
Expand Down
18 changes: 17 additions & 1 deletion packages/gui-plugins/src/terminal/terminal-key-event.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"
import { consumeTerminalMetaKey, terminalKeyInput, terminalLinkTarget } from "./terminal-key-event"
import { consumeTerminalMetaKey, terminalKeyInput, terminalLinkTarget, terminalScrollKey } from "./terminal-key-event"

function keyEvent(init: KeyboardEventInit) {
return new KeyboardEvent("keydown", { cancelable: true, ...init })
Expand Down Expand Up @@ -36,6 +36,22 @@ describe("terminalKeyEvent", () => {
expect(consumeTerminalMetaKey(keyEvent({ key: "c", code: "KeyI", metaKey: true }), { copy: () => true })).toBe(true)
})

test("maps Shift+PageUp, PageDown, Home and End to scrollback moves", () => {
expect(terminalScrollKey(keyEvent({ key: "PageUp", code: "PageUp", shiftKey: true }))).toBe("page-up")
expect(terminalScrollKey(keyEvent({ key: "PageDown", code: "PageDown", shiftKey: true }))).toBe("page-down")
expect(terminalScrollKey(keyEvent({ key: "Home", code: "Home", shiftKey: true }))).toBe("top")
expect(terminalScrollKey(keyEvent({ key: "End", code: "End", shiftKey: true }))).toBe("bottom")
})

test("leaves PageUp and other chords to the shell", () => {
expect(terminalScrollKey(keyEvent({ key: "PageUp", code: "PageUp" }))).toBeUndefined()
expect(
terminalScrollKey(keyEvent({ key: "PageUp", code: "PageUp", shiftKey: true, ctrlKey: true })),
).toBeUndefined()
expect(terminalScrollKey(keyEvent({ key: "Home", code: "Home", shiftKey: true, metaKey: true }))).toBeUndefined()
expect(terminalScrollKey(keyEvent({ key: "A", code: "KeyA", shiftKey: true }))).toBeUndefined()
})

test("never consumes Ctrl chords so they reach the shell", () => {
expect(consumeTerminalMetaKey(keyEvent({ key: "c", code: "KeyC", ctrlKey: true }))).toBe(false)
expect(consumeTerminalMetaKey(keyEvent({ key: "a", code: "KeyA", ctrlKey: true }))).toBe(false)
Expand Down
13 changes: 13 additions & 0 deletions packages/gui-plugins/src/terminal/terminal-key-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ export function terminalKeyInput(event: KeyboardEvent) {
return "\x15"
}

/** Shift+PageUp, PageDown, Home and End: the scrollback moves other terminals give these keys. */
export function terminalScrollKey(event: KeyboardEvent) {
if (!event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) return

if (event.key === "PageUp") return "page-up"

if (event.key === "PageDown") return "page-down"

if (event.key === "Home") return "top"

if (event.key === "End") return "bottom"
}

// ghostty-web sends the raw character to the PTY for Command chords, so consume them here.
// Returning true makes ghostty-web preventDefault, so physical KeyV/KeyC are left alone
// (whatever character the layout gives them, e.g. RTL) so native paste and copy still run.
Expand Down
22 changes: 20 additions & 2 deletions packages/gui-plugins/src/terminal/terminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
import type { TerminalProps } from "./props"
import { disposeIfDisposable, getHoveredLinkText, setOptionIfSupported } from "./runtime-adapters"
import { terminalLinkLabel } from "./hover-label"
import { consumeTerminalMetaKey, terminalKeyInput, terminalLinkTarget } from "./terminal-key-event"
import { consumeTerminalMetaKey, terminalKeyInput, terminalScrollKey, terminalLinkTarget } from "./terminal-key-event"
import { TerminalQuote } from "./quote"

type TerminalColors = {
Expand Down Expand Up @@ -116,7 +116,9 @@ const useTerminalUiBindings = (input: {

event.preventDefault()
event.stopPropagation()
input.term.paste(text)
// A terminal sends Enter as CR. Windows clipboards end lines with CR LF, which PowerShell reads as Enter followed by
// a stray line feed, so send each line break as one CR, as other terminals do.
input.term.paste(text.replace(/\r?\n/g, "\r"))
}

const handleTextareaFocus = () => {
Expand Down Expand Up @@ -476,6 +478,22 @@ export const Terminal = (props: TerminalProps) => {
return true
}

// Programs on the alternate screen (vim, less) keep these keys; on the normal screen they move through the
// scrollback, as in other terminals.
const scroll = terminalScrollKey(event)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the normal screen this always takes Shift+Home and Shift+End. PowerShell's line editor (PSReadLine), the main Windows shell, binds them by default to select to the start and end of the line, and fish and zsh users sometimes bind them too. Windows Terminal leaves Shift+Home and Shift+End to the shell and only scrolls with Ctrl+Shift+Home and Ctrl+Shift+End. Shift+PageUp and Shift+PageDown look safe; Home and End could be limited to Ctrl+Shift, or not taken at all.


if (scroll && !t.wasmTerm?.isAlternateScreen()) {
if (scroll === "page-up") t.scrollPages(-1)

if (scroll === "page-down") t.scrollPages(1)

if (scroll === "top") t.scrollToTop()

if (scroll === "bottom") t.scrollToBottom()

return true
}

if (event.ctrlKey && event.shiftKey && !event.metaKey && key === "c") {
document.execCommand("copy")

Expand Down
56 changes: 56 additions & 0 deletions packages/process-daemon/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ const OUTPUT_BATCH_BYTES: usize = 8 * 1024;
const OUTPUT_BATCH_DELAY: Duration = Duration::from_millis(1);
const MAX_INPUT_BYTES: usize = 1024 * 1024;
const MAX_ROWS_BYTES: usize = 1024 * 1024;
/// How long terminate waits for a terminal's workers before ending what is left
/// of its process tree, and again before it stops waiting for them.
#[cfg(windows)]
const TEARDOWN_GRACE: Duration = Duration::from_millis(1500);

pub type TerminalId = u64;

Expand Down Expand Up @@ -651,6 +655,9 @@ struct TerminalHandle {
process: Option<Arc<pipe::Process>>,
info: Arc<RwLock<ProcessInfo>>,
joins: Mutex<Option<Vec<JoinHandle<()>>>>,
/// PTY only: the job the root shell and its descendants run in.
#[cfg(windows)]
job: Option<windows::TerminalJob>,
}

/// The actor thread and the channels other workers share with it.
Expand Down Expand Up @@ -753,6 +760,8 @@ impl TerminalHandle {
.spawn_command(command)
.with_context(|| format!("failed to spawn {}", request.program))?;
let pid = child.process_id();
#[cfg(windows)]
let job = windows::TerminalJob::assign(id, child.as_raw_handle());
let killer = child.clone_killer();
let mut reader = pair
.master
Expand Down Expand Up @@ -890,6 +899,8 @@ impl TerminalHandle {
reader_thread,
wait_thread,
])),
#[cfg(windows)]
job,
})
}

Expand Down Expand Up @@ -942,11 +953,54 @@ impl TerminalHandle {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.take();
#[cfg(windows)]
let handles = self.release_stuck_console(handles);
for join in handles {
let _ = join.join();
}
Ok(())
}

/// Closing ConPTY ends the programs on its console, and its output ends
/// with them. A program that cannot leave the console (one that is
/// suspended, or never answers the close) keeps the output open, and the
/// reader waiting on it, for as long as it lives. Give the close a moment,
/// then end what is left of the root's process tree; a worker still blocked
/// after that is left to finish on its own rather than blocking terminate.
#[cfg(windows)]
fn release_stuck_console(&self, handles: Vec<JoinHandle<()>>) -> Vec<JoinHandle<()>> {
if finished_within(&handles, TEARDOWN_GRACE) {
return handles;
}
if let Some(job) = &self.job {
job.terminate();
}
if finished_within(&handles, TEARDOWN_GRACE) {
return handles;
}
eprintln!(
"terminal {}: its workers are still blocked; terminate stops waiting for them",
self.info().id
);
handles
.into_iter()
.filter(|handle| handle.is_finished())
.collect()
}
}

#[cfg(windows)]
fn finished_within(handles: &[JoinHandle<()>], grace: Duration) -> bool {
let deadline = Instant::now() + grace;
loop {
if handles.iter().all(JoinHandle::is_finished) {
return true;
}
if Instant::now() >= deadline {
return false;
}
thread::sleep(Duration::from_millis(10));
}
}

/// Info for a new process, without its `pty` or `pipe` group.
Expand Down Expand Up @@ -2285,6 +2339,8 @@ mod tests {
#[cfg(windows)]
closer,
])),
#[cfg(windows)]
job: None,
},
writer_rx,
)
Expand Down
3 changes: 3 additions & 0 deletions packages/process-daemon/src/service/pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ fn start_pipe(
process: Some(process),
info,
joins: Mutex::new(Some(joins)),
// The pipe process owns its own job.
#[cfg(windows)]
job: None,
})
}

Expand Down
Loading
Loading