From 4e9f27ab0b72e6ad3cadb07b56a89e9389c0512f Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 10:22:08 -0400 Subject: [PATCH] section 7: Phase 7: Goal recovery on restart and outcome notifications --- backend/src/index.ts | 17 +- backend/src/services/notification.ts | 96 +++++++++- backend/src/services/session-goals.ts | 87 ++++++++- .../test/helpers/fake-session-goal-client.ts | 12 ++ .../services/notification-service.test.ts | 154 ++++++++++++++++ backend/test/services/session-goals.test.ts | 174 +++++++++++++++++- shared/src/schemas/notifications.ts | 2 + 7 files changed, 535 insertions(+), 7 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 1fbca0b8..f33e8a8a 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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(), ) diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index 76f20038..d2884d0b 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -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([ NotificationEventType.SESSION_FAILED, ]); +const GOAL_OUTCOME_TITLES: Record = { + active: "Goal active", + paused: "Goal paused", + completed: "Goal completed", + blocked: "Goal blocked", + stopped: "Goal stopped", +}; + +const GOAL_STOP_REASON_LABELS: Record = { + 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 { + 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 { await this.sendToUser(userId, { title: "Test Notification", diff --git a/backend/src/services/session-goals.ts b/backend/src/services/session-goals.ts index 95a25908..b7c0a45d 100644 --- a/backend/src/services/session-goals.ts +++ b/backend/src/services/session-goals.ts @@ -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 = { ok: true; value: T } | { ok: false } @@ -79,6 +85,7 @@ export function toSessionGoal(record: SessionGoalRecord): SessionGoal { export class SessionGoalService { private readonly goalBySession = new Map() private readonly auditTimers = new Map>() + private readonly recoveryTimers = new Map>() private readonly auditing = new Set() private readonly auditRequested = new Set() private readonly auditGeneration = new Map() @@ -102,6 +109,76 @@ export class SessionGoalService { } } + async recoverOpenGoals(): Promise { + 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 { + 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 { + 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 { 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 { diff --git a/backend/test/helpers/fake-session-goal-client.ts b/backend/test/helpers/fake-session-goal-client.ts index 1e810305..7acbd483 100644 --- a/backend/test/helpers/fake-session-goal-client.ts +++ b/backend/test/helpers/fake-session-goal-client.ts @@ -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(Object.entries(options.tokens ?? {})) const messages = new Map(Object.entries(options.messages ?? {})) const busySessions = new Set(options.busySessions ?? []) + const missingSessions = new Set() 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) + } + }, } } diff --git a/backend/test/services/notification-service.test.ts b/backend/test/services/notification-service.test.ts index 32a769d5..14f8bc89 100644 --- a/backend/test/services/notification-service.test.ts +++ b/backend/test/services/notification-service.test.ts @@ -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) + }) +}) diff --git a/backend/test/services/session-goals.test.ts b/backend/test/services/session-goals.test.ts index 0331a2dd..f312c5e7 100644 --- a/backend/test/services/session-goals.test.ts +++ b/backend/test/services/session-goals.test.ts @@ -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) + }) +}) diff --git a/shared/src/schemas/notifications.ts b/shared/src/schemas/notifications.ts index 2b5304cf..fcd21e71 100644 --- a/shared/src/schemas/notifications.ts +++ b/shared/src/schemas/notifications.ts @@ -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, }, };