From af99ec8b99e2c99e4e679791d1492c584634fc06 Mon Sep 17 00:00:00 2001 From: hayxel Date: Wed, 11 Nov 2026 11:58:29 +0300 Subject: [PATCH 1/6] fix!: keep history navigation on the recorded process instance BREAKING CHANGE: New daily history files use version 3 to retain process creation times. Version 2 files remain readable and continue in their original format for the current day. Older builds cannot read version 3 recordings. Back up history before downgrading. --- crates/argus-core/src/history.rs | 126 ++++++++++++-- docs/guide/README.md | 4 +- locales/de-DE/history.json | 3 +- locales/en-US/history.json | 3 +- locales/es-ES/history.json | 3 +- locales/fr-FR/history.json | 3 +- locales/ja-JP/history.json | 3 +- locales/ru-RU/history.json | 3 +- locales/zh-CN/history.json | 3 +- locales/zh-TW/history.json | 3 +- src-gpui/src/frontend/pages.rs | 7 + src-gpui/src/frontend/pages/history.rs | 79 +++++++-- .../fixtures/history-instances.mjs | 21 +++ .../window-probe/steps/history-instances.json | 162 ++++++++++++++++++ 14 files changed, 390 insertions(+), 33 deletions(-) create mode 100644 tools/window-probe/fixtures/history-instances.mjs create mode 100644 tools/window-probe/steps/history-instances.json diff --git a/crates/argus-core/src/history.rs b/crates/argus-core/src/history.rs index 78937fab..00221794 100644 --- a/crates/argus-core/src/history.rs +++ b/crates/argus-core/src/history.rs @@ -15,7 +15,9 @@ //! u64, memory total u64, disk u64 (B/s), network u64 (B/s), battery f32 //! (percent, -1 when absent), battery rate f32 (mW, NaN when unknown), //! entry count u8, then per entry: name u16, PID u32, CPU f32, memory u32 -//! (KiB), I/O u32 (B/s), GPU f32, network u32 (B/s). +//! (KiB), I/O u32 (B/s), GPU f32, network u32 (B/s), creation time i64 +//! (Unix ms, v3 only; nonpositive means unknown). V2 files remain readable +//! and are appended in their original format until the next day. use std::collections::HashMap; use std::ffi::OsStr; @@ -34,11 +36,13 @@ pub const FRAME_MS: i64 = 5_000; /// Days of history kept. pub const KEEP_DAYS: i64 = 7; -const MAGIC: &[u8; 5] = b"ARGH\x02"; +const MAGIC: &[u8; 5] = b"ARGH\x03"; +const LEGACY_MAGIC: &[u8; 5] = b"ARGH\x02"; const TAG_NAME: u8 = 1; const TAG_FRAME: u8 = 2; const FRAME_HEAD: usize = 8 + 4 * 3 + 8 * 4 + 4 * 2 + 1; const ENTRY: usize = 2 + 4 + 4 + 4 + 4 + 4 + 4; +const ENTRY_V3: usize = ENTRY + 8; const DAY_MS: i64 = 86_400_000; /// System totals for one frame (or one chart bucket). @@ -72,8 +76,11 @@ pub struct HistoryPoint { pub struct HistoryProcess { pub name: String, pub pid: u32, - /// Averages over the frame. + /// None in legacy history or when the instance could not be identified. + pub create_time: Option, + /// CPU, I/O, GPU and network are averages over the frame. pub cpu: f32, + /// Maximum private working set in the frame, bytes. pub mem: u64, pub io: u64, pub gpu: f32, @@ -106,6 +113,7 @@ struct ProcAcc { missing: u32, name: Arc, pid: u32, + create_time: i64, cpu: f64, mem: u64, io: f64, @@ -141,6 +149,7 @@ struct DayFile { day: i64, out: BufWriter, names: HashMap, u16>, + legacy: bool, } pub struct HistoryRecorder { @@ -236,6 +245,9 @@ impl HistoryRecorder { pid: p.pid, ..Default::default() }); + if p.create_time > 0 { + acc.create_time = p.create_time; + } if p.stale || p.sample_reused || p.counters_pending { acc.missing += 1; continue; @@ -320,6 +332,9 @@ impl HistoryRecorder { buf.extend_from_slice(&clamp(p.io / process_n).to_le_bytes()); buf.extend_from_slice(&((p.gpu / process_n) as f32).to_le_bytes()); buf.extend_from_slice(&clamp(p.net / process_n).to_le_bytes()); + if !file.legacy { + buf.extend_from_slice(&p.create_time.to_le_bytes()); + } } // One write and flush per frame, so readers and crashes see whole frames. file.out.write_all(&buf)?; @@ -386,6 +401,7 @@ fn open_day(dir: &Path, day: i64) -> io::Result { let path = day_path(dir, day); let mut names = HashMap::new(); let mut valid = 0u64; + let mut legacy = false; // Only a missing file starts empty: truncating after a transient read // failure would erase the day recorded so far. let existing = match fs::read(&path) { @@ -394,8 +410,9 @@ fn open_day(dir: &Path, day: i64) -> io::Result { Err(e) => return Err(e), }; if let Some(bytes) = existing - && bytes.starts_with(MAGIC) + && (bytes.starts_with(MAGIC) || bytes.starts_with(LEGACY_MAGIC)) { + legacy = bytes.starts_with(LEGACY_MAGIC); let mut table = Vec::new(); valid = parse(&bytes, &mut table, |_, _, _| true) as u64; for (i, name) in table.into_iter().enumerate() { @@ -415,7 +432,12 @@ fn open_day(dir: &Path, day: i64) -> io::Result { out.write_all(MAGIC)?; out.flush()?; } - Ok(DayFile { day, out, names }) + Ok(DayFile { + day, + out, + names, + legacy, + }) } /// Deletes day files older than the retention window. @@ -468,6 +490,11 @@ fn parse( names: &mut Vec, mut frame: impl FnMut(&HistoryPoint, &[u8], &[String]) -> bool, ) -> usize { + let entry_size = if bytes.starts_with(LEGACY_MAGIC) { + ENTRY + } else { + ENTRY_V3 + }; let mut at = MAGIC.len(); let mut valid = at; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[i], b[i + 1]]); @@ -515,13 +542,13 @@ fn parse( }, }; let count = b[60] as usize; - let end = at + 1 + FRAME_HEAD + count * ENTRY; + let end = at + 1 + FRAME_HEAD + count * entry_size; if end > bytes.len() { break; } at = end; valid = at; - if !frame(&point, &bytes[end - count * ENTRY..end], names) { + if !frame(&point, &bytes[end - count * entry_size..end], names) { return valid; } continue; @@ -533,10 +560,8 @@ fn parse( valid } -fn entries(raw: &[u8], names: &[String]) -> Vec { - raw.as_chunks::() - .0 - .iter() +fn entries(raw: &[u8], names: &[String], legacy: bool) -> Vec { + raw.chunks_exact(if legacy { ENTRY } else { ENTRY_V3 }) .map(|e| { let u32_at = |i: usize| u32::from_le_bytes(e[i..i + 4].try_into().unwrap()); let f32_at = |i: usize| f32::from_le_bytes(e[i..i + 4].try_into().unwrap()); @@ -544,6 +569,12 @@ fn entries(raw: &[u8], names: &[String]) -> Vec { HistoryProcess { name: names.get(name).cloned().unwrap_or_default(), pid: u32_at(2), + create_time: if legacy { + None + } else { + let created = i64::from_le_bytes(e[ENTRY..ENTRY_V3].try_into().unwrap()); + (created > 0).then_some(created) + }, cpu: f32_at(6), mem: u32_at(10) as u64 * 1024, io: u32_at(14) as u64, @@ -575,7 +606,7 @@ fn read_day(dir: &Path, day: i64) -> Option> { } }) .ok()?; - bytes.starts_with(MAGIC).then_some(bytes) + (bytes.starts_with(MAGIC) || bytes.starts_with(LEGACY_MAGIC)).then_some(bytes) } /// Unix ms of the oldest frame. @@ -731,7 +762,7 @@ pub fn moment(dir: &Path, ts: i64) -> Option { dist, HistoryMoment { system: p.clone(), - processes: entries(raw, names), + processes: entries(raw, names, bytes.starts_with(LEGACY_MAGIC)), }, )); } @@ -847,6 +878,67 @@ mod tests { } } + #[test] + fn keeps_legacy_frames_and_appends_without_inventing_identity() { + let dir = temp_dir("legacy-identity"); + let base = 20_737 * DAY_MS; + fs::create_dir_all(&dir).unwrap(); + let mut bytes = LEGACY_MAGIC.to_vec(); + bytes.extend_from_slice(&[TAG_NAME, 0, 0, 10]); + bytes.extend_from_slice(b"worker.exe"); + bytes.push(TAG_FRAME); + let mut head = vec![0u8; FRAME_HEAD]; + head[..8].copy_from_slice(&base.to_le_bytes()); + head[60] = 1; + bytes.extend_from_slice(&head); + let mut entry = vec![0u8; ENTRY]; + entry[2..6].copy_from_slice(&42u32.to_le_bytes()); + bytes.extend_from_slice(&entry); + let path = day_path(&dir, 20_737); + fs::write(&path, &bytes).unwrap(); + let old = moment(&dir, base).unwrap(); + assert_eq!(old.processes[0].create_time, None); + let mut rec = HistoryRecorder::new(dir.clone()); + rec.record(&snapshot( + base + FRAME_MS, + 1., + vec![proc(42, "worker.exe", 1., 1024)], + )); + rec.record(&snapshot(base + 2 * FRAME_MS, 1., Vec::new())); + drop(rec); + assert!(fs::read(&path).unwrap().starts_with(&bytes)); + assert_eq!( + moment(&dir, base + FRAME_MS).unwrap().processes[0].create_time, + None + ); + assert_eq!(series(&dir, base, base + 2 * FRAME_MS, 10).len(), 2); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn persists_separate_instances_and_resolved_creation_time() { + let dir = temp_dir("instances"); + let base = 20_737 * DAY_MS; + let mut rec = HistoryRecorder::new(dir.clone()); + let mut first = proc(42, "worker.exe", 20., 1024); + first.create_time = base - 1000; + let mut second = first.clone(); + second.create_time = base + 1000; + rec.record(&snapshot(base, 20., vec![first])); + rec.record(&snapshot(base + 1000, 20., vec![second])); + rec.record(&snapshot(base + FRAME_MS, 1., Vec::new())); + drop(rec); + let frame = moment(&dir, base).unwrap(); + let mut created = frame + .processes + .iter() + .map(|p| p.create_time) + .collect::>(); + created.sort(); + assert_eq!(created, vec![Some(base - 1000), Some(base + 1000)]); + fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn records_battery_level_and_rate() { let dir = temp_dir("battery"); @@ -932,6 +1024,14 @@ mod tests { let data = moment(&dir, base + 1000).unwrap(); assert_eq!(data.processes.iter().find(|p| p.pid == 1).unwrap().cpu, 20.); assert_eq!(data.processes.iter().find(|p| p.pid == 2).unwrap().cpu, 40.); + assert_eq!( + data.processes + .iter() + .find(|p| p.pid == 2) + .unwrap() + .create_time, + Some(123) + ); let _ = fs::remove_dir_all(dir); } diff --git a/docs/guide/README.md b/docs/guide/README.md index 1bee2766..b8a01a06 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -188,11 +188,11 @@ Argus 运行时每 5 秒记录一帧:整机的 CPU(这 5 秒内各次采样 - **查看某一时刻**:指针移到曲线上,左侧显示那一刻的数值;单击选中这一时刻,下方列出当时最忙的进程。选中后在曲线上按 ← →(加 Shift 一次移动更多)前后移动,按 Esc 或工具栏上的“回到最新”取消选中。选中时刻后图表仍随时间前移,该时刻移出图表时自动取消选中。 - **切换范围**:切换后总是显示新范围截至当前的时间段。选中的时刻仍在新范围内时保持选中,下方的进程列表不变;否则取消选中,读数与进程列表回到最新数据。查看更早的时段需选择更长的范围。 - **电池数据缺失**:设备暂未上报电池电量的时段,电池曲线留空,读数显示“无记录”;实际电量为 0% 时仍显示为 0%。 -- **转到进程**:双击列表中的进程,如果它仍在运行,就转到进程页并选中它。 +- **转到进程**:双击列表中的进程,仅在 PID、名称和记录的创建时间与当前运行实例一致时转到进程页;执行跳转时再次核对。旧记录没有创建时间时保留历史读数,不提供跳转。创建时间可以位于该帧的 5 秒记录窗口内,不能晚于该窗口。 每进程网络流量会在本地采集或特权服务采集可用时记录。记录保存在 `%LOCALAPPDATA%\dev.argus.taskmanager\history`,每天一个文件,保留 7 天,连续运行一天约 8 MB。在“设置 → 数据与历史”里可以关闭记录、查看占用的空间或清除全部历史,见[设置](settings.md#数据与历史)。 -从 0.2.0 升级且需要保留旧历史时,请先退出 Argus 并备份 `history` 目录,旧版可读取备份。新版从新的记录格式开始显示历史。 +当前读取 v2 和 v3 历史。新建的 v3 文件保存进程创建时间;已有的当天 v2 文件继续按原格式追加,到下一天才创建 v3 文件,不覆盖旧记录。v2 记录的进程创建时间未知。更早的格式仍需用对应旧版读取备份。 ## 文件占用 diff --git a/locales/de-DE/history.json b/locales/de-DE/history.json index a488f75c..0bf504d4 100644 --- a/locales/de-DE/history.json +++ b/locales/de-DE/history.json @@ -43,5 +43,6 @@ "noRecordAt": "Keine Aufzeichnung für diesen Zeitpunkt", "earliest": "Frühester Datensatz", "note": "Zeichnet alle 5 Sekunden die Prozesse mit der höchsten CPU-, Arbeitsspeicher-, I/O-, GPU- und Netzwerkauslastung auf. Bei längerem Intervall im minimierten Zustand oder im Infobereich gilt dieses Intervall. Die Daten bleiben 7 Tage erhalten.", - "off": "Die Verlaufsaufzeichnung ist deaktiviert; neue Daten werden nicht aufgezeichnet. Einstellungen öffnen" + "off": "Die Verlaufsaufzeichnung ist deaktiviert; neue Daten werden nicht aufgezeichnet. Einstellungen öffnen", + "instanceUnavailable": "Die aufgezeichnete Instanz von {name} (PID {pid}) wurde beendet oder ihre Identität kann nicht bestätigt werden." } diff --git a/locales/en-US/history.json b/locales/en-US/history.json index 07ca2574..642b81d3 100644 --- a/locales/en-US/history.json +++ b/locales/en-US/history.json @@ -43,5 +43,6 @@ "noRecordAt": "No records at this moment", "earliest": "Earliest record", "note": "Records the top processes by CPU, memory, I/O, GPU and network every 5 seconds (or at the minimized or tray refresh rate when that is slower) and keeps them for 7 days.", - "off": "History recording is off; no new data is being recorded. Open Settings" + "off": "History recording is off; no new data is being recorded. Open Settings", + "instanceUnavailable": "The recorded instance of {name} (PID {pid}) has exited or its identity cannot be confirmed." } diff --git a/locales/es-ES/history.json b/locales/es-ES/history.json index 865d6c60..fc95a925 100644 --- a/locales/es-ES/history.json +++ b/locales/es-ES/history.json @@ -45,5 +45,6 @@ "noRecordAt": "No hay registros en este momento", "earliest": "Registro más antiguo", "note": "Registra cada 5 segundos los procesos con mayor uso de CPU, memoria, I/O, GPU y red; si el intervalo al minimizar o permanecer en la bandeja es mayor, utiliza ese intervalo. Conserva los registros durante 7 días.", - "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración" + "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración", + "instanceUnavailable": "La instancia registrada de {name} (PID {pid}) ha finalizado o no se puede confirmar su identidad." } diff --git a/locales/fr-FR/history.json b/locales/fr-FR/history.json index 486dd002..67b2f803 100644 --- a/locales/fr-FR/history.json +++ b/locales/fr-FR/history.json @@ -45,5 +45,6 @@ "noRecordAt": "Aucun enregistrement à cet instant", "earliest": "Premier enregistrement", "note": "Enregistre les processus utilisant le plus de CPU, mémoire, I/O, GPU et réseau toutes les 5 secondes, ou selon l’intervalle de la fenêtre réduite ou de la zone de notification s’il est plus long. Les données sont conservées 7 jours.", - "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres" + "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres", + "instanceUnavailable": "L’instance enregistrée de {name} (PID {pid}) est terminée ou son identité ne peut pas être confirmée." } diff --git a/locales/ja-JP/history.json b/locales/ja-JP/history.json index bc02fec5..2324a7ec 100644 --- a/locales/ja-JP/history.json +++ b/locales/ja-JP/history.json @@ -41,5 +41,6 @@ "noRecordAt": "この時刻の記録はありません", "earliest": "最も古い記録", "note": "CPU、メモリ、I/O、GPU、ネットワークの使用量が多いプロセスを 5 秒ごとに記録し、7 日間保存します。最小化中や通知領域への常駐中の更新間隔が長い場合は、その間隔で記録します。", - "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く" + "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く", + "instanceUnavailable": "記録された {name}(PID {pid})のインスタンスは終了したか、同一性を確認できません。" } diff --git a/locales/ru-RU/history.json b/locales/ru-RU/history.json index 376ba8f6..30403574 100644 --- a/locales/ru-RU/history.json +++ b/locales/ru-RU/history.json @@ -47,5 +47,6 @@ "noRecordAt": "Для этого момента нет записи", "earliest": "Самая ранняя запись", "note": "Записывает процессы с наибольшей нагрузкой на CPU, память, I/O, GPU и сеть каждые 5 секунд. Если интервал для свёрнутого окна или области уведомлений больше, используется он. Записи хранятся 7 дней.", - "off": "Запись истории отключена; новые данные не записываются. Открыть параметры" + "off": "Запись истории отключена; новые данные не записываются. Открыть параметры", + "instanceUnavailable": "Записанный запуск {name} (PID {pid}) завершён или его идентичность не подтверждена." } diff --git a/locales/zh-CN/history.json b/locales/zh-CN/history.json index 68b0ad9b..60eec959 100644 --- a/locales/zh-CN/history.json +++ b/locales/zh-CN/history.json @@ -37,5 +37,6 @@ "noRecordAt": "该时刻无记录", "earliest": "最早的记录", "note": "每 5 秒记录 CPU、内存、I/O、GPU 和网络占用最高的进程(最小化或后台常驻时的刷新间隔更长时按该间隔),保留 7 天。", - "off": "历史记录已关闭,不再记录新的数据。打开设置" + "off": "历史记录已关闭,不再记录新的数据。打开设置", + "instanceUnavailable": "进程 {name}(PID {pid})的记录实例已结束,或无法确认其身份。" } diff --git a/locales/zh-TW/history.json b/locales/zh-TW/history.json index 106a0cb4..fa4a4882 100644 --- a/locales/zh-TW/history.json +++ b/locales/zh-TW/history.json @@ -37,5 +37,6 @@ "noRecordAt": "該時刻無記錄", "earliest": "最早的記錄", "note": "每 5 秒記錄 CPU、記憶體、I/O、GPU 和網路佔用最高的處理程序(最小化或背景常駐時的重新整理間隔更長時依該間隔),保留 7 天。", - "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定" + "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定", + "instanceUnavailable": "處理程序 {name}(PID {pid})的記錄執行個體已結束,或無法確認其身分。" } diff --git a/src-gpui/src/frontend/pages.rs b/src-gpui/src/frontend/pages.rs index da2bc83b..a8c0c399 100644 --- a/src-gpui/src/frontend/pages.rs +++ b/src-gpui/src/frontend/pages.rs @@ -516,6 +516,13 @@ impl Desktop { p["pid"] == value["pid"] && (value["createTime"].is_null() || p["createTime"] == value["createTime"]) + && (value["historyFrame"].is_null() + || history::recorded_target( + &value, + value["historyFrame"].as_i64(), + std::slice::from_ref(*p), + ) + .is_some()) }) .cloned(); if let Some(process) = found { diff --git a/src-gpui/src/frontend/pages/history.rs b/src-gpui/src/frontend/pages/history.rs index 2e7b7e48..3dc2cf7b 100644 --- a/src-gpui/src/frontend/pages/history.rs +++ b/src-gpui/src/frontend/pages/history.rs @@ -24,6 +24,27 @@ const AXIS: f32 = 22.; const BORDER: f32 = 1.; const TABLE_ROW: f32 = 28.; +/// Old frames have no creation time: a matching PID and name cannot establish +/// identity, even if the live process is older than the frame. A process may +/// start inside the five-second frame, but never after it. +pub(super) fn recorded_target(row: &Value, frame: Option, live: &[Value]) -> Option { + let created = row["createTime"].as_i64().filter(|time| *time > 0)?; + let end = frame?.checked_add(argus_core::history::FRAME_MS)?; + if created >= end { + return None; + } + live.iter() + .find(|process| { + process["pid"] == row["pid"] + && process["createTime"].as_i64() == Some(created) + && text(process, "name") == text(row, "name") + }) + .map(|process| { + json!({"pid": process["pid"], "createTime": created, + "name": process["name"], "historyFrame": frame}) + }) +} + pub(super) fn range_label(id: &str) -> String { let hours = RANGES .iter() @@ -893,7 +914,13 @@ impl Desktop { .data .get("historyRange") .and_then(|range| range[0].as_i64()); - let table = self.history_table(values(&moment["processes"]), bits, window, cx); + let table = self.history_table( + values(&moment["processes"]), + moment["system"]["ts"].as_i64(), + bits, + window, + cx, + ); let foot = div() .flex() .flex_wrap() @@ -1008,6 +1035,7 @@ impl Desktop { fn history_table( &self, processes: &[Value], + frame: Option, bits: bool, window: &mut Window, cx: &mut Context, @@ -1161,15 +1189,12 @@ impl Desktop { for (index, row) in rows.iter().enumerate() { let name = text(row, "name").to_owned(); let pid = row["pid"].clone(); - let key = format!("{name}:{pid}"); + let key = format!("{name}:{pid}:{}", row["createTime"]); let current = selected_key.as_deref() == Some(key.as_str()); - // A reused PID is not the recorded process: the name must match too. - let running = live - .iter() - .find(|process| process["pid"] == pid) - .is_some_and(|process| text(process, "name") == name); - let reveal = Action::Preference("revealProcess".into(), json!({"pid": pid})); - let exited = tr!("history.exited", name = name, pid = pid); + let target = recorded_target(row, frame, live); + let running = target.is_some(); + let reveal = Action::Preference("revealProcess".into(), target.unwrap_or(Value::Null)); + let exited = tr!("history.instanceUnavailable", name = name, pid = pid); let menu = vec![ MenuItem::new(label("common.goToProcess"), reveal.clone()).disabled(!running), MenuItem::new( @@ -1269,12 +1294,46 @@ impl Desktop { #[cfg(test)] mod tests { use super::{ - DAY, HOUR, MINUTE, joins, kept, plan_load, point_at, refresh_every, span_of, stepped, + DAY, HOUR, MINUTE, joins, kept, plan_load, point_at, recorded_target, refresh_every, + span_of, stepped, }; use serde_json::{Value, json}; const NOW: i64 = 1_800_000_000_000; + #[test] + fn history_navigation_requires_the_recorded_instance() { + let recorded = json!({"pid":42,"name":"worker.exe","createTime":NOW - 1000}); + let live = vec![recorded.clone()]; + let target = recorded_target(&recorded, Some(NOW), &live).unwrap(); + assert_eq!(target["createTime"], NOW - 1000); + assert!(recorded_target(&target, Some(NOW), &live).is_some()); + let mut replacement = recorded.clone(); + replacement["createTime"] = json!(NOW + 60_000); + assert!(recorded_target(&recorded, Some(NOW), &[replacement.clone()]).is_none()); + assert!( + recorded_target(&replacement, Some(NOW), std::slice::from_ref(&replacement)).is_none() + ); + let legacy = json!({"pid":42,"name":"worker.exe"}); + assert!(recorded_target(&legacy, Some(NOW), &live).is_none()); + assert!(recorded_target(&recorded, Some(NOW), &[]).is_none()); + let mut renamed = recorded.clone(); + renamed["name"] = json!("other.exe"); + assert!(recorded_target(&recorded, Some(NOW), &[renamed]).is_none()); + for unknown in [Value::Null, json!(0), json!(-1)] { + let mut pending = recorded.clone(); + pending["createTime"] = unknown; + assert!(recorded_target(&pending, Some(NOW), &live).is_none()); + } + // The timestamp is the frame's start, not the last sample's time. + let mut inside = recorded; + inside["createTime"] = json!(NOW + 4999); + assert!(recorded_target(&inside, Some(NOW), &[inside.clone()]).is_some()); + inside["createTime"] = json!(NOW + 5000); + assert!(recorded_target(&inside, Some(NOW), &[inside.clone()]).is_none()); + assert!(recorded_target(&inside, None, &live).is_none()); + } + /// The last query sent, as `load_history` stores it. fn sent(range: &str, at: i64) -> Value { json!({"range": range, "buckets": 600, "to": at, "at": at}) diff --git a/tools/window-probe/fixtures/history-instances.mjs b/tools/window-probe/fixtures/history-instances.mjs new file mode 100644 index 00000000..2ef052c6 --- /dev/null +++ b/tools/window-probe/fixtures/history-instances.mjs @@ -0,0 +1,21 @@ +// Generate synthetic history/live identities; never select a real process. +// Run from the repository root, then use steps/history-instances.json with +// --fixture target/history-instances.json. +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; + +const fixture = JSON.parse(readFileSync(new URL("desktop.json", import.meta.url), "utf8")); +const ts = fixture.historyMoment.system.ts; +const process = fixture.snapshot.processes[0]; +const live = (pid, name, created) => ({ ...process, pid, ppid: 0, name, description: name, + createTime: created, instanceKey: undefined, sequenceNumber: undefined, appWindow: true }); +fixture.snapshot.processes = [live(44101, "restarted-worker.exe", ts + 60000), + live(44102, "new-name.exe", ts + 60000), live(44103, "confirmed-worker.exe", ts + 1000)]; +fixture.snapshot.timestamp = ts + 120000; +fixture.snapshot.system.processCount = 3; +fixture.historyMoment.processes = [ + { pid: 44101, name: "restarted-worker.exe", cpu: 85, mem: 1048576, io: 0, gpu: 0, net: 0 }, + { pid: 44102, name: "old-name.exe", cpu: 1, mem: 1048576, io: 0, gpu: 0, net: 0 }, + { pid: 44103, name: "confirmed-worker.exe", createTime: ts + 1000, cpu: 0.5, mem: 1048576, io: 0, gpu: 0, net: 0 }, +]; +mkdirSync("target", { recursive: true }); +writeFileSync("target/history-instances.json", JSON.stringify(fixture)); diff --git a/tools/window-probe/steps/history-instances.json b/tools/window-probe/steps/history-instances.json new file mode 100644 index 00000000..d78d0849 --- /dev/null +++ b/tools/window-probe/steps/history-instances.json @@ -0,0 +1,162 @@ +{ + "window": [ + 1200, + 800 + ], + "steps": [ + { + "control": { + "page": "history", + "pointerOutside": true + }, + "wait": 800, + "inspect": "layout", + "label": "history", + "expect": { + "page": "history" + }, + "capture": "history" + }, + { + "control": { + "mouse": { + "type": "down", + "button": "right", + "x": 283, + "y": 666 + } + }, + "wait": 300, + "inspect": "menu", + "label": "renamed", + "expect": { + "state.open": true, + "state.disabled.0": true + } + }, + { + "control": { + "keys": [ + "escape" + ] + }, + "wait": 300 + }, + { + "control": { + "mouse": { + "type": "down", + "button": "right", + "x": 283, + "y": 635 + } + }, + "wait": 300, + "inspect": "menu", + "label": "legacy-reused", + "expect": { + "state.open": true, + "state.disabled.0": true + } + }, + { + "control": { + "keys": [ + "home", + "enter" + ] + }, + "wait": 300 + }, + { + "inspect": "layout", + "label": "still-history", + "expect": { + "page": "history" + }, + "capture": "blocked" + }, + { + "control": { + "keys": [ + "escape" + ] + }, + "wait": 300 + }, + { + "control": { + "mouse": { + "type": "down", + "button": "right", + "x": 283, + "y": 691 + } + }, + "wait": 300, + "inspect": "menu", + "label": "confirmed", + "expect": { + "state.open": true, + "state.disabled.0": false + } + }, + { + "control": { + "keys": [ + "home", + "enter" + ] + }, + "wait": 500, + "inspect": "layout", + "label": "same-instance", + "expect": { + "page": "processes" + }, + "capture": "confirmed" + }, + { + "control": { + "page": "history" + }, + "wait": 500 + }, + { + "control": { + "preference": { + "revealProcess": { + "pid": 44103, + "name": "confirmed-worker.exe", + "createTime": 1792731860999, + "historyFrame": 1792731860000 + } + } + }, + "wait": 300, + "inspect": "layout", + "label": "recheck-replaced", + "expect": { + "page": "history" + } + }, + { + "control": { + "preference": { + "revealProcess": { + "pid": 44104, + "name": "gone.exe", + "createTime": 1792731859000, + "historyFrame": 1792731860000 + } + } + }, + "wait": 300, + "inspect": "layout", + "label": "recheck-exited", + "expect": { + "page": "history" + } + } + ] +} \ No newline at end of file From ddae8a3e57dec1f2cd5d5cfd12a3811665b2aab2 Mon Sep 17 00:00:00 2001 From: hayxel Date: Wed, 11 Nov 2026 12:13:44 +0300 Subject: [PATCH 2/6] fix: open actual history frames for CPU peaks and chart buckets --- crates/argus-core/AGENTS.md | 2 +- crates/argus-core/src/history.rs | 69 ++++++++++++ docs/guide/README.md | 3 +- locales/de-DE/history.json | 7 +- locales/en-US/history.json | 7 +- locales/es-ES/history.json | 7 +- locales/fr-FR/history.json | 7 +- locales/ja-JP/history.json | 7 +- locales/ru-RU/history.json | 7 +- locales/zh-CN/history.json | 7 +- locales/zh-TW/history.json | 7 +- src-gpui/src/frontend/backend.rs | 3 +- src-gpui/src/frontend/pages.rs | 11 ++ src-gpui/src/frontend/pages/history.rs | 105 ++++++++++++++++++- src-gpui/src/frontend/test_control.rs | 1 + tools/window-probe/fixtures/history-peak.mjs | 21 ++++ 16 files changed, 247 insertions(+), 24 deletions(-) create mode 100644 tools/window-probe/fixtures/history-peak.mjs diff --git a/crates/argus-core/AGENTS.md b/crates/argus-core/AGENTS.md index ae298660..566bbccc 100644 --- a/crates/argus-core/AGENTS.md +++ b/crates/argus-core/AGENTS.md @@ -19,4 +19,4 @@ - `process.rs` 给每个运行中的进程实例缓存一个 `PROCESS_QUERY_LIMITED_INFORMATION` 句柄(读效率模式用),快照线程数归零时立即关闭,进程消失时随条目关闭;零线程记录不得建立缓存句柄,最终 CPU 与 I/O 计数仍从快照读取。不要改成每次采样重新打开。 - 规则引擎(`rules.rs`)由 `argus-service::RuleRunner` 的独立宿主线程驱动;采样线程只提交最新的 PID、启动时间和名称,不要让服务 RPC 阻塞采样。规则保存或执行权限来源变化时重新检查并重新计数;同一轮里一个进程实例只套用一次,传输失败不自动重放。 - 修改采集行为时用相关示例核对结果(命令见 `docs/development/README.md` 的“验证采集数据”);修改 `history.rs` 的录制、编码或写入路径时,用 `--example history --release -- <秒数>` 看录制开销和每帧大小。 -- 改动历史文件的格式(`history.rs`)时要升 `MAGIC` 里的版本号:读取侧跳过版本不符的文件,写入侧会重建当天的文件。 +- 改动历史文件的格式(`history.rs`)时要升 `MAGIC` 里的版本号并核对兼容读写。当前新建文件使用 v3,已有当天 v2 文件按原格式续写,读取支持 v2/v3;旧记录没有的创建时间保持未知。不要把 v3 条目追加到 v2 文件,也不要为补全身份重写旧记录。 diff --git a/crates/argus-core/src/history.rs b/crates/argus-core/src/history.rs index 00221794..dd2b75ae 100644 --- a/crates/argus-core/src/history.rs +++ b/crates/argus-core/src/history.rs @@ -51,6 +51,11 @@ const DAY_MS: i64 = 86_400_000; pub struct HistoryPoint { /// Unix ms: the frame's start, or a bucket's average. pub ts: i64, + /// An actual frame, chosen as the first frame of a bucket. Unlike `ts`, + /// this timestamp can always address its process table. + pub frame_ts: i64, + /// Actual frame containing the highest CPU sample; earliest frame on ties. + pub cpu_peak_ts: i64, /// Average CPU, percent. pub cpu: f32, /// Highest CPU sample in the frame (or bucket). @@ -525,6 +530,8 @@ fn parse( let u64_at = |i: usize| u64::from_le_bytes(b[i..i + 8].try_into().unwrap()); let point = HistoryPoint { ts: i64::from_le_bytes(b[0..8].try_into().unwrap()), + frame_ts: i64::from_le_bytes(b[0..8].try_into().unwrap()), + cpu_peak_ts: i64::from_le_bytes(b[0..8].try_into().unwrap()), cpu: f32_at(8), cpu_peak: f32_at(12), gpu: f32_at(16), @@ -676,6 +683,8 @@ pub fn series(dir: &Path, from: i64, to: i64, buckets: usize) -> Vec Vec= from && p.ts <= to { let i = (((p.ts - from) as f64 / span) * buckets as f64) as usize; let a = &mut acc[i.min(buckets - 1)]; + if a.n == 0 { + a.frame_ts = p.ts; + } + if a.n == 0 + || p.cpu_peak > a.cpu_peak + || (p.cpu_peak == a.cpu_peak && p.ts < a.cpu_peak_ts) + { + a.cpu_peak_ts = p.ts; + } a.n += 1; a.ts += p.ts as f64; a.cpu += p.cpu as f64; @@ -728,6 +746,8 @@ pub fn series(dir: &Path, from: i64, to: i64, buckets: usize) -> VecEinstellungen öffnen", - "instanceUnavailable": "Die aufgezeichnete Instanz von {name} (PID {pid}) wurde beendet oder ihre Identität kann nicht bestätigt werden." + "instanceUnavailable": "Die aufgezeichnete Instanz von {name} (PID {pid}) wurde beendet oder ihre Identität kann nicht bestätigt werden.", + "showCpuPeak": "CPU-Spitzenframe zeigen", + "cpuSummary": "CPU-Mittel {average}%, Spitze {peak}%; Spitzenframe: {time}. Prozesswerte sind Frame-Mittelwerte und belegen nicht die Ursache einer kurzen Spitze." } diff --git a/locales/en-US/history.json b/locales/en-US/history.json index 642b81d3..16edea77 100644 --- a/locales/en-US/history.json +++ b/locales/en-US/history.json @@ -17,7 +17,8 @@ "peak": "Peak {value}%", "total": "of {value} GB", "charging": "Charging {value}", - "discharging": "Discharging {value}" + "discharging": "Discharging {value}", + "average": "Average {value}%" }, "exited": "{name} (PID {pid}) has exited.", "copied": { @@ -44,5 +45,7 @@ "earliest": "Earliest record", "note": "Records the top processes by CPU, memory, I/O, GPU and network every 5 seconds (or at the minimized or tray refresh rate when that is slower) and keeps them for 7 days.", "off": "History recording is off; no new data is being recorded. Open Settings", - "instanceUnavailable": "The recorded instance of {name} (PID {pid}) has exited or its identity cannot be confirmed." + "instanceUnavailable": "The recorded instance of {name} (PID {pid}) has exited or its identity cannot be confirmed.", + "showCpuPeak": "Show CPU peak frame", + "cpuSummary": "CPU average {average}%, peak {peak}%; peak frame: {time}. Process readings are frame averages and do not establish the cause of a brief peak." } diff --git a/locales/es-ES/history.json b/locales/es-ES/history.json index fc95a925..4d5d7d39 100644 --- a/locales/es-ES/history.json +++ b/locales/es-ES/history.json @@ -19,7 +19,8 @@ "peak": "Pico {value} %", "total": "de {value} GB", "charging": "Cargando {value}", - "discharging": "Descargando {value}" + "discharging": "Descargando {value}", + "average": "Media {value}%" }, "exited": "{name} (PID {pid}) ha finalizado.", "copied": { @@ -46,5 +47,7 @@ "earliest": "Registro más antiguo", "note": "Registra cada 5 segundos los procesos con mayor uso de CPU, memoria, I/O, GPU y red; si el intervalo al minimizar o permanecer en la bandeja es mayor, utiliza ese intervalo. Conserva los registros durante 7 días.", "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración", - "instanceUnavailable": "La instancia registrada de {name} (PID {pid}) ha finalizado o no se puede confirmar su identidad." + "instanceUnavailable": "La instancia registrada de {name} (PID {pid}) ha finalizado o no se puede confirmar su identidad.", + "showCpuPeak": "Ver fotograma del pico CPU", + "cpuSummary": "CPU: media {average}%, máximo {peak}%; fotograma del pico: {time}. Los valores de procesos son medias por fotograma y no prueban la causa de un pico breve." } diff --git a/locales/fr-FR/history.json b/locales/fr-FR/history.json index 67b2f803..b9a719be 100644 --- a/locales/fr-FR/history.json +++ b/locales/fr-FR/history.json @@ -19,7 +19,8 @@ "peak": "Pic {value} %", "total": "de {value} GB", "charging": "Chargement {value}", - "discharging": "Décharge {value}" + "discharging": "Décharge {value}", + "average": "Moyenne {value}%" }, "exited": "{name} (PID {pid}) s’est arrêté.", "copied": { @@ -46,5 +47,7 @@ "earliest": "Premier enregistrement", "note": "Enregistre les processus utilisant le plus de CPU, mémoire, I/O, GPU et réseau toutes les 5 secondes, ou selon l’intervalle de la fenêtre réduite ou de la zone de notification s’il est plus long. Les données sont conservées 7 jours.", "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres", - "instanceUnavailable": "L’instance enregistrée de {name} (PID {pid}) est terminée ou son identité ne peut pas être confirmée." + "instanceUnavailable": "L’instance enregistrée de {name} (PID {pid}) est terminée ou son identité ne peut pas être confirmée.", + "showCpuPeak": "Voir la mesure du pic CPU", + "cpuSummary": "CPU : moyenne {average}%, pic {peak}% ; mesure du pic : {time}. Les valeurs des processus sont des moyennes par mesure et ne prouvent pas la cause d’un bref pic." } diff --git a/locales/ja-JP/history.json b/locales/ja-JP/history.json index 2324a7ec..15d75851 100644 --- a/locales/ja-JP/history.json +++ b/locales/ja-JP/history.json @@ -15,7 +15,8 @@ "peak": "最大 {value}%", "total": "{value} GB 中", "charging": "充電中 {value}", - "discharging": "放電中 {value}" + "discharging": "放電中 {value}", + "average": "平均 {value}%" }, "exited": "{name}(PID {pid}) は終了しました。", "copied": { @@ -42,5 +43,7 @@ "earliest": "最も古い記録", "note": "CPU、メモリ、I/O、GPU、ネットワークの使用量が多いプロセスを 5 秒ごとに記録し、7 日間保存します。最小化中や通知領域への常駐中の更新間隔が長い場合は、その間隔で記録します。", "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く", - "instanceUnavailable": "記録された {name}(PID {pid})のインスタンスは終了したか、同一性を確認できません。" + "instanceUnavailable": "記録された {name}(PID {pid})のインスタンスは終了したか、同一性を確認できません。", + "showCpuPeak": "CPU ピークのフレームを表示", + "cpuSummary": "CPU 平均 {average}%、最大 {peak}%。ピークのフレーム:{time}。プロセスの値はフレーム内の平均であり、短いピークの原因を証明するものではありません。" } diff --git a/locales/ru-RU/history.json b/locales/ru-RU/history.json index 30403574..7d8338f5 100644 --- a/locales/ru-RU/history.json +++ b/locales/ru-RU/history.json @@ -21,7 +21,8 @@ "peak": "Пик {value} %", "total": "из {value} GB", "charging": "Зарядка {value}", - "discharging": "Разрядка {value}" + "discharging": "Разрядка {value}", + "average": "Среднее {value}%" }, "exited": "Процесс {name} (PID {pid}) завершился.", "copied": { @@ -48,5 +49,7 @@ "earliest": "Самая ранняя запись", "note": "Записывает процессы с наибольшей нагрузкой на CPU, память, I/O, GPU и сеть каждые 5 секунд. Если интервал для свёрнутого окна или области уведомлений больше, используется он. Записи хранятся 7 дней.", "off": "Запись истории отключена; новые данные не записываются. Открыть параметры", - "instanceUnavailable": "Записанный запуск {name} (PID {pid}) завершён или его идентичность не подтверждена." + "instanceUnavailable": "Записанный запуск {name} (PID {pid}) завершён или его идентичность не подтверждена.", + "showCpuPeak": "Кадр пика CPU", + "cpuSummary": "CPU: среднее {average}%, максимум {peak}%; кадр пика: {time}. Показатели процессов усреднены за кадр и не доказывают причину краткого пика." } diff --git a/locales/zh-CN/history.json b/locales/zh-CN/history.json index 60eec959..ab601566 100644 --- a/locales/zh-CN/history.json +++ b/locales/zh-CN/history.json @@ -11,7 +11,8 @@ "peak": "最高 {value}%", "total": "共 {value} GB", "charging": "充电 {value}", - "discharging": "放电 {value}" + "discharging": "放电 {value}", + "average": "平均 {value}%" }, "exited": "{name}(PID {pid})已经退出。", "copied": { @@ -38,5 +39,7 @@ "earliest": "最早的记录", "note": "每 5 秒记录 CPU、内存、I/O、GPU 和网络占用最高的进程(最小化或后台常驻时的刷新间隔更长时按该间隔),保留 7 天。", "off": "历史记录已关闭,不再记录新的数据。打开设置", - "instanceUnavailable": "进程 {name}(PID {pid})的记录实例已结束,或无法确认其身份。" + "instanceUnavailable": "进程 {name}(PID {pid})的记录实例已结束,或无法确认其身份。", + "showCpuPeak": "查看 CPU 峰值帧", + "cpuSummary": "区间 CPU 平均 {average}%,峰值 {peak}%;峰值记录帧:{time}。帧内进程读数为平均值,不能据此确定瞬时峰值的原因。" } diff --git a/locales/zh-TW/history.json b/locales/zh-TW/history.json index fa4a4882..0a6ef828 100644 --- a/locales/zh-TW/history.json +++ b/locales/zh-TW/history.json @@ -11,7 +11,8 @@ "peak": "最高 {value}%", "total": "共 {value} GB", "charging": "充電 {value}", - "discharging": "放電 {value}" + "discharging": "放電 {value}", + "average": "平均 {value}%" }, "exited": "{name}(PID {pid})已經結束。", "copied": { @@ -38,5 +39,7 @@ "earliest": "最早的記錄", "note": "每 5 秒記錄 CPU、記憶體、I/O、GPU 和網路佔用最高的處理程序(最小化或背景常駐時的重新整理間隔更長時依該間隔),保留 7 天。", "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定", - "instanceUnavailable": "處理程序 {name}(PID {pid})的記錄執行個體已結束,或無法確認其身分。" + "instanceUnavailable": "處理程序 {name}(PID {pid})的記錄執行個體已結束,或無法確認其身分。", + "showCpuPeak": "檢視 CPU 峰值影格", + "cpuSummary": "區間 CPU 平均 {average}%,峰值 {peak}%;峰值記錄影格:{time}。影格內處理程序讀數為平均值,無法據此確定瞬間峰值的原因。" } diff --git a/src-gpui/src/frontend/backend.rs b/src-gpui/src/frontend/backend.rs index b95d26a9..12066523 100644 --- a/src-gpui/src/frontend/backend.rs +++ b/src-gpui/src/frontend/backend.rs @@ -94,7 +94,8 @@ impl Desktop { return; } if pending.command == "history_moment" - && pending.args["cursor"] != json!(self.history_cursor) + && (pending.args["cursor"] != json!(self.history_cursor) + || self.data.get("historyMomentAt") != Some(&pending.args["ts"])) { self.data.remove("historyMomentAt"); self.load_history(window, cx); diff --git a/src-gpui/src/frontend/pages.rs b/src-gpui/src/frontend/pages.rs index a8c0c399..2fcd7d97 100644 --- a/src-gpui/src/frontend/pages.rs +++ b/src-gpui/src/frontend/pages.rs @@ -487,7 +487,18 @@ impl Desktop { self.load_history(window, cx); } "historyMetric" => self.history_metric = value.as_str().unwrap_or("cpu").into(), + "historyPeak" => { + if let Some(at) = value.as_i64() { + self.history_hover = None; + self.history_cursor = Some(at); + self.data.insert("historyPeakAt".into(), json!(at)); + self.load_history(window, cx); + cx.notify(); + } + return; + } "historyLatest" => { + self.data.remove("historyPeakAt"); self.history_cursor = None; self.history_hover = None; self.load_history(window, cx); diff --git a/src-gpui/src/frontend/pages/history.rs b/src-gpui/src/frontend/pages/history.rs index 3dc2cf7b..66455fad 100644 --- a/src-gpui/src/frontend/pages/history.rs +++ b/src-gpui/src/frontend/pages/history.rs @@ -2,6 +2,7 @@ //! charts are drawn once per query; pointing at them only moves the cursor marks. use super::*; use charts::GIB; +use widgets::Tone; pub(super) const RANGES: [(&str, i64); 4] = [ ("1h", 3_600_000), @@ -45,6 +46,23 @@ pub(super) fn recorded_target(row: &Value, frame: Option, live: &[Value]) - }) } +/// Choose a recorded frame, never the average timestamp between distant frames. +fn frame_at(records: &[Value], cursor: Option, peak: bool) -> Option { + let point = match cursor { + Some(at) => { + if peak && records.iter().any(|p| p["cpuPeakTs"].as_i64() == Some(at)) { + return Some(at); + } + let Some(point) = records.iter().find(|p| p["ts"].as_i64() == Some(at)) else { + return Some(at); + }; + point + } + None => records.last()?, + }; + point["frameTs"].as_i64().or_else(|| point["ts"].as_i64()) +} + pub(super) fn range_label(id: &str) -> String { let hours = RANGES .iter() @@ -352,7 +370,16 @@ impl Desktop { self.request("history_range", json!({}), Some("historyRange"), window, cx); } // A kept moment keeps its processes: they are read again only for another moment. - let moment = self.history_cursor.unwrap_or(now); + let records = self + .data + .get("historySeries") + .map(values) + .unwrap_or_default(); + let peak = self + .history_cursor + .is_some_and(|at| self.data.get("historyPeakAt").and_then(Value::as_i64) == Some(at)); + let moment = frame_at(records, self.history_cursor, peak) + .unwrap_or(self.history_cursor.unwrap_or(now)); if self.data.get("historyMomentAt") != Some(&json!(moment)) { self.data.insert("historyMomentAt".into(), json!(moment)); self.request( @@ -378,8 +405,8 @@ impl Desktop { let cursor = kept(self.history_cursor, from, to); if cursor != self.history_cursor { self.history_cursor = cursor; - self.load_history(window, cx); } + self.load_history(window, cx); } /// Keyboard on the history page: arrows step between points (Shift and Page keys by a /// tenth), Home and End jump to either end, Escape returns to the newest data. Steps @@ -396,6 +423,7 @@ impl Desktop { return false; } self.history_cursor = None; + self.data.remove("historyPeakAt"); self.load_history(window, cx); cx.notify(); return true; @@ -418,6 +446,7 @@ impl Desktop { return true; }; self.history_cursor = Some(at); + self.data.remove("historyPeakAt"); self.load_history(window, cx); cx.notify(); true @@ -500,7 +529,8 @@ impl Desktop { let value_of = |r: &Value| r[metric.field].as_f64(); let reading = readout.and_then(|r| value_of(r).map(|v| (r, v))); let value_text = reading.map(|(_, v)| match metric.field { - "cpu" | "gpu" => format!("{}%", theme::cpu(v)), + "cpu" => tr!("history.metric.average", value = theme::cpu(v)), + "gpu" => format!("{}%", theme::cpu(v)), "memUsed" => crate::regional::number!("{:.1} GB", v / GIB), "disk" => charts::byte_rate(v), "net" => charts::net_rate(v, bits), @@ -842,6 +872,7 @@ impl Desktop { cx.listener(move |this, event: &MouseDownEvent, window, cx| { if let Some(at) = click_time(event.position) { this.history_cursor = Some(at); + this.data.remove("historyPeakAt"); this.load_history(window, cx); cx.notify(); } @@ -910,6 +941,21 @@ impl Desktop { Some(time) => tr!("history.busiestAt", time = moment_label(time)), None => label("history.busiest"), }; + let selected_point = match self.history_cursor { + Some(at) => records.iter().find(|point| { + point["ts"].as_i64() == Some(at) || point["cpuPeakTs"].as_i64() == Some(at) + }), + None => records.last(), + }; + let peak_at = selected_point.and_then(|point| point["cpuPeakTs"].as_i64()); + let summary = selected_point.and_then(|point| { + Some(tr!( + "history.cpuSummary", + average = theme::cpu(point["cpu"].as_f64()?), + peak = theme::cpu(point["cpuPeak"].as_f64()?), + time = moment_label(point["cpuPeakTs"].as_i64()?) + )) + }); let earliest = self .data .get("historyRange") @@ -990,6 +1036,21 @@ impl Desktop { .pt(px(10.)) .px(px(14.)) .pb(px(4.)) + .when_some(peak_at, |d, at| { + d.child( + self.btn_small( + "history-peak", + label("history.showCpuPeak"), + None, + Tone::Plain, + ) + .on_click(cx.listener( + move |this, _, window, cx| { + this.preference("historyPeak", json!(at), window, cx); + }, + )), + ) + }) .child( div() .text_size(theme::font(14.)) @@ -1007,6 +1068,16 @@ impl Desktop { })), ), ) + .when_some(summary, |d, text| { + d.child( + div() + .px(px(14.)) + .pb(px(4.)) + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(text), + ) + }) .child(table) .child(foot); let page = window @@ -1294,13 +1365,37 @@ impl Desktop { #[cfg(test)] mod tests { use super::{ - DAY, HOUR, MINUTE, joins, kept, plan_load, point_at, recorded_target, refresh_every, - span_of, stepped, + DAY, HOUR, MINUTE, frame_at, joins, kept, plan_load, point_at, recorded_target, + refresh_every, span_of, stepped, }; use serde_json::{Value, json}; const NOW: i64 = 1_800_000_000_000; + #[test] + fn buckets_open_real_frames_without_reaching_across_gaps() { + let points = vec![json!({"ts":NOW + 300000,"frameTs":NOW,"cpuPeakTs":NOW + 600000})]; + assert_eq!(frame_at(&points, Some(NOW + 300000), false), Some(NOW)); + assert_eq!( + frame_at(&points, Some(NOW + 600000), true), + Some(NOW + 600000) + ); + assert_eq!(frame_at(&points, None, false), Some(NOW)); + // An actual empty location keeps the normal limited moment lookup. + assert_eq!( + frame_at(&points, Some(NOW + 900000), false), + Some(NOW + 900000) + ); + assert_eq!(frame_at(&[], None, false), None); + assert_eq!(frame_at(&[json!({"ts":NOW})], None, false), Some(NOW)); + let collision = vec![json!({"ts":NOW+5000,"frameTs":NOW,"cpuPeakTs":NOW+5000})]; + assert_eq!(frame_at(&collision, Some(NOW + 5000), false), Some(NOW)); + assert_eq!( + frame_at(&collision, Some(NOW + 5000), true), + Some(NOW + 5000) + ); + } + #[test] fn history_navigation_requires_the_recorded_instance() { let recorded = json!({"pid":42,"name":"worker.exe","createTime":NOW - 1000}); diff --git a/src-gpui/src/frontend/test_control.rs b/src-gpui/src/frontend/test_control.rs index 1b4eeb31..33a98e9a 100644 --- a/src-gpui/src/frontend/test_control.rs +++ b/src-gpui/src/frontend/test_control.rs @@ -513,6 +513,7 @@ impl Desktop { "toasts":self.ui.toasts.iter().filter(|toast| toast.leaving.is_none()).map(|toast| toast.text.as_str()).collect::>(), "performance":self.performance_test_state(), "star":self.star_test_state(), + "history":{"cursor":self.history_cursor,"requestedFrame":self.data.get("historyMomentAt"),"frame":self.data.get("historyMoment").map(|m| &m["system"]["ts"])}, "sequence":self.sequence,"timestamp":self.snapshot["timestamp"],"processIcons":self.ui.icons.borrow().len(), "allocationHeadroomBytes":crate::memory_pressure::available_memory(), "width":f32::from(window.viewport_size().width),"height":f32::from(window.viewport_size().height),"scaleFactor":window.scale_factor(),"remSize":f32::from(window.rem_size()), diff --git a/tools/window-probe/fixtures/history-peak.mjs b/tools/window-probe/fixtures/history-peak.mjs new file mode 100644 index 00000000..505bb288 --- /dev/null +++ b/tools/window-probe/fixtures/history-peak.mjs @@ -0,0 +1,21 @@ +import {readFileSync,writeFileSync} from 'node:fs'; +const f=JSON.parse(readFileSync('tools/window-probe/fixtures/desktop.json','utf8')); +const base=Math.floor(Date.now()/5000)*5000-30000; +const point={...f.historySeries[0],ts:base+5000,frameTs:base,cpuPeakTs:base+5000,cpu:34,cpuPeak:98}; +f.historySeries=[{...point,ts:base-60000,frameTs:base-60000,cpuPeakTs:base-60000,cpu:2,cpuPeak:2},point]; +f.historyWindow={from:base-3600000,to:base+30000}; +f.historyMoment={system:{...point,ts:base},processes:[{pid:44101,name:'quiet.exe',cpu:2,mem:1048576,io:0,gpu:0,net:0}]}; +writeFileSync('target/history-peak.json',JSON.stringify(f)); +const peakMoment={...f.historyMoment,system:{...point,ts:base+5000},processes:[{...f.historyMoment.processes[0],name:'burst.exe',cpu:98}]}; +const steps=[ + {control:{page:'history',pointerOutside:true},wait:700,inspect:'layout',label:'representative',expect:{'history.requestedFrame':base},capture:'average'}, + {control:{mouse:{type:'down',button:'left',x:96,y:577}},wait:300}, + {control:{mouse:{type:'up',button:'left',x:96,y:577}},wait:300,inspect:'layout',label:'peak-selected',expect:{'history.cursor':base+5000,'history.requestedFrame':base+5000}}, + {control:{resolve:{command:'history_moment',cache:'historyMoment',args:{cursor:base+5000,ts:base+5000},ok:true,value:peakMoment}},wait:300,inspect:'layout',label:'peak-frame',expect:{'history.frame':base+5000},capture:'peak'}, + {control:{keys:['end']},wait:300,inspect:'layout',label:'ordinary-same-time',expect:{'history.cursor':base+5000,'history.requestedFrame':base}}, + {control:{resolve:{command:'history_moment',cache:'historyMoment',args:{cursor:base+5000,ts:base+5000},ok:true,value:peakMoment}},wait:300,inspect:'layout',label:'stale-peak-rejected',expect:{'history.requestedFrame':base}}, + {control:{resolve:{command:'history_moment',cache:'historyMoment',args:{cursor:base+5000,ts:base},ok:true,value:f.historyMoment}},wait:300,inspect:'layout',label:'ordinary-frame',expect:{'history.frame':base},capture:'ordinary'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:600,capture:'peak-small'}, + {control:{wheel:{x:700,y:450,lines:-16}},wait:500,capture:'peak-small-card'}, +]; +writeFileSync('target/history-peak-steps.json',JSON.stringify({window:[1200,800],steps},null,2)); From 5e1383301f06b98d425d99968554716a4ec54465 Mon Sep 17 00:00:00 2001 From: hayxel Date: Thu, 12 Nov 2026 22:46:54 +0300 Subject: [PATCH 3/6] =?UTF-8?q?feat:=20=E8=A7=82=E5=AF=9F=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F=E5=90=84=E6=AC=A1=E8=BF=90=E8=A1=8C=E7=9A=84=E7=A7=81?= =?UTF-8?q?=E6=9C=89=E5=86=85=E5=AD=98=E5=8F=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/argus-app/src/sampler.rs | 42 +- crates/argus-app/tests/process_watch.rs | 148 ++++ crates/argus-core/examples/process_watch.rs | 242 ++++++ crates/argus-core/src/lib.rs | 1 + crates/argus-core/src/process.rs | 7 + crates/argus-core/src/watch.rs | 750 ++++++++++++++++++ crates/argus-core/src/watch/identity.rs | 200 +++++ crates/argus-core/src/watch/program.rs | 695 ++++++++++++++++ crates/argus-core/src/watch/store.rs | 424 ++++++++++ docs/guide/README.md | 16 + locales/de-DE/history.json | 44 +- locales/en-US/history.json | 44 +- locales/es-ES/history.json | 44 +- locales/fr-FR/history.json | 44 +- locales/ja-JP/history.json | 44 +- locales/ru-RU/history.json | 44 +- locales/zh-CN/history.json | 44 +- locales/zh-TW/history.json | 44 +- src-gpui/src/commands.rs | 32 +- src-gpui/src/dispatch.rs | 7 + src-gpui/src/frontend/backend.rs | 27 + src-gpui/src/frontend/pages.rs | 27 + src-gpui/src/frontend/pages/details.rs | 23 +- src-gpui/src/frontend/pages/history.rs | 6 + src-gpui/src/frontend/pages/process_watch.rs | 427 ++++++++++ src-gpui/src/frontend/pages/settings.rs | 10 + src-gpui/src/frontend/test_control.rs | 10 +- tools/window-probe/fixtures/process-watch.mjs | 29 + tools/window-probe/fixtures/program-watch.mjs | 61 ++ 29 files changed, 3518 insertions(+), 18 deletions(-) create mode 100644 crates/argus-app/tests/process_watch.rs create mode 100644 crates/argus-core/examples/process_watch.rs create mode 100644 crates/argus-core/src/watch.rs create mode 100644 crates/argus-core/src/watch/identity.rs create mode 100644 crates/argus-core/src/watch/program.rs create mode 100644 crates/argus-core/src/watch/store.rs create mode 100644 src-gpui/src/frontend/pages/process_watch.rs create mode 100644 tools/window-probe/fixtures/process-watch.mjs create mode 100644 tools/window-probe/fixtures/program-watch.mjs diff --git a/crates/argus-app/src/sampler.rs b/crates/argus-app/src/sampler.rs index 72d903d8..44ceb486 100644 --- a/crates/argus-app/src/sampler.rs +++ b/crates/argus-app/src/sampler.rs @@ -9,6 +9,7 @@ use std::time::{Duration, Instant}; use crate::channel::Channel; use argus_core::history::{self, HistoryRecorder}; +use argus_core::watch::{WatchAction, WatchError, WatchRecorder, WatchView}; use argus_core::{Collector, Snapshot}; use argus_service::{DiskClient, NetworkClient, RuleRunner, SensorClient}; @@ -66,6 +67,11 @@ pub enum Control { /// Deletes the history in this folder; replies once the files are gone. /// Goes through this thread so no frame is being written meanwhile. ClearHistory(PathBuf, Sender>), + Watch( + PathBuf, + WatchAction, + Sender, WatchError>>, + ), } pub struct Sampler { @@ -190,6 +196,7 @@ impl Sampler { let mut subscriber: Option> = None; let mut window: Option = None; let mut history: Option = None; + let mut watch: Option = None; let mut interval = DEFAULT_INTERVAL; let mut minimized = BACKGROUND_INTERVAL; let mut tray = BACKGROUND_INTERVAL; @@ -241,11 +248,32 @@ impl Sampler { history = dir.map(HistoryRecorder::new); continue; } + Ok(Control::Watch(dir, action, reply)) => { + let result = if let Some(recorder) = &mut watch { + recorder.action(action) + } else if matches!(action, WatchAction::Delete) { + WatchRecorder::delete_saved(&dir).map(|()| None) + } else { + WatchRecorder::open(dir).and_then(|mut recorder| { + let result = recorder.action(action); + watch = Some(recorder); + result + }) + }; + let _ = reply.send(result); + continue; + } Ok(Control::ClearHistory(dir, reply)) => { - let result = match &mut history { - Some(recorder) => recorder.clear(), - None => history::clear(&dir), + let observed = match &mut watch { + Some(recorder) => recorder.action(WatchAction::Delete).map(|_| ()), + None => WatchRecorder::delete_saved(&dir), }; + let result = observed + .map_err(|_| io::Error::other("process observation cleanup failed")) + .and_then(|()| match &mut history { + Some(recorder) => recorder.clear(), + None => history::clear(&dir), + }); let _ = reply.send(result); continue; } @@ -282,6 +310,14 @@ impl Sampler { if let Some(recorder) = &mut history { recorder.record(&snapshot); } + if let Some(recorder) = &mut watch + && recorder.record(&snapshot).is_err() + { + argus_core::diagnostics::warn( + "process observation", + "recording interrupted", + ); + } // A paused view stays as it is, except right after an action. let send = publish_refresh(&mut owed, collector.process_sample_started()) || !paused; diff --git a/crates/argus-app/tests/process_watch.rs b/crates/argus-app/tests/process_watch.rs new file mode 100644 index 00000000..cde1267f --- /dev/null +++ b/crates/argus-app/tests/process_watch.rs @@ -0,0 +1,148 @@ +//! Real sampler integration; only observes this test process and writes its own temp folder. +use argus_app::{ + channel::Channel, + sampler::{Control, Sampler}, +}; +use argus_core::{ + Collector, MetaStore, + watch::{WatchAction, WatchError, WatchMode, WatchRecorder, WatchState, WatchView}, +}; +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +fn request( + sampler: &Sampler, + dir: &std::path::Path, + action: WatchAction, +) -> Result, WatchError> { + let (tx, rx) = mpsc::channel(); + sampler.send(Control::Watch(dir.to_owned(), action, tx)); + rx.recv_timeout(Duration::from_secs(15)).unwrap() +} + +#[test] +#[ignore = "real Windows collector integration, run explicitly with --ignored"] +fn observes_and_deletes_through_the_real_sampler() { + let dir = std::env::temp_dir().join(format!("argus-sampler-watch-{}", std::process::id())); + let rules = Arc::new(argus_service::RuleRunner::spawn(false)); + // No rules are installed and no service operations or system settings are changed. + let sampler = Sampler::spawn(|| Collector::new(MetaStore::new()), rules); + let (tx, rx) = mpsc::channel(); + sampler.send(Control::Subscribe(Channel::new(move |snapshot| { + tx.send(snapshot)?; + Ok(()) + }))); + let snapshot = rx.recv_timeout(Duration::from_secs(30)).unwrap(); + let own = snapshot + .processes + .iter() + .find(|p| p.pid == std::process::id()) + .unwrap(); + let start = WatchAction::Start { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-test".into(), + }; + request(&sampler, &dir, start).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + let _ = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let view = request(&sampler, &dir, WatchAction::Status) + .unwrap() + .unwrap(); + if view.points.iter().any(|point| point.memory.is_some()) { + break; + } + assert!( + std::time::Instant::now() < deadline, + "no valid observation through sampler" + ); + } + assert_eq!( + request(&sampler, &dir, WatchAction::Stop) + .unwrap() + .unwrap() + .state, + WatchState::Stopped + ); + assert!( + request(&sampler, &dir, WatchAction::Delete) + .unwrap() + .is_none() + ); + assert!(!dir.join("process-watch.jsonl").exists()); + request( + &sampler, + &dir, + WatchAction::Start { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-test".into(), + }, + ) + .unwrap(); + let (clear_tx, clear_rx) = mpsc::channel(); + sampler.send(Control::ClearHistory(dir.clone(), clear_tx)); + clear_rx + .recv_timeout(Duration::from_secs(15)) + .unwrap() + .unwrap(); + assert!( + request(&sampler, &dir, WatchAction::Status) + .unwrap() + .is_none() + ); + request( + &sampler, + &dir, + WatchAction::StartProgram { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-program".into(), + }, + ) + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + let _ = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let view = request(&sampler, &dir, WatchAction::Status) + .unwrap() + .unwrap(); + assert_eq!(view.mode, WatchMode::Program); + if view.points.iter().any(|point| point.memory.is_some()) { + break; + } + assert!(std::time::Instant::now() < deadline); + } + let stopped = request(&sampler, &dir, WatchAction::Stop).unwrap().unwrap(); + assert_eq!(stopped.state, WatchState::Stopped); + assert_eq!(stopped.live_runs, 0); + assert!(WatchRecorder::storage_bytes(&dir) > 0); + request(&sampler, &dir, WatchAction::Delete).unwrap(); + assert_eq!(WatchRecorder::storage_bytes(&dir), 0); + request( + &sampler, + &dir, + WatchAction::StartProgram { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-program".into(), + }, + ) + .unwrap(); + let (clear_tx, clear_rx) = mpsc::channel(); + sampler.send(Control::ClearHistory(dir.clone(), clear_tx)); + clear_rx + .recv_timeout(Duration::from_secs(15)) + .unwrap() + .unwrap(); + assert!( + request(&sampler, &dir, WatchAction::Status) + .unwrap() + .is_none() + ); + assert_eq!(WatchRecorder::storage_bytes(&dir), 0); + drop(sampler); + drop(rx); + std::fs::remove_dir(dir).unwrap(); +} diff --git a/crates/argus-core/examples/process_watch.rs b/crates/argus-core/examples/process_watch.rs new file mode 100644 index 00000000..d349e508 --- /dev/null +++ b/crates/argus-core/examples/process_watch.rs @@ -0,0 +1,242 @@ +//! Controlled real-memory observation. Only owns helper processes and a temporary folder. +//! cargo run -p argus-core --example process_watch --release +use argus_core::{ + Collector, MetaStore, + history::{self, HistoryRecorder}, + watch::{WatchAction, WatchRecorder, WatchState}, +}; +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::os::windows::{io::AsRawHandle, process::CommandExt}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::time::{Duration, Instant}; +use windows::Win32::{ + Foundation::HANDLE, + System::{ + Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}, + Threading::GetProcessTimes, + }, +}; + +fn helper(competitor: bool) { + let running = Arc::new(AtomicBool::new(true)); + let worker = competitor.then(|| { + let running = running.clone(); + std::thread::spawn(move || { + let mut value = 1u64; + while running.load(Ordering::Relaxed) { + for _ in 0..10_000 { + value = + std::hint::black_box(value.wrapping_mul(1664525).wrapping_add(1013904223)); + } + } + value + }) + }); + let mut allocation: *mut std::ffi::c_void = std::ptr::null_mut(); + println!("ready"); + for line in std::io::stdin().lock().lines() { + let line = line.unwrap(); + if !allocation.is_null() { + unsafe { VirtualFree(allocation, 0, MEM_RELEASE) }.unwrap(); + allocation = std::ptr::null_mut(); + } + if line == "exit" { + break; + } + let mib: usize = line.parse().unwrap(); + if mib > 0 { + let size = mib * 1024 * 1024; + allocation = + unsafe { VirtualAlloc(None, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!allocation.is_null()); + for offset in (0..size).step_by(4096) { + unsafe { std::ptr::write_volatile(allocation.cast::().add(offset), 1) }; + } + } + println!("allocated {mib}"); + } + if !allocation.is_null() { + unsafe { VirtualFree(allocation, 0, MEM_RELEASE) }.unwrap(); + } + running.store(false, Ordering::Relaxed); + if let Some(worker) = worker { + worker.join().unwrap(); + } +} + +struct Helper { + child: Child, + input: Option, + output: BufReader, +} +impl Helper { + fn spawn(mode: &str) -> Self { + let mut child = Command::new(std::env::current_exe().unwrap()) + .arg(mode) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let input = child.stdin.take(); + let output = BufReader::new(child.stdout.take().unwrap()); + let mut helper = Self { + child, + input, + output, + }; + let mut ready = String::new(); + helper.output.read_line(&mut ready).unwrap(); + assert_eq!(ready.trim(), "ready"); + helper + } + fn memory(&mut self, mib: usize) { + writeln!(self.input.as_mut().unwrap(), "{mib}").unwrap(); + let mut reply = String::new(); + self.output.read_line(&mut reply).unwrap(); + assert_eq!(reply.trim(), format!("allocated {mib}")); + } + fn creation(&self) -> i64 { + let (mut c, mut e, mut k, mut u) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(self.child.as_raw_handle()), + &mut c, + &mut e, + &mut k, + &mut u, + ) + } + .unwrap(); + let ticks = ((c.dwHighDateTime as u64) << 32) | c.dwLowDateTime as u64; + (ticks / 10000) as i64 - 11_644_473_600_000 + } + fn exit(&mut self) { + if let Some(mut input) = self.input.take() { + writeln!(input, "exit").unwrap(); + drop(input); + } + assert!(self.child.wait().unwrap().success()); + } +} +impl Drop for Helper { + fn drop(&mut self) { + self.input = None; + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if self.child.try_wait().ok().flatten().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn main() { + match std::env::args().nth(1).as_deref() { + Some("memory-helper") => return helper(false), + Some("competitor") => return helper(true), + _ => {} + } + let dir = std::env::temp_dir().join(format!("argus-watch-real-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + let mut target = Helper::spawn("memory-helper"); + let mut competitor = Helper::spawn("competitor"); + let pid = target.child.id(); + let competitor_pid = competitor.child.id(); + let created = target.creation(); + let mut collector = Collector::new(MetaStore::new()); + let mut history = HistoryRecorder::new(dir.clone()); + let mut recorder = WatchRecorder::open(dir.clone()).unwrap(); + recorder + .action(WatchAction::Start { + pid, + create_time: created, + name: "controlled-memory-helper".into(), + }) + .unwrap(); + let mut times = Vec::new(); + let mut ranges = Vec::new(); + for mib in [4, 12, 2] { + target.memory(mib); + println!("phase {mib} MiB: sampling real process for 7 seconds"); + let mut last = None; + for _ in 0..7 { + std::thread::sleep(Duration::from_secs(1)); + let snapshot = collector.sample(); + last = Some(snapshot.timestamp); + history.record(&snapshot); + let t = Instant::now(); + recorder.record(&snapshot).unwrap(); + times.push(t.elapsed().as_micros()); + } + let view = recorder.view().unwrap(); + let point = view + .points + .iter() + .rev() + .find(|p| p.memory.is_some()) + .unwrap(); + ranges.push((mib, point.memory.unwrap(), point.commit.unwrap())); + if mib == 12 { + println!("controlled sampling pause: 11 seconds (creates an explicit gap)"); + std::thread::sleep(Duration::from_secs(11)); + } + if mib == 2 { + let snapshot = collector.sample(); + history.record(&snapshot); + let moment = history::moment(&dir, last.unwrap() - 5000).unwrap(); + assert!( + !moment.processes.iter().any(|p| p.pid == pid), + "watched helper unexpectedly entered the overall top" + ); + assert!( + moment.processes.iter().any(|p| p.pid == competitor_pid), + "controlled CPU competitor missing from top" + ); + } + } + assert!(ranges[1].1 > ranges[0].1 + 4 * 1024 * 1024); + assert!(ranges[1].2 > ranges[0].2 + 4 * 1024 * 1024); + assert!(ranges[2].1 + 4 * 1024 * 1024 < ranges[1].1); + assert!(ranges[2].2 + 4 * 1024 * 1024 < ranges[1].2); + target.exit(); + std::thread::sleep(Duration::from_millis(100)); + recorder.record(&collector.sample()).unwrap(); + let view = recorder.view().unwrap(); + assert_eq!(view.state, WatchState::Exited); + if let Some(path) = std::env::args().nth(1) { + fs::write(path, serde_json::to_vec_pretty(&view).unwrap()).unwrap(); + } + assert!(view.points.iter().any(|p| p.state == WatchState::Gap)); + assert!( + recorder + .action(WatchAction::Start { + pid: competitor_pid, + create_time: competitor.creation(), + name: "other-run".into() + }) + .is_err() + ); + recorder.action(WatchAction::Stop).unwrap(); + recorder.action(WatchAction::Delete).unwrap(); + assert!(recorder.view().is_none()); + assert!(!dir.join("process-watch.jsonl").exists()); + competitor.exit(); + drop(history); + drop(recorder); + fs::remove_dir_all(&dir).unwrap(); + println!( + "PASS: private WS and commit grew/released; target below top; competitor in top; explicit gap; exact-instance exit; stop/delete; no replacement attached." + ); + println!("memory phases (MiB requested, private WS bytes, private commit bytes): {ranges:?}"); + times.sort(); + println!("watch record time us (dev/release per invocation): {times:?}"); +} diff --git a/crates/argus-core/src/lib.rs b/crates/argus-core/src/lib.rs index cfdc56ff..29c18988 100644 --- a/crates/argus-core/src/lib.rs +++ b/crates/argus-core/src/lib.rs @@ -35,6 +35,7 @@ pub mod startup; pub mod system; pub mod theme; mod util; +pub mod watch; mod webview; pub use collector::{Collector, Snapshot}; diff --git a/crates/argus-core/src/process.rs b/crates/argus-core/src/process.rs index 2402d2b2..414f5328 100644 --- a/crates/argus-core/src/process.rs +++ b/crates/argus-core/src/process.rs @@ -861,6 +861,13 @@ pub(crate) fn list_lineage() -> Vec<(u32, u32, i64)> { #[cfg(test)] mod tests { + #[test] + #[ignore = "owned child fixture for watch identity and launch regressions"] + fn liveness_child() { + use std::io::Read; + let _ = std::io::stdin().read(&mut [0u8]); + } + #[test] fn pending_queries_keep_recent_readings_but_expire_a_stuck_source() { let at = std::time::Instant::now(); diff --git a/crates/argus-core/src/watch.rs b/crates/argus-core/src/watch.rs new file mode 100644 index 00000000..f0b03239 --- /dev/null +++ b/crates/argus-core/src/watch.rs @@ -0,0 +1,750 @@ +//! Explicit, bounded observation of an instance or program, independent of top lists. +//! Local versioned storage. A closed observation is never resumed implicitly. +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use crate::{Snapshot, util::OwnedHandle}; +use serde::{Deserialize, Serialize}; +use windows::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows::Win32::System::Threading::WaitForSingleObject; +mod identity; +mod program; +mod store; +pub use identity::ProgramIdentity; +pub use store::{ + CAPACITY as PROGRAM_CAPACITY, MAX_BYTES as PROGRAM_MAX_BYTES, + RETENTION_MS as PROGRAM_RETENTION_MS, +}; + +pub const SAMPLE_MS: i64 = 5_000; +pub const MAX_POINTS: usize = 720; +pub const MAX_BYTES: u64 = 1 << 20; +const FILE_NAME: &str = "process-watch.jsonl"; + +#[derive(Clone, Debug, Deserialize)] +#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)] +pub enum WatchAction { + Start { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + name: String, + }, + StartProgram { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + name: String, + }, + SelectRun { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + }, + Page { + before: Option, + }, + Runs { + offset: usize, + }, + Status, + Stop, + Delete, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WatchState { + Recording, + Gap, + Exited, + Stopped, + Interrupted, + Limit, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchPoint { + pub ts: i64, + pub memory: Option, + pub commit: Option, + pub state: WatchState, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WatchMode { + #[default] + Instance, + Program, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchRun { + pub pid: u32, + pub create_time: i64, + pub first_ts: i64, + pub last_ts: i64, + pub points: usize, + pub state: WatchState, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchView { + pub version: u32, + pub pid: u32, + pub create_time: i64, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub program: Option, + #[serde(default)] + pub mode: WatchMode, + #[serde(default)] + pub runs: Vec, + #[serde(default)] + pub total_runs: usize, + #[serde(default)] + pub total_points: usize, + #[serde(default)] + pub damaged: bool, + #[serde(default)] + pub first_sequence: Option, + #[serde(default)] + pub has_earlier: bool, + #[serde(default)] + pub has_later: bool, + #[serde(default)] + pub run_offset: usize, + #[serde(default)] + pub live_runs: usize, + #[serde(default)] + pub unconfirmed: usize, + pub state: WatchState, + pub points: Vec, +} + +#[derive(Debug)] +pub enum WatchError { + Identity, + Access, + Existing, + Missing, + Storage, + Invalid, +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +enum Record { + Header { + version: u32, + pid: u32, + created: i64, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + program: Option, + }, + Point(WatchPoint), +} + +pub struct WatchRecorder { + dir: PathBuf, + program_watch: Option, + view: Option, + handle: Option, + file: Option, + bytes: u64, + started: Option, + last: Option, +} + +impl WatchRecorder { + pub fn storage_bytes(dir: &std::path::Path) -> u64 { + [FILE_NAME, store::FILE_NAME] + .iter() + .map(|name| fs::metadata(dir.join(name)).map_or(0, |meta| meta.len())) + .sum() + } + pub fn delete_saved(dir: &std::path::Path) -> Result<(), WatchError> { + for name in [FILE_NAME, store::FILE_NAME] { + match fs::remove_file(dir.join(name)) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(WatchError::Storage), + } + } + Ok(()) + } + + pub fn open(dir: PathBuf) -> Result { + let mut recorder = Self { + dir, + program_watch: None, + view: None, + handle: None, + file: None, + bytes: 0, + started: None, + last: None, + }; + let path = recorder.dir.join(FILE_NAME); + if recorder + .dir + .join(store::FILE_NAME) + .try_exists() + .map_err(|_| WatchError::Storage)? + { + if path.try_exists().map_err(|_| WatchError::Storage)? { + return Err(WatchError::Existing); + } + recorder.program_watch = Some(program::ProgramWatch::open(&recorder.dir)?); + return Ok(recorder); + } + let bytes = match File::open(&path) { + Ok(file) => { + let mut bytes = Vec::new(); + file.take(MAX_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| WatchError::Storage)?; + if bytes.len() as u64 > MAX_BYTES { + return Err(WatchError::Invalid); + } + bytes + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(recorder), + Err(_) => return Err(WatchError::Storage), + }; + let mut lines = bytes.split(|b| *b == b'\n'); + let header: Record = serde_json::from_slice(lines.next().ok_or(WatchError::Invalid)?) + .map_err(|_| WatchError::Invalid)?; + let Record::Header { + version, + pid, + created, + name, + program, + } = header + else { + return Err(WatchError::Invalid); + }; + if !matches!(version, 1 | 2) || program.as_ref().is_some_and(|program| !program.valid()) { + return Err(WatchError::Invalid); + } + let mut view = WatchView { + version, + pid, + create_time: created, + name, + program, + mode: WatchMode::Instance, + runs: Vec::new(), + total_runs: 0, + total_points: 0, + damaged: false, + first_sequence: None, + has_earlier: false, + has_later: false, + run_offset: 0, + live_runs: 0, + unconfirmed: 0, + state: WatchState::Interrupted, + points: Vec::new(), + }; + let mut damaged = false; + for line in lines.filter(|line| !line.is_empty()) { + let Ok(Record::Point(point)) = serde_json::from_slice(line) else { + damaged = true; + break; + }; + if view.points.len() > MAX_POINTS { + return Err(WatchError::Invalid); + } + view.state = point.state; + view.points.push(point); + } + if damaged || matches!(view.state, WatchState::Recording | WatchState::Gap) { + view.state = WatchState::Interrupted; + } + recorder.bytes = bytes.len() as u64; + recorder.view = Some(view); + Ok(recorder) + } + + pub fn view(&self) -> Option { + self.program_watch + .as_ref() + .map(program::ProgramWatch::view) + .or_else(|| { + self.view.clone().map(|mut view| { + view.live_runs = usize::from(self.handle.is_some()); + view.total_runs = 1; + view.total_points = view.points.len(); + view + }) + }) + } + + pub fn action(&mut self, action: WatchAction) -> Result, WatchError> { + match action { + WatchAction::Status => {} + WatchAction::Start { + pid, + create_time, + name, + } => { + if self.view.is_some() || self.program_watch.is_some() { + return Err(WatchError::Existing); + } + if pid == 0 || create_time <= 0 || name.is_empty() || name.len() > 1024 { + return Err(WatchError::Identity); + } + let instance = identity::Instance::open(pid, create_time)?; + // Image identity is optional for a single-run observation. + let program = instance.program().ok(); + let handle = instance.into_handle(); + fs::create_dir_all(&self.dir).map_err(|_| WatchError::Storage)?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(self.dir.join(FILE_NAME)) + .map_err(|_| WatchError::Storage)?; + let mut header = serde_json::to_vec(&Record::Header { + version: 2, + pid, + created: create_time, + name: name.clone(), + program: program.clone(), + }) + .map_err(|_| WatchError::Storage)?; + header.push(b'\n'); + if file.write_all(&header).and_then(|()| file.flush()).is_err() { + drop(file); + let _ = fs::remove_file(self.dir.join(FILE_NAME)); + return Err(WatchError::Storage); + } + self.bytes = header.len() as u64; + self.file = Some(file); + self.handle = Some(handle); + self.started = Some(Instant::now()); + self.last = None; + self.view = Some(WatchView { + version: 2, + pid, + create_time, + name, + program, + mode: WatchMode::Instance, + runs: Vec::new(), + total_runs: 0, + total_points: 0, + damaged: false, + first_sequence: None, + has_earlier: false, + has_later: false, + run_offset: 0, + live_runs: 1, + unconfirmed: 0, + state: WatchState::Recording, + points: Vec::new(), + }); + } + WatchAction::StartProgram { + pid, + create_time, + name, + } => { + if self.view.is_some() || self.program_watch.is_some() { + return Err(WatchError::Existing); + } + if name.is_empty() || name.len() > 1024 { + return Err(WatchError::Identity); + } + self.program_watch = Some(program::ProgramWatch::start( + &self.dir, + pid, + create_time, + name, + )?); + } + WatchAction::SelectRun { pid, create_time } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .select(pid, create_time)?; + } + WatchAction::Page { before } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .page(before)?; + } + WatchAction::Runs { offset } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .runs_page(offset); + } + WatchAction::Stop => { + if let Some(program) = &mut self.program_watch { + program.stop(WatchState::Stopped, now_ms())?; + return Ok(self.view()); + } + if self.view.is_none() { + return Err(WatchError::Missing); + } + if self.file.is_some() { + self.finish(WatchState::Stopped, now_ms())?; + } + } + WatchAction::Delete => { + self.program_watch = None; + self.file = None; + self.handle = None; + if Self::delete_saved(&self.dir).is_err() { + if let Some(view) = &mut self.view { + view.state = WatchState::Interrupted; + } + return Err(WatchError::Storage); + } + self.view = None; + self.started = None; + self.last = None; + self.bytes = 0; + } + } + Ok(self.view()) + } + + pub fn record(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if let Some(program) = &mut self.program_watch { + return program.record(snapshot); + } + let result = self.record_sample(snapshot); + if result.is_err() { + self.file = None; + self.handle = None; + if let Some(view) = &mut self.view { + view.state = WatchState::Interrupted; + } + } + result + } + + fn record_sample(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + let Some(handle) = &self.handle else { + return Ok(()); + }; + match unsafe { WaitForSingleObject(handle.0, 0) } { + WAIT_OBJECT_0 => return self.finish(WatchState::Exited, snapshot.timestamp), + WAIT_TIMEOUT => {} + _ => return self.finish(WatchState::Interrupted, snapshot.timestamp), + } + if self + .started + .is_some_and(|start| start.elapsed() >= Duration::from_secs(3600)) + || self + .view + .as_ref() + .is_some_and(|view| view.points.len() >= MAX_POINTS) + { + return self.finish(WatchState::Limit, snapshot.timestamp); + } + if self + .last + .is_some_and(|last| last.elapsed() < Duration::from_millis(SAMPLE_MS as u64)) + { + return Ok(()); + } + let view = self.view.as_ref().ok_or(WatchError::Missing)?; + if let Some(previous) = view.points.last() { + if snapshot.timestamp < previous.ts { + return self.finish(WatchState::Interrupted, previous.ts); + } + if snapshot.timestamp - previous.ts > SAMPLE_MS * 2 { + let missing = previous.ts + SAMPLE_MS; + self.push(WatchPoint { + ts: missing, + memory: None, + commit: None, + state: WatchState::Gap, + })?; + if self.handle.is_none() { + return Ok(()); + } + } + } + let view = self.view.as_ref().ok_or(WatchError::Missing)?; + let row = snapshot.processes.iter().find(|p| { + p.pid == view.pid + && p.create_time == view.create_time + && !p.stale + && !p.sample_reused + && !p.counters_pending + }); + let point = WatchPoint { + ts: snapshot.timestamp, + memory: row.map(|p| p.private_ws), + commit: row.map(|p| p.commit), + state: if row.is_some() { + WatchState::Recording + } else { + WatchState::Gap + }, + }; + self.push(point)?; + self.last = Some(Instant::now()); + Ok(()) + } + + fn push(&mut self, point: WatchPoint) -> Result<(), WatchError> { + if matches!(point.state, WatchState::Recording | WatchState::Gap) + && self + .view + .as_ref() + .is_some_and(|view| view.points.len() >= MAX_POINTS) + { + return self.finish(WatchState::Limit, point.ts); + } + let mut bytes = + serde_json::to_vec(&Record::Point(point.clone())).map_err(|_| WatchError::Storage)?; + bytes.push(b'\n'); + if self.bytes + bytes.len() as u64 > MAX_BYTES - 512 + && matches!(point.state, WatchState::Recording | WatchState::Gap) + { + return self.finish(WatchState::Limit, point.ts); + } + if self.bytes + bytes.len() as u64 > MAX_BYTES { + return Err(WatchError::Storage); + } + self.file + .as_mut() + .ok_or(WatchError::Storage)? + .write_all(&bytes) + .map_err(|_| WatchError::Storage)?; + self.bytes += bytes.len() as u64; + let view = self.view.as_mut().ok_or(WatchError::Missing)?; + view.state = point.state; + view.points.push(point); + Ok(()) + } + + fn finish(&mut self, state: WatchState, ts: i64) -> Result<(), WatchError> { + let result = self.push(WatchPoint { + ts, + memory: None, + commit: None, + state, + }); + self.file = None; + self.handle = None; + self.started = None; + if let Some(view) = &mut self.view { + view.state = if result.is_ok() { + state + } else { + WatchState::Interrupted + }; + } + result + } +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ProcessRow; + use crate::util::{filetime_ticks, ticks_to_unix_ms}; + use windows::Win32::System::Threading::{ + GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, + }; + + fn own_start() -> WatchAction { + let handle = OwnedHandle( + unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, std::process::id()) } + .unwrap(), + ); + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { GetProcessTimes(handle.0, &mut created, &mut exited, &mut kernel, &mut user) } + .unwrap(); + WatchAction::Start { + pid: std::process::id(), + create_time: ticks_to_unix_ms(filetime_ticks(created)), + name: "owned-helper.exe".into(), + } + } + + fn folder(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!("argus-watch-{tag}-{}", std::process::id())) + } + fn sample(view: &WatchView) -> Snapshot { + Snapshot { + seq: 1, + timestamp: now_ms(), + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: vec![ProcessRow { + pid: view.pid, + create_time: view.create_time, + private_ws: 1024, + commit: 8192, + ..Default::default() + }], + } + } + + #[test] + fn legacy_observation_has_no_invented_program_identity_and_is_not_rewritten() { + let dir = folder("legacy-program"); + fs::create_dir(&dir).unwrap(); + let header = + b"{\"kind\":\"header\",\"version\":1,\"pid\":42,\"created\":1,\"name\":\"same.exe\"}\n"; + fs::write(dir.join(FILE_NAME), header).unwrap(); + let recorder = WatchRecorder::open(dir.clone()).unwrap(); + let view = recorder.view().unwrap(); + assert_eq!(view.version, 1); + assert!(view.program.is_none()); + assert_eq!(fs::read(dir.join(FILE_NAME)).unwrap(), header); + WatchRecorder::delete_saved(&dir).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn observes_below_top_and_never_attaches_to_a_replacement() { + let dir = folder("identity"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + assert!( + rec.view() + .unwrap() + .program + .as_ref() + .is_some_and(ProgramIdentity::valid) + ); + let mut snapshot = sample(&rec.view().unwrap()); + for pid in 100000..100100 { + snapshot.processes.push(ProcessRow { + pid, + private_ws: 1 << 30, + ..Default::default() + }); + } + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().points[0].memory, Some(1024)); + rec.last = None; + snapshot.processes[0].create_time += 1; + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().points[1].state, WatchState::Gap); + assert_eq!(rec.view().unwrap().points[1].memory, None); + rec.action(WatchAction::Stop).unwrap(); + let mut reopened = WatchRecorder::open(dir.clone()).unwrap(); + assert_eq!(reopened.view().unwrap().state, WatchState::Stopped); + assert!(matches!( + reopened.action(own_start()), + Err(WatchError::Existing) + )); + reopened.action(WatchAction::Delete).unwrap(); + assert!(!dir.join(FILE_NAME).exists()); + assert!(reopened.view().is_none()); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn restart_is_interrupted_and_storage_is_bounded() { + let dir = folder("bounded"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + let snapshot = sample(&rec.view().unwrap()); + rec.record(&snapshot).unwrap(); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Interrupted + ); + for _ in 1..=MAX_POINTS { + rec.last = None; + rec.record(&snapshot).unwrap(); + } + assert_eq!(rec.view().unwrap().state, WatchState::Limit); + assert!(fs::metadata(dir.join(FILE_NAME)).unwrap().len() <= MAX_BYTES); + assert!(rec.handle.is_none()); + rec.action(WatchAction::Delete).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn torn_or_oversized_records_are_bounded_and_can_be_deleted() { + let dir = folder("corrupt"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + rec.record(&sample(&rec.view().unwrap())).unwrap(); + rec.action(WatchAction::Stop).unwrap(); + OpenOptions::new() + .append(true) + .open(dir.join(FILE_NAME)) + .unwrap() + .write_all(b"{\"kind\":") + .unwrap(); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Interrupted + ); + WatchRecorder::delete_saved(&dir).unwrap(); + let file = File::create(dir.join(FILE_NAME)).unwrap(); + file.set_len(MAX_BYTES + 1).unwrap(); + drop(file); + assert!(matches!( + WatchRecorder::open(dir.clone()), + Err(WatchError::Invalid) + )); + WatchRecorder::delete_saved(&dir).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn gaps_at_the_quota_boundary_remain_readable() { + let dir = folder("gap-quota"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + let mut snapshot = sample(&rec.view().unwrap()); + for _ in 0..MAX_POINTS - 1 { + rec.last = None; + rec.record(&snapshot).unwrap(); + } + snapshot.timestamp += 60_000; + rec.last = None; + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().state, WatchState::Limit); + assert!(rec.view().unwrap().points.len() <= MAX_POINTS + 1); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Limit + ); + rec.action(WatchAction::Delete).unwrap(); + fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/identity.rs b/crates/argus-core/src/watch/identity.rs new file mode 100644 index 00000000..da0ba9d7 --- /dev/null +++ b/crates/argus-core/src/watch/identity.rs @@ -0,0 +1,200 @@ +//! A watched program is identified from the validated process handle, never a UI label. +use super::WatchError; +use crate::util::{OwnedHandle, filetime_ticks, ticks_to_unix_ms}; +use serde::{Deserialize, Serialize}; +use windows::{ + Win32::{ + Foundation::{FILETIME, WAIT_TIMEOUT}, + System::Threading::{ + GetProcessTimes, OpenProcess, PROCESS_NAME_FORMAT, PROCESS_NAME_NATIVE, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, QueryFullProcessImageNameW, + WaitForSingleObject, + }, + }, + core::PWSTR, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProgramIdentity { + /// The native image path avoids conflating two executables with the same basename. + pub native_path: String, + pub display_path: String, +} + +impl ProgramIdentity { + pub fn valid(&self) -> bool { + [&self.native_path, &self.display_path].iter().all(|path| { + !path.is_empty() && path.encode_utf16().count() < 32768 && !path.contains('\0') + }) + } + + /// Exact native identity is deliberately conservative around case-sensitive directories. + pub fn same_program(&self, other: &Self) -> bool { + self.native_path == other.native_path + } +} + +pub(super) struct Instance { + handle: OwnedHandle, +} + +fn error(error: windows::core::Error) -> WatchError { + match error.code().0 as u32 { + 0x80070005 => WatchError::Access, + _ => WatchError::Identity, + } +} + +impl Instance { + pub(super) fn open(pid: u32, created: i64) -> Result { + if pid == 0 || created <= 0 { + return Err(WatchError::Identity); + } + let handle = OwnedHandle( + unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE, + false, + pid, + ) + } + .map_err(error)?, + ); + let (mut birth, mut exited, mut kernel, mut user) = Default::default(); + unsafe { GetProcessTimes(handle.0, &mut birth, &mut exited, &mut kernel, &mut user) } + .map_err(error)?; + let birth: FILETIME = birth; + if ticks_to_unix_ms(filetime_ticks(birth)) != created + || unsafe { WaitForSingleObject(handle.0, 0) } != WAIT_TIMEOUT + { + return Err(WatchError::Identity); + } + Ok(Self { handle }) + } + + pub(super) fn program(&self) -> Result { + fn image(handle: &OwnedHandle, flags: PROCESS_NAME_FORMAT) -> Result { + let mut buffer = vec![0u16; 32768]; + let mut length = buffer.len() as u32; + unsafe { + QueryFullProcessImageNameW(handle.0, flags, PWSTR(buffer.as_mut_ptr()), &mut length) + } + .map_err(error)?; + String::from_utf16(&buffer[..length as usize]).map_err(|_| WatchError::Identity) + } + let identity = ProgramIdentity { + native_path: image(&self.handle, PROCESS_NAME_NATIVE)?, + display_path: image(&self.handle, PROCESS_NAME_FORMAT(0))?, + }; + if !identity.valid() || unsafe { WaitForSingleObject(self.handle.0, 0) } != WAIT_TIMEOUT { + return Err(WatchError::Identity); + } + Ok(identity) + } + + pub(super) fn into_handle(self) -> OwnedHandle { + self.handle + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn names_and_case_sensitive_paths_are_not_program_identity() { + let identity = |path: &str| ProgramIdentity { + native_path: path.into(), + display_path: String::new(), + }; + assert!( + !identity("\\Device\\disk\\one\\same.exe") + .same_program(&identity("\\Device\\disk\\two\\same.exe")) + ); + assert!( + !identity("\\Device\\disk\\Folder\\same.exe") + .same_program(&identity("\\Device\\disk\\folder\\same.exe")) + ); + assert!(Instance::open(std::process::id(), 0).is_err()); + } + + #[test] + #[ignore = "owned hidden child images in two temporary folders; run explicitly"] + fn two_copies_stay_distinct_and_restarting_the_same_copy_keeps_program_identity() { + use std::{ + os::windows::{io::AsRawHandle, process::CommandExt}, + process::{Child, Command, Stdio}, + }; + use windows::Win32::Foundation::HANDLE; + fn birth(child: &Child) -> i64 { + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(child.as_raw_handle()), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + } + .unwrap(); + ticks_to_unix_ms(filetime_ticks(created)) + } + fn start(path: &std::path::Path) -> Child { + Command::new(path) + .args(["--exact", "process::tests::liveness_child", "--ignored"]) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap() + } + fn exit(mut child: Child) { + drop(child.stdin.take()); + assert!(child.wait().unwrap().success()); + } + let suffix = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = std::env::temp_dir().join(format!( + "argus-program-identity-{}-{suffix}", + std::process::id() + )); + std::fs::create_dir(&dir).unwrap(); + for name in ["one", "two"] { + std::fs::create_dir(dir.join(name)).unwrap(); + std::fs::copy( + std::env::current_exe().unwrap(), + dir.join(name).join("same.exe"), + ) + .unwrap(); + } + let one = dir.join("one/same.exe"); + let two = dir.join("two/same.exe"); + let a = start(&one); + let b = start(&two); + let first = Instance::open(a.id(), birth(&a)).unwrap(); + let second = Instance::open(b.id(), birth(&b)).unwrap(); + let a_program = first.program().unwrap(); + assert!(!a_program.same_program(&second.program().unwrap())); + let first_pid = a.id(); + exit(a); + let again = start(&one); + assert_ne!(again.id(), first_pid); + let restarted = Instance::open(again.id(), birth(&again)).unwrap(); + assert!(a_program.same_program(&restarted.program().unwrap())); + assert!(Instance::open(again.id(), birth(&again) + 1000).is_err()); + exit(again); + exit(b); + drop((first, second, restarted)); + for path in [&one, &two] { + std::fs::remove_file(path).unwrap(); + } + for name in ["one", "two"] { + std::fs::remove_dir(dir.join(name)).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/program.rs b/crates/argus-core/src/watch/program.rs new file mode 100644 index 00000000..f8ec743f --- /dev/null +++ b/crates/argus-core/src/watch/program.rs @@ -0,0 +1,695 @@ +//! Opt-in observation of future instances, with one validated handle per live instance. +use super::{ + SAMPLE_MS, WatchError, WatchMode, WatchPoint, WatchRun, WatchState, WatchView, + identity::Instance, + store::{self, Metadata, Store}, +}; +use crate::{Snapshot, util::OwnedHandle}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + path::Path, + time::{Duration, Instant}, +}; +use windows::Win32::{ + Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}, + System::Threading::WaitForSingleObject, +}; + +type Key = (u32, i64); +const MAX_ACTIVE: usize = 512; +const PREVIEW_POINTS: usize = 1000; +const PREVIEW_RUNS: usize = 256; + +pub(super) struct ProgramWatch { + store: Store, + handles: HashMap, + seen: HashSet, + unconfirmed: HashMap, + selected: Option, + before: Option, + run_offset: usize, + active: bool, + state: WatchState, + last: Option, + last_ts: Option, +} + +impl ProgramWatch { + pub fn start(dir: &Path, pid: u32, created: i64, name: String) -> Result { + let instance = Instance::open(pid, created)?; + let program = instance.program()?; + std::fs::create_dir_all(dir).map_err(|_| WatchError::Storage)?; + let store = Store::create(&dir.join(store::FILE_NAME), Metadata { program, name })?; + Ok(Self { + store, + handles: HashMap::from([((pid, created), instance.into_handle())]), + seen: HashSet::from([(pid, created)]), + unconfirmed: HashMap::new(), + selected: Some((pid, created)), + before: None, + run_offset: 0, + active: true, + state: WatchState::Recording, + last: None, + last_ts: None, + }) + } + + pub fn open(dir: &Path) -> Result { + let store = Store::open(&dir.join(store::FILE_NAME), super::now_ms())?; + // Restarting Argus never silently resumes an observation. + let state = match store.entries.back().map(|e| e.point.state) { + Some(WatchState::Stopped) => WatchState::Stopped, + Some(WatchState::Limit) => WatchState::Limit, + _ => WatchState::Interrupted, + }; + Ok(Self { + store, + handles: HashMap::new(), + seen: HashSet::new(), + unconfirmed: HashMap::new(), + selected: None, + before: None, + run_offset: 0, + active: false, + state, + last: None, + last_ts: None, + }) + } + + pub fn select(&mut self, pid: u32, created: i64) -> Result<(), WatchError> { + if !self.handles.contains_key(&(pid, created)) + && !self + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == (pid, created)) + { + return Err(WatchError::Missing); + } + self.selected = Some((pid, created)); + self.before = None; + Ok(()) + } + + pub fn page(&mut self, before: Option) -> Result<(), WatchError> { + if let Some(before) = before { + let view = self.view(); + if !self + .store + .entries + .iter() + .any(|e| e.seq < before && (e.pid, e.created) == (view.pid, view.create_time)) + { + return Err(WatchError::Missing); + } + } + self.before = before; + Ok(()) + } + + pub fn runs_page(&mut self, offset: usize) { + self.run_offset = offset.min(store::CAPACITY - 1); + } + + fn terminal(&mut self, key: Key, state: WatchState, ts: i64) -> Result<(), WatchError> { + self.store.push( + key.0, + key.1, + WatchPoint { + ts, + memory: None, + commit: None, + state, + }, + ) + } + + pub fn stop(&mut self, state: WatchState, ts: i64) -> Result<(), WatchError> { + self.active = false; + self.state = state; + let keys: Vec<_> = self.handles.keys().copied().collect(); + self.handles.clear(); + self.unconfirmed.clear(); + let ts = ts.max(self.last_ts.unwrap_or(ts)); + for key in keys { + self.terminal(key, state, ts)?; + } + // Preserve a durable stop marker even while waiting between launches. + if let Some(entry) = self.store.entries.back() + && entry.point.state != state + { + self.terminal((entry.pid, entry.created), state, ts)?; + } + self.store.flush() + } + + pub fn record(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if !self.active { + return self.store.prune(snapshot.timestamp); + } + let result = self.sample(snapshot); + if result.is_err() { + self.handles.clear(); + self.unconfirmed.clear(); + self.active = false; + self.state = WatchState::Interrupted; + } + result + } + + fn sample(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if self.last_ts.is_some_and(|ts| snapshot.timestamp < ts) { + return self.stop(WatchState::Interrupted, self.last_ts.unwrap()); + } + let present: HashSet<_> = snapshot + .processes + .iter() + .map(|row| (row.pid, row.create_time)) + .collect(); + self.seen + .retain(|key| present.contains(key) || self.handles.contains_key(key)); + self.unconfirmed.retain(|key, attempted| { + if !present.contains(key) { + return false; + } + if attempted.elapsed() >= Duration::from_secs(60) { + self.seen.remove(key); + return false; + } + true + }); + let basename = self + .store + .meta + .program + .display_path + .rsplit(['\\', '/']) + .next() + .unwrap_or(""); + for row in &snapshot.processes { + let key = (row.pid, row.create_time); + // The basename only reduces queries. Final identity always comes from the validated handle. + if row.create_time <= 0 + || !row.name.eq_ignore_ascii_case(basename) + || !self.seen.insert(key) + { + continue; + } + let Ok(instance) = Instance::open(row.pid, row.create_time) else { + self.unconfirmed.insert(key, Instant::now()); + continue; + }; + let Ok(identity) = instance.program() else { + self.unconfirmed.insert(key, Instant::now()); + continue; + }; + if !self.store.meta.program.same_program(&identity) { + continue; + } + if self.handles.len() == MAX_ACTIVE { + return self.stop(WatchState::Limit, snapshot.timestamp); + } + self.handles.insert(key, instance.into_handle()); + } + let terminal: Vec<_> = self + .handles + .iter() + .filter_map( + |(key, handle)| match unsafe { WaitForSingleObject(handle.0, 0) } { + WAIT_TIMEOUT => None, + WAIT_OBJECT_0 => Some((*key, WatchState::Exited)), + _ => Some((*key, WatchState::Interrupted)), + }, + ) + .collect(); + for (key, state) in terminal { + self.terminal(key, state, snapshot.timestamp)?; + self.handles.remove(&key); + } + if self + .last + .is_some_and(|last| last.elapsed() < Duration::from_millis(SAMPLE_MS as u64)) + { + return Ok(()); + } + if let Some(previous) = self.last_ts + && snapshot.timestamp.saturating_sub(previous) > SAMPLE_MS * 2 + { + let keys: Vec<_> = self.handles.keys().copied().collect(); + // Terminal records may already have this snapshot's timestamp; keep sequence time monotonic. + let gap_ts = self.store.entries.back().map_or(previous + SAMPLE_MS, |e| { + e.point.ts.max(previous + SAMPLE_MS) + }); + for key in keys { + self.terminal(key, WatchState::Gap, gap_ts)?; + } + } + let rows: HashMap<_, _> = snapshot + .processes + .iter() + .map(|p| ((p.pid, p.create_time), p)) + .collect(); + for key in self.handles.keys() { + let row = rows + .get(key) + .filter(|p| !p.stale && !p.sample_reused && !p.counters_pending); + self.store.push( + key.0, + key.1, + WatchPoint { + ts: snapshot.timestamp, + memory: row.map(|p| p.private_ws), + commit: row.map(|p| p.commit), + state: if row.is_some() { + WatchState::Recording + } else { + WatchState::Gap + }, + }, + )?; + } + self.store.prune(snapshot.timestamp)?; + self.store.flush()?; + self.last = Some(Instant::now()); + self.last_ts = Some(snapshot.timestamp); + Ok(()) + } + + pub fn view(&self) -> WatchView { + let mut runs: BTreeMap = BTreeMap::new(); + for entry in &self.store.entries { + let run = runs.entry((entry.pid, entry.created)).or_insert(WatchRun { + pid: entry.pid, + create_time: entry.created, + first_ts: entry.point.ts, + last_ts: entry.point.ts, + points: 0, + state: WatchState::Interrupted, + }); + run.last_ts = entry.point.ts; + run.points += 1; + run.state = if !self.active + && matches!(entry.point.state, WatchState::Recording | WatchState::Gap) + { + WatchState::Interrupted + } else { + entry.point.state + }; + } + for key in self.handles.keys() { + runs.entry(*key).or_insert(WatchRun { + pid: key.0, + create_time: key.1, + first_ts: 0, + last_ts: 0, + points: 0, + state: WatchState::Recording, + }); + } + let key = self + .selected + .filter(|key| runs.contains_key(key) || self.handles.contains_key(key)) + .or_else(|| { + self.store + .entries + .back() + .map(|entry| (entry.pid, entry.created)) + }) + .or(self.selected) + .unwrap_or((0, 0)); + let mut entries: Vec<_> = self + .store + .entries + .iter() + .rev() + .filter(|entry| { + (entry.pid, entry.created) == key + && self.before.is_none_or(|before| entry.seq < before) + }) + .take(PREVIEW_POINTS) + .collect(); + entries.reverse(); + let first_sequence = entries.first().map(|entry| entry.seq); + let has_earlier = first_sequence.is_some_and(|seq| { + self.store + .entries + .iter() + .any(|e| e.seq < seq && (e.pid, e.created) == key) + }); + let mut points: Vec = Vec::new(); + for entry in entries { + if let Some(previous) = points.last() + && entry.point.ts.saturating_sub(previous.ts) > SAMPLE_MS * 2 + && previous.memory.is_some() + { + points.push(WatchPoint { + ts: previous.ts + SAMPLE_MS, + memory: None, + commit: None, + state: WatchState::Gap, + }); + } + points.push(entry.point.clone()); + } + let mut runs: Vec<_> = runs.into_values().collect(); + runs.sort_unstable_by_key(|run| (run.create_time, run.pid)); + let total_runs = runs.len(); + let selected_run = runs + .iter() + .find(|run| (run.pid, run.create_time) == key) + .cloned(); + let run_offset = self.run_offset.min(total_runs.saturating_sub(1)); + let end = total_runs - run_offset; + let start = end.saturating_sub(PREVIEW_RUNS); + let runs = runs[start..end].to_vec(); + WatchView { + version: 2, + pid: key.0, + create_time: key.1, + name: self.store.meta.name.clone(), + program: Some(self.store.meta.program.clone()), + mode: WatchMode::Program, + state: self.state, + points, + runs, + total_runs, + total_points: selected_run.map_or(0, |run| run.points), + damaged: self.store.damaged, + first_sequence, + has_earlier, + has_later: self.before.is_some(), + run_offset, + live_runs: self.handles.len(), + unconfirmed: self.unconfirmed.len(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Collector, + meta::MetaStore, + util::{filetime_ticks, ticks_to_unix_ms}, + }; + use std::{ + os::windows::{io::AsRawHandle, process::CommandExt}, + process::{Child, Command, Stdio}, + }; + use windows::Win32::{Foundation::HANDLE, System::Threading::GetProcessTimes}; + + #[test] + fn pages_keep_older_points_and_launches_accessible_and_clock_reversal_interrupts() { + let dir = std::env::temp_dir().join(format!("argus-watch-pages-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let mut store = Store::create( + &dir.join(store::FILE_NAME), + Metadata { + name: "same.exe".into(), + program: super::super::ProgramIdentity { + native_path: "\\Device\\disk\\same.exe".into(), + display_path: "C:\\same.exe".into(), + }, + }, + ) + .unwrap(); + let start = super::super::now_ms() - 10_000_000; + for i in 0..2001 { + store + .push( + 17, + 100, + WatchPoint { + ts: start + i * SAMPLE_MS, + memory: Some(i as u64), + commit: Some(0), + state: WatchState::Recording, + }, + ) + .unwrap(); + } + for pid in 1000..1300 { + store + .push( + pid, + i64::from(pid), + WatchPoint { + ts: start + 2000 * SAMPLE_MS, + memory: Some(0), + commit: Some(0), + state: WatchState::Recording, + }, + ) + .unwrap(); + } + store.flush().unwrap(); + drop(store); + let mut watch = ProgramWatch::open(&dir).unwrap(); + watch.select(17, 100).unwrap(); + let view = watch.view(); + assert_eq!(view.total_runs, 301); + assert_eq!(view.runs.len(), 256); + assert_eq!(view.total_points, 2001); + assert_eq!(view.points.first().unwrap().memory, Some(1001)); + assert!(view.has_earlier); + watch.page(view.first_sequence).unwrap(); + let view = watch.view(); + assert_eq!(view.points.first().unwrap().memory, Some(1)); + assert!(view.has_earlier && view.has_later); + watch.page(view.first_sequence).unwrap(); + assert_eq!(watch.view().points.first().unwrap().memory, Some(0)); + assert!(!watch.view().has_earlier); + watch.page(None).unwrap(); + assert!(!watch.view().has_later); + watch.runs_page(256); + assert_eq!(watch.view().runs.len(), 45); + assert_eq!(watch.view().runs[0].pid, 17); + watch.runs_page(usize::MAX); + assert_eq!(watch.view().runs.len(), 1); + watch.active = true; + watch.state = WatchState::Recording; + let unconfirmed = Snapshot { + seq: 1, + timestamp: start + 2000 * SAMPLE_MS, + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: vec![crate::ProcessRow { + pid: std::process::id(), + create_time: 1, + name: "same.exe".into(), + ..Default::default() + }], + }; + watch.record(&unconfirmed).unwrap(); + assert_eq!(watch.view().unconfirmed, 1); + assert!(watch.handles.is_empty()); + assert!(watch.view().points.iter().all(|p| p.memory.is_some())); + watch.last_ts = Some(start + 2000 * SAMPLE_MS); + let snapshot = Snapshot { + seq: 1, + timestamp: start, + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: Vec::new(), + }; + watch.record(&snapshot).unwrap(); + assert!(!watch.active); + assert_eq!(watch.state, WatchState::Interrupted); + drop(watch); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + std::fs::remove_dir(dir).unwrap(); + } + + struct Helper(Child); + impl Helper { + fn spawn(path: &Path) -> Self { + Self( + Command::new(path) + .args(["--exact", "process::tests::liveness_child", "--ignored"]) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(), + ) + } + fn key(&self) -> Key { + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(self.0.as_raw_handle()), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + } + .unwrap(); + (self.0.id(), ticks_to_unix_ms(filetime_ticks(created))) + } + } + impl Drop for Helper { + fn drop(&mut self) { + drop(self.0.stdin.take()); + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if self.0.try_wait().unwrap().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + #[test] + #[ignore = "100 owned hidden idle helpers, real collector and two image folders; run explicitly"] + fn real_idle_instances_restart_and_same_name_other_folder_remain_separate() { + let dir = + std::env::temp_dir().join(format!("argus-program-watch-real-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + for folder in ["one", "two"] { + std::fs::create_dir(dir.join(folder)).unwrap(); + std::fs::copy( + std::env::current_exe().unwrap(), + dir.join(folder).join("same.exe"), + ) + .unwrap(); + } + let one = dir.join("one/same.exe"); + let two = dir.join("two/same.exe"); + let mut helpers: Vec<_> = (0..100).map(|_| Helper::spawn(&one)).collect(); + let other = Helper::spawn(&two); + let seed = helpers[0].key(); + let mut watch = + ProgramWatch::start(&dir, seed.0, seed.1, "UI label is not an identity".into()) + .unwrap(); + let mut collector = Collector::new(MetaStore::new()); + let deadline = Instant::now() + Duration::from_secs(15); + let mut max_record_us = 0; + let mut max_view_us = 0; + loop { + let snapshot = collector.sample(); + watch.last = None; + let started = Instant::now(); + watch.record(&snapshot).unwrap(); + max_record_us = max_record_us.max(started.elapsed().as_micros()); + let started = Instant::now(); + let view = watch.view(); + max_view_us = max_view_us.max(started.elapsed().as_micros()); + let measured = view + .runs + .iter() + .filter(|run| { + watch.store.entries.iter().any(|e| { + (e.pid, e.created) == (run.pid, run.create_time) && e.point.memory.is_some() + }) + }) + .count(); + if measured == 100 { + break; + } + assert!( + Instant::now() < deadline, + "not all 100 idle helpers received real measurements" + ); + std::thread::sleep(Duration::from_millis(150)); + } + assert_eq!(watch.handles.len(), 100); + assert!(!watch.handles.contains_key(&other.key())); + assert_eq!(watch.view().total_runs, 100); + // Removing one instance never reuses its curve for the next launch. + drop(helpers.remove(0)); + watch.record(&collector.sample()).unwrap(); + assert!( + watch + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == seed && e.point.state == WatchState::Exited) + ); + helpers.push(Helper::spawn(&one)); + let restarted = helpers.last().unwrap().key(); + assert_ne!(seed, restarted); + let deadline = Instant::now() + Duration::from_secs(10); + while !watch + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == restarted && e.point.memory.is_some()) + { + watch.last = None; + watch.record(&collector.sample()).unwrap(); + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(150)); + } + assert_eq!(watch.view().total_runs, 101); + if let Some(path) = std::env::var_os("ARGUS_TEST_PROGRAM_WATCH_OUTPUT") { + std::fs::write(path, serde_json::to_vec_pretty(&watch.view()).unwrap()).unwrap(); + } + watch.select(seed.0, seed.1).unwrap(); + assert_eq!( + watch.view().points.last().unwrap().state, + WatchState::Exited + ); + watch.select(restarted.0, restarted.1).unwrap(); + assert!( + watch + .view() + .points + .iter() + .all(|p| p.state != WatchState::Exited) + ); + assert!(matches!( + watch.select(seed.0, seed.1 + 1), + Err(WatchError::Missing) + )); + // A delayed observation is explicitly broken; old readings are never filled forward. + let mut snapshot = collector.sample(); + snapshot.timestamp = watch.last_ts.unwrap() + 3 * SAMPLE_MS; + watch.last = None; + watch.record(&snapshot).unwrap(); + assert!( + watch + .view() + .points + .iter() + .any(|p| p.state == WatchState::Gap && p.memory.is_none()) + ); + watch.stop(WatchState::Stopped, snapshot.timestamp).unwrap(); + let saved = watch.view().points.len(); + watch.record(&snapshot).unwrap(); + assert_eq!(watch.view().points.len(), saved); + assert!(watch.handles.is_empty()); + println!( + "owned_idle=100 runs=101 other_folder_attached=0 max_record_us={max_record_us} max_view_us={max_view_us} bytes={}", + std::fs::metadata(dir.join(store::FILE_NAME)).unwrap().len() + ); + drop(watch); + let mut reopened = ProgramWatch::open(&dir).unwrap(); + assert!(!reopened.active); + assert_eq!(reopened.state, WatchState::Stopped); + reopened.select(seed.0, seed.1).unwrap(); + assert_eq!( + reopened.view().points.last().unwrap().state, + WatchState::Exited + ); + drop(reopened); + drop((helpers, other, collector)); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + for folder in ["one", "two"] { + std::fs::remove_file(dir.join(folder).join("same.exe")).unwrap(); + std::fs::remove_dir(dir.join(folder)).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/store.rs b/crates/argus-core/src/watch/store.rs new file mode 100644 index 00000000..520d3996 --- /dev/null +++ b/crates/argus-core/src/watch/store.rs @@ -0,0 +1,424 @@ +//! Fixed-size rolling records. Legacy single-run JSONL is never rewritten. +use super::{ProgramIdentity, WatchError, WatchPoint, WatchState}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::VecDeque, + fs::{File, OpenOptions}, + io::{Read, Seek, SeekFrom, Write}, + path::Path, +}; + +pub(super) const FILE_NAME: &str = "program-watch.v1.bin"; +const MAGIC: &[u8; 8] = b"ARGWCH01"; +const HEADER: u64 = 1 << 20; +const RECORD: u64 = 64; +pub const CAPACITY: usize = 131072; +pub const RETENTION_MS: i64 = 7 * 24 * 60 * 60 * 1000; +pub const MAX_BYTES: u64 = HEADER + CAPACITY as u64 * RECORD; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Metadata { + pub program: ProgramIdentity, + pub name: String, +} + +#[derive(Clone, Debug)] +pub(super) struct Entry { + pub seq: u64, + pub pid: u32, + pub created: i64, + pub point: WatchPoint, +} + +pub(super) struct Store { + file: File, + pub meta: Metadata, + pub entries: VecDeque, + next: u64, + pub damaged: bool, +} + +// Integrity detection for torn records, not authentication of local files. +fn checksum(bytes: &[u8]) -> u32 { + bytes.iter().fold(2166136261, |h, b| { + (h ^ u32::from(*b)).wrapping_mul(16777619) + }) +} + +fn state_byte(state: WatchState) -> u8 { + match state { + WatchState::Recording => 1, + WatchState::Gap => 2, + WatchState::Exited => 3, + WatchState::Stopped => 4, + WatchState::Interrupted => 5, + WatchState::Limit => 6, + } +} + +impl Entry { + fn encode(&self) -> [u8; RECORD as usize] { + let mut bytes = [0; RECORD as usize]; + bytes[0..8].copy_from_slice(&self.seq.to_le_bytes()); + bytes[8..16].copy_from_slice(&self.point.ts.to_le_bytes()); + bytes[16..20].copy_from_slice(&self.pid.to_le_bytes()); + bytes[20..28].copy_from_slice(&self.created.to_le_bytes()); + bytes[28..36].copy_from_slice(&self.point.memory.unwrap_or_default().to_le_bytes()); + bytes[36..44].copy_from_slice(&self.point.commit.unwrap_or_default().to_le_bytes()); + bytes[44] = state_byte(self.point.state); + bytes[45] = + u8::from(self.point.memory.is_some()) | (u8::from(self.point.commit.is_some()) << 1); + let sum = checksum(&bytes[..52]); + bytes[52..56].copy_from_slice(&sum.to_le_bytes()); + bytes[56..64].copy_from_slice(&(!self.seq).to_le_bytes()); + bytes + } + + fn decode(bytes: &[u8; RECORD as usize], slot: usize) -> Option { + let seq = u64::from_le_bytes(bytes[0..8].try_into().ok()?); + let ts = i64::from_le_bytes(bytes[8..16].try_into().ok()?); + let pid = u32::from_le_bytes(bytes[16..20].try_into().ok()?); + let created = i64::from_le_bytes(bytes[20..28].try_into().ok()?); + if seq == 0 + || (seq - 1) % CAPACITY as u64 != slot as u64 + || !seq != u64::from_le_bytes(bytes[56..64].try_into().ok()?) + || checksum(&bytes[..52]) != u32::from_le_bytes(bytes[52..56].try_into().ok()?) + || pid == 0 + || created <= 0 + || ts <= 0 + || bytes[45] & !3 != 0 + || bytes[46..52] != [0; 6] + { + return None; + } + let state = match bytes[44] { + 1 => WatchState::Recording, + 2 => WatchState::Gap, + 3 => WatchState::Exited, + 4 => WatchState::Stopped, + 5 => WatchState::Interrupted, + 6 => WatchState::Limit, + _ => return None, + }; + if state != WatchState::Recording && bytes[45] != 0 { + return None; + } + Some(Self { + seq, + pid, + created, + point: WatchPoint { + ts, + state, + memory: (bytes[45] & 1 != 0) + .then(|| u64::from_le_bytes(bytes[28..36].try_into().unwrap())), + commit: (bytes[45] & 2 != 0) + .then(|| u64::from_le_bytes(bytes[36..44].try_into().unwrap())), + }, + }) + } +} + +impl Store { + pub fn create(path: &Path, meta: Metadata) -> Result { + let encoded = serde_json::to_vec(&meta).map_err(|_| WatchError::Invalid)?; + if !meta.program.valid() + || meta.name.is_empty() + || meta.name.len() > 1024 + || encoded.len() as u64 > HEADER - 16 + { + return Err(WatchError::Invalid); + } + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(path) + .map_err(|_| WatchError::Storage)?; + let result = (|| -> std::io::Result<()> { + file.write_all(MAGIC)?; + file.write_all(&(encoded.len() as u32).to_le_bytes())?; + file.write_all(&checksum(&encoded).to_le_bytes())?; + file.write_all(&encoded)?; + file.set_len(HEADER)?; + file.flush() + })(); + if result.is_err() { + drop(file); + let _ = std::fs::remove_file(path); + return Err(WatchError::Storage); + } + Ok(Self { + file, + meta, + entries: VecDeque::new(), + next: 1, + damaged: false, + }) + } + + pub fn open(path: &Path, now: i64) -> Result { + let mut file = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .map_err(|_| WatchError::Storage)?; + let size = file.metadata().map_err(|_| WatchError::Storage)?.len(); + if !(HEADER..=MAX_BYTES).contains(&size) { + return Err(WatchError::Invalid); + } + let mut header = [0u8; 16]; + file.read_exact(&mut header) + .map_err(|_| WatchError::Storage)?; + let len = u32::from_le_bytes(header[8..12].try_into().unwrap()) as usize; + if &header[..8] != MAGIC || len as u64 > HEADER - 16 { + return Err(WatchError::Invalid); + } + let mut data = vec![0; len]; + file.read_exact(&mut data) + .map_err(|_| WatchError::Storage)?; + if checksum(&data) != u32::from_le_bytes(header[12..16].try_into().unwrap()) { + return Err(WatchError::Invalid); + } + let meta: Metadata = serde_json::from_slice(&data).map_err(|_| WatchError::Invalid)?; + if !meta.program.valid() || meta.name.is_empty() || meta.name.len() > 1024 { + return Err(WatchError::Invalid); + } + file.seek(SeekFrom::Start(HEADER)) + .map_err(|_| WatchError::Storage)?; + let mut raw = Vec::new(); + file.read_to_end(&mut raw) + .map_err(|_| WatchError::Storage)?; + let mut entries = Vec::new(); + let mut damaged = raw.len() % RECORD as usize != 0; + let mut invalid_slots = Vec::new(); + for (slot, bytes) in raw.as_chunks::<{ RECORD as usize }>().0.iter().enumerate() { + if bytes.iter().all(|b| *b == 0) { + continue; + } + match Entry::decode(bytes, slot) { + Some(entry) => entries.push(entry), + None => { + damaged = true; + invalid_slots.push(slot); + } + } + } + entries.sort_unstable_by_key(|entry| entry.seq); + // Only the newest ring generation can survive a partial overwrite. + let next = entries + .last() + .map_or(Some(1), |entry| entry.seq.checked_add(1)) + .ok_or(WatchError::Invalid)?; + entries.retain(|entry| { + let keep = next - entry.seq <= CAPACITY as u64; + if !keep { + invalid_slots.push(((entry.seq - 1) % CAPACITY as u64) as usize); + } + keep + }); + if entries.windows(2).any(|p| p[0].point.ts > p[1].point.ts) { + return Err(WatchError::Invalid); + } + // Remove unreadable values as well: expiry must not leave damaged payloads indefinitely. + for slot in invalid_slots { + file.seek(SeekFrom::Start(HEADER + slot as u64 * RECORD)) + .and_then(|_| file.write_all(&[0; RECORD as usize])) + .map_err(|_| WatchError::Storage)?; + } + if raw.len() % RECORD as usize != 0 { + file.set_len(HEADER + (raw.len() as u64 / RECORD) * RECORD) + .map_err(|_| WatchError::Storage)?; + } + let mut store = Self { + file, + meta, + entries: entries.into(), + next, + damaged, + }; + store.prune(now)?; + Ok(store) + } + + fn offset(seq: u64) -> u64 { + HEADER + ((seq - 1) % CAPACITY as u64) * RECORD + } + + pub fn prune(&mut self, now: i64) -> Result<(), WatchError> { + let cutoff = now.saturating_sub(RETENTION_MS); + while self + .entries + .front() + .is_some_and(|entry| entry.point.ts < cutoff) + { + let entry = self.entries.front().unwrap(); + self.file + .seek(SeekFrom::Start(Self::offset(entry.seq))) + .and_then(|_| self.file.write_all(&[0; RECORD as usize])) + .map_err(|_| WatchError::Storage)?; + self.entries.pop_front(); + } + self.file.flush().map_err(|_| WatchError::Storage) + } + + pub fn push(&mut self, pid: u32, created: i64, point: WatchPoint) -> Result<(), WatchError> { + if pid == 0 + || created <= 0 + || point.ts <= 0 + || self + .entries + .back() + .is_some_and(|last| point.ts < last.point.ts) + || (point.state != WatchState::Recording + && (point.memory.is_some() || point.commit.is_some())) + { + return Err(WatchError::Invalid); + } + let next = self.next.checked_add(1).ok_or(WatchError::Invalid)?; + self.prune(point.ts)?; + let entry = Entry { + seq: self.next, + pid, + created, + point, + }; + self.file + .seek(SeekFrom::Start(Self::offset(entry.seq))) + .and_then(|_| self.file.write_all(&entry.encode())) + .map_err(|_| WatchError::Storage)?; + self.next = next; + while self + .entries + .front() + .is_some_and(|old| next - old.seq > CAPACITY as u64) + { + self.entries.pop_front(); + } + self.entries.push_back(entry); + Ok(()) + } + + pub fn flush(&mut self) -> Result<(), WatchError> { + self.file.flush().map_err(|_| WatchError::Storage) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn meta() -> Metadata { + Metadata { + name: "same.exe".into(), + program: ProgramIdentity { + native_path: "\\Device\\disk\\one\\same.exe".into(), + display_path: "C:\\one\\same.exe".into(), + }, + } + } + fn point(ts: i64, value: u64) -> WatchPoint { + WatchPoint { + ts, + memory: Some(value), + commit: Some(value + 1), + state: WatchState::Recording, + } + } + fn path(tag: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!( + "argus-watch-store-{}-{tag}.bin", + std::process::id() + )) + } + + #[test] + fn rolling_quota_and_runs_survive_reopen_without_splicing() { + let path = path("quota"); + let start = super::super::now_ms(); + let began = std::time::Instant::now(); + let mut store = Store::create(&path, meta()).unwrap(); + for i in 0..CAPACITY + 3 { + store + .push( + if i % 2 == 0 { 17 } else { 18 }, + 100 + (i % 2) as i64, + point(start + i as i64, i as u64), + ) + .unwrap(); + } + store.flush().unwrap(); + assert_eq!(store.entries.len(), CAPACITY); + assert_eq!(store.file.metadata().unwrap().len(), MAX_BYTES); + let writer_us = began.elapsed().as_micros(); + drop(store); + let began = std::time::Instant::now(); + let store = Store::open(&path, start + CAPACITY as i64).unwrap(); + println!( + "ring_records={} bytes={} writer_us={writer_us} reopen_us={}", + CAPACITY, + MAX_BYTES, + began.elapsed().as_micros() + ); + assert_eq!(store.entries.len(), CAPACITY); + assert_eq!(store.entries.front().unwrap().point.memory, Some(3)); + assert_eq!( + store.entries.back().unwrap().point.memory, + Some((CAPACITY + 2) as u64) + ); + assert_eq!(store.entries.front().unwrap().pid, 18); + assert!(!store.damaged); + drop(store); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn expiry_erases_values_and_torn_record_does_not_become_a_measurement() { + let path = path("expiry"); + let start = super::super::now_ms(); + let mut store = Store::create(&path, meta()).unwrap(); + store.push(17, 100, point(start, 12345)).unwrap(); + store + .push(17, 100, point(start + RETENTION_MS + 1, 23456)) + .unwrap(); + assert_eq!(store.entries.len(), 1); + let mut raw = std::fs::read(&path).unwrap(); + assert!( + raw[HEADER as usize..HEADER as usize + RECORD as usize] + .iter() + .all(|b| *b == 0) + ); + drop(store); + raw[HEADER as usize + RECORD as usize + 30] ^= 1; + std::fs::write(&path, raw).unwrap(); + let store = Store::open(&path, start + RETENTION_MS + 1).unwrap(); + assert!(store.entries.is_empty()); + assert!(store.damaged); + drop(store); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn unknown_header_and_oversize_are_rejected_without_truncation() { + let path = path("invalid"); + let store = Store::create(&path, meta()).unwrap(); + drop(store); + let mut raw = std::fs::read(&path).unwrap(); + raw[0] ^= 1; + std::fs::write(&path, &raw).unwrap(); + assert!(matches!( + Store::open(&path, super::super::now_ms()), + Err(WatchError::Invalid) + )); + assert_eq!(std::fs::read(&path).unwrap(), raw); + let file = OpenOptions::new().write(true).open(&path).unwrap(); + file.set_len(MAX_BYTES + 1).unwrap(); + drop(file); + assert!(matches!( + Store::open(&path, super::super::now_ms()), + Err(WatchError::Invalid) + )); + assert_eq!(std::fs::metadata(&path).unwrap().len(), MAX_BYTES + 1); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/docs/guide/README.md b/docs/guide/README.md index af9f6c43..63234e68 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -199,6 +199,22 @@ Argus 运行时每 5 秒记录一帧:整机的 CPU(这 5 秒内各次采样 从 0.2.0 升级且需要保留旧历史时,请先退出 Argus 并备份 `history` 目录,旧版可读取备份。新版从新的记录格式开始显示历史。 +### 观察程序与运行实例 + +新的单实例观察文件使用 JSONL v2,在可查询时保存由同一已验证进程句柄取得的本机映像路径与显示路径,作为程序身份;界面传入的名称仅作标签。旧 v1 记录继续读取,程序路径保持未知,不从同名进程补全,也不重写旧文件。此元数据保存在本地观察文件中,单次运行的观察仍以 PID、创建时间及保留的句柄为准。 + +在进程列表中选中一个运行实例,在详细信息面板选择“观察此运行实例”或“观察后续运行”。记录在“历史”页顶部显示,即使该进程未进入系统历史的排行榜,也会记录其专用工作集与专用提交量。工作集表示当前驻留的私人内存;提交量表示程序获得的私人已提交内存,工作集增长本身不证明内存泄漏。 + +“观察此运行实例”仅限一个由 PID 与创建时间确认的实例,不跟随重启。每条记录最多 1 小时、720 个点及 1 MiB,达到任一上限后停止,保存在历史目录中的 `process-watch.jsonl`。 + +“观察后续运行”从所选实例的已验证句柄读取本机映像路径,记录当前及随后启动的同路径程序;界面名称只作标签,不用于认定程序身份。不同目录的同名 EXE 不合并,路径比较保持大小写敏感目录的区别,不承诺合并路径别名,也不以文件签名或哈希定义二进制版本。每个已确认的实例保留一个只读查询句柄,直到退出;各实例的曲线按 PID 与创建时间分开。新实例的身份暂时无法读取时,显示无法确认的同名实例数,每分钟重试,不拼接到旧实例的数据。程序全部退出后保持等待,直到后续运行、手动停止或达到同时观察 512 个实例的上限。 + +后续运行记录使用独立文件 `program-watch.v1.bin`,最多保留 7 天、131072 个记录点及 9 MiB;先到的上限触发最旧记录清理,时间过期的记录槽位会清零。停止后的数据也按此策略清理,Argus 关闭期间的过期记录在再次打开时清理。记录带序列与完整性校验,损坏记录不会当成读数。实例列表每页最多 256 项,曲线每页最多 1000 个已存点及空缺标记,可分别浏览较早实例、较早点或返回最新记录。 + +两种观察通常每 5 秒保留一个点;后台采样较慢、读数无效或采样中断时显示空缺,不补零。通过同一进程句柄确认退出。系统时钟倒退时中断观察,不把逆序时间拼接进曲线。观察文件与排行榜文件独立,关闭排行榜记录不停止显式选择的观察。 + +“停止记录”保留已有数据;“删除记录”停止观察并删除该条文件。开始另一条记录前需删除已有记录。退出或重启 Argus 不会自动继续旧观察,保留的未完成记录显示为中断。未知格式或损坏的记录也可删除。设置中的历史占用包含观察文件,“清除历史记录”同时停止并删除观察。 + ## 文件占用 单击工具栏上的“查找占用文件的进程”,或者直接把文件、文件夹拖到窗口上,即可查询占用。结果合并两种来源:Restart Manager 查找文件引用和已加载的模块,句柄扫描补充打开的文件、目录及后代,包括把所选文件夹当作当前目录的命令行进程。文件 ID 可识别通过硬链接打开同一文件的情况。 diff --git a/locales/de-DE/history.json b/locales/de-DE/history.json index a488f75c..b8818f8e 100644 --- a/locales/de-DE/history.json +++ b/locales/de-DE/history.json @@ -43,5 +43,47 @@ "noRecordAt": "Keine Aufzeichnung für diesen Zeitpunkt", "earliest": "Frühester Datensatz", "note": "Zeichnet alle 5 Sekunden die Prozesse mit der höchsten CPU-, Arbeitsspeicher-, I/O-, GPU- und Netzwerkauslastung auf. Bei längerem Intervall im minimierten Zustand oder im Infobereich gilt dieses Intervall. Die Daten bleiben 7 Tage erhalten.", - "off": "Die Verlaufsaufzeichnung ist deaktiviert; neue Daten werden nicht aufgezeichnet. Einstellungen öffnen" + "off": "Die Verlaufsaufzeichnung ist deaktiviert; neue Daten werden nicht aufgezeichnet. Einstellungen öffnen", + "watch": { + "title": "Prozessbeobachtung", + "empty": "In den Details eines einzelnen Prozesses „Diese Instanz beobachten“ wählen, um Speicher auch unterhalb der Spitzenliste aufzuzeichnen.", + "start": "Diese Instanz beobachten", + "target": "Beobachtung: {name} (PID {pid})", + "stop": "Aufzeichnung stoppen", + "delete": "Aufzeichnung löschen", + "note": "Nur diese Instanz; bis zu 1 Stunde, 720 Punkte und 1 MiB. Messungen meist alle 5 Sekunden; langsamere Hintergrundabfragen können Lücken lassen. Ein wachsender Arbeitssatz allein belegt kein Speicherleck. Stoppen behält Daten; Löschen stoppt und entfernt diese Aufzeichnung.", + "metric": { + "memory": "Privater Arbeitssatz", + "commit": "Privat zugesicherter Speicher" + }, + "state": { + "recording": "Aufzeichnung läuft", + "gap": "Keine gültige Messung", + "exited": "Diese Instanz wurde beendet", + "stopped": "Aufzeichnung gestoppt", + "interrupted": "Unterbrochen; nicht fortgesetzt", + "limit": "Aufzeichnungsgrenze erreicht" + }, + "error": { + "unavailable": "Der Sampler antwortete nicht rechtzeitig. Ergebnis unbekannt; vor einem erneuten Versuch den Status prüfen.", + "identity": "Die ausgewählte Instanz konnte nicht bestätigt werden. Aktualisieren und erneut versuchen.", + "access": "Die aktuellen Rechte reichen zum Lesen dieser Instanz nicht aus.", + "existing": "Eine Beobachtung existiert bereits. Vor einer neuen die bisherige stoppen und löschen.", + "missing": "Keine Beobachtung vorhanden.", + "storage": "Die Aufzeichnung konnte nicht gelesen oder geschrieben werden. Sie wurde gestoppt.", + "invalid": "Die Aufzeichnung ist beschädigt oder das Format wird nicht unterstützt. Sie kann gelöscht werden." + }, + "startProgram": "Weitere Starts beobachten", + "chooseRun": "Start auswählen", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} Starts angezeigt; {points} gespeicherte Punkte in diesem Start", + "earlier": "Frühere Punkte", + "latest": "Neueste Punkte", + "programNote": "Aktuelle und künftige Starts dieses Abbildpfads werden getrennt erfasst. Bis zu 7 Tage, 131072 Punkte und 9 MiB; beim ersten erreichten Limit werden die ältesten Daten entfernt. Bis zu 512 gleichzeitige Instanzen. Die Liste zeigt die letzten 256 Starts; jede Seite bis zu 1000 gespeicherte Punkte und Lückenmarkierungen. Frühere Punkte bleiben abrufbar. Meist 5 Sekunden Abstand; langsamere Abtastung lässt Lücken. Ein wachsender Arbeitssatz beweist kein Speicherleck. Stoppen behält Daten, Löschen entfernt sie. Ein Neustart von Argus setzt die Aufzeichnung nicht fort.", + "damaged": "Einige Datensätze haben die Integritätsprüfung nicht bestanden; fehlende Intervalle bleiben Lücken.", + "earlierRuns": "Frühere Starts", + "latestRuns": "Neueste Starts", + "waiting": "Warten auf einen weiteren Start", + "unconfirmed": "Identität von {count} gleichnamigen Instanzen nicht bestätigt; erneuter Versuch einmal pro Minute." + } } diff --git a/locales/en-US/history.json b/locales/en-US/history.json index 07ca2574..501e6ca5 100644 --- a/locales/en-US/history.json +++ b/locales/en-US/history.json @@ -43,5 +43,47 @@ "noRecordAt": "No records at this moment", "earliest": "Earliest record", "note": "Records the top processes by CPU, memory, I/O, GPU and network every 5 seconds (or at the minimized or tray refresh rate when that is slower) and keeps them for 7 days.", - "off": "History recording is off; no new data is being recorded. Open Settings" + "off": "History recording is off; no new data is being recorded. Open Settings", + "watch": { + "title": "Process observation", + "empty": "Choose “Watch this instance” in the details of a single process to record memory even below the top list.", + "start": "Watch this instance", + "target": "Watching {name} (PID {pid})", + "stop": "Stop recording", + "delete": "Delete recording", + "note": "This instance only; up to 1 hour, 720 points and 1 MiB. Samples are usually 5 seconds apart; slower background sampling may leave gaps. Working set growth alone does not prove a memory leak. Stop keeps data; Delete stops and removes this recording.", + "metric": { + "memory": "Private working set", + "commit": "Private commit" + }, + "state": { + "recording": "Recording", + "gap": "No valid sample", + "exited": "This instance exited", + "stopped": "Recording stopped", + "interrupted": "Recording interrupted; not resumed", + "limit": "Recording limit reached" + }, + "error": { + "unavailable": "The sampler did not reply in time. The outcome is unknown; check recording status before retrying.", + "identity": "The selected instance could not be confirmed. Refresh and try again.", + "access": "This instance cannot be read with current permissions.", + "existing": "An observation already exists. Stop and delete it before starting another.", + "missing": "No observation exists.", + "storage": "The recording could not be read or written. Recording has stopped.", + "invalid": "The recording is damaged or uses an unsupported format. It can be deleted." + }, + "startProgram": "Watch future launches", + "chooseRun": "Choose a launch", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Showing {shown}/{total} launches; {points} saved points in this launch", + "earlier": "Earlier points", + "latest": "Latest points", + "programNote": "Current and future launches at this image path are recorded separately. Up to 7 days, 131072 points and 9 MiB; the first limit reached removes oldest data. Up to 512 concurrent instances. The list shows the latest 256 launches; each page shows up to 1000 saved points plus gap markers. Earlier points remain browsable. Samples are usually 5 seconds apart; slower sampling leaves gaps. Working set growth does not prove a leak. Stop keeps data; Delete removes it. Restarting Argus does not resume recording.", + "damaged": "Some stored records failed integrity checks; missing intervals remain gaps.", + "earlierRuns": "Earlier launches", + "latestRuns": "Latest launches", + "waiting": "Waiting for another launch", + "unconfirmed": "Could not confirm {count} same-named instances; retrying once per minute." + } } diff --git a/locales/es-ES/history.json b/locales/es-ES/history.json index 865d6c60..dba19eb5 100644 --- a/locales/es-ES/history.json +++ b/locales/es-ES/history.json @@ -45,5 +45,47 @@ "noRecordAt": "No hay registros en este momento", "earliest": "Registro más antiguo", "note": "Registra cada 5 segundos los procesos con mayor uso de CPU, memoria, I/O, GPU y red; si el intervalo al minimizar o permanecer en la bandeja es mayor, utiliza ese intervalo. Conserva los registros durante 7 días.", - "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración" + "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración", + "watch": { + "title": "Observación de proceso", + "empty": "Elija «Observar esta instancia» en los detalles de un solo proceso para registrar memoria fuera de la lista principal.", + "start": "Observar esta instancia", + "target": "Observando {name} (PID {pid})", + "stop": "Detener registro", + "delete": "Eliminar registro", + "note": "Solo esta instancia; hasta 1 hora, 720 puntos y 1 MiB. Muestras normalmente cada 5 segundos; un muestreo más lento puede dejar huecos. El crecimiento del conjunto de trabajo no prueba una fuga. Detener conserva datos; Eliminar detiene y borra este registro.", + "metric": { + "memory": "Conjunto de trabajo privado", + "commit": "Memoria privada comprometida" + }, + "state": { + "recording": "Registrando", + "gap": "Sin muestra válida", + "exited": "Esta instancia terminó", + "stopped": "Registro detenido", + "interrupted": "Registro interrumpido; no reanudado", + "limit": "Límite de registro alcanzado" + }, + "error": { + "unavailable": "El muestreador no respondió a tiempo. Resultado desconocido; compruebe el estado antes de reintentar.", + "identity": "No se pudo confirmar la instancia seleccionada. Actualice y reintente.", + "access": "Los permisos actuales no permiten leer esta instancia.", + "existing": "Ya existe una observación. Deténgala y elimínela antes de iniciar otra.", + "missing": "No existe ninguna observación.", + "storage": "No se pudo leer o escribir el registro. Se ha detenido.", + "invalid": "El registro está dañado o su formato no es compatible. Puede eliminarlo." + }, + "startProgram": "Observar próximos inicios", + "chooseRun": "Elegir un inicio", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Se muestran {shown}/{total} inicios; {points} puntos guardados en este inicio", + "earlier": "Puntos anteriores", + "latest": "Últimos puntos", + "programNote": "Los inicios actuales y futuros de esta ruta de imagen se registran por separado. Hasta 7 días, 131072 puntos y 9 MiB; el primer límite alcanzado elimina los datos más antiguos. Hasta 512 instancias simultáneas. La lista muestra los últimos 256 inicios; cada página hasta 1000 puntos guardados y marcas de huecos. Los puntos anteriores siguen disponibles. Normalmente cada 5 segundos; un muestreo más lento deja huecos. El crecimiento del conjunto de trabajo no demuestra una fuga. Detener conserva los datos; Eliminar los borra. Reiniciar Argus no reanuda la grabación.", + "damaged": "Algunos registros no superaron la comprobación de integridad; los intervalos ausentes siguen siendo huecos.", + "earlierRuns": "Inicios anteriores", + "latestRuns": "Últimos inicios", + "waiting": "Esperando otro inicio", + "unconfirmed": "No se pudieron confirmar {count} instancias con el mismo nombre; se reintenta una vez por minuto." + } } diff --git a/locales/fr-FR/history.json b/locales/fr-FR/history.json index 486dd002..2f836401 100644 --- a/locales/fr-FR/history.json +++ b/locales/fr-FR/history.json @@ -45,5 +45,47 @@ "noRecordAt": "Aucun enregistrement à cet instant", "earliest": "Premier enregistrement", "note": "Enregistre les processus utilisant le plus de CPU, mémoire, I/O, GPU et réseau toutes les 5 secondes, ou selon l’intervalle de la fenêtre réduite ou de la zone de notification s’il est plus long. Les données sont conservées 7 jours.", - "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres" + "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres", + "watch": { + "title": "Observation du processus", + "empty": "Choisir «Observer cette instance» dans les détails d’un seul processus pour enregistrer la mémoire hors du classement.", + "start": "Observer cette instance", + "target": "Observation de {name} (PID {pid})", + "stop": "Arrêter l’enregistrement", + "delete": "Supprimer l’enregistrement", + "note": "Cette instance uniquement ; jusqu’à 1 heure, 720 points et 1 MiB. Mesures généralement toutes les 5 secondes ; un échantillonnage plus lent peut laisser des lacunes. La croissance du jeu de travail ne prouve pas une fuite. Arrêter conserve les données ; Supprimer arrête et efface cet enregistrement.", + "metric": { + "memory": "Jeu de travail privé", + "commit": "Mémoire privée engagée" + }, + "state": { + "recording": "Enregistrement en cours", + "gap": "Aucune mesure valide", + "exited": "Cette instance est terminée", + "stopped": "Enregistrement arrêté", + "interrupted": "Enregistrement interrompu ; non repris", + "limit": "Limite d’enregistrement atteinte" + }, + "error": { + "unavailable": "L’échantillonneur n’a pas répondu à temps. Résultat inconnu ; vérifier l’état avant de réessayer.", + "identity": "L’instance choisie n’a pas pu être confirmée. Actualiser et réessayer.", + "access": "Les autorisations actuelles ne permettent pas de lire cette instance.", + "existing": "Une observation existe déjà. L’arrêter et la supprimer avant d’en commencer une autre.", + "missing": "Aucune observation enregistrée.", + "storage": "Impossible de lire ou d’écrire l’enregistrement. Il est arrêté.", + "invalid": "L’enregistrement est endommagé ou son format n’est pas pris en charge. Il peut être supprimé." + }, + "startProgram": "Observer les prochains lancements", + "chooseRun": "Choisir un lancement", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} lancements affichés ; {points} points enregistrés pour ce lancement", + "earlier": "Points antérieurs", + "latest": "Derniers points", + "programNote": "Les lancements actuels et futurs de ce chemin sont enregistrés séparément. Jusqu’à 7 jours, 131072 points et 9 Mio ; la première limite atteinte supprime les données les plus anciennes. Jusqu’à 512 instances simultanées. La liste affiche les 256 derniers lancements ; chaque page jusqu’à 1000 points enregistrés et des repères de lacunes. Les points antérieurs restent consultables. En général toutes les 5 secondes ; un échantillonnage plus lent laisse des lacunes. La croissance du jeu de travail ne prouve pas une fuite. Arrêter conserve les données ; Supprimer les efface. Redémarrer Argus ne reprend pas l’enregistrement.", + "damaged": "Certains enregistrements ont échoué au contrôle d’intégrité ; les intervalles manquants restent des lacunes.", + "earlierRuns": "Lancements antérieurs", + "latestRuns": "Derniers lancements", + "waiting": "En attente d’un autre lancement", + "unconfirmed": "Identité non confirmée pour {count} instances du même nom ; nouvel essai chaque minute." + } } diff --git a/locales/ja-JP/history.json b/locales/ja-JP/history.json index bc02fec5..51816a36 100644 --- a/locales/ja-JP/history.json +++ b/locales/ja-JP/history.json @@ -41,5 +41,47 @@ "noRecordAt": "この時刻の記録はありません", "earliest": "最も古い記録", "note": "CPU、メモリ、I/O、GPU、ネットワークの使用量が多いプロセスを 5 秒ごとに記録し、7 日間保存します。最小化中や通知領域への常駐中の更新間隔が長い場合は、その間隔で記録します。", - "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く" + "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く", + "watch": { + "title": "プロセスの観測", + "empty": "単一プロセスの詳細で「このインスタンスを観測」を選ぶと、上位リストにない場合もメモリを記録できます。", + "start": "このインスタンスを観測", + "target": "観測:{name}(PID {pid})", + "stop": "記録を停止", + "delete": "記録を削除", + "note": "このインスタンスのみ。最大 1 時間、720 点、1 MiB。通常は 5 秒ごとですが、バックグラウンドの間隔が長いと欠測が生じます。ワーキングセットの増加だけではリークを証明できません。停止はデータを保持し、削除は停止して記録を消去します。", + "metric": { + "memory": "プライベートワーキングセット", + "commit": "プライベートコミット" + }, + "state": { + "recording": "記録中", + "gap": "有効な測定なし", + "exited": "このインスタンスは終了", + "stopped": "記録停止", + "interrupted": "記録中断・自動再開なし", + "limit": "記録上限に到達" + }, + "error": { + "unavailable": "収集処理が時間内に応答しませんでした。結果は不明です。再試行前に記録状態を確認してください。", + "identity": "選択したインスタンスを確認できません。更新して再試行してください。", + "access": "現在の権限ではこのインスタンスを読み取れません。", + "existing": "観測が既に存在します。新しい観測の前に停止して削除してください。", + "missing": "観測記録がありません。", + "storage": "記録を読み書きできませんでした。記録は停止しています。", + "invalid": "記録が破損しているか、未対応の形式です。削除できます。" + }, + "startProgram": "以後の起動も監視", + "chooseRun": "起動を選択", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} 件の起動を表示・選択中の起動に {points} 点を保存", + "earlier": "以前のデータ", + "latest": "最新のデータ", + "programNote": "このイメージパスの現在および以後の起動を個別に記録します。上限は 7 日、131072 点、9 MiB で、先に達した制限に従い古いデータを削除します。同時監視は 512 インスタンスまで。一覧には最新 256 件の起動を表示し、1 ページに最大 1000 点と欠測マーカーを表示します。以前のデータも参照できます。通常は 5 秒間隔で、低速の取得では欠測を残します。ワーキングセットの増加だけではリークを証明できません。停止はデータを保持し、削除は消去します。Argus の再起動後は自動再開しません。", + "damaged": "一部の保存レコードが整合性チェックに失敗しました。不明な区間は欠測のまま表示します。", + "earlierRuns": "以前の起動", + "latestRuns": "最新の起動", + "waiting": "次の起動を待機中", + "unconfirmed": "同名の {count} インスタンスの識別を確認できませんでした。1 分ごとに再試行します。" + } } diff --git a/locales/ru-RU/history.json b/locales/ru-RU/history.json index 376ba8f6..15a2c414 100644 --- a/locales/ru-RU/history.json +++ b/locales/ru-RU/history.json @@ -47,5 +47,47 @@ "noRecordAt": "Для этого момента нет записи", "earliest": "Самая ранняя запись", "note": "Записывает процессы с наибольшей нагрузкой на CPU, память, I/O, GPU и сеть каждые 5 секунд. Если интервал для свёрнутого окна или области уведомлений больше, используется он. Записи хранятся 7 дней.", - "off": "Запись истории отключена; новые данные не записываются. Открыть параметры" + "off": "Запись истории отключена; новые данные не записываются. Открыть параметры", + "watch": { + "title": "Наблюдение за процессом", + "empty": "Выберите «Наблюдать за этим запуском» в подробностях отдельного процесса, чтобы записывать память даже ниже порога топа.", + "start": "Наблюдать за этим запуском", + "target": "Наблюдение: {name} (PID {pid})", + "stop": "Остановить запись", + "delete": "Удалить запись", + "note": "Только этот запуск: до 1 часа, 720 точек и 1 MiB. Обычно выборки идут через 5 секунд; при более редком фоновом сборе возможны пропуски. Рост рабочего набора сам по себе не доказывает утечку. Остановка сохраняет данные; удаление останавливает и удаляет эту запись.", + "metric": { + "memory": "Частный рабочий набор", + "commit": "Частная выделенная память" + }, + "state": { + "recording": "Идёт запись", + "gap": "Нет достоверной выборки", + "exited": "Этот запуск завершён", + "stopped": "Запись остановлена", + "interrupted": "Запись прервана; автоматически не продолжена", + "limit": "Достигнут предел записи" + }, + "error": { + "unavailable": "Сборщик не ответил вовремя. Результат операции неизвестен; проверьте состояние записи перед повтором.", + "identity": "Выбранный запуск не подтверждён. Обновите данные и повторите попытку.", + "access": "Текущих прав недостаточно для чтения этого запуска.", + "existing": "Наблюдение уже существует. Перед новым остановите и удалите прежнюю запись.", + "missing": "Записи наблюдения нет.", + "storage": "Не удалось прочитать или записать наблюдение. Запись остановлена.", + "invalid": "Запись повреждена или имеет неподдерживаемый формат. Её можно удалить." + }, + "startProgram": "Наблюдать следующие запуски", + "chooseRun": "Выбрать запуск", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Показано запусков: {shown}/{total}; в выбранном сохранено точек: {points}", + "earlier": "Более ранние точки", + "latest": "Последние точки", + "programNote": "Текущие и следующие запуски по этому пути записываются отдельно. До 7 дней, 131072 точек и 9 МиБ; при достижении первого предела удаляются самые старые данные. До 512 одновременных экземпляров. В списке — последние 256 запусков; на странице — до 1000 сохранённых точек и отметки пропусков. Более ранние точки доступны для просмотра. Обычно шаг — 5 секунд; редкая выборка оставляет пропуски. Рост рабочего набора не доказывает утечку. Остановка сохраняет данные, удаление стирает их. После перезапуска Argus запись не возобновляется.", + "damaged": "Часть записей не прошла проверку целостности; отсутствующие интервалы остаются пропусками.", + "earlierRuns": "Более ранние запуски", + "latestRuns": "Последние запуски", + "waiting": "Ожидание следующего запуска", + "unconfirmed": "Не удалось проверить одноимённые экземпляры: {count}. Повторная проверка — раз в минуту." + } } diff --git a/locales/zh-CN/history.json b/locales/zh-CN/history.json index 68b0ad9b..5b54d030 100644 --- a/locales/zh-CN/history.json +++ b/locales/zh-CN/history.json @@ -37,5 +37,47 @@ "noRecordAt": "该时刻无记录", "earliest": "最早的记录", "note": "每 5 秒记录 CPU、内存、I/O、GPU 和网络占用最高的进程(最小化或后台常驻时的刷新间隔更长时按该间隔),保留 7 天。", - "off": "历史记录已关闭,不再记录新的数据。打开设置" + "off": "历史记录已关闭,不再记录新的数据。打开设置", + "watch": { + "title": "进程观察", + "empty": "在单个进程的详细信息中选择“观察此运行实例”,即可记录未进入排行榜的内存变化。", + "start": "观察此运行实例", + "target": "观察 {name}(PID {pid})", + "stop": "停止记录", + "delete": "删除记录", + "note": "仅观察此运行实例;最多 1 小时、720 个记录点、1 MiB。通常每 5 秒记录一次,较慢的后台采样可能产生空缺。工作集增长本身不证明内存泄漏。停止保留数据;删除会停止并移除本条记录。", + "metric": { + "memory": "专用工作集", + "commit": "专用提交量" + }, + "state": { + "recording": "正在记录", + "gap": "缺少有效采样", + "exited": "此运行实例已结束", + "stopped": "已停止记录", + "interrupted": "记录已中断,未自动继续", + "limit": "已达到记录上限" + }, + "error": { + "unavailable": "采样器未及时回复;操作结果未知,请先查看记录状态。", + "identity": "无法确认所选运行实例;请刷新后重试。", + "access": "无法以当前权限读取此运行实例。", + "existing": "已有观察记录;如需开始新记录,请先停止并删除旧记录。", + "missing": "没有观察记录。", + "storage": "无法读写观察记录;记录已停止。", + "invalid": "观察记录损坏或格式不受支持;可删除此记录。" + }, + "startProgram": "观察后续运行", + "chooseRun": "选择运行实例", + "run": "{started} · PID {pid} · {state}", + "runSummary": "显示 {shown}/{total} 个实例;所选实例共 {points} 个记录点", + "earlier": "更早的记录", + "latest": "最新记录", + "programNote": "同一映像路径的当前及后续实例分别记录。最多保存 7 天、131072 个点及 9 MiB,先到的上限触发旧记录清理;最多同时观察 512 个实例。列表显示最近 256 个实例,每页最多 1000 个已存点及空缺标记,可查看更早记录。通常每 5 秒记录;较慢采样保留空缺。工作集增长不证明内存泄漏。停止保留数据,删除移除记录;重启 Argus 不自动继续。", + "damaged": "部分存储记录未通过完整性检查;缺失区间保留为空缺。", + "earlierRuns": "更早的实例", + "latestRuns": "最新实例", + "waiting": "等待后续运行", + "unconfirmed": "有 {count} 个同名实例无法确认身份;每分钟重试一次。" + } } diff --git a/locales/zh-TW/history.json b/locales/zh-TW/history.json index 106a0cb4..46c6940b 100644 --- a/locales/zh-TW/history.json +++ b/locales/zh-TW/history.json @@ -37,5 +37,47 @@ "noRecordAt": "該時刻無記錄", "earliest": "最早的記錄", "note": "每 5 秒記錄 CPU、記憶體、I/O、GPU 和網路佔用最高的處理程序(最小化或背景常駐時的重新整理間隔更長時依該間隔),保留 7 天。", - "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定" + "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定", + "watch": { + "title": "處理程序觀察", + "empty": "在單一處理程序的詳細資料中選擇「觀察此執行個體」,即可記錄未進入排行榜的記憶體變化。", + "start": "觀察此執行個體", + "target": "觀察 {name}(PID {pid})", + "stop": "停止記錄", + "delete": "刪除記錄", + "note": "僅觀察此執行個體;最多 1 小時、720 個記錄點、1 MiB。通常每 5 秒記錄一次,較慢的背景取樣可能產生缺漏。工作集增長本身不證明記憶體洩漏。停止會保留資料;刪除會停止並移除此記錄。", + "metric": { + "memory": "私人工作集", + "commit": "私人認可用量" + }, + "state": { + "recording": "正在記錄", + "gap": "缺少有效取樣", + "exited": "此執行個體已結束", + "stopped": "已停止記錄", + "interrupted": "記錄已中斷,未自動繼續", + "limit": "已達記錄上限" + }, + "error": { + "unavailable": "取樣器未及時回覆;操作結果未知,請先檢視記錄狀態。", + "identity": "無法確認所選執行個體;請重新整理後重試。", + "access": "無法以目前權限讀取此執行個體。", + "existing": "已有觀察記錄;若要開始新記錄,請先停止並刪除舊記錄。", + "missing": "沒有觀察記錄。", + "storage": "無法讀寫觀察記錄;記錄已停止。", + "invalid": "觀察記錄損壞或格式不受支援;可刪除此記錄。" + }, + "startProgram": "觀察後續執行", + "chooseRun": "選擇執行個體", + "run": "{started} · PID {pid} · {state}", + "runSummary": "顯示 {shown}/{total} 個執行個體;所選個體共 {points} 個記錄點", + "earlier": "較早的記錄", + "latest": "最新記錄", + "programNote": "同一映像路徑的目前及後續執行個體分別記錄。最多保留 7 天、131072 個點及 9 MiB,先到的上限觸發舊記錄清理;最多同時觀察 512 個個體。清單顯示最近 256 個個體,每頁最多 1000 個已存點及空缺標記,可查看較早記錄。通常每 5 秒記錄;較慢取樣保留空缺。工作集成長不證明記憶體洩漏。停止保留資料,刪除移除記錄;重啟 Argus 不自動繼續。", + "damaged": "部分儲存記錄未通過完整性檢查;缺失區間保留為空缺。", + "earlierRuns": "較早的執行個體", + "latestRuns": "最新執行個體", + "waiting": "等待後續執行", + "unconfirmed": "有 {count} 個同名執行個體無法確認身分;每分鐘重試一次。" + } } diff --git a/src-gpui/src/commands.rs b/src-gpui/src/commands.rs index 96fdf0a7..df98a2cc 100644 --- a/src-gpui/src/commands.rs +++ b/src-gpui/src/commands.rs @@ -593,7 +593,37 @@ pub fn history_moment(dir: State<'_, HistoryDir>, ts: i64) -> Option) -> HistoryUsage { - history::usage(&dir.0) + let mut usage = history::usage(&dir.0); + usage.bytes = usage + .bytes + .saturating_add(argus_core::watch::WatchRecorder::storage_bytes(&dir.0)); + usage +} + +/// Explicit observation runs on the sampler, where its file and instance handle live. +pub fn watch_process( + state: State<'_, AppState>, + dir: State<'_, HistoryDir>, + action: argus_core::watch::WatchAction, +) -> Result, String> { + use argus_core::watch::WatchError; + let (tx, rx) = std::sync::mpsc::channel(); + state + .sampler + .send(Control::Watch(dir.0.clone(), action, tx)); + let result = rx + .recv_timeout(std::time::Duration::from_secs(5)) + .map_err(|_| tr!("history.watch.error.unavailable"))?; + result.map_err(|error| { + argus_core::i18n::text(match error { + WatchError::Identity => "history.watch.error.identity", + WatchError::Access => "history.watch.error.access", + WatchError::Existing => "history.watch.error.existing", + WatchError::Missing => "history.watch.error.missing", + WatchError::Storage => "history.watch.error.storage", + WatchError::Invalid => "history.watch.error.invalid", + }) + }) } /// Starts or stops recording; what is already recorded stays until it expires. diff --git a/src-gpui/src/dispatch.rs b/src-gpui/src/dispatch.rs index f249ab5a..88fa40c8 100644 --- a/src-gpui/src/dispatch.rs +++ b/src-gpui/src/dispatch.rs @@ -237,6 +237,13 @@ pub fn invoke(host: &Host, name: &str, args: Value) -> Result { serde_json::to_value(crate::commands::history_usage(host.state())) .expect("serializable command response"), ), + "watch_process" => crate::commands::watch_process( + host.state(), + host.state(), + argument::(&args, "action")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), "set_history_enabled" => crate::commands::set_history_enabled( host.clone(), host.state(), diff --git a/src-gpui/src/frontend/backend.rs b/src-gpui/src/frontend/backend.rs index a128816c..877321b8 100644 --- a/src-gpui/src/frontend/backend.rs +++ b/src-gpui/src/frontend/backend.rs @@ -85,6 +85,16 @@ impl Desktop { let Some(pending) = self.pending.remove(&id) else { return; }; + if pending.command == "watch_process" + && pending.args["generation"].as_u64().unwrap_or(0) + != self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + { + return; + } // An answer for another range or moment is dropped. One history query of each // kind is in flight at a time, so the one for what is shown now may have been // held back while this one was read: forget it was sent and ask again. @@ -139,9 +149,21 @@ impl Desktop { if let Some(key) = pending.cache { self.data.insert(key, value.clone()); } + if pending.command == "watch_process" { + self.data.remove("watchError"); + self.data.insert("processWatch".into(), value.clone()); + } if pending.command == "history_series" { self.history_answered(&pending.args, window, cx); } + if pending.command == "watch_process" + && matches!( + pending.args["action"]["op"].as_str(), + Some("start" | "startProgram") + ) + { + self.act(Action::Page("history".into()), window, cx); + } if pending.command.starts_with("set_") && value.get("closeToTray").is_some() { self.data.insert("settings".into(), value.clone()); } @@ -162,6 +184,11 @@ impl Desktop { .as_str() .map(str::to_owned) .unwrap_or_else(|| self.action_error(&pending.command, &pending.args, &error)); + if pending.command == "watch_process" && pending.args["action"]["op"] == "status" { + self.data.insert("watchError".into(), json!(message)); + cx.notify(); + return; + } self.command_failed(&pending.command, &pending.args, &error, message, window, cx); } } diff --git a/src-gpui/src/frontend/pages.rs b/src-gpui/src/frontend/pages.rs index bac9e8f0..87456ea1 100644 --- a/src-gpui/src/frontend/pages.rs +++ b/src-gpui/src/frontend/pages.rs @@ -3,6 +3,7 @@ mod about; mod details; mod history; mod performance; +mod process_watch; mod settings; mod vitals; use super::*; @@ -513,6 +514,32 @@ impl Desktop { self.load_history(window, cx); } "historyMetric" => self.history_metric = value.as_str().unwrap_or("cpu").into(), + "watchProcess" => { + if self.pending.values().any(|pending| { + pending.command == "watch_process" && pending.args["action"]["op"] != "status" + }) { + return; + } + let generation = self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + + 1; + self.data + .insert("watchGeneration".into(), json!(generation)); + if self.options.fixture.is_some() { + self.data.insert("watchLastAction".into(), value.clone()); + } + self.request( + "watch_process", + json!({"action":value,"generation":generation}), + None, + window, + cx, + ); + return; + } "historyLatest" => { self.history_cursor = None; self.history_hover = None; diff --git a/src-gpui/src/frontend/pages/details.rs b/src-gpui/src/frontend/pages/details.rs index 4e896a39..354dad65 100644 --- a/src-gpui/src/frontend/pages/details.rs +++ b/src-gpui/src/frontend/pages/details.rs @@ -1162,7 +1162,28 @@ impl Desktop { .hover(move |style| style.bg(control_hover)), ); } - row.into_any_element() + let mut actions = div().flex_none().flex().flex_col(); + if !picked.group && number(process, "createTime") > 0. { + actions = actions.child(div().px(px(16.)).pt(px(8.)).child( + self.btn_small("details-watch", label("history.watch.start"), None, widgets::Tone::Plain) + .child(self.watch_anchor("details-watch")) + .w_full() + .on_click(cx.listener({ + let target = json!({"op":"start","pid":process["pid"],"createTime":process["createTime"],"name":process["name"]}); + move |this, _, window, cx| this.preference("watchProcess",target.clone(),window,cx) + })) + )); + actions = actions.child(div().px(px(16.)).pt(px(8.)).child( + self.btn_small("details-watch-program", label("history.watch.startProgram"), None, widgets::Tone::Plain) + .child(self.watch_anchor("details-watch-program")) + .w_full() + .on_click(cx.listener({ + let target = json!({"op":"startProgram","pid":process["pid"],"createTime":process["createTime"],"name":process["name"]}); + move |this, _, window, cx| this.preference("watchProcess",target.clone(),window,cx) + })) + )); + } + actions.child(row).into_any_element() } fn details_exited(&self, cx: &mut Context) -> AnyElement { diff --git a/src-gpui/src/frontend/pages/history.rs b/src-gpui/src/frontend/pages/history.rs index 2e7b7e48..fccd053d 100644 --- a/src-gpui/src/frontend/pages/history.rs +++ b/src-gpui/src/frontend/pages/history.rs @@ -300,6 +300,7 @@ impl Desktop { window: &mut Window, cx: &mut Context, ) { + self.load_watch(window, cx); let now = now_ms(); let span = self.history_span(); let buckets = ((span as f64 / FRAME).ceil() as i64) @@ -999,6 +1000,11 @@ impl Desktop { .flex_col() .gap(px(10.)) .line_height(relative(1.4)) + .when( + self.data.get("processWatch").is_some_and(Value::is_object) + || self.data.contains_key("watchError"), + |d| d.child(self.watch_card(window, cx)), + ) .child(graphs) .child(moment_card) .child(scrollbar::scrollbar("history-scrollbar", &page, p.dark)) diff --git a/src-gpui/src/frontend/pages/process_watch.rs b/src-gpui/src/frontend/pages/process_watch.rs new file mode 100644 index 00000000..9511ee03 --- /dev/null +++ b/src-gpui/src/frontend/pages/process_watch.rs @@ -0,0 +1,427 @@ +//! Explicit instance or program observation, independent of historical top lists. +use super::*; +use widgets::Tone; + +impl Desktop { + pub(super) fn watch_anchor(&self, key: &'static str) -> AnyElement { + let anchors = self.ui.anchors.clone(); + canvas( + move |bounds, _, _| { + anchors.borrow_mut().insert(key.into(), bounds); + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0() + .into_any_element() + } + pub(super) fn load_watch(&mut self, window: &mut Window, cx: &mut Context) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64; + let active = !self.data.contains_key("processWatch") + || self.data.contains_key("watchError") + || self + .data + .get("processWatch") + .is_some_and(|watch| matches!(text(watch, "state"), "recording" | "gap")); + let last = self.data.get("watchQueryAt").and_then(Value::as_i64); + if last.is_none() + || (active && last.is_some_and(|at| now - at >= argus_core::watch::SAMPLE_MS)) + || last.is_some_and(|at| now < at || now - at >= 60_000) + { + self.data.insert("watchQueryAt".into(), json!(now)); + self.request( + "watch_process", + json!({"action":{"op":"status"},"generation":self.data.get("watchGeneration").and_then(Value::as_u64).unwrap_or(0)}), + Some("processWatch"), + window, + cx, + ); + } + } + + pub(super) fn watch_card(&self, window: &mut Window, cx: &mut Context) -> AnyElement { + let p = self.palette; + let watch = self.data.get("processWatch").unwrap_or(&Value::Null); + let mut card = div() + .flex_none() + .p(px(14.)) + .flex() + .flex_col() + .gap(px(8.)) + .border_1() + .border_color(p.stroke) + .rounded(px(8.)) + .bg(p.layer); + if !watch.is_object() { + if let Some(message) = self.data.get("watchError").and_then(Value::as_str) { + return card + .child(div().child(message.to_owned())) + .child( + self.btn_small( + "watch-delete-invalid", + label("history.watch.delete"), + None, + Tone::Plain, + ) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"delete"}), window, cx) + })), + ) + .into_any_element(); + } + return card + .child( + div() + .font_weight(theme::LABEL_WEIGHT) + .child(label("history.watch.title")), + ) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label("history.watch.empty")), + ) + .into_any_element(); + } + let state = text(watch, "state"); + let program_mode = text(watch, "mode") == "program"; + let points = values(&watch["points"]); + let start = points + .first() + .map(|point| number(point, "ts")) + .unwrap_or(0.); + let end = points + .last() + .map(|point| number(point, "ts")) + .unwrap_or(start) + + argus_core::watch::SAMPLE_MS as f64; + let latest = points.last(); + let names = [ + label("history.watch.metric.memory"), + label("history.watch.metric.commit"), + ]; + let key = charts::hash_of(( + watch["pid"].as_u64(), + watch["createTime"].as_i64(), + points.len(), + end.to_bits(), + latest.and_then(|point| point["memory"].as_u64()), + latest.and_then(|point| point["commit"].as_u64()), + p.dark, + &names, + )); + let cached = window.use_keyed_state("process-watch-series", cx, |_, _| { + None::<(u64, Arc>, f64)> + }); + let plot = cached + .read(cx) + .as_ref() + .filter(|(stored, _, _)| *stored == key) + .cloned(); + let (_, series, maximum) = plot.unwrap_or_else(|| { + let mut maximum = 1024. * 1024.; + let mut series = Vec::new(); + for ((field, color), name) in [("memory", p.memory), ("commit", p.cpu)] + .into_iter() + .zip(&names) + { + let data = points + .iter() + .map(|point| (number(point, "ts"), point[field].as_f64())) + .collect::>(); + maximum = data + .iter() + .filter_map(|(_, value)| *value) + .fold(maximum, f64::max); + series.push( + charts::Series::new(name.clone(), data, color, charts::MetricFormat::Gigabytes) + .source(charts::hash_of((key, field))), + ); + } + let plot = (key, Arc::new(series), maximum); + cached.update(cx, |cache, _| *cache = Some(plot.clone())); + plot + }); + let mut legend = div().flex().flex_wrap().gap_x_4().gap_y_1(); + for (field, color) in [("memory", p.memory), ("commit", p.cpu)] { + let value = latest + .and_then(|point| point[field].as_f64()) + .map(theme::memory) + .unwrap_or_else(|| label("format.missing")); + legend = legend.child(div().text_size(theme::font(12.)).text_color(color).child( + format!( + "{}: {value}", + label(&format!("history.watch.metric.{field}")) + ), + )); + } + let active = matches!(state, "recording" | "gap"); + let header = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(div().font_weight(theme::LABEL_WEIGHT).child(tr!( + "history.watch.target", + name = text(watch, "name"), + pid = watch["pid"] + ))) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label( + &if program_mode && active && watch["liveRuns"] == 0 { + "history.watch.waiting".into() + } else { + format!("history.watch.state.{state}") + }, + )), + ) + .child( + self.btn_small("watch-stop", label("history.watch.stop"), None, Tone::Plain) + .child(self.watch_anchor("watch-stop")) + .disabled(!active) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"stop"}), window, cx) + })), + ) + .child( + self.btn_small( + "watch-delete", + label("history.watch.delete"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-delete")) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"delete"}), window, cx) + })), + ); + card = card.child(header).child(legend); + if program_mode { + let runs = values(&watch["runs"]); + let options = runs + .iter() + .map(|run| { + tr!( + "history.watch.run", + started = date_time(number(run, "createTime")), + pid = run["pid"], + state = label(&format!("history.watch.state.{}", text(run, "state"))) + ) + }) + .collect(); + let selected = runs.iter().position(|run| { + run["pid"] == watch["pid"] && run["createTime"] == watch["createTime"] + }); + let keys: Vec<_> = runs + .iter() + .map( + |run| json!({"op":"selectRun","pid":run["pid"],"createTime":run["createTime"]}), + ) + .collect(); + card = card.child(self.select( + "watch-run", + label("history.watch.chooseRun"), + options, + selected, + keys.is_empty(), + move |this, index, window, cx| { + if let Some(action) = keys.get(index) { + this.preference("watchProcess", action.clone(), window, cx); + } + }, + cx, + )); + let offset = watch["runOffset"].as_u64().unwrap_or(0); + let total = watch["totalRuns"].as_u64().unwrap_or(0); + card = card.child( + div() + .flex() + .flex_wrap() + .gap(px(8.)) + .child( + self.btn_small( + "watch-older-runs", + label("history.watch.earlierRuns"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-older-runs")) + .disabled(offset + runs.len() as u64 >= total) + .on_click(cx.listener( + move |this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"runs","offset":offset+256}), + window, + cx, + ) + }, + )), + ) + .child( + self.btn_small( + "watch-latest-runs", + label("history.watch.latestRuns"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-latest-runs")) + .disabled(offset == 0) + .on_click(cx.listener(|this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"runs","offset":0}), + window, + cx, + ) + })), + ), + ); + card = card.child( + div() + .min_w_0() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(text(&watch["program"], "displayPath").to_owned()), + ); + card = card.child( + div() + .flex() + .flex_wrap() + .gap(px(8.)) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(tr!( + "history.watch.runSummary", + shown = runs.len(), + total = watch["totalRuns"], + points = watch["totalPoints"] + )), + ) + .child( + self.btn_small( + "watch-earlier", + label("history.watch.earlier"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-earlier")) + .disabled(watch["hasEarlier"] != true) + .on_click(cx.listener({ + let before = watch["firstSequence"].clone(); + move |this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"page","before":before}), + window, + cx, + ) + } + })), + ) + .child( + self.btn_small( + "watch-latest", + label("history.watch.latest"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-latest")) + .disabled(watch["hasLater"] != true) + .on_click(cx.listener(|this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"page","before":null}), + window, + cx, + ) + })), + ), + ); + if watch["damaged"] == true { + card = card.child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label("history.watch.damaged")), + ); + } + if number(watch, "unconfirmed") > 0. { + card = card.child(div().text_size(theme::font(12.)).text_color(p.muted).child( + tr!("history.watch.unconfirmed", count = watch["unconfirmed"]), + )); + } + } + if let Some(message) = self.data.get("watchError").and_then(Value::as_str) { + card = card.child(div().text_size(theme::font(12.)).child(message.to_owned())); + } + if !points.is_empty() { + card = card.child( + div() + .h(px(110.)) + .border_1() + .border_color(p.stroke) + .rounded(px(4.)) + .bg(p.chart_surface) + .child(charts::TimePlot { + id: "process-watch-memory".into(), + series, + start, + end, + max: maximum * 1.1, + min: 0., + interactive: true, + grid: true, + fill: false, + background_separate: false, + smooth: false, + ticks: None, + geometry_start: start, + measured_width: Rc::new(Cell::new(1.)), + live_clock: None, + image_surface: Default::default(), + dash_phases: Default::default(), + rescale: Default::default(), + readout: Default::default(), + captions: None, + }), + ); + } + card = card.child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label(if program_mode { + "history.watch.programNote" + } else { + "history.watch.note" + })), + ); + for point in points + .iter() + .filter(|point| text(point, "state") != "recording") + .rev() + .take(6) + .collect::>() + .into_iter() + .rev() + { + card = card.child(div().text_size(theme::font(12.)).text_color(p.muted).child( + format!( + "{} — {}", + date_time(number(point, "ts")), + label(&format!("history.watch.state.{}", text(point, "state"))) + ), + )); + } + card.into_any_element() + } +} diff --git a/src-gpui/src/frontend/pages/settings.rs b/src-gpui/src/frontend/pages/settings.rs index e78bc166..0c286eba 100644 --- a/src-gpui/src/frontend/pages/settings.rs +++ b/src-gpui/src/frontend/pages/settings.rs @@ -3887,6 +3887,16 @@ impl Desktop { } "clear_history" => { self.ui.busy.remove("clearHistory"); + let generation = self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + + 1; + self.data + .insert("watchGeneration".into(), json!(generation)); + self.data.insert("processWatch".into(), Value::Null); + self.data.remove("watchError"); self.notify_toast_for( ToastKind::Success, label("settings.data.history.cleared"), diff --git a/src-gpui/src/frontend/test_control.rs b/src-gpui/src/frontend/test_control.rs index 4e33d958..aefe986c 100644 --- a/src-gpui/src/frontend/test_control.rs +++ b/src-gpui/src/frontend/test_control.rs @@ -552,9 +552,7 @@ impl Desktop { && (f32::from(viewport.height) - client.bottom as f32).abs() < 1. })) }); - println!( - "{}", - json!({"event":"ui-layout","label":label,"page":self.page,"device":self.device, + let mut layout = json!({"event":"ui-layout","label":label,"page":self.page,"device":self.device, "vitals":self.vitals_band_state(), "visibility":{"enabled":self.prefs.get::(visibility::preference(&self.page),false), "pids":self.rows.iter().filter(|row|row.section.is_none()).flat_map(|row| if row.members.is_empty(){std::slice::from_ref(&row.raw)}else{row.members.as_slice()}).filter_map(|p|p["pid"].as_u64()).collect::>()}, @@ -580,8 +578,10 @@ impl Desktop { "performanceCardHeight":self.perf_card_chrome.get().map(|chrome| f32::from(window.viewport_size().height - chrome)), "aboutScroll":{"max":about_max,"offset":about_offset,"canScroll":about_max > 0.5, "atEnd":about_max > 0.5 && (about_offset-about_max).abs() < 0.5}, - "settingsScrollY":f32::from(self.settings_scroll.max_offset().y),"settingsTop":self.settings_scroll.top_item()}) - ); + "settingsScrollY":f32::from(self.settings_scroll.max_offset().y),"settingsTop":self.settings_scroll.top_item()}); + layout["watch"] = json!(self.data.get("processWatch").map(|watch|json!({"pid":watch["pid"],"state":watch["state"],"mode":watch["mode"],"runs":values(&watch["runs"]).len(),"liveRuns":watch["liveRuns"],"points":values(&watch["points"]).len(),"missing":values(&watch["points"]).iter().filter(|point|point["memory"].is_null()).count()}))); + layout["watchAction"] = json!(self.data.get("watchLastAction")); + println!("{layout}"); } if self.options.fixture.is_some() && let Some(key) = control["clickHeader"].as_str() diff --git a/tools/window-probe/fixtures/process-watch.mjs b/tools/window-probe/fixtures/process-watch.mjs new file mode 100644 index 00000000..6a61c5b8 --- /dev/null +++ b/tools/window-probe/fixtures/process-watch.mjs @@ -0,0 +1,29 @@ +// Window test data; accepts a WatchView exported by the real process_watch example. +// Without an input path the trajectory is synthetic. No process commands run. +import {mkdirSync,readFileSync,writeFileSync} from 'node:fs'; +const base=Date.now()-40000; +const point=(offset,memory,state='recording')=>({ts:base+offset,memory,commit:memory===null?null:memory+1048576,state}); +const recorded=process.argv[2]?JSON.parse(readFileSync(process.argv[2],'utf8')):{version:1,pid:44101,createTime:base-1000,name:'controlled-memory-helper',state:'exited',points:[point(0,4<<20),point(5000,4<<20),point(10000,12<<20),point(15000,null,'gap'),point(30000,2<<20),point(35000,null,'exited')]}; +const fixture=JSON.parse(readFileSync(new URL('desktop.json',import.meta.url),'utf8')); +fixture.snapshot.processes=[{...fixture.snapshot.processes[0],pid:recorded.pid,ppid:0,createTime:recorded.createTime,instanceKey:undefined,name:recorded.name,description:recorded.name,appWindow:true}]; +fixture.snapshot.system.processCount=1; +fixture.processWatch=null; +mkdirSync('target',{recursive:true}); +writeFileSync('target/process-watch.json',JSON.stringify(fixture)); +const active={...recorded,state:'recording',points:recorded.points.filter(point=>point.state==='recording').slice(0,3)}; +const stopped={...active,state:'stopped',points:[...active.points,{ts:recorded.points.at(-1).ts,memory:null,commit:null,state:'stopped'}]}; +const resolve=(action,value,generation)=>({resolve:{command:'watch_process',args:{action:{op:action},generation},ok:true,value}}); +const steps=[ + {control:{page:'processes',view:'list',selectRow:0,pointerOutside:true},wait:700,inspect:'layout',label:'selected',expect:{'processTree.visibleRows':1},capture:'start-button'}, + {control:{clickAnchor:'details-watch'},wait:300,inspect:'layout',label:'start-action',expect:{'watchAction.op':'start','watchAction.pid':recorded.pid}}, + {control:resolve('start',active,1),wait:600,inspect:'layout',label:'recording',expect:{page:'history','watch.state':'recording','watch.points':active.points.length},capture:'recording'}, + {control:{clickAnchor:'watch-stop'},wait:300,inspect:'layout',label:'stop-action',expect:{'watchAction.op':'stop'}}, + {control:resolve('stop',stopped,2),wait:400,inspect:'layout',label:'stopped',expect:{'watch.state':'stopped'},capture:'stopped'}, + {control:resolve('status',recorded,2),wait:500,inspect:'layout',label:'real-exit-and-gap',expect:{'watch.state':'exited','watch.missing':recorded.points.filter(point=>point.memory===null).length},capture:'exit-and-gap'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:900,capture:'small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 800',wait:900}, + {control:{clickAnchor:'watch-delete'},wait:300,inspect:'layout',label:'delete-action',expect:{'watchAction.op':'delete'}}, + {control:resolve('delete',null,3),wait:400,inspect:'layout',label:'deleted',expect:{'watch.state':null,'watch.points':0},capture:'deleted'}, + {control:resolve('status',active,2),wait:300,inspect:'layout',label:'stale-status-rejected',expect:{'watch.state':null,'watch.points':0}}, +]; +writeFileSync('target/process-watch-steps.json',JSON.stringify({window:[1200,800],source:process.argv[2]??'synthetic',steps},null,2)); diff --git a/tools/window-probe/fixtures/program-watch.mjs b/tools/window-probe/fixtures/program-watch.mjs new file mode 100644 index 00000000..5fbde301 --- /dev/null +++ b/tools/window-probe/fixtures/program-watch.mjs @@ -0,0 +1,61 @@ +// Native-window fixture: commands are mocked; actual identity/collector is tested in Rust. +import {readFileSync,writeFileSync,mkdirSync} from 'node:fs'; +const fixture=JSON.parse(readFileSync(new URL('desktop.json',import.meta.url),'utf8')); +const base=Date.now()-60000; +const pid=44101,created=base-20000; +const point=(ts,memory,state='recording')=>({ts,memory,commit:memory===null?null:memory+1048576,state}); +const runs=[ + {pid,createTime:created,firstTs:base,lastTs:base+15000,points:1008,state:'exited'}, + {pid:44102,createTime:base+16000,firstTs:base+20000,lastTs:base+50000,points:7,state:'recording'} +]; +const view={version:2,pid,createTime:created,name:'same.exe',mode:'program',state:'recording',liveRuns:1, + program:{nativePath:'\\Device\\HarddiskVolume3\\Argus test\\one\\same.exe',displayPath:'C:\\Argus test\\one\\same.exe'}, + runs,totalRuns:2,totalPoints:1008,runOffset:0,damaged:false,unconfirmed:0, + firstSequence:101,hasEarlier:true,hasLater:false, + points:[point(base,4<<20),point(base+5000,12<<20),point(base+10000,null,'gap'),point(base+15000,null,'exited')] +}; +fixture.snapshot.processes=[{...fixture.snapshot.processes[0],pid,ppid:0,createTime:created,instanceKey:undefined,name:'same.exe',description:'same.exe',appWindow:true}]; +fixture.snapshot.system.processCount=1; +fixture.processWatch=null; +const second={...view,pid:44102,createTime:runs[1].createTime,totalPoints:7,firstSequence:1200,hasEarlier:false, + points:[point(base+20000,2<<20),point(base+25000,3<<20),point(base+30000,4<<20)]}; +const earlier={...view,firstSequence:1,hasEarlier:false,hasLater:true,points:[point(base-40000,1<<20),point(base-35000,2<<20)]}; +const waiting={...view,liveRuns:0,runs:runs.map(run=>({...run,state:'exited'}))}; +const stopped={...waiting,state:'stopped'}; +const answer=(op,value,generation)=>({resolve:{command:'watch_process',args:{action:{op},generation},ok:true,value}}); +const steps=[ + {control:{page:'processes',view:'list',selectRow:0,pointerOutside:true},wait:700,capture:'two-choices'}, + {control:{clickAnchor:'details-watch-program'},wait:250,inspect:'layout',label:'start-program-action',expect:{'watchAction.op':'startProgram','watchAction.pid':pid}}, + {control:answer('startProgram',view,1),wait:600,inspect:'layout',label:'program-history',expect:{page:'history','watch.mode':'program','watch.runs':2,'watch.pid':pid},capture:'first-launch'}, + {control:{clickAnchor:'watch-earlier'},wait:250,inspect:'layout',label:'earlier-action',expect:{'watchAction.op':'page','watchAction.before':101}}, + {control:answer('page',earlier,2),wait:350,capture:'earlier-points'}, + {control:{clickAnchor:'watch-latest'},wait:200,inspect:'layout',label:'latest-action',expect:{'watchAction.op':'page','watchAction.before':null}}, + {control:answer('page',view,3),wait:300}, + {control:{clickSelect:'watch-run'},wait:250,capture:'launch-menu'}, + {control:{keys:['down','enter']},wait:250,inspect:'layout',label:'choose-second',expect:{'watchAction.op':'selectRun','watchAction.pid':44102}}, + {control:answer('selectRun',second,4),wait:400,inspect:'layout',label:'second-curve',expect:{'watch.pid':44102,'watch.points':3},capture:'second-launch'}, + {control:answer('status',waiting,4),wait:350,inspect:'layout',label:'waiting',expect:{'watch.state':'recording','watch.liveRuns':0},capture:'waiting'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:800,capture:'small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 900',wait:600}, + {control:{clickAnchor:'watch-stop'},wait:200,inspect:'layout',label:'stop-action',expect:{'watchAction.op':'stop'}}, + {control:answer('stop',stopped,5),wait:350,inspect:'layout',label:'stopped',expect:{'watch.state':'stopped','watch.points':4},capture:'stopped'}, + {control:{clickAnchor:'watch-delete'},wait:200,inspect:'layout',label:'delete-action',expect:{'watchAction.op':'delete'}}, + {control:answer('delete',null,6),wait:300,inspect:'layout',label:'deleted',expect:{'watch.state':null}}, + {control:answer('status',view,5),wait:250,inspect:'layout',label:'stale-rejected',expect:{'watch.state':null}} +]; +mkdirSync('target',{recursive:true}); +writeFileSync('target/program-watch.json',JSON.stringify(fixture)); +writeFileSync('target/program-watch-steps.json',JSON.stringify({window:[1200,900],steps},null,2)); +if(process.argv[2]){ + const real=JSON.parse(readFileSync(process.argv[2],'utf8')); + const last=real.runs.at(-1); + const realSteps=[ + {control:{page:'history',pointerOutside:true},wait:400}, + {control:answer('status',real,0),wait:600,inspect:'layout',label:'real-runs',expect:{'watch.mode':'program','watch.runs':real.runs.length},capture:'real-recording'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:700,capture:'real-small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 900',wait:500}, + {control:{clickSelect:'watch-run'},wait:300,capture:'real-launch-list'}, + {control:{keys:[...Array(real.runs.length-1).fill('down'),'enter']},wait:300,inspect:'layout',label:'last-real-launch',expect:{'watchAction.op':'selectRun','watchAction.pid':last.pid}}, + ]; + writeFileSync('target/program-watch-real-steps.json',JSON.stringify({window:[1200,900],source:process.argv[2],steps:realSteps},null,2)); +} From 8b3300402d2586344b174c45667162025eeafad5 Mon Sep 17 00:00:00 2001 From: Raylea <101520596+Ray-lea@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:21:31 -0800 Subject: [PATCH 4/6] =?UTF-8?q?fix(ui):=20=E5=8E=86=E5=8F=B2=E5=B3=B0?= =?UTF-8?q?=E5=80=BC=E9=80=89=E6=8B=A9=E5=90=8E=E6=8C=89=E6=89=80=E5=B1=9E?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=E7=A7=BB=E5=8A=A8=E9=94=AE=E7=9B=98=E5=85=89?= =?UTF-8?q?=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/guide/README.md | 2 +- src-gpui/src/frontend/pages/history.rs | 35 +++++++++++------- .../fixtures/history-keyboard.mjs | 37 +++++++++++++++++++ 3 files changed, 60 insertions(+), 14 deletions(-) create mode 100644 tools/window-probe/fixtures/history-keyboard.mjs diff --git a/docs/guide/README.md b/docs/guide/README.md index e09af862..2ab5a6b8 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -193,7 +193,7 @@ Argus 运行时每 5 秒记录一帧:整机的 CPU(这 5 秒内各次采样 - **时间范围**:在页面栏选择 1 小时、6 小时、24 小时或 7 天,图表显示截至当前的这段时间,并随时间定期前移(1 小时的范围每 10 秒,7 天的范围每 5 分钟)。CPU 曲线上方较淡的线是每段时间里采样的最高值。 - **CPU 峰值帧**:平均值与最高值分别显示;“查看 CPU 峰值帧”打开所选图表区间内含最高 CPU 采样的实际记录帧,最高值相同时选最早的帧。标题给出列表所对应的真实时间;进程读数为该帧的平均值,不能确定瞬时峰值的原因。普通图表点显示该区间的第一个实际记录帧,避免用两个相距较远的帧的平均时间查询空白时段。此选择不改写历史文件。 -- **查看某一时刻**:指针移到曲线上,左侧显示那一刻的数值;单击选中这一时刻,下方列出当时最忙的进程。选中后在曲线上按 ← →(加 Shift 一次移动更多)前后移动,按 Esc 或页面栏上的“回到最新”取消选中。选中时刻后图表仍随时间前移,该时刻移出图表时自动取消选中。 +- **查看某一时刻**:指针移到曲线上,左侧显示那一刻的数值;单击选中这一时刻,下方列出当时最忙的进程。选中后在曲线上按 ← →(加 Shift 一次移动更多)前后移动;选中 CPU 峰值帧时,从峰值所属区间开始移动。按 Esc 或页面栏上的“回到最新”取消选中。选中时刻后图表仍随时间前移,该时刻移出图表时自动取消选中。 - **切换范围**:切换后总是显示新范围截至当前的时间段。选中的时刻仍在新范围内时保持选中,下方的进程列表不变;否则取消选中,读数与进程列表回到最新数据。查看更早的时段需选择更长的范围。 - **电池数据缺失**:设备暂未上报电池电量的时段,电池曲线留空,读数显示“无记录”;实际电量为 0% 时仍显示为 0%。 - **转到进程**:双击列表中的进程,仅在 PID、名称和记录的创建时间与当前运行实例一致时转到进程页;执行跳转时再次核对。旧记录没有创建时间时保留历史读数,不提供跳转。创建时间可以位于该帧的 5 秒记录窗口内,不能晚于该窗口。 diff --git a/src-gpui/src/frontend/pages/history.rs b/src-gpui/src/frontend/pages/history.rs index b4e44e6e..4c467def 100644 --- a/src-gpui/src/frontend/pages/history.rs +++ b/src-gpui/src/frontend/pages/history.rs @@ -490,6 +490,18 @@ impl Desktop { } self.load_history(window, cx); } + fn history_selected_point<'a>(&self, records: &'a [Value]) -> Option<&'a Value> { + let at = self.history_cursor?; + selected_point( + records, + at, + self.data.get("historyPeakAt").and_then(Value::as_i64) == Some(at), + self.data + .get("historySelection") + .and_then(|saved| saved["frame"].as_i64()), + self.data.get("historyWindow").unwrap_or(&Value::Null), + ) + } /// Keyboard on the history page: arrows step between points (Shift and Page keys by a /// tenth), Home and End jump to either end, Escape returns to the newest data. Steps /// stay among the points on screen and never move the window. @@ -517,15 +529,21 @@ impl Desktop { ) { return false; } - let ts = self + let records = self .data .get("historySeries") .map(values) - .unwrap_or_default() + .unwrap_or_default(); + let ts = records .iter() .filter_map(|p| p["ts"].as_f64()) .collect::>(); - let Some(at) = stepped(&ts, self.history_cursor, key, shift) else { + // A retained frame or peak starts from the bucket shown in the readout. + let origin = self + .history_selected_point(records) + .and_then(|point| point["ts"].as_i64()) + .or(self.history_cursor); + let Some(at) = stepped(&ts, origin, key, shift) else { return true; }; self.history_cursor = Some(at); @@ -597,16 +615,7 @@ impl Desktop { .collect::>(); let shown_at = |at: f64| point_at(&ts, &joined, step, at).and_then(|index| records.get(index)); - let picked = self.history_cursor.and_then(|at| { - let selection = self.data.get("historySelection"); - selected_point( - &records, - at, - self.data.get("historyPeakAt").and_then(Value::as_i64) == Some(at), - selection.and_then(|saved| saved["frame"].as_i64()), - self.data.get("historyWindow").unwrap_or(&Value::Null), - ) - }); + let picked = self.history_selected_point(&records); let read_ts = self.history_hover.or(self.history_cursor); let readout = match (self.history_hover, self.history_cursor) { (Some(at), _) => shown_at(at as f64), diff --git a/tools/window-probe/fixtures/history-keyboard.mjs b/tools/window-probe/fixtures/history-keyboard.mjs new file mode 100644 index 00000000..559593e2 --- /dev/null +++ b/tools/window-probe/fixtures/history-keyboard.mjs @@ -0,0 +1,37 @@ +// Generate a peak near the previous bucket's mean, then move using actual keys. +// Run from the repository root; ui-shots consumes the two generated target files. +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; + +const fixture = JSON.parse(readFileSync(new URL("desktop.json", import.meta.url), "utf8")); +const base = Math.floor(Date.now() / 5000) * 5000 - 21600000 + 60000; +const point = fixture.historySeries[0]; +fixture.historySeries = [ + [20000, 10000, 20000, 2, 2], + [140000, 90000, 140000, 4, 4], + [190000, 145000, 145000, 34, 98], + [285000, 220000, 285000, 3, 3], +].map(([ts, frameTs, cpuPeakTs, cpu, cpuPeak]) => ({ + ...point, ts: base + ts, frameTs: base + frameTs, + cpuPeakTs: base + cpuPeakTs, cpu, cpuPeak, +})); +fixture.historyWindow = { from: base, to: base + 21600000, buckets: 300 }; +fixture.historyMoment = { system: { ...fixture.historySeries[2], ts: base + 145000 }, processes: [] }; +const peak = { control: { preference: { historyPeak: base + 145000 } }, wait: 200 }; +const steps = [ + { control: { preference: { historyRange: "6h" }, page: "history", pointerOutside: true }, wait: 500 }, + peak, + { control: { keys: ["right"] }, wait: 300, inspect: "layout", label: "next-bucket", + expect: { "history.cursor": base + 285000, "history.requestedFrame": base + 220000 }, capture: "next" }, + peak, + { control: { keys: ["left"] }, wait: 300, inspect: "layout", label: "previous-bucket", + expect: { "history.cursor": base + 140000, "history.requestedFrame": base + 90000 }, capture: "previous" }, + peak, + { control: { keys: ["home"] }, wait: 200, inspect: "layout", label: "first-bucket", + expect: { "history.cursor": base + 20000, "history.requestedFrame": base + 10000 } }, + peak, + { control: { keys: ["end"] }, wait: 200, inspect: "layout", label: "last-bucket", + expect: { "history.cursor": base + 285000, "history.requestedFrame": base + 220000 } }, +]; +mkdirSync("target", { recursive: true }); +writeFileSync("target/history-keyboard.json", JSON.stringify(fixture)); +writeFileSync("target/history-keyboard-steps.json", JSON.stringify({ window: [1200, 800], steps }, null, 2)); From 25273307de1a1d2a0a1b7df4d458be5dfa5184d3 Mon Sep 17 00:00:00 2001 From: Raylea <101520596+Ray-lea@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:35:37 -0800 Subject: [PATCH 5/6] =?UTF-8?q?fix(core):=20=E6=96=B0=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E5=AE=9E=E4=BE=8B=E4=B8=8D=E5=86=8D=E7=BB=A7=E6=89=BF=E5=90=AF?= =?UTF-8?q?=E5=8A=A8=E5=89=8D=E7=9A=84=E8=A7=82=E5=AF=9F=E7=BC=BA=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/argus-core/src/watch/program.rs | 71 +++++++++++++++++++++++++- docs/guide/README.md | 2 +- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/crates/argus-core/src/watch/program.rs b/crates/argus-core/src/watch/program.rs index f8ec743f..afb79cc4 100644 --- a/crates/argus-core/src/watch/program.rs +++ b/crates/argus-core/src/watch/program.rs @@ -237,7 +237,13 @@ impl ProgramWatch { if let Some(previous) = self.last_ts && snapshot.timestamp.saturating_sub(previous) > SAMPLE_MS * 2 { - let keys: Vec<_> = self.handles.keys().copied().collect(); + // New launches start at their first sample; an earlier gap belongs to older runs. + let keys: Vec<_> = self + .handles + .keys() + .filter(|key| key.1 <= previous) + .copied() + .collect(); // Terminal records may already have this snapshot's timestamp; keep sequence time monotonic. let gap_ts = self.store.entries.back().map_or(previous + SAMPLE_MS, |e| { e.point.ts.max(previous + SAMPLE_MS) @@ -508,6 +514,69 @@ mod tests { } struct Helper(Child); + + #[test] + fn a_new_launch_does_not_inherit_a_gap_before_its_creation() { + let dir = std::env::temp_dir().join(format!( + "argus-program-watch-birth-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let exe = std::env::current_exe().unwrap(); + let name = exe.file_name().unwrap().to_str().unwrap().to_owned(); + let first = Helper::spawn(&exe); + let first_key = first.key(); + let mut watch = ProgramWatch::start(&dir, first_key.0, first_key.1, name.clone()).unwrap(); + let snapshot = |keys: &[Key]| Snapshot { + seq: 1, + timestamp: super::super::now_ms(), + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: keys + .iter() + .map(|&(pid, created)| crate::ProcessRow { + pid, + create_time: created, + name: name.clone().into(), + ..Default::default() + }) + .collect(), + }; + watch.record(&snapshot(&[first_key])).unwrap(); + std::thread::sleep(Duration::from_millis((SAMPLE_MS * 2 + 1000) as u64)); + let later = Helper::spawn(&exe); + let later_key = later.key(); + watch.record(&snapshot(&[first_key, later_key])).unwrap(); + let before_birth = watch + .store + .entries + .iter() + .filter(|entry| (entry.pid, entry.created) == later_key && entry.point.ts < later_key.1) + .map(|entry| (entry.point.ts, entry.point.state)) + .collect::>(); + let existing_gap = watch.store.entries.iter().any(|entry| { + (entry.pid, entry.created) == first_key && entry.point.state == WatchState::Gap + }); + drop(watch); + drop(later); + drop(first); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + std::fs::remove_dir(dir).unwrap(); + assert!( + before_birth.is_empty(), + "records before creation: {before_birth:?}" + ); + assert!( + existing_gap, + "the existing run must retain the sampling gap" + ); + } + impl Helper { fn spawn(path: &Path) -> Self { Self( diff --git a/docs/guide/README.md b/docs/guide/README.md index 68570103..fe65d9a8 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -213,7 +213,7 @@ Argus 运行时每 5 秒记录一帧:整机的 CPU(这 5 秒内各次采样 后续运行记录使用独立文件 `program-watch.v1.bin`,最多保留 7 天、131072 个记录点及 9 MiB;先到的上限触发最旧记录清理,时间过期的记录槽位会清零。停止后的数据也按此策略清理,Argus 关闭期间的过期记录在再次打开时清理。记录带序列与完整性校验,损坏记录不会当成读数。实例列表每页最多 256 项,曲线每页最多 1000 个已存点及空缺标记,可分别浏览较早实例、较早点或返回最新记录。 -两种观察通常每 5 秒保留一个点;后台采样较慢、读数无效或采样中断时显示空缺,不补零。通过同一进程句柄确认退出。系统时钟倒退时中断观察,不把逆序时间拼接进曲线。观察文件与排行榜文件独立,关闭排行榜记录不停止显式选择的观察。 +两种观察通常每 5 秒保留一个点;后台采样较慢、读数无效或采样中断时显示空缺,不补零。新启动的实例不继承其启动前的采样空缺。通过同一进程句柄确认退出。系统时钟倒退时中断观察,不把逆序时间拼接进曲线。观察文件与排行榜文件独立,关闭排行榜记录不停止显式选择的观察。 “停止记录”保留已有数据;“删除记录”停止观察并删除该条文件。开始另一条记录前需删除已有记录。退出或重启 Argus 不会自动继续旧观察,保留的未完成记录显示为中断。未知格式或损坏的记录也可删除。设置中的历史占用包含观察文件,“清除历史记录”同时停止并删除观察。 From d38f60427ef69da94df668cf96cdbc472acea983 Mon Sep 17 00:00:00 2001 From: Raylea <101520596+Ray-lea@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:39:26 -0800 Subject: [PATCH 6/6] =?UTF-8?q?test(ui):=20=E6=A0=B8=E5=AF=B9=E6=94=BE?= =?UTF-8?q?=E5=A4=A7=E7=95=8C=E9=9D=A2=E5=90=8E=E7=9A=84=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E5=B3=B0=E5=80=BC=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/window-probe/fixtures/history-peak.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/window-probe/fixtures/history-peak.mjs b/tools/window-probe/fixtures/history-peak.mjs index 505bb288..30e97e7d 100644 --- a/tools/window-probe/fixtures/history-peak.mjs +++ b/tools/window-probe/fixtures/history-peak.mjs @@ -16,6 +16,6 @@ const steps=[ {control:{resolve:{command:'history_moment',cache:'historyMoment',args:{cursor:base+5000,ts:base+5000},ok:true,value:peakMoment}},wait:300,inspect:'layout',label:'stale-peak-rejected',expect:{'history.requestedFrame':base}}, {control:{resolve:{command:'history_moment',cache:'historyMoment',args:{cursor:base+5000,ts:base},ok:true,value:f.historyMoment}},wait:300,inspect:'layout',label:'ordinary-frame',expect:{'history.frame':base},capture:'ordinary'}, {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:600,capture:'peak-small'}, - {control:{wheel:{x:700,y:450,lines:-16}},wait:500,capture:'peak-small-card'}, + {control:{wheel:{x:350,y:250,lines:-16}},wait:500,capture:'peak-small-card'}, ]; writeFileSync('target/history-peak-steps.json',JSON.stringify({window:[1200,800],steps},null,2));