Type the electron and matrix plugin call sites instead of any. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 2s

This commit is contained in:
2026-11-01 22:08:24 +11:00
parent eaa9ac00dd
commit 3781b05f6f
4 changed files with 67 additions and 54 deletions
+23 -23
View File
@@ -7,7 +7,7 @@
* To use this, import and call initPaarrotAPI() early in your app initialization. * To use this, import and call initPaarrotAPI() early in your app initialization.
*/ */
import { MatrixClient } from 'matrix-js-sdk'; import { MatrixClient, Room } from 'matrix-js-sdk';
import { getHomeRoomPath, getDirectRoomPath, getSpaceRoomPath } from './pages/pathUtils'; import { getHomeRoomPath, getDirectRoomPath, getSpaceRoomPath } from './pages/pathUtils';
import { getCanonicalAliasOrRoomId } from './utils/matrix'; import { getCanonicalAliasOrRoomId } from './utils/matrix';
import { getCallService } from './features/call/useCall'; import { getCallService } from './features/call/useCall';
@@ -31,11 +31,7 @@ let navigateFunction: ((path: string) => void) | null = null;
*/ */
let isInitialized = false; let isInitialized = false;
/** function isSpaceLikeRoom(room: Room): boolean {
* @param {any} room
* @returns {boolean}
*/
function isSpaceLikeRoom(room: any): boolean {
if (!room) return false; if (!room) return false;
if (typeof room.isSpaceRoom === 'function' && room.isSpaceRoom()) return true; if (typeof room.isSpaceRoom === 'function' && room.isSpaceRoom()) return true;
const roomKindEvent = room.currentState?.getStateEvents?.(StateEvent.PaarrotRoomKind, ''); const roomKindEvent = room.currentState?.getStateEvents?.(StateEvent.PaarrotRoomKind, '');
@@ -237,7 +233,7 @@ async function setDeafen(matrixClient: MatrixClient, deafened: boolean) {
/** /**
* Change to a different room/channel * Change to a different room/channel
*/ */
async function changeChannel(matrixClient: any, roomId: string) { async function changeChannel(matrixClient: MatrixClient, roomId: string) {
const room = matrixClient?.getRoom(roomId); const room = matrixClient?.getRoom(roomId);
if (!room) { if (!room) {
throw new Error(`Room not found: ${roomId}`); throw new Error(`Room not found: ${roomId}`);
@@ -280,12 +276,12 @@ async function changeChannel(matrixClient: any, roomId: string) {
/** /**
* Get list of rooms/channels * Get list of rooms/channels
*/ */
async function getChannels(matrixClient: any) { async function getChannels(matrixClient: MatrixClient) {
const rooms = matrixClient?.getRooms() || []; const rooms = matrixClient?.getRooms() || [];
return rooms return rooms
.filter((room: any) => !isSpaceLikeRoom(room)) .filter((room) => !isSpaceLikeRoom(room))
.map((room: any) => { .map((room) => {
// Extract server domain from roomId (!localpart:domain.tld) // Extract server domain from roomId (!localpart:domain.tld)
const serverMatch = room.roomId.match(/:(.+)$/); const serverMatch = room.roomId.match(/:(.+)$/);
const server = serverMatch ? serverMatch[1] : null; const server = serverMatch ? serverMatch[1] : null;
@@ -298,7 +294,7 @@ async function getChannels(matrixClient: any) {
avatar: room.getMxcAvatarUrl() || null, avatar: room.getMxcAvatarUrl() || null,
}; };
}) })
.sort((a: any, b: any) => a.name.localeCompare(b.name)); .sort((a, b) => a.name.localeCompare(b.name));
} }
/** /**
@@ -326,7 +322,7 @@ async function sendMessage(matrixClient: any, roomId: string, message: string) {
/** /**
* Send a message to the current room * Send a message to the current room
*/ */
async function sendMessageCurrent(matrixClient: any, message: string) { async function sendMessageCurrent(matrixClient: MatrixClient, message: string) {
const currentRoomId = getCurrentRoomId(); const currentRoomId = getCurrentRoomId();
if (!currentRoomId) { if (!currentRoomId) {
throw new Error('No room currently active'); throw new Error('No room currently active');
@@ -338,7 +334,7 @@ async function sendMessageCurrent(matrixClient: any, message: string) {
/** /**
* Get information about the current room * Get information about the current room
*/ */
async function getCurrentRoom(matrixClient: any) { async function getCurrentRoom(matrixClient: MatrixClient) {
const currentRoomId = getCurrentRoomId(); const currentRoomId = getCurrentRoomId();
if (!currentRoomId) { if (!currentRoomId) {
throw new Error('No room currently active'); throw new Error('No room currently active');
@@ -379,7 +375,7 @@ type ApiMessage = {
body: string; body: string;
}; };
function isDirectRoom(room: any): boolean { function isDirectRoom(room: Room): boolean {
return room?.guessDMUserId?.() !== null; return room?.guessDMUserId?.() !== null;
} }
@@ -395,7 +391,7 @@ function parseMessageLimit(limit?: number | string): number {
* Collect recent room messages from the local live timeline (newest last). * Collect recent room messages from the local live timeline (newest last).
* Skips reactions, edits, and redacted events. * Skips reactions, edits, and redacted events.
*/ */
function collectRecentMessages(room: any, limit: number): ApiMessage[] { function collectRecentMessages(room: Room, limit: number): ApiMessage[] {
const liveEvents = room.getLiveTimeline?.()?.getEvents?.() ?? []; const liveEvents = room.getLiveTimeline?.()?.getEvents?.() ?? [];
const isDirect = isDirectRoom(room); const isDirect = isDirectRoom(room);
const { roomId } = room; const { roomId } = room;
@@ -451,16 +447,16 @@ function collectRecentMessages(room: any, limit: number): ApiMessage[] {
return messages.reverse(); return messages.reverse();
} }
function getRoomsForScope(matrixClient: any, scope: MessageScope) { function getRoomsForScope(matrixClient: MatrixClient, scope: MessageScope) {
const rooms = (matrixClient?.getRooms?.() || []).filter( const rooms = (matrixClient?.getRooms?.() || []).filter(
(room: any) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join', (room) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join',
); );
if (scope === 'groups') { if (scope === 'groups') {
return rooms.filter((room: any) => !isDirectRoom(room)); return rooms.filter((room) => !isDirectRoom(room));
} }
if (scope === 'dms') { if (scope === 'dms') {
return rooms.filter((room: any) => isDirectRoom(room)); return rooms.filter((room) => isDirectRoom(room));
} }
return rooms; return rooms;
} }
@@ -468,7 +464,11 @@ function getRoomsForScope(matrixClient: any, scope: MessageScope) {
/** /**
* Get recent messages across groups, DMs, or both (combined). * Get recent messages across groups, DMs, or both (combined).
*/ */
async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit?: number | string) { async function getMessagesByScope(
matrixClient: MatrixClient,
scope: MessageScope,
limit?: number | string,
) {
const limitNum = parseMessageLimit(limit); const limitNum = parseMessageLimit(limit);
const rooms = getRoomsForScope(matrixClient, scope); const rooms = getRoomsForScope(matrixClient, scope);
@@ -493,7 +493,7 @@ async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit?
* List unread conversations across groups, DMs, or both (combined). * List unread conversations across groups, DMs, or both (combined).
* Uses the same unread rules as the app UI (notification counts + read receipts, muted excluded). * Uses the same unread rules as the app UI (notification counts + read receipts, muted excluded).
*/ */
async function getUnreadsByScope(matrixClient: any, scope: MessageScope) { async function getUnreadsByScope(matrixClient: MatrixClient, scope: MessageScope) {
const rooms = getRoomsForScope(matrixClient, scope); const rooms = getRoomsForScope(matrixClient, scope);
const unreads: Array<{ const unreads: Array<{
roomId: string; roomId: string;
@@ -662,13 +662,13 @@ export function initPaarrotAPI(matrixClient: MatrixClient) {
}); });
console.log('Paarrot API: Action completed successfully:', action.action); console.log('Paarrot API: Action completed successfully:', action.action);
} catch (error: any) { } catch (error) {
console.error('Paarrot API: Action failed:', action.action, error); console.error('Paarrot API: Action failed:', action.action, error);
// Send error response back // Send error response back
(window as any).electron.api.sendResponse(action.responseChannel, { (window as any).electron.api.sendResponse(action.responseChannel, {
success: false, success: false,
error: error.message || 'Unknown error', error: error instanceof Error ? error.message : 'Unknown error',
}); });
} }
}, },
+31 -25
View File
@@ -1,3 +1,4 @@
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { useAtomValue } from 'jotai'; import { useAtomValue } from 'jotai';
import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react'; import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
@@ -137,10 +138,11 @@ function InviteNotifications() {
(count: number) => { (count: number) => {
const body = `You have ${count} new invitation request.`; const body = `You have ${count} new invitation request.`;
const invitesPath = getInboxInvitesPath(); const invitesPath = getInboxInvitesPath();
const { electron } = window;
// Flash taskbar icon for desktop notifications (only visible when window is not focused) // Flash taskbar icon for desktop notifications (only visible when window is not focused)
if (isElectron() && (window as any).electron?.window?.flashFrame) { if (isElectron() && electron?.window?.flashFrame) {
(window as any).electron.window electron.window
.flashFrame(true) .flashFrame(true)
.then((result: { success: boolean }) => { .then((result: { success: boolean }) => {
console.log('[InviteNotifications] flashFrame result:', result); console.log('[InviteNotifications] flashFrame result:', result);
@@ -172,8 +174,8 @@ function InviteNotifications() {
if (!window.closed) navigate(invitesPath); if (!window.closed) navigate(invitesPath);
noti.close(); noti.close();
// Stop flashing when user clicks notification // Stop flashing when user clicks notification
if ((window as any).electron?.window?.flashFrame) { if (electron?.window?.flashFrame) {
(window as any).electron.window.flashFrame(false); electron.window.flashFrame(false);
} }
}; };
} }
@@ -183,12 +185,13 @@ function InviteNotifications() {
const playSound = useCallback(() => { const playSound = useCallback(() => {
console.log('[InviteNotifications] playSound called, isElectron:', isElectron()); console.log('[InviteNotifications] playSound called, isElectron:', isElectron());
if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { const { electron } = window;
if (isElectron() && electron?.audio?.playNotificationSound) {
console.log('[InviteNotifications] Using Electron audio API'); console.log('[InviteNotifications] Using Electron audio API');
(window as any).electron.audio electron.audio
.playNotificationSound('invite') .playNotificationSound('invite')
.then((result: any) => console.log('[InviteNotifications] Sound result:', result)) .then((result) => console.log('[InviteNotifications] Sound result:', result))
.catch((err: any) => console.error('[InviteNotifications] Sound error:', err)); .catch((err) => console.error('[InviteNotifications] Sound error:', err));
} else { } else {
console.log('[InviteNotifications] Using HTML5 Audio fallback'); console.log('[InviteNotifications] Using HTML5 Audio fallback');
new Audio('./sound/invite.ogg').play().catch((err) => { new Audio('./sound/invite.ogg').play().catch((err) => {
@@ -252,6 +255,7 @@ function MessageNotifications() {
}) => { }) => {
const notificationTitle = username; const notificationTitle = username;
const notificationBody = messageBody || 'New message'; const notificationBody = messageBody || 'New message';
const { electron } = window;
/** Replicates TitleBar click navigation logic */ /** Replicates TitleBar click navigation logic */
const navigateToRoom = () => { const navigateToRoom = () => {
@@ -277,8 +281,8 @@ function MessageNotifications() {
// Flash taskbar icon for desktop notifications (only visible when window is not focused) // Flash taskbar icon for desktop notifications (only visible when window is not focused)
console.log('[Notifications] Attempting flashFrame'); console.log('[Notifications] Attempting flashFrame');
if (isElectron() && (window as any).electron?.window?.flashFrame) { if (isElectron() && electron?.window?.flashFrame) {
(window as any).electron.window electron.window
.flashFrame(true) .flashFrame(true)
.then((result: { success: boolean }) => { .then((result: { success: boolean }) => {
console.log('[Notifications] flashFrame result:', result); console.log('[Notifications] flashFrame result:', result);
@@ -316,13 +320,13 @@ function MessageNotifications() {
noti.onclick = () => { noti.onclick = () => {
// Tell main process to bring window to front // Tell main process to bring window to front
(window as any).electron?.window?.focus(); electron?.window?.focus();
if (!window.closed) navigateToRoom(); if (!window.closed) navigateToRoom();
noti.close(); noti.close();
notifRef.current = undefined; notifRef.current = undefined;
// Stop flashing when user clicks notification // Stop flashing when user clicks notification
if ((window as any).electron?.window?.flashFrame) { if (electron?.window?.flashFrame) {
(window as any).electron.window.flashFrame(false); electron.window.flashFrame(false);
} }
}; };
@@ -335,12 +339,13 @@ function MessageNotifications() {
const playSound = useCallback(() => { const playSound = useCallback(() => {
console.log('[MessageNotifications] playSound called, isElectron:', isElectron()); console.log('[MessageNotifications] playSound called, isElectron:', isElectron());
if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { const { electron } = window;
if (isElectron() && electron?.audio?.playNotificationSound) {
console.log('[MessageNotifications] Using Electron audio API'); console.log('[MessageNotifications] Using Electron audio API');
(window as any).electron.audio electron.audio
.playNotificationSound('message') .playNotificationSound('message')
.then((result: any) => console.log('[MessageNotifications] Sound result:', result)) .then((result) => console.log('[MessageNotifications] Sound result:', result))
.catch((err: any) => console.error('[MessageNotifications] Sound error:', err)); .catch((err) => console.error('[MessageNotifications] Sound error:', err));
} else { } else {
console.log('[MessageNotifications] Using HTML5 Audio fallback'); console.log('[MessageNotifications] Using HTML5 Audio fallback');
new Audio('./sound/notification.ogg').play().catch((err) => { new Audio('./sound/notification.ogg').play().catch((err) => {
@@ -503,18 +508,19 @@ function PaarrotAPIInitializer() {
*/ */
function TaskbarFlashStopper() { function TaskbarFlashStopper() {
useEffect(() => { useEffect(() => {
const { electron } = window;
// Log what's available on mount // Log what's available on mount
console.log('[TaskbarFlashStopper] window.electron:', (window as any).electron); console.log('[TaskbarFlashStopper] window.electron:', electron);
console.log('[TaskbarFlashStopper] Available APIs:', { console.log('[TaskbarFlashStopper] Available APIs:', {
hasWindow: !!(window as any).electron?.window, hasWindow: !!electron?.window,
hasFlashFrame: !!(window as any).electron?.window?.flashFrame, hasFlashFrame: !!electron?.window?.flashFrame,
hasAudio: !!(window as any).electron?.audio, hasAudio: !!electron?.audio,
hasPlaySound: !!(window as any).electron?.audio?.playNotificationSound, hasPlaySound: !!electron?.audio?.playNotificationSound,
}); });
const handleFocus = () => { const handleFocus = () => {
if ((window as any).electron?.window?.flashFrame) { if (electron?.window?.flashFrame) {
(window as any).electron.window.flashFrame(false); electron.window.flashFrame(false);
} }
}; };
@@ -558,7 +564,7 @@ function AndroidShareIntentHandler() {
const originalFile = await materializeSharedFile(sharedFile, share.receivedAt); const originalFile = await materializeSharedFile(sharedFile, share.receivedAt);
let fileToUpload = originalFile; let fileToUpload = originalFile;
let encInfo: any; let encInfo: EncryptedAttachmentInfo | undefined;
if (room.hasEncryptionStateEvent()) { if (room.hasEncryptionStateEvent()) {
const encrypted = await encryptFile(originalFile); const encrypted = await encryptFile(originalFile);
+6 -6
View File
@@ -181,7 +181,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
// Since we can't directly intercept, we'll use a MutationObserver-style approach // Since we can't directly intercept, we'll use a MutationObserver-style approach
// by checking for repeated key upload failures // by checking for repeated key upload failures
const checkKeyConflict = (args: any[]): boolean => { const checkKeyConflict = (args: unknown[]): boolean => {
const message = args.map((a) => String(a)).join(' '); const message = args.map((a) => String(a)).join(' ');
return keyConflictPattern.test(message); return keyConflictPattern.test(message);
}; };
@@ -190,7 +190,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
const originalError = console.error; const originalError = console.error;
const originalWarn = console.warn; const originalWarn = console.warn;
const errorHandler = (...args: any[]) => { const errorHandler = (...args: unknown[]) => {
if (checkKeyConflict(args)) { if (checkKeyConflict(args)) {
keyConflictCount += 1; keyConflictCount += 1;
console.log( console.log(
@@ -236,7 +236,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
}; };
console.error = errorHandler; console.error = errorHandler;
console.warn = (...args: any[]) => { console.warn = (...args: unknown[]) => {
if (checkKeyConflict(args)) { if (checkKeyConflict(args)) {
keyConflictCount += 1; keyConflictCount += 1;
} }
@@ -332,9 +332,9 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
console.log('[initMatrix] Registered global MatrixClient for auth utils'); console.log('[initMatrix] Registered global MatrixClient for auth utils');
return mx; return mx;
} catch (error: any) { } catch (error) {
// Handle crypto store account mismatch error // Handle crypto store account mismatch error
if (error && error.message && error.message.includes("account in the store doesn't match")) { if (error instanceof Error && error.message.includes("account in the store doesn't match")) {
console.error('[initMatrix] ❌ Crypto store account mismatch detected!'); console.error('[initMatrix] ❌ Crypto store account mismatch detected!');
console.error('[initMatrix] Error details:', error.message); console.error('[initMatrix] Error details:', error.message);
console.error('[initMatrix] Expected account:', session.userId, session.deviceId); console.error('[initMatrix] Expected account:', session.userId, session.deviceId);
@@ -433,7 +433,7 @@ export const logoutClient = async (mx: MatrixClient) => {
const currentUserId = getLocalStorageItem('currentSessionUserId', undefined); const currentUserId = getLocalStorageItem('currentSessionUserId', undefined);
// Remove the current session // Remove the current session
const remainingSessions = allSessions.filter((s: any) => s.userId !== userId); const remainingSessions = allSessions.filter((s: Session) => s.userId !== userId);
setLocalStorageItem('matrixSessions', remainingSessions); setLocalStorageItem('matrixSessions', remainingSessions);
// If we're logging out the current session and there are other sessions, switch to the first one // If we're logging out the current session and there are other sessions, switch to the first one
+7
View File
@@ -28,6 +28,13 @@ interface PluginAPI {
interface ElectronAPI { interface ElectronAPI {
platform?: string; platform?: string;
arch?: string; arch?: string;
window?: {
focus: () => Promise<unknown>;
flashFrame: (flash?: boolean) => Promise<{ success: boolean; error?: string }>;
};
audio?: {
playNotificationSound: (soundType?: string) => Promise<{ success: boolean; error?: string }>;
};
clipboard?: { clipboard?: {
writeText: (text: string) => void; writeText: (text: string) => void;
}; };