Skip to content
Closed
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
62 changes: 40 additions & 22 deletions packages/cli-rs/crates/mini/src/footers/permission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ pub struct Info {
pub title: String,
pub lines: Vec<String>,
pub diff: Option<String>,
/// `(label, file, diff)` for each file when a request edits more than one.
pub files: Vec<(String, String, String)>,
pub patch: Option<String>,
/// The file the diff belongs to, for its highlighting.
pub file: Option<String>,
Expand All @@ -163,26 +165,32 @@ pub fn info(request: &Request, format_path: &dyn Fn(&str) -> String, mono: bool)
&request.metadata,
format_path,
);
let files: Vec<(String, String, String)> =
info.files.into_iter().map(|(file, diff)| (format_path(&file), file, diff)).collect();
if !mono {
return Info {
icon: info.icon.to_owned(),
title: info.title,
lines: info.lines,
diff: info.diff,
files,
patch: info.patch,
file: info.file,
};
}
Info {
icon: mono_prefix(info.icon, true),
title: info.title,
lines: info
.diff
.or(info.patch)
.into_iter()
.chain(info.lines.iter().map(|line| mono_prefix(line, true)))
.collect(),
lines: if files.is_empty() {
info.diff.or(info.patch).into_iter().collect::<Vec<_>>()
} else {
files.into_iter().flat_map(|(label, _, diff)| [label, diff]).collect()
}
.into_iter()
.chain(info.lines.iter().map(|line| mono_prefix(line, true)))
.collect(),
diff: None,
files: Vec::new(),
patch: None,
file: None,
}
Expand Down Expand Up @@ -339,23 +347,33 @@ pub fn paint(app: &App, root: &View, body: &Body<'_>) -> Painted {
);
// A diff draws as the scrollback draws an edit, a patch as highlighted text; narrow, both stay text.
if let Some(diff) = &info.diff {
if width >= 40 {
let syntax = body.run.syntax.clone().unwrap_or_default();
let filetype = info.file.as_deref().and_then(crate::tools::filetype);
let look = crate::tools::diff_look(&body.run.block, theme.text);
let diff = opencode_ui::diff::view_with(
app,
&look,
&syntax,
diff,
opentui::widget::DiffView::Unified,
filetype,
WrapMode::Word,
0,
);
content.add(&diff.shrink(0.0));
let shown = if info.files.is_empty() {
vec![(None, info.file.as_deref(), diff.as_str())]
} else {
content.add(&line(diff.clone(), theme.text));
info.files.iter().map(|(label, file, diff)| (Some(label), Some(file.as_str()), diff.as_str())).collect()
};
for (label, file, diff) in shown {
if let Some(label) = label {
content.add(&line(label.clone(), theme.muted));
}
if width >= 40 {
let syntax = body.run.syntax.clone().unwrap_or_default();
let filetype = file.and_then(crate::tools::filetype);
let look = crate::tools::diff_look(&body.run.block, theme.text);
let diff = opencode_ui::diff::view_with(
app,
&look,
&syntax,
diff,
opentui::widget::DiffView::Unified,
filetype,
WrapMode::Word,
0,
);
content.add(&diff.shrink(0.0));
} else {
content.add(&line(diff.to_owned(), theme.text));
}
}
} else if let Some(patch) = &info.patch {
match &body.run.syntax {
Expand Down
53 changes: 49 additions & 4 deletions packages/cli-rs/crates/ui/src/permission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pub struct Presentation {
pub title: String,
pub lines: Vec<String>,
pub diff: Option<String>,
/// `(file, diff)` for each file when a request edits more than one.
pub files: Vec<(String, String)>,
pub patch: Option<String>,
pub file: Option<String>,
}
Expand Down Expand Up @@ -42,14 +44,25 @@ pub fn presentation(
match ToolKind::of(action) {
ToolKind::Edit => {
let file = or(path, &first);
let files = metadata.get("files").and_then(Value::as_array);
let changed = dict(files.and_then(|files| files.first()).unwrap_or(&Value::Null));
let diff = some(or(&or(&text(&changed, "patch"), &text(&changed, "diff")), &text(&metadata, "diff")));
let entries = metadata.get("files").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let files: Vec<(String, String)> = entries
.iter()
.map(dict)
.filter_map(|entry| {
some(or(&text(&entry, "patch"), &text(&entry, "diff"))).map(|diff| (text(&entry, "file"), diff))
})
.collect();
let diff = files.first().map(|(_, diff)| diff.clone()).or_else(|| some(text(&metadata, "diff")));
Presentation {
icon: "→",
title: format!("Edit {}", format_path(&file)),
title: if entries.len() > 1 {
format!("Edit {} files", entries.len())
} else {
format!("Edit {}", format_path(&file))
},
patch: if diff.is_some() { None } else { EditInput(input).patch_text().non_empty().map(str::to_owned) },
diff,
files: if files.len() > 1 { files } else { Vec::new() },
file: Some(file),
..Presentation::default()
}
Expand Down Expand Up @@ -191,3 +204,35 @@ fn wildcard_directory(value: &str) -> String {
fn dict(value: &Value) -> Map<String, Value> {
value.as_object().cloned().unwrap_or_default()
}

#[cfg(test)]
mod tests {
use serde_json::json;

use super::presentation;

fn edit(metadata: serde_json::Value) -> super::Presentation {
presentation("edit", &["src/a.ts".to_owned()], None, &json!({}), &metadata, &|value| value.to_owned())
}

#[test]
fn multi_file_edit_keeps_every_file_diff() {
let info = edit(json!({
"diff": "combined",
"files": [{ "file": "src/a.ts", "patch": "a-diff" }, { "file": "src/b.ts", "patch": "b-diff" }],
}));
assert_eq!(info.title, "Edit 2 files");
assert_eq!(
info.files,
vec![("src/a.ts".to_owned(), "a-diff".to_owned()), ("src/b.ts".to_owned(), "b-diff".to_owned())]
);
}

#[test]
fn single_file_edit_keeps_title_and_diff() {
let info = edit(json!({ "files": [{ "file": "src/a.ts", "patch": "a-diff" }] }));
assert_eq!(info.title, "Edit src/a.ts");
assert_eq!(info.diff.as_deref(), Some("a-diff"));
assert!(info.files.is_empty());
}
}
74 changes: 42 additions & 32 deletions packages/tui/src/mini/footer.permission.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
type PermissionOption,
} from "./permission.shared"
import { stringWidth } from "../util/string-width"
import { toolFiletype } from "./tool"
import { toolFiletype, toolPath } from "./tool"
import { transparent, type RunBlockTheme, type RunFooterTheme } from "./theme"
import type { MiniPermissionRequest, PermissionReply } from "./types"
import { PatchDiff } from "../component/patch-diff"
Expand Down Expand Up @@ -155,7 +155,6 @@ export function RunPermissionBody(props: {
const [state, setState] = createSignal(createPermissionBodyState(props.request))
const stage = createMemo(() => state().stage)
const info = createMemo(() => permissionInfo(props.request, props.directory?.(), props.mono))
const ft = createMemo(() => toolFiletype(info().file))
let scroll: ScrollBoxRenderable | undefined
const scrollbar = createMemo(() => ({
visible: !props.mono,
Expand Down Expand Up @@ -453,36 +452,47 @@ export function RunPermissionBody(props: {
</Show>
}
>
<Show
when={width() >= 40}
fallback={
<text width="100%" fg={props.theme.text} wrapMode="word" flexShrink={0}>
{info().diff}
</text>
}
>
<PatchDiff
diff={info().diff!}
hunkFg={props.block.diffLineNumber}
view="unified"
filetype={ft()}
syntaxStyle={props.block.syntax}
showLineNumbers={true}
width="100%"
flexShrink={0}
wrapMode="word"
fg={props.theme.text}
addedBg={props.block.diffAddedBg}
removedBg={props.block.diffRemovedBg}
contextBg={props.block.diffContextBg}
addedSignColor={props.block.diffHighlightAdded}
removedSignColor={props.block.diffHighlightRemoved}
lineNumberFg={props.block.diffLineNumber}
lineNumberBg={props.block.diffContextBg}
addedLineNumberBg={props.block.diffAddedLineNumberBg}
removedLineNumberBg={props.block.diffRemovedLineNumberBg}
/>
</Show>
<For each={info().files ?? [{ file: info().file ?? "", diff: info().diff! }]}>
{(item) => (
<box width="100%" flexDirection="column" flexShrink={0}>
<Show when={info().files}>
<text width="100%" fg={props.theme.muted} wrapMode="word" flexShrink={0}>
{toolPath(item.file, { home: true, directory: props.directory?.() })}
</text>
</Show>
<Show
when={width() >= 40}
fallback={
<text width="100%" fg={props.theme.text} wrapMode="word" flexShrink={0}>
{item.diff}
</text>
}
>
<PatchDiff
diff={item.diff}
hunkFg={props.block.diffLineNumber}
view="unified"
filetype={toolFiletype(item.file)}
syntaxStyle={props.block.syntax}
showLineNumbers={true}
width="100%"
flexShrink={0}
wrapMode="word"
fg={props.theme.text}
addedBg={props.block.diffAddedBg}
removedBg={props.block.diffRemovedBg}
contextBg={props.block.diffContextBg}
addedSignColor={props.block.diffHighlightAdded}
removedSignColor={props.block.diffHighlightRemoved}
lineNumberFg={props.block.diffLineNumber}
lineNumberBg={props.block.diffContextBg}
addedLineNumberBg={props.block.diffAddedLineNumberBg}
removedLineNumberBg={props.block.diffRemovedLineNumberBg}
/>
</Show>
</box>
)}
</For>
</Show>
<Show when={!info().diff && !info().patch && info().lines.length === 0}>
<text width="100%" fg={props.theme.muted} flexShrink={0}>
Expand Down
7 changes: 6 additions & 1 deletion packages/tui/src/mini/permission.shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,15 @@ export function permissionInfo(request: MiniPermissionRequest, directory?: strin
...info,
icon: monoPrefix(info.icon, true),
lines: [
...(info.diff || info.patch ? [info.diff ?? info.patch!] : []),
...(info.files
? info.files.flatMap((item) => [toolPath(item.file, { home: true, directory }), item.diff])
: info.diff || info.patch
? [info.diff ?? info.patch!]
: []),
...info.lines.map((line) => monoPrefix(line, true)),
],
diff: undefined,
files: undefined,
patch: undefined,
}
}
Expand Down
70 changes: 46 additions & 24 deletions packages/tui/src/routes/session/permission.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,21 @@ import { useToast } from "../../ui/toast"

type PermissionStage = "permission" | "reject"

function EditBody(props: { file?: string; diff?: string; patch?: string }) {
function EditBody(props: {
file?: string
diff?: string
files?: { file: string; diff: string }[]
patch?: string
formatPath: (value: string) => string
}) {
const theme = useTheme()
const themes = useThemes()
const syntax = themes.currentSyntax
const config = useConfig().data
const dimensions = useTerminalDimensions()

const filepath = createMemo(() => props.file ?? "")
const diff = createMemo(() => props.diff ?? "")
const files = createMemo(() => props.files ?? [{ file: props.file ?? "", diff: diff() }])

const view = createMemo(() => {
const diffView = config.diffs?.view
Expand All @@ -36,7 +42,6 @@ function EditBody(props: { file?: string; diff?: string; patch?: string }) {
return dimensions().width > 120 ? "split" : "unified"
})

const ft = createMemo(() => filetype(filepath()))
const scrollAcceleration = createMemo(() => getScrollAcceleration(config))

return (
Expand All @@ -52,26 +57,37 @@ function EditBody(props: { file?: string; diff?: string; patch?: string }) {
},
}}
>
<PatchDiff
diff={diff()}
hunkFg={theme.diff.text.hunkHeader}
view={view()}
filetype={ft()}
syntaxStyle={syntax()}
showLineNumbers={true}
width="100%"
wrapMode="word"
fg={theme.text.base}
addedBg={theme.diff.background.added}
removedBg={theme.diff.background.removed}
contextBg={theme.diff.background.context}
addedSignColor={theme.diff.highlight.added}
removedSignColor={theme.diff.highlight.removed}
lineNumberFg={theme.diff.lineNumber.text}
lineNumberBg={theme.diff.background.context}
addedLineNumberBg={theme.diff.lineNumber.background.added}
removedLineNumberBg={theme.diff.lineNumber.background.removed}
/>
<For each={files()}>
{(item) => (
<box flexDirection="column">
<Show when={props.files}>
<box paddingLeft={1}>
<text fg={theme.text.muted}>{props.formatPath(item.file)}</text>
</box>
</Show>
<PatchDiff
diff={item.diff}
hunkFg={theme.diff.text.hunkHeader}
view={view()}
filetype={filetype(item.file)}
syntaxStyle={syntax()}
showLineNumbers={true}
width="100%"
wrapMode="word"
fg={theme.text.base}
addedBg={theme.diff.background.added}
removedBg={theme.diff.background.removed}
contextBg={theme.diff.background.context}
addedSignColor={theme.diff.highlight.added}
removedSignColor={theme.diff.highlight.removed}
lineNumberFg={theme.diff.lineNumber.text}
lineNumberBg={theme.diff.background.context}
addedLineNumberBg={theme.diff.lineNumber.background.added}
removedLineNumberBg={theme.diff.lineNumber.background.removed}
/>
</box>
)}
</For>
</scrollbox>
</Show>
<Show when={!diff()}>
Expand Down Expand Up @@ -167,7 +183,13 @@ export function PermissionPrompt(props: { request: PermissionRequest; directory?
)
const presentationBody = () =>
props.request.action === "edit" ? (
<EditBody file={current.file} diff={current.diff} patch={current.patch} />
<EditBody
file={current.file}
diff={current.diff}
files={current.files}
patch={current.patch}
formatPath={pathFormatter.format}
/>
) : props.request.action === "external_directory" ? (
<Show when={current.lines.length > 0}>
<box paddingLeft={1} gap={1}>
Expand Down
Loading