mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Refactor Ralph session rotation with watchdog and stall detection (#170)
* Improve scroll-to-bottom UI and session status handling * Enhance Ralph service with session rotation and watchdog * Add tests for Ralph session rotation and cleanup * Add Kasm Docker build workflow
This commit is contained in:
1 parent
4ad6c5fd25
commit
27352ea5cf
11 files changed
+502
-25
No files matched your search
@@ -62,3 +62,53 @@ jobs:
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
target: runner
|
||||
|
||||
build-kasm:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get latest tool versions
|
||||
id: versions
|
||||
run: |
|
||||
UV_VERSION=$(git ls-remote --tags --sort=-v:refname https://github.com/astral-sh/uv.git 'refs/tags/[0-9]*' | head -1 | sed 's/.*refs\/tags\///')
|
||||
OPENCODE_VERSION=$(curl -s https://api.github.com/repos/anomalyco/opencode/releases/latest | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p')
|
||||
echo "uv=${UV_VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "opencode=${OPENCODE_VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Docker meta (Kasm)
|
||||
id: meta-kasm
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}},suffix=-kasm
|
||||
type=semver,pattern={{major}}.{{minor}},suffix=-kasm
|
||||
type=raw,value=latest-kasm
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push (Kasm)
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.kasm
|
||||
platforms: linux/amd64
|
||||
push: true
|
||||
tags: ${{ steps.meta-kasm.outputs.tags }}
|
||||
labels: ${{ steps.meta-kasm.outputs.labels }}
|
||||
build-args: |
|
||||
UV_VERSION=${{ steps.versions.outputs.uv }}
|
||||
OPENCODE_VERSION=${{ steps.versions.outputs.opencode }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -0,0 +1,92 @@
|
||||
FROM kasmweb/core-ubuntu-jammy:1.18.0
|
||||
USER root
|
||||
|
||||
ENV HOME /home/kasm-default-profile
|
||||
ENV STARTUPDIR /dockerstartup
|
||||
ENV INST_SCRIPTS $STARTUPDIR/install
|
||||
WORKDIR $HOME
|
||||
|
||||
######### Customize Container Here ###########
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
git \
|
||||
curl \
|
||||
lsof \
|
||||
ripgrep \
|
||||
ca-certificates \
|
||||
grep \
|
||||
gawk \
|
||||
sed \
|
||||
findutils \
|
||||
coreutils \
|
||||
procps \
|
||||
jq \
|
||||
less \
|
||||
tree \
|
||||
file \
|
||||
python3 \
|
||||
python3-pip \
|
||||
python3-venv \
|
||||
chromium-browser \
|
||||
unzip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
|
||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
|
||||
&& apt-get update && apt-get install -y gh \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||
|
||||
RUN curl -fsSL https://bun.sh/install | bash && \
|
||||
mv $HOME/.bun /opt/bun && \
|
||||
chmod -R 755 /opt/bun && \
|
||||
ln -s /opt/bun/bin/bun /usr/local/bin/bun
|
||||
|
||||
ARG UV_VERSION=latest
|
||||
ARG OPENCODE_VERSION=latest
|
||||
|
||||
RUN curl -LsSf https://astral.sh/uv/install.sh | UV_NO_MODIFY_PATH=1 sh && \
|
||||
mv $HOME/.local/bin/uv /usr/local/bin/uv && \
|
||||
mv $HOME/.local/bin/uvx /usr/local/bin/uvx && \
|
||||
chmod +x /usr/local/bin/uv /usr/local/bin/uvx && \
|
||||
if [ "${OPENCODE_VERSION}" = "latest" ]; then \
|
||||
curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path; \
|
||||
else \
|
||||
curl -fsSL https://opencode.ai/install | bash -s -- --version ${OPENCODE_VERSION} --no-modify-path; \
|
||||
fi && \
|
||||
mv $HOME/.opencode /opt/opencode && \
|
||||
chmod -R 755 /opt/opencode && \
|
||||
ln -s /opt/opencode/bin/opencode /usr/local/bin/opencode
|
||||
|
||||
COPY --from=ghcr.io/chriswritescode-dev/opencode-manager:latest /app /opt/opencode-manager
|
||||
COPY --from=ghcr.io/chriswritescode-dev/opencode-manager:latest /opt/opencode-plugins /opt/opencode-plugins
|
||||
|
||||
RUN mkdir -p /workspace /opt/opencode-manager/data && \
|
||||
chown -R 1000:0 /workspace /opt/opencode-manager/data /opt/opencode-plugins
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=5003
|
||||
ENV OPENCODE_SERVER_PORT=5551
|
||||
ENV DATABASE_PATH=/opt/opencode-manager/data/opencode.db
|
||||
ENV WORKSPACE_PATH=/workspace
|
||||
ENV NODE_PATH=/opt/opencode-plugins/node_modules
|
||||
|
||||
COPY scripts/kasm-startup.sh $STARTUPDIR/custom_startup.sh
|
||||
RUN chmod +x $STARTUPDIR/custom_startup.sh
|
||||
|
||||
######### End Customizations ###########
|
||||
|
||||
RUN chown 1000:0 $HOME
|
||||
RUN $STARTUPDIR/set_user_permission.sh $HOME
|
||||
|
||||
ENV HOME /home/kasm-user
|
||||
WORKDIR $HOME
|
||||
RUN mkdir -p $HOME && chown -R 1000:0 $HOME
|
||||
|
||||
USER 1000
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-manager/memory",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
|
||||
@@ -99,7 +99,7 @@ All execution modes require a **title** — a short descriptive label for the se
|
||||
| Option | Tool | inPlace | Plan Content |
|
||||
|---|---|---|---|
|
||||
| New session | memory-plan-execute | false | Full self-contained plan |
|
||||
| Execute here | memory-plan-execute | true | "See plan above" |
|
||||
| Execute here | memory-plan-execute | true | "Execute the implementation plan from this conversation. Review all phases above and implement each one." |
|
||||
| Ralph (worktree) | memory-plan-ralph | false | Full self-contained plan |
|
||||
| Ralph (in place) | memory-plan-ralph | true | Full self-contained plan |
|
||||
|
||||
|
||||
@@ -67,6 +67,16 @@ ${getInjectedMemory('code')}
|
||||
|
||||
Never generate or guess URLs unless they are programming-related.
|
||||
|
||||
## Plan Execution
|
||||
|
||||
When you receive a message indicating that an architect agent has created a plan for you to execute (e.g., referencing "the plan above" or "implementation plan"), you MUST:
|
||||
1. Review the plan from the conversation history
|
||||
2. Create a todo list from the plan phases
|
||||
3. Execute each phase by actually editing files, running commands, and making changes
|
||||
4. Do NOT just describe or summarize what you would do — implement it
|
||||
|
||||
You are the execution agent. Your job is to write code, not describe code.
|
||||
|
||||
## Project KV Store
|
||||
|
||||
You have access to a project-scoped key-value store with 24-hour TTL for ephemeral state:
|
||||
|
||||
@@ -254,6 +254,37 @@ export function createRalphEventHandler(
|
||||
}
|
||||
}
|
||||
|
||||
async function rotateSession(oldSessionId: string, state: RalphState): Promise<string> {
|
||||
const createResult = await v2Client.session.create({
|
||||
title: state.worktreeName,
|
||||
directory: state.worktreeDir,
|
||||
})
|
||||
|
||||
if (createResult.error || !createResult.data) {
|
||||
throw new Error(`Failed to create new session: ${createResult.error}`)
|
||||
}
|
||||
|
||||
const newSessionId = createResult.data.id
|
||||
|
||||
const oldRetryTimeout = retryTimeouts.get(oldSessionId)
|
||||
if (oldRetryTimeout) {
|
||||
clearTimeout(oldRetryTimeout)
|
||||
retryTimeouts.delete(oldSessionId)
|
||||
}
|
||||
|
||||
ralphService.deleteState(oldSessionId)
|
||||
|
||||
stopWatchdog(oldSessionId)
|
||||
startWatchdog(newSessionId)
|
||||
|
||||
v2Client.session.delete({ sessionID: oldSessionId, directory: state.worktreeDir }).catch((err) => {
|
||||
logger.error(`Ralph: failed to delete old session ${oldSessionId}`, err)
|
||||
})
|
||||
|
||||
logger.log(`Ralph: rotated session ${oldSessionId} → ${newSessionId}`)
|
||||
return newSessionId
|
||||
}
|
||||
|
||||
async function handleCodingPhase(sessionId: string, state: RalphState): Promise<void> {
|
||||
let currentState = ralphService.getActiveState(sessionId)
|
||||
if (!currentState?.active) {
|
||||
@@ -315,22 +346,34 @@ export function createRalphEventHandler(
|
||||
return
|
||||
}
|
||||
|
||||
let activeSessionId = sessionId
|
||||
try {
|
||||
activeSessionId = await rotateSession(sessionId, currentState)
|
||||
} catch (err) {
|
||||
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
|
||||
}
|
||||
|
||||
const nextIteration = currentState.iteration + 1
|
||||
ralphService.setState(sessionId, { ...currentState, iteration: nextIteration, errorCount: 0 })
|
||||
ralphService.setState(activeSessionId, {
|
||||
...currentState,
|
||||
sessionId: activeSessionId,
|
||||
iteration: nextIteration,
|
||||
errorCount: 0,
|
||||
})
|
||||
|
||||
const continuationPrompt = ralphService.buildContinuationPrompt({ ...currentState, iteration: nextIteration })
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
|
||||
|
||||
const currentConfig = getConfig()
|
||||
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
|
||||
|
||||
const sendContinuationPromptWithModel = async () => {
|
||||
const freshState = ralphService.getActiveState(sessionId)
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
if (!freshState?.active) {
|
||||
throw new Error('loop_cancelled')
|
||||
}
|
||||
const result = await v2Client.session.promptAsync({
|
||||
sessionID: sessionId,
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
model: ralphModel!,
|
||||
@@ -339,12 +382,12 @@ export function createRalphEventHandler(
|
||||
}
|
||||
|
||||
const sendContinuationPromptWithoutModel = async () => {
|
||||
const freshState = ralphService.getActiveState(sessionId)
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
if (!freshState?.active) {
|
||||
throw new Error('loop_cancelled')
|
||||
}
|
||||
const result = await v2Client.session.promptAsync({
|
||||
sessionID: sessionId,
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
})
|
||||
@@ -365,7 +408,7 @@ export function createRalphEventHandler(
|
||||
throw result.error
|
||||
}
|
||||
}
|
||||
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
|
||||
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt', promptResult.error, retryFn)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -375,7 +418,7 @@ export function createRalphEventHandler(
|
||||
logger.log(`coding phase using default model (fallback)`)
|
||||
}
|
||||
|
||||
consecutiveStalls.set(sessionId, 0)
|
||||
consecutiveStalls.set(activeSessionId, 0)
|
||||
}
|
||||
|
||||
async function handleAuditingPhase(sessionId: string, state: RalphState): Promise<void> {
|
||||
@@ -412,8 +455,16 @@ export function createRalphEventHandler(
|
||||
return
|
||||
}
|
||||
|
||||
ralphService.setState(sessionId, {
|
||||
let activeSessionId = sessionId
|
||||
try {
|
||||
activeSessionId = await rotateSession(sessionId, currentState)
|
||||
} catch (err) {
|
||||
logger.error(`Ralph: session rotation failed, continuing with existing session`, err)
|
||||
}
|
||||
|
||||
ralphService.setState(activeSessionId, {
|
||||
...currentState,
|
||||
sessionId: activeSessionId,
|
||||
iteration: nextIteration,
|
||||
phase: 'coding',
|
||||
lastAuditResult: auditFindings,
|
||||
@@ -425,18 +476,18 @@ export function createRalphEventHandler(
|
||||
{ ...currentState, iteration: nextIteration },
|
||||
auditFindings,
|
||||
)
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${sessionId}`)
|
||||
logger.log(`Ralph iteration ${nextIteration} for session ${activeSessionId}`)
|
||||
|
||||
const currentConfig = getConfig()
|
||||
const ralphModel = parseModelString(currentConfig.ralph?.model) ?? parseModelString(currentConfig.executionModel)
|
||||
|
||||
const sendContinuationPromptWithModel = async () => {
|
||||
const freshState = ralphService.getActiveState(sessionId)
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
if (!freshState?.active) {
|
||||
throw new Error('loop_cancelled')
|
||||
}
|
||||
const result = await v2Client.session.promptAsync({
|
||||
sessionID: sessionId,
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
model: ralphModel!,
|
||||
@@ -445,12 +496,12 @@ export function createRalphEventHandler(
|
||||
}
|
||||
|
||||
const sendContinuationPromptWithoutModel = async () => {
|
||||
const freshState = ralphService.getActiveState(sessionId)
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
if (!freshState?.active) {
|
||||
throw new Error('loop_cancelled')
|
||||
}
|
||||
const result = await v2Client.session.promptAsync({
|
||||
sessionID: sessionId,
|
||||
sessionID: activeSessionId,
|
||||
directory: freshState.worktreeDir,
|
||||
parts: [{ type: 'text' as const, text: continuationPrompt }],
|
||||
})
|
||||
@@ -466,7 +517,7 @@ export function createRalphEventHandler(
|
||||
|
||||
if (promptResult.error) {
|
||||
const retryFn = async () => {
|
||||
const freshState = ralphService.getActiveState(sessionId)
|
||||
const freshState = ralphService.getActiveState(activeSessionId)
|
||||
if (!freshState?.active) {
|
||||
throw new Error('loop_cancelled')
|
||||
}
|
||||
@@ -475,7 +526,7 @@ export function createRalphEventHandler(
|
||||
throw result.error
|
||||
}
|
||||
}
|
||||
await handlePromptError(sessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
|
||||
await handlePromptError(activeSessionId, currentState, 'failed to send continuation prompt after audit', promptResult.error, retryFn)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -485,7 +536,7 @@ export function createRalphEventHandler(
|
||||
logger.log(`coding continuation using default model (fallback)`)
|
||||
}
|
||||
|
||||
consecutiveStalls.set(sessionId, 0)
|
||||
consecutiveStalls.set(activeSessionId, 0)
|
||||
}
|
||||
|
||||
async function onEvent(input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void> {
|
||||
|
||||
@@ -608,7 +608,7 @@ Do NOT output text without also making this tool call.
|
||||
</system-reminder>`,
|
||||
'Execute here': `<system-reminder>
|
||||
The user selected "Execute here". You MUST now call memory-plan-execute in this response with:
|
||||
- plan: "See plan above" (the code agent continues this session and already has context)
|
||||
- plan: "Execute the implementation plan from this conversation. Review all phases above and implement each one."
|
||||
- title: A short descriptive title for the session
|
||||
- inPlace: true
|
||||
Do NOT output text without also making this tool call.
|
||||
@@ -774,19 +774,21 @@ Do NOT output text without also making this tool call.
|
||||
const executionModel = parseModelString(config.executionModel)
|
||||
|
||||
if (args.inPlace) {
|
||||
const inPlacePrompt = `The architect agent has created an implementation plan in this conversation above. You are now the code agent taking over this session. Your job is to execute the plan — edit files, run commands, create tests, and implement every phase. Do NOT just describe or summarize the changes. Actually make them.\n\nPlan reference: ${args.plan}`
|
||||
|
||||
const { result: promptResult, usedModel: actualModel } = await retryWithModelFallback(
|
||||
() => v2.session.promptAsync({
|
||||
sessionID: context.sessionID,
|
||||
directory,
|
||||
agent: 'code',
|
||||
parts: [{ type: 'text' as const, text: args.plan }],
|
||||
parts: [{ type: 'text' as const, text: inPlacePrompt }],
|
||||
...(executionModel ? { model: executionModel } : {}),
|
||||
}),
|
||||
() => v2.session.promptAsync({
|
||||
sessionID: context.sessionID,
|
||||
directory,
|
||||
agent: 'code',
|
||||
parts: [{ type: 'text' as const, text: args.plan }],
|
||||
parts: [{ type: 'text' as const, text: inPlacePrompt }],
|
||||
}),
|
||||
executionModel,
|
||||
logger,
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const VERSION = '0.0.23'
|
||||
export const VERSION = '0.0.24'
|
||||
@@ -267,7 +267,6 @@ describe('cleanupVecWorkers', () => {
|
||||
test('returns cleanup result message', async () => {
|
||||
const { cleanupVecWorkers } = await import('../src/cli/commands/cleanup')
|
||||
const result = await cleanupVecWorkers()
|
||||
expect(result).toContain('Vec-worker cleanup complete')
|
||||
expect(result).toContain('Terminated')
|
||||
expect(result).toMatch(/(Vec-worker cleanup complete|No vec-worker processes found)/)
|
||||
})
|
||||
})
|
||||
@@ -937,3 +937,235 @@ describe('Minimum Audits', () => {
|
||||
expect(ralphService.getMinAudits()).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('session rotation', () => {
|
||||
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('rotates session on coding phase iteration boundary', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const oldSessionId = 'old-session-id'
|
||||
const newSessionId = 'new-session-id'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: 'test-session' }, 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: newSessionId }, 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: oldSessionId,
|
||||
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(oldSessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: oldSessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const oldState = ralphService.getActiveState(oldSessionId)
|
||||
expect(oldState).toBeNull()
|
||||
|
||||
const newState = ralphService.getActiveState(newSessionId)
|
||||
expect(newState).not.toBeNull()
|
||||
expect(newState?.iteration).toBe(2)
|
||||
expect(newState?.sessionId).toBe(newSessionId)
|
||||
})
|
||||
|
||||
test('rotates session on auditing phase completion', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const oldSessionId = 'old-session-id'
|
||||
const newSessionId = 'new-session-id'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: 'test-session' }, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: [
|
||||
{
|
||||
info: { role: 'assistant' },
|
||||
parts: [{ type: 'text', text: 'No issues found.' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
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: newSessionId }, error: undefined }),
|
||||
delete: async () => ({ data: undefined, error: undefined }),
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
messages: async () => ({
|
||||
data: [
|
||||
{
|
||||
info: { role: 'assistant' },
|
||||
parts: [{ type: 'text', text: 'No issues found.' }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
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: oldSessionId,
|
||||
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(oldSessionId, state)
|
||||
|
||||
await handler.onEvent({
|
||||
event: {
|
||||
type: 'session.idle',
|
||||
properties: { sessionID: oldSessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const newState = ralphService.getActiveState(newSessionId)
|
||||
expect(newState).not.toBeNull()
|
||||
expect(newState?.phase).toBe('coding')
|
||||
expect(newState?.iteration).toBe(2)
|
||||
expect(newState?.sessionId).toBe(newSessionId)
|
||||
})
|
||||
|
||||
test('falls back to existing session when rotation fails', async () => {
|
||||
const { createRalphEventHandler } = require('../src/hooks/ralph')
|
||||
const sessionId = 'existing-session-id'
|
||||
|
||||
const mockClient = {
|
||||
session: {
|
||||
promptAsync: async () => ({ data: undefined, error: undefined }),
|
||||
create: async () => ({ data: { id: 'test-session' }, 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: undefined, error: 'connection failed' }),
|
||||
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.idle',
|
||||
properties: { sessionID: sessionId },
|
||||
},
|
||||
})
|
||||
|
||||
const existingState = ralphService.getActiveState(sessionId)
|
||||
expect(existingState).not.toBeNull()
|
||||
expect(existingState?.iteration).toBe(2)
|
||||
expect(existingState?.sessionId).toBe(sessionId)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
export PATH="/opt/bun/bin:/opt/opencode/bin:/usr/local/bin:$PATH"
|
||||
export BUN_INSTALL="/opt/bun"
|
||||
|
||||
START_COMMAND="bun backend/src/index.ts"
|
||||
WORK_DIR="/opt/opencode-manager"
|
||||
export MAXIMIZE="true"
|
||||
export MAXIMIZE_NAME="Chromium"
|
||||
MAXIMIZE_SCRIPT=$STARTUPDIR/maximize_window.sh
|
||||
|
||||
/usr/bin/desktop_ready
|
||||
|
||||
if [ -z "$AUTH_SECRET" ]; then
|
||||
export AUTH_SECRET=$(openssl rand -base64 32)
|
||||
fi
|
||||
|
||||
BROWSER=$(which chromium-browser || which chromium || which google-chrome || echo "")
|
||||
|
||||
set +e
|
||||
while true; do
|
||||
if ! pgrep -f "$START_COMMAND" > /dev/null; then
|
||||
cd "$WORK_DIR"
|
||||
$START_COMMAND > /tmp/opencode-manager.log 2>&1 &
|
||||
sleep 3
|
||||
if [ -n "$BROWSER" ]; then
|
||||
if ! pgrep -f "$BROWSER" > /dev/null; then
|
||||
bash ${MAXIMIZE_SCRIPT} 2>/dev/null &
|
||||
$BROWSER \
|
||||
--no-first-run \
|
||||
--no-default-browser-check \
|
||||
--disable-gpu \
|
||||
--start-maximized \
|
||||
--window-position=0,0 \
|
||||
"http://localhost:5003" &
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
Reference in new issue
Block a user