mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
section 7: Phase 7: Goal recovery on restart and outcome notifications
This commit is contained in:
1 parent
40bbe5aff3
commit
4e9f27ab0b
7 files changed
+535
-7
No files matched your search
+16
-1
@@ -232,7 +232,13 @@ const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db)
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, settingsServiceForSchedules)
|
||||
const sessionGoalService = new SessionGoalService(db, openCodeClient, settingsServiceForSchedules)
|
||||
const sessionGoalService = new SessionGoalService(db, openCodeClient, settingsServiceForSchedules, {
|
||||
onOutcome: (goal) => {
|
||||
void notificationService.notifyGoalOutcome(goal).catch((error) => {
|
||||
logger.error('Goal outcome notification error:', error)
|
||||
})
|
||||
},
|
||||
})
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
@@ -249,6 +255,11 @@ notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto'
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
if (event.type !== 'session.idle' || !sessionId) return false
|
||||
return sessionGoalService.hasActiveGoal(sessionId)
|
||||
})
|
||||
|
||||
if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
if (!ENV.VAPID.SUBJECT) {
|
||||
logger.warn('VAPID_SUBJECT is not set — push notifications require a mailto: subject (e.g. mailto:you@example.com)')
|
||||
@@ -272,6 +283,10 @@ sseAggregator.setPendingActionsFetcher(openCodeClient)
|
||||
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
sseAggregator.start()
|
||||
|
||||
void sessionGoalService.recoverOpenGoals().catch((error) => {
|
||||
logger.error('Session goal recovery error:', error)
|
||||
})
|
||||
|
||||
sseAggregator.setScheduledSessionsResolver(
|
||||
() => scheduleService.getActiveRunSessions(),
|
||||
)
|
||||
|
||||
@@ -6,6 +6,9 @@ import type { PushNotificationPayload } from "@opencode-manager/shared/types";
|
||||
import {
|
||||
NotificationEventType,
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type SessionGoal,
|
||||
type SessionGoalStatus,
|
||||
type SessionGoalStopReason,
|
||||
} from "@opencode-manager/shared/schemas";
|
||||
import {
|
||||
getPermissionLabel,
|
||||
@@ -77,6 +80,55 @@ const RUN_OUTCOME_EVENTS = new Set<string>([
|
||||
NotificationEventType.SESSION_FAILED,
|
||||
]);
|
||||
|
||||
const GOAL_OUTCOME_TITLES: Record<SessionGoalStatus, string> = {
|
||||
active: "Goal active",
|
||||
paused: "Goal paused",
|
||||
completed: "Goal completed",
|
||||
blocked: "Goal blocked",
|
||||
stopped: "Goal stopped",
|
||||
};
|
||||
|
||||
const GOAL_STOP_REASON_LABELS: Record<SessionGoalStopReason, string> = {
|
||||
cancelled: "Cancelled",
|
||||
user_paused: "Paused by user",
|
||||
continuation_limit: "Continuation limit reached",
|
||||
token_budget: "Token budget reached",
|
||||
turn_error: "Turn failed",
|
||||
interrupted: "Interrupted",
|
||||
audit_failed: "Audit failed",
|
||||
session_deleted: "Session deleted",
|
||||
};
|
||||
|
||||
function truncateNotificationBody(rawBody: string): string {
|
||||
return rawBody.length > MAX_BODY_LENGTH
|
||||
? `${rawBody.slice(0, MAX_BODY_LENGTH - 1)}…`
|
||||
: rawBody;
|
||||
}
|
||||
|
||||
function truncateWithEllipsis(text: string, maxLength: number): string {
|
||||
if (maxLength <= 0) return "";
|
||||
if (text.length <= maxLength) return text;
|
||||
if (maxLength === 1) return "…";
|
||||
return `${text.slice(0, maxLength - 1)}…`;
|
||||
}
|
||||
|
||||
function buildGoalOutcomeBody(goal: SessionGoal, repoName: string | undefined): string {
|
||||
const reason = goal.stopReason
|
||||
? GOAL_STOP_REASON_LABELS[goal.stopReason]
|
||||
: goal.lastReason?.trim() || undefined;
|
||||
const prefix = repoName ? `${repoName} · ` : "";
|
||||
const separator = " — ";
|
||||
|
||||
const reasonBudget = Math.max(0, MAX_BODY_LENGTH - prefix.length - separator.length);
|
||||
const boundedReason = reason ? truncateWithEllipsis(reason, reasonBudget) : "";
|
||||
const suffix = boundedReason ? `${separator}${boundedReason}` : "";
|
||||
|
||||
const objectiveBudget = Math.max(0, MAX_BODY_LENGTH - prefix.length - suffix.length);
|
||||
const objective = truncateWithEllipsis(goal.objective, objectiveBudget);
|
||||
|
||||
return truncateNotificationBody(`${prefix}${objective}${suffix}`);
|
||||
}
|
||||
|
||||
function resolveEventSessionId(event: SSEEvent): string | undefined {
|
||||
if (event.type === NotificationEventType.FORM_CREATED) {
|
||||
return event.data.form.sessionID;
|
||||
@@ -117,10 +169,7 @@ export function buildEventNotificationPayload(
|
||||
const rawBody = context.repoName
|
||||
? `${context.repoName} · ${detail}`
|
||||
: detail;
|
||||
const body =
|
||||
rawBody.length > MAX_BODY_LENGTH
|
||||
? `${rawBody.slice(0, MAX_BODY_LENGTH - 1)}…`
|
||||
: rawBody;
|
||||
const body = truncateNotificationBody(rawBody);
|
||||
|
||||
return {
|
||||
title,
|
||||
@@ -364,6 +413,45 @@ export class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
async notifyGoalOutcome(goal: SessionGoal): Promise<void> {
|
||||
if (!this.isConfigured()) return;
|
||||
|
||||
const userIds = this.getAllUserIds();
|
||||
if (userIds.length === 0) return;
|
||||
|
||||
const repo = goal.directory
|
||||
? await this.resolveRepoForDirectory(goal.directory)
|
||||
: null;
|
||||
const repoName = repo ? getRepoName(repo) : undefined;
|
||||
|
||||
const payload: PushNotificationPayload = {
|
||||
title: GOAL_OUTCOME_TITLES[goal.status],
|
||||
body: buildGoalOutcomeBody(goal, repoName),
|
||||
tag: `session-goal-${goal.id}`,
|
||||
timestamp: Date.now(),
|
||||
renotify: true,
|
||||
data: {
|
||||
eventType: "session.goal.outcome",
|
||||
sessionId: goal.sessionId,
|
||||
directory: goal.directory,
|
||||
repoId: repo?.id,
|
||||
repoName,
|
||||
url: buildNotificationUrl(repo, goal.sessionId),
|
||||
},
|
||||
};
|
||||
|
||||
for (const userId of userIds) {
|
||||
const settings = this.settingsService.getSettings(userId);
|
||||
const notifPrefs =
|
||||
settings.preferences.notifications ?? DEFAULT_NOTIFICATION_PREFERENCES;
|
||||
|
||||
if (!notifPrefs.enabled) continue;
|
||||
if (notifPrefs.events.goalOutcome === false) continue;
|
||||
|
||||
await this.sendToUser(userId, payload);
|
||||
}
|
||||
}
|
||||
|
||||
async sendTestNotification(userId: string): Promise<void> {
|
||||
await this.sendToUser(userId, {
|
||||
title: "Test Notification",
|
||||
|
||||
@@ -7,7 +7,12 @@ import {
|
||||
type SessionGoalTurnState,
|
||||
type StartSessionGoalRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { parseOpenCodeModelRef, sessionIDFromEvent, type ModelRef } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
isSessionNotFoundError,
|
||||
parseOpenCodeModelRef,
|
||||
sessionIDFromEvent,
|
||||
type ModelRef,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
getLatestSessionGoal,
|
||||
getSessionGoalById,
|
||||
@@ -33,6 +38,7 @@ import type { SSEEvent } from './sse-aggregator'
|
||||
const DEFAULT_QUIET_MS = 3000
|
||||
const BLOCKED_LIMIT = 3
|
||||
const AUDITOR_ATTEMPTS = 2
|
||||
const RECOVERY_RETRY_MS = 5000
|
||||
|
||||
type PrerequisiteResult<T> = { ok: true; value: T } | { ok: false }
|
||||
|
||||
@@ -79,6 +85,7 @@ export function toSessionGoal(record: SessionGoalRecord): SessionGoal {
|
||||
export class SessionGoalService {
|
||||
private readonly goalBySession = new Map<string, number>()
|
||||
private readonly auditTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
private readonly recoveryTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
private readonly auditing = new Set<number>()
|
||||
private readonly auditRequested = new Set<number>()
|
||||
private readonly auditGeneration = new Map<string, number>()
|
||||
@@ -102,6 +109,76 @@ export class SessionGoalService {
|
||||
}
|
||||
}
|
||||
|
||||
async recoverOpenGoals(): Promise<void> {
|
||||
for (const record of listOpenSessionGoals(this.db)) {
|
||||
if (record.status !== 'active' || record.turnState !== 'running') {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await this.recoverRunningGoal(record)
|
||||
} catch (error) {
|
||||
logger.error(`Session goal recovery failed for goal ${record.id}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async recoverRunningGoal(record: SessionGoalRecord): Promise<void> {
|
||||
const generation = this.currentAuditGeneration(record.sessionId)
|
||||
try {
|
||||
await this.openCodeClient.api.session.get({ sessionID: record.sessionId })
|
||||
} catch (error) {
|
||||
if (isSessionNotFoundError(error)) {
|
||||
this.finishGoal(record.id, 'stopped', 'session_deleted')
|
||||
return
|
||||
}
|
||||
logger.error(`Session goal recovery could not read session ${record.sessionId}:`, error)
|
||||
this.scheduleRecoveryRetry(record.sessionId, record.id, generation)
|
||||
return
|
||||
}
|
||||
|
||||
const busy = await this.readPrerequisite(record.id, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, record.sessionId),
|
||||
)
|
||||
if (!busy.ok) {
|
||||
this.scheduleRecoveryRetry(record.sessionId, record.id, generation)
|
||||
return
|
||||
}
|
||||
if (busy.value) {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(record.sessionId, record.id, 0)
|
||||
}
|
||||
|
||||
private scheduleRecoveryRetry(sessionId: string, goalId: number, generation: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
const timer = setTimeout(() => {
|
||||
this.recoveryTimers.delete(sessionId)
|
||||
void this.retryRecovery(sessionId, goalId, generation).catch((error) => {
|
||||
logger.error(`Session goal recovery retry failed for goal ${goalId}:`, error)
|
||||
})
|
||||
}, RECOVERY_RETRY_MS)
|
||||
this.recoveryTimers.set(sessionId, timer)
|
||||
}
|
||||
|
||||
private async retryRecovery(sessionId: string, goalId: number, generation: number): Promise<void> {
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
if (!record || record.status !== 'active' || record.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
if (this.currentAuditGeneration(sessionId) !== generation) {
|
||||
return
|
||||
}
|
||||
await this.recoverRunningGoal(record)
|
||||
}
|
||||
|
||||
private clearRecoveryTimer(sessionId: string): void {
|
||||
const timer = this.recoveryTimers.get(sessionId)
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
this.recoveryTimers.delete(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
async start(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
const defaults = this.settingsService.getSettings().preferences.sessionDefaults
|
||||
const maxContinuations =
|
||||
@@ -131,6 +208,10 @@ export class SessionGoalService {
|
||||
return record ? toSessionGoal(record) : null
|
||||
}
|
||||
|
||||
hasActiveGoal(sessionId: string): boolean {
|
||||
return getLatestSessionGoal(this.db, sessionId)?.status === 'active'
|
||||
}
|
||||
|
||||
pause(id: number): SessionGoal {
|
||||
return this.transitionWithOutcome(id, ['active'], { status: 'paused', stopReason: 'user_paused' })
|
||||
}
|
||||
@@ -226,6 +307,7 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
private scheduleAudit(sessionId: string, goalId: number, delay: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
this.clearAuditTimer(sessionId)
|
||||
const timer = setTimeout(() => {
|
||||
this.auditTimers.delete(sessionId)
|
||||
@@ -539,6 +621,9 @@ export class SessionGoalService {
|
||||
this.goalBySession.delete(record.sessionId)
|
||||
this.clearAuditTimer(record.sessionId)
|
||||
}
|
||||
if (record.status !== 'active') {
|
||||
this.clearRecoveryTimer(record.sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
private maybeInvalidateAudits(record: SessionGoalRecord, patch: SessionGoalPatch): void {
|
||||
|
||||
@@ -54,12 +54,14 @@ export interface FakeSessionGoalClient {
|
||||
setFailSessionGet(fail: boolean): void
|
||||
setFailSessionActive(fail: boolean): void
|
||||
setFailMessageList(fail: boolean): void
|
||||
setSessionMissing(sessionId: string, missing: boolean): void
|
||||
}
|
||||
|
||||
export function createFakeSessionGoalClient(options: FakeSessionGoalClientOptions = {}): FakeSessionGoalClient {
|
||||
const tokens = new Map<string, FakeSessionGoalTokens>(Object.entries(options.tokens ?? {}))
|
||||
const messages = new Map<string, SessionMessageInfo[]>(Object.entries(options.messages ?? {}))
|
||||
const busySessions = new Set<string>(options.busySessions ?? [])
|
||||
const missingSessions = new Set<string>()
|
||||
const promptCalls: FakeSessionGoalPromptCall[] = []
|
||||
const auditorCalls: FakeSessionGoalAuditorCall[] = []
|
||||
const pendingAuditorCalls: FakeSessionGoalAuditorDeferral[] = []
|
||||
@@ -78,6 +80,9 @@ export function createFakeSessionGoalClient(options: FakeSessionGoalClientOption
|
||||
api: {
|
||||
session: {
|
||||
get: async ({ sessionID }: { sessionID: string }) => {
|
||||
if (missingSessions.has(sessionID)) {
|
||||
throw Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
|
||||
}
|
||||
if (sessionGetFails) {
|
||||
throw new Error('upstream unavailable')
|
||||
}
|
||||
@@ -197,6 +202,13 @@ export function createFakeSessionGoalClient(options: FakeSessionGoalClientOption
|
||||
setFailMessageList: (fail) => {
|
||||
messageListFails = fail
|
||||
},
|
||||
setSessionMissing: (sessionId, missing) => {
|
||||
if (missing) {
|
||||
missingSessions.add(sessionId)
|
||||
} else {
|
||||
missingSessions.delete(sessionId)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,12 @@ import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SessionGoalService } from '../../src/services/session-goals'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator'
|
||||
import type { PushNotificationPayload } from '@opencode-manager/shared/types'
|
||||
import type { SessionGoal } from '@opencode-manager/shared/schemas'
|
||||
import { createFakeSessionGoalClient } from '../helpers/fake-session-goal-client'
|
||||
|
||||
const DIRECTORY = '/abs/repo'
|
||||
const USER_ID = 'user-1'
|
||||
@@ -181,3 +184,154 @@ describe('NotificationService.handleSSEEvent session routing', () => {
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('NotificationService goal outcomes', () => {
|
||||
beforeEach(() => {
|
||||
sseAggregator.shutdown()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function sessionIdleEvent(sessionID: string): SSEEvent {
|
||||
return {
|
||||
id: `evt_idle_${sessionID}`,
|
||||
created: 1700000000000,
|
||||
type: 'session.idle',
|
||||
location: { directory: DIRECTORY },
|
||||
data: { sessionID },
|
||||
} as SSEEvent
|
||||
}
|
||||
|
||||
const completedGoal: SessionGoal = {
|
||||
id: 1,
|
||||
sessionId: 'ses_goal',
|
||||
directory: DIRECTORY,
|
||||
objective: 'Ship the feature',
|
||||
status: 'completed',
|
||||
stopReason: null,
|
||||
turnState: 'running',
|
||||
continuationCount: 1,
|
||||
maxContinuations: 5,
|
||||
tokenBudget: null,
|
||||
tokensUsed: 0,
|
||||
consecutiveBlocked: 0,
|
||||
lastVerdict: 'done',
|
||||
lastReason: 'Objective achieved',
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
finishedAt: 3,
|
||||
}
|
||||
|
||||
it('notifies a goal outcome when the preference is unset', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome(completedGoal)
|
||||
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.title).toBe('Goal completed')
|
||||
expect(payload.body).toContain('Ship the feature')
|
||||
expect(payload.body).toContain('Objective achieved')
|
||||
expect(payload.tag).toBe('session-goal-1')
|
||||
expect(payload.data?.eventType).toBe('session.goal.outcome')
|
||||
expect(payload.data?.sessionId).toBe('ses_goal')
|
||||
expect(payload.data?.url).toBe('/repos/1/sessions/ses_goal')
|
||||
})
|
||||
|
||||
it('reports the stop reason instead of a stale verdict reason', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome({
|
||||
...completedGoal,
|
||||
id: 2,
|
||||
status: 'stopped',
|
||||
stopReason: 'token_budget',
|
||||
lastVerdict: 'continue',
|
||||
lastReason: 'Keep working on the tests',
|
||||
})
|
||||
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.title).toBe('Goal stopped')
|
||||
expect(payload.body).toContain('Token budget reached')
|
||||
expect(payload.body).not.toContain('Keep working on the tests')
|
||||
})
|
||||
|
||||
it('states the pause cause when a paused goal has no verdict reason', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome({
|
||||
...completedGoal,
|
||||
id: 3,
|
||||
status: 'paused',
|
||||
stopReason: 'audit_failed',
|
||||
lastVerdict: null,
|
||||
lastReason: null,
|
||||
})
|
||||
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.title).toBe('Goal paused')
|
||||
expect(payload.body).toContain('Audit failed')
|
||||
})
|
||||
|
||||
it('keeps the reason visible for a long objective within the body limit', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome({
|
||||
...completedGoal,
|
||||
id: 4,
|
||||
objective: 'Ship the entire feature '.repeat(20),
|
||||
status: 'stopped',
|
||||
stopReason: 'continuation_limit',
|
||||
})
|
||||
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.body.length).toBeLessThanOrEqual(140)
|
||||
expect(payload.body).toContain('Continuation limit reached')
|
||||
expect(payload.body).toContain('…')
|
||||
})
|
||||
|
||||
it('respects a disabled goalOutcome preference', async () => {
|
||||
const db = new Database(':memory:')
|
||||
const service = createService(db)
|
||||
new SettingsService(db).updateSettings(
|
||||
{
|
||||
notifications: {
|
||||
enabled: true,
|
||||
events: { permissionAsked: true, questionAsked: true, sessionError: true, sessionIdle: true, goalOutcome: false },
|
||||
},
|
||||
},
|
||||
USER_ID,
|
||||
)
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome(completedGoal)
|
||||
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('suppresses session.idle while the session goal is active and notifies once it ends', async () => {
|
||||
const db = new Database(':memory:')
|
||||
const service = createService(db)
|
||||
const fake = createFakeSessionGoalClient()
|
||||
const goalService = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
service.addEventSuppressor(async (event, sessionId) => {
|
||||
if (event.type !== 'session.idle' || !sessionId) return false
|
||||
return goalService.hasActiveGoal(sessionId)
|
||||
})
|
||||
const started = await goalService.start({ sessionId: 'ses_goal', directory: DIRECTORY, objective: 'Ship it' })
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, sessionIdleEvent('ses_goal'))
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
|
||||
goalService.pause(started.id)
|
||||
await service.handleSSEEvent(DIRECTORY, sessionIdleEvent('ses_goal'))
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getSessionGoalById, listOpenSessionGoals } from '../../src/db/session-goals'
|
||||
import { getSessionGoalById, listOpenSessionGoals, transitionSessionGoal } from '../../src/db/session-goals'
|
||||
import { SessionGoalService, type SessionGoalServiceOptions } from '../../src/services/session-goals'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import type { SSEEvent } from '../../src/services/sse-aggregator'
|
||||
@@ -895,3 +895,175 @@ describe('SessionGoalService audit loop', () => {
|
||||
expect(fake.promptCalls).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionGoalService recovery', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('resumes auditing a running goal on recovery and leaves a waiting goal alone', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
const waiting = await createService(db).start({ sessionId: 'ses_wait', directory: DIRECTORY, objective: 'Later' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient()
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(fake.auditorCalls).toHaveLength(1)
|
||||
expect(fake.auditorCalls[0]?.prompt).toContain('Ship it')
|
||||
expect(getSessionGoalById(db, waiting.id)?.turnState).toBe('waiting')
|
||||
expect(fake.auditorCalls[0]?.prompt).not.toContain('Later')
|
||||
})
|
||||
|
||||
it('leaves a running goal alone while the session is busy', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient()
|
||||
fake.setBusy('ses_run', true)
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
expect(getSessionGoalById(db, running.id)?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('stops a running goal when its session no longer exists', async () => {
|
||||
const outcomes: string[] = []
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient()
|
||||
fake.setSessionMissing('ses_run', true)
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), {
|
||||
quietMs: 0,
|
||||
onOutcome: (goal) => outcomes.push(goal.status),
|
||||
})
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
const latest = restarted.getLatest('ses_run')
|
||||
expect(latest?.status).toBe('stopped')
|
||||
expect(latest?.stopReason).toBe('session_deleted')
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
expect(outcomes).toEqual(['stopped'])
|
||||
})
|
||||
|
||||
it('reports whether a session has an active goal', async () => {
|
||||
const service = createService(db)
|
||||
const started = await service.start({ sessionId: 'ses_1', directory: DIRECTORY, objective: 'Ship it' })
|
||||
|
||||
expect(service.hasActiveGoal('ses_1')).toBe(true)
|
||||
expect(service.hasActiveGoal('ses_missing')).toBe(false)
|
||||
|
||||
service.pause(started.id)
|
||||
|
||||
expect(service.hasActiveGoal('ses_1')).toBe(false)
|
||||
})
|
||||
|
||||
it('retries recovery after a transient session lookup failure without session events', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient({ failSessionGet: true })
|
||||
fake.setAuditorReplies(['{"verdict":"done","reason":"finished"}'])
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
expect(restarted.getLatest('ses_run')?.status).toBe('active')
|
||||
|
||||
fake.setFailSessionGet(false)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(fake.auditorCalls).toHaveLength(1)
|
||||
expect(restarted.getLatest('ses_run')?.status).toBe('completed')
|
||||
})
|
||||
|
||||
it('retries recovery after a transient busy-check failure without session events', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient()
|
||||
fake.setAuditorReplies(['{"verdict":"done","reason":"finished"}'])
|
||||
fake.setFailSessionActive(true)
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
|
||||
fake.setFailSessionActive(false)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(fake.auditorCalls).toHaveLength(1)
|
||||
expect(restarted.getLatest('ses_run')?.status).toBe('completed')
|
||||
})
|
||||
|
||||
it('stops with session_deleted when the session disappears before the recovery retry', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient({ failSessionGet: true })
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
fake.setFailSessionGet(false)
|
||||
fake.setSessionMissing('ses_run', true)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
const latest = restarted.getLatest('ses_run')
|
||||
expect(latest?.status).toBe('stopped')
|
||||
expect(latest?.stopReason).toBe('session_deleted')
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not audit a goal paused during the recovery retry delay', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient({ failSessionGet: true })
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
restarted.pause(running.id)
|
||||
|
||||
fake.setFailSessionGet(false)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(restarted.getLatest('ses_run')?.status).toBe('paused')
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not audit a goal cancelled during the recovery retry delay', async () => {
|
||||
const running = await createService(db).start({ sessionId: 'ses_run', directory: DIRECTORY, objective: 'Ship it' })
|
||||
transitionSessionGoal(db, running.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const fake = createFakeSessionGoalClient({ failSessionGet: true })
|
||||
const restarted = new SessionGoalService(db, fake.client, new SettingsService(db), { quietMs: 0 })
|
||||
|
||||
await restarted.recoverOpenGoals()
|
||||
restarted.cancel(running.id)
|
||||
|
||||
fake.setFailSessionGet(false)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
const latest = restarted.getLatest('ses_run')
|
||||
expect(latest?.status).toBe('stopped')
|
||||
expect(latest?.stopReason).toBe('cancelled')
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -17,6 +17,7 @@ export const NotificationPreferencesSchema = z.object({
|
||||
questionAsked: z.boolean(),
|
||||
sessionError: z.boolean(),
|
||||
sessionIdle: z.boolean(),
|
||||
goalOutcome: z.boolean().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -27,6 +28,7 @@ export const DEFAULT_NOTIFICATION_PREFERENCES = {
|
||||
questionAsked: true,
|
||||
sessionError: true,
|
||||
sessionIdle: false,
|
||||
goalOutcome: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user