diff --git a/backend/src/index.ts b/backend/src/index.ts index dd739b6f..be7db75c 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -40,6 +40,7 @@ import { createAuthMiddleware } from './auth/middleware' import { createPromptTemplateRoutes } from './routes/prompt-templates' import { createSessionPinRoutes } from './routes/session-pins' import { createChatRoutes } from './routes/chats' +import { createChatTerminalRoutes, createChatTerminalSocketRoutes } from './routes/chat-terminals' import { createSessionPermissionModeRoutes } from './routes/session-permission-modes' import { createSessionSandboxRoutes } from './routes/session-sandbox' import { createMultiRunRoutes } from './routes/multi-runs' @@ -303,13 +304,13 @@ scheduleService.setWorktreeRemovedHandler(async (directory) => { const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) -const notificationService = new NotificationService(db, opencodeServerRegistry) +const chatService = new ChatService(openCodeClient) +const notificationService = new NotificationService(db, opencodeServerRegistry, chatService) const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry) const goalOutcomes = new GoalOutcomeTracker() const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId)) const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService) -const chatService = new ChatService(openCodeClient) sseAggregator.onEvent((directory, event) => { sessionSandboxService.handleEvent(directory, event).catch((err) => { @@ -425,7 +426,9 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db)) protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret')) protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable')) protectedApi.route('/session-pins', createSessionPinRoutes(db)) +protectedApi.route('/chats', createChatTerminalSocketRoutes(chatService, terminalService, upgradeWebSocket)) protectedApi.route('/chats', createChatRoutes(chatService)) +protectedApi.route('/chats', createChatTerminalRoutes(chatService, terminalService)) protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService)) protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket)) protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService)) diff --git a/backend/src/routes/chat-terminals.ts b/backend/src/routes/chat-terminals.ts new file mode 100644 index 00000000..346a0881 --- /dev/null +++ b/backend/src/routes/chat-terminals.ts @@ -0,0 +1,144 @@ +import { Hono } from 'hono' +import type { MiddlewareHandler } from 'hono' +import type { UpgradeWebSocket } from 'hono/ws' +import { getTrustedOrigins } from '@opencode-manager/shared/config/env' +import { CreateTerminalRequestSchema, ResizeTerminalRequestSchema } from '@opencode-manager/shared/schemas' +import type { ChatService } from '../services/chats' +import { TerminalNotFoundError, type TerminalService } from '../services/terminal' +import { createBridgedSocketEvents, isAllowedUpgradeOrigin } from '../utils/websocket-bridge' +import { parseTerminalCursor } from '../utils/terminal-cursor' +import { handleOpenCodeError } from '../utils/route-helpers' +import type { Session } from '../auth' + +export function createChatTerminalRoutes(chatService: ChatService, terminalService: TerminalService) { + const app = new Hono() + + app.get('/:chatId/terminals', async (c) => { + const chat = await chatService.resolve(c.req.param('chatId')) + if (!chat) return c.json({ error: 'Chat not found' }, 404) + + try { + const terminals = await terminalService.list(chat.directory) + return c.json({ terminals }) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.post('/:chatId/terminals', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = CreateTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const chat = await chatService.resolve(c.req.param('chatId')) + if (!chat) return c.json({ error: 'Chat not found' }, 404) + + try { + const terminal = await terminalService.create(chat.directory, { + kind: 'shell', + name: parsed.data.title ?? 'Terminal', + }) + return c.json(terminal) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.patch('/:chatId/terminals/:ptyID', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = ResizeTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const chat = await chatService.resolve(c.req.param('chatId')) + if (!chat) return c.json({ error: 'Chat not found' }, 404) + + const ptyID = c.req.param('ptyID') + + try { + await terminalService.requireTerminal(chat.directory, ptyID) + await terminalService.resize(chat.directory, ptyID, { cols: parsed.data.cols, rows: parsed.data.rows }) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.delete('/:chatId/terminals/:ptyID', async (c) => { + const chat = await chatService.resolve(c.req.param('chatId')) + if (!chat) return c.json({ error: 'Chat not found' }, 404) + + const ptyID = c.req.param('ptyID') + + try { + await terminalService.requireTerminal(chat.directory, ptyID) + await terminalService.remove(chat.directory, ptyID) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + return app +} + +interface ChatTerminalSocketVariables { + terminalDirectory: string + terminalCursor: number | undefined + session?: Session['session'] +} + +export function createChatTerminalSocketRoutes( + chatService: ChatService, + terminalService: TerminalService, + upgradeWebSocket: UpgradeWebSocket, + trustedOrigins: readonly string[] = getTrustedOrigins(), +) { + const app = new Hono<{ Variables: ChatTerminalSocketVariables }>() + + const validate: MiddlewareHandler<{ Variables: ChatTerminalSocketVariables }> = async (c, next) => { + if (!isAllowedUpgradeOrigin(c.req.header('origin'), trustedOrigins)) { + return c.json({ error: 'Origin not allowed' }, 403) + } + + const cursor = parseTerminalCursor(c.req.query('cursor')) + if (cursor === null) { + return c.json({ error: 'Invalid cursor' }, 400) + } + + const chat = await chatService.resolve(c.req.param('chatId') ?? '') + if (!chat) { + return c.json({ error: 'Chat not found' }, 404) + } + + c.set('terminalDirectory', chat.directory) + c.set('terminalCursor', cursor) + await next() + } + + app.get( + '/:chatId/terminals/:ptyID/connect', + validate, + upgradeWebSocket((c) => { + const directory = c.get('terminalDirectory') + const cursor = c.get('terminalCursor') + const ptyID = c.req.param('ptyID') ?? '' + + return createBridgedSocketEvents( + (peer) => terminalService.connect(directory, ptyID, cursor, peer), + { sessionId: c.get('session')?.id }, + ) + }), + ) + + return app +} diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index b634e840..b3e12a22 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -25,7 +25,7 @@ import { getScheduleRunBySessionId, isQuietScheduleRunSession } from "../db/sche import { ensurePushSubscriptionsTable } from "../db/push-subscriptions"; import { isAuthSessionActive } from "../db/auth-sessions"; import type { Repo } from "../types/repo"; -import { buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils"; +import { buildChatSessionPath, buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils"; import { sessionIDFromEvent } from "@opencode-manager/shared/opencode"; import { resolveRepoForDirectory } from "./repo"; import type { SessionGoalOutcome } from "./goal-outcomes"; @@ -34,6 +34,10 @@ export interface NotificationServerRegistry { get(serverId: string): Pick | null; } +export interface ChatDirectoryResolver { + findByDirectory(directory: string): Promise<{ id: string } | null>; +} + interface VapidConfig { publicKey: string; privateKey: string; @@ -122,8 +126,14 @@ export function buildScheduleRunReportUrl(runId: number): string { export function buildNotificationUrl( repo: Pick | null, - sessionId: string | undefined + sessionId: string | undefined, + chat?: { id: string } | null ): string { + if (chat) { + return sessionId + ? buildChatSessionPath(chat.id, sessionId) + : `/chats/${encodeURIComponent(chat.id)}`; + } if (!repo) return "/"; if (!sessionId) return `/repos/${repo.id}`; return buildSessionPath(repo.id, sessionId); @@ -132,6 +142,7 @@ export function buildNotificationUrl( export function buildEventNotificationPayload( event: Pick, context: { + displayName?: string; repoName?: string; repoId?: number; serverId?: string; @@ -147,7 +158,7 @@ export function buildEventNotificationPayload( const title = config.titleFn(event.data); const detail = config.bodyFn(event.data); - const displayName = context.repoName ?? context.serverName; + const displayName = context.displayName ?? context.repoName ?? context.serverName; const rawBody = displayName ? `${displayName} · ${detail}` : detail; @@ -185,7 +196,8 @@ export class NotificationService { constructor( private db: Database, - private serverRegistry: NotificationServerRegistry | null = null + private serverRegistry: NotificationServerRegistry | null = null, + private chatService: ChatDirectoryResolver | null = null ) { this.settingsService = new SettingsService(db); ensurePushSubscriptionsTable(db); @@ -393,12 +405,16 @@ export class NotificationService { } const repo = directory ? await resolveRepoForDirectory(this.db, directory) : null; + const chat = !repo && directory + ? (await this.chatService?.findByDirectory(directory)) ?? null + : null; const repoId = repo?.id; const repoName = repo ? getRepoName(repo) : undefined; const reportUrl = RUN_OUTCOME_EVENTS.has(event.type) ? this.getScheduleRunReportUrl(sessionId) : null; - const url = reportUrl ?? buildNotificationUrl(repo, sessionId); + const url = reportUrl ?? buildNotificationUrl(repo, sessionId, chat); const payload = buildEventNotificationPayload(event, { + displayName: repoName ?? (chat ? "Chat" : undefined), repoName, repoId, sessionId, @@ -454,9 +470,12 @@ export class NotificationService { const repo = !isRemote && outcome.directory ? await resolveRepoForDirectory(this.db, outcome.directory) : null; + const chat = !isRemote && !repo && outcome.directory + ? (await this.chatService?.findByDirectory(outcome.directory)) ?? null + : null; const server = isRemote ? this.serverRegistry?.get(outcome.serverId) ?? null : null; const repoName = repo ? getRepoName(repo) : undefined; - const displayName = repoName ?? server?.name; + const displayName = repoName ?? (chat ? "Chat" : undefined) ?? server?.name; const payload: PushNotificationPayload = { title: getGoalStatusTitle(goal.status), @@ -474,7 +493,7 @@ export class NotificationService { serverName: server?.name, url: isRemote ? buildServerSessionPath(outcome.serverId, outcome.sessionId) - : buildNotificationUrl(repo, outcome.sessionId), + : buildNotificationUrl(repo, outcome.sessionId, chat), }, }; diff --git a/backend/test/routes/chat-terminals.test.ts b/backend/test/routes/chat-terminals.test.ts new file mode 100644 index 00000000..dc976d01 --- /dev/null +++ b/backend/test/routes/chat-terminals.test.ts @@ -0,0 +1,340 @@ +import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest' +import { Hono } from 'hono' +import { createNodeWebSocket } from '@hono/node-ws' +import { createChatTerminalRoutes, createChatTerminalSocketRoutes } from '../../src/routes/chat-terminals' +import { TerminalNotFoundError } from '../../src/services/terminal' +import type { TerminalService } from '../../src/services/terminal' +import type { ChatService } from '../../src/services/chats' +import { startWebSocketServer, type WebSocketTestServer } from '../helpers/websocket-server' +import { rawWebSocketHandshake } from '../helpers/raw-websocket-handshake' + +const CHAT_ID = '20260304-050607-abcdef' +const UNKNOWN_CHAT_ID = '20260304-050607-aaaaaa' +const chatDirectory = '/tmp/chat' +const TRUSTED_ORIGIN = 'http://localhost:5003' + +const chat = { + id: CHAT_ID, + directory: chatDirectory, + filesPath: `chats/${CHAT_ID}`, + createdAt: 0, +} + +const shellTerminal = { + id: 'pty-1', + title: 'Terminal', + kind: 'shell', + cwd: chatDirectory, + status: 'running', +} as const + +function createChatService(overrides: { resolve?: ReturnType } = {}): ChatService { + return { + resolve: + overrides.resolve ?? + vi.fn(async (chatId: string) => (chatId === CHAT_ID ? chat : null)), + } as unknown as ChatService +} + +function createService(overrides: Partial = {}): TerminalService { + return { + list: vi.fn(async () => []), + create: vi.fn(async () => shellTerminal), + requireTerminal: vi.fn(async () => shellTerminal), + resize: vi.fn(async () => undefined), + remove: vi.fn(async () => undefined), + removeAll: vi.fn(async () => undefined), + ...overrides, + } as unknown as TerminalService +} + +function createApp(chatService: ChatService, service: TerminalService): Hono { + const app = new Hono() + app.route('/', createChatTerminalRoutes(chatService, service)) + return app +} + +const jsonHeaders = { 'Content-Type': 'application/json' } + +describe('Chat Terminal Routes', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + describe('GET /:chatId/terminals', () => { + it('lists the terminals for the chat directory', async () => { + const terminals = [{ ...shellTerminal }] + const list = vi.fn(async () => terminals) + const res = await createApp(createChatService(), createService({ list })).request(`/${CHAT_ID}/terminals`) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ terminals }) + expect(list).toHaveBeenCalledWith(chatDirectory) + }) + + it('ignores a directory query parameter', async () => { + const list = vi.fn(async () => []) + const res = await createApp(createChatService(), createService({ list })).request( + `/${CHAT_ID}/terminals?directory=/tmp/other`, + ) + + expect(res.status).toBe(200) + expect(list).toHaveBeenCalledWith(chatDirectory) + }) + + it('returns 404 for an unknown chat', async () => { + const list = vi.fn(async () => []) + const res = await createApp(createChatService(), createService({ list })).request( + `/${UNKNOWN_CHAT_ID}/terminals`, + ) + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Chat not found' }) + expect(list).not.toHaveBeenCalled() + }) + }) + + describe('POST /:chatId/terminals', () => { + it('creates a shell with the default name in the chat directory', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ create })).request( + `/${CHAT_ID}/terminals`, + { method: 'POST', headers: jsonHeaders, body: JSON.stringify({}) }, + ) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual(shellTerminal) + expect(create).toHaveBeenCalledWith(chatDirectory, { kind: 'shell', name: 'Terminal' }) + }) + + it('creates a shell with the requested title and ignores the body directory', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ create })).request( + `/${CHAT_ID}/terminals`, + { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/other', title: 'My shell' }), + }, + ) + + expect(res.status).toBe(200) + expect(create).toHaveBeenCalledWith(chatDirectory, { kind: 'shell', name: 'My shell' }) + }) + + it('returns 400 for an invalid body', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ create })).request( + `/${CHAT_ID}/terminals`, + { method: 'POST', headers: jsonHeaders, body: JSON.stringify({ title: 'a'.repeat(81) }) }, + ) + + expect(res.status).toBe(400) + expect(create).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown chat', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ create })).request( + `/${UNKNOWN_CHAT_ID}/terminals`, + { method: 'POST', headers: jsonHeaders, body: JSON.stringify({}) }, + ) + + expect(res.status).toBe(404) + expect(create).not.toHaveBeenCalled() + }) + }) + + describe('PATCH /:chatId/terminals/:ptyID', () => { + it('resizes a known terminal in the chat directory', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const resize = vi.fn(async () => undefined) + const res = await createApp(createChatService(), createService({ requireTerminal, resize })).request( + `/${CHAT_ID}/terminals/pty-1`, + { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/other', cols: 80, rows: 24 }), + }, + ) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith(chatDirectory, 'pty-1') + expect(resize).toHaveBeenCalledWith(chatDirectory, 'pty-1', { cols: 80, rows: 24 }) + }) + + it('returns 400 for invalid resize bounds', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const app = createApp(createChatService(), createService({ requireTerminal })) + + for (const body of ['{"cols":0,"rows":24}', '{"cols":80}', '{"cols":80,"rows":501}', '{"cols":1.5,"rows":24}']) { + const res = await app.request(`/${CHAT_ID}/terminals/pty-1`, { method: 'PATCH', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + + expect(requireTerminal).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createChatService(), createService({ requireTerminal })).request( + `/${CHAT_ID}/terminals/missing`, + { method: 'PATCH', headers: jsonHeaders, body: JSON.stringify({ cols: 80, rows: 24 }) }, + ) + + expect(res.status).toBe(404) + }) + + it('returns 404 for an unknown chat', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ requireTerminal })).request( + `/${UNKNOWN_CHAT_ID}/terminals/pty-1`, + { method: 'PATCH', headers: jsonHeaders, body: JSON.stringify({ cols: 80, rows: 24 }) }, + ) + + expect(res.status).toBe(404) + expect(requireTerminal).not.toHaveBeenCalled() + }) + }) + + describe('DELETE /:chatId/terminals/:ptyID', () => { + it('removes a known terminal in the chat directory', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const remove = vi.fn(async () => undefined) + const res = await createApp(createChatService(), createService({ requireTerminal, remove })).request( + `/${CHAT_ID}/terminals/pty-1?directory=/tmp/other`, + { method: 'DELETE' }, + ) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith(chatDirectory, 'pty-1') + expect(remove).toHaveBeenCalledWith(chatDirectory, 'pty-1') + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createChatService(), createService({ requireTerminal })).request( + `/${CHAT_ID}/terminals/missing`, + { method: 'DELETE' }, + ) + + expect(res.status).toBe(404) + }) + + it('returns 404 for an unknown chat', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const res = await createApp(createChatService(), createService({ requireTerminal })).request( + `/${UNKNOWN_CHAT_ID}/terminals/pty-1`, + { method: 'DELETE' }, + ) + + expect(res.status).toBe(404) + expect(requireTerminal).not.toHaveBeenCalled() + }) + }) +}) + +describe('Chat Terminal Socket Route', () => { + const connect = vi.fn(async () => ({ send: vi.fn(), close: vi.fn() })) + const resolve = vi.fn(async (chatId: string) => (chatId === CHAT_ID ? chat : null)) + + let server: WebSocketTestServer + let binding: ReturnType + let port = 0 + + beforeAll(async () => { + const app = new Hono() + binding = createNodeWebSocket({ app }) + app.route( + '/', + createChatTerminalSocketRoutes( + { resolve } as unknown as ChatService, + { connect } as unknown as TerminalService, + binding.upgradeWebSocket, + [TRUSTED_ORIGIN], + ), + ) + server = await startWebSocketServer({ app, injectWebSocket: binding.injectWebSocket }) + port = server.port + }) + + afterAll(async () => { + binding.wss.close() + await server.close() + }) + + beforeEach(() => { + connect.mockClear() + resolve.mockClear() + }) + + function connectPath(chatId = CHAT_ID, query = ''): string { + return `/${chatId}/terminals/pty-1/connect${query}` + } + + function openEvent(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + if (socket.readyState === WebSocket.OPEN) { + resolve() + return + } + socket.addEventListener('open', () => resolve(), { once: true }) + socket.addEventListener('error', () => reject(new Error('WebSocket error before open')), { once: true }) + }) + } + + async function waitFor(predicate: () => boolean, timeoutMs = 5000): Promise { + const start = Date.now() + while (!predicate()) { + if (Date.now() - start > timeoutMs) throw new Error('Timed out waiting for condition') + await new Promise((resolve) => setTimeout(resolve, 10)) + } + } + + it('connects with the chat directory and parsed cursor', async () => { + const socket = new WebSocket(`ws://127.0.0.1:${port}${connectPath(CHAT_ID, '?cursor=-1')}`) + + await openEvent(socket) + await waitFor(() => connect.mock.calls.length > 0) + + expect(connect).toHaveBeenCalledWith(chatDirectory, 'pty-1', -1, expect.anything()) + socket.close() + }) + + it('accepts a trusted Origin handshake', async () => { + const outcome = await rawWebSocketHandshake({ port, path: connectPath(), origin: TRUSTED_ORIGIN }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('accepts a handshake without an Origin header', async () => { + const outcome = await rawWebSocketHandshake({ port, path: connectPath() }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('rejects an untrusted Origin with 403', async () => { + const outcome = await rawWebSocketHandshake({ port, path: connectPath(), origin: 'http://evil.example' }) + + expect(outcome).toEqual({ upgraded: false, status: 403 }) + }) + + it('rejects a malformed cursor with 400', async () => { + const outcome = await rawWebSocketHandshake({ port, path: connectPath(CHAT_ID, '?cursor=abc') }) + + expect(outcome).toEqual({ upgraded: false, status: 400 }) + }) + + it('returns 404 for an unknown chat without connecting', async () => { + const outcome = await rawWebSocketHandshake({ port, path: connectPath(UNKNOWN_CHAT_ID) }) + + expect(outcome).toEqual({ upgraded: false, status: 404 }) + expect(connect).not.toHaveBeenCalled() + }) +}) diff --git a/backend/test/services/notification-format.test.ts b/backend/test/services/notification-format.test.ts index c6f4dcf6..a4ea5b98 100644 --- a/backend/test/services/notification-format.test.ts +++ b/backend/test/services/notification-format.test.ts @@ -12,6 +12,7 @@ import { buildEventNotificationPayload, buildNotificationUrl } from '../../src/s import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' const ctx = { repoName: 'oc-manager', repoId: 1, sessionId: 'ses_1', directory: '/abs/repo', url: '/repos/1/sessions/ses_1' } +const CHAT_ID = '20260304-050607-abcdef' describe('OpenCode goal labels', () => { it('titles each OpenCode goal status', () => { @@ -239,4 +240,7 @@ describe('buildNotificationUrl', () => { it('appends ?assistant=1 for the assistant repo session', () => { expect(buildNotificationUrl({ id: ASSISTANT_REPO_ID }, 'ses_1')).toBe('/repos/0/sessions/ses_1?assistant=1') }) + it('returns the chat session page for a chat folder', () => { + expect(buildNotificationUrl(null, 'ses_1', { id: CHAT_ID })).toBe(`/chats/${CHAT_ID}/sessions/ses_1`) + }) }) diff --git a/backend/test/services/notification-service.test.ts b/backend/test/services/notification-service.test.ts index d3b73721..aed89636 100644 --- a/backend/test/services/notification-service.test.ts +++ b/backend/test/services/notification-service.test.ts @@ -5,7 +5,7 @@ import { allMigrations } from '../../src/db/migrations' import { createRepo } from '../../src/db/queries' import { createScheduleJob, createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules' import { buildCreateSchedulePersistenceInput } from '../../src/services/schedule-config' -import { NotificationService, type NotificationServerRegistry } from '../../src/services/notification' +import { NotificationService, type ChatDirectoryResolver, type NotificationServerRegistry } from '../../src/services/notification' import { SettingsService } from '../../src/services/settings' import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator' import type { PushNotificationPayload } from '@opencode-manager/shared/types' @@ -14,6 +14,8 @@ import type { SessionGoalOutcome } from '../../src/services/goal-outcomes' import { CreateScheduleJobRequestSchema, type ScheduleJob } from '@opencode-manager/shared/schemas' const DIRECTORY = '/abs/repo' +const CHAT_ID = '20260304-050607-abcdef' +const CHAT_DIRECTORY = '/abs/chat' const USER_ID = 'user-1' const sendResult = { delivered: 0, expired: 0, failed: 0, total: 0 } @@ -53,6 +55,7 @@ function permissionAskedEvent(sessionID: string): SSEEvent { function createService( db = new Database(':memory:'), registry: NotificationServerRegistry | null = null, + chatService: ChatDirectoryResolver | null = null, ): NotificationService { migrate(db, allMigrations) createRepo(db, { @@ -64,7 +67,7 @@ function createService( isLocal: true, }) - const service = new NotificationService(db, registry) + const service = new NotificationService(db, registry, chatService) vi.spyOn(service, 'isConfigured').mockReturnValue(true) service.saveSubscription(USER_ID, 'https://push.example.com/sub-1', 'p256dh-key', 'auth-key') new SettingsService(db).updateSettings( @@ -213,6 +216,23 @@ describe('NotificationService.handleSSEEvent session routing', () => { expect(send).toHaveBeenCalledTimes(1) }) + + it('links a session in a chat folder to the chat route with a Chat prefix', async () => { + const findByDirectory = vi.fn(async (directory: string) => + directory === CHAT_DIRECTORY ? { id: CHAT_ID } : null, + ) + const service = createService(undefined, null, { findByDirectory }) + const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult) + + await service.handleSSEEvent(CHAT_DIRECTORY, formCreatedEvent('ses_chat')) + + expect(findByDirectory).toHaveBeenCalledTimes(1) + expect(findByDirectory).toHaveBeenCalledWith(CHAT_DIRECTORY) + expect(send).toHaveBeenCalledTimes(1) + const payload = send.mock.calls[0]?.[1] as PushNotificationPayload + expect(payload.data?.url).toBe(`/chats/${CHAT_ID}/sessions/ses_chat`) + expect(payload.body.startsWith('Chat · ')).toBe(true) + }) }) describe('NotificationService quiet schedule announcements', () => { @@ -491,4 +511,24 @@ describe('NotificationService goal outcomes', () => { expect(send).toHaveBeenCalledTimes(1) }) + + it('links a goal outcome in a chat folder to the chat route with a Chat prefix', async () => { + const findByDirectory = vi.fn(async (directory: string) => + directory === CHAT_DIRECTORY ? { id: CHAT_ID } : null, + ) + const service = createService(undefined, null, { findByDirectory }) + const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult) + + await service.notifyGoalOutcome({ + ...goalOutcome, + sessionId: 'ses_chat_goal', + directory: CHAT_DIRECTORY, + }) + + expect(findByDirectory).toHaveBeenCalledWith(CHAT_DIRECTORY) + expect(send).toHaveBeenCalledTimes(1) + const payload = send.mock.calls[0]?.[1] as PushNotificationPayload + expect(payload.data?.url).toBe(`/chats/${CHAT_ID}/sessions/ses_chat_goal`) + expect(payload.body.startsWith('Chat · ')).toBe(true) + }) })