feat: integrate Syncthing for cloud sync functionality

- Added Syncthing related types and interfaces in shared/types.ts
- Implemented Syncthing management functions in main/syncthing.ts including install, start, stop, and device/folder management.
- Created a new ErrorBoundary component for better error handling in the renderer.
- Developed CloudSyncPage component to manage cloud sync setup, installation, and device pairing.
- Enhanced settings to include cloud sync options in AppSettings.
This commit is contained in:
miles committed 2026-07-14 03:08:30 -05:00
1 parent e1db14b1c2
commit b7420d591e
14 files changed
+1448 -52

No files matched your search

+9
View File
@@ -7,6 +7,7 @@ import { isMacOS } from './platform';
import { ensureRomsStructure } from './emulators';
import { setupAutoUpdater } from './updater';
import { generatePegasusCollectionsForRomDir } from './configurator';
import { startSyncthing } from './syncthing';
let mainWindow: BrowserWindow | null = null;
let tray: Tray | null = null;
@@ -132,6 +133,14 @@ app.whenReady().then(() => {
}
} catch { /* ignore */ }
// Auto-start Syncthing if cloud sync was previously enabled
try {
const s = settings.get();
if (s.cloudSyncEnabled) {
startSyncthing().catch(() => { /* ignore */ });
}
} catch { /* ignore */ }
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
else mainWindow?.show();
+75
View File
@@ -25,6 +25,16 @@ import { addRecentGame, parseGameTitle, buildScrapeTitle, findValidThumbnail, ca
import { getGameAchievements } from './ra';
import { scanBiosDirectory, getKnownBiosList, getDefaultBiosDir, updateRetroarchBiosPath } from './bios';
import { listAllSaves, deleteSave, backupSave } from './saveManager';
import {
installSyncthing,
startSyncthing,
stopSyncthing,
getSyncthingStatus,
addRemoteDevice,
removeRemoteDevice,
addSharedFolder,
removeSharedFolder,
} from './syncthing';
export function registerIpcHandlers(): void {
// System
@@ -351,4 +361,69 @@ export function registerIpcHandlers(): void {
settings.save({ saveDirectories: dirs });
return true;
});
// Cloud Sync (Syncthing)
ipcMain.handle('cloud:status', async () => {
try {
return await getSyncthingStatus();
} catch (err) {
console.error('cloud:status error:', err);
return { installed: false, running: false, deviceId: '', apiAddress: '', apiKey: '', version: '', folders: [], remoteDevices: [] };
}
});
ipcMain.handle('cloud:install', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
const ok = await installSyncthing((stage, percent, message) => {
win?.webContents.send('cloud:install-progress', { stage, percent, message });
});
return ok;
});
ipcMain.handle('cloud:start', async () => {
try {
// Fire-and-forget: start the process, don't block IPC
startSyncthing().catch(err => console.error('cloud:start background error:', err));
// Give it a moment to see if it comes up quickly
await new Promise(r => setTimeout(r, 2000));
return await getSyncthingStatus();
} catch (err) {
console.error('cloud:start error:', err);
return null;
}
});
ipcMain.handle('cloud:stop', async () => {
try {
await stopSyncthing();
} catch (err) {
console.error('cloud:stop error:', err);
}
return getSyncthingStatus();
});
ipcMain.handle('cloud:add-device', async (_event, deviceId: string, name: string) => {
return addRemoteDevice(deviceId, name);
});
ipcMain.handle('cloud:remove-device', async (_event, deviceId: string) => {
return removeRemoteDevice(deviceId);
});
ipcMain.handle('cloud:add-folder', async (_event, id: string, label: string, path: string, deviceIds: string[]) => {
return addSharedFolder(id, label, path, deviceIds);
});
ipcMain.handle('cloud:remove-folder', async (_event, folderId: string) => {
return removeSharedFolder(folderId);
});
ipcMain.handle('cloud:open-web-ui', async () => {
const status = await getSyncthingStatus();
if (status.running && status.apiAddress) {
shell.openExternal(status.apiAddress);
return true;
}
return false;
});
}
+22
View File
@@ -9,6 +9,7 @@ import type {
ConfigPreset,
GameMetadata,
AchievementInfo,
SyncthingStatus,
} from '../shared/types';
const api = {
@@ -151,6 +152,27 @@ const api = {
return () => ipcRenderer.removeListener('updates:download-progress', handler);
},
},
cloud: {
status: (): Promise<SyncthingStatus> => ipcRenderer.invoke('cloud:status'),
install: (): Promise<boolean> => ipcRenderer.invoke('cloud:install'),
start: (): Promise<SyncthingStatus | null> => ipcRenderer.invoke('cloud:start'),
stop: (): Promise<SyncthingStatus> => ipcRenderer.invoke('cloud:stop'),
addDevice: (deviceId: string, name: string): Promise<boolean> =>
ipcRenderer.invoke('cloud:add-device', deviceId, name),
removeDevice: (deviceId: string): Promise<boolean> =>
ipcRenderer.invoke('cloud:remove-device', deviceId),
addFolder: (id: string, label: string, path: string, deviceIds: string[]): Promise<boolean> =>
ipcRenderer.invoke('cloud:add-folder', id, label, path, deviceIds),
removeFolder: (folderId: string): Promise<boolean> =>
ipcRenderer.invoke('cloud:remove-folder', folderId),
openWebUI: (): Promise<boolean> => ipcRenderer.invoke('cloud:open-web-ui'),
onInstallProgress: (cb: (progress: { stage: string; percent: number; message: string }) => void) => {
const handler = (_event: Electron.IpcRendererEvent, p: { stage: string; percent: number; message: string }) => cb(p);
ipcRenderer.on('cloud:install-progress', handler);
return () => ipcRenderer.removeListener('cloud:install-progress', handler);
},
},
};
contextBridge.exposeInMainWorld('omni', api);
+125 -36
View File
@@ -1,4 +1,4 @@
import { existsSync, readdirSync, statSync, unlinkSync, copyFileSync, mkdirSync } from 'fs';
import { existsSync, readdirSync, statSync, unlinkSync, copyFileSync, mkdirSync, readFileSync } from 'fs';
import { join, extname, basename } from 'path';
import { app } from 'electron';
import { homedir } from 'os';
@@ -15,20 +15,102 @@ interface SaveDirConfig {
states?: string;
}
function parseRetroarchConfig(cfgPath: string): Record<string, string> {
try {
if (!existsSync(cfgPath)) return {};
const content = readFileSync(cfgPath, 'utf-8');
const result: Record<string, string> = {};
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx < 0) continue;
const key = trimmed.slice(0, eqIdx).trim();
let val = trimmed.slice(eqIdx + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
result[key] = val;
}
return result;
} catch { return {}; }
}
function resolveRetroarchSaveDirs(): SaveDirConfig {
const candidates: string[] = [];
if (platform === 'win32') {
candidates.push(join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch'));
} else if (platform === 'darwin') {
candidates.push(join(home, 'Library', 'Application Support', 'RetroArch'));
candidates.push(join(home, 'Documents', 'RetroArch'));
candidates.push(join(home, 'Desktop', 'RetroArch'));
} else {
candidates.push(join(home, '.config', 'retroarch'));
}
const customDirs = settings.get().saveDirectories || {};
if (customDirs.retroarch) {
candidates.unshift(customDirs.retroarch);
}
for (const dir of candidates) {
const cfgPath = join(dir, 'retroarch.cfg');
if (existsSync(cfgPath)) {
const cfg = parseRetroarchConfig(cfgPath);
const saveDir = cfg['savefile_directory'];
const stateDir = cfg['savestate_directory'];
let saves: string;
let states: string | undefined;
if (saveDir && saveDir !== 'default') {
saves = saveDir.startsWith('/') ? saveDir : join(dir, saveDir);
} else {
saves = join(dir, 'saves');
}
if (stateDir && stateDir !== 'default') {
states = stateDir.startsWith('/') ? stateDir : join(dir, stateDir);
} else {
states = join(dir, 'states');
}
if (existsSync(saves) || existsSync(states || '')) {
return { saves, states };
}
}
const saves = join(dir, 'saves');
const states = join(dir, 'states');
if (existsSync(saves) || existsSync(states)) {
return { saves, states };
}
}
return {
saves: platform === 'win32'
? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'saves')
: platform === 'darwin'
? join(home, 'Library', 'Application Support', 'RetroArch', 'saves')
: join(home, '.config', 'retroarch', 'saves'),
states: platform === 'win32'
? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'states')
: platform === 'darwin'
? join(home, 'Library', 'Application Support', 'RetroArch', 'states')
: join(home, '.config', 'retroarch', 'states'),
};
}
let _retroarchDirs: SaveDirConfig | null = null;
function getRetroarchSaveDirs(): SaveDirConfig {
if (!_retroarchDirs) _retroarchDirs = resolveRetroarchSaveDirs();
return _retroarchDirs;
}
function emulatorSaveDirs(emuId: string): SaveDirConfig | null {
const configs: Record<string, SaveDirConfig> = {
retroarch: {
saves: platform === 'win32'
? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'saves')
: platform === 'darwin'
? join(home, 'Library', 'Application Support', 'RetroArch', 'saves')
: join(home, '.config', 'retroarch', 'saves'),
states: platform === 'win32'
? join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'RetroArch', 'states')
: platform === 'darwin'
? join(home, 'Library', 'Application Support', 'RetroArch', 'states')
: join(home, '.config', 'retroarch', 'states'),
},
retroarch: getRetroarchSaveDirs(),
dolphin: {
saves: platform === 'win32'
? join(home, 'Documents', 'Dolphin Emulator', 'GC')
@@ -129,31 +211,38 @@ function gameNameFromSave(fileName: string): string {
return name.trim() || fileName;
}
function scanDir(dir: string): SaveEntry[] {
function scanDir(dir: string, maxDepth = 3): SaveEntry[] {
if (!existsSync(dir)) return [];
const entries: SaveEntry[] = [];
try {
const files = readdirSync(dir);
for (const file of files) {
const fullPath = join(dir, file);
try {
const st = statSync(fullPath);
if (!st.isFile()) continue;
const type = isSaveFile(file);
if (!type) continue;
entries.push({
id: fullPath,
emulatorId: '',
gameName: gameNameFromSave(file),
fileName: file,
filePath: fullPath,
fileSize: st.size,
lastModified: st.mtime.toISOString(),
type,
});
} catch { /* skip unreadable */ }
}
} catch { /* skip unreadable dir */ }
const scan = (d: string, depth: number) => {
if (depth > maxDepth) return;
try {
const files = readdirSync(d);
for (const file of files) {
const fullPath = join(d, file);
try {
const st = statSync(fullPath);
if (st.isDirectory()) {
scan(fullPath, depth + 1);
continue;
}
const type = isSaveFile(file);
if (!type) continue;
entries.push({
id: fullPath,
emulatorId: '',
gameName: gameNameFromSave(file),
fileName: file,
filePath: fullPath,
fileSize: st.size,
lastModified: st.mtime.toISOString(),
type,
});
} catch { /* skip unreadable */ }
}
} catch { /* skip unreadable dir */ }
};
scan(dir, 0);
return entries;
}
+1
View File
@@ -32,6 +32,7 @@ const defaultSettings: AppSettings = {
retroAchievementsPassword: '',
retroAchievementsApiKey: '',
steamGridDbApiKey: '',
syncthingPort: 8384,
};
let cached: AppSettings | null = null;
+461
View File
@@ -0,0 +1,461 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { app } from 'electron';
import http from 'http';
import { spawn, ChildProcess } from 'child_process';
import { getPlatform, getArch } from './platform';
import { settings } from './settings';
import { SyncthingStatus, SyncthingFolder, SyncthingRemoteDevice } from '../shared/types';
let stProcess: ChildProcess | null = null;
const VERSION = 'v2.1.2';
function getSyncthingDir(): string {
return join(app.getPath('userData'), 'syncthing');
}
function getBinaryPath(): string {
const platform = getPlatform();
const dir = getSyncthingDir();
return platform === 'win32' ? join(dir, 'syncthing.exe') : join(dir, 'syncthing');
}
function getConfigDir(): string {
return join(getSyncthingDir(), 'config');
}
function getDataDir(): string {
return join(getSyncthingDir(), 'data');
}
function getApiKeyPath(): string {
return join(getSyncthingDir(), '.apikey');
}
function generateApiKey(): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let key = '';
for (let i = 0; i < 32; i++) {
key += chars.charAt(Math.floor(Math.random() * chars.length));
}
return key;
}
function getApiKey(): string {
const apiKeyPath = getApiKeyPath();
if (existsSync(apiKeyPath)) {
return readFileSync(apiKeyPath, 'utf-8').trim();
}
const key = generateApiKey();
const dir = getSyncthingDir();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(apiKeyPath, key, 'utf-8');
return key;
}
function getPort(): number {
return settings.get().syncthingPort || 8384;
}
function apiUrl(path: string): string {
return `http://127.0.0.1:${getPort()}${path}`;
}
function httpRequest(
method: string,
url: string,
headers: Record<string, string>,
body?: string
): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
const req = http.request(url, { method, headers, timeout: 5000 }, (res) => {
let data = '';
res.on('data', (chunk: Buffer) => { data += chunk.toString(); });
res.on('end', () => resolve({ status: res.statusCode || 0, body: data }));
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
if (body) req.write(body);
req.end();
});
}
async function apiRequest(method: string, path: string, body?: any): Promise<any> {
const url = apiUrl(path);
const apiKey = getApiKey();
const resp = await httpRequest(method, url, {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
}, body ? JSON.stringify(body) : undefined);
if (resp.status < 200 || resp.status >= 300) {
throw new Error(`Syncthing API ${method} ${path} failed (${resp.status}): ${resp.body}`);
}
if (!resp.body) return null;
try { return JSON.parse(resp.body); } catch { return resp.body; }
}
async function healthCheck(timeoutMs = 1000): Promise<boolean> {
return new Promise((resolve) => {
const req = http.request(apiUrl('/rest/noauth/health'), { method: 'GET', timeout: timeoutMs }, (res) => {
let data = '';
res.on('data', () => {});
res.on('end', () => resolve(res.statusCode === 200));
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
req.end();
});
}
function ensureConfigXml(): void {
const configDir = getConfigDir();
const dataDir = getDataDir();
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
if (!existsSync(dataDir)) mkdirSync(dataDir, { recursive: true });
const cfgPath = join(configDir, 'config.xml');
if (existsSync(cfgPath)) return;
const apiKey = getApiKey();
const port = getPort();
const xml = `<configuration version="37">
<folder id="omniemu-saves" label="OmniEmu Saves" path="${join(dataDir, 'saves').replace(/\\/g, '/')}" type="sendreceive" rescanIntervalS="3600" fsWatcherEnabled="true" fsWatcherDelayS="10" ignorePerms="false" autoNormalize="true">
<filesystemType>basic</filesystemType>
<minDiskFree unit="%">1</minDiskFree>
</folder>
<device id="" name="OmniEmu" compression="metadata" introducer="false">
<address>dynamic</address>
</device>
<gui enabled="true" tls="false">
<address>127.0.0.1:${port}</address>
<apikey>${apiKey}</apikey>
<theme>default</theme>
</gui>
<options>
<listenAddress>default</listenAddress>
<globalAnnounceEnabled>false</globalAnnounceEnabled>
<localAnnounceEnabled>true</localAnnounceEnabled>
<startBrowser>false</startBrowser>
<urAccepted>-1</urAccepted>
</options>
</configuration>`;
writeFileSync(cfgPath, xml, 'utf-8');
}
export async function installSyncthing(
onProgress?: (stage: string, percent: number, message: string) => void
): Promise<boolean> {
const platform = getPlatform();
const arch = getArch();
let assetName: string;
let ext: string;
if (platform === 'win32') {
assetName = `syncthing-windows-amd64-${VERSION}`;
ext = 'zip';
} else if (platform === 'darwin') {
assetName = arch === 'arm64'
? `syncthing-macos-arm64-${VERSION}`
: `syncthing-macos-amd64-${VERSION}`;
ext = 'zip';
} else {
assetName = `syncthing-linux-amd64-${VERSION}`;
ext = 'tar.gz';
}
const url = `https://github.com/syncthing/syncthing/releases/download/${VERSION}/${assetName}.${ext}`;
const dir = getSyncthingDir();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
onProgress?.('downloading', 0, `Downloading Syncthing ${VERSION}...`);
const tmpFile = join(dir, `tmp_${Date.now()}.${ext}`);
try {
const buffer = await downloadFile(url, (received, total) => {
const pct = total > 0 ? Math.round((received / total) * 60) : 0;
onProgress?.('downloading', pct, `Downloading... ${Math.round(received / 1024 / 1024 * 10) / 10}MB`);
});
writeFileSync(tmpFile, buffer);
onProgress?.('extracting', 70, 'Extracting...');
if (ext === 'zip') {
const { execSync } = require('child_process');
if (platform === 'win32') {
execSync(`powershell -Command "Expand-Archive -Path '${tmpFile}' -DestinationPath '${dir}' -Force"`);
const extracted = join(dir, `${assetName}\\syncthing.exe`);
const target = join(dir, 'syncthing.exe');
if (existsSync(extracted) && !existsSync(target)) {
const { renameSync } = require('fs');
renameSync(extracted, target);
}
} else {
execSync(`ditto -x -k '${tmpFile}' '${dir}'`, { stdio: 'ignore' });
const binaryPath = getBinaryPath();
if (!existsSync(binaryPath)) {
try { execSync(`unzip -o '${tmpFile}' -d '${dir}'`, { stdio: 'ignore' }); } catch { /* ignore */ }
}
}
// Move binary out of nested directory if needed
const binaryPath = getBinaryPath();
if (!existsSync(binaryPath)) {
const nestedBinary = join(dir, assetName, getPlatform() === 'win32' ? 'syncthing.exe' : 'syncthing');
if (existsSync(nestedBinary)) {
const { renameSync } = require('fs');
renameSync(nestedBinary, binaryPath);
}
}
} else {
const { execSync } = require('child_process');
execSync(`tar -xzf '${tmpFile}' -C '${dir}' --strip-components=1`, { stdio: 'ignore' });
}
onProgress?.('installing', 90, 'Setting up...');
const binaryPath = getBinaryPath();
if (platform !== 'win32' && existsSync(binaryPath)) {
const { chmodSync } = require('fs');
chmodSync(binaryPath, 0o755);
}
ensureConfigXml();
onProgress?.('done', 100, 'Syncthing installed!');
return true;
} catch (err) {
onProgress?.('error', 0, `Install failed: ${err}`);
return false;
} finally {
try { const { unlinkSync } = require('fs'); unlinkSync(tmpFile); } catch { /* ignore */ }
}
}
function downloadFile(
url: string,
onProgress?: (received: number, total: number) => void
): Promise<Buffer> {
return new Promise((resolve, reject) => {
const https = require('https');
const get = url.startsWith('https') ? https.get : http.get;
get(url, (res: any) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
downloadFile(res.headers.location, onProgress).then(resolve, reject);
return;
}
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}`));
return;
}
const total = parseInt(res.headers['content-length'] || '0', 10);
const chunks: Buffer[] = [];
let received = 0;
res.on('data', (chunk: Buffer) => {
chunks.push(chunk);
received += chunk.length;
onProgress?.(received, total);
});
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
}).on('error', reject);
});
}
export async function startSyncthing(): Promise<boolean> {
const binaryPath = getBinaryPath();
if (!existsSync(binaryPath)) return false;
// If already running and healthy, just return
if (stProcess && !stProcess.killed && await healthCheck()) return true;
// Kill stale process if any
if (stProcess && !stProcess.killed) {
try { stProcess.kill(); } catch { /* ignore */ }
stProcess = null;
await new Promise(r => setTimeout(r, 500));
}
ensureConfigXml();
stProcess = spawn(binaryPath, [
'--no-browser',
'--no-restart',
'--config', getConfigDir(),
'--data', getDataDir(),
], {
detached: false,
stdio: 'ignore',
});
stProcess.on('error', () => { stProcess = null; });
stProcess.on('exit', (code) => { stProcess = null; });
// Quick check — if process died immediately, bail
await new Promise(r => setTimeout(r, 300));
if (!stProcess || stProcess.killed) return false;
// Wait for Syncthing to become healthy, but bail early if process dies
for (let i = 0; i < 15; i++) {
await new Promise(r => setTimeout(r, 1000));
// Process died — don't keep polling
if (!stProcess || stProcess.killed) return false;
if (await healthCheck()) return true;
}
return false;
}
export async function stopSyncthing(): Promise<void> {
if (!stProcess || stProcess.killed) return;
try {
await apiRequest('POST', '/rest/system/shutdown');
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
stProcess?.kill();
resolve();
}, 3000);
stProcess!.on('exit', () => {
clearTimeout(timeout);
resolve();
});
});
} catch {
stProcess?.kill();
}
stProcess = null;
}
export async function getSyncthingStatus(): Promise<SyncthingStatus> {
const installed = existsSync(getBinaryPath());
const running = installed ? await healthCheck() : false;
if (!running) {
return {
installed,
running: false,
deviceId: '',
apiAddress: '',
apiKey: '',
version: '',
folders: [],
remoteDevices: [],
};
}
try {
const status = await apiRequest('GET', '/rest/system/status');
const config = await apiRequest('GET', '/rest/config');
const folders: SyncthingFolder[] = (config.folders || []).map((f: any) => ({
id: f.id,
label: f.label || f.id,
path: f.path,
type: f.type,
}));
const remoteDevices: SyncthingRemoteDevice[] = (config.devices || [])
.filter((d: any) => d.id && d.id !== status.myID)
.map((d: any) => ({
id: d.id,
name: d.name || (d.id ? d.id.slice(0, 8) : 'Unknown'),
addresses: d.addresses || [],
connected: !!status?.connections?.[d.id]?.connected,
}));
return {
installed: true,
running: true,
deviceId: status.myID || '',
apiAddress: apiUrl(''),
apiKey: getApiKey(),
version: status?.version || VERSION,
folders,
remoteDevices,
};
} catch {
return {
installed: true,
running: true,
deviceId: '',
apiAddress: apiUrl(''),
apiKey: getApiKey(),
version: '',
folders: [],
remoteDevices: [],
};
}
}
export async function addRemoteDevice(deviceId: string, name: string): Promise<boolean> {
try {
await apiRequest('POST', '/rest/config/devices', {
deviceID: deviceId,
name: name || deviceId.slice(0, 8),
addresses: ['dynamic'],
compression: 'metadata',
introducer: false,
});
return true;
} catch {
return false;
}
}
export async function removeRemoteDevice(deviceId: string): Promise<boolean> {
try {
await apiRequest('DELETE', `/rest/config/devices/${deviceId}`);
return true;
} catch {
return false;
}
}
export async function addSharedFolder(
id: string,
label: string,
path: string,
deviceIds: string[]
): Promise<boolean> {
try {
const devices = deviceIds.map(dId => ({ deviceID: dId }));
await apiRequest('POST', '/rest/config/folders', {
id,
label,
path,
type: 'sendreceive',
rescanIntervalS: 3600,
fsWatcherEnabled: true,
fsWatcherDelayS: 10,
devices,
});
return true;
} catch {
return false;
}
}
export async function removeSharedFolder(folderId: string): Promise<boolean> {
try {
await apiRequest('DELETE', `/rest/config/folders/${folderId}`);
return true;
} catch {
return false;
}
}
export async function getSyncthingVersion(): Promise<string> {
try {
const status = await apiRequest('GET', '/rest/system/version');
return status?.version || '';
} catch {
return '';
}
}
export { getBinaryPath, getPort, getApiKey, apiUrl, getSyncthingDir };
+5 -1
View File
@@ -1,5 +1,6 @@
import React, { useState, useEffect } from 'react';
import { Sidebar } from './components/Sidebar';
import { ErrorBoundary } from './components/ErrorBoundary';
import { Dashboard } from './pages/Dashboard';
import { EmulatorsPage } from './pages/EmulatorsPage';
import { LibraryPage } from './pages/LibraryPage';
@@ -7,9 +8,10 @@ import { SettingsPage } from './pages/SettingsPage';
import { ControllerPage } from './pages/ControllerPage';
import { UtilitiesPage } from './pages/UtilitiesPage';
import { SaveManagerPage } from './pages/SaveManagerPage';
import { CloudSyncPage } from './pages/CloudSyncPage';
import { useGamepadNav } from './hooks/useGamepadNav';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities';
export function applyTheme(theme: string) {
if (theme === 'system') {
@@ -39,6 +41,8 @@ export function App() {
return <LibraryPage />;
case 'saves':
return <SaveManagerPage />;
case 'cloud':
return <ErrorBoundary><CloudSyncPage /></ErrorBoundary>;
case 'settings':
return <SettingsPage />;
case 'controller':
+51
View File
@@ -0,0 +1,51 @@
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught:', error, errorInfo);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div style={{ padding: 24 }}>
<h2 style={{ color: 'var(--danger, #ff4444)', marginTop: 0 }}>Something went wrong</h2>
<p className="text-muted" style={{ marginBottom: 12 }}>
An error occurred while loading this page.
</p>
<div style={{
padding: 12, borderRadius: 8, background: 'var(--bg-tertiary, #222)',
fontFamily: 'monospace', fontSize: 12, color: 'var(--danger, #ff4444)',
whiteSpace: 'pre-wrap', marginBottom: 16, border: '1px solid var(--border, #555)',
}}>
{this.state.error?.message || 'Unknown error'}
</div>
<button className="btn btn-primary" onClick={() => this.setState({ hasError: false, error: null })}>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
+2 -1
View File
@@ -1,6 +1,6 @@
import React from 'react';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities';
interface TopBarProps {
currentPage: Page;
@@ -12,6 +12,7 @@ const navItems: { page: Page; label: string; icon: string }[] = [
{ page: 'emulators', label: 'Emulators', icon: '🕹️' },
{ page: 'library', label: 'Library', icon: '📚' },
{ page: 'saves', label: 'Saves', icon: '💾' },
{ page: 'cloud', label: 'Cloud Sync', icon: '☁️' },
{ page: 'controller', label: 'Controller', icon: '🎮' },
{ page: 'utilities', label: 'Utilities', icon: '🔧' },
{ page: 'settings', label: 'Settings', icon: '⚙️' },
+2 -2
View File
@@ -3,9 +3,9 @@ import { useEffect, useRef, useState, useCallback } from 'react';
const DEBOUNCE_MS = 180;
const LEGEND_TIMEOUT_MS = 8000;
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'settings' | 'controller' | 'utilities';
type Page = 'dashboard' | 'emulators' | 'library' | 'saves' | 'cloud' | 'settings' | 'controller' | 'utilities';
const pageOrder: Page[] = ['dashboard', 'emulators', 'library', 'saves', 'controller', 'utilities', 'settings'];
const pageOrder: Page[] = ['dashboard', 'emulators', 'library', 'saves', 'cloud', 'controller', 'utilities', 'settings'];
export function useGamepadNav(onNavigate: (page: Page) => void, currentPage: Page) {
const lastTime = useRef<Record<string, number>>({});
+641
View File
@@ -0,0 +1,641 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
import type { SyncthingStatus } from '../../shared/types';
type SetupStep = 'install' | 'start' | 'setup' | 'ready';
export function CloudSyncPage() {
const [status, setStatus] = useState<SyncthingStatus | null>(null);
const [loading, setLoading] = useState(true);
const [installing, setInstalling] = useState(false);
const [installMsg, setInstallMsg] = useState('');
const [installPercent, setInstallPercent] = useState(0);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [remoteDeviceId, setRemoteDeviceId] = useState('');
const [remoteDeviceName, setRemoteDeviceName] = useState('');
const [addingDevice, setAddingDevice] = useState(false);
const [folderLabel, setFolderLabel] = useState('');
const [folderPath, setFolderPath] = useState('');
const [showAddFolder, setShowAddFolder] = useState(false);
const [copied, setCopied] = useState(false);
const [cloudEnabled, setCloudEnabled] = useState(false);
const uninstallRef = useRef<HTMLTextAreaElement>(null);
const DEFAULT_STATUS: SyncthingStatus = {
installed: false, running: false, deviceId: '', apiAddress: '',
apiKey: '', version: '', folders: [], remoteDevices: [],
};
const loadStatus = useCallback(async () => {
setLoading(true);
try {
const s = await Promise.race([
window.omni.cloud.status(),
new Promise<null>((_, reject) => setTimeout(() => reject(new Error('timeout')), 8000)),
]);
if (s) setStatus(s);
else setStatus(DEFAULT_STATUS);
} catch {
setStatus(DEFAULT_STATUS);
}
setLoading(false);
}, []);
const loadSettings = useCallback(async () => {
try {
const s = await window.omni.settings.get();
setCloudEnabled(!!s.cloudSyncEnabled);
} catch { /* ignore */ }
}, []);
useEffect(() => { loadStatus(); loadSettings(); }, [loadStatus, loadSettings]);
useEffect(() => {
const unsub = window.omni.cloud.onInstallProgress((p) => {
setInstallMsg(p.message);
setInstallPercent(p.percent);
if (p.stage === 'done' || p.stage === 'error') {
setInstalling(false);
if (p.stage === 'done') {
loadStatus();
}
}
});
return unsub;
}, [loadStatus]);
const showSuccess = (msg: string) => {
setSuccess(msg);
setError('');
setTimeout(() => setSuccess(''), 4000);
};
const showError = (msg: string) => {
setError(msg);
setSuccess('');
setTimeout(() => setError(''), 4000);
};
const saveCloudEnabled = async (enabled: boolean) => {
setCloudEnabled(enabled);
try { await window.omni.settings.save({ cloudSyncEnabled: enabled }); } catch { /* ignore */ }
};
const handleInstall = async () => {
setInstalling(true);
setInstallPercent(0);
setInstallMsg('Starting download...');
try {
const ok = await window.omni.cloud.install();
if (!ok) {
setInstalling(false);
showError('Installation failed');
}
} catch (err) {
setInstalling(false);
showError(`Install error: ${err}`);
}
};
const handleStart = async () => {
setLoading(true);
try {
// Start kicks off the process in the background
const s = await window.omni.cloud.start();
if (s) {
setStatus(s);
if (s.running) {
await saveCloudEnabled(true);
showSuccess('Syncthing started! Auto-start enabled.');
} else {
// Process was kicked off but may need more time — poll
let attempts = 0;
const poll = setInterval(async () => {
attempts++;
try {
const latest = await window.omni.cloud.status();
setStatus(latest);
if (latest.running) {
clearInterval(poll);
await saveCloudEnabled(true);
showSuccess('Syncthing started! Auto-start enabled.');
setLoading(false);
} else if (attempts >= 15) {
clearInterval(poll);
showError('Syncthing took too long to start. Check that the binary is not blocked by your OS.');
setLoading(false);
}
} catch {
if (attempts >= 15) {
clearInterval(poll);
showError('Could not reach Syncthing.');
setLoading(false);
}
}
}, 1000);
}
} else {
showError('Failed to start Syncthing — binary not found');
}
} catch (err) {
showError(`Start error: ${err}`);
}
setLoading(false);
};
const handleStop = async () => {
setLoading(true);
try {
const s = await window.omni.cloud.stop();
setStatus(s);
await saveCloudEnabled(false);
showSuccess('Syncthing stopped. Auto-start disabled.');
} catch (err) {
showError(`Stop error: ${err}`);
}
setLoading(false);
};
const handleAddDevice = async () => {
if (!remoteDeviceId.trim()) {
showError('Enter a device ID');
return;
}
setAddingDevice(true);
try {
const ok = await window.omni.cloud.addDevice(remoteDeviceId.trim(), remoteDeviceName.trim());
if (ok) {
showSuccess('Device added! Wait for it to accept, or add this device on the other machine.');
setRemoteDeviceId('');
setRemoteDeviceName('');
loadStatus();
} else {
showError('Failed to add device');
}
} catch (err) {
showError(`Error: ${err}`);
}
setAddingDevice(false);
};
const handleRemoveDevice = async (deviceId: string) => {
try {
await window.omni.cloud.removeDevice(deviceId);
showSuccess('Device removed');
loadStatus();
} catch { /* ignore */ }
};
const handleAddFolder = async () => {
if (!folderLabel.trim() || !folderPath.trim()) {
showError('Enter folder label and path');
return;
}
const id = folderLabel.toLowerCase().replace(/[^a-z0-9]/g, '-');
const deviceIds = status?.remoteDevices?.map(d => d.id) || [];
try {
const ok = await window.omni.cloud.addFolder(id, folderLabel.trim(), folderPath.trim(), deviceIds);
if (ok) {
showSuccess('Shared folder added');
setFolderLabel('');
setFolderPath('');
setShowAddFolder(false);
loadStatus();
} else {
showError('Failed to add folder');
}
} catch (err) {
showError(`Error: ${err}`);
}
};
const handleRemoveFolder = async (folderId: string) => {
try {
await window.omni.cloud.removeFolder(folderId);
showSuccess('Folder removed');
loadStatus();
} catch { /* ignore */ }
};
const handleCopyDeviceId = () => {
if (status?.deviceId) {
navigator.clipboard.writeText(status.deviceId);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
const handleCopyApiKey = () => {
if (status?.apiKey) {
navigator.clipboard.writeText(status.apiKey);
showSuccess('API key copied');
}
};
const handleOpenWebUI = async () => {
await window.omni.cloud.openWebUI();
};
if (loading && !status) {
return <div className="loading">Checking Syncthing status...</div>;
}
const installed = status?.installed ?? false;
const running = status?.running ?? false;
// Determine current step
let step: SetupStep;
if (!installed) step = 'install';
else if (!running) step = 'start';
else if (!cloudEnabled || (status?.remoteDevices?.length ?? 0) === 0) step = 'setup';
else step = 'ready';
return (
<div>
<h2 style={{ marginTop: 0, marginBottom: 16 }}>Cloud Sync</h2>
<p className="text-muted" style={{ marginBottom: 20 }}>
Sync your game saves between devices using Syncthing. Once set up, it runs automatically on launch.
</p>
{error && (
<div className="info-bar mb-4" style={{ color: 'var(--danger, #ff4444)' }}>{error}</div>
)}
{success && (
<div className="info-bar mb-4" style={{ color: 'var(--success, #44ff44)' }}>{success}</div>
)}
{/* Progress indicator */}
<div style={{
display: 'flex', gap: 8, marginBottom: 24, alignItems: 'center',
padding: '12px 16px', borderRadius: 10,
background: 'var(--bg-secondary, #1a1a2e)', border: '1px solid var(--border, #333)',
}}>
{(['install', 'start', 'setup', 'ready'] as SetupStep[]).map((s, i) => (
<React.Fragment key={s}>
<div style={{
width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center',
justifyContent: 'center', fontSize: 12, fontWeight: 700,
background: step === s
? 'var(--accent)'
: (['install', 'start', 'setup', 'ready'].indexOf(step) > i
? 'var(--success, #44ff44)' : 'var(--bg-tertiary, #333)'),
color: step === s ? '#fff' : 'var(--text-muted, #888)',
transition: 'all 0.2s ease',
}}>
{['install', 'start', 'setup', 'ready'].indexOf(step) > i ? '✓' : i + 1}
</div>
<span style={{
fontSize: 12, fontWeight: step === s ? 600 : 400,
color: step === s ? 'var(--text)' : 'var(--text-muted, #888)',
marginRight: i < 3 ? 8 : 0,
}}>
{s === 'install' ? 'Install' : s === 'start' ? 'Start' : s === 'setup' ? 'Pair' : 'Syncing'}
</span>
{i < 3 && <div style={{
flex: 1, height: 2, background: 'var(--bg-tertiary, #333)',
maxWidth: 40,
}} />}
</React.Fragment>
))}
</div>
{/* Status badge */}
{running && (
<div style={{
display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px',
borderRadius: 20, marginBottom: 20, fontSize: 13, fontWeight: 600,
background: cloudEnabled ? 'rgba(68,255,68,0.1)' : 'rgba(255,200,68,0.1)',
border: `1px solid ${cloudEnabled ? 'rgba(68,255,68,0.3)' : 'rgba(255,200,68,0.3)'}`,
color: cloudEnabled ? 'var(--success, #44ff44)' : '#ffc844',
}}>
<span style={{
width: 8, height: 8, borderRadius: '50%',
background: cloudEnabled ? 'var(--success, #44ff44)' : '#ffc844',
}} />
{cloudEnabled ? 'Cloud sync active' : 'Running — not yet paired'}
</div>
)}
{/* Step 1: Install */}
{!installed && !installing && (
<div className="card mb-4" style={{
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))',
}}>
<div className="card-header">
<h3 style={{ margin: 0 }}>Install Syncthing</h3>
</div>
<div style={{ padding: 16 }}>
<p className="text-muted" style={{ marginBottom: 16 }}>
Syncthing is the engine behind cloud sync. It's free, open-source, and runs locally — no third-party accounts needed.
</p>
<button
className="btn btn-primary"
onClick={handleInstall}
style={{ fontSize: 15, padding: '12px 28px' }}
>
⬇ Install Syncthing
</button>
</div>
</div>
)}
{installing && (
<div className="card mb-4">
<div className="card-header">
<h3>Installing Syncthing...</h3>
</div>
<div style={{ padding: 16 }}>
<div style={{ marginBottom: 10, fontSize: 13 }}>{installMsg}</div>
<div style={{
height: 8, borderRadius: 4, background: 'var(--bg-tertiary, #333)',
overflow: 'hidden', width: '100%',
}}>
<div style={{
height: '100%', borderRadius: 4,
width: `${installPercent}%`,
background: 'linear-gradient(90deg, var(--accent), rgba(108,99,255,0.7))',
transition: 'width 0.3s ease',
}} />
</div>
</div>
</div>
)}
{/* Step 2: Start */}
{installed && !running && (
<div className="card mb-4" style={{
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))',
}}>
<div className="card-header">
<h3 style={{ margin: 0 }}>Start Syncthing</h3>
</div>
<div style={{ padding: 16 }}>
<p className="text-muted" style={{ marginBottom: 16 }}>
Start the sync service. It will auto-start on future app launches once enabled.
</p>
<button
className="btn btn-primary"
onClick={handleStart}
disabled={loading}
style={{ fontSize: 15, padding: '12px 28px' }}
>
▶ Start Syncthing
</button>
</div>
</div>
)}
{/* Steps 3-4: Host & Pair (running) */}
{running && (
<>
{/* Host section — show your device ID */}
<div className="card mb-4">
<div className="card-header">
<h3>Host — Share This Device</h3>
</div>
<div style={{ padding: 16 }}>
<p className="text-muted text-sm" style={{ marginBottom: 12 }}>
Copy this Device ID and paste it into the other machine's OmniEmu or Syncthing to pair.
</p>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<textarea
ref={uninstallRef}
readOnly
value={status?.deviceId || ''}
style={{
flex: 1, fontFamily: 'monospace', fontSize: 12, padding: 8,
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
resize: 'none', height: 48,
}}
/>
<button className="btn btn-primary btn-sm" onClick={handleCopyDeviceId} style={{ whiteSpace: 'nowrap' }}>
{copied ? 'Copied!' : 'Copy ID'}
</button>
</div>
</div>
</div>
{/* Pair section — connect to another device */}
<div className="card mb-4">
<div className="card-header">
<h3>Pair — Connect Another Device</h3>
</div>
<div style={{ padding: 16 }}>
<p className="text-muted text-sm" style={{ marginBottom: 12 }}>
Enter the Device ID from another machine to connect. Both devices must add each other.
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text"
placeholder="Remote Device ID"
value={remoteDeviceId}
onChange={e => setRemoteDeviceId(e.target.value)}
style={{
fontFamily: 'monospace', fontSize: 12, padding: '8px 10px',
borderRadius: 6, border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<input
type="text"
placeholder="Device name (optional)"
value={remoteDeviceName}
onChange={e => setRemoteDeviceName(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-tertiary, #222)', color: 'var(--text, #fff)',
}}
/>
<button
className="btn btn-primary"
onClick={handleAddDevice}
disabled={addingDevice || !remoteDeviceId.trim()}
style={{ alignSelf: 'flex-start' }}
>
{addingDevice ? 'Adding...' : '🔗 Pair Device'}
</button>
</div>
</div>
</div>
{/* Paired Devices */}
{status?.remoteDevices && status.remoteDevices.length > 0 && (
<div className="card mb-4">
<div className="card-header">
<h3>Paired Devices</h3>
</div>
<div style={{ padding: '0 12px 12px' }}>
{status.remoteDevices.filter(d => d.id).map(device => (
<div key={device.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '8px 10px', borderRadius: 8,
border: '1px solid var(--border, #555)', marginBottom: 4,
background: 'var(--bg-tertiary, #222)',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{device.name || 'Unknown Device'}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{device.id.slice(0, 12)}...{device.id.slice(-6)}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{
fontSize: 11, color: device.connected ? 'var(--success, #44ff44)' : 'var(--text-muted, #888)',
}}>
{device.connected ? 'Connected' : 'Not connected'}
</span>
<button
className="btn btn-danger btn-sm"
onClick={() => handleRemoveDevice(device.id)}
>
Remove
</button>
</div>
</div>
))}
</div>
</div>
)}
{/* Shared Folders */}
<div className="card mb-4">
<div className="card-header">
<h3>Shared Folders</h3>
<button
className="btn btn-secondary btn-sm"
onClick={() => setShowAddFolder(!showAddFolder)}
>
{showAddFolder ? 'Cancel' : '+ Add Folder'}
</button>
</div>
<div style={{ padding: 12 }}>
{showAddFolder && (
<div style={{
marginBottom: 12, padding: 12, borderRadius: 8,
border: '1px solid var(--border, #555)', background: 'var(--bg-tertiary, #222)',
}}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text"
placeholder="Folder label (e.g. RetroArch Saves)"
value={folderLabel}
onChange={e => setFolderLabel(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-secondary, #1a1a1a)', color: 'var(--text, #fff)',
}}
/>
<input
type="text"
placeholder="Folder path (e.g. ~/Documents/RetroArch/saves)"
value={folderPath}
onChange={e => setFolderPath(e.target.value)}
style={{
padding: '8px 10px', borderRadius: 6,
border: '1px solid var(--border, #555)',
background: 'var(--bg-secondary, #1a1a1a)', color: 'var(--text, #fff)',
}}
/>
<button className="btn btn-primary btn-sm" onClick={handleAddFolder} style={{ alignSelf: 'flex-start' }}>
Add Shared Folder
</button>
</div>
</div>
)}
{status?.folders && status.folders.length > 0 ? (
status.folders.map(folder => (
<div key={folder.id} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '8px 10px', borderRadius: 8,
border: '1px solid var(--border, #555)', marginBottom: 4,
background: 'var(--bg-tertiary, #222)',
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 13 }}>{folder.label}</div>
<div className="text-sm text-muted" style={{ fontFamily: 'monospace', fontSize: 10 }}>
{folder.path}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span className="badge badge-installed" style={{ fontSize: 10 }}>
{folder.type}
</span>
<button
className="btn btn-danger btn-sm"
onClick={() => handleRemoveFolder(folder.id)}
>
Remove
</button>
</div>
</div>
))
) : (
<p className="text-muted text-sm">No shared folders. Add one to start syncing.</p>
)}
</div>
</div>
{/* Control bar */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '12px 16px', borderRadius: 10,
background: 'var(--bg-secondary, #1a1a2e)', border: '1px solid var(--border, #333)',
marginBottom: 16,
}}>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn btn-secondary btn-sm" onClick={handleOpenWebUI}>
Open Web UI
</button>
<button className="btn btn-secondary btn-sm" onClick={loadStatus} disabled={loading}>
Refresh
</button>
</div>
<button className="btn btn-danger btn-sm" onClick={handleStop} disabled={loading}>
Stop Syncthing
</button>
</div>
{/* Advanced */}
{status?.apiKey && (
<details style={{ marginBottom: 16 }}>
<summary style={{
cursor: 'pointer', fontSize: 13, color: 'var(--text-muted, #888)',
padding: '8px 0',
}}>
Advanced Settings
</summary>
<div className="card" style={{ marginTop: 8 }}>
<div className="card-header">
<h3>Advanced</h3>
</div>
<div style={{ padding: 12 }}>
<p className="text-muted text-sm" style={{ marginBottom: 8 }}>
API Key for the Syncthing Web UI.
</p>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<code style={{
flex: 1, padding: '6px 10px', borderRadius: 6,
background: 'var(--bg-tertiary, #222)', fontSize: 11,
wordBreak: 'break-all',
}}>
{status.apiKey}
</code>
<button className="btn btn-secondary btn-sm" onClick={handleCopyApiKey}>
Copy
</button>
</div>
</div>
</div>
</details>
)}
</>
)}
</div>
);
}
+12 -12
View File
@@ -198,46 +198,46 @@ body::before {
.topbar-nav {
display: flex;
align-items: center;
height: 80px;
height: 64px;
background: linear-gradient(180deg, var(--bg-secondary) 0%, var(--bg-primary) 100%);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-bottom: 2px solid var(--border);
padding: 0 32px;
padding: 0 16px;
flex-shrink: 0;
gap: 16px;
gap: 8px;
z-index: 10;
}
.topbar-brand {
font-size: 24px;
font-size: 16px;
font-weight: 900;
background: var(--accent-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-right: 32px;
margin-right: 8px;
white-space: nowrap;
letter-spacing: -1px;
letter-spacing: -0.5px;
text-shadow: 0 0 20px rgba(0, 212, 255, 0.3);
}
.topbar-tabs {
display: flex;
gap: 4px;
gap: 2px;
flex: 1;
}
.topbar-tab {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 20px;
border-radius: 8px;
gap: 6px;
padding: 8px 12px;
border-radius: 6px;
border: 2px solid transparent;
background: transparent;
color: var(--text-secondary);
font-size: 14px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all var(--transition);
@@ -280,7 +280,7 @@ body::before {
}
.topbar-tab-icon {
font-size: 20px;
font-size: 16px;
filter: drop-shadow(0 0 8px color-mix(in srgb, var(--accent) 30%, transparent));
}
+13
View File
@@ -9,6 +9,7 @@ import type {
InstallProgress,
ConfigPreset,
EmulatorSaves,
SyncthingStatus,
} from '../shared/types';
declare global {
@@ -83,6 +84,18 @@ declare global {
onStatus: (cb: (status: Record<string, unknown>) => void) => () => void;
onDownloadProgress: (cb: (progress: Record<string, unknown>) => void) => () => void;
};
cloud: {
status: () => Promise<SyncthingStatus>;
install: () => Promise<boolean>;
start: () => Promise<SyncthingStatus | null>;
stop: () => Promise<SyncthingStatus>;
addDevice: (deviceId: string, name: string) => Promise<boolean>;
removeDevice: (deviceId: string) => Promise<boolean>;
addFolder: (id: string, label: string, path: string, deviceIds: string[]) => Promise<boolean>;
removeFolder: (folderId: string) => Promise<boolean>;
openWebUI: () => Promise<boolean>;
onInstallProgress: (cb: (progress: { stage: string; percent: number; message: string }) => void) => () => void;
};
};
}
}
+29
View File
@@ -123,6 +123,10 @@ export interface AppSettings {
steamGridDbApiKey?: string;
/** Custom save directories per emulator: emulatorId -> save directory path */
saveDirectories?: Record<string, string>;
/** Syncthing GUI port */
syncthingPort?: number;
/** Cloud sync enabled (Syncthing installed and configured) */
cloudSyncEnabled?: boolean;
}
export interface RetroAchievement {
@@ -189,3 +193,28 @@ export interface EmulatorSaves {
stateDir?: string;
saves: SaveEntry[];
}
export interface SyncthingStatus {
installed: boolean;
running: boolean;
deviceId: string;
apiAddress: string;
apiKey: string;
version: string;
folders: SyncthingFolder[];
remoteDevices: SyncthingRemoteDevice[];
}
export interface SyncthingFolder {
id: string;
label: string;
path: string;
type: string;
}
export interface SyncthingRemoteDevice {
id: string;
name: string;
addresses: string[];
connected: boolean;
}