Fix session creation error handling and health endpoint status codes (#177) (#179)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-04-05 09:07:34 -04:00
1 parent 2f9c57a642
commit c32feae8ef
18 files changed
+257 -59

No files matched your search

+1 -1
View File
@@ -96,7 +96,7 @@ export function createHealthRoutes(db: Database) {
response.error = startupError
}
return c.json(response)
return c.json(response, status === 'unhealthy' ? 503 : 200)
} catch (error) {
const opencodeManagerVersion = await opencodeManagerVersionPromise
return c.json({
+8 -4
View File
@@ -118,13 +118,15 @@ export async function proxyRequest(request: Request) {
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
return new Response(response.body, {
const body = await response.text()
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
@@ -159,13 +161,15 @@ export async function proxyToOpenCodeWithDirectory(
})
const responseHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
if (!skipHeaders.has(key.toLowerCase())) {
responseHeaders[key] = value
}
})
return new Response(response.body, {
const responseBody = await response.text()
return new Response(responseBody, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
+116
View File
@@ -0,0 +1,116 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: {
checkHealth: vi.fn(),
getLastStartupError: vi.fn(),
getPort: vi.fn(() => 5551),
getVersion: vi.fn(() => '1.0.0'),
getMinVersion: vi.fn(() => '1.0.137'),
isVersionSupported: vi.fn(() => true),
},
}))
vi.mock('bun:sqlite', () => ({
Database: class Database {
prepare() {
return {
get: vi.fn(),
}
}
},
}))
import { opencodeServerManager } from '../../src/services/opencode-single-server'
import { createHealthRoutes } from '../../src/routes/health'
describe('Health Routes', () => {
let healthApp: ReturnType<typeof createHealthRoutes>
let mockDb: any
beforeEach(() => {
vi.clearAllMocks()
const mockPrepareGet = vi.fn()
mockDb = {
prepare: vi.fn(() => ({
get: mockPrepareGet,
})),
} as any
healthApp = createHealthRoutes(mockDb)
})
describe('GET /', () => {
it('should return healthy status when database and opencode are healthy', async () => {
mockDb.prepare().get.mockReturnValue({ 1: 1 })
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
const req = new Request('http://localhost/')
const res = await healthApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.status).toBe('healthy')
expect(json.database).toBe('connected')
expect(json.opencode).toBe('healthy')
})
it('should return degraded status when opencode is unhealthy but no startup error', async () => {
mockDb.prepare().get.mockReturnValue({ 1: 1 })
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(false)
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
const req = new Request('http://localhost/')
const res = await healthApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.status).toBe('degraded')
expect(json.opencode).toBe('unhealthy')
})
it('should return unhealthy status with 503 when startup error exists and opencode unhealthy', async () => {
mockDb.prepare().get.mockReturnValue({ 1: 1 })
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(false)
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce('Failed to start OpenCode server')
const req = new Request('http://localhost/')
const res = await healthApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(503)
expect(json.status).toBe('unhealthy')
expect(json.error).toBe('Failed to start OpenCode server')
})
it('should return degraded status when database is disconnected but opencode healthy', async () => {
mockDb.prepare().get.mockReturnValue(null)
;(opencodeServerManager.checkHealth as ReturnType<typeof vi.fn>).mockResolvedValueOnce(true)
;(opencodeServerManager.getLastStartupError as ReturnType<typeof vi.fn>).mockReturnValueOnce(null)
const req = new Request('http://localhost/')
const res = await healthApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.status).toBe('degraded')
expect(json.database).toBe('disconnected')
})
it('should return 503 when health check throws an error', async () => {
mockDb.prepare().get.mockImplementationOnce(() => {
throw new Error('Database error')
})
const req = new Request('http://localhost/')
const res = await healthApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(503)
expect(json.status).toBe('unhealthy')
expect(json.error).toBe('Database error')
})
})
})
+2 -1
View File
@@ -71,7 +71,7 @@ export function useCommandHandler({
break
case 'new':
case 'clear':
case 'clear': {
try {
const newSession = await createSession.mutateAsync({
agent: undefined
@@ -91,6 +91,7 @@ export function useCommandHandler({
showToast.error(`Failed to create new session: ${error instanceof Error ? error.message : 'Unknown error'}`)
}
break
}
case 'details':
if (onToggleDetails) {
+18 -8
View File
@@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useMemo, useRef, useEffect, useCallback, useState } from "react";
import { OpenCodeClient } from "../api/opencode";
import { API_BASE_URL } from "../config";
import { fetchWrapper } from "../api/fetchWrapper";
import { fetchWrapper, FetchError } from "../api/fetchWrapper";
import { cancelLoop } from "../api/memory";
import type {
Message,
@@ -99,7 +99,11 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str
});
};
export const useCreateSession = (opcodeUrl: string | null | undefined, directory?: string) => {
export const useCreateSession = (
opcodeUrl: string | null | undefined,
directory?: string,
onSuccess?: (session: { id: string }) => void,
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
@@ -112,8 +116,16 @@ export const useCreateSession = (opcodeUrl: string | null | undefined, directory
if (!client) throw new Error("No client available");
return client.createSession(data);
},
onSuccess: () => {
onSuccess: (session) => {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, directory] });
onSuccess?.(session);
},
onError: (error) => {
const parsed = parseNetworkError(error);
showToast.error(parsed.title, {
description: parsed.message,
duration: 5000,
});
},
});
};
@@ -355,11 +367,9 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
const { sessionID } = variables;
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
const axiosError = error as { code?: string; response?: unknown };
const isNetworkError = axiosError.code === 'ECONNABORTED' ||
axiosError.code === 'ERR_NETWORK' ||
!axiosError.response;
const isNetworkError = error instanceof TypeError ||
(error instanceof FetchError && error.code === 'TIMEOUT');
if (isNetworkError) {
return;
}
+4 -3
View File
@@ -65,16 +65,17 @@ export function RepoDetail() {
useSSE(opcodeUrl, repoDirectory);
const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory);
const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory, (session) => {
navigate(`/repos/${repoId}/sessions/${session.id}`);
});
const handleCreateSession = async (options?: {
agentSlug?: string;
promptSlug?: string;
}) => {
const session = await createSessionMutation.mutateAsync({
await createSessionMutation.mutateAsync({
agent: options?.agentSlug,
});
navigate(`/repos/${repoId}/sessions/${session.id}`);
};
const handleSelectSession = (sessionId: string) => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.27",
"version": "0.0.28",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
+14
View File
@@ -100,6 +100,11 @@ KV entries are scoped to the current project and expire after 7 days. Use this f
Present plans with:
- **Objective**: What we're building and why
- **Phases**: Ordered implementation steps, each with specific files to create/modify, what changes to make, and acceptance criteria
- **Verification**: Concrete, runnable commands that prove the plan is complete. Every plan MUST include at least one verification step. Examples:
- Test commands: \`pnpm test\`, \`vitest run src/path/to/test.ts\`
- Type checking: \`pnpm tsc --noEmit\`, \`pnpm lint\`
- Runtime checks: curl commands, specific assertions about output
Plans without verification steps are incomplete. If no existing tests cover the changes, the plan MUST include a phase to write tests.
- **Decisions**: Architectural choices made during planning with rationale
- **Conventions**: Existing project conventions that must be followed
- **Key Context**: Relevant code patterns, file locations, integration points, and dependencies discovered during research
@@ -121,5 +126,14 @@ All execution modes require a **title** — a short descriptive label for the se
| Loop | memory-loop | false | Full self-contained plan |
"Full self-contained" means the plan must include every file path, implementation detail, code pattern, phase dependency, verification step, and gotcha. The receiving agent starts with zero context. Do NOT summarize, abbreviate, or include <promise> tags.
**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully AND all verification steps pass, you MUST output the following tag exactly: <promise>DONE</promise>
Before outputting this tag, you MUST:
1. Run every verification command listed in the plan (tests, type checks, linting, build)
2. Confirm all verifications pass — if any fail, fix the issues first
3. Do NOT output the completion signal with known failing tests or type errors
The loop will continue until this signal is detected.
`,
}
+4
View File
@@ -57,6 +57,10 @@ Diffs alone are not enough. After getting the diff:
**Behavior Changes** — If a behavioral change is introduced, raise it (especially if possibly unintentional).
**Plan Compliance** — When reviewing loop iterations, check whether the implementation satisfies the plan's stated acceptance criteria and verification steps.
- If the task context includes verification commands (test, lint, type check), check whether they were run and passed
- If acceptance criteria from the plan are not met, report as a **warning** with the specific unmet criterion
## Before You Flag Something
Be certain. If you're going to call something a bug, you need to be confident it actually is one.
+9
View File
@@ -77,6 +77,15 @@ When you receive a message indicating that an architect agent has created a plan
You are the execution agent. Your job is to write code, not describe code.
**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully AND all verification steps pass, you MUST output the following tag exactly: <promise>DONE</promise>
Before outputting this tag, you MUST:
1. Run every verification command listed in the plan (tests, type checks, linting, build)
2. Confirm all verifications pass — if any fail, fix the issues first
3. Do NOT output the completion signal with known failing tests or type errors
The loop will continue until this signal is detected.
## Project KV Store
You have access to a project-scoped key-value store with 7-day TTL for ephemeral state:
+34 -12
View File
@@ -29,26 +29,46 @@ export interface StatusArgs {
export async function run(argv: StatusArgs): Promise<void> {
const db = openDatabase(argv.dbPath)
function createStatusClient(serverUrl: string, directory: string) {
const url = new URL(serverUrl)
const password = url.password || process.env['OPENCODE_SERVER_PASSWORD']
const cleanUrl = new URL(url.toString())
cleanUrl.username = ''
cleanUrl.password = ''
const clientConfig: Parameters<typeof createOpencodeClient>[0] = { baseUrl: cleanUrl.toString(), directory }
if (password) {
clientConfig.headers = {
Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`,
}
}
return createOpencodeClient(clientConfig)
}
async function tryFetchSessionOutput(serverUrl: string, sessionId: string, directory: string) {
try {
const url = new URL(serverUrl)
const password = url.password || process.env['OPENCODE_SERVER_PASSWORD']
const cleanUrl = new URL(url.toString())
cleanUrl.username = ''
cleanUrl.password = ''
const clientConfig: Parameters<typeof createOpencodeClient>[0] = { baseUrl: cleanUrl.toString(), directory }
if (password) {
clientConfig.headers = {
Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`,
}
}
const client = createOpencodeClient(clientConfig)
const client = createStatusClient(serverUrl, directory)
return await fetchSessionOutput(client, sessionId, directory)
} catch {
return null
}
}
async function tryFetchSessionStatus(serverUrl: string, sessionId: string, directory: string): Promise<string> {
try {
const client = createStatusClient(serverUrl, directory)
const statusResult = await client.session.status({ directory })
const statuses = (statusResult.data ?? {}) as Record<string, { type: string; attempt?: number; message?: string; next?: number }>
const status = statuses[sessionId]
if (!status) return 'unknown'
if (status.type === 'retry') {
return `retry (attempt ${status.attempt}, next in ${Math.round(((status.next ?? 0) - Date.now()) / 1000)}s)`
}
return status.type
} catch {
return 'unavailable'
}
}
try {
if (argv.listWorktrees) {
const rows = db.prepare('SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?').all('loop:%', Date.now()) as Array<{ key: string; data: string }>
@@ -201,6 +221,8 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log(` Error Count: ${state.errorCount ?? 0}`)
console.log(` Audit Count: ${state.auditCount ?? 0}`)
console.log(` Started: ${new Date(startedAt).toISOString()}`)
const sessionStatus = await tryFetchSessionStatus(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir!)
console.log(` Status: ${sessionStatus}`)
if (state.completionPromise) {
console.log(` Completion: ${state.completionPromise}`)
}
+1 -1
View File
@@ -115,7 +115,7 @@ export function createLoopEventHandler(
const sessionId = state.sessionId
try {
const statusResult = await v2Client.session.status()
const statusResult = await v2Client.session.status({ directory: state.worktreeDir })
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
const status = statuses[sessionId]?.type
+31 -15
View File
@@ -1180,8 +1180,15 @@ Do NOT output text without also making this tool call.
let statuses: Record<string, { type: string; attempt?: number; message?: string; next?: number }> = {}
try {
const statusResult = await v2.session.status()
statuses = (statusResult.data ?? {}) as typeof statuses
const uniqueDirs = [...new Set(active.map((s) => s.worktreeDir).filter(Boolean))]
const results = await Promise.allSettled(
uniqueDirs.map((dir) => v2.session.status({ directory: dir })),
)
for (const result of results) {
if (result.status === 'fulfilled' && result.value.data) {
Object.assign(statuses, result.value.data)
}
}
} catch {
}
@@ -1192,7 +1199,7 @@ Do NOT output text without also making this tool call.
const seconds = elapsed % 60
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const iterInfo = s.maxIterations && s.maxIterations > 0 ? `${s.iteration} / ${s.maxIterations}` : `${s.iteration} (unlimited)`
const sessionStatus = statuses[s.sessionId]?.type ?? 'unknown'
const sessionStatus = statuses[s.sessionId]?.type ?? 'unavailable'
const modeIndicator = !s.worktree ? ' (in-place)' : ''
const stallInfo = loopHandler.getStallInfo(s.worktreeName)
const stallCount = stallInfo?.consecutiveStalls ?? 0
@@ -1289,7 +1296,7 @@ Do NOT output text without also making this tool call.
let sessionStatus = 'unknown'
try {
const statusResult = await v2.session.status()
const statusResult = await v2.session.status({ directory: state.worktreeDir })
const statuses = statusResult.data as Record<string, { type: string; attempt?: number; message?: string; next?: number }> | undefined
const status = statuses?.[state.sessionId]
if (status) {
@@ -1334,7 +1341,27 @@ Do NOT output text without also making this tool call.
if (state.worktreeBranch) {
statusLines.push(`Branch: ${state.worktreeBranch}`)
}
let sessionOutput: LoopSessionOutput | null = null
if (state.worktreeDir) {
try {
sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger)
} catch {
// Silently ignore fetch errors to avoid cluttering output
}
}
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
statusLines.push(...formatSessionOutput(sessionOutput))
}
if (state.lastAuditResult) {
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
statusLines.push(
'',
`Completion promise: ${state.completionPromise ?? 'none'}`,
`Started: ${state.startedAt}`,
...(state.errorCount && state.errorCount > 0 ? [`Error count: ${state.errorCount} (retries before termination: ${MAX_RETRIES})`] : []),
@@ -1347,17 +1374,6 @@ Do NOT output text without also making this tool call.
`Prompt: ${promptPreview}`,
)
if (state.lastAuditResult) {
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
const sessionOutput = state.worktreeDir ? await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) : null
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
statusLines.push(...formatSessionOutput(sessionOutput))
}
return statusLines.join('\n')
},
}),
+1 -1
View File
@@ -133,7 +133,7 @@ export function createLoopService(
let systemLine = `Loop iteration ${state.iteration ?? 0}`
if (state.completionPromise) {
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY when all requirements are met)`
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY after all verification steps pass)`
} else if ((state.maxIterations ?? 0) > 0) {
systemLine += ` / ${state.maxIterations}`
} else {
+10 -9
View File
@@ -7,6 +7,16 @@ export function formatTokens(n: number): string {
export function formatSessionOutput(sessionOutput: LoopSessionOutput): string[] {
const lines: string[] = []
if (sessionOutput.messages.length > 0) {
lines.push('Recent Activity:')
for (const msg of sessionOutput.messages) {
const preview = truncate(msg.text.replace(/\n/g, ' ').trim(), 1000)
lines.push(` [assistant] ${preview}`)
}
lines.push('')
}
const costStr = `$${sessionOutput.totalCost.toFixed(4)}`
const t = sessionOutput.totalTokens
const tokensStr = `${formatTokens(t.input)} in / ${formatTokens(t.output)} out / ${formatTokens(t.reasoning)} reasoning / ${formatTokens(t.cacheRead)} cache read / ${formatTokens(t.cacheWrite)} cache write`
@@ -17,15 +27,6 @@ export function formatSessionOutput(sessionOutput: LoopSessionOutput): string[]
lines.push(` Files changed: ${fc.files} (+${fc.additions}/-${fc.deletions} lines)`)
}
if (sessionOutput.messages.length > 0) {
lines.push('')
lines.push('Recent Activity:')
for (const msg of sessionOutput.messages) {
const preview = truncate(msg.text.replace(/\n/g, ' ').trim(), 200)
lines.push(` [assistant] ${preview}`)
}
}
return lines
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.27'
export const VERSION = '0.0.28'
+1 -1
View File
@@ -167,7 +167,7 @@ describe('formatSessionOutput', () => {
const lines = formatSessionOutput(sessionOutput)
const messageLine = lines.find((line) => line.includes('[assistant]'))
expect(messageLine).toBeDefined()
expect(messageLine!.length).toBeLessThanOrEqual(220)
expect(messageLine!.length).toBeLessThanOrEqual(1020)
})
test('handles multiline messages', () => {
+1 -1
View File
@@ -183,7 +183,7 @@ describe('LoopService', () => {
}
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('[Loop iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY when all requirements are met)]')
expect(prompt).toContain('[Loop iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY after all verification steps pass)]')
})
test('buildContinuationPrompt includes max iterations when no promise', () => {