返回 CodeWhale
render.rs
根目录 / crates / tui / src / commands / groups / plugins / render.rs
1 //! Presentation for `/plugin`: bundle detail, the capability review body,
2 //! and diagnostics.
3 //!
4 //! Everything here is a pure portable transform — no registry mutation, no
5 //! disk access. [`escape_review_text`] is the security-relevant part:
6 //! manifest fields are attacker-controlled, so they are escaped before they
7 //! reach a review the user is about to approve.
8 //!
9 //! FEAT-020: render helpers consume portable `PluginDetail` values and the
10 //! presentation facet; the concrete `LoadedPlugin` never crosses the
11 //! boundary.
12
13 use std::fmt::Write as _;
14 use std::path::Path;
15
16 use codewhale_command_contract::facets::{
17 CommandPresentationContext, PluginDetail, PluginDiagnostic, PluginDiagnosticLevel,
18 PluginMcpServerDetail,
19 };
20
21 use super::append_diagnostics;
22
23 pub(super) fn render_bundle_detail(
24 presentation: &mut dyn CommandPresentationContext,
25 detail: &PluginDetail,
26 include_hashes: bool,
27 context: ReviewTextContext,
28 ) -> String {
29 let unsupported = if detail.unsupported_labels.is_empty() {
30 "none".to_string()
31 } else {
32 display_component_labels(&detail.unsupported_labels)
33 };
34 let active_components = if detail.active {
35 let labels = &detail.supported_labels;
36 if labels.is_empty() {
37 "none".to_string()
38 } else {
39 display_component_labels(labels)
40 }
41 } else {
42 "none".to_string()
43 };
44 let extension_host = codewhale_plugins::activation::extension_host_policy_enabled();
45 let (content_hash, capability_hash) = if include_hashes {
46 (
47 detail.content_hash.as_str(),
48 detail.capability_hash.as_str(),
49 )
50 } else {
51 ("hidden", "hidden")
52 };
53 let mut output = presentation
54 .translate(
55 "cmd_plugin_bundle_detail",
56 &[
57 ("name", &escape_review_text(&detail.name, context)),
58 ("id", &escape_review_text(&detail.id, context)),
59 ("version", &escape_review_text(&detail.version, context)),
60 ("origin", &detail.origin),
61 ("scope", &detail.scope),
62 ("state", &detail.state_label),
63 (
64 "trust",
65 detail
66 .trust_display
67 .as_deref()
68 .unwrap_or(&detail.trust_status),
69 ),
70 ("inventory", &detail.inventory_summary),
71 ("permissions", &render_permissions(detail, context)),
72 ("mcp", &render_mcp_inventory(detail, context)),
73 ("unsupported", &unsupported),
74 ("content_hash", content_hash),
75 ("capability_hash", capability_hash),
76 ("path", &escape_review_path(&detail.canonical_root, context)),
77 ],
78 )
79 .unwrap_or_default();
80 let skills = detail
81 .skills
82 .iter()
83 .map(|skill| escape_review_text(skill, context))
84 .collect::<Vec<_>>();
85 let commands = detail
86 .commands
87 .iter()
88 .map(|command| escape_review_text(command, context))
89 .collect::<Vec<_>>();
90 let profiles = detail
91 .profiles
92 .iter()
93 .map(|profile| escape_review_text(profile, context))
94 .collect::<Vec<_>>();
95 let _ = write!(
96 output,
97 "\nCompatibility: {}\nActive components: [{active_components}]\nInactive components: [{unsupported}]\nQualified skills: [{}]\nCommands: [{}]\nProfiles: [{}]\nActivation boundary: trust stages the exact reviewed content but does not activate it; enable rebuilds this workspace's Skills, MCP, Commands, Agents, and Hooks immediately. Every plugin command dispatch, Agent spawn, Hook process start, Skill use, and MCP call rechecks current authority. {}",
98 detail.compatibility,
99 if skills.is_empty() {
100 "none".to_string()
101 } else {
102 skills.join(", ")
103 },
104 if commands.is_empty() {
105 "none".to_string()
106 } else {
107 commands.join(", ")
108 },
109 if profiles.is_empty() {
110 "none".to_string()
111 } else {
112 profiles.join(", ")
113 },
114 if extension_host {
115 "Native host code (JavaScript) runs in the experimental plugin host with your user permissions (sandboxed where the OS sandbox is available); plugin tools are never auto-approved by the plugin itself, and each call needs approval under your approval mode. LSP, filesystem-roots, and lifecycle-mutation stay inventoried and inactive."
116 } else {
117 "LSP, native, filesystem-roots, and lifecycle-mutation stay inventoried and inactive."
118 }
119 );
120 if let Some(approver) = detail.approver.as_deref() {
121 if let Some(date) = detail.reviewed_date.as_deref() {
122 let safe_date = escape_review_text(date, ReviewTextContext::Plain);
123 let approved_date = presentation
124 .translate("cmd_plugin_audit_approved_date", &[("date", &safe_date)])
125 .unwrap_or_else(|_| format!("approved {safe_date}"));
126 let _ = write!(output, "\nApproval: {approver} ({approved_date})");
127 } else {
128 let _ = write!(output, "\nApproval: {approver}");
129 }
130 }
131 if let Some(thread_id) = detail.agent_thread_id.as_deref() {
132 let _ = write!(
133 output,
134 "\nApproval thread: {}",
135 escape_review_text(thread_id, context)
136 );
137 }
138 if let Some(enabled_by) = detail.enabled_by.as_deref() {
139 let _ = write!(output, "\nTurned on by: {enabled_by}");
140 }
141 if detail.outside_reach
142 || detail.reach_folder.is_some()
143 || detail.agent_workspace_path.is_some()
144 {
145 let folder =
146 escape_review_text(detail.reach_folder.as_deref().unwrap_or("unknown"), context);
147 let key = if detail.outside_reach {
148 "cmd_plugin_audit_reach_only_in"
149 } else {
150 "cmd_plugin_audit_reach_here"
151 };
152 let reach = presentation
153 .translate(key, &[("folder", &folder)])
154 .unwrap_or(folder);
155 if let Some(workspace_path) = detail.agent_workspace_path.as_deref() {
156 let _ = write!(
157 output,
158 "\nReach: {reach} — {}",
159 escape_review_text(workspace_path, context)
160 );
161 } else {
162 let _ = write!(output, "\nReach: {reach}");
163 }
164 }
165 if let Some(note) = detail.process_note.as_deref() {
166 let _ = write!(output, "\nProcess: {note}");
167 }
168 if !detail.host_services.is_empty() {
169 output.push_str("\nHost services:");
170 for service in &detail.host_services {
171 let line = if !service.withheld_by.is_empty() && service.can_use {
172 let peer_context = if context == ReviewTextContext::Prose {
173 ReviewTextContext::InlineCode
174 } else {
175 context
176 };
177 let peers = service
178 .withheld_by
179 .iter()
180 .map(|peer| format!("`{}`", escape_review_text(peer, peer_context)))
181 .collect::<Vec<_>>()
182 .join(", ");
183 let key = if service.withheld_by.len() == 1 {
184 "cmd_plugin_audit_service_withheld_one"
185 } else {
186 "cmd_plugin_audit_service_withheld_many"
187 };
188 presentation
189 .translate(key, &[("service", &service.service), ("peers", &peers)])
190 .unwrap_or_else(|_| format!("{}: off for now: {peers}", service.service))
191 } else if service.can_use {
192 presentation
193 .translate(
194 "cmd_plugin_audit_service_can_use",
195 &[("service", &service.service)],
196 )
197 .unwrap_or_else(|_| format!("{}: can use", service.service))
198 } else {
199 presentation
200 .translate(
201 "cmd_plugin_audit_service_not_offered",
202 &[("service", &service.service)],
203 )
204 .unwrap_or_else(|_| {
205 format!("{}: this version does not offer it", service.service)
206 })
207 };
208 let _ = write!(output, "\n - {line}");
209 }
210 }
211 if !detail.earlier_reviews.is_empty() {
212 output.push_str("\nEarlier reviews:");
213 for entry in &detail.earlier_reviews {
214 let safe_date = escape_review_text(&entry.reviewed_at, ReviewTextContext::Plain);
215 let _ = write!(output, "\n - {safe_date}: {}", entry.approver);
216 }
217 }
218 append_diagnostics(presentation, &mut output, &detail.diagnostics, context);
219 output
220 }
221
222 /// Component labels for review text. With the experimental extension host
223 /// on, `native` is shown by what it is; with it off the text is unchanged.
224 /// The hashed label itself (`PluginActivationCapability::as_str`) never
225 /// changes.
226 fn display_component_labels(labels: &[String]) -> String {
227 let extension_host = codewhale_plugins::activation::extension_host_policy_enabled();
228 labels
229 .iter()
230 .map(|label| match label.as_str() {
231 "native" if extension_host => "native (host code: JavaScript)",
232 other => other,
233 })
234 .collect::<Vec<_>>()
235 .join(", ")
236 }
237
238 fn render_permissions(detail: &PluginDetail, context: ReviewTextContext) -> String {
239 let filesystem = if detail.filesystem_roots.is_empty() {
240 "none".to_string()
241 } else {
242 detail
243 .filesystem_roots
244 .iter()
245 .map(|value| escape_review_text(value, context))
246 .collect::<Vec<_>>()
247 .join(", ")
248 };
249 let network = if detail.network_hosts.is_empty() {
250 "none".to_string()
251 } else {
252 detail
253 .network_hosts
254 .iter()
255 .map(|value| escape_review_text(value, context))
256 .collect::<Vec<_>>()
257 .join(", ")
258 };
259 let stdio_authority = if detail.stdio_mcp_servers == 0 {
260 "none".to_string()
261 } else {
262 format!(
263 "{} local child process(es) with host-user filesystem/network authority; MCP tool approvals still apply",
264 detail.stdio_mcp_servers
265 )
266 };
267 format!(
268 "filesystem_roots=[{filesystem}] network_hosts=[{network}] (exact allowlist for Codewhale-managed remote requests; redirects stay same-origin) lifecycle_mutation={} stdio_runtime=[{stdio_authority}]",
269 detail.lifecycle_mutation
270 )
271 }
272
273 fn render_mcp_inventory(detail: &PluginDetail, context: ReviewTextContext) -> String {
274 if detail.mcp_servers.is_empty() {
275 return "none".to_string();
276 }
277 detail
278 .mcp_servers
279 .iter()
280 .map(|server| render_mcp_server(server, context))
281 .collect::<Vec<_>>()
282 .join("; ")
283 }
284
285 fn render_mcp_server(server: &PluginMcpServerDetail, context: ReviewTextContext) -> String {
286 let enabled = if server.enabled {
287 "configured-on"
288 } else {
289 "configured-off"
290 };
291 if let Some(command) = server.command.as_deref() {
292 let mut env_provenance = server
293 .env
294 .iter()
295 .map(|(destination, source)| {
296 let source = source
297 .strip_prefix("${")
298 .and_then(|source| source.strip_suffix('}'))
299 .unwrap_or("invalid");
300 format!(
301 "{} <- {}",
302 escape_review_text(destination, context),
303 escape_review_text(source, context)
304 )
305 })
306 .collect::<Vec<_>>();
307 env_provenance.sort_unstable();
308 let cwd = server
309 .cwd
310 .as_deref()
311 .map(|value| escape_review_path(value, context))
312 .unwrap_or_else(|| "plugin-root".to_string());
313 let argv = render_review_argv(&server.argv, context);
314 format!(
315 "{}: transport=stdio command={} argv=[{}] cwd={cwd} env=[{}] timeouts={} required={} enabled_tools=[{}] disabled_tools=[{}] host-user-filesystem/network-authority {enabled}",
316 escape_review_text(&server.name, context),
317 escape_review_text(command, context),
318 argv.join(", "),
319 if env_provenance.is_empty() {
320 "none".to_string()
321 } else {
322 env_provenance.join(", ")
323 },
324 render_mcp_timeouts(server),
325 server.required,
326 render_review_values(&server.enabled_tools, context),
327 render_review_values(&server.disabled_tools, context),
328 )
329 } else if let Some(url) = server.url.as_deref() {
330 let endpoint = reqwest::Url::parse(url)
331 .ok()
332 .map(|url| escape_review_text(url.as_str(), context))
333 .unwrap_or_else(|| "invalid-url".to_string());
334 let mut env_headers = server
335 .env_headers
336 .iter()
337 .map(|(header, source)| {
338 format!(
339 "{} <- {}",
340 escape_review_text(header, context),
341 escape_review_text(source, context)
342 )
343 })
344 .collect::<Vec<_>>();
345 env_headers.sort_unstable();
346 let bearer = server
347 .bearer_token_env_var
348 .as_deref()
349 .map(|value| escape_review_text(value, context))
350 .unwrap_or_else(|| "none".to_string());
351 let transport = transport_label(&server.transport);
352 format!(
353 "{}: transport={} endpoint={} redirects=same-origin-only env_headers=[{}] bearer_env={} oauth=disabled timeouts={} required={} enabled_tools=[{}] disabled_tools=[{}] {enabled}",
354 escape_review_text(&server.name, context),
355 escape_review_text(transport, context),
356 endpoint,
357 if env_headers.is_empty() {
358 "none".to_string()
359 } else {
360 env_headers.join(", ")
361 },
362 bearer,
363 render_mcp_timeouts(server),
364 server.required,
365 render_review_values(&server.enabled_tools, context),
366 render_review_values(&server.disabled_tools, context),
367 )
368 } else {
369 format!("{}: invalid", escape_review_text(&server.name, context))
370 }
371 }
372
373 fn transport_label(
374 transport: &codewhale_command_contract::facets::PluginMcpTransport,
375 ) -> &'static str {
376 match transport {
377 codewhale_command_contract::facets::PluginMcpTransport::Stdio => "stdio",
378 codewhale_command_contract::facets::PluginMcpTransport::Http => "http",
379 codewhale_command_contract::facets::PluginMcpTransport::Invalid => "invalid",
380 }
381 }
382
383 fn render_review_argv(arguments: &[String], context: ReviewTextContext) -> Vec<String> {
384 arguments
385 .iter()
386 .enumerate()
387 .map(|(index, argument)| {
388 let position = index + 1;
389 format!(
390 "#{position} value={}",
391 render_review_argv_value(argument, context)
392 )
393 })
394 .collect()
395 }
396
397 fn render_review_argv_value(value: &str, context: ReviewTextContext) -> String {
398 // JSON string syntax is a lossless, unambiguous terminal representation:
399 // whitespace, quotes, backslashes, and punctuation retain their exact
400 // argv semantics without hiding arbitrary values behind redaction.
401 let rendered = serde_json::to_string(value).expect("serializing a Rust string cannot fail");
402 if context != ReviewTextContext::Prose {
403 return rendered;
404 }
405 let mut escaped = String::with_capacity(rendered.len());
406 let mut chars = rendered.chars();
407 while let Some(ch) = chars.next() {
408 if ch == '\\' {
409 match chars.next() {
410 Some(next @ ('\\' | '"')) => {
411 let _ = write!(escaped, "\\u{:04x}", next as u32);
412 }
413 Some(next) => {
414 escaped.push('\\');
415 escaped.push(next);
416 }
417 None => escaped.push(ch),
418 }
419 } else if "&`*_[](){}#+-.!|~<>:".contains(ch)
420 || codewhale_sanitize::sanitize::is_bidi_control(ch)
421 {
422 let _ = write!(escaped, "\\u{:04x}", ch as u32);
423 } else {
424 escaped.push(ch);
425 }
426 }
427 escaped
428 }
429
430 fn render_review_values(values: &[String], context: ReviewTextContext) -> String {
431 if values.is_empty() {
432 return "none".to_string();
433 }
434 values
435 .iter()
436 .map(|value| escape_review_text(value, context))
437 .collect::<Vec<_>>()
438 .join(", ")
439 }
440
441 fn render_mcp_timeouts(server: &PluginMcpServerDetail) -> String {
442 format!(
443 "connect={}/execute={}/read={}",
444 server
445 .connect_timeout_secs
446 .map_or_else(|| "default".to_string(), |value| format!("{value}s")),
447 server
448 .execute_timeout_secs
449 .map_or_else(|| "default".to_string(), |value| format!("{value}s")),
450 server
451 .read_timeout_secs
452 .map_or_else(|| "default".to_string(), |value| format!("{value}s")),
453 )
454 }
455
456 #[derive(Clone, Copy, PartialEq, Eq)]
457 pub(crate) enum ReviewTextContext {
458 Prose,
459 InlineCode,
460 Plain,
461 }
462
463 pub(crate) fn escape_review_path(path: &Path, context: ReviewTextContext) -> String {
464 escape_review_text(&path.to_string_lossy(), context)
465 }
466
467 pub(crate) fn escape_review_text(value: &str, context: ReviewTextContext) -> String {
468 let mut escaped = String::with_capacity(value.len());
469 for ch in value.chars() {
470 if ch.is_control()
471 || codewhale_sanitize::sanitize::is_bidi_control(ch)
472 || (context == ReviewTextContext::InlineCode && ch == '`')
473 {
474 let _ = write!(escaped, "\\u{{{:x}}}", ch as u32);
475 } else if context == ReviewTextContext::Prose && ch == '&' {
476 escaped.push_str("&amp;");
477 } else if context == ReviewTextContext::Prose
478 && matches!(
479 ch,
480 '\\' | '`'
481 | '*'
482 | '_'
483 | '{'
484 | '}'
485 | '['
486 | ']'
487 | '<'
488 | '>'
489 | '('
490 | ')'
491 | '#'
492 | '+'
493 | '-'
494 | '.'
495 | '!'
496 | '|'
497 )
498 {
499 escaped.push('\\');
500 escaped.push(ch);
501 } else {
502 escaped.push(ch);
503 }
504 }
505 escaped
506 }
507
508 fn _diagnostic_level_label(level: PluginDiagnosticLevel) -> &'static str {
509 match level {
510 PluginDiagnosticLevel::Warning => "warning",
511 PluginDiagnosticLevel::Error => "error",
512 }
513 }
514
515 fn _diagnostic_path(diagnostic: &PluginDiagnostic) -> Option<String> {
516 diagnostic
517 .path
518 .as_ref()
519 .map(|path| path.display().to_string())
520 }
521
522 /// `/plugin doctor` output: what is superseded, what was kept and why, and
523 /// the state-file effect. Every dynamic string is escaped; paths and ids come
524 /// from the filesystem and from plugin state, which a bundle can influence.
525 pub(super) fn render_gc_report(
526 report: &codewhale_plugins::registry::gc::GcReport,
527 fixed: bool,
528 ) -> String {
529 use codewhale_plugins::registry::gc::format_bytes;
530
531 const SHOWN: usize = 40;
532 let mut out = String::new();
533 let title = if fixed {
534 "Plugin doctor: applied"
535 } else {
536 "Plugin doctor: report (nothing was changed)"
537 };
538 let _ = writeln!(out, "{title}\n");
539 if report.items.is_empty() {
540 let _ = writeln!(
541 out,
542 "Nothing to retire. {} state records, {}.",
543 report.records_before,
544 format_bytes(report.state_bytes_before)
545 );
546 } else {
547 let verb = if fixed { "Retired" } else { "Would retire" };
548 let records = report
549 .items
550 .iter()
551 .filter(|item| item.kind == codewhale_plugins::registry::gc::GcKind::Record)
552 .count();
553 let _ = writeln!(
554 out,
555 "{verb} {records} records and {} directories ({} on disk). state.json: {} -> {} records, {} -> {}.\n",
556 report.items.len() - records,
557 format_bytes(report.reclaimable_bytes()),
558 report.records_before,
559 report.records_after,
560 format_bytes(report.state_bytes_before),
561 format_bytes(report.state_bytes_after),
562 );
563 for item in report.items.iter().take(SHOWN) {
564 let gate = if item.explicit && !fixed {
565 " [--fix only]"
566 } else {
567 ""
568 };
569 let _ = writeln!(
570 out,
571 " {}{gate} {}: {}",
572 item.kind.label(),
573 escape_review_text(&item.target, ReviewTextContext::Prose),
574 escape_review_text(&item.reason, ReviewTextContext::Prose)
575 );
576 }
577 if report.items.len() > SHOWN {
578 let _ = writeln!(out, " ... and {} more", report.items.len() - SHOWN);
579 }
580 }
581 if !report.kept.is_empty() {
582 let _ = writeln!(out, "\nKept ({}):", report.kept.len());
583 for line in report.kept.iter().take(10) {
584 let _ = writeln!(
585 out,
586 " {}",
587 escape_review_text(line, ReviewTextContext::Prose)
588 );
589 }
590 if report.kept.len() > 10 {
591 let _ = writeln!(out, " ... and {} more", report.kept.len() - 10);
592 }
593 }
594 for note in &report.notes {
595 let _ = writeln!(
596 out,
597 "\nNote: {}",
598 escape_review_text(note, ReviewTextContext::Prose)
599 );
600 }
601 for failure in &report.failures {
602 let _ = writeln!(
603 out,
604 "\nCould not remove {}",
605 escape_review_text(failure, ReviewTextContext::Prose)
606 );
607 }
608 if fixed {
609 if !report.items.is_empty() {
610 out.push_str("\nThe previous state.json is kept as state.json.pre-gc.");
611 }
612 } else if !report.items.is_empty() {
613 out.push_str(
614 "\nRun /plugin doctor --fix to apply. Items not marked [--fix only] are also retired automatically at startup.",
615 );
616 }
617 out
618 }
619
619 lines RUST