返回 CodeWhale
share.rs
根目录 / crates / tui / src / commands / groups / project / share.rs
1 //! /share command — publish a redacted copy of the session as a secret gist.
2 //!
3 //! The page is the HTML rendering of the same projection `/export` uses, so
4 //! hidden instructions, internal reasoning, and reasoning signatures are
5 //! dropped and secret-like values are redacted before anything leaves the
6 //! machine. The raw `api_messages` JSON never reaches the page.
7 //!
8 //! # Usage
9 //!
10 //! - `/share` — preview only: what would be uploaded; no network call
11 //! - `/share confirm` — upload as a secret gist (unlisted, not private)
12 //! - `/share help` — show usage
13
14 use std::io::Write;
15 use std::path::Path;
16
17 use codewhale_command_contract::facets::{
18 CommandSessionExportContext, ConversationExportProjection, ExportBlock, RestorePointProjection,
19 TranscriptProjection,
20 };
21 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
22 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
23
24 use crate::commands::CommandResult;
25 use crate::commands::groups::session::export::count_redactions;
26 use crate::commands::groups::session::export_html;
27 use crate::tui::app::AppAction;
28 use codewhale_dependencies::ExternalTool;
29
30 const VISIBILITY_NOTE: &str =
31 "a secret GitHub gist (unlisted, not private: anyone with the link can read it)";
32
33 /// Preview or share the current session.
34 fn share(export: &dyn CommandSessionExportContext, arg: Option<&str>) -> CommandResult {
35 let raw = arg.map(str::trim).unwrap_or("");
36
37 match raw {
38 "" => preview(export),
39 "confirm" => confirm(export),
40 "help" | "--help" | "-h" => CommandResult::message(format!(
41 "/share — Share a redacted copy of this session.\n\
42 \n\
43 Usage:\n\
44 /share Preview what would be uploaded (nothing leaves the machine)\n\
45 /share confirm Upload it as {VISIBILITY_NOTE}\n\
46 \n\
47 The page is the same redacted HTML that `/export file <name>.html`\n\
48 writes: hidden instructions and reasoning are omitted and\n\
49 secret-like values are masked. Uploading needs the `gh` CLI,\n\
50 installed and signed in."
51 )),
52 _ => CommandResult::error(format!(
53 "Unknown /share argument `{raw}`. Use `/share`, `/share confirm`, or `/share help`."
54 )),
55 }
56 }
57
58 /// What `/share` would publish, measured on the exact page it would upload.
59 #[derive(Debug, Clone, PartialEq, Eq)]
60 struct SharePlan {
61 html: String,
62 message_count: usize,
63 /// `None` when the page is the visible-history fallback, which may carry
64 /// tool output it cannot count.
65 tool_results: Option<usize>,
66 redactions: usize,
67 }
68
69 /// Project the conversation the way `/export` does, minus the local
70 /// restore-point table (snapshot ids mean nothing to a reader of the link).
71 fn plan(export: &dyn CommandSessionExportContext) -> Option<SharePlan> {
72 let mut projection: ConversationExportProjection = export.conversation_projection();
73 if projection.metadata.message_count == 0 {
74 return None;
75 }
76 projection.restore_points = RestorePointProjection::None;
77 // The visible-history fallback cannot tell tool output apart from the
78 // rest, so it is not counted as "none".
79 let tool_results = match &projection.transcript {
80 TranscriptProjection::Authoritative(messages) => Some(
81 messages
82 .iter()
83 .flat_map(|message| &message.blocks)
84 .filter(|block| matches!(block, ExportBlock::ToolResult { .. }))
85 .count(),
86 ),
87 TranscriptProjection::HistoryFallback(_) => None,
88 };
89 let message_count = projection.metadata.message_count;
90 let html = export_html::render(projection);
91 let redactions = count_redactions(&html);
92 Some(SharePlan {
93 html,
94 message_count,
95 tool_results,
96 redactions,
97 })
98 }
99
100 const NOTHING_TO_SHARE: &str = "Nothing to share. The current session is empty.";
101
102 /// The counts both steps print, measured on the page itself. `confirm`
103 /// re-renders, so it states what it actually uploads rather than repeating
104 /// the preview's numbers (messages that arrived in between are included).
105 fn plan_summary(plan: &SharePlan) -> String {
106 let tool_output = match plan.tool_results {
107 Some(0) => "none".to_string(),
108 Some(count) => format!("included ({count} tool result(s), redacted)"),
109 None => "may be included (visible history, redacted)".to_string(),
110 };
111 format!(
112 "Messages: {}\n\
113 Tool output: {tool_output}\n\
114 Redacted: {} item(s)\n\
115 Omitted: hidden instructions, internal reasoning, reasoning signatures",
116 plan.message_count, plan.redactions
117 )
118 }
119
120 /// Plain `/share`: describe the page, upload nothing.
121 fn preview(export: &dyn CommandSessionExportContext) -> CommandResult {
122 let Some(plan) = plan(export) else {
123 return CommandResult::error(NOTHING_TO_SHARE);
124 };
125 CommandResult::message(format!(
126 "Share preview — nothing has been uploaded.\n\
127 \n\
128 {}\n\
129 \n\
130 Run `/share confirm` to upload this page as {VISIBILITY_NOTE}.\n\
131 Use `/export file <name>.html` to read the exact page first.",
132 plan_summary(&plan)
133 ))
134 }
135
136 /// `/share confirm`: hand the rendered, redacted page to the host to upload.
137 fn confirm(export: &dyn CommandSessionExportContext) -> CommandResult {
138 let Some(plan) = plan(export) else {
139 return CommandResult::error(NOTHING_TO_SHARE);
140 };
141 CommandResult::with_message_and_action(
142 format!(
143 "Uploading this page as {VISIBILITY_NOTE}...\n\
144 \n\
145 {}",
146 plan_summary(&plan)
147 ),
148 AppAction::ShareSession { html: plan.html },
149 )
150 }
151
152 /// Upload a rendered page, then delete the local temp copy.
153 ///
154 /// Called from the UI loop for `AppAction::ShareSession`. The upload runs on a
155 /// blocking thread because it shells out to `gh`.
156 pub async fn perform_share(html: String) -> Result<String, String> {
157 tokio::task::spawn_blocking(move || upload_via_temp_file(&html, upload_gist))
158 .await
159 .map_err(|join_err| format!("share upload panicked: {join_err}"))?
160 }
161
162 /// Write `html` to a private temp file, run `upload` on its path, and remove
163 /// the file whatever the upload returned.
164 fn upload_via_temp_file(
165 html: &str,
166 upload: impl FnOnce(&Path) -> Result<String, String>,
167 ) -> Result<String, String> {
168 let tmp = write_temp_html(html).map_err(|e| format!("Failed to write temp file: {e}"))?;
169 let result = upload(tmp.path());
170 let removed = tmp.close();
171 let url = result?;
172 removed
173 .map_err(|e| format!("Shared at {url}, but the local temp copy was not removed: {e}"))?;
174 Ok(url)
175 }
176
177 /// Write HTML to a secure temp file and keep it alive for upload.
178 fn write_temp_html(html: &str) -> Result<tempfile::NamedTempFile, String> {
179 let mut tmp = tempfile::Builder::new()
180 .prefix("codewhale-share-")
181 .suffix(".html")
182 .tempfile()
183 .map_err(|e| format!("{e}"))?;
184 tmp.write_all(html.as_bytes()).map_err(|e| format!("{e}"))?;
185 Ok(tmp)
186 }
187
188 /// Upload a file as a secret GitHub gist using the `gh` CLI. `gh gist
189 /// create` makes secret gists unless `--public` is passed; it never is here.
190 fn upload_gist(path: &Path) -> Result<String, String> {
191 let mut cmd = codewhale_dependencies::Gh::command()
192 .ok_or_else(|| "the `gh` CLI was not found".to_string())?;
193 let output = cmd
194 .args(gist_create_args(path))
195 .output()
196 .map_err(|e| format!("Failed to run `gh gist create`: {e}"))?;
197
198 if !output.status.success() {
199 let stderr = String::from_utf8_lossy(&output.stderr);
200 return Err(format!("`gh gist create` failed: {stderr}"));
201 }
202
203 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
204 if stdout.is_empty() {
205 return Err("`gh gist create` returned no output".to_string());
206 }
207
208 Ok(stdout)
209 }
210
211 fn gist_create_args(path: &Path) -> Vec<String> {
212 vec![
213 "gist".to_string(),
214 "create".to_string(),
215 path.to_string_lossy().into_owned(),
216 "--filename".to_string(),
217 "session-export.html".to_string(),
218 "--desc".to_string(),
219 "codewhale Session Export".to_string(),
220 ]
221 }
222
223 pub(in crate::commands) const SHARE_INFO: CommandInfo = CommandInfo {
224 name: "share",
225 aliases: &[],
226 usage: "/share [confirm]",
227 description_key: "cmd_share_description",
228 };
229
230 pub(in crate::commands) struct ShareCmd;
231
232 impl RegisterCommand<CommandResult> for ShareCmd {
233 fn info() -> &'static CommandInfo {
234 &SHARE_INFO
235 }
236
237 fn handler() -> CommandHandler<CommandResult> {
238 CommandHandler::Contextual {
239 capabilities: CommandCapabilities::SESSION_EXPORT,
240 handler: share_contextual,
241 }
242 }
243 }
244
245 /// Contextual `/share` dispatch. `/share` reads the conversation through the
246 /// session-export facet, the same authority `/export` uses.
247 fn share_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
248 let parts = contexts.into_parts();
249 let Some(export) = parts.export.as_deref() else {
250 return CommandResult::error("Command capability unavailable: session_export");
251 };
252 share(export, arg)
253 }
254
255 #[cfg(test)]
256 mod tests {
257 use super::*;
258 use codewhale_command_contract::facets::{
259 ExportMessage, ExportMetadata, TurnHandoffProjection,
260 };
261 use std::cell::Cell;
262 use std::path::PathBuf;
263
264 const FAKE_KEY: &str = "sk-proj-abcdefghijklmnopqrstuvwxyz0123456789ABCD";
265
266 /// Fake export facet: serves one projection and fails loudly if `/share`
267 /// ever reaches for clipboard or filesystem effects.
268 struct FakeExport {
269 messages: Vec<ExportMessage>,
270 projections: Cell<usize>,
271 }
272
273 impl FakeExport {
274 fn new(messages: Vec<ExportMessage>) -> Self {
275 Self {
276 messages,
277 projections: Cell::new(0),
278 }
279 }
280 }
281
282 impl CommandSessionExportContext for FakeExport {
283 fn conversation_projection(&self) -> ConversationExportProjection {
284 self.projections.set(self.projections.get() + 1);
285 ConversationExportProjection {
286 metadata: ExportMetadata {
287 session_label: "sess1234".to_string(),
288 title: None,
289 provider: "deepseek".to_string(),
290 model: "deepseek-v4-pro".to_string(),
291 mode: "agent".to_string(),
292 workspace_name: "workspace".to_string(),
293 message_count: self.messages.len(),
294 exported_at_unix: 1_700_000_000,
295 },
296 transcript: TranscriptProjection::Authoritative(self.messages.clone()),
297 restore_points: RestorePointProjection::Unreadable {
298 reason: "local-only snapshot detail".to_string(),
299 },
300 turn_outcomes: Vec::new(),
301 }
302 }
303
304 fn turn_handoff_projection(&self) -> TurnHandoffProjection {
305 panic!("/share must not read the turn handoff");
306 }
307
308 fn clipboard_requires_terminal_paste(&self) -> bool {
309 panic!("/share must not touch the clipboard");
310 }
311
312 fn write_recovery_copy(&self, _markdown: &str) -> Option<PathBuf> {
313 panic!("/share must not write a recovery copy");
314 }
315
316 fn write_clipboard(&self, _markdown: &str) -> Result<(), String> {
317 panic!("/share must not touch the clipboard");
318 }
319
320 fn resolve_export_path(&self, _raw: &str) -> Result<PathBuf, String> {
321 panic!("/share must not resolve export paths");
322 }
323
324 fn default_export_path(&self, _file_name: &str) -> Result<PathBuf, String> {
325 panic!("/share must not resolve export paths");
326 }
327
328 fn write_export_file(
329 &self,
330 _path: &Path,
331 _contents: &[u8],
332 _force: bool,
333 ) -> Result<(), String> {
334 panic!("/share must not write export files");
335 }
336 }
337
338 fn message(role: &str, blocks: Vec<ExportBlock>) -> ExportMessage {
339 ExportMessage {
340 role: role.to_string(),
341 is_user_role: role == "user",
342 blocks,
343 prompt_snippet: None,
344 }
345 }
346
347 fn session_with_secret_tool_result() -> FakeExport {
348 FakeExport::new(vec![
349 message(
350 "system",
351 vec![ExportBlock::Text {
352 text: "HIDDEN SYSTEM PROMPT".to_string(),
353 }],
354 ),
355 message(
356 "user",
357 vec![ExportBlock::Text {
358 text: "print my env".to_string(),
359 }],
360 ),
361 message(
362 "assistant",
363 vec![
364 ExportBlock::InternalReasoning,
365 ExportBlock::ToolCall {
366 id: "call_1".to_string(),
367 name: "exec_shell".to_string(),
368 caller: None,
369 input: serde_json::json!({"command": "env"}),
370 },
371 ],
372 ),
373 message(
374 "user",
375 vec![ExportBlock::ToolResult {
376 tool_use_id: "call_1".to_string(),
377 content: format!("PATH=/usr/bin\nOPENAI_API_KEY={FAKE_KEY}\nleaked {FAKE_KEY}"),
378 is_error: false,
379 structured: None,
380 }],
381 ),
382 ])
383 }
384
385 fn share_html(result: &CommandResult) -> &str {
386 match result.action.as_ref() {
387 Some(AppAction::ShareSession { html }) => html,
388 other => panic!("expected ShareSession, got {other:?}"),
389 }
390 }
391
392 #[test]
393 fn plain_share_previews_without_an_upload_action() {
394 let export = session_with_secret_tool_result();
395 let result = share(&export, Some(""));
396 assert!(!result.is_error, "{result:?}");
397 assert!(
398 result.action.is_none(),
399 "plain /share must not start an upload: {:?}",
400 result.action
401 );
402 let msg = result.message.unwrap();
403 assert!(msg.contains("nothing has been uploaded"), "{msg}");
404 assert!(msg.contains("Messages: 4"), "{msg}");
405 assert!(
406 msg.contains("Tool output: included (1 tool result(s), redacted)"),
407 "{msg}"
408 );
409 assert!(msg.contains("Redacted: 2 item(s)"), "{msg}");
410 assert!(msg.contains("/share confirm"), "{msg}");
411 assert!(msg.contains("unlisted, not private"), "{msg}");
412 assert!(!msg.contains(FAKE_KEY), "{msg}");
413 }
414
415 #[test]
416 fn confirm_renders_the_redacted_export_projection_not_raw_messages() {
417 let export = session_with_secret_tool_result();
418 let result = share(&export, Some("confirm"));
419 assert!(!result.is_error, "{result:?}");
420 assert!(
421 result
422 .message
423 .as_deref()
424 .unwrap()
425 .contains("unlisted, not private"),
426 "{result:?}"
427 );
428 let msg = result.message.as_deref().unwrap();
429 assert!(msg.contains("Messages: 4"), "{msg}");
430 assert!(
431 msg.contains("Tool output: included (1 tool result(s), redacted)"),
432 "{msg}"
433 );
434 assert!(msg.contains("Redacted: 2 item(s)"), "{msg}");
435 let html = share_html(&result);
436 assert!(!html.contains(FAKE_KEY), "secret leaked into the page");
437 assert!(
438 !html.contains("sk-proj-"),
439 "secret prefix leaked into the page"
440 );
441 assert!(!html.contains("HIDDEN SYSTEM PROMPT"), "system text leaked");
442 assert!(html.contains("[internal context omitted]"));
443 assert!(html.contains("[internal reasoning and signature omitted]"));
444 assert!(
445 html.contains("PATH=/usr/bin"),
446 "ordinary tool output is kept"
447 );
448 assert!(
449 !html.contains("local-only snapshot detail"),
450 "restore-point table is local-only"
451 );
452 assert!(html.contains("deepseek-v4-pro"));
453 assert_eq!(export.projections.get(), 1);
454 }
455
456 #[test]
457 fn empty_session_errors_for_preview_and_confirm() {
458 let export = FakeExport::new(Vec::new());
459 for arg in ["", "confirm"] {
460 let result = share(&export, Some(arg));
461 assert!(result.is_error, "{arg}: {result:?}");
462 assert!(result.message.unwrap().contains("Nothing to share"));
463 assert!(result.action.is_none());
464 }
465 }
466
467 #[test]
468 fn help_and_unknown_routes() {
469 let export = session_with_secret_tool_result();
470 for arg in ["help", "--help", "-h"] {
471 let result = share(&export, Some(arg));
472 assert!(!result.is_error);
473 assert!(result.action.is_none());
474 let msg = result.message.unwrap();
475 assert!(msg.contains("/share confirm"), "{msg}");
476 assert!(msg.contains("unlisted, not private"), "{msg}");
477 }
478 let result = share(&export, Some("bogus"));
479 assert!(result.is_error);
480 assert!(
481 result
482 .message
483 .unwrap()
484 .contains("Unknown /share argument `bogus`")
485 );
486 assert_eq!(export.projections.get(), 0, "help/unknown read nothing");
487 }
488
489 #[test]
490 fn missing_export_facet_fails_safely() {
491 let result = share_contextual(CommandContexts::empty(), Some("confirm"));
492 assert!(result.is_error);
493 assert!(result.action.is_none());
494 assert!(
495 result
496 .message
497 .unwrap()
498 .contains("Command capability unavailable: session_export")
499 );
500 }
501
502 #[test]
503 fn gist_is_created_without_public_flag() {
504 let args = gist_create_args(Path::new("/tmp/page.html"));
505 assert!(!args.iter().any(|arg| arg == "--public"), "{args:?}");
506 assert_eq!(&args[..3], ["gist", "create", "/tmp/page.html"]);
507 }
508
509 #[test]
510 fn temp_page_is_removed_after_upload_success_and_failure() {
511 let mut seen = None;
512 let url = upload_via_temp_file("<html>ok</html>", |path| {
513 assert_eq!(std::fs::read_to_string(path).unwrap(), "<html>ok</html>");
514 seen = Some(path.to_path_buf());
515 Ok("https://gist.github.com/x".to_string())
516 })
517 .unwrap();
518 assert_eq!(url, "https://gist.github.com/x");
519 assert!(
520 !seen.unwrap().exists(),
521 "temp page must be deleted after upload"
522 );
523
524 let mut seen = None;
525 let err = upload_via_temp_file("<html>no</html>", |path| {
526 seen = Some(path.to_path_buf());
527 Err("gh failed".to_string())
528 })
529 .unwrap_err();
530 assert_eq!(err, "gh failed");
531 assert!(
532 !seen.unwrap().exists(),
533 "temp page must be deleted on failure"
534 );
535 }
536
537 #[test]
538 fn html_escapes_the_rendered_conversation() {
539 let export = FakeExport::new(vec![message(
540 "user",
541 vec![ExportBlock::Text {
542 text: "<script>x</script> & \"q\"".to_string(),
543 }],
544 )]);
545 let result = share(&export, Some("confirm"));
546 let html = share_html(&result);
547 assert!(html.contains("&lt;script&gt;x&lt;/script&gt; &amp; &quot;q&quot;"));
548 assert!(!html.contains("<script>"));
549 }
550 }
551
551 lines RUST