Skip to content

Commit 52a10f5

Browse files
authored
fix(tui): keep long-pending requests past Bun's fetch deadline (#55149)
Give the TUI client timeout: false, share the no-timeout fetch helper across run, mini and the TUI via @opencode/util/no-timeout-fetch, and surface existing-session shell failures with a toast and composer restore. Closes #54974 Co-authored-by: Finn763 <[email protected]>
1 parent b56e253 commit 52a10f5

7 files changed

Lines changed: 128 additions & 7 deletions

File tree

‎packages/cli/src/mini.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Service, type Endpoint } from "@opencode/client/effect/service"
22
import { ClientError, OpenCode, type OpenCodeClient } from "@opencode/client/promise"
33
import type { MiniFrontendInput } from "@opencode/tui/mini"
4+
import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch"
45
import { setTimeout } from "node:timers/promises"
56
import { readStdin } from "./util/io"
67
import { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from "./mini-host"
@@ -141,8 +142,7 @@ export function createMiniConnection(input: MiniCommandInput["server"]) {
141142
baseUrl: endpoint.url,
142143
headers: Service.headers(endpoint),
143144
// Session waits can remain idle until background work finishes.
144-
fetch: ((request: RequestInfo | URL, init?: RequestInit) =>
145-
fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,
145+
fetch: noTimeoutFetch,
146146
})
147147
const reconnect = input.reconnect
148148
return {

‎packages/cli/src/run/run.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Service, type Endpoint } from "@opencode/client/effect/service"
22
import { OpenCode, type SessionMessageAssistantTool } from "@opencode/client/promise"
33
import { FSUtil } from "@opencode/util/fs-util"
4+
import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch"
45
import { open } from "node:fs/promises"
56
import path from "node:path"
67
import { readStdin } from "../util/io"
@@ -85,8 +86,7 @@ async function execute(input: RunCommandInput, prepared: Prepared, endpoint: End
8586
baseUrl: endpoint.url,
8687
headers: Service.headers(endpoint),
8788
// Bun's default five-minute deadline terminates the event stream used by long-running sessions.
88-
fetch: ((request: RequestInfo | URL, init?: RequestInit) =>
89-
fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch,
89+
fetch: noTimeoutFetch,
9090
})
9191
const explicit = parseRunModel(input.model)
9292
const target = await resolveSessionTarget({

‎packages/tui/src/app.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Effect, Latch } from "effect"
66
import { Service, type Endpoint } from "@opencode/client/effect/service"
77
import { OpenCode, type SessionInfo } from "@opencode/client"
88
import { Global } from "@opencode/util/global"
9+
import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch"
910
import { ClipboardProvider, useClipboard } from "./context/clipboard"
1011
import { LogProvider, type LogSink } from "./context/log"
1112
import { ExitProvider, useExit } from "./context/exit"
@@ -211,7 +212,11 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
211212
const config = Config.resolve(yield* Effect.tryPromise(() => input.config.get()), {
212213
terminalSuspend: process.platform !== "win32",
213214
})
214-
const options = { baseUrl: input.server.endpoint.url, headers: Service.headers(input.server.endpoint) }
215+
const options = {
216+
baseUrl: input.server.endpoint.url,
217+
headers: Service.headers(input.server.endpoint),
218+
fetch: noTimeoutFetch,
219+
}
215220
const api = OpenCode.make(options)
216221
const location = yield* Effect.tryPromise(() => api.file.list({ location: { directory: process.cwd() } })).pipe(
217222
Effect.map((response) => response.location),
@@ -225,7 +230,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
225230
? {
226231
reconnect: async (signal: AbortSignal) => {
227232
const endpoint = await managed.reconnect(signal)
228-
const next = { baseUrl: endpoint.url, headers: Service.headers(endpoint) }
233+
const next = { baseUrl: endpoint.url, headers: Service.headers(endpoint), fetch: noTimeoutFetch }
229234
return { api: OpenCode.make(next), url: endpoint.url }
230235
},
231236
restart: managed.restart,

‎packages/tui/src/component/prompt/index.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1311,7 +1311,9 @@ export function Prompt(props: PromptProps) {
13111311
if (currentMode === "shell") {
13121312
move.startSubmit()
13131313
const send = () => client.api.session.shell({ sessionID: target, command: inputText })
1314-
void (newSession ? newSession.gate.then(send).catch(newSession.recover) : send())
1314+
void (newSession ? newSession.gate.then(send) : send()).catch((error) =>
1315+
newSession ? newSession.recover(error) : fail("Failed to run shell command", error),
1316+
)
13151317
setStore("mode", "normal")
13161318
} else if (slashHead && isCommand) {
13171319
const send = async () => {
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { expect, test } from "bun:test"
2+
import { createTestRenderer } from "@opentui/core/testing"
3+
import { Effect, FileSystem } from "effect"
4+
import { Global } from "@opencode/util/global"
5+
import { createEventStream, createFetch, directory, json } from "./fixture/tui-client"
6+
import { tmpdir } from "./fixture/fixture"
7+
8+
test("a failed shell command in an existing session toasts and restores the composer", async () => {
9+
await using state = await tmpdir()
10+
const setup = await createTestRenderer({ width: 100, height: 30, kittyKeyboard: true })
11+
await setup.renderer.setupTerminal()
12+
setup.renderer.start()
13+
const ready = Promise.withResolvers<void>()
14+
const shell = Promise.withResolvers<string>()
15+
const events = createEventStream()
16+
// The draft stash is process-wide, so reruns use a fresh session for an empty composer.
17+
const sessionID = `ses_shell_failure_${crypto.randomUUID()}`
18+
const location = { directory, project: { id: "project", directory, canonical: directory } }
19+
const calls = createFetch(async (url, request) => {
20+
if (url.pathname === `/api/session/${sessionID}`)
21+
return json({
22+
data: {
23+
id: sessionID,
24+
projectID: "project",
25+
title: "Shell fixture",
26+
agent: "build",
27+
model: { providerID: "demo", id: "model" },
28+
location: { directory },
29+
cost: 0,
30+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
31+
time: { created: 0, updated: 0 },
32+
},
33+
})
34+
if (url.pathname === `/api/session/${sessionID}/message`) return json({ data: [], cursor: {} })
35+
if (url.pathname === `/api/session/${sessionID}/inbox` || url.pathname === `/api/session/${sessionID}/permission`)
36+
return json({ data: [] })
37+
if (url.pathname === "/api/agent")
38+
return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] })
39+
if (url.pathname === "/api/provider") return json({ location, data: [{ id: "demo", name: "Demo" }] })
40+
if (url.pathname === "/api/model")
41+
return json({ location, data: [{ id: "model", providerID: "demo", name: "Demo Model", variants: [] }] })
42+
if (url.pathname === `/api/session/${sessionID}/shell`) {
43+
shell.resolve((await request.json()).command)
44+
return json({ message: "Shell unavailable" }, { status: 400 })
45+
}
46+
return undefined
47+
}, events)
48+
const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
49+
const { run } = await import("../src/app")
50+
const task = Effect.runPromise(
51+
run({
52+
app: { name: "test", version: "test", channel: "test" },
53+
server: { endpoint: { url: server.url.toString() } },
54+
config: { get: async () => ({ animations: false }), update: async () => ({}) },
55+
packages: { prepare: async () => ({ directory: "" }) },
56+
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: ready.resolve }),
57+
args: { sessionID },
58+
log: () => {},
59+
}).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
60+
)
61+
try {
62+
await ready.promise
63+
await setup.waitForFrame((frame) => frame.includes("Demo Model"))
64+
await setup.mockInput.typeText("!")
65+
await setup.mockInput.typeText("echo restored")
66+
setup.mockInput.pressEnter()
67+
expect(await shell.promise).toBe("echo restored")
68+
const frame = await setup.waitForFrame((frame) => frame.includes("Shell unavailable"))
69+
expect(frame).toContain("Failed to run shell command")
70+
expect(frame).toContain("echo restored")
71+
} finally {
72+
setup.renderer.destroy()
73+
await task
74+
await server.stop()
75+
}
76+
})
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { afterAll, expect, test } from "bun:test"
2+
import { noTimeoutFetch } from "./no-timeout-fetch.js"
3+
4+
const pending = Promise.withResolvers<void>()
5+
const server = Bun.serve({
6+
port: 0,
7+
fetch: async (request) => {
8+
if (new URL(request.url).pathname === "/hang") {
9+
pending.resolve()
10+
return new Promise<Response>(() => {})
11+
}
12+
return Response.json({ method: request.method, header: request.headers.get("x-test"), body: await request.text() })
13+
},
14+
})
15+
16+
afterAll(() => server.stop(true))
17+
18+
test("preserves the request init", async () => {
19+
const response = await noTimeoutFetch(new URL("/echo", server.url), {
20+
method: "POST",
21+
headers: { "x-test": "value" },
22+
body: "payload",
23+
})
24+
expect(await response.json()).toEqual({ method: "POST", header: "value", body: "payload" })
25+
})
26+
27+
test("still honours an abort signal", async () => {
28+
const controller = new AbortController()
29+
const request = noTimeoutFetch(new URL("/hang", server.url), { signal: controller.signal })
30+
await pending.promise
31+
controller.abort()
32+
await expect(request).rejects.toMatchObject({ name: "AbortError" })
33+
})
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Bun's fetch aborts requests after its default idle deadline (about five minutes). Clients that
2+
// hold requests open for long-running work (session waits, event streams, plugin commands,
3+
// shell calls) opt out while keeping every other init option, including `signal`.
4+
export const noTimeoutFetch = ((request: RequestInfo | URL, init?: RequestInit) =>
5+
fetch(request, { ...init, timeout: false } as BunFetchRequestInit)) as typeof fetch

0 commit comments

Comments
 (0)