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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/dim-app-server/src/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2165,7 +2165,7 @@ impl AgentsPlugin {
.local_execution()
.then(|| names.key::<SettingsService>())
.transpose()?,
loader: names.key()?,
loader: Key::of(),
directory: Key::of(),
activity: names.key()?,
parts: names.key()?,
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-app-server/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2471,7 +2471,7 @@ impl RpcPlugin {
collaboration: names.key()?,
hub: names.key()?,
control: names.key()?,
loader: names.key()?,
loader: Key::of(),
management: names.key()?,
callers: Key::of(),
})
Expand Down
5 changes: 1 addition & 4 deletions crates/dim-app-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1434,8 +1434,8 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata
register::<storage::Store>(catalog, None);
catalog.register_shared("store");
register::<worktrees::ManagedWorktrees>(catalog, None);
catalog.register_shared("managedWorktrees");
register::<AgentIndex>(catalog, None);
register::<rutis_loader::Loader>(catalog, None);
catalog.register_shared(dim_agent_runtime::names::name_of::<
collaboration::CollaborationDirectory,
>());
Expand Down Expand Up @@ -1500,10 +1500,7 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) {
("grokOAuthService", "secret"),
("historyRenderer", "hot-path"),
("hostPlatform", "object"),
("loader", "owner-api"),
("loopState", "hot-path"),
// Session creation calls it directly; no leaf needs the service.
("managedWorktrees", "hot-path"),
("mentionIndex", "host-resource"),
("modelHost", "owner-api"),
("openAICodexOAuthService", "secret"),
Expand Down
12 changes: 10 additions & 2 deletions crates/dim-app-server/src/plugin_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1653,7 +1653,14 @@ impl Manager {
== Some(&self.state.config_of(name, &code.config))
});
if same {
if let Err(error) = self.loader.reload(&row).await {
if let Err(error) = rutis_bridge::session::call_service::<()>(
&self.ctx,
"rutis/loader",
"reload",
(&row,),
)
.await
{
tracing::warn!(%row, %error, "plugin reload refused");
}
} else {
Expand Down Expand Up @@ -2345,7 +2352,7 @@ impl PluginManagerPlugin {
Ok(Self {
state,
plugin_tools,
loader: names.key()?,
loader: Key::of(),
methods: names.key()?,
parts: names.key()?,
skills: names.key()?,
Expand All @@ -2365,6 +2372,7 @@ impl DynPlugin for PluginManagerPlugin {
fn injects(&self) -> Vec<TypeKey> {
vec![
self.loader.erase(),
rutis_bridge::session::host_key("rutis/loader").erase(),
self.methods.erase(),
self.parts.erase(),
]
Expand Down
91 changes: 81 additions & 10 deletions crates/dim-app-server/src/worktrees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
//! writes them in the Session's own transaction, and a removal runs under the
//! store's ownership lock so a late association cannot slip in between the
//! re-check and the record deletion. Git is the fact; a record is a candidate.
mod face;

use crate::methods::ManagementMethods;
use crate::storage::{PreparedWorktree, Store, WorktreeDirectory, WorktreeDirectoryRecord};
use dim_agent_capabilities::methods::{
Expand All @@ -29,9 +31,13 @@ const ALLOCATION_ATTEMPTS: usize = 3;

/// The managed worktree root and the operations over it. It owns no Session
/// or branch state; the records belong to SessionStore and Git to the host.
#[derive(Clone)]
pub struct ManagedWorktrees {
root: PathBuf,
sessions: Arc<Store>,
preparations: Arc<std::sync::Mutex<std::collections::HashMap<String, CreatedWorktree>>>,
preparing: tokio_util::task::TaskTracker,
closing: CancellationToken,
}

/// A worktree this call created, with what it needs to be reported or
Expand Down Expand Up @@ -140,7 +146,13 @@ impl From<AgentError> for WorktreeError {

impl ManagedWorktrees {
pub fn new(root: PathBuf, sessions: Arc<Store>) -> Self {
Self { root, sessions }
Self {
root,
sessions,
preparations: Default::default(),
preparing: Default::default(),
closing: CancellationToken::new(),
}
}

/// Creates one worktree for `source` at `$HOME/worktrees/<task-id>/<repo>`
Expand Down Expand Up @@ -185,9 +197,13 @@ impl ManagedWorktrees {
.trim(),
);
let repository = canonical(repository).await?;
let base = base.unwrap_or("HEAD");
let revision = format!("{}^{{commit}}", base.unwrap_or("HEAD"));
let base = self
.git(&top, &["rev-parse", "--verify", base], cancel)
.git(
&top,
&["rev-parse", "--verify", "--end-of-options", &revision],
cancel,
)
.await?
.trim()
.to_owned();
Expand Down Expand Up @@ -267,15 +283,15 @@ impl ManagedWorktrees {
let root_dir = match canonical(directory.clone()).await {
Ok(root_dir) => root_dir,
Err(error) => {
self.rollback_add(&repository, &directory, &branch_name)
self.rollback_add(&repository, &directory, &branch_name, &base)
.await;
return Err(error);
}
};
let subtree = match checked_subtree(&root_dir, &relative).await {
Ok(subtree) => subtree,
Err(error) => {
self.rollback_add(&repository, &root_dir, &branch_name)
self.rollback_add(&repository, &root_dir, &branch_name, &base)
.await;
return Err(error);
}
Expand All @@ -300,13 +316,15 @@ impl ManagedWorktrees {
/// exclusion, without `--force` and with a token that cannot be cancelled.
/// The branch goes only after Git accepted the removal. A Session or
/// content that appeared since the checkout keeps both.
async fn rollback_add(&self, repository: &Path, root: &Path, branch: &str) {
async fn rollback_add(&self, repository: &Path, root: &Path, branch: &str, base: &str) {
let directory = WorktreeDirectory {
repository: repository.to_owned(),
root: root.to_owned(),
};
let repository = directory.repository.clone();
let branch = branch.to_owned();
let base = base.to_owned();
let managed = self.root.clone();
let _ = self
.sessions
.remove_worktree(directory, move |root| {
Expand All @@ -315,6 +333,43 @@ impl ManagedWorktrees {
AgentError::InvalidInput("the worktree path is not UTF-8".into())
})?;
let cancel = CancellationToken::new();
let managed = canonical(managed)
.await
.map_err(|error| AgentError::Storage(error.message().into()))?;
check_recorded_root(&root, &managed)
.await
.map_err(|error| AgentError::InvalidInput(error.message().into()))?;
let actual_repository = git(
&root,
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
&cancel,
GIT_READ_TIMEOUT,
)
.await
.map_err(|error| AgentError::Storage(error.message().into()))?;
let actual_repository = canonical(PathBuf::from(actual_repository.trim()))
.await
.map_err(|error| AgentError::Storage(error.message().into()))?;
if actual_repository != repository {
return Err(AgentError::InvalidInput(
"the prepared worktree changed repository".into(),
));
}
let current_branch =
git(&root, &["symbolic-ref", "HEAD"], &cancel, GIT_READ_TIMEOUT)
.await
.map_err(|error| AgentError::Storage(error.message().into()))?;
let current_head =
git(&root, &["rev-parse", "HEAD"], &cancel, GIT_READ_TIMEOUT)
.await
.map_err(|error| AgentError::Storage(error.message().into()))?;
if current_branch.trim_end() != format!("refs/heads/{branch}")
|| current_head.trim_end() != base
Comment thread
eric8810 marked this conversation as resolved.
Resolved
{
return Err(AgentError::InvalidInput(
"the prepared worktree changed".into(),
));
}
git(
&repository,
&["worktree", "remove", text],
Expand Down Expand Up @@ -348,6 +403,7 @@ impl ManagedWorktrees {
&created.prepared.directory.repository,
&created.prepared.directory.root,
&created.branch,
&created.base,
)
.await;
}
Expand Down Expand Up @@ -694,9 +750,11 @@ impl ManagedWorktrees {
== Some(task_id)
});
let Some(record) = record else {
return self
let removed = self
.remove_unregistered(task_id, &root, force, cancel)
.await;
.await?;
self.preparations.lock().unwrap().remove(task_id);
return Ok(removed);
};
check_recorded_root(&record.directory.root, &root).await?;
let directory = record.directory;
Expand Down Expand Up @@ -779,6 +837,7 @@ impl ManagedWorktrees {
})
.await
.map_err(WorktreeError::from)?;
self.preparations.lock().unwrap().remove(task_id);
Ok(removed)
}

Expand Down Expand Up @@ -1162,8 +1221,8 @@ fn valid_task_id(task_id: &str) -> bool {

/// The managed-worktree reply of `session.create` and `sessions.launch`: the
/// task id, the management root, and the directory the Session starts in.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreatedWorktreeReply {
pub task_id: String,
pub root: String,
Expand Down Expand Up @@ -1221,7 +1280,19 @@ impl DynPlugin for ManagedWorktreesPlugin {
let sessions = ctx.require_at(&self.sessions)?;
let methods = ctx.require_at(&self.methods)?;
let managed = Arc::new(ManagedWorktrees::new(self.root.clone(), sessions));
let preparing = managed.preparing.clone();
let closing = managed.closing.clone();
ctx.effect(move || async move {
closing.cancel();
preparing.close();
preparing.wait().await;
Ok(())
})?;
ctx.provide_as::<ManagedWorktrees>(managed.clone())?;
ctx.provide_at::<dyn rutis_bridge::session::HostDispatch>(
rutis_bridge::session::host_key("managedWorktrees"),
managed.clone(),
)?;
methods.register(
ctx,
"worktree",
Expand Down
Loading