Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/ui/src/chat/components/activity.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,8 +239,9 @@ fn activity_detail(
let detail = match &entry.content {
EntryContent::Item(ItemContent::CommandExecution {
command, output, ..
}) => command_detail
.unwrap_or_else(|| CommandPanelCache::new().render(&entry.id, command, output, cx)),
}) => command_detail.unwrap_or_else(|| {
CommandPanelCache::new().render(&entry.id, command, output, None, cx)
}),
EntryContent::Item(ItemContent::ToolCall { input, output, .. }) => {
let mut input_brief = tool_brief(input);
if input_brief.is_empty() {
Expand Down
237 changes: 173 additions & 64 deletions crates/ui/src/chat/components/command_panel.rs
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
use std::collections::HashMap;

use gpui::{
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, canvas, div,
px,
AnyElement, App, ContentMask, IntoElement as _, ParentElement as _, Styled as _, StyledText,
Window, canvas, div, prelude::FluentBuilder as _, px,
};
use gpui_base::{ElementExt as _, h_flex};
use term::{GridEmulator, TermSnapshot};

use crate::highlight;
use crate::terminal_drawer::{
TERMINAL_CELL_HEIGHT, TERMINAL_CELL_WIDTH, TerminalPalette, layout_grid, paint_terminal_grid,
};
use crate::theme::ActiveTheme as _;

const COLS: usize = 80;
const DEFAULT_COLS: usize = 80;
const MIN_COLS: usize = 20;
const MAX_COLS: usize = 400;
const MAX_ROWS: usize = 16;
const MAX_COMMAND_ROWS: usize = 4;
const PROMPT_COLS: usize = 2;
const OUTPUT_TAIL_BYTES: usize = 32 * 1024;

pub(crate) type ColsChangeHandler = Box<dyn Fn(&usize, &mut Window, &mut App) + 'static>;

pub(crate) struct CommandPanelCache {
entries: HashMap<String, CachedPanel>,
}
Expand All@@ -31,39 +38,60 @@ impl CommandPanelCache {
self.entries.clear();
}

pub(crate) fn render(&mut self, id: &str, command: &str, output: &str, cx: &App) -> AnyElement {
pub(crate) fn resize(&mut self, id: &str, cols: usize) -> bool {
self.entries
.get_mut(id)
.is_some_and(|panel| panel.resize(cols))
}

pub(crate) fn render(
&mut self,
id: &str,
command: &str,
output: &str,
on_cols_change: Option<ColsChangeHandler>,
cx: &App,
) -> AnyElement {
let panel = self
.entries
.entry(id.to_string())
.or_insert_with(|| CachedPanel::new(command, output));
panel.update(command, output);
panel.render(cx)
panel.render(on_cols_change, cx)
}
}

struct CachedPanel {
command: String,
command_snapshot: TermSnapshot,
displayed_command: String,
command_rows: usize,
cols: usize,
output_emulator: GridEmulator,
output: Vec<u8>,
fed_start: usize,
last_fed_was_cr: bool,
output_snapshot: TermSnapshot,
output_rows: usize,
}

impl CachedPanel {
fn new(command: &str, output: &str) -> Self {
let (command_snapshot, command_rows) = command_snapshot(command);
let output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - command_rows);
Self::with_cols(command, output, DEFAULT_COLS)
}

fn with_cols(command: &str, output: &str, cols: usize) -> Self {
let (displayed_command, command_rows) = clamp_command(command, cols);
let output_emulator = GridEmulator::with_size(cols, MAX_ROWS - command_rows);
let output_snapshot = output_emulator.snapshot();
let mut panel = Self {
command: command.to_string(),
command_snapshot,
displayed_command,
command_rows,
cols,
output_emulator,
output: Vec::new(),
fed_start: 0,
last_fed_was_cr: false,
output_snapshot,
output_rows: 0,
};
Expand All@@ -74,7 +102,7 @@ impl CachedPanel {
fn update(&mut self, command: &str, output: &str) {
if self.command != command {
self.command = command.to_string();
(self.command_snapshot, self.command_rows) = command_snapshot(command);
(self.displayed_command, self.command_rows) = clamp_command(command, self.cols);
self.rebuild_output(output.as_bytes());
return;
}
Expand All@@ -85,49 +113,111 @@ impl CachedPanel {
}
let append_only = bytes.starts_with(&self.output);
if append_only && bytes.len().saturating_sub(self.fed_start) <= OUTPUT_TAIL_BYTES {
self.output_emulator.feed(&bytes[self.output.len()..]);
self.feed_output(&bytes[self.output.len()..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
} else {
self.rebuild_output(bytes);
}
}

fn resize(&mut self, cols: usize) -> bool {
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if self.cols == cols {
return false;
}
self.cols = cols;
(self.displayed_command, self.command_rows) = clamp_command(&self.command, cols);
let output = self.output.clone();
self.rebuild_output(&output);
true
}

fn rebuild_output(&mut self, bytes: &[u8]) {
self.output_emulator = GridEmulator::with_size(COLS, MAX_ROWS - self.command_rows);
self.output_emulator =
GridEmulator::with_size(self.cols, MAX_ROWS.saturating_sub(self.command_rows).max(1));
self.fed_start = bytes.len().saturating_sub(OUTPUT_TAIL_BYTES);
self.output_emulator.feed(&bytes[self.fed_start..]);
self.last_fed_was_cr = self.fed_start > 0 && bytes[self.fed_start - 1] == b'\r';
self.feed_output(&bytes[self.fed_start..]);
self.output = bytes.to_vec();
self.refresh_output_snapshot();
}

fn feed_output(&mut self, bytes: &[u8]) {
let mut normalized = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' && !self.last_fed_was_cr {
normalized.push(b'\r');
}
normalized.push(byte);
self.last_fed_was_cr = byte == b'\r';
}
self.output_emulator.feed(&normalized);
}

fn refresh_output_snapshot(&mut self) {
self.output_snapshot = self.output_emulator.snapshot();
self.output_rows =
trim_snapshot(&mut self.output_snapshot, MAX_ROWS - self.command_rows, 0);
self.output_rows = trim_snapshot(
&mut self.output_snapshot,
MAX_ROWS.saturating_sub(self.command_rows).max(1),
0,
);
}

fn render(&self, cx: &App) -> AnyElement {
fn render(&self, on_cols_change: Option<ColsChangeHandler>, cx: &App) -> AnyElement {
let palette = TerminalPalette {
foreground: cx.theme().foreground,
background: cx.theme().background,
selection: cx.theme().primary.opacity(0.28),
};
let command = grid_element(&self.command_snapshot, self.command_rows, palette);
let highlights = highlight::highlight_source(
&self.displayed_command,
"bash",
&cx.theme().highlight_theme,
);
let command = h_flex()
.w_full()
.min_w_0()
.items_start()
.px_1()
.py_1()
.bg(cx.theme().tokens.colors.muted)
.font_family(cx.theme().mono_font_family.clone())
.text_size(px(13.))
.child(div().flex_none().text_color(cx.theme().primary).child("❯ "))
.child(div().flex_1().min_w_0().whitespace_normal().child(
StyledText::new(self.displayed_command.clone()).with_highlights(highlights),
));
let output = (self.output_rows > 0)
.then(|| grid_element(&self.output_snapshot, self.output_rows, palette));
.then(|| grid_element(&self.output_snapshot, self.output_rows, self.cols, palette));
let rendered_cols = self.cols;
div()
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.max_w_full()
.w_full()
.overflow_hidden()
.bg(palette.background)
.child(command)
.children(output)
.children(output.map(|output| div().mt_1().child(output)))
.when_some(on_cols_change, |panel, on_cols_change| {
panel.on_prepaint(move |bounds, window, cx| {
let cols = (f32::from(bounds.size.width) / TERMINAL_CELL_WIDTH)
.floor()
.max(0.) as usize;
let cols = cols.clamp(MIN_COLS, MAX_COLS);
if cols != rendered_cols {
on_cols_change(&cols, window, cx);
}
})
})
.into_any_element()
}
}

fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette) -> AnyElement {
fn grid_element(
snapshot: &TermSnapshot,
rows: usize,
cols: usize,
palette: TerminalPalette,
) -> AnyElement {
let paint_data = layout_grid(snapshot, palette, false, None, false, false);
canvas(
|_bounds, _window, _cx| (),
Expand All@@ -147,54 +237,46 @@ fn grid_element(snapshot: &TermSnapshot, rows: usize, palette: TerminalPalette)
});
},
)
.w(px(COLS as f32 * TERMINAL_CELL_WIDTH))
.w(px(cols as f32 * TERMINAL_CELL_WIDTH))
.h(px(rows as f32 * TERMINAL_CELL_HEIGHT))
.into_any_element()
}

fn command_snapshot(command: &str) -> (TermSnapshot, usize) {
let emulator = GridEmulator::with_size(COLS, MAX_COMMAND_ROWS);
emulator.feed(clamp_command(command).as_bytes());
let mut snapshot = emulator.snapshot();
let rows = trim_snapshot(&mut snapshot, MAX_COMMAND_ROWS, 1);
(snapshot, rows)
}

fn clamp_command(command: &str) -> String {
let mut result = String::new();
let mut row = 0;
let mut col = 0;
let mut chars = command.chars().peekable();
fn clamp_command(command: &str, cols: usize) -> (String, usize) {
let line_cols = cols.saturating_sub(PROMPT_COLS).max(1);
let mut lines = vec![String::new()];
let mut truncated = false;
let mut chars = command.chars().filter(|ch| *ch != '\r').peekable();
while let Some(ch) = chars.next() {
if ch == '\n' {
if row + 1 == MAX_COMMAND_ROWS && chars.peek().is_some() {
result.push('…');
if lines.len() == MAX_COMMAND_ROWS {
truncated = chars.peek().is_some();
break;
}
result.push_str("\r\n");
row += 1;
col = 0;
continue;
}
if ch == '\r' {
lines.push(String::new());
continue;
}
if col == COLS {
row += 1;
col = 0;
}
if row == MAX_COMMAND_ROWS {
result.push('…');
break;
if lines
.last()
.is_some_and(|line| line.chars().count() == line_cols)
{
if lines.len() == MAX_COMMAND_ROWS {
truncated = true;
break;
}
lines.push(String::new());
}
if row + 1 == MAX_COMMAND_ROWS && col + 1 == COLS && chars.peek().is_some() {
result.push('…');
break;
lines.last_mut().expect("command has one line").push(ch);
}
if truncated {
let last = lines.last_mut().expect("command has one line");
if last.chars().count() == line_cols {
last.pop();
}
result.push(ch);
col += 1;
last.push('…');
}
result
let rows = lines.len();
(lines.join("\n"), rows)
}

fn trim_snapshot(snapshot: &mut TermSnapshot, max_rows: usize, minimum: usize) -> usize {
Expand DownExpand Up@@ -248,19 +330,46 @@ mod tests {

#[test]
fn command_is_clamped_to_four_rows() {
let panel = CachedPanel::new(&"x".repeat(COLS * MAX_COMMAND_ROWS + 1), "");
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(
panel
.command_snapshot
.cell_text(MAX_COMMAND_ROWS - 1, COLS - 1)
.is_some_and(|text| text == "…")
let panel = CachedPanel::new(
&"x".repeat((DEFAULT_COLS - PROMPT_COLS) * MAX_COMMAND_ROWS + 1),
"",
);
assert_eq!(panel.command_rows, MAX_COMMAND_ROWS);
assert!(panel.displayed_command.ends_with('…'));
assert_eq!(panel.displayed_command.lines().count(), MAX_COMMAND_ROWS);
}

#[test]
fn trailing_blank_output_rows_are_trimmed() {
let panel = CachedPanel::new("printf one", "one\n\n");
assert_eq!(panel.output_rows, 1);
}

#[test]
fn bare_lf_returns_output_to_first_column() {
let panel = CachedPanel::new("cmd", "a\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
}

#[test]
fn split_crlf_is_not_double_converted() {
let mut panel = CachedPanel::new("cmd", "a\r");
panel.update("cmd", "a\r\nb");
assert_eq!(panel.output_snapshot.cell_text(1, 0), Some("b".to_string()));
assert_eq!(panel.output_rows, 2);
}

#[test]
fn output_wraps_at_the_configured_column_count() {
let output = "abcdefghijklmnopqrstuvwxy";
let narrow = CachedPanel::with_cols("cmd", output, 20);
let wide = CachedPanel::with_cols("cmd", output, 40);
assert_eq!(
narrow.output_snapshot.cell_text(1, 0),
Some("u".to_string())
);
assert_eq!(narrow.output_rows, 2);
assert_eq!(wide.output_snapshot.cell_text(0, 20), Some("u".to_string()));
assert_eq!(wide.output_rows, 1);
}
}
Loading