[1.8] PoC Помощника: трей и замеры на Windows (#8)
ci / smoke (push) Successful in 3s

**Задача:** #1.8
**Пункты:** 1.8.1, 1.8.2

## Что сделано
- PoC в poc/helper-tray/: Tauri 2 только с иконкой в трее (окна при старте нет), меню из трёх пунктов, окно создаётся по клику и уничтожается при закрытии.
- Форма «Сообщить о проблеме» по прототипу; «Выход» только в debug-сборке.
- Замер времени открытия — команда first_paint (invoke после двойного rAF); сценарий --measure-scenario + measure.ps1: PrivateBytes и WorkingSetPrivate дерева процессов по отметкам этапов в логе.
- Замеры Windows 11 (release, 5 прогонов, медиана): покой 2,0 МБ PB, окно 155,3 МБ PB (цель 150 — не дотянуто ~5 МБ), после закрытия 5,2 МБ, открытие 580/555 мс. Выводы и методика — docs/research/helper-tray-poc.md.
- AGENTS.md: добавлена временная папка poc/ (удаляется после ADR-0005).

## Как проверить
1. cd poc/helper-tray && pnpm install && pnpm tauri build
2. Запустить src-tauri/target/release/helper-tray.exe — только трей, без окна.
3. powershell -ExecutionPolicy Bypass -File measure.ps1 — 5 прогонов, таблица.
4. На Linux: сборка по docs/research/helper-tray-poc.md, замер через PSS.

## Чек-лист
- [x] Коммиты и название PR по-русски, в каждом коммите есть Refs:
- [x] Ветка свежая: git rebase origin/main, конфликтов нет
- [x] Секретов и персональных данных в коде, логах и документах нет
- [x] Документация обновлена: запись журнала, docs/status/, docs/research/
- [ ] Ссылка на этот PR добавлена в «Ссылки» задачи в дорожной карте
<!-- Прочие пункты шаблона неприменимы: нет запросов к БД, прав, миграций, флагов -->

Reviewed-on: #8
Co-authored-by: BrowenSiz <top.timashevsky@gmail.com>
This commit was merged in pull request #8.
This commit is contained in:
TMSH authored and TMSH committed 2026-11-10 21:42:07 +00:00
1 parent 9547fa7076
commit 22d1698764
42 files changed
+6074 -6

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "helper-tray"
version = "0.1.0"
description = "PoC «Штиль Помощник»: Tauri только с иконкой в трее (#1.8)"
authors = ["T&B.Soft"]
edition = "2024"
[lib]
name = "helper_tray_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["tray-icon"] }
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "helper-windows",
"description": "Окна Помощника, создаваемые динамически из меню трея. Команды приложения не входят в ACL, плагинов нет — разрешений не нужно",
"windows": ["win-*"],
"permissions": []
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

+199
View File
@@ -0,0 +1,199 @@
use std::{
collections::HashMap,
fs::{File, OpenOptions},
io::Write,
sync::Mutex,
time::{Duration, Instant},
};
use tauri::{
AppHandle, Manager, State, WebviewUrl, WebviewWindow, Wry,
menu::{IsMenuItem, Menu, MenuItem},
tray::{TrayIcon, TrayIconBuilder},
webview::WebviewWindowBuilder,
};
struct MeasureLog {
started: Instant,
file: Mutex<Option<File>>,
}
impl MeasureLog {
fn marker(&self, text: &str) {
let line = format!("[{:>7.2}s] {}", self.started.elapsed().as_secs_f64(), text);
if let Some(f) = self.file.lock().unwrap().as_mut() {
let _ = writeln!(f, "{}", line).and_then(|_| f.flush());
}
eprintln!("{}", line);
}
}
struct AppState {
tray: Mutex<Option<TrayIcon>>,
open_started: Mutex<HashMap<String, Instant>>,
window_seq: Mutex<u32>,
last_label: Mutex<Option<String>>,
measure: MeasureLog,
}
#[tauri::command]
fn first_paint(window: WebviewWindow, state: State<'_, AppState>) -> Option<u128> {
let elapsed = state
.open_started
.lock()
.unwrap()
.remove(window.label())
.map(|t| t.elapsed().as_millis());
if let Some(ms) = elapsed {
state
.measure
.marker(&format!("window-opened {} ms={}", window.label(), ms));
}
elapsed
}
fn open_window(app: &AppHandle, view: &str) {
let state = app.state::<AppState>();
let label = {
let mut seq = state.window_seq.lock().unwrap();
*seq += 1;
format!("win-{}-{}", view, *seq)
};
let title = match view {
"report" => "Сообщить о проблеме",
"tickets" => "Мои обращения",
_ => "О программе",
};
let started = Instant::now();
match WebviewWindowBuilder::new(app, &label, WebviewUrl::App("index.html".into()))
.title(title)
.inner_size(460.0, 560.0)
.build()
{
Ok(_) => {
state
.open_started
.lock()
.unwrap()
.insert(label.clone(), started);
*state.last_label.lock().unwrap() = Some(label);
}
Err(e) => state
.measure
.marker(&format!("open-failed {}: {}", label, e)),
}
}
fn close_last_window(app: &AppHandle) {
let label = app.state::<AppState>().last_label.lock().unwrap().take();
if let Some(label) = label
&& let Some(window) = app.get_webview_window(&label)
{
let _ = window.destroy();
}
}
fn build_tray(app: &AppHandle) -> tauri::Result<TrayIcon> {
let report = MenuItem::with_id(app, "report", "Сообщить о проблеме", true, None::<&str>)?;
let tickets = MenuItem::with_id(app, "tickets", "Мои обращения", true, None::<&str>)?;
let about = MenuItem::with_id(app, "about", "О программе", true, None::<&str>)?;
// Выход только в debug-сборке: в релизном Помощнике пункта «Выход» не будет.
let quit = MenuItem::with_id(app, "quit", "Выход (debug)", true, None::<&str>)?;
let items: Vec<&dyn IsMenuItem<Wry>> = if cfg!(debug_assertions) {
vec![&report, &tickets, &about, &quit]
} else {
vec![&report, &tickets, &about]
};
let menu = Menu::with_items(app, &items)?;
TrayIconBuilder::new()
.icon(app.default_window_icon().unwrap().clone())
.tooltip("Штиль Помощник (PoC)")
.menu(&menu)
.on_menu_event(|app, event| match event.id().as_ref() {
"quit" => app.exit(0),
view @ ("report" | "tickets" | "about") => open_window(app, view),
_ => {}
})
.build(app)
}
// Отметка этапа пишется заранее, чтобы measure.ps1 успел снять ОЗУ до действия:
// два CIM-запроса в скрипте занимают ~0,5 с, поэтому запас делаем больше.
fn stage_then(app: &AppHandle, name: &str, action: impl Fn(&AppHandle) + Send + 'static) {
app.state::<AppState>().measure.marker(name);
std::thread::sleep(Duration::from_millis(1500));
let app2 = app.clone();
let _ = app.run_on_main_thread(move || action(&app2));
}
fn spawn_measure_scenario(app: AppHandle) {
std::thread::spawn(move || {
let sleep = |secs: u64| std::thread::sleep(Duration::from_secs(secs));
sleep(30);
stage_then(&app, "stage open-window-1", |a| open_window(a, "report"));
sleep(10);
stage_then(&app, "stage close-window-1", close_last_window);
sleep(10);
stage_then(&app, "stage open-window-2", |a| open_window(a, "report"));
sleep(10);
stage_then(&app, "stage close-window-2", close_last_window);
app.state::<AppState>().measure.marker("stage done");
app.exit(0);
});
}
fn measure_log_file() -> Option<File> {
let exe_dir = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.to_path_buf()));
for dir in [exe_dir, Some(std::env::temp_dir())].into_iter().flatten() {
match OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(dir.join("helper-tray-poc.measure.log"))
{
Ok(f) => return Some(f),
Err(e) => eprintln!("не удалось открыть лог в {}: {}", dir.display(), e),
}
}
None
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let measure = std::env::args().any(|a| a == "--measure-scenario");
let app = tauri::Builder::default()
.invoke_handler(tauri::generate_handler![first_paint])
.setup(move |app| {
app.manage(AppState {
tray: Mutex::new(None),
open_started: Mutex::new(HashMap::new()),
window_seq: Mutex::new(0),
last_label: Mutex::new(None),
measure: MeasureLog {
started: Instant::now(),
file: Mutex::new(if measure { measure_log_file() } else { None }),
},
});
let tray = build_tray(app.handle())?;
*app.state::<AppState>().tray.lock().unwrap() = Some(tray);
if measure {
app.state::<AppState>().measure.marker("stage app-started");
spawn_measure_scenario(app.handle().clone());
}
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building tauri application");
// Трею нельзя завершаться при закрытии последнего окна (code == None);
// при программном выходе code задан — prevent_exit не вызываем,
// иначе app.exit(0) был бы заблокирован.
app.run(|_handle, event| {
if let tauri::RunEvent::ExitRequested { code, api, .. } = event
&& code.is_none()
{
api.prevent_exit();
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
helper_tray_lib::run()
}
+29
View File
@@ -0,0 +1,29 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "shtil-helper-poc",
"version": "0.1.0",
"identifier": "ru.tbsoft.shtil.helper.poc",
"build": {
"beforeDevCommand": "pnpm dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "pnpm build",
"frontendDist": "../dist"
},
"app": {
"windows": [],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost"
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}