mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Add Ralph status dialog and session management improvements (#171)
This commit is contained in:
1 parent
27352ea5cf
commit
86613b1ea4
12 files changed
+1132
-65
No files matched your search
@@ -8,6 +8,7 @@ import { resolveProjectId } from '../services/project-id-resolver'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { OPENCODE_SERVER_URL } from '../services/proxy'
|
||||
import {
|
||||
CreateMemoryRequestSchema,
|
||||
UpdateMemoryRequestSchema,
|
||||
@@ -16,7 +17,9 @@ import {
|
||||
PluginConfigSchema,
|
||||
CreateKvEntryRequestSchema,
|
||||
UpdateKvEntryRequestSchema,
|
||||
RalphStateSchema,
|
||||
type PluginConfig,
|
||||
type RalphState,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
function resolveMemoryDataDir(): string {
|
||||
@@ -525,6 +528,51 @@ export function createMemoryRoutes(db: Database): Hono {
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/ralph/status', async (c) => {
|
||||
const repoIdParam = c.req.query('repoId')
|
||||
|
||||
if (!repoIdParam) {
|
||||
return c.json({ error: 'Missing repoId' }, 400)
|
||||
}
|
||||
|
||||
const repoId = parseInt(repoIdParam, 10)
|
||||
|
||||
if (isNaN(repoId)) {
|
||||
return c.json({ error: 'Invalid repoId' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const repo = getRepoById(db, repoId)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ loops: [], projectId: null })
|
||||
}
|
||||
|
||||
const projectId = await resolveProjectId(repo.fullPath)
|
||||
|
||||
if (!projectId) {
|
||||
return c.json({ loops: [], projectId: null })
|
||||
}
|
||||
|
||||
const entries = pluginMemory.listKv(projectId, 'ralph:')
|
||||
const loops = entries
|
||||
.map(e => e.data)
|
||||
.filter((data): data is Record<string, unknown> =>
|
||||
data !== null && typeof data === 'object' && 'active' in data
|
||||
)
|
||||
.map(data => {
|
||||
const result = RalphStateSchema.safeParse(data)
|
||||
return result.success ? result.data : null
|
||||
})
|
||||
.filter((loop): loop is RalphState => loop !== null)
|
||||
|
||||
return c.json({ loops, projectId })
|
||||
} catch (error) {
|
||||
logger.error('Failed to get Ralph status:', error)
|
||||
return c.json({ error: 'Failed to get Ralph status' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/ralph/cancel', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
@@ -552,9 +600,16 @@ export function createMemoryRoutes(db: Database): Hono {
|
||||
return c.json({ cancelled: false })
|
||||
}
|
||||
|
||||
const state = kvEntry.data as { active?: boolean; worktreeName?: string } | undefined
|
||||
const result = RalphStateSchema.safeParse(kvEntry.data)
|
||||
|
||||
if (!state?.active) {
|
||||
if (!result.success) {
|
||||
logger.warn('Failed to parse Ralph state for cancel:', result.error)
|
||||
return c.json({ cancelled: false })
|
||||
}
|
||||
|
||||
const state = result.data
|
||||
|
||||
if (!state.active) {
|
||||
return c.json({ cancelled: false })
|
||||
}
|
||||
|
||||
@@ -567,6 +622,14 @@ export function createMemoryRoutes(db: Database): Hono {
|
||||
|
||||
pluginMemory.setKv(projectId, `ralph:${sessionId}`, updatedState)
|
||||
|
||||
try {
|
||||
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${sessionId}/abort`)
|
||||
abortUrl.searchParams.set('directory', repo.fullPath)
|
||||
await fetch(abortUrl.toString(), { method: 'POST' })
|
||||
} catch {
|
||||
// Session may already be idle
|
||||
}
|
||||
|
||||
return c.json({ cancelled: true, worktreeName: state.worktreeName })
|
||||
} catch (error) {
|
||||
logger.error('Failed to cancel Ralph loop:', error)
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn().mockImplementation(() => ({})),
|
||||
}))
|
||||
|
||||
const mockListKv = vi.fn()
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/project-id-resolver', () => ({
|
||||
resolveProjectId: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/plugin-memory', () => ({
|
||||
PluginMemoryService: vi.fn().mockImplementation(() => ({
|
||||
listKv: mockListKv,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/test-workspace/.config/opencode.json'),
|
||||
getAgentsMdPath: vi.fn(() => '/tmp/test-workspace/AGENTS.md'),
|
||||
getDatabasePath: vi.fn(() => ':memory:'),
|
||||
getConfigPath: vi.fn(() => '/tmp/test-workspace/config'),
|
||||
ENV: {
|
||||
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
|
||||
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
|
||||
WORKSPACE: { BASE_PATH: '/tmp/test-workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
|
||||
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
|
||||
DATABASE: { PATH: ':memory:' },
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
},
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/utils', () => ({
|
||||
parseJsonc: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createMemoryRoutes } from '../../src/routes/memory'
|
||||
import { resolveProjectId } from '../../src/services/project-id-resolver'
|
||||
import { getRepoById } from '../../src/db/queries'
|
||||
|
||||
const mockResolveProjectId = resolveProjectId as ReturnType<typeof vi.fn>
|
||||
const mockGetRepoById = getRepoById as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('Memory Routes - Ralph Status', () => {
|
||||
let memoryApp: ReturnType<typeof createMemoryRoutes>
|
||||
let testDb: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockResolveProjectId.mockReset()
|
||||
mockListKv.mockReset()
|
||||
mockGetRepoById.mockReset()
|
||||
|
||||
testDb = {} as any
|
||||
memoryApp = createMemoryRoutes(testDb)
|
||||
})
|
||||
|
||||
describe('GET /ralph/status', () => {
|
||||
it('should return 400 when repoId query param is missing', async () => {
|
||||
const req = new Request('http://localhost/ralph/status')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.error).toBe('Missing repoId')
|
||||
})
|
||||
|
||||
it('should return 400 when repoId is not a valid number', async () => {
|
||||
const req = new Request('http://localhost/ralph/status?repoId=abc')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.error).toBe('Invalid repoId')
|
||||
})
|
||||
|
||||
it('should return 200 with empty loops when repo is not found in DB', async () => {
|
||||
mockGetRepoById.mockReturnValue(null)
|
||||
|
||||
const req = new Request('http://localhost/ralph/status?repoId=1')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.loops).toEqual([])
|
||||
})
|
||||
|
||||
it('should return 200 with empty loops when resolveProjectId returns null', async () => {
|
||||
mockGetRepoById.mockReturnValue({
|
||||
id: 1,
|
||||
fullPath: '/tmp/test-repo',
|
||||
repoUrl: 'https://github.com/test/repo.git',
|
||||
localPath: 'test-repo',
|
||||
sourcePath: '',
|
||||
branch: 'main',
|
||||
currentBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
isWorktree: false,
|
||||
openCodeConfigName: 'default',
|
||||
})
|
||||
mockResolveProjectId.mockResolvedValue(null)
|
||||
|
||||
const req = new Request('http://localhost/ralph/status?repoId=1')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.loops).toEqual([])
|
||||
})
|
||||
|
||||
it('should return 200 with loops array for a valid repo with active loops', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/tmp/test-repo',
|
||||
repoUrl: 'https://github.com/test/repo.git',
|
||||
localPath: 'test-repo',
|
||||
sourcePath: '',
|
||||
branch: 'main',
|
||||
currentBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
isWorktree: false,
|
||||
openCodeConfigName: 'default',
|
||||
}
|
||||
mockGetRepoById.mockReturnValue(mockRepo)
|
||||
mockResolveProjectId.mockResolvedValue('test-project-id')
|
||||
mockListKv.mockReturnValue([
|
||||
{
|
||||
key: 'ralph:session-123',
|
||||
data: {
|
||||
active: true,
|
||||
sessionId: 'session-123',
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/worktrees/test',
|
||||
iteration: 1,
|
||||
maxIterations: 10,
|
||||
startedAt: '2024-01-01T00:00:00.000Z',
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding',
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
},
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
expiresAt: Date.now() + 86400000,
|
||||
},
|
||||
])
|
||||
|
||||
const req = new Request('http://localhost/ralph/status?repoId=1')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.loops).toHaveLength(1)
|
||||
expect((json.loops as Array<Record<string, unknown>>)[0]?.active).toBe(true)
|
||||
})
|
||||
|
||||
it('should filter out KV entries that do not have an active field', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/tmp/test-repo',
|
||||
repoUrl: 'https://github.com/test/repo.git',
|
||||
localPath: 'test-repo',
|
||||
sourcePath: '',
|
||||
branch: 'main',
|
||||
currentBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
isWorktree: false,
|
||||
openCodeConfigName: 'default',
|
||||
}
|
||||
mockGetRepoById.mockReturnValue(mockRepo)
|
||||
mockResolveProjectId.mockResolvedValue('test-project-id')
|
||||
mockListKv.mockReturnValue([
|
||||
{
|
||||
key: 'ralph:session-123',
|
||||
data: { active: true, sessionId: 'session-123' },
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
expiresAt: Date.now() + 86400000,
|
||||
},
|
||||
{
|
||||
key: 'ralph:session-456',
|
||||
data: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
expiresAt: Date.now() + 86400000,
|
||||
},
|
||||
{
|
||||
key: 'ralph:session-789',
|
||||
data: 'string-data',
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
expiresAt: Date.now() + 86400000,
|
||||
},
|
||||
{
|
||||
key: 'ralph:session-abc',
|
||||
data: { sessionId: 'session-abc' },
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
expiresAt: Date.now() + 86400000,
|
||||
},
|
||||
])
|
||||
|
||||
const req = new Request('http://localhost/ralph/status?repoId=1')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.loops).toHaveLength(1)
|
||||
expect((json.loops as Array<Record<string, unknown>>)[0]?.active).toBe(true)
|
||||
})
|
||||
|
||||
it('should return 500 when an unexpected error is thrown', async () => {
|
||||
mockGetRepoById.mockImplementation(() => {
|
||||
throw new Error('Database error')
|
||||
})
|
||||
|
||||
const req = new Request('http://localhost/ralph/status?repoId=1')
|
||||
const res = await memoryApp.fetch(req)
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.error).toBe('Failed to get Ralph status')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest } from '@opencode-manager/shared/types'
|
||||
import type { Memory, MemoryStats, CreateMemoryRequest, UpdateMemoryRequest, PluginConfig, KvEntry, CreateKvEntryRequest, UpdateKvEntryRequest, RalphState } from '@opencode-manager/shared/types'
|
||||
|
||||
export async function listMemories(filters?: {
|
||||
projectId?: string
|
||||
@@ -123,7 +123,11 @@ export async function updateKvEntry(projectId: string, key: string, data: Update
|
||||
})
|
||||
}
|
||||
|
||||
export async function cancelRalphLoop(repoId: string, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
|
||||
export async function getRalphStatus(repoId: number): Promise<{ loops: RalphState[]; projectId?: string | null }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/memory/ralph/status?repoId=${repoId}`)
|
||||
}
|
||||
|
||||
export async function cancelRalphLoop(repoId: number, sessionId: string): Promise<{ cancelled: boolean; worktreeName?: string }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/memory/ralph/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Loader2, CheckCircle2, XCircle, Ban, AlertCircle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import type { RalphState } from '@opencode-manager/shared'
|
||||
|
||||
interface RepoRalphListProps {
|
||||
isLoading: boolean
|
||||
data: RalphState[] | undefined
|
||||
error: Error | null
|
||||
onCancel: (sessionId: string) => void
|
||||
pendingSessionId: string | null
|
||||
}
|
||||
|
||||
function StatusIcon({ loop }: { loop: RalphState }) {
|
||||
if (loop.active) return <Loader2 className="h-4 w-4 animate-spin text-blue-400" />
|
||||
if (loop.terminationReason === 'completed') return <CheckCircle2 className="h-4 w-4 text-green-400" />
|
||||
if (loop.terminationReason === 'cancelled' || loop.terminationReason === 'user_aborted') return <Ban className="h-4 w-4 text-yellow-400" />
|
||||
return <XCircle className="h-4 w-4 text-red-400" />
|
||||
}
|
||||
|
||||
function formatDuration(startedAt: string, completedAt?: string): string {
|
||||
const start = new Date(startedAt).getTime()
|
||||
const end = completedAt ? new Date(completedAt).getTime() : Date.now()
|
||||
const seconds = Math.floor((end - start) / 1000)
|
||||
if (seconds < 60) return `${seconds}s`
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
if (minutes < 60) return `${minutes}m ${seconds % 60}s`
|
||||
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
|
||||
}
|
||||
|
||||
export function RepoRalphList({ isLoading, data, error, onCancel, pendingSessionId }: RepoRalphListProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 p-6 text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span className="text-sm">Failed to load Ralph status</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!data?.length) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-muted-foreground">
|
||||
<span className="text-sm">No Ralph loops found</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 p-4 overflow-y-auto">
|
||||
{data.map((loop) => (
|
||||
<div key={loop.sessionId} className="rounded-lg border bg-card p-4 flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<StatusIcon loop={loop} />
|
||||
<span className="font-medium text-sm truncate">{loop.worktreeName}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Badge variant="outline" className="text-xs capitalize">
|
||||
{loop.phase ?? 'coding'}
|
||||
</Badge>
|
||||
{loop.active && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => onCancel(loop.sessionId)}
|
||||
disabled={pendingSessionId === loop.sessionId}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span>Iteration {loop.iteration ?? 0}/{loop.maxIterations ?? 0}</span>
|
||||
<span>{formatDuration(loop.startedAt ?? new Date().toISOString(), loop.completedAt)}</span>
|
||||
{loop.worktreeBranch && <span className="truncate">{loop.worktreeBranch}</span>}
|
||||
</div>
|
||||
{loop.terminationReason && !loop.active && (
|
||||
<span className="text-xs text-muted-foreground capitalize">
|
||||
{loop.terminationReason.replace(/_/g, ' ')}
|
||||
</span>
|
||||
)}
|
||||
{loop.lastAuditResult && (
|
||||
<p className="text-xs text-muted-foreground line-clamp-2 mt-1">{loop.lastAuditResult}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -544,7 +544,7 @@ export const useAbortSession = (
|
||||
attemptAbort();
|
||||
|
||||
if (repoId) {
|
||||
cancelRalphLoop(String(repoId), targetSessionID).catch(() => {})
|
||||
cancelRalphLoop(repoId, targetSessionID).catch(() => {})
|
||||
}
|
||||
|
||||
retryIntervalRef.current = setInterval(() => {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { getRalphStatus, cancelRalphLoop } from '@/api/memory'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function useRalphStatus(repoId: number | undefined, open: boolean) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['ralph-status', repoId],
|
||||
queryFn: () => getRalphStatus(repoId!),
|
||||
enabled: open && !!repoId,
|
||||
staleTime: 0,
|
||||
refetchInterval: ({ state }) => {
|
||||
const loops = state.data?.loops ?? []
|
||||
return loops.some(l => l.active) ? 5000 : false
|
||||
},
|
||||
})
|
||||
|
||||
const cancelMutation = useMutation({
|
||||
mutationFn: ({ sessionId }: { sessionId: string }) =>
|
||||
cancelRalphLoop(repoId!, sessionId),
|
||||
onSuccess: (result) => {
|
||||
if (result.cancelled) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ralph-status', repoId] })
|
||||
} else {
|
||||
showToast.error('Ralph loop is no longer active')
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Unable to cancel the Ralph loop. Please try again.')
|
||||
},
|
||||
})
|
||||
|
||||
const pendingSessionId = cancelMutation.isPending ? (cancelMutation.variables?.sessionId ?? null) : null
|
||||
|
||||
return { data, isLoading, error, cancelMutation, pendingSessionId }
|
||||
}
|
||||
|
||||
export function useRalphActiveCount(repoId: number | undefined, enabled: boolean) {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['ralph-status', repoId],
|
||||
queryFn: () => getRalphStatus(repoId!),
|
||||
enabled: enabled && !!repoId,
|
||||
staleTime: 0,
|
||||
refetchInterval: 10000,
|
||||
})
|
||||
return data?.loops.filter(l => l.active).length ?? 0
|
||||
}
|
||||
@@ -3,16 +3,18 @@ import { useParams } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import { useProjectSummary, useKvEntries } from '@/hooks/useMemories'
|
||||
import { useRalphStatus } from '@/hooks/useRalphStatus'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Loader2, Plus, Brain, Key } from 'lucide-react'
|
||||
import { Loader2, Plus, Brain, Key, Bot } from 'lucide-react'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { MemoryList } from '@/components/memory/MemoryList'
|
||||
import { MemoryFormDialog } from '@/components/memory/MemoryFormDialog'
|
||||
import { KvList } from '@/components/memory/KvList'
|
||||
import { RepoRalphList } from '@/components/repo/RepoRalphList'
|
||||
|
||||
export function Memories() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
@@ -28,6 +30,7 @@ export function Memories() {
|
||||
|
||||
const { data: projectSummary, isLoading: projectSummaryLoading } = useProjectSummary(repoId)
|
||||
const { data: kvEntries } = useKvEntries(projectSummary?.projectId ?? undefined)
|
||||
const { data: ralphData, isLoading: ralphLoading, error: ralphError, cancelMutation, pendingSessionId } = useRalphStatus(repoId, activeTab === 'ralph')
|
||||
|
||||
const projectId = projectSummary?.projectId ?? null
|
||||
const stats = projectSummary?.stats ?? null
|
||||
@@ -125,6 +128,10 @@ export function Memories() {
|
||||
<Key className="w-4 h-4 mr-2" />
|
||||
Key-Value
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="ralph">
|
||||
<Bot className="w-4 h-4 mr-2" />
|
||||
Ralph
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="memories">
|
||||
<MemoryList projectId={projectId} showFilters={true} />
|
||||
@@ -132,6 +139,15 @@ export function Memories() {
|
||||
<TabsContent value="kv">
|
||||
<KvList projectId={projectId ?? undefined} />
|
||||
</TabsContent>
|
||||
<TabsContent value="ralph">
|
||||
<RepoRalphList
|
||||
isLoading={ralphLoading}
|
||||
data={ralphData?.loops}
|
||||
error={ralphError}
|
||||
onCancel={(sessionId) => cancelMutation.mutate({ sessionId })}
|
||||
pendingSessionId={pendingSessionId}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -64,17 +64,19 @@ export function createRalphEventHandler(
|
||||
logger.error(`Ralph: failed to commit changes in worktree ${state.worktreeDir}`, err)
|
||||
}
|
||||
|
||||
try {
|
||||
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
|
||||
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
|
||||
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
|
||||
if (removeResult.status !== 0) {
|
||||
throw new Error(removeResult.stderr || 'git worktree remove failed')
|
||||
if (state.worktreeDir && state.worktreeBranch) {
|
||||
try {
|
||||
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
|
||||
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
|
||||
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
|
||||
if (removeResult.status !== 0) {
|
||||
throw new Error(removeResult.stderr || 'git worktree remove failed')
|
||||
}
|
||||
cleaned = true
|
||||
logger.log(`Ralph: removed worktree ${state.worktreeDir}, branch ${state.worktreeBranch} preserved`)
|
||||
} catch (err) {
|
||||
logger.error(`Ralph: failed to remove worktree ${state.worktreeDir}`, err)
|
||||
}
|
||||
cleaned = true
|
||||
logger.log(`Ralph: removed worktree ${state.worktreeDir}, branch ${state.worktreeBranch} preserved`)
|
||||
} catch (err) {
|
||||
logger.error(`Ralph: failed to remove worktree ${state.worktreeDir}`, err)
|
||||
}
|
||||
|
||||
return { committed, cleaned }
|
||||
@@ -188,7 +190,7 @@ export function createRalphEventHandler(
|
||||
logger.log(`Ralph loop terminated: reason="${reason}", worktree="${state.worktreeName}", iteration=${state.iteration}`)
|
||||
|
||||
let commitResult: { committed: boolean; cleaned: boolean } | undefined
|
||||
if (reason === 'completed') {
|
||||
if (reason === 'completed' || reason === 'cancelled') {
|
||||
commitResult = await commitAndCleanupWorktree(state)
|
||||
}
|
||||
}
|
||||
@@ -227,7 +229,7 @@ export function createRalphEventHandler(
|
||||
}
|
||||
}
|
||||
|
||||
async function getLastAssistantText(sessionId: string, worktreeDir: string): Promise<string | null> {
|
||||
async function getLastAssistantInfo(sessionId: string, worktreeDir: string): Promise<{ text: string | null; error: string | null }> {
|
||||
try {
|
||||
const messagesResult = await v2Client.session.messages({
|
||||
sessionID: sessionId,
|
||||
@@ -236,21 +238,25 @@ export function createRalphEventHandler(
|
||||
})
|
||||
|
||||
const messages = (messagesResult.data ?? []) as Array<{
|
||||
info: { role: string }
|
||||
info: { role: string; error?: { name?: string; data?: { message?: string } } }
|
||||
parts: Array<{ type: string; text?: string }>
|
||||
}>
|
||||
|
||||
const lastAssistant = [...messages].reverse().find((m) => m.info.role === 'assistant')
|
||||
|
||||
if (!lastAssistant) return null
|
||||
if (!lastAssistant) return { text: null, error: null }
|
||||
|
||||
return lastAssistant.parts
|
||||
const text = lastAssistant.parts
|
||||
.filter((p) => p.type === 'text' && typeof p.text === 'string')
|
||||
.map((p) => p.text as string)
|
||||
.join('\n')
|
||||
.join('\n') || null
|
||||
|
||||
const error = lastAssistant.info.error?.data?.message ?? lastAssistant.info.error?.name ?? null
|
||||
|
||||
return { text, error }
|
||||
} catch (err) {
|
||||
logger.error(`Ralph: could not read session messages`, err)
|
||||
return null
|
||||
return { text: null, error: null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,9 +298,31 @@ export function createRalphEventHandler(
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentState.worktreeDir) {
|
||||
logger.error(`Ralph: loop ${sessionId} missing worktreeDir in coding phase, terminating`)
|
||||
await terminateLoop(sessionId, currentState, 'missing_worktree_dir')
|
||||
return
|
||||
}
|
||||
|
||||
let assistantErrorDetected = false
|
||||
if (currentState.completionPromise) {
|
||||
const textContent = await getLastAssistantText(sessionId, currentState.worktreeDir)
|
||||
if (textContent && ralphService.checkCompletionPromise(textContent, currentState.completionPromise)) {
|
||||
const { text: textContent, error: assistantError } = await getLastAssistantInfo(sessionId, currentState.worktreeDir)
|
||||
if (assistantError) {
|
||||
assistantErrorDetected = true
|
||||
logger.error(`Ralph: assistant error detected in coding phase: ${assistantError}`)
|
||||
const isModelError = /provider|auth|model|api\s*error/i.test(assistantError)
|
||||
if (isModelError) {
|
||||
const nextErrorCount = (currentState.errorCount ?? 0) + 1
|
||||
if (nextErrorCount >= MAX_RETRIES) {
|
||||
await terminateLoop(sessionId, currentState, `error_max_retries: assistant error: ${assistantError}`)
|
||||
return
|
||||
}
|
||||
ralphService.setState(sessionId, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
|
||||
logger.log(`Ralph: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
|
||||
currentState = ralphService.getActiveState(sessionId)!
|
||||
}
|
||||
}
|
||||
if (textContent && currentState.completionPromise && ralphService.checkCompletionPromise(textContent, currentState.completionPromise)) {
|
||||
const currentAuditCount = currentState.auditCount ?? 0
|
||||
if (!currentState.audit || currentAuditCount >= minAudits) {
|
||||
await terminateLoop(sessionId, currentState, 'completed')
|
||||
@@ -305,14 +333,20 @@ export function createRalphEventHandler(
|
||||
}
|
||||
}
|
||||
|
||||
if (currentState.maxIterations > 0 && currentState.iteration >= currentState.maxIterations) {
|
||||
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
|
||||
ralphService.setState(sessionId, { ...currentState, errorCount: 0 })
|
||||
logger.log(`Ralph: resetting error count after successful retry in coding phase`)
|
||||
currentState = ralphService.getActiveState(sessionId)!
|
||||
}
|
||||
|
||||
if ((currentState.maxIterations ?? 0) > 0 && (currentState.iteration ?? 0) >= (currentState.maxIterations ?? 0)) {
|
||||
await terminateLoop(sessionId, currentState, 'max_iterations')
|
||||
return
|
||||
}
|
||||
|
||||
if (currentState.audit) {
|
||||
ralphService.setState(sessionId, { ...currentState, phase: 'auditing', errorCount: 0 })
|
||||
logger.log(`Ralph iteration ${currentState.iteration} complete, running auditor for session ${sessionId}`)
|
||||
logger.log(`Ralph iteration ${currentState.iteration ?? 0} complete, running auditor for session ${sessionId}`)
|
||||
|
||||
const auditPrompt = {
|
||||
sessionID: sessionId,
|
||||
@@ -353,19 +387,26 @@ export function createRalphEventHandler(
|
||||
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
|
||||
}
|
||||
|
||||
const nextIteration = currentState.iteration + 1
|
||||
const nextIteration = (currentState.iteration ?? 0) + 1
|
||||
ralphService.setState(activeSessionId, {
|
||||
...currentState,
|
||||
sessionId: activeSessionId,
|
||||
iteration: nextIteration,
|
||||
errorCount: 0,
|
||||
errorCount: assistantErrorDetected ? currentState.errorCount : 0,
|
||||
})
|
||||
|
||||
const continuationPrompt = ralphService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
|
||||
|
||||
const currentConfig = getConfig()
|
||||
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
|
||||
const freshStateForModel = ralphService.getActiveState(activeSessionId)
|
||||
const ralphModel = freshStateForModel?.modelFailed
|
||||
? undefined
|
||||
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
|
||||
|
||||
if (freshStateForModel?.modelFailed) {
|
||||
logger.log(`Ralph: configured model previously failed, using default model`)
|
||||
}
|
||||
|
||||
const sendContinuationPromptWithModel = async () => {
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
@@ -376,7 +417,7 @@ export function createRalphEventHandler(
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
model: ralphModel!,
|
||||
model: ralphModel,
|
||||
})
|
||||
return { data: result.data, error: result.error }
|
||||
}
|
||||
@@ -405,7 +446,8 @@ export function createRalphEventHandler(
|
||||
const retryFn = async () => {
|
||||
const result = await sendContinuationPromptWithoutModel()
|
||||
if (result.error) {
|
||||
throw result.error
|
||||
await handlePromptError(activeSessionId, currentState, 'retry failed', result.error)
|
||||
return
|
||||
}
|
||||
}
|
||||
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
|
||||
@@ -423,17 +465,46 @@ export function createRalphEventHandler(
|
||||
|
||||
async function handleAuditingPhase(sessionId: string, state: RalphState): Promise<void> {
|
||||
// Re-fetch and validate state to catch aborts that happened during idle event processing
|
||||
const currentState = ralphService.getActiveState(sessionId)
|
||||
let currentState = ralphService.getActiveState(sessionId)
|
||||
if (!currentState?.active) {
|
||||
logger.log(`Ralph: loop ${sessionId} no longer active, skipping auditing phase`)
|
||||
return
|
||||
}
|
||||
|
||||
const auditText = await getLastAssistantText(sessionId, currentState.worktreeDir)
|
||||
if (!currentState.worktreeDir) {
|
||||
logger.error(`Ralph: loop ${sessionId} missing worktreeDir in auditing phase, terminating`)
|
||||
await terminateLoop(sessionId, currentState, 'missing_worktree_dir')
|
||||
return
|
||||
}
|
||||
|
||||
const nextIteration = currentState.iteration + 1
|
||||
const { text: auditText, error: assistantError } = await getLastAssistantInfo(sessionId, currentState.worktreeDir)
|
||||
|
||||
let assistantErrorDetected = false
|
||||
if (assistantError) {
|
||||
assistantErrorDetected = true
|
||||
logger.error(`Ralph: assistant error detected in auditing phase: ${assistantError}`)
|
||||
const isModelError = /provider|auth|model|api\s*error/i.test(assistantError)
|
||||
if (isModelError) {
|
||||
const nextErrorCount = (currentState.errorCount ?? 0) + 1
|
||||
if (nextErrorCount >= MAX_RETRIES) {
|
||||
await terminateLoop(sessionId, currentState, `error_max_retries: assistant error: ${assistantError}`)
|
||||
return
|
||||
}
|
||||
ralphService.setState(sessionId, { ...currentState, modelFailed: true, errorCount: nextErrorCount })
|
||||
logger.log(`Ralph: marking model as failed, will fall back to default model (error ${nextErrorCount}/${MAX_RETRIES})`)
|
||||
currentState = ralphService.getActiveState(sessionId)!
|
||||
}
|
||||
}
|
||||
|
||||
if (!assistantErrorDetected && currentState.errorCount && currentState.errorCount > 0) {
|
||||
ralphService.setState(sessionId, { ...currentState, errorCount: 0 })
|
||||
logger.log(`Ralph: resetting error count after successful retry in auditing phase`)
|
||||
currentState = ralphService.getActiveState(sessionId)!
|
||||
}
|
||||
|
||||
const nextIteration = (currentState.iteration ?? 0) + 1
|
||||
const newAuditCount = (currentState.auditCount ?? 0) + 1
|
||||
logger.log(`Ralph audit ${newAuditCount} at iteration ${currentState.iteration}`)
|
||||
logger.log(`Ralph audit ${newAuditCount} at iteration ${currentState.iteration ?? 0}`)
|
||||
|
||||
// Always pass the full audit response to the code agent
|
||||
const auditFindings = auditText ?? undefined
|
||||
@@ -450,7 +521,7 @@ export function createRalphEventHandler(
|
||||
}
|
||||
}
|
||||
|
||||
if (currentState.maxIterations > 0 && nextIteration > currentState.maxIterations) {
|
||||
if ((currentState.maxIterations ?? 0) > 0 && nextIteration > (currentState.maxIterations ?? 0)) {
|
||||
await terminateLoop(sessionId, currentState, 'max_iterations')
|
||||
return
|
||||
}
|
||||
@@ -469,7 +540,7 @@ export function createRalphEventHandler(
|
||||
phase: 'coding',
|
||||
lastAuditResult: auditFindings,
|
||||
auditCount: newAuditCount,
|
||||
errorCount: 0,
|
||||
errorCount: assistantErrorDetected ? currentState.errorCount : 0,
|
||||
})
|
||||
|
||||
const continuationPrompt = ralphService.buildContinuationPrompt(
|
||||
@@ -479,7 +550,14 @@ export function createRalphEventHandler(
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
|
||||
|
||||
const currentConfig = getConfig()
|
||||
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
|
||||
const freshStateForModel = ralphService.getActiveState(activeSessionId)
|
||||
const ralphModel = freshStateForModel?.modelFailed
|
||||
? undefined
|
||||
: (parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel))
|
||||
|
||||
if (freshStateForModel?.modelFailed) {
|
||||
logger.log(`Ralph: configured model previously failed, using default model`)
|
||||
}
|
||||
|
||||
const sendContinuationPromptWithModel = async () => {
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
@@ -490,7 +568,7 @@ export function createRalphEventHandler(
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
model: ralphModel!,
|
||||
model: ralphModel,
|
||||
})
|
||||
return { data: result.data, error: result.error }
|
||||
}
|
||||
@@ -523,7 +601,8 @@ export function createRalphEventHandler(
|
||||
}
|
||||
const result = await sendContinuationPromptWithoutModel()
|
||||
if (result.error) {
|
||||
throw result.error
|
||||
await handlePromptError(activeSessionId, currentState, 'retry failed after audit', result.error)
|
||||
return
|
||||
}
|
||||
}
|
||||
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
|
||||
@@ -558,17 +637,31 @@ export function createRalphEventHandler(
|
||||
}
|
||||
|
||||
if (event.type === 'session.error') {
|
||||
const errorProps = event.properties as { sessionID?: string; error?: { name?: string } }
|
||||
const errorProps = event.properties as { sessionID?: string; error?: { name?: string; data?: { message?: string } } }
|
||||
const eventSessionId = errorProps?.sessionID
|
||||
const errorName = errorProps?.error?.name
|
||||
const isAbort = errorName === 'MessageAbortedError' || errorName === 'AbortError'
|
||||
|
||||
if (!eventSessionId || !isAbort) return
|
||||
if (!eventSessionId) return
|
||||
|
||||
if (isAbort) {
|
||||
const state = ralphService.getActiveState(eventSessionId)
|
||||
if (state?.active) {
|
||||
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
|
||||
await terminateLoop(eventSessionId, state, 'user_aborted')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const state = ralphService.getActiveState(eventSessionId)
|
||||
if (state?.active) {
|
||||
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
|
||||
await terminateLoop(eventSessionId, state, 'user_aborted')
|
||||
const errorMessage = errorProps?.error?.data?.message ?? errorName ?? 'unknown error'
|
||||
logger.error(`Ralph: session error for ${eventSessionId}: ${errorMessage}`)
|
||||
const isModelError = /provider|auth|model|api\s*error/i.test(errorMessage)
|
||||
if (isModelError && !state.modelFailed) {
|
||||
logger.log(`Ralph: marking model as failed, will fall back to default on next iteration`)
|
||||
ralphService.setState(eventSessionId, { ...state, modelFailed: true })
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -12,23 +12,24 @@ export const RECENT_MESSAGES_COUNT = 5
|
||||
export interface RalphState {
|
||||
active: boolean
|
||||
sessionId: string
|
||||
worktreeName: string
|
||||
worktreeDir: string
|
||||
worktreeName?: string
|
||||
worktreeDir?: string
|
||||
worktreeBranch?: string
|
||||
workspaceId: string
|
||||
iteration: number
|
||||
maxIterations: number
|
||||
workspaceId?: string
|
||||
iteration?: number
|
||||
maxIterations?: number
|
||||
completionPromise: string | null
|
||||
startedAt: string
|
||||
prompt: string
|
||||
phase: 'coding' | 'auditing'
|
||||
audit: boolean
|
||||
startedAt?: string
|
||||
prompt?: string
|
||||
phase?: 'coding' | 'auditing'
|
||||
audit?: boolean
|
||||
lastAuditResult?: string
|
||||
errorCount: number
|
||||
auditCount: number
|
||||
errorCount?: number
|
||||
auditCount?: number
|
||||
terminationReason?: string
|
||||
completedAt?: string
|
||||
inPlace?: boolean
|
||||
modelFailed?: boolean
|
||||
}
|
||||
|
||||
export interface RalphService {
|
||||
@@ -86,17 +87,17 @@ export function createRalphService(
|
||||
}
|
||||
|
||||
function buildContinuationPrompt(state: RalphState, auditFindings?: string): string {
|
||||
let systemLine = `Ralph iteration ${state.iteration}`
|
||||
let systemLine = `Ralph iteration ${state.iteration ?? 0}`
|
||||
|
||||
if (state.completionPromise) {
|
||||
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY when all requirements are met)`
|
||||
} else if (state.maxIterations > 0) {
|
||||
} else if ((state.maxIterations ?? 0) > 0) {
|
||||
systemLine += ` / ${state.maxIterations}`
|
||||
} else {
|
||||
systemLine += ` | No completion promise set - loop runs until cancelled`
|
||||
}
|
||||
|
||||
let prompt = `[${systemLine}]\n\n${state.prompt}`
|
||||
let prompt = `[${systemLine}]\n\n${state.prompt ?? ''}`
|
||||
|
||||
if (auditFindings) {
|
||||
const completionInstruction = state.completionPromise
|
||||
@@ -109,13 +110,13 @@ export function createRalphService(
|
||||
}
|
||||
|
||||
function buildAuditPrompt(state: RalphState): string {
|
||||
const taskSummary = state.prompt.length > 200
|
||||
? `${state.prompt.substring(0, 197)}...`
|
||||
: state.prompt
|
||||
const taskSummary = (state.prompt?.length ?? 0) > 200
|
||||
? `${state.prompt?.substring(0, 197)}...`
|
||||
: (state.prompt ?? '')
|
||||
|
||||
const branchInfo = state.worktreeBranch ? ` (branch: ${state.worktreeBranch})` : ''
|
||||
return [
|
||||
`Post-iteration ${state.iteration} code review${branchInfo}.`,
|
||||
`Post-iteration ${state.iteration ?? 0} code review${branchInfo}.`,
|
||||
'',
|
||||
`Task context: ${taskSummary}`,
|
||||
'',
|
||||
|
||||
@@ -476,13 +476,11 @@ describe('RalphService', () => {
|
||||
errorCount: 2,
|
||||
auditCount: 1,
|
||||
terminationReason: undefined,
|
||||
parentSessionId: 'parent-session-123',
|
||||
}
|
||||
ralphService.setState('session-err', state)
|
||||
const retrieved = ralphService.getActiveState('session-err')
|
||||
expect(retrieved?.errorCount).toBe(2)
|
||||
expect(retrieved?.auditCount).toBe(1)
|
||||
expect(retrieved?.parentSessionId).toBe('parent-session-123')
|
||||
})
|
||||
|
||||
test('state defaults errorCount to 0', () => {
|
||||
@@ -1169,3 +1167,474 @@ describe('session rotation', () => {
|
||||
expect(existingState?.sessionId).toBe(sessionId)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Assistant Error Detection', () => {
|
||||
let db: Database
|
||||
let kvService: ReturnType<typeof createKvService>
|
||||
let ralphService: ReturnType<typeof createRalphService>
|
||||
const projectId = 'test-project'
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
kvService = createKvService(db)
|
||||
ralphService = createRalphService(kvService, projectId, createMockLogger())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
test('detects assistant error in coding phase and triggers error handling', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'error-session'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: [
|
||||
{
|
||||
info: {
|
||||
role: 'assistant',
|
||||
error: { name: 'ProviderError', data: { message: 'Model not found' } },
|
||||
},
|
||||
parts: [{ type: 'text', text: '' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: 'DONE',
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding' as const,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const updatedState = ralphService.getActiveState(sessionId)
|
||||
expect(updatedState?.errorCount).toBe(1)
|
||||
expect(updatedState?.modelFailed).toBe(true)
|
||||
})
|
||||
|
||||
test('detects assistant error in auditing phase and triggers error handling', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'audit-error-session'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: [
|
||||
{
|
||||
info: {
|
||||
role: 'assistant',
|
||||
error: { name: 'AuthError', data: { message: 'Authentication failed' } },
|
||||
},
|
||||
parts: [{ type: 'text', text: '' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'auditing' as const,
|
||||
audit: true,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const updatedState = ralphService.getActiveState(sessionId)
|
||||
expect(updatedState?.errorCount).toBe(1)
|
||||
expect(updatedState?.modelFailed).toBe(true)
|
||||
})
|
||||
|
||||
test('session.error event with non-abort error sets modelFailed flag', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'session-error-test'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding' as const,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.error',
|
||||
properties: {
|
||||
sessionID: sessionId,
|
||||
error: {
|
||||
name: 'ProviderError',
|
||||
data: { message: 'Model not found' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const updatedState = ralphService.getActiveState(sessionId)
|
||||
expect(updatedState?.modelFailed).toBe(true)
|
||||
})
|
||||
|
||||
test('session.error event with abort error terminates loop immediately', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'abort-session'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding' as const,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.error',
|
||||
properties: {
|
||||
sessionID: sessionId,
|
||||
error: {
|
||||
name: 'MessageAbortedError',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const updatedState = ralphService.getActiveState(sessionId)
|
||||
expect(updatedState).toBeNull()
|
||||
})
|
||||
|
||||
test('modelFailed flag causes default model usage in coding phase', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'model-fail-session'
|
||||
|
||||
let modelUsed: string | undefined
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async (params: any) => {
|
||||
modelUsed = params.model
|
||||
return { data: undefined, error: undefined }
|
||||
},
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({
|
||||
ralph: { model: 'custom/model' },
|
||||
executionModel: 'execution/model',
|
||||
auditorModel: undefined,
|
||||
})
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding' as const,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
modelFailed: true,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
expect(modelUsed).toBeUndefined()
|
||||
})
|
||||
|
||||
test('three consecutive errors terminate loop', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'three-errors-session'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
messages: async () => ({ data: [] }),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
worktree: {
|
||||
create: async () => ({ data: { id: 'wt-1', directory: '/tmp/wt', branch: 'main' }, error: undefined }),
|
||||
remove: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockV2Client = {
|
||||
session: {
|
||||
create: async () => ({ data: { id: sessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: [
|
||||
{
|
||||
info: {
|
||||
role: 'assistant',
|
||||
error: { name: 'ProviderError', data: { message: 'Model not found' } },
|
||||
},
|
||||
parts: [{ type: 'text', text: '' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
status: async () => ({ data: {} }),
|
||||
abort: async () => ({ data: undefined, error: undefined }),
|
||||
},
|
||||
} as any
|
||||
|
||||
const mockGetConfig = () => ({ ralph: {}, executionModel: undefined, auditorModel: undefined })
|
||||
const handler = createRalphEventHandler(ralphService, mockClient, mockV2Client, createMockLogger(), mockGetConfig)
|
||||
|
||||
const state = {
|
||||
active: true,
|
||||
sessionId,
|
||||
worktreeName: 'test-worktree',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
worktreeBranch: 'main',
|
||||
workspaceId: 'wrk-test',
|
||||
iteration: 1,
|
||||
maxIterations: 5,
|
||||
completionPromise: 'DONE',
|
||||
startedAt: new Date().toISOString(),
|
||||
prompt: 'Test prompt',
|
||||
phase: 'coding' as const,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
let stateAfterSecondError = ralphService.getActiveState(sessionId)
|
||||
expect(stateAfterSecondError?.errorCount).toBe(1)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
let stateAfterThirdError = ralphService.getActiveState(sessionId)
|
||||
expect(stateAfterThirdError?.errorCount).toBe(2)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const finalState = ralphService.getActiveState(sessionId)
|
||||
expect(finalState).toBeNull()
|
||||
|
||||
const terminatedState = ralphService.getAnyState(sessionId)
|
||||
expect(terminatedState?.active).toBe(false)
|
||||
expect(terminatedState?.terminationReason).toContain('error_max_retries')
|
||||
})
|
||||
})
|
||||
@@ -139,3 +139,27 @@ export const UpdateKvEntryRequestSchema = z.object({
|
||||
ttlMs: z.number().optional(),
|
||||
})
|
||||
export type UpdateKvEntryRequest = z.infer<typeof UpdateKvEntryRequestSchema>
|
||||
|
||||
export const RalphStateSchema = z.object({
|
||||
active: z.boolean(),
|
||||
sessionId: z.string(),
|
||||
worktreeName: z.string().optional(),
|
||||
worktreeDir: z.string().optional(),
|
||||
worktreeBranch: z.string().optional(),
|
||||
workspaceId: z.string().optional(),
|
||||
iteration: z.number().optional(),
|
||||
maxIterations: z.number().optional(),
|
||||
completionPromise: z.string().nullable().optional(),
|
||||
startedAt: z.string().optional(),
|
||||
prompt: z.string().optional(),
|
||||
phase: z.enum(['coding', 'auditing']).optional(),
|
||||
audit: z.boolean().optional(),
|
||||
lastAuditResult: z.string().optional(),
|
||||
errorCount: z.number().optional(),
|
||||
auditCount: z.number().optional(),
|
||||
terminationReason: z.string().optional(),
|
||||
completedAt: z.string().optional(),
|
||||
inPlace: z.boolean().optional(),
|
||||
modelFailed: z.boolean().optional(),
|
||||
})
|
||||
export type RalphState = z.infer<typeof RalphStateSchema>
|
||||
@@ -98,6 +98,7 @@ export type {
|
||||
KvListQuery,
|
||||
CreateKvEntryRequest,
|
||||
UpdateKvEntryRequest,
|
||||
RalphState,
|
||||
} from '../schemas/memory'
|
||||
|
||||
export type {
|
||||
|
||||
Reference in new issue
Block a user