Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion packages/desktop-electron/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ registerAboutIpc()

function killSidecar() {
if (!server) return
server.stop()
server.stop(true)
server = null
}

Expand Down
87 changes: 79 additions & 8 deletions packages/opencode/src/pty/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import { envValueCaseInsensitive, withoutInternalServerAuthEnv } from "@/util/en
import { PtyID } from "./schema"
import { Effect, Layer, Context } from "effect"
import * as EffectLogger from "@opencode-ai/core/effect/logger"
import { setTimeout as sleep } from "node:timers/promises"

export namespace Pty {
const log = Log.create({ service: "pty" })

const BUFFER_LIMIT = 1024 * 1024 * 2
const BUFFER_CHUNK = 64 * 1024
const TERMINATION_GRACE_MS = 200
const EXIT_WAIT_MS = 1000
const encoder = new TextEncoder()

type Socket = {
Expand Down Expand Up @@ -121,10 +124,8 @@ export namespace Pty {
Effect.gen(function* () {
const bus = yield* Bus.Service
const plugin = yield* Plugin.Service
function teardown(session: Active) {
try {
session.process.kill()
} catch {}

function closeSubscribers(session: Active) {
for (const [sub, ws] of session.subscribers.entries()) {
try {
if (sock(ws) === sub) ws.close()
Expand All @@ -133,6 +134,78 @@ export namespace Pty {
session.subscribers.clear()
}

function waitForExit(session: Active) {
if (session.info.status === "exited") return Promise.resolve()
return new Promise<void>((resolve) => {
const timer = setTimeout(resolve, EXIT_WAIT_MS)
const sub = session.process.onExit(() => {
clearTimeout(timer)
sub.dispose()
resolve()
})
})
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function signalGroup(session: Active, signal: string) {
try {
process.kill(-session.process.pid, signal)
return true
} catch {
return false
}
}

function signalProcess(session: Active, signal: string) {
try {
session.process.kill(signal)
} catch {}
}

const terminate = Effect.fn("Pty.terminate")(function* (session: Active) {
const exited = waitForExit(session)
if (process.platform === "win32") {
signalProcess(session, "SIGTERM")
yield* Effect.promise(() => exited)
return
}

if (signalGroup(session, "SIGTERM")) {
yield* Effect.promise(() => sleep(TERMINATION_GRACE_MS))
signalGroup(session, "SIGKILL")
} else {
signalProcess(session, "SIGTERM")
yield* Effect.promise(() => sleep(TERMINATION_GRACE_MS))
signalProcess(session, "SIGKILL")
}
yield* Effect.promise(() => exited)
})

const terminateSync = (session: Active) => {
if (process.platform === "win32") {
signalProcess(session, "SIGTERM")
return
}

const killedGroup = signalGroup(session, "SIGTERM")
if (!killedGroup) {
signalProcess(session, "SIGTERM")
}
setTimeout(() => {
if (killedGroup) signalGroup(session, "SIGKILL")
else signalProcess(session, "SIGKILL")
}, TERMINATION_GRACE_MS).unref()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

const teardown = Effect.fn("Pty.teardown")(function* (session: Active) {
closeSubscribers(session)
yield* terminate(session)
})

function teardownSync(session: Active) {
closeSubscribers(session)
terminateSync(session)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

const state = yield* InstanceState.make<State>(
Effect.fn("Pty.state")(function* (ctx) {
const state = {
Expand All @@ -142,9 +215,7 @@ export namespace Pty {

yield* Effect.addFinalizer(() =>
Effect.sync(() => {
for (const session of state.sessions.values()) {
teardown(session)
}
for (const session of state.sessions.values()) teardownSync(session)
state.sessions.clear()
}),
)
Expand All @@ -159,7 +230,7 @@ export namespace Pty {
if (!session) return
s.sessions.delete(id)
log.info("removing session", { id })
teardown(session)
yield* teardown(session)
yield* bus.publish(Event.Deleted, { id: session.info.id })
})

Expand Down
4 changes: 3 additions & 1 deletion packages/opencode/src/session/llm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,9 @@ const live: Layer.Layer<

const result = yield* run({ ...input, abort: ctrl.signal })

return Stream.fromAsyncIterable(result.fullStream, (e) => (e instanceof Error ? e : new Error(String(e))))
return Stream.fromAsyncIterable(result.fullStream, (e) => (e instanceof Error ? e : new Error(String(e)))).pipe(
Stream.timeout("10 minutes"),
)
}),
),
)
Expand Down
2 changes: 1 addition & 1 deletion packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ export const layer: Layer.Layer<

yield* Effect.forEach(
Object.values(ctx.toolcalls),
(call) => Deferred.await(call.done).pipe(Effect.timeout("250 millis"), Effect.ignore),
(call) => Deferred.await(call.done).pipe(Effect.timeout("5 seconds"), Effect.ignore),
{ concurrency: "unbounded" },
)

Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/session/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const RETRY_INITIAL_DELAY = 2000
export const RETRY_BACKOFF_FACTOR = 2
export const RETRY_MAX_DELAY_NO_HEADERS = 30_000 // 30 seconds
export const RETRY_MAX_DELAY = 2_147_483_647 // max 32-bit signed integer for setTimeout
export const RETRY_MAX_ATTEMPTS = 10

function cap(ms: number) {
return Math.min(ms, RETRY_MAX_DELAY)
Expand Down Expand Up @@ -112,6 +113,7 @@ export function policy(opts: {
const error = opts.parse(meta.input)
const message = retryable(error)
if (!message) return Cause.done(meta.attempt)
if (meta.attempt >= RETRY_MAX_ATTEMPTS) return Cause.done(meta.attempt)
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
return Effect.gen(function* () {
const wait = delay(meta.attempt, MessageV2.APIError.isInstance(error) ? error : undefined)
const now = yield* Clock.currentTimeMillis
Expand Down
39 changes: 39 additions & 0 deletions packages/opencode/test/pty/pty-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Pty } from "../../src/pty"
import type { PtyID } from "../../src/pty/schema"
import { tmpdir } from "../fixture/fixture"
import { setTimeout as sleep } from "node:timers/promises"
import { existsSync } from "node:fs"

const wait = async (fn: () => boolean, ms = 5000) => {
const end = Date.now() + ms
Expand Down Expand Up @@ -90,6 +91,44 @@ describe("pty", () => {
})
})

test("remove terminates child processes started inside the pty", async () => {
if (process.platform === "win32") return

await using dir = await tmpdir({ git: true })

await Instance.provide({
directory: dir.path,
fn: async () => {
const pidFile = `${dir.path}/pty-child.pid`
let id: PtyID | undefined
try {
const info = await Pty.create({
command: "/bin/sh",
args: ["-c", `trap '' HUP TERM; sleep 30 & echo $! > ${JSON.stringify(pidFile)}; wait`],
title: "child-tree",
})
id = info.id

await wait(() => existsSync(pidFile))
const pid = Number((await Bun.file(pidFile).text()).trim())
expect(pid).toBeGreaterThan(0)

await Pty.remove(id)
await wait(() => {
try {
process.kill(pid, 0)
return false
} catch {
return true
}
})
} finally {
if (id) await Pty.remove(id)
}
},
})
})

test("does not expose internal server auth env to terminal sessions", async () => {
if (process.platform === "win32") return

Expand Down
56 changes: 56 additions & 0 deletions packages/opencode/test/tool/bash.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { describe, expect, test } from "bun:test"
import { Effect, Layer, ManagedRuntime } from "effect"
import os from "os"
import path from "path"
import { existsSync } from "node:fs"
import { setTimeout as sleep } from "node:timers/promises"
import { Shell } from "../../src/shell/shell"
import { BashTool } from "../../src/tool/bash"
import { Instance } from "../../src/project/instance"
Expand Down Expand Up @@ -90,6 +92,15 @@ const forms = (dir: string) => {
return Array.from(new Set([full, slash, root, root.toLowerCase()]))
}

const wait = async (fn: () => boolean, ms = 5000) => {
const end = Date.now() + ms
while (Date.now() < end) {
if (fn()) return
await sleep(25)
}
throw new Error("timeout waiting for condition")
}

const withShell = (item: { label: string; shell: string }, fn: () => Promise<void>) => async () => {
const prev = process.env.SHELL
process.env.SHELL = item.shell
Expand Down Expand Up @@ -1067,6 +1078,51 @@ describe("tool.bash abort", () => {
})
}, 15_000)

test("terminates child processes that ignore TERM on abort", async () => {
if (process.platform === "win32") return

await using dir = await tmpdir()

await Instance.provide({
directory: dir.path,
fn: async () => {
const bash = await initBash()
const controller = new AbortController()
const pidFile = path.join(dir.path, "bash-child.pid")
const res = await Effect.runPromise(
bash.execute(
{
command: `trap '' HUP TERM; sleep 30 & echo $! > ${JSON.stringify(pidFile)}; echo before; wait`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
description: "Abort child tree",
},
{
...ctx,
abort: controller.signal,
metadata: (input) =>
Effect.sync(() => {
const output = (input.metadata as { output?: string })?.output
if (output?.includes("before") && !controller.signal.aborted) controller.abort()
}),
},
),
)

expect(res.output).toContain("before")
expect(res.output).toContain("User aborted the command")
await wait(() => existsSync(pidFile))
const pid = Number((await Bun.file(pidFile).text()).trim())
await wait(() => {
try {
process.kill(pid, 0)
return false
} catch {
return true
}
})
},
})
}, 15_000)

test("terminates command on timeout", async () => {
await Instance.provide({
directory: projectRoot,
Expand Down
Loading