diff --git a/backend/src/index.ts b/backend/src/index.ts index 2d64f803..6bbbe7cb 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -231,6 +231,17 @@ const scheduleRunnerInstance = new ScheduleRunner(scheduleService) const notificationService = new NotificationService(db) const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, settingsServiceForSchedules) +sseAggregator.onEvent((directory, event) => { + sessionPermissionModeService.handleEvent(directory, event).catch((err) => { + logger.error('Session permission mode event handling error:', err) + }) +}) + +notificationService.addEventSuppressor(async (event, sessionId) => { + if (event.type !== 'permission.asked' || !sessionId) return false + return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto' +}) + 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)') diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index d64e2ab2..76f20038 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -139,9 +139,12 @@ export function buildEventNotificationPayload( }; } +type EventSuppressor = (event: SSEEvent, sessionId: string | undefined) => Promise; + export class NotificationService { private vapidConfig: VapidConfig | null = null; private settingsService: SettingsService; + private eventSuppressors: EventSuppressor[] = []; constructor(private db: Database) { this.settingsService = new SettingsService(db); @@ -178,6 +181,10 @@ export class NotificationService { return this.vapidConfig?.publicKey ?? null; } + addEventSuppressor(suppressor: EventSuppressor): void { + this.eventSuppressors.push(suppressor); + } + isConfigured(): boolean { return this.vapidConfig !== null; } @@ -321,6 +328,10 @@ export class NotificationService { if (sessionId && sseAggregator.isSessionBeingViewed(sessionId)) return; if (sessionId && sseAggregator.isSubagentSession(sessionId)) return; + for (const suppressor of this.eventSuppressors) { + if (await suppressor(event, sessionId)) return; + } + if (!this.isConfigured()) return; const userIds = this.getAllUserIds(); diff --git a/backend/src/services/session-permission-modes.ts b/backend/src/services/session-permission-modes.ts index 9b693f8d..cee972fc 100644 --- a/backend/src/services/session-permission-modes.ts +++ b/backend/src/services/session-permission-modes.ts @@ -3,9 +3,17 @@ import type { SessionPermissionMode, SessionPermissionModeState, } from '@opencode-manager/shared/schemas' +import { openCodeLocation, type PermissionRequest } from '@opencode-manager/shared/opencode' import { getScheduleRunBySessionId } from '../db/schedules' -import { getSessionPermissionMode, setSessionPermissionMode } from '../db/session-permission-modes' +import { + deleteSessionPermissionMode, + getSessionPermissionMode, + insertSessionPermissionModeIfAbsent, + setSessionPermissionMode, +} from '../db/session-permission-modes' +import { logger } from '../utils/logger' import type { OpenCodeClient } from './opencode/client' +import type { SSEEvent } from './sse-aggregator' import type { SettingsService } from './settings' const MAX_PARENT_HOPS = 10 @@ -46,28 +54,36 @@ export class SessionPermissionModeService { return current } + async handleEvent(directory: string, event: SSEEvent): Promise { + switch (event.type) { + case 'session.created': { + const { sessionID, parentID } = event.data + this.rememberParent(sessionID, parentID) + if (!parentID && this.defaultMode() === 'auto') { + insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto') + } + return + } + case 'permission.asked': { + const { sessionID, id } = event.data + await this.autoAcceptRequest(sessionID, id) + return + } + case 'session.deleted': { + const { sessionID } = event.data + this.parentBySession.delete(sessionID) + deleteSessionPermissionMode(this.db, sessionID) + return + } + } + } + async getEffectiveMode(sessionId: string): Promise { - let rootSessionId: string - - try { - rootSessionId = await this.resolveRootSessionId(sessionId) - } catch { - return { sessionId, rootSessionId: sessionId, mode: 'ask', inherited: false } - } - - const inherited = rootSessionId !== sessionId - - if (getScheduleRunBySessionId(this.db, rootSessionId)) { - return { sessionId, rootSessionId, mode: 'ask', inherited } - } - - const stored = getSessionPermissionMode(this.db, rootSessionId) - return { sessionId, rootSessionId, mode: stored ?? 'ask', inherited } + const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId) + return this.effectiveModeForRoot(sessionId, rootSessionId) } async setMode(sessionId: string, mode: SessionPermissionMode, directory: string): Promise { - void directory - const rootSessionId = await this.resolveRootSessionId(sessionId) if (rootSessionId !== sessionId) { throw new SessionPermissionModeError( @@ -84,6 +100,9 @@ export class SessionPermissionModeService { } setSessionPermissionMode(this.db, sessionId, mode) + if (mode === 'auto') { + await this.acceptPendingRequests(sessionId, directory) + } return { sessionId, rootSessionId, mode, inherited: false } } @@ -91,6 +110,77 @@ export class SessionPermissionModeService { return this.settingsService.getSettings().preferences.sessionDefaults?.permissionMode ?? 'ask' } + private effectiveModeForRoot( + sessionId: string, + rootSessionId: string | null, + ): SessionPermissionModeState { + if (!rootSessionId) { + return { sessionId, rootSessionId: sessionId, mode: 'ask', inherited: false } + } + + const inherited = rootSessionId !== sessionId + + if (getScheduleRunBySessionId(this.db, rootSessionId)) { + return { sessionId, rootSessionId, mode: 'ask', inherited } + } + + const stored = getSessionPermissionMode(this.db, rootSessionId) + return { sessionId, rootSessionId, mode: stored ?? 'ask', inherited } + } + + private async acceptPendingRequests(rootSessionId: string, directory: string): Promise { + let requests: PermissionRequest[] + try { + const result = await this.openCodeClient.api.permission.request.list(openCodeLocation(directory)) + requests = result.data + } catch (error) { + logger.error(`Failed to list pending permission requests for session ${rootSessionId}:`, error) + return + } + + for (const request of requests) { + await this.autoAcceptRequest(request.sessionID, request.id, rootSessionId) + } + } + + private async autoAcceptRequest( + sessionID: string, + requestID: string, + expectedRootSessionId?: string, + ): Promise { + const rootSessionId = await this.resolveRootSessionIdOrNull(sessionID) + if (!rootSessionId) { + return + } + + if (expectedRootSessionId !== undefined && rootSessionId !== expectedRootSessionId) { + return + } + + if (this.effectiveModeForRoot(sessionID, rootSessionId).mode !== 'auto') { + return + } + + await this.replyOnce(sessionID, requestID) + } + + private async replyOnce(sessionID: string, requestID: string): Promise { + try { + await this.openCodeClient.api.permission.reply({ sessionID, requestID, decision: 'once' }) + logger.info(`Auto-accepted permission request ${requestID} for session ${sessionID}`) + } catch (error) { + logger.error(`Failed to auto-accept permission request ${requestID} for session ${sessionID}:`, error) + } + } + + private async resolveRootSessionIdOrNull(sessionId: string): Promise { + try { + return await this.resolveRootSessionId(sessionId) + } catch { + return null + } + } + private async getParentId(sessionId: string): Promise { if (this.parentBySession.has(sessionId)) { return this.parentBySession.get(sessionId) ?? null diff --git a/backend/test/helpers/fake-session-permission-client.ts b/backend/test/helpers/fake-session-permission-client.ts index 96a44143..93bf422f 100644 --- a/backend/test/helpers/fake-session-permission-client.ts +++ b/backend/test/helpers/fake-session-permission-client.ts @@ -1,26 +1,62 @@ +import { vi } from 'vitest' import type { OpenCodeClient } from '../../src/services/opencode/client' +export interface FakePendingPermissionRequest { + id: string + sessionID: string +} + export interface FakeSessionPermissionClientOptions { parents?: Record failSessionGet?: boolean + pendingRequests?: Record + getSession?: (sessionID: string) => Promise<{ parentID?: string | null }> + listRequests?: (directory: string) => Promise +} + +export interface FakeSessionPermissionClient extends OpenCodeClient { + replyPermission: ReturnType } export function createFakeSessionPermissionClient( options: FakeSessionPermissionClientOptions = {}, -): OpenCodeClient { +): FakeSessionPermissionClient { const parents = options.parents ?? {} + const pendingRequests = options.pendingRequests ?? {} + const replyPermission = vi.fn(async () => {}) + + const getSession = + options.getSession ?? + (async (sessionID: string) => { + if (options.failSessionGet) { + throw new Error('upstream unavailable') + } + return { parentID: parents[sessionID] ?? undefined } + }) + + const listRequests = + options.listRequests ?? + (async (directory: string) => pendingRequests[directory] ?? []) return { + replyPermission, api: { session: { - get: async ({ sessionID }: { sessionID: string }) => { - if (options.failSessionGet) { - throw new Error('upstream unavailable') - } - return { parentID: parents[sessionID] ?? undefined } + get: async ({ sessionID }: { sessionID: string }) => getSession(sessionID), + }, + permission: { + request: { + list: async (input?: { location?: { directory?: string } }) => { + const directory = input?.location?.directory ?? '' + return { + location: { directory }, + data: await listRequests(directory), + } + }, }, + reply: replyPermission, }, }, forwardRaw: async () => new Response(), - } as unknown as OpenCodeClient + } as unknown as FakeSessionPermissionClient } diff --git a/backend/test/services/notification-service.test.ts b/backend/test/services/notification-service.test.ts index eb0cace1..32a769d5 100644 --- a/backend/test/services/notification-service.test.ts +++ b/backend/test/services/notification-service.test.ts @@ -158,4 +158,26 @@ describe('NotificationService.handleSSEEvent session routing', () => { expect(send).not.toHaveBeenCalled() }) + + it('suppresses an event when a registered suppressor resolves true', async () => { + const service = createService() + const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult) + const suppressor = vi.fn(async () => true) + service.addEventSuppressor(suppressor) + + await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_perm')) + + expect(suppressor).toHaveBeenCalledWith(expect.objectContaining({ type: 'permission.asked' }), 'ses_perm') + expect(send).not.toHaveBeenCalled() + }) + + it('keeps notifying when every registered suppressor resolves false', async () => { + const service = createService() + const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult) + service.addEventSuppressor(async () => false) + + await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_perm')) + + expect(send).toHaveBeenCalledTimes(1) + }) }) diff --git a/backend/test/services/session-permission-modes.test.ts b/backend/test/services/session-permission-modes.test.ts index d7072af7..73b00fee 100644 --- a/backend/test/services/session-permission-modes.test.ts +++ b/backend/test/services/session-permission-modes.test.ts @@ -7,7 +7,24 @@ import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/sched import { getSessionPermissionMode, setSessionPermissionMode } from '../../src/db/session-permission-modes' import { SettingsService } from '../../src/services/settings' import { SessionPermissionModeService } from '../../src/services/session-permission-modes' -import { createFakeSessionPermissionClient } from '../helpers/fake-session-permission-client' +import type { SSEEvent } from '../../src/services/sse-aggregator' +import { + createFakeSessionPermissionClient, + type FakePendingPermissionRequest, +} from '../helpers/fake-session-permission-client' + +const DIRECTORY = '/abs/repo' + +function createDeferred(): { + promise: Promise + resolve: (value: T) => void +} { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} function createTestDb(): Database { const db = new Database(':memory:') @@ -15,6 +32,36 @@ function createTestDb(): Database { return db } +function permissionAskedEvent(sessionID: string, id: string): SSEEvent { + return { + id: `evt_${id}`, + created: Date.now(), + type: 'permission.asked', + location: { directory: DIRECTORY }, + data: { id, sessionID, action: 'shell', resources: ['ls'] }, + } as unknown as SSEEvent +} + +function sessionCreatedEvent(sessionID: string, parentID?: string): SSEEvent { + return { + id: `evt_created_${sessionID}`, + created: Date.now(), + type: 'session.created', + location: { directory: DIRECTORY }, + data: { sessionID, parentID }, + } as unknown as SSEEvent +} + +function sessionDeletedEvent(sessionID: string): SSEEvent { + return { + id: `evt_deleted_${sessionID}`, + created: Date.now(), + type: 'session.deleted', + location: { directory: DIRECTORY }, + data: { sessionID }, + } as unknown as SSEEvent +} + describe('SessionPermissionModeService', () => { let db: Database @@ -109,4 +156,151 @@ describe('SessionPermissionModeService', () => { settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } }) expect(service.defaultMode()).toBe('auto') }) + + it('auto-accepts a permission request for an auto root session', async () => { + setSessionPermissionMode(db, 'ses_root', 'auto') + const client = createFakeSessionPermissionClient({ parents: { ses_root: null } }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_root', 'perm-1')) + + expect(client.replyPermission).toHaveBeenCalledTimes(1) + expect(client.replyPermission).toHaveBeenCalledWith({ + sessionID: 'ses_root', + requestID: 'perm-1', + decision: 'once', + }) + }) + + it('auto-accepts a permission request for a child of an auto root session', async () => { + setSessionPermissionMode(db, 'ses_root', 'auto') + const client = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_child', 'perm-2')) + + expect(client.replyPermission).toHaveBeenCalledTimes(1) + expect(client.replyPermission).toHaveBeenCalledWith({ + sessionID: 'ses_child', + requestID: 'perm-2', + decision: 'once', + }) + }) + + it('leaves an ask session permission request unanswered', async () => { + const client = createFakeSessionPermissionClient({ parents: { ses_root: null } }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_root', 'perm-3')) + + expect(client.replyPermission).not.toHaveBeenCalled() + }) + + it('stamps the default auto mode on a new root session but not on a child', async () => { + const settingsService = new SettingsService(db) + settingsService.updateSettings({ sessionDefaults: { permissionMode: 'auto' } }) + const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), settingsService) + + await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root')) + await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_child', 'ses_root')) + + expect(getSessionPermissionMode(db, 'ses_root')).toBe('auto') + expect(getSessionPermissionMode(db, 'ses_child')).toBeNull() + }) + + it('does not stamp a new root session when the default mode is ask', async () => { + const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db)) + + await service.handleEvent(DIRECTORY, sessionCreatedEvent('ses_root')) + + expect(getSessionPermissionMode(db, 'ses_root')).toBeNull() + }) + + it('clears the stored mode when the session is deleted', async () => { + setSessionPermissionMode(db, 'ses_root', 'auto') + const service = new SessionPermissionModeService(db, createFakeSessionPermissionClient(), new SettingsService(db)) + + await service.handleEvent(DIRECTORY, sessionDeletedEvent('ses_root')) + + expect(getSessionPermissionMode(db, 'ses_root')).toBeNull() + }) + + it('replies to pending requests for the switched root only', async () => { + const client = createFakeSessionPermissionClient({ + parents: { ses_root: null, ses_other: null }, + pendingRequests: { + [DIRECTORY]: [ + { id: 'perm-root', sessionID: 'ses_root' }, + { id: 'perm-other', sessionID: 'ses_other' }, + ], + }, + }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + await service.setMode('ses_root', 'auto', DIRECTORY) + + expect(client.replyPermission).toHaveBeenCalledTimes(1) + expect(client.replyPermission).toHaveBeenCalledWith({ + sessionID: 'ses_root', + requestID: 'perm-root', + decision: 'once', + }) + }) + + it('does not approve pending requests when the root switches to ask while the listing is in flight', async () => { + const listDeferred = createDeferred() + const listStarted = createDeferred() + const client = createFakeSessionPermissionClient({ + parents: { ses_root: null }, + listRequests: () => { + listStarted.resolve() + return listDeferred.promise + }, + }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + const autoSwitch = service.setMode('ses_root', 'auto', DIRECTORY) + await listStarted.promise + await service.setMode('ses_root', 'ask', DIRECTORY) + listDeferred.resolve([{ id: 'perm-root', sessionID: 'ses_root' }]) + await autoSwitch + + expect(getSessionPermissionMode(db, 'ses_root')).toBe('ask') + expect(client.replyPermission).not.toHaveBeenCalled() + }) + + it('does not approve a pending child request when the root switches to ask while child resolution is in flight', async () => { + const childDeferred = createDeferred<{ parentID?: string }>() + const childResolutionStarted = createDeferred() + const client = createFakeSessionPermissionClient({ + parents: { ses_root: null }, + pendingRequests: { [DIRECTORY]: [{ id: 'perm-child', sessionID: 'ses_child' }] }, + getSession: (sessionID) => { + if (sessionID === 'ses_child') { + childResolutionStarted.resolve() + return childDeferred.promise + } + return Promise.resolve({ parentID: null }) + }, + }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + const autoSwitch = service.setMode('ses_root', 'auto', DIRECTORY) + await childResolutionStarted.promise + await service.setMode('ses_root', 'ask', DIRECTORY) + childDeferred.resolve({ parentID: 'ses_root' }) + await autoSwitch + + expect(getSessionPermissionMode(db, 'ses_root')).toBe('ask') + expect(client.replyPermission).not.toHaveBeenCalled() + }) + + it('does not list pending requests when switching to ask', async () => { + const client = createFakeSessionPermissionClient({ parents: { ses_root: null } }) + const service = new SessionPermissionModeService(db, client, new SettingsService(db)) + + await service.setMode('ses_root', 'ask', DIRECTORY) + + expect(client.replyPermission).not.toHaveBeenCalled() + }) })