section 7: Phase 7: Goal recovery on restart and outcome notifications

This commit is contained in:
Chris Scott committed 2026-10-03 10:22:08 -04:00
1 parent 40bbe5aff3
commit 4e9f27ab0b
7 files changed
+535 -7

No files matched your search

+16 -1
View File
@@ -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(),
)
+92 -4
View File
@@ -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",
+86 -1
View File
@@ -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 {