Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(desktop): localize the native tray menu and popover

Tashfeenfcd2970a82ba
diff --git a/desktop/renderer/popover.html b/desktop/renderer/popover.html
index 1a6a2164..977301aa 100644
--- a/desktop/renderer/popover.html
+++ b/desktop/renderer/popover.html
@@ -168,27 +168,27 @@
<div class="title">FreeLLMAPI</div>
<div class="addr" id="addr">127.0.0.1:…</div>
</div>
- <div class="status"><span class="dot"></span>running</div>
+ <div class="status"><span class="dot"></span><span id="status-label">running</span></div>
</div>
<div class="stats">
<div class="stat">
<div class="v" id="reqs">0</div>
- <div class="l">Requests today</div>
+ <div class="l" id="l-reqs">Requests today</div>
<div class="sub" id="rate"></div>
</div>
<div class="stat">
<div class="v" id="tokens">0</div>
- <div class="l">Tokens today</div>
+ <div class="l" id="l-tokens">Tokens today</div>
</div>
</div>
<div class="chartwrap">
<canvas id="chart" width="0" height="0"></canvas>
- <div class="axis"><span>24h ago</span><span id="peak"></span><span>now</span></div>
+ <div class="axis"><span id="ax-ago">24h ago</span><span id="peak"></span><span id="ax-now">now</span></div>
</div>
- <div class="lastmodel">Last model <b id="model">—</b></div>
+ <div class="lastmodel"><span id="lastmodel-label">Last model</span> <b id="model">—</b></div>
<div class="actions">
<button class="primary" id="open">Open Dashboard</button>
@@ -198,7 +198,7 @@
<div class="foot">
<div class="switch" id="login"></div>
- <span>Start at login</span>
+ <span id="login-label">Start at login</span>
<button class="quit" id="quit">Quit</button>
</div>
</div>
@@ -207,6 +207,12 @@
const $ = (id) => document.getElementById(id);
const fmt = (n) => n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'k' : String(n);
+ // Native-UI strings for the active locale, sent by main in each snapshot.
+ // Seeded with the English defaults already in the HTML so the very first
+ // paint (before the first snapshot resolves) is never blank.
+ let S = {};
+ const setText = (id, v) => { const el = $(id); if (el && v) el.textContent = v; };
+
function drawChart(hourly) {
const c = $('chart');
const cssW = c.clientWidth, cssH = 64, dpr = window.devicePixelRatio || 2;
@@ -229,17 +235,30 @@
ctx.roundRect(x, y, bw, h, Math.min(3, bw / 2));
ctx.fill();
}
- $('peak').textContent = max > 1 ? 'peak ' + max + '/h' : '';
+ $('peak').textContent = max > 1 ? (S.peak || 'peak {n}/h').replace('{n}', max) : '';
}
let loginOn = false;
async function refresh() {
const s = await window.freeapi.snapshot();
+ S = s.strings || {};
document.body.classList.toggle('light', s.theme === 'light');
+ // Localize the static labels.
+ setText('status-label', S.running);
+ setText('l-reqs', S.requestsToday);
+ setText('l-tokens', S.tokensToday);
+ setText('lastmodel-label', S.lastModel);
+ setText('open', S.openDashboard);
+ setText('copyurl', S.copyUrl);
+ setText('copykey', S.copyKey);
+ setText('login-label', S.startAtLogin);
+ setText('quit', S.quit);
+ setText('ax-ago', S.hoursAgo);
+ setText('ax-now', S.now);
$('addr').textContent = '127.0.0.1:' + s.port;
$('reqs').textContent = fmt(s.requests);
$('tokens').textContent = fmt(s.tokens);
- $('rate').textContent = s.successRate == null ? '' : s.successRate + '% success';
+ $('rate').textContent = s.successRate == null ? '' : (S.successSuffix || '{n}% success').replace('{n}', s.successRate);
$('model').textContent = s.lastModel;
loginOn = s.loginItem;
$('login').classList.toggle('on', loginOn);
@@ -253,8 +272,8 @@
}
$('open').addEventListener('click', () => window.freeapi.openDashboard());
- $('copyurl').addEventListener('click', (e) => { window.freeapi.copyBaseUrl(); flash(e.target, 'Copied ✓'); });
- $('copykey').addEventListener('click', (e) => { window.freeapi.copyApiKey(); flash(e.target, 'Copied ✓'); });
+ $('copyurl').addEventListener('click', (e) => { window.freeapi.copyBaseUrl(); flash(e.target, S.copied || 'Copied ✓'); });
+ $('copykey').addEventListener('click', (e) => { window.freeapi.copyApiKey(); flash(e.target, S.copied || 'Copied ✓'); });
$('quit').addEventListener('click', () => window.freeapi.quit());
$('login').addEventListener('click', () => {
loginOn = !loginOn;
diff --git a/desktop/src/config.ts b/desktop/src/config.ts
index 3b236bce..df504161 100644
--- a/desktop/src/config.ts
+++ b/desktop/src/config.ts
@@ -5,6 +5,8 @@ import { app } from 'electron';
export interface DesktopConfig {
port?: number;
theme?: 'dark' | 'light';
+ // BCP-47 locale mirrored from the dashboard (en, zh-CN, fr, es, pt-BR).
+ locale?: string;
}
function configPath(): string {
diff --git a/desktop/src/i18n.ts b/desktop/src/i18n.ts
new file mode 100644
index 00000000..26bf3d9a
--- /dev/null
+++ b/desktop/src/i18n.ts
@@ -0,0 +1,134 @@
+// Translations for the desktop's NATIVE chrome — the tray menu and the
+// Control-Center popover. These live outside the React dashboard (the menu is
+// built in the main process; the popover is a file:// page), so they can't read
+// the dashboard's i18n. The active locale is mirrored from the dashboard via the
+// `freeapi:locale-changed` IPC (preload watches <html lang>) and persisted in
+// config, exactly like the theme. Keep these keys in sync with the five locales
+// shipped by the client (client/src/i18n/locales).
+
+export const NATIVE_LOCALES = ['en', 'zh-CN', 'fr', 'es', 'pt-BR'] as const;
+export type NativeLocale = (typeof NATIVE_LOCALES)[number];
+export const DEFAULT_NATIVE_LOCALE: NativeLocale = 'en';
+
+// `navigator.language`-style value → closest supported locale (primary subtag).
+export function normalizeLocale(raw: string | undefined | null): NativeLocale {
+ const l = (raw ?? '').toLowerCase();
+ if (l.startsWith('zh')) return 'zh-CN';
+ if (l.startsWith('pt')) return 'pt-BR';
+ if (l.startsWith('fr')) return 'fr';
+ if (l.startsWith('es')) return 'es';
+ return 'en';
+}
+
+type Strings = Record<string, string>;
+
+const STRINGS: Record<NativeLocale, Strings> = {
+ en: {
+ tooltip: 'FreeLLMAPI — local LLM router',
+ runningOn: 'Running on {addr}',
+ openDashboard: 'Open Dashboard',
+ quitApp: 'Quit FreeLLMAPI',
+ running: 'running',
+ requestsToday: 'Requests today',
+ tokensToday: 'Tokens today',
+ lastModel: 'Last model',
+ copyUrl: 'Copy URL',
+ copyKey: 'Copy Key',
+ copied: 'Copied ✓',
+ startAtLogin: 'Start at login',
+ quit: 'Quit',
+ hoursAgo: '24h ago',
+ now: 'now',
+ peak: 'peak {n}/h',
+ successSuffix: '{n}% success',
+ },
+ 'zh-CN': {
+ tooltip: 'FreeLLMAPI — 本地 LLM 路由器',
+ runningOn: '运行于 {addr}',
+ openDashboard: '打开仪表板',
+ quitApp: '退出 FreeLLMAPI',
+ running: '运行中',
+ requestsToday: '今日请求',
+ tokensToday: '今日 token',
+ lastModel: '上次模型',
+ copyUrl: '复制 URL',
+ copyKey: '复制密钥',
+ copied: '已复制 ✓',
+ startAtLogin: '登录时启动',
+ quit: '退出',
+ hoursAgo: '24 小时前',
+ now: '现在',
+ peak: '峰值 {n}/小时',
+ successSuffix: '{n}% 成功',
+ },
+ fr: {
+ tooltip: 'FreeLLMAPI — routeur LLM local',
+ runningOn: 'En cours sur {addr}',
+ openDashboard: 'Ouvrir le tableau de bord',
+ quitApp: 'Quitter FreeLLMAPI',
+ running: 'en cours',
+ requestsToday: "Requêtes aujourd'hui",
+ tokensToday: "Tokens aujourd'hui",
+ lastModel: 'Dernier modèle',
+ copyUrl: "Copier l'URL",
+ copyKey: 'Copier la clé',
+ copied: 'Copié ✓',
+ startAtLogin: "Lancer à l'ouverture de session",
+ quit: 'Quitter',
+ hoursAgo: 'il y a 24 h',
+ now: 'maintenant',
+ peak: 'pic {n}/h',
+ successSuffix: '{n} % de réussite',
+ },
+ es: {
+ tooltip: 'FreeLLMAPI — enrutador LLM local',
+ runningOn: 'En ejecución en {addr}',
+ openDashboard: 'Abrir el panel',
+ quitApp: 'Salir de FreeLLMAPI',
+ running: 'en ejecución',
+ requestsToday: 'Solicitudes hoy',
+ tokensToday: 'Tokens hoy',
+ lastModel: 'Último modelo',
+ copyUrl: 'Copiar URL',
+ copyKey: 'Copiar clave',
+ copied: 'Copiado ✓',
+ startAtLogin: 'Iniciar al arrancar sesión',
+ quit: 'Salir',
+ hoursAgo: 'hace 24 h',
+ now: 'ahora',
+ peak: 'pico {n}/h',
+ successSuffix: '{n}% de aciertos',
+ },
+ 'pt-BR': {
+ tooltip: 'FreeLLMAPI — roteador LLM local',
+ runningOn: 'Em execução em {addr}',
+ openDashboard: 'Abrir o painel',
+ quitApp: 'Sair do FreeLLMAPI',
+ running: 'em execução',
+ requestsToday: 'Solicitações hoje',
+ tokensToday: 'Tokens hoje',
+ lastModel: 'Último modelo',
+ copyUrl: 'Copiar URL',
+ copyKey: 'Copiar chave',
+ copied: 'Copiado ✓',
+ startAtLogin: 'Iniciar ao fazer login',
+ quit: 'Sair',
+ hoursAgo: '24 h atrás',
+ now: 'agora',
+ peak: 'pico {n}/h',
+ successSuffix: '{n}% de sucesso',
+ },
+};
+
+// Translate a native key, falling back to English then the key itself.
+export function dt(locale: NativeLocale, key: string, vars?: Record<string, string | number>): string {
+ const raw = STRINGS[locale]?.[key] ?? STRINGS.en[key] ?? key;
+ if (!vars) return raw;
+ return raw.replace(/\{(\w+)\}/g, (_, name) => (name in vars ? String(vars[name]) : `{${name}}`));
+}
+
+// The full string bundle for one locale, sent to the popover in the snapshot so
+// its file:// renderer (which has no access to this module) can label itself.
+export function nativeStrings(locale: NativeLocale): Strings {
+ return { ...STRINGS.en, ...STRINGS[locale] };
+}
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 8ba97767..29e0628c 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -3,9 +3,10 @@ import { fileURLToPath } from 'node:url';
import { app, dialog, ipcMain, clipboard, nativeTheme, shell } from 'electron';
import { startServer, ensureSessionToken, getUnifiedApiKey } from './server.mjs';
import { loadConfig, saveConfig } from './config.js';
-import { buildTray } from './tray.js';
+import { buildTray, refreshTrayLocale } from './tray.js';
import { openDashboard } from './window.js';
import { todayStats, hourlyRequests, successRateToday } from './stats.js';
+import { normalizeLocale, nativeStrings, type NativeLocale } from './i18n.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DEFAULT_PORT = 31415;
@@ -30,6 +31,11 @@ if (!app.requestSingleInstanceLock()) {
?? loadConfig().theme
?? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
nativeTheme.themeSource = theme;
+ // The dashboard also owns the language (its ⋯-menu selector); the native tray
+ // menu and popover follow via the same mirror-and-persist pattern as the theme.
+ let locale: NativeLocale = normalizeLocale(
+ (process.env.FREEAPI_LOCALE as string | undefined) ?? loadConfig().locale,
+ );
app.on('second-instance', () => {
if (sessionToken) openDashboard(resolvedPort, sessionToken);
@@ -77,6 +83,10 @@ if (!app.requestSingleInstanceLock()) {
hourly: hourlyRequests(),
loginItem: app.getLoginItemSettings().openAtLogin,
theme,
+ locale,
+ // The popover renderer is a file:// page with no access to the desktop
+ // i18n module, so ship it the resolved string bundle for the active locale.
+ strings: nativeStrings(locale),
};
});
ipcMain.on('freeapi:theme-changed', async (_e, next: 'dark' | 'light') => {
@@ -89,6 +99,16 @@ if (!app.requestSingleInstanceLock()) {
const { getPopoverWindow } = await import('./popover.js');
getPopoverWindow()?.webContents.send('freeapi:refresh');
});
+ ipcMain.on('freeapi:locale-changed', async (_e, raw: string) => {
+ const next = normalizeLocale(raw);
+ if (next === locale) return;
+ locale = next;
+ saveConfig({ ...loadConfig(), locale });
+ refreshTrayLocale(locale);
+ // Re-label the popover if it's open (snapshot now carries the new strings).
+ const { getPopoverWindow } = await import('./popover.js');
+ getPopoverWindow()?.webContents.send('freeapi:refresh');
+ });
ipcMain.handle('freeapi:open-dashboard', () => openDashboard(resolvedPort, sessionToken));
ipcMain.handle('freeapi:copy-base-url', () => clipboard.writeText(`http://127.0.0.1:${resolvedPort}/v1`));
ipcMain.handle('freeapi:copy-api-key', () => clipboard.writeText(getUnifiedApiKey()));
@@ -118,7 +138,7 @@ if (!app.requestSingleInstanceLock()) {
resolvedPort = port;
saveConfig({ ...cfg, port });
sessionToken = ensureSessionToken();
- const tray = buildTray(port, sessionToken);
+ const tray = buildTray(port, sessionToken, () => locale);
console.log(`[desktop] FreeLLMAPI running on http://127.0.0.1:${port}`);
// Dev-only UI verification: FREEAPI_SHOT=1 opens the popover and the
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 77cc85dd..ba74f0b7 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -46,11 +46,24 @@ function reportTheme() {
document.documentElement.classList.contains('dark') ? 'dark' : 'light',
);
}
+
+// Mirror the dashboard's locale to the main process so the native tray menu and
+// the popover match. The I18nProvider sets `<html lang>` on every locale change,
+// so observe that attribute rather than reaching into the dashboard's
+// localStorage from this preload world.
+function reportLocale() {
+ const lang = document.documentElement.lang;
+ if (lang) ipcRenderer.send('freeapi:locale-changed', lang);
+}
window.addEventListener('DOMContentLoaded', () => {
applyDesktopClass();
reportTheme();
- new MutationObserver(reportTheme).observe(document.documentElement, {
+ reportLocale();
+ new MutationObserver(() => {
+ reportTheme();
+ reportLocale();
+ }).observe(document.documentElement, {
attributes: true,
- attributeFilter: ['class'],
+ attributeFilter: ['class', 'lang'],
});
});
diff --git a/desktop/src/tray.ts b/desktop/src/tray.ts
index 97d8268f..9f3ab09d 100644
--- a/desktop/src/tray.ts
+++ b/desktop/src/tray.ts
@@ -3,30 +3,41 @@ import { fileURLToPath } from 'node:url';
import { Tray, Menu, app, nativeImage } from 'electron';
import { togglePopover } from './popover.js';
import { openDashboard } from './window.js';
+import { dt, type NativeLocale } from './i18n.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let tray: Tray | null = null;
// Left-click opens the glass popover; right-click keeps a minimal native
-// menu as an escape hatch (quit even if the popover renderer breaks).
-export function buildTray(port: number, token: string): Tray {
+// menu as an escape hatch (quit even if the popover renderer breaks). The menu
+// is rebuilt on every right-click, so reading the live locale via getLocale()
+// keeps its labels current after a language switch; the static tooltip is
+// refreshed separately (refreshTrayLocale).
+export function buildTray(port: number, token: string, getLocale: () => NativeLocale): Tray {
const iconPath = path.join(__dirname, '../assets/trayTemplate.png');
const icon = nativeImage.createFromPath(iconPath);
icon.setTemplateImage(true); // auto light/dark tint in the macOS menu bar
tray = new Tray(icon);
- tray.setToolTip('FreeLLMAPI — local LLM router');
+ tray.setToolTip(dt(getLocale(), 'tooltip'));
tray.on('click', () => togglePopover(tray!));
tray.on('right-click', () => {
+ const locale = getLocale();
tray!.popUpContextMenu(Menu.buildFromTemplate([
- { label: `Running on 127.0.0.1:${port}`, enabled: false },
- { label: 'Open Dashboard', click: () => openDashboard(port, token) },
+ { label: dt(locale, 'runningOn', { addr: `127.0.0.1:${port}` }), enabled: false },
+ { label: dt(locale, 'openDashboard'), click: () => openDashboard(port, token) },
{ type: 'separator' },
- { label: 'Quit FreeLLMAPI', click: () => app.quit() },
+ { label: dt(locale, 'quitApp'), click: () => app.quit() },
]));
});
return tray;
}
+
+// Update the static tooltip after a locale change (the menu reads the locale
+// live when it opens, so it needs no explicit refresh).
+export function refreshTrayLocale(locale: NativeLocale): void {
+ tray?.setToolTip(dt(locale, 'tooltip'));
+}