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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions app/src/ai/blocklist/context_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

use ai::project_context::model::ProjectContextModel;
use parking_lot::FairMutex;
use warp_core::features::FeatureFlag;
use warp_util::local_or_remote_path::LocalOrRemotePath;
use warpui::{
AppContext, Entity, EntityId, ModelContext, ModelHandle, SingletonEntity, WeakModelHandle,
};
Expand Down Expand Up @@ -393,7 +393,14 @@ impl BlocklistAIContextModel {
/// Returns `AIAgentContext` for the blocks to be included in the current AI query.
/// If `is_user_query` is true, includes blocks, selected text, and images as context.
/// If false, excludes these user-specific contexts but includes everything else.
pub fn pending_context(&self, app: &AppContext, is_user_query: bool) -> Vec<AIAgentContext> {
pub fn pending_context(
&self,
app: &AppContext,
is_user_query: bool,
current_working_directory_location: Option<&LocalOrRemotePath>,
Comment thread
moirahuang marked this conversation as resolved.
) -> Vec<AIAgentContext> {
// `pwd` is the shell-reported path used for directory context and local indexing.
// The location is passed separately because it preserves remote host identity for rules.
let pwd = self.current_pwd();
let is_pwd_indexed = if cfg!(feature = "agent_mode_evals") {
// In evals, we want to disable file outline based search. Full
Expand All @@ -406,15 +413,8 @@ impl BlocklistAIContextModel {
})
};

let project_rules = if let Some(pwd) = pwd.clone().and_then(|path| {
PathBuf::from_str(&path)
.ok()
.and_then(|s| s.canonicalize().ok())
}) {
ProjectContextModel::as_ref(app).find_applicable_rules(&pwd)
} else {
None
};
let project_rules = current_working_directory_location

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we're already typed, that simplifies this logic here

.and_then(|pwd| ProjectContextModel::as_ref(app).find_applicable_rules(pwd));

let mut context = Vec::new();

Expand Down Expand Up @@ -451,14 +451,14 @@ impl BlocklistAIContextModel {
// Always include project rules if available
if let Some(rules) = project_rules {
context.push(AIAgentContext::ProjectRules {
root_path: rules.root_path.to_string_lossy().into(),
root_path: rules.root_path.display_path(),
active_rules: rules
.active_rules
.into_iter()
.map(|rule| {
let line_count = rule.content.lines().count();
FileContext {
file_name: rule.path.to_string_lossy().into(),
file_name: rule.path.display_path(),
content: AnyFileContent::StringContent(rule.content.clone()),
line_range: None,
last_modified: None,
Expand Down
7 changes: 6 additions & 1 deletion app/src/ai/blocklist/controller/input_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ pub(super) fn input_context_for_request(
additional_context: Vec<AIAgentContext>,
app: &AppContext,
) -> Arc<[AIAgentContext]> {
let mut context = context_model.pending_context(app, is_user_query);
let current_working_directory_location = active_session.current_working_directory_location(app);
let mut context = context_model.pending_context(
app,
is_user_query,
current_working_directory_location.as_ref(),
);

context.push(AIAgentContext::CurrentTime {
current_time: Local::now(),
Expand Down
3 changes: 2 additions & 1 deletion app/src/ai/facts/view/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::path::PathBuf;

use warp_core::ui::appearance::Appearance;
use warp_util::local_or_remote_path::LocalOrRemotePath;
use warpui::elements::{
Align, ChildView, ClippedScrollStateHandle, ClippedScrollable, ConstrainedBox, Container,
CrossAxisAlignment, Expanded, Flex, MainAxisAlignment, MainAxisSize, ParentElement,
Expand Down Expand Up @@ -55,7 +56,7 @@ impl std::fmt::Display for AIFactPage {
pub enum AIFactViewEvent {
Pane(PaneEvent),
OpenSettings,
OpenFile(PathBuf),
OpenFile(LocalOrRemotePath),
InitializeProject(PathBuf),
}

Expand Down
25 changes: 16 additions & 9 deletions app/src/ai/facts/view/rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use markdown_parser::weight::CustomWeight;
use markdown_parser::{FormattedText, FormattedTextFragment, FormattedTextLine};
use warp_core::ui::appearance::{Appearance, AppearanceEvent};
use warp_core::ui::theme::color::internal_colors;
use warp_util::local_or_remote_path::LocalOrRemotePath;
use warpui::elements::{
Align, Border, ChildView, ConstrainedBox, Container, CornerRadius, CrossAxisAlignment,
Expanded, Flex, FormattedTextElement, HighlightedHyperlink, Hoverable, MainAxisAlignment,
Expand Down Expand Up @@ -38,6 +39,7 @@ use crate::server::ids::{ClientId, SyncId};
use crate::server::sync_queue::SyncQueue;
use crate::settings::{AISettings, AISettingsChangedEvent};
use crate::ui_components::icons::Icon;
use crate::util::path::display_path_with_host;
use crate::view_components::action_button::{ActionButton, NakedTheme};
use crate::view_components::DismissibleToast;
use crate::workspace::ToastStack;
Expand Down Expand Up @@ -68,7 +70,7 @@ pub enum RuleViewEvent {
AddRule,
Edit(SyncId),
OpenSettings,
OpenFile(PathBuf),
OpenFile(LocalOrRemotePath),
InitializeProject(PathBuf),
}

Expand All @@ -79,7 +81,7 @@ pub enum RuleViewAction {
Edit(SyncId),
OpenSettings,
SelectScope(RuleScope),
OpenFile(PathBuf),
OpenFile(LocalOrRemotePath),
}

#[derive(Default, Debug, Clone)]
Expand All @@ -101,7 +103,7 @@ struct CloudRuleRow {
/// plus an "Open file" button.
#[derive(Debug, Clone)]
struct FileBackedRow {
file_path: PathBuf,
file_path: LocalOrRemotePath,
mouse_state: MouseStateHandle,
}

Expand All @@ -126,9 +128,9 @@ impl RuleRow {
}
RuleRow::FileBacked(row) => row
.file_path
.to_str()
.map(|s| s.to_lowercase().contains(search_term))
.unwrap_or(false),
.display_path()
.to_lowercase()
.contains(search_term),
}
}

Expand All @@ -137,7 +139,9 @@ impl RuleRow {
(RuleRow::Global(a), RuleRow::Global(b)) => {
b.fact.metadata().revision.cmp(&a.fact.metadata().revision)
}
(RuleRow::FileBacked(a), RuleRow::FileBacked(b)) => a.file_path.cmp(&b.file_path),
(RuleRow::FileBacked(a), RuleRow::FileBacked(b)) => {
a.file_path.display_path().cmp(&b.file_path.display_path())
}
_ => std::cmp::Ordering::Equal,
}
}
Expand Down Expand Up @@ -704,8 +708,9 @@ impl RuleView {
&self,
project_row: FileBackedRow,
appearance: &Appearance,
app: &AppContext,
) -> Option<Box<dyn Element>> {
let row_name = project_row.file_path.to_str().map(|s| s.to_string())?;
let row_name = display_path_with_host(&project_row.file_path, false, app);
let mut row = Flex::row()
.with_main_axis_size(MainAxisSize::Max)
.with_main_axis_alignment(MainAxisAlignment::SpaceBetween)
Expand Down Expand Up @@ -868,7 +873,9 @@ impl RuleView {
RuleRow::Global(global_row) => {
Some(self.render_global_rule_row(*global_row, appearance, app))
}
RuleRow::FileBacked(file_row) => self.render_file_backed_row(file_row, appearance),
RuleRow::FileBacked(file_row) => {
self.render_file_backed_row(file_row, appearance, app)
}
};

if let Some(row) = row {
Expand Down
110 changes: 110 additions & 0 deletions app/src/ai/metadata_project_rules.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use std::collections::HashMap;

use ai::project_context::model::ProjectRuleContents;
use futures::future::{BoxFuture, FutureExt as _};
use remote_server::proto::{
file_context_proto, FileContextProto, ReadFileContextFile, ReadFileContextRequest,
};
use warp_util::local_or_remote_path::LocalOrRemotePath;
use warpui::{AppContext, SingletonEntity};

use crate::remote_server::manager::RemoteServerManager;

pub(crate) fn read_project_rule_contents(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aka ProjectRuleContentReader

rule_paths: Vec<LocalOrRemotePath>,
ctx: &AppContext,
) -> BoxFuture<'static, anyhow::Result<ProjectRuleContents>> {
match rule_paths.first() {
None => futures::future::ready(Ok(Vec::new())).boxed(),
Some(LocalOrRemotePath::Local(_)) => async move {
let mut contents = Vec::new();
for path in rule_paths {
let Some(local_path) = path.to_local_path().map(std::path::Path::to_path_buf)
else {
anyhow::bail!("Project rule paths mixed local and remote locations");
};
match async_fs::read_to_string(&local_path).await {
Ok(content) => contents.push((path, content)),
Err(error) => log::debug!(
"Failed to read project rule file {}: {error}",
local_path.display()
),
}
}
Ok(contents)
}
.boxed(),
Some(LocalOrRemotePath::Remote(remote)) => {
let host_id = remote.host_id.clone();
let handle = RemoteServerManager::as_ref(ctx).host_request_handle(&host_id);
async move {
if rule_paths.iter().any(|path| {
!matches!(
path,
LocalOrRemotePath::Remote(candidate) if candidate.host_id == host_id
)
}) {
anyhow::bail!("Project rule paths span multiple locations");
}
let response = handle
.read_file_context(remote_rule_read_request(&rule_paths))
.await?;
Ok(pair_remote_rule_paths_with_contents(
rule_paths,
response.file_contexts,
))
}
.boxed()
}
}
}

fn remote_rule_read_request(rule_paths: &[LocalOrRemotePath]) -> ReadFileContextRequest {
ReadFileContextRequest {
files: rule_paths
.iter()
.filter_map(|path| match path {
LocalOrRemotePath::Remote(remote) => Some(ReadFileContextFile {
path: remote.path.as_str().to_string(),
line_ranges: Vec::new(),
}),
LocalOrRemotePath::Local(_) => None,
})
.collect(),
max_file_bytes: None,
max_batch_bytes: None,
}
}

/// Pairs remote read responses with the original host-qualified paths.
///
/// Responses may be reordered or omit unreadable files, and their file names do not include the
/// host ID. Matching by path preserves the correct host identity without relying on response order.
fn pair_remote_rule_paths_with_contents(
rule_paths: Vec<LocalOrRemotePath>,
file_contexts: Vec<FileContextProto>,
) -> Vec<(LocalOrRemotePath, String)> {
let content_by_path = file_contexts
.into_iter()
.filter_map(|file_context| {
let file_context_proto::Content::TextContent(content) = file_context.content? else {
return None;
};
Some((file_context.file_name, content))
})
.collect::<HashMap<_, _>>();
rule_paths
.into_iter()
.filter_map(|path| {
let LocalOrRemotePath::Remote(remote) = &path else {
return None;
};
let content = content_by_path.get(remote.path.as_str())?.clone();
Some((path, content))
})
.collect()
}

#[cfg(test)]
#[path = "metadata_project_rules_tests.rs"]
mod tests;
89 changes: 89 additions & 0 deletions app/src/ai/metadata_project_rules_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use remote_server::proto::{file_context_proto, FileContextProto};
use warp_util::host_id::HostId;
use warp_util::local_or_remote_path::LocalOrRemotePath;
use warp_util::remote_path::RemotePath;
use warp_util::standardized_path::StandardizedPath;

use super::{pair_remote_rule_paths_with_contents, remote_rule_read_request};

fn remote_rule_path(host_id: &HostId, name: &str) -> LocalOrRemotePath {
LocalOrRemotePath::Remote(RemotePath::new(
host_id.clone(),
StandardizedPath::try_new(format!("/repo/{name}").as_str()).unwrap(),
))
}

fn remote_rule_file_context(path: &LocalOrRemotePath, content: &str) -> FileContextProto {
let LocalOrRemotePath::Remote(remote) = path else {
panic!("Expected a remote rule path");
};

FileContextProto {
file_name: remote.path.as_str().to_string(),
content: Some(file_context_proto::Content::TextContent(
content.to_string(),
)),
line_range_start: None,
line_range_end: None,
last_modified_epoch_millis: None,
line_count: content.lines().count() as u32,
}
}

#[test]
fn remote_rule_contents_match_reordered_responses_by_path() {
let host = HostId::new("test-host".to_string());
let first_path = remote_rule_path(&host, "WARP.md");
let second_path = remote_rule_path(&host, "nested/AGENTS.md");

let contents = pair_remote_rule_paths_with_contents(
vec![first_path.clone(), second_path.clone()],
vec![
remote_rule_file_context(&second_path, "second rules"),
remote_rule_file_context(&first_path, "first rules"),
],
);

assert_eq!(
contents,
vec![
(first_path, "first rules".to_string()),
(second_path, "second rules".to_string()),
]
);
}

#[test]
fn remote_rule_contents_keep_paths_aligned_after_missing_reads() {
let host = HostId::new("test-host".to_string());
let missing_path = remote_rule_path(&host, "WARP.md");
let present_path = remote_rule_path(&host, "nested/AGENTS.md");

let contents = pair_remote_rule_paths_with_contents(
vec![missing_path, present_path.clone()],
vec![remote_rule_file_context(&present_path, "present rules")],
);

assert_eq!(contents, vec![(present_path, "present rules".to_string())]);
}

#[test]
fn remote_rule_read_request_preserves_discovered_paths() {
let host = HostId::new("test-host".to_string());
let first_path = remote_rule_path(&host, "WARP.md");
let second_path = remote_rule_path(&host, "nested/AGENTS.md");

let request = remote_rule_read_request(&[first_path.clone(), second_path.clone()]);

assert_eq!(request.max_file_bytes, None);
assert_eq!(request.max_batch_bytes, None);
assert_eq!(request.files.len(), 2);
let LocalOrRemotePath::Remote(first_remote) = first_path else {
panic!("Expected a remote rule path");
};
let LocalOrRemotePath::Remote(second_remote) = second_path else {
panic!("Expected a remote rule path");
};
assert_eq!(request.files[0].path, first_remote.path.as_str());
assert_eq!(request.files[1].path, second_remote.path.as_str());
}
1 change: 1 addition & 0 deletions app/src/ai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod harness_availability;
pub(crate) mod harness_display;
pub(crate) mod llms;
pub(crate) mod local_harness_setup;
pub(crate) mod metadata_project_rules;
pub mod onboarding;
pub(crate) mod persisted_workspace;
pub(crate) mod predict;
Expand Down
Loading
Loading