Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

desktop: add notifications (and icons) #4535

Merged
merged 4 commits into from
Mar 17, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
desktop: get desktop notifications working
patosullivan committed Mar 17, 2025
commit 55725bfc4c78129f4615abbb6b8961ed6f4de62f
3 changes: 3 additions & 0 deletions apps/tlon-desktop/src/main/index.ts
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import { BrowserWindow, app, ipcMain, shell } from 'electron';
import fs from 'fs';
import path from 'path';

import { setupNotificationService } from './notification-service';
import { setupSQLiteIPC } from './sqlite-service';
import store from './store';

@@ -108,6 +109,8 @@ async function createWindow() {
},
});

setupNotificationService(mainWindow);

const webSession = mainWindow.webContents.session;

// Add auth cookie to requests
28 changes: 28 additions & 0 deletions apps/tlon-desktop/src/main/notification-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { BrowserWindow, Notification, ipcMain } from 'electron';

export function setupNotificationService(mainWindow: BrowserWindow) {
ipcMain.handle('show-notification', (event, { title, body, data }) => {
// Don't show notifications if window is focused and visible
if (mainWindow.isFocused() && mainWindow.isVisible()) {
return false;
}

const notification = new Notification({
title,
body,
silent: false
});

notification.on('click', () => {
// Focus window when notification is clicked
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();

// Send notification data back to renderer for navigation
mainWindow.webContents.send('notification-clicked', data);
});

notification.show();
return true;
});
}
10 changes: 10 additions & 0 deletions apps/tlon-desktop/src/preload/preload.ts
Original file line number Diff line number Diff line change
@@ -11,6 +11,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
storeAuthInfo: (authInfo) => ipcRenderer.invoke('store-auth-info', authInfo),
getAuthInfo: () => ipcRenderer.invoke('get-auth-info'),
clearAuthInfo: () => ipcRenderer.invoke('clear-auth-info'),

// Notification functions
showNotification: (options) => ipcRenderer.invoke('show-notification', options),
onNotificationClicked: (callback) => {
const handler = (_event: IpcRendererEvent, data: any) => callback(data);
ipcRenderer.on('notification-clicked', handler);
return () => {
ipcRenderer.removeListener('notification-clicked', handler);
};
},
});

// Expose SQLite bridge
4 changes: 3 additions & 1 deletion apps/tlon-web-new/src/app.tsx
Original file line number Diff line number Diff line change
@@ -36,6 +36,7 @@ import { useIsDark, useIsMobile } from '@/logic/useMedia';
import { preSig } from '@/logic/utils';
import { toggleDevTools, useLocalState, useShowDevTools } from '@/state/local';
import { useAnalyticsId, useLogActivity, useTheme } from '@/state/settings';
import useDesktopNotifications from '@tloncorp/app/hooks/useDesktopNotifications';

import { DesktopLoginScreen } from './components/DesktopLoginScreen';
import { isElectron } from './electron-bridge';
@@ -268,7 +269,8 @@ function ConnectedDesktopApp({
const configureClient = useConfigureUrbitClient();
const hasSyncedRef = React.useRef(false);
useFindSuggestedContacts();

useDesktopNotifications(clientReady);

useEffect(() => {
window.ship = ship;
window.our = ship;
4 changes: 4 additions & 0 deletions apps/tlon-web-new/src/electron-bridge.ts
Original file line number Diff line number Diff line change
@@ -7,6 +7,10 @@ declare global {
storeAuthInfo: (authInfo: any) => Promise<boolean>;
getAuthInfo: () => Promise<any>;
clearAuthInfo: () => Promise<boolean>;

// Notification functions
showNotification: (options: { title: string; body: string; data?: any }) => Promise<boolean>;
onNotificationClicked: (callback: (data: any) => void) => () => void;
};
sqliteBridge?: {
init: () => Promise<boolean>;
158 changes: 158 additions & 0 deletions packages/app/hooks/useDesktopNotifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { createDevLogger } from '@tloncorp/shared';
import * as api from '@tloncorp/shared/api';
import * as db from '@tloncorp/shared/db';
import { getTextContent } from '@tloncorp/shared/urbit';
import { useCallback, useEffect, useRef } from 'react';

import { useIsElectron } from './useIsElectron';

const logger = createDevLogger('useDesktopNotifications', false);

interface NotificationData {
type: string;
channelId?: string;
groupId?: string;
}

export default function useDesktopNotifications(isClientReady: boolean) {
const processedNotifications = useRef<Set<string>>(new Set());
const isElectron = useIsElectron();

const processActivityEvent = useCallback(
async (activityEvent: db.ActivityEvent) => {
if (!isElectron || !window.electronAPI) {
return;
}

const notificationKey = `${activityEvent.channelId}-${activityEvent.timestamp}`;

if (processedNotifications.current.has(notificationKey)) {
return;
}

processedNotifications.current.add(notificationKey);

// Limit the size of the set to avoid memory leaks
if (processedNotifications.current.size > 100) {
// Keep only the most recent 50 notification keys
processedNotifications.current = new Set(
Array.from(processedNotifications.current).slice(-50)
);
}

let body = '';

if (!activityEvent.channelId) {
logger.error('No channel ID in activity event:', activityEvent);
return;
}

try {
const channel = await db.getChannelWithRelations({
id: activityEvent.channelId,
});
if (activityEvent.content) {
body =
getTextContent(activityEvent.content as api.PostContent) ||
'New message';
} else {
body = 'New message';
}

const contactId = activityEvent.authorId;
const contact = contactId
? await db.getContact({ id: contactId })
: null;

if (!channel) return;

let title = channel.title
? channel.title
: contact?.peerNickname
? contact.peerNickname
: contact?.customNickname
? contact.customNickname
: contactId
? contactId
: 'New Message';

const contactName = contact?.peerNickname
? contact.peerNickname
: contact?.customNickname
? contact.customNickname
: contactId;

if (activityEvent.groupId) {
const group = await db.getGroup({ id: activityEvent.groupId });
if (group) {
if (activityEvent.content) {
body = `${contactName}: ${getTextContent(activityEvent.content as api.PostContent)}`;
title = title + ` in ${group.title}`;
} else {
body = `New message in ${group.title}`;
}
}
}

logger.log('Showing desktop notification:', title);

window.electronAPI.showNotification({
title,
body,
data: {
type: 'channel',
channelId: activityEvent.channelId,
groupId: channel.groupId,
},
});
} catch (error) {
logger.error(
'Error processing channel activity for notifications',
error
);
}
},
[]
);

const handleNotificationClick = useCallback(
async (data: NotificationData) => {
if (!data || !data.channelId) return;

try {
logger.log('Notification clicked:', data);
await api.markChatRead(data.channelId);

// In the future, we could add navigation logic here
} catch (error) {
logger.error('Error handling notification click', error);
}
},
[]
);

useEffect(() => {
if (!isElectron || !window.electronAPI || !isClientReady) return;

const handleActivityEvent = (event: api.ActivityEvent) => {
console.log('Activity event:', event);
if (event.type === 'addActivityEvent' && event.events[0].shouldNotify) {
processActivityEvent(event.events[0]);
}
};

api.subscribeToActivity(handleActivityEvent);

const unsubscribeNotificationClick =
window.electronAPI.onNotificationClicked(handleNotificationClick);

return () => {
unsubscribeNotificationClick();
};
}, [
processActivityEvent,
handleNotificationClick,
isClientReady,
isElectron,
]);
}
18 changes: 18 additions & 0 deletions packages/app/window.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
interface ElectronAPI {
setUrbitShip: (shipUrl: string) => Promise<boolean>;
getVersion: () => Promise<string>;
loginToShip: (shipUrl: string, accessCode: string) => Promise<string>;
storeAuthInfo: (authInfo: any) => Promise<boolean>;
getAuthInfo: () => Promise<any>;
clearAuthInfo: () => Promise<boolean>;

// Notification functions
showNotification: (options: {
title: string;
body: string;
data?: any;
}) => Promise<boolean>;
onNotificationClicked: (callback: (data: any) => void) => () => void;
}

declare global {
interface Window {
our: string;
electronAPI?: ElectronAPI;
}
}