mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
agent: Remove checkpoints (#65989)
Closes #62283 Closes #58444 Follow-up #65304 Supersede #64000, #62301 Before every message, the agent snapshotted every Git repo in the project and waited for it before sending the prompt, and every Git status change during a turn took another one. In large workspaces this took tens of seconds, and on Windows it could hang forever. #65304 already skipped it for external agents and subagents. The snapshot only exists for "Restore Checkpoint", which very few people use, so this removes checkpoints entirely. Putting them behind a setting would keep the snapshot code and its maintenance around for a feature few people use. - Removed: - "Restore Checkpoint" button - Snapshots before, during and after each turn - Git, remote and proto code behind them (proto ids reserved) - Checkpoints docs section - Stays: - Editing an earlier message - Rejecting the agent's edits - Worktree archive snapshots Release Notes: - Removed agent checkpoints and the "Restore Checkpoint" button. Taking a checkpoint before every message made the agent slow to respond, or hang, in large Git repositories. To undo the agent's changes, reject its edits or use Git.
This commit is contained in:
@@ -69,7 +69,6 @@ gpui = [
|
||||
"../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf",
|
||||
"../../assets/fonts/lilex/Lilex-Regular.ttf",
|
||||
]
|
||||
git = ["src/checkpoint.gitignore"]
|
||||
git_ui = ["src/commit_message_prompt.txt"]
|
||||
editor = ["../grammars/src/**"]
|
||||
edit_prediction = ["license_patterns/**"]
|
||||
|
||||
+49
-1072
File diff suppressed because it is too large
Load Diff
@@ -998,6 +998,7 @@ mod test_support {
|
||||
close_sessions_on_release: bool,
|
||||
supports_session_additional_directories: bool,
|
||||
supports_set_title: bool,
|
||||
supports_truncate: bool,
|
||||
agent_id: AgentId,
|
||||
telemetry_id: SharedString,
|
||||
prompt_capabilities_rx: watch::Receiver<acp_v2::PromptCapabilities>,
|
||||
@@ -1048,6 +1049,7 @@ mod test_support {
|
||||
close_sessions_on_release: true,
|
||||
supports_session_additional_directories: false,
|
||||
supports_set_title: true,
|
||||
supports_truncate: true,
|
||||
agent_id: AgentId::new("stub"),
|
||||
telemetry_id: "stub".into(),
|
||||
prompt_capabilities_rx: watch::Receiver::constant(
|
||||
@@ -1224,6 +1226,11 @@ mod test_support {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_supports_truncate(mut self, supports_truncate: bool) -> Self {
|
||||
self.supports_truncate = supports_truncate;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_agent_id(mut self, agent_id: AgentId) -> Self {
|
||||
self.agent_id = agent_id;
|
||||
self
|
||||
@@ -1547,9 +1554,11 @@ mod test_support {
|
||||
_cx: &App,
|
||||
) -> Option<Rc<dyn AgentSessionTruncate>> {
|
||||
// Capability checks also call this; only run may consume the gate.
|
||||
Some(Rc::new(StubAgentSessionEditor {
|
||||
next_truncate: self.next_truncate.clone(),
|
||||
}))
|
||||
self.supports_truncate.then(|| {
|
||||
Rc::new(StubAgentSessionEditor {
|
||||
next_truncate: self.next_truncate.clone(),
|
||||
}) as Rc<dyn AgentSessionTruncate>
|
||||
})
|
||||
}
|
||||
|
||||
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
|
||||
|
||||
+69
-119
@@ -2525,7 +2525,7 @@ impl NativeAgentConnection {
|
||||
}),
|
||||
))
|
||||
})??;
|
||||
let (message_id, preparation, retry_action) = if let Some(content) = content {
|
||||
let (message_id, retry_action) = if let Some(content) = content {
|
||||
let message_id = ClientUserMessageId::new();
|
||||
let retry_action = agent.read_with(cx, |agent, cx| {
|
||||
let project_state = agent
|
||||
@@ -2558,10 +2558,10 @@ impl NativeAgentConnection {
|
||||
cx,
|
||||
)
|
||||
})?;
|
||||
let preparation = acp_thread.update(cx, |thread, cx| {
|
||||
thread.prepare_local_prompt(message_id.clone(), source, cx)
|
||||
acp_thread.update(cx, |thread, cx| {
|
||||
thread.upsert_local_user_message(message_id.clone(), source, cx)
|
||||
})?;
|
||||
(message_id, preparation, Some(retry_action))
|
||||
(message_id, Some(retry_action))
|
||||
} else {
|
||||
let previous_execution = previous_execution
|
||||
.filter(|(id, _retry_action)| thread.read(cx).has_user_message(id));
|
||||
@@ -2573,7 +2573,7 @@ impl NativeAgentConnection {
|
||||
let retry_action =
|
||||
previous_execution.and_then(|(_id, retry_action)| retry_action);
|
||||
thread.update(cx, |thread, cx| thread.prepare_local_turn(cx));
|
||||
(message_id, Task::ready(()), retry_action)
|
||||
(message_id, retry_action)
|
||||
};
|
||||
let (cancellation_sender, cancellation_receiver) = oneshot::channel();
|
||||
let driver = Self::drive_execution(
|
||||
@@ -2583,7 +2583,6 @@ impl NativeAgentConnection {
|
||||
acp_thread.downgrade(),
|
||||
message_id.clone(),
|
||||
retry_action.clone(),
|
||||
preparation,
|
||||
cancellation_receiver,
|
||||
completion_sender,
|
||||
cx,
|
||||
@@ -2630,7 +2629,6 @@ impl NativeAgentConnection {
|
||||
acp_thread: WeakEntity<AcpThread>,
|
||||
message_id: ClientUserMessageId,
|
||||
retry_action: Option<NativeRetryAction>,
|
||||
preparation: Task<()>,
|
||||
cancellation: oneshot::Receiver<NativeCancellation>,
|
||||
completion: oneshot::Sender<std::result::Result<acp_v2::StopReason, Arc<anyhow::Error>>>,
|
||||
cx: &App,
|
||||
@@ -2639,7 +2637,6 @@ impl NativeAgentConnection {
|
||||
let execution = cx.spawn({
|
||||
let agent = agent.clone();
|
||||
async move |cx| {
|
||||
preparation.await;
|
||||
let task = cx.update(|cx| -> Result<_> {
|
||||
let connection = NativeAgentConnection(
|
||||
agent.upgrade().context("Native agent was released")?,
|
||||
@@ -2685,34 +2682,25 @@ impl NativeAgentConnection {
|
||||
thread.update(cx, |thread, cx| thread.cancel(cx)).detach();
|
||||
}
|
||||
let result = match result {
|
||||
Ok(reason) => {
|
||||
let finish = acp_thread.update(cx, |thread, cx| {
|
||||
thread.finish_local_turn(reason.clone(), cx)
|
||||
});
|
||||
match finish {
|
||||
Ok(finish) => match finish.await {
|
||||
Ok(()) => acp_thread.update(cx, |thread, cx| {
|
||||
thread.update_session_state(
|
||||
acp_v2::StateUpdate::Idle(
|
||||
acp_v2::IdleStateUpdate::new().stop_reason(reason.clone()),
|
||||
),
|
||||
cx,
|
||||
)
|
||||
}).and_then(|result| result).map(|()| reason),
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
Ok(reason) => acp_thread
|
||||
.update(cx, |thread, cx| thread.finish_local_turn(reason.clone(), cx))
|
||||
.and_then(|()| {
|
||||
acp_thread.update(cx, |thread, cx| {
|
||||
thread.update_session_state(
|
||||
acp_v2::StateUpdate::Idle(
|
||||
acp_v2::IdleStateUpdate::new().stop_reason(reason.clone()),
|
||||
),
|
||||
cx,
|
||||
)
|
||||
})
|
||||
})
|
||||
.and_then(|result| result)
|
||||
.map(|()| reason),
|
||||
Err(error) => {
|
||||
let finish = acp_thread.update(cx, |thread, cx| {
|
||||
if let Err(finish_error) = acp_thread.update(cx, |thread, cx| {
|
||||
thread.finish_local_turn(acp_v2::ErrorStopReason::new().into(), cx)
|
||||
});
|
||||
match finish {
|
||||
Ok(finish) => {
|
||||
finish.await.log_err();
|
||||
}
|
||||
Err(finish_error) => log::error!("Native error cleanup: {finish_error:#}"),
|
||||
}) {
|
||||
log::error!("Native error cleanup: {finish_error:#}");
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
@@ -3594,7 +3582,8 @@ impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
|
||||
let thread = self.thread.clone();
|
||||
let acp_thread = self.acp_thread.clone();
|
||||
cx.spawn(async move |cx| {
|
||||
// Preparation is session-owned and may precede the model turn.
|
||||
// An MCP prompt, skill, or compaction may still be preparing before
|
||||
// the model turn starts, so cancel it before truncating.
|
||||
cancellation.await?;
|
||||
let usage = thread.update(cx, |thread, cx| {
|
||||
thread.truncate(client_user_message_id, cx)?;
|
||||
@@ -4610,90 +4599,6 @@ mod internal_tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_native_rewind_cancels_pending_preparation(cx: &mut TestAppContext) {
|
||||
let fake = init_test(cx);
|
||||
let (_connection, agent, _project, acp_thread) = setup_native_agent_session(cx).await;
|
||||
let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
|
||||
let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));
|
||||
let message_id = ClientUserMessageId::new();
|
||||
let content = vec!["rewound before model startup".into()];
|
||||
let (release, preparation) = oneshot::channel::<()>();
|
||||
let completion = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.set_model(fake.model("fake"), cx);
|
||||
let path_style = thread.project().read(cx).path_style(cx);
|
||||
thread
|
||||
.push_acp_user_block(message_id.clone(), content.clone(), path_style, cx)
|
||||
.expect("accepted provider message");
|
||||
});
|
||||
acp_thread.update(cx, |thread, cx| {
|
||||
thread
|
||||
.prepare_local_prompt(message_id.clone(), content.clone(), cx)
|
||||
.expect("accepted display message")
|
||||
.detach();
|
||||
thread
|
||||
.update_session_state(
|
||||
acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),
|
||||
cx,
|
||||
)
|
||||
.expect("running");
|
||||
});
|
||||
// The initial Git checkpoint can remain pending after acceptance.
|
||||
let preparation = cx.spawn(async move |_cx| {
|
||||
preparation.await.expect("release preparation");
|
||||
});
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
let completion = receiver.shared();
|
||||
let (cancellation, cancelled) = oneshot::channel();
|
||||
let retry_action = Some(NativeRetryAction::Prompt(content));
|
||||
let driver = NativeAgentConnection::drive_execution(
|
||||
agent.downgrade(),
|
||||
session_id.clone(),
|
||||
thread.clone(),
|
||||
acp_thread.downgrade(),
|
||||
message_id.clone(),
|
||||
retry_action.clone(),
|
||||
preparation,
|
||||
cancelled,
|
||||
sender,
|
||||
cx,
|
||||
);
|
||||
agent.update(cx, |agent, _cx| {
|
||||
agent
|
||||
.sessions
|
||||
.get_mut(&session_id)
|
||||
.expect("session")
|
||||
.execution = Some(NativeExecution {
|
||||
_driver: driver,
|
||||
message_id: message_id.clone(),
|
||||
retry_action,
|
||||
cancellation: Some(cancellation),
|
||||
completion: completion.clone(),
|
||||
});
|
||||
});
|
||||
completion
|
||||
});
|
||||
cx.run_until_parked();
|
||||
acp_thread
|
||||
.update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
|
||||
.await
|
||||
.expect("rewind accepted message");
|
||||
if release.send(()).is_err() {
|
||||
log::debug!("Rewind already dropped pending preparation");
|
||||
}
|
||||
cx.run_until_parked();
|
||||
assert!(
|
||||
fake.pending_completions().is_empty(),
|
||||
"rewind must fence startup"
|
||||
);
|
||||
assert!(!thread.read_with(cx, |thread, _| thread.has_user_message(&message_id)));
|
||||
assert_eq!(
|
||||
completion.await.expect("settled").expect("cancelled"),
|
||||
acp_v2::StopReason::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_native_stop_does_not_wait_for_uncooperative_tool(cx: &mut TestAppContext) {
|
||||
use crate::tests::test_tools::DelayTool;
|
||||
@@ -5394,6 +5299,51 @@ mod internal_tests {
|
||||
assert_failed_native_command_context("/native-prompts.prepare", true, cx).await;
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_native_rewind_cancels_pending_mcp_prompt(cx: &mut TestAppContext) {
|
||||
let fake = init_test(cx);
|
||||
let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;
|
||||
let mut requests = setup_native_prompt_server(&project, cx);
|
||||
let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
|
||||
let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));
|
||||
thread.update(cx, |thread, cx| thread.set_model(fake.model("fake"), cx));
|
||||
let (receipt, completion) = cx.update(|cx| {
|
||||
connection.submit_native(
|
||||
session_id.clone(),
|
||||
Some(vec!["/native-prompts.prepare".into()]),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
receipt.await.expect("command accepted");
|
||||
// Holding the prompt response keeps the turn before model startup.
|
||||
let prompt_response = requests.next().await.expect("fetch prompt");
|
||||
let message_id = thread
|
||||
.read_with(cx, |thread, _| thread.last_user_message_id())
|
||||
.expect("accepted command retained");
|
||||
acp_thread
|
||||
.update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
|
||||
.await
|
||||
.expect("rewind accepted message");
|
||||
if prompt_response
|
||||
.send(json!({
|
||||
"messages": [{"role": "user", "content": {"type": "text", "text": "prepared"}}]
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
log::debug!("Rewind already dropped the pending prompt fetch");
|
||||
}
|
||||
cx.run_until_parked();
|
||||
assert!(
|
||||
fake.pending_completions().is_empty(),
|
||||
"rewind must fence startup"
|
||||
);
|
||||
assert!(!thread.read_with(cx, |thread, _| thread.has_user_message(&message_id)));
|
||||
assert_eq!(
|
||||
completion.await.expect("settled").expect("cancelled"),
|
||||
acp_v2::StopReason::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_native_failed_skill_follow_up_context(cx: &mut TestAppContext) {
|
||||
assert_failed_native_command_context("/:missing-skill do work", false, cx).await;
|
||||
|
||||
@@ -2793,7 +2793,7 @@ impl Thread {
|
||||
|
||||
pub(crate) fn prepare_local_turn(&mut self, cx: &mut Context<Self>) {
|
||||
// Freeze the old partial before inserting a successor's user message,
|
||||
// and fence detached cleanup while its checkpoint or command is prepared.
|
||||
// and fence detached cleanup while its command is prepared.
|
||||
self.flush_pending_message(cx);
|
||||
self.advance_prompt_id();
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use acp_thread::{
|
||||
AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
|
||||
AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore,
|
||||
ForegroundActivity, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice,
|
||||
PermissionOptions, PermissionPattern, PermissionRequest, PermissionRequestId,
|
||||
ProtocolErrorInfo, RetryStatus, SelectedPermissionOutcome, ThreadStatus, ToolCall,
|
||||
ToolCallContent, ToolCallStatus,
|
||||
AuthRequired, ElicitationEntryId, ElicitationStatus, ElicitationStore, ForegroundActivity,
|
||||
LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, PermissionOptions,
|
||||
PermissionPattern, PermissionRequest, PermissionRequestId, ProtocolErrorInfo, RetryStatus,
|
||||
SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
|
||||
};
|
||||
use acp_thread::{AgentConnection, Plan};
|
||||
use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
|
||||
@@ -4301,7 +4300,7 @@ fn plan_label_markdown_style(
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use acp_thread::StubAgentConnection;
|
||||
use acp_thread::{ClientUserMessageId, StubAgentConnection};
|
||||
use action_log::ActionLog;
|
||||
use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
|
||||
use agent_client_protocol::schema::v1 as acp_v1;
|
||||
@@ -14477,6 +14476,79 @@ pub(crate) mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_user_message_is_editable_when_thread_can_rewind(cx: &mut TestAppContext) {
|
||||
assert!(user_message_is_editable(StubAgentConnection::new(), false, cx).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_user_message_is_read_only_without_truncate(cx: &mut TestAppContext) {
|
||||
let connection = StubAgentConnection::new().with_supports_truncate(false);
|
||||
assert!(!user_message_is_editable(connection, false, cx).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_subagent_user_message_is_read_only(cx: &mut TestAppContext) {
|
||||
assert!(!user_message_is_editable(StubAgentConnection::new(), true, cx).await);
|
||||
}
|
||||
|
||||
async fn user_message_is_editable(
|
||||
connection: StubAgentConnection,
|
||||
subagent: bool,
|
||||
cx: &mut TestAppContext,
|
||||
) -> bool {
|
||||
init_test(cx);
|
||||
let (conversation_view, cx) =
|
||||
setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
|
||||
let root =
|
||||
active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
|
||||
let thread = if subagent {
|
||||
let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());
|
||||
let child = conversation_view.update(cx, |view, cx| {
|
||||
create_test_acp_thread(
|
||||
Some(root_session_id),
|
||||
"child",
|
||||
Rc::new(connection.clone()),
|
||||
view.project.clone(),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));
|
||||
child
|
||||
} else {
|
||||
root
|
||||
};
|
||||
thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.upsert_local_user_message(
|
||||
ClientUserMessageId::new(),
|
||||
vec!["Hello".into()],
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.expect("user message");
|
||||
cx.run_until_parked();
|
||||
|
||||
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
|
||||
conversation_view.read_with(cx, |view, cx| {
|
||||
let thread_view = view.thread_view(&session_id).expect("thread view");
|
||||
let thread_view = thread_view.read(cx);
|
||||
let read_only = thread_view
|
||||
.entry_view_state
|
||||
.read(cx)
|
||||
.entry(0)
|
||||
.and_then(|entry| entry.message_editor())
|
||||
.expect("user message editor")
|
||||
.read(cx)
|
||||
.editor()
|
||||
.read(cx)
|
||||
.read_only(cx);
|
||||
let can_edit = thread_view.can_edit_user_message(0, cx);
|
||||
assert_eq!(can_edit, !read_only);
|
||||
can_edit
|
||||
})
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
@@ -3783,19 +3783,6 @@ impl ThreadView {
|
||||
|
||||
// thread stuff
|
||||
|
||||
pub fn restore_checkpoint(&mut self, client_id: &ClientUserMessageId, cx: &mut Context<Self>) {
|
||||
self.thread
|
||||
.update(cx, |thread, cx| {
|
||||
telemetry::event!(
|
||||
"Agent Checkpoint Restored",
|
||||
agent = thread.connection().telemetry_id(),
|
||||
session = thread.session_id().clone(),
|
||||
);
|
||||
thread.restore_checkpoint(client_id.clone(), cx)
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
|
||||
pub fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
|
||||
self.thread_error = None;
|
||||
self.thread_error_markdown = None;
|
||||
@@ -7286,13 +7273,8 @@ impl ThreadView {
|
||||
let opaque_window = cx.theme().window_background_appearance()
|
||||
== gpui::WindowBackgroundAppearance::Opaque;
|
||||
|
||||
let has_checkpoint_button = message
|
||||
.checkpoint
|
||||
.as_ref()
|
||||
.is_some_and(|checkpoint| checkpoint.show);
|
||||
|
||||
let is_subagent = self.is_subagent();
|
||||
let can_restore_checkpoint = self
|
||||
let can_rewind = self
|
||||
.thread
|
||||
.read(cx)
|
||||
.can_rewind_to(message.client_id.as_ref(), cx);
|
||||
@@ -7301,7 +7283,7 @@ impl ThreadView {
|
||||
.source_blocks()
|
||||
.iter()
|
||||
.all(acp_thread::content::can_convert_to_v1);
|
||||
let is_editable = can_restore_checkpoint && source_is_representable;
|
||||
let is_editable = can_rewind && source_is_representable;
|
||||
let agent_name = if is_subagent {
|
||||
"subagents".into()
|
||||
} else {
|
||||
@@ -7321,25 +7303,6 @@ impl ThreadView {
|
||||
.px_2()
|
||||
.gap_1p5()
|
||||
.w_full()
|
||||
.when(can_restore_checkpoint && has_checkpoint_button, |this| {
|
||||
this.children(message.client_id.clone().map(|client_id| {
|
||||
h_flex()
|
||||
.px_3()
|
||||
.gap_2()
|
||||
.child(Divider::horizontal())
|
||||
.child(
|
||||
Button::new("restore-checkpoint", "Restore Checkpoint")
|
||||
.start_icon(Icon::new(IconName::Undo).size(IconSize::XSmall).color(Color::Muted))
|
||||
.label_size(LabelSize::XSmall)
|
||||
.color(Color::Muted)
|
||||
.tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
|
||||
.on_click(cx.listener(move |this, _, _window, cx| {
|
||||
this.restore_checkpoint(&client_id, cx);
|
||||
}))
|
||||
)
|
||||
.child(Divider::horizontal())
|
||||
}))
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.relative()
|
||||
|
||||
+12
-143
@@ -14,9 +14,8 @@ use git::{
|
||||
repository::{
|
||||
AskPassDelegate, Branch, CommitData, CommitDataReader, CommitDetails, CommitOptions,
|
||||
CreateWorktreeTarget, FetchOptions, FileHistoryChangedFileSets, GRAPH_CHUNK_SIZE,
|
||||
GitRepository, GitRepositoryCheckpoint, InitialGraphCommitData, LogOrder, LogSource,
|
||||
PushOptions, RefEdit, Remote, RepoPath, ResetMode, SearchCommitArgs, Worktree,
|
||||
commit_hash_search_query,
|
||||
GitRepository, InitialGraphCommitData, LogOrder, LogSource, PushOptions, RefEdit, Remote,
|
||||
RepoPath, ResetMode, SearchCommitArgs, Worktree, commit_hash_search_query,
|
||||
},
|
||||
stash::GitStash,
|
||||
status::{
|
||||
@@ -1479,38 +1478,6 @@ impl GitRepository for FakeGitRepository {
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
|
||||
let executor = self.executor.clone();
|
||||
let fs = self.fs.clone();
|
||||
let checkpoints = self.checkpoints.clone();
|
||||
let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf();
|
||||
async move {
|
||||
executor.simulate_random_delay().await;
|
||||
let oid = git::Oid::random(&mut *executor.rng().lock());
|
||||
let entry = fs.entry(&repository_dir_path)?;
|
||||
checkpoints.lock().insert(oid, entry);
|
||||
Ok(GitRepositoryCheckpoint { commit_sha: oid })
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
|
||||
let executor = self.executor.clone();
|
||||
let fs = self.fs.clone();
|
||||
let checkpoints = self.checkpoints.clone();
|
||||
let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf();
|
||||
async move {
|
||||
executor.simulate_random_delay().await;
|
||||
let checkpoints = checkpoints.lock();
|
||||
let entry = checkpoints
|
||||
.get(&checkpoint.commit_sha)
|
||||
.context(format!("invalid checkpoint: {}", checkpoint.commit_sha))?;
|
||||
fs.insert_entry(&repository_dir_path, entry.clone())?;
|
||||
Ok(())
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>> {
|
||||
let executor = self.executor.clone();
|
||||
let fs = self.fs.clone();
|
||||
@@ -1535,119 +1502,21 @@ impl GitRepository for FakeGitRepository {
|
||||
_staged_sha: String,
|
||||
unstaged_sha: String,
|
||||
) -> BoxFuture<'_, Result<()>> {
|
||||
match unstaged_sha.parse() {
|
||||
Ok(commit_sha) => self.restore_checkpoint(GitRepositoryCheckpoint { commit_sha }),
|
||||
Err(error) => async move {
|
||||
Err(anyhow::anyhow!(error).context("failed to parse unstaged SHA as Oid"))
|
||||
}
|
||||
.boxed(),
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_checkpoints(
|
||||
&self,
|
||||
left: GitRepositoryCheckpoint,
|
||||
right: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<bool>> {
|
||||
let executor = self.executor.clone();
|
||||
let fs = self.fs.clone();
|
||||
let checkpoints = self.checkpoints.clone();
|
||||
let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf();
|
||||
async move {
|
||||
let commit_sha: Oid = unstaged_sha
|
||||
.parse()
|
||||
.context("failed to parse unstaged SHA as Oid")?;
|
||||
executor.simulate_random_delay().await;
|
||||
let checkpoints = checkpoints.lock();
|
||||
let left = checkpoints
|
||||
.get(&left.commit_sha)
|
||||
.context(format!("invalid left checkpoint: {}", left.commit_sha))?;
|
||||
let right = checkpoints
|
||||
.get(&right.commit_sha)
|
||||
.context(format!("invalid right checkpoint: {}", right.commit_sha))?;
|
||||
|
||||
Ok(left == right)
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn diff_checkpoints(
|
||||
&self,
|
||||
base_checkpoint: GitRepositoryCheckpoint,
|
||||
target_checkpoint: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<String>> {
|
||||
let executor = self.executor.clone();
|
||||
let checkpoints = self.checkpoints.clone();
|
||||
async move {
|
||||
executor.simulate_random_delay().await;
|
||||
let checkpoints = checkpoints.lock();
|
||||
let base = checkpoints
|
||||
.get(&base_checkpoint.commit_sha)
|
||||
.context(format!(
|
||||
"invalid base checkpoint: {}",
|
||||
base_checkpoint.commit_sha
|
||||
))?;
|
||||
let target = checkpoints
|
||||
.get(&target_checkpoint.commit_sha)
|
||||
.context(format!(
|
||||
"invalid target checkpoint: {}",
|
||||
target_checkpoint.commit_sha
|
||||
))?;
|
||||
|
||||
fn collect_files(
|
||||
entry: &FakeFsEntry,
|
||||
prefix: String,
|
||||
out: &mut std::collections::BTreeMap<String, String>,
|
||||
) {
|
||||
match entry {
|
||||
FakeFsEntry::File { content, .. } => {
|
||||
out.insert(prefix, String::from_utf8_lossy(content).into_owned());
|
||||
}
|
||||
FakeFsEntry::Dir { entries, .. } => {
|
||||
for (name, child) in entries {
|
||||
let path = if prefix.is_empty() {
|
||||
name.clone()
|
||||
} else {
|
||||
format!("{prefix}/{name}")
|
||||
};
|
||||
collect_files(child, path, out);
|
||||
}
|
||||
}
|
||||
FakeFsEntry::Symlink { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
let mut base_files = std::collections::BTreeMap::new();
|
||||
let mut target_files = std::collections::BTreeMap::new();
|
||||
collect_files(base, String::new(), &mut base_files);
|
||||
collect_files(target, String::new(), &mut target_files);
|
||||
|
||||
let all_paths: std::collections::BTreeSet<&String> =
|
||||
base_files.keys().chain(target_files.keys()).collect();
|
||||
|
||||
let mut diff = String::new();
|
||||
for path in all_paths {
|
||||
match (base_files.get(path), target_files.get(path)) {
|
||||
(Some(base_content), Some(target_content))
|
||||
if base_content != target_content =>
|
||||
{
|
||||
diff.push_str(&format!("diff --git a/{path} b/{path}\n"));
|
||||
diff.push_str(&format!("--- a/{path}\n"));
|
||||
diff.push_str(&format!("+++ b/{path}\n"));
|
||||
for line in base_content.lines() {
|
||||
diff.push_str(&format!("-{line}\n"));
|
||||
}
|
||||
for line in target_content.lines() {
|
||||
diff.push_str(&format!("+{line}\n"));
|
||||
}
|
||||
}
|
||||
(Some(_), None) => {
|
||||
diff.push_str(&format!("diff --git a/{path} /dev/null\n"));
|
||||
diff.push_str("deleted file\n");
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
diff.push_str(&format!("diff --git /dev/null b/{path}\n"));
|
||||
diff.push_str("new file\n");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(diff)
|
||||
let entry = checkpoints
|
||||
.get(&commit_sha)
|
||||
.context(format!("invalid checkpoint: {commit_sha}"))?;
|
||||
fs.insert_entry(&repository_dir_path, entry.clone())?;
|
||||
Ok(())
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use fs::{FakeFs, Fs};
|
||||
use fs::{FakeFs, Fs, RemoveOptions};
|
||||
use gpui::{BackgroundExecutor, TestAppContext};
|
||||
use serde_json::json;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -122,7 +122,7 @@ async fn test_fake_worktree_lifecycle(cx: &mut TestAppContext) {
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_checkpoints(executor: BackgroundExecutor) {
|
||||
async fn test_archive_checkpoints(executor: BackgroundExecutor) {
|
||||
let fs = FakeFs::new(executor);
|
||||
fs.insert_tree(
|
||||
path!("/"),
|
||||
@@ -144,27 +144,15 @@ async fn test_checkpoints(executor: BackgroundExecutor) {
|
||||
.open_repo(Path::new("/foo/.git"), Some("git".as_ref()))
|
||||
.unwrap();
|
||||
|
||||
let checkpoint_1 = repository.checkpoint().await.unwrap();
|
||||
let (staged_sha, unstaged_sha) = repository.create_archive_checkpoint().await.unwrap();
|
||||
fs.remove_file(Path::new("/foo/a"), RemoveOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
fs.write(Path::new("/foo/b"), b"IPSUM").await.unwrap();
|
||||
fs.write(Path::new("/foo/c"), b"dolor").await.unwrap();
|
||||
let checkpoint_2 = repository.checkpoint().await.unwrap();
|
||||
let checkpoint_3 = repository.checkpoint().await.unwrap();
|
||||
|
||||
assert!(
|
||||
repository
|
||||
.compare_checkpoints(checkpoint_2.clone(), checkpoint_3.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!repository
|
||||
.compare_checkpoints(checkpoint_1.clone(), checkpoint_2.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
repository
|
||||
.restore_checkpoint(checkpoint_1.clone())
|
||||
.restore_archive_checkpoint(staged_sha, unstaged_sha)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -175,22 +163,4 @@ async fn test_checkpoints(executor: BackgroundExecutor) {
|
||||
(Path::new(path!("/foo/b")).into(), b"ipsum".into())
|
||||
]
|
||||
);
|
||||
|
||||
// diff_checkpoints: identical checkpoints produce empty diff
|
||||
let diff = repository
|
||||
.diff_checkpoints(checkpoint_2.clone(), checkpoint_3.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
diff.is_empty(),
|
||||
"identical checkpoints should produce empty diff"
|
||||
);
|
||||
|
||||
// diff_checkpoints: different checkpoints produce non-empty diff
|
||||
let diff = repository
|
||||
.diff_checkpoints(checkpoint_1.clone(), checkpoint_2.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(diff.contains("b"), "diff should mention changed file 'b'");
|
||||
assert!(diff.contains("c"), "diff should mention added file 'c'");
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
# This lists files that we don't track in checkpoints
|
||||
|
||||
# Compiled source and executables
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.a
|
||||
*.lib
|
||||
*.o
|
||||
*.obj
|
||||
*.elf
|
||||
*.out
|
||||
*.app
|
||||
*.deb
|
||||
*.rpm
|
||||
*.dmg
|
||||
*.pkg
|
||||
*.msi
|
||||
|
||||
# Archives and compressed files
|
||||
*.7z
|
||||
*.zip
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
*.tar.bz2
|
||||
*.tbz2
|
||||
*.tar.xz
|
||||
*.txz
|
||||
*.rar
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Media files
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.png
|
||||
*.gif
|
||||
*.ico
|
||||
*.svg
|
||||
*.webp
|
||||
*.bmp
|
||||
*.tiff
|
||||
*.mp3
|
||||
*.mp4
|
||||
*.avi
|
||||
*.mov
|
||||
*.wmv
|
||||
*.flv
|
||||
*.mkv
|
||||
*.webm
|
||||
*.wav
|
||||
*.flac
|
||||
*.aac
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.mdb
|
||||
|
||||
# Documents (often binary)
|
||||
*.pdf
|
||||
*.doc
|
||||
*.docx
|
||||
*.xls
|
||||
*.xlsx
|
||||
*.ppt
|
||||
*.pptx
|
||||
|
||||
# IDE and editor files
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Language-specific files
|
||||
*.rlib
|
||||
*.rmeta
|
||||
*.pdb
|
||||
*.class
|
||||
*.egg
|
||||
*.egg-info/
|
||||
*.pyc
|
||||
*.pto
|
||||
__pycache__
|
||||
+87
-510
@@ -1072,12 +1072,6 @@ pub trait GitRepository: Send + Sync {
|
||||
path_prefixes: &[RepoPath],
|
||||
) -> BoxFuture<'static, Result<crate::status::GitDiffStat>>;
|
||||
|
||||
/// Creates a checkpoint for the repository.
|
||||
fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;
|
||||
|
||||
/// Resets to a previously-created checkpoint.
|
||||
fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>>;
|
||||
|
||||
/// Creates two detached commits capturing the current staged and unstaged
|
||||
/// state without moving any branch. Returns (staged_sha, unstaged_sha).
|
||||
fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>>;
|
||||
@@ -1092,20 +1086,6 @@ pub trait GitRepository: Send + Sync {
|
||||
unstaged_sha: String,
|
||||
) -> BoxFuture<'_, Result<()>>;
|
||||
|
||||
/// Compares two checkpoints, returning true if they are equal
|
||||
fn compare_checkpoints(
|
||||
&self,
|
||||
left: GitRepositoryCheckpoint,
|
||||
right: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<bool>>;
|
||||
|
||||
/// Computes a diff between two checkpoints.
|
||||
fn diff_checkpoints(
|
||||
&self,
|
||||
base_checkpoint: GitRepositoryCheckpoint,
|
||||
target_checkpoint: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<String>>;
|
||||
|
||||
fn load_commit_template(&self) -> BoxFuture<'_, Result<Option<GitCommitTemplate>>>;
|
||||
|
||||
fn default_branch(
|
||||
@@ -1344,11 +1324,6 @@ impl RealGitRepository {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GitRepositoryCheckpoint {
|
||||
pub commit_sha: Oid,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GitCommitter {
|
||||
pub name: Option<String>,
|
||||
@@ -3083,64 +3058,6 @@ impl GitRepository for RealGitRepository {
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
|
||||
let git = self.git_binary_in_worktree();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
let mut git = git?.envs(checkpoint_author_envs());
|
||||
git.with_temp_index(async |git| {
|
||||
let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
|
||||
|
||||
git.run(&["add", "--update"]).await?;
|
||||
let untracked_files = untracked_files_for_checkpoint(git).await?;
|
||||
add_files_to_index(git, &untracked_files).await?;
|
||||
let tree = git.run(&["write-tree"]).await?;
|
||||
let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
|
||||
git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
|
||||
.await?
|
||||
} else {
|
||||
git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
|
||||
};
|
||||
|
||||
Ok(GitRepositoryCheckpoint {
|
||||
commit_sha: checkpoint_sha.parse()?,
|
||||
})
|
||||
})
|
||||
.await
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
|
||||
let git = self.git_binary_in_worktree();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
let git = git?;
|
||||
git.run(&[
|
||||
"restore",
|
||||
"--source",
|
||||
&checkpoint.commit_sha.to_string(),
|
||||
"--worktree",
|
||||
".",
|
||||
])
|
||||
.await?;
|
||||
|
||||
// TODO: We don't track binary and large files anymore,
|
||||
// so the following call would delete them.
|
||||
// Implement an alternative way to track files added by agent.
|
||||
//
|
||||
// git.with_temp_index(async move |git| {
|
||||
// git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
|
||||
// .await?;
|
||||
// git.run(&["clean", "-d", "--force"]).await
|
||||
// })
|
||||
// .await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>> {
|
||||
let git = self.git_binary_in_worktree();
|
||||
self.executor
|
||||
@@ -3223,61 +3140,6 @@ impl GitRepository for RealGitRepository {
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn compare_checkpoints(
|
||||
&self,
|
||||
left: GitRepositoryCheckpoint,
|
||||
right: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<bool>> {
|
||||
let git = self.git_binary_in_worktree();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
let git = git?;
|
||||
let result = git
|
||||
.run(&[
|
||||
"diff-tree",
|
||||
"--quiet",
|
||||
&left.commit_sha.to_string(),
|
||||
&right.commit_sha.to_string(),
|
||||
])
|
||||
.await;
|
||||
match result {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) => {
|
||||
if let Some(GitBinaryCommandError { status, .. }) =
|
||||
error.downcast_ref::<GitBinaryCommandError>()
|
||||
&& status.code() == Some(1)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn diff_checkpoints(
|
||||
&self,
|
||||
base_checkpoint: GitRepositoryCheckpoint,
|
||||
target_checkpoint: GitRepositoryCheckpoint,
|
||||
) -> BoxFuture<'_, Result<String>> {
|
||||
let git = self.git_binary_in_worktree();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
let git = git?;
|
||||
git.run(&[
|
||||
"diff",
|
||||
"--find-renames",
|
||||
"--patch",
|
||||
&base_checkpoint.commit_sha.to_string(),
|
||||
&target_checkpoint.commit_sha.to_string(),
|
||||
])
|
||||
.await
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn default_branch(
|
||||
&self,
|
||||
include_remote_name: bool,
|
||||
@@ -3792,111 +3654,6 @@ fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
|
||||
args
|
||||
}
|
||||
|
||||
/// Lists untracked files that should be included in a checkpoint, skipping
|
||||
/// commonly ignored file types and files over 2MB.
|
||||
async fn untracked_files_for_checkpoint(git: &GitBinary) -> Result<Vec<String>> {
|
||||
const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
|
||||
|
||||
// The extra checkpoint excludes are passed ad hoc via --exclude-from
|
||||
// rather than by mutating .git/info/exclude, whose writes would trigger a
|
||||
// rescan of the repository. The scratch file is placed directly in the
|
||||
// .git directory with a .tmp extension so that the worktree scanner
|
||||
// filters out the events it generates.
|
||||
let excludes_file_path = git
|
||||
.git_directory
|
||||
.join(format!("checkpoint-excludes-{}.tmp", Uuid::new_v4()));
|
||||
|
||||
let delete_excludes_file = util::defer({
|
||||
let excludes_file_path = excludes_file_path.clone();
|
||||
let executor = git.executor.clone();
|
||||
move || {
|
||||
executor
|
||||
.spawn(async move {
|
||||
smol::fs::remove_file(excludes_file_path).await.log_err();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
});
|
||||
|
||||
smol::fs::write(&excludes_file_path, include_str!("./checkpoint.gitignore")).await?;
|
||||
|
||||
let mut exclude_from_arg = OsString::from("--exclude-from=");
|
||||
exclude_from_arg.push(&excludes_file_path);
|
||||
let output = git
|
||||
.run(&[
|
||||
OsStr::new("ls-files"),
|
||||
OsStr::new("--others"),
|
||||
OsStr::new("--exclude-standard"),
|
||||
OsStr::new("-z"),
|
||||
exclude_from_arg.as_os_str(),
|
||||
])
|
||||
.await;
|
||||
|
||||
smol::fs::remove_file(&excludes_file_path).await.ok();
|
||||
delete_excludes_file.abort();
|
||||
let output = output?;
|
||||
|
||||
let working_directory = git.working_directory.clone();
|
||||
let size_checks = output
|
||||
.split('\0')
|
||||
.filter(|path| !path.is_empty())
|
||||
.map(|path| {
|
||||
let full_path = working_directory.join(path);
|
||||
let path = path.to_string();
|
||||
smol::spawn(async move {
|
||||
match smol::fs::metadata(&full_path).await {
|
||||
Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => None,
|
||||
_ => Some(path),
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let untracked_files = futures::future::join_all(size_checks)
|
||||
.await
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
Ok(untracked_files)
|
||||
}
|
||||
|
||||
async fn add_files_to_index(git: &GitBinary, files: &[String]) -> Result<()> {
|
||||
if files.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut process = git
|
||||
.build_command(&["update-index", "--add", "-z", "--stdin"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
let mut stdin = BufWriter::new(
|
||||
process
|
||||
.stdin
|
||||
.take()
|
||||
.context("no stdin for git update-index subprocess")?,
|
||||
);
|
||||
for file in files {
|
||||
stdin.write_all(file.as_bytes()).await?;
|
||||
stdin.write_all(b"\0").await?;
|
||||
}
|
||||
stdin.flush().await?;
|
||||
drop(stdin);
|
||||
|
||||
let output = process.output().await?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
GitBinaryCommandError {
|
||||
stdout: String::from_utf8_lossy(&output.stdout).to_string(),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
|
||||
status: output.status,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) struct GitBinary {
|
||||
git_binary_path: PathBuf,
|
||||
working_directory: PathBuf,
|
||||
@@ -5755,96 +5512,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_checkpoint_basic(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let repo_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
git_init_repo(repo_dir.path());
|
||||
let file_path = repo_dir.path().join("file");
|
||||
smol::fs::write(&file_path, "initial").await.unwrap();
|
||||
|
||||
let repo = RealGitRepository::new(
|
||||
&repo_dir.path().join(".git"),
|
||||
None,
|
||||
Some("git".into()),
|
||||
cx.executor(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
repo.commit(
|
||||
"Initial commit".into(),
|
||||
None,
|
||||
CommitOptions::default(),
|
||||
AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
|
||||
Arc::new(test_commit_envs()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
smol::fs::write(&file_path, "modified before checkpoint")
|
||||
.await
|
||||
.unwrap();
|
||||
smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
|
||||
.await
|
||||
.unwrap();
|
||||
let checkpoint = repo.checkpoint().await.unwrap();
|
||||
|
||||
// Ensure the user can't see any branches after creating a checkpoint.
|
||||
assert_eq!(repo.branches().await.unwrap().branches.len(), 1);
|
||||
|
||||
smol::fs::write(&file_path, "modified after checkpoint")
|
||||
.await
|
||||
.unwrap();
|
||||
repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
repo.commit(
|
||||
"Commit after checkpoint".into(),
|
||||
None,
|
||||
CommitOptions::default(),
|
||||
AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
|
||||
Arc::new(test_commit_envs()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
|
||||
.await
|
||||
.unwrap();
|
||||
smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Ensure checkpoint stays alive even after a Git GC.
|
||||
repo.gc().await.unwrap();
|
||||
repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
smol::fs::read_to_string(&file_path).await.unwrap(),
|
||||
"modified before checkpoint"
|
||||
);
|
||||
assert_eq!(
|
||||
smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
|
||||
.await
|
||||
.unwrap(),
|
||||
"1"
|
||||
);
|
||||
// See TODO above
|
||||
// assert_eq!(
|
||||
// smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
|
||||
// .await
|
||||
// .ok(),
|
||||
// None
|
||||
// );
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[gpui::test]
|
||||
async fn test_commit_runs_git_hooks(cx: &mut TestAppContext) {
|
||||
@@ -6113,52 +5780,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let repo_dir = tempfile::tempdir().unwrap();
|
||||
git_init_repo(repo_dir.path());
|
||||
let repo = RealGitRepository::new(
|
||||
&repo_dir.path().join(".git"),
|
||||
None,
|
||||
Some("git".into()),
|
||||
cx.executor(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
smol::fs::write(repo_dir.path().join("foo"), "foo")
|
||||
.await
|
||||
.unwrap();
|
||||
let checkpoint_sha = repo.checkpoint().await.unwrap();
|
||||
|
||||
// Ensure the user can't see any branches after creating a checkpoint.
|
||||
assert_eq!(repo.branches().await.unwrap().branches.len(), 1);
|
||||
|
||||
smol::fs::write(repo_dir.path().join("foo"), "bar")
|
||||
.await
|
||||
.unwrap();
|
||||
smol::fs::write(repo_dir.path().join("baz"), "qux")
|
||||
.await
|
||||
.unwrap();
|
||||
repo.restore_checkpoint(checkpoint_sha).await.unwrap();
|
||||
assert_eq!(
|
||||
smol::fs::read_to_string(repo_dir.path().join("foo"))
|
||||
.await
|
||||
.unwrap(),
|
||||
"foo"
|
||||
);
|
||||
// See TODOs above
|
||||
// assert_eq!(
|
||||
// smol::fs::read_to_string(repo_dir.path().join("baz"))
|
||||
// .await
|
||||
// .ok(),
|
||||
// None
|
||||
// );
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_branches_return_head_when_commit_metadata_cannot_be_read(
|
||||
cx: &mut TestAppContext,
|
||||
@@ -6217,111 +5838,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_compare_checkpoints(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let repo_dir = tempfile::tempdir().unwrap();
|
||||
git_init_repo(repo_dir.path());
|
||||
let repo = RealGitRepository::new(
|
||||
&repo_dir.path().join(".git"),
|
||||
None,
|
||||
Some("git".into()),
|
||||
cx.executor(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
smol::fs::write(repo_dir.path().join("file1"), "content1")
|
||||
.await
|
||||
.unwrap();
|
||||
let checkpoint1 = repo.checkpoint().await.unwrap();
|
||||
|
||||
smol::fs::write(repo_dir.path().join("file2"), "content2")
|
||||
.await
|
||||
.unwrap();
|
||||
let checkpoint2 = repo.checkpoint().await.unwrap();
|
||||
|
||||
assert!(
|
||||
!repo
|
||||
.compare_checkpoints(checkpoint1, checkpoint2.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
let checkpoint3 = repo.checkpoint().await.unwrap();
|
||||
assert!(
|
||||
repo.compare_checkpoints(checkpoint2, checkpoint3)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let repo_dir = tempfile::tempdir().unwrap();
|
||||
let text_path = repo_dir.path().join("main.rs");
|
||||
let bin_path = repo_dir.path().join("binary.o");
|
||||
|
||||
git_init_repo(repo_dir.path());
|
||||
|
||||
smol::fs::write(&text_path, "fn main() {}").await.unwrap();
|
||||
|
||||
smol::fs::write(&bin_path, "some binary file here")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let repo = RealGitRepository::new(
|
||||
&repo_dir.path().join(".git"),
|
||||
None,
|
||||
Some("git".into()),
|
||||
cx.executor(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// initial commit
|
||||
repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
repo.commit(
|
||||
"Initial commit".into(),
|
||||
None,
|
||||
CommitOptions::default(),
|
||||
AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
|
||||
Arc::new(test_commit_envs()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let checkpoint = repo.checkpoint().await.unwrap();
|
||||
|
||||
smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
|
||||
.await
|
||||
.unwrap();
|
||||
smol::fs::write(&bin_path, "Modified binary file")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
repo.restore_checkpoint(checkpoint).await.unwrap();
|
||||
|
||||
// Text files should be restored to checkpoint state,
|
||||
// but binaries should not (they aren't tracked)
|
||||
assert_eq!(
|
||||
smol::fs::read_to_string(&text_path).await.unwrap(),
|
||||
"fn main() {}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
smol::fs::read_to_string(&bin_path).await.unwrap(),
|
||||
"Modified binary file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_branches_parsing() {
|
||||
// suppress "help: octal escapes are not supported, `\0` is always null"
|
||||
@@ -6787,6 +6303,78 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_archive_checkpoint_round_trip(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
cx.executor().allow_parking();
|
||||
|
||||
let repo_dir = tempfile::tempdir().unwrap();
|
||||
let path = repo_dir.path();
|
||||
git_init_repo(path);
|
||||
// Archive commits must not depend on the user having a Git identity.
|
||||
git_command(path, ["config", "user.useConfigOnly", "true"]);
|
||||
for name in ["staged", "unstaged", "deleted"] {
|
||||
fs::write(path.join(name), "initial").unwrap();
|
||||
}
|
||||
git_command(path, ["add", "--all"]);
|
||||
git_command(path, ["commit", "-m", "Initial commit"]);
|
||||
|
||||
fs::write(path.join("staged"), "staged change").unwrap();
|
||||
git_command(path, ["add", "staged"]);
|
||||
fs::write(path.join("unstaged"), "unstaged change").unwrap();
|
||||
fs::write(path.join("untracked"), "untracked").unwrap();
|
||||
fs::remove_file(path.join("deleted")).unwrap();
|
||||
let status_before = git_command_output(path, ["status", "--porcelain"]);
|
||||
|
||||
let repo =
|
||||
RealGitRepository::new(&path.join(".git"), None, Some("git".into()), cx.executor())
|
||||
.unwrap();
|
||||
let (staged_sha, unstaged_sha) = repo.create_archive_checkpoint().await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
git_command_output(path, ["status", "--porcelain"]),
|
||||
status_before,
|
||||
"archiving must not touch the index or working tree"
|
||||
);
|
||||
assert_eq!(
|
||||
git_command_output(path, ["for-each-ref", "refs/heads"])
|
||||
.lines()
|
||||
.count(),
|
||||
1,
|
||||
"archiving must not create branches"
|
||||
);
|
||||
let leftover_temp_indexes = fs::read_dir(path.join(".git"))
|
||||
.unwrap()
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| entry.file_name().to_string_lossy().starts_with("index-"))
|
||||
.count();
|
||||
assert_eq!(leftover_temp_indexes, 0);
|
||||
|
||||
git_command(path, ["reset", "--hard"]);
|
||||
git_command(path, ["clean", "--force"]);
|
||||
repo.restore_archive_checkpoint(staged_sha, unstaged_sha)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
git_command_output(path, ["status", "--porcelain"]),
|
||||
status_before
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(path.join("staged")).unwrap(),
|
||||
"staged change"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(path.join("unstaged")).unwrap(),
|
||||
"unstaged change"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(path.join("untracked")).unwrap(),
|
||||
"untracked"
|
||||
);
|
||||
assert!(!path.join("deleted").exists());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_initial_graph_data_ref_set(cx: &mut TestAppContext) {
|
||||
disable_git_global_config();
|
||||
@@ -6817,11 +6405,24 @@ mod tests {
|
||||
}
|
||||
commits
|
||||
};
|
||||
// Commits the worktree without moving HEAD or any branch.
|
||||
let commit_worktree = |parent: Option<&str>| -> Oid {
|
||||
git_command(repo_dir.path(), ["add", "--all"]);
|
||||
let tree = git_command_output(repo_dir.path(), ["write-tree"]);
|
||||
let mut arguments = vec!["commit-tree", tree.trim(), "-m", "commit"];
|
||||
if let Some(parent) = parent {
|
||||
arguments.extend(["-p", parent]);
|
||||
}
|
||||
git_command_output(repo_dir.path(), arguments)
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
smol::fs::write(repo_dir.path().join("file1"), "1")
|
||||
.await
|
||||
.unwrap();
|
||||
let branch_sha = repo.checkpoint().await.unwrap().commit_sha;
|
||||
let branch_sha = commit_worktree(None);
|
||||
repo.update_ref("refs/heads/main".into(), branch_sha.to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -6829,7 +6430,7 @@ mod tests {
|
||||
smol::fs::write(repo_dir.path().join("file2"), "2")
|
||||
.await
|
||||
.unwrap();
|
||||
let hidden_sha = repo.checkpoint().await.unwrap().commit_sha;
|
||||
let hidden_sha = commit_worktree(Some(&branch_sha.to_string()));
|
||||
repo.update_ref("refs/custom/hidden".into(), hidden_sha.to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -6980,30 +6581,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
impl RealGitRepository {
|
||||
/// Force a Git garbage collection on the repository.
|
||||
fn gc(&self) -> BoxFuture<'_, Result<()>> {
|
||||
let working_directory = self.command_directory();
|
||||
let git_directory = self.path();
|
||||
let git_binary_path = self.any_git_binary_path.clone();
|
||||
let executor = self.executor.clone();
|
||||
self.executor
|
||||
.spawn(async move {
|
||||
let git_binary_path = git_binary_path.clone();
|
||||
let git = GitBinary::new(
|
||||
git_binary_path,
|
||||
working_directory,
|
||||
git_directory,
|
||||
executor,
|
||||
true,
|
||||
);
|
||||
git.run(&["gc", "--prune"]).await?;
|
||||
Ok(())
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_remote_urls() {
|
||||
let stdout = concat!(
|
||||
|
||||
@@ -40,10 +40,9 @@ use git::{
|
||||
repository::{
|
||||
Branch, BranchesScanResult, CommitData, CommitDetails, CommitFileStatus, CommitOptions,
|
||||
CreateWorktreeTarget, DiffStatType, DiffType, FetchOptions, FileHistoryChangedFileSets,
|
||||
GitCommitTemplate, GitRepository, GitRepositoryCheckpoint, InitialGraphCommitData,
|
||||
LogOrder, LogSource, PushOptions, Remote, RemoteCommandOutput, RepoPath, ResetMode,
|
||||
SearchCommitArgs, UpstreamTrackingStatus, Worktree as GitWorktree, delete_branch_flag,
|
||||
is_binary_content,
|
||||
GitCommitTemplate, GitRepository, InitialGraphCommitData, LogOrder, LogSource, PushOptions,
|
||||
Remote, RemoteCommandOutput, RepoPath, ResetMode, SearchCommitArgs, UpstreamTrackingStatus,
|
||||
Worktree as GitWorktree, delete_branch_flag, is_binary_content,
|
||||
},
|
||||
stash::{GitStash, StashEntry},
|
||||
status::{
|
||||
@@ -494,11 +493,6 @@ struct LocalDownstreamState {
|
||||
_task: Task<Result<()>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GitStoreCheckpoint {
|
||||
checkpoints_by_work_dir_abs_path: HashMap<Arc<Path>, GitRepositoryCheckpoint>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StatusEntry {
|
||||
pub repo_path: RepoPath,
|
||||
@@ -1065,12 +1059,8 @@ impl GitStore {
|
||||
client.add_entity_request_handler(Self::handle_run_hook);
|
||||
client.add_entity_request_handler(Self::handle_reset);
|
||||
client.add_entity_request_handler(Self::handle_show);
|
||||
client.add_entity_request_handler(Self::handle_create_checkpoint);
|
||||
client.add_entity_request_handler(Self::handle_create_archive_checkpoint);
|
||||
client.add_entity_request_handler(Self::handle_restore_checkpoint);
|
||||
client.add_entity_request_handler(Self::handle_restore_archive_checkpoint);
|
||||
client.add_entity_request_handler(Self::handle_compare_checkpoints);
|
||||
client.add_entity_request_handler(Self::handle_diff_checkpoints);
|
||||
client.add_entity_request_handler(Self::handle_load_commit_diff);
|
||||
client.add_entity_request_handler(Self::handle_checkout_files);
|
||||
client.add_entity_request_handler(Self::handle_add_path_to_gitignore);
|
||||
@@ -2152,92 +2142,6 @@ impl GitStore {
|
||||
Some(repo.read(cx).status_for_path(&repo_path)?.status)
|
||||
}
|
||||
|
||||
pub fn checkpoint(&self, cx: &mut App) -> Task<Result<GitStoreCheckpoint>> {
|
||||
let mut work_directory_abs_paths = Vec::new();
|
||||
let mut checkpoints = Vec::new();
|
||||
for repository in self.repositories.values() {
|
||||
repository.update(cx, |repository, _| {
|
||||
work_directory_abs_paths.push(repository.snapshot.work_directory_abs_path.clone());
|
||||
checkpoints.push(repository.checkpoint().map(|checkpoint| checkpoint?));
|
||||
});
|
||||
}
|
||||
|
||||
cx.background_executor().spawn(async move {
|
||||
let checkpoints = future::try_join_all(checkpoints).await?;
|
||||
Ok(GitStoreCheckpoint {
|
||||
checkpoints_by_work_dir_abs_path: work_directory_abs_paths
|
||||
.into_iter()
|
||||
.zip(checkpoints)
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn restore_checkpoint(
|
||||
&self,
|
||||
checkpoint: GitStoreCheckpoint,
|
||||
cx: &mut App,
|
||||
) -> Task<Result<()>> {
|
||||
let repositories_by_work_dir_abs_path = self
|
||||
.repositories
|
||||
.values()
|
||||
.map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
for (work_dir_abs_path, checkpoint) in checkpoint.checkpoints_by_work_dir_abs_path {
|
||||
if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path) {
|
||||
let restore = repository.update(cx, |repository, _| {
|
||||
repository.restore_checkpoint(checkpoint)
|
||||
});
|
||||
tasks.push(async move { restore.await? });
|
||||
}
|
||||
}
|
||||
cx.background_spawn(async move {
|
||||
future::try_join_all(tasks).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Compares two checkpoints, returning true if they are equal.
|
||||
pub fn compare_checkpoints(
|
||||
&self,
|
||||
left: GitStoreCheckpoint,
|
||||
mut right: GitStoreCheckpoint,
|
||||
cx: &mut App,
|
||||
) -> Task<Result<bool>> {
|
||||
let repositories_by_work_dir_abs_path = self
|
||||
.repositories
|
||||
.values()
|
||||
.map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
for (work_dir_abs_path, left_checkpoint) in left.checkpoints_by_work_dir_abs_path {
|
||||
if let Some(right_checkpoint) = right
|
||||
.checkpoints_by_work_dir_abs_path
|
||||
.remove(&work_dir_abs_path)
|
||||
{
|
||||
if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path)
|
||||
{
|
||||
let compare = repository.update(cx, |repository, _| {
|
||||
repository.compare_checkpoints(left_checkpoint, right_checkpoint)
|
||||
});
|
||||
|
||||
tasks.push(async move { compare.await? });
|
||||
}
|
||||
} else {
|
||||
return Task::ready(Ok(false));
|
||||
}
|
||||
}
|
||||
cx.background_spawn(async move {
|
||||
Ok(future::try_join_all(tasks)
|
||||
.await?
|
||||
.into_iter()
|
||||
.all(|result| result))
|
||||
})
|
||||
}
|
||||
|
||||
/// Blames a buffer.
|
||||
pub fn blame_buffer(
|
||||
&self,
|
||||
@@ -4453,23 +4357,6 @@ impl GitStore {
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_create_checkpoint(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitCreateCheckpoint>,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<proto::GitCreateCheckpointResponse> {
|
||||
let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
|
||||
let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
|
||||
|
||||
let checkpoint = repository_handle
|
||||
.update(&mut cx, |repository, _| repository.checkpoint())
|
||||
.await??;
|
||||
|
||||
Ok(proto::GitCreateCheckpointResponse {
|
||||
commit_sha: checkpoint.commit_sha.as_bytes().to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_create_archive_checkpoint(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitCreateArchiveCheckpoint>,
|
||||
@@ -4490,27 +4377,6 @@ impl GitStore {
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_restore_checkpoint(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitRestoreCheckpoint>,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<proto::Ack> {
|
||||
let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
|
||||
let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
|
||||
|
||||
let checkpoint = GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&envelope.payload.commit_sha)?,
|
||||
};
|
||||
|
||||
repository_handle
|
||||
.update(&mut cx, |repository, _| {
|
||||
repository.restore_checkpoint(checkpoint)
|
||||
})
|
||||
.await??;
|
||||
|
||||
Ok(proto::Ack {})
|
||||
}
|
||||
|
||||
async fn handle_restore_archive_checkpoint(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitRestoreArchiveCheckpoint>,
|
||||
@@ -4530,54 +4396,6 @@ impl GitStore {
|
||||
Ok(proto::Ack {})
|
||||
}
|
||||
|
||||
async fn handle_compare_checkpoints(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitCompareCheckpoints>,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<proto::GitCompareCheckpointsResponse> {
|
||||
let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
|
||||
let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
|
||||
|
||||
let left = GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&envelope.payload.left_commit_sha)?,
|
||||
};
|
||||
let right = GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&envelope.payload.right_commit_sha)?,
|
||||
};
|
||||
|
||||
let equal = repository_handle
|
||||
.update(&mut cx, |repository, _| {
|
||||
repository.compare_checkpoints(left, right)
|
||||
})
|
||||
.await??;
|
||||
|
||||
Ok(proto::GitCompareCheckpointsResponse { equal })
|
||||
}
|
||||
|
||||
async fn handle_diff_checkpoints(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::GitDiffCheckpoints>,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<proto::GitDiffCheckpointsResponse> {
|
||||
let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
|
||||
let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
|
||||
|
||||
let base = GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&envelope.payload.base_commit_sha)?,
|
||||
};
|
||||
let target = GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&envelope.payload.target_commit_sha)?,
|
||||
};
|
||||
|
||||
let diff = repository_handle
|
||||
.update(&mut cx, |repository, _| {
|
||||
repository.diff_checkpoints(base, target)
|
||||
})
|
||||
.await??;
|
||||
|
||||
Ok(proto::GitDiffCheckpointsResponse { diff })
|
||||
}
|
||||
|
||||
async fn handle_load_commit_diff(
|
||||
this: Entity<Self>,
|
||||
envelope: TypedEnvelope<proto::LoadCommitDiff>,
|
||||
@@ -9986,53 +9804,6 @@ impl Repository {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn checkpoint(&mut self) -> oneshot::Receiver<Result<GitRepositoryCheckpoint>> {
|
||||
let id = self.id;
|
||||
self.send_job("checkpoint", None, move |repo, _cx| async move {
|
||||
match repo {
|
||||
RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
|
||||
backend.checkpoint().await
|
||||
}
|
||||
RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
|
||||
let response = client
|
||||
.request(proto::GitCreateCheckpoint {
|
||||
project_id: project_id.0,
|
||||
repository_id: id.to_proto(),
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(GitRepositoryCheckpoint {
|
||||
commit_sha: Oid::from_bytes(&response.commit_sha)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn restore_checkpoint(
|
||||
&mut self,
|
||||
checkpoint: GitRepositoryCheckpoint,
|
||||
) -> oneshot::Receiver<Result<()>> {
|
||||
let id = self.id;
|
||||
self.send_job("restore_checkpoint", None, move |repo, _cx| async move {
|
||||
match repo {
|
||||
RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
|
||||
backend.restore_checkpoint(checkpoint).await
|
||||
}
|
||||
RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
|
||||
client
|
||||
.request(proto::GitRestoreCheckpoint {
|
||||
project_id: project_id.0,
|
||||
repository_id: id.to_proto(),
|
||||
commit_sha: checkpoint.commit_sha.as_bytes().to_vec(),
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn apply_remote_update(
|
||||
&mut self,
|
||||
update: proto::UpdateRepository,
|
||||
@@ -10134,60 +9905,6 @@ impl Repository {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn compare_checkpoints(
|
||||
&mut self,
|
||||
left: GitRepositoryCheckpoint,
|
||||
right: GitRepositoryCheckpoint,
|
||||
) -> oneshot::Receiver<Result<bool>> {
|
||||
let id = self.id;
|
||||
self.send_job("compare_checkpoints", None, move |repo, _cx| async move {
|
||||
match repo {
|
||||
RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
|
||||
backend.compare_checkpoints(left, right).await
|
||||
}
|
||||
RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
|
||||
let response = client
|
||||
.request(proto::GitCompareCheckpoints {
|
||||
project_id: project_id.0,
|
||||
repository_id: id.to_proto(),
|
||||
left_commit_sha: left.commit_sha.as_bytes().to_vec(),
|
||||
right_commit_sha: right.commit_sha.as_bytes().to_vec(),
|
||||
})
|
||||
.await?;
|
||||
Ok(response.equal)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn diff_checkpoints(
|
||||
&mut self,
|
||||
base_checkpoint: GitRepositoryCheckpoint,
|
||||
target_checkpoint: GitRepositoryCheckpoint,
|
||||
) -> oneshot::Receiver<Result<String>> {
|
||||
let id = self.id;
|
||||
self.send_job("diff_checkpoints", None, move |repo, _cx| async move {
|
||||
match repo {
|
||||
RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
|
||||
backend
|
||||
.diff_checkpoints(base_checkpoint, target_checkpoint)
|
||||
.await
|
||||
}
|
||||
RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
|
||||
let response = client
|
||||
.request(proto::GitDiffCheckpoints {
|
||||
project_id: project_id.0,
|
||||
repository_id: id.to_proto(),
|
||||
base_commit_sha: base_checkpoint.commit_sha.as_bytes().to_vec(),
|
||||
target_commit_sha: target_checkpoint.commit_sha.as_bytes().to_vec(),
|
||||
})
|
||||
.await?;
|
||||
Ok(response.diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_pending_ops(&mut self, cx: &mut Context<Self>) {
|
||||
let updated = SumTree::from_iter(
|
||||
self.pending_ops.iter().filter_map(|ops| {
|
||||
|
||||
@@ -674,15 +674,6 @@ message GitCreateWorktree {
|
||||
bool use_existing_branch = 6;
|
||||
}
|
||||
|
||||
message GitCreateCheckpoint {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
}
|
||||
|
||||
message GitCreateCheckpointResponse {
|
||||
bytes commit_sha = 1;
|
||||
}
|
||||
|
||||
message GitCreateArchiveCheckpoint {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
@@ -693,12 +684,6 @@ message GitCreateArchiveCheckpointResponse {
|
||||
string unstaged_commit_sha = 2;
|
||||
}
|
||||
|
||||
message GitRestoreCheckpoint {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
bytes commit_sha = 3;
|
||||
}
|
||||
|
||||
message GitRestoreArchiveCheckpoint {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
@@ -706,28 +691,6 @@ message GitRestoreArchiveCheckpoint {
|
||||
string unstaged_commit_sha = 4;
|
||||
}
|
||||
|
||||
message GitCompareCheckpoints {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
bytes left_commit_sha = 3;
|
||||
bytes right_commit_sha = 4;
|
||||
}
|
||||
|
||||
message GitCompareCheckpointsResponse {
|
||||
bool equal = 1;
|
||||
}
|
||||
|
||||
message GitDiffCheckpoints {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
bytes base_commit_sha = 3;
|
||||
bytes target_commit_sha = 4;
|
||||
}
|
||||
|
||||
message GitDiffCheckpointsResponse {
|
||||
string diff = 1;
|
||||
}
|
||||
|
||||
message GitRemoveWorktree {
|
||||
uint64 project_id = 1;
|
||||
uint64 repository_id = 2;
|
||||
|
||||
@@ -465,13 +465,6 @@ message Envelope {
|
||||
KillKernel kill_kernel = 428;
|
||||
GitRemoveWorktree git_remove_worktree = 431;
|
||||
GitRenameWorktree git_rename_worktree = 432;
|
||||
GitCreateCheckpoint git_create_checkpoint = 433;
|
||||
GitCreateCheckpointResponse git_create_checkpoint_response = 434;
|
||||
GitRestoreCheckpoint git_restore_checkpoint = 435;
|
||||
GitCompareCheckpoints git_compare_checkpoints = 436;
|
||||
GitCompareCheckpointsResponse git_compare_checkpoints_response = 437;
|
||||
GitDiffCheckpoints git_diff_checkpoints = 438;
|
||||
GitDiffCheckpointsResponse git_diff_checkpoints_response = 439;
|
||||
GitGetHeadSha git_get_head_sha = 440;
|
||||
GitGetHeadShaResponse git_get_head_sha_response = 441;
|
||||
GitRepairWorktrees git_repair_worktrees = 442;
|
||||
@@ -553,6 +546,7 @@ message Envelope {
|
||||
reserved 211 to 216, 232 to 233;
|
||||
reserved 397 to 398;
|
||||
reserved 406 to 408;
|
||||
reserved 433 to 439;
|
||||
}
|
||||
|
||||
message Hello {
|
||||
|
||||
@@ -346,16 +346,9 @@ messages!(
|
||||
(GitAddPathToGitInfoExclude, Background),
|
||||
(GitShow, Background),
|
||||
(GitCommitDetails, Background),
|
||||
(GitCreateCheckpoint, Background),
|
||||
(GitCreateCheckpointResponse, Background),
|
||||
(GitCreateArchiveCheckpoint, Background),
|
||||
(GitCreateArchiveCheckpointResponse, Background),
|
||||
(GitRestoreCheckpoint, Background),
|
||||
(GitRestoreArchiveCheckpoint, Background),
|
||||
(GitCompareCheckpoints, Background),
|
||||
(GitCompareCheckpointsResponse, Background),
|
||||
(GitDiffCheckpoints, Background),
|
||||
(GitDiffCheckpointsResponse, Background),
|
||||
(SetIndexText, Background),
|
||||
(Push, Background),
|
||||
(Fetch, Background),
|
||||
@@ -612,15 +605,11 @@ request_messages!(
|
||||
(InstallExtension, Ack),
|
||||
(RegisterBufferWithLanguageServers, Ack),
|
||||
(GitShow, GitCommitDetails),
|
||||
(GitCreateCheckpoint, GitCreateCheckpointResponse),
|
||||
(
|
||||
GitCreateArchiveCheckpoint,
|
||||
GitCreateArchiveCheckpointResponse
|
||||
),
|
||||
(GitRestoreCheckpoint, Ack),
|
||||
(GitRestoreArchiveCheckpoint, Ack),
|
||||
(GitCompareCheckpoints, GitCompareCheckpointsResponse),
|
||||
(GitDiffCheckpoints, GitDiffCheckpointsResponse),
|
||||
(GitReset, Ack),
|
||||
(GitDeleteBranch, Ack),
|
||||
(GitCheckoutFiles, Ack),
|
||||
@@ -844,10 +833,6 @@ entity_messages!(
|
||||
CancelLanguageServerWork,
|
||||
RegisterBufferWithLanguageServers,
|
||||
GitShow,
|
||||
GitCreateCheckpoint,
|
||||
GitRestoreCheckpoint,
|
||||
GitCompareCheckpoints,
|
||||
GitDiffCheckpoints,
|
||||
GitReset,
|
||||
GitDeleteBranch,
|
||||
GitCheckoutFiles,
|
||||
|
||||
@@ -4735,153 +4735,6 @@ async fn test_remote_git_branches(cx: &mut TestAppContext, server_cx: &mut TestA
|
||||
assert_eq!(default_branch_with_remote.as_deref(), Some("origin/main"));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_remote_git_checkpoints(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
|
||||
let fs = FakeFs::new(server_cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/code"),
|
||||
json!({
|
||||
"project1": {
|
||||
".git": {},
|
||||
"file.txt": "original content",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let (project, _headless) = init_test(&fs, cx, server_cx).await;
|
||||
|
||||
let (_worktree, _) = project
|
||||
.update(cx, |project, cx| {
|
||||
project.find_or_create_worktree(path!("/code/project1"), true, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
let repository = project.update(cx, |project, cx| project.active_repository(cx).unwrap());
|
||||
|
||||
// 1. Create a checkpoint of the original state
|
||||
let checkpoint_1 = repository
|
||||
.update(cx, |repository, _| repository.checkpoint())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// 2. Modify a file on the server-side fs
|
||||
fs.write(
|
||||
Path::new(path!("/code/project1/file.txt")),
|
||||
b"modified content",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// 3. Create a second checkpoint with the modified state
|
||||
let checkpoint_2 = repository
|
||||
.update(cx, |repository, _| repository.checkpoint())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// 4. compare_checkpoints: same checkpoint with itself => equal
|
||||
let equal = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_1.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(equal, "a checkpoint compared with itself should be equal");
|
||||
|
||||
// 5. compare_checkpoints: different states => not equal
|
||||
let equal = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_2.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!equal,
|
||||
"checkpoints of different states should not be equal"
|
||||
);
|
||||
|
||||
// 6. diff_checkpoints: same checkpoint => empty diff
|
||||
let diff = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_1.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
diff.is_empty(),
|
||||
"diff of identical checkpoints should be empty"
|
||||
);
|
||||
|
||||
// 7. diff_checkpoints: different checkpoints => non-empty diff mentioning the changed file
|
||||
let diff = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_2.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!diff.is_empty(),
|
||||
"diff of different checkpoints should be non-empty"
|
||||
);
|
||||
assert!(
|
||||
diff.contains("file.txt"),
|
||||
"diff should mention the changed file"
|
||||
);
|
||||
assert!(
|
||||
diff.contains("original content"),
|
||||
"diff should contain removed content"
|
||||
);
|
||||
assert!(
|
||||
diff.contains("modified content"),
|
||||
"diff should contain added content"
|
||||
);
|
||||
|
||||
// 8. restore_checkpoint: restore to original state
|
||||
repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.restore_checkpoint(checkpoint_1.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
// 9. Create a checkpoint after restore
|
||||
let checkpoint_3 = repository
|
||||
.update(cx, |repository, _| repository.checkpoint())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// 10. compare_checkpoints: restored state matches original
|
||||
let equal = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_3.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(equal, "restored state should match original checkpoint");
|
||||
|
||||
// 11. diff_checkpoints: restored state vs original => empty diff
|
||||
let diff = repository
|
||||
.update(cx, |repository, _| {
|
||||
repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_3.clone())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(diff.is_empty(), "diff after restore should be empty");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_remote_agent_fs_tool_calls(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
|
||||
let fs = FakeFs::new(server_cx.executor());
|
||||
|
||||
@@ -13444,8 +13444,7 @@ mod property_test {
|
||||
let thread_id = active_thread_id(&panel, cx);
|
||||
let session_id = active_session_id(&panel, cx);
|
||||
// Make the thread non-draft without exercising the prompt
|
||||
// send path; these invariants are about sidebar state, not
|
||||
// git checkpointing during user prompts.
|
||||
// send path; these invariants are about sidebar state.
|
||||
cx.update(|_, cx| {
|
||||
connection.send_update(
|
||||
session_id.clone(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: AI Coding Agent - Zed Agent Panel
|
||||
description: Use Zed's AI coding agent to generate, refactor, and debug code with tool calling, checkpoints, and multi-model support.
|
||||
description: Use Zed's AI coding agent to generate, refactor, and debug code with tool calling and multi-model support.
|
||||
---
|
||||
|
||||
# Agent Panel
|
||||
@@ -26,7 +26,7 @@ Expand the editor with {#kb agent::ExpandMessageEditor} if you need more room.
|
||||
Responses stream in with indicators showing [which tools](./tools.md) the model is using.
|
||||
The sections below cover what you can do from here.
|
||||
|
||||
> Note that some Agent Panel features may not be available for every External Agent. Restoring threads from history, checkpoints, token usage display, and similar features depend on the agent integration.
|
||||
> Note that some Agent Panel features may not be available for every External Agent. Restoring threads from history, token usage display, and similar features depend on the agent integration.
|
||||
> Their availability varies depending on the agent.
|
||||
|
||||
### Creating New Threads {#new-thread}
|
||||
@@ -69,12 +69,6 @@ By default, queued messages get sent once the agent finishes generating. If you
|
||||
You can edit or remove (an individual or all) queued messages.
|
||||
You can also still interrupt the agent immediately if you want by either clicking on the stop button or by clicking the "Send Now" (double-enter) on a queued message.
|
||||
|
||||
### Checkpoints {#checkpoints}
|
||||
|
||||
Every time the model performs an edit, you should see a "Restore Checkpoint" button at the top of your message, allowing you to return your code base to the state it was in prior to that message.
|
||||
|
||||
The checkpoint button appears even if you interrupt the thread midway through an edit, as this is likely a moment when you've identified that the agent is not heading in the right direction and you want to revert back.
|
||||
|
||||
### Context Menu {#context-menu}
|
||||
|
||||
Right-click on any agent response in the thread view to access a context menu with the following actions:
|
||||
|
||||
Reference in New Issue
Block a user