Skip to content

Commit 3188e9f

Browse files
committed
fix(session): prevent orphaned task slots blocking allocation (#33)
- Store release_slot callback in TaskMetadata for lifecycle tracking - Release slot in trackBackgroundTask finally block (handles timeout/crash/abort) - Fix double-release race in task.ts with slotReleased guard - Release slot before metadata deletion in cancelBackgroundTask - Simplify cleanupAllTaskSlots to prevent race with finally blocks - Add comprehensive AGENTS.md aligned with project standards (#34) Closes #33 Closes #34
1 parent c2a9a4a commit 3188e9f

9 files changed

Lines changed: 997 additions & 333 deletions

File tree

‎AGENTS.md‎

Lines changed: 550 additions & 4 deletions
Large diffs are not rendered by default.

‎packages/opencode/src/agent/agent.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,15 @@ export namespace Agent {
320320
}),
321321
onError: () => {},
322322
})
323-
for await (const part of result.fullStream) {
324-
if (part.type === "error") throw part.error
323+
try {
324+
for await (const part of result.fullStream) {
325+
if (part.type === "error") throw part.error
326+
}
327+
} catch (e: any) {
328+
if (e?.name === "AbortError" || (e instanceof DOMException && e.name === "AbortError")) {
329+
throw e
330+
}
331+
throw e
325332
}
326333
return result.object
327334
}

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

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export interface TaskMetadata {
3232
description: string
3333
session_id: string
3434
start_time: number
35+
release_slot?: () => void
3536
}
3637

3738
export interface BackgroundTaskResult {
@@ -78,7 +79,7 @@ function sanitizeError(error: string): string {
7879

7980
const MAX_ERROR_LENGTH = 2000
8081
if (sanitized.length > MAX_ERROR_LENGTH) {
81-
const prefix = sanitized.slice(0, Math.max(0, MAX_ERROR_LENGTH - 50))
82+
const prefix = sanitized.slice(0, Math.max(0, MAX_ERROR_LENGTH - ERROR_TRUNCATION_SUFFIX_LENGTH))
8283
const suffix = "...truncated"
8384
sanitized = prefix + suffix
8485
}
@@ -100,20 +101,26 @@ const deliveredTaskResults = new Set<string>()
100101
const DEFAULT_TASK_TIMEOUT = 5 * 60 * 1000
101102
const closingSessions = new Set<string>()
102103

104+
// Constants for metadata and result truncation
105+
const MAX_AGENT_DESCRIPTION_LENGTH = 200
106+
const MAX_TASK_RESULT_LENGTH = 5000
107+
const SECONDS_TO_MS_MULTIPLIER = 1000
108+
const ERROR_TRUNCATION_SUFFIX_LENGTH = 50
109+
103110
export function getSessionTaskCount(sessionID: string): number {
104-
const reserved = reservedTaskSlots.get(sessionID)?.size ?? 0
105-
let tracked = 0
106-
for (const metadata of pendingTaskMetadata.values()) {
107-
if (metadata.session_id === sessionID) tracked++
108-
}
109-
return reserved + tracked
111+
return reservedTaskSlots.get(sessionID)?.size ?? 0
110112
}
111113

112114
export function reserveTaskSlot(sessionID: string): () => void {
113115
const slotId = `reserved_${Date.now()}_${crypto.randomUUID()}`
114-
const slots = reservedTaskSlots.get(sessionID) ?? new Set<string>()
116+
117+
let slots = reservedTaskSlots.get(sessionID)
118+
if (!slots) {
119+
slots = new Set<string>()
120+
reservedTaskSlots.set(sessionID, slots)
121+
}
122+
115123
slots.add(slotId)
116-
reservedTaskSlots.set(sessionID, slots)
117124

118125
const release = () => {
119126
const currentSlots = reservedTaskSlots.get(sessionID)
@@ -278,6 +285,14 @@ export namespace Session {
278285
} finally {
279286
pendingBackgroundTasks.delete(id)
280287
pendingTaskMetadata.delete(id)
288+
289+
if (metadata?.release_slot) {
290+
try {
291+
metadata.release_slot()
292+
} catch (e) {
293+
log.warn("failed to release task slot", { error: e instanceof Error ? e.message : String(e) })
294+
}
295+
}
281296
}
282297
}
283298

@@ -342,17 +357,21 @@ export namespace Session {
342357
const lines: string[] = ["[System: Background tasks completed]", ""]
343358

344359
for (const task of tasks) {
345-
const agent = (task.metadata?.agent_type ?? "unknown-agent").replace(/[<>\[\]{}]/g, "").slice(0, 200)
346-
const description = (task.metadata?.description ?? "No description").replace(/[<>\[\]{}]/g, "").slice(0, 200)
360+
const agent = (task.metadata?.agent_type ?? "unknown-agent")
361+
.replace(/[<>\[\]{}]/g, "")
362+
.slice(0, MAX_AGENT_DESCRIPTION_LENGTH)
363+
const description = (task.metadata?.description ?? "No description")
364+
.replace(/[<>\[\]{}]/g, "")
365+
.slice(0, MAX_AGENT_DESCRIPTION_LENGTH)
347366

348367
lines.push(`Task ${task.id} (@${agent})`)
349368

350369
if (task.status === "completed") {
351-
const duration = Math.round((task.time.completed - task.time.started) / 1000)
370+
const duration = Math.round((task.time.completed - task.time.started) / SECONDS_TO_MS_MULTIPLIER)
352371
lines.push(` Status: Completed (${duration}s)`)
353372

354373
if (task.result) {
355-
const cleanedResult = task.result.replace(/[<>\[\]{}]/g, "").slice(0, 5000)
374+
const cleanedResult = task.result.replace(/[<>\[\]{}]/g, "").slice(0, MAX_TASK_RESULT_LENGTH)
356375
lines.push(` Result: ${cleanedResult}`)
357376
}
358377
}
@@ -484,6 +503,15 @@ export namespace Session {
484503
const metadata = pendingTaskMetadata.get(id)
485504
const startTime = metadata?.start_time ?? Date.now()
486505

506+
// Release slot BEFORE deleting metadata to prevent permanent slot leak
507+
if (metadata?.release_slot) {
508+
try {
509+
metadata.release_slot()
510+
} catch (e) {
511+
log.warn("failed to release slot during cancellation", { error: e instanceof Error ? e.message : String(e) })
512+
}
513+
}
514+
487515
cancelledTasks.add(id)
488516
pendingBackgroundTasks.delete(id)
489517
pendingTaskMetadata.delete(id)
@@ -840,14 +868,6 @@ export namespace Session {
840868
const pendingEntries = Array.from(pendingTaskMetadata.entries())
841869
const cancelNeeded = pendingEntries.some(([_, metadata]) => metadata.session_id === sessionID)
842870

843-
for (const [id, metadata] of pendingEntries) {
844-
if (metadata.session_id === sessionID) {
845-
cancelledTasks.add(id)
846-
pendingBackgroundTasks.delete(id)
847-
pendingTaskMetadata.delete(id)
848-
}
849-
}
850-
851871
if (cancelNeeded) {
852872
SessionPrompt.cancel(sessionID)
853873
}
@@ -862,6 +882,13 @@ export namespace Session {
862882
}
863883
}
864884

885+
export function cleanupAllTaskSlots(): void {
886+
for (const [sessionID] of reservedTaskSlots.entries()) {
887+
reservedTaskSlots.delete(sessionID)
888+
autoWakeupSubscribers.delete(sessionID)
889+
}
890+
}
891+
865892
export const remove = fn(Identifier.schema("session"), async (sessionID) => {
866893
closingSessions.add(sessionID)
867894
disableAutoWakeup(sessionID)

0 commit comments

Comments
 (0)