Compare commits
6 Commits
v0.5.4
...
fd62177375
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd62177375 | ||
|
|
0a753ad4c7 | ||
|
|
34fb03b265 | ||
|
|
e7ccca98e7 | ||
|
|
4745f5e091 | ||
|
|
a41dce511b |
72
CHANGELOG.md
72
CHANGELOG.md
@@ -6,6 +6,75 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.5.5] — 2026-05-22
|
||||
|
||||
Большой sweep по ревизии: 4 спринта правок (≈14 пунктов), все 135 тестов
|
||||
зелёные. Главное — UI больше не залипает при retry'ях I/O, GSI порт не
|
||||
зависает в TIME_WAIT после выхода, sandbox включён, шрифты self-hosted.
|
||||
|
||||
### Security
|
||||
|
||||
- **`sandbox: true`** на обоих BrowserWindow. Preload использует только
|
||||
contextBridge + ipcRenderer (sandbox-safe), никаких Node-built-ins.
|
||||
OS-уровневый sandbox изолирует renderer на уровне процессов — даже
|
||||
RCE в зависимости рендерера не получит Node-доступа через preload.
|
||||
- **CSP ужесточён.** Убраны `https://fonts.googleapis.com` и
|
||||
`https://fonts.gstatic.com` origins (шрифты теперь self-hosted),
|
||||
добавлены `connect-src 'self'`, `base-uri 'self'`,
|
||||
`frame-ancestors 'none'`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Self-hosted шрифты.** Plus Jakarta Sans, Bricolage Grotesque,
|
||||
JetBrains Mono подключены через `@fontsource/*` пакеты — в bundle
|
||||
лежат локально, без интернета шрифты работают, CSP без внешних
|
||||
origins. +22 .woff/.woff2 (~500KB) в installer.
|
||||
- **`src/main/logger.ts`** — структурный logger с уровнями
|
||||
(debug/info/warn/error) и ротацией. Пишет в
|
||||
`%APPDATA%/Exercise Reminder/logs/latest.log` (≤1MB) и дублирует
|
||||
в console. При 1MB ротируется в `prev.log`. `LAUDE_DEBUG=1`
|
||||
включает debug-уровень. Подключён в hot paths: store, updater,
|
||||
GSI server, registry, dota2 provider — особенно полезно для
|
||||
диагностики «челленджи не срабатывают» (видно token verify,
|
||||
POST_GAME detection, фильтрацию challenges).
|
||||
- `<html lang>` синхронизируется с `settings.language` через
|
||||
ThemeProvider — screen readers корректно произносят язык.
|
||||
- `dev:simulateMatchEnd` channel вынесен в IPC enum
|
||||
(`IPC.devSimulateMatchEnd`).
|
||||
- `test:coverage` npm script.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`broadcastState` больше не шлёт `history`** через IPC. Раньше
|
||||
каждый markDone/snooze отправлял весь state включая до 10k
|
||||
history-записей (~500KB JSON) к каждому BrowserWindow. Теперь
|
||||
`AppState` (renderer-facing) без `history`, а `PersistedState`
|
||||
(internal) с историей. Renderer и так дёргал `getHistory()`
|
||||
отдельно, поведение не изменилось — только perf.
|
||||
- **`lib/icon.tsx`**: `import * as Lucide` (wildcard, ~500KB всех
|
||||
1500+ иконок в bundle) → explicit named imports + ICON_MAP.
|
||||
В bundle только 18 ICON_CHOICES.
|
||||
- **ChallengeEditor**: multiplier клампится в UI до [0.5, 1000]
|
||||
(совпадает с validate.ts). Раньше save с 9999 молча отклонялся
|
||||
IPC-валидатором.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`atomicWrite` spin-loop → async setTimeout.** Раньше при retry
|
||||
на EBUSY/EPERM (антивирус, OneDrive) main process замораживался
|
||||
на 50/200/800ms × до 3 итераций ≈ секунда залипания UI. Сейчас
|
||||
async sleep — event-loop живёт. Аналогичный фикс в
|
||||
`games/steam-launch-options.ts`. Сохранён sync-вариант для
|
||||
`flushNow` в `before-quit` (там event-loop уже не работает).
|
||||
- **`before-quit` дожидается `stopGamesRegistry`** через
|
||||
`e.preventDefault()` + `app.exit(0)`. Раньше GSI HTTP server
|
||||
не успевал `closeAllConnections` до exit, и следующий запуск
|
||||
получал EADDRINUSE на порту 4701 (TIME_WAIT) — GSI молча не
|
||||
работал.
|
||||
- **IPC `getState` не мутирует кэш.** Раньше `state.settings.startWithWindows`
|
||||
перезаписывалось напрямую, разъезжаясь с persisted-disk-значением
|
||||
до следующего mutation. Сейчас возвращается поверхностная копия.
|
||||
|
||||
## [0.5.4] — 2026-05-19
|
||||
|
||||
Обновление приложения теперь по-настоящему фоновое + почти моментальный
|
||||
@@ -222,7 +291,8 @@
|
||||
иконки), системный трей, автозапуск с Windows, native-уведомления,
|
||||
NSIS-инсталлятор, auto-update через electron-updater.
|
||||
|
||||
[Unreleased]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/compare/v0.5.4...HEAD
|
||||
[Unreleased]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/compare/v0.5.5...HEAD
|
||||
[0.5.5]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.5
|
||||
[0.5.4]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.4
|
||||
[0.5.3]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.3
|
||||
[0.5.2]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.2
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## TL;DR
|
||||
|
||||
**Laude / Exercise Reminder** — Windows desktop приложение на Electron 33, которое напоминает делать упражнения и опционально парсит статистику матчей Dota 2 (через GSI) в количество повторений. Текущая версия — **0.5.4**. Один разработчик (AnRil), один remote — self-hosted Gitea.
|
||||
**Laude / Exercise Reminder** — Windows desktop приложение на Electron 33, которое напоминает делать упражнения и опционально парсит статистику матчей Dota 2 (через GSI) в количество повторений. Текущая версия — **0.5.5**. Один разработчик (AnRil), один remote — self-hosted Gitea.
|
||||
|
||||
## Стек
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Windows desktop приложение, которое напоминает делать упражнения во время работы за компьютером. Опционально подключается к Dota 2 и после каждого матча превращает статистику (смерти, убийства, ассисты) в количество повторений.
|
||||
|
||||
[](https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/latest)
|
||||
[](https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/latest)
|
||||
[]()
|
||||
[]()
|
||||
|
||||
|
||||
34
package-lock.json
generated
34
package-lock.json
generated
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "laude",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "laude",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.4",
|
||||
"dependencies": {
|
||||
"@fontsource/bricolage-grotesque": "^5.2.10",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
||||
"electron-updater": "^6.8.3",
|
||||
"framer-motion": "^11.11.17",
|
||||
"lucide-react": "^0.460.0",
|
||||
@@ -1264,6 +1267,33 @@
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/bricolage-grotesque": {
|
||||
"version": "5.2.10",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/bricolage-grotesque/-/bricolage-grotesque-5.2.10.tgz",
|
||||
"integrity": "sha512-V2xS+1P7C8IrSypXLUx/bLtX/LsTlYtV2k2CsU+S/0t8qepZ2hvKSlyJIx7Ub/iY8Bbnj+IjAuUF9nvFz+BbIg==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/jetbrains-mono": {
|
||||
"version": "5.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.2.8.tgz",
|
||||
"integrity": "sha512-6w8/SG4kqvIMu7xd7wt6x3idn1Qux3p9N62s6G3rfldOUYHpWcc2FKrqf+Vo44jRvqWj2oAtTHrZXEP23oSKwQ==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/plus-jakarta-sans": {
|
||||
"version": "5.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/plus-jakarta-sans/-/plus-jakarta-sans-5.2.8.tgz",
|
||||
"integrity": "sha512-P5qE49fqdeD+7DXH1KBxmMPlB17LTz1zvBhFH0tFzfnYTKVJVyb0pR6plh0ZGXxcB+Oayb54FZZw3V42/DawTw==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@gar/promisify": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "laude",
|
||||
"version": "0.5.4",
|
||||
"version": "0.5.5",
|
||||
"description": "Exercise reminder — Windows desktop app",
|
||||
"main": "out/main/index.js",
|
||||
"author": "AnRil",
|
||||
@@ -14,6 +14,7 @@
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\" \".github/**/*.yml\"",
|
||||
"format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\"",
|
||||
"lint": "eslint src --ext .ts,.tsx --max-warnings 0",
|
||||
@@ -24,6 +25,9 @@
|
||||
"gen:icons": "powershell -ExecutionPolicy Bypass -File scripts/gen-icons.ps1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/bricolage-grotesque": "^5.2.10",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
||||
"electron-updater": "^6.8.3",
|
||||
"framer-motion": "^11.11.17",
|
||||
"lucide-react": "^0.460.0",
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
isSteamRunning
|
||||
} from './steam-launch-options'
|
||||
import type { GameId, GameStatus, LaunchOptionStatus } from '@shared/types'
|
||||
import { log } from '../logger'
|
||||
|
||||
const APP_ID = '570'
|
||||
const INSTALL_DIR = 'dota 2 beta'
|
||||
@@ -198,6 +199,8 @@ export class Dota2Provider implements GameProvider {
|
||||
this.latest = undefined
|
||||
}
|
||||
|
||||
private rejectedTokenLogged = false
|
||||
|
||||
private handle(g: DotaGsi): void {
|
||||
// Verify the per-install token. Dota always sends auth.token; anything
|
||||
// without it (or with the wrong one) is some other process on localhost
|
||||
@@ -207,6 +210,15 @@ export class Dota2Provider implements GameProvider {
|
||||
typeof incoming !== 'string' ||
|
||||
!safeEqualStrings(incoming, this.token)
|
||||
) {
|
||||
// Логируем только ОДИН раз за процесс — Dota шлёт payload каждые
|
||||
// ~100ms во время матча, иначе zass'мём latest.log.
|
||||
if (!this.rejectedTokenLogged) {
|
||||
this.rejectedTokenLogged = true
|
||||
log.warn(
|
||||
'[dota2] GSI payload with invalid/missing token rejected. ' +
|
||||
'Если приложение переустанавливалось — заново подключи Dota 2 в Games.'
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -235,8 +247,12 @@ export class Dota2Provider implements GameProvider {
|
||||
if (prev && prev !== state && state === 'DOTA_GAMERULES_STATE_POST_GAME') {
|
||||
// De-dupe: Dota can fire POST_GAME repeatedly while the scoreboard is open.
|
||||
const now = Date.now()
|
||||
if (now - this.lastMatchEndAt < 30_000) return
|
||||
if (now - this.lastMatchEndAt < 30_000) {
|
||||
log.debug('[dota2] suppressed duplicate POST_GAME within 30s window')
|
||||
return
|
||||
}
|
||||
this.lastMatchEndAt = now
|
||||
log.info('[dota2] POST_GAME detected, emitting match_end event')
|
||||
|
||||
const p = this.latest?.player ?? {}
|
||||
const m = this.latest?.map ?? {}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type Server,
|
||||
type ServerResponse
|
||||
} from 'node:http'
|
||||
import { log } from '../logger'
|
||||
|
||||
export type GsiHandler = (
|
||||
payload: unknown,
|
||||
@@ -87,7 +88,7 @@ async function onRequest(
|
||||
payload = text.length > 0 ? JSON.parse(text) : {}
|
||||
} catch (err) {
|
||||
// Log the real reason locally; do not echo it to the client.
|
||||
console.warn('[gsi] bad request:', err instanceof Error ? err.message : err)
|
||||
log.warn('[gsi] bad request', err instanceof Error ? err.message : err)
|
||||
res.statusCode = 400
|
||||
res.end()
|
||||
return
|
||||
@@ -99,7 +100,7 @@ async function onRequest(
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.end('ok')
|
||||
} catch (err) {
|
||||
console.error('[gsi] handler threw:', err)
|
||||
log.error('[gsi] handler threw', err)
|
||||
res.statusCode = 500
|
||||
res.end()
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
import { STAT_LABELS } from '@shared/types'
|
||||
import { getChallenges, getGamesEnabled } from '../store'
|
||||
import { fireMatchSummary } from '../notifications'
|
||||
import { log } from '../logger'
|
||||
|
||||
const providers: Record<GameId, GameProvider> = {
|
||||
dota2: new Dota2Provider()
|
||||
@@ -25,14 +26,23 @@ async function onMatchEnd(
|
||||
payload: MatchEndPayload
|
||||
): Promise<void> {
|
||||
const provider = providers[gameId]
|
||||
const challenges = getChallenges().filter(
|
||||
(c) => c.gameId === gameId && c.enabled
|
||||
const allChallenges = getChallenges().filter((c) => c.gameId === gameId)
|
||||
const enabledChallenges = allChallenges.filter((c) => c.enabled)
|
||||
log.info(
|
||||
`[games] match_end gameId=${gameId} stats=${JSON.stringify(
|
||||
payload.stats
|
||||
)} challenges=${enabledChallenges.length}/${allChallenges.length} (enabled/total)`
|
||||
)
|
||||
const results: ChallengeResult[] = []
|
||||
for (const ch of challenges) {
|
||||
for (const ch of enabledChallenges) {
|
||||
const statValue = payload.stats[ch.stat] ?? 0
|
||||
const reps = Math.round(statValue * ch.multiplier)
|
||||
if (reps <= 0) continue
|
||||
if (reps <= 0) {
|
||||
log.debug(
|
||||
`[games] skip challenge "${ch.name}": ${ch.stat}=${statValue} × ${ch.multiplier} = ${reps}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
results.push({
|
||||
challengeId: ch.id,
|
||||
name: ch.name,
|
||||
@@ -44,7 +54,21 @@ async function onMatchEnd(
|
||||
stat: ch.stat
|
||||
})
|
||||
}
|
||||
if (results.length === 0) return
|
||||
if (results.length === 0) {
|
||||
log.warn(
|
||||
`[games] match_end produced no reps (no enabled challenges matched stats). ` +
|
||||
`Enabled challenges: ${enabledChallenges.length}, stats keys: ${Object.keys(
|
||||
payload.stats
|
||||
).join(',')}`
|
||||
)
|
||||
return
|
||||
}
|
||||
log.info(
|
||||
`[games] firing match summary: ${results.length} challenges, total reps ${results.reduce(
|
||||
(s, r) => s + r.reps,
|
||||
0
|
||||
)}`
|
||||
)
|
||||
|
||||
const summary: MatchSummary = {
|
||||
gameId,
|
||||
@@ -61,8 +85,9 @@ export async function startGamesRegistry(): Promise<void> {
|
||||
running = true
|
||||
try {
|
||||
await startGsiServer()
|
||||
log.info('[games] GSI server started on port 4701')
|
||||
} catch (err) {
|
||||
console.error('GSI server failed to start:', err)
|
||||
log.error('[games] GSI server failed to start', err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -79,7 +104,7 @@ export async function startGamesRegistry(): Promise<void> {
|
||||
try {
|
||||
await provider.reconcile?.()
|
||||
} catch (err) {
|
||||
console.error('reconcile failed for', id, err)
|
||||
log.error(`[games] reconcile failed for ${id}`, err)
|
||||
}
|
||||
if (!enabled[id]) continue
|
||||
await provider.start((e) => {
|
||||
|
||||
@@ -123,20 +123,19 @@ function writeBackup(path: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(path: string, contents: string): void {
|
||||
async function atomicWrite(path: string, contents: string): Promise<void> {
|
||||
// Write to temp then rename (atomic on Windows for same directory). Retry a
|
||||
// few times on transient EBUSY/EPERM (AV scanners and OneDrive sometimes
|
||||
// hold a handle briefly during a Steam config rewrite).
|
||||
//
|
||||
// Раньше тут был busy-loop sleep — Steam-конфиги пишутся редко, но из main
|
||||
// process, и при попадании на занятый файл (Steam ещё держит handle) морозили
|
||||
// весь UI на 250мс. Заменили на async setTimeout-sleep.
|
||||
const tmp = path + '.exr.tmp'
|
||||
const delays = [0, 50, 200]
|
||||
let lastErr: unknown
|
||||
for (const delay of delays) {
|
||||
if (delay > 0) {
|
||||
const until = Date.now() + delay
|
||||
while (Date.now() < until) {
|
||||
/* spin */
|
||||
}
|
||||
}
|
||||
if (delay > 0) await new Promise<void>((r) => setTimeout(r, delay))
|
||||
try {
|
||||
writeFileSync(tmp, contents, 'utf-8')
|
||||
renameSync(tmp, path)
|
||||
@@ -148,11 +147,11 @@ function atomicWrite(path: string, contents: string): void {
|
||||
throw lastErr
|
||||
}
|
||||
|
||||
function modifyLaunchOptions(
|
||||
async function modifyLaunchOptions(
|
||||
configPath: string,
|
||||
appId: string,
|
||||
fn: (current: string) => string | null
|
||||
): boolean {
|
||||
): Promise<boolean> {
|
||||
let raw: string
|
||||
try {
|
||||
raw = readFileSync(configPath, 'utf-8')
|
||||
@@ -188,7 +187,7 @@ function modifyLaunchOptions(
|
||||
|
||||
writeBackup(configPath)
|
||||
try {
|
||||
atomicWrite(configPath, stringifyVdf(parsed))
|
||||
await atomicWrite(configPath, stringifyVdf(parsed))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -225,7 +224,7 @@ async function applyOptionToAllConfigs(
|
||||
): Promise<void> {
|
||||
const paths = await getLocalConfigPaths()
|
||||
for (const p of paths) {
|
||||
modifyLaunchOptions(p, appId, (current) => {
|
||||
await modifyLaunchOptions(p, appId, (current) => {
|
||||
if (current.includes(option)) return current
|
||||
return current.length > 0 ? `${current} ${option}` : option
|
||||
})
|
||||
@@ -238,7 +237,7 @@ async function removeOptionFromAllConfigs(
|
||||
): Promise<void> {
|
||||
const paths = await getLocalConfigPaths()
|
||||
for (const p of paths) {
|
||||
modifyLaunchOptions(p, appId, (current) => {
|
||||
await modifyLaunchOptions(p, appId, (current) => {
|
||||
if (!current.includes(option)) return current
|
||||
return current
|
||||
.split(/\s+/)
|
||||
|
||||
@@ -73,11 +73,26 @@ if (!gotLock) {
|
||||
}
|
||||
})
|
||||
|
||||
app.on('before-quit', () => {
|
||||
// Перехватываем первый before-quit, чтобы дождаться `stopGamesRegistry`
|
||||
// (закрывает GSI HTTP server со всеми pending connections). Без этого
|
||||
// следующий запуск получает EADDRINUSE на port 4701 (TIME_WAIT), и
|
||||
// GSI молча не работает. После cleanup'а — реально quit.
|
||||
let quitting = false
|
||||
app.on('before-quit', (e) => {
|
||||
if (quitting) return
|
||||
e.preventDefault()
|
||||
quitting = true
|
||||
stopScheduler()
|
||||
stopUpdater()
|
||||
void stopGamesRegistry()
|
||||
flushNow()
|
||||
void (async () => {
|
||||
try {
|
||||
await stopGamesRegistry()
|
||||
} catch (err) {
|
||||
console.error('[index] stopGamesRegistry threw:', err)
|
||||
}
|
||||
flushNow()
|
||||
app.exit(0)
|
||||
})()
|
||||
})
|
||||
|
||||
app.on('activate', () => {
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
deleteExercise,
|
||||
getHistory,
|
||||
getState,
|
||||
getStateForRenderer,
|
||||
markDone,
|
||||
setGameEnabled,
|
||||
skip,
|
||||
@@ -56,8 +57,13 @@ import {
|
||||
|
||||
export function registerIpc(): void {
|
||||
ipcMain.handle(IPC.getState, () => {
|
||||
const state = getState()
|
||||
state.settings.startWithWindows = isAutostartEnabled()
|
||||
// Без history (см. getStateForRenderer) и с актуальным значением
|
||||
// autostart из OS — мутацию делаем по копии, не по cache.
|
||||
const state = getStateForRenderer()
|
||||
state.settings = {
|
||||
...state.settings,
|
||||
startWithWindows: isAutostartEnabled()
|
||||
}
|
||||
return state
|
||||
})
|
||||
|
||||
@@ -275,7 +281,7 @@ export function registerIpc(): void {
|
||||
// otherwise fabricate arbitrary match-end events at will.
|
||||
if (!app.isPackaged) {
|
||||
ipcMain.handle(
|
||||
'dev:simulateMatchEnd',
|
||||
IPC.devSimulateMatchEnd,
|
||||
(_e, id: GameId, stats: Record<string, number>) => {
|
||||
simulateMatchEnd(id, stats)
|
||||
}
|
||||
|
||||
125
src/main/logger.ts
Normal file
125
src/main/logger.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/* eslint-disable no-console -- этот файл — единственное место где console.*
|
||||
разрешён намеренно: дублирование лога в stderr для dev-режима. */
|
||||
/**
|
||||
* Минимальный logger для main process.
|
||||
*
|
||||
* Пишет в файл `%APPDATA%/Exercise Reminder/logs/latest.log` + дублирует
|
||||
* в stderr через console.* (чтобы dev-режим оставался удобным).
|
||||
*
|
||||
* Ротация: при достижении 1MB latest.log переименовывается в prev.log
|
||||
* (предыдущий prev.log удаляется). Две сессии истории — этого достаточно
|
||||
* для воспроизведения «случилось вчера, а сегодня перезапустил». Никакой
|
||||
* remote-телеметрии: лог локальный, пользователь сам может вложить его в
|
||||
* issue если что-то сломалось.
|
||||
*
|
||||
* Уровни:
|
||||
* - debug: подробный traceback, видим только если LAUDE_DEBUG=1
|
||||
* - info: значимые события (startup, GSI matched, updater progress)
|
||||
* - warn: recoverable issues (transient network, retry succeeded)
|
||||
* - error: что-то реально сломалось (atomic write fail, IPC validation)
|
||||
*/
|
||||
import { app } from 'electron'
|
||||
import {
|
||||
appendFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
unlinkSync
|
||||
} from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const ROTATE_AT_BYTES = 1 * 1024 * 1024 // 1 MB
|
||||
|
||||
type Level = 'debug' | 'info' | 'warn' | 'error'
|
||||
|
||||
let logDir = ''
|
||||
let logPath = ''
|
||||
let prevPath = ''
|
||||
|
||||
function ensurePaths(): void {
|
||||
if (logDir) return
|
||||
try {
|
||||
logDir = join(app.getPath('userData'), 'logs')
|
||||
if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true })
|
||||
logPath = join(logDir, 'latest.log')
|
||||
prevPath = join(logDir, 'prev.log')
|
||||
} catch {
|
||||
// app.getPath не готов (очень ранний boot) — отложим, console продолжит.
|
||||
}
|
||||
}
|
||||
|
||||
function rotateIfNeeded(): void {
|
||||
if (!logPath) return
|
||||
try {
|
||||
if (!existsSync(logPath)) return
|
||||
const size = statSync(logPath).size
|
||||
if (size < ROTATE_AT_BYTES) return
|
||||
if (existsSync(prevPath)) unlinkSync(prevPath)
|
||||
renameSync(logPath, prevPath)
|
||||
} catch {
|
||||
// не критично — продолжим писать в latest.log с overflow
|
||||
}
|
||||
}
|
||||
|
||||
function ts(): string {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function levelTag(l: Level): string {
|
||||
return l.toUpperCase().padEnd(5, ' ')
|
||||
}
|
||||
|
||||
function write(level: Level, msg: string, extra?: unknown): void {
|
||||
// Always dup to console for dev. structuredClone-style serialize:
|
||||
const line = `[${ts()}] ${levelTag(level)} ${msg}${
|
||||
extra !== undefined ? ' ' + safeStringify(extra) : ''
|
||||
}\n`
|
||||
switch (level) {
|
||||
case 'error':
|
||||
console.error(line.trimEnd())
|
||||
break
|
||||
case 'warn':
|
||||
console.warn(line.trimEnd())
|
||||
break
|
||||
case 'debug':
|
||||
case 'info':
|
||||
default:
|
||||
console.log(line.trimEnd())
|
||||
}
|
||||
ensurePaths()
|
||||
rotateIfNeeded()
|
||||
if (!logPath) return
|
||||
try {
|
||||
appendFileSync(logPath, line, 'utf-8')
|
||||
} catch {
|
||||
// Если AV держит файл — переживём, в console уже залогировали.
|
||||
}
|
||||
}
|
||||
|
||||
function safeStringify(v: unknown): string {
|
||||
if (v instanceof Error) {
|
||||
return v.stack ?? `${v.name}: ${v.message}`
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(v)
|
||||
} catch {
|
||||
return String(v)
|
||||
}
|
||||
}
|
||||
|
||||
const DEBUG_ENABLED = process.env.LAUDE_DEBUG === '1'
|
||||
|
||||
export const log = {
|
||||
debug: (msg: string, extra?: unknown): void => {
|
||||
if (DEBUG_ENABLED) write('debug', msg, extra)
|
||||
},
|
||||
info: (msg: string, extra?: unknown): void => write('info', msg, extra),
|
||||
warn: (msg: string, extra?: unknown): void => write('warn', msg, extra),
|
||||
error: (msg: string, extra?: unknown): void => write('error', msg, extra)
|
||||
}
|
||||
|
||||
/** Путь к логам (для диагностики). Возвращает пустую строку до initLogger(). */
|
||||
export function getLogDir(): string {
|
||||
return logDir
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import { getExercises, getState, updateExercise } from './store'
|
||||
import { getExercises, getStateForRenderer, updateExercise } from './store'
|
||||
|
||||
export function broadcastState(): void {
|
||||
const state = getState()
|
||||
// Используем variant без `history` — иначе при 10k записей через IPC
|
||||
// на каждый markDone летит 500KB JSON × M подписчиков. Renderer
|
||||
// запрашивает историю отдельно через IPC.getHistory.
|
||||
const state = getStateForRenderer()
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
if (!win.isDestroyed()) win.webContents.send(IPC.evtStateChanged, state)
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@ import {
|
||||
GameId,
|
||||
HistoryAction,
|
||||
HistoryEntry,
|
||||
PersistedState,
|
||||
SAMPLE_EXERCISES,
|
||||
Settings
|
||||
} from '@shared/types'
|
||||
import { log } from './logger'
|
||||
|
||||
/**
|
||||
* Keep at most this many history entries (≈2.7 years at 10/day).
|
||||
@@ -30,7 +32,7 @@ const HISTORY_MAX = 10_000
|
||||
const WRITE_DEBOUNCE_MS = 1500
|
||||
const WRITE_RETRY_DELAYS = [50, 200, 800] // ms backoff on transient EBUSY/EPERM
|
||||
|
||||
let cache: AppState | null = null
|
||||
let cache: PersistedState | null = null
|
||||
let storePath = ''
|
||||
let pendingWrite: NodeJS.Timeout | null = null
|
||||
|
||||
@@ -43,7 +45,7 @@ function getStorePath(): string {
|
||||
return storePath
|
||||
}
|
||||
|
||||
function makeInitial(): AppState {
|
||||
function makeInitial(): PersistedState {
|
||||
const now = Date.now()
|
||||
return {
|
||||
exercises: SAMPLE_EXERCISES.map((e) => ({
|
||||
@@ -88,12 +90,11 @@ function quarantineCorrupt(p: string, reason: string): void {
|
||||
.replace(/Z$/, '')
|
||||
const dest = `${p}.corrupt-${stamp}`
|
||||
renameSync(p, dest)
|
||||
console.error(
|
||||
`[store] app-state.json was unreadable (${reason}); ` +
|
||||
`moved to ${dest} and starting fresh.`
|
||||
log.error(
|
||||
`[store] app-state.json was unreadable (${reason}); moved to ${dest} and starting fresh.`
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('[store] failed to quarantine corrupt state file:', e)
|
||||
log.error('[store] failed to quarantine corrupt state file', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,8 +145,8 @@ function runMigrations(s: StoredState): StoredState {
|
||||
return cursor
|
||||
}
|
||||
|
||||
/** Coerce a (possibly partial) migrated state into a fully-formed AppState. */
|
||||
function coerce(s: StoredState): AppState {
|
||||
/** Coerce a (possibly partial) migrated state into a fully-formed PersistedState. */
|
||||
function coerce(s: StoredState): PersistedState {
|
||||
return {
|
||||
exercises: Array.isArray(s.exercises) ? (s.exercises as Exercise[]) : [],
|
||||
settings: {
|
||||
@@ -162,11 +163,12 @@ function coerce(s: StoredState): AppState {
|
||||
}
|
||||
}
|
||||
|
||||
function load(): AppState {
|
||||
function load(): PersistedState {
|
||||
const p = getStorePath()
|
||||
if (!existsSync(p)) {
|
||||
const initial = makeInitial()
|
||||
atomicWrite(
|
||||
// Cold path — sync write на инициализации (event-loop ещё не активен).
|
||||
atomicWriteSync(
|
||||
p,
|
||||
JSON.stringify(
|
||||
{ __schemaVersion: CURRENT_SCHEMA_VERSION, ...initial },
|
||||
@@ -180,7 +182,7 @@ function load(): AppState {
|
||||
try {
|
||||
raw = readFileSync(p, 'utf-8')
|
||||
} catch (e) {
|
||||
console.error('[store] cannot read state file:', e)
|
||||
log.error('[store] cannot read state file', e)
|
||||
return makeInitial() // do not quarantine — we can't read it anyway
|
||||
}
|
||||
let parsed: unknown
|
||||
@@ -235,8 +237,16 @@ export function clearHistory(beforeTs?: number): number {
|
||||
/**
|
||||
* Atomically write to `path` via a sibling .tmp file + rename. Retries a few
|
||||
* times on transient EBUSY/EPERM (AV/OneDrive holding the file).
|
||||
*
|
||||
* Async version (используется debounced scheduleWrite/flush) — раньше был
|
||||
* busy-loop `while (Date.now() < until)`, который морозил весь main process
|
||||
* на retry-delay (до 800мс). При активном AV это превращалось в видимое
|
||||
* залипание UI. Сейчас sleep через setTimeout-promise.
|
||||
*
|
||||
* Для процесса-выхода используется `atomicWriteSync` — там event-loop уже
|
||||
* не работает, async sleep не сработает.
|
||||
*/
|
||||
function atomicWrite(path: string, contents: string): void {
|
||||
async function atomicWrite(path: string, contents: string): Promise<void> {
|
||||
const tmp = `${path}.tmp`
|
||||
let lastErr: unknown
|
||||
for (let i = 0; i <= WRITE_RETRY_DELAYS.length; i++) {
|
||||
@@ -246,7 +256,6 @@ function atomicWrite(path: string, contents: string): void {
|
||||
return
|
||||
} catch (e) {
|
||||
lastErr = e
|
||||
// best-effort cleanup of the stale .tmp
|
||||
try {
|
||||
if (existsSync(tmp)) unlinkSync(tmp)
|
||||
} catch {
|
||||
@@ -254,40 +263,97 @@ function atomicWrite(path: string, contents: string): void {
|
||||
}
|
||||
const delay = WRITE_RETRY_DELAYS[i]
|
||||
if (delay === undefined) break
|
||||
// Synchronous sleep — write path is short and called outside the hot loop.
|
||||
await new Promise<void>((r) => setTimeout(r, delay))
|
||||
}
|
||||
}
|
||||
log.error('[store] atomic write failed after retries', lastErr)
|
||||
}
|
||||
|
||||
/**
|
||||
* Синхронный вариант для use-cases где event loop уже не работает
|
||||
* (process exit в `before-quit`). При retry — короткий sync sleep, потому
|
||||
* что иначе мы дропнем pending write при exit'е.
|
||||
*/
|
||||
function atomicWriteSync(path: string, contents: string): void {
|
||||
const tmp = `${path}.tmp`
|
||||
let lastErr: unknown
|
||||
for (let i = 0; i <= WRITE_RETRY_DELAYS.length; i++) {
|
||||
try {
|
||||
writeFileSync(tmp, contents, 'utf-8')
|
||||
renameSync(tmp, path)
|
||||
return
|
||||
} catch (e) {
|
||||
lastErr = e
|
||||
try {
|
||||
if (existsSync(tmp)) unlinkSync(tmp)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const delay = WRITE_RETRY_DELAYS[i]
|
||||
if (delay === undefined) break
|
||||
// Event-loop остановлен, async sleep не вернётся — приходится spin.
|
||||
const until = Date.now() + delay
|
||||
while (Date.now() < until) {
|
||||
/* spin */
|
||||
}
|
||||
}
|
||||
}
|
||||
console.error('[store] atomic write failed after retries:', lastErr)
|
||||
log.error('[store] atomic sync write failed after retries', lastErr)
|
||||
}
|
||||
|
||||
function flush(): void {
|
||||
async function flush(): Promise<void> {
|
||||
if (!cache) return
|
||||
// Persist the schema version alongside the state so future migrations know
|
||||
// where to pick up from. The renderer never reads this key.
|
||||
const payload = { __schemaVersion: CURRENT_SCHEMA_VERSION, ...cache }
|
||||
atomicWrite(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
await atomicWrite(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
}
|
||||
|
||||
function flushSync(): void {
|
||||
if (!cache) return
|
||||
const payload = { __schemaVersion: CURRENT_SCHEMA_VERSION, ...cache }
|
||||
atomicWriteSync(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
}
|
||||
|
||||
function scheduleWrite(): void {
|
||||
if (pendingWrite) return
|
||||
pendingWrite = setTimeout(() => {
|
||||
pendingWrite = null
|
||||
flush()
|
||||
void flush()
|
||||
}, WRITE_DEBOUNCE_MS)
|
||||
// Don't keep the event loop alive solely for a pending write — `before-quit`
|
||||
// calls `flushNow()` and we explicitly want the process to exit on schedule.
|
||||
pendingWrite.unref?.()
|
||||
}
|
||||
|
||||
export function getState(): AppState {
|
||||
/**
|
||||
* Internal persisted state — единственный source of truth. Включает историю.
|
||||
* Mutate напрямую (mutations внутри store.ts), затем scheduleWrite().
|
||||
*/
|
||||
export function getState(): PersistedState {
|
||||
if (!cache) cache = load()
|
||||
return cache
|
||||
}
|
||||
|
||||
/**
|
||||
* State для отправки renderer'у. Копия БЕЗ `history` — историю renderer
|
||||
* запрашивает отдельным IPC.getHistory. Раньше каждый markDone/snooze
|
||||
* отправлял весь state через evtStateChanged, и при 10k entries в истории
|
||||
* это 500KB JSON × N IPC mutations подряд → заметный лаг.
|
||||
*
|
||||
* Возвращаемая копия безопасна для мутации (ipc.ts накладывает на settings
|
||||
* актуальное OS-значение startWithWindows) — мы НЕ мутируем cache.
|
||||
*/
|
||||
export function getStateForRenderer(): AppState {
|
||||
const p = getState()
|
||||
return {
|
||||
exercises: p.exercises,
|
||||
settings: p.settings,
|
||||
challenges: p.challenges,
|
||||
gamesEnabled: p.gamesEnabled
|
||||
}
|
||||
}
|
||||
|
||||
export function getSettings(): Settings {
|
||||
return getState().settings
|
||||
}
|
||||
@@ -389,7 +455,9 @@ export function flushNow(): void {
|
||||
clearTimeout(pendingWrite)
|
||||
pendingWrite = null
|
||||
}
|
||||
flush()
|
||||
// before-quit вызывает нас когда event-loop уже на пути к выходу — async
|
||||
// promise не успеет resolved, поэтому sync.
|
||||
flushSync()
|
||||
}
|
||||
|
||||
export function getChallenges(): Challenge[] {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { app, BrowserWindow } from 'electron'
|
||||
import { autoUpdater } from 'electron-updater'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import type { UpdaterStatus } from '@shared/types'
|
||||
import { log } from './logger'
|
||||
|
||||
let currentStatus: UpdaterStatus = { kind: 'idle' }
|
||||
let lastCheckedAt: number | undefined
|
||||
@@ -98,7 +99,7 @@ export function initUpdater(): void {
|
||||
if (silentMode) {
|
||||
// Background check failed — keep previous status, don't show red banner.
|
||||
// Will retry on the next hourly tick.
|
||||
console.warn('[updater] silent check failed:', message)
|
||||
log.warn('[updater] silent check failed', message)
|
||||
return
|
||||
}
|
||||
setStatus({ kind: 'error', message })
|
||||
@@ -148,7 +149,7 @@ export async function checkForUpdates(
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (silentMode) {
|
||||
console.warn('[updater] silent check failed (sync):', message)
|
||||
log.warn('[updater] silent check failed (sync)', message)
|
||||
} else {
|
||||
setStatus({ kind: 'error', message })
|
||||
}
|
||||
|
||||
@@ -106,7 +106,12 @@ export function createMainWindow(showImmediately = true): BrowserWindow {
|
||||
...(icon ? { icon } : {}),
|
||||
webPreferences: {
|
||||
preload: preloadPath(),
|
||||
sandbox: false,
|
||||
// sandbox: true — preload использует только contextBridge + ipcRenderer
|
||||
// (оба sandbox-safe), никаких Node-built-ins (fs/path/child_process).
|
||||
// Sandbox изолирует renderer от Chromium GPU/IPC процессов на уровне
|
||||
// OS-сэндбокса; даже RCE через зависимости renderer'а не получит
|
||||
// полного Node-доступа из preload.
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
@@ -171,7 +176,7 @@ export function createReminderWindow(): BrowserWindow {
|
||||
...(icon ? { icon } : {}),
|
||||
webPreferences: {
|
||||
preload: preloadPath(),
|
||||
sandbox: false,
|
||||
sandbox: true, // см. createMainWindow — preload не использует Node.
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ const api = {
|
||||
id: GameId,
|
||||
stats: Record<string, number>
|
||||
): Promise<void> =>
|
||||
ipcRenderer.invoke('dev:simulateMatchEnd', id, stats)
|
||||
ipcRenderer.invoke(IPC.devSimulateMatchEnd, id, stats)
|
||||
}
|
||||
: {}),
|
||||
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; script-src 'self'" />
|
||||
<!--
|
||||
CSP: всё локально, без внешних origins. Шрифты подгружаются через
|
||||
@fontsource/* импорты в globals.css. style-src 'unsafe-inline' нужен
|
||||
для Tailwind utility-классов и инлайн-стилей framer-motion. font-src
|
||||
включает data: на случай если кто-то вставит base64 SVG-glyph.
|
||||
-->
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; script-src 'self'; connect-src 'self'; base-uri 'self'; frame-ancestors 'none'" />
|
||||
<title>Exercise Reminder</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700;12..96,800&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,11 +1,51 @@
|
||||
import * as Lucide from 'lucide-react'
|
||||
// Explicit-named imports — НЕ wildcard. Wildcard `* as Lucide` ломает
|
||||
// tree-shaking: в bundle попадает вся библиотека (~500KB minified, 1500+
|
||||
// иконок). Сейчас в bundle только 18 ICON_CHOICES.
|
||||
import {
|
||||
Activity,
|
||||
Dumbbell,
|
||||
StretchHorizontal,
|
||||
PersonStanding,
|
||||
Heart,
|
||||
Footprints,
|
||||
Hand,
|
||||
Eye,
|
||||
Brain,
|
||||
Bike,
|
||||
Waves,
|
||||
Wind,
|
||||
Sun,
|
||||
Coffee,
|
||||
Apple,
|
||||
GlassWater,
|
||||
BookOpen,
|
||||
Sparkles
|
||||
} from 'lucide-react'
|
||||
import type { LucideProps } from 'lucide-react'
|
||||
import { ICON_CHOICES, type IconName } from './icon-choices'
|
||||
|
||||
// Re-export для обратной совместимости с импортёрами icon.tsx.
|
||||
export { ICON_CHOICES, type IconName }
|
||||
|
||||
const ICON_SET = new Set<string>(ICON_CHOICES)
|
||||
const ICON_MAP: Record<IconName, React.ComponentType<LucideProps>> = {
|
||||
Activity,
|
||||
Dumbbell,
|
||||
StretchHorizontal,
|
||||
PersonStanding,
|
||||
Heart,
|
||||
Footprints,
|
||||
Hand,
|
||||
Eye,
|
||||
Brain,
|
||||
Bike,
|
||||
Waves,
|
||||
Wind,
|
||||
Sun,
|
||||
Coffee,
|
||||
Apple,
|
||||
GlassWater,
|
||||
BookOpen,
|
||||
Sparkles
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a Lucide icon by name. Restricted to the curated ICON_CHOICES set —
|
||||
@@ -17,15 +57,12 @@ export function Icon({
|
||||
name,
|
||||
...props
|
||||
}: { name: string } & LucideProps): JSX.Element {
|
||||
if (!ICON_SET.has(name)) {
|
||||
const Cmp = ICON_MAP[name as IconName]
|
||||
if (!Cmp) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`[Icon] unknown icon name "${name}" — falling back`)
|
||||
}
|
||||
return <Lucide.Activity {...props} />
|
||||
return <Activity {...props} />
|
||||
}
|
||||
const Cmp = (
|
||||
Lucide as unknown as Record<string, React.ComponentType<LucideProps>>
|
||||
)[name]
|
||||
if (!Cmp) return <Lucide.Activity {...props} />
|
||||
return <Cmp {...props} />
|
||||
}
|
||||
|
||||
@@ -264,11 +264,18 @@ function ChallengeEditor({
|
||||
type="number"
|
||||
step="0.5"
|
||||
min="0.5"
|
||||
max="1000"
|
||||
value={draft.multiplier}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
multiplier: Math.max(0.5, Number(e.target.value) || 1)
|
||||
// Клампим к диапазону [0.5, 1000] — совпадает с validate.ts
|
||||
// (multiplier ∈ [0, 1000]). Без max=1000 пользователь мог
|
||||
// ввести 9999 и save молча отклонялся IPC-валидатором.
|
||||
multiplier: Math.max(
|
||||
0.5,
|
||||
Math.min(1000, Number(e.target.value) || 1)
|
||||
)
|
||||
})
|
||||
}
|
||||
className="ios-input font-mono-num"
|
||||
|
||||
@@ -25,5 +25,15 @@ export function ThemeProvider({
|
||||
else document.documentElement.classList.remove('dark')
|
||||
}, [settings?.theme, osTheme])
|
||||
|
||||
// Синхронизируем <html lang> с языком приложения. Без этого screen-readers
|
||||
// продолжают читать английский текст как кириллицу (или ломаются) при
|
||||
// переключении на EN, и наоборот — это a11y-баг.
|
||||
useEffect(() => {
|
||||
const lang = settings?.language ?? 'ru'
|
||||
if (document.documentElement.lang !== lang) {
|
||||
document.documentElement.lang = lang
|
||||
}
|
||||
}, [settings?.language])
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
/* Self-hosted шрифты — раньше тянулись с fonts.googleapis.com через <link>
|
||||
в index.html. Минусы: внешняя зависимость (без интернета шрифты не
|
||||
загружаются), CSP вынужден разрешать style-src https://fonts.googleapis.com
|
||||
и font-src https://fonts.gstatic.com. Сейчас локальные .woff2 в bundle. */
|
||||
@import '@fontsource/plus-jakarta-sans/400.css';
|
||||
@import '@fontsource/plus-jakarta-sans/500.css';
|
||||
@import '@fontsource/plus-jakarta-sans/600.css';
|
||||
@import '@fontsource/plus-jakarta-sans/700.css';
|
||||
@import '@fontsource/plus-jakarta-sans/800.css';
|
||||
@import '@fontsource/bricolage-grotesque/500.css';
|
||||
@import '@fontsource/bricolage-grotesque/600.css';
|
||||
@import '@fontsource/bricolage-grotesque/700.css';
|
||||
@import '@fontsource/bricolage-grotesque/800.css';
|
||||
@import '@fontsource/jetbrains-mono/400.css';
|
||||
@import '@fontsource/jetbrains-mono/500.css';
|
||||
@import '@fontsource/jetbrains-mono/600.css';
|
||||
@import '@fontsource/jetbrains-mono/700.css';
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@@ -38,6 +38,10 @@ export const IPC = {
|
||||
markChallengeDone: 'challenge:markDone',
|
||||
closeMatchSummary: 'matchSummary:close',
|
||||
|
||||
// Dev-only IPC (handler ungated в prod, см. ipc.ts). Держим в enum чтобы
|
||||
// main/preload/renderer не разошлись в hardcoded-строках.
|
||||
devSimulateMatchEnd: 'dev:simulateMatchEnd',
|
||||
|
||||
// Auto-updater
|
||||
updaterStatus: 'updater:status',
|
||||
updaterCheck: 'updater:check',
|
||||
|
||||
@@ -39,11 +39,22 @@ export type Settings = {
|
||||
quietHours: QuietHours
|
||||
}
|
||||
|
||||
/**
|
||||
* State, видимое renderer'у (через IPC.getState и evtStateChanged).
|
||||
* `history` намеренно НЕ включена — она достигает 10k записей × ~50 байт =
|
||||
* 500KB JSON, и шлать её на каждый markDone/snooze/etc слишком дорого.
|
||||
* Renderer запрашивает историю отдельно через `getHistory()` IPC (с опц.
|
||||
* `sinceMs` для инкрементальной подгрузки).
|
||||
*/
|
||||
export type AppState = {
|
||||
exercises: Exercise[]
|
||||
settings: Settings
|
||||
challenges: Challenge[]
|
||||
gamesEnabled: Partial<Record<GameId, boolean>>
|
||||
}
|
||||
|
||||
/** Persisted shape — расширяет AppState историей (живёт только в main). */
|
||||
export type PersistedState = AppState & {
|
||||
history?: HistoryEntry[]
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user