Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Prevent idle sleep during AI response streaming (#53130)

Xiaobo Liu450775244fad
diff --git a/Cargo.lock b/Cargo.lock
index c075e43b68a..1e74bce4596 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -88,6 +88,7 @@ version = "0.1.0"
dependencies = [
"action_log",
"agent-client-protocol",
+ "agent_settings",
"anyhow",
"async-channel 2.5.0",
"base64 0.22.1",
@@ -10167,7 +10168,6 @@ dependencies = [
"anyhow",
"async-trait",
"audio",
- "cocoa 0.26.0",
"collections",
"core-foundation 0.10.0",
"core-video",
@@ -10184,7 +10184,6 @@ dependencies = [
"livekit_api",
"log",
"nanoid",
- "objc",
"parking_lot",
"postage",
"rodio",
diff --git a/Cargo.toml b/Cargo.toml
index 144d3f138f4..cfe8f56d63f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -525,6 +525,7 @@ any_vec = "0.14"
anyhow = "1.0.86"
ashpd = { version = "0.13", default-features = false, features = [
"async-io",
+ "inhibit",
"notification",
"open_uri",
"file_chooser",
@@ -955,6 +956,7 @@ features = [
"Win32_System_Ole",
"Win32_System_Performance",
"Win32_System_Pipes",
+ "Win32_System_Power",
"Win32_System_RestartManager",
"Win32_System_SystemInformation",
"Win32_System_SystemServices",
diff --git a/assets/settings/default.json b/assets/settings/default.json
index 86ddd622432..fd52963231c 100644
--- a/assets/settings/default.json
+++ b/assets/settings/default.json
@@ -1330,6 +1330,10 @@
//
// Default: never
"play_sound_when_agent_done": "never",
+ // Whether to keep the system awake while agent threads are running.
+ //
+ // Default: true
+ "prevent_idle_sleep": true,
// Whether to have edit cards in the agent panel expanded, showing a preview of the full diff.
//
// Default: true
diff --git a/crates/acp_thread/Cargo.toml b/crates/acp_thread/Cargo.toml
index 3c4f592a554..3b5a9fa3cce 100644
--- a/crates/acp_thread/Cargo.toml
+++ b/crates/acp_thread/Cargo.toml
@@ -17,6 +17,7 @@ test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot"]
[dependencies]
action_log.workspace = true
+agent_settings.workspace = true
agent-client-protocol.workspace = true
async-channel.workspace = true
base64.workspace = true
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 194a528590f..c3ec880cb58 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -5,6 +5,7 @@ mod terminal;
pub use ::terminal::HeadlessTerminal;
use action_log::{ActionLog, ActionLogTelemetry};
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp};
+use agent_settings::AgentSettings;
use anyhow::{Context as _, Result, anyhow};
use collections::HashSet;
pub use connection::*;
@@ -12,8 +13,8 @@ pub use diff::*;
use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
use futures::{FutureExt, channel::oneshot, future::BoxFuture};
use gpui::{
- AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Subscription, Task,
- WeakEntity,
+ ActivityGuard, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Subscription,
+ Task, WeakEntity,
};
use itertools::Itertools;
use language::language_settings::FormatOnSave;
@@ -29,6 +30,7 @@ use project::{
};
use serde::{Deserialize, Serialize};
use serde_json::to_string_pretty;
+use settings::{Settings, SettingsStore};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Formatter, Write};
@@ -2108,6 +2110,7 @@ pub struct AcpThread {
prompt_capabilities: acp::PromptCapabilities,
available_commands: Vec<acp::AvailableCommand>,
_observe_prompt_capabilities: Task<anyhow::Result<()>>,
+ _idle_sleep_subscriptions: Vec<Subscription>,
terminals: HashMap<acp::TerminalId, Entity<Terminal>>,
pending_terminal_output: HashMap<acp::TerminalId, Vec<Vec<u8>>>,
pending_terminal_exit: HashMap<acp::TerminalId, acp::TerminalExitStatus>,
@@ -2121,6 +2124,14 @@ pub struct AcpThread {
/// gradually to create a fluid typing effect instead of choppy chunk-at-a-time
/// updates.
streaming_text_buffer: Option<StreamingTextBuffer>,
+ idle_sleep_prevention: IdleSleepPrevention,
+}
+
+enum IdleSleepPrevention {
+ Inactive,
+ Acquiring { _task: Task<()> },
+ Active { _guard: ActivityGuard },
+ Failed,
}
struct StreamingTextBuffer {
@@ -2283,6 +2294,34 @@ impl AcpThread {
})?;
}
});
+ let idle_sleep_settings_subscription = cx.observe_global::<SettingsStore>(|this, cx| {
+ this.update_idle_sleep_prevention(cx);
+ });
+ let idle_sleep_event_subscription =
+ cx.subscribe_self(|this, event: &AcpThreadEvent, cx| match event {
+ AcpThreadEvent::StatusChanged
+ | AcpThreadEvent::EntriesRemoved(_)
+ | AcpThreadEvent::ToolAuthorizationRequested(_)
+ | AcpThreadEvent::ToolAuthorizationReceived(_)
+ | AcpThreadEvent::ElicitationRequested(_)
+ | AcpThreadEvent::ElicitationResponded(_) => this.update_idle_sleep_prevention(cx),
+ AcpThreadEvent::PromptUpdated
+ | AcpThreadEvent::NewEntry
+ | AcpThreadEvent::TitleUpdated
+ | AcpThreadEvent::TokenUsageUpdated
+ | AcpThreadEvent::EntryUpdated(_)
+ | AcpThreadEvent::Retry(_)
+ | AcpThreadEvent::SubagentSpawned(_)
+ | AcpThreadEvent::Stopped(_)
+ | AcpThreadEvent::Error
+ | AcpThreadEvent::LoadError(_)
+ | AcpThreadEvent::PromptCapabilitiesUpdated
+ | AcpThreadEvent::Refusal
+ | AcpThreadEvent::AvailableCommandsUpdated(_)
+ | AcpThreadEvent::ModeUpdated(_)
+ | AcpThreadEvent::ConfigOptionsUpdated(_)
+ | AcpThreadEvent::WorkingDirectoriesUpdated => {}
+ });
let git_store = project.read(cx).git_store().clone();
let _git_store_subscription = cx.subscribe(&git_store, |this, _, event, cx| {
@@ -2321,6 +2360,10 @@ impl AcpThread {
prompt_capabilities,
available_commands: Vec::new(),
_observe_prompt_capabilities: task,
+ _idle_sleep_subscriptions: vec![
+ idle_sleep_settings_subscription,
+ idle_sleep_event_subscription,
+ ],
terminals: HashMap::default(),
pending_terminal_output: HashMap::default(),
pending_terminal_exit: HashMap::default(),
@@ -2328,6 +2371,7 @@ impl AcpThread {
draft_prompt: None,
ui_scroll_position: None,
streaming_text_buffer: None,
+ idle_sleep_prevention: IdleSleepPrevention::Inactive,
}
}
@@ -3158,14 +3202,17 @@ impl AcpThread {
match update {
ToolCallUpdate::UpdateFields(update) => {
let location_updated = update.fields.locations.is_some();
- call.update_fields(
+ if let Err(error) = call.update_fields(
update.fields,
update.meta,
languages,
path_style,
&self.terminals,
cx,
- )?;
+ ) {
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ return Err(error);
+ }
if location_updated {
self.resolve_locations(update.tool_call_id, cx);
}
@@ -3230,14 +3277,17 @@ impl AcpThread {
unreachable!()
};
- call.update_fields(
+ if let Err(error) = call.update_fields(
update.fields,
update.meta,
language_registry,
path_style,
&self.terminals,
cx,
- )?;
+ ) {
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ return Err(acp::Error::from(error));
+ }
call.update_status(status);
cx.emit(AcpThreadEvent::EntryUpdated(ix));
@@ -3753,14 +3803,21 @@ impl AcpThread {
});
cx.emit(AcpThreadEvent::StatusChanged);
- cx.spawn(async move |this, cx| {
+ let completion = async move |thread: WeakEntity<Self>, cx: &mut AsyncApp| {
let response = rx.await;
- this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
+ thread
+ .update(cx, |this, cx| {
+ if this.turn_id == turn_id {
+ this.update_last_checkpoint(cx)
+ } else {
+ Task::ready(Ok(()))
+ }
+ })?
.await?;
- this.update(cx, |this, cx| {
- if this.parent_session_id.is_none() {
+ thread.update(cx, |this, cx| {
+ if this.turn_id == turn_id && this.parent_session_id.is_none() {
this.project
.update(cx, |project, cx| project.set_agent_location(None, cx));
}
@@ -3787,6 +3844,10 @@ impl AcpThread {
return Ok(None);
};
+ if this.turn_id != turn_id {
+ return response.map(Some);
+ }
+
match response {
Ok(r) => {
Self::flush_streaming_text(&mut this.streaming_text_buffer, cx);
@@ -3894,8 +3955,13 @@ impl AcpThread {
}
}
})?
+ };
+ let (completion_tx, completion_rx) = oneshot::channel();
+ cx.spawn(async move |thread, cx| {
+ completion_tx.send(completion(thread, cx).await).ok();
})
- .boxed()
+ .detach();
+ async move { completion_rx.await? }.boxed()
}
pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
@@ -3921,6 +3987,38 @@ impl AcpThread {
cx.background_spawn(turn.send_task)
}
+ fn update_idle_sleep_prevention(&mut self, cx: &mut Context<Self>) {
+ if !AgentSettings::get_global(cx).prevent_idle_sleep
+ || self.running_turn.is_none()
+ || self.is_waiting_for_confirmation()
+ {
+ self.idle_sleep_prevention = IdleSleepPrevention::Inactive;
+ return;
+ }
+
+ if !matches!(self.idle_sleep_prevention, IdleSleepPrevention::Inactive) {
+ return;
+ }
+
+ let acquisition = cx.prevent_idle_sleep("Agent thread in progress");
+ self.idle_sleep_prevention = IdleSleepPrevention::Acquiring {
+ _task: cx.spawn(async move |thread, cx| {
+ let result = acquisition.await;
+ thread
+ .update(cx, |thread, _| {
+ thread.idle_sleep_prevention = match result {
+ Ok(guard) => IdleSleepPrevention::Active { _guard: guard },
+ Err(error) => {
+ log::error!("Failed to prevent idle sleep: {error:#}");
+ IdleSleepPrevention::Failed
+ }
+ };
+ })
+ .log_err();
+ }),
+ };
+ }
+
fn cancel_pending_turn_entries(&mut self, cx: &mut Context<Self>) {
self.mark_pending_entries_as_canceled(RequestPermissionOutcome::Cancelled, cx);
self.cancel_outstanding_elicitations(cx);
@@ -9481,6 +9579,8 @@ mod tests {
// First handler waits for this signal before completing
let (first_complete_tx, first_complete_rx) = futures::channel::oneshot::channel::<()>();
let first_complete_rx = RefCell::new(Some(first_complete_rx));
+ let (second_complete_tx, second_complete_rx) = oneshot::channel::<()>();
+ let second_complete_rx = RefCell::new(Some(second_complete_rx));
let connection = Rc::new(FakeAgentConnection::new().on_user_message({
move |params, _thread, _cx| {
@@ -9489,6 +9589,11 @@ mod tests {
.prompt
.iter()
.any(|c| matches!(c, acp::ContentBlock::Text(t) if t.text.contains("first")));
+ let second_complete_rx = if is_first {
+ None
+ } else {
+ second_complete_rx.borrow_mut().take()
+ };
async move {
if is_first {
@@ -9496,6 +9601,10 @@ mod tests {
if let Some(rx) = first_complete_rx {
rx.await.ok();
}
+ } else {
+ second_complete_rx
+ .expect("second completion receiver should be available")
+ .await?;
}
Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
}
@@ -9512,7 +9621,9 @@ mod tests {
// Send first message (turn_id=1) - handler will block
let first_request = thread.update(cx, |thread, cx| thread.send_raw("first", cx));
+ cx.run_until_parked();
assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
@@ -9523,6 +9634,7 @@ mod tests {
)
})
.unwrap();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
// Send second message (turn_id=2) while first is still blocked
// This calls cancel() which takes turn 1's running_turn and sets turn 2's
@@ -9532,6 +9644,7 @@ mod tests {
RequestPermissionOutcome::InterruptedByFollowUp
));
assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 2);
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
let running_turn_after_second_send =
thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
@@ -9555,8 +9668,12 @@ mod tests {
Some(2),
"first turn completing should not clear running_turn (belongs to turn 2)"
);
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
// Second request completes - SHOULD clear running_turn
+ second_complete_tx
+ .send(())
+ .expect("second completion receiver should still be alive");
second_request.await.unwrap();
let running_turn_after_second =
@@ -9565,6 +9682,40 @@ mod tests {
!running_turn_after_second,
"second turn completing should clear running_turn"
);
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_setting_toggle_updates_idle_sleep_prevention_for_running_turn(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ set_prevent_idle_sleep(false, cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ for (enabled, expected_count) in [(true, 1), (true, 1), (false, 0), (false, 0), (true, 1)] {
+ set_prevent_idle_sleep(enabled, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), expected_count);
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+ }
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ for enabled in [false, true] {
+ set_prevent_idle_sleep(enabled, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
}
#[gpui::test]
@@ -10197,4 +10348,1095 @@ mod tests {
"running_turn must be cleared even when tx was dropped without send"
);
}
+
+ #[gpui::test]
+ async fn test_dropped_completion_waiter_does_not_leave_thread_generating(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, completion) = oneshot::channel::<()>();
+ let backend_finished = Rc::new(AtomicBool::new(false));
+ let statuses = Rc::new(RefCell::new(Vec::new()));
+ let _subscription = cx.update(|cx| {
+ cx.subscribe(&thread, {
+ let statuses = statuses.clone();
+ move |thread, event, cx| {
+ if matches!(event, AcpThreadEvent::StatusChanged) {
+ statuses.borrow_mut().push(thread.read(cx).status());
+ }
+ }
+ })
+ });
+ let request = thread.update(cx, |thread, cx| {
+ thread.run_turn(cx, {
+ let backend_finished = backend_finished.clone();
+ async move |_, _| {
+ completion.await?;
+ backend_finished.store(true, SeqCst);
+ Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ }
+ })
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+ assert!(!backend_finished.load(SeqCst));
+
+ drop(request);
+ cx.run_until_parked();
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+ complete.send(()).expect("backend should still be running");
+ cx.run_until_parked();
+
+ assert!(backend_finished.load(SeqCst));
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Idle
+ );
+ assert_eq!(
+ *statuses.borrow(),
+ vec![ThreadStatus::Generating, ThreadStatus::Idle]
+ );
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_released_on_turn_completion(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ assert!(cx.read(|cx| AgentSettings::get_global(cx).prevent_idle_sleep));
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ for (delay, expected_count) in [(Duration::ZERO, 1), (Duration::from_secs(2), 0)] {
+ cx.set_idle_sleep_prevention_delay(delay);
+ for (backend_result, expected_result, expected_had_error) in [
+ (
+ Ok(acp::StopReason::EndTurn),
+ Ok(acp::StopReason::EndTurn),
+ false,
+ ),
+ (
+ Ok(acp::StopReason::Cancelled),
+ Ok(acp::StopReason::Cancelled),
+ false,
+ ),
+ (
+ Ok(acp::StopReason::Refusal),
+ Ok(acp::StopReason::Refusal),
+ true,
+ ),
+ (
+ Ok(acp::StopReason::MaxTokens),
+ Err("output token limit reached"),
+ true,
+ ),
+ (Err(anyhow!("backend failed")), Err("backend failed"), true),
+ ] {
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), expected_count);
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+ assert!(!thread.read_with(cx, |thread, _| thread.had_error()));
+
+ complete
+ .send(backend_result.map(acp::PromptResponse::new))
+ .expect("turn should still be running");
+ let result = request
+ .await
+ .map(|response| response.map(|response| response.stop_reason))
+ .map_err(|error| error.to_string());
+ assert_eq!(result, expected_result.map(Some).map_err(String::from));
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.status(), ThreadStatus::Idle);
+ assert_eq!(thread.had_error(), expected_had_error);
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ });
+ cx.executor().advance_clock(Duration::from_secs(2));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_overlaps_distinct_threads_and_subagent(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let parent = new_test_thread(cx).await;
+ let independent = new_test_thread(cx).await;
+ let subagent = cx.update(|cx| {
+ let parent = parent.read(cx);
+ let session_id = parent.session_id().clone();
+ let connection = parent.connection.clone();
+ let project = parent.project.clone();
+ let action_log = cx.new(|_| ActionLog::new(project.clone()));
+ cx.new(|cx| {
+ AcpThread::new(
+ Some(session_id),
+ None,
+ None,
+ connection,
+ project,
+ action_log,
+ acp::SessionId::new("subagent"),
+ watch::Receiver::constant(acp::PromptCapabilities::new()),
+ cx,
+ )
+ })
+ });
+ assert_ne!(parent.entity_id(), independent.entity_id());
+ assert_ne!(parent.entity_id(), subagent.entity_id());
+ assert_ne!(independent.entity_id(), subagent.entity_id());
+ assert_eq!(
+ subagent.read_with(cx, |thread, _| thread.parent_session_id().cloned()),
+ Some(parent.read_with(cx, |thread, _| thread.session_id().clone()))
+ );
+
+ let (parent_complete, parent_request) = start_test_turn(&parent, cx);
+ let (independent_complete, independent_request) = start_test_turn(&independent, cx);
+ let (subagent_complete, subagent_request) = start_test_turn(&subagent, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 3);
+
+ let parent_cancel = parent.update(cx, |thread, cx| thread.cancel(cx));
+ assert_eq!(cx.active_idle_sleep_preventions(), 2);
+ parent_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .expect("parent backend should still be running");
+ parent_cancel.await;
+ parent_request.await.expect("parent turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 2);
+
+ independent_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("independent turn should still be running");
+ independent_request
+ .await
+ .expect("independent turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ assert_eq!(
+ subagent.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+
+ subagent_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("subagent should still be running");
+ subagent_request
+ .await
+ .expect("subagent turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_cancel_releases_pending_idle_sleep_prevention(cx: &mut TestAppContext) {
+ init_test(cx);
+ for (delay, acquisition_fails, expected_count) in [
+ (Duration::ZERO, false, 1),
+ (Duration::from_secs(2), false, 0),
+ (Duration::from_secs(2), true, 0),
+ ] {
+ cx.set_idle_sleep_prevention_delay(delay);
+ cx.set_idle_sleep_prevention_fails(acquisition_fails);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ assert_eq!(cx.active_idle_sleep_preventions(), expected_count);
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Acquiring { .. }
+ ));
+ });
+
+ let cancel = thread.update(cx, |thread, cx| thread.cancel(cx));
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(2));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.status(), ThreadStatus::Idle);
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ });
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("backend should still be running");
+ cancel.await;
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_setting_disables_pending_idle_sleep_prevention(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.set_idle_sleep_prevention_delay(Duration::from_secs(2));
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ set_prevent_idle_sleep(false, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.status(), ThreadStatus::Generating);
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ });
+
+ set_prevent_idle_sleep(true, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ set_prevent_idle_sleep(true, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_follow_up_keeps_pending_idle_sleep_prevention(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.set_idle_sleep_prevention_delay(Duration::from_secs(2));
+ let thread = new_test_thread(cx).await;
+ let (first_complete, first_request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ let (second_complete, second_request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.running_turn.as_ref().map(|turn| turn.id), Some(2));
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Acquiring { .. }
+ ));
+ });
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+
+ first_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .expect("first backend should still be running");
+ first_request.await.expect("first turn should complete");
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.running_turn.as_ref().map(|turn| turn.id), Some(2));
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+
+ second_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("second backend should still be running");
+ second_request.await.expect("second turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_dropping_thread_releases_idle_sleep_prevention(cx: &mut TestAppContext) {
+ init_test(cx);
+ for (delay, expected_count) in [(Duration::ZERO, 1), (Duration::from_secs(2), 0)] {
+ cx.set_idle_sleep_prevention_delay(delay);
+ let thread = new_test_thread(cx).await;
+ let weak_thread = thread.downgrade();
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), expected_count);
+
+ cx.update(|_| drop(thread));
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(2));
+ cx.run_until_parked();
+ assert!(weak_thread.upgrade().is_none());
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ assert!(request.await.is_err());
+ drop(complete);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_failure_retries_only_on_setting_toggle(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ for delay in [Duration::ZERO, Duration::from_secs(2)] {
+ cx.set_idle_sleep_prevention_delay(delay);
+ cx.set_idle_sleep_prevention_fails(true);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(delay);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Failed
+ ));
+ assert_eq!(thread.status(), ThreadStatus::Generating);
+ assert!(!thread.had_error());
+ });
+
+ cx.set_idle_sleep_prevention_fails(false);
+ set_prevent_idle_sleep(true, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(4));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ assert!(thread.read_with(cx, |thread, _| matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Failed
+ )));
+
+ set_prevent_idle_sleep(false, cx);
+ cx.run_until_parked();
+ assert!(!thread.read_with(cx, |thread, _| matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Failed
+ )));
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ set_prevent_idle_sleep(true, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(delay);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_failure_clears_when_turn_stops(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ for cancel_turn in [false, true] {
+ cx.set_idle_sleep_prevention_fails(true);
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert!(thread.read_with(cx, |thread, _| matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Failed
+ )));
+
+ let cancel = if cancel_turn {
+ let cancel = thread.update(cx, |thread, cx| thread.cancel(cx));
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ assert_eq!(thread.status(), ThreadStatus::Idle);
+ });
+ Some(cancel)
+ } else {
+ None
+ };
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("backend should still be running");
+ if let Some(cancel) = cancel {
+ cancel.await;
+ }
+ request.await.expect("turn should complete");
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ assert_eq!(thread.status(), ThreadStatus::Idle);
+ });
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ cx.set_idle_sleep_prevention_fails(false);
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("next turn should still be running");
+ request.await.expect("next turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_waits_for_all_confirmations(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ let first_id = acp::ToolCallId::new("first-permission");
+ let second_id = acp::ToolCallId::new("second-permission");
+ let first_permission = request_test_permission(&thread, first_id.clone(), cx);
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ let second_permission = request_test_permission(&thread, second_id.clone(), cx);
+ let (elicitation_id, elicitation_response) = request_test_form_elicitation(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ for enabled in [false, true] {
+ set_prevent_idle_sleep(enabled, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ thread.update(cx, |thread, cx| {
+ thread
+ .update_tool_call(
+ acp::ToolCallUpdate::new(
+ first_id.clone(),
+ acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
+ ),
+ cx,
+ )
+ .expect("tool update should succeed");
+ thread.authorize_tool_call(
+ second_id,
+ SelectedPermissionOutcome::new(
+ acp::PermissionOptionId::new("reject"),
+ acp::PermissionOptionKind::RejectOnce,
+ ),
+ cx,
+ );
+ });
+ assert!(matches!(
+ second_permission.await,
+ RequestPermissionOutcome::Selected(outcome)
+ if outcome.option_kind == acp::PermissionOptionKind::RejectOnce
+ ));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ });
+ assert_eq!(
+ elicitation_response.await.action,
+ acp::ElicitationAction::Decline
+ );
+ cx.run_until_parked();
+ assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ thread.update(cx, |thread, cx| {
+ thread.authorize_tool_call(
+ first_id,
+ SelectedPermissionOutcome::new(
+ acp::PermissionOptionId::new("allow"),
+ acp::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ });
+ assert!(matches!(
+ first_permission.await,
+ RequestPermissionOutcome::Selected(outcome)
+ if outcome.option_kind == acp::PermissionOptionKind::AllowOnce
+ ));
+ cx.run_until_parked();
+ assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_resumes_after_permission_cancellation_or_terminal_update(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ for status in [
+ None,
+ Some(acp::ToolCallStatus::Completed),
+ Some(acp::ToolCallStatus::Failed),
+ ] {
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ let tool_call_id = acp::ToolCallId::new("permission");
+ let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ thread.update(cx, |thread, cx| {
+ if let Some(status) = status {
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ tool_call_id,
+ acp::ToolCallUpdateFields::new().status(status),
+ )),
+ cx,
+ )
+ .expect("terminal tool update should succeed");
+ } else {
+ thread.cancel_tool_call_authorization(&tool_call_id, cx);
+ }
+ });
+ assert!(matches!(
+ permission.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ cx.run_until_parked();
+ assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 1, "status: {status:?}");
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+
+ #[gpui::test]
+ async fn test_permission_suspends_pending_idle_sleep_prevention(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.set_idle_sleep_prevention_delay(Duration::from_secs(2));
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ let tool_call_id = acp::ToolCallId::new("permission");
+ let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.read_with(cx, |thread, _| {
+ assert!(thread.is_waiting_for_confirmation());
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Inactive
+ ));
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.authorize_tool_call(
+ tool_call_id,
+ SelectedPermissionOutcome::new(
+ acp::PermissionOptionId::new("allow"),
+ acp::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ });
+ assert!(matches!(
+ permission.await,
+ RequestPermissionOutcome::Selected(_)
+ ));
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_resumes_after_form_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ for action in [
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
+ acp::ElicitationAction::Decline,
+ acp::ElicitationAction::Cancel,
+ ] {
+ let (elicitation_id, response) = request_test_form_elicitation(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Generating
+ );
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(action.clone()),
+ cx,
+ );
+ });
+ assert_eq!(response.await.action, action);
+ cx.run_until_parked();
+ assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ }
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_idle_sleep_prevention_resumes_after_url_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ for (url_id, accept) in [("accepted", true), ("canceled", false)] {
+ let url_id = acp::ElicitationId::new(url_id);
+ let (entry_id, response) = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation_with_id(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(thread.session_id().clone()),
+ url_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .expect("URL elicitation should succeed")
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_id, cx)
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ let expected_action = if accept {
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new())
+ } else {
+ acp::ElicitationAction::Cancel
+ };
+ thread.update(cx, |thread, cx| {
+ if accept {
+ thread.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(expected_action.clone()),
+ cx,
+ );
+ } else {
+ thread.cancel_elicitation(&entry_id, cx);
+ }
+ });
+ assert_eq!(response.await.action, expected_action);
+ cx.run_until_parked();
+ assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_id, cx)
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ }
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("turn should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_confirmation_resolution_does_not_reacquire_idle_sleep_prevention_after_cancel(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ let tool_call_id = acp::ToolCallId::new("permission");
+ let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
+ let (elicitation_id, elicitation_response) = request_test_form_elicitation(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ let cancel = thread.update(cx, |thread, cx| thread.cancel(cx));
+ assert!(matches!(
+ permission.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ assert_eq!(
+ elicitation_response.await.action,
+ acp::ElicitationAction::Cancel
+ );
+ thread.update(cx, |thread, cx| {
+ thread.authorize_tool_call(
+ tool_call_id,
+ SelectedPermissionOutcome::new(
+ acp::PermissionOptionId::new("allow"),
+ acp::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.status()),
+ ThreadStatus::Idle
+ );
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .expect("backend should still be running");
+ cancel.await;
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+
+ #[gpui::test]
+ async fn test_stale_refusal_does_not_affect_follow_up_turn(cx: &mut TestAppContext) {
+ assert_stale_completion_does_not_affect_follow_up_turn(Ok(acp::StopReason::Refusal), cx)
+ .await;
+ }
+
+ #[gpui::test]
+ async fn test_stale_error_does_not_affect_follow_up_turn(cx: &mut TestAppContext) {
+ assert_stale_completion_does_not_affect_follow_up_turn(Err("first turn failed"), cx).await;
+ }
+
+ #[gpui::test]
+ async fn test_failed_tool_update_resumes_sleep_prevention(cx: &mut TestAppContext) {
+ assert_failed_tool_update_resumes_sleep_prevention(false, cx).await;
+ }
+
+ #[gpui::test]
+ async fn test_failed_tool_upsert_resumes_sleep_prevention(cx: &mut TestAppContext) {
+ assert_failed_tool_update_resumes_sleep_prevention(true, cx).await;
+ }
+
+ fn start_test_turn(
+ thread: &Entity<AcpThread>,
+ cx: &mut TestAppContext,
+ ) -> (
+ oneshot::Sender<Result<acp::PromptResponse>>,
+ BoxFuture<'static, Result<Option<acp::PromptResponse>>>,
+ ) {
+ let (complete, completion) = oneshot::channel::<Result<acp::PromptResponse>>();
+ let request = thread.update(cx, |thread, cx| {
+ thread.run_turn(cx, async move |_, _| completion.await?)
+ });
+ (complete, request)
+ }
+
+ fn request_test_permission(
+ thread: &Entity<AcpThread>,
+ tool_call_id: acp::ToolCallId,
+ cx: &mut TestAppContext,
+ ) -> Task<RequestPermissionOutcome> {
+ thread.update(cx, |thread, cx| {
+ thread
+ .request_tool_call_authorization(
+ acp::ToolCall::new(tool_call_id, "Needs permission").into(),
+ PermissionOptions::Flat(vec![
+ acp::PermissionOption::new(
+ acp::PermissionOptionId::new("allow"),
+ "Allow",
+ acp::PermissionOptionKind::AllowOnce,
+ ),
+ acp::PermissionOption::new(
+ acp::PermissionOptionId::new("reject"),
+ "Reject",
+ acp::PermissionOptionKind::RejectOnce,
+ ),
+ ]),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ .expect("permission request should succeed")
+ })
+ }
+
+ fn request_test_form_elicitation(
+ thread: &Entity<AcpThread>,
+ cx: &mut TestAppContext,
+ ) -> (ElicitationEntryId, Task<acp::CreateElicitationResponse>) {
+ thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation_with_id(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(thread.session_id().clone()),
+ acp::ElicitationSchema::new().string("name", false),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .expect("form elicitation should succeed")
+ })
+ }
+
+ fn set_prevent_idle_sleep(enabled: bool, cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |content| {
+ content.agent.get_or_insert_default().prevent_idle_sleep = Some(enabled);
+ });
+ });
+ });
+ }
+
+ async fn assert_stale_completion_does_not_affect_follow_up_turn(
+ backend_result: Result<acp::StopReason, &'static str>,
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ for drop_waiter in [false, true] {
+ let thread = new_test_thread(cx).await;
+ let (first_complete, first_request) = start_test_turn(&thread, cx);
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block(None, "first".into(), cx);
+ thread.push_assistant_content_block("first reply".into(), false, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ let first_request = if drop_waiter {
+ drop(first_request);
+ None
+ } else {
+ Some(first_request)
+ };
+ first_complete
+ .send(
+ backend_result
+ .map(acp::PromptResponse::new)
+ .map_err(|message| anyhow!(message)),
+ )
+ .expect("first backend should still be running");
+ let (second_complete, second_request) = start_test_turn(&thread, cx);
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block(None, "second".into(), cx);
+ thread.push_assistant_content_block("second reply".into(), false, cx);
+ assert_eq!(thread.running_turn.as_ref().map(|turn| turn.id), Some(2));
+ assert!(!thread.had_error());
+ });
+ let events = Rc::new(RefCell::new(Vec::new()));
+ let _subscription = cx.update(|cx| {
+ cx.subscribe(&thread, {
+ let events = events.clone();
+ move |_, event, _| {
+ let event = match event {
+ AcpThreadEvent::StatusChanged => "status changed",
+ AcpThreadEvent::EntriesRemoved(_) => "entries removed",
+ AcpThreadEvent::Stopped(_) => "stopped",
+ AcpThreadEvent::Refusal => "refusal",
+ AcpThreadEvent::Error => "error",
+ _ => return,
+ };
+ events.borrow_mut().push(event);
+ }
+ })
+ });
+ cx.run_until_parked();
+ if let Some(first_request) = first_request {
+ assert_eq!(
+ first_request
+ .await
+ .map(|response| response.map(|response| response.stop_reason))
+ .map_err(|error| error.to_string()),
+ backend_result.map(Some).map_err(String::from)
+ );
+ }
+
+ thread.read_with(cx, |thread, cx| {
+ assert_eq!(thread.entries().len(), 4);
+ assert_eq!(
+ thread.to_markdown(cx),
+ concat!(
+ "## User\n\nfirst\n\n",
+ "## Assistant\n\nfirst reply\n\n",
+ "## User\n\nsecond\n\n",
+ "## Assistant\n\nsecond reply\n\n",
+ )
+ );
+ assert!(!thread.had_error());
+ assert_eq!(thread.turn_id, 2);
+ assert_eq!(thread.running_turn.as_ref().map(|turn| turn.id), Some(2));
+ assert_eq!(thread.status(), ThreadStatus::Generating);
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+ assert_eq!(*events.borrow(), Vec::<&str>::new());
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+
+ second_complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("second backend should still be running");
+ second_request.await.expect("second turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
+ }
+
+ async fn assert_failed_tool_update_resumes_sleep_prevention(
+ upsert: bool,
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let (complete, request) = start_test_turn(&thread, cx);
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ let tool_call_id = acp::ToolCallId::new("permission");
+ let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
+ cx.run_until_parked();
+ assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+
+ thread.update(cx, |thread, cx| {
+ let update = acp::ToolCallUpdate::new(
+ tool_call_id.clone(),
+ acp::ToolCallUpdateFields::new()
+ .status(acp::ToolCallStatus::Completed)
+ .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
+ acp::TerminalId::new("unknown-terminal"),
+ ))]),
+ );
+ if upsert {
+ assert!(
+ thread
+ .upsert_tool_call_inner(update, ToolCallStatus::Completed, cx)
+ .is_err()
+ );
+ } else {
+ assert_eq!(
+ thread
+ .update_tool_call(update, cx)
+ .map_err(|error| error.to_string()),
+ Err(String::from(
+ "Terminal with id `unknown-terminal` not found"
+ ))
+ );
+ }
+ assert_eq!(
+ thread
+ .tool_call(&tool_call_id)
+ .expect("tool call should remain present")
+ .1
+ .status
+ .as_acp_status(),
+ Some(acp::ToolCallStatus::Completed)
+ );
+ assert!(!thread.is_waiting_for_confirmation());
+ });
+ assert!(matches!(
+ permission.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ cx.run_until_parked();
+ assert_eq!(cx.active_idle_sleep_preventions(), 1);
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.status(), ThreadStatus::Generating);
+ assert_eq!(thread.running_turn.as_ref().map(|turn| turn.id), Some(1));
+ assert!(!thread.had_error());
+ assert!(matches!(
+ thread.idle_sleep_prevention,
+ IdleSleepPrevention::Active { .. }
+ ));
+ });
+
+ complete
+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .expect("backend should still be running");
+ request.await.expect("turn should complete");
+ assert_eq!(cx.active_idle_sleep_preventions(), 0);
+ }
}
diff --git a/crates/agent/src/tool_permissions.rs b/crates/agent/src/tool_permissions.rs
index 601c24d73af..9be962547f8 100644
--- a/crates/agent/src/tool_permissions.rs
+++ b/crates/agent/src/tool_permissions.rs
@@ -590,6 +590,7 @@ mod tests {
profiles: Default::default(),
notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
play_sound_when_agent_done: PlaySoundWhenAgentDone::default(),
+ prevent_idle_sleep: true,
single_file_review: false,
model_parameters: vec![],
auto_compact: agent_settings::AutoCompactSettings {
diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs
index 875b8fef456..05e90208a69 100644
--- a/crates/agent_settings/src/agent_settings.rs
+++ b/crates/agent_settings/src/agent_settings.rs
@@ -227,6 +227,7 @@ pub struct AgentSettings {
pub notify_when_agent_waiting: NotifyWhenAgentWaiting,
pub play_sound_when_agent_done: PlaySoundWhenAgentDone,
+ pub prevent_idle_sleep: bool,
pub single_file_review: bool,
pub model_parameters: Vec<LanguageModelParameters>,
pub auto_compact: AutoCompactSettings,
@@ -792,6 +793,7 @@ impl Settings for AgentSettings {
notify_when_agent_waiting: agent.notify_when_agent_waiting.unwrap(),
play_sound_when_agent_done: agent.play_sound_when_agent_done.unwrap_or_default(),
+ prevent_idle_sleep: agent.prevent_idle_sleep.unwrap(),
single_file_review: agent.single_file_review.unwrap(),
model_parameters: agent.model_parameters,
auto_compact: {
@@ -1062,6 +1064,33 @@ mod tests {
assert!(result.is_none());
}
+ #[gpui::test]
+ fn test_prevent_idle_sleep_defaults_to_true_and_follows_user_settings(cx: &mut gpui::App) {
+ let store = SettingsStore::test(cx);
+ cx.set_global(store);
+ project::DisableAiSettings::register(cx);
+ AgentSettings::register(cx);
+ assert!(AgentSettings::get_global(cx).prevent_idle_sleep);
+
+ for (content, expected) in [
+ (r#"{"agent": {"prevent_idle_sleep": false}}"#, false),
+ (r#"{"agent": {"prevent_idle_sleep": true}}"#, true),
+ (r#"{"agent": {"prevent_idle_sleep": null}}"#, true),
+ (r#"{"agent": {}}"#, true),
+ ] {
+ SettingsStore::update_global(cx, |store, cx| {
+ store
+ .set_user_settings(content, cx)
+ .expect("user settings should load");
+ });
+ assert_eq!(
+ AgentSettings::get_global(cx).prevent_idle_sleep,
+ expected,
+ "{content}"
+ );
+ }
+ }
+
#[gpui::test]
fn test_terminal_init_command_filters_empty_without_trimming(cx: &mut gpui::App) {
let store = SettingsStore::test(cx);
diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rs
index 30900097e93..28fc3c7c624 100644
--- a/crates/agent_ui/src/agent_ui.rs
+++ b/crates/agent_ui/src/agent_ui.rs
@@ -992,6 +992,7 @@ mod tests {
profiles: Default::default(),
notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
play_sound_when_agent_done: PlaySoundWhenAgentDone::Never,
+ prevent_idle_sleep: true,
single_file_review: false,
model_parameters: vec![],
auto_compact: agent_settings::AutoCompactSettings {
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 668b8c9f5c2..8f71b9c5c38 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -41,11 +41,11 @@ pub use visual_test_context::*;
use crate::InspectorElementRegistry;
use crate::asset_cache::CachedLoad;
use crate::{
- Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
- ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError,
- CursorStyle, DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
- FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
- Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
+ Action, ActionBuildError, ActionRegistry, ActivityGuard, Any, AnyView, AnyWindowHandle,
+ AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem,
+ ClipboardReadError, CursorStyle, DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload,
+ FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke,
+ LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
@@ -1350,6 +1350,11 @@ impl App {
self.platform.thermal_state()
}
+ /// Prevents idle sleep while the returned guard is held.
+ pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ self.platform.prevent_idle_sleep(reason)
+ }
+
/// Invokes a handler when the thermal state changes
pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
where
diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs
index a34a7790072..b062ddf65a6 100644
--- a/crates/gpui/src/app/test_context.rs
+++ b/crates/gpui/src/app/test_context.rs
@@ -169,6 +169,21 @@ impl TestAppContext {
self.test_platform.did_prompt_for_new_path()
}
+ /// Returns the number of active idle sleep prevention tokens.
+ pub fn active_idle_sleep_preventions(&self) -> usize {
+ self.test_platform.active_idle_sleep_preventions()
+ }
+
+ /// Sets the delay for subsequent idle sleep prevention acquisitions.
+ pub fn set_idle_sleep_prevention_delay(&self, delay: Duration) {
+ self.test_platform.set_idle_sleep_prevention_delay(delay);
+ }
+
+ /// Makes subsequent idle sleep prevention acquisitions fail or succeed.
+ pub fn set_idle_sleep_prevention_fails(&self, fails: bool) {
+ self.test_platform.set_idle_sleep_prevention_fails(fails);
+ }
+
/// returns a new `TestAppContext` re-using the same executors to interleave tasks.
pub fn new_app(&self) -> TestAppContext {
Self::build(self.dispatcher.clone(), self.fn_name)
diff --git a/crates/gpui/src/executor.rs b/crates/gpui/src/executor.rs
index 444bb071806..513119520df 100644
--- a/crates/gpui/src/executor.rs
+++ b/crates/gpui/src/executor.rs
@@ -1,4 +1,4 @@
-use crate::{App, PlatformDispatcher, PlatformScheduler};
+use crate::{ActivityGuard, App, PlatformDispatcher, PlatformScheduler};
#[cfg(not(target_family = "wasm"))]
use futures::channel::mpsc;
use futures::prelude::*;
@@ -91,6 +91,13 @@ impl BackgroundExecutor {
self.inner.clone()
}
+ /// Prevents App Nap-style throttling while the returned guard is held.
+ ///
+ /// This does not prevent the system from entering idle sleep.
+ pub fn prevent_app_nap(&self, reason: &str) -> ActivityGuard {
+ self.dispatcher.prevent_app_nap(reason)
+ }
+
/// Spawn a closure on a fresh session pinned to its own [`SchedulerLocalExecutor`].
/// The closure runs on a new OS thread under the platform scheduler, or on
/// the test scheduler's loop in tests.
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 14f1f028759..aff37c0981f 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -90,6 +90,25 @@ pub use threaded_dispatcher::ThreadedDispatcher;
#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
pub use visual_test::VisualTestPlatform;
+/// Keeps an operating system activity, such as an idle sleep inhibitor, alive until dropped.
+pub struct ActivityGuard {
+ _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
+}
+
+impl ActivityGuard {
+ /// Runs `release` when the guard is dropped.
+ pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
+ Self {
+ _release: gpui_util::defer(Box::new(release)),
+ }
+ }
+
+ /// A guard for platforms without a corresponding activity.
+ pub fn noop() -> Self {
+ Self::new(|| {})
+ }
+}
+
// TODO(jk): return an enum instead of a string
/// Return which compositor we're guessing we'll use.
/// Does not attempt to connect to the given compositor.
@@ -249,6 +268,7 @@ pub trait Platform: 'static {
fn thermal_state(&self) -> ThermalState;
fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
/// Sets the application's process-wide identity and user-visible name.
///
@@ -1065,6 +1085,10 @@ pub trait PlatformDispatcher: Send + Sync {
gpui_util::defer(Box::new(|| {}))
}
+ fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
+ ActivityGuard::noop()
+ }
+
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
fn as_test(&self) -> Option<&TestDispatcher> {
None
diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rs
index df1d0f4d131..21422e16f9c 100644
--- a/crates/gpui/src/platform/test/platform.rs
+++ b/crates/gpui/src/platform/test/platform.rs
@@ -3,7 +3,7 @@ use crate::NoopTextSystem;
#[cfg(any(test, feature = "test-support"))]
use crate::PathPromptOptions;
use crate::{
- AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
+ ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
DummyKeyboardMapper, ForegroundExecutor, Keymap, OwnedMenu, Platform, PlatformDisplay,
PlatformHeadlessRenderer, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream, SharedString,
@@ -16,10 +16,14 @@ use collections::VecDeque;
use futures::channel::oneshot;
use parking_lot::Mutex;
use std::{
- cell::RefCell,
+ cell::{Cell, RefCell},
path::{Path, PathBuf},
rc::{Rc, Weak},
- sync::Arc,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ time::Duration,
};
/// TestPlatform implements the Platform trait for use in tests.
@@ -43,6 +47,9 @@ pub(crate) struct TestPlatform {
pub text_system: Arc<dyn PlatformTextSystem>,
pub expect_restart:
RefCell<Option<oneshot::Sender<(Option<PathBuf>, Vec<std::ffi::OsString>)>>>,
+ idle_sleep_prevention_count: Arc<AtomicUsize>,
+ idle_sleep_prevention_delay: Cell<Duration>,
+ idle_sleep_prevention_fails: Cell<bool>,
headless_renderer_factory: Option<Box<dyn Fn() -> Option<Box<dyn PlatformHeadlessRenderer>>>>,
weak: Weak<Self>,
menus: RefCell<Vec<OwnedMenu>>,
@@ -155,6 +162,9 @@ impl TestPlatform {
current_primary_item: Mutex::new(None),
#[cfg(target_os = "macos")]
current_find_pasteboard_item: Mutex::new(None),
+ idle_sleep_prevention_count: Arc::new(AtomicUsize::new(0)),
+ idle_sleep_prevention_delay: Cell::new(Duration::ZERO),
+ idle_sleep_prevention_fails: Cell::new(false),
weak: weak.clone(),
opened_url: Default::default(),
system_notifications: Default::default(),
@@ -308,6 +318,21 @@ impl TestPlatform {
!self.prompts.borrow().new_path.is_empty()
}
+ #[cfg(any(test, feature = "test-support"))]
+ pub(crate) fn active_idle_sleep_preventions(&self) -> usize {
+ self.idle_sleep_prevention_count.load(Ordering::SeqCst)
+ }
+
+ #[cfg(any(test, feature = "test-support"))]
+ pub(crate) fn set_idle_sleep_prevention_delay(&self, delay: Duration) {
+ self.idle_sleep_prevention_delay.set(delay);
+ }
+
+ #[cfg(any(test, feature = "test-support"))]
+ pub(crate) fn set_idle_sleep_prevention_fails(&self, fails: bool) {
+ self.idle_sleep_prevention_fails.set(fails);
+ }
+
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn app_identity(&self) -> Option<(SharedString, SharedString)> {
self.system_notifications.borrow().app_identity.clone()
@@ -377,6 +402,32 @@ impl Platform for TestPlatform {
ThermalState::Nominal
}
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ let count = self.idle_sleep_prevention_count.clone();
+ let fails = self.idle_sleep_prevention_fails.get();
+ let reason = reason.to_owned();
+ let acquire = move || {
+ if fails {
+ anyhow::bail!("Idle sleep prevention for {reason:?} is set to fail in this test");
+ }
+ count.fetch_add(1, Ordering::SeqCst);
+ Ok(ActivityGuard::new(move || {
+ count.fetch_sub(1, Ordering::SeqCst);
+ }))
+ };
+
+ let delay = self.idle_sleep_prevention_delay.get();
+ if delay.is_zero() {
+ Task::ready(acquire())
+ } else {
+ let delay = self.background_executor.timer(delay);
+ self.foreground_executor.spawn(async move {
+ delay.await;
+ acquire()
+ })
+ }
+ }
+
fn run(&self, _on_finish_launching: Box<dyn FnOnce()>) {
unimplemented!()
}
diff --git a/crates/gpui/src/platform/visual_test.rs b/crates/gpui/src/platform/visual_test.rs
index 042a757f22f..2db3e34db8f 100644
--- a/crates/gpui/src/platform/visual_test.rs
+++ b/crates/gpui/src/platform/visual_test.rs
@@ -7,10 +7,10 @@
use crate::ScreenCaptureSource;
use crate::{
- AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor, Keymap,
- Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform, PlatformDisplay,
- PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, PlatformWindow, Task,
- TestDispatcher, WindowAppearance, WindowParams,
+ ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
+ ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,
+ PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
+ PlatformWindow, Task, TestDispatcher, WindowAppearance, WindowParams,
};
use anyhow::Result;
use futures::channel::oneshot;
@@ -261,4 +261,10 @@ impl Platform for VisualTestPlatform {
}
fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
+
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ Task::ready(Err(anyhow::anyhow!(
+ "Idle sleep prevention for {reason:?} is not supported in visual tests"
+ )))
+ }
}
diff --git a/crates/gpui_linux/Cargo.toml b/crates/gpui_linux/Cargo.toml
index 583ad389721..ecc9ceb5a4b 100644
--- a/crates/gpui_linux/Cargo.toml
+++ b/crates/gpui_linux/Cargo.toml
@@ -129,5 +129,8 @@ xim = { git = "https://github.com/zed-industries/xim-rs.git", rev = "16f35a2c881
], package = "zed-xim", version = "0.4.0-zed", optional = true }
x11-clipboard = { version = "0.9.3", optional = true }
+[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dev-dependencies]
+gpui = { workspace = true, features = ["test-support"] }
+
[package.metadata.cargo-shear]
ignored = ["bitflags", "scap", "x11-clipboard"]
diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs
index 53dec5dca99..f2184543e70 100644
--- a/crates/gpui_linux/src/linux/platform.rs
+++ b/crates/gpui_linux/src/linux/platform.rs
@@ -16,6 +16,14 @@ use std::{
#[cfg(any(feature = "wayland", feature = "x11"))]
use anyhow::ensure;
use anyhow::{Context as _, anyhow};
+#[cfg(any(feature = "wayland", feature = "x11"))]
+use ashpd::{
+ desktop::{
+ Request,
+ inhibit::{InhibitFlags, InhibitOptions, InhibitProxy},
+ },
+ enumflags2::BitFlags,
+};
use calloop::{LoopSignal, channel::Sender};
use futures::channel::oneshot;
use gpui_util::{ResultExt as _, new_std_command};
@@ -24,8 +32,8 @@ use xkbcommon::xkb::{self, Keycode, Keysym, State};
use crate::linux::{LinuxDispatcher, PriorityQueueCalloopReceiver};
use gpui::{
- Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
- ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,
+ Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
+ DisplayId, ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,
PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
PlatformWindow, Result, RunnableVariant, Task, ThermalState, WindowAppearance,
WindowButtonLayout, WindowParams,
@@ -264,6 +272,33 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
ThermalState::Nominal
}
+ #[cfg(not(any(feature = "wayland", feature = "x11")))]
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ Task::ready(Err(anyhow!(
+ "Idle sleep prevention for {reason:?} requires a Linux windowing backend"
+ )))
+ }
+
+ #[cfg(any(feature = "wayland", feature = "x11"))]
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ let executor = self.background_executor();
+ let (guard_tx, guard_rx) = oneshot::channel();
+ executor
+ .spawn({
+ let executor = executor.clone();
+ let reason = reason.to_owned();
+ async move {
+ guard_tx
+ .send(inhibit_idle_sleep(reason, executor).await)
+ .ok();
+ }
+ })
+ .detach();
+ executor
+ .clone()
+ .spawn(async move { await_idle_sleep_prevention(guard_rx, &executor).await })
+ }
+
fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
on_finish_launching();
@@ -1258,6 +1293,56 @@ pub(super) fn compositor_gpu_hint_from_dev_t(dev: u64) -> Option<gpui_wgpu::Comp
})
}
+#[cfg(any(feature = "wayland", feature = "x11"))]
+async fn inhibit_idle_sleep(reason: String, executor: BackgroundExecutor) -> Result<ActivityGuard> {
+ let proxy = InhibitProxy::new()
+ .await
+ .context("Idle sleep prevention portal is unavailable")?;
+ let request = proxy
+ .inhibit(
+ None,
+ BitFlags::from(InhibitFlags::Suspend),
+ InhibitOptions::default().set_reason(reason.as_str()),
+ )
+ .await
+ .context("Failed to request idle sleep prevention")?;
+ request
+ .response()
+ .context("Idle sleep prevention request was rejected")?;
+ Ok(release_on_drop(request, executor))
+}
+
+#[cfg(any(feature = "wayland", feature = "x11"))]
+fn release_on_drop(request: Request<()>, executor: BackgroundExecutor) -> ActivityGuard {
+ ActivityGuard::new(move || {
+ executor
+ .spawn(async move {
+ request
+ .close()
+ .await
+ .context("Failed to release idle sleep prevention")
+ .log_err();
+ })
+ .detach();
+ })
+}
+
+#[cfg(any(feature = "wayland", feature = "x11"))]
+async fn await_idle_sleep_prevention(
+ guard_rx: oneshot::Receiver<Result<ActivityGuard>>,
+ executor: &BackgroundExecutor,
+) -> Result<ActivityGuard> {
+ match futures::future::select(guard_rx, executor.timer(Duration::from_secs(10))).await {
+ futures::future::Either::Left((Ok(result), _)) => result,
+ futures::future::Either::Left((Err(_), _)) => {
+ Err(anyhow!("Idle sleep prevention request was abandoned"))
+ }
+ futures::future::Either::Right(_) => Err(anyhow!(
+ "Idle sleep prevention acquisition timed out after 10 seconds"
+ )),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1298,6 +1383,98 @@ mod tests {
),);
}
+ #[cfg(any(feature = "wayland", feature = "x11"))]
+ mod idle_sleep_prevention {
+ use super::super::await_idle_sleep_prevention;
+ use anyhow::{Result, anyhow};
+ use futures::channel::oneshot;
+ use gpui::{ActivityGuard, TestAppContext};
+ use std::{
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering::SeqCst},
+ },
+ time::Duration,
+ };
+
+ #[gpui::test]
+ async fn guard_passes_through_and_releases_on_drop(cx: &mut TestAppContext) {
+ let released = Arc::new(AtomicUsize::new(0));
+ let (guard_tx, guard_rx) = oneshot::channel();
+ assert!(guard_tx.send(Ok(release_guard(released.clone()))).is_ok());
+ let guard = await_idle_sleep_prevention(guard_rx, &cx.background_executor)
+ .await
+ .expect("acquisition should succeed");
+
+ assert_eq!(released.load(SeqCst), 0);
+ drop(guard);
+ assert_eq!(released.load(SeqCst), 1);
+ }
+
+ #[gpui::test]
+ async fn acquisition_error_passes_through(cx: &mut TestAppContext) {
+ let (guard_tx, guard_rx) = oneshot::channel::<Result<ActivityGuard>>();
+ assert!(guard_tx.send(Err(anyhow!("inhibition rejected"))).is_ok());
+ assert_eq!(
+ await_idle_sleep_prevention(guard_rx, &cx.background_executor)
+ .await
+ .err()
+ .expect("acquisition should fail")
+ .to_string(),
+ "inhibition rejected"
+ );
+ }
+
+ #[gpui::test]
+ async fn abandoned_acquisition_is_an_error(cx: &mut TestAppContext) {
+ let (guard_tx, guard_rx) = oneshot::channel::<Result<ActivityGuard>>();
+ drop(guard_tx);
+ assert_eq!(
+ await_idle_sleep_prevention(guard_rx, &cx.background_executor)
+ .await
+ .err()
+ .expect("acquisition should fail")
+ .to_string(),
+ "Idle sleep prevention request was abandoned"
+ );
+ }
+
+ #[gpui::test]
+ async fn late_guard_after_timeout_is_released(cx: &mut TestAppContext) {
+ let released = Arc::new(AtomicUsize::new(0));
+ let (guard_tx, guard_rx) = oneshot::channel();
+ let task = cx.background_executor.spawn({
+ let executor = cx.background_executor.clone();
+ async move { await_idle_sleep_prevention(guard_rx, &executor).await }
+ });
+ cx.run_until_parked();
+ cx.executor().advance_clock(Duration::from_secs(9));
+ cx.run_until_parked();
+ assert!(!guard_tx.is_canceled());
+ cx.executor().advance_clock(Duration::from_secs(1));
+ assert_eq!(
+ task.await
+ .err()
+ .expect("acquisition should time out")
+ .to_string(),
+ "Idle sleep prevention acquisition timed out after 10 seconds"
+ );
+
+ assert!(guard_tx.is_canceled());
+ if let Err(Ok(guard)) = guard_tx.send(Ok(release_guard(released.clone()))) {
+ assert_eq!(released.load(SeqCst), 0);
+ drop(guard);
+ }
+ assert_eq!(released.load(SeqCst), 1);
+ }
+
+ fn release_guard(released: Arc<AtomicUsize>) -> ActivityGuard {
+ ActivityGuard::new(move || {
+ released.fetch_add(1, SeqCst);
+ })
+ }
+ }
+
#[cfg(any(feature = "wayland", feature = "x11"))]
mod read_fd_with_timeout {
use super::super::{PIPE_READ_TIMEOUT, read_fd_with_timeout};
diff --git a/crates/gpui_macos/src/dispatcher.rs b/crates/gpui_macos/src/dispatcher.rs
index 0e5ebdcaf3b..a50288cd647 100644
--- a/crates/gpui_macos/src/dispatcher.rs
+++ b/crates/gpui_macos/src/dispatcher.rs
@@ -1,5 +1,5 @@
use dispatch2::{DispatchQueue, DispatchQueueGlobalPriority, DispatchTime, GlobalQueueIdentifier};
-use gpui::{PlatformDispatcher, Priority, RunnableMeta, RunnableVariant};
+use gpui::{ActivityGuard, PlatformDispatcher, Priority, RunnableMeta, RunnableVariant};
use gpui_util::ResultExt;
use mach2::{
kern_return::KERN_SUCCESS,
@@ -18,6 +18,8 @@ use objc::{
runtime::{BOOL, YES},
sel, sel_impl,
};
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::{NSActivityOptions, NSObjectProtocol, NSProcessInfo, NSString};
use std::{ffi::c_void, ptr::NonNull, time::Duration};
pub(crate) struct MacDispatcher;
@@ -76,6 +78,36 @@ impl PlatformDispatcher for MacDispatcher {
f();
});
}
+
+ fn prevent_app_nap(&self, reason: &str) -> ActivityGuard {
+ MacActivity::begin(
+ reason,
+ NSActivityOptions::UserInitiatedAllowingIdleSystemSleep,
+ )
+ }
+}
+
+pub(crate) struct MacActivity {
+ activity: Retained<ProtocolObject<dyn NSObjectProtocol>>,
+}
+
+// The activity token returned by NSProcessInfo is thread-safe
+unsafe impl Send for MacActivity {}
+
+impl MacActivity {
+ pub(crate) fn begin(reason: &str, options: NSActivityOptions) -> ActivityGuard {
+ let activity = Self {
+ activity: NSProcessInfo::processInfo()
+ .beginActivityWithOptions_reason(options, &NSString::from_str(reason)),
+ };
+ ActivityGuard::new(move || drop(activity))
+ }
+}
+
+impl Drop for MacActivity {
+ fn drop(&mut self) {
+ unsafe { NSProcessInfo::processInfo().endActivity(&self.activity) };
+ }
}
fn set_audio_thread_priority() -> anyhow::Result<()> {
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index c6f75a85bbb..3a28477635d 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -1,6 +1,6 @@
use crate::{
- BoolExt, MacDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow,
- events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
+ BoolExt, MacActivity, MacDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper,
+ MacWindow, events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
set_active_window_cursor_style,
};
use anyhow::{Context as _, anyhow};
@@ -29,9 +29,9 @@ use ctor::ctor;
use dispatch2::DispatchQueue;
use futures::channel::oneshot;
use gpui::{
- Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
- KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
- PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
+ Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
+ ForegroundExecutor, KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions,
+ Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowKind,
WindowParams, popup::PopupNotSupportedError,
};
@@ -45,6 +45,7 @@ use objc::{
sel, sel_impl,
};
use objc2::MainThreadMarker;
+use objc2_foundation::NSActivityOptions;
use parking_lot::Mutex;
use ptr::null_mut;
use semver::Version;
@@ -1005,6 +1006,13 @@ impl Platform for MacPlatform {
}
}
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ Task::ready(Ok(MacActivity::begin(
+ reason,
+ NSActivityOptions::UserInitiated,
+ )))
+ }
+
fn show_system_notification(&self, notification: gpui::SystemNotification) {
let mut state = self.0.lock();
let executor = state.foreground_executor.clone();
diff --git a/crates/gpui_web/src/platform.rs b/crates/gpui_web/src/platform.rs
index af8cc8584d6..c527e4cbd27 100644
--- a/crates/gpui_web/src/platform.rs
+++ b/crates/gpui_web/src/platform.rs
@@ -7,12 +7,12 @@ use crate::window::WebWindow;
use anyhow::Result;
use futures::channel::oneshot;
use gpui::{
- Action, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem, ClipboardReadError,
- ClipboardString, CursorStyle, DummyKeyboardMapper, ForegroundExecutor, GestureTuning, Image,
- ImageFormat, Keymap, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay,
- PlatformGestures, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
- PlatformWindow, ScrollPhysics, Task, ThermalState, WindowAppearance, WindowKind, WindowParams,
- popup::PopupNotSupportedError,
+ Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem,
+ ClipboardReadError, ClipboardString, CursorStyle, DummyKeyboardMapper, ForegroundExecutor,
+ GestureTuning, Image, ImageFormat, Keymap, Menu, MenuItem, PathPromptOptions, Platform,
+ PlatformDisplay, PlatformGestures, PlatformKeyboardLayout, PlatformKeyboardMapper,
+ PlatformTextSystem, PlatformWindow, ScrollPhysics, Task, ThermalState, WindowAppearance,
+ WindowKind, WindowParams, popup::PopupNotSupportedError,
};
use gpui_wgpu::{PreparedWebGraphics, WebBackendPreference, WgpuContext, wgpu};
use std::{
@@ -519,6 +519,12 @@ impl Platform for WebPlatform {
self.callbacks.borrow_mut().thermal_state_change = Some(callback);
}
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ Task::ready(Err(anyhow::anyhow!(
+ "Idle sleep prevention for {reason:?} is not supported in the browser"
+ )))
+ }
+
fn compositor_name(&self) -> &'static str {
"Web"
}
diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs
index d0ae3c764fe..c8b4c92356b 100644
--- a/crates/gpui_windows/src/platform.rs
+++ b/crates/gpui_windows/src/platform.rs
@@ -22,7 +22,15 @@ use windows::{
Foundation::*,
Graphics::{Direct3D11::ID3D11Device, Gdi::*},
Security::Credentials::*,
- System::{Com::*, LibraryLoader::*, Ole::*, Power::*, SystemInformation::*},
+ System::{
+ Com::*,
+ LibraryLoader::*,
+ Ole::*,
+ Power::*,
+ SystemInformation::*,
+ SystemServices::POWER_REQUEST_CONTEXT_VERSION,
+ Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, REASON_CONTEXT_0},
+ },
UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
},
core::*,
@@ -106,6 +114,45 @@ impl WindowsPlatformState {
}
}
+struct PowerRequest {
+ handle: HANDLE,
+}
+
+unsafe impl Send for PowerRequest {}
+
+impl PowerRequest {
+ fn prevent_idle_sleep(reason: &str) -> Result<Self> {
+ let mut reason = reason.encode_utf16().chain([0]).collect::<Vec<_>>();
+ let context = REASON_CONTEXT {
+ Version: POWER_REQUEST_CONTEXT_VERSION,
+ Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
+ Reason: REASON_CONTEXT_0 {
+ SimpleReasonString: PWSTR(reason.as_mut_ptr()),
+ },
+ };
+ let handle = unsafe { PowerCreateRequest(&context) }
+ .context("Failed to create a Windows power request")?;
+ if let Err(error) = unsafe { PowerSetRequest(handle, PowerRequestSystemRequired) } {
+ unsafe { CloseHandle(handle) }
+ .context("Failed to close the Windows power request")
+ .log_err();
+ return Err(error).context("Failed to set the Windows power request");
+ }
+ Ok(Self { handle })
+ }
+}
+
+impl Drop for PowerRequest {
+ fn drop(&mut self) {
+ unsafe { PowerClearRequest(self.handle, PowerRequestSystemRequired) }
+ .context("Failed to clear the Windows power request")
+ .log_err();
+ unsafe { CloseHandle(self.handle) }
+ .context("Failed to close the Windows power request")
+ .log_err();
+ }
+}
+
impl WindowsPlatform {
pub fn new(headless: bool) -> Result<Self> {
unsafe {
@@ -444,6 +491,13 @@ impl Platform for WindowsPlatform {
ThermalState::Nominal
}
+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
+ Task::ready(
+ PowerRequest::prevent_idle_sleep(reason)
+ .map(|request| ActivityGuard::new(move || drop(request))),
+ )
+ }
+
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
on_finish_launching();
if !self.headless {
diff --git a/crates/livekit_client/Cargo.toml b/crates/livekit_client/Cargo.toml
index ab4b8411a62..3aa30a7e85e 100644
--- a/crates/livekit_client/Cargo.toml
+++ b/crates/livekit_client/Cargo.toml
@@ -55,11 +55,9 @@ webrtc-sys.workspace = true
scap.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
-cocoa.workspace = true
core-foundation.workspace = true
core-video.workspace = true
coreaudio-rs = "0.12.1"
-objc.workspace = true
[dev-dependencies]
collections = { workspace = true, features = ["test-support"] }
diff --git a/crates/livekit_client/src/livekit_client/playback.rs b/crates/livekit_client/src/livekit_client/playback.rs
index f00b64768e7..1febcd4e868 100644
--- a/crates/livekit_client/src/livekit_client/playback.rs
+++ b/crates/livekit_client/src/livekit_client/playback.rs
@@ -232,10 +232,7 @@ impl AudioStack {
_num_channels: u32,
output_audio_device: Option<DeviceId>,
) -> Result<()> {
- // Prevent App Nap from throttling audio playback on macOS.
- // This guard is held for the entire duration of audio output.
- #[cfg(target_os = "macos")]
- let _prevent_app_nap = PreventAppNapGuard::new();
+ let _app_nap_guard = executor.prevent_app_nap("Audio playback in progress");
loop {
let mut device_change_listener = DeviceChangeListener::new(false)?;
@@ -828,10 +825,6 @@ trait DeviceChangeListenerApi: Stream<Item = ()> + Sized {
#[cfg(target_os = "macos")]
mod macos {
- use cocoa::{
- base::{id, nil},
- foundation::{NSProcessInfo, NSString},
- };
use coreaudio::sys::{
AudioObjectAddPropertyListener, AudioObjectID, AudioObjectPropertyAddress,
AudioObjectRemovePropertyListener, OSStatus, kAudioHardwarePropertyDefaultInputDevice,
@@ -839,52 +832,6 @@ mod macos {
kAudioObjectPropertyScopeGlobal, kAudioObjectSystemObject,
};
use futures::{StreamExt, channel::mpsc::UnboundedReceiver};
- use objc::{msg_send, sel, sel_impl};
-
- /// A guard that prevents App Nap while held.
- ///
- /// On macOS, App Nap can throttle background apps to save power. This can cause
- /// audio artifacts when the app is not in the foreground. This guard tells macOS
- /// that we're doing latency-sensitive work and should not be throttled.
- ///
- /// See Apple's documentation on prioritizing work at the app level:
- /// https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/PrioritizeWorkAtTheAppLevel.html
- pub struct PreventAppNapGuard {
- activity: id,
- }
-
- // The activity token returned by NSProcessInfo is thread-safe
- unsafe impl Send for PreventAppNapGuard {}
-
- // From NSProcessInfo.h
- const NS_ACTIVITY_IDLE_SYSTEM_SLEEP_DISABLED: u64 = 1 << 20;
- const NS_ACTIVITY_USER_INITIATED: u64 = 0x00FFFFFF | NS_ACTIVITY_IDLE_SYSTEM_SLEEP_DISABLED;
- const NS_ACTIVITY_USER_INITIATED_ALLOWING_IDLE_SYSTEM_SLEEP: u64 =
- NS_ACTIVITY_USER_INITIATED & !NS_ACTIVITY_IDLE_SYSTEM_SLEEP_DISABLED;
-
- impl PreventAppNapGuard {
- pub fn new() -> Self {
- unsafe {
- let process_info = NSProcessInfo::processInfo(nil);
- #[allow(clippy::disallowed_methods)]
- let reason = NSString::alloc(nil).init_str("Audio playback in progress");
- let activity: id = msg_send![process_info, beginActivityWithOptions:NS_ACTIVITY_USER_INITIATED_ALLOWING_IDLE_SYSTEM_SLEEP reason:reason];
- let _: () = msg_send![reason, release];
- let _: () = msg_send![activity, retain];
- Self { activity }
- }
- }
- }
-
- impl Drop for PreventAppNapGuard {
- fn drop(&mut self) {
- unsafe {
- let process_info = NSProcessInfo::processInfo(nil);
- let _: () = msg_send![process_info, endActivity:self.activity];
- let _: () = msg_send![self.activity, release];
- }
- }
- }
/// Implementation from: https://github.com/zed-industries/cpal/blob/fd8bc2fd39f1f5fdee5a0690656caff9a26d9d50/src/host/coreaudio/macos/property_listener.rs#L15
pub struct CoreAudioDefaultDeviceChangeListener {
@@ -1065,8 +1012,6 @@ mod macos {
#[cfg(target_os = "macos")]
type DeviceChangeListener = macos::CoreAudioDefaultDeviceChangeListener;
-#[cfg(target_os = "macos")]
-use macos::PreventAppNapGuard;
#[cfg(not(target_os = "macos"))]
mod noop_change_listener {
diff --git a/crates/settings_content/src/agent.rs b/crates/settings_content/src/agent.rs
index 107c19b55bd..61e189244b6 100644
--- a/crates/settings_content/src/agent.rs
+++ b/crates/settings_content/src/agent.rs
@@ -279,6 +279,10 @@ pub struct AgentSettingsContent {
///
/// Default: never
pub play_sound_when_agent_done: Option<PlaySoundWhenAgentDone>,
+ /// Whether to keep the system awake while agent threads are running.
+ ///
+ /// Default: true
+ pub prevent_idle_sleep: Option<bool>,
/// Whether to display agent edits in single-file editors in addition to the review multibuffer pane.
///
/// Default: false
diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs
index da860a884a6..1f76abe448a 100644
--- a/crates/settings_ui/src/page_data.rs
+++ b/crates/settings_ui/src/page_data.rs
@@ -8806,6 +8806,25 @@ fn ai_page(cx: &App) -> SettingsPage {
metadata: None,
files: USER,
}),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "Prevent Idle Sleep",
+ description: "Whether to keep the system awake while agent threads are running.",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("agent.prevent_idle_sleep"),
+ pick: |settings_content| {
+ settings_content.agent.as_ref()?.prevent_idle_sleep.as_ref()
+ },
+ write: |settings_content, value, _| {
+ settings_content
+ .agent
+ .get_or_insert_default()
+ .prevent_idle_sleep = value;
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Expand Edit Card",
description: "Whether to have edit cards in the agent panel expanded, showing a Preview of the diff.",
diff --git a/docs/src/ai/agent-panel.md b/docs/src/ai/agent-panel.md
index d659523f59a..b284954f5f1 100644
--- a/docs/src/ai/agent-panel.md
+++ b/docs/src/ai/agent-panel.md
@@ -103,6 +103,14 @@ Your editor will jump to each file the agent touches.
You can also hold `cmd`/`ctrl` when submitting a message to automatically follow.
+### Keeping the System Awake {#prevent-idle-sleep}
+
+While an agent thread is running, Zed asks the operating system not to idle-sleep, so long-running turns are not interrupted when you step away.
+The display can still turn off and the screen can still lock; only system sleep is held back, and only while a thread is generating, not while it waits for your confirmation.
+
+Turn this off with the `agent.prevent_idle_sleep` setting.
+If the operating system rejects the request, Zed logs the reason and continues without it.
+
### Get Notified {#get-notified}
If you send a prompt to the Agent and then put Zed in the background, you can choose to be notified when its generation wraps up via:
diff --git a/docs/src/reference/all-settings.md b/docs/src/reference/all-settings.md
index 016de7031d3..e584dd64142 100644
--- a/docs/src/reference/all-settings.md
+++ b/docs/src/reference/all-settings.md
@@ -5808,6 +5808,16 @@ Available variables:
Visit [AI Quick Start](../ai/quick-start.md) under the AI section to learn more about AI setup.
+### Prevent Idle Sleep
+
+- Description: Whether to keep the system from idle-sleeping while an agent thread is running. See [Keeping the System Awake](../ai/agent-panel.md#prevent-idle-sleep).
+- Setting: `agent.prevent_idle_sleep`
+- Default: `true`
+
+**Options**
+
+`boolean` values
+
## Collaboration Panel
- Description: Customizations for the collaboration panel.