chatgpt_panic_hook/
lib.rs1use std::{
19 any::Any,
20 borrow::Cow,
21 io::{self, Write},
22 panic::{self, PanicHookInfo},
23 sync::{
24 Once,
25 atomic::{AtomicBool, Ordering},
26 },
27};
28
29use url::Url;
30
31const CHATGPT_URL: &str = "https://chatgpt.com/";
32const MAX_PANIC_MESSAGE_BYTES: usize = 2_000;
33const TRUNCATION_MARKER: &str = "\n⦠[panic message truncated]";
34static INSTALL: Once = Once::new();
35static BROWSER_OPENING: AtomicBool = AtomicBool::new(false);
36
37pub fn install() {
57 INSTALL.call_once(|| {
58 let previous_hook = panic::take_hook();
59
60 panic::set_hook(Box::new(move |info| {
61 previous_hook(info);
62
63 let Some(_launch) = BrowserLaunch::acquire() else {
64 return;
65 };
66 let prompt = panic_prompt(info);
67 let url = chatgpt_url(&prompt);
68 if let Err(error) = webbrowser::open(url.as_str()) {
69 report_browser_error(&error);
70 }
71 }));
72 });
73}
74
75fn panic_prompt(info: &PanicHookInfo<'_>) -> String {
76 let message = bounded_panic_message(panic_message(info.payload()));
77 let location = info
78 .location()
79 .map(|location| {
80 format!(
81 "{}:{}:{}",
82 location.file(),
83 location.line(),
84 location.column()
85 )
86 })
87 .unwrap_or_else(|| "unknown".to_owned());
88 let thread = std::thread::current();
89 let thread_name = thread.name().unwrap_or("<unnamed>");
90
91 format!(
92 "A Rust thread named `{thread_name}` panicked.\n\n\
93 Panic message: {message}\n\
94 Source location: {location}\n\n\
95 Explain the likely cause and suggest a fix."
96 )
97}
98
99fn bounded_panic_message(message: &str) -> Cow<'_, str> {
100 if message.len() <= MAX_PANIC_MESSAGE_BYTES {
101 return Cow::Borrowed(message);
102 }
103
104 let mut end = MAX_PANIC_MESSAGE_BYTES;
105 while !message.is_char_boundary(end) {
106 end -= 1;
107 }
108
109 let mut truncated = String::with_capacity(end + TRUNCATION_MARKER.len());
110 truncated.push_str(&message[..end]);
111 truncated.push_str(TRUNCATION_MARKER);
112 Cow::Owned(truncated)
113}
114
115fn panic_message(payload: &(dyn Any + Send)) -> &str {
116 payload
117 .downcast_ref::<&str>()
118 .copied()
119 .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
120 .unwrap_or("<non-string panic payload>")
121}
122
123fn chatgpt_url(prompt: &str) -> Url {
124 let mut url = Url::parse(CHATGPT_URL).expect("CHATGPT_URL must be a valid URL");
125 url.query_pairs_mut().append_pair("q", prompt);
126 url
127}
128
129fn report_browser_error(error: &io::Error) {
130 let mut stderr = io::stderr().lock();
131 let _ = writeln!(
132 stderr,
133 "chatgpt-panic-hook: could not open ChatGPT: {error}"
134 );
135}
136
137struct BrowserLaunch;
138
139impl BrowserLaunch {
140 fn acquire() -> Option<Self> {
141 BROWSER_OPENING
142 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
143 .is_ok()
144 .then_some(Self)
145 }
146}
147
148impl Drop for BrowserLaunch {
149 fn drop(&mut self) {
150 BROWSER_OPENING.store(false, Ordering::Release);
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn query_round_trips_punctuation_and_newlines() {
160 let prompt = "panic: expected `&str`?\nTry again.";
161 let url = chatgpt_url(prompt);
162
163 assert_eq!(url.scheme(), "https");
164 assert_eq!(url.host_str(), Some("chatgpt.com"));
165 assert_eq!(
166 url.query_pairs().find(|(key, _)| key == "q").unwrap().1,
167 prompt
168 );
169 }
170
171 #[test]
172 fn string_panic_payload_is_preserved() {
173 let payload = String::from("the crab escaped");
174
175 assert_eq!(panic_message(&payload), "the crab escaped");
176 }
177
178 #[test]
179 fn borrowed_string_panic_payload_is_preserved() {
180 let payload = "the crab escaped";
181
182 assert_eq!(panic_message(&payload), "the crab escaped");
183 }
184
185 #[test]
186 fn non_string_panic_payload_has_a_safe_fallback() {
187 let payload = 42_u32;
188
189 assert_eq!(panic_message(&payload), "<non-string panic payload>");
190 }
191
192 #[test]
193 fn oversized_panic_message_is_truncated_at_a_utf8_boundary() {
194 let message = format!("{}š¦", "a".repeat(MAX_PANIC_MESSAGE_BYTES - 1));
195
196 let bounded = bounded_panic_message(&message);
197
198 assert!(bounded.ends_with(TRUNCATION_MARKER));
199 assert!(!bounded.contains('š¦'));
200 }
201
202 #[test]
203 fn overlapping_browser_launch_is_suppressed() {
204 let first = BrowserLaunch::acquire().unwrap();
205
206 assert!(BrowserLaunch::acquire().is_none());
207
208 drop(first);
209 assert!(BrowserLaunch::acquire().is_some());
210 }
211}