Skip to content

Commit d1d211e

Browse files
fix(tui,sdk): audit-v7 wave B — desync recovery, resurrection guard, bounds
- tui/context/sync.tsx: tombstone deleted sessions so an in-flight sync cannot resurrect them (opus P1-03/D-P2-11); clear pendingDiffs/syncing/hydrating on bootstrap (opus P3-14); sweep orphan part mirrors by session id (opus P3-15); handle server.desync by clearing synced markers and refetching (D-P1-02) - tui/context/data.tsx: refetch mirrored sessions on server.desync (D-P1-02); cap message.refresh() to the same limit as the event path (opus P3-23) - tui/context/sdk.tsx: survive a throw before onSseError, reset the backoff after a healthy run, and parse the status from the error/response (D-P2-12/D-P3-05) - tui/util/collapse-tool-output.ts: bound by code points and honour maxChars (opus P3-16/D-P2-08) - tui/routes/session/index.tsx: drop side effects for a superseded session id (opus P3-24) - sdk/js: bump version for the close()/stop() async API change and await/void the start timeout stop paths (D-P2-02/D-P3-09); drop the stop() exit listener (opus P3-01)
1 parent 9e9b666 commit d1d211e

10 files changed

Lines changed: 159 additions & 43 deletions

File tree

‎packages/sdk/js/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"$schema": "https://json.schemastore.org/package.json",
33
"name": "@opencode-ai/sdk",
4-
"version": "1.18.31",
4+
"version": "1.19.0",
55
"type": "module",
66
"license": "MIT",
77
"scripts": {

‎packages/sdk/js/src/process.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,23 @@ export async function stop(proc: ChildProcess) {
1515
return
1616
}
1717

18-
const exited = new Promise<void>((resolve) => proc.once("exit", () => resolve()))
19-
proc.kill("SIGTERM")
20-
const escalate = setTimeout(() => {
18+
let finished = false
19+
let escalate: ReturnType<typeof setTimeout> | undefined
20+
let resolveExit: (() => void) | undefined
21+
const onExit = () => {
22+
finished = true
23+
if (escalate) clearTimeout(escalate)
24+
resolveExit?.()
25+
}
26+
const exited = new Promise<void>((resolve) => {
27+
resolveExit = resolve
28+
proc.once("exit", onExit)
29+
})
30+
try {
31+
proc.kill("SIGTERM")
32+
} catch {}
33+
escalate = setTimeout(() => {
34+
if (finished || proc.exitCode !== null || proc.signalCode !== null) return
2135
try {
2236
proc.kill("SIGKILL")
2337
} catch {}
@@ -29,8 +43,11 @@ export async function stop(proc: ChildProcess) {
2943
finalWait = setTimeout(resolve, STOP_FINAL_WAIT_MS)
3044
}),
3145
])
32-
clearTimeout(escalate)
46+
if (escalate) clearTimeout(escalate)
3347
if (finalWait) clearTimeout(finalWait)
48+
// The 5s final wait wins over a hung child, whose `exit` never fires; drop the listener
49+
// so repeated stop() calls cannot accumulate them or re-arm a SIGKILL per call.
50+
proc.removeListener("exit", onExit)
3451
}
3552

3653
export function bindAbort(proc: ChildProcess, signal?: AbortSignal, onAbort?: () => void) {

‎packages/sdk/js/src/server.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export async function createOpencodeServer(options?: ServerOptions) {
4343
const url = await new Promise<string>((resolve, reject) => {
4444
const id = setTimeout(() => {
4545
clear()
46-
stop(proc)
46+
void stop(proc)
4747
reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`))
4848
}, options.timeout)
4949
let output = ""
@@ -57,7 +57,7 @@ export async function createOpencodeServer(options?: ServerOptions) {
5757
const match = line.match(/on\s+(https?:\/\/[^\s]+)/)
5858
if (!match) {
5959
clear()
60-
stop(proc)
60+
void stop(proc)
6161
clearTimeout(id)
6262
reject(new Error(`Failed to parse server url from output: ${line}`))
6363
return

‎packages/sdk/js/src/v2/server.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export async function createOpencodeServer(options?: ServerOptions) {
4343
const url = await new Promise<string>((resolve, reject) => {
4444
const id = setTimeout(() => {
4545
clear()
46-
stop(proc)
46+
void stop(proc)
4747
reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`))
4848
}, options.timeout)
4949
let output = ""
@@ -57,7 +57,7 @@ export async function createOpencodeServer(options?: ServerOptions) {
5757
const match = line.match(/on\s+(https?:\/\/[^\s]+)/)
5858
if (!match) {
5959
clear()
60-
stop(proc)
60+
void stop(proc)
6161
clearTimeout(id)
6262
reject(new Error(`Failed to parse server url from output: ${line}`))
6363
return

‎packages/tui/src/context/data.tsx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,18 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
142142
}
143143

144144
function handleEvent(event: Event, metadata: EventMetadata) {
145+
// `server.desync` is a raw SSE marker, not part of the typed Event union.
146+
if (String(event.type) === "server.desync") {
147+
// The server dropped events for this connection; refetch every mirrored session
148+
// so the store cannot stay silently behind the authoritative state.
149+
for (const sessionID of Object.keys(store.session.info)) {
150+
void result.session.refresh(sessionID)
151+
void result.session.message.refresh(sessionID)
152+
void result.session.permission.refresh(sessionID)
153+
void result.session.question.refresh(sessionID)
154+
}
155+
return
156+
}
145157
switch (event.type) {
146158
case "catalog.updated":
147159
void Promise.all([
@@ -495,7 +507,9 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
495507
},
496508
async refresh(sessionID: string) {
497509
const result = await sdk.client.v2.session.messages({ sessionID }, { throwOnError: true })
498-
setStore("session", "message", sessionID, result.data.data)
510+
// Server order is newest-first, so cap the page like the event path; an
511+
// uncapped refresh would reintroduce the unbounded mirror the cap guards.
512+
setStore("session", "message", sessionID, result.data.data.slice(0, MESSAGE_LIMIT))
499513
},
500514
},
501515
permission: {

‎packages/tui/src/context/sdk.tsx‎

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,18 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
7979
flush()
8080
}
8181

82+
const parseSseStatus = (error: unknown): string | undefined => {
83+
if (error instanceof Error) {
84+
const match = /SSE failed:\s*(\d{3})/.exec(error.message)
85+
if (match?.[1]) return match[1]
86+
}
87+
if (typeof error === "object" && error !== null && "status" in error) {
88+
const status = (error as { status?: unknown }).status
89+
if (typeof status === "number") return String(status)
90+
}
91+
return undefined
92+
}
93+
8294
function startSSE() {
8395
sse?.abort()
8496
const ctrl = new AbortController()
@@ -89,39 +101,45 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
89101
if (abort.signal.aborted || ctrl.signal.aborted) break
90102

91103
let sseError: unknown
92-
const events = await sdk.global.event({
93-
signal: ctrl.signal,
94-
sseMaxRetryAttempts: 0,
95-
onSseError: (error) => {
96-
sseError = error
97-
},
98-
})
99-
100-
if (Flag.OPENCODE_EXPERIMENTAL_WORKSPACES) {
101-
// Start syncing workspaces, it's important to do this after
102-
// we've started listening to events
103-
await sdk.sync.start().catch(() => {})
104-
}
105-
106-
for await (const event of events.stream) {
107-
if (ctrl.signal.aborted) break
108-
handleEvent(event)
104+
let received = false
105+
try {
106+
const events = await sdk.global.event({
107+
signal: ctrl.signal,
108+
sseMaxRetryAttempts: 0,
109+
onSseError: (error) => {
110+
sseError = error
111+
},
112+
})
113+
114+
if (Flag.OPENCODE_EXPERIMENTAL_WORKSPACES) {
115+
// Start syncing workspaces, it's important to do this after
116+
// we've started listening to events
117+
await sdk.sync.start().catch(() => {})
118+
}
119+
120+
for await (const event of events.stream) {
121+
if (ctrl.signal.aborted) break
122+
received = true
123+
handleEvent(event)
124+
}
125+
} catch (error) {
126+
// A rejection before `onSseError` fires must still reach the retry path
127+
// instead of escaping to the outer catch and deafening the TUI.
128+
sseError = error
109129
}
110130

111131
if (timer) clearTimeout(timer)
112132
if (queue.length > 0) flush()
113-
attempt += 1
114133
if (abort.signal.aborted || ctrl.signal.aborted) break
115134

116-
// Auth/not-found rejections never recover on retry; stop instead of
117-
// reconnecting silently forever.
118-
const status = /SSE failed:\s*(\d{3})/.exec(sseError instanceof Error ? sseError.message : "")?.[1]
119-
if (status === "400" || status === "401" || status === "403" || status === "404") {
120-
console.error(`[tui] global event stream rejected with HTTP ${status}; giving up`)
121-
break
122-
}
135+
// A run that produced events resets the backoff; only consecutive failures
136+
// escalate it, so hours of health cannot pin the delay at the cap.
137+
attempt = received ? 1 : attempt + 1
138+
const status = parseSseStatus(sseError)
139+
if (status) console.error(`[tui] global event stream failed with HTTP ${status}; retrying`)
123140

124-
// Exponential backoff
141+
// Retry every status (including auth) with backoff: a transient token refresh
142+
// must not permanently deafen the TUI, and a fixed credential recovers it.
125143
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), maxRetryDelay)
126144
await new Promise((resolve) => setTimeout(resolve, backoff))
127145
}

‎packages/tui/src/context/sync.tsx‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ export const {
151151
const syncingSessions = new Map<string, Promise<void>>()
152152
const hydratingSessions = new Map<string, { messages: Set<string>; parts: Set<string> }>()
153153
const pendingDiffs = new Map<string, Map<string, SnapshotFileDiff[]>>()
154+
// A deleted session must not be resurrected by an in-flight sync that resolves after
155+
// the delete; the tombstone is checked before the post-await store write.
156+
const deletedSessions = new Set<string>()
154157
const touchMessage = (sessionID: string, messageID: string) => {
155158
hydratingSessions.get(sessionID)?.messages.add(messageID)
156159
}
@@ -180,6 +183,9 @@ export const {
180183
.then((x) => (x.data ?? []).toSorted((a, b) => a.id.localeCompare(b.id)))
181184
}
182185

186+
// Assigned once `result` exists; the desync handler runs later, so the holder lets
187+
// it trigger a refetch of everything currently mirrored without a forward reference.
188+
let resyncOnDesync: (() => void) | undefined
183189
const unsubscribeSyncEvent = event.subscribe((event, { directory, workspace }) => {
184190
if (event.type === "message.diff.updated") {
185191
const messages = store.message[event.properties.sessionID]
@@ -207,6 +213,13 @@ export const {
207213
)
208214
return
209215
}
216+
// `server.desync` is a raw SSE marker, not part of the typed Event union.
217+
if (String(event.type) === "server.desync") {
218+
// The server dropped events for this connection; every incremental mirror may
219+
// be stale, so drop the "already synced" markers and refetch what is loaded.
220+
resyncOnDesync?.()
221+
return
222+
}
210223
switch (event.type) {
211224
case "server.instance.disposed":
212225
void bootstrap()
@@ -305,8 +318,13 @@ export const {
305318

306319
case "session.deleted": {
307320
const sessionID = event.properties.info.id
321+
deletedSessions.add(sessionID)
308322
pendingDiffs.delete(sessionID)
309323
fullSyncedSessions.delete(sessionID)
324+
// Drop in-flight markers so a late resolution cannot re-add the session; the
325+
// tombstone guard in sync() is the backstop.
326+
syncingSessions.delete(sessionID)
327+
hydratingSessions.delete(sessionID)
310328
const messageIDs = (store.message[sessionID] ?? []).map((message) => message.id)
311329
const result = search(store.session, sessionID, (s) => s.id)
312330
if (result.found) {
@@ -357,11 +375,18 @@ export const {
357375
"part",
358376
produce((draft) => {
359377
for (const messageID of messageIDs) delete draft[messageID]
378+
// A part can arrive before its message, so sweep by session id too instead
379+
// of leaking an orphan mirror that no known message id covers.
380+
for (const messageID of Object.keys(draft)) {
381+
if (draft[messageID]?.some((part) => part.sessionID === sessionID)) delete draft[messageID]
382+
}
360383
}),
361384
)
362385
break
363386
}
364387
case "session.updated": {
388+
// A genuinely re-created session clears the delete tombstone.
389+
deletedSessions.delete(event.properties.info.id)
365390
const result = search(store.session, event.properties.info.id, (s) => s.id)
366391
if (result.found) {
367392
setStore("session", result.index, reconcile(event.properties.info))
@@ -533,6 +558,10 @@ export const {
533558
async function bootstrap(input: { fatal?: boolean } = {}) {
534559
const fatal = input.fatal ?? true
535560
fullSyncedSessions.clear()
561+
// Buffered/in-flight state from before a restart must not merge into the fresh fetch.
562+
pendingDiffs.clear()
563+
syncingSessions.clear()
564+
hydratingSessions.clear()
536565
const workspace = project.workspace.current()
537566
const projectPromise = project.sync()
538567
const sessionListPromise = projectPromise.then(() => listSessions())
@@ -675,7 +704,7 @@ export const {
675704
return last.time.completed ? "idle" : "working"
676705
},
677706
async sync(sessionID: string) {
678-
if (fullSyncedSessions.has(sessionID)) return
707+
if (fullSyncedSessions.has(sessionID) || deletedSessions.has(sessionID)) return
679708
const syncing = syncingSessions.get(sessionID)
680709
if (syncing) return syncing
681710
const tracker = { messages: new Set<string>(), parts: new Set<string>() }
@@ -687,6 +716,8 @@ export const {
687716
sdk.client.session.todo({ sessionID }),
688717
sdk.client.session.diff({ sessionID }),
689718
])
719+
// The session may have been deleted while these four requests were in flight.
720+
if (deletedSessions.has(sessionID)) return
690721
setStore(
691722
produce((draft) => {
692723
const match = search(draft.session, sessionID, (s) => s.id)
@@ -760,6 +791,11 @@ export const {
760791
},
761792
bootstrap,
762793
}
794+
resyncOnDesync = () => {
795+
fullSyncedSessions.clear()
796+
void bootstrap({ fatal: false })
797+
for (const sessionID of Object.keys(store.message)) void result.session.sync(sessionID)
798+
}
763799
return result
764800
},
765801
})

‎packages/tui/src/routes/session/index.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,9 @@ export function Session() {
296296
void (async () => {
297297
const previousWorkspace = untrack(() => project.workspace.current())
298298
const result = await sdk.client.session.get({ sessionID }, { throwOnError: true })
299+
// A fast A->B switch dispatches this effect for the old session; drop every side
300+
// effect once the route moved on so B never inherits A's workspace/sync state.
301+
if (route.sessionID !== sessionID) return
299302
if (!result.data) {
300303
toast.show({
301304
message: `Session not found: ${sessionID}`,

‎packages/tui/src/util/collapse-tool-output.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
export function collapseToolOutput(output: string, maxLines: number, maxChars: number) {
22
const lines = output.split("\n", maxLines + 1)
3-
if (lines.length <= maxLines && output.length <= maxChars) {
3+
// Code points, not UTF-16 units: an astral glyph must count as one character or the
4+
// bound is exceeded by surrogate pairs.
5+
if (lines.length <= maxLines && Array.from(output).length <= maxChars) {
46
return { output, overflow: false }
57
}
68

79
const preview = lines.slice(0, maxLines).join("\n")
8-
if (preview.length > maxChars) {
9-
const bounded = Array.from(preview.slice(0, maxChars * 2))
10-
if (bounded.length > maxChars) {
11-
return { output: bounded.slice(0, Math.max(0, maxChars - 1)).join("") + "…", overflow: true }
12-
}
10+
if (Array.from(preview).length > maxChars) {
11+
return { output: Array.from(preview).slice(0, Math.max(0, maxChars - 1)).join("") + "…", overflow: true }
1312
}
1413

1514
return { output: [...lines.slice(0, maxLines), "…"].join("\n"), overflow: true }
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { collapseToolOutput } from "../../src/util/collapse-tool-output"
3+
4+
describe("collapseToolOutput", () => {
5+
test("returns short output untouched", () => {
6+
expect(collapseToolOutput("abc", 10, 100)).toEqual({ output: "abc", overflow: false })
7+
})
8+
9+
test("counts astral characters as one code point", () => {
10+
const emoji = "😀".repeat(60)
11+
expect(Array.from(collapseToolOutput(emoji, 10, 100).output).length).toBeLessThanOrEqual(100)
12+
})
13+
14+
test("honours maxChars when the preview is longer", () => {
15+
const result = collapseToolOutput("abcdefghij", 1, 5)
16+
expect(result.overflow).toBe(true)
17+
expect(Array.from(result.output).length).toBeLessThanOrEqual(5)
18+
})
19+
20+
test("honours a zero maxChars bound", () => {
21+
const result = collapseToolOutput("abc", 10, 0)
22+
expect(result).toEqual({ output: "…", overflow: true })
23+
})
24+
25+
test("appends an ellipsis line when only the line bound is exceeded", () => {
26+
const result = collapseToolOutput("a\nb\nc", 2, 100)
27+
expect(result).toEqual({ output: "a\nb\n…", overflow: true })
28+
})
29+
})

0 commit comments

Comments
 (0)