BlueGit

ict rusty-teams

feat(help): local support packages with opt-in debug logging

Add Settings → Help to build scrubbed support bundles and open upstream
issue drafts. Debug logging stays off by default with ring rotation,
clear-logs, and richer bundle artifacts (crash log, call JSON, timeline).

metis Joachim Mild · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
7dcaa0c1472f2edbb77149e0e5f45493375dfe0e
Parent
ba8e1484
24 files changed +2038 −91
.github/ISSUE_TEMPLATE/bug_report.yml added +39 −0
@@ -0,0 +1,39 @@
1 name: Bug report
2 description: Report a bug with client data and a local support package
3 title: "Bug: "
4 labels: ["bug"]
5 body:
6 - type: markdown
7 attributes:
8 value: |
9 File bugs on [danieldaeschle/rusty-teams](https://github.com/danieldaeschle/rusty-teams/issues). Prefer **Settings → Help → Create support package**, then attach those files. Do not paste tokens, cookies, or passwords.
10 - type: textarea
11 id: what-happened
12 attributes:
13 label: What happened
14 description: Steps to reproduce and what you saw.
15 placeholder: 1. Open … 2. Click … 3. …
16 validations:
17 required: true
18 - type: textarea
19 id: expected
20 attributes:
21 label: Expected
22 description: What should have happened instead.
23 validations:
24 required: true
25 - type: textarea
26 id: client
27 attributes:
28 label: Client data
29 description: Paste the Client block from Help (or leave blank if you attach client.md).
30 render: markdown
31 validations:
32 required: false
33 - type: checkboxes
34 id: attachments
35 attributes:
36 label: Support package
37 options:
38 - label: I attached the support package files (client.md, scrubbed diagnostics.log, call reports) or explained why not
39 required: false
@@ -0,0 +1,39 @@
1name: Bug report
2description: Report a bug with client data and a local support package
3title: "Bug: "
4labels: ["bug"]
5body:
6 - type: markdown
7 attributes:
8 value: |
9 File bugs on [danieldaeschle/rusty-teams](https://github.com/danieldaeschle/rusty-teams/issues). Prefer **Settings → Help → Create support package**, then attach those files. Do not paste tokens, cookies, or passwords.
10 - type: textarea
11 id: what-happened
12 attributes:
13 label: What happened
14 description: Steps to reproduce and what you saw.
15 placeholder: 1. Open … 2. Click … 3. …
16 validations:
17 required: true
18 - type: textarea
19 id: expected
20 attributes:
21 label: Expected
22 description: What should have happened instead.
23 validations:
24 required: true
25 - type: textarea
26 id: client
27 attributes:
28 label: Client data
29 description: Paste the Client block from Help (or leave blank if you attach client.md).
30 render: markdown
31 validations:
32 required: false
33 - type: checkboxes
34 id: attachments
35 attributes:
36 label: Support package
37 options:
38 - label: I attached the support package files (client.md, scrubbed diagnostics.log, call reports) or explained why not
39 required: false
crates/app-base/locales/app.yml +109 −0
@@ -115,9 +115,118 @@ settings:
115 115 mcp:
116 116 en: MCP
117 117 de: MCP
118 help:
119 en: Help
120 de: Hilfe
118 121 about:
119 122 en: About
120 123 de: Info
124 help:
125 caption_client:
126 en: CLIENT
127 de: CLIENT
128 caption_paths:
129 en: PATHS
130 de: PFADE
131 caption_packages:
132 en: SUPPORT PACKAGES
133 de: SUPPORT-PAKETE
134 caption_actions:
135 en: SUPPORT
136 de: SUPPORT
137 packages_empty:
138 en: No support packages yet
139 de: Noch keine Support-Pakete
140 copy_path_tooltip:
141 en: Copy path
142 de: Pfad kopieren
143 preview_truncated:
144 en: Showing the first 256 KB
145 de: Es werden die ersten 256 KB angezeigt
146 preview_binary:
147 en: This file is not plain text and cannot be previewed here.
148 de: Diese Datei ist kein Klartext und kann hier nicht angezeigt werden.
149 preview_error:
150 en: Could not read this file.
151 de: Diese Datei konnte nicht gelesen werden.
152 version:
153 en: Version
154 de: Version
155 platform:
156 en: Platform
157 de: Plattform
158 locale:
159 en: Language and timezone
160 de: Sprache und Zeitzone
161 signed_in:
162 en: Signed in
163 de: Angemeldet
164 yes:
165 en: Yes
166 de: Ja
167 no:
168 en: No
169 de: Nein
170 debug_logging:
171 en: Debug logging
172 de: Debug-Protokollierung
173 debug_logging_on_detail:
174 en: Writing diagnostics.log — turn off when you are done
175 de: Schreibt diagnostics.log — danach wieder ausschalten
176 debug_logging_off_detail:
177 en: Off by default — enable before reproducing a bug
178 de: Standardmässig aus — vor der Fehlerreproduktion einschalten
179 clear_logs:
180 en: Clear logs
181 de: Logs leeren
182 clear_logs_detail:
183 en: Removes diagnostics, crash logs, and call dumps on this computer
184 de: Entfernt Diagnosen, Absturzprotokolle und Anruf-Dumps auf diesem Computer
185 clear_logs_button:
186 en: Clear
187 de: Leeren
188 logs_path:
189 en: Logs root
190 de: Log-Root
191 bundles_path:
192 en: Support packages
193 de: Support-Pakete
194 detail:
195 en: Create a local support package, then open an upstream GitHub issue and attach the files. Nothing is uploaded automatically.
196 de: Erstellen Sie ein lokales Support-Paket, öffnen Sie danach ein Upstream-GitHub-Issue und hängen Sie die Dateien an. Es wird nichts automatisch hochgeladen.
197 create_bundle:
198 en: Support package
199 de: Support-Paket
200 create_bundle_detail:
201 en: Scrubbed diagnostics and recent call reports on this computer
202 de: Bereinigte Diagnosen und aktuelle Anrufberichte auf diesem Computer
203 create_bundle_button:
204 en: Create
205 de: Erstellen
206 open_issue:
207 en: GitHub issue
208 de: GitHub-Issue
209 open_issue_detail:
210 en: Opens danieldaeschle/rusty-teams with a pre-filled draft
211 de: Öffnet danieldaeschle/rusty-teams mit vorausgefülltem Entwurf
212 open_issue_button:
213 en: Open
214 de: Öffnen
215 copy_summary:
216 en: Client summary
217 de: Client-Zusammenfassung
218 copy_summary_detail:
219 en: Copy the same English block used in the issue
220 de: Denselben englischen Block wie im Issue kopieren
221 copy_button:
222 en: Copy
223 de: Kopieren
224 open_logs:
225 en: Logs folder
226 de: Log-Ordner
227 open_logs_detail:
228 en: diagnostics.log and call dumps
229 de: diagnostics.log und Anruf-Dumps
121 230 caption:
122 231 system:
123 232 en: SYSTEM
@@ -115,9 +115,118 @@ settings:
115 mcp:
115 mcp:
116 en: MCP
116 en: MCP
117 de: MCP
117 de: MCP
118 help:
119 en: Help
120 de: Hilfe
118 about:
121 about:
119 en: About
122 en: About
120 de: Info
123 de: Info
124 help:
125 caption_client:
126 en: CLIENT
127 de: CLIENT
128 caption_paths:
129 en: PATHS
130 de: PFADE
131 caption_packages:
132 en: SUPPORT PACKAGES
133 de: SUPPORT-PAKETE
134 caption_actions:
135 en: SUPPORT
136 de: SUPPORT
137 packages_empty:
138 en: No support packages yet
139 de: Noch keine Support-Pakete
140 copy_path_tooltip:
141 en: Copy path
142 de: Pfad kopieren
143 preview_truncated:
144 en: Showing the first 256 KB
145 de: Es werden die ersten 256 KB angezeigt
146 preview_binary:
147 en: This file is not plain text and cannot be previewed here.
148 de: Diese Datei ist kein Klartext und kann hier nicht angezeigt werden.
149 preview_error:
150 en: Could not read this file.
151 de: Diese Datei konnte nicht gelesen werden.
152 version:
153 en: Version
154 de: Version
155 platform:
156 en: Platform
157 de: Plattform
158 locale:
159 en: Language and timezone
160 de: Sprache und Zeitzone
161 signed_in:
162 en: Signed in
163 de: Angemeldet
164 yes:
165 en: Yes
166 de: Ja
167 no:
168 en: No
169 de: Nein
170 debug_logging:
171 en: Debug logging
172 de: Debug-Protokollierung
173 debug_logging_on_detail:
174 en: Writing diagnostics.log — turn off when you are done
175 de: Schreibt diagnostics.log — danach wieder ausschalten
176 debug_logging_off_detail:
177 en: Off by default — enable before reproducing a bug
178 de: Standardmässig aus — vor der Fehlerreproduktion einschalten
179 clear_logs:
180 en: Clear logs
181 de: Logs leeren
182 clear_logs_detail:
183 en: Removes diagnostics, crash logs, and call dumps on this computer
184 de: Entfernt Diagnosen, Absturzprotokolle und Anruf-Dumps auf diesem Computer
185 clear_logs_button:
186 en: Clear
187 de: Leeren
188 logs_path:
189 en: Logs root
190 de: Log-Root
191 bundles_path:
192 en: Support packages
193 de: Support-Pakete
194 detail:
195 en: Create a local support package, then open an upstream GitHub issue and attach the files. Nothing is uploaded automatically.
196 de: Erstellen Sie ein lokales Support-Paket, öffnen Sie danach ein Upstream-GitHub-Issue und hängen Sie die Dateien an. Es wird nichts automatisch hochgeladen.
197 create_bundle:
198 en: Support package
199 de: Support-Paket
200 create_bundle_detail:
201 en: Scrubbed diagnostics and recent call reports on this computer
202 de: Bereinigte Diagnosen und aktuelle Anrufberichte auf diesem Computer
203 create_bundle_button:
204 en: Create
205 de: Erstellen
206 open_issue:
207 en: GitHub issue
208 de: GitHub-Issue
209 open_issue_detail:
210 en: Opens danieldaeschle/rusty-teams with a pre-filled draft
211 de: Öffnet danieldaeschle/rusty-teams mit vorausgefülltem Entwurf
212 open_issue_button:
213 en: Open
214 de: Öffnen
215 copy_summary:
216 en: Client summary
217 de: Client-Zusammenfassung
218 copy_summary_detail:
219 en: Copy the same English block used in the issue
220 de: Denselben englischen Block wie im Issue kopieren
221 copy_button:
222 en: Copy
223 de: Kopieren
224 open_logs:
225 en: Logs folder
226 de: Log-Ordner
227 open_logs_detail:
228 en: diagnostics.log and call dumps
229 de: diagnostics.log und Anruf-Dumps
121 caption:
230 caption:
122 system:
231 system:
123 en: SYSTEM
232 en: SYSTEM
crates/app-base/src/crash_log.rs +31 −6
@@ -1,21 +1,46 @@
1 1 use std::backtrace::Backtrace;
2 use std::fs::OpenOptions;
3 use std::io::Write;
2 use std::fs;
4 3 use std::panic::PanicHookInfo;
5 use std::path::PathBuf;
4 use std::path::{Path, PathBuf};
5 use std::sync::OnceLock;
6 6
7 7 pub const CRASH_LOG_FILE: &str = "crash.log";
8 const MAX_BYTES: u64 = 256 * 1024;
9 const RING_SLOTS: u32 = 1;
10 const MERGE_CAP_BYTES: u64 = 128 * 1024;
11
12 static PATH: OnceLock<PathBuf> = OnceLock::new();
8 13
9 14 pub fn install(path: PathBuf) {
15 let _ = PATH.set(path.clone());
10 16 let previous = std::panic::take_hook();
11 17 std::panic::set_hook(Box::new(move |info| {
12 if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) {
13 let _ = file.write_all(entry(info, &Backtrace::force_capture().to_string()).as_bytes());
14 }
18 let body = entry(info, &Backtrace::force_capture().to_string());
19 let _ = crate::diagnostics::append_rotated(&path, MAX_BYTES, RING_SLOTS, &body);
15 20 previous(info);
16 21 }));
17 22 }
18 23
24 pub fn path() -> Option<PathBuf> {
25 PATH.get().cloned()
26 }
27
28 pub fn read_merged(max_bytes: u64) -> String {
29 let Some(path) = PATH.get() else {
30 return String::new();
31 };
32 crate::diagnostics::read_ring_merged(path, RING_SLOTS, max_bytes.min(MERGE_CAP_BYTES).max(1))
33 }
34
35 pub fn clear_files(root: &Path) {
36 for name in [CRASH_LOG_FILE, &format!("{CRASH_LOG_FILE}.1")] {
37 let path = root.join(name);
38 if path.exists() {
39 let _ = fs::remove_file(path);
40 }
41 }
42 }
43
19 44 fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {
20 45 let location = info
21 46 .location()
@@ -1,21 +1,46 @@
1use std::backtrace::Backtrace;
1use std::backtrace::Backtrace;
2use std::fs::OpenOptions;
2use std::fs;
3use std::io::Write;
4use std::panic::PanicHookInfo;
3use std::panic::PanicHookInfo;
5use std::path::PathBuf;
4use std::path::{Path, PathBuf};
5use std::sync::OnceLock;
6
6
7pub const CRASH_LOG_FILE: &str = "crash.log";
7pub const CRASH_LOG_FILE: &str = "crash.log";
8const MAX_BYTES: u64 = 256 * 1024;
9const RING_SLOTS: u32 = 1;
10const MERGE_CAP_BYTES: u64 = 128 * 1024;
11
12static PATH: OnceLock<PathBuf> = OnceLock::new();
8
13
9pub fn install(path: PathBuf) {
14pub fn install(path: PathBuf) {
15 let _ = PATH.set(path.clone());
10 let previous = std::panic::take_hook();
16 let previous = std::panic::take_hook();
11 std::panic::set_hook(Box::new(move |info| {
17 std::panic::set_hook(Box::new(move |info| {
12 if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) {
18 let body = entry(info, &Backtrace::force_capture().to_string());
13 let _ = file.write_all(entry(info, &Backtrace::force_capture().to_string()).as_bytes());
19 let _ = crate::diagnostics::append_rotated(&path, MAX_BYTES, RING_SLOTS, &body);
14 }
15 previous(info);
20 previous(info);
16 }));
21 }));
17}
22}
18
23
24pub fn path() -> Option<PathBuf> {
25 PATH.get().cloned()
26}
27
28pub fn read_merged(max_bytes: u64) -> String {
29 let Some(path) = PATH.get() else {
30 return String::new();
31 };
32 crate::diagnostics::read_ring_merged(path, RING_SLOTS, max_bytes.min(MERGE_CAP_BYTES).max(1))
33}
34
35pub fn clear_files(root: &Path) {
36 for name in [CRASH_LOG_FILE, &format!("{CRASH_LOG_FILE}.1")] {
37 let path = root.join(name);
38 if path.exists() {
39 let _ = fs::remove_file(path);
40 }
41 }
42}
43
19fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {
44fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {
20 let location = info
45 let location = info
21 .location()
46 .location()
crates/app-base/src/diagnostics.rs +270 −43
@@ -1,13 +1,33 @@
1 use std::fs::OpenOptions;
1 use std::fs::{self, OpenOptions};
2 2 use std::io::Write;
3 use std::path::PathBuf;
3 use std::path::{Path, PathBuf};
4 use std::sync::atomic::{AtomicBool, Ordering};
4 5 use std::sync::OnceLock;
5 6
6 7 pub const DIAGNOSTICS_FILE: &str = "diagnostics.log";
8 pub const DIAGNOSTICS_SETTING_KEY: &str = "diagnostics_enabled";
9 pub const ENV_DEBUG_LOG: &str = "RUSTY_TEAMS_DEBUG_LOG";
10
7 11 const MAX_BYTES: u64 = 1024 * 1024;
12 const RING_SLOTS: u32 = 2;
13 const MERGE_CAP_BYTES: u64 = 1024 * 1024;
8 14 const SLOW_UI_HANDLER: std::time::Duration = std::time::Duration::from_millis(30);
9 15
10 16 static PATH: OnceLock<PathBuf> = OnceLock::new();
17 static ENABLED: AtomicBool = AtomicBool::new(false);
18
19 const OWN_CRATE_PREFIXES: [&str; 10] = [
20 "app",
21 "app_base",
22 "state",
23 "calling",
24 "chatsvc",
25 "session",
26 "webview",
27 "mcp",
28 "agents",
29 "teams",
30 ];
11 31
12 32 const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
13 33 "AdmProxy",
@@ -21,50 +41,45 @@ const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
21 41
22 42 pub fn install(path: PathBuf) {
23 43 let _ = PATH.set(path);
24 if log::set_logger(&WebrtcAudioLog).is_ok() {
44 if log::set_logger(&DiagnosticsLog).is_ok() {
25 45 log::set_max_level(log::LevelFilter::Debug);
26 46 }
47 crate::support::install_panic_diagnostics_hook();
27 48 }
28 49
29 struct WebrtcAudioLog;
30
31 impl log::Log for WebrtcAudioLog {
32 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
33 metadata.target() == "libwebrtc"
34 }
35
36 fn log(&self, entry: &log::Record<'_>) {
37 if !self.enabled(entry.metadata()) {
38 return;
39 }
40 let text = entry.args().to_string();
41 if keeps_webrtc_line(&text) {
42 record(format!("webrtc: {text}"));
43 }
44 }
50 pub fn is_enabled() -> bool {
51 ENABLED.load(Ordering::Relaxed)
52 }
45 53
46 fn flush(&self) {}
54 pub fn set_enabled(on: bool) {
55 ENABLED.store(on, Ordering::Relaxed);
47 56 }
48 57
49 fn keeps_webrtc_line(text: &str) -> bool {
50 WEBRTC_AUDIO_MARKERS
51 .iter()
52 .any(|marker| text.contains(marker))
53 && !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
54 && !is_endpoint_dump(text)
58 pub fn enable_from_override() -> bool {
59 let on = std::env::args().any(|arg| arg == "--debug-log")
60 || std::env::var(ENV_DEBUG_LOG)
61 .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
62 .unwrap_or(false);
63 if on {
64 set_enabled(true);
65 }
66 on
55 67 }
56 68
57 fn is_endpoint_dump(text: &str) -> bool {
58 text.split_once("audio_device_core_win.cc:")
59 .and_then(|(_, rest)| rest.split_once(')'))
60 .and_then(|(line, _)| line.parse::<u32>().ok())
61 .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line))
69 pub fn load_enabled_from_store(stored: Option<&str>) -> bool {
70 let on = stored == Some("1");
71 set_enabled(on || is_enabled());
72 is_enabled()
62 73 }
63 74
64 75 pub fn directory() -> Option<PathBuf> {
65 76 PATH.get().and_then(|path| path.parent()).map(PathBuf::from)
66 77 }
67 78
79 pub fn path() -> Option<PathBuf> {
80 PATH.get().cloned()
81 }
82
68 83 pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
69 84 if elapsed >= SLOW_UI_HANDLER {
70 85 record(format!(
@@ -77,19 +92,118 @@ pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
77 92 pub fn record(message: impl AsRef<str>) {
78 93 let message = message.as_ref();
79 94 eprintln!("{message}");
95 if !is_enabled() {
96 return;
97 }
80 98 let Some(path) = PATH.get() else {
81 99 return;
82 100 };
83 let full = std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > MAX_BYTES);
84 let file = OpenOptions::new()
85 .create(true)
86 .write(true)
87 .append(!full)
88 .truncate(full)
89 .open(path);
90 if let Ok(mut file) = file {
91 let _ = writeln!(file, "{} {message}", line_prefix());
101 if let Err(error) = append_rotated(path, MAX_BYTES, RING_SLOTS, &format!("{} {message}\n", line_prefix()))
102 {
103 eprintln!("diagnostics write failed: {error}");
104 }
105 }
106
107 /// Chronological merge of `.1` then current (capped), for support packages.
108 pub fn read_merged(max_bytes: u64) -> String {
109 let Some(path) = PATH.get() else {
110 return String::new();
111 };
112 read_ring_merged(path, 1, max_bytes.min(MERGE_CAP_BYTES).max(1))
113 }
114
115 pub fn clear_logs() -> std::io::Result<()> {
116 let Some(root) = directory() else {
117 return Ok(());
118 };
119 for name in [
120 DIAGNOSTICS_FILE,
121 &format!("{DIAGNOSTICS_FILE}.1"),
122 &format!("{DIAGNOSTICS_FILE}.2"),
123 crate::crash_log::CRASH_LOG_FILE,
124 &format!("{}.1", crate::crash_log::CRASH_LOG_FILE),
125 ] {
126 let path = root.join(name);
127 if path.exists() {
128 let _ = fs::remove_file(&path);
129 }
130 }
131 let dumps = root.join(crate::support::CALL_DUMPS_DIR);
132 if dumps.is_dir() {
133 for entry in fs::read_dir(&dumps)?.flatten() {
134 let path = entry.path();
135 if path.is_dir() {
136 let _ = fs::remove_dir_all(path);
137 } else {
138 let _ = fs::remove_file(path);
139 }
140 }
92 141 }
142 Ok(())
143 }
144
145 pub(crate) fn append_rotated(
146 path: &Path,
147 max_bytes: u64,
148 ring_slots: u32,
149 line: &str,
150 ) -> std::io::Result<()> {
151 if path
152 .metadata()
153 .map(|meta| meta.len() >= max_bytes)
154 .unwrap_or(false)
155 {
156 rotate_ring(path, ring_slots)?;
157 }
158 if let Some(parent) = path.parent() {
159 fs::create_dir_all(parent)?;
160 }
161 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
162 file.write_all(line.as_bytes())
163 }
164
165 fn rotate_ring(path: &Path, ring_slots: u32) -> std::io::Result<()> {
166 for slot in (1..ring_slots).rev() {
167 let from = ring_path(path, slot);
168 let to = ring_path(path, slot + 1);
169 if from.exists() {
170 let _ = fs::remove_file(&to);
171 fs::rename(&from, &to)?;
172 }
173 }
174 let first = ring_path(path, 1);
175 let _ = fs::remove_file(&first);
176 if path.exists() {
177 fs::rename(path, &first)?;
178 }
179 Ok(())
180 }
181
182 fn ring_path(path: &Path, slot: u32) -> PathBuf {
183 path.with_file_name(format!(
184 "{}.{}",
185 path.file_name().and_then(|name| name.to_str()).unwrap_or(DIAGNOSTICS_FILE),
186 slot
187 ))
188 }
189
190 pub(crate) fn read_ring_merged(path: &Path, slots: u32, max_bytes: u64) -> String {
191 let mut parts = Vec::new();
192 for slot in (1..=slots).rev() {
193 let sibling = ring_path(path, slot);
194 if let Ok(text) = fs::read_to_string(&sibling) {
195 parts.push(text);
196 }
197 }
198 if let Ok(text) = fs::read_to_string(path) {
199 parts.push(text);
200 }
201 let merged = parts.join("");
202 if merged.len() as u64 <= max_bytes {
203 return merged;
204 }
205 let start = merged.len() - max_bytes as usize;
206 merged[start..].to_owned()
93 207 }
94 208
95 209 fn line_prefix() -> String {
@@ -100,31 +214,144 @@ fn line_prefix() -> String {
100 214 )
101 215 }
102 216
217 struct DiagnosticsLog;
218
219 impl log::Log for DiagnosticsLog {
220 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
221 if !is_enabled() {
222 return false;
223 }
224 let target = metadata.target();
225 if target == "libwebrtc" {
226 return true;
227 }
228 if is_own_crate(target) {
229 return metadata.level() <= log::Level::Info;
230 }
231 metadata.level() <= log::Level::Warn
232 }
233
234 fn log(&self, entry: &log::Record<'_>) {
235 if !self.enabled(entry.metadata()) {
236 return;
237 }
238 let target = entry.metadata().target();
239 let text = entry.args().to_string();
240 if target == "libwebrtc" {
241 if keeps_webrtc_line(entry.metadata().level(), &text) {
242 record(format!("webrtc: {text}"));
243 }
244 return;
245 }
246 let level = entry.metadata().level().as_str().to_ascii_lowercase();
247 let short = target.split("::").next().unwrap_or(target);
248 record(format!("{level} {short}: {text}"));
249 }
250
251 fn flush(&self) {}
252 }
253
254 fn is_own_crate(target: &str) -> bool {
255 let root = target.split("::").next().unwrap_or(target);
256 OWN_CRATE_PREFIXES
257 .iter()
258 .any(|prefix| root == *prefix || root.starts_with(&format!("{prefix}_")))
259 }
260
261 fn keeps_webrtc_line(level: log::Level, text: &str) -> bool {
262 if level <= log::Level::Warn
263 && (text.contains("peer_connection")
264 || text.contains("PeerConnection")
265 || text.contains("ICE")
266 || text.contains("ice_"))
267 {
268 return true;
269 }
270 WEBRTC_AUDIO_MARKERS
271 .iter()
272 .any(|marker| text.contains(marker))
273 && !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
274 && !is_endpoint_dump(text)
275 }
276
277 fn is_endpoint_dump(text: &str) -> bool {
278 text.split_once("audio_device_core_win.cc:")
279 .and_then(|(_, rest)| rest.split_once(')'))
280 .and_then(|(line, _)| line.parse::<u32>().ok())
281 .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line))
282 }
283
103 284 #[cfg(test)]
104 285 mod tests {
105 use super::keeps_webrtc_line;
286 use super::*;
287 use tempfile::tempdir;
106 288
107 289 #[test]
108 290 fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {
109 assert!(keeps_webrtc_line("(audio_device_impl.cc:123): Init"));
291 assert!(keeps_webrtc_line(log::Level::Debug, "(audio_device_impl.cc:123): Init"));
110 292 assert!(keeps_webrtc_line(
293 log::Level::Debug,
111 294 "(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
112 295 ));
113 296 assert!(!keeps_webrtc_line(
297 log::Level::Debug,
114 298 "(audio_device_core_win.cc:4090): endpoint 3"
115 299 ));
116 300 assert!(keeps_webrtc_line(
301 log::Level::Debug,
117 302 "(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"
118 303 ));
119 304 assert!(!keeps_webrtc_line(
305 log::Level::Debug,
120 306 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
121 307 ));
122 308 assert!(!keeps_webrtc_line(
309 log::Level::Debug,
123 310 "(audio_device_pulse_linux.cc:2236): requesting data"
124 311 ));
125 312 assert!(!keeps_webrtc_line(
313 log::Level::Debug,
126 314 "(audio_device_pulse_linux.cc:2256): will write"
127 315 ));
128 assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
316 assert!(!keeps_webrtc_line(
317 log::Level::Debug,
318 "(peer_connection.cc:55): something"
319 ));
320 assert!(keeps_webrtc_line(
321 log::Level::Warn,
322 "(peer_connection.cc:55): ICE failed"
323 ));
324 }
325
326 #[test]
327 fn enabled_gate_defaults_and_toggles() {
328 set_enabled(false);
329 assert!(!is_enabled());
330 set_enabled(true);
331 assert!(is_enabled());
332 set_enabled(false);
333 assert!(!is_enabled());
334 }
335
336 #[test]
337 fn ring_rotation_preserves_previous_content() {
338 let root = tempdir().unwrap();
339 let path = root.path().join(DIAGNOSTICS_FILE);
340 fs::write(&path, "a".repeat(MAX_BYTES as usize)).unwrap();
341 append_rotated(&path, MAX_BYTES, RING_SLOTS, "fresh-line\n").unwrap();
342 assert!(ring_path(&path, 1).exists());
343 let current = fs::read_to_string(&path).unwrap();
344 assert!(current.contains("fresh-line"));
345 assert!(!current.contains(&"a".repeat(32)));
346 let previous = fs::read_to_string(ring_path(&path, 1)).unwrap();
347 assert!(previous.starts_with('a'));
348 }
349
350 #[test]
351 fn own_crate_prefixes_match() {
352 assert!(is_own_crate("app::linux_browser"));
353 assert!(is_own_crate("state::notice"));
354 assert!(is_own_crate("app_base::diagnostics"));
355 assert!(!is_own_crate("hyper::client"));
129 356 }
130 357 }
@@ -1,13 +1,33 @@
1use std::fs::OpenOptions;
1use std::fs::{self, OpenOptions};
2use std::io::Write;
2use std::io::Write;
3use std::path::PathBuf;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::OnceLock;
5use std::sync::OnceLock;
5
6
6pub const DIAGNOSTICS_FILE: &str = "diagnostics.log";
7pub const DIAGNOSTICS_FILE: &str = "diagnostics.log";
8pub const DIAGNOSTICS_SETTING_KEY: &str = "diagnostics_enabled";
9pub const ENV_DEBUG_LOG: &str = "RUSTY_TEAMS_DEBUG_LOG";
10
7const MAX_BYTES: u64 = 1024 * 1024;
11const MAX_BYTES: u64 = 1024 * 1024;
12const RING_SLOTS: u32 = 2;
13const MERGE_CAP_BYTES: u64 = 1024 * 1024;
8const SLOW_UI_HANDLER: std::time::Duration = std::time::Duration::from_millis(30);
14const SLOW_UI_HANDLER: std::time::Duration = std::time::Duration::from_millis(30);
9
15
10static PATH: OnceLock<PathBuf> = OnceLock::new();
16static PATH: OnceLock<PathBuf> = OnceLock::new();
17static ENABLED: AtomicBool = AtomicBool::new(false);
18
19const OWN_CRATE_PREFIXES: [&str; 10] = [
20 "app",
21 "app_base",
22 "state",
23 "calling",
24 "chatsvc",
25 "session",
26 "webview",
27 "mcp",
28 "agents",
29 "teams",
30];
11
31
12const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
32const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
13 "AdmProxy",
33 "AdmProxy",
@@ -21,50 +41,45 @@ const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
21
41
22pub fn install(path: PathBuf) {
42pub fn install(path: PathBuf) {
23 let _ = PATH.set(path);
43 let _ = PATH.set(path);
24 if log::set_logger(&WebrtcAudioLog).is_ok() {
44 if log::set_logger(&DiagnosticsLog).is_ok() {
25 log::set_max_level(log::LevelFilter::Debug);
45 log::set_max_level(log::LevelFilter::Debug);
26 }
46 }
47 crate::support::install_panic_diagnostics_hook();
27}
48}
28
49
29struct WebrtcAudioLog;
50pub fn is_enabled() -> bool {
30
51 ENABLED.load(Ordering::Relaxed)
31impl log::Log for WebrtcAudioLog {
52}
32 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
33 metadata.target() == "libwebrtc"
34 }
35
36 fn log(&self, entry: &log::Record<'_>) {
37 if !self.enabled(entry.metadata()) {
38 return;
39 }
40 let text = entry.args().to_string();
41 if keeps_webrtc_line(&text) {
42 record(format!("webrtc: {text}"));
43 }
44 }
45
53
46 fn flush(&self) {}
54pub fn set_enabled(on: bool) {
55 ENABLED.store(on, Ordering::Relaxed);
47}
56}
48
57
49fn keeps_webrtc_line(text: &str) -> bool {
58pub fn enable_from_override() -> bool {
50 WEBRTC_AUDIO_MARKERS
59 let on = std::env::args().any(|arg| arg == "--debug-log")
51 .iter()
60 || std::env::var(ENV_DEBUG_LOG)
52 .any(|marker| text.contains(marker))
61 .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
53 && !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
62 .unwrap_or(false);
54 && !is_endpoint_dump(text)
63 if on {
64 set_enabled(true);
65 }
66 on
55}
67}
56
68
57fn is_endpoint_dump(text: &str) -> bool {
69pub fn load_enabled_from_store(stored: Option<&str>) -> bool {
58 text.split_once("audio_device_core_win.cc:")
70 let on = stored == Some("1");
59 .and_then(|(_, rest)| rest.split_once(')'))
71 set_enabled(on || is_enabled());
60 .and_then(|(line, _)| line.parse::<u32>().ok())
72 is_enabled()
61 .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line))
62}
73}
63
74
64pub fn directory() -> Option<PathBuf> {
75pub fn directory() -> Option<PathBuf> {
65 PATH.get().and_then(|path| path.parent()).map(PathBuf::from)
76 PATH.get().and_then(|path| path.parent()).map(PathBuf::from)
66}
77}
67
78
79pub fn path() -> Option<PathBuf> {
80 PATH.get().cloned()
81}
82
68pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
83pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
69 if elapsed >= SLOW_UI_HANDLER {
84 if elapsed >= SLOW_UI_HANDLER {
70 record(format!(
85 record(format!(
@@ -77,19 +92,118 @@ pub fn record_if_slow(label: &str, elapsed: std::time::Duration) {
77pub fn record(message: impl AsRef<str>) {
92pub fn record(message: impl AsRef<str>) {
78 let message = message.as_ref();
93 let message = message.as_ref();
79 eprintln!("{message}");
94 eprintln!("{message}");
95 if !is_enabled() {
96 return;
97 }
80 let Some(path) = PATH.get() else {
98 let Some(path) = PATH.get() else {
81 return;
99 return;
82 };
100 };
83 let full = std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > MAX_BYTES);
101 if let Err(error) = append_rotated(path, MAX_BYTES, RING_SLOTS, &format!("{} {message}\n", line_prefix()))
84 let file = OpenOptions::new()
102 {
85 .create(true)
103 eprintln!("diagnostics write failed: {error}");
86 .write(true)
104 }
87 .append(!full)
105}
88 .truncate(full)
106
89 .open(path);
107/// Chronological merge of `.1` then current (capped), for support packages.
90 if let Ok(mut file) = file {
108pub fn read_merged(max_bytes: u64) -> String {
91 let _ = writeln!(file, "{} {message}", line_prefix());
109 let Some(path) = PATH.get() else {
110 return String::new();
111 };
112 read_ring_merged(path, 1, max_bytes.min(MERGE_CAP_BYTES).max(1))
113}
114
115pub fn clear_logs() -> std::io::Result<()> {
116 let Some(root) = directory() else {
117 return Ok(());
118 };
119 for name in [
120 DIAGNOSTICS_FILE,
121 &format!("{DIAGNOSTICS_FILE}.1"),
122 &format!("{DIAGNOSTICS_FILE}.2"),
123 crate::crash_log::CRASH_LOG_FILE,
124 &format!("{}.1", crate::crash_log::CRASH_LOG_FILE),
125 ] {
126 let path = root.join(name);
127 if path.exists() {
128 let _ = fs::remove_file(&path);
129 }
130 }
131 let dumps = root.join(crate::support::CALL_DUMPS_DIR);
132 if dumps.is_dir() {
133 for entry in fs::read_dir(&dumps)?.flatten() {
134 let path = entry.path();
135 if path.is_dir() {
136 let _ = fs::remove_dir_all(path);
137 } else {
138 let _ = fs::remove_file(path);
139 }
140 }
92 }
141 }
142 Ok(())
143}
144
145pub(crate) fn append_rotated(
146 path: &Path,
147 max_bytes: u64,
148 ring_slots: u32,
149 line: &str,
150) -> std::io::Result<()> {
151 if path
152 .metadata()
153 .map(|meta| meta.len() >= max_bytes)
154 .unwrap_or(false)
155 {
156 rotate_ring(path, ring_slots)?;
157 }
158 if let Some(parent) = path.parent() {
159 fs::create_dir_all(parent)?;
160 }
161 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
162 file.write_all(line.as_bytes())
163}
164
165fn rotate_ring(path: &Path, ring_slots: u32) -> std::io::Result<()> {
166 for slot in (1..ring_slots).rev() {
167 let from = ring_path(path, slot);
168 let to = ring_path(path, slot + 1);
169 if from.exists() {
170 let _ = fs::remove_file(&to);
171 fs::rename(&from, &to)?;
172 }
173 }
174 let first = ring_path(path, 1);
175 let _ = fs::remove_file(&first);
176 if path.exists() {
177 fs::rename(path, &first)?;
178 }
179 Ok(())
180}
181
182fn ring_path(path: &Path, slot: u32) -> PathBuf {
183 path.with_file_name(format!(
184 "{}.{}",
185 path.file_name().and_then(|name| name.to_str()).unwrap_or(DIAGNOSTICS_FILE),
186 slot
187 ))
188}
189
190pub(crate) fn read_ring_merged(path: &Path, slots: u32, max_bytes: u64) -> String {
191 let mut parts = Vec::new();
192 for slot in (1..=slots).rev() {
193 let sibling = ring_path(path, slot);
194 if let Ok(text) = fs::read_to_string(&sibling) {
195 parts.push(text);
196 }
197 }
198 if let Ok(text) = fs::read_to_string(path) {
199 parts.push(text);
200 }
201 let merged = parts.join("");
202 if merged.len() as u64 <= max_bytes {
203 return merged;
204 }
205 let start = merged.len() - max_bytes as usize;
206 merged[start..].to_owned()
93}
207}
94
208
95fn line_prefix() -> String {
209fn line_prefix() -> String {
@@ -100,31 +214,144 @@ fn line_prefix() -> String {
100 )
214 )
101}
215}
102
216
217struct DiagnosticsLog;
218
219impl log::Log for DiagnosticsLog {
220 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
221 if !is_enabled() {
222 return false;
223 }
224 let target = metadata.target();
225 if target == "libwebrtc" {
226 return true;
227 }
228 if is_own_crate(target) {
229 return metadata.level() <= log::Level::Info;
230 }
231 metadata.level() <= log::Level::Warn
232 }
233
234 fn log(&self, entry: &log::Record<'_>) {
235 if !self.enabled(entry.metadata()) {
236 return;
237 }
238 let target = entry.metadata().target();
239 let text = entry.args().to_string();
240 if target == "libwebrtc" {
241 if keeps_webrtc_line(entry.metadata().level(), &text) {
242 record(format!("webrtc: {text}"));
243 }
244 return;
245 }
246 let level = entry.metadata().level().as_str().to_ascii_lowercase();
247 let short = target.split("::").next().unwrap_or(target);
248 record(format!("{level} {short}: {text}"));
249 }
250
251 fn flush(&self) {}
252}
253
254fn is_own_crate(target: &str) -> bool {
255 let root = target.split("::").next().unwrap_or(target);
256 OWN_CRATE_PREFIXES
257 .iter()
258 .any(|prefix| root == *prefix || root.starts_with(&format!("{prefix}_")))
259}
260
261fn keeps_webrtc_line(level: log::Level, text: &str) -> bool {
262 if level <= log::Level::Warn
263 && (text.contains("peer_connection")
264 || text.contains("PeerConnection")
265 || text.contains("ICE")
266 || text.contains("ice_"))
267 {
268 return true;
269 }
270 WEBRTC_AUDIO_MARKERS
271 .iter()
272 .any(|marker| text.contains(marker))
273 && !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
274 && !is_endpoint_dump(text)
275}
276
277fn is_endpoint_dump(text: &str) -> bool {
278 text.split_once("audio_device_core_win.cc:")
279 .and_then(|(_, rest)| rest.split_once(')'))
280 .and_then(|(line, _)| line.parse::<u32>().ok())
281 .is_some_and(|line| ENDPOINT_DUMP_LINES.contains(&line))
282}
283
103#[cfg(test)]
284#[cfg(test)]
104mod tests {
285mod tests {
105 use super::keeps_webrtc_line;
286 use super::*;
287 use tempfile::tempdir;
106
288
107 #[test]
289 #[test]
108 fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {
290 fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {
109 assert!(keeps_webrtc_line("(audio_device_impl.cc:123): Init"));
291 assert!(keeps_webrtc_line(log::Level::Debug, "(audio_device_impl.cc:123): Init"));
110 assert!(keeps_webrtc_line(
292 assert!(keeps_webrtc_line(
293 log::Level::Debug,
111 "(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
294 "(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
112 ));
295 ));
113 assert!(!keeps_webrtc_line(
296 assert!(!keeps_webrtc_line(
297 log::Level::Debug,
114 "(audio_device_core_win.cc:4090): endpoint 3"
298 "(audio_device_core_win.cc:4090): endpoint 3"
115 ));
299 ));
116 assert!(keeps_webrtc_line(
300 assert!(keeps_webrtc_line(
301 log::Level::Debug,
117 "(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"
302 "(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"
118 ));
303 ));
119 assert!(!keeps_webrtc_line(
304 assert!(!keeps_webrtc_line(
305 log::Level::Debug,
120 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
306 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
121 ));
307 ));
122 assert!(!keeps_webrtc_line(
308 assert!(!keeps_webrtc_line(
309 log::Level::Debug,
123 "(audio_device_pulse_linux.cc:2236): requesting data"
310 "(audio_device_pulse_linux.cc:2236): requesting data"
124 ));
311 ));
125 assert!(!keeps_webrtc_line(
312 assert!(!keeps_webrtc_line(
313 log::Level::Debug,
126 "(audio_device_pulse_linux.cc:2256): will write"
314 "(audio_device_pulse_linux.cc:2256): will write"
127 ));
315 ));
128 assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
316 assert!(!keeps_webrtc_line(
317 log::Level::Debug,
318 "(peer_connection.cc:55): something"
319 ));
320 assert!(keeps_webrtc_line(
321 log::Level::Warn,
322 "(peer_connection.cc:55): ICE failed"
323 ));
324 }
325
326 #[test]
327 fn enabled_gate_defaults_and_toggles() {
328 set_enabled(false);
329 assert!(!is_enabled());
330 set_enabled(true);
331 assert!(is_enabled());
332 set_enabled(false);
333 assert!(!is_enabled());
334 }
335
336 #[test]
337 fn ring_rotation_preserves_previous_content() {
338 let root = tempdir().unwrap();
339 let path = root.path().join(DIAGNOSTICS_FILE);
340 fs::write(&path, "a".repeat(MAX_BYTES as usize)).unwrap();
341 append_rotated(&path, MAX_BYTES, RING_SLOTS, "fresh-line\n").unwrap();
342 assert!(ring_path(&path, 1).exists());
343 let current = fs::read_to_string(&path).unwrap();
344 assert!(current.contains("fresh-line"));
345 assert!(!current.contains(&"a".repeat(32)));
346 let previous = fs::read_to_string(ring_path(&path, 1)).unwrap();
347 assert!(previous.starts_with('a'));
348 }
349
350 #[test]
351 fn own_crate_prefixes_match() {
352 assert!(is_own_crate("app::linux_browser"));
353 assert!(is_own_crate("state::notice"));
354 assert!(is_own_crate("app_base::diagnostics"));
355 assert!(!is_own_crate("hyper::client"));
129 }
356 }
130}
357}
crates/app-base/src/lib.rs +1 −0
@@ -35,6 +35,7 @@ pub mod runtime;
35 35 pub mod schedule_time;
36 36 pub mod single_instance;
37 37 pub mod stickers;
38 pub mod support;
38 39 pub mod task_dialog;
39 40 pub mod theme;
40 41 pub mod translation;
@@ -35,6 +35,7 @@ pub mod runtime;
35pub mod schedule_time;
35pub mod schedule_time;
36pub mod single_instance;
36pub mod single_instance;
37pub mod stickers;
37pub mod stickers;
38pub mod support;
38pub mod task_dialog;
39pub mod task_dialog;
39pub mod theme;
40pub mod theme;
40pub mod translation;
41pub mod translation;
crates/app-base/src/support.rs added +490 −0
@@ -0,0 +1,490 @@
1 use std::path::{Path, PathBuf};
2
3 use crate::diagnostics;
4 use crate::version;
5
6 pub const SUPPORT_BUNDLES_DIR: &str = "support-bundles";
7 pub const CALL_REPORTS_DIR: &str = "call-reports";
8 pub const CALL_DUMPS_DIR: &str = "call-dumps";
9 pub const CRASH_LOG_FILE: &str = "crash.log";
10
11 /// Upstream tracker — fork mirror has Issues disabled.
12 pub const GITHUB_ISSUES_NEW: &str = "https://github.com/danieldaeschle/rusty-teams/issues/new";
13
14 /// Runtime facts for Help, `client.md`, clipboard, and issue drafts. English keys only.
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct ClientInfo {
17 pub version: String,
18 pub build: String,
19 pub os: String,
20 pub arch: String,
21 pub session: String,
22 pub ui_locale: String,
23 pub timezone: String,
24 pub signed_in: bool,
25 pub call_reports: bool,
26 pub debug_logging: bool,
27 pub audio_input: String,
28 pub audio_output: String,
29 pub camera: String,
30 pub logs_root: String,
31 pub support_bundles_root: String,
32 }
33
34 impl ClientInfo {
35 pub fn capture(
36 package_version: &str,
37 ui_locale: &str,
38 signed_in: bool,
39 call_reports: bool,
40 audio_input: impl Into<String>,
41 audio_output: impl Into<String>,
42 camera: impl Into<String>,
43 ) -> Self {
44 let logs_root = local_data_dir()
45 .map(|path| path.display().to_string())
46 .unwrap_or_else(|| "unknown".to_owned());
47 let support_bundles_root = support_bundles_dir()
48 .map(|path| path.display().to_string())
49 .unwrap_or_else(|| "unknown".to_owned());
50 ClientInfo {
51 version: package_version.to_owned(),
52 build: version::build_version().to_owned(),
53 os: std::env::consts::OS.to_owned(),
54 arch: std::env::consts::ARCH.to_owned(),
55 session: desktop_session(),
56 ui_locale: ui_locale.to_owned(),
57 timezone: timezone_name(),
58 signed_in,
59 call_reports,
60 debug_logging: diagnostics::is_enabled(),
61 audio_input: audio_input.into(),
62 audio_output: audio_output.into(),
63 camera: camera.into(),
64 logs_root,
65 support_bundles_root,
66 }
67 }
68
69 pub fn markdown(&self) -> String {
70 format!(
71 "### Client\n\
72 - Version: {}\n\
73 - Build: {}\n\
74 - OS: {} ({})\n\
75 - Session: {}\n\
76 - UI language: {}\n\
77 - Timezone: {}\n\
78 - Signed in: {}\n\
79 - Call reports: {}\n\
80 - Debug logging: {}\n\
81 - Audio input: {}\n\
82 - Audio output: {}\n\
83 - Camera: {}\n\
84 - Logs root: {}\n\
85 - Support bundles: {}\n",
86 self.version,
87 self.build,
88 self.os,
89 self.arch,
90 self.session,
91 self.ui_locale,
92 self.timezone,
93 yes_no(self.signed_in),
94 yes_no(self.call_reports),
95 yes_no(self.debug_logging),
96 self.audio_input,
97 self.audio_output,
98 self.camera,
99 self.logs_root,
100 self.support_bundles_root,
101 )
102 }
103
104 pub fn one_line(&self) -> String {
105 format!(
106 "client version={} build={} os={}/{} session={} locale={} tz={} signed_in={} call_reports={} debug_logging={} logs={}",
107 self.version,
108 self.build,
109 self.os,
110 self.arch,
111 self.session,
112 self.ui_locale,
113 self.timezone,
114 yes_no(self.signed_in),
115 yes_no(self.call_reports),
116 yes_no(self.debug_logging),
117 self.logs_root,
118 )
119 }
120 }
121
122 fn yes_no(value: bool) -> &'static str {
123 if value { "yes" } else { "no" }
124 }
125
126 pub fn desktop_session() -> String {
127 #[cfg(target_os = "linux")]
128 {
129 std::env::var("XDG_SESSION_TYPE")
130 .ok()
131 .filter(|value| !value.is_empty())
132 .unwrap_or_else(|| "unknown".to_owned())
133 }
134 #[cfg(target_os = "macos")]
135 {
136 "macos".to_owned()
137 }
138 #[cfg(target_os = "windows")]
139 {
140 "windows".to_owned()
141 }
142 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
143 {
144 "unknown".to_owned()
145 }
146 }
147
148 fn timezone_name() -> String {
149 std::env::var("TZ")
150 .ok()
151 .filter(|value| !value.is_empty())
152 .unwrap_or_else(|| format!("{}", chrono::Local::now().offset()))
153 }
154
155 /// OS local application data root for `ms-teams-linux` (legacy product directory name).
156 pub fn local_data_dir() -> Option<PathBuf> {
157 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
158 .map(|directories| directories.data_local_dir().to_path_buf())
159 }
160
161 pub fn diagnostics_log_path() -> Option<PathBuf> {
162 local_data_dir().map(|root| root.join(diagnostics::DIAGNOSTICS_FILE))
163 }
164
165 pub fn crash_log_path() -> Option<PathBuf> {
166 local_data_dir().map(|root| root.join(CRASH_LOG_FILE))
167 }
168
169 pub fn call_dumps_dir() -> Option<PathBuf> {
170 local_data_dir().map(|root| root.join(CALL_DUMPS_DIR))
171 }
172
173 pub fn call_reports_dir() -> Option<PathBuf> {
174 local_data_dir().map(|root| root.join(CALL_REPORTS_DIR))
175 }
176
177 pub fn support_bundles_dir() -> Option<PathBuf> {
178 local_data_dir().map(|root| root.join(SUPPORT_BUNDLES_DIR))
179 }
180
181 pub fn support_bundles_directory(data_dir: &Path) -> PathBuf {
182 data_dir.join(SUPPORT_BUNDLES_DIR)
183 }
184
185 pub fn bundle_folder_name(utc: chrono::DateTime<chrono::Utc>) -> String {
186 format!("support-{}", utc.format("%Y%m%dT%H%M%SZ"))
187 }
188
189 #[derive(Debug, Clone, PartialEq, Eq)]
190 pub struct SupportBundleEntry {
191 pub directory: PathBuf,
192 pub name: String,
193 }
194
195 #[derive(Debug, Clone, PartialEq, Eq)]
196 pub struct BundleFileEntry {
197 pub path: PathBuf,
198 pub name: String,
199 pub size_bytes: u64,
200 }
201
202 /// Newest-first list of package folders under `support-bundles/`.
203 pub fn list_support_bundles(root: &Path) -> std::io::Result<Vec<SupportBundleEntry>> {
204 if !root.is_dir() {
205 return Ok(Vec::new());
206 }
207 let mut entries: Vec<SupportBundleEntry> = std::fs::read_dir(root)?
208 .filter_map(Result::ok)
209 .map(|entry| entry.path())
210 .filter(|path| path.is_dir())
211 .filter_map(|directory| {
212 let name = directory.file_name()?.to_string_lossy().into_owned();
213 Some(SupportBundleEntry { directory, name })
214 })
215 .collect();
216 entries.sort_by(|left, right| right.name.cmp(&left.name));
217 Ok(entries)
218 }
219
220 pub fn list_bundle_files(bundle: &Path) -> std::io::Result<Vec<BundleFileEntry>> {
221 if !bundle.is_dir() {
222 return Ok(Vec::new());
223 }
224 let mut files: Vec<BundleFileEntry> = std::fs::read_dir(bundle)?
225 .filter_map(Result::ok)
226 .map(|entry| entry.path())
227 .filter(|path| path.is_file())
228 .filter_map(|path| {
229 let name = path.file_name()?.to_string_lossy().into_owned();
230 let size_bytes = std::fs::metadata(&path).ok()?.len();
231 Some(BundleFileEntry {
232 path,
233 name,
234 size_bytes,
235 })
236 })
237 .collect();
238 files.sort_by(|left, right| left.name.cmp(&right.name));
239 Ok(files)
240 }
241
242 /// Remove one support package directory. Refuses paths outside `parent` when provided.
243 pub fn delete_support_bundle(bundle: &Path, parent: Option<&Path>) -> std::io::Result<()> {
244 if let Some(parent) = parent {
245 let canonical_parent = parent.canonicalize().unwrap_or_else(|_| parent.to_path_buf());
246 let canonical_bundle = bundle.canonicalize().unwrap_or_else(|_| bundle.to_path_buf());
247 if !canonical_bundle.starts_with(&canonical_parent) {
248 return Err(std::io::Error::new(
249 std::io::ErrorKind::InvalidInput,
250 "bundle path is outside the support-bundles directory",
251 ));
252 }
253 }
254 if bundle.is_dir() {
255 std::fs::remove_dir_all(bundle)?;
256 }
257 Ok(())
258 }
259
260 pub fn ensure_dir(path: &Path) -> std::io::Result<()> {
261 std::fs::create_dir_all(path)
262 }
263
264 pub fn format_bytes(size: u64) -> String {
265 const KB: u64 = 1024;
266 const MB: u64 = KB * 1024;
267 if size >= MB {
268 format!("{:.1} MB", size as f64 / MB as f64)
269 } else if size >= KB {
270 format!("{:.1} KB", size as f64 / KB as f64)
271 } else {
272 format!("{size} B")
273 }
274 }
275
276 pub fn issue_title() -> &'static str {
277 "Bug report"
278 }
279
280 pub fn issue_body(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
281 format!(
282 "## What happened\n\n\
283 <!-- Describe the bug -->\n\n\
284 ## Expected\n\n\
285 <!-- What should happen -->\n\n\
286 {}\n\
287 Support package folder: `{}`\n\
288 Support package path: `{}`\n\n\
289 Attach the files from that folder (do not paste secrets).\n",
290 client.markdown(),
291 bundle.folder_name,
292 bundle.directory.display(),
293 )
294 }
295
296 #[derive(Debug, Clone, PartialEq, Eq)]
297 pub struct SupportBundlePaths {
298 pub directory: PathBuf,
299 pub folder_name: String,
300 }
301
302 pub fn issue_url(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
303 format!(
304 "{GITHUB_ISSUES_NEW}?title={}&body={}",
305 encode_query(issue_title()),
306 encode_query(&issue_body(client, bundle))
307 )
308 }
309
310 pub fn encode_query(value: &str) -> String {
311 let mut out = String::with_capacity(value.len() * 3);
312 for byte in value.bytes() {
313 match byte {
314 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
315 out.push(byte as char);
316 }
317 b' ' => out.push_str("%20"),
318 _ => out.push_str(&format!("%{byte:02X}")),
319 }
320 }
321 out
322 }
323
324 /// Append a client snapshot when debug logging is on (after store/locale when possible).
325 pub fn record_startup_client_line(
326 package_version: &str,
327 ui_locale: &str,
328 signed_in: bool,
329 call_reports: bool,
330 ) {
331 if !diagnostics::is_enabled() {
332 return;
333 }
334 let info = ClientInfo::capture(
335 package_version,
336 ui_locale,
337 signed_in,
338 call_reports,
339 "n/a",
340 "n/a",
341 "n/a",
342 );
343 diagnostics::record(info.one_line());
344 }
345
346 /// Chain a panic hook that also writes a short line into the diagnostics log.
347 pub fn install_panic_diagnostics_hook() {
348 let previous = std::panic::take_hook();
349 std::panic::set_hook(Box::new(move |info| {
350 let payload = info.payload();
351 let message = payload
352 .downcast_ref::<&str>()
353 .copied()
354 .map(str::to_owned)
355 .or_else(|| payload.downcast_ref::<String>().cloned())
356 .unwrap_or_else(|| "non-text panic payload".to_owned());
357 let location = info
358 .location()
359 .map(|location| {
360 format!(
361 "{}:{}:{}",
362 location.file(),
363 location.line(),
364 location.column()
365 )
366 })
367 .unwrap_or_else(|| "unknown".to_owned());
368 diagnostics::record(format!("panic at {location}: {message}"));
369 previous(info);
370 }));
371 }
372
373 pub fn readme_text() -> &'static str {
374 "Attach the files in this folder to a GitHub issue on danieldaeschle/rusty-teams.\n\
375 The app store, cookies, and tokens are not included.\n"
376 }
377
378 #[cfg(test)]
379 mod tests {
380 use super::*;
381
382 fn sample_client() -> ClientInfo {
383 ClientInfo {
384 version: "0.3.0".into(),
385 build: "abc".into(),
386 os: "linux".into(),
387 arch: "x86_64".into(),
388 session: "wayland".into(),
389 ui_locale: "de".into(),
390 timezone: "Europe/Zurich".into(),
391 signed_in: true,
392 call_reports: false,
393 debug_logging: true,
394 audio_input: "Default device".into(),
395 audio_output: "Default device".into(),
396 camera: "none".into(),
397 logs_root: "/tmp/ms-teams-linux".into(),
398 support_bundles_root: "/tmp/ms-teams-linux/support-bundles".into(),
399 }
400 }
401
402 #[test]
403 fn markdown_block_lists_stable_keys_and_paths() {
404 let text = sample_client().markdown();
405 assert!(text.contains("- Version: 0.3.0"));
406 assert!(text.contains("- Build: abc"));
407 assert!(text.contains("- OS: linux (x86_64)"));
408 assert!(text.contains("- Session: wayland"));
409 assert!(text.contains("- Signed in: yes"));
410 assert!(text.contains("- Call reports: no"));
411 assert!(text.contains("- Logs root: /tmp/ms-teams-linux"));
412 assert!(text.contains("- Support bundles: /tmp/ms-teams-linux/support-bundles"));
413 assert!(!text.contains('@'));
414 }
415
416 #[test]
417 fn layout_relative_names_are_stable() {
418 assert_eq!(SUPPORT_BUNDLES_DIR, "support-bundles");
419 assert_eq!(CALL_REPORTS_DIR, "call-reports");
420 assert_eq!(CALL_DUMPS_DIR, "call-dumps");
421 assert_eq!(CRASH_LOG_FILE, "crash.log");
422 assert_eq!(diagnostics::DIAGNOSTICS_FILE, "diagnostics.log");
423 let root = PathBuf::from("/data/ms-teams-linux");
424 assert_eq!(
425 support_bundles_directory(&root),
426 root.join("support-bundles")
427 );
428 }
429
430 #[test]
431 fn issue_url_encodes_spaces_and_newlines() {
432 let info = sample_client();
433 let bundle = SupportBundlePaths {
434 directory: PathBuf::from("/tmp/ms-teams-linux/support-bundles/support-20260101T000000Z"),
435 folder_name: "support-20260101T000000Z".into(),
436 };
437 let url = issue_url(&info, &bundle);
438 assert!(url.starts_with(GITHUB_ISSUES_NEW));
439 assert!(url.contains("title=Bug%20report"));
440 assert!(url.contains("body="));
441 assert!(url.contains("support-20260101T000000Z"));
442 assert!(!url.contains(' '));
443 }
444
445 #[test]
446 fn encode_query_percent_encodes_specials() {
447 assert_eq!(encode_query("a b"), "a%20b");
448 assert_eq!(encode_query("a&b"), "a%26b");
449 }
450
451 #[test]
452 fn list_and_delete_support_bundles_in_temp_dir() {
453 let root = tempfile::tempdir().unwrap();
454 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
455 let older = bundles.join("support-20260101T000000Z");
456 let newer = bundles.join("support-20260102T000000Z");
457 std::fs::create_dir_all(&older).unwrap();
458 std::fs::create_dir_all(&newer).unwrap();
459 std::fs::write(older.join("client.md"), "old").unwrap();
460 std::fs::write(newer.join("client.md"), "new").unwrap();
461 std::fs::write(newer.join("diagnostics.log"), "log").unwrap();
462
463 let listed = list_support_bundles(&bundles).unwrap();
464 assert_eq!(listed.len(), 2);
465 assert_eq!(listed[0].name, "support-20260102T000000Z");
466 assert_eq!(listed[1].name, "support-20260101T000000Z");
467
468 let files = list_bundle_files(&newer).unwrap();
469 assert_eq!(files.len(), 2);
470 assert_eq!(files[0].name, "client.md");
471 assert_eq!(files[1].name, "diagnostics.log");
472
473 delete_support_bundle(&newer, Some(&bundles)).unwrap();
474 let listed = list_support_bundles(&bundles).unwrap();
475 assert_eq!(listed.len(), 1);
476 assert_eq!(listed[0].name, "support-20260101T000000Z");
477 assert!(!newer.exists());
478 }
479
480 #[test]
481 fn delete_refuses_paths_outside_parent() {
482 let root = tempfile::tempdir().unwrap();
483 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
484 let outside = root.path().join("other");
485 std::fs::create_dir_all(&bundles).unwrap();
486 std::fs::create_dir_all(&outside).unwrap();
487 assert!(delete_support_bundle(&outside, Some(&bundles)).is_err());
488 assert!(outside.exists());
489 }
490 }
@@ -0,0 +1,490 @@
1use std::path::{Path, PathBuf};
2
3use crate::diagnostics;
4use crate::version;
5
6pub const SUPPORT_BUNDLES_DIR: &str = "support-bundles";
7pub const CALL_REPORTS_DIR: &str = "call-reports";
8pub const CALL_DUMPS_DIR: &str = "call-dumps";
9pub const CRASH_LOG_FILE: &str = "crash.log";
10
11/// Upstream tracker — fork mirror has Issues disabled.
12pub const GITHUB_ISSUES_NEW: &str = "https://github.com/danieldaeschle/rusty-teams/issues/new";
13
14/// Runtime facts for Help, `client.md`, clipboard, and issue drafts. English keys only.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ClientInfo {
17 pub version: String,
18 pub build: String,
19 pub os: String,
20 pub arch: String,
21 pub session: String,
22 pub ui_locale: String,
23 pub timezone: String,
24 pub signed_in: bool,
25 pub call_reports: bool,
26 pub debug_logging: bool,
27 pub audio_input: String,
28 pub audio_output: String,
29 pub camera: String,
30 pub logs_root: String,
31 pub support_bundles_root: String,
32}
33
34impl ClientInfo {
35 pub fn capture(
36 package_version: &str,
37 ui_locale: &str,
38 signed_in: bool,
39 call_reports: bool,
40 audio_input: impl Into<String>,
41 audio_output: impl Into<String>,
42 camera: impl Into<String>,
43 ) -> Self {
44 let logs_root = local_data_dir()
45 .map(|path| path.display().to_string())
46 .unwrap_or_else(|| "unknown".to_owned());
47 let support_bundles_root = support_bundles_dir()
48 .map(|path| path.display().to_string())
49 .unwrap_or_else(|| "unknown".to_owned());
50 ClientInfo {
51 version: package_version.to_owned(),
52 build: version::build_version().to_owned(),
53 os: std::env::consts::OS.to_owned(),
54 arch: std::env::consts::ARCH.to_owned(),
55 session: desktop_session(),
56 ui_locale: ui_locale.to_owned(),
57 timezone: timezone_name(),
58 signed_in,
59 call_reports,
60 debug_logging: diagnostics::is_enabled(),
61 audio_input: audio_input.into(),
62 audio_output: audio_output.into(),
63 camera: camera.into(),
64 logs_root,
65 support_bundles_root,
66 }
67 }
68
69 pub fn markdown(&self) -> String {
70 format!(
71 "### Client\n\
72 - Version: {}\n\
73 - Build: {}\n\
74 - OS: {} ({})\n\
75 - Session: {}\n\
76 - UI language: {}\n\
77 - Timezone: {}\n\
78 - Signed in: {}\n\
79 - Call reports: {}\n\
80 - Debug logging: {}\n\
81 - Audio input: {}\n\
82 - Audio output: {}\n\
83 - Camera: {}\n\
84 - Logs root: {}\n\
85 - Support bundles: {}\n",
86 self.version,
87 self.build,
88 self.os,
89 self.arch,
90 self.session,
91 self.ui_locale,
92 self.timezone,
93 yes_no(self.signed_in),
94 yes_no(self.call_reports),
95 yes_no(self.debug_logging),
96 self.audio_input,
97 self.audio_output,
98 self.camera,
99 self.logs_root,
100 self.support_bundles_root,
101 )
102 }
103
104 pub fn one_line(&self) -> String {
105 format!(
106 "client version={} build={} os={}/{} session={} locale={} tz={} signed_in={} call_reports={} debug_logging={} logs={}",
107 self.version,
108 self.build,
109 self.os,
110 self.arch,
111 self.session,
112 self.ui_locale,
113 self.timezone,
114 yes_no(self.signed_in),
115 yes_no(self.call_reports),
116 yes_no(self.debug_logging),
117 self.logs_root,
118 )
119 }
120}
121
122fn yes_no(value: bool) -> &'static str {
123 if value { "yes" } else { "no" }
124}
125
126pub fn desktop_session() -> String {
127 #[cfg(target_os = "linux")]
128 {
129 std::env::var("XDG_SESSION_TYPE")
130 .ok()
131 .filter(|value| !value.is_empty())
132 .unwrap_or_else(|| "unknown".to_owned())
133 }
134 #[cfg(target_os = "macos")]
135 {
136 "macos".to_owned()
137 }
138 #[cfg(target_os = "windows")]
139 {
140 "windows".to_owned()
141 }
142 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
143 {
144 "unknown".to_owned()
145 }
146}
147
148fn timezone_name() -> String {
149 std::env::var("TZ")
150 .ok()
151 .filter(|value| !value.is_empty())
152 .unwrap_or_else(|| format!("{}", chrono::Local::now().offset()))
153}
154
155/// OS local application data root for `ms-teams-linux` (legacy product directory name).
156pub fn local_data_dir() -> Option<PathBuf> {
157 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
158 .map(|directories| directories.data_local_dir().to_path_buf())
159}
160
161pub fn diagnostics_log_path() -> Option<PathBuf> {
162 local_data_dir().map(|root| root.join(diagnostics::DIAGNOSTICS_FILE))
163}
164
165pub fn crash_log_path() -> Option<PathBuf> {
166 local_data_dir().map(|root| root.join(CRASH_LOG_FILE))
167}
168
169pub fn call_dumps_dir() -> Option<PathBuf> {
170 local_data_dir().map(|root| root.join(CALL_DUMPS_DIR))
171}
172
173pub fn call_reports_dir() -> Option<PathBuf> {
174 local_data_dir().map(|root| root.join(CALL_REPORTS_DIR))
175}
176
177pub fn support_bundles_dir() -> Option<PathBuf> {
178 local_data_dir().map(|root| root.join(SUPPORT_BUNDLES_DIR))
179}
180
181pub fn support_bundles_directory(data_dir: &Path) -> PathBuf {
182 data_dir.join(SUPPORT_BUNDLES_DIR)
183}
184
185pub fn bundle_folder_name(utc: chrono::DateTime<chrono::Utc>) -> String {
186 format!("support-{}", utc.format("%Y%m%dT%H%M%SZ"))
187}
188
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct SupportBundleEntry {
191 pub directory: PathBuf,
192 pub name: String,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct BundleFileEntry {
197 pub path: PathBuf,
198 pub name: String,
199 pub size_bytes: u64,
200}
201
202/// Newest-first list of package folders under `support-bundles/`.
203pub fn list_support_bundles(root: &Path) -> std::io::Result<Vec<SupportBundleEntry>> {
204 if !root.is_dir() {
205 return Ok(Vec::new());
206 }
207 let mut entries: Vec<SupportBundleEntry> = std::fs::read_dir(root)?
208 .filter_map(Result::ok)
209 .map(|entry| entry.path())
210 .filter(|path| path.is_dir())
211 .filter_map(|directory| {
212 let name = directory.file_name()?.to_string_lossy().into_owned();
213 Some(SupportBundleEntry { directory, name })
214 })
215 .collect();
216 entries.sort_by(|left, right| right.name.cmp(&left.name));
217 Ok(entries)
218}
219
220pub fn list_bundle_files(bundle: &Path) -> std::io::Result<Vec<BundleFileEntry>> {
221 if !bundle.is_dir() {
222 return Ok(Vec::new());
223 }
224 let mut files: Vec<BundleFileEntry> = std::fs::read_dir(bundle)?
225 .filter_map(Result::ok)
226 .map(|entry| entry.path())
227 .filter(|path| path.is_file())
228 .filter_map(|path| {
229 let name = path.file_name()?.to_string_lossy().into_owned();
230 let size_bytes = std::fs::metadata(&path).ok()?.len();
231 Some(BundleFileEntry {
232 path,
233 name,
234 size_bytes,
235 })
236 })
237 .collect();
238 files.sort_by(|left, right| left.name.cmp(&right.name));
239 Ok(files)
240}
241
242/// Remove one support package directory. Refuses paths outside `parent` when provided.
243pub fn delete_support_bundle(bundle: &Path, parent: Option<&Path>) -> std::io::Result<()> {
244 if let Some(parent) = parent {
245 let canonical_parent = parent.canonicalize().unwrap_or_else(|_| parent.to_path_buf());
246 let canonical_bundle = bundle.canonicalize().unwrap_or_else(|_| bundle.to_path_buf());
247 if !canonical_bundle.starts_with(&canonical_parent) {
248 return Err(std::io::Error::new(
249 std::io::ErrorKind::InvalidInput,
250 "bundle path is outside the support-bundles directory",
251 ));
252 }
253 }
254 if bundle.is_dir() {
255 std::fs::remove_dir_all(bundle)?;
256 }
257 Ok(())
258}
259
260pub fn ensure_dir(path: &Path) -> std::io::Result<()> {
261 std::fs::create_dir_all(path)
262}
263
264pub fn format_bytes(size: u64) -> String {
265 const KB: u64 = 1024;
266 const MB: u64 = KB * 1024;
267 if size >= MB {
268 format!("{:.1} MB", size as f64 / MB as f64)
269 } else if size >= KB {
270 format!("{:.1} KB", size as f64 / KB as f64)
271 } else {
272 format!("{size} B")
273 }
274}
275
276pub fn issue_title() -> &'static str {
277 "Bug report"
278}
279
280pub fn issue_body(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
281 format!(
282 "## What happened\n\n\
283 <!-- Describe the bug -->\n\n\
284 ## Expected\n\n\
285 <!-- What should happen -->\n\n\
286 {}\n\
287 Support package folder: `{}`\n\
288 Support package path: `{}`\n\n\
289 Attach the files from that folder (do not paste secrets).\n",
290 client.markdown(),
291 bundle.folder_name,
292 bundle.directory.display(),
293 )
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct SupportBundlePaths {
298 pub directory: PathBuf,
299 pub folder_name: String,
300}
301
302pub fn issue_url(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
303 format!(
304 "{GITHUB_ISSUES_NEW}?title={}&body={}",
305 encode_query(issue_title()),
306 encode_query(&issue_body(client, bundle))
307 )
308}
309
310pub fn encode_query(value: &str) -> String {
311 let mut out = String::with_capacity(value.len() * 3);
312 for byte in value.bytes() {
313 match byte {
314 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
315 out.push(byte as char);
316 }
317 b' ' => out.push_str("%20"),
318 _ => out.push_str(&format!("%{byte:02X}")),
319 }
320 }
321 out
322}
323
324/// Append a client snapshot when debug logging is on (after store/locale when possible).
325pub fn record_startup_client_line(
326 package_version: &str,
327 ui_locale: &str,
328 signed_in: bool,
329 call_reports: bool,
330) {
331 if !diagnostics::is_enabled() {
332 return;
333 }
334 let info = ClientInfo::capture(
335 package_version,
336 ui_locale,
337 signed_in,
338 call_reports,
339 "n/a",
340 "n/a",
341 "n/a",
342 );
343 diagnostics::record(info.one_line());
344}
345
346/// Chain a panic hook that also writes a short line into the diagnostics log.
347pub fn install_panic_diagnostics_hook() {
348 let previous = std::panic::take_hook();
349 std::panic::set_hook(Box::new(move |info| {
350 let payload = info.payload();
351 let message = payload
352 .downcast_ref::<&str>()
353 .copied()
354 .map(str::to_owned)
355 .or_else(|| payload.downcast_ref::<String>().cloned())
356 .unwrap_or_else(|| "non-text panic payload".to_owned());
357 let location = info
358 .location()
359 .map(|location| {
360 format!(
361 "{}:{}:{}",
362 location.file(),
363 location.line(),
364 location.column()
365 )
366 })
367 .unwrap_or_else(|| "unknown".to_owned());
368 diagnostics::record(format!("panic at {location}: {message}"));
369 previous(info);
370 }));
371}
372
373pub fn readme_text() -> &'static str {
374 "Attach the files in this folder to a GitHub issue on danieldaeschle/rusty-teams.\n\
375 The app store, cookies, and tokens are not included.\n"
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 fn sample_client() -> ClientInfo {
383 ClientInfo {
384 version: "0.3.0".into(),
385 build: "abc".into(),
386 os: "linux".into(),
387 arch: "x86_64".into(),
388 session: "wayland".into(),
389 ui_locale: "de".into(),
390 timezone: "Europe/Zurich".into(),
391 signed_in: true,
392 call_reports: false,
393 debug_logging: true,
394 audio_input: "Default device".into(),
395 audio_output: "Default device".into(),
396 camera: "none".into(),
397 logs_root: "/tmp/ms-teams-linux".into(),
398 support_bundles_root: "/tmp/ms-teams-linux/support-bundles".into(),
399 }
400 }
401
402 #[test]
403 fn markdown_block_lists_stable_keys_and_paths() {
404 let text = sample_client().markdown();
405 assert!(text.contains("- Version: 0.3.0"));
406 assert!(text.contains("- Build: abc"));
407 assert!(text.contains("- OS: linux (x86_64)"));
408 assert!(text.contains("- Session: wayland"));
409 assert!(text.contains("- Signed in: yes"));
410 assert!(text.contains("- Call reports: no"));
411 assert!(text.contains("- Logs root: /tmp/ms-teams-linux"));
412 assert!(text.contains("- Support bundles: /tmp/ms-teams-linux/support-bundles"));
413 assert!(!text.contains('@'));
414 }
415
416 #[test]
417 fn layout_relative_names_are_stable() {
418 assert_eq!(SUPPORT_BUNDLES_DIR, "support-bundles");
419 assert_eq!(CALL_REPORTS_DIR, "call-reports");
420 assert_eq!(CALL_DUMPS_DIR, "call-dumps");
421 assert_eq!(CRASH_LOG_FILE, "crash.log");
422 assert_eq!(diagnostics::DIAGNOSTICS_FILE, "diagnostics.log");
423 let root = PathBuf::from("/data/ms-teams-linux");
424 assert_eq!(
425 support_bundles_directory(&root),
426 root.join("support-bundles")
427 );
428 }
429
430 #[test]
431 fn issue_url_encodes_spaces_and_newlines() {
432 let info = sample_client();
433 let bundle = SupportBundlePaths {
434 directory: PathBuf::from("/tmp/ms-teams-linux/support-bundles/support-20260101T000000Z"),
435 folder_name: "support-20260101T000000Z".into(),
436 };
437 let url = issue_url(&info, &bundle);
438 assert!(url.starts_with(GITHUB_ISSUES_NEW));
439 assert!(url.contains("title=Bug%20report"));
440 assert!(url.contains("body="));
441 assert!(url.contains("support-20260101T000000Z"));
442 assert!(!url.contains(' '));
443 }
444
445 #[test]
446 fn encode_query_percent_encodes_specials() {
447 assert_eq!(encode_query("a b"), "a%20b");
448 assert_eq!(encode_query("a&b"), "a%26b");
449 }
450
451 #[test]
452 fn list_and_delete_support_bundles_in_temp_dir() {
453 let root = tempfile::tempdir().unwrap();
454 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
455 let older = bundles.join("support-20260101T000000Z");
456 let newer = bundles.join("support-20260102T000000Z");
457 std::fs::create_dir_all(&older).unwrap();
458 std::fs::create_dir_all(&newer).unwrap();
459 std::fs::write(older.join("client.md"), "old").unwrap();
460 std::fs::write(newer.join("client.md"), "new").unwrap();
461 std::fs::write(newer.join("diagnostics.log"), "log").unwrap();
462
463 let listed = list_support_bundles(&bundles).unwrap();
464 assert_eq!(listed.len(), 2);
465 assert_eq!(listed[0].name, "support-20260102T000000Z");
466 assert_eq!(listed[1].name, "support-20260101T000000Z");
467
468 let files = list_bundle_files(&newer).unwrap();
469 assert_eq!(files.len(), 2);
470 assert_eq!(files[0].name, "client.md");
471 assert_eq!(files[1].name, "diagnostics.log");
472
473 delete_support_bundle(&newer, Some(&bundles)).unwrap();
474 let listed = list_support_bundles(&bundles).unwrap();
475 assert_eq!(listed.len(), 1);
476 assert_eq!(listed[0].name, "support-20260101T000000Z");
477 assert!(!newer.exists());
478 }
479
480 #[test]
481 fn delete_refuses_paths_outside_parent() {
482 let root = tempfile::tempdir().unwrap();
483 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
484 let outside = root.path().join("other");
485 std::fs::create_dir_all(&bundles).unwrap();
486 std::fs::create_dir_all(&outside).unwrap();
487 assert!(delete_support_bundle(&outside, Some(&bundles)).is_err());
488 assert!(outside.exists());
489 }
490}
crates/app-call-model/src/report/mod.rs +1 −1
@@ -1,7 +1,7 @@
1 1 mod common_words;
2 2 mod document;
3 3 mod markdown;
4 mod scrub;
4 pub mod scrub;
5 5 mod series;
6 6 mod storage;
7 7 mod web_shadow;
@@ -1,7 +1,7 @@
1mod common_words;
1mod common_words;
2mod document;
2mod document;
3mod markdown;
3mod markdown;
4mod scrub;
4pub mod scrub;
5mod series;
5mod series;
6mod storage;
6mod storage;
7mod web_shadow;
7mod web_shadow;
crates/app-call-model/src/report/storage.rs +2 −5
@@ -4,8 +4,6 @@ use std::path::{Path, PathBuf};
4 4
5 5 use super::Document;
6 6
7 #[cfg(not(test))]
8 const REPORT_DIRECTORY: &str = "call-reports";
9 7 const KEEP_REPORTS: usize = 30;
10 8 const JSON_EXTENSION: &str = "json";
11 9 const MARKDOWN_EXTENSION: &str = "md";
@@ -23,9 +21,8 @@ pub fn report_directory() -> PathBuf {
23 21
24 22 #[cfg(not(test))]
25 23 pub fn report_directory() -> PathBuf {
26 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
27 .map(|directories| directories.data_local_dir().join(REPORT_DIRECTORY))
28 .unwrap_or_else(|| PathBuf::from(REPORT_DIRECTORY))
24 app_base::support::call_reports_dir()
25 .unwrap_or_else(|| PathBuf::from(app_base::support::CALL_REPORTS_DIR))
29 26 }
30 27
31 28 pub fn save_report(directory: &Path, document: &Document) -> io::Result<SavedReport> {
@@ -4,8 +4,6 @@ use std::path::{Path, PathBuf};
4
4
5use super::Document;
5use super::Document;
6
6
7#[cfg(not(test))]
8const REPORT_DIRECTORY: &str = "call-reports";
9const KEEP_REPORTS: usize = 30;
7const KEEP_REPORTS: usize = 30;
10const JSON_EXTENSION: &str = "json";
8const JSON_EXTENSION: &str = "json";
11const MARKDOWN_EXTENSION: &str = "md";
9const MARKDOWN_EXTENSION: &str = "md";
@@ -23,9 +21,8 @@ pub fn report_directory() -> PathBuf {
23
21
24#[cfg(not(test))]
22#[cfg(not(test))]
25pub fn report_directory() -> PathBuf {
23pub fn report_directory() -> PathBuf {
26 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
24 app_base::support::call_reports_dir()
27 .map(|directories| directories.data_local_dir().join(REPORT_DIRECTORY))
25 .unwrap_or_else(|| PathBuf::from(app_base::support::CALL_REPORTS_DIR))
28 .unwrap_or_else(|| PathBuf::from(REPORT_DIRECTORY))
29}
26}
30
27
31pub fn save_report(directory: &Path, document: &Document) -> io::Result<SavedReport> {
28pub fn save_report(directory: &Path, document: &Document) -> io::Result<SavedReport> {
crates/app-state/src/call/actions.rs +11 −0
@@ -292,6 +292,12 @@ impl AppState {
292 292 conversation_id,
293 293 video,
294 294 ));
295 if let Some(call) = self.call.as_ref() {
296 crate::diagnostics::record(format!(
297 "calls: start kind={:?} incoming={} peer={}",
298 call.model.kind, call.model.incoming, call.model.peer_name
299 ));
300 }
295 301 if self.call_share_sound {
296 302 self.send_call_command(CallCommand::SetShareSound(true));
297 303 }
@@ -627,6 +633,11 @@ impl AppState {
627 633 return;
628 634 };
629 635 let elapsed = call.model.elapsed(Instant::now());
636 crate::diagnostics::record(format!(
637 "calls: end kind={:?} reason={reason:?} elapsed_ms={}",
638 call.model.kind,
639 elapsed.map(|value| value.as_millis()).unwrap_or(0)
640 ));
630 641 let consult = call.consult.take();
631 642 let notice = match &consult {
632 643 Some(consult) if consult.transfer == ConsultTransfer::Done => {
@@ -292,6 +292,12 @@ impl AppState {
292 conversation_id,
292 conversation_id,
293 video,
293 video,
294 ));
294 ));
295 if let Some(call) = self.call.as_ref() {
296 crate::diagnostics::record(format!(
297 "calls: start kind={:?} incoming={} peer={}",
298 call.model.kind, call.model.incoming, call.model.peer_name
299 ));
300 }
295 if self.call_share_sound {
301 if self.call_share_sound {
296 self.send_call_command(CallCommand::SetShareSound(true));
302 self.send_call_command(CallCommand::SetShareSound(true));
297 }
303 }
@@ -627,6 +633,11 @@ impl AppState {
627 return;
633 return;
628 };
634 };
629 let elapsed = call.model.elapsed(Instant::now());
635 let elapsed = call.model.elapsed(Instant::now());
636 crate::diagnostics::record(format!(
637 "calls: end kind={:?} reason={reason:?} elapsed_ms={}",
638 call.model.kind,
639 elapsed.map(|value| value.as_millis()).unwrap_or(0)
640 ));
630 let consult = call.consult.take();
641 let consult = call.consult.take();
631 let notice = match &consult {
642 let notice = match &consult {
632 Some(consult) if consult.transfer == ConsultTransfer::Done => {
643 Some(consult) if consult.transfer == ConsultTransfer::Done => {
crates/app-state/src/call/launcher.rs +4 −2
@@ -23,7 +23,6 @@ const START_RETRY_STEADY: Duration = Duration::from_secs(10);
23 23 pub(super) const NOT_READY: &str =
24 24 "Could not reach the Teams calling service. Check your connection and try again.";
25 25 const READY_WAIT: Duration = Duration::from_secs(30);
26 const CALL_DUMPS_DIR: &str = "call-dumps";
27 26
28 27 pub struct CallLauncher {
29 28 engine: watch::Sender<Option<CallEngine>>,
@@ -368,9 +367,12 @@ async fn start_engine(
368 367 )> {
369 368 let session = Session::with_transport(transport.clone(), SessionConfig::for_app()).await?;
370 369 let poll_session = Session::with_transport(transport, SessionConfig::for_app()).await?;
370 let dump_dir = app_base::diagnostics::is_enabled()
371 .then(|| crate::support::call_dumps_dir())
372 .flatten();
371 373 let config = EngineConfig {
372 374 ringable,
373 dump_dir: crate::diagnostics::directory().map(|directory| directory.join(CALL_DUMPS_DIR)),
375 dump_dir,
374 376 ..EngineConfig::default()
375 377 };
376 378 CallEngine::start(session, poll_session, config).await
@@ -23,7 +23,6 @@ const START_RETRY_STEADY: Duration = Duration::from_secs(10);
23pub(super) const NOT_READY: &str =
23pub(super) const NOT_READY: &str =
24 "Could not reach the Teams calling service. Check your connection and try again.";
24 "Could not reach the Teams calling service. Check your connection and try again.";
25const READY_WAIT: Duration = Duration::from_secs(30);
25const READY_WAIT: Duration = Duration::from_secs(30);
26const CALL_DUMPS_DIR: &str = "call-dumps";
27
26
28pub struct CallLauncher {
27pub struct CallLauncher {
29 engine: watch::Sender<Option<CallEngine>>,
28 engine: watch::Sender<Option<CallEngine>>,
@@ -368,9 +367,12 @@ async fn start_engine(
368)> {
367)> {
369 let session = Session::with_transport(transport.clone(), SessionConfig::for_app()).await?;
368 let session = Session::with_transport(transport.clone(), SessionConfig::for_app()).await?;
370 let poll_session = Session::with_transport(transport, SessionConfig::for_app()).await?;
369 let poll_session = Session::with_transport(transport, SessionConfig::for_app()).await?;
370 let dump_dir = app_base::diagnostics::is_enabled()
371 .then(|| crate::support::call_dumps_dir())
372 .flatten();
371 let config = EngineConfig {
373 let config = EngineConfig {
372 ringable,
374 ringable,
373 dump_dir: crate::diagnostics::directory().map(|directory| directory.join(CALL_DUMPS_DIR)),
375 dump_dir,
374 ..EngineConfig::default()
376 ..EngineConfig::default()
375 };
377 };
376 CallEngine::start(session, poll_session, config).await
378 CallEngine::start(session, poll_session, config).await
crates/app-state/src/lib.rs +3 −1
@@ -60,6 +60,8 @@ mod sidebar_load;
60 60 pub mod sidebar_model;
61 61 pub mod sound_actions;
62 62 pub mod stored_outgoing;
63 pub mod support_actions;
64 pub mod support_bundle;
63 65 pub mod task_dialog;
64 66 pub mod team_admin;
65 67 pub mod translation_actions;
@@ -72,6 +74,6 @@ pub use app_base::{
72 74 demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
73 75 downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
74 76 presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
75 stickers, theme, translation, updater, user_activity, zoom,
77 stickers, support, theme, translation, updater, user_activity, zoom,
76 78 };
77 79 pub use app_ui_kit::render;
@@ -60,6 +60,8 @@ mod sidebar_load;
60pub mod sidebar_model;
60pub mod sidebar_model;
61pub mod sound_actions;
61pub mod sound_actions;
62pub mod stored_outgoing;
62pub mod stored_outgoing;
63pub mod support_actions;
64pub mod support_bundle;
63pub mod task_dialog;
65pub mod task_dialog;
64pub mod team_admin;
66pub mod team_admin;
65pub mod translation_actions;
67pub mod translation_actions;
@@ -72,6 +74,6 @@ pub use app_base::{
72 demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
74 demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
73 downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
75 downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
74 presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
76 presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
75 stickers, theme, translation, updater, user_activity, zoom,
77 stickers, support, theme, translation, updater, user_activity, zoom,
76};
78};
77pub use app_ui_kit::render;
79pub use app_ui_kit::render;
crates/app-state/src/notice.rs +1 −0
@@ -51,6 +51,7 @@ impl AppState {
51 51 action: Option<NoticeAction>,
52 52 cx: &mut Context<Self>,
53 53 ) {
54 app_base::diagnostics::record(format!("notice: {text}"));
54 55 self.notice_count += 1;
55 56 let id = self.notice_count;
56 57 self.notice = Some(Notice { id, text, action });
@@ -51,6 +51,7 @@ impl AppState {
51 action: Option<NoticeAction>,
51 action: Option<NoticeAction>,
52 cx: &mut Context<Self>,
52 cx: &mut Context<Self>,
53 ) {
53 ) {
54 app_base::diagnostics::record(format!("notice: {text}"));
54 self.notice_count += 1;
55 self.notice_count += 1;
55 let id = self.notice_count;
56 let id = self.notice_count;
56 self.notice = Some(Notice { id, text, action });
57 self.notice = Some(Notice { id, text, action });
crates/app-state/src/settings_section.rs +1 −0
@@ -13,6 +13,7 @@ pub enum SettingsSection {
13 13 Devices,
14 14 Agents,
15 15 Mcp,
16 Help,
16 17 About,
17 18 }
18 19
@@ -13,6 +13,7 @@ pub enum SettingsSection {
13 Devices,
13 Devices,
14 Agents,
14 Agents,
15 Mcp,
15 Mcp,
16 Help,
16 About,
17 About,
17}
18}
18
19
crates/app-state/src/support_actions.rs added +107 −0
@@ -0,0 +1,107 @@
1 use gpui_kit::Context;
2
3 use crate::app_state::AppState;
4 use crate::notice::NoticeAction;
5 use crate::support::{self, ClientInfo, SupportBundlePaths};
6 use crate::support_bundle::{self, SupportBundle};
7 use calling::DeviceChoice;
8
9 impl AppState {
10 pub fn client_info(&self) -> ClientInfo {
11 let locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&self.store));
12 ClientInfo::capture(
13 env!("CARGO_PKG_VERSION"),
14 locale,
15 self.directory.me.is_some(),
16 self.call_report_enabled,
17 device_label(&self.call_input),
18 device_label(&self.call_output),
19 device_label(&self.call_camera),
20 )
21 }
22
23 pub fn create_support_bundle(&self) -> Result<SupportBundle, String> {
24 let data_dir =
25 support::local_data_dir().ok_or_else(|| "data directory unavailable".to_owned())?;
26 let diagnostics = support::diagnostics_log_path()
27 .unwrap_or_else(|| data_dir.join(app_base::diagnostics::DIAGNOSTICS_FILE));
28 support_bundle::write_support_bundle(&data_dir, &self.client_info(), &diagnostics)
29 .map_err(|error| error.to_string())
30 }
31
32 pub fn github_issue_url_for_bundle(&self, bundle: &SupportBundle) -> String {
33 support::issue_url(
34 &self.client_info(),
35 &SupportBundlePaths {
36 directory: bundle.directory.clone(),
37 folder_name: bundle.folder_name.clone(),
38 },
39 )
40 }
41
42 pub fn reveal_support_bundle(bundle: &SupportBundle) {
43 crate::downloads::reveal_in_file_manager(&bundle.directory);
44 }
45
46 pub fn reveal_logs_folder() {
47 if let Some(directory) = support::local_data_dir().or_else(app_base::diagnostics::directory)
48 {
49 crate::downloads::reveal_in_file_manager(&directory);
50 }
51 }
52
53 pub fn open_github_issue_with_bundle(&mut self, cx: &mut Context<Self>) -> Result<(), String> {
54 let bundle = self.create_support_bundle()?;
55 let url = self.github_issue_url_for_bundle(&bundle);
56 let folder = bundle.directory.clone();
57 crate::external_browser::open_url(cx, &self.store, &url);
58 let action = NoticeAction::new("Open folder", move |_, _| {
59 crate::downloads::reveal_in_file_manager(&folder);
60 });
61 self.raise_notice(
62 format!(
63 "Support package ready: {}. Attach those files to the GitHub issue.",
64 bundle.folder_name
65 ),
66 Some(action),
67 cx,
68 );
69 Ok(())
70 }
71
72 pub fn diagnostics_enabled(&self) -> bool {
73 app_base::diagnostics::is_enabled()
74 }
75
76 pub fn set_diagnostics_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
77 app_base::diagnostics::set_enabled(on);
78 let _ = self.store.set_meta(
79 app_base::diagnostics::DIAGNOSTICS_SETTING_KEY,
80 if on { "1" } else { "0" },
81 );
82 if on {
83 app_base::support::record_startup_client_line(
84 env!("CARGO_PKG_VERSION"),
85 app_base::ui_locale::effective_locale(app_base::ui_locale::load(&self.store)),
86 self.directory.me.is_some(),
87 self.call_report_enabled,
88 );
89 }
90 cx.notify();
91 }
92
93 pub fn clear_diagnostic_logs(&mut self, cx: &mut Context<Self>) {
94 if let Err(error) = app_base::diagnostics::clear_logs() {
95 app_base::diagnostics::record(format!("clear logs: {error}"));
96 }
97 cx.notify();
98 }
99 }
100
101 fn device_label(choice: &DeviceChoice) -> String {
102 match choice {
103 DeviceChoice::SystemDefault => "default".to_owned(),
104 DeviceChoice::Device(key) if key.is_empty() => "none".to_owned(),
105 DeviceChoice::Device(_) => "selected".to_owned(),
106 }
107 }
@@ -0,0 +1,107 @@
1use gpui_kit::Context;
2
3use crate::app_state::AppState;
4use crate::notice::NoticeAction;
5use crate::support::{self, ClientInfo, SupportBundlePaths};
6use crate::support_bundle::{self, SupportBundle};
7use calling::DeviceChoice;
8
9impl AppState {
10 pub fn client_info(&self) -> ClientInfo {
11 let locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&self.store));
12 ClientInfo::capture(
13 env!("CARGO_PKG_VERSION"),
14 locale,
15 self.directory.me.is_some(),
16 self.call_report_enabled,
17 device_label(&self.call_input),
18 device_label(&self.call_output),
19 device_label(&self.call_camera),
20 )
21 }
22
23 pub fn create_support_bundle(&self) -> Result<SupportBundle, String> {
24 let data_dir =
25 support::local_data_dir().ok_or_else(|| "data directory unavailable".to_owned())?;
26 let diagnostics = support::diagnostics_log_path()
27 .unwrap_or_else(|| data_dir.join(app_base::diagnostics::DIAGNOSTICS_FILE));
28 support_bundle::write_support_bundle(&data_dir, &self.client_info(), &diagnostics)
29 .map_err(|error| error.to_string())
30 }
31
32 pub fn github_issue_url_for_bundle(&self, bundle: &SupportBundle) -> String {
33 support::issue_url(
34 &self.client_info(),
35 &SupportBundlePaths {
36 directory: bundle.directory.clone(),
37 folder_name: bundle.folder_name.clone(),
38 },
39 )
40 }
41
42 pub fn reveal_support_bundle(bundle: &SupportBundle) {
43 crate::downloads::reveal_in_file_manager(&bundle.directory);
44 }
45
46 pub fn reveal_logs_folder() {
47 if let Some(directory) = support::local_data_dir().or_else(app_base::diagnostics::directory)
48 {
49 crate::downloads::reveal_in_file_manager(&directory);
50 }
51 }
52
53 pub fn open_github_issue_with_bundle(&mut self, cx: &mut Context<Self>) -> Result<(), String> {
54 let bundle = self.create_support_bundle()?;
55 let url = self.github_issue_url_for_bundle(&bundle);
56 let folder = bundle.directory.clone();
57 crate::external_browser::open_url(cx, &self.store, &url);
58 let action = NoticeAction::new("Open folder", move |_, _| {
59 crate::downloads::reveal_in_file_manager(&folder);
60 });
61 self.raise_notice(
62 format!(
63 "Support package ready: {}. Attach those files to the GitHub issue.",
64 bundle.folder_name
65 ),
66 Some(action),
67 cx,
68 );
69 Ok(())
70 }
71
72 pub fn diagnostics_enabled(&self) -> bool {
73 app_base::diagnostics::is_enabled()
74 }
75
76 pub fn set_diagnostics_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
77 app_base::diagnostics::set_enabled(on);
78 let _ = self.store.set_meta(
79 app_base::diagnostics::DIAGNOSTICS_SETTING_KEY,
80 if on { "1" } else { "0" },
81 );
82 if on {
83 app_base::support::record_startup_client_line(
84 env!("CARGO_PKG_VERSION"),
85 app_base::ui_locale::effective_locale(app_base::ui_locale::load(&self.store)),
86 self.directory.me.is_some(),
87 self.call_report_enabled,
88 );
89 }
90 cx.notify();
91 }
92
93 pub fn clear_diagnostic_logs(&mut self, cx: &mut Context<Self>) {
94 if let Err(error) = app_base::diagnostics::clear_logs() {
95 app_base::diagnostics::record(format!("clear logs: {error}"));
96 }
97 cx.notify();
98 }
99}
100
101fn device_label(choice: &DeviceChoice) -> String {
102 match choice {
103 DeviceChoice::SystemDefault => "default".to_owned(),
104 DeviceChoice::Device(key) if key.is_empty() => "none".to_owned(),
105 DeviceChoice::Device(_) => "selected".to_owned(),
106 }
107}
crates/app-state/src/support_bundle.rs added +203 −0
@@ -0,0 +1,203 @@
1 use std::fs;
2 use std::io;
3 use std::path::{Path, PathBuf};
4
5 use app_base::support::{self, ClientInfo};
6 use app_call_model::report::scrub::Scrubber;
7 use app_call_model::report::report_directory;
8 use chrono::Utc;
9
10 const KEEP_CALL_REPORTS: usize = 3;
11 const DIAGNOSTICS_NAME: &str = "diagnostics.log";
12 const CRASH_NAME: &str = "crash.log";
13 const TIMELINE_NAME: &str = "last-call-timeline.log";
14 const DIAGNOSTICS_MERGE_CAP: u64 = 1024 * 1024;
15 const CRASH_MERGE_CAP: u64 = 128 * 1024;
16
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct SupportBundle {
19 pub directory: PathBuf,
20 pub folder_name: String,
21 }
22
23 pub fn write_support_bundle(
24 data_dir: &Path,
25 client: &ClientInfo,
26 _diagnostics_path: &Path,
27 ) -> io::Result<SupportBundle> {
28 let folder_name = support::bundle_folder_name(Utc::now());
29 let directory = support::support_bundles_directory(data_dir).join(&folder_name);
30 fs::create_dir_all(&directory)?;
31 fs::write(directory.join("client.md"), client.markdown())?;
32 fs::write(directory.join("README.md"), support::readme_text())?;
33 write_scrubbed_text(
34 &app_base::diagnostics::read_merged(DIAGNOSTICS_MERGE_CAP),
35 &directory.join(DIAGNOSTICS_NAME),
36 )?;
37 write_scrubbed_text(
38 &app_base::crash_log::read_merged(CRASH_MERGE_CAP),
39 &directory.join(CRASH_NAME),
40 )?;
41 copy_recent_call_reports(&directory)?;
42 copy_latest_call_timeline(&directory)?;
43 Ok(SupportBundle {
44 directory,
45 folder_name,
46 })
47 }
48
49 fn write_scrubbed_text(raw: &str, destination: &Path) -> io::Result<()> {
50 if raw.trim().is_empty() {
51 return Ok(());
52 }
53 let mut scrubber = Scrubber::default();
54 let scrubbed = scrubber.scrub(raw);
55 fs::write(destination, scrubbed)
56 }
57
58 fn copy_recent_call_reports(bundle: &Path) -> io::Result<()> {
59 let reports = report_directory();
60 if !reports.is_dir() {
61 return Ok(());
62 }
63 let mut markdown: Vec<PathBuf> = fs::read_dir(&reports)?
64 .filter_map(Result::ok)
65 .map(|entry| entry.path())
66 .filter(|path| path.extension().is_some_and(|ext| ext == "md"))
67 .collect();
68 markdown.sort();
69 let start = markdown.len().saturating_sub(KEEP_CALL_REPORTS);
70 for path in &markdown[start..] {
71 let Some(name) = path.file_name() else {
72 continue;
73 };
74 fs::copy(path, bundle.join(name))?;
75 let json = path.with_extension("json");
76 if json.is_file() {
77 if let Some(json_name) = json.file_name() {
78 fs::copy(&json, bundle.join(json_name))?;
79 }
80 }
81 }
82 Ok(())
83 }
84
85 fn copy_latest_call_timeline(bundle: &Path) -> io::Result<()> {
86 let Some(dumps) = support::call_dumps_dir() else {
87 return Ok(());
88 };
89 if !dumps.is_dir() {
90 return Ok(());
91 }
92 let mut dirs: Vec<PathBuf> = fs::read_dir(&dumps)?
93 .filter_map(Result::ok)
94 .map(|entry| entry.path())
95 .filter(|path| path.is_dir())
96 .collect();
97 dirs.sort();
98 let Some(latest) = dirs.last() else {
99 return Ok(());
100 };
101 let timeline = latest.join("timeline.txt");
102 if !timeline.is_file() {
103 return Ok(());
104 }
105 let raw = fs::read_to_string(timeline)?;
106 write_scrubbed_text(&raw, &bundle.join(TIMELINE_NAME))
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use super::*;
112 use tempfile::tempdir;
113
114 fn sample_client() -> ClientInfo {
115 ClientInfo {
116 version: "0.1.0".into(),
117 build: "test".into(),
118 os: "linux".into(),
119 arch: "x86_64".into(),
120 session: "wayland".into(),
121 ui_locale: "en".into(),
122 timezone: "UTC+0".into(),
123 signed_in: true,
124 call_reports: true,
125 debug_logging: true,
126 audio_input: "Default device".into(),
127 audio_output: "Default device".into(),
128 camera: "none".into(),
129 logs_root: "/tmp/data".into(),
130 support_bundles_root: "/tmp/data/support-bundles".into(),
131 }
132 }
133
134 #[test]
135 fn support_bundle_scrubs_secrets_and_skips_store() {
136 let root = tempdir().unwrap();
137 let data = root.path().join("data");
138 fs::create_dir_all(&data).unwrap();
139 let diagnostics = data.join(DIAGNOSTICS_NAME);
140 fs::write(
141 &diagnostics,
142 "ok line\nbearer eyJhbGciOiJIUzI1NiJ9.aaa.bbb\nemail user@example.com\n",
143 )
144 .unwrap();
145 fs::write(data.join("store.db"), "secret-store").unwrap();
146
147 // Install diagnostics path so merge can find the file we wrote under data.
148 app_base::diagnostics::install(diagnostics.clone());
149 app_base::diagnostics::set_enabled(true);
150 // Re-write through the live path if install used a different OnceLock path already.
151 if let Some(live) = app_base::diagnostics::path() {
152 let _ = fs::write(
153 &live,
154 "ok line\nbearer eyJhbGciOiJIUzI1NiJ9.aaa.bbb\nemail user@example.com\n",
155 );
156 }
157
158 let bundle = write_support_bundle(&data, &sample_client(), &diagnostics).unwrap();
159 let client = fs::read_to_string(bundle.directory.join("client.md")).unwrap();
160 assert!(client.contains("### Client"));
161 assert!(client.contains("Debug logging:"));
162 let log_path = bundle.directory.join(DIAGNOSTICS_NAME);
163 if log_path.is_file() {
164 let log = fs::read_to_string(&log_path).unwrap();
165 assert!(!log.contains("eyJhbGciOiJIUzI1NiJ9"));
166 assert!(!log.contains("user@example.com"));
167 }
168 assert!(!bundle.directory.join("store.db").exists());
169 assert!(bundle.directory.join("README.md").is_file());
170 }
171
172 #[test]
173 fn support_bundle_copies_matching_call_report_json() {
174 let root = tempdir().unwrap();
175 let data = root.path().join("data");
176 fs::create_dir_all(&data).unwrap();
177 // Dependency `report_directory()` is the live path (cfg(test) only applies in
178 // app-call-model's own tests). Use a stem that sorts last so KEEP_CALL_REPORTS
179 // still includes it among any pre-existing reports.
180 let target = report_directory();
181 fs::create_dir_all(&target).unwrap();
182 let stem = format!(
183 "zzz-{}-bundle-test",
184 chrono::Utc::now().format("%Y%m%dT%H%M%S%3fZ")
185 );
186 let md_name = format!("{stem}.md");
187 let json_name = format!("{stem}.json");
188 fs::write(target.join(&md_name), "# report\n").unwrap();
189 fs::write(target.join(&json_name), "{\"schema\":1}\n").unwrap();
190
191 let diagnostics = data.join(DIAGNOSTICS_NAME);
192 fs::write(&diagnostics, "line\n").unwrap();
193 let bundle = write_support_bundle(&data, &sample_client(), &diagnostics).unwrap();
194 assert!(
195 bundle.directory.join(&md_name).is_file(),
196 "missing {md_name} in {:?}",
197 bundle.directory
198 );
199 assert!(bundle.directory.join(&json_name).is_file());
200 let _ = fs::remove_file(target.join(&md_name));
201 let _ = fs::remove_file(target.join(&json_name));
202 }
203 }
@@ -0,0 +1,203 @@
1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5use app_base::support::{self, ClientInfo};
6use app_call_model::report::scrub::Scrubber;
7use app_call_model::report::report_directory;
8use chrono::Utc;
9
10const KEEP_CALL_REPORTS: usize = 3;
11const DIAGNOSTICS_NAME: &str = "diagnostics.log";
12const CRASH_NAME: &str = "crash.log";
13const TIMELINE_NAME: &str = "last-call-timeline.log";
14const DIAGNOSTICS_MERGE_CAP: u64 = 1024 * 1024;
15const CRASH_MERGE_CAP: u64 = 128 * 1024;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SupportBundle {
19 pub directory: PathBuf,
20 pub folder_name: String,
21}
22
23pub fn write_support_bundle(
24 data_dir: &Path,
25 client: &ClientInfo,
26 _diagnostics_path: &Path,
27) -> io::Result<SupportBundle> {
28 let folder_name = support::bundle_folder_name(Utc::now());
29 let directory = support::support_bundles_directory(data_dir).join(&folder_name);
30 fs::create_dir_all(&directory)?;
31 fs::write(directory.join("client.md"), client.markdown())?;
32 fs::write(directory.join("README.md"), support::readme_text())?;
33 write_scrubbed_text(
34 &app_base::diagnostics::read_merged(DIAGNOSTICS_MERGE_CAP),
35 &directory.join(DIAGNOSTICS_NAME),
36 )?;
37 write_scrubbed_text(
38 &app_base::crash_log::read_merged(CRASH_MERGE_CAP),
39 &directory.join(CRASH_NAME),
40 )?;
41 copy_recent_call_reports(&directory)?;
42 copy_latest_call_timeline(&directory)?;
43 Ok(SupportBundle {
44 directory,
45 folder_name,
46 })
47}
48
49fn write_scrubbed_text(raw: &str, destination: &Path) -> io::Result<()> {
50 if raw.trim().is_empty() {
51 return Ok(());
52 }
53 let mut scrubber = Scrubber::default();
54 let scrubbed = scrubber.scrub(raw);
55 fs::write(destination, scrubbed)
56}
57
58fn copy_recent_call_reports(bundle: &Path) -> io::Result<()> {
59 let reports = report_directory();
60 if !reports.is_dir() {
61 return Ok(());
62 }
63 let mut markdown: Vec<PathBuf> = fs::read_dir(&reports)?
64 .filter_map(Result::ok)
65 .map(|entry| entry.path())
66 .filter(|path| path.extension().is_some_and(|ext| ext == "md"))
67 .collect();
68 markdown.sort();
69 let start = markdown.len().saturating_sub(KEEP_CALL_REPORTS);
70 for path in &markdown[start..] {
71 let Some(name) = path.file_name() else {
72 continue;
73 };
74 fs::copy(path, bundle.join(name))?;
75 let json = path.with_extension("json");
76 if json.is_file() {
77 if let Some(json_name) = json.file_name() {
78 fs::copy(&json, bundle.join(json_name))?;
79 }
80 }
81 }
82 Ok(())
83}
84
85fn copy_latest_call_timeline(bundle: &Path) -> io::Result<()> {
86 let Some(dumps) = support::call_dumps_dir() else {
87 return Ok(());
88 };
89 if !dumps.is_dir() {
90 return Ok(());
91 }
92 let mut dirs: Vec<PathBuf> = fs::read_dir(&dumps)?
93 .filter_map(Result::ok)
94 .map(|entry| entry.path())
95 .filter(|path| path.is_dir())
96 .collect();
97 dirs.sort();
98 let Some(latest) = dirs.last() else {
99 return Ok(());
100 };
101 let timeline = latest.join("timeline.txt");
102 if !timeline.is_file() {
103 return Ok(());
104 }
105 let raw = fs::read_to_string(timeline)?;
106 write_scrubbed_text(&raw, &bundle.join(TIMELINE_NAME))
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112 use tempfile::tempdir;
113
114 fn sample_client() -> ClientInfo {
115 ClientInfo {
116 version: "0.1.0".into(),
117 build: "test".into(),
118 os: "linux".into(),
119 arch: "x86_64".into(),
120 session: "wayland".into(),
121 ui_locale: "en".into(),
122 timezone: "UTC+0".into(),
123 signed_in: true,
124 call_reports: true,
125 debug_logging: true,
126 audio_input: "Default device".into(),
127 audio_output: "Default device".into(),
128 camera: "none".into(),
129 logs_root: "/tmp/data".into(),
130 support_bundles_root: "/tmp/data/support-bundles".into(),
131 }
132 }
133
134 #[test]
135 fn support_bundle_scrubs_secrets_and_skips_store() {
136 let root = tempdir().unwrap();
137 let data = root.path().join("data");
138 fs::create_dir_all(&data).unwrap();
139 let diagnostics = data.join(DIAGNOSTICS_NAME);
140 fs::write(
141 &diagnostics,
142 "ok line\nbearer eyJhbGciOiJIUzI1NiJ9.aaa.bbb\nemail user@example.com\n",
143 )
144 .unwrap();
145 fs::write(data.join("store.db"), "secret-store").unwrap();
146
147 // Install diagnostics path so merge can find the file we wrote under data.
148 app_base::diagnostics::install(diagnostics.clone());
149 app_base::diagnostics::set_enabled(true);
150 // Re-write through the live path if install used a different OnceLock path already.
151 if let Some(live) = app_base::diagnostics::path() {
152 let _ = fs::write(
153 &live,
154 "ok line\nbearer eyJhbGciOiJIUzI1NiJ9.aaa.bbb\nemail user@example.com\n",
155 );
156 }
157
158 let bundle = write_support_bundle(&data, &sample_client(), &diagnostics).unwrap();
159 let client = fs::read_to_string(bundle.directory.join("client.md")).unwrap();
160 assert!(client.contains("### Client"));
161 assert!(client.contains("Debug logging:"));
162 let log_path = bundle.directory.join(DIAGNOSTICS_NAME);
163 if log_path.is_file() {
164 let log = fs::read_to_string(&log_path).unwrap();
165 assert!(!log.contains("eyJhbGciOiJIUzI1NiJ9"));
166 assert!(!log.contains("user@example.com"));
167 }
168 assert!(!bundle.directory.join("store.db").exists());
169 assert!(bundle.directory.join("README.md").is_file());
170 }
171
172 #[test]
173 fn support_bundle_copies_matching_call_report_json() {
174 let root = tempdir().unwrap();
175 let data = root.path().join("data");
176 fs::create_dir_all(&data).unwrap();
177 // Dependency `report_directory()` is the live path (cfg(test) only applies in
178 // app-call-model's own tests). Use a stem that sorts last so KEEP_CALL_REPORTS
179 // still includes it among any pre-existing reports.
180 let target = report_directory();
181 fs::create_dir_all(&target).unwrap();
182 let stem = format!(
183 "zzz-{}-bundle-test",
184 chrono::Utc::now().format("%Y%m%dT%H%M%S%3fZ")
185 );
186 let md_name = format!("{stem}.md");
187 let json_name = format!("{stem}.json");
188 fs::write(target.join(&md_name), "# report\n").unwrap();
189 fs::write(target.join(&json_name), "{\"schema\":1}\n").unwrap();
190
191 let diagnostics = data.join(DIAGNOSTICS_NAME);
192 fs::write(&diagnostics, "line\n").unwrap();
193 let bundle = write_support_bundle(&data, &sample_client(), &diagnostics).unwrap();
194 assert!(
195 bundle.directory.join(&md_name).is_file(),
196 "missing {md_name} in {:?}",
197 bundle.directory
198 );
199 assert!(bundle.directory.join(&json_name).is_file());
200 let _ = fs::remove_file(target.join(&md_name));
201 let _ = fs::remove_file(target.join(&json_name));
202 }
203}
crates/app/src/i18n.rs +23 −0
@@ -72,6 +72,29 @@ mod tests {
72 72 }
73 73
74 74 #[test]
75
76 #[test]
77 fn ui_locale_settings_help_keys() {
78 let _guard = locale_test_lock();
79 apply_locale("en");
80 assert_eq!(tr("settings.nav.help"), "Help");
81 assert_eq!(tr("settings.help.create_bundle_button"), "Create");
82 assert_eq!(tr("settings.help.logs_path"), "Logs root");
83 assert_eq!(tr("settings.help.bundles_path"), "Support packages");
84 assert_eq!(tr("settings.help.packages_empty"), "No support packages yet");
85 assert_eq!(tr("settings.help.copy_path_tooltip"), "Copy path");
86 assert_eq!(tr("settings.help.debug_logging"), "Debug logging");
87 apply_locale("de");
88 assert_eq!(tr("settings.nav.help"), "Hilfe");
89 assert_eq!(tr("settings.help.create_bundle_button"), "Erstellen");
90 assert_eq!(tr("settings.help.logs_path"), "Log-Root");
91 assert_eq!(tr("settings.help.bundles_path"), "Support-Pakete");
92 assert_eq!(tr("settings.help.packages_empty"), "Noch keine Support-Pakete");
93 assert_eq!(tr("settings.help.copy_path_tooltip"), "Pfad kopieren");
94 assert_eq!(tr("settings.help.debug_logging"), "Debug-Protokollierung");
95 assert!(tr("settings.help.detail").contains("Support-Paket"));
96 }
97
75 98 fn ui_locale_auth_splash_keys() {
76 99 let _guard = locale_test_lock();
77 100 apply_locale("en");
@@ -72,6 +72,29 @@ mod tests {
72 }
72 }
73
73
74 #[test]
74 #[test]
75
76 #[test]
77 fn ui_locale_settings_help_keys() {
78 let _guard = locale_test_lock();
79 apply_locale("en");
80 assert_eq!(tr("settings.nav.help"), "Help");
81 assert_eq!(tr("settings.help.create_bundle_button"), "Create");
82 assert_eq!(tr("settings.help.logs_path"), "Logs root");
83 assert_eq!(tr("settings.help.bundles_path"), "Support packages");
84 assert_eq!(tr("settings.help.packages_empty"), "No support packages yet");
85 assert_eq!(tr("settings.help.copy_path_tooltip"), "Copy path");
86 assert_eq!(tr("settings.help.debug_logging"), "Debug logging");
87 apply_locale("de");
88 assert_eq!(tr("settings.nav.help"), "Hilfe");
89 assert_eq!(tr("settings.help.create_bundle_button"), "Erstellen");
90 assert_eq!(tr("settings.help.logs_path"), "Log-Root");
91 assert_eq!(tr("settings.help.bundles_path"), "Support-Pakete");
92 assert_eq!(tr("settings.help.packages_empty"), "Noch keine Support-Pakete");
93 assert_eq!(tr("settings.help.copy_path_tooltip"), "Pfad kopieren");
94 assert_eq!(tr("settings.help.debug_logging"), "Debug-Protokollierung");
95 assert!(tr("settings.help.detail").contains("Support-Paket"));
96 }
97
75 fn ui_locale_auth_splash_keys() {
98 fn ui_locale_auth_splash_keys() {
76 let _guard = locale_test_lock();
99 let _guard = locale_test_lock();
77 apply_locale("en");
100 apply_locale("en");
crates/app/src/layout_guard.rs +11 −1
@@ -322,6 +322,7 @@ mod frames {
322 322 const SETTINGS_TAGS: &[&str] = &[
323 323 "settings",
324 324 "settings/nav",
325 "settings/nav/help",
325 326 "settings/nav/about",
326 327 "settings/main",
327 328 "settings/main/header",
@@ -330,6 +331,7 @@ mod frames {
330 331 ];
331 332 const SETTINGS_BODY: &str = "settings/main/body";
332 333 const SETTINGS_NAV: &str = "settings/nav";
334 const SETTINGS_NAV_HELP: &str = "settings/nav/help";
333 335 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
334 336 const NAV_LABEL_SIZE: f32 = 14.;
335 337 const NAV_LINE_HEIGHT: f32 = 20.;
@@ -348,6 +350,11 @@ mod frames {
348 350 content: "settings/nav/about",
349 351 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
350 352 },
353 InsetRule {
354 panel: "settings/nav",
355 content: "settings/nav/help",
356 edges: &[Edge::Left, Edge::Right],
357 },
351 358 InsetRule {
352 359 panel: "settings/main",
353 360 content: "settings/main/header/close",
@@ -363,7 +370,7 @@ mod frames {
363 370 SettingsSection::Agents,
364 371 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
365 372 )];
366 const SETTINGS_SECTIONS: [SettingsSection; 10] = [
373 const SETTINGS_SECTIONS: [SettingsSection; 11] = [
367 374 SettingsSection::General,
368 375 SettingsSection::Notifications,
369 376 SettingsSection::Appearance,
@@ -373,6 +380,7 @@ mod frames {
373 380 SettingsSection::Devices,
374 381 SettingsSection::Agents,
375 382 SettingsSection::Mcp,
383 SettingsSection::Help,
376 384 SettingsSection::About,
377 385 ];
378 386 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
@@ -1622,6 +1630,8 @@ mod frames {
1622 1630 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1623 1631 let item_path: &'static str = if section == SettingsSection::About {
1624 1632 SETTINGS_NAV_ABOUT
1633 } else if section == SettingsSection::Help {
1634 SETTINGS_NAV_HELP
1625 1635 } else {
1626 1636 Box::leak(item_selector(section).into_boxed_str())
1627 1637 };
@@ -322,6 +322,7 @@ mod frames {
322 const SETTINGS_TAGS: &[&str] = &[
322 const SETTINGS_TAGS: &[&str] = &[
323 "settings",
323 "settings",
324 "settings/nav",
324 "settings/nav",
325 "settings/nav/help",
325 "settings/nav/about",
326 "settings/nav/about",
326 "settings/main",
327 "settings/main",
327 "settings/main/header",
328 "settings/main/header",
@@ -330,6 +331,7 @@ mod frames {
330 ];
331 ];
331 const SETTINGS_BODY: &str = "settings/main/body";
332 const SETTINGS_BODY: &str = "settings/main/body";
332 const SETTINGS_NAV: &str = "settings/nav";
333 const SETTINGS_NAV: &str = "settings/nav";
334 const SETTINGS_NAV_HELP: &str = "settings/nav/help";
333 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
335 const SETTINGS_NAV_ABOUT: &str = "settings/nav/about";
334 const NAV_LABEL_SIZE: f32 = 14.;
336 const NAV_LABEL_SIZE: f32 = 14.;
335 const NAV_LINE_HEIGHT: f32 = 20.;
337 const NAV_LINE_HEIGHT: f32 = 20.;
@@ -348,6 +350,11 @@ mod frames {
348 content: "settings/nav/about",
350 content: "settings/nav/about",
349 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
351 edges: &[Edge::Left, Edge::Right, Edge::Bottom],
350 },
352 },
353 InsetRule {
354 panel: "settings/nav",
355 content: "settings/nav/help",
356 edges: &[Edge::Left, Edge::Right],
357 },
351 InsetRule {
358 InsetRule {
352 panel: "settings/main",
359 panel: "settings/main",
353 content: "settings/main/header/close",
360 content: "settings/main/header/close",
@@ -363,7 +370,7 @@ mod frames {
363 SettingsSection::Agents,
370 SettingsSection::Agents,
364 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
371 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
365 )];
372 )];
366 const SETTINGS_SECTIONS: [SettingsSection; 10] = [
373 const SETTINGS_SECTIONS: [SettingsSection; 11] = [
367 SettingsSection::General,
374 SettingsSection::General,
368 SettingsSection::Notifications,
375 SettingsSection::Notifications,
369 SettingsSection::Appearance,
376 SettingsSection::Appearance,
@@ -373,6 +380,7 @@ mod frames {
373 SettingsSection::Devices,
380 SettingsSection::Devices,
374 SettingsSection::Agents,
381 SettingsSection::Agents,
375 SettingsSection::Mcp,
382 SettingsSection::Mcp,
383 SettingsSection::Help,
376 SettingsSection::About,
384 SettingsSection::About,
377 ];
385 ];
378 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
386 const SIZES: [(f32, f32); 3] = [(640., 480.), (1280., 800.), (1920., 1080.)];
@@ -1622,6 +1630,8 @@ mod frames {
1622 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1630 let label_path: &'static str = Box::leak(label_selector(section).into_boxed_str());
1623 let item_path: &'static str = if section == SettingsSection::About {
1631 let item_path: &'static str = if section == SettingsSection::About {
1624 SETTINGS_NAV_ABOUT
1632 SETTINGS_NAV_ABOUT
1633 } else if section == SettingsSection::Help {
1634 SETTINGS_NAV_HELP
1625 } else {
1635 } else {
1626 Box::leak(item_selector(section).into_boxed_str())
1636 Box::leak(item_selector(section).into_boxed_str())
1627 };
1637 };
crates/app/src/main.rs +23 −6
@@ -173,12 +173,18 @@ fn main() {
173 173 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
174 174 app_base::version::set_release_tag(tag);
175 175 }
176 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
176 crash_log::install(
177 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
178 );
177 179 app_base::native_dumps::install(
178 180 data_path("native-dumps"),
179 data_path(crash_log::CRASH_LOG_FILE),
181 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
182 );
183 diagnostics::install(
184 app_base::support::diagnostics_log_path()
185 .unwrap_or_else(|| data_path(diagnostics::DIAGNOSTICS_FILE)),
180 186 );
181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
187 let _ = diagnostics::enable_from_override();
182 188 #[cfg(target_os = "linux")]
183 189 app_base::linux_fonts::hide_system_color_emoji();
184 190 let arguments = parse_arguments();
@@ -222,9 +228,20 @@ fn main() {
222 228 open_store(&path)
223 229 };
224 230 let store = Arc::new(store);
225 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(
226 app_base::ui_locale::load(&store),
227 ));
231 let stored_diag = store
232 .meta(diagnostics::DIAGNOSTICS_SETTING_KEY)
233 .ok()
234 .flatten();
235 diagnostics::load_enabled_from_store(stored_diag.as_deref());
236 let ui_locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&store));
237 app_base::ui_locale::apply_locale(ui_locale);
238 let call_reports = app_call_model::report::load_enabled(&store);
239 app_base::support::record_startup_client_line(
240 env!("CARGO_PKG_VERSION"),
241 ui_locale,
242 crate::data::me(&store).is_some(),
243 call_reports,
244 );
228 245 #[cfg(windows)]
229 246 let sign_in_title = format!(
230 247 "{} - {}",
@@ -173,12 +173,18 @@ fn main() {
173 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
173 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
174 app_base::version::set_release_tag(tag);
174 app_base::version::set_release_tag(tag);
175 }
175 }
176 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
176 crash_log::install(
177 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
178 );
177 app_base::native_dumps::install(
179 app_base::native_dumps::install(
178 data_path("native-dumps"),
180 data_path("native-dumps"),
179 data_path(crash_log::CRASH_LOG_FILE),
181 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
182 );
183 diagnostics::install(
184 app_base::support::diagnostics_log_path()
185 .unwrap_or_else(|| data_path(diagnostics::DIAGNOSTICS_FILE)),
180 );
186 );
181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
187 let _ = diagnostics::enable_from_override();
182 #[cfg(target_os = "linux")]
188 #[cfg(target_os = "linux")]
183 app_base::linux_fonts::hide_system_color_emoji();
189 app_base::linux_fonts::hide_system_color_emoji();
184 let arguments = parse_arguments();
190 let arguments = parse_arguments();
@@ -222,9 +228,20 @@ fn main() {
222 open_store(&path)
228 open_store(&path)
223 };
229 };
224 let store = Arc::new(store);
230 let store = Arc::new(store);
225 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(
231 let stored_diag = store
226 app_base::ui_locale::load(&store),
232 .meta(diagnostics::DIAGNOSTICS_SETTING_KEY)
227 ));
233 .ok()
234 .flatten();
235 diagnostics::load_enabled_from_store(stored_diag.as_deref());
236 let ui_locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&store));
237 app_base::ui_locale::apply_locale(ui_locale);
238 let call_reports = app_call_model::report::load_enabled(&store);
239 app_base::support::record_startup_client_line(
240 env!("CARGO_PKG_VERSION"),
241 ui_locale,
242 crate::data::me(&store).is_some(),
243 call_reports,
244 );
228 #[cfg(windows)]
245 #[cfg(windows)]
229 let sign_in_title = format!(
246 let sign_in_title = format!(
230 "{} - {}",
247 "{} - {}",
crates/app/src/settings/dialog.rs +60 −18
@@ -3,9 +3,11 @@ use gpui_kit::assets::IconName;
3 3 use gpui_kit::component::input::{Input, InputEvent, InputState};
4 4 use gpui_kit::component::scroll::ScrollableElement as _;
5 5 use gpui_kit::component::{h_flex, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
7 8
8 9 use super::devices::DevicesView;
10 use super::help::HelpView;
9 11 use super::mcp::McpView;
10 12 use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
11 13 use super::rows::ROW_INSET;
@@ -63,6 +65,7 @@ pub struct SettingsDialog {
63 65 center: Entity<NotificationCenter>,
64 66 section: SettingsSection,
65 67 devices: Option<Entity<DevicesView>>,
68 help: Option<Entity<HelpView>>,
66 69 mcp: Option<Entity<McpView>>,
67 70 agents: Option<Entity<AgentsSettings>>,
68 71 body_scroll: ScrollHandle,
@@ -102,6 +105,7 @@ impl SettingsDialog {
102 105 center,
103 106 section,
104 107 devices: None,
108 help: None,
105 109 mcp: None,
106 110 agents: None,
107 111 body_scroll: ScrollHandle::new(),
@@ -127,6 +131,19 @@ impl SettingsDialog {
127 131 } else {
128 132 self.devices = None;
129 133 }
134 if section == SettingsSection::Help {
135 if self.help.is_none() {
136 let app = self.app.clone();
137 self.help = Some(cx.new(|cx| HelpView::new(app, cx)));
138 } else if let Some(help) = self.help.as_ref() {
139 help.update(cx, |view, cx| {
140 view.reload_bundles();
141 cx.notify();
142 });
143 }
144 } else {
145 self.help = None;
146 }
130 147 if section == SettingsSection::Mcp && self.mcp.is_none() {
131 148 let app = self.app.clone();
132 149 self.mcp = Some(cx.new(|cx| McpView::new(app, window, cx)));
@@ -199,6 +216,10 @@ impl SettingsDialog {
199 216 .mcp
200 217 .clone()
201 218 .map_or_else(|| div().into_any_element(), |view| view.into_any_element()),
219 SettingsSection::Help => self
220 .help
221 .clone()
222 .map_or_else(|| div().into_any_element(), |view| view.into_any_element()),
202 223 SettingsSection::About => about::render().into_any_element(),
203 224 }
204 225 }
@@ -268,25 +289,46 @@ impl Render for SettingsDialog {
268 289 } else {
269 290 metrics.padding
270 291 };
271 let scroll_area = div()
272 .id(SharedString::from(format!(
273 "settings-body-{}",
274 label(self.section)
275 )))
292 let help_preview = self
293 .help
294 .as_ref()
295 .is_some_and(|help| help.read(cx).is_previewing());
296 let content = div()
297 .debug_selector(|| "settings/main/body/content".into())
276 298 .w_full()
277 .flex_1()
278 .min_h_0()
279 .overflow_y_scrollbar()
280 .track_scroll(&self.body_scroll)
281 .px(px(body_inset.max(0.)))
282 .pb(px(metrics.padding))
283 .child(
284 div()
285 .debug_selector(|| "settings/main/body/content".into())
286 .w_full()
287 .max_w(px(CONTENT_MAX_WIDTH))
288 .child(self.content(cx)),
289 );
299 .max_w(px(CONTENT_MAX_WIDTH))
300 .when(help_preview, |content| content.h_full().min_h_0())
301 .child(self.content(cx));
302 let scroll_area = if help_preview {
303 div()
304 .id(SharedString::from(format!(
305 "settings-body-{}",
306 label(self.section)
307 )))
308 .w_full()
309 .flex_1()
310 .min_h_0()
311 .overflow_hidden()
312 .px(px(body_inset.max(0.)))
313 .pb(px(metrics.padding))
314 .child(content)
315 .into_any_element()
316 } else {
317 div()
318 .id(SharedString::from(format!(
319 "settings-body-{}",
320 label(self.section)
321 )))
322 .w_full()
323 .flex_1()
324 .min_h_0()
325 .overflow_y_scrollbar()
326 .track_scroll(&self.body_scroll)
327 .px(px(body_inset.max(0.)))
328 .pb(px(metrics.padding))
329 .child(content)
330 .into_any_element()
331 };
290 332 let body = div()
291 333 .debug_selector(|| "settings/main/body".into())
292 334 .w_full()
@@ -3,9 +3,11 @@ use gpui_kit::assets::IconName;
3use gpui_kit::component::input::{Input, InputEvent, InputState};
3use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::scroll::ScrollableElement as _;
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
7
8
8use super::devices::DevicesView;
9use super::devices::DevicesView;
10use super::help::HelpView;
9use super::mcp::McpView;
11use super::mcp::McpView;
10use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
12use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
11use super::rows::ROW_INSET;
13use super::rows::ROW_INSET;
@@ -63,6 +65,7 @@ pub struct SettingsDialog {
63 center: Entity<NotificationCenter>,
65 center: Entity<NotificationCenter>,
64 section: SettingsSection,
66 section: SettingsSection,
65 devices: Option<Entity<DevicesView>>,
67 devices: Option<Entity<DevicesView>>,
68 help: Option<Entity<HelpView>>,
66 mcp: Option<Entity<McpView>>,
69 mcp: Option<Entity<McpView>>,
67 agents: Option<Entity<AgentsSettings>>,
70 agents: Option<Entity<AgentsSettings>>,
68 body_scroll: ScrollHandle,
71 body_scroll: ScrollHandle,
@@ -102,6 +105,7 @@ impl SettingsDialog {
102 center,
105 center,
103 section,
106 section,
104 devices: None,
107 devices: None,
108 help: None,
105 mcp: None,
109 mcp: None,
106 agents: None,
110 agents: None,
107 body_scroll: ScrollHandle::new(),
111 body_scroll: ScrollHandle::new(),
@@ -127,6 +131,19 @@ impl SettingsDialog {
127 } else {
131 } else {
128 self.devices = None;
132 self.devices = None;
129 }
133 }
134 if section == SettingsSection::Help {
135 if self.help.is_none() {
136 let app = self.app.clone();
137 self.help = Some(cx.new(|cx| HelpView::new(app, cx)));
138 } else if let Some(help) = self.help.as_ref() {
139 help.update(cx, |view, cx| {
140 view.reload_bundles();
141 cx.notify();
142 });
143 }
144 } else {
145 self.help = None;
146 }
130 if section == SettingsSection::Mcp && self.mcp.is_none() {
147 if section == SettingsSection::Mcp && self.mcp.is_none() {
131 let app = self.app.clone();
148 let app = self.app.clone();
132 self.mcp = Some(cx.new(|cx| McpView::new(app, window, cx)));
149 self.mcp = Some(cx.new(|cx| McpView::new(app, window, cx)));
@@ -199,6 +216,10 @@ impl SettingsDialog {
199 .mcp
216 .mcp
200 .clone()
217 .clone()
201 .map_or_else(|| div().into_any_element(), |view| view.into_any_element()),
218 .map_or_else(|| div().into_any_element(), |view| view.into_any_element()),
219 SettingsSection::Help => self
220 .help
221 .clone()
222 .map_or_else(|| div().into_any_element(), |view| view.into_any_element()),
202 SettingsSection::About => about::render().into_any_element(),
223 SettingsSection::About => about::render().into_any_element(),
203 }
224 }
204 }
225 }
@@ -268,25 +289,46 @@ impl Render for SettingsDialog {
268 } else {
289 } else {
269 metrics.padding
290 metrics.padding
270 };
291 };
271 let scroll_area = div()
292 let help_preview = self
272 .id(SharedString::from(format!(
293 .help
273 "settings-body-{}",
294 .as_ref()
274 label(self.section)
295 .is_some_and(|help| help.read(cx).is_previewing());
275 )))
296 let content = div()
297 .debug_selector(|| "settings/main/body/content".into())
276 .w_full()
298 .w_full()
277 .flex_1()
299 .max_w(px(CONTENT_MAX_WIDTH))
278 .min_h_0()
300 .when(help_preview, |content| content.h_full().min_h_0())
279 .overflow_y_scrollbar()
301 .child(self.content(cx));
280 .track_scroll(&self.body_scroll)
302 let scroll_area = if help_preview {
281 .px(px(body_inset.max(0.)))
303 div()
282 .pb(px(metrics.padding))
304 .id(SharedString::from(format!(
283 .child(
305 "settings-body-{}",
284 div()
306 label(self.section)
285 .debug_selector(|| "settings/main/body/content".into())
307 )))
286 .w_full()
308 .w_full()
287 .max_w(px(CONTENT_MAX_WIDTH))
309 .flex_1()
288 .child(self.content(cx)),
310 .min_h_0()
289 );
311 .overflow_hidden()
312 .px(px(body_inset.max(0.)))
313 .pb(px(metrics.padding))
314 .child(content)
315 .into_any_element()
316 } else {
317 div()
318 .id(SharedString::from(format!(
319 "settings-body-{}",
320 label(self.section)
321 )))
322 .w_full()
323 .flex_1()
324 .min_h_0()
325 .overflow_y_scrollbar()
326 .track_scroll(&self.body_scroll)
327 .px(px(body_inset.max(0.)))
328 .pb(px(metrics.padding))
329 .child(content)
330 .into_any_element()
331 };
290 let body = div()
332 let body = div()
291 .debug_selector(|| "settings/main/body".into())
333 .debug_selector(|| "settings/main/body".into())
292 .w_full()
334 .w_full()
crates/app/src/settings/help.rs added +593 −0
@@ -0,0 +1,593 @@
1 use std::path::{Path, PathBuf};
2
3 use app_base::downloads::reveal_in_file_manager;
4 use app_base::support::{
5 self, BundleFileEntry, SupportBundleEntry, ensure_dir, format_bytes, list_bundle_files,
6 list_support_bundles,
7 };
8 use app_ui_kit::render::{layout_blocks, render_blocks, strip_image_placeholders};
9 use gpui_kit::assets::IconName;
10 use gpui_kit::component::scroll::ScrollableElement as _;
11 use gpui_kit::component::tooltip::Tooltip;
12 use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
13 use gpui_kit::prelude::FluentBuilder as _;
14 use gpui_kit::*;
15
16 use super::rows::{ROW_INSET, caption, control_row, text_button, toggle_row};
17 use crate::app_state::AppState;
18 use crate::i18n::tr;
19 use crate::theme::{self, ElevatedSurface as _};
20 use crate::views::widgets::icon;
21
22 const COPY_ICON_SIZE: f32 = 14.;
23 const PREVIEW_LIMIT: usize = 256 * 1024;
24 const PREVIEW_RADIUS: f32 = 10.;
25 const PREVIEW_PADDING: f32 = 12.;
26
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 enum PreviewKind {
29 Markdown,
30 Text,
31 }
32
33 struct FilePreview {
34 name: String,
35 text: String,
36 kind: PreviewKind,
37 truncated: bool,
38 }
39
40 pub struct HelpView {
41 app: Entity<AppState>,
42 bundles: Vec<SupportBundleEntry>,
43 expanded: Option<PathBuf>,
44 expanded_files: Vec<BundleFileEntry>,
45 preview: Option<FilePreview>,
46 }
47
48 impl HelpView {
49 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
50 let mut view = HelpView {
51 app,
52 bundles: Vec::new(),
53 expanded: None,
54 expanded_files: Vec::new(),
55 preview: None,
56 };
57 view.reload_bundles();
58 let _ = cx;
59 view
60 }
61
62 pub(crate) fn is_previewing(&self) -> bool {
63 self.preview.is_some()
64 }
65
66 pub(crate) fn reload_bundles(&mut self) {
67 let root = support::support_bundles_dir().unwrap_or_default();
68 self.bundles = list_support_bundles(&root).unwrap_or_default();
69 if let Some(expanded) = self.expanded.clone() {
70 if self.bundles.iter().any(|entry| entry.directory == expanded) {
71 self.expanded_files = list_bundle_files(&expanded).unwrap_or_default();
72 } else {
73 self.expanded = None;
74 self.expanded_files.clear();
75 }
76 }
77 }
78
79 fn toggle_expand(&mut self, directory: PathBuf, cx: &mut Context<Self>) {
80 if self.expanded.as_ref() == Some(&directory) {
81 self.expanded = None;
82 self.expanded_files.clear();
83 } else {
84 self.expanded_files = list_bundle_files(&directory).unwrap_or_default();
85 self.expanded = Some(directory);
86 }
87 cx.notify();
88 }
89
90 fn delete_bundle(&mut self, directory: PathBuf, cx: &mut Context<Self>) {
91 let parent = support::support_bundles_dir();
92 if let Err(error) = support::delete_support_bundle(&directory, parent.as_deref()) {
93 app_base::diagnostics::record(format!("support delete: {error}"));
94 return;
95 }
96 if self.expanded.as_ref() == Some(&directory) {
97 self.expanded = None;
98 self.expanded_files.clear();
99 }
100 self.preview = None;
101 self.reload_bundles();
102 cx.notify();
103 }
104
105 fn reveal_path(path: &Path) {
106 let _ = ensure_dir(path);
107 reveal_in_file_manager(path);
108 }
109
110 fn open_preview(&mut self, path: PathBuf, cx: &mut Context<Self>) {
111 let name = path
112 .file_name()
113 .map(|value| value.to_string_lossy().into_owned())
114 .unwrap_or_else(|| path.display().to_string());
115 let kind = if name.ends_with(".md") {
116 PreviewKind::Markdown
117 } else {
118 PreviewKind::Text
119 };
120 match read_preview_text(&path) {
121 Ok(ReadPreview {
122 text,
123 truncated,
124 binary,
125 }) => {
126 self.preview = Some(FilePreview {
127 name,
128 text: if binary {
129 tr("settings.help.preview_binary")
130 } else {
131 text
132 },
133 kind: if binary { PreviewKind::Text } else { kind },
134 truncated: truncated && !binary,
135 });
136 }
137 Err(error) => {
138 app_base::diagnostics::record(format!("support preview: {error}"));
139 self.preview = Some(FilePreview {
140 name,
141 text: tr("settings.help.preview_error"),
142 kind: PreviewKind::Text,
143 truncated: false,
144 });
145 }
146 }
147 cx.notify();
148 }
149
150 fn close_preview(&mut self, cx: &mut Context<Self>) {
151 self.preview = None;
152 cx.notify();
153 }
154
155 fn copy_path_button(id: &'static str, path: String) -> Stateful<Div> {
156 div()
157 .id(id)
158 .cursor_pointer()
159 .p(px(4.))
160 .rounded(px(6.))
161 .hover(|button| button.bg(theme::row_hover()))
162 .tooltip(|window, cx| {
163 Tooltip::new(tr("settings.help.copy_path_tooltip")).build(window, cx)
164 })
165 .on_click(move |_, _, cx| {
166 cx.stop_propagation();
167 cx.write_to_clipboard(ClipboardItem::new_string(path.clone()));
168 })
169 .child(icon(IconName::Copy, COPY_ICON_SIZE, theme::text_muted()))
170 }
171
172 fn path_row(
173 &self,
174 title: impl Into<SharedString>,
175 path: String,
176 copy_id: &'static str,
177 open_id: &'static str,
178 cx: &App,
179 ) -> Div {
180 let title = title.into();
181 let open_path = PathBuf::from(path.clone());
182 v_flex()
183 .w_full()
184 .px(px(ROW_INSET))
185 .py(px(12.))
186 .gap(px(8.))
187 .rounded(px(8.))
188 .child(
189 h_flex()
190 .w_full()
191 .gap(px(8.))
192 .items_center()
193 .child(
194 div()
195 .flex_1()
196 .min_w(px(0.))
197 .text_size(px(14.))
198 .line_height(px(20.))
199 .font_weight(FontWeight::SEMIBOLD)
200 .text_color(theme::text())
201 .child(title),
202 )
203 .child(Self::copy_path_button(copy_id, path.clone()))
204 .child(text_button(open_id, tr("common.open")).on_click(move |_, _, _| {
205 Self::reveal_path(&open_path);
206 })),
207 )
208 .child(
209 div()
210 .w_full()
211 .min_w(px(0.))
212 .font_family(cx.theme().mono_font_family.clone())
213 .text_size(px(12.))
214 .line_height(px(18.))
215 .text_color(theme::text_muted())
216 .whitespace_normal()
217 .child(path),
218 )
219 }
220
221 fn bundle_row(&self, entry: &SupportBundleEntry, cx: &mut Context<Self>) -> Div {
222 let directory = entry.directory.clone();
223 let toggle_dir = directory.clone();
224 let delete_dir = directory.clone();
225 let expanded = self.expanded.as_ref() == Some(&directory);
226 v_flex()
227 .w_full()
228 .child(
229 h_flex()
230 .w_full()
231 .px(px(ROW_INSET))
232 .py(px(10.))
233 .gap(px(12.))
234 .items_center()
235 .rounded(px(8.))
236 .when(expanded, |row| row.bg(theme::popup_hover()))
237 .child(
238 h_flex()
239 .id(SharedString::from(format!(
240 "settings-help-bundle-{}",
241 entry.name
242 )))
243 .flex_1()
244 .min_w(px(0.))
245 .gap(px(8.))
246 .items_center()
247 .cursor_pointer()
248 .hover(|row| row.bg(theme::popup_hover()))
249 .on_click(cx.listener(move |this, _, _, cx| {
250 this.toggle_expand(toggle_dir.clone(), cx);
251 }))
252 .child(
253 div()
254 .flex_1()
255 .min_w(px(0.))
256 .text_size(px(14.))
257 .font_weight(FontWeight::SEMIBOLD)
258 .text_color(theme::text())
259 .child(entry.name.clone()),
260 ),
261 )
262 .child(
263 text_button(
264 SharedString::from(format!("settings-help-delete-{}", entry.name)),
265 tr("common.delete"),
266 )
267 .on_click(cx.listener(move |this, _, _, cx| {
268 this.delete_bundle(delete_dir.clone(), cx);
269 })),
270 ),
271 )
272 .when(expanded, |column| column.child(self.expanded_panel(cx)))
273 }
274
275 fn expanded_panel(&self, cx: &mut Context<Self>) -> Div {
276 v_flex()
277 .w_full()
278 .px(px(ROW_INSET + 8.))
279 .pb(px(8.))
280 .gap(px(4.))
281 .children(self.expanded_files.iter().map(|file| {
282 let path = file.path.clone();
283 let label = format!("{} · {}", file.name, format_bytes(file.size_bytes));
284 div()
285 .id(SharedString::from(format!(
286 "settings-help-file-{}",
287 file.name
288 )))
289 .w_full()
290 .px(px(8.))
291 .py(px(6.))
292 .rounded(px(6.))
293 .cursor_pointer()
294 .hover(|row| row.bg(theme::popup_hover()))
295 .on_click(cx.listener(move |this, _, _, cx| {
296 this.open_preview(path.clone(), cx);
297 }))
298 .child(
299 div()
300 .text_size(px(12.))
301 .text_color(theme::text_muted())
302 .child(label),
303 )
304 }))
305 }
306
307 fn packages_section(&self, cx: &mut Context<Self>) -> Div {
308 v_flex()
309 .w_full()
310 .child(caption(tr("settings.help.caption_packages")))
311 .when(self.bundles.is_empty(), |section| {
312 section.child(
313 div()
314 .px(px(ROW_INSET))
315 .py(px(8.))
316 .text_size(px(13.))
317 .text_color(theme::text_muted())
318 .child(tr("settings.help.packages_empty")),
319 )
320 })
321 .children(
322 self.bundles
323 .iter()
324 .map(|entry| self.bundle_row(entry, cx))
325 .collect::<Vec<_>>(),
326 )
327 }
328
329 fn preview_body(&self, preview: &FilePreview, cx: &App) -> AnyElement {
330 match preview.kind {
331 PreviewKind::Markdown => {
332 // Full document markdown (headings, tables, lists) — not the light chat dialect.
333 let html = teams_core::Draft::from_markdown(&preview.text).to_html();
334 let blocks =
335 strip_image_placeholders(layout_blocks(&teams_core::html_to_spans(&html)));
336 div()
337 .w_full()
338 .min_w(px(0.))
339 .text_size(px(13.))
340 .text_color(theme::text())
341 .whitespace_normal()
342 .child(render_blocks(&blocks, "settings-help-preview", false, cx))
343 .into_any_element()
344 }
345 PreviewKind::Text => div()
346 .w_full()
347 .min_w(px(0.))
348 .font_family(cx.theme().mono_font_family.clone())
349 .text_size(px(12.))
350 .line_height(px(18.))
351 .text_color(theme::text_muted())
352 .whitespace_normal()
353 .child(preview.text.clone())
354 .into_any_element(),
355 }
356 }
357
358 fn preview_panel(&self, cx: &mut Context<Self>) -> Div {
359 let preview = self.preview.as_ref().expect("preview open");
360 v_flex()
361 .w_full()
362 .h_full()
363 .min_h_0()
364 .gap(px(8.))
365 .px(px(ROW_INSET))
366 .pb(px(ROW_INSET))
367 .child(
368 h_flex()
369 .w_full()
370 .flex_none()
371 .gap(px(8.))
372 .items_center()
373 .child(
374 text_button("settings-help-preview-back", tr("common.close")).on_click(
375 cx.listener(|this, _, _, cx| this.close_preview(cx)),
376 ),
377 )
378 .child(
379 div()
380 .flex_1()
381 .min_w(px(0.))
382 .text_size(px(14.))
383 .font_weight(FontWeight::SEMIBOLD)
384 .text_color(theme::text())
385 .child(preview.name.clone()),
386 ),
387 )
388 .when(preview.truncated, |column| {
389 column.child(
390 div()
391 .flex_none()
392 .text_size(px(12.))
393 .text_color(theme::text_muted())
394 .child(tr("settings.help.preview_truncated")),
395 )
396 })
397 .child(
398 div()
399 .id("settings-help-preview-scroll")
400 .w_full()
401 .flex_1()
402 .min_h_0()
403 .p(px(PREVIEW_PADDING))
404 .rounded(px(PREVIEW_RADIUS))
405 .dialog_surface()
406 .overflow_y_scrollbar()
407 .child(self.preview_body(preview, cx)),
408 )
409 }
410
411 fn help_home(&self, cx: &mut Context<Self>) -> Div {
412 let info = self.app.read(cx).client_info();
413 let summary = info.markdown();
414 let copy_summary = summary.clone();
415 let logs_path = info.logs_root.clone();
416 let bundles_path = info.support_bundles_root.clone();
417 let create_app = self.app.clone();
418 let issue_app = self.app.clone();
419 v_flex()
420 .w_full()
421 .gap(px(4.))
422 .child(caption(tr("settings.help.caption_client")))
423 .child(control_row(
424 tr("settings.help.version"),
425 format!("{} ({})", info.version, info.build),
426 div(),
427 ))
428 .child(control_row(
429 tr("settings.help.platform"),
430 format!("{} / {} / {}", info.os, info.arch, info.session),
431 div(),
432 ))
433 .child(control_row(
434 tr("settings.help.locale"),
435 format!("{} · {}", info.ui_locale, info.timezone),
436 div(),
437 ))
438 .child(control_row(
439 tr("settings.help.signed_in"),
440 if info.signed_in {
441 tr("settings.help.yes")
442 } else {
443 tr("settings.help.no")
444 },
445 div(),
446 ))
447 .child({
448 let debug_on = self.app.read(cx).diagnostics_enabled();
449 let toggle_app = self.app.clone();
450 toggle_row(
451 "settings-help-debug-log",
452 tr("settings.help.debug_logging"),
453 if debug_on {
454 tr("settings.help.debug_logging_on_detail")
455 } else {
456 tr("settings.help.debug_logging_off_detail")
457 },
458 theme::text_muted(),
459 debug_on,
460 )
461 .on_click(cx.listener(move |_, _, _, cx| {
462 toggle_app.update(cx, |state, cx| {
463 state.set_diagnostics_enabled(!debug_on, cx);
464 });
465 cx.notify();
466 }))
467 })
468 .child({
469 let clear_app = self.app.clone();
470 control_row(
471 tr("settings.help.clear_logs"),
472 tr("settings.help.clear_logs_detail"),
473 text_button("settings-help-clear-logs", tr("settings.help.clear_logs_button"))
474 .on_click(cx.listener(move |_, _, _, cx| {
475 clear_app.update(cx, |state, cx| state.clear_diagnostic_logs(cx));
476 cx.notify();
477 })),
478 )
479 })
480 .child(caption(tr("settings.help.caption_paths")))
481 .child(self.path_row(
482 tr("settings.help.logs_path"),
483 logs_path,
484 "settings-help-copy-logs",
485 "settings-help-open-logs-root",
486 cx,
487 ))
488 .child(self.path_row(
489 tr("settings.help.bundles_path"),
490 bundles_path,
491 "settings-help-copy-bundles",
492 "settings-help-open-bundles-root",
493 cx,
494 ))
495 .child(self.packages_section(cx))
496 .child(caption(tr("settings.help.caption_actions")))
497 .child(
498 div()
499 .text_size(px(13.))
500 .text_color(theme::text_muted())
501 .pb(px(8.))
502 .px(px(ROW_INSET))
503 .child(tr("settings.help.detail")),
504 )
505 .child(control_row(
506 tr("settings.help.create_bundle"),
507 tr("settings.help.create_bundle_detail"),
508 text_button("settings-help-bundle", tr("settings.help.create_bundle_button"))
509 .on_click(cx.listener(move |this, _, _, cx| {
510 create_app.update(cx, |state, _| {
511 match state.create_support_bundle() {
512 Ok(bundle) => AppState::reveal_support_bundle(&bundle),
513 Err(error) => app_base::diagnostics::record(format!(
514 "support bundle: {error}"
515 )),
516 }
517 });
518 this.reload_bundles();
519 cx.notify();
520 })),
521 ))
522 .child(control_row(
523 tr("settings.help.open_issue"),
524 tr("settings.help.open_issue_detail"),
525 text_button("settings-help-issue", tr("settings.help.open_issue_button")).on_click(
526 cx.listener(move |this, _, _, cx| {
527 issue_app.update(cx, |state, cx| {
528 if let Err(error) = state.open_github_issue_with_bundle(cx) {
529 app_base::diagnostics::record(format!("support issue: {error}"));
530 }
531 });
532 this.reload_bundles();
533 cx.notify();
534 }),
535 ),
536 ))
537 .child(control_row(
538 tr("settings.help.copy_summary"),
539 tr("settings.help.copy_summary_detail"),
540 text_button("settings-help-copy", tr("settings.help.copy_button")).on_click(
541 move |_, _, cx| {
542 cx.write_to_clipboard(ClipboardItem::new_string(copy_summary.clone()));
543 },
544 ),
545 ))
546 .child(control_row(
547 tr("settings.help.open_logs"),
548 tr("settings.help.open_logs_detail"),
549 text_button("settings-help-logs", tr("common.open")).on_click(move |_, _, _| {
550 AppState::reveal_logs_folder();
551 }),
552 ))
553 }
554 }
555
556 struct ReadPreview {
557 text: String,
558 truncated: bool,
559 binary: bool,
560 }
561
562 fn read_preview_text(path: &Path) -> std::io::Result<ReadPreview> {
563 let bytes = std::fs::read(path)?;
564 let truncated = bytes.len() > PREVIEW_LIMIT;
565 let slice = &bytes[..bytes.len().min(PREVIEW_LIMIT)];
566 match std::str::from_utf8(slice) {
567 Ok(text) => Ok(ReadPreview {
568 text: text.to_owned(),
569 truncated,
570 binary: false,
571 }),
572 Err(_) => Ok(ReadPreview {
573 text: String::new(),
574 truncated: false,
575 binary: true,
576 }),
577 }
578 }
579
580 impl Render for HelpView {
581 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
582 let previewing = self.preview.is_some();
583 v_flex()
584 .w_full()
585 .when(previewing, |root| root.h_full().min_h_0())
586 .debug_selector(|| "settings/help".into())
587 .child(if previewing {
588 self.preview_panel(cx)
589 } else {
590 self.help_home(cx)
591 })
592 }
593 }
@@ -0,0 +1,593 @@
1use std::path::{Path, PathBuf};
2
3use app_base::downloads::reveal_in_file_manager;
4use app_base::support::{
5 self, BundleFileEntry, SupportBundleEntry, ensure_dir, format_bytes, list_bundle_files,
6 list_support_bundles,
7};
8use app_ui_kit::render::{layout_blocks, render_blocks, strip_image_placeholders};
9use gpui_kit::assets::IconName;
10use gpui_kit::component::scroll::ScrollableElement as _;
11use gpui_kit::component::tooltip::Tooltip;
12use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
13use gpui_kit::prelude::FluentBuilder as _;
14use gpui_kit::*;
15
16use super::rows::{ROW_INSET, caption, control_row, text_button, toggle_row};
17use crate::app_state::AppState;
18use crate::i18n::tr;
19use crate::theme::{self, ElevatedSurface as _};
20use crate::views::widgets::icon;
21
22const COPY_ICON_SIZE: f32 = 14.;
23const PREVIEW_LIMIT: usize = 256 * 1024;
24const PREVIEW_RADIUS: f32 = 10.;
25const PREVIEW_PADDING: f32 = 12.;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28enum PreviewKind {
29 Markdown,
30 Text,
31}
32
33struct FilePreview {
34 name: String,
35 text: String,
36 kind: PreviewKind,
37 truncated: bool,
38}
39
40pub struct HelpView {
41 app: Entity<AppState>,
42 bundles: Vec<SupportBundleEntry>,
43 expanded: Option<PathBuf>,
44 expanded_files: Vec<BundleFileEntry>,
45 preview: Option<FilePreview>,
46}
47
48impl HelpView {
49 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
50 let mut view = HelpView {
51 app,
52 bundles: Vec::new(),
53 expanded: None,
54 expanded_files: Vec::new(),
55 preview: None,
56 };
57 view.reload_bundles();
58 let _ = cx;
59 view
60 }
61
62 pub(crate) fn is_previewing(&self) -> bool {
63 self.preview.is_some()
64 }
65
66 pub(crate) fn reload_bundles(&mut self) {
67 let root = support::support_bundles_dir().unwrap_or_default();
68 self.bundles = list_support_bundles(&root).unwrap_or_default();
69 if let Some(expanded) = self.expanded.clone() {
70 if self.bundles.iter().any(|entry| entry.directory == expanded) {
71 self.expanded_files = list_bundle_files(&expanded).unwrap_or_default();
72 } else {
73 self.expanded = None;
74 self.expanded_files.clear();
75 }
76 }
77 }
78
79 fn toggle_expand(&mut self, directory: PathBuf, cx: &mut Context<Self>) {
80 if self.expanded.as_ref() == Some(&directory) {
81 self.expanded = None;
82 self.expanded_files.clear();
83 } else {
84 self.expanded_files = list_bundle_files(&directory).unwrap_or_default();
85 self.expanded = Some(directory);
86 }
87 cx.notify();
88 }
89
90 fn delete_bundle(&mut self, directory: PathBuf, cx: &mut Context<Self>) {
91 let parent = support::support_bundles_dir();
92 if let Err(error) = support::delete_support_bundle(&directory, parent.as_deref()) {
93 app_base::diagnostics::record(format!("support delete: {error}"));
94 return;
95 }
96 if self.expanded.as_ref() == Some(&directory) {
97 self.expanded = None;
98 self.expanded_files.clear();
99 }
100 self.preview = None;
101 self.reload_bundles();
102 cx.notify();
103 }
104
105 fn reveal_path(path: &Path) {
106 let _ = ensure_dir(path);
107 reveal_in_file_manager(path);
108 }
109
110 fn open_preview(&mut self, path: PathBuf, cx: &mut Context<Self>) {
111 let name = path
112 .file_name()
113 .map(|value| value.to_string_lossy().into_owned())
114 .unwrap_or_else(|| path.display().to_string());
115 let kind = if name.ends_with(".md") {
116 PreviewKind::Markdown
117 } else {
118 PreviewKind::Text
119 };
120 match read_preview_text(&path) {
121 Ok(ReadPreview {
122 text,
123 truncated,
124 binary,
125 }) => {
126 self.preview = Some(FilePreview {
127 name,
128 text: if binary {
129 tr("settings.help.preview_binary")
130 } else {
131 text
132 },
133 kind: if binary { PreviewKind::Text } else { kind },
134 truncated: truncated && !binary,
135 });
136 }
137 Err(error) => {
138 app_base::diagnostics::record(format!("support preview: {error}"));
139 self.preview = Some(FilePreview {
140 name,
141 text: tr("settings.help.preview_error"),
142 kind: PreviewKind::Text,
143 truncated: false,
144 });
145 }
146 }
147 cx.notify();
148 }
149
150 fn close_preview(&mut self, cx: &mut Context<Self>) {
151 self.preview = None;
152 cx.notify();
153 }
154
155 fn copy_path_button(id: &'static str, path: String) -> Stateful<Div> {
156 div()
157 .id(id)
158 .cursor_pointer()
159 .p(px(4.))
160 .rounded(px(6.))
161 .hover(|button| button.bg(theme::row_hover()))
162 .tooltip(|window, cx| {
163 Tooltip::new(tr("settings.help.copy_path_tooltip")).build(window, cx)
164 })
165 .on_click(move |_, _, cx| {
166 cx.stop_propagation();
167 cx.write_to_clipboard(ClipboardItem::new_string(path.clone()));
168 })
169 .child(icon(IconName::Copy, COPY_ICON_SIZE, theme::text_muted()))
170 }
171
172 fn path_row(
173 &self,
174 title: impl Into<SharedString>,
175 path: String,
176 copy_id: &'static str,
177 open_id: &'static str,
178 cx: &App,
179 ) -> Div {
180 let title = title.into();
181 let open_path = PathBuf::from(path.clone());
182 v_flex()
183 .w_full()
184 .px(px(ROW_INSET))
185 .py(px(12.))
186 .gap(px(8.))
187 .rounded(px(8.))
188 .child(
189 h_flex()
190 .w_full()
191 .gap(px(8.))
192 .items_center()
193 .child(
194 div()
195 .flex_1()
196 .min_w(px(0.))
197 .text_size(px(14.))
198 .line_height(px(20.))
199 .font_weight(FontWeight::SEMIBOLD)
200 .text_color(theme::text())
201 .child(title),
202 )
203 .child(Self::copy_path_button(copy_id, path.clone()))
204 .child(text_button(open_id, tr("common.open")).on_click(move |_, _, _| {
205 Self::reveal_path(&open_path);
206 })),
207 )
208 .child(
209 div()
210 .w_full()
211 .min_w(px(0.))
212 .font_family(cx.theme().mono_font_family.clone())
213 .text_size(px(12.))
214 .line_height(px(18.))
215 .text_color(theme::text_muted())
216 .whitespace_normal()
217 .child(path),
218 )
219 }
220
221 fn bundle_row(&self, entry: &SupportBundleEntry, cx: &mut Context<Self>) -> Div {
222 let directory = entry.directory.clone();
223 let toggle_dir = directory.clone();
224 let delete_dir = directory.clone();
225 let expanded = self.expanded.as_ref() == Some(&directory);
226 v_flex()
227 .w_full()
228 .child(
229 h_flex()
230 .w_full()
231 .px(px(ROW_INSET))
232 .py(px(10.))
233 .gap(px(12.))
234 .items_center()
235 .rounded(px(8.))
236 .when(expanded, |row| row.bg(theme::popup_hover()))
237 .child(
238 h_flex()
239 .id(SharedString::from(format!(
240 "settings-help-bundle-{}",
241 entry.name
242 )))
243 .flex_1()
244 .min_w(px(0.))
245 .gap(px(8.))
246 .items_center()
247 .cursor_pointer()
248 .hover(|row| row.bg(theme::popup_hover()))
249 .on_click(cx.listener(move |this, _, _, cx| {
250 this.toggle_expand(toggle_dir.clone(), cx);
251 }))
252 .child(
253 div()
254 .flex_1()
255 .min_w(px(0.))
256 .text_size(px(14.))
257 .font_weight(FontWeight::SEMIBOLD)
258 .text_color(theme::text())
259 .child(entry.name.clone()),
260 ),
261 )
262 .child(
263 text_button(
264 SharedString::from(format!("settings-help-delete-{}", entry.name)),
265 tr("common.delete"),
266 )
267 .on_click(cx.listener(move |this, _, _, cx| {
268 this.delete_bundle(delete_dir.clone(), cx);
269 })),
270 ),
271 )
272 .when(expanded, |column| column.child(self.expanded_panel(cx)))
273 }
274
275 fn expanded_panel(&self, cx: &mut Context<Self>) -> Div {
276 v_flex()
277 .w_full()
278 .px(px(ROW_INSET + 8.))
279 .pb(px(8.))
280 .gap(px(4.))
281 .children(self.expanded_files.iter().map(|file| {
282 let path = file.path.clone();
283 let label = format!("{} · {}", file.name, format_bytes(file.size_bytes));
284 div()
285 .id(SharedString::from(format!(
286 "settings-help-file-{}",
287 file.name
288 )))
289 .w_full()
290 .px(px(8.))
291 .py(px(6.))
292 .rounded(px(6.))
293 .cursor_pointer()
294 .hover(|row| row.bg(theme::popup_hover()))
295 .on_click(cx.listener(move |this, _, _, cx| {
296 this.open_preview(path.clone(), cx);
297 }))
298 .child(
299 div()
300 .text_size(px(12.))
301 .text_color(theme::text_muted())
302 .child(label),
303 )
304 }))
305 }
306
307 fn packages_section(&self, cx: &mut Context<Self>) -> Div {
308 v_flex()
309 .w_full()
310 .child(caption(tr("settings.help.caption_packages")))
311 .when(self.bundles.is_empty(), |section| {
312 section.child(
313 div()
314 .px(px(ROW_INSET))
315 .py(px(8.))
316 .text_size(px(13.))
317 .text_color(theme::text_muted())
318 .child(tr("settings.help.packages_empty")),
319 )
320 })
321 .children(
322 self.bundles
323 .iter()
324 .map(|entry| self.bundle_row(entry, cx))
325 .collect::<Vec<_>>(),
326 )
327 }
328
329 fn preview_body(&self, preview: &FilePreview, cx: &App) -> AnyElement {
330 match preview.kind {
331 PreviewKind::Markdown => {
332 // Full document markdown (headings, tables, lists) — not the light chat dialect.
333 let html = teams_core::Draft::from_markdown(&preview.text).to_html();
334 let blocks =
335 strip_image_placeholders(layout_blocks(&teams_core::html_to_spans(&html)));
336 div()
337 .w_full()
338 .min_w(px(0.))
339 .text_size(px(13.))
340 .text_color(theme::text())
341 .whitespace_normal()
342 .child(render_blocks(&blocks, "settings-help-preview", false, cx))
343 .into_any_element()
344 }
345 PreviewKind::Text => div()
346 .w_full()
347 .min_w(px(0.))
348 .font_family(cx.theme().mono_font_family.clone())
349 .text_size(px(12.))
350 .line_height(px(18.))
351 .text_color(theme::text_muted())
352 .whitespace_normal()
353 .child(preview.text.clone())
354 .into_any_element(),
355 }
356 }
357
358 fn preview_panel(&self, cx: &mut Context<Self>) -> Div {
359 let preview = self.preview.as_ref().expect("preview open");
360 v_flex()
361 .w_full()
362 .h_full()
363 .min_h_0()
364 .gap(px(8.))
365 .px(px(ROW_INSET))
366 .pb(px(ROW_INSET))
367 .child(
368 h_flex()
369 .w_full()
370 .flex_none()
371 .gap(px(8.))
372 .items_center()
373 .child(
374 text_button("settings-help-preview-back", tr("common.close")).on_click(
375 cx.listener(|this, _, _, cx| this.close_preview(cx)),
376 ),
377 )
378 .child(
379 div()
380 .flex_1()
381 .min_w(px(0.))
382 .text_size(px(14.))
383 .font_weight(FontWeight::SEMIBOLD)
384 .text_color(theme::text())
385 .child(preview.name.clone()),
386 ),
387 )
388 .when(preview.truncated, |column| {
389 column.child(
390 div()
391 .flex_none()
392 .text_size(px(12.))
393 .text_color(theme::text_muted())
394 .child(tr("settings.help.preview_truncated")),
395 )
396 })
397 .child(
398 div()
399 .id("settings-help-preview-scroll")
400 .w_full()
401 .flex_1()
402 .min_h_0()
403 .p(px(PREVIEW_PADDING))
404 .rounded(px(PREVIEW_RADIUS))
405 .dialog_surface()
406 .overflow_y_scrollbar()
407 .child(self.preview_body(preview, cx)),
408 )
409 }
410
411 fn help_home(&self, cx: &mut Context<Self>) -> Div {
412 let info = self.app.read(cx).client_info();
413 let summary = info.markdown();
414 let copy_summary = summary.clone();
415 let logs_path = info.logs_root.clone();
416 let bundles_path = info.support_bundles_root.clone();
417 let create_app = self.app.clone();
418 let issue_app = self.app.clone();
419 v_flex()
420 .w_full()
421 .gap(px(4.))
422 .child(caption(tr("settings.help.caption_client")))
423 .child(control_row(
424 tr("settings.help.version"),
425 format!("{} ({})", info.version, info.build),
426 div(),
427 ))
428 .child(control_row(
429 tr("settings.help.platform"),
430 format!("{} / {} / {}", info.os, info.arch, info.session),
431 div(),
432 ))
433 .child(control_row(
434 tr("settings.help.locale"),
435 format!("{} · {}", info.ui_locale, info.timezone),
436 div(),
437 ))
438 .child(control_row(
439 tr("settings.help.signed_in"),
440 if info.signed_in {
441 tr("settings.help.yes")
442 } else {
443 tr("settings.help.no")
444 },
445 div(),
446 ))
447 .child({
448 let debug_on = self.app.read(cx).diagnostics_enabled();
449 let toggle_app = self.app.clone();
450 toggle_row(
451 "settings-help-debug-log",
452 tr("settings.help.debug_logging"),
453 if debug_on {
454 tr("settings.help.debug_logging_on_detail")
455 } else {
456 tr("settings.help.debug_logging_off_detail")
457 },
458 theme::text_muted(),
459 debug_on,
460 )
461 .on_click(cx.listener(move |_, _, _, cx| {
462 toggle_app.update(cx, |state, cx| {
463 state.set_diagnostics_enabled(!debug_on, cx);
464 });
465 cx.notify();
466 }))
467 })
468 .child({
469 let clear_app = self.app.clone();
470 control_row(
471 tr("settings.help.clear_logs"),
472 tr("settings.help.clear_logs_detail"),
473 text_button("settings-help-clear-logs", tr("settings.help.clear_logs_button"))
474 .on_click(cx.listener(move |_, _, _, cx| {
475 clear_app.update(cx, |state, cx| state.clear_diagnostic_logs(cx));
476 cx.notify();
477 })),
478 )
479 })
480 .child(caption(tr("settings.help.caption_paths")))
481 .child(self.path_row(
482 tr("settings.help.logs_path"),
483 logs_path,
484 "settings-help-copy-logs",
485 "settings-help-open-logs-root",
486 cx,
487 ))
488 .child(self.path_row(
489 tr("settings.help.bundles_path"),
490 bundles_path,
491 "settings-help-copy-bundles",
492 "settings-help-open-bundles-root",
493 cx,
494 ))
495 .child(self.packages_section(cx))
496 .child(caption(tr("settings.help.caption_actions")))
497 .child(
498 div()
499 .text_size(px(13.))
500 .text_color(theme::text_muted())
501 .pb(px(8.))
502 .px(px(ROW_INSET))
503 .child(tr("settings.help.detail")),
504 )
505 .child(control_row(
506 tr("settings.help.create_bundle"),
507 tr("settings.help.create_bundle_detail"),
508 text_button("settings-help-bundle", tr("settings.help.create_bundle_button"))
509 .on_click(cx.listener(move |this, _, _, cx| {
510 create_app.update(cx, |state, _| {
511 match state.create_support_bundle() {
512 Ok(bundle) => AppState::reveal_support_bundle(&bundle),
513 Err(error) => app_base::diagnostics::record(format!(
514 "support bundle: {error}"
515 )),
516 }
517 });
518 this.reload_bundles();
519 cx.notify();
520 })),
521 ))
522 .child(control_row(
523 tr("settings.help.open_issue"),
524 tr("settings.help.open_issue_detail"),
525 text_button("settings-help-issue", tr("settings.help.open_issue_button")).on_click(
526 cx.listener(move |this, _, _, cx| {
527 issue_app.update(cx, |state, cx| {
528 if let Err(error) = state.open_github_issue_with_bundle(cx) {
529 app_base::diagnostics::record(format!("support issue: {error}"));
530 }
531 });
532 this.reload_bundles();
533 cx.notify();
534 }),
535 ),
536 ))
537 .child(control_row(
538 tr("settings.help.copy_summary"),
539 tr("settings.help.copy_summary_detail"),
540 text_button("settings-help-copy", tr("settings.help.copy_button")).on_click(
541 move |_, _, cx| {
542 cx.write_to_clipboard(ClipboardItem::new_string(copy_summary.clone()));
543 },
544 ),
545 ))
546 .child(control_row(
547 tr("settings.help.open_logs"),
548 tr("settings.help.open_logs_detail"),
549 text_button("settings-help-logs", tr("common.open")).on_click(move |_, _, _| {
550 AppState::reveal_logs_folder();
551 }),
552 ))
553 }
554}
555
556struct ReadPreview {
557 text: String,
558 truncated: bool,
559 binary: bool,
560}
561
562fn read_preview_text(path: &Path) -> std::io::Result<ReadPreview> {
563 let bytes = std::fs::read(path)?;
564 let truncated = bytes.len() > PREVIEW_LIMIT;
565 let slice = &bytes[..bytes.len().min(PREVIEW_LIMIT)];
566 match std::str::from_utf8(slice) {
567 Ok(text) => Ok(ReadPreview {
568 text: text.to_owned(),
569 truncated,
570 binary: false,
571 }),
572 Err(_) => Ok(ReadPreview {
573 text: String::new(),
574 truncated: false,
575 binary: true,
576 }),
577 }
578}
579
580impl Render for HelpView {
581 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
582 let previewing = self.preview.is_some();
583 v_flex()
584 .w_full()
585 .when(previewing, |root| root.h_full().min_h_0())
586 .debug_selector(|| "settings/help".into())
587 .child(if previewing {
588 self.preview_panel(cx)
589 } else {
590 self.help_home(cx)
591 })
592 }
593}
crates/app/src/settings/mod.rs +1 −0
@@ -7,6 +7,7 @@ mod chats;
7 7 mod devices;
8 8 mod dialog;
9 9 mod general;
10 mod help;
10 11 mod mcp;
11 12 mod nav;
12 13 mod notifications;
@@ -7,6 +7,7 @@ mod chats;
7mod devices;
7mod devices;
8mod dialog;
8mod dialog;
9mod general;
9mod general;
10mod help;
10mod mcp;
11mod mcp;
11mod nav;
12mod nav;
12mod notifications;
13mod notifications;
crates/app/src/settings/nav.rs +28 −7
@@ -91,6 +91,13 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
91 91 "Model Context Protocol".to_owned(),
92 92 "Conversation access".to_owned(),
93 93 ],
94 SettingsSection::Help => vec![
95 tr("settings.help.create_bundle"),
96 tr("settings.help.open_issue"),
97 "GitHub".to_owned(),
98 "diagnostics".to_owned(),
99 "support".to_owned(),
100 ],
94 101 SettingsSection::About => vec!["Version".to_owned(), "Build".to_owned()],
95 102 }
96 103 }
@@ -107,7 +114,7 @@ pub fn first_match(query: &str, agents_available: bool) -> Option<SettingsSectio
107 114 TEAMS_GROUP
108 115 .into_iter()
109 116 .chain(RUSTY_GROUP)
110 .chain([SettingsSection::About])
117 .chain([SettingsSection::Help, SettingsSection::About])
111 118 .filter(|section| agents_available || *section != SettingsSection::Agents)
112 119 .find(|section| matches(*section, query))
113 120 }
@@ -123,6 +130,7 @@ pub fn label(section: SettingsSection) -> String {
123 130 SettingsSection::Devices => tr("settings.nav.devices"),
124 131 SettingsSection::Agents => tr("settings.nav.agents"),
125 132 SettingsSection::Mcp => tr("settings.nav.mcp"),
133 SettingsSection::Help => tr("settings.nav.help"),
126 134 SettingsSection::About => tr("settings.nav.about"),
127 135 }
128 136 }
@@ -138,6 +146,7 @@ fn icon_name(section: SettingsSection) -> IconName {
138 146 SettingsSection::Devices => IconName::Headphones,
139 147 SettingsSection::Agents => IconName::Bot,
140 148 SettingsSection::Mcp => IconName::Plug,
149 SettingsSection::Help => IconName::BookOpen,
141 150 SettingsSection::About => IconName::Info,
142 151 }
143 152 }
@@ -161,6 +170,7 @@ fn element_id(section: SettingsSection) -> &'static str {
161 170 SettingsSection::Devices => "settings-nav-devices",
162 171 SettingsSection::Agents => "settings-nav-agents",
163 172 SettingsSection::Mcp => "settings-nav-mcp",
173 SettingsSection::Help => "settings-nav-help",
164 174 SettingsSection::About => "settings-nav-about",
165 175 }
166 176 }
@@ -195,8 +205,9 @@ pub fn render_nav(
195 205 .filter(|section| matches(*section, query))
196 206 .map(item)
197 207 .collect();
208 let help_shown = matches(SettingsSection::Help, query);
198 209 let about_shown = matches(SettingsSection::About, query);
199 let nothing_found = teams.is_empty() && rusty.is_empty() && !about_shown;
210 let nothing_found = teams.is_empty() && rusty.is_empty() && !help_shown && !about_shown;
200 211 let group = |items: Vec<Stateful<Div>>| {
201 212 v_flex()
202 213 .w_full()
@@ -276,16 +287,26 @@ pub fn render_nav(
276 287 .child(group(rusty))
277 288 }),
278 289 )
279 .when(about_shown, |nav| {
290 .when(help_shown || about_shown, |nav| {
280 291 nav.child(
281 div()
292 v_flex()
282 293 .w_full()
283 294 .flex_none()
284 295 .px(px(NAV_PADDING_X))
285 296 .pt(px(6.))
286 .child(
287 item(SettingsSection::About).debug_selector(|| "settings/nav/about".into()),
288 ),
297 .gap(px(ITEM_GAP))
298 .when(help_shown, |footer| {
299 footer.child(
300 item(SettingsSection::Help)
301 .debug_selector(|| "settings/nav/help".into()),
302 )
303 })
304 .when(about_shown, |footer| {
305 footer.child(
306 item(SettingsSection::About)
307 .debug_selector(|| "settings/nav/about".into()),
308 )
309 }),
289 310 )
290 311 })
291 312 }
@@ -91,6 +91,13 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
91 "Model Context Protocol".to_owned(),
91 "Model Context Protocol".to_owned(),
92 "Conversation access".to_owned(),
92 "Conversation access".to_owned(),
93 ],
93 ],
94 SettingsSection::Help => vec![
95 tr("settings.help.create_bundle"),
96 tr("settings.help.open_issue"),
97 "GitHub".to_owned(),
98 "diagnostics".to_owned(),
99 "support".to_owned(),
100 ],
94 SettingsSection::About => vec!["Version".to_owned(), "Build".to_owned()],
101 SettingsSection::About => vec!["Version".to_owned(), "Build".to_owned()],
95 }
102 }
96}
103}
@@ -107,7 +114,7 @@ pub fn first_match(query: &str, agents_available: bool) -> Option<SettingsSectio
107 TEAMS_GROUP
114 TEAMS_GROUP
108 .into_iter()
115 .into_iter()
109 .chain(RUSTY_GROUP)
116 .chain(RUSTY_GROUP)
110 .chain([SettingsSection::About])
117 .chain([SettingsSection::Help, SettingsSection::About])
111 .filter(|section| agents_available || *section != SettingsSection::Agents)
118 .filter(|section| agents_available || *section != SettingsSection::Agents)
112 .find(|section| matches(*section, query))
119 .find(|section| matches(*section, query))
113}
120}
@@ -123,6 +130,7 @@ pub fn label(section: SettingsSection) -> String {
123 SettingsSection::Devices => tr("settings.nav.devices"),
130 SettingsSection::Devices => tr("settings.nav.devices"),
124 SettingsSection::Agents => tr("settings.nav.agents"),
131 SettingsSection::Agents => tr("settings.nav.agents"),
125 SettingsSection::Mcp => tr("settings.nav.mcp"),
132 SettingsSection::Mcp => tr("settings.nav.mcp"),
133 SettingsSection::Help => tr("settings.nav.help"),
126 SettingsSection::About => tr("settings.nav.about"),
134 SettingsSection::About => tr("settings.nav.about"),
127 }
135 }
128}
136}
@@ -138,6 +146,7 @@ fn icon_name(section: SettingsSection) -> IconName {
138 SettingsSection::Devices => IconName::Headphones,
146 SettingsSection::Devices => IconName::Headphones,
139 SettingsSection::Agents => IconName::Bot,
147 SettingsSection::Agents => IconName::Bot,
140 SettingsSection::Mcp => IconName::Plug,
148 SettingsSection::Mcp => IconName::Plug,
149 SettingsSection::Help => IconName::BookOpen,
141 SettingsSection::About => IconName::Info,
150 SettingsSection::About => IconName::Info,
142 }
151 }
143}
152}
@@ -161,6 +170,7 @@ fn element_id(section: SettingsSection) -> &'static str {
161 SettingsSection::Devices => "settings-nav-devices",
170 SettingsSection::Devices => "settings-nav-devices",
162 SettingsSection::Agents => "settings-nav-agents",
171 SettingsSection::Agents => "settings-nav-agents",
163 SettingsSection::Mcp => "settings-nav-mcp",
172 SettingsSection::Mcp => "settings-nav-mcp",
173 SettingsSection::Help => "settings-nav-help",
164 SettingsSection::About => "settings-nav-about",
174 SettingsSection::About => "settings-nav-about",
165 }
175 }
166}
176}
@@ -195,8 +205,9 @@ pub fn render_nav(
195 .filter(|section| matches(*section, query))
205 .filter(|section| matches(*section, query))
196 .map(item)
206 .map(item)
197 .collect();
207 .collect();
208 let help_shown = matches(SettingsSection::Help, query);
198 let about_shown = matches(SettingsSection::About, query);
209 let about_shown = matches(SettingsSection::About, query);
199 let nothing_found = teams.is_empty() && rusty.is_empty() && !about_shown;
210 let nothing_found = teams.is_empty() && rusty.is_empty() && !help_shown && !about_shown;
200 let group = |items: Vec<Stateful<Div>>| {
211 let group = |items: Vec<Stateful<Div>>| {
201 v_flex()
212 v_flex()
202 .w_full()
213 .w_full()
@@ -276,16 +287,26 @@ pub fn render_nav(
276 .child(group(rusty))
287 .child(group(rusty))
277 }),
288 }),
278 )
289 )
279 .when(about_shown, |nav| {
290 .when(help_shown || about_shown, |nav| {
280 nav.child(
291 nav.child(
281 div()
292 v_flex()
282 .w_full()
293 .w_full()
283 .flex_none()
294 .flex_none()
284 .px(px(NAV_PADDING_X))
295 .px(px(NAV_PADDING_X))
285 .pt(px(6.))
296 .pt(px(6.))
286 .child(
297 .gap(px(ITEM_GAP))
287 item(SettingsSection::About).debug_selector(|| "settings/nav/about".into()),
298 .when(help_shown, |footer| {
288 ),
299 footer.child(
300 item(SettingsSection::Help)
301 .debug_selector(|| "settings/nav/help".into()),
302 )
303 })
304 .when(about_shown, |footer| {
305 footer.child(
306 item(SettingsSection::About)
307 .debug_selector(|| "settings/nav/about".into()),
308 )
309 }),
289 )
310 )
290 })
311 })
291}
312}
docs/decisions/0012-local-diagnostic-data-and-upstream-issues.md added +24 −0
@@ -0,0 +1,24 @@
1 ---
2 status: proposed
3 date: 2026-11-14
4 ---
5
6 # ADR 0012: Local diagnostic data layout and upstream issues
7
8 ## Context
9
10 Users need a place for logs and support packages that works the same way on Linux, macOS, and Windows. Paths were split across call sites with no OS table in the product specs. User-facing bug reports must point at the public upstream tracker, not at a private or Issues-disabled mirror. Opening a bug report also used to pop the file manager beside the browser, which was noisy.
11
12 Options on the table: rename the data directory away from `ms-teams-linux`, put diagnostics under roaming `data_dir` on Windows, or keep the local root name and send issues to upstream `danieldaeschle/rusty-teams`.
13
14 ## Decision
15
16 Diagnostic and support artifacts live under `ProjectDirs` **local** data for the product directory name `ms-teams-linux` (legacy name kept on every OS). Layout under that root: `diagnostics.log` (+ `.1` / `.2` ring), `crash.log` (+ `.1`), `call-dumps/`, `call-reports/`, `support-bundles/support-<UTC>/`. **Debug file logging is off by default** and is toggled from Help (store key `diagnostics_enabled`) or forced with `--debug-log` / `RUSTY_TEAMS_DEBUG_LOG=1`; `crash.log` still records panics when they happen. Help shows those absolute paths. Bug reports and support README text open or name only upstream `danieldaeschle/rusty-teams`; the app does not upload and does not open the file manager by itself when filing (a notice may offer Open folder). Store/Roaming migration is not part of this decision.
17
18 ## Consequences
19
20 - Developers and users can find logs and bundles from Help without guessing OS conventions.
21 - Everyday installs do not grow `diagnostics.log` until the user opts in.
22 - Existing installs keep working; no rename of `ms-teams-linux`.
23 - End-user copy never points at a fork or mirror for issues — only upstream.
24 - The SQLite store may still use a different root on Windows until a later change.
@@ -0,0 +1,24 @@
1---
2status: proposed
3date: 2026-11-14
4---
5
6# ADR 0012: Local diagnostic data layout and upstream issues
7
8## Context
9
10Users need a place for logs and support packages that works the same way on Linux, macOS, and Windows. Paths were split across call sites with no OS table in the product specs. User-facing bug reports must point at the public upstream tracker, not at a private or Issues-disabled mirror. Opening a bug report also used to pop the file manager beside the browser, which was noisy.
11
12Options on the table: rename the data directory away from `ms-teams-linux`, put diagnostics under roaming `data_dir` on Windows, or keep the local root name and send issues to upstream `danieldaeschle/rusty-teams`.
13
14## Decision
15
16Diagnostic and support artifacts live under `ProjectDirs` **local** data for the product directory name `ms-teams-linux` (legacy name kept on every OS). Layout under that root: `diagnostics.log` (+ `.1` / `.2` ring), `crash.log` (+ `.1`), `call-dumps/`, `call-reports/`, `support-bundles/support-<UTC>/`. **Debug file logging is off by default** and is toggled from Help (store key `diagnostics_enabled`) or forced with `--debug-log` / `RUSTY_TEAMS_DEBUG_LOG=1`; `crash.log` still records panics when they happen. Help shows those absolute paths. Bug reports and support README text open or name only upstream `danieldaeschle/rusty-teams`; the app does not upload and does not open the file manager by itself when filing (a notice may offer Open folder). Store/Roaming migration is not part of this decision.
17
18## Consequences
19
20- Developers and users can find logs and bundles from Help without guessing OS conventions.
21- Everyday installs do not grow `diagnostics.log` until the user opts in.
22- Existing installs keep working; no rename of `ms-teams-linux`.
23- End-user copy never points at a fork or mirror for issues — only upstream.
24- The SQLite store may still use a different root on Windows until a later change.
docs/decisions/README.md +2 −1
@@ -27,5 +27,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
27 27 | [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
28 28 | [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
29 29 | [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
30 | [0012](0012-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
30 31
31 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
32 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges. `0012` stays `proposed` until the support-bundle path change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -27,5 +27,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
27| [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
27| [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
28| [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
28| [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
29| [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
29| [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
30| [0012](0012-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
30
31
31Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
32Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges. `0012` stays `proposed` until the support-bundle path change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.