feat: add push notifications with VAPID (#110)

* Add OAuth authentication support for MCP servers

* Improve mobile text sizing with responsive text classes

* refactor: improve virtualized text viewer with React Query infinite scroll and simplified buffering

* Add push notifications with VAPID and PWA support

* feat: add VAPID environment variables for push notifications

* Replace SquareFill with MicOff icon for stop recording buttons

* Send push notifications when app is not focused

* Fix stop generation button icons to use X instead of MicOff

* feat: enhance push notification logging and debugging

- Add structured logging throughout push notification flow
- Improve error handling with detailed diagnostics
- Add /api/notifications/debug endpoint for troubleshooting
- Enhanced test notification response with per-subscription results
- Add service worker logging and better install/activate handling

* Improve VAPID push notification configuration with validation and better defaults

- Add validation warnings for VAPID_SUBJECT format (requires mailto: prefix for iOS/Safari)
- Expose VAPID details via notifications API endpoint
- Update default VAPID_SUBJECT from mailto:admin@opencode.local to empty string
- Enhance VAPID logging with key lengths and subject info
- Improve documentation in .env.example with setup instructions

* Fix notification URL to use repo ID instead of filesystem path

* Clean up push notification logging and debug endpoints

* Add push notifications documentation
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-06 11:23:10 -05:00
1 parent 3d9e9b8322
commit ae644e851d
47 files changed
+4506 -67

No files matched your search

+22
View File
@@ -83,6 +83,28 @@ PASSKEY_RP_ID=localhost
PASSKEY_RP_NAME=OpenCode Manager
PASSKEY_ORIGIN=http://localhost:5003
# ============================================
# Push Notifications (VAPID)
# Enables push notifications for the PWA (background alerts for agent
# questions, permission requests, errors, and session completions).
#
# Setup:
# 1. Generate keys: npx web-push generate-vapid-keys
# 2. Set VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY from the output
# 3. Set VAPID_SUBJECT to a mailto: address (REQUIRED for iOS/Safari)
#
# IMPORTANT: VAPID_SUBJECT MUST use the mailto: format for iOS/Safari
# push notifications to work. Apple's push service rejects https:// subjects.
# Example: mailto:you@yourdomain.com
#
# Browser requirements:
# - HTTPS required (except localhost)
# - Safari/iOS: Requires mailto: VAPID_SUBJECT and HTTPS
# ============================================
# VAPID_PUBLIC_KEY=
# VAPID_PRIVATE_KEY=
# VAPID_SUBJECT=mailto:you@yourdomain.com
# ============================================
# Frontend Configuration (Vite)
# These are optional - frontend uses defaults if not set
+1
View File
@@ -12,6 +12,7 @@ coverage/
.vscode/
.idea/
*.test.js
*.tsbuildinfo
data/
workspace/
+14
View File
@@ -76,6 +76,7 @@ On first launch, you'll be prompted to create an admin account. That's it!
- **Mobile-First Design** - Responsive UI optimized for mobile
- **PWA Installable** - Add to home screen on any device
- **iOS Optimized** - Proper keyboard handling and swipe navigation
- **Push Notifications** - Background alerts for agent events when app is closed
## Installation
@@ -163,6 +164,19 @@ PASSKEY_RP_NAME=OpenCode Manager
PASSKEY_ORIGIN=https://yourdomain.com
```
### Push Notifications (VAPID)
Enable push notifications for the PWA (background alerts for agent questions, permission requests, errors, and session completions):
```bash
# Generate keys: npx web-push generate-vapid-keys
VAPID_PUBLIC_KEY=your-public-key
VAPID_PRIVATE_KEY=your-private-key
VAPID_SUBJECT=mailto:you@yourdomain.com
```
**Important**: `VAPID_SUBJECT` MUST use `mailto:` format for iOS/Safari push notifications to work. Apple's push service rejects `https://` subjects.
### Dev Server Ports
The Docker container exposes ports `5100-5103` for running dev servers inside repositories:
+2
View File
@@ -24,6 +24,7 @@
"eventsource": "^4.1.0",
"hono": "^4.11.7",
"strip-json-comments": "^3.1.1",
"web-push": "^3.6.7",
"zod": "^4.1.12"
},
"devDependencies": {
@@ -32,6 +33,7 @@
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "latest",
"@types/eventsource": "^3.0.0",
"@types/web-push": "^3.6.4",
"@vitest/ui": "^3.2.4",
"eslint": "^9.39.1",
"typescript-eslint": "^8.45.0",
+24
View File
@@ -17,6 +17,7 @@ import { createProvidersRoutes } from './routes/providers'
import { createOAuthRoutes } from './routes/oauth'
import { createTitleRoutes } from './routes/title'
import { createSSERoutes } from './routes/sse'
import { createNotificationRoutes } from './routes/notifications'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
@@ -26,6 +27,7 @@ import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
import { cleanupOrphanedDirectories } from './services/repo'
import { proxyRequest } from './services/proxy'
import { NotificationService } from './services/notification'
import { logger } from './utils/logger'
import {
getWorkspacePath,
@@ -201,6 +203,27 @@ try {
logger.error('Failed to initialize workspace:', error)
}
const notificationService = new NotificationService(db)
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)')
} else if (!ENV.VAPID.SUBJECT.startsWith('mailto:')) {
logger.warn(`VAPID_SUBJECT="${ENV.VAPID.SUBJECT}" does not use mailto: format — iOS/Safari push notifications will fail`)
}
notificationService.configureVapid({
publicKey: ENV.VAPID.PUBLIC_KEY,
privateKey: ENV.VAPID.PRIVATE_KEY,
subject: ENV.VAPID.SUBJECT || 'mailto:push@localhost',
})
sseAggregator.onEvent((directory, event) => {
notificationService.handleSSEEvent(directory, event).catch((err) => {
logger.error('Push notification dispatch error:', err)
})
})
}
app.route('/api/auth', createAuthRoutes(auth))
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
@@ -218,6 +241,7 @@ protectedApi.route('/tts', createTTSRoutes(db))
protectedApi.route('/stt', createSTTRoutes(db))
protectedApi.route('/generate-title', createTitleRoutes())
protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
app.route('/api', protectedApi)
+99
View File
@@ -0,0 +1,99 @@
import { Hono } from "hono";
import { z } from "zod";
import { PushSubscriptionRequestSchema } from "@opencode-manager/shared/schemas";
import type { NotificationService } from "../services/notification";
export function createNotificationRoutes(
notificationService: NotificationService
) {
const app = new Hono();
app.get("/vapid-public-key", (c) => {
const publicKey = notificationService.getVapidPublicKey();
if (!publicKey) {
return c.json(
{ error: "Push notifications are not configured" },
503
);
}
return c.json({ publicKey });
});
app.post("/subscribe", async (c) => {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json();
const parsed = PushSubscriptionRequestSchema.safeParse(body);
if (!parsed.success) {
return c.json({ error: "Invalid subscription data", details: parsed.error.issues }, 400);
}
const { endpoint, keys, deviceName } = parsed.data;
const subscription = notificationService.saveSubscription(
userId,
endpoint,
keys.p256dh,
keys.auth,
deviceName
);
return c.json({ subscription });
});
app.delete("/subscribe", async (c) => {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json();
const parsed = z.object({ endpoint: z.string().url() }).safeParse(body);
if (!parsed.success) {
return c.json({ error: "Valid endpoint URL is required", details: parsed.error.issues }, 400);
}
const removed = notificationService.removeSubscription(parsed.data.endpoint, userId);
return c.json({ success: removed });
});
app.get("/subscriptions", (c) => {
const userId = c.req.query('userId') || 'default'
const subscriptions = notificationService.getSubscriptions(userId);
return c.json({ subscriptions });
});
app.delete("/subscriptions/:id", (c) => {
const userId = c.req.query('userId') || 'default'
const id = parseInt(c.req.param("id"), 10);
if (isNaN(id)) {
return c.json({ error: "Invalid subscription ID" }, 400);
}
const removed = notificationService.removeSubscriptionById(id, userId);
return c.json({ success: removed });
});
app.post("/test", async (c) => {
const userId = c.req.query('userId') || 'default'
if (!notificationService.isConfigured()) {
return c.json(
{ error: "Push notifications are not configured" },
503
);
}
const subscriptions = notificationService.getSubscriptions(userId);
if (subscriptions.length === 0) {
return c.json(
{ error: "No push subscriptions registered" },
404
);
}
await notificationService.sendTestNotification(userId);
return c.json({ success: true, devicesNotified: subscriptions.length });
});
return app;
}
+14 -1
View File
@@ -1,7 +1,7 @@
import { Hono } from 'hono'
import { stream } from 'hono/streaming'
import { sseAggregator } from '../services/sse-aggregator'
import { SSESubscribeSchema } from '@opencode-manager/shared/schemas'
import { SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
import { logger } from '../utils/logger'
import { DEFAULTS } from '@opencode-manager/shared/config'
@@ -88,6 +88,19 @@ export function createSSERoutes() {
return c.json({ success: true })
})
app.post('/visibility', async (c) => {
const body = await c.req.json()
const result = SSEVisibilitySchema.safeParse(body)
if (!result.success) {
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
}
const success = sseAggregator.setClientVisibility(result.data.clientId, result.data.visible)
if (!success) {
return c.json({ success: false, error: 'Client not found' }, 404)
}
return c.json({ success: true })
})
app.get('/status', (c) => {
return c.json({
...sseAggregator.getConnectionStatus(),
+296
View File
@@ -0,0 +1,296 @@
import { Database } from "bun:sqlite";
import webpush from "web-push";
import { logger } from "../utils/logger";
import type { PushSubscriptionRecord } from "../types/settings";
import type { PushNotificationPayload } from "@opencode-manager/shared/types";
import {
NotificationEventType,
DEFAULT_NOTIFICATION_PREFERENCES,
} from "@opencode-manager/shared/schemas";
import { SettingsService } from "./settings";
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
import { getRepoByLocalPath } from "../db/queries";
import { getReposPath } from "@opencode-manager/shared/config/env";
import path from "path";
interface VapidConfig {
publicKey: string;
privateKey: string;
subject: string;
}
const EVENT_CONFIG: Record<
string,
{ preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events; title: string; bodyFn: (props: Record<string, unknown>) => string }
> = {
[NotificationEventType.PERMISSION_ASKED]: {
preferencesKey: "permissionAsked",
title: "Permission Required",
bodyFn: () => "OpenCode needs your approval to continue",
},
[NotificationEventType.QUESTION_ASKED]: {
preferencesKey: "questionAsked",
title: "Question from Agent",
bodyFn: () => "The agent has a question for you",
},
[NotificationEventType.SESSION_ERROR]: {
preferencesKey: "sessionError",
title: "Session Error",
bodyFn: (props) => {
const error = props.error as { message?: string } | undefined;
return error?.message ?? "A session encountered an error";
},
},
[NotificationEventType.SESSION_IDLE]: {
preferencesKey: "sessionIdle",
title: "Session Complete",
bodyFn: () => "Your session has finished processing",
},
};
export class NotificationService {
private vapidConfig: VapidConfig | null = null;
private settingsService: SettingsService;
constructor(private db: Database) {
this.settingsService = new SettingsService(db);
this.initializePushSubscriptionsTable();
}
private initializePushSubscriptionsTable(): void {
this.db.run(`
CREATE TABLE IF NOT EXISTS push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
device_name TEXT,
created_at INTEGER NOT NULL,
last_used_at INTEGER
)
`);
this.db.run(
"CREATE INDEX IF NOT EXISTS idx_push_sub_user ON push_subscriptions(user_id)"
);
this.db.run(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_push_sub_endpoint ON push_subscriptions(endpoint)"
);
}
configureVapid(config: VapidConfig): void {
this.vapidConfig = config;
webpush.setVapidDetails(config.subject, config.publicKey, config.privateKey);
}
getVapidPublicKey(): string | null {
return this.vapidConfig?.publicKey ?? null;
}
isConfigured(): boolean {
return this.vapidConfig !== null;
}
saveSubscription(
userId: string,
endpoint: string,
p256dh: string,
auth: string,
deviceName?: string
): PushSubscriptionRecord {
const now = Date.now();
this.db
.prepare(
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, device_name, created_at, last_used_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(endpoint) DO UPDATE SET
user_id = excluded.user_id,
p256dh = excluded.p256dh,
auth = excluded.auth,
device_name = excluded.device_name,
last_used_at = excluded.last_used_at`
)
.run(userId, endpoint, p256dh, auth, deviceName ?? null, now, now);
const row = this.db
.prepare("SELECT * FROM push_subscriptions WHERE endpoint = ?")
.get(endpoint) as {
id: number;
user_id: string;
endpoint: string;
p256dh: string;
auth: string;
device_name: string | null;
created_at: number;
last_used_at: number | null;
};
return {
id: row.id,
userId: row.user_id,
endpoint: row.endpoint,
p256dh: row.p256dh,
auth: row.auth,
deviceName: row.device_name,
createdAt: row.created_at,
lastUsedAt: row.last_used_at,
};
}
removeSubscription(endpoint: string, userId?: string): boolean {
if (userId) {
const result = this.db
.prepare("DELETE FROM push_subscriptions WHERE endpoint = ? AND user_id = ?")
.run(endpoint, userId);
return result.changes > 0;
}
const result = this.db
.prepare("DELETE FROM push_subscriptions WHERE endpoint = ?")
.run(endpoint);
return result.changes > 0;
}
removeSubscriptionById(id: number, userId: string): boolean {
const result = this.db
.prepare("DELETE FROM push_subscriptions WHERE id = ? AND user_id = ?")
.run(id, userId);
return result.changes > 0;
}
getSubscriptions(userId: string): PushSubscriptionRecord[] {
const rows = this.db
.prepare("SELECT * FROM push_subscriptions WHERE user_id = ? ORDER BY created_at DESC")
.all(userId) as Array<{
id: number;
user_id: string;
endpoint: string;
p256dh: string;
auth: string;
device_name: string | null;
created_at: number;
last_used_at: number | null;
}>;
return rows.map((row) => ({
id: row.id,
userId: row.user_id,
endpoint: row.endpoint,
p256dh: row.p256dh,
auth: row.auth,
deviceName: row.device_name,
createdAt: row.created_at,
lastUsedAt: row.last_used_at,
}));
}
getAllUserIds(): string[] {
const rows = this.db
.prepare("SELECT DISTINCT user_id FROM push_subscriptions")
.all() as Array<{ user_id: string }>;
return rows.map((r) => r.user_id);
}
private hasActiveSSEClients(): boolean {
return sseAggregator.hasVisibleClients();
}
async handleSSEEvent(
_directory: string,
event: SSEEvent
): Promise<void> {
const config = EVENT_CONFIG[event.type];
if (!config) return;
if (this.hasActiveSSEClients()) return;
if (!this.isConfigured()) return;
const userIds = this.getAllUserIds();
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[config.preferencesKey]) continue;
const sessionId = event.properties.sessionID as string | undefined;
let notificationUrl = "/";
if (sessionId && _directory) {
const reposBasePath = getReposPath();
const localPath = path.relative(reposBasePath, _directory);
const repo = getRepoByLocalPath(this.db, localPath);
if (repo) {
notificationUrl = `/repos/${repo.id}/sessions/${sessionId}`;
}
}
const payload: PushNotificationPayload = {
title: config.title,
body: config.bodyFn(event.properties),
tag: `${event.type}-${sessionId ?? "global"}`,
data: {
eventType: event.type,
sessionId,
directory: _directory,
url: notificationUrl,
},
};
await this.sendToUser(userId, payload);
}
}
async sendTestNotification(userId: string): Promise<void> {
await this.sendToUser(userId, {
title: "Test Notification",
body: "Push notifications are working correctly",
tag: "test",
data: { eventType: "test", url: "/" },
});
}
private async sendToUser(
userId: string,
payload: PushNotificationPayload
): Promise<void> {
const subscriptions = this.getSubscriptions(userId);
const expiredEndpoints: string[] = [];
await Promise.allSettled(
subscriptions.map(async (sub) => {
try {
await webpush.sendNotification(
{
endpoint: sub.endpoint,
keys: { p256dh: sub.p256dh, auth: sub.auth },
},
JSON.stringify(payload)
);
this.db
.prepare(
"UPDATE push_subscriptions SET last_used_at = ? WHERE id = ?"
)
.run(Date.now(), sub.id);
} catch (error) {
const statusCode = (error as { statusCode?: number }).statusCode;
if (statusCode === 404 || statusCode === 410) {
expiredEndpoints.push(sub.endpoint);
} else {
logger.error(`Push delivery failed for ${sub.endpoint.slice(0, 50)}:`, error);
}
}
})
);
for (const endpoint of expiredEndpoints) {
this.removeSubscription(endpoint);
}
}
}
+32 -2
View File
@@ -4,11 +4,13 @@ import { ENV } from '@opencode-manager/shared/config/env'
import { DEFAULTS } from '@opencode-manager/shared/config'
type SSEClientCallback = (event: string, data: string) => void
type SSEEventListener = (directory: string, event: SSEEvent) => void
interface SSEClient {
id: string
callback: SSEClientCallback
directories: Set<string>
visible: boolean
}
interface DirectoryConnection {
@@ -18,7 +20,7 @@ interface DirectoryConnection {
isConnected: boolean
}
interface SSEEvent {
export interface SSEEvent {
type: string
properties: Record<string, unknown>
}
@@ -33,6 +35,7 @@ class SSEAggregator {
private activeSessions: Map<string, Set<string>> = new Map()
private idleTimeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()
private sessionStateVersion: Map<string, number> = new Map()
private eventListeners: Set<SSEEventListener> = new Set()
private constructor() {}
@@ -47,7 +50,8 @@ class SSEAggregator {
const client: SSEClient = {
id,
callback,
directories: new Set(directories)
directories: new Set(directories),
visible: false
}
this.clients.set(id, client)
@@ -192,10 +196,18 @@ class SSEAggregator {
}, conn.reconnectDelay)
}
onEvent(listener: SSEEventListener): () => void {
this.eventListeners.add(listener)
return () => { this.eventListeners.delete(listener) }
}
private broadcastToDirectory(directory: string, event: string, data: string): void {
try {
const parsed = JSON.parse(data) as SSEEvent
this.handleEvent(directory, parsed)
this.eventListeners.forEach(listener => {
try { listener(directory, parsed) } catch { /* ignore listener errors */ }
})
} catch {
// Ignore parse errors
}
@@ -341,6 +353,23 @@ class SSEAggregator {
return this.clients.size
}
setClientVisibility(id: string, visible: boolean): boolean {
const client = this.clients.get(id)
if (!client) {
logger.warn(`setClientVisibility: client ${id} not found`)
return false
}
client.visible = visible
return true
}
hasVisibleClients(): boolean {
for (const client of this.clients.values()) {
if (client.visible) return true
}
return false
}
getActiveDirectories(): string[] {
return Array.from(this.connections.keys())
}
@@ -364,6 +393,7 @@ class SSEAggregator {
})
this.connections.clear()
this.clients.clear()
this.eventListeners.clear()
}
getActiveSessions(): Record<string, string[]> {
+3
View File
@@ -39,6 +39,9 @@ services:
- PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost}
- PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager}
- PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003}
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY:-}
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY:-}
- VAPID_SUBJECT=${VAPID_SUBJECT:-}
volumes:
- opencode-workspace:/workspace
- opencode-data:/app/data
+63 -17
View File
@@ -33,9 +33,38 @@ Complete reference for all configuration options.
| `PASSKEY_RP_NAME` | Display name for passkey prompts | `OpenCode Manager` |
| `PASSKEY_ORIGIN` | Origin URL for WebAuthn (backend port) | `http://localhost:5003` |
!!! tip "IMPORTANT"
- `PASSKEY_ORIGIN` must use the **backend** port (5003), not the frontend port (5173)
- The origin must exactly match where the auth API is served
## Push Notifications (VAPID)
| Variable | Description | Required |
|----------|-------------|----------|
| `VAPID_PUBLIC_KEY` | VAPID public key for push notifications | Yes |
| `VAPID_PRIVATE_KEY` | VAPID private key for push notifications | Yes |
| `VAPID_SUBJECT` | Contact email for VAPID (MUST use `mailto:` format) | Yes |
### Generating VAPID Keys
Generate VAPID public/private key pair:
```bash
npx web-push generate-vapid-keys
```
Add to `.env`:
```bash
VAPID_PUBLIC_KEY=BMx-1234567890abcdefghijklmnopqrstuv...
VAPID_PRIVATE_KEY=abcd1234567890abcdef...
VAPID_SUBJECT=mailto:you@example.com
```
!!! warning "iOS/Safari Requirement"
`VAPID_SUBJECT` **MUST** use `mailto:` format for iOS/Safari push notifications to work. Apple's push service rejects `https://` subjects.
**Correct:** `VAPID_SUBJECT=mailto:you@yourdomain.com`
**Incorrect:** `VAPID_SUBJECT=https://yourdomain.com`
When configured, users can enable push notifications in Settings → Notifications to receive background alerts for agent events.
## Server
@@ -67,6 +96,11 @@ GITHUB_CLIENT_SECRET=your-client-secret
PASSKEY_RP_ID=localhost
PASSKEY_RP_NAME=OpenCode Manager
PASSKEY_ORIGIN=http://localhost:5003
# Push notifications (optional)
VAPID_PUBLIC_KEY=BMx-1234567890abcdefghijklmnopqrstuv...
VAPID_PRIVATE_KEY=abcd1234567890abcdef...
VAPID_SUBJECT=mailto:you@example.com
```
## Generating Secrets
@@ -84,10 +118,32 @@ Output example:
K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
```
!!! warning "Security"
- Never commit AUTH_SECRET to version control
- Use different secrets for development and production
- Rotate secrets periodically
### VAPID Keys
Generate VAPID public/private key pair for push notifications:
```bash
npx web-push generate-vapid-keys
```
Output example:
```
=======================================
Public Key:
BMx-1234567890abcdefghijklmnopqrstuv...
Private Key:
abcd1234567890abcdef...
Subject:
mailto:you@example.com
===========================================
```
!!! warning "iOS/Safari Requirement"
`VAPID_SUBJECT` **MUST** use `mailto:` format for iOS/Safari push notifications to work.
## Environment Precedence
@@ -98,14 +154,4 @@ Variables are loaded in this order (later overrides earlier):
3. Docker Compose `environment` section
4. Docker Compose `env_file` reference
## Validating Configuration
Check your configuration:
```bash
# View current environment (inside container)
docker exec opencode-manager env | grep -E '^(AUTH|ADMIN|PASSKEY)'
# Check if secrets are set (without revealing values)
docker exec opencode-manager sh -c 'if [ -n "$AUTH_SECRET" ]; then echo "AUTH_SECRET: set"; else echo "AUTH_SECRET: NOT SET"; fi'
```
+116
View File
@@ -0,0 +1,116 @@
# Push Notifications
Send background notifications when the OpenCode Manager PWA is closed, keeping you informed of agent activity without keeping the app open.
## Overview
Push notifications allow you to receive alerts on your mobile device or desktop when:
- The **agent needs permission** to continue (file operations, tool use, etc.)
- The **agent has a question** for you (clarifications, confirmations)
- A **session encounters an error** during execution
- A **session completes successfully**
Notifications are only sent when you don't have the app open (no SSE connections), preventing duplicate alerts while you're actively monitoring a session.
## Supported Events
| Event | Description | Default |
|-------|-------------|---------|
| `permissionAsked` | Agent requests permission for an action | Enabled |
| `questionAsked` | Agent asks a clarifying question | Enabled |
| `sessionError` | Session encounters an error | Enabled |
| `sessionIdle` | Session completes successfully | Disabled |
## Browser Compatibility
Push notifications require HTTPS (except on `localhost`) and browser support:
| Browser | Support | Notes |
|---------|---------|-------|
| Chrome/Edge | ✅ Full | Works well |
| Firefox | ✅ Full | Works well |
| Safari (iOS/macOS) | ✅ Full | Requires `mailto:` VAPID subject |
| Android browser | ✅ Full | Works well |
### iOS/Safari Requirements
Apple's Push Notification Service (APNs) has strict requirements:
1. **HTTPS is required** - `localhost` testing requires Safari Dev Tools
2. **VAPID_SUBJECT must use `mailto:` format** - `https://` subjects are rejected
**Correct:** `VAPID_SUBJECT=mailto:you@yourdomain.com`
**Incorrect:** `VAPID_SUBJECT=https://yourdomain.com`
## Setup
### 1. Generate VAPID Keys
Generate VAPID public/private key pair:
```bash
npx web-push generate-vapid-keys
```
Output:
```
=======================================
Public Key:
BMx-123456... (your public key here)
Private Key:
abcd1234... (your private key here)
Subject:
mailto:your-email@example.com
=======================================
```
### 2. Configure Environment Variables
Add to your `.env` file:
```bash
VAPID_PUBLIC_KEY=BMx-123456...
VAPID_PRIVATE_KEY=abcd1234...
VAPID_SUBJECT=mailto:you@yourdomain.com
```
### 3. Subscribe Devices
1. Open OpenCode Manager in your browser
2. Go to **Settings** → **Notifications**
3. Click **Enable Push Notifications**
4. Allow browser permission when prompted
5. Your device is now subscribed
## Managing Subscriptions
### View Subscribed Devices
Navigate to **Settings** → **Notifications** to see all registered devices:
- Device name (if provided)
- Subscription date
- Last used timestamp
### Remove a Device
Click **Unsubscribe** next to a device to remove it from receiving notifications.
### Test Notifications
Go to **Settings** → **Notifications** and click **Send Test Notification** to verify your setup is working.
## Notification Preferences
Control which events trigger notifications:
**Notification Settings:**
- **Enable Push Notifications** - Master toggle (default: off)
- **Permission Requested** - Get notified when agent needs permission (default: on)
- **Question Asked** - Get notified when agent has a question (default: on)
- **Session Error** - Get notified on session errors (default: on)
- **Session Complete** - Get notified when session finishes (default: off)
+9
View File
@@ -68,3 +68,12 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
[Learn more →](mobile.md)
### Push Notifications
- **Background Alerts** - Receive notifications when the app is closed
- **Agent Events** - Get alerted for permissions, questions, errors, and completions
- **Multi-Device** - Subscribe multiple devices (phone, tablet, desktop)
- **Customizable** - Control which events trigger notifications
[Learn more →](notifications.md)
+2 -1
View File
@@ -22,7 +22,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
- **Manage repositories** - Clone, browse, and work with multiple git repos
- **Chat with AI** - Real-time streaming chat with file mentions and slash commands
- **View diffs** - See code changes with syntax highlighting
- **Control from anywhere** - Mobile-first PWA works on any device
- **Control from anywhere** - Mobile-first PWA with push notifications
- **Configure AI** - Manage models, providers, and MCP servers
## Key Features
@@ -31,6 +31,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
- **Git Integration** - View diffs, manage branches, create PRs directly from the UI
- **Real-time Chat** - Stream responses with file mentions and custom slash commands
- **Mobile-First PWA** - Install as an app on any device with offline support
- **Push Notifications** - Get background alerts for agent events when app is closed
- **AI Configuration** - Configure models, providers, OAuth, and custom agents
- **MCP Servers** - Add local or remote MCP servers with pre-built templates
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="manifest" href="/manifest.json" />
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0a0a0a" />
<meta name="description" content="AI-powered coding assistant interface" />
+3 -1
View File
@@ -73,6 +73,8 @@
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "^7.1.7",
"vitest": "^3.2.4"
"vite-plugin-pwa": "^1.2.0",
"vitest": "^3.2.4",
"workbox-precaching": "^7.4.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

+24 -1
View File
@@ -1,4 +1,5 @@
{
"id": "/",
"name": "OpenCode Manager",
"short_name": "OpenCode",
"description": "AI-powered coding assistant interface",
@@ -13,8 +14,30 @@
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml"
},
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/icons/icon-maskable-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/icons/icon-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"categories": ["developer", "productivity", "utilities"],
"lang": "en"
}
}
+64
View File
@@ -0,0 +1,64 @@
import type { PushSubscriptionRecord } from "@opencode-manager/shared/types";
import { API_BASE_URL } from "@/config";
import { fetchWrapper } from "./fetchWrapper";
export const notificationsApi = {
getVapidPublicKey: async (): Promise<{ publicKey: string }> => {
return fetchWrapper(`${API_BASE_URL}/api/notifications/vapid-public-key`);
},
subscribe: async (
subscription: PushSubscriptionJSON,
deviceName?: string,
userId = 'default'
): Promise<{ subscription: PushSubscriptionRecord }> => {
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
endpoint: subscription.endpoint,
keys: subscription.keys,
deviceName,
}),
params: { userId },
});
},
unsubscribe: async (endpoint: string, userId = 'default'): Promise<{ success: boolean }> => {
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ endpoint }),
params: { userId },
});
},
getSubscriptions: async (userId = 'default'): Promise<{
subscriptions: PushSubscriptionRecord[];
}> => {
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscriptions`, {
params: { userId },
});
},
removeSubscription: async (
id: number,
userId = 'default'
): Promise<{ success: boolean }> => {
return fetchWrapper(
`${API_BASE_URL}/api/notifications/subscriptions/${id}`,
{ method: "DELETE", params: { userId } }
);
},
sendTest: async (userId = 'default'): Promise<{
success: boolean;
devicesNotified: number;
}> => {
return fetchWrapper(`${API_BASE_URL}/api/notifications/test`, {
method: "POST",
headers: { "Content-Type": "application/json" },
params: { userId },
});
},
};
+3 -1
View File
@@ -8,8 +8,9 @@ import {
type STTConfig,
type OpenCodeConfigContent,
} from '@opencode-manager/shared'
import type { NotificationPreferences } from '@opencode-manager/shared/types'
export type { TTSConfig, STTConfig, OpenCodeConfigContent }
export type { TTSConfig, STTConfig, OpenCodeConfigContent, NotificationPreferences }
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY }
export interface CustomCommand {
@@ -54,6 +55,7 @@ export interface UserPreferences {
gitIdentity?: GitIdentity
tts?: TTSConfig
stt?: STTConfig
notifications?: NotificationPreferences
repoOrder?: number[]
}
@@ -12,10 +12,9 @@ import { useUserBash } from '@/stores/userBashStore'
import { useMobile } from '@/hooks/useMobile'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissions } from '@/contexts/EventContext'
import { ChevronDown, Upload, X, Mic } from 'lucide-react'
import { ChevronDown, Upload, X, Mic, MicOff } from 'lucide-react'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { SquareFill } from '@/components/ui/square-fill'
import { MentionSuggestions, type MentionItem } from './MentionSuggestions'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
@@ -765,7 +764,7 @@ return (
className="border fixed bottom-19 right-0 md:hidden z-50 p-3 rounded-xl transition-all duration-200 active:scale-95 hover:scale-105 bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 shadow-lg shadow-red-500/30"
title="Stop"
>
<SquareFill className="w-5 h-5" />
<X className="w-5 h-5" />
</button>
)}
@@ -863,7 +862,7 @@ return (
className="hidden md:block p-1.5 px-5 md:p-2 md:px-6 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 hover:border-red-400 shadow-md shadow-red-500/30 hover:shadow-red-500/40 ring-1 ring-red-500/20 hover:ring-red-500/30"
title="Stop"
>
<SquareFill className="w-4 h-4 md:w-5 md:h-5" />
<X className="w-4 h-4 md:w-5 md:h-5" />
</button>
)}
<input
@@ -898,7 +897,7 @@ return (
) : isProcessing && !isRecording ? (
<div className="w-5 h-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
) : isRecording ? (
<SquareFill className="w-5 h-5" />
<MicOff className="w-5 h-5" />
) : (
<Mic className="w-5 h-5" />
)}
@@ -920,7 +919,7 @@ return (
) : isProcessing && !isRecording ? (
<div className="w-5 h-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
) : isRecording ? (
<SquareFill className="w-5 h-5" />
<MicOff className="w-5 h-5" />
) : (
<Mic className="w-5 h-5" />
)}
@@ -1,5 +1,4 @@
import { X, Mic } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
import { X, Mic, MicOff } from 'lucide-react'
interface RecordingOverlayProps {
interimTranscript: string
@@ -44,7 +43,7 @@ export function RecordingOverlay({
onClick={onStop}
className="flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-white border border-red-500/60 shadow-md shadow-red-500/30 transition-all duration-200 active:scale-95"
>
<SquareFill className="w-3 h-3" />
<MicOff className="w-3 h-3" />
<span>Done</span>
</button>
</div>
@@ -0,0 +1,288 @@
import { useNotifications } from "@/hooks/useNotifications";
import { Loader2, BellOff, Trash2, Send, Monitor } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { showToast } from "@/lib/toast";
import { formatDistanceToNow } from "date-fns";
export function NotificationSettings() {
const {
isSupported,
isAvailable,
permission,
isEnabled,
preferences,
subscriptions,
isLoadingSubscriptions,
enable,
disable,
updateEventPreference,
removeDevice,
sendTest,
isSubscribing,
isTesting,
} = useNotifications();
if (!isSupported) {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Push Notifications
</h2>
<div className="flex items-center gap-3 text-muted-foreground">
<BellOff className="h-5 w-5" />
<p className="text-sm">
Push notifications are not supported in this browser.
</p>
</div>
</div>
);
}
if (!isAvailable) {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Push Notifications
</h2>
<div className="flex items-center gap-3 text-muted-foreground">
<BellOff className="h-5 w-5" />
<p className="text-sm">
Push notifications are not configured on the server. Set VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY environment
variables to enable.
</p>
</div>
</div>
);
}
if (permission === "denied") {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Push Notifications
</h2>
<div className="flex items-center gap-3 text-yellow-500">
<BellOff className="h-5 w-5" />
<p className="text-sm">
Notification permission was denied. Please enable notifications in
your browser settings for this site.
</p>
</div>
</div>
);
}
const handleEnable = async () => {
try {
await enable();
showToast.success("Push notifications enabled");
} catch {
showToast.error("Failed to enable push notifications");
}
};
const handleDisable = async () => {
try {
await disable();
showToast.success("Push notifications disabled");
} catch {
showToast.error("Failed to disable push notifications");
}
};
const handleTest = () => {
sendTest(undefined, {
onSuccess: (data) => {
showToast.success(
`Test notification sent to ${data.devicesNotified} device(s)`
);
},
onError: () => {
showToast.error("Failed to send test notification");
},
});
};
return (
<div className="space-y-6">
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">
Push Notifications
</h2>
<div className="space-y-6">
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notificationsEnabled" className="text-base">
Enable push notifications
</Label>
<p className="text-sm text-muted-foreground">
Receive notifications when the app is in the background
</p>
</div>
<Switch
id="notificationsEnabled"
checked={isEnabled}
disabled={isSubscribing}
onCheckedChange={(checked) =>
checked ? handleEnable() : handleDisable()
}
/>
</div>
{isEnabled && (
<>
<div className="space-y-4">
<h3 className="text-sm font-medium text-foreground">
Notification Events
</h3>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label
htmlFor="notifPermission"
className="text-base"
>
Permission requests
</Label>
<p className="text-sm text-muted-foreground">
When the agent needs approval to proceed
</p>
</div>
<Switch
id="notifPermission"
checked={preferences.events.permissionAsked}
onCheckedChange={(checked) =>
updateEventPreference("permissionAsked", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifQuestion" className="text-base">
Agent questions
</Label>
<p className="text-sm text-muted-foreground">
When the agent has a question for you
</p>
</div>
<Switch
id="notifQuestion"
checked={preferences.events.questionAsked}
onCheckedChange={(checked) =>
updateEventPreference("questionAsked", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifError" className="text-base">
Session errors
</Label>
<p className="text-sm text-muted-foreground">
When a session encounters an error
</p>
</div>
<Switch
id="notifError"
checked={preferences.events.sessionError}
onCheckedChange={(checked) =>
updateEventPreference("sessionError", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifIdle" className="text-base">
Session completion
</Label>
<p className="text-sm text-muted-foreground">
When a session finishes processing
</p>
</div>
<Switch
id="notifIdle"
checked={preferences.events.sessionIdle}
onCheckedChange={(checked) =>
updateEventPreference("sessionIdle", checked)
}
/>
</div>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={handleTest}
disabled={isTesting || subscriptions.length === 0}
>
{isTesting ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<Send className="h-4 w-4 mr-2" />
)}
Send test notification
</Button>
</div>
</>
)}
</div>
</div>
{isEnabled && (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Registered Devices
</h2>
{isLoadingSubscriptions ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : subscriptions.length === 0 ? (
<p className="text-sm text-muted-foreground">
No devices registered for push notifications.
</p>
) : (
<div className="space-y-3">
{subscriptions.map((sub) => (
<div
key={sub.id}
className="flex items-center justify-between rounded-lg border border-border p-3"
>
<div className="flex items-center gap-3 min-w-0">
<Monitor className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{sub.deviceName ?? (sub.endpoint.length > 60 ? sub.endpoint.slice(0, 60) + "..." : sub.endpoint)}
</p>
<p className="text-xs text-muted-foreground">
{sub.lastUsedAt
? `Last used ${formatDistanceToNow(sub.lastUsedAt, { addSuffix: true })}`
: `Added ${formatDistanceToNow(sub.createdAt, { addSuffix: true })}`}
</p>
</div>
</div>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive flex-shrink-0"
onClick={() => removeDevice(sub.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
</div>
)}
</div>
);
}
@@ -6,9 +6,8 @@ import { useSettings } from '@/hooks/useSettings'
import { useSTT } from '@/hooks/useSTT'
import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer'
import { sttApi } from '@/api/stt'
import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff } from 'lucide-react'
import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff, MicOff } from 'lucide-react'
import { Switch } from '@/components/ui/switch'
import { SquareFill } from '@/components/ui/square-fill'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Combobox } from '@/components/ui/combobox'
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
@@ -445,7 +444,7 @@ export function STTSettings() {
>
{isRecording ? (
<>
<SquareFill className="w-4 h-4" />
<MicOff className="w-4 h-4" />
Stop
</>
) : isProcessing ? (
@@ -6,9 +6,10 @@ import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManag
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { AccountSettings } from '@/components/settings/AccountSettings'
import { VoiceSettings } from '@/components/settings/VoiceSettings'
import { NotificationSettings } from '@/components/settings/NotificationSettings'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User, Volume2 } from 'lucide-react'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User, Volume2, Bell } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useSwipeBack } from '@/hooks/useMobile'
@@ -17,7 +18,7 @@ interface SettingsDialogProps {
onOpenChange: (open: boolean) => void
}
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice'
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications'
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const [mobileView, setMobileView] = useState<SettingsView>('menu')
@@ -43,6 +44,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const menuItems = [
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
{ id: 'notifications', icon: Bell, label: 'Notifications', description: 'Push notification preferences' },
{ id: 'voice', icon: Volume2, label: 'Voice', description: 'Text-to-speech and speech-to-text settings' },
{ id: 'git', icon: GitBranch, label: 'Git', description: 'Git identity and credentials for repositories' },
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
@@ -59,7 +61,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent
ref={contentRef}
className="max-w-4xl w-full h-[100vh] sm:h-auto sm:w-[95vw] sm:max-h-[90vh] bg-gradient-to-br from-background via-background to-background border-border p-0 sm:rounded-lg overflow-hidden !flex !flex-col left-0 top-0 translate-x-0 translate-y-0 max-h-[100vh] sm:left-[50%] sm:top-[50%] sm:translate-x-[-50%] sm:translate-y-[-50%] [&>button:last-child]:hidden"
className="w-full h-[100vh] sm:h-auto sm:w-[95vw] sm:max-h-[90vh] bg-gradient-to-br from-background via-background to-background border-border p-0 sm:rounded-lg overflow-hidden !flex !flex-col left-0 top-0 translate-x-0 translate-y-0 max-h-[100vh] sm:left-[50%] sm:top-[50%] sm:translate-x-[-50%] sm:translate-y-[-50%] [&>button:last-child]:hidden"
style={swipeStyles}
>
@@ -71,13 +73,16 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
</div>
<Tabs defaultValue="account" className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-7 bg-card p-1">
<TabsList className="grid w-full grid-cols-8 bg-card p-1">
<TabsTrigger value="account" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Account
</TabsTrigger>
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
General
</TabsTrigger>
<TabsTrigger value="notifications" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Notify
</TabsTrigger>
<TabsTrigger value="voice" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Voice
</TabsTrigger>
@@ -100,6 +105,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
<div className="px-6 pb-6">
<TabsContent value="account" className="mt-0"><AccountSettings /></TabsContent>
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent value="notifications" className="mt-0"><NotificationSettings /></TabsContent>
<TabsContent value="voice" className="mt-0"><VoiceSettings /></TabsContent>
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
@@ -162,6 +168,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
{mobileView === 'account' && <AccountSettings />}
{mobileView === 'general' && <GeneralSettings />}
{mobileView === 'notifications' && <NotificationSettings />}
{mobileView === 'voice' && <VoiceSettings />}
{mobileView === 'git' && <GitSettings />}
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
+161
View File
@@ -0,0 +1,161 @@
import { useCallback, useEffect, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { notificationsApi } from "@/api/notifications";
import { useSettings } from "@/hooks/useSettings";
import {
getServiceWorkerRegistration,
urlBase64ToUint8Array,
} from "@/lib/serviceWorker";
import type { NotificationPreferences } from "@/api/types/settings";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@opencode-manager/shared/schemas";
type PermissionState = NotificationPermission | "unsupported";
function getPermissionState(): PermissionState {
if (!("Notification" in window)) return "unsupported";
return Notification.permission;
}
export function useNotifications() {
const queryClient = useQueryClient();
const { preferences, updateSettings } = useSettings();
const [permission, setPermission] = useState<PermissionState>(getPermissionState);
const notificationPrefs: NotificationPreferences =
preferences?.notifications ?? DEFAULT_NOTIFICATION_PREFERENCES;
useEffect(() => {
setPermission(getPermissionState());
}, []);
const { data: vapidData } = useQuery({
queryKey: ["notifications", "vapid-public-key"],
queryFn: notificationsApi.getVapidPublicKey,
staleTime: Infinity,
retry: false,
});
const { data: subscriptionsData, isLoading: isLoadingSubscriptions } =
useQuery({
queryKey: ["notifications", "subscriptions"],
queryFn: () => notificationsApi.getSubscriptions(),
enabled: notificationPrefs.enabled && permission === "granted",
});
const subscribeMutation = useMutation({
mutationFn: async (deviceName?: string) => {
const reg = await getServiceWorkerRegistration();
if (!reg) throw new Error("Service worker not registered");
if (!vapidData?.publicKey) throw new Error("VAPID key not available");
const existingSub = await reg.pushManager.getSubscription();
if (existingSub) {
const json = existingSub.toJSON();
return notificationsApi.subscribe(json, deviceName);
}
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidData.publicKey).buffer as ArrayBuffer,
});
const json = subscription.toJSON();
return notificationsApi.subscribe(json, deviceName);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["notifications", "subscriptions"],
});
},
});
const unsubscribeMutation = useMutation({
mutationFn: async () => {
const reg = await getServiceWorkerRegistration();
if (reg) {
const sub = await reg.pushManager.getSubscription();
if (sub) {
await notificationsApi.unsubscribe(sub.endpoint);
await sub.unsubscribe();
}
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["notifications", "subscriptions"],
});
},
});
const removeDeviceMutation = useMutation({
mutationFn: (id: number) => notificationsApi.removeSubscription(id),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["notifications", "subscriptions"],
});
},
});
const testMutation = useMutation({
mutationFn: () => notificationsApi.sendTest(),
});
const requestPermissionAndSubscribe = useCallback(async (): Promise<boolean> => {
if (!("Notification" in window)) return false;
const result = await Notification.requestPermission();
setPermission(result);
if (result !== "granted") return false;
const reg = await getServiceWorkerRegistration();
if (reg) {
await subscribeMutation.mutateAsync(undefined);
}
return true;
}, [subscribeMutation]);
const enable = useCallback(async () => {
const granted = await requestPermissionAndSubscribe();
if (!granted) return;
updateSettings({
notifications: { ...notificationPrefs, enabled: true },
});
}, [requestPermissionAndSubscribe, updateSettings, notificationPrefs]);
const disable = useCallback(async () => {
await unsubscribeMutation.mutateAsync();
updateSettings({
notifications: { ...notificationPrefs, enabled: false },
});
}, [unsubscribeMutation, updateSettings, notificationPrefs]);
const updateEventPreference = useCallback(
(key: keyof NotificationPreferences["events"], value: boolean) => {
updateSettings({
notifications: {
...notificationPrefs,
events: { ...notificationPrefs.events, [key]: value },
},
});
},
[updateSettings, notificationPrefs]
);
return {
isSupported: "Notification" in window && "serviceWorker" in navigator,
isAvailable: !!vapidData?.publicKey,
permission,
isEnabled: notificationPrefs.enabled,
preferences: notificationPrefs,
subscriptions: subscriptionsData?.subscriptions ?? [],
isLoadingSubscriptions,
enable,
disable,
updateEventPreference,
removeDevice: removeDeviceMutation.mutate,
sendTest: testMutation.mutate,
isSubscribing: subscribeMutation.isPending,
isTesting: testMutation.isPending,
};
}
+8 -1
View File
@@ -6,7 +6,7 @@ import { showToast } from '@/lib/toast'
import { settingsApi } from '@/api/settings'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import { subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
import { parseOpenCodeError } from '@/lib/opencode-errors'
const handleRestartServer = async () => {
@@ -363,6 +363,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
if (connected) {
setError(null)
fetchInitialData()
sseManager.reportVisibility(document.visibilityState === 'visible')
} else {
setError('Connection lost. Reconnecting...')
}
@@ -376,11 +377,17 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
reconnectSSE()
}
const handleVisibilityChange = () => {
sseManager.reportVisibility(document.visibilityState === 'visible')
}
document.addEventListener('visibilitychange', handleVisibilityChange)
window.addEventListener('focus', handleReconnect)
window.addEventListener('online', handleReconnect)
return () => {
mountedRef.current = false
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('focus', handleReconnect)
window.removeEventListener('online', handleReconnect)
unsubscribe()
+32
View File
@@ -0,0 +1,32 @@
export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
if (!("serviceWorker" in navigator)) return null;
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
type: "module",
});
registration.update().catch(() => {});
return registration;
} catch {
return null;
}
}
export async function getServiceWorkerRegistration(): Promise<ServiceWorkerRegistration | null> {
if (!("serviceWorker" in navigator)) return null;
return (await navigator.serviceWorker.getRegistration("/")) ?? null;
}
export function urlBase64ToUint8Array(base64String: string): Uint8Array {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
+9
View File
@@ -266,6 +266,15 @@ class SSEManager {
return this.isConnected
}
reportVisibility(visible: boolean): void {
if (!this.clientId || !this.isConnected) return
fetch('/api/sse/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, visible })
}).catch(() => {})
}
async ensureConnected(timeoutMs: number = 5000): Promise<boolean> {
if (this.isConnected && this.clientId) {
return true
+3
View File
@@ -2,6 +2,9 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { registerServiceWorker } from './lib/serviceWorker'
registerServiceWorker().catch(() => {})
createRoot(document.getElementById('root')!).render(
<StrictMode>
+82
View File
@@ -0,0 +1,82 @@
/// <reference lib="webworker" />
import { precacheAndRoute, cleanupOutdatedCaches } from "workbox-precaching";
declare const self: ServiceWorkerGlobalScope & {
__WB_MANIFEST: Array<{ url: string; revision: string | null }>;
};
cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST);
interface PushNotificationData {
title: string;
body: string;
icon?: string;
badge?: string;
tag?: string;
data?: {
url?: string;
eventType: string;
sessionId?: string;
directory?: string;
};
}
self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener("install", () => {
self.skipWaiting();
});
self.addEventListener("push", (event: PushEvent) => {
if (!event.data) return;
let payload: PushNotificationData;
try {
payload = event.data.json() as PushNotificationData;
} catch {
payload = {
title: "OpenCode Manager",
body: event.data.text(),
data: { eventType: "unknown" },
};
}
const options: NotificationOptions = {
body: payload.body,
icon: payload.icon ?? "/icons/icon-192x192.png",
badge: payload.badge ?? "/icons/icon-192x192.png",
tag: payload.tag,
data: payload.data,
requireInteraction: isHighPriority(payload.data?.eventType),
};
event.waitUntil(self.registration.showNotification(payload.title, options));
});
self.addEventListener("notificationclick", (event: NotificationEvent) => {
event.notification.close();
const url = (event.notification.data?.url as string) ?? "/";
event.waitUntil(
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
if (new URL(client.url).origin === self.location.origin) {
client.focus();
(client as WindowClient).navigate(url);
return;
}
}
return self.clients.openWindow(url);
})
);
});
function isHighPriority(eventType?: string): boolean {
return eventType === "permission.asked" || eventType === "question.asked";
}
+1 -1
View File
@@ -31,6 +31,6 @@
}
},
"include": ["src"],
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/sw.ts"]
}
+2 -1
View File
@@ -2,6 +2,7 @@
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.sw.json" }
]
}
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022", "WebWorker"],
"moduleResolution": "bundler",
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true
},
"include": ["src/sw.ts"]
}
+19 -1
View File
@@ -2,6 +2,7 @@ import path from "path";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import { VitePWA } from "vite-plugin-pwa";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, path.resolve(__dirname, ".."), "");
@@ -9,7 +10,24 @@ export default defineConfig(({ mode }) => {
return {
envDir: path.resolve(__dirname, ".."),
plugins: [react(), tailwindcss()],
plugins: [
react(),
tailwindcss(),
VitePWA({
registerType: "autoUpdate",
strategies: "injectManifest",
srcDir: "src",
filename: "sw.ts",
injectRegister: false,
manifest: false,
injectManifest: {
globPatterns: ["**/*.{html,svg,png,ico}"],
},
devOptions: {
enabled: false,
},
}),
],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
+1
View File
@@ -45,6 +45,7 @@ nav:
- AI Configuration: features/ai-config.md
- MCP Servers: features/mcp.md
- Text-to-Speech: features/tts.md
- Push Notifications: features/notifications.md
- Mobile & PWA: features/mobile.md
- Configuration:
- Environment Variables: configuration/environment.md
+2978 -23
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -87,6 +87,12 @@ export const ENV = {
LOG_LEVEL: getEnvString('LOG_LEVEL', DEFAULTS.LOGGING.LOG_LEVEL),
},
VAPID: {
PUBLIC_KEY: process.env.VAPID_PUBLIC_KEY ?? '',
PRIVATE_KEY: process.env.VAPID_PRIVATE_KEY ?? '',
SUBJECT: process.env.VAPID_SUBJECT ?? '',
},
AUTH: {
SECRET: getEnvString('AUTH_SECRET', process.env.NODE_ENV === 'production' ? '' : generateDefaultSecret()),
TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003'),
+1
View File
@@ -4,3 +4,4 @@ export * from './files'
export * from './opencode'
export * from './auth'
export * from './sse'
export * from './notifications'
+69
View File
@@ -0,0 +1,69 @@
import { z } from "zod";
export const NotificationEventType = {
PERMISSION_ASKED: "permission.asked",
QUESTION_ASKED: "question.asked",
SESSION_ERROR: "session.error",
SESSION_IDLE: "session.idle",
} as const;
export type NotificationEventType =
(typeof NotificationEventType)[keyof typeof NotificationEventType];
export const NotificationPreferencesSchema = z.object({
enabled: z.boolean(),
events: z.object({
permissionAsked: z.boolean(),
questionAsked: z.boolean(),
sessionError: z.boolean(),
sessionIdle: z.boolean(),
}),
});
export const DEFAULT_NOTIFICATION_PREFERENCES = {
enabled: false,
events: {
permissionAsked: true,
questionAsked: true,
sessionError: true,
sessionIdle: false,
},
};
export const PushSubscriptionKeysSchema = z.object({
p256dh: z.string(),
auth: z.string(),
});
export const PushSubscriptionRequestSchema = z.object({
endpoint: z.string().url(),
keys: PushSubscriptionKeysSchema,
deviceName: z.string().optional(),
});
export const PushSubscriptionRecordSchema = z.object({
id: z.number(),
userId: z.string(),
endpoint: z.string(),
p256dh: z.string(),
auth: z.string(),
deviceName: z.string().nullable(),
createdAt: z.number(),
lastUsedAt: z.number().nullable(),
});
export const PushNotificationPayloadSchema = z.object({
title: z.string(),
body: z.string(),
icon: z.string().optional(),
badge: z.string().optional(),
tag: z.string().optional(),
data: z
.object({
url: z.string().optional(),
eventType: z.string(),
sessionId: z.string().optional(),
directory: z.string().optional(),
})
.optional(),
});
+3
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { NotificationPreferencesSchema, DEFAULT_NOTIFICATION_PREFERENCES } from "./notifications";
export const CustomCommandSchema = z.object({
name: z.string(),
@@ -124,6 +125,7 @@ export const UserPreferencesSchema = z.object({
gitIdentity: GitIdentitySchema.optional(),
tts: TTSConfigSchema.optional(),
stt: STTConfigSchema.optional(),
notifications: NotificationPreferencesSchema.optional(),
lastKnownGoodConfig: z.string().optional(),
repoOrder: z.array(z.number()).optional(),
});
@@ -169,6 +171,7 @@ export const DEFAULT_USER_PREFERENCES = {
gitIdentity: DEFAULT_GIT_IDENTITY,
tts: DEFAULT_TTS_CONFIG,
stt: DEFAULT_STT_CONFIG,
notifications: DEFAULT_NOTIFICATION_PREFERENCES,
};
export const SettingsResponseSchema = z.object({
+6
View File
@@ -5,4 +5,10 @@ export const SSESubscribeSchema = z.object({
directories: z.array(z.string()),
});
export const SSEVisibilitySchema = z.object({
clientId: z.string().min(1),
visible: z.boolean(),
});
export type SSESubscribeRequest = z.infer<typeof SSESubscribeSchema>;
export type SSEVisibilityRequest = z.infer<typeof SSEVisibilitySchema>;
+11
View File
@@ -30,6 +30,12 @@ import {
SessionSchema,
MessageSchema,
} from '../schemas/opencode'
import {
NotificationPreferencesSchema,
PushSubscriptionRequestSchema,
PushSubscriptionRecordSchema,
PushNotificationPayloadSchema,
} from '../schemas/notifications'
export type UserPreferences = z.infer<typeof UserPreferencesSchema>
export type SettingsResponse = z.infer<typeof SettingsResponseSchema>
@@ -58,6 +64,11 @@ export type FilePatchRequest = z.infer<typeof FilePatchRequestSchema>
export type Session = z.infer<typeof SessionSchema>
export type Message = z.infer<typeof MessageSchema>
export type NotificationPreferences = z.infer<typeof NotificationPreferencesSchema>
export type PushSubscriptionRequest = z.infer<typeof PushSubscriptionRequestSchema>
export type PushSubscriptionRecord = z.infer<typeof PushSubscriptionRecordSchema>
export type PushNotificationPayload = z.infer<typeof PushNotificationPayloadSchema>
export interface ErrorResponse {
error: string
details?: unknown