1#[cfg(feature = "copilot")]
6use super::{
7 Client, EventLogReadRequest, EventsReadDirection, Session, SessionEvent, SessionId,
8 SessionsReadPersistedEventsRequest, history_entries,
9};
10use super::{Entry, Path, ToolStatus, TranscriptEntry, state};
11use crate::{ATTACHMENT_MARKER, ToolCall};
12
13#[cfg(feature = "copilot")]
16const PAGE: i64 = 200;
17#[cfg(feature = "copilot")]
18const MAX_PAGES: usize = 50;
19
20#[cfg(feature = "copilot")]
22pub(super) async fn session_history(
23 client: &Client,
24 session: SessionId,
25) -> Result<Vec<TranscriptEntry>, String> {
26 let mut events = Vec::new();
27 let mut cursor = None;
28 for _ in 0..MAX_PAGES {
29 let page = client
30 .rpc()
31 .sessions()
32 .read_persisted_events(SessionsReadPersistedEventsRequest {
33 cursor: cursor.take(),
34 direction: Some(EventsReadDirection::Forward),
35 max: Some(PAGE),
36 session_id: session.clone(),
37 })
38 .await
39 .map_err(|_| "Cannot read that chat's saved transcript.".to_string())?;
40 events.extend(page.events);
41 if !page.has_more {
42 break;
43 }
44 cursor = Some(page.cursor);
45 }
46 Ok(history_entries(&events))
47}
48
49#[cfg(feature = "copilot")]
53pub(super) async fn open_session_events(session: &Session) -> Result<Vec<SessionEvent>, String> {
54 let mut events = Vec::new();
55 let mut cursor = None;
56 for _ in 0..MAX_PAGES {
57 let page = session
58 .rpc()
59 .event_log()
60 .read(EventLogReadRequest {
61 cursor: cursor.take(),
62 direction: Some(EventsReadDirection::Forward),
63 include_ephemeral: Some(false),
66 max: Some(PAGE),
67 ..Default::default()
68 })
69 .await
70 .map_err(|_| "Cannot read this chat's transcript.".to_string())?;
71 events.extend(page.events);
72 if !page.has_more {
73 break;
74 }
75 cursor = Some(page.cursor);
76 }
77 Ok(events)
78}
79
80#[cfg(feature = "copilot")]
82pub(super) fn markdown(title: &str, entries: &[TranscriptEntry]) -> String {
83 markdown_with_agent(title, entries, "Copilot")
84}
85
86pub(super) fn markdown_with_agent(
87 title: &str,
88 entries: &[TranscriptEntry],
89 assistant: &str,
90) -> String {
91 let mut text = format!("# {}\n", title.trim());
92 for entry in entries {
93 text.push('\n');
94 text.push_str(&block(&entry.entry, assistant));
95 text.push('\n');
96 }
97 text
98}
99
100fn block(entry: &Entry, assistant: &str) -> String {
101 match entry {
102 Entry::User { text, .. } => format!("## You\n\n{}\n", folded(text)),
103 Entry::Assistant(text) => format!("## {assistant}\n\n{}\n", text.trim_end()),
104 Entry::Info(text) => format!("> {}\n", text.trim_end()),
105 Entry::Thinking { seconds, .. } => match seconds {
106 Some(seconds) => format!("_Thought for {seconds}s_\n"),
107 None => "_Thought_\n".to_owned(),
108 },
109 Entry::Tool(call) => format!("- {}\n", tool_line(call)),
110 }
111}
112
113pub(super) fn tool_line(call: &ToolCall) -> String {
116 let mut line = format!("`{}`", call.title.trim());
117 let detail = call.shown_detail();
118 if !detail.is_empty() {
119 line.push(' ');
120 line.push_str(detail);
121 }
122 if call.status == ToolStatus::Aborted {
123 line.push_str(" (did not finish)");
124 }
125 line
126}
127
128fn folded(text: &str) -> String {
131 let mut blocks = text.split(ATTACHMENT_MARKER);
132 let mut folded = blocks.next().unwrap_or_default().trim_end().to_owned();
133 for attachment in blocks {
134 let label = attachment.lines().next().unwrap_or_default().trim();
135 folded.push_str(&format!("\n\n_Attached: {label}_"));
136 }
137 folded
138}
139
140pub fn export_file_name(title: &str) -> String {
143 let safe: String = title
144 .trim_end()
145 .trim_end_matches('…')
146 .trim_end()
147 .chars()
148 .map(|character| match character {
149 '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
150 character if character.is_control() => ' ',
151 character => character,
152 })
153 .collect();
154 let safe = safe.trim().trim_matches('.').trim();
155 if safe.is_empty() {
156 return "chat.md".to_owned();
157 }
158 format!("{safe}.md")
159}
160
161pub(super) fn write_export(path: &Path, text: &str) -> Result<(), String> {
162 state::write_atomic(path, text).map_err(|_| "Cannot write the export file.".into())
163}
164
165#[cfg(test)]
166mod tests {
167 use super::{export_file_name, markdown_with_agent, tool_line};
168 use crate::{ATTACHMENT_MARKER, Entry, ToolCall, ToolStatus, TranscriptEntry};
169
170 fn markdown(title: &str, entries: &[TranscriptEntry]) -> String {
171 markdown_with_agent(title, entries, "Copilot")
172 }
173
174 fn entry(id: &str, entry: Entry) -> TranscriptEntry {
175 TranscriptEntry {
176 id: id.into(),
177 entry,
178 }
179 }
180
181 #[test]
182 fn an_export_reads_as_the_conversation_did() {
183 let entries = vec![
184 entry(
185 "1",
186 Entry::User {
187 text: "Check the risks".into(),
188 steering: false,
189 },
190 ),
191 entry(
192 "2",
193 Entry::Thinking {
194 text: "reasoning".into(),
195 seconds: Some(4),
196 },
197 ),
198 entry(
199 "3",
200 Entry::Tool(ToolCall {
201 call_id: "c1".into(),
202 title: "Read services".into(),
203 detail: "github_search query=is:open".into(),
204 status: ToolStatus::Done,
205 result: "3 risks".into(),
206 }),
207 ),
208 entry("4", Entry::Assistant("Three risks need attention.".into())),
209 entry("5", Entry::Info("The skill command finished.".into())),
210 ];
211 let text = markdown("Release risks", &entries);
212 assert!(text.starts_with("# Release risks\n"));
213 assert!(text.contains("## You\n\nCheck the risks\n"));
214 assert!(text.contains("## Copilot\n\nThree risks need attention.\n"));
215 assert!(text.contains("_Thought for 4s_"));
216 assert!(text.contains("- `Read services` github_search query=is:open"));
217 assert!(text.contains("> The skill command finished."));
218 assert!(
219 !text.contains("3 risks"),
220 "a tool result is not replayed into the export"
221 );
222 }
223
224 #[test]
225 fn attached_references_are_folded_to_their_labels() {
226 let message = format!("Review this{ATTACHMENT_MARKER}GH: octo/app#12\nState: Open");
227 let text = markdown(
228 "Review",
229 &[entry(
230 "1",
231 Entry::User {
232 text: message,
233 steering: false,
234 },
235 )],
236 );
237 assert!(text.contains("Review this"));
238 assert!(text.contains("_Attached: GH: octo/app#12_"));
239 assert!(
240 !text.contains("State: Open"),
241 "the attached content stays out of the export"
242 );
243 }
244
245 #[test]
246 fn an_export_file_name_is_safe_on_every_platform() {
247 assert_eq!(export_file_name("Release risks"), "Release risks.md");
248 assert_eq!(export_file_name("a/b:c*d?"), "a-b-c-d-.md");
249 assert_eq!(export_file_name(" "), "chat.md");
250 assert_eq!(export_file_name(".."), "chat.md");
251 }
252
253 #[test]
256 fn an_export_file_name_drops_the_display_ellipsis() {
257 assert_eq!(
258 export_file_name("give me a change log style list of the…"),
259 "give me a change log style list of the.md"
260 );
261 assert_eq!(export_file_name("…"), "chat.md");
262 }
263
264 #[test]
265 fn a_tool_line_says_each_thing_once() {
266 let call = |title: &str, detail: &str, status| ToolCall {
267 call_id: "c1".into(),
268 title: title.into(),
269 detail: detail.into(),
270 status,
271 result: String::new(),
272 };
273 assert_eq!(
274 tool_line(&call("Read services", "github_search", ToolStatus::Done)),
275 "`Read services` github_search"
276 );
277 assert_eq!(
278 tool_line(&call("SELECT 1", "query=SELECT 1", ToolStatus::Done)),
279 "`SELECT 1`",
280 "the arguments are not repeated after the title"
281 );
282 assert_eq!(
283 tool_line(&call("Read services", "", ToolStatus::Aborted)),
284 "`Read services` (did not finish)"
285 );
286 }
287
288 #[test]
289 fn an_empty_chat_still_exports_its_name() {
290 assert_eq!(markdown("New chat", &[]), "# New chat\n");
291 }
292}