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
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions apps/tlon-desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"gatekeeperAssess": false,
"entitlements": null,
"entitlementsInherit": null,
"icon": "resources/icons/mac/icon.icns",
"target": [
{
"target": "dmg",
Expand All @@ -76,6 +77,7 @@
]
},
"win": {
"icon": "resources/icons/win/icon.ico",
"target": [
{
"target": "nsis",
Expand All @@ -86,6 +88,7 @@
]
},
"linux": {
"icon": "resources/icons/png",
"target": "AppImage"
}
}
Expand Down
Binary file added apps/tlon-desktop/resources/icons/mac/icon.icns
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/128x128.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/16x16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/24x24.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/256x256.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/48x48.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/png/64x64.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/tlon-desktop/resources/icons/win/icon.ico
Binary file not shown.
30 changes: 14 additions & 16 deletions apps/tlon-desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -93,18 +94,23 @@ interface AuthInfo {
let mainWindow: BrowserWindow | null = null;

async function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.resolve(__dirname, '../../build/main/preload.js'),
// SECURITY NOTE: webSecurity is disabled to allow communication with local Urbit ships
// This is necessary because Urbit doesn't properly handle CORS/OPTIONS preflight requests
// for SSE connections (it just prints `eyre: session not a put` and doesn't respond).
// Long-term, we should implement a more secure solution.
webSecurity: false,
},
});

setupNotificationService(mainWindow);

const webSession = mainWindow.webContents.session;

// Add auth cookie to requests
Expand All @@ -129,26 +135,17 @@ async function createWindow() {
});

// Configure session for CORS handling
// We've disabled web security for now, so we don't need to worry about this.
// We should probably revisit this and re-enable web security.
// webSession.webRequest.onBeforeSendHeaders((details, callback) => {
// // Only modify headers for requests to the configured ship
// if (cachedShipUrl && details.url.startsWith(cachedShipUrl)) {
// callback({
// requestHeaders: details.requestHeaders,
// });
// } else {
// callback({ requestHeaders: details.requestHeaders });
// }
// });

// Disabled for now, see above note about disabling webSecurity
// webSession.webRequest.onHeadersReceived((details, callback) => {
// // Only modify headers for responses from the configured ship
// if (cachedShipUrl && details.url.startsWith(cachedShipUrl)) {
// console.log('Setting CORS headers for response from', cachedShipUrl);

// if (details.method === 'OPTIONS') {
// console.log('Setting CORS headers for OPTIONS request');
// console.log(
// 'Setting CORS headers for OPTIONS request',
// JSON.stringify(details)
// );
// callback({
// responseHeaders: {
// ...details.responseHeaders,
Expand All @@ -162,13 +159,14 @@ async function createWindow() {
// status: ['200'],
// statusText: ['OK'],
// },
// statusLine: 'HTTP/1.1 200 OK',
// });
// } else {
// console.log('Setting CORS headers for non-OPTIONS request');
// callback({
// responseHeaders: {
// ...details.responseHeaders,
// 'Access-Control-Allow-Origin': ['http://localhost:3000'],
// 'Access-Control-Allow-Origin': ['*'],
// 'Access-Control-Allow-Methods': ['GET, POST, PUT, DELETE, OPTIONS'],
// 'Access-Control-Allow-Headers': [
// 'Content-Type, Authorization, Cookie',
Expand Down
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
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion apps/tlon-web-new/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -268,7 +269,8 @@ function ConnectedDesktopApp({
const configureClient = useConfigureUrbitClient();
const hasSyncedRef = React.useRef(false);
useFindSuggestedContacts();

useDesktopNotifications(clientReady);

useEffect(() => {
window.ship = ship;
window.our = ship;
Expand Down
4 changes: 4 additions & 0 deletions apps/tlon-web-new/src/electron-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
Expand Down
154 changes: 154 additions & 0 deletions packages/app/hooks/useDesktopNotifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
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?.nickname
? contact.nickname
: 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) => {
logger.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;
}
}

Expand Down