mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
|
||||
import { usePermissions, useQuestions } from '@/contexts/EventContext'
|
||||
import { getQuestionText } from '@opencode-manager/shared/notifications'
|
||||
import { Bell, HelpCircle } from 'lucide-react'
|
||||
|
||||
interface NotificationsSheetProps {
|
||||
@@ -87,7 +88,7 @@ export function NotificationsSheet({ isOpen, onClose }: NotificationsSheetProps)
|
||||
className="flex flex-col items-start gap-1 p-3 rounded-lg border border-border hover:bg-accent transition-colors text-left w-full"
|
||||
>
|
||||
<span className="font-medium text-foreground">
|
||||
{currentQuestion.questions?.[0]?.question || 'Question'}
|
||||
{getQuestionText(currentQuestion) || 'Question'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate w-full">
|
||||
Tap to view
|
||||
|
||||
@@ -9,32 +9,10 @@ import {
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { PermissionRequest, PermissionResponse } from '@/api/types'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import { getPermissionLabel, getPermissionDetail } from '@opencode-manager/shared/notifications'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
type PermissionConfig = components['schemas']['PermissionConfig']
|
||||
type KnownPermissionType = keyof Exclude<PermissionConfig, string> & string
|
||||
|
||||
const PERMISSION_LABELS: Record<KnownPermissionType, string> = {
|
||||
read: 'Read File',
|
||||
edit: 'Edit File',
|
||||
glob: 'Search Files',
|
||||
grep: 'Search Content',
|
||||
list: 'List Directory',
|
||||
bash: 'Run Command',
|
||||
task: 'Run Task',
|
||||
external_directory: 'External Access',
|
||||
todowrite: 'Write Todo',
|
||||
todoread: 'Read Todo',
|
||||
question: 'Ask Question',
|
||||
webfetch: 'Fetch URL',
|
||||
websearch: 'Web Search',
|
||||
codesearch: 'Code Search',
|
||||
lsp: 'LSP Action',
|
||||
doom_loop: 'Repeated Action',
|
||||
}
|
||||
|
||||
interface PermissionRequestDialogProps {
|
||||
permission: PermissionRequest | null
|
||||
pendingCount: number
|
||||
@@ -46,76 +24,6 @@ interface PermissionRequestDialogProps {
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
function getPermissionTypeLabel(type: string): string {
|
||||
if (type in PERMISSION_LABELS) {
|
||||
return PERMISSION_LABELS[type as KnownPermissionType]
|
||||
}
|
||||
return type.charAt(0).toUpperCase() + type.slice(1)
|
||||
}
|
||||
|
||||
function getPermissionDetails(permission: PermissionRequest): { primary: string; secondary?: string } {
|
||||
const metadata = permission.metadata || {}
|
||||
|
||||
switch (permission.permission) {
|
||||
case 'bash': {
|
||||
const command = metadata.command as string | undefined
|
||||
if (command) {
|
||||
return { primary: command }
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'edit':
|
||||
case 'write': {
|
||||
const filePath = metadata.filePath as string | undefined
|
||||
const diff = metadata.diff as string | undefined
|
||||
if (filePath) {
|
||||
return {
|
||||
primary: filePath,
|
||||
secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'webfetch': {
|
||||
const url = metadata.url as string | undefined
|
||||
if (url) {
|
||||
return { primary: url }
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'external_directory': {
|
||||
const command = metadata.command as string | undefined
|
||||
const filepath = metadata.filepath as string | undefined
|
||||
if (command) {
|
||||
return { primary: command }
|
||||
}
|
||||
if (filepath) {
|
||||
return { primary: filepath }
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'doom_loop': {
|
||||
const tool = metadata.tool as string | undefined
|
||||
const input = metadata.input
|
||||
if (tool) {
|
||||
return {
|
||||
primary: `Tool: ${tool}`,
|
||||
secondary: input ? JSON.stringify(input, null, 2).slice(0, 300) : undefined
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const patterns = permission.patterns || []
|
||||
|
||||
if (patterns.length > 0) {
|
||||
return { primary: patterns.join('\n') }
|
||||
}
|
||||
|
||||
return { primary: '' }
|
||||
}
|
||||
|
||||
export function PermissionRequestDialog({
|
||||
permission,
|
||||
pendingCount,
|
||||
@@ -145,8 +53,8 @@ export function PermissionRequestDialog({
|
||||
}
|
||||
}
|
||||
|
||||
const typeLabel = getPermissionTypeLabel(permission.permission)
|
||||
const details = getPermissionDetails(permission)
|
||||
const typeLabel = getPermissionLabel(permission.permission)
|
||||
const details = getPermissionDetail(permission)
|
||||
const hasMultiple = pendingCount > 1
|
||||
const displaySessionName = sessionTitle || `Session ${permission.sessionID.slice(0, 8)}...`
|
||||
|
||||
|
||||
+2
-1
@@ -14,7 +14,8 @@
|
||||
"./config/defaults": "./src/config/defaults.ts",
|
||||
"./config/env": "./src/config/env.ts",
|
||||
"./config/client": "./src/config/client.ts",
|
||||
"./utils": "./src/utils/index.ts"
|
||||
"./utils": "./src/utils/index.ts",
|
||||
"./notifications": "./src/notifications/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonc-parser": "^3.3.1",
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './config'
|
||||
export * from './schemas'
|
||||
export * from './types'
|
||||
export * from './utils'
|
||||
export * from './notifications'
|
||||
@@ -0,0 +1,93 @@
|
||||
const PERMISSION_LABELS: Record<string, string> = {
|
||||
read: 'Read File',
|
||||
edit: 'Edit File',
|
||||
write: 'Write File',
|
||||
glob: 'Search Files',
|
||||
grep: 'Search Content',
|
||||
list: 'List Directory',
|
||||
bash: 'Run Command',
|
||||
task: 'Run Task',
|
||||
external_directory: 'External Access',
|
||||
todowrite: 'Write Todo',
|
||||
todoread: 'Read Todo',
|
||||
question: 'Ask Question',
|
||||
webfetch: 'Fetch URL',
|
||||
websearch: 'Web Search',
|
||||
codesearch: 'Code Search',
|
||||
lsp: 'LSP Action',
|
||||
doom_loop: 'Repeated Action',
|
||||
}
|
||||
|
||||
export function getPermissionLabel(permission: string): string {
|
||||
if (!permission) return 'Approval'
|
||||
return PERMISSION_LABELS[permission] ?? permission.charAt(0).toUpperCase() + permission.slice(1)
|
||||
}
|
||||
|
||||
interface PermissionLike {
|
||||
permission?: unknown
|
||||
metadata?: unknown
|
||||
patterns?: unknown
|
||||
}
|
||||
|
||||
export interface PermissionDetail {
|
||||
primary: string
|
||||
secondary?: string
|
||||
}
|
||||
|
||||
export function getPermissionDetail(input: PermissionLike): PermissionDetail {
|
||||
const permission = typeof input.permission === 'string' ? input.permission : ''
|
||||
const metadata = (input.metadata && typeof input.metadata === 'object' ? input.metadata : {}) as Record<string, unknown>
|
||||
const str = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined)
|
||||
|
||||
switch (permission) {
|
||||
case 'bash': {
|
||||
const command = str(metadata.command)
|
||||
if (command) return { primary: command }
|
||||
break
|
||||
}
|
||||
case 'edit':
|
||||
case 'write': {
|
||||
const filePath = str(metadata.filePath)
|
||||
if (filePath) {
|
||||
const diff = str(metadata.diff)
|
||||
return { primary: filePath, secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined }
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'webfetch': {
|
||||
const url = str(metadata.url)
|
||||
if (url) return { primary: url }
|
||||
break
|
||||
}
|
||||
case 'external_directory': {
|
||||
const value = str(metadata.command) ?? str(metadata.filepath)
|
||||
if (value) return { primary: value }
|
||||
break
|
||||
}
|
||||
case 'doom_loop': {
|
||||
const tool = str(metadata.tool)
|
||||
if (tool) {
|
||||
const input2 = metadata.input
|
||||
return { primary: `Tool: ${tool}`, secondary: input2 ? JSON.stringify(input2, null, 2).slice(0, 300) : undefined }
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { primary: fallbackPattern(input) }
|
||||
}
|
||||
|
||||
function fallbackPattern(input: PermissionLike): string {
|
||||
const patterns = Array.isArray(input.patterns) ? input.patterns.filter((p): p is string => typeof p === 'string') : []
|
||||
return patterns.join('\n')
|
||||
}
|
||||
|
||||
interface QuestionLike {
|
||||
questions?: unknown
|
||||
}
|
||||
|
||||
export function getQuestionText(input: QuestionLike): string {
|
||||
const questions = Array.isArray(input.questions) ? input.questions : []
|
||||
const first = questions[0] as { question?: unknown } | undefined
|
||||
return first && typeof first.question === 'string' && first.question.length > 0 ? first.question : ''
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './format'
|
||||
Reference in new issue
Block a user