feat(dashboard): make overview action-first

This commit is contained in:
Codex
2026-06-07 22:48:24 +07:00
parent ea052f64b8
commit 84b2bbf0a6
10 changed files with 353 additions and 43 deletions

View File

@@ -0,0 +1,73 @@
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
const h = vi.hoisted(() => ({
app: {
setLoginItemSettings: vi.fn(),
getLoginItemSettings: vi.fn(() => ({ openAtLogin: false })),
wasOpenedAsHidden: false
}
}))
vi.mock('electron', () => ({ app: h.app }))
const originalPlatform = process.platform
function setPlatform(platform: NodeJS.Platform): void {
Object.defineProperty(process, 'platform', {
value: platform,
configurable: true
})
}
async function load(): Promise<typeof import('./autostart')> {
vi.resetModules()
return import('./autostart')
}
beforeEach(() => {
setPlatform('win32')
h.app.setLoginItemSettings.mockClear()
h.app.getLoginItemSettings.mockReset()
h.app.getLoginItemSettings.mockReturnValue({ openAtLogin: false })
})
afterEach(() => {
setPlatform(originalPlatform)
})
describe('autostart', () => {
it('writes Windows login item with the hidden startup argument', async () => {
const { setAutostart } = await load()
setAutostart(true)
expect(h.app.setLoginItemSettings).toHaveBeenCalledWith({
openAtLogin: true,
openAsHidden: true,
path: process.execPath,
args: ['--hidden']
})
})
it('reads Windows login item using the same path and args', async () => {
h.app.getLoginItemSettings.mockReturnValue({ openAtLogin: true })
const { isAutostartEnabled } = await load()
expect(isAutostartEnabled()).toBe(true)
expect(h.app.getLoginItemSettings).toHaveBeenCalledWith({
path: process.execPath,
args: ['--hidden']
})
})
it('does nothing on non-Windows platforms', async () => {
setPlatform('linux')
const { setAutostart, isAutostartEnabled } = await load()
setAutostart(true)
expect(isAutostartEnabled()).toBe(false)
expect(h.app.setLoginItemSettings).not.toHaveBeenCalled()
expect(h.app.getLoginItemSettings).not.toHaveBeenCalled()
})
})

View File

@@ -1,19 +1,29 @@
import { app } from 'electron'
const HIDDEN_FLAG = '--hidden'
type LoginItemOptions = NonNullable<
Parameters<typeof app.getLoginItemSettings>[0]
>
function loginItemOptions(): LoginItemOptions {
return {
path: process.execPath,
args: [HIDDEN_FLAG]
}
}
export function setAutostart(enabled: boolean): void {
if (process.platform !== 'win32') return
app.setLoginItemSettings({
...loginItemOptions(),
openAtLogin: enabled,
path: process.execPath,
args: [HIDDEN_FLAG]
openAsHidden: true
})
}
export function isAutostartEnabled(): boolean {
if (process.platform !== 'win32') return false
return app.getLoginItemSettings().openAtLogin
return app.getLoginItemSettings(loginItemOptions()).openAtLogin
}
export function wasStartedHidden(): boolean {

View File

@@ -84,13 +84,19 @@ describe('isMeetingActive', () => {
})
it('кэширует результат в пределах CACHE_MS (exec вызывается один раз)', async () => {
h.execImpl = (_c, _o, cb) => cb(null, { stdout: csv('discord.exe') })
h.execImpl = (_c, _o, cb) => cb(null, { stdout: csv('zoom.exe') })
const { isMeetingActive } = await load()
await isMeetingActive()
await isMeetingActive()
expect(h.calls).toBe(1)
})
it('не считает Discord встречей', async () => {
h.execImpl = (_c, _o, cb) => cb(null, { stdout: csv('discord.exe') })
const { isMeetingActive } = await load()
expect(await isMeetingActive()).toBe(false)
})
it('при падении tasklist возвращает false и логирует warn', async () => {
h.execImpl = (_c, _o, cb) => cb(new Error('ETIMEDOUT'))
const { isMeetingActive } = await load()

View File

@@ -1,7 +1,7 @@
/**
* Эвристическое обнаружение «человек на ВКС» по списку запущенных процессов.
*
* Идея: если запущен Zoom/Teams/Discord/Meet/Webex — пользователь скорее
* Идея: если запущен Zoom/Teams/Meet/Webex — пользователь скорее
* всего на встрече или собирается зайти. Останавливаем напоминания, чтобы
* не прерывать. После «снятия» процессов возобновляем.
*
@@ -36,7 +36,6 @@ const MEETING_PROCESSES = new Set([
'zoom.exe',
'teams.exe',
'ms-teams.exe', // новые Teams 2.0
'discord.exe',
'webex.exe',
'webexmta.exe',
'meet.exe', // Google Meet desktop (редкость)

View File

@@ -12,7 +12,7 @@ export type Dict = Record<string, string>
export const ru: Dict = {
// Sidebar / nav
'nav.today': 'Сегодня',
'nav.today': 'Обзор',
'nav.exercises': 'Упражнения',
'nav.meals': 'Питание',
'nav.games': 'Игры',
@@ -60,11 +60,34 @@ export const ru: Dict = {
'btn.retry': 'Повторить',
// Dashboard
'dashboard.kicker': 'Тренировка дня',
'dashboard.title': 'Сегодня',
'dashboard.kicker': 'План перерывов',
'dashboard.title': 'Что важно сейчас',
'dashboard.header.date': 'План на {date}',
'dashboard.header.status.paused': 'пауза',
'dashboard.header.status.meeting': 'встреча',
'dashboard.header.status.due': 'ждёт действия',
'dashboard.header.status.running': 'в работе',
'dashboard.header.status.clear': 'спокойно',
'dashboard.header.title.paused': 'Напоминания на паузе',
'dashboard.header.subtitle.paused':
'Запусти их снова, когда будешь готов вернуться к коротким перерывам.',
'dashboard.header.title.meeting': 'Встреча активна',
'dashboard.header.subtitle.meeting':
'Пауза на встречах включена. Напоминания продолжатся, когда звонок закончится.',
'dashboard.header.title.due': 'Пора сделать: {name}',
'dashboard.header.subtitle.due':
'{kind} · {meta}. Это ближайшее действие по плану.',
'dashboard.header.title.next': 'Следующее: {name}',
'dashboard.header.subtitle.next': '{kind} · {meta} · {time}',
'dashboard.header.title.empty': 'Настрой первый перерыв',
'dashboard.header.subtitle.empty':
'Добавь упражнение или питание, чтобы приложение собрало понятный план дня.',
'dashboard.header.title.clear': 'План под контролем',
'dashboard.header.subtitle.clear':
'Срочных действий нет. Ниже видно цели, ритм недели и игровые долги.',
'dashboard.stat.active': 'Активных',
'dashboard.stat.active.of': 'из {total}',
'dashboard.stat.today_done': 'Сегодня',
'dashboard.stat.today_done': 'Сделано',
'dashboard.stat.today_done.subtitle': 'повторов за день',
'dashboard.stat.streak': 'Стрик',
'dashboard.stat.streak.subtitle': '{n} дн. подряд',
@@ -82,11 +105,11 @@ export const ru: Dict = {
'нужно закрыть Steam и снова открыть',
'dashboard.paused.title': 'Напоминания на паузе',
'dashboard.paused.hint': 'Возобнови, чтобы продолжить отсчёт',
'dashboard.meeting.title': 'Не дёргаем — ты на встрече',
'dashboard.meeting.title': 'Встреча активна',
'dashboard.meeting.hint':
'Запущен Zoom / Teams / Discord / Webex / Slack-huddle. Напоминания возобновятся когда закроешь.',
'dashboard.plan.title': 'План дня',
'dashboard.plan.subtitle': 'Следующее действие и дневные цели',
'Запущен Zoom / Teams / Webex / Slack-huddle. Напоминания возобновятся, когда встреча закончится.',
'dashboard.plan.title': 'Ближайший шаг',
'dashboard.plan.subtitle': 'Что сделать сейчас, дневные цели и питание',
'dashboard.plan.due_count': '{n} ждёт',
'dashboard.plan.all_caught_up': 'всё спокойно',
'dashboard.plan.next_action': 'Следующее действие',
@@ -145,7 +168,7 @@ export const ru: Dict = {
'momentum.quest.week_reps.desc': 'набери тысячу повторов за неделю',
'momentum.quest.match_debt.title': 'Закрыть катки',
'momentum.quest.match_debt.desc': 'закрой 3 игровых долга за неделю',
'momentum.quest.today_anchor.title': 'Сегодня не ноль',
'momentum.quest.today_anchor.title': 'День не ноль',
'momentum.quest.today_anchor.desc': 'сделай хотя бы одно действие сегодня',
'momentum.game.kicker': 'После катки',
'momentum.game.title': 'Игровой долг',
@@ -348,7 +371,7 @@ export const ru: Dict = {
'Диктор произносит название упражнения и количество — полезно когда фокус на коде.',
'settings.meeting_pause.label': 'Пауза на встречах',
'settings.meeting_pause.hint':
'Не дёргать, если запущен Zoom / Teams / Discord / Webex / Slack-huddle.',
'Ставить напоминания на паузу, если запущен Zoom / Teams / Webex / Slack-huddle.',
'settings.snooze.label': '«Отложить» на',
'settings.snooze.hint': 'Сколько минут добавлять при отложении',
'settings.snooze.1': '1 минута',
@@ -501,7 +524,7 @@ export const ru: Dict = {
export const en: Dict = {
// Sidebar / nav
'nav.today': 'Today',
'nav.today': 'Overview',
'nav.exercises': 'Exercises',
'nav.meals': 'Meals',
'nav.games': 'Games',
@@ -549,11 +572,34 @@ export const en: Dict = {
'btn.retry': 'Retry',
// Dashboard
'dashboard.kicker': 'Daily training',
'dashboard.title': 'Today',
'dashboard.kicker': 'Break plan',
'dashboard.title': 'What matters now',
'dashboard.header.date': 'Plan for {date}',
'dashboard.header.status.paused': 'paused',
'dashboard.header.status.meeting': 'meeting',
'dashboard.header.status.due': 'action due',
'dashboard.header.status.running': 'running',
'dashboard.header.status.clear': 'clear',
'dashboard.header.title.paused': 'Reminders are paused',
'dashboard.header.subtitle.paused':
'Start them again when you are ready to return to short breaks.',
'dashboard.header.title.meeting': 'Meeting active',
'dashboard.header.subtitle.meeting':
'Meeting pause is enabled. Reminders will continue when the call ends.',
'dashboard.header.title.due': 'Time to do: {name}',
'dashboard.header.subtitle.due':
'{kind} · {meta}. This is the closest action in the plan.',
'dashboard.header.title.next': 'Next: {name}',
'dashboard.header.subtitle.next': '{kind} · {meta} · {time}',
'dashboard.header.title.empty': 'Set up your first break',
'dashboard.header.subtitle.empty':
'Add an exercise or meal so the app can build a clear day plan.',
'dashboard.header.title.clear': 'Plan under control',
'dashboard.header.subtitle.clear':
'No urgent actions. Goals, weekly rhythm and game debts are below.',
'dashboard.stat.active': 'Active',
'dashboard.stat.active.of': 'of {total}',
'dashboard.stat.today_done': 'Today',
'dashboard.stat.today_done': 'Done',
'dashboard.stat.today_done.subtitle': 'reps logged',
'dashboard.stat.streak': 'Streak',
'dashboard.stat.streak.subtitle': '{n} days in a row',
@@ -569,12 +615,12 @@ export const en: Dict = {
'dashboard.stat.tracking.subtitle_off': 'disabled',
'dashboard.stat.tracking.subtitle_pending': 'close & reopen Steam',
'dashboard.paused.title': 'Reminders paused',
'dashboard.meeting.title': "You're in a meeting — won't interrupt",
'dashboard.meeting.title': 'Meeting active',
'dashboard.meeting.hint':
'Zoom / Teams / Discord / Webex / Slack-huddle is running. Reminders resume when you close it.',
'Zoom / Teams / Webex / Slack-huddle is running. Reminders resume when the meeting ends.',
'dashboard.paused.hint': 'Resume to continue countdown',
'dashboard.plan.title': 'Day plan',
'dashboard.plan.subtitle': 'Next action and daily goals',
'dashboard.plan.title': 'Closest step',
'dashboard.plan.subtitle': 'What to do now, daily goals and meals',
'dashboard.plan.due_count': '{n} due',
'dashboard.plan.all_caught_up': 'all clear',
'dashboard.plan.next_action': 'Next action',
@@ -633,7 +679,7 @@ export const en: Dict = {
'momentum.quest.week_reps.desc': 'reach one thousand reps this week',
'momentum.quest.match_debt.title': 'Close matches',
'momentum.quest.match_debt.desc': 'close 3 game debts this week',
'momentum.quest.today_anchor.title': 'Today is not zero',
'momentum.quest.today_anchor.title': 'Non-zero day',
'momentum.quest.today_anchor.desc': 'complete at least one action today',
'momentum.game.kicker': 'After match',
'momentum.game.title': 'Game debt',
@@ -836,7 +882,7 @@ export const en: Dict = {
'Speaks the exercise name and count — useful when your eyes are on the code.',
'settings.meeting_pause.label': 'Pause during meetings',
'settings.meeting_pause.hint':
'Skip reminders when Zoom / Teams / Discord / Webex / Slack-huddle is running.',
'Pause reminders when Zoom / Teams / Webex / Slack-huddle is running.',
'settings.snooze.label': '“Snooze” for',
'settings.snooze.hint': 'How many minutes to postpone',
'settings.snooze.1': '1 minute',

View File

@@ -187,18 +187,39 @@ export default function Dashboard(): JSX.Element {
lang === 'en' ? 'en-US' : 'ru-RU',
{ weekday: 'long', day: 'numeric', month: 'long' }
)
const header = dashboardHeaderCopy({
plan,
paused,
meetingPaused,
hasSetup: exercises.length > 0 || meals.length > 0,
lang,
t
})
return (
<div className="h-full overflow-y-auto">
<div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-12">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-8">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-6">
<div className="min-w-0">
<div className="text-[14px] text-text/65 font-semibold capitalize">
{today}
{t('dashboard.header.date', { date: today })}
</div>
<h1 className="font-serif text-[34px] sm:text-[40px] leading-[1.02] tracking-tight mt-1 font-bold">
{t('dashboard.title')}
</h1>
<div className="mt-2 flex flex-wrap items-center gap-3">
<h1 className="font-serif text-[34px] sm:text-[40px] leading-[1.02] tracking-tight font-bold">
{header.title}
</h1>
<span
className={[
'h-7 px-3 rounded-full inline-flex items-center text-[12px] font-bold uppercase tracking-[0.06em]',
dashboardStatusClass(header.tone)
].join(' ')}
>
{header.status}
</span>
</div>
<p className="text-[15px] text-text/65 mt-2 font-medium leading-relaxed max-w-2xl">
{header.subtitle}
</p>
</div>
<div className="flex items-center gap-2">
<Button variant="tinted" onClick={togglePause}>
@@ -414,6 +435,95 @@ export default function Dashboard(): JSX.Element {
)
}
type DashboardHeaderTone = 'accent' | 'success' | 'warning' | 'info' | 'muted'
function dashboardHeaderCopy({
plan,
paused,
meetingPaused,
hasSetup,
lang,
t
}: {
plan: TodayPlan
paused: boolean
meetingPaused: boolean
hasSetup: boolean
lang: Language
t: TFn
}): {
title: string
subtitle: string
status: string
tone: DashboardHeaderTone
} {
if (paused) {
return {
title: t('dashboard.header.title.paused'),
subtitle: t('dashboard.header.subtitle.paused'),
status: t('dashboard.header.status.paused'),
tone: 'muted'
}
}
if (meetingPaused) {
return {
title: t('dashboard.header.title.meeting'),
subtitle: t('dashboard.header.subtitle.meeting'),
status: t('dashboard.header.status.meeting'),
tone: 'info'
}
}
if (!hasSetup) {
return {
title: t('dashboard.header.title.empty'),
subtitle: t('dashboard.header.subtitle.empty'),
status: t('dashboard.header.status.clear'),
tone: 'warning'
}
}
const nextItem = plan.nextItem
if (nextItem) {
const payload = {
name: nextItem.name,
kind: t(`dashboard.plan.kind.${nextItem.kind}`),
meta: planItemMeta(nextItem, t),
time: planItemTiming(nextItem, false, lang, t)
}
if (nextItem.due) {
return {
title: t('dashboard.header.title.due', payload),
subtitle: t('dashboard.header.subtitle.due', payload),
status: t('dashboard.header.status.due'),
tone: 'accent'
}
}
return {
title: t('dashboard.header.title.next', payload),
subtitle: t('dashboard.header.subtitle.next', payload),
status: t('dashboard.header.status.running'),
tone: 'success'
}
}
return {
title: t('dashboard.header.title.clear'),
subtitle: t('dashboard.header.subtitle.clear'),
status: t('dashboard.header.status.clear'),
tone: 'success'
}
}
function dashboardStatusClass(tone: DashboardHeaderTone): string {
if (tone === 'accent') return 'bg-accent/12 text-accent'
if (tone === 'success') return 'bg-success/12 text-success'
if (tone === 'warning') return 'bg-warning/12 text-warning'
if (tone === 'info') return 'bg-info/12 text-info'
return 'bg-text/10 text-text/55'
}
function MomentumPanel({
momentum,
gamesLive,

View File

@@ -21,6 +21,48 @@ export type ReleaseNoteItem = {
export type ReleaseNotes = Record<Language, ReleaseNoteItem[]>
export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
'0.6.5': {
ru: [
{
title: 'Главный экран стал обзором действий',
detail:
'Верхний заголовок теперь показывает состояние: что сделать сейчас, что ждёт, пауза или встреча.',
tag: 'new'
},
{
title: 'Исправлен запуск с Windows',
detail:
'Проверка автозапуска теперь использует тот же путь и аргументы, что и запись в Windows.',
tag: 'fix'
},
{
title: 'Discord больше не ставит перерывы на паузу',
detail:
'Авто-пауза встреч реагирует на Zoom, Teams, Webex и Slack-huddle, но не на обычный Discord.',
tag: 'fix'
}
],
en: [
{
title: 'The main screen is now an action overview',
detail:
'The header shows the current state: what to do now, what is due, pause or meeting.',
tag: 'new'
},
{
title: 'Fixed Start with Windows',
detail:
'Autostart now reads Windows login items with the same path and arguments it writes.',
tag: 'fix'
},
{
title: 'Discord no longer pauses breaks',
detail:
'Meeting auto-pause still handles Zoom, Teams, Webex and Slack-huddle, but ignores Discord.',
tag: 'fix'
}
]
},
'0.6.4': {
ru: [
{
@@ -193,7 +235,7 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
{
title: 'Видно когда мы молчим из-за ВКС',
detail:
'Запущен Zoom/Teams — на Dashboard баннер «Не дёргаем — ты на встрече».',
'Запущен Zoom/Teams — на Dashboard появляется баннер активной встречи.',
tag: 'new'
},
{
@@ -276,7 +318,7 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
{
title: 'Авто-пауза на ВКС',
detail:
'Не дёргает напоминаниями, если запущен Zoom/Teams/Discord/Webex/Slack-huddle.',
'Ставит напоминания на паузу, если запущен Zoom/Teams/Webex/Slack-huddle.',
tag: 'new'
},
{
@@ -323,7 +365,7 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
{
title: 'Meeting auto-pause',
detail:
'No reminders while Zoom/Teams/Discord/Webex/Slack-huddle is running.',
'Pauses reminders while Zoom/Teams/Webex/Slack-huddle is running.',
tag: 'new'
},
{

View File

@@ -105,7 +105,7 @@ export type Settings = {
voicePromptsEnabled: boolean
/**
* Авто-пауза напоминаний во время ВКС-звонков. Сканирует список процессов
* (Zoom/Teams/Discord/Webex/Slack-huddle/etc) раз в 30 сек, если хоть один
* (Zoom/Teams/Webex/Slack-huddle/etc) раз в 30 сек, если хоть один
* запущен — fires не происходят. Чисто Windows (через tasklist).
*/
meetingAutoPause: boolean