diff --git a/Cargo.lock b/Cargo.lock index 03a7ca31b9d..f2f375f5ceb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1845,9 +1845,9 @@ dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", - "h2 0.4.12", + "h2 0.4.19", "http 1.3.1", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-rustls", "hyper-util", "pin-project-lite", @@ -7244,6 +7244,7 @@ dependencies = [ "time", "time_format", "tracing", + "tree-sitter-md", "ui", "ui_input", "unindent", @@ -7927,9 +7928,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.12" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" dependencies = [ "atomic-waker", "bytes 1.11.1", @@ -8424,21 +8425,20 @@ dependencies = [ [[package]] name = "hyper" -version = "1.7.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" dependencies = [ "atomic-waker", "bytes 1.11.1", "futures-channel", "futures-core", - "h2 0.4.12", + "h2 0.4.19", "http 1.3.1", "http-body 1.0.1", "httparse", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -8451,7 +8451,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http 1.3.1", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-util", "log", "rustls", @@ -8467,7 +8467,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 1.7.0", + "hyper 1.11.1", "hyper-util", "pin-project-lite", "tokio", @@ -8500,7 +8500,7 @@ dependencies = [ "futures-util", "http 1.3.1", "http-body 1.0.1", - "hyper 1.7.0", + "hyper 1.11.1", "ipnet", "libc", "percent-encoding", @@ -9772,6 +9772,7 @@ dependencies = [ "openai_subscribed", "opencode", "parking_lot", + "paths", "rand 0.9.4", "release_channel", "schemars 1.0.4", @@ -12262,7 +12263,7 @@ dependencies = [ "http 1.3.1", "http-body 1.0.1", "http-body-util", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-rustls", "hyper-timeout", "hyper-util", @@ -15434,7 +15435,7 @@ dependencies = [ "http 1.3.1", "http-body 1.0.1", "http-body-util", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-rustls", "hyper-util", "js-sys", @@ -16408,6 +16409,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "serde" version = "1.0.229" @@ -18108,6 +18115,7 @@ dependencies = [ "editor", "fuzzy", "gpui", + "indexmap 2.14.0", "log", "picker", "project", @@ -22694,8 +22702,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yawc" -version = "0.3.3" -source = "git+https://github.com/zed-industries/yawc?rev=71a452f551cac178367eaac5d7418a09afa1f3a2#71a452f551cac178367eaac5d7418a09afa1f3a2" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35e709a1923e34cf52d5b1466653b8da2f0360bccfbdd9870c5bf78732d4faad" dependencies = [ "base64 0.22.1", "bytes 1.11.1", @@ -22703,13 +22712,15 @@ dependencies = [ "futures 0.3.34", "getrandom 0.2.16", "http-body-util", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-util", "js-sys", "log", "nom 8.0.0", + "percent-encoding", "pin-project", "rand 0.8.6", + "send_wrapper", "sha1", "thiserror 2.0.17", "tokio", @@ -23072,11 +23083,11 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2 0.4.12", + "h2 0.4.19", "http 1.3.1", "http-body 1.0.1", "http-body-util", - "hyper 1.7.0", + "hyper 1.11.1", "hyper-rustls", "hyper-util", "ipnet", diff --git a/Cargo.toml b/Cargo.toml index 7a48f0ff58f..439822fab56 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -932,7 +932,7 @@ which = "8" windows-core = "0.62" windows-registry = "0.6.0" yaml-rust2 = "0.8" -yawc = { git = "https://github.com/zed-industries/yawc", rev = "71a452f551cac178367eaac5d7418a09afa1f3a2", version = "0.3.3" } +yawc = "0.4.2" zeroize = "1.8" zstd = "0.11" diff --git a/assets/keymaps/default-linux.json b/assets/keymaps/default-linux.json index 89fb803d58b..fcdc8f7a9c6 100644 --- a/assets/keymaps/default-linux.json +++ b/assets/keymaps/default-linux.json @@ -617,7 +617,7 @@ }, }, { - "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv)", + "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv || extension == jsonl || extension == ndjson)", "use_key_equivalents": true, "bindings": { "ctrl-k v": "tabular_data::OpenPreviewToTheSide", diff --git a/assets/keymaps/default-macos.json b/assets/keymaps/default-macos.json index 2226cb43eb0..1e6374ef661 100644 --- a/assets/keymaps/default-macos.json +++ b/assets/keymaps/default-macos.json @@ -656,7 +656,7 @@ }, }, { - "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv)", + "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv || extension == jsonl || extension == ndjson)", "use_key_equivalents": true, "bindings": { "cmd-k v": "tabular_data::OpenPreviewToTheSide", diff --git a/assets/keymaps/default-windows.json b/assets/keymaps/default-windows.json index 56aa6d3a508..c9c5f90af42 100644 --- a/assets/keymaps/default-windows.json +++ b/assets/keymaps/default-windows.json @@ -615,7 +615,7 @@ }, }, { - "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv)", + "context": "Editor && (extension == csv || extension == tsv || extension == ssv || extension == psv || extension == jsonl || extension == ndjson)", "use_key_equivalents": true, "bindings": { "ctrl-k v": "tabular_data::OpenPreviewToTheSide", diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index 91814582145..e22a738ec04 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -399,7 +399,6 @@ pub enum AgentThreadEntry { AssistantMessage(AssistantMessage), ToolCall(ToolCall), Elicitation(ElicitationEntryId), - CompletedPlan(Vec), ContextCompaction(ContextCompaction), } @@ -863,7 +862,6 @@ impl AgentThreadEntry { Self::AssistantMessage(message) => message.indented, Self::ToolCall(_) => false, Self::Elicitation(_) => false, - Self::CompletedPlan(_) => false, Self::ContextCompaction(_) => false, } } @@ -874,14 +872,6 @@ impl AgentThreadEntry { Self::AssistantMessage(message) => message.to_markdown(cx), Self::ToolCall(tool_call) => tool_call.to_markdown(cx), Self::Elicitation(_) => "## Input Requested\n\n".to_string(), - Self::CompletedPlan(entries) => { - let mut md = String::from("## Plan\n\n"); - for entry in entries { - let source = entry.content.read(cx).source().to_string(); - md.push_str(&format!("- [x] {}\n", source)); - } - md - } Self::ContextCompaction(compaction) => { let status = match &compaction.status { ContextCompactionStatus::InProgress => "In Progress", @@ -953,13 +943,14 @@ pub struct ToolCall { pub label: Entity, title: Option, pub kind: acp_v1::ToolKind, - pub content: Vec, + structured_content: Vec, pub status: ToolCallStatus, pub locations: Vec, pub resolved_locations: Vec>, pub raw_input: Option, pub raw_input_markdown: Option>, pub raw_output: Option, + raw_output_content: Option>, pub tool_name: Option, pub subagent_session_info: Option, pub sandbox_authorization_details: Option, @@ -1010,28 +1001,30 @@ impl ToolCall { title.as_ref(), tool_name.as_ref(), tool_call.kind, - language_registry, + language_registry.clone(), cx, ); - let result = Self { + let mut result = Self { id: tool_call.tool_call_id, label, title, kind: tool_call.kind, - content, + structured_content: content, locations: tool_call.locations, resolved_locations: Vec::default(), status, raw_input: tool_call.raw_input, raw_input_markdown, raw_output: tool_call.raw_output, + raw_output_content: None, tool_name, subagent_session_info, sandbox_authorization_details, sandbox_fallback_authorization_details, sandbox_not_applied, }; + result.update_raw_output_content(&language_registry, cx); Ok(result) } @@ -1094,6 +1087,7 @@ impl ToolCall { raw_output, .. } = fields; + let output_changed = content.is_some() || raw_output.is_some(); let was_plain_text = self.title.is_none() || self.kind == acp_v1::ToolKind::Execute; let mut label_changed = title.is_some() || kind.is_some(); @@ -1169,7 +1163,7 @@ impl ToolCall { let mut content = content.into_iter(); // Reuse existing content if we can - for (old, new) in self.content.iter_mut().zip(content.by_ref()) { + for (old, new) in self.structured_content.iter_mut().zip(content.by_ref()) { let valid_content = old.update_from_acp(new, language_registry.clone(), terminals, cx)?; if !valid_content { @@ -1180,12 +1174,12 @@ impl ToolCall { if let Some(new) = ToolCallContent::from_acp(new, language_registry.clone(), terminals, cx)? { - self.content.push(new); + self.structured_content.push(new); } else { new_content_len -= 1; } } - self.content.truncate(new_content_len); + self.structured_content.truncate(new_content_len); } if let Some(locations) = locations { @@ -1198,19 +1192,51 @@ impl ToolCall { } if let Some(raw_output) = raw_output { - if self.content.is_empty() - && let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx) - { - self.content - .push(ToolCallContent::ContentBlock(ContentBlock::from_markdown( - markdown, - ))); - } self.raw_output = Some(raw_output); } + if output_changed { + self.update_raw_output_content(&language_registry, cx); + } Ok(()) } + fn update_raw_output_content( + &mut self, + language_registry: &Arc, + cx: &mut App, + ) { + if !self.structured_content.is_empty() { + self.raw_output_content = None; + return; + } + let Some(text) = self.raw_output.as_ref().and_then(raw_output_text) else { + self.raw_output_content = None; + return; + }; + if let Some(ToolCallContent::ContentBlock(block)) = self.raw_output_content.as_deref() + && let Some(markdown) = block.markdown() + { + update_markdown_in_place(markdown, &text, cx); + } else { + let markdown = + cx.new(|cx| Markdown::new(text.into(), Some(language_registry.clone()), None, cx)); + self.raw_output_content = Some(Box::new(ToolCallContent::ContentBlock( + ContentBlock::from_markdown(markdown), + ))); + } + } + + pub fn content(&self) -> &[ToolCallContent] { + if self.structured_content.is_empty() { + self.raw_output_content + .as_deref() + .map(std::slice::from_ref) + .unwrap_or_default() + } else { + &self.structured_content + } + } + fn update_status(&mut self, status: ToolCallStatus) { match status { ToolCallStatus::Pending => self.update_acp_status(acp_v1::ToolCallStatus::Pending), @@ -1239,19 +1265,23 @@ impl ToolCall { } pub fn diffs(&self) -> impl Iterator> { - self.content.iter().filter_map(|content| match content { - ToolCallContent::Diff(diff) => Some(diff), - ToolCallContent::ContentBlock(_) => None, - ToolCallContent::Terminal(_) => None, - }) + self.structured_content + .iter() + .filter_map(|content| match content { + ToolCallContent::Diff(diff) => Some(diff), + ToolCallContent::ContentBlock(_) => None, + ToolCallContent::Terminal(_) => None, + }) } pub fn terminals(&self) -> impl Iterator> { - self.content.iter().filter_map(|content| match content { - ToolCallContent::Terminal(terminal) => Some(terminal), - ToolCallContent::ContentBlock(_) => None, - ToolCallContent::Diff(_) => None, - }) + self.structured_content + .iter() + .filter_map(|content| match content { + ToolCallContent::Terminal(terminal) => Some(terminal), + ToolCallContent::ContentBlock(_) => None, + ToolCallContent::Diff(_) => None, + }) } pub fn is_subagent(&self) -> bool { @@ -1267,7 +1297,7 @@ impl ToolCall { label.to_string() }; let mut markdown = format!("**Tool Call: {}**\nStatus: {}\n\n", label, self.status); - for content in &self.content { + for content in self.content() { markdown.push_str(content.to_markdown(cx).as_str()); markdown.push_str("\n\n"); } @@ -1799,15 +1829,7 @@ impl ContentBlock { let acp_v2::ContentBlock::Text(text_content) = block else { return false; }; - let new_content = &text_content.text; - markdown.update(cx, |markdown, cx| { - let current = markdown.source().to_string(); - match new_content.strip_prefix(¤t) { - Some("") => {} - Some(suffix) => markdown.append(suffix, cx), - None => markdown.reset(new_content.clone().into(), cx), - } - }); + update_markdown_in_place(markdown, &text_content.text, cx); true } @@ -2969,7 +2991,6 @@ impl AcpThread { AgentThreadEntry::ToolCall(_) | AgentThreadEntry::Elicitation(_) | AgentThreadEntry::AssistantMessage(_) - | AgentThreadEntry::CompletedPlan(_) | AgentThreadEntry::ContextCompaction(_) => {} } } @@ -2999,7 +3020,6 @@ impl AcpThread { AgentThreadEntry::ToolCall(_) | AgentThreadEntry::Elicitation(_) | AgentThreadEntry::AssistantMessage(_) - | AgentThreadEntry::CompletedPlan(_) | AgentThreadEntry::ContextCompaction(_) => {} } } @@ -3020,7 +3040,6 @@ impl AcpThread { AgentThreadEntry::ToolCall(_) | AgentThreadEntry::Elicitation(_) | AgentThreadEntry::AssistantMessage(_) - | AgentThreadEntry::CompletedPlan(_) | AgentThreadEntry::ContextCompaction(_) => {} } } @@ -3033,7 +3052,6 @@ impl AcpThread { match entry { AgentThreadEntry::UserMessage(..) => return false, AgentThreadEntry::AssistantMessage(..) - | AgentThreadEntry::CompletedPlan(..) | AgentThreadEntry::ContextCompaction(_) | AgentThreadEntry::Elicitation(_) => continue, AgentThreadEntry::ToolCall(..) => return true, @@ -3713,17 +3731,16 @@ impl AcpThread { label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)), title: Some("Tool call not found".into()), kind: acp_v1::ToolKind::Fetch, - content: vec![ToolCallContent::ContentBlock(ContentBlock::new_output( - "Tool call not found".into(), - &languages, - cx, - ))], + structured_content: vec![ToolCallContent::ContentBlock( + ContentBlock::new_output("Tool call not found".into(), &languages, cx), + )], status: ToolCallStatus::Failed, locations: Vec::new(), resolved_locations: Vec::new(), raw_input: None, raw_input_markdown: None, raw_output: None, + raw_output_content: None, tool_name: None, subagent_session_info: None, sandbox_authorization_details: None, @@ -3752,13 +3769,16 @@ impl AcpThread { } } ToolCallUpdate::UpdateDiff(update) => { - call.content.clear(); - call.content.push(ToolCallContent::Diff(update.diff)); + call.structured_content.clear(); + call.structured_content + .push(ToolCallContent::Diff(update.diff)); + call.update_raw_output_content(&languages, cx); } ToolCallUpdate::UpdateTerminal(update) => { - call.content.clear(); - call.content + call.structured_content.clear(); + call.structured_content .push(ToolCallContent::Terminal(update.terminal)); + call.update_raw_output_content(&languages, cx); } } @@ -4191,13 +4211,6 @@ impl AcpThread { cx.notify(); } - pub fn snapshot_completed_plan(&mut self, cx: &mut Context) { - if !self.plan.is_empty() && self.plan.stats().pending == 0 { - let completed_entries = std::mem::take(&mut self.plan.entries); - self.push_entry(AgentThreadEntry::CompletedPlan(completed_entries), cx); - } - } - fn clear_completed_plan_entries(&mut self, cx: &mut Context) { self.plan .entries @@ -4437,10 +4450,6 @@ impl AcpThread { this.cancel_pending_turn_entries(cx); } - if !canceled { - this.snapshot_completed_plan(cx); - } - // Handle refusal - distinguish between user prompt and tool call refusals if let acp_v1::StopReason::Refusal = r.stop_reason { this.had_error = true; @@ -5385,45 +5394,33 @@ fn markdown_for_raw_output( language_registry: &Arc, cx: &mut App, ) -> Option> { + let text = raw_output_text(raw_output)?; + Some(cx.new(|cx| Markdown::new(text.into(), Some(language_registry.clone()), None, cx))) +} + +fn raw_output_text(raw_output: &serde_json::Value) -> Option { match raw_output { serde_json::Value::Null => None, - serde_json::Value::Bool(value) => Some(cx.new(|cx| { - Markdown::new( - value.to_string().into(), - Some(language_registry.clone()), - None, - cx, - ) - })), - serde_json::Value::Number(value) => Some(cx.new(|cx| { - Markdown::new( - value.to_string().into(), - Some(language_registry.clone()), - None, - cx, - ) - })), - serde_json::Value::String(value) => Some(cx.new(|cx| { - Markdown::new( - value.clone().into(), - Some(language_registry.clone()), - None, - cx, - ) - })), - value => Some(cx.new(|cx| { + serde_json::Value::Bool(value) => Some(value.to_string()), + serde_json::Value::Number(value) => Some(value.to_string()), + serde_json::Value::String(value) => Some(value.clone()), + value => { let pretty_json = to_string_pretty(value).unwrap_or_else(|_| value.to_string()); - - Markdown::new( - format!("```json\n{}\n```", pretty_json).into(), - Some(language_registry.clone()), - None, - cx, - ) - })), + Some(format!("```json\n{}\n```", pretty_json)) + } } } +fn update_markdown_in_place(markdown: &Entity, text: &str, cx: &mut App) { + markdown.update(cx, |markdown, cx| { + match text.strip_prefix(markdown.source().as_ref()) { + Some("") => {} + Some(suffix) => markdown.append(suffix, cx), + None => markdown.reset(text.to_owned().into(), cx), + } + }); +} + #[cfg(test)] mod tests { use super::*; @@ -8365,6 +8362,167 @@ mod tests { } } + #[gpui::test] + fn test_tool_call_raw_output_creation_and_updates_export_latest_content( + cx: &mut TestAppContext, + ) { + init_test(cx); + let languages = + cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone()))); + let mut created_with_raw_output = cx.update(|cx| { + ToolCall::from_acp( + acp_v1::ToolCall::new("created", "Tool").raw_output(serde_json::json!("first")), + ToolCallStatus::Pending, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("raw-only tool call should convert") + }); + let mut updated_with_raw_output = cx.update(|cx| { + ToolCall::from_acp( + acp_v1::ToolCall::new("updated", "Tool"), + ToolCallStatus::Pending, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("empty tool call should convert") + }); + + let created_export = cx.read(|cx| created_with_raw_output.to_markdown(cx)); + cx.update(|cx| { + updated_with_raw_output + .update_fields( + acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("first")), + None, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("first raw output update should apply"); + }); + let first_update_export = cx.read(|cx| updated_with_raw_output.to_markdown(cx)); + let Some(ToolCallContent::ContentBlock(block)) = updated_with_raw_output.content().first() + else { + panic!("expected raw output content"); + }; + let raw_markdown = block + .markdown() + .expect("raw output should be Markdown") + .clone(); + cx.update(|cx| { + created_with_raw_output + .update_fields( + acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")), + None, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("second raw output update should apply"); + updated_with_raw_output + .update_fields( + acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")), + None, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("second raw output update should apply"); + }); + let latest_exports = cx.read(|cx| { + assert_eq!(raw_markdown.read(cx).source(), "second"); + ( + created_with_raw_output.to_markdown(cx), + updated_with_raw_output.to_markdown(cx), + ) + }); + assert_eq!( + (created_export, first_update_export, latest_exports), + ( + "**Tool Call: Tool**\nStatus: Pending\n\nfirst\n\n".to_string(), + "**Tool Call: Tool**\nStatus: Pending\n\nfirst\n\n".to_string(), + ( + "**Tool Call: Tool**\nStatus: Pending\n\nsecond\n\n".to_string(), + "**Tool Call: Tool**\nStatus: Pending\n\nsecond\n\n".to_string(), + ), + ) + ); + } + + #[gpui::test] + fn test_tool_call_clearing_structured_content_restores_retained_raw_output( + cx: &mut TestAppContext, + ) { + init_test(cx); + let languages = + cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone()))); + let mut call = cx.update(|cx| { + ToolCall::from_acp( + acp_v1::ToolCall::new("tool", "Tool") + .content(vec!["structured".into()]) + .raw_output(serde_json::json!("raw")), + ToolCallStatus::Pending, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("tool call should convert") + }); + cx.read(|cx| { + assert_eq!( + call.to_markdown(cx), + "**Tool Call: Tool**\nStatus: Pending\n\nstructured\n\n" + ); + }); + cx.update(|cx| { + call.update_fields( + acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("new raw")), + None, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("raw output should update without replacing structured content"); + assert_eq!( + call.to_markdown(cx), + "**Tool Call: Tool**\nStatus: Pending\n\nstructured\n\n" + ); + }); + cx.update(|cx| { + call.update_fields( + acp_v1::ToolCallUpdateFields::new().content(vec![]), + None, + languages.clone(), + &HashMap::default(), + cx, + ) + .expect("clearing structured content should apply"); + }); + cx.read(|cx| { + assert_eq!(call.raw_output, Some(serde_json::json!("new raw"))); + assert_eq!( + call.to_markdown(cx), + "**Tool Call: Tool**\nStatus: Pending\n\nnew raw\n\n" + ); + }); + cx.update(|cx| { + call.update_fields( + acp_v1::ToolCallUpdateFields::new().content(vec!["replacement".into()]), + None, + languages, + &HashMap::default(), + cx, + ) + .expect("structured content should replace the raw fallback"); + assert_eq!( + call.to_markdown(cx), + "**Tool Call: Tool**\nStatus: Pending\n\nreplacement\n\n" + ); + }); + } + #[gpui::test] async fn test_tool_call_name_precedence_and_updates(cx: &mut TestAppContext) { init_test(cx); @@ -8645,8 +8803,8 @@ mod tests { tool_call.status, ToolCallStatus::WaitingForConfirmation { .. } )); - assert_eq!(tool_call.content.len(), 1); - assert_eq!(tool_call.content[0].to_markdown(cx), "updated content"); + assert_eq!(tool_call.content().len(), 1); + assert_eq!(tool_call.content()[0].to_markdown(cx), "updated content"); }); thread @@ -8673,8 +8831,8 @@ mod tests { tool_call.status, ToolCallStatus::WaitingForConfirmation { .. } )); - assert_eq!(tool_call.content.len(), 1); - assert_eq!(tool_call.content[0].to_markdown(cx), "updated again"); + assert_eq!(tool_call.content().len(), 1); + assert_eq!(tool_call.content()[0].to_markdown(cx), "updated again"); }); let selected_outcome = SelectedPermissionOutcome::new( @@ -8724,8 +8882,8 @@ mod tests { .expect("tool call should exist"); assert_eq!(tool_call.label.read(cx).source(), "Completed"); assert!(matches!(tool_call.status, ToolCallStatus::Completed)); - assert_eq!(tool_call.content.len(), 1); - assert_eq!(tool_call.content[0].to_markdown(cx), "done"); + assert_eq!(tool_call.content().len(), 1); + assert_eq!(tool_call.content()[0].to_markdown(cx), "done"); }); } @@ -11289,12 +11447,12 @@ mod tests { assert_eq!(tool_call.kind, acp_v1::ToolKind::Fetch); // Check that the content contains the error message - assert_eq!(tool_call.content.len(), 1); - if let ToolCallContent::ContentBlock(content_block) = &tool_call.content[0] { + assert_eq!(tool_call.content().len(), 1); + if let ToolCallContent::ContentBlock(content_block) = &tool_call.content()[0] { let markdown = content_block.plain_markdown().expect("expected markdown"); assert!(markdown.read(cx).source().contains("Tool call not found")); } else { - panic!("Expected ContentBlock, got: {:?}", tool_call.content[0]); + panic!("Expected ContentBlock, got: {:?}", tool_call.content()[0]); } } else { panic!("Expected ToolCall entry, got: {:?}", thread.entries[0]); diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs index f64fb289965..bee3f904346 100644 --- a/crates/agent/src/agent.rs +++ b/crates/agent/src/agent.rs @@ -1729,9 +1729,6 @@ impl NativeAgent { }) .await .map_err(Arc::new)?; - acp_thread.update(cx, |thread, cx| { - thread.snapshot_completed_plan(cx); - }); Ok(acp_thread) } }) diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs index fdd16eb3281..c93e11d031f 100644 --- a/crates/agent/src/tests/mod.rs +++ b/crates/agent/src/tests/mod.rs @@ -4197,9 +4197,11 @@ async fn test_building_request_with_pending_tools(cx: &mut TestAppContext) { async fn test_agent_connection(cx: &mut TestAppContext) { cx.update(settings::init); let templates = Templates::new(); + let fake_fs = fs::FakeFs::new(cx.background_executor.clone()); // Initialize language model system with test provider cx.update(|cx| { + ::set_global(fake_fs.clone(), cx); gpui_tokio::init(cx); let http_client = FakeHttpClient::with_404_response(); @@ -4214,7 +4216,6 @@ async fn test_agent_connection(cx: &mut TestAppContext) { cx.executor().forbid_parking(); // Create a project for new_thread - let fake_fs = cx.update(|cx| fs::FakeFs::new(cx.background_executor().clone())); fake_fs.insert_tree(path!("/test"), json!({})).await; let project = Project::test(fake_fs.clone(), [Path::new("/test")], cx).await; let cwd = PathList::new(&[Path::new("/test")]); @@ -4950,6 +4951,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest { match model { TestModel::Fake => {} TestModel::Sonnet4 => { + ::set_global(fs.clone(), cx); gpui_tokio::init(cx); let http_client = ReqwestClient::user_agent("agent tests").unwrap(); cx.set_http_client(Arc::new(http_client)); diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index be234e5147b..f8dbde992b2 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -1652,8 +1652,6 @@ impl Thread { let Some(tool) = tool else { // Tool not found (e.g., MCP server not connected after restart), // but still display the saved result if available. - // We need to send both ToolCall and ToolCallUpdate events because the UI - // only converts raw_output to displayable content in update_fields, not from_acp. stream .sender .unbounded_send(Ok(ThreadEvent::ToolCall( diff --git a/crates/agent/src/tools/evals/edit_file.rs b/crates/agent/src/tools/evals/edit_file.rs index 73e449fa3cd..124664fd39d 100644 --- a/crates/agent/src/tools/evals/edit_file.rs +++ b/crates/agent/src/tools/evals/edit_file.rs @@ -235,6 +235,7 @@ impl EditToolTest { let fs = FakeFs::new(cx.executor()); cx.update(|cx| { + ::set_global(fs.clone(), cx); let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| { diff --git a/crates/agent/src/tools/evals/terminal_tool.rs b/crates/agent/src/tools/evals/terminal_tool.rs index 463a95975ae..03b6c3a07c2 100644 --- a/crates/agent/src/tools/evals/terminal_tool.rs +++ b/crates/agent/src/tools/evals/terminal_tool.rs @@ -154,6 +154,7 @@ impl TerminalToolTest { cx.executor().allow_parking(); cx.update(|cx| { + ::set_global(fs::FakeFs::new(cx.background_executor().clone()), cx); let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); diff --git a/crates/agent/src/tools/evals/write_file.rs b/crates/agent/src/tools/evals/write_file.rs index 739b251770a..4c471ab61af 100644 --- a/crates/agent/src/tools/evals/write_file.rs +++ b/crates/agent/src/tools/evals/write_file.rs @@ -77,6 +77,7 @@ impl WriteToolTest { let fs = FakeFs::new(cx.executor()); cx.update(|cx| { + ::set_global(fs.clone(), cx); let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| { diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index f5ebfd73328..859cf7bbd32 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -4326,7 +4326,6 @@ exit 7 acp_thread::AgentThreadEntry::AssistantMessage(_) => "assistant", acp_thread::AgentThreadEntry::ToolCall(_) => "tool_call", acp_thread::AgentThreadEntry::Elicitation(_) => "elicitation", - acp_thread::AgentThreadEntry::CompletedPlan(_) => "plan", acp_thread::AgentThreadEntry::ContextCompaction(_) => "compaction", }) .collect::>() diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rs index 6fb97b915e7..7087e5b539e 100644 --- a/crates/agent_servers/src/e2e_tests.rs +++ b/crates/agent_servers/src/e2e_tests.rs @@ -230,8 +230,7 @@ pub async fn test_tool_call_with_permission( full_turn.await.unwrap(); thread.read_with(cx, |thread, cx| { - let AgentThreadEntry::ToolCall(ToolCall { - content, + let AgentThreadEntry::ToolCall(tool_call @ ToolCall { status: ToolCallStatus::Pending | ToolCallStatus::InProgress | ToolCallStatus::Completed, @@ -246,7 +245,7 @@ pub async fn test_tool_call_with_permission( }; assert!( - content.iter().any(|c| c.to_markdown(cx).contains("Hello")), + tool_call.content().iter().any(|content| content.to_markdown(cx).contains("Hello")), "Expected content to contain 'Hello'" ); }); diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 271f6c657c3..05b7dbf454c 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -5986,7 +5986,7 @@ pub(crate) mod tests { } #[gpui::test] - async fn test_completed_plan_snapshot_keeps_list_state_in_sync(cx: &mut TestAppContext) { + async fn test_plan_completion_does_not_add_transcript_entries(cx: &mut TestAppContext) { init_test(cx); let connection = StubAgentConnection::new(); @@ -6001,10 +6001,12 @@ pub(crate) mod tests { }); cx.run_until_parked(); - let session_id = active_thread(&conversation_view, cx).read_with(cx, |view, cx| { - assert_thread_list_item_count_matches_entries(view, cx); - view.thread.read(cx).session_id().clone() - }); + let (session_id, entry_count) = + active_thread(&conversation_view, cx).read_with(cx, |view, cx| { + assert_thread_list_item_count_matches_entries(view, cx); + let thread = view.thread.read(cx); + (thread.session_id().clone(), thread.entries().len()) + }); cx.update(|_, cx| { connection.send_update( @@ -6018,8 +6020,15 @@ pub(crate) mod tests { ); }); cx.run_until_parked(); - active_thread(&conversation_view, cx).read_with(cx, |view, cx| { - assert_thread_list_item_count_matches_entries(view, cx); + let plan_content = active_thread(&conversation_view, cx).read_with(cx, |view, cx| { + view.thread + .read(cx) + .plan() + .entries + .first() + .expect("active plan entry") + .content + .clone() }); cx.update(|_, cx| { @@ -6038,11 +6047,84 @@ pub(crate) mod tests { assert_thread_list_item_count_matches_entries(view, cx); }); - connection.end_turn(session_id, acp_v1::StopReason::EndTurn); + connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn); cx.run_until_parked(); active_thread(&conversation_view, cx).read_with(cx, |view, cx| { assert_thread_list_item_count_matches_entries(view, cx); + let thread = view.thread.read(cx); + assert_eq!(thread.status(), ThreadStatus::Idle); + assert_eq!(thread.entries().len(), entry_count); + assert_eq!(thread.plan().stats().completed, 1); + assert_eq!(thread.plan().stats().pending, 0); + assert_eq!( + thread + .plan() + .entries + .first() + .expect("completed plan entry") + .content, + plan_content + ); }); + + cx.update(|_, cx| { + connection.send_update( + session_id.clone(), + acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new( + "Revise the thing", + acp_v1::PlanEntryPriority::High, + acp_v1::PlanEntryStatus::InProgress, + )])), + cx, + ); + }); + cx.run_until_parked(); + active_thread(&conversation_view, cx).read_with(cx, |view, cx| { + assert_thread_list_item_count_matches_entries(view, cx); + let thread = view.thread.read(cx); + let entry = thread.plan().entries.first().expect("reopened plan entry"); + assert_eq!(entry.content, plan_content); + assert_eq!(entry.content.read(cx).source(), "Revise the thing"); + assert_eq!(thread.plan().stats().pending, 1); + assert_eq!(thread.entries().len(), entry_count); + }); + + active_thread(&conversation_view, cx).update(cx, |view, cx| { + view.thread.update(cx, |thread, cx| { + thread.clear_plan(cx); + assert!(thread.plan().is_empty()); + assert_eq!(thread.entries().len(), entry_count); + }); + }); + cx.update(|_, cx| { + connection.send_update( + session_id.clone(), + acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new( + "Another task", + acp_v1::PlanEntryPriority::Medium, + acp_v1::PlanEntryStatus::Completed, + )])), + cx, + ); + }); + cx.run_until_parked(); + active_thread(&conversation_view, cx).read_with(cx, |view, cx| { + assert_eq!(view.thread.read(cx).plan().stats().completed, 1); + }); + + message_editor(&conversation_view, cx).update_in(cx, |editor, window, cx| { + editor.set_text("Continue", window, cx); + }); + active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| { + view.send(window, cx); + }); + cx.run_until_parked(); + active_thread(&conversation_view, cx).read_with(cx, |view, cx| { + assert_thread_list_item_count_matches_entries(view, cx); + assert!(view.thread.read(cx).plan().is_empty()); + }); + connection.end_turn(session_id, acp_v1::StopReason::EndTurn); + cx.run_until_parked(); } async fn setup_conversation_view_with_initial_content( @@ -8077,6 +8159,41 @@ pub(crate) mod tests { 2, "all Markdown leaves in replacement tool output should be searchable", ); + + for (fields, expected_matches) in [ + ( + acp_v1::ToolCallUpdateFields::new() + .content(vec![]) + .raw_output(serde_json::json!("Raw mango")), + 1, + ), + ( + acp_v1::ToolCallUpdateFields::new() + .raw_output(serde_json::json!("Raw mango mango")), + 2, + ), + ] { + thread + .update(cx, |thread, cx| { + thread.handle_session_update( + acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new( + "search-tool-content", + fields, + )), + cx, + ) + }) + .expect("raw output update should apply"); + cx.run_until_parked(); + cx.executor() + .advance_clock(super::thread_search_bar::SEARCH_UPDATE_DEBOUNCE * 2); + cx.run_until_parked(); + assert_eq!( + bar.read_with(cx, |bar, _| bar.match_count()), + expected_matches, + "expanded tool search should track the latest raw fallback", + ); + } } #[gpui::test] diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs index d0b66a70dc6..437c3babb2f 100644 --- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs +++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs @@ -909,7 +909,7 @@ fn collect_markdowns( if entry_view_state.is_tool_call_expanded(&tool_call.id) { out.extend( tool_call - .content + .content() .iter() .filter_map(|content| match content { ToolCallContent::ContentBlock(content) => content.markdown().cloned(), @@ -918,9 +918,6 @@ fn collect_markdowns( ); } } - AgentThreadEntry::CompletedPlan(entries) => { - out.extend(entries.iter().map(|e| e.content.clone())) - } AgentThreadEntry::ContextCompaction(compaction) => out.extend(compaction_markdowns( compaction, entry_view_state.is_compaction_expanded(entry_ix), diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 68dd31305ef..774bb46090f 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -1,6 +1,5 @@ use crate::{ DEFAULT_THREAD_TITLE, SelectPermissionGranularity, - agent_configuration::configure_context_server_modal::default_markdown_style, conversation_view::thread_search_bar::{ThreadSearchBar, ThreadSearchBarEvent}, open_abs_path_at_point, thread_metadata_store::{ThreadId, ThreadMetadataStore}, @@ -9,7 +8,7 @@ use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2}; use std::cell::RefCell; use acp_thread::{ - Elicitation, ElicitationEntryId, ElicitationStatus, PlanEntry, SandboxAuthorizationDetails, + Elicitation, ElicitationEntryId, ElicitationStatus, SandboxAuthorizationDetails, SandboxFallbackAuthorizationDetails, SandboxNotAppliedReason, decode_path_escapes, }; use agent::{ @@ -3895,76 +3894,6 @@ impl ThreadView { .into_any_element() } - fn render_completed_plan( - &self, - entries: &[PlanEntry], - window: &Window, - cx: &Context, - ) -> AnyElement { - v_flex() - .px_5() - .py_1p5() - .w_full() - .child( - v_flex() - .w_full() - .rounded_md() - .border_1() - .border_color(self.tool_card_border_color(cx)) - .child( - h_flex() - .px_2() - .py_1() - .gap_1() - .bg(self.tool_card_header_bg(cx)) - .border_b_1() - .border_color(self.tool_card_border_color(cx)) - .child( - Label::new("Completed Plan") - .size(LabelSize::Small) - .color(Color::Muted), - ) - .child( - Label::new(format!( - "— {} {}", - entries.len(), - if entries.len() == 1 { "step" } else { "steps" } - )) - .size(LabelSize::Small) - .color(Color::Muted), - ), - ) - .child( - v_flex().children(entries.iter().enumerate().map(|(index, entry)| { - h_flex() - .py_1() - .px_2() - .gap_1p5() - .when(index < entries.len() - 1, |this| { - this.border_b_1().border_color(cx.theme().colors().border) - }) - .child( - Icon::new(IconName::TodoComplete) - .size(IconSize::Small) - .color(Color::Success), - ) - .child( - div() - .max_w_full() - .overflow_x_hidden() - .text_xs() - .text_color(cx.theme().colors().text_muted) - .child(MarkdownElement::new( - entry.content.clone(), - default_markdown_style(window, cx), - )), - ) - })), - ), - ) - .into_any() - } - fn render_context_compaction( &self, entry_ix: usize, @@ -6456,7 +6385,7 @@ impl ThreadView { // renders as a useless "Canceled" card — hide those entirely. if matches!(tool_call.status, ToolCallStatus::Canceled) { let has_visible_content = - tool_call.content.iter().any(|content| match content { + tool_call.content().iter().any(|content| match content { ToolCallContent::ContentBlock(block) => block.visible_content(cx), ToolCallContent::Diff(_) | ToolCallContent::Terminal(_) => true, }); @@ -6507,9 +6436,6 @@ impl ThreadView { Empty.into_any() } } - AgentThreadEntry::CompletedPlan(entries) => { - self.render_completed_plan(entries, window, cx) - } AgentThreadEntry::ContextCompaction(compaction) => { self.render_context_compaction(entry_ix, compaction, window, cx) } @@ -7827,7 +7753,6 @@ impl ThreadView { AgentThreadEntry::ToolCall(_) | AgentThreadEntry::Elicitation(_) | AgentThreadEntry::AssistantMessage(_) - | AgentThreadEntry::CompletedPlan(_) | AgentThreadEntry::ContextCompaction(_) => {} } } @@ -8289,11 +8214,11 @@ impl ThreadView { let use_card_layout = needs_confirmation || is_edit || is_terminal_tool; - let has_image_content = tool_call.content.iter().any(|c| c.image().is_some()); + let has_image_content = tool_call.content().iter().any(|c| c.image().is_some()); let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content; - let has_content = !tool_call.content.is_empty() + let has_content = !tool_call.content().is_empty() || (should_show_raw_input && tool_call.raw_input.is_some()); let is_collapsible = has_content && !needs_confirmation; @@ -8316,7 +8241,7 @@ impl ThreadView { ToolCallStatus::WaitingForConfirmation { .. } => { let confirmation_content = v_flex() .w_full() - .children(tool_call.content.iter().enumerate().map( + .children(tool_call.content().iter().enumerate().map( |(content_ix, content)| { div() .child(self.render_tool_call_content( @@ -8427,7 +8352,7 @@ impl ThreadView { } ToolCallStatus::Pending | ToolCallStatus::InProgress if is_edit - && tool_call.content.is_empty() + && tool_call.content().is_empty() && self.as_native_connection(cx).is_some() => { self.render_diff_loading(cx) @@ -8459,32 +8384,28 @@ impl ThreadView { .child(input_output_header("Output:".into())), ) }) - .children( - tool_call - .content - .iter() - .enumerate() - .map(|(content_ix, content)| { - let output_id = SharedString::from(format!( - "tool-call-output-{entry_ix}-{content_ix}" - )); - div() - .id(output_id.clone()) - .debug_selector(move || output_id.to_string()) - .child(self.render_tool_call_content( - active_session_id, - entry_ix, - content, - content_ix, - tool_call, - use_card_layout, - failed_or_canceled, - focus_handle, - window, - cx, - )) - }), - ) + .children(tool_call.content().iter().enumerate().map( + |(content_ix, content)| { + let output_id = SharedString::from(format!( + "tool-call-output-{entry_ix}-{content_ix}" + )); + div() + .id(output_id.clone()) + .debug_selector(move || output_id.to_string()) + .child(self.render_tool_call_content( + active_session_id, + entry_ix, + content, + content_ix, + tool_call, + use_card_layout, + failed_or_canceled, + focus_handle, + window, + cx, + )) + }, + )) .when(!use_card_layout, |this| { let button_id = SharedString::from(format!("tool_output-collapse-{:?}", tool_call.id)); @@ -10722,7 +10643,7 @@ impl ThreadView { ); let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled) - || tool_call.content.iter().any(|c| match c { + || tool_call.content().iter().any(|c| match c { ToolCallContent::ContentBlock(block) => { block.text_content(cx) == Some("User canceled") } @@ -11137,7 +11058,7 @@ impl ThreadView { cx: &App, ) -> Option { if matches!(status, ToolCallStatus::Failed) { - tool_call.content.iter().find_map(|content| { + tool_call.content().iter().find_map(|content| { if let ToolCallContent::ContentBlock(block) = content { if let Some(source) = block.text_content(cx).filter(|source| !source.is_empty()) { diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs index 31f9e5b56af..9440cf9ffc2 100644 --- a/crates/agent_ui/src/entry_view_state.rs +++ b/crates/agent_ui/src/entry_view_state.rs @@ -424,11 +424,6 @@ impl EntryViewState { }; entry.sync(message); } - AgentThreadEntry::CompletedPlan(_) => { - if !matches!(self.entries.get(index), Some(Entry::CompletedPlan)) { - self.set_entry(index, Entry::CompletedPlan); - } - } AgentThreadEntry::ContextCompaction(_) => { if !matches!(self.entries.get(index), Some(Entry::ContextCompaction)) { self.set_entry(index, Entry::ContextCompaction); @@ -480,7 +475,6 @@ impl EntryViewState { Entry::UserMessage { .. } | Entry::AssistantMessage { .. } | Entry::Elicitation { .. } - | Entry::CompletedPlan | Entry::ContextCompaction => {} Entry::ToolCall(ToolCallEntry { content, .. }) => { for view in content.values() { @@ -550,7 +544,6 @@ pub enum Entry { AssistantMessage(AssistantMessageEntry), ToolCall(ToolCallEntry), Elicitation { focus_handle: FocusHandle }, - CompletedPlan, ContextCompaction, } @@ -561,7 +554,7 @@ impl Entry { Self::AssistantMessage(message) => Some(message.focus_handle.clone()), Self::ToolCall(tool_call) => Some(tool_call.focus_handle.clone()), Self::Elicitation { focus_handle } => Some(focus_handle.clone()), - Self::CompletedPlan | Self::ContextCompaction => None, + Self::ContextCompaction => None, } } @@ -571,7 +564,6 @@ impl Entry { Self::AssistantMessage(_) | Self::ToolCall(_) | Self::Elicitation { .. } - | Self::CompletedPlan | Self::ContextCompaction => None, } } @@ -602,7 +594,6 @@ impl Entry { Self::UserMessage(_) | Self::ToolCall(_) | Self::Elicitation { .. } - | Self::CompletedPlan | Self::ContextCompaction => None, } } @@ -621,7 +612,6 @@ impl Entry { Self::UserMessage(_) | Self::AssistantMessage(_) | Self::Elicitation { .. } - | Self::CompletedPlan | Self::ContextCompaction => false, } } @@ -640,7 +630,7 @@ impl Focusable for Entry { Self::AssistantMessage(message) => message.focus_handle.clone(), Self::ToolCall(tool_call) => tool_call.focus_handle.clone(), Self::Elicitation { focus_handle } => focus_handle.clone(), - Self::CompletedPlan | Self::ContextCompaction => cx.focus_handle(), + Self::ContextCompaction => cx.focus_handle(), } } } diff --git a/crates/agent_ui/src/threads_archive_view.rs b/crates/agent_ui/src/threads_archive_view.rs index 09a3ea8c969..ca56756195b 100644 --- a/crates/agent_ui/src/threads_archive_view.rs +++ b/crates/agent_ui/src/threads_archive_view.rs @@ -28,6 +28,7 @@ use picker::{ Picker, PickerDelegate, highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths}, }; +use platform_title_bar::apply_title_bar_insets; use project::{AgentId, AgentServerStore}; use settings::Settings as _; use theme::ActiveTheme; @@ -869,7 +870,12 @@ impl ThreadsArchiveView { h_flex() .h(header_height) .map(|header| match window.window_decorations() { - Decorations::Client { .. } => header.mt(px(-1.)), + Decorations::Client { .. } => apply_title_bar_insets( + header, + left_window_controls, + right_window_controls, + false, + ), Decorations::Server => header.mt_px().pb_px(), }) .when(left_window_controls, |this| { diff --git a/crates/edit_prediction_cli/src/headless.rs b/crates/edit_prediction_cli/src/headless.rs index b19c2612b28..0b62b1124eb 100644 --- a/crates/edit_prediction_cli/src/headless.rs +++ b/crates/edit_prediction_cli/src/headless.rs @@ -67,6 +67,7 @@ pub fn init(cx: &mut App) -> EpAppState { let git_binary_path = None; let fs = RealFs::new(git_binary_path, cx.background_executor().clone()); + ::set_global(fs.clone(), cx); let mut languages = LanguageRegistry::new(cx.background_executor().clone()); languages.set_language_server_download_dir(paths::languages_dir().clone()); diff --git a/crates/editor/src/code_context_menus.rs b/crates/editor/src/code_context_menus.rs index d635a02ff39..1b5394a3649 100644 --- a/crates/editor/src/code_context_menus.rs +++ b/crates/editor/src/code_context_menus.rs @@ -1070,9 +1070,13 @@ impl CompletionsMenu { .with_default_highlights(&style.text, main_highlights); let suffix_label = if !suffix_text.is_empty() { + let suffix_text_style = gpui::TextStyle { + color: cx.theme().colors().text_muted, + ..style.text.clone() + }; Some( StyledText::new(suffix_text.to_string()) - .with_default_highlights(&style.text, suffix_highlights), + .with_default_highlights(&suffix_text_style, suffix_highlights), ) } else { None @@ -1801,7 +1805,11 @@ fn split_completion_label<'a>( } let shifted_start = range.start.saturating_sub(filter_range.end); let shifted_end = range.end - filter_range.end; - Some((shifted_start..shifted_end, *highlight)) + let mut highlight = *highlight; + if highlight.color.is_none() { + highlight.fade_out = None; + } + Some((shifted_start..shifted_end, highlight)) }) .collect(); ( @@ -2168,6 +2176,7 @@ mod tests { fn colored() -> HighlightStyle { HighlightStyle { + color: Some(gpui::red()), fade_out: Some(0.5), ..Default::default() } @@ -2184,6 +2193,18 @@ mod tests { assert_eq!(suffix_highlights, vec![(2..8, colored())]); } + #[test] + fn test_split_completion_label_unfades_uncolored_suffix() { + let faded = HighlightStyle { + fade_out: Some(0.35), + ..Default::default() + }; + let (_, (_, suffix_highlights)) = + split_completion_label("item detail", &(0..4), &[(4..11, faded)]); + + assert_eq!(suffix_highlights, vec![(0..7, HighlightStyle::default())]); + } + #[test] fn test_split_completion_label_splits_boundary_spanning_highlight() { let ((main_text, main_highlights), (suffix_text, suffix_highlights)) = diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index 3a69748472c..a26cf4a88d7 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -5582,7 +5582,13 @@ impl Editor { let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row)); let indent_delta = match (current_indent.kind, indent_kind) { (IndentKind::Space, IndentKind::Space) => { - let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size); + let columns_to_next_tab_stop = if delta_for_start_row > 0 { + delta_for_start_row + } else if has_multiple_rows { + tab_size + } else { + tab_size - (current_indent.len % tab_size) + }; IndentSize::spaces(columns_to_next_tab_stop) } (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size), diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs index db8f9bb71b2..4b57c52760e 100644 --- a/crates/editor/src/editor_tests.rs +++ b/crates/editor/src/editor_tests.rs @@ -6856,6 +6856,146 @@ async fn test_indent_yaml_non_comments_with_multiple_cursors(cx: &mut TestAppCon ); } +#[gpui::test] +async fn test_multicursor_input_preserves_yaml_indentation(cx: &mut TestAppContext) { + init_test(cx, |_| {}); + + let mut cx = EditorTestContext::new(cx).await; + let yaml_language = languages::language("yaml", tree_sitter_yaml::LANGUAGE.into()); + cx.update_buffer(|buffer, cx| buffer.set_language(Some(yaml_language), cx)); + + let initial_state = indoc! {r#" + ˇcoverage: + ˇrange: 40..60 + ˇstatus: + ˇpatch: off + ˇproject: + ˇdefault: + ˇinformational: true + + ˇ# Don't leave comments on PRs + ˇcomment: false + "#}; + + for input in ["2", "#"] { + cx.set_state(initial_state); + cx.update_editor(|editor, window, cx| editor.handle_input(input, window, cx)); + cx.wait_for_autoindent_applied().await; + cx.assert_editor_state(&initial_state.replace('ˇ', &format!("{input}ˇ"))); + + // Recreate the cursors and delete the inserted characters, as in #21334. + cx.update_editor(|editor, window, cx| editor.cancel(&Cancel, window, cx)); + cx.set_selections_state(&initial_state.replace('ˇ', &format!("ˇ{input}"))); + cx.update_editor(|editor, window, cx| editor.delete(&Delete, window, cx)); + cx.wait_for_autoindent_applied().await; + cx.assert_editor_state(initial_state); + } + + // A multiline replacement must not reindent the other single-line edits. + cx.set_state(indoc! {" + ˇroot: + ˇchild: + ˇleaf: 1 + replacement: + « first: 1 + second: 2ˇ» + "}); + cx.update_editor(|editor, window, cx| editor.handle_input("2", window, cx)); + cx.wait_for_autoindent_applied().await; + cx.assert_editor_state(indoc! {" + 2ˇroot: + 2ˇchild: + 2ˇleaf: 1 + replacement: + 2ˇ + "}); +} + +#[gpui::test] +async fn test_multicursor_input_autoindents_multiline_replacements(cx: &mut TestAppContext) { + init_test(cx, |_| {}); + + let mut cx = EditorTestContext::new(cx).await; + let python_language = languages::language("python", tree_sitter_python::LANGUAGE.into()); + cx.update_buffer(|buffer, cx| buffer.set_language(Some(python_language), cx)); + + cx.set_state(indoc! {" + def f(): + « a = 1 + b = 2ˇ» + def g(): + « a = 1 + b = 2ˇ» + "}); + + cx.update_editor(|editor, window, cx| editor.handle_input("pass", window, cx)); + cx.wait_for_autoindent_applied().await; + + assert_eq!( + cx.buffer_text(), + indoc! {" + def f(): + pass + def g(): + pass + "} + ); +} + +#[gpui::test] +async fn test_tab_indents_selected_yaml_block(cx: &mut TestAppContext) { + init_test(cx, |_| {}); + + let mut cx = EditorTestContext::new(cx).await; + let yaml_language = languages::language("yaml", tree_sitter_yaml::LANGUAGE.into()); + cx.update_buffer(|buffer, cx| buffer.set_language(Some(yaml_language), cx)); + + cx.set_state(indoc! {" + «foo: + - bar + - zop + x: + q + bar: + qˇ» + "}); + + cx.update_editor(|editor, window, cx| editor.tab(&Tab, window, cx)); + + assert_eq!( + cx.buffer_text(), + indoc! {" + \x20 foo: + - bar + - zop + x: + q + bar: + q + "} + ); +} + +#[gpui::test] +async fn test_tab_indents_overlapping_selections_consistently(cx: &mut TestAppContext) { + init_test(cx, |_| {}); + + let mut cx = EditorTestContext::new(cx).await; + cx.set_state(indoc! {" + \x20 «firstˇ»: «1 + \x20 second: 2 + \x20 third: 3ˇ» + "}); + + cx.update_editor(|editor, window, cx| editor.tab(&Tab, window, cx)); + + cx.assert_editor_state(indoc! {" + \x20 «firstˇ»: «1 + \x20 second: 2 + \x20 third: 3ˇ» + "}); +} + #[gpui::test] async fn test_indent_outdent_with_hard_tabs(cx: &mut TestAppContext) { init_test(cx, |settings| { @@ -40439,6 +40579,34 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) { else:ˇ "}); + // Completing `else:` at multiple cursors must still trigger syntax outdents. + cx.set_state(indoc! {" + def f(): + if True: + pass + elseˇ + pass + def g(): + if True: + pass + elseˇ + pass + "}); + cx.update_editor(|editor, window, cx| editor.handle_input(":", window, cx)); + cx.wait_for_autoindent_applied().await; + cx.assert_editor_state(indoc! {" + def f(): + if True: + pass + else:ˇ + pass + def g(): + if True: + pass + else:ˇ + pass + "}); + // test `except` auto outdents when typed inside `try` block cx.set_state(indoc! {" def main(): diff --git a/crates/editor/src/input.rs b/crates/editor/src/input.rs index 9524382be94..96f631e780a 100644 --- a/crates/editor/src/input.rs +++ b/crates/editor/src/input.rs @@ -79,6 +79,7 @@ impl Editor { self.unfold_buffers_with_selections(cx); let selections = self.selections.all_adjusted(&self.display_snapshot(cx)); + let has_multiple_selections = selections.len() > 1; let mut bracket_inserted = false; let mut edits = Vec::new(); let mut linked_edits = LinkedEdits::new(); @@ -416,11 +417,18 @@ impl Editor { let initial_buffer_versions = jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx); + let autoindent_mode = if has_multiple_selections { + this.autoindent_mode + .clone() + .map(|_| AutoindentMode::PreserveSingleLine) + } else { + this.autoindent_mode.clone() + }; this.buffer.update(cx, |buffer, cx| { if has_adjacent_edits { - buffer.edit_non_coalesce(edits, this.autoindent_mode.clone(), cx); + buffer.edit_non_coalesce(edits, autoindent_mode, cx); } else { - buffer.edit(edits, this.autoindent_mode.clone(), cx); + buffer.edit(edits, autoindent_mode, cx); } }); linked_edits.apply(cx); diff --git a/crates/git_ui/Cargo.toml b/crates/git_ui/Cargo.toml index 727d4601ed3..4ea810d6410 100644 --- a/crates/git_ui/Cargo.toml +++ b/crates/git_ui/Cargo.toml @@ -82,6 +82,7 @@ fs = { workspace = true, features = ["test-support"] } git = { workspace = true, features = ["test-support"] } gpui = { workspace = true, features = ["test-support"] } indoc.workspace = true +language = { workspace = true, features = ["test-support"] } pretty_assertions.workspace = true project = { workspace = true, features = ["test-support"] } rand.workspace = true @@ -89,6 +90,7 @@ remote_connection = { workspace = true, features = ["test-support"] } search.workspace = true settings = { workspace = true, features = ["test-support"] } task.workspace = true +tree-sitter-md.workspace = true unindent.workspace = true workspace = { workspace = true, features = ["test-support"] } zlog.workspace = true diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rs index e5786864d72..4db00ef647d 100644 --- a/crates/git_ui/src/commit_view.rs +++ b/crates/git_ui/src/commit_view.rs @@ -1139,6 +1139,7 @@ pub(crate) async fn build_buffer( text, ); let mut buffer = Buffer::build(buffer, Some(blob), Capability::ReadWrite, cx); + buffer.set_language_registry(language_registry.clone()); buffer.set_language_async(language, cx); buffer }); @@ -1529,3 +1530,78 @@ fn stash_matches_index(sha: &str, stash_index: usize, repo: &Repository) -> bool .map(|entry| entry.oid.to_string() == sha) .unwrap_or(false) } + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{EmptyView, TestAppContext}; + use indoc::indoc; + use language::{Language, LanguageConfig, markdown_lang}; + use settings::SettingsStore; + + #[gpui::test] + async fn test_build_buffer_resolves_injected_languages(cx: &mut TestAppContext) { + cx.update(|cx| { + let store = SettingsStore::test(cx); + cx.set_global(store); + }); + + let language_registry = Arc::new(LanguageRegistry::test(cx.executor())); + language_registry.add(markdown_lang()); + language_registry.add(Arc::new(markdown_inline_lang())); + + let window = cx.add_window(|_, _| EmptyView); + let mut async_cx = window + .update(cx, |_, window, cx| window.to_async(cx)) + .expect("window should be open"); + + let text = indoc! {" + # Title + + Some *emphasized* text. + "} + .to_string(); + let blob = Arc::new(GitBlob { + path: RepoPath::new("notes.md").unwrap(), + worktree_id: WorktreeId::from_usize(0), + is_deleted: false, + is_binary: false, + display_name: "abc1234 - notes.md".into(), + }) as Arc; + + let buffer = build_buffer(text, blob, &language_registry, &mut async_cx) + .await + .expect("buffer should build"); + + cx.run_until_parked(); + + buffer.read_with(cx, |buffer, _| { + let language = buffer.language().expect("buffer should have a language"); + assert_eq!(language.name().as_ref(), "Markdown"); + + let layers = buffer + .snapshot() + .syntax_layers() + .map(|layer| layer.language.name().to_string()) + .collect::>(); + assert!( + layers.iter().any(|name| name == "Markdown-Inline"), + "emphasis, links, and fenced code blocks are highlighted by the injected \ + Markdown-Inline grammar, but the buffer parsed with layers {layers:?}", + ); + }); + } + + fn markdown_inline_lang() -> Language { + Language::new( + LanguageConfig { + name: "Markdown-Inline".into(), + hidden: true, + ..LanguageConfig::default() + }, + Some(tree_sitter_md::INLINE_LANGUAGE.into()), + ) + .with_highlights_query("(emphasis) @emphasis") + .unwrap() + } +} diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index ae0cca86b8f..645f9dbc51a 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -7437,6 +7437,12 @@ impl TryInto for ElementId { } } +impl From for ElementId { + fn from(id: u64) -> Self { + ElementId::Integer(id) + } +} + impl From for ElementId { fn from(id: usize) -> Self { ElementId::Integer(id as u64) diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs index eab3b5e55c7..348aaa3f23f 100644 --- a/crates/gpui_windows/src/platform.rs +++ b/crates/gpui_windows/src/platform.rs @@ -964,19 +964,13 @@ impl Platform for WindowsPlatform { } if credentials.is_null() { - Ok(None) - } else { - let username: String = unsafe { (*credentials).UserName.to_string()? }; - let credential_blob = unsafe { - std::slice::from_raw_parts( - (*credentials).CredentialBlob, - (*credentials).CredentialBlobSize as usize, - ) - }; - let password = credential_blob.to_vec(); - unsafe { CredFree(credentials as *const _ as _) }; - Ok(Some((username, password))) + return Ok(None); } + + // SAFETY: `CredReadW` succeeded, so this points to a valid `CREDENTIALW` until `CredFree` below. + let result = unsafe { username_and_password(&*credentials) }; + unsafe { CredFree(credentials as *const _ as _) }; + result.map(Some) }) } @@ -1634,14 +1628,104 @@ unsafe extern "system" fn window_procedure( result } +/// Copies the username and secret out of a credential returned by `CredReadW`. +/// +/// Both `UserName` and `CredentialBlob` are optional in Credential Manager and +/// come back as null pointers when absent, so they are treated as empty here. +/// +/// # Safety +/// +/// A non-null `UserName` must point to a NUL-terminated wide string and a +/// non-null `CredentialBlob` must be readable for `CredentialBlobSize` bytes, +/// as is the case for credentials returned by `CredReadW`. +unsafe fn username_and_password(credential: &CREDENTIALW) -> Result<(String, Vec)> { + let username = if credential.UserName.is_null() { + String::new() + } else { + // SAFETY: guaranteed by the caller. + unsafe { credential.UserName.to_string()? } + }; + let password = if credential.CredentialBlob.is_null() { + Vec::new() + } else { + // SAFETY: guaranteed by the caller. + unsafe { + std::slice::from_raw_parts( + credential.CredentialBlob, + credential.CredentialBlobSize as usize, + ) + } + .to_vec() + }; + Ok((username, password)) +} + #[cfg(test)] mod tests { use std::ffi::{OsStr, OsString}; use crate::{read_from_clipboard, write_to_clipboard}; use gpui::ClipboardItem; + use windows::Win32::Security::Credentials::{ + CRED_PERSIST_SESSION, CRED_TYPE_GENERIC, CREDENTIALW, CredDeleteW, CredFree, CredReadW, + CredWriteW, + }; + use windows::core::{PCWSTR, PWSTR}; - use super::encode_restart_arguments; + use super::{encode_restart_arguments, username_and_password}; + + #[test] + fn test_read_credential_with_username() { + assert_eq!( + round_trip_credential(Some("alice"), b"secret"), + ("alice".to_string(), b"secret".to_vec()) + ); + } + + #[test] + fn test_read_credential_without_username() { + assert_eq!( + round_trip_credential(None, b"secret"), + (String::new(), b"secret".to_vec()) + ); + } + + fn round_trip_credential(username: Option<&str>, secret: &[u8]) -> (String, Vec) { + let mut target_name: Vec = format!( + "zed-test-{}-{}", + std::process::id(), + username.unwrap_or_default() + ) + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut username: Vec = username + .map(|username| username.encode_utf16().chain(Some(0)).collect()) + .unwrap_or_default(); + let mut secret = secret.to_vec(); + let credential = CREDENTIALW { + Type: CRED_TYPE_GENERIC, + TargetName: PWSTR::from_raw(target_name.as_mut_ptr()), + CredentialBlobSize: secret.len() as u32, + CredentialBlob: secret.as_mut_ptr(), + Persist: CRED_PERSIST_SESSION, + UserName: if username.is_empty() { + PWSTR::null() + } else { + PWSTR::from_raw(username.as_mut_ptr()) + }, + ..CREDENTIALW::default() + }; + let target_name = PCWSTR::from_raw(target_name.as_ptr()); + unsafe { CredWriteW(&credential, 0) }.unwrap(); + + let mut credentials: *mut CREDENTIALW = std::ptr::null_mut(); + unsafe { CredReadW(target_name, CRED_TYPE_GENERIC, None, &mut credentials) }.unwrap(); + let result = unsafe { username_and_password(&*credentials) }; + unsafe { CredFree(credentials as *const _ as _) }; + unsafe { CredDeleteW(target_name, CRED_TYPE_GENERIC, None) }.unwrap(); + result.unwrap() + } #[test] fn test_encode_restart_arguments() { diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs index 17ad2f30301..e54228e6e7e 100644 --- a/crates/language/src/buffer.rs +++ b/crates/language/src/buffer.rs @@ -475,6 +475,8 @@ pub trait LocalFile: File { pub enum AutoindentMode { /// Indent each line of inserted text. EachLine, + /// Autoindent multiline edits, but only apply syntax-triggered outdents to single-line edits. + PreserveSingleLine, /// Apply the same indentation adjustment to all of the lines /// in a given insertion. Block { @@ -509,6 +511,7 @@ struct AutoindentRequestEntry { old_row: Option, indent_size: IndentSize, original_indent_column: Option, + only_explicit_outdents: bool, } #[derive(Debug)] @@ -516,6 +519,7 @@ struct IndentSuggestion { basis_row: u32, delta: Ordering, within_error: bool, + explicit_outdent: bool, } struct BufferChunkHighlights<'a> { @@ -2138,7 +2142,11 @@ impl Buffer { if let Some(old_row) = entry.old_row { old_to_new_rows.insert(old_row, new_row); } - row_ranges.push((new_row..new_end_row, entry.original_indent_column)); + row_ranges.push(( + new_row..new_end_row, + entry.original_indent_column, + entry.only_explicit_outdents, + )); } // Build a map containing the suggested indentation for each of the edited lines @@ -2190,7 +2198,7 @@ impl Buffer { // if they differ from the old suggestion for that line. let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable(); let mut language_indent_size = IndentSize::default(); - for (row_range, original_indent_column) in row_ranges { + for (row_range, original_indent_column, only_explicit_outdents) in row_ranges { let new_edited_row_range = if request.is_block_mode { row_range.start..row_range.start + 1 } else { @@ -2226,7 +2234,8 @@ impl Buffer { suggested_indent != *old_indentation && (!suggestion.within_error || *was_within_error) }, - ) { + ) && (!only_explicit_outdents || suggestion.explicit_outdent) + { indent_sizes.insert( new_row, (suggested_indent, request.ignore_empty_lines), @@ -3043,6 +3052,9 @@ impl Buffer { } AutoindentRequestEntry { + only_explicit_outdents: matches!(mode, AutoindentMode::PreserveSingleLine) + && old_start.row == old_end.row + && !new_text.contains('\n'), original_indent_column, old_row: if first_line_is_new { None @@ -3115,6 +3127,7 @@ impl Buffer { old_row: None, indent_size: before_edit.language_indent_size_at(range.start, cx), original_indent_column: None, + only_explicit_outdents: false, }) .collect(); self.autoindent_requests.push(Arc::new(AutoindentRequest { @@ -4053,24 +4066,28 @@ impl BufferSnapshot { basis_row: prev_row, delta: Ordering::Equal, within_error: within_error && !from_regex, + explicit_outdent: true, }) } else if indent_from_prev_row { Some(IndentSuggestion { basis_row: prev_row, delta: Ordering::Greater, within_error: within_error && !from_regex, + explicit_outdent: false, }) } else if outdent_to_row < prev_row { Some(IndentSuggestion { basis_row: outdent_to_row, delta: Ordering::Equal, within_error: within_error && !from_regex, + explicit_outdent: true, }) } else if outdent_from_prev_row { Some(IndentSuggestion { basis_row: prev_row, delta: Ordering::Less, within_error: within_error && !from_regex, + explicit_outdent: true, }) } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row) { @@ -4078,6 +4095,7 @@ impl BufferSnapshot { basis_row: prev_row, delta: Ordering::Equal, within_error: within_error && !from_regex, + explicit_outdent: false, }) } else { None diff --git a/crates/language_models/Cargo.toml b/crates/language_models/Cargo.toml index ae6c7c5687a..552e9e296fc 100644 --- a/crates/language_models/Cargo.toml +++ b/crates/language_models/Cargo.toml @@ -57,6 +57,7 @@ open_ai = { workspace = true, features = ["schemars"] } openai_subscribed.workspace = true opencode = { workspace = true, features = ["schemars"] } open_router = { workspace = true, features = ["schemars"] } +paths.workspace = true rand.workspace = true release_channel.workspace = true schemars.workspace = true diff --git a/crates/language_models/src/provider/opencode.rs b/crates/language_models/src/provider/opencode.rs index e4a472530ba..17c490e8242 100644 --- a/crates/language_models/src/provider/opencode.rs +++ b/crates/language_models/src/provider/opencode.rs @@ -3,8 +3,10 @@ use collections::{BTreeMap, HashMap}; use credentials_provider::CredentialsProvider; use fs::Fs; use futures::{AsyncReadExt, FutureExt, StreamExt, future::BoxFuture}; -use gpui::{App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window}; -use http_client::{AsyncBody, CustomHeaders, HttpClient, Method, Request, RequestBuilderExt, http}; +use gpui::{ + App, AsyncApp, BackgroundExecutor, Context, Entity, SharedString, Task, TaskExt, Window, +}; +use http_client::{AsyncBody, CustomHeaders, HttpClient, Method, Request, http}; use language_model::{ ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, InlineDescription, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel, @@ -18,7 +20,11 @@ use serde::Deserialize; pub use settings::OpenCodeApiProtocol; pub use settings::OpenCodeAvailableModel as AvailableModel; use settings::{Settings, SettingsStore, update_settings_file}; -use std::sync::{Arc, LazyLock}; +use std::{ + path::{Path, PathBuf}, + sync::{Arc, LazyLock}, + time::{Duration, SystemTime}, +}; use ui::{ Banner, ButtonLink, ConfiguredApiCard, Divider, List, ListBulletItem, Severity, Switch, SwitchLabelPosition, ToggleState, prelude::*, @@ -73,6 +79,9 @@ static API_KEY_ENV_VAR: LazyLock = env_var!(API_KEY_ENV_VAR_NAME); const OPENCODE_SESSION_HEADER_NAME: &str = "x-opencode-session"; const RICH_MODEL_CATALOG_URL: &str = "https://models.opencode.ai/api.json"; const MODEL_CATALOG_RESPONSE_LIMIT_BYTES: u64 = 8 * 1024 * 1024; +const MODEL_CATALOG_FETCH_TIMEOUT: Duration = Duration::from_secs(15); +const MODEL_CATALOG_DISK_FRESHNESS: Duration = Duration::from_secs(5 * 60); +const MODEL_CATALOG_REFRESH_INTERVAL: Duration = Duration::from_secs(60 * 60); pub(crate) const RESERVED_HEADER_NAMES: &[&str] = &[OPENCODE_SESSION_HEADER_NAME]; #[derive(Default, Clone, Debug, PartialEq)] @@ -96,6 +105,9 @@ pub struct State { discovered_models: HashMap>, fetch_models_errors: HashMap, fetch_models_task: Option>, + refresh_models_task: Option>, + cache_path: PathBuf, + fs: Arc, } #[derive(Clone)] @@ -114,6 +126,7 @@ impl State { let credentials_provider = self.credentials_provider.clone(); let api_url = OpenCodeLanguageModelProvider::api_url(cx); self.fetch_models_task = None; + self.refresh_models_task = None; self.discovered_models.clear(); self.fetch_models_errors.clear(); let task = self.api_key_state.store( @@ -155,51 +168,153 @@ impl State { fn restart_fetch_models_task(&mut self, cx: &mut Context) { self.fetch_models_task = None; - self.discovered_models.clear(); - self.fetch_models_errors.clear(); + self.refresh_models_task = None; let api_url = OpenCodeLanguageModelProvider::api_url(cx); - let custom_headers = OpenCodeLanguageModelProvider::settings(cx) - .custom_headers - .clone(); - let Some(api_key) = self.api_key_state.key(&api_url) else { + if self.api_key_state.key(&api_url).is_none() { self.fetch_models_task = None; cx.notify(); return; - }; + } let http_client = self.http_client.clone(); + let fs = self.fs.clone(); + let cache_path = self.cache_path.clone(); + let executor = cx.background_executor().clone(); self.fetch_models_task = Some(cx.spawn(async move |this, cx| { - let mut discovered_models = HashMap::default(); - let mut fetch_models_errors = HashMap::default(); - for subscription in [OpenCodeSubscription::Zen, OpenCodeSubscription::Go] { - match fetch_discovered_models( - http_client.clone(), - &api_url, - subscription, - &api_key, - &custom_headers, - ) - .await - { - Ok(models) => { - discovered_models.insert(subscription, models); - } - Err(error) => { - log::warn!( - "Failed to fetch OpenCode {} models: {error:#}", - subscription.display_name() - ); - fetch_models_errors.insert(subscription, format!("{error:#}").into()); - } - } + let cached_catalog = load_cached_catalog(fs.as_ref(), &cache_path).await; + if let Ok(Some((catalog, _))) = &cached_catalog { + let results = catalog_results(Ok(catalog)); + this.update(cx, |this, cx| { + apply_discovery_results( + &mut this.discovered_models, + &mut this.fetch_models_errors, + results, + ); + cx.notify(); + }) + .ok(); + } + + if cached_catalog + .as_ref() + .ok() + .and_then(|catalog| catalog.as_ref()) + .is_some_and(|(_, is_fresh)| *is_fresh) + { + this.update(cx, |this, _| this.fetch_models_task = None) + .ok(); + return; + } + + let catalog = fetch_model_catalog(http_client, executor).await; + let results = catalog_results(catalog.as_ref().map(String::as_str)); + if results.iter().all(|(_, result)| result.is_ok()) + && let Ok(catalog) = catalog + && let Err(error) = store_cached_catalog(fs.as_ref(), cache_path, catalog).await + { + log::warn!("Failed to cache OpenCode model catalog: {error:#}"); } this.update(cx, |this, cx| { - this.discovered_models = discovered_models; - this.fetch_models_errors = fetch_models_errors; + apply_discovery_results( + &mut this.discovered_models, + &mut this.fetch_models_errors, + results, + ); this.fetch_models_task = None; cx.notify(); }) .ok(); })); + + let http_client = self.http_client.clone(); + let fs = self.fs.clone(); + let cache_path = self.cache_path.clone(); + let executor = cx.background_executor().clone(); + self.refresh_models_task = Some(cx.spawn(async move |this, cx| { + loop { + executor.timer(MODEL_CATALOG_REFRESH_INTERVAL).await; + let catalog = fetch_model_catalog(http_client.clone(), executor.clone()).await; + let results = catalog_results(catalog.as_ref().map(String::as_str)); + if results.iter().all(|(_, result)| result.is_ok()) + && let Ok(catalog) = catalog + && let Err(error) = + store_cached_catalog(fs.as_ref(), cache_path.clone(), catalog).await + { + log::warn!("Failed to cache OpenCode model catalog: {error:#}"); + } + if this + .update(cx, |this, cx| { + apply_discovery_results( + &mut this.discovered_models, + &mut this.fetch_models_errors, + results, + ); + cx.notify(); + }) + .is_err() + { + break; + } + } + })); + } +} + +fn catalog_results( + catalog: Result<&str, &anyhow::Error>, +) -> [(OpenCodeSubscription, Result>); 2] { + [OpenCodeSubscription::Zen, OpenCodeSubscription::Go].map(|subscription| { + let result = catalog + .map_err(|error| anyhow!("{error:#}")) + .and_then(|catalog| parse_discovered_models(catalog, subscription)); + if let Err(error) = &result { + log::warn!( + "Failed to fetch OpenCode {} models: {error:#}", + subscription.display_name() + ); + } + (subscription, result) + }) +} + +async fn load_cached_catalog(fs: &dyn Fs, path: &Path) -> Result> { + let Some(metadata) = fs.metadata(path).await? else { + return Ok(None); + }; + let catalog = fs.load(path).await?; + for subscription in [OpenCodeSubscription::Zen, OpenCodeSubscription::Go] { + parse_discovered_models(&catalog, subscription)?; + } + let is_fresh = SystemTime::now() + .duration_since(metadata.mtime.timestamp_for_user()) + .is_ok_and(|age| age < MODEL_CATALOG_DISK_FRESHNESS); + Ok(Some((catalog, is_fresh))) +} + +async fn store_cached_catalog(fs: &dyn Fs, path: PathBuf, catalog: String) -> Result<()> { + let mut catalog = serde_json::from_str::>(&catalog)?; + catalog.retain(|provider, _| matches!(provider.as_str(), "opencode" | "opencode-go")); + if let Some(parent) = path.parent() { + fs.create_dir(parent).await?; + } + fs.atomic_write(path, serde_json::to_string(&catalog)?) + .await +} + +fn apply_discovery_results( + discovered_models: &mut HashMap>, + fetch_models_errors: &mut HashMap, + results: [(OpenCodeSubscription, Result>); 2], +) { + for (subscription, result) in results { + match result { + Ok(models) => { + discovered_models.insert(subscription, models); + fetch_models_errors.remove(&subscription); + } + Err(error) => { + fetch_models_errors.insert(subscription, format!("{error:#}").into()); + } + } } } @@ -208,24 +323,35 @@ impl OpenCodeLanguageModelProvider { http_client: Arc, credentials_provider: Arc, cx: &mut App, + ) -> Self { + Self::new_with_cache( + http_client, + credentials_provider, + ::global(cx), + paths::temp_dir().join("opencode").join("models.json"), + cx, + ) + } + + fn new_with_cache( + http_client: Arc, + credentials_provider: Arc, + fs: Arc, + cache_path: PathBuf, + cx: &mut App, ) -> Self { let state = cx.new(|cx| { cx.observe_global::({ let mut last_api_url = Self::api_url(cx); - let mut last_custom_headers = Self::settings(cx).custom_headers.clone(); move |this: &mut State, cx| { let api_url = Self::api_url(cx); - let custom_headers = Self::settings(cx).custom_headers.clone(); if api_url != last_api_url { last_api_url = api_url; - last_custom_headers = custom_headers; this.discovered_models.clear(); this.fetch_models_errors.clear(); this.fetch_models_task = None; + this.refresh_models_task = None; this.authenticate(cx).detach(); - } else if custom_headers != last_custom_headers { - last_custom_headers = custom_headers; - this.restart_fetch_models_task(cx); } cx.notify(); } @@ -238,6 +364,9 @@ impl OpenCodeLanguageModelProvider { discovered_models: HashMap::default(), fetch_models_errors: HashMap::default(), fetch_models_task: None, + refresh_models_task: None, + cache_path, + fs, } }); @@ -682,7 +811,19 @@ impl LanguageModel for OpenCodeLanguageModel { if levels.is_empty() { return Vec::new(); } - let default_index = levels.len() - 1; + let default_index = if levels.contains(&ReasoningEffort::Max) { + [ + ReasoningEffort::High, + ReasoningEffort::Medium, + ReasoningEffort::Low, + ReasoningEffort::Minimal, + ] + .into_iter() + .find_map(|effort| levels.iter().position(|level| *level == effort)) + .unwrap_or(levels.len() - 1) + } else { + levels.len() - 1 + }; levels .into_iter() .enumerate() @@ -869,16 +1010,6 @@ impl LanguageModel for OpenCodeLanguageModel { } } -#[derive(Deserialize)] -struct AvailableModelsResponse { - data: Vec, -} - -#[derive(Deserialize)] -struct AvailableModelResponse { - id: String, -} - #[derive(Deserialize)] struct RichCatalogProvider { npm: Option, @@ -902,6 +1033,7 @@ struct RichCatalogModel { limit: ModelLimits, provider: Option, cost: Option, + status: Option, } #[derive(Deserialize)] @@ -938,11 +1070,9 @@ struct ReasoningOption { } fn parse_discovered_models( - available_models: &str, rich_catalog: &str, subscription: OpenCodeSubscription, ) -> Result> { - let available_models = serde_json::from_str::(available_models)?; let provider_key = match subscription { OpenCodeSubscription::Zen => "opencode", OpenCodeSubscription::Go => "opencode-go", @@ -953,22 +1083,22 @@ fn parse_discovered_models( .cloned() .ok_or_else(|| anyhow!("OpenCode catalog is missing {provider_key}"))?; let provider = serde_json::from_value::(provider)?; - let mut available_model_count = available_models.data.len(); - let models = available_models - .data + let mut compatible_candidate_count = provider.models.len(); + let models = provider + .models .into_iter() - .filter_map(|available| { - let metadata = provider.models.get(&available.id)?; - if subscription == OpenCodeSubscription::Zen - && metadata - .cost - .as_ref() - .is_some_and(|cost| cost.input == Some(0.0) && cost.output == Some(0.0)) + .filter_map(|(catalog_id, metadata)| { + if metadata.status.as_deref() == Some("deprecated") + || (subscription == OpenCodeSubscription::Zen + && metadata + .cost + .as_ref() + .is_some_and(|cost| cost.input == Some(0.0) && cost.output == Some(0.0))) { - available_model_count -= 1; + compatible_candidate_count -= 1; return None; } - if metadata.id != available.id + if metadata.id != catalog_id || !metadata.tool_call || !metadata .modalities @@ -1021,7 +1151,7 @@ fn parse_discovered_models( }) }) .collect::>(); - if available_model_count > 0 && models.is_empty() { + if compatible_candidate_count > 0 && models.is_empty() { bail!("OpenCode model metadata did not contain any compatible models"); } Ok(models) @@ -1037,43 +1167,22 @@ fn protocol_for_transport(transport: &str) -> Option { } } -async fn fetch_discovered_models( +async fn fetch_model_catalog( client: Arc, - api_url: &str, - subscription: OpenCodeSubscription, - api_key: &str, - custom_headers: &CustomHeaders, -) -> Result> { - let models_url = format!( - "{}{}/v1/models", - api_url.trim_end_matches('/'), - subscription.api_path_suffix() - ); - let available_models = - fetch_catalog_resource(client.as_ref(), &models_url, Some(api_key), custom_headers).await?; - let rich_catalog = fetch_catalog_resource( - client.as_ref(), - RICH_MODEL_CATALOG_URL, - None, - &CustomHeaders::default(), - ) - .await?; - parse_discovered_models(&available_models, &rich_catalog, subscription) + executor: BackgroundExecutor, +) -> Result { + let fetch = fetch_catalog_resource(client.as_ref(), RICH_MODEL_CATALOG_URL).fuse(); + let timeout = executor.timer(MODEL_CATALOG_FETCH_TIMEOUT).fuse(); + futures::pin_mut!(fetch, timeout); + futures::select_biased! { + result = fetch => result, + _ = timeout => bail!("OpenCode model catalog request timed out"), + } } -async fn fetch_catalog_resource( - client: &dyn HttpClient, - url: &str, - api_key: Option<&str>, - custom_headers: &CustomHeaders, -) -> Result { - let mut request = Request::builder() - .method(Method::GET) - .uri(url) - .extra_headers(custom_headers); - if let Some(api_key) = api_key { - request = request.header(http::header::AUTHORIZATION, format!("Bearer {api_key}")); - } +async fn fetch_catalog_resource(client: &dyn HttpClient, url: &str) -> Result { + // Catalogs are public; completion credentials and custom headers must not be sent here. + let request = Request::builder().method(Method::GET).uri(url); let mut response = client .send(request.body(AsyncBody::empty())?) .await @@ -1329,76 +1438,168 @@ impl Render for ConfigurationView { #[cfg(test)] mod tests { use super::*; + use fs::FakeFs; use http_client::{FakeHttpClient, Response}; use language_model::{LanguageModelRequestMessage, MessageContent, Role}; use parking_lot::Mutex; - #[gpui::test] - async fn test_discovery_authenticates_and_applies_custom_headers() { - let requests = Arc::new(Mutex::new(Vec::new())); - let http_client = FakeHttpClient::create({ - let requests = requests.clone(); - move |request| { - let requests = requests.clone(); - async move { - let uri = request.uri().to_string(); - requests.lock().push(( - uri.clone(), - request.headers().get(http::header::AUTHORIZATION).cloned(), - request.headers().get("x-test-header").cloned(), - )); - let body = if uri == RICH_MODEL_CATALOG_URL { - r#"{ - "opencode": { - "npm": "@ai-sdk/anthropic", - "models": { - "new-model": { - "id": "new-model", - "name": "New Model", - "tool_call": true, - "modalities": {"input":["text"],"output":["text"]}, - "limit": {"context": 12345} - } - } - } - }"# - } else { - r#"{"data":[{"id":"new-model"}]}"# - }; - Ok(Response::builder() - .status(200) - .body(AsyncBody::from(body))?) + fn test_catalog() -> &'static str { + r#"{ + "opencode": { + "npm": "@ai-sdk/anthropic", + "models": { + "zen-model": { + "id": "zen-model", + "name": "Zen Model", + "tool_call": true, + "modalities": {"input":["text"],"output":["text"]}, + "limit": {"context": 12345} + } + } + }, + "opencode-go": { + "npm": "@ai-sdk/openai-compatible", + "models": { + "go-model": { + "id": "go-model", + "name": "Go Model", + "tool_call": true, + "modalities": {"input":["text"],"output":["text"]}, + "limit": {"context": 12345} + } } } - }); - let custom_headers = CustomHeaders::new(vec![( - http::HeaderName::from_static("x-test-header"), - http::HeaderValue::from_static("configured"), - )]); + }"# + } - let models = fetch_discovered_models( - http_client, - "https://api.example.test", - OpenCodeSubscription::Zen, - "secret", - &custom_headers, - ) - .await - .unwrap(); + #[gpui::test] + async fn test_disk_cache_and_hourly_refresh(cx: &mut gpui::TestAppContext) { + for (cached, stale, fail, initial_requests) in [ + (Some(test_catalog()), false, false, 0), + (Some("not json"), false, false, 1), + (Some(test_catalog()), true, true, 1), + (None, false, false, 1), + ] { + let fs = FakeFs::new(cx.background_executor.clone()); + let cache_path = PathBuf::from("/cache/opencode/models.json"); + if let Some(cached) = cached { + fs.create_dir(Path::new("/cache/opencode")).await.unwrap(); + fs.set_next_mtime(if stale { + SystemTime::now() - MODEL_CATALOG_REFRESH_INTERVAL + } else { + SystemTime::now() - Duration::from_secs(1) + }); + fs.atomic_write(cache_path.clone(), cached.to_string()) + .await + .unwrap(); + } + let requests = Arc::new(Mutex::new(0)); + let fail_request = Arc::new(Mutex::new(fail)); + let client = FakeHttpClient::create({ + let requests = requests.clone(); + let fail_request = fail_request.clone(); + move |_| { + *requests.lock() += 1; + let status = if *fail_request.lock() { 503 } else { 200 }; + async move { + Ok(Response::builder().status(status).body(AsyncBody::from( + test_catalog().replace("zen-model", "updated-model"), + ))?) + } + } + }); + let provider = cx.update(|cx| { + let settings_store = SettingsStore::test(cx); + cx.set_global(settings_store); + OpenCodeLanguageModelProvider::new_with_cache( + client, + Arc::new(TestCredentialsProvider), + fs.clone(), + cache_path.clone(), + cx, + ) + }); + provider + .state + .update(cx, |state, cx| { + state.set_api_key(Some("secret".to_string()), cx) + }) + .await + .unwrap(); + cx.run_until_parked(); + assert_eq!(*requests.lock(), initial_requests); + let expected = if initial_requests == 0 || fail { + "zen-model" + } else { + "updated-model" + }; + provider.state.read_with(cx, |state, _cx| { + assert_eq!( + state.discovered_models[&OpenCodeSubscription::Zen][0] + .model + .id(), + expected, + ); + }); + if fail { + assert_eq!(fs.load(&cache_path).await.unwrap(), test_catalog()); + } - assert_eq!(models.len(), 1); - let requests = requests.lock(); - assert_eq!(requests.len(), 2); - assert_eq!( - requests[0].1.as_ref().and_then(|value| value.to_str().ok()), - Some("Bearer secret") - ); - assert_eq!( - requests[0].2.as_ref().and_then(|value| value.to_str().ok()), - Some("configured") - ); - assert_eq!(requests[1].1, None); - assert_eq!(requests[1].2, None); + *fail_request.lock() = false; + cx.background_executor + .advance_clock(MODEL_CATALOG_REFRESH_INTERVAL); + cx.run_until_parked(); + assert_eq!(*requests.lock(), initial_requests + 1); + provider.state.read_with(cx, |state, _cx| { + assert_eq!( + state.discovered_models[&OpenCodeSubscription::Zen][0] + .model + .id(), + "updated-model", + ); + assert!(state.fetch_models_errors.is_empty()); + }); + assert_eq!( + serde_json::from_str::(&fs.load(&cache_path).await.unwrap()) + .unwrap(), + serde_json::from_str::( + &test_catalog().replace("zen-model", "updated-model") + ) + .unwrap(), + ); + drop(provider); + cx.run_until_parked(); + } + } + + #[gpui::test] + async fn test_fresh_disk_catalog_is_usable(cx: &mut gpui::TestAppContext) { + let fs = FakeFs::new(cx.background_executor.clone()); + let cache_path = PathBuf::from("/cache/models.json"); + fs.set_next_mtime(SystemTime::now()); + fs.atomic_write(cache_path.clone(), test_catalog().to_string()) + .await + .unwrap(); + + let (catalog, is_fresh) = load_cached_catalog(fs.as_ref(), &cache_path) + .await + .unwrap() + .unwrap(); + + assert!(is_fresh); + assert_eq!(catalog, test_catalog()); + } + + #[gpui::test] + async fn test_invalid_disk_catalog_falls_back_to_network(cx: &mut gpui::TestAppContext) { + let fs = FakeFs::new(cx.background_executor.clone()); + let cache_path = PathBuf::from("/cache/models.json"); + fs.atomic_write(cache_path.clone(), "not json".to_string()) + .await + .unwrap(); + + assert!(load_cached_catalog(fs.as_ref(), &cache_path).await.is_err()); + assert_eq!(fs.load(&cache_path).await.unwrap(), "not json"); } #[gpui::test] @@ -1408,9 +1609,11 @@ mod tests { let provider = cx.update(|cx| { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); - OpenCodeLanguageModelProvider::new( + OpenCodeLanguageModelProvider::new_with_cache( FakeHttpClient::with_404_response(), Arc::new(TestCredentialsProvider), + FakeFs::new(cx.background_executor().clone()), + PathBuf::from("/cache/models.json"), cx, ) }); @@ -1442,6 +1645,105 @@ mod tests { store_task.await.unwrap(); } + #[test] + fn test_refresh_failure_preserves_last_success_per_subscription() { + let mut discovered_models = HashMap::default(); + discovered_models.insert( + OpenCodeSubscription::Zen, + vec![DiscoveredModel { + model: test_model("old-zen", ApiProtocol::Anthropic), + supports_images: true, + supports_thinking: false, + }], + ); + discovered_models.insert( + OpenCodeSubscription::Go, + vec![DiscoveredModel { + model: test_model("old-go", ApiProtocol::OpenAiChat), + supports_images: false, + supports_thinking: false, + }], + ); + let mut errors = HashMap::default(); + let new_go_model = DiscoveredModel { + model: test_model("new-go", ApiProtocol::OpenAiChat), + supports_images: true, + supports_thinking: true, + }; + + apply_discovery_results( + &mut discovered_models, + &mut errors, + [ + (OpenCodeSubscription::Zen, Err(anyhow!("refresh failed"))), + (OpenCodeSubscription::Go, Ok(vec![new_go_model])), + ], + ); + + assert_eq!( + discovered_models[&OpenCodeSubscription::Zen][0].model.id(), + "old-zen" + ); + assert_eq!( + discovered_models[&OpenCodeSubscription::Go][0].model.id(), + "new-go" + ); + assert!(errors.contains_key(&OpenCodeSubscription::Zen)); + assert!(!errors.contains_key(&OpenCodeSubscription::Go)); + } + + #[gpui::test] + fn test_default_reasoning_effort(cx: &mut gpui::TestAppContext) { + use ReasoningEffort::{High, Low, Max, Medium, Minimal, XHigh}; + + cx.update(|cx| { + let settings_store = SettingsStore::test(cx); + cx.set_global(settings_store); + let provider = OpenCodeLanguageModelProvider::new_with_cache( + FakeHttpClient::with_404_response(), + Arc::new(TestCredentialsProvider), + FakeFs::new(cx.background_executor().clone()), + PathBuf::from("/cache/models.json"), + cx, + ); + for (levels, expected) in [ + (vec![Low, Medium, High, XHigh, Max], Some("high")), + (vec![Max, High, Medium], Some("high")), + (vec![Low, Medium, Max], Some("medium")), + (vec![Minimal, Low, Max], Some("low")), + (vec![Minimal, Max], Some("minimal")), + (vec![Low, High, XHigh], Some("xhigh")), + (vec![High, Low], Some("low")), + (vec![Max], Some("max")), + (vec![ReasoningEffort::None], None), + (vec![], None), + ] { + let model = provider.create_language_model_with_capabilities( + opencode::Model::new( + "test-model".to_string(), + None, + 1000, + None, + ApiProtocol::OpenAiChat, + Some(levels), + None, + false, + ), + OpenCodeSubscription::Zen, + false, + true, + ); + assert_eq!( + model + .default_effort_level() + .map(|effort| effort.value.to_string()) + .as_deref(), + expected, + ); + } + }); + } + #[test] fn test_none_only_reasoning_does_not_enable_thinking() { let model = opencode::Model::new( @@ -1492,11 +1794,7 @@ mod tests { (OpenCodeSubscription::Zen, zen_model_count), (OpenCodeSubscription::Go, 1), ] { - let models = parse_discovered_models( - r#"{"data":[{"id":"model"}]}"#, - &catalog, - subscription, - )?; + let models = parse_discovered_models(&catalog, subscription)?; assert_eq!(models.len(), expected_count, "{subscription:?}: {cost}"); } } @@ -1504,9 +1802,44 @@ mod tests { } #[test] - fn test_parse_discovered_models_joins_subscription_and_metadata_catalogs() { + fn test_discovery_filters_deprecated_status_per_subscription() -> Result<()> { + for (zen_status, go_status, zen_count, go_count) in [ + (Some("deprecated"), None, 0, 1), + (None, Some("deprecated"), 1, 0), + (Some("active"), Some("preview"), 1, 1), + (Some("deprecated"), Some("deprecated"), 0, 0), + ] { + let mut catalog = serde_json::json!({}); + for (provider_key, status) in [("opencode", zen_status), ("opencode-go", go_status)] { + let mut model = serde_json::json!({ + "id": "model", + "name": "Model", + "tool_call": true, + "modalities": {"output": ["text"]}, + "limit": {"context": 1000}, + }); + if let Some(status) = status { + model["status"] = status.into(); + } + catalog[provider_key] = serde_json::json!({ + "npm": "@ai-sdk/openai-compatible", + "models": {"model": model}, + }); + } + for (subscription, expected_count) in [ + (OpenCodeSubscription::Zen, zen_count), + (OpenCodeSubscription::Go, go_count), + ] { + let models = parse_discovered_models(&catalog.to_string(), subscription)?; + assert_eq!(models.len(), expected_count, "{subscription:?}: {catalog}",); + } + } + Ok(()) + } + + #[test] + fn test_parse_discovered_models_uses_catalog_entries_directly() { let models = parse_discovered_models( - r#"{"data":[{"id":"new-model"}]}"#, r#"{ "opencode-go": { "npm": "@ai-sdk/openai-compatible", @@ -1545,7 +1878,6 @@ mod tests { #[test] fn test_parse_discovered_models_rejects_catalog_without_compatible_models() { let result = parse_discovered_models( - r#"{"data":[{"id":"text-only"}]}"#, r#"{ "opencode": { "npm": "@ai-sdk/anthropic", @@ -1615,7 +1947,13 @@ mod tests { let provider = cx.update(|cx| { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); - OpenCodeLanguageModelProvider::new(http_client, Arc::new(TestCredentialsProvider), cx) + OpenCodeLanguageModelProvider::new_with_cache( + http_client, + Arc::new(TestCredentialsProvider), + FakeFs::new(cx.background_executor().clone()), + PathBuf::from("/cache/models.json"), + cx, + ) }); let store_key = provider.state.update(cx, |state, cx| { state.set_api_key(Some("test-key".to_string()), cx) diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs index 201d25da7fe..d0f5cc90d82 100644 --- a/crates/markdown/src/markdown.rs +++ b/crates/markdown/src/markdown.rs @@ -1279,7 +1279,13 @@ impl Markdown { let mut fallback_code_block_language = None; if let Some(registry) = language_registry.as_ref() { for name in language_names { - if let Ok(language) = registry.language_for_name_or_extension(&name).await { + let mut language = registry.language_for_name_or_extension(&name).await; + if language.is_err() + && let Some((first_word, _)) = name.split_once(char::is_whitespace) + { + language = registry.language_for_name_or_extension(first_word).await; + } + if let Ok(language) = language { languages_by_name.insert(name, language); } } @@ -5649,6 +5655,45 @@ mod tests { ); } + #[gpui::test] + fn test_code_block_language_uses_first_word_of_info_string(cx: &mut TestAppContext) { + let source = "```rust import.meta.vitest\nfn main() {}\n```"; + let (_, markdown) = markdown_with_rust_language(source, cx); + + let code_start = source.find("fn main").unwrap(); + let cached = cached_code_block_highlights(&markdown, code_start, cx); + assert!(!cached.runs.is_empty()); + } + + #[gpui::test] + fn test_code_block_language_prefers_full_info_string(cx: &mut TestAppContext) { + let language_registry = Arc::new(LanguageRegistry::test(cx.executor())); + for name in ["Go", "Go Mod"] { + language_registry.add(Arc::new(Language::new( + LanguageConfig { + name: name.into(), + ..LanguageConfig::default() + }, + None, + ))); + } + + let source = "```Go Mod\nmodule example\n```\n\n```Go extra\npackage main\n```"; + let markdown = cx.new(|cx| Markdown::new(source.into(), Some(language_registry), None, cx)); + cx.run_until_parked(); + + markdown.read_with(cx, |markdown, _| { + let languages_by_name = &markdown.parsed_markdown().languages_by_name; + let resolved_name = |info: &str| { + languages_by_name + .get(&SharedString::from(info.to_string())) + .map(|language| language.name()) + }; + assert_eq!(resolved_name("Go Mod"), Some("Go Mod".into())); + assert_eq!(resolved_name("Go extra"), Some("Go".into())); + }); + } + #[gpui::test] fn test_code_block_highlights_reused_when_streaming(cx: &mut TestAppContext) { let source = "```rust\nfn main() {}\n```\n\nSome trailing text"; diff --git a/crates/outline_panel/src/outline_panel.rs b/crates/outline_panel/src/outline_panel.rs index 083d4fcacec..861d506da94 100644 --- a/crates/outline_panel/src/outline_panel.rs +++ b/crates/outline_panel/src/outline_panel.rs @@ -1470,9 +1470,21 @@ impl OutlinePanel { let mut change_focus = prefer_focus_change; let mut scroll_to_buffer = None; let scroll_target = match entry { - PanelEntry::FoldedDirs(..) | PanelEntry::Fs(FsEntry::Directory(..)) => { + PanelEntry::FoldedDirs(FoldedDirsEntry { + first_buffer_id, .. + }) + | PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory { + first_buffer_id, .. + })) => { + change_selection = false; change_focus = false; - None + scroll_to_buffer = Some(*first_buffer_id); + multi_buffer_snapshot + .excerpts_for_buffer(*first_buffer_id) + .next() + .and_then(|excerpt_range| { + multi_buffer_snapshot.anchor_in_excerpt(excerpt_range.context.start) + }) } PanelEntry::Fs(FsEntry::ExternalFile(file)) => { change_selection = false; @@ -1918,7 +1930,7 @@ impl OutlinePanel { if buffers_to_unfold.is_empty() { self.update_cached_entries(None, window, cx); } else { - self.toggle_buffers_fold(buffers_to_unfold, false, window, cx) + self.toggle_buffers_fold(buffers_to_unfold, false, true, window, cx) .detach(); } } else { @@ -2011,7 +2023,7 @@ impl OutlinePanel { if buffers_to_fold.is_empty() { self.update_cached_entries(None, window, cx); } else { - self.toggle_buffers_fold(buffers_to_fold, true, window, cx) + self.toggle_buffers_fold(buffers_to_fold, true, true, window, cx) .detach(); } } else { @@ -2099,7 +2111,7 @@ impl OutlinePanel { if buffers_to_unfold.is_empty() { self.update_cached_entries(None, window, cx); } else { - self.toggle_buffers_fold(buffers_to_unfold, false, window, cx) + self.toggle_buffers_fold(buffers_to_unfold, false, true, window, cx) .detach(); } } @@ -2158,7 +2170,7 @@ impl OutlinePanel { if buffers_to_fold.is_empty() { self.update_cached_entries(None, window, cx); } else { - self.toggle_buffers_fold(buffers_to_fold, true, window, cx) + self.toggle_buffers_fold(buffers_to_fold, true, true, window, cx) .detach(); } } @@ -2245,7 +2257,7 @@ impl OutlinePanel { if buffers_to_toggle.is_empty() { self.update_cached_entries(None, window, cx); } else { - self.toggle_buffers_fold(buffers_to_toggle, fold, window, cx) + self.toggle_buffers_fold(buffers_to_toggle, fold, false, window, cx) .detach(); } } @@ -2254,6 +2266,7 @@ impl OutlinePanel { &self, buffers: HashSet, fold: bool, + scroll_to_selection: bool, window: &mut Window, cx: &mut Context, ) -> Task<()> { @@ -2275,7 +2288,9 @@ impl OutlinePanel { } } }); - if let Some(selection) = outline_panel.selected_entry().cloned() { + if scroll_to_selection + && let Some(selection) = outline_panel.selected_entry().cloned() + { outline_panel.scroll_editor_to_entry(&selection, false, false, window, cx); } }) @@ -2479,12 +2494,15 @@ impl OutlinePanel { .contains(&CollapsedEntry::Excerpt(excerpt.clone())); let color = entry_label_color(is_active); let icon = if has_outlines { - FileIcons::get_chevron_icon(is_expanded, cx) - .map(|icon_path| Icon::from_path(icon_path).color(color).into_any_element()) + self.chevron_toggle( + PanelEntry::Outline(OutlineEntry::Excerpt(excerpt.clone())), + is_expanded, + color, + cx, + ) } else { - None - } - .unwrap_or_else(empty_icon); + empty_icon() + }; let label = self.excerpt_label(&excerpt, cx)?; let label_element = Label::new(label) @@ -2555,13 +2573,12 @@ impl OutlinePanel { .contains(&CollapsedEntry::Outline(outline.range.clone())); let icon = if has_children { - FileIcons::get_chevron_icon(is_expanded, cx) - .map(|icon_path| { - Icon::from_path(icon_path) - .color(entry_label_color(is_active)) - .into_any_element() - }) - .unwrap_or_else(empty_icon) + self.chevron_toggle( + PanelEntry::Outline(OutlineEntry::Outline(outline.clone())), + is_expanded, + entry_label_color(is_active), + cx, + ) } else { empty_icon() }; @@ -2617,9 +2634,14 @@ impl OutlinePanel { ) .color(color) .into_any_element(), - reserve_chevron_slot( - settings.folder_indicator, - icon.unwrap_or_else(empty_icon), + self.file_expand_collapse_icon( + rendered_entry, + !self + .collapsed_entries + .contains(&CollapsedEntry::File(*worktree_id, *buffer_id)), + icon, + color, + cx, ), ) } @@ -2635,8 +2657,8 @@ impl OutlinePanel { directory.entry.is_ignored, is_active, ); - let icon = folder_indicator_element( - settings.folder_indicator, + let icon = self.folder_expand_collapse_icon( + PanelEntry::Fs(rendered_entry.clone()), is_expanded, directory.entry.path.as_std_path(), color, @@ -2656,7 +2678,7 @@ impl OutlinePanel { ) .color(color) .into_any_element(), - icon.unwrap_or_else(empty_icon), + icon, ) } FsEntry::ExternalFile(external_file) => { @@ -2688,9 +2710,14 @@ impl OutlinePanel { ) .color(color) .into_any_element(), - reserve_chevron_slot( - settings.folder_indicator, - icon.unwrap_or_else(empty_icon), + self.file_expand_collapse_icon( + rendered_entry, + !self + .collapsed_entries + .contains(&CollapsedEntry::ExternalFile(external_file.buffer_id)), + icon, + color, + cx, ), ) } @@ -2716,7 +2743,6 @@ impl OutlinePanel { window: &mut Window, cx: &mut Context, ) -> Stateful
{ - let settings = OutlinePanelSettings::get_global(cx); let is_active = match self.selected_entry() { Some(PanelEntry::FoldedDirs(selected_dirs)) => selected_dirs == folded_dir, _ => false, @@ -2737,8 +2763,8 @@ impl OutlinePanel { .map(|entry| entry.git_summary) .unwrap_or_default(); let color = entry_git_aware_label_color(git_status, is_ignored, is_active); - let icon = folder_indicator_element( - settings.folder_indicator, + let icon = self.folder_expand_collapse_icon( + PanelEntry::FoldedDirs(folded_dir.clone()), is_expanded, Path::new(&name), color, @@ -2766,7 +2792,7 @@ impl OutlinePanel { ) .color(color) .into_any_element(), - icon.unwrap_or_else(empty_icon), + icon, ) }; @@ -2875,6 +2901,121 @@ impl OutlinePanel { )) } + fn chevron_toggle( + &self, + entry: PanelEntry, + is_expanded: bool, + color: Color, + cx: &mut Context, + ) -> AnyElement { + let chevron = FileIcons::get_chevron_icon(is_expanded, cx) + .map(|path| Icon::from_path(path).color(color).into_any_element()) + .unwrap_or_else(empty_icon); + self.expand_collapse_icon(entry, is_expanded, chevron, cx) + } + + fn expand_collapse_icon( + &self, + entry: PanelEntry, + is_expanded: bool, + icon: AnyElement, + cx: &mut Context, + ) -> AnyElement { + h_flex() + .id("expand-collapse") + .role(gpui::Role::Button) + .aria_label(if is_expanded { "Collapse" } else { "Expand" }) + .aria_expanded(is_expanded) + .flex_none() + .cursor_pointer() + .rounded_sm() + .hover(|style| style.bg(cx.theme().colors().ghost_element_hover)) + .tooltip(Tooltip::text(if is_expanded { + "Collapse" + } else { + "Expand" + })) + .on_click( + cx.listener(move |panel, event: &gpui::ClickEvent, window, cx| { + if event.is_right_click() || event.first_focus() { + return; + } + cx.stop_propagation(); + panel.toggle_expanded(&entry, window, cx); + }), + ) + .child(icon) + .into_any_element() + } + + fn folder_expand_collapse_icon( + &self, + entry: PanelEntry, + is_expanded: bool, + path: &Path, + color: Color, + cx: &mut Context, + ) -> AnyElement { + let settings = OutlinePanelSettings::get_global(cx); + let indicator = settings.folder_indicator; + let file_icons = settings.file_icons; + let indicators = FileIcons::get_folder_indicators(indicator, is_expanded, path, cx); + let chevron = indicators.chevron.map(|path| { + self.expand_collapse_icon( + entry, + is_expanded, + Icon::from_path(path).color(color).into_any_element(), + cx, + ) + }); + let icon = indicators + .icon + .map(|path| Icon::from_path(path).color(color).into_any_element()); + let (leading, trailing) = if file_icons || indicator == FolderIndicator::Both { + ( + chevron.unwrap_or_else(empty_icon), + Some(icon.unwrap_or_else(empty_icon)), + ) + } else { + (chevron.or(icon).unwrap_or_else(empty_icon), None) + }; + h_flex() + .flex_none() + .gap_0p5() + .child(leading) + .children(trailing) + .into_any_element() + } + + fn file_expand_collapse_icon( + &self, + entry: &FsEntry, + is_expanded: bool, + icon: Option, + color: Color, + cx: &mut Context, + ) -> AnyElement { + if !self.multi_buffer_active(cx) { + return icon.unwrap_or_else(empty_icon); + } + let settings = OutlinePanelSettings::get_global(cx); + let icon = icon.or_else(|| { + (settings.file_icons || settings.folder_indicator == FolderIndicator::Both) + .then(empty_icon) + }); + let expand_collapse_icon = if self.hide_symbols_active(cx) { + empty_icon() + } else { + self.chevron_toggle(PanelEntry::Fs(entry.clone()), is_expanded, color, cx) + }; + h_flex() + .flex_none() + .gap_0p5() + .child(expand_collapse_icon) + .children(icon) + .into_any_element() + } + fn entry_element( &self, rendered_entry: PanelEntry, @@ -2902,8 +3043,7 @@ impl OutlinePanel { } let change_focus = event.click_count() > 1; - outline_panel.toggle_expanded(&clicked_entry, window, cx); - + outline_panel.select_entry(clicked_entry.clone(), true, window, cx); outline_panel.scroll_editor_to_entry( &clicked_entry, true, @@ -5830,48 +5970,6 @@ fn empty_icon() -> AnyElement { .into_any_element() } -fn folder_indicator_element( - indicator: FolderIndicator, - expanded: bool, - path: &Path, - color: Color, - cx: &App, -) -> Option { - let indicators = FileIcons::get_folder_indicators(indicator, expanded, path, cx); - let render_indicator = |icon_path| Icon::from_path(icon_path).color(color); - - match (indicators.chevron, indicators.icon) { - (Some(chevron), Some(icon)) => Some( - h_flex() - .flex_none() - .gap_0p5() - .child(render_indicator(chevron)) - .child(render_indicator(icon)) - .into_any_element(), - ), - (Some(only), None) | (None, Some(only)) => Some(render_indicator(only).into_any_element()), - (None, None) => None, - } -} - -/// Adds a blank as wide as a chevron in front of `icon` in `both` mode. Leaves `icon` -/// alone in the other modes. -/// -/// Directories show a chevron and an icon in `both` mode. Without the blank, a file's -/// icon would line up under the folder chevrons instead of the folder icons. -fn reserve_chevron_slot(indicator: FolderIndicator, icon: AnyElement) -> AnyElement { - if indicator.shows_chevron() && indicator.shows_icon() { - h_flex() - .flex_none() - .gap_0p5() - .child(empty_icon()) - .child(icon) - .into_any_element() - } else { - icon - } -} - #[derive(Debug, Default)] struct GenerationState { entries: Vec, @@ -5893,7 +5991,7 @@ mod tests { use db::indoc; use editor::{HiddenUnstagedDiffHunkRenderer, PathKey}; use futures::{FutureExt as _, StreamExt as _, future::poll_fn, task::Poll}; - use gpui::{TestAppContext, UpdateGlobal, VisualTestContext, WindowHandle}; + use gpui::{MouseUpEvent, TestAppContext, UpdateGlobal, VisualTestContext, WindowHandle}; use language::{self, FakeLspAdapter, markdown_lang, rust_lang}; use pretty_assertions::assert_eq; use project::FakeFs; @@ -10633,6 +10731,376 @@ outline: fn main" ); } + #[gpui::test] + async fn test_rendered_outline_click_navigation(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.background_executor.clone()); + fs.insert_tree( + path!("/test"), + json!({"main.rs": "\nmod parent {\n fn leaf() {}\n}\n"}), + ) + .await; + let project = Project::test(fs, [Path::new(path!("/test"))], cx).await; + project.read_with(cx, |project, _| project.languages().add(rust_lang())); + let (workspace, panel, mut cx) = active_outline_panel(&project, cx).await; + let cx = &mut cx; + workspace + .update_in(cx, |workspace, window, cx| { + workspace.open_abs_path( + PathBuf::from(path!("/test/main.rs")), + OpenOptions::default(), + window, + cx, + ) + }) + .await + .expect("open singleton editor"); + wait_for_outline_tasks(&panel, cx).await; + let (editor, parent, leaf) = panel.read_with(cx, |panel, _| { + assert_eq!(panel.cached_entries.len(), 2); + ( + panel.active_editor().expect("active editor"), + panel.cached_entries[0].entry.clone(), + panel.cached_entries[1].entry.clone(), + ) + }); + let PanelEntry::Outline(OutlineEntry::Outline(outline)) = &parent else { + panic!("parent symbol"); + }; + let buffer_id = outline.range.start.buffer_id; + let collapsed = CollapsedEntry::Outline(outline.range.clone()); + for (entry, click_arrow, count, caret, is_collapsed) in [ + (&parent, false, 1, language::Point::new(1, 0), false), + (&leaf, true, 1, language::Point::new(2, 4), false), + (&parent, true, 1, language::Point::new(2, 4), true), + (&parent, false, 1, language::Point::new(1, 0), true), + (&parent, false, 2, language::Point::new(1, 0), true), + (&parent, true, 1, language::Point::new(1, 0), false), + (&leaf, false, 2, language::Point::new(2, 4), false), + ] { + click_outline_row(&panel, entry, click_arrow, count, cx); + wait_for_outline_tasks(&panel, cx).await; + assert_eq!(click_test_selection(&editor, cx), (buffer_id, caret..caret)); + panel.read_with(cx, |panel, _| { + assert_eq!(panel.selected_entry(), Some(entry)); + assert_eq!( + panel.collapsed_entries, + if is_collapsed { + HashSet::from_iter([collapsed.clone()]) + } else { + HashSet::default() + } + ); + }); + cx.update(|window, cx| { + let focus = if count == 2 { + editor.focus_handle(cx) + } else { + panel.focus_handle(cx) + }; + assert_eq!(window.focused(cx), Some(focus)); + }); + } + + let buffer = open_buffer(&project, path!("/test/main.rs"), cx).await; + buffer.update(cx, |buffer, cx| { + buffer.set_text("plain text", cx); + }); + wait_for_outline_tasks(&panel, cx).await; + let entry = panel.update(cx, |panel, _| { + assert_eq!(panel.cached_entries.len(), 1); + panel.selected_entry = SelectedEntry::None; + panel.cached_entries[0].entry.clone() + }); + assert!(matches!(entry, PanelEntry::Fs(FsEntry::File(_)))); + click_outline_row(&panel, &entry, true, 1, cx); + wait_for_outline_tasks(&panel, cx).await; + panel.read_with(cx, |panel, _| { + assert_eq!(panel.selected_entry(), Some(&entry)); + assert_eq!(panel.collapsed_entries, HashSet::default()); + }); + } + + #[gpui::test] + async fn test_rendered_multibuffer_click_navigation(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.background_executor.clone()); + fs.insert_tree( + path!("/test"), + json!({ + "dir": {"sub": {"a.rs": "fn alpha() {}\n", "c.rs": "fn charlie() {}\n"}}, + "other": {"b.rs": "fn bravo() {}\n"} + }), + ) + .await; + let project = Project::test(fs, [Path::new(path!("/test"))], cx).await; + project.read_with(cx, |project, _| project.languages().add(rust_lang())); + let (workspace, panel, mut cx) = active_outline_panel(&project, cx).await; + let cx = &mut cx; + let first = open_buffer(&project, path!("/test/dir/sub/a.rs"), cx).await; + let middle = open_buffer(&project, path!("/test/other/b.rs"), cx).await; + let last = open_buffer(&project, path!("/test/dir/sub/c.rs"), cx).await; + let editor = add_multi_buffer_editor( + &workspace, + &project, + &[ + (&first, Vec::new()), + (&middle, Vec::new()), + (&last, Vec::new()), + ], + cx, + ); + set_buffer_order(&editor, &[&last, &middle, &first], cx); + let [first_id, middle_id, last_id] = [&first, &middle, &last] + .map(|buffer| buffer.read_with(cx, |buffer, _| buffer.remote_id())); + editor.update_in(cx, |editor, window, cx| { + let snapshot = editor.buffer().read(cx).snapshot(cx); + let buffer = middle.read(cx); + let start = snapshot + .anchor_in_excerpt(buffer.anchor_before(3)) + .expect("selection start"); + let end = snapshot + .anchor_in_excerpt(buffer.anchor_before(7)) + .expect("selection end"); + editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| { + selections.select_ranges([start..end]) + }); + }); + let worktree_id = first.read_with(cx, |buffer, cx| { + File::from_dyn(buffer.file()) + .expect("file") + .worktree + .read(cx) + .id() + }); + let expected_selection = ( + middle_id, + language::Point::new(0, 3)..language::Point::new(0, 7), + ); + for hidden in [false, true] { + for compact in [false, true] { + update_outline_panel_settings(cx, |settings| { + settings.multi_buffer_hide_symbols = Some(hidden); + settings.auto_fold_dirs = Some(compact); + }); + wait_for_outline_tasks(&panel, cx).await; + let rows = panel.read_with(cx, |panel, _| { + panel + .cached_entries + .iter() + .map(|entry| &entry.entry) + .filter(|entry| match entry { + PanelEntry::Fs(FsEntry::File(file)) => file.buffer_id != middle_id, + PanelEntry::Fs(FsEntry::Directory(directory)) => { + !compact && directory.entry.path.as_ref() == rel_path("dir/sub") + } + PanelEntry::FoldedDirs(directories) => { + compact + && directories + .entries + .iter() + .map(|entry| entry.path.as_ref()) + .collect::>() + == vec![rel_path("dir"), rel_path("dir/sub")] + } + PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => { + excerpt.context.start.buffer_id != middle_id + } + _ => false, + }) + .cloned() + .collect::>() + }); + assert_eq!(rows.len(), if hidden { 4 } else { 6 }); + for (iteration, folded) in [false, true, false].into_iter().enumerate() { + if iteration > 0 { + for file in rows + .iter() + .filter(|entry| matches!(entry, PanelEntry::Fs(FsEntry::File(_)))) + { + let scroll = editor.update_in(cx, |editor, window, cx| { + let snapshot = editor.buffer().read(cx).snapshot(cx); + let anchor = snapshot + .anchor_in_excerpt(middle.read(cx).anchor_before(0)) + .expect("middle buffer scroll target"); + editor.set_scroll_anchor( + ScrollAnchor { + anchor, + offset: point(0., -2.), + }, + window, + cx, + ); + editor.scroll_manager.shared_scroll_anchor(cx).scroll_anchor + }); + assert_eq!(scroll.anchor.buffer_id(), Some(middle_id)); + if hidden && let PanelEntry::Fs(FsEntry::File(file)) = file { + editor.update(cx, |editor, cx| { + if folded { + editor.fold_buffer(file.buffer_id, cx); + } else { + editor.unfold_buffer(file.buffer_id, cx); + } + }); + } else { + click_outline_row(&panel, file, true, 1, cx); + } + wait_for_outline_tasks(&panel, cx).await; + editor.read_with(cx, |editor, cx| { + assert_eq!( + editor.scroll_manager.shared_scroll_anchor(cx).scroll_anchor, + scroll + ); + }); + assert_eq!(click_test_selection(&editor, cx), expected_selection); + } + } + let collapsed = if folded { + [last_id, first_id] + .map(|id| CollapsedEntry::File(worktree_id, id)) + .into_iter() + .collect::>() + } else { + HashSet::default() + }; + for (section, buffer_id) in rows + .chunks(if hidden { 2 } else { 3 }) + .zip([last_id, first_id]) + { + for entry in section { + let is_file = matches!(entry, PanelEntry::Fs(FsEntry::File(_))); + let is_excerpt = + matches!(entry, PanelEntry::Outline(OutlineEntry::Excerpt(_))); + if folded && is_excerpt { + continue; + } + for (click_arrow, count) in [(false, 1), (false, 2)] + .into_iter() + .chain((hidden && is_file).then_some((true, 1))) + { + click_outline_row(&panel, entry, click_arrow, count, cx); + assert_eq!(click_test_selection(&editor, cx), expected_selection); + panel.read_with(cx, |panel, _| { + assert_eq!(panel.selected_entry(), Some(entry)); + assert_eq!(panel.collapsed_entries, collapsed); + }); + cx.update(|window, cx| { + let editor = editor.read(cx); + let scroll = editor + .scroll_manager + .shared_scroll_anchor(cx) + .scroll_anchor; + assert_eq!( + (scroll.anchor.buffer_id(), scroll.offset), + ( + Some(buffer_id), + point(0., if folded || is_excerpt { 0. } else { -2. }) + ) + ); + assert_eq!(editor.is_buffer_folded(buffer_id, cx), folded); + let focus = if is_file && count == 2 { + editor.focus_handle(cx) + } else { + panel.focus_handle(cx) + }; + assert_eq!(window.focused(cx), Some(focus)); + }); + } + } + } + } + + for (indicator, file_icons, icon_offset) in [ + (FolderIndicator::Icon, false, 15.), + (FolderIndicator::Icon, true, 33.), + (FolderIndicator::Both, false, 33.), + (FolderIndicator::Both, true, 33.), + ] { + update_outline_panel_settings(cx, |settings| { + settings.folder_indicator = Some(indicator); + settings.file_icons = Some(file_icons); + }); + wait_for_outline_tasks(&panel, cx).await; + click_outline_row(&panel, &rows[0], false, 1, cx); + let directory = &rows[rows.len() / 2]; + let bounds = render_outline_row(&panel, directory, cx); + cx.simulate_click( + point(bounds.left() + px(icon_offset), bounds.center().y), + gpui::Modifiers::default(), + ); + wait_for_outline_tasks(&panel, cx).await; + assert_eq!(click_test_selection(&editor, cx), expected_selection); + panel.read_with(cx, |panel, _| { + assert_eq!(panel.selected_entry(), Some(directory)); + assert_eq!(panel.collapsed_entries, HashSet::default()); + }); + cx.update(|window, cx| { + let scroll = editor + .read(cx) + .scroll_manager + .shared_scroll_anchor(cx) + .scroll_anchor; + assert_eq!( + (scroll.anchor.buffer_id(), scroll.offset), + (Some(first_id), point(0., -2.)) + ); + assert_eq!(window.focused(cx), Some(panel.focus_handle(cx))); + }); + if indicator == FolderIndicator::Icon { + continue; + } + + click_outline_row(&panel, &rows[0], true, 1, cx); + wait_for_outline_tasks(&panel, cx).await; + let collapsed = HashSet::from_iter([ + CollapsedEntry::Dir( + worktree_id, + Arc::from(rel_path(if compact { "dir" } else { "dir/sub" })), + ), + CollapsedEntry::File(worktree_id, last_id), + CollapsedEntry::File(worktree_id, first_id), + ]); + let second_directory = panel.read_with(cx, |panel, _| { + assert_eq!(panel.collapsed_entries, collapsed); + panel + .cached_entries + .iter() + .find(|entry| entry.entry == rows[rows.len() / 2]) + .expect("second collapsed directory occurrence") + .entry + .clone() + }); + for count in [1, 2] { + click_outline_row(&panel, &second_directory, false, count, cx); + wait_for_outline_tasks(&panel, cx).await; + assert_eq!(click_test_selection(&editor, cx), expected_selection); + panel.read_with(cx, |panel, _| { + assert_eq!(panel.selected_entry(), Some(&second_directory)); + assert_eq!(panel.collapsed_entries, collapsed); + }); + cx.update(|window, cx| { + let scroll = editor + .read(cx) + .scroll_manager + .shared_scroll_anchor(cx) + .scroll_anchor; + assert_eq!( + (scroll.anchor.buffer_id(), scroll.offset), + (Some(first_id), point(0., 0.)) + ); + assert_eq!(window.focused(cx), Some(panel.focus_handle(cx))); + }); + } + click_outline_row(&panel, &second_directory, true, 1, cx); + wait_for_outline_tasks(&panel, cx).await; + panel.read_with(cx, |panel, _| { + assert_eq!(panel.collapsed_entries, HashSet::default()); + }); + } + } + } + } + #[gpui::test] async fn test_outline_click_toggle_behavior(cx: &mut TestAppContext) { init_test(cx); @@ -12717,4 +13185,100 @@ test/ ); }); } + + struct ClickTestRow(Entity, PanelEntry); + + impl Render for ClickTestRow { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.0.update(cx, |panel, cx| { + let editor_focus = panel + .active_editor() + .expect("active editor") + .focus_handle(cx); + let row = match &self.1 { + PanelEntry::Fs(entry) => panel.render_entry(entry, 0, None, window, cx), + PanelEntry::FoldedDirs(entry) => { + panel.render_folded_dirs(entry, 0, None, window, cx) + } + PanelEntry::Outline(OutlineEntry::Outline(entry)) => { + panel.render_outline(entry, 0, None, window, cx) + } + PanelEntry::Outline(OutlineEntry::Excerpt(entry)) => panel + .render_excerpt(entry, 0, window, cx) + .expect("excerpt row"), + PanelEntry::Search(_) => panic!("unexpected search row"), + } + .w(px(400.)) + .track_focus(&panel.focus_handle) + .debug_selector(|| "click-test-row".to_owned()); + div() + .child(row) + .child(div().id("editor-focus").track_focus(&editor_focus)) + }) + } + } + + fn render_outline_row( + panel: &Entity, + entry: &PanelEntry, + cx: &mut VisualTestContext, + ) -> Bounds { + cx.update(|window, cx| { + window.replace_root(cx, |_, _| ClickTestRow(panel.clone(), entry.clone())); + panel.focus_handle(cx).focus(window, cx); + }); + cx.run_until_parked(); + cx.debug_bounds("click-test-row").expect("rendered row") + } + + fn click_outline_row( + panel: &Entity, + entry: &PanelEntry, + click_arrow: bool, + click_count: usize, + cx: &mut VisualTestContext, + ) { + let bounds = render_outline_row(panel, entry, cx); + let position = point( + if click_arrow { + bounds.left() + px(15.) + } else { + bounds.center().x + }, + bounds.center().y, + ); + cx.simulate_event(MouseDownEvent { + position, + button: MouseButton::Left, + click_count, + ..MouseDownEvent::default() + }); + cx.simulate_event(MouseUpEvent { + position, + button: MouseButton::Left, + click_count, + ..MouseUpEvent::default() + }); + } + + fn click_test_selection( + editor: &Entity, + cx: &mut VisualTestContext, + ) -> (BufferId, Range) { + editor.read_with(cx, |editor, cx| { + let snapshot = editor.buffer().read(cx).snapshot(cx); + let [selection] = editor.selections.disjoint_anchors() else { + panic!("one selection"); + }; + let (start, buffer) = snapshot + .anchor_to_buffer_anchor(selection.start) + .expect("selection start"); + let (end, _) = snapshot + .anchor_to_buffer_anchor(selection.end) + .expect("selection end"); + assert_eq!(start.buffer_id, end.buffer_id); + assert_eq!(selection.head(), selection.end); + (start.buffer_id, (start..end).to_point(buffer)) + }) + } } diff --git a/crates/platform_title_bar/src/platform_title_bar.rs b/crates/platform_title_bar/src/platform_title_bar.rs index b44f019ff43..b69bb0d1ff0 100644 --- a/crates/platform_title_bar/src/platform_title_bar.rs +++ b/crates/platform_title_bar/src/platform_title_bar.rs @@ -25,6 +25,29 @@ pub use system_window_tabs::{ DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, ShowNextWindowTab, ShowPreviousWindowTab, }; +/// With client-side decorations, the title bar is pulled over the window frame's +/// border to avoid a transparent gap in the rounded corners, and a border in the +/// title bar's own color insets its content back by the same amount. Headers that +/// render window controls in place of the title bar use this to apply the same +/// insets as padding, so the controls stay on the same pixel. +/// +/// `pad_bottom` should be false when the header already has a bottom border of +/// its own occupying that space. +pub fn apply_title_bar_insets( + header: E, + left_window_controls: bool, + right_window_controls: bool, + pad_bottom: bool, +) -> E { + let inset = theme::CLIENT_SIDE_DECORATION_BORDER; + header + .mt(-inset) + .pt(inset) + .when(pad_bottom, |header| header.pb(inset)) + .when(left_window_controls, |header| header.pl(inset)) + .when(right_window_controls, |header| header.pr(inset)) +} + pub struct PlatformTitleBar { id: ElementId, platform_style: PlatformStyle, @@ -277,10 +300,10 @@ impl Render for PlatformTitleBar { && !(sidebar.open && sidebar.side == SidebarSide::Left), |el| el.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING), ) - // this border is to avoid a transparent gap in the rounded corners - .mt(px(-1.)) - .mb(px(-1.)) - .border(px(1.)) + // Keep in sync with `apply_title_bar_insets`. + .mt(-theme::CLIENT_SIDE_DECORATION_BORDER) + .mb(-theme::CLIENT_SIDE_DECORATION_BORDER) + .border(theme::CLIENT_SIDE_DECORATION_BORDER) .border_color(titlebar_color), }) .bg(titlebar_color) diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rs index 36a25ec5f7d..3769fec8bea 100644 --- a/crates/project_panel/src/project_panel.rs +++ b/crates/project_panel/src/project_panel.rs @@ -1544,7 +1544,7 @@ impl ProjectPanel { loop { let entry_id = entry.id; match expanded_dir_ids.binary_search(&entry_id) { - Ok(ix) => { + Ok(ix) if entry.is_dir() => { expanded_dir_ids.remove(ix); self.selection = Some(SelectedEntry { worktree_id, @@ -1560,7 +1560,7 @@ impl ProjectPanel { cx.notify(); break; } - Err(_) => { + Ok(_) | Err(_) => { if let Some(parent_entry) = entry.path.parent().and_then(|p| worktree.entry_for_path(p)) { @@ -1722,7 +1722,9 @@ impl ProjectPanel { }; let include_ignored_dirs = !entry.is_ignored; - if let Err(ix) = expanded_dir_ids.binary_search(&entry_id) { + if entry.is_dir() + && let Err(ix) = expanded_dir_ids.binary_search(&entry_id) + { expanded_dir_ids.insert(ix, entry_id); } @@ -1814,7 +1816,9 @@ impl ProjectPanel { if let Some(mut entry) = worktree.entry_for_id(entry_id) { loop { - if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) { + if entry.is_dir() + && let Err(ix) = expanded_dir_ids.binary_search(&entry.id) + { expanded_dir_ids.insert(ix, entry.id); } @@ -4853,7 +4857,9 @@ impl ProjectPanel { if let Some(mut entry) = worktree.entry_for_id(entry_id) { loop { - if let Err(ix) = expanded_dir_ids.binary_search(&entry.id) { + if entry.is_dir() + && let Err(ix) = expanded_dir_ids.binary_search(&entry.id) + { expanded_dir_ids.insert(ix, entry.id); } diff --git a/crates/project_panel/src/project_panel_tests.rs b/crates/project_panel/src/project_panel_tests.rs index d75248288bc..999dd13a49b 100644 --- a/crates/project_panel/src/project_panel_tests.rs +++ b/crates/project_panel/src/project_panel_tests.rs @@ -4130,6 +4130,112 @@ async fn test_collapse_selected_entry_scrolls_into_view(cx: &mut TestAppContext) } } +#[gpui::test] +async fn test_collapse_opened_file_scrolls_to_parent(cx: &mut TestAppContext) { + init_test_with_editor(cx); + let (panel, mut cx) = open_panel_with_tree( + json!({ + "src": { + "a.rs": "", + "b.rs": "", + "c.rs": "", + "d.rs": "", + "e.rs": "", + "f.rs": "", + "g.rs": "", + "h.rs": "", + }, + "tests": { + "a.rs": "", + "b.rs": "", + "c.rs": "", + "d.rs": "", + "e.rs": "", + "f.rs": "", + "g.rs": "", + "h.rs": "", + } + }), + size(px(800.), px(160.)), + cx, + ) + .await; + let cx = &mut cx; + toggle_expand_dir(&panel, "root/src", cx); + toggle_expand_dir(&panel, "root/tests", cx); + select_path(&panel, "root/src/h.rs", cx); + panel.update_in(cx, |panel, window, cx| panel.open(&Open, window, cx)); + cx.run_until_parked(); + + let workspace = panel.read_with(cx, |panel, _| { + panel.workspace.upgrade().expect("workspace is open") + }); + ensure_single_file_is_opened(&workspace, "src/h.rs", cx); + let parent_id = find_project_entry(&panel, "root/src", cx).expect("src exists"); + let opened_entry = panel.read_with(cx, |panel, _| panel.selection.expect("file is selected")); + let mut expected_expanded_dir_ids = ["root", "root/src", "root/tests"] + .map(|path| find_project_entry(&panel, path, cx).expect("directory exists")); + expected_expanded_dir_ids.sort_unstable(); + for expand_children in [false, true] { + if expand_children { + toggle_expand_dir(&panel, "root/src", cx); + select_path(&panel, "root/src/h.rs", cx); + panel.update_in(cx, |panel, window, cx| { + panel.expand_selected_entry_and_children( + &ExpandSelectedEntryAndChildren, + window, + cx, + ); + }); + cx.run_until_parked(); + } + panel.update_in(cx, |panel, window, cx| { + panel.scroll_cursor_center(&ScrollCursorCenter, window, cx); + }); + cx.run_until_parked(); + panel.read_with(cx, |panel, _| { + assert_eq!( + panel.state.expanded_dir_ids[&opened_entry.worktree_id], expected_expanded_dir_ids, + "expand_children={expand_children}" + ); + assert!( + entry_row_bounds(panel, parent_id).bottom() < panel.scroll_handle.viewport().top() + ); + }); + + panel.update_in(cx, |panel, window, cx| { + panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx); + }); + cx.run_until_parked(); + + assert_eq!( + visible_entries_as_strings(&panel, 0..usize::MAX, cx), + &[ + "v root", + " > src <== selected", + " v tests", + " a.rs", + " b.rs", + " c.rs", + " d.rs", + " e.rs", + " f.rs", + " g.rs", + " h.rs", + ], + "expand_children={expand_children}" + ); + panel.read_with(cx, |panel, _| { + assert_eq!(panel.marked_entries, [opened_entry]); + let parent_bounds = entry_row_bounds(panel, parent_id); + let viewport = panel.scroll_handle.viewport(); + let sticky_height = parent_bounds.size.height * panel.sticky_items_count; + assert!(parent_bounds.top() >= viewport.top() + sticky_height); + assert!(parent_bounds.bottom() <= viewport.bottom()); + }); + } +} + #[gpui::test] async fn test_collapse_selected_entry_does_not_scroll_visible_parent(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index a0b6f43fc26..37491eb69e3 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -39,6 +39,7 @@ use menu::{ Cancel, Confirm, SelectChild, SelectFirst, SelectLast, SelectNext, SelectParent, SelectPrevious, }; use notifications::status_toast::StatusToast; +use platform_title_bar::apply_title_bar_insets; use project::{ AgentId, AgentRegistryStore, Event as ProjectEvent, WorktreeId, repo_identity_path_if_local, }; @@ -7348,7 +7349,13 @@ impl Sidebar { h_flex() .h(header_height) .map(|header| match window.window_decorations() { - Decorations::Client { .. } => header.mt(px(-1.)), + // Without projects there's no bottom border to match the title bar's. + Decorations::Client { .. } => apply_title_bar_insets( + header, + left_window_controls, + right_window_controls, + no_open_projects, + ), Decorations::Server => header.mt_px().pb_px(), }) .when(left_window_controls, |this| { diff --git a/crates/tabular_data_preview/Cargo.toml b/crates/tabular_data_preview/Cargo.toml index dfa12397019..6fa37648b52 100644 --- a/crates/tabular_data_preview/Cargo.toml +++ b/crates/tabular_data_preview/Cargo.toml @@ -17,13 +17,14 @@ picker.workspace = true ui.workspace = true workspace.workspace = true log.workspace = true +indexmap.workspace = true +serde_json.workspace = true text.workspace = true [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } project = { workspace = true, features = ["test-support"] } proptest.workspace = true -serde_json.workspace = true util.workspace = true workspace = { workspace = true, features = ["test-support"] } diff --git a/crates/tabular_data_preview/src/parser.rs b/crates/tabular_data_preview/src/parser.rs index 791d311f663..9c691d03b36 100644 --- a/crates/tabular_data_preview/src/parser.rs +++ b/crates/tabular_data_preview/src/parser.rs @@ -1,4 +1,7 @@ -use std::sync::Arc; +use indexmap::{IndexMap, IndexSet}; + +use anyhow::Context as _; +use serde_json::value::RawValue; use crate::{ TabularDataPreviewPane, @@ -19,12 +22,13 @@ pub(crate) struct EditorState { pub _subscription: Subscription, } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum TabularFormat { Csv, Tsv, Psv, Ssv, + JsonLines, } const TABULAR_FORMATS: &[(&str, TabularFormat)] = &[ @@ -32,6 +36,8 @@ const TABULAR_FORMATS: &[(&str, TabularFormat)] = &[ ("tsv", TabularFormat::Tsv), ("psv", TabularFormat::Psv), ("ssv", TabularFormat::Ssv), + ("jsonl", TabularFormat::JsonLines), + ("ndjson", TabularFormat::JsonLines), ]; impl TabularFormat { @@ -46,13 +52,15 @@ impl TabularFormat { .map(|(_, format)| *format) } - fn delimiter(self) -> char { - match self { - TabularFormat::Csv => ',', - TabularFormat::Tsv => '\t', - TabularFormat::Psv => '|', - TabularFormat::Ssv => ';', - } + fn parse(self, buffer_snapshot: &BufferSnapshot) -> anyhow::Result { + let delimiter = match self { + Self::Csv => ',', + Self::Tsv => '\t', + Self::Psv => '|', + Self::Ssv => ';', + Self::JsonLines => return from_json_lines(buffer_snapshot), + }; + Ok(from_buffer_with_delimiter(buffer_snapshot, delimiter)) } } @@ -101,7 +109,7 @@ impl TabularDataPreviewPane { } } - let (buffer_snapshot, delimiter) = view.update(cx, |_, cx| { + let (buffer_snapshot, format) = view.update(cx, |_, cx| { let buffer_ref = editor .read(cx) .buffer() @@ -111,26 +119,30 @@ impl TabularDataPreviewPane { let extension = editor_file_extension(&editor, cx); - let delimiter = extension + let format = extension .and_then(TabularFormat::from_extension) - .map(TabularFormat::delimiter) .unwrap_or_else(|| { log::warn!( - "unrecognized tabular data extension {extension:?}, defaulting to comma delimiter" + "unrecognized tabular data extension {extension:?}, defaulting to CSV" ); - ',' + TabularFormat::Csv }); - (buffer_ref, delimiter) + (buffer_ref, format) })?; let Some(buffer_snapshot) = buffer_snapshot else { + view.update(cx, |view, cx| { + view.is_parsing = false; + view.parse_error = Some("Preview requires a single file".into()); + cx.notify(); + })?; return Ok(()); }; let instant = Instant::now(); let parsed_contents = cx - .background_spawn(async move { from_buffer_with_delimiter(&buffer_snapshot, delimiter) }) + .background_spawn(async move { format.parse(&buffer_snapshot) }) .await; let parse_duration = instant.elapsed(); let parse_end_time: Instant = Instant::now(); @@ -140,13 +152,24 @@ impl TabularDataPreviewPane { .timings .insert("Parsing", (parse_duration, Instant::now())); - log::debug!("Parsed {} rows", parsed_contents.rows.len()); - view.engine.contents = Arc::new(parsed_contents); - view.engine.calculate_available_filters(); - view.sync_column_widths(cx); view.last_parse_end_time = Some(parse_end_time); - view.is_parsing = false; + let parsed_contents = match parsed_contents { + Ok(contents) => contents, + Err(error) => { + view.parse_error = Some(format!("{error:#}").into()); + view.filter_sort_task = None; + cx.notify(); + return; + } + }; + + log::debug!("Parsed {} rows", parsed_contents.rows.len()); + view.parse_error = None; + view.engine.set_contents(parsed_contents); + view.list_state + .reset_with_uniform_height(0, view.row_height); + view.sync_column_widths(cx); view.apply_filter_sort(cx); cx.notify(); }) @@ -154,6 +177,98 @@ impl TabularDataPreviewPane { } } +fn from_json_lines(buffer_snapshot: &BufferSnapshot) -> anyhow::Result { + let text = buffer_snapshot.text(); + let mut records = Vec::new(); + let mut columns = IndexSet::new(); + let mut line_numbers = Vec::new(); + + for (line_index, line) in text.lines().enumerate() { + // Ignore blank lines, but keep physical line numbers for the source gutter. + if line.trim().is_empty() { + continue; + } + let record: IndexMap = + serde_json::from_str(line).with_context(|| { + format!( + "Cannot preview JSONL line {}: expected a JSON object", + line_index + 1 + ) + })?; + columns.extend(record.keys().cloned()); + records.push(record); + line_numbers.push(LineNumber::Line(line_index + 1)); + } + + let number_of_cols = columns.len(); + let headers = TableRow::from_vec( + columns + .iter() + .map(|name| TableCell::Generated(name.clone().into())) + .collect(), + number_of_cols, + ); + let rows = records + .into_iter() + .map(|record| { + let cells = columns + .iter() + .map(|name| { + let Some(value) = record.get(name) else { + return Ok(TableCell::Virtual); + }; + let raw = value.get(); + // RawValue borrows the original text, so its span stays exact even + // for repeated values, escaped strings, and large numbers. + let start = (raw.as_ptr() as usize) + .checked_sub(text.as_ptr() as usize) + .context("JSON value is outside the source buffer")?; + Ok(TableCell::from_buffer_position( + compact_json(raw).into(), + start, + start + raw.len(), + buffer_snapshot, + )) + }) + .collect::>>()?; + Ok(TableRow::from_vec(cells, number_of_cols)) + }) + .collect::>>()?; + + Ok(TableLikeContent { + headers, + rows, + line_numbers, + number_of_cols, + }) +} + +fn compact_json(raw: &str) -> String { + // Reserializing through Value can round numbers. Remove only insignificant + // whitespace from the already validated JSON instead. + let mut compact = String::with_capacity(raw.len()); + let mut in_string = false; + let mut escaped = false; + for character in raw.chars() { + if in_string { + compact.push(character); + if escaped { + escaped = false; + } else if character == '\\' { + escaped = true; + } else if character == '"' { + in_string = false; + } + } else if character == '"' { + in_string = true; + compact.push(character); + } else if !matches!(character, ' ' | '\t' | '\r' | '\n') { + compact.push(character); + } + } + compact +} + pub fn from_buffer_with_delimiter( buffer_snapshot: &BufferSnapshot, delimiter: char, @@ -383,6 +498,201 @@ fn create_table_row( #[cfg(test)] mod tests { use super::*; + use text::{Buffer, BufferId, ReplicaId, ToOffset}; + + fn snapshot(text: &str) -> anyhow::Result { + let buffer_id = BufferId::new(1).context("invalid test buffer ID")?; + Ok(Buffer::new(ReplicaId::LOCAL, buffer_id, text.to_owned()) + .snapshot() + .clone()) + } + + fn values(row: &TableRow) -> Vec> { + row.as_slice() + .iter() + .map(|cell| cell.display_value().map(|value| value.as_str())) + .collect() + } + + #[test] + fn test_json_lines_columns_and_values() -> anyhow::Result<()> { + let input = concat!( + "{\"b\":null,\"a\":\"null\",\"nested\":{ \"items\": [1, true] }}\n", + "{\"b\":\"\",\"late\":123456789012345678901234567890}\n", + "{}" + ); + let parsed = TabularFormat::JsonLines.parse(&snapshot(input)?)?; + assert_eq!( + values(&parsed.headers), + vec![Some("b"), Some("a"), Some("nested"), Some("late")] + ); + assert_eq!(parsed.rows.len(), 3); + let rows: Vec<_> = parsed.rows.iter().map(values).collect(); + assert_eq!( + rows, + vec![ + vec![ + Some("null"), + Some(r#""null""#), + Some(r#"{"items":[1,true]}"#), + None + ], + vec![ + Some(r#""""#), + None, + None, + Some("123456789012345678901234567890") + ], + vec![None, None, None, None], + ] + ); + Ok(()) + } + + #[test] + fn test_json_lines_columns_follow_first_seen_key_order() -> anyhow::Result<()> { + let input = concat!( + "{}\n", + "{\"id\":2,\"name\":\"Grace\",\"active\":true}\n", + "{\"name\":\"Ada\",\"tags\":[],\"id\":1,\"details\":{}}\n", + "{\"details\":{},\"active\":false,\"extra\":null}\n" + ); + let parsed = from_json_lines(&snapshot(input)?)?; + assert_eq!( + values(&parsed.headers), + vec![ + Some("id"), + Some("name"), + Some("active"), + Some("tags"), + Some("details"), + Some("extra") + ] + ); + assert_eq!( + values(parsed.rows.get(2).context("missing record")?), + vec![ + Some("1"), + Some(r#""Ada""#), + None, + Some("[]"), + Some("{}"), + None + ] + ); + Ok(()) + } + + #[test] + fn test_json_lines_source_spans_and_line_numbers() -> anyhow::Result<()> { + let input = + "\r\n{\"é\": \"🦀\", \"same\": \"🦀\"}\r\n \t\r\n{\"é\": 1.234567890123456789e100}\n"; + let snapshot = snapshot(input)?; + let parsed = from_json_lines(&snapshot)?; + let normalized_input = snapshot.text(); + assert!(matches!( + parsed.line_numbers.as_slice(), + [LineNumber::Line(2), LineNumber::Line(4)] + )); + assert_eq!(values(&parsed.headers), vec![Some("é"), Some("same")]); + let first_row = parsed.rows.first().context("missing first row")?; + for (cell, expected_start) in first_row.as_slice().iter().zip([ + normalized_input + .find("\"🦀\"") + .context("missing first value")?, + normalized_input + .rfind("\"🦀\"") + .context("missing second value")?, + ]) { + let TableCell::Real { position, .. } = cell else { + anyhow::bail!("expected a source-backed cell"); + }; + assert_eq!(position.start.to_offset(&snapshot), expected_start); + assert_eq!( + position.end.to_offset(&snapshot), + expected_start + "\"🦀\"".len() + ); + } + assert_eq!( + values(parsed.rows.last().context("missing last row")?), + vec![Some("1.234567890123456789e100"), None] + ); + Ok(()) + } + + #[test] + fn test_json_lines_compact_values_preserve_strings_and_numbers() -> anyhow::Result<()> { + let input = r#"{"value": { "text": "a b\t\"c\\", "numbers": [ -0, 1e999, 123456789012345678901234567890 ] }}"#; + let parsed = from_json_lines(&snapshot(input)?)?; + assert_eq!( + values(parsed.rows.first().context("missing row")?), + vec![Some( + r#"{"text":"a b\t\"c\\","numbers":[-0,1e999,123456789012345678901234567890]}"# + )] + ); + Ok(()) + } + + #[test] + fn test_json_lines_empty_input_and_empty_objects() -> anyhow::Result<()> { + for input in ["", "\n \t\r\n"] { + let parsed = from_json_lines(&snapshot(input)?)?; + assert!(parsed.rows.is_empty()); + assert_eq!(parsed.number_of_cols, 0); + } + let parsed = from_json_lines(&snapshot("{}\n{}\n")?)?; + assert_eq!(parsed.number_of_cols, 0); + assert_eq!(parsed.rows.len(), 2); + assert!(parsed.rows.iter().all(|row| row.cols() == 0)); + Ok(()) + } + + #[test] + fn test_json_lines_errors_identify_the_source_line() -> anyhow::Result<()> { + for invalid in [ + "{", + "{\"a\":}", + "{} trailing", + "{} {}", + "[]", + "null", + "true", + "42", + "\"text\"", + ] { + let input = format!("{{}}\n\n{invalid}\n{{}}\n"); + let result = from_json_lines(&snapshot(&input)?); + let Err(error) = result else { + anyhow::bail!("accepted invalid record: {invalid}"); + }; + assert!(error.to_string().contains("line 3"), "{error:#}"); + } + Ok(()) + } + + #[test] + fn test_format_dispatch() -> anyhow::Result<()> { + for extension in ["jsonl", "ndjson", "JSONL", "nDjSoN"] { + let format = TabularFormat::from_extension(extension).context("format not detected")?; + assert_eq!(format, TabularFormat::JsonLines); + assert_eq!( + format.parse(&snapshot("{\"name\":\"Ada\"}")?)?.rows.len(), + 1 + ); + } + assert!(TabularFormat::from_extension("json").is_none()); + for (extension, delimiter) in [("csv", ','), ("tsv", '\t'), ("psv", '|'), ("ssv", ';')] { + let input = format!("name{delimiter}age\nAda{delimiter}36"); + let format = TabularFormat::from_extension(extension).context("format not detected")?; + let parsed = format.parse(&snapshot(&input)?)?; + assert_eq!(values(&parsed.headers), vec![Some("name"), Some("age")]); + assert_eq!( + values(parsed.rows.first().context("missing row")?), + vec![Some("Ada"), Some("36")] + ); + } + Ok(()) + } #[test] fn test_csv_parsing_basic() { diff --git a/crates/tabular_data_preview/src/renderer/preview_view.rs b/crates/tabular_data_preview/src/renderer/preview_view.rs index e8c4822523f..505b18aea6b 100644 --- a/crates/tabular_data_preview/src/renderer/preview_view.rs +++ b/crates/tabular_data_preview/src/renderer/preview_view.rs @@ -6,6 +6,14 @@ use crate::TabularDataPreviewPane; use super::settings::settings_popover_menu; +impl TabularDataPreviewPane { + fn is_ready_to_render_content(&self) -> bool { + !self.is_parsing + && self.parse_error.is_none() + && (self.engine.contents.number_of_cols > 0 || !self.engine.contents.rows.is_empty()) + } +} + impl Render for TabularDataPreviewPane { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -25,7 +33,7 @@ impl Render for TabularDataPreviewPane { .track_focus(&self.focus_handle) .child({ let is_parsing = self.is_parsing; - if is_parsing || self.engine.contents.number_of_cols == 0 { + if !self.is_ready_to_render_content() { v_flex() .size_full() .child( @@ -54,7 +62,15 @@ impl Render for TabularDataPreviewPane { .child("Loading…"), ) }) - .when(!is_parsing, |div| div.child("No data to display")), + .when(!is_parsing, |div| { + if let Some(error) = &self.parse_error { + div.p_4() + .text_color(cx.theme().status().error) + .child(error.clone()) + } else { + div.child("No data to display") + } + }), ) .into_any_element() } else { diff --git a/crates/tabular_data_preview/src/renderer/render_table.rs b/crates/tabular_data_preview/src/renderer/render_table.rs index 90e71a1d5ea..7ed0841f4bc 100644 --- a/crates/tabular_data_preview/src/renderer/render_table.rs +++ b/crates/tabular_data_preview/src/renderer/render_table.rs @@ -17,7 +17,11 @@ impl TabularDataPreviewPane { current_widths: &Entity, cx: &mut Context, ) -> AnyElement { - self.create_table_inner(self.engine.contents.rows.len(), current_widths, cx) + self.create_table_inner( + self.engine.d2d_mapping().visible_row_count(), + current_widths, + cx, + ) } fn create_table_inner( @@ -164,6 +168,7 @@ impl TabularDataPreviewPane { format!("Pos {so}(L{slv})-{eo}(L{elv})") } TableCell::Virtual => "Virtual cell".into(), + TableCell::Generated(_) => "Generated cell".into(), }, )) }) diff --git a/crates/tabular_data_preview/src/table_data_engine.rs b/crates/tabular_data_preview/src/table_data_engine.rs index 5a8f86a4659..b803439d6d4 100644 --- a/crates/tabular_data_preview/src/table_data_engine.rs +++ b/crates/tabular_data_preview/src/table_data_engine.rs @@ -34,6 +34,30 @@ pub(crate) struct TableDataEngine { } impl TableDataEngine { + pub(crate) fn set_contents(&mut self, contents: TableLikeContent) { + if self + .contents + .headers + .as_slice() + .iter() + .map(TableCell::display_value) + .ne(contents + .headers + .as_slice() + .iter() + .map(TableCell::display_value)) + { + // Filters and sorting use column indexes, which may now name different fields. + self.filter_stack = FilterStack::default(); + self.applied_sorting = None; + } + self.contents = Arc::new(contents); + // The previous mapping can reference rows removed by an edit. Keep it empty + // until the background filter/sort task builds a mapping for the new contents. + self.d2d_mapping = DisplayToDataMapping::default(); + self.calculate_available_filters(); + } + pub(crate) fn d2d_mapping(&self) -> &DisplayToDataMapping { &self.d2d_mapping } diff --git a/crates/tabular_data_preview/src/tabular_data_preview.rs b/crates/tabular_data_preview/src/tabular_data_preview.rs index 8ec5689b85f..9b72d6f15aa 100644 --- a/crates/tabular_data_preview/src/tabular_data_preview.rs +++ b/crates/tabular_data_preview/src/tabular_data_preview.rs @@ -33,6 +33,7 @@ pub struct TabularDataPreviewPane { pub(crate) column_widths: ColumnWidths, pub(crate) parsing_task: Option>>, pub(crate) is_parsing: bool, + pub(crate) parse_error: Option, /// Background task computing the display-to-data mapping after a filter/sort change. /// Stored here so that a new change cancels the previous in-flight computation. pub(crate) filter_sort_task: Option>, @@ -187,6 +188,7 @@ impl TabularDataPreviewPane { column_widths: ColumnWidths::new(cx, 1), parsing_task: None, is_parsing: false, + parse_error: None, filter_sort_task: None, performance_metrics: PerformanceMetrics::default(), list_state: gpui::ListState::new(contents.rows.len(), ListAlignment::Top, px(1.)) @@ -379,12 +381,12 @@ mod tests { let fs = FakeFs::new(cx.executor()); fs.insert_tree( path!("/project"), - json!({ "inside.csv": "a,b\n1,2\n", "inside.txt": "plain" }), + json!({ "inside.csv": "a,b\n1,2\n", "inside.jsonl": "{}\n", "inside.txt": "plain" }), ) .await; fs.insert_tree( path!("/elsewhere"), - json!({ "outside.csv": "a,b\n1,2\n", "outside.txt": "plain" }), + json!({ "outside.csv": "a,b\n1,2\n", "outside.NDJSON": "{}\n", "outside.txt": "plain" }), ) .await; @@ -392,8 +394,10 @@ mod tests { for (abs_path, expected) in [ (path!("/project/inside.csv"), true), + (path!("/project/inside.jsonl"), true), (path!("/project/inside.txt"), false), (path!("/elsewhere/outside.csv"), true), + (path!("/elsewhere/outside.NDJSON"), true), (path!("/elsewhere/outside.txt"), false), ] { let buffer = project @@ -409,6 +413,211 @@ mod tests { } } + #[gpui::test(iterations = 20)] + async fn test_csv_preview_mapping_stays_valid_after_deleting_multiline_rows( + cx: &mut TestAppContext, + ) { + use types::DisplayRow; + + init_test(cx); + let result: anyhow::Result<()> = async { + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/project"), + json!({ "records.csv": "id,note\n1,first\n2,\"two\nlines\"\n" }), + ) + .await; + let project = Project::test(fs, [Path::new(path!("/project"))], cx).await; + let buffer = project + .update(cx, |project, cx| { + project.open_local_buffer(path!("/project/records.csv"), cx) + }) + .await?; + let (workspace, cx) = + cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); + let editor = cx.update(|window, cx| { + cx.new(|cx| Editor::for_buffer(buffer, Some(project), window, cx)) + }); + let preview = workspace.update_in(cx, |workspace, window, cx| { + let pane = workspace.active_pane().clone(); + TabularDataPreviewPane::open_preview_in_pane( + editor.clone(), + pane.clone(), + window, + cx, + ); + pane.read(cx) + .items_of_type::() + .next() + }); + let Some(preview) = preview else { + anyhow::bail!("preview did not open"); + }; + cx.condition(&preview, |preview, _| { + !preview.is_parsing && preview.engine.d2d_mapping().visible_row_count() == 2 + }) + .await; + + let _subscription = cx.update(|_, cx| { + cx.observe(&preview, |preview, cx| { + let preview = preview.read(cx); + if !preview.is_parsing && preview.parse_error.is_none() { + let mapping = preview.engine.d2d_mapping(); + assert_eq!(preview.list_state.item_count(), mapping.visible_row_count()); + for display_row in 0..mapping.visible_row_count() { + assert!( + mapping + .get_data_row(DisplayRow(display_row)) + .and_then(|data_row| preview.engine.contents.get_row(data_row)) + .is_some(), + "display mapping points to a deleted row" + ); + } + } + }) + }); + + for (text, expected_rows) in [ + ( + "id,note\n1,first\n2,\"two\nlines\"\n3,\"pasted\ntext\"\n", + 3, + ), + ("id,note\n1,first\n", 1), + ("id,note\n", 0), + ("id,note\n1,\"restored\ntext\"\n", 1), + ] { + editor.update_in(cx, |editor, window, cx| { + editor.set_text(text, window, cx); + }); + cx.condition(&preview, |preview, _| { + !preview.is_parsing + && preview.engine.contents.rows.len() == expected_rows + && preview.engine.d2d_mapping().visible_row_count() == expected_rows + }) + .await; + } + Ok(()) + } + .await; + assert!(result.is_ok(), "{result:?}"); + } + + #[gpui::test] + async fn test_json_lines_preview_recovers_after_edits(cx: &mut TestAppContext) { + use table_data_engine::sorting_by_column::{AppliedSorting, SortDirection}; + use types::{AnyColumn, DataRow, DisplayRow}; + + init_test(cx); + let result: anyhow::Result<()> = async { + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/project"), + json!({ "records.jsonl": "{\"name\":\"Grace\"}\n{\"name\":\"Ada\"}\n" }), + ) + .await; + let project = Project::test(fs, [Path::new(path!("/project"))], cx).await; + let buffer = project + .update(cx, |project, cx| { + project.open_local_buffer(path!("/project/records.jsonl"), cx) + }) + .await?; + let (workspace, cx) = + cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); + let editor = cx.update(|window, cx| { + cx.new(|cx| Editor::for_buffer(buffer, Some(project), window, cx)) + }); + let preview = workspace.update_in(cx, |workspace, window, cx| { + let pane = workspace.active_pane().clone(); + TabularDataPreviewPane::open_preview_in_pane( + editor.clone(), + pane.clone(), + window, + cx, + ); + pane.read(cx) + .items_of_type::() + .next() + }); + let Some(preview) = preview else { + anyhow::bail!("preview did not open"); + }; + cx.condition(&preview, |preview, _| { + !preview.is_parsing && preview.engine.d2d_mapping().visible_row_count() == 2 + }) + .await; + + preview.update(cx, |preview, cx| { + preview.engine.applied_sorting = Some(AppliedSorting { + col_idx: AnyColumn(0), + direction: SortDirection::Asc, + }); + preview.toggle_filter(AnyColumn(0), Some(r#""Ada""#.into()), cx); + }); + cx.condition(&preview, |preview, _| { + preview.engine.d2d_mapping().visible_row_count() == 1 + }) + .await; + preview.read_with(cx, |preview, _| { + assert_eq!( + preview.engine.d2d_mapping().get_data_row(DisplayRow(0)), + Some(DataRow(1)) + ); + }); + + editor.update_in(cx, |editor, window, cx| { + editor.set_text("{\"name\":\"Ada\"}\n{", window, cx); + }); + cx.condition(&preview, |preview, _| { + !preview.is_parsing && preview.parse_error.is_some() + }) + .await; + preview.read_with(cx, |preview, _| { + assert!( + preview + .parse_error + .as_ref() + .is_some_and(|error| error.contains("line 2")) + ); + }); + + editor.update_in(cx, |editor, window, cx| { + editor.set_text("{\"name\":\"Ada\"}\n{\"name\":\"Grace\"}", window, cx); + }); + cx.condition(&preview, |preview, _| { + !preview.is_parsing + && preview.parse_error.is_none() + && preview.engine.d2d_mapping().get_data_row(DisplayRow(0)) == Some(DataRow(0)) + }) + .await; + preview.read_with(cx, |preview, _| { + assert!(preview.engine.has_active_filters(AnyColumn(0))); + assert!(preview.engine.applied_sorting.is_some()); + }); + + editor.update_in(cx, |editor, window, cx| { + editor.set_text( + "{\"age\":36,\"name\":\"Ada\"}\n{\"name\":\"Grace\"}", + window, + cx, + ); + }); + cx.condition(&preview, |preview, _| { + !preview.is_parsing + && preview.engine.contents.number_of_cols == 2 + && preview.engine.d2d_mapping().visible_row_count() == 2 + }) + .await; + preview.read_with(cx, |preview, _| { + assert!(!preview.engine.has_active_filters(AnyColumn(0))); + assert!(preview.engine.applied_sorting.is_none()); + assert!(preview.parse_error.is_none()); + }); + Ok(()) + } + .await; + assert!(result.is_ok(), "{result:?}"); + } + fn init_test(cx: &mut TestAppContext) { cx.update(|cx| { AppState::test(cx); diff --git a/crates/tabular_data_preview/src/types/table_cell.rs b/crates/tabular_data_preview/src/types/table_cell.rs index 4e9c8bb0b66..64ba8cb51bc 100644 --- a/crates/tabular_data_preview/src/types/table_cell.rs +++ b/crates/tabular_data_preview/src/types/table_cell.rs @@ -20,6 +20,8 @@ pub enum TableCell { /// Cached display value (for performance) cached_value: SharedString, }, + /// Display text without a source span, used for generated column headings. + Generated(SharedString), /// Virtual cell, created to pad malformed row Virtual, } @@ -48,6 +50,7 @@ impl TableCell { pub fn display_value(&self) -> Option<&SharedString> { match self { TableCell::Real { cached_value, .. } => Some(cached_value), + TableCell::Generated(value) => Some(value), TableCell::Virtual => None, } } diff --git a/crates/theme/src/theme.rs b/crates/theme/src/theme.rs index a23bedd504f..d2e13047267 100644 --- a/crates/theme/src/theme.rs +++ b/crates/theme/src/theme.rs @@ -53,6 +53,8 @@ pub const DEFAULT_DARK_THEME: &str = "One Dark"; pub const CLIENT_SIDE_DECORATION_ROUNDING: Pixels = px(10.0); /// Defines window shadow size for platforms that use client side decorations. pub const CLIENT_SIDE_DECORATION_SHADOW: Pixels = px(10.0); +/// Defines window border width for platforms that use client side decorations. +pub const CLIENT_SIDE_DECORATION_BORDER: Pixels = px(1.0); /// Styling helpers for elements that follow client-side window decorations. pub trait ClientDecorationsExt: Styled { diff --git a/crates/ui/src/components/data_table.rs b/crates/ui/src/components/data_table.rs index d7cdaf2a8d8..a8c103d910b 100644 --- a/crates/ui/src/components/data_table.rs +++ b/crates/ui/src/components/data_table.rs @@ -641,7 +641,6 @@ pub fn render_table_row( Some(widths) => widths.clone().map(Some), None => vec![None; cols].into_table_row(cols), }; - let mut row = div() // NOTE: `h_flex()` sneakily applies `items_center()` which is not default behavior for div element. // Applying `.flex().flex_row()` manually to overcome that @@ -652,38 +651,56 @@ pub fn render_table_row( .when_some(bg, |row, bg| row.bg(bg)) .when(table_context.show_row_hover, |row| { row.hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.6))) - }) - .when(!is_striped && table_context.show_row_borders, |row| { - row.border_b_1() - .border_color(transparent_black()) - .when(!is_last, |row| row.border_color(cx.theme().colors().border)) }); let pinned_cols = table_context.pinned_cols; let column_filter = &table_context.column_filter; - if is_pinned_layout(pinned_cols, cols) { - let items_vec: Vec = items.map(IntoElement::into_any_element).into_vec(); - let widths_vec: Vec> = column_widths.into_vec(); + // Only `Resizable` columns (independent absolute pixel widths) should leave the wrapper + // hugging their combined width so the row border stops at the last column. Percentage + // widths (`Redistributable`) need a full-size ancestor for their fractions to resolve + // against, and `flex_1`/auto cells are meant to stretch across the whole row anyway. + let is_absolute_width_table = table_context.column_widths.as_ref().is_some_and(|widths| { + widths + .as_slice() + .iter() + .all(|width| matches!(width, Length::Definite(DefiniteLength::Absolute(_)))) + }); + let cell_iter = items + .into_vec() + .into_iter() + .map(IntoElement::into_any_element) + .zip(column_widths.into_vec()) + .enumerate() + .filter(|(idx, _)| column_is_visible(column_filter, *idx)) + .map(|(_, pair)| pair); + + let render_section = |cells: Box)>>| { + div() + .flex() + .flex_row() + .when(!is_striped && table_context.show_row_borders, |row| { + row.border_b_1().map(|row| { + if is_last { + row.border_color(transparent_black()) + } else { + row.border_color(cx.theme().colors().border) + } + }) + }) + .children(cells.map(|(cell, width)| render_cell(width, cell, &table_context, cx))) + }; + + if is_pinned_layout(pinned_cols, cols) && is_absolute_width_table { // Drop filtered columns before splitting into pinned/scrollable sections. The number of // pinned columns that survive filtering determines where the kept cells are split. let pinned_visible = (0..pinned_cols) .filter(|&idx| column_is_visible(column_filter, idx)) .count(); - let mut kept: Vec<(AnyElement, Option)> = items_vec - .into_iter() - .zip(widths_vec) - .enumerate() - .filter(|(idx, _)| column_is_visible(column_filter, *idx)) - .map(|(_, pair)| pair) - .collect(); - let scrollable: Vec<(AnyElement, Option)> = kept.drain(pinned_visible..).collect(); - let pinned_section = div().flex().flex_row().flex_shrink_0().children( - kept.into_iter() - .map(|(cell, width)| render_cell(width, cell, &table_context, cx)), - ); + let mut cells: Vec<_> = cell_iter.collect(); + let scrollable_cells = cells.split_off(pinned_visible); // Scrollable section: overflow_x_scroll + track_scroll so GPUI handles the visual // shift natively without requiring per-scroll re-renders of list items. @@ -694,29 +711,19 @@ pub fn render_table_row( .overflow_x_scroll() .restrict_scroll_to_axis() .flex() - .child( - div().flex().flex_row().children( - scrollable - .into_iter() - .map(|(cell, width)| render_cell(width, cell, &table_context, cx)), - ), - ); + .child(render_section(Box::new(scrollable_cells.into_iter()))); if let Some(ref handle) = table_context.h_scroll_handle { scrollable_section = scrollable_section.track_scroll(handle); } + let pinned_section = render_section(Box::new(cells.into_iter())).flex_shrink_0(); + row = row.child(pinned_section).child(scrollable_section); } else { - row = row.children( - items - .map(IntoElement::into_any_element) - .into_vec() - .into_iter() - .zip(column_widths.into_vec()) - .enumerate() - .filter(|(idx, _)| column_is_visible(column_filter, *idx)) - .map(|(_, (cell, width))| render_cell(width, cell, &table_context, cx)), + row = row.child( + render_section(Box::new(cell_iter)) + .when(!is_absolute_width_table, |this| this.size_full()), ); } diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index afe8c7d7adb..7d50ce7297f 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -11938,7 +11938,6 @@ pub fn client_side_decorations( window: &mut Window, cx: &mut App, ) -> Stateful
{ - const BORDER_SIZE: Pixels = px(1.0); let decorations = window.window_decorations(); let is_resizable = window.is_resizable(); let tiling = match decorations { @@ -12018,10 +12017,18 @@ pub fn client_side_decorations( Decorations::Client { .. } => div .border_color(cx.theme().colors().border) .rounded_client_corners(tiling) - .when(!tiling.top, |div| div.border_t(BORDER_SIZE)) - .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE)) - .when(!tiling.left, |div| div.border_l(BORDER_SIZE)) - .when(!tiling.right, |div| div.border_r(BORDER_SIZE)) + .when(!tiling.top, |div| { + div.border_t(theme::CLIENT_SIDE_DECORATION_BORDER) + }) + .when(!tiling.bottom, |div| { + div.border_b(theme::CLIENT_SIDE_DECORATION_BORDER) + }) + .when(!tiling.left, |div| { + div.border_l(theme::CLIENT_SIDE_DECORATION_BORDER) + }) + .when(!tiling.right, |div| { + div.border_r(theme::CLIENT_SIDE_DECORATION_BORDER) + }) .when(!tiling.is_tiled(), |div| { div.shadow(vec![ gpui::BoxShadow::new( diff --git a/docs/src/languages/json.md b/docs/src/languages/json.md index dcede992407..6aadc0c8565 100644 --- a/docs/src/languages/json.md +++ b/docs/src/languages/json.md @@ -10,6 +10,14 @@ JSON support is available natively in Zed. - Tree-sitter: [tree-sitter/tree-sitter-json](https://github.com/tree-sitter/tree-sitter-json) - Language Server: [zed-industries/json-language-server](https://github.com/zed-industries/json-language-server) +## JSON Lines Preview + +Open a `.jsonl` or `.ndjson` file and run {#action tabular_data::OpenPreview} to view it as a read-only table. Use {#action tabular_data::OpenPreviewToTheSide} to keep the source visible alongside the preview. + +Each nonblank line must contain a JSON object. Top-level keys become columns in the order they first appear in the file. Keys from the first record keep their source order, and new keys from later records are appended to the right. Missing fields appear as empty cells. Values retain their JSON representation, so `null`, `"null"`, and `""` remain distinct; nested objects and arrays appear as compact JSON. + +The preview updates as you edit the source. Invalid records show an error with the source line number. Sorting compares the displayed text, and changing the column names or order clears active sorting and filters. + ## JSONC Zed also supports a super-set of JSON called JSONC, which allows single line comments (`//`) in JSON files. diff --git a/docs/src/outline-panel.md b/docs/src/outline-panel.md index f6c3dc59b25..973835c6a98 100644 --- a/docs/src/outline-panel.md +++ b/docs/src/outline-panel.md @@ -11,6 +11,22 @@ When viewing a "singleton" buffer (i.e., a single file on a tab), the outline pa ![Using the outline panel in a singleton buffer](https://zed.dev/img/outline-panel/singleton.png) +## Navigation {#navigation} + +Single-click a row to select it and scroll the editor without expanding or collapsing it, including folded files and symbols. +Double-click a row to navigate and focus the editor, except for folder and excerpt rows, which keep focus in the outline panel. + +Click an entry's expand/collapse arrow to fold or unfold it without navigating to it. +Clicking a file or folder icon navigates like clicking its label; it does not toggle expansion. + +For folder arrows, set `outline_panel.folder_indicator` to `"chevron"` or `"both"`. +The `"icon"` setting hides folder arrows, but you can still use {#action outline_panel::ExpandSelectedEntry} and {#action outline_panel::CollapseSelectedEntry}. + +In a multibuffer, clicking a folder row scrolls to the first file beneath that occurrence of the folder and leaves the folder selected. +This also works for collapsed folders and compacted folder paths. +When symbols are hidden in a multibuffer, file rows have no expand/collapse arrows because they have no children in the panel. +Folder arrows remain available, and clicking any row still navigates without changing its folded state. + ## Usage with multibuffers File rows follow the order of the files in the multibuffer.