mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(notification): rich notification content with shared format helpers (#245)
* loop: notification-format completed after 2 iterations * refactor: deduplicate permission display logic into shared package
This commit is contained in:
1 parent
dbd6866682
commit
626a4c42d1
8 files changed
+313
-140
No files matched your search
@@ -7,6 +7,11 @@ import {
|
||||
NotificationEventType,
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
} from "@opencode-manager/shared/schemas";
|
||||
import {
|
||||
getPermissionLabel,
|
||||
getPermissionDetail,
|
||||
getQuestionText,
|
||||
} from "@opencode-manager/shared/notifications";
|
||||
import { SettingsService } from "./settings";
|
||||
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
|
||||
import { getRepoByLocalPath, getRepoBySourcePath } from "../db/queries";
|
||||
@@ -21,21 +26,28 @@ interface VapidConfig {
|
||||
|
||||
const EVENT_CONFIG: Record<
|
||||
string,
|
||||
{ preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events; title: string; bodyFn: (props: Record<string, unknown>) => string }
|
||||
{
|
||||
preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events;
|
||||
titleFn: (props: Record<string, unknown>) => string;
|
||||
bodyFn: (props: Record<string, unknown>) => string;
|
||||
}
|
||||
> = {
|
||||
[NotificationEventType.PERMISSION_ASKED]: {
|
||||
preferencesKey: "permissionAsked",
|
||||
title: "Permission Required",
|
||||
bodyFn: () => "OpenCode needs your approval to continue",
|
||||
titleFn: (props) =>
|
||||
getPermissionLabel(
|
||||
typeof props.permission === "string" ? props.permission : ""
|
||||
),
|
||||
bodyFn: (props) => getPermissionDetail(props).primary || "Approval required",
|
||||
},
|
||||
[NotificationEventType.QUESTION_ASKED]: {
|
||||
preferencesKey: "questionAsked",
|
||||
title: "Question from Agent",
|
||||
bodyFn: () => "The agent has a question for you",
|
||||
titleFn: () => "Question",
|
||||
bodyFn: (props) => getQuestionText(props) || "A question needs your answer",
|
||||
},
|
||||
[NotificationEventType.SESSION_ERROR]: {
|
||||
preferencesKey: "sessionError",
|
||||
title: "Session Error",
|
||||
titleFn: () => "Error",
|
||||
bodyFn: (props) => {
|
||||
const error = props.error as { message?: string } | undefined;
|
||||
return error?.message ?? "A session encountered an error";
|
||||
@@ -43,11 +55,52 @@ const EVENT_CONFIG: Record<
|
||||
},
|
||||
[NotificationEventType.SESSION_IDLE]: {
|
||||
preferencesKey: "sessionIdle",
|
||||
title: "Session Complete",
|
||||
titleFn: () => "Session complete",
|
||||
bodyFn: () => "Your session has finished processing",
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_BODY_LENGTH = 140;
|
||||
|
||||
export function buildEventNotificationPayload(
|
||||
event: SSEEvent,
|
||||
context: {
|
||||
repoName?: string;
|
||||
repoId?: number;
|
||||
sessionId?: string;
|
||||
directory?: string;
|
||||
url: string;
|
||||
}
|
||||
): PushNotificationPayload | null {
|
||||
const config = EVENT_CONFIG[event.type];
|
||||
if (!config) return null;
|
||||
|
||||
const action = config.titleFn(event.properties);
|
||||
const title = context.repoName
|
||||
? `${context.repoName}: ${action}`
|
||||
: action;
|
||||
|
||||
const rawBody = config.bodyFn(event.properties);
|
||||
const body =
|
||||
rawBody.length > MAX_BODY_LENGTH
|
||||
? `${rawBody.slice(0, MAX_BODY_LENGTH - 1)}…`
|
||||
: rawBody;
|
||||
|
||||
return {
|
||||
title,
|
||||
body,
|
||||
tag: `${event.type}-${context.sessionId ?? "global"}`,
|
||||
data: {
|
||||
eventType: event.type,
|
||||
sessionId: context.sessionId,
|
||||
directory: context.directory,
|
||||
repoId: context.repoId,
|
||||
repoName: context.repoName,
|
||||
url: context.url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export class NotificationService {
|
||||
private vapidConfig: VapidConfig | null = null;
|
||||
private settingsService: SettingsService;
|
||||
@@ -205,6 +258,34 @@ export class NotificationService {
|
||||
if (!this.isConfigured()) return;
|
||||
|
||||
const userIds = this.getAllUserIds();
|
||||
if (userIds.length === 0) return;
|
||||
|
||||
let notificationUrl = "/";
|
||||
let repoName = "";
|
||||
let repoId: number | undefined;
|
||||
|
||||
if (_directory) {
|
||||
const reposBasePath = getReposPath();
|
||||
const localPath = path.relative(reposBasePath, _directory);
|
||||
const repo = getRepoBySourcePath(this.db, path.resolve(_directory)) ?? getRepoByLocalPath(this.db, localPath);
|
||||
|
||||
if (repo) {
|
||||
repoId = repo.id;
|
||||
repoName = path.basename(repo.localPath);
|
||||
notificationUrl = sessionId
|
||||
? `/repos/${repo.id}/sessions/${sessionId}`
|
||||
: `/repos/${repo.id}`;
|
||||
}
|
||||
}
|
||||
|
||||
const payload = buildEventNotificationPayload(event, {
|
||||
repoName: repoName || undefined,
|
||||
repoId,
|
||||
sessionId,
|
||||
directory: _directory,
|
||||
url: notificationUrl,
|
||||
});
|
||||
if (!payload) return;
|
||||
|
||||
for (const userId of userIds) {
|
||||
const settings = this.settingsService.getSettings(userId);
|
||||
@@ -214,42 +295,6 @@ export class NotificationService {
|
||||
if (!notifPrefs.enabled) continue;
|
||||
if (!notifPrefs.events[config.preferencesKey]) continue;
|
||||
|
||||
let notificationUrl = "/";
|
||||
let repoName = "";
|
||||
let repoId: number | undefined;
|
||||
|
||||
if (_directory) {
|
||||
const reposBasePath = getReposPath();
|
||||
const localPath = path.relative(reposBasePath, _directory);
|
||||
const repo = getRepoBySourcePath(this.db, path.resolve(_directory)) ?? getRepoByLocalPath(this.db, localPath);
|
||||
|
||||
if (repo) {
|
||||
repoId = repo.id;
|
||||
repoName = path.basename(repo.localPath);
|
||||
if (sessionId) {
|
||||
notificationUrl = `/repos/${repo.id}/sessions/${sessionId}`;
|
||||
} else {
|
||||
notificationUrl = `/repos/${repo.id}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const body = config.bodyFn(event.properties);
|
||||
|
||||
const payload: PushNotificationPayload = {
|
||||
title: repoName ? `[${repoName.toUpperCase()}] ${config.title}` : config.title,
|
||||
body: body,
|
||||
tag: `${event.type}-${sessionId ?? "global"}`,
|
||||
data: {
|
||||
eventType: event.type,
|
||||
sessionId,
|
||||
directory: _directory,
|
||||
repoId,
|
||||
repoName,
|
||||
url: notificationUrl,
|
||||
},
|
||||
};
|
||||
|
||||
await this.sendToUser(userId, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getPermissionLabel, getPermissionDetail, getQuestionText } from '@opencode-manager/shared/notifications'
|
||||
import { buildEventNotificationPayload } from '../../src/services/notification'
|
||||
|
||||
const ctx = { repoName: 'oc-manager', repoId: 1, sessionId: 'ses_1', directory: '/abs/repo', url: '/repos/1/sessions/ses_1' }
|
||||
|
||||
describe('getPermissionLabel', () => {
|
||||
it('maps known permission types to friendly labels', () => {
|
||||
expect(getPermissionLabel('bash')).toBe('Run Command')
|
||||
expect(getPermissionLabel('webfetch')).toBe('Fetch URL')
|
||||
expect(getPermissionLabel('edit')).toBe('Edit File')
|
||||
})
|
||||
it('capitalizes unknown types', () => {
|
||||
expect(getPermissionLabel('frobnicate')).toBe('Frobnicate')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPermissionDetail', () => {
|
||||
it('returns the bash command', () => {
|
||||
expect(getPermissionDetail({ permission: 'bash', metadata: { command: 'rm -rf node_modules' } }).primary).toBe('rm -rf node_modules')
|
||||
})
|
||||
it('returns the edited file path with a diff secondary', () => {
|
||||
const detail = getPermissionDetail({ permission: 'edit', metadata: { filePath: 'src/index.ts', diff: 'a\nb' } })
|
||||
expect(detail.primary).toBe('src/index.ts')
|
||||
expect(detail.secondary).toBe('a\nb')
|
||||
})
|
||||
it('returns the fetched url', () => {
|
||||
expect(getPermissionDetail({ permission: 'webfetch', metadata: { url: 'https://example.com' } }).primary).toBe('https://example.com')
|
||||
})
|
||||
it('falls back to patterns when metadata is missing', () => {
|
||||
expect(getPermissionDetail({ permission: 'bash', patterns: ['git *'] }).primary).toBe('git *')
|
||||
})
|
||||
it('returns empty primary when no detail available', () => {
|
||||
expect(getPermissionDetail({ permission: 'bash' }).primary).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getQuestionText', () => {
|
||||
it('returns the first question text', () => {
|
||||
expect(getQuestionText({ questions: [{ question: 'Deploy to prod?' }] })).toBe('Deploy to prod?')
|
||||
})
|
||||
it('returns empty string when no questions', () => {
|
||||
expect(getQuestionText({ questions: [] })).toBe('')
|
||||
expect(getQuestionText({})).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildEventNotificationPayload', () => {
|
||||
it('formats a bash permission as "{repo}: Run Command" + command body', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'permission.asked', properties: { permission: 'bash', metadata: { command: 'rm -rf node_modules' }, patterns: ['rm *'] } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.title).toBe('oc-manager: Run Command')
|
||||
expect(p.body).toBe('rm -rf node_modules')
|
||||
expect(p.tag).toBe('permission.asked-ses_1')
|
||||
expect(p.data?.eventType).toBe('permission.asked')
|
||||
})
|
||||
|
||||
it('formats an edit permission with the file path', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'permission.asked', properties: { permission: 'edit', metadata: { filePath: 'src/index.ts' } } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.title).toBe('oc-manager: Edit File')
|
||||
expect(p.body).toBe('src/index.ts')
|
||||
})
|
||||
|
||||
it('uses "Approval required" body when no detail is available', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'permission.asked', properties: { permission: 'bash' } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.body).toBe('Approval required')
|
||||
})
|
||||
|
||||
it('formats a question as "{repo}: Question" + question text body', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'question.asked', properties: { questions: [{ question: 'Deploy to prod?' }] } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.title).toBe('oc-manager: Question')
|
||||
expect(p.body).toBe('Deploy to prod?')
|
||||
})
|
||||
|
||||
it('formats session.error as "{repo}: Error" + error message', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'session.error', properties: { error: { message: 'boom' } } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.title).toBe('oc-manager: Error')
|
||||
expect(p.body).toBe('boom')
|
||||
})
|
||||
|
||||
it('formats session.idle as "{repo}: Session complete"', () => {
|
||||
const p = buildEventNotificationPayload({ type: 'session.idle', properties: {} }, ctx)!
|
||||
expect(p.title).toBe('oc-manager: Session complete')
|
||||
expect(p.body).toBe('Your session has finished processing')
|
||||
})
|
||||
|
||||
it('omits the repo prefix when no repoName is provided', () => {
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'permission.asked', properties: { permission: 'bash', metadata: { command: 'ls' } } },
|
||||
{ url: '/' },
|
||||
)!
|
||||
expect(p.title).toBe('Run Command')
|
||||
expect(p.tag).toBe('permission.asked-global')
|
||||
})
|
||||
|
||||
it('returns null for unknown event types', () => {
|
||||
expect(buildEventNotificationPayload({ type: 'session.created', properties: {} }, ctx)).toBeNull()
|
||||
})
|
||||
|
||||
it('truncates bodies longer than 140 chars with an ellipsis', () => {
|
||||
const long = 'x'.repeat(300)
|
||||
const p = buildEventNotificationPayload(
|
||||
{ type: 'permission.asked', properties: { permission: 'bash', metadata: { command: long } } },
|
||||
ctx,
|
||||
)!
|
||||
expect(p.body.length).toBeLessThanOrEqual(140)
|
||||
expect(p.body.endsWith('…')).toBe(true)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user