Skip to content

Commit df01d3c

Browse files
fix: Explicitly exit CLI to prevent hanging subprocesses (anomalyco#3083)
Co-authored-by: Aiden Cline <[email protected]>
1 parent 7e2ae18 commit df01d3c

7 files changed

Lines changed: 71 additions & 51 deletions

File tree

‎packages/opencode/src/file/watcher.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ export namespace FileWatcher {
6363
return { sub }
6464
},
6565
async (state) => {
66-
state.sub?.unsubscribe()
66+
if (!state.sub) return
67+
await state.sub?.unsubscribe()
6768
},
6869
)
6970

‎packages/opencode/src/index.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ import { AttachCommand } from "./cli/cmd/attach"
2222
import { AcpCommand } from "./cli/cmd/acp"
2323
import { EOL } from "os"
2424

25-
const cancel = new AbortController()
26-
2725
process.on("unhandledRejection", (e) => {
2826
Log.Default.error("rejection", {
2927
e: e instanceof Error ? e.message : e,
@@ -135,6 +133,10 @@ try {
135133
console.error(e)
136134
}
137135
process.exitCode = 1
136+
} finally {
137+
// Some subprocesses don't react properly to SIGTERM and similar signals.
138+
// Most notably, some docker-container-based MCP servers don't handle such signals unless
139+
// run using `docker run --init`.
140+
// Explicitly exit to avoid any hanging subprocesses.
141+
process.exit();
138142
}
139-
140-
cancel.abort()

‎packages/opencode/src/lsp/index.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,7 @@ export namespace LSP {
101101
}
102102
},
103103
async (state) => {
104-
for (const client of state.clients) {
105-
await client.shutdown()
106-
}
104+
await Promise.all(state.clients.map((client) => client.shutdown()))
107105
},
108106
)
109107

‎packages/opencode/src/mcp/index.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,7 @@ export namespace MCP {
145145
}
146146
},
147147
async (state) => {
148-
for (const client of Object.values(state.clients)) {
149-
client.close()
150-
}
148+
await Promise.all(Object.values(state.clients).map((client) => client.close()))
151149
},
152150
)
153151

‎packages/opencode/src/project/bootstrap.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export async function InstanceBootstrap() {
1111
await Plugin.init()
1212
Share.init()
1313
Format.init()
14-
LSP.init()
14+
await LSP.init()
1515
FileWatcher.init()
1616
File.init()
1717
}
Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,26 @@
1+
import { Log } from "@/util/log"
2+
13
export namespace State {
24
interface Entry {
35
state: any
46
dispose?: (state: any) => Promise<void>
57
}
68

7-
const entries = new Map<string, Map<any, Entry>>()
9+
const log = Log.create({ service: "state" })
10+
const recordsByKey = new Map<string, Map<any, Entry>>()
811

912
export function create<S>(root: () => string, init: () => S, dispose?: (state: Awaited<S>) => Promise<void>) {
1013
return () => {
1114
const key = root()
12-
let collection = entries.get(key)
13-
if (!collection) {
14-
collection = new Map<string, Entry>()
15-
entries.set(key, collection)
15+
let entries = recordsByKey.get(key)
16+
if (!entries) {
17+
entries = new Map<string, Entry>()
18+
recordsByKey.set(key, entries)
1619
}
17-
const exists = collection.get(init)
20+
const exists = entries.get(init)
1821
if (exists) return exists.state as S
1922
const state = init()
20-
collection.set(init, {
23+
entries.set(init, {
2124
state,
2225
dispose,
2326
})
@@ -26,9 +29,38 @@ export namespace State {
2629
}
2730

2831
export async function dispose(key: string) {
29-
for (const [_, entry] of entries.get(key)?.entries() ?? []) {
32+
const entries = recordsByKey.get(key)
33+
if (!entries) return
34+
35+
log.info("waiting for state disposal to complete", { key })
36+
37+
let disposalFinished = false
38+
39+
setTimeout(() => {
40+
if (!disposalFinished) {
41+
log.warn(
42+
"state disposal is taking an unusually long time - if it does not complete in a reasonable time, please report this as a bug",
43+
{ key },
44+
)
45+
}
46+
}, 10000).unref()
47+
48+
const tasks: Promise<void>[] = []
49+
for (const entry of entries.values()) {
3050
if (!entry.dispose) continue
31-
await entry.dispose(await entry.state)
51+
52+
const task = Promise.resolve(entry.state)
53+
.then((state) => entry.dispose!(state))
54+
.catch((error) => {
55+
log.error("Error while disposing state:", { error, key })
56+
})
57+
58+
tasks.push(task)
3259
}
60+
61+
await Promise.all(tasks)
62+
63+
disposalFinished = true
64+
log.info("state disposal completed", { key })
3365
}
3466
}

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,22 @@ export namespace SessionPrompt {
7474
callback: (input: MessageV2.WithParts) => void
7575
}[]
7676
>()
77+
const pending = new Set<Promise<void>>()
78+
79+
const track = (promise: Promise<void>) => {
80+
pending.add(promise)
81+
promise.finally(() => pending.delete(promise))
82+
}
7783

7884
return {
7985
queued,
86+
pending,
87+
track,
8088
}
8189
},
8290
async (current) => {
8391
current.queued.clear()
92+
await Promise.allSettled([...current.pending])
8493
},
8594
)
8695

@@ -191,28 +200,6 @@ export namespace SessionPrompt {
191200
processor,
192201
})
193202

194-
// const permUnsub = (() => {
195-
// const handled = new Set<string>()
196-
// const options = [
197-
// { optionId: "allow_once", kind: "allow_once", name: "Allow once" },
198-
// { optionId: "allow_always", kind: "allow_always", name: "Always allow" },
199-
// { optionId: "reject_once", kind: "reject_once", name: "Reject" },
200-
// ]
201-
// return Bus.subscribe(Permission.Event.Updated, async (event) => {
202-
// const info = event.properties
203-
// if (info.sessionID !== input.sessionID) return
204-
// if (handled.has(info.id)) return
205-
// handled.add(info.id)
206-
// const toolCallId = info.callID ?? info.id
207-
// const metadata = info.metadata ?? {}
208-
// // TODO: emit permission event to bus for ACP to handle
209-
// Permission.respond({ sessionID: info.sessionID, permissionID: info.id, response: "reject" })
210-
// })
211-
// })()
212-
// await using _permSub = defer(() => {
213-
// permUnsub?.()
214-
// })
215-
216203
const params = await Plugin.trigger(
217204
"chat.params",
218205
{
@@ -247,13 +234,15 @@ export namespace SessionPrompt {
247234
step++
248235
await processor.next(msgs.findLast((m) => m.info.role === "user")?.info.id!)
249236
if (step === 1) {
250-
ensureTitle({
251-
session,
252-
history: msgs,
253-
message: userMsg,
254-
providerID: model.providerID,
255-
modelID: model.info.id,
256-
})
237+
state().track(
238+
ensureTitle({
239+
session,
240+
history: msgs,
241+
message: userMsg,
242+
providerID: model.providerID,
243+
modelID: model.info.id,
244+
}),
245+
)
257246
SessionSummary.summarize({
258247
sessionID: input.sessionID,
259248
messageID: userMsg.info.id,
@@ -1730,7 +1719,7 @@ export namespace SessionPrompt {
17301719
thinkingBudget: 0,
17311720
}
17321721
}
1733-
generateText({
1722+
await generateText({
17341723
maxOutputTokens: small.info.reasoning ? 1500 : 20,
17351724
providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, options),
17361725
messages: [

0 commit comments

Comments
 (0)