1use futures::channel::oneshot;
2use futures::{FutureExt, select_biased};
3use gpui::{App, Context, Global, Subscription, Task, Window};
4use std::cell::RefCell;
5use std::rc::Rc;
6use std::sync::LazyLock;
7use std::time::Duration;
8use std::{future::Future, pin::Pin, task::Poll};
9
10#[derive(Default)]
11struct FeatureFlags {
12 flags: Vec<String>,
13 staff: bool,
14}
15
16pub static ZED_DISABLE_STAFF: LazyLock<bool> = LazyLock::new(|| {
17 std::env::var("ZED_DISABLE_STAFF").is_ok_and(|value| !value.is_empty() && value != "0")
18});
19
20impl FeatureFlags {
21 fn has_flag<T: FeatureFlag>(&self) -> bool {
22 if T::enabled_for_all() {
23 return true;
24 }
25
26 if self.staff && T::enabled_for_staff() {
27 return true;
28 }
29
30 self.flags.iter().any(|f| f.as_str() == T::NAME)
31 }
32}
33
34impl Global for FeatureFlags {}
35
36/// To create a feature flag, implement this trait on a trivial type and use it as
37/// a generic parameter when called [`FeatureFlagAppExt::has_flag`].
38///
39/// Feature flags are enabled for members of Zed staff by default. To disable this behavior
40/// so you can test flags being disabled, set ZED_DISABLE_STAFF=1 in your environment,
41/// which will force Zed to treat the current user as non-staff.
42pub trait FeatureFlag {
43 const NAME: &'static str;
44
45 /// Returns whether this feature flag is enabled for Zed staff.
46 fn enabled_for_staff() -> bool {
47 true
48 }
49
50 /// Returns whether this feature flag is enabled for everyone.
51 ///
52 /// This is generally done on the server, but we provide this as a way to entirely enable a feature flag client-side
53 /// without needing to remove all of the call sites.
54 fn enabled_for_all() -> bool {
55 false
56 }
57}
58
59pub struct PredictEditsRateCompletionsFeatureFlag;
60impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
61 const NAME: &'static str = "predict-edits-rate-completions";
62}
63
64pub struct LlmClosedBetaFeatureFlag {}
65impl FeatureFlag for LlmClosedBetaFeatureFlag {
66 const NAME: &'static str = "llm-closed-beta";
67}
68
69pub struct NotebookFeatureFlag;
70
71impl FeatureFlag for NotebookFeatureFlag {
72 const NAME: &'static str = "notebooks";
73}
74
75pub struct PanicFeatureFlag;
76
77impl FeatureFlag for PanicFeatureFlag {
78 const NAME: &'static str = "panic";
79}
80
81pub struct JjUiFeatureFlag {}
82
83impl FeatureFlag for JjUiFeatureFlag {
84 const NAME: &'static str = "jj-ui";
85}
86
87pub struct GeminiAndNativeFeatureFlag;
88
89impl FeatureFlag for GeminiAndNativeFeatureFlag {
90 // This was previously called "acp".
91 //
92 // We renamed it because existing builds used it to enable the Claude Code
93 // integration too, and we'd like to turn Gemini/Native on in new builds
94 // without enabling Claude Code in old builds.
95 const NAME: &'static str = "gemini-and-native";
96
97 fn enabled_for_all() -> bool {
98 true
99 }
100}
101
102pub struct ClaudeCodeFeatureFlag;
103
104impl FeatureFlag for ClaudeCodeFeatureFlag {
105 const NAME: &'static str = "claude-code";
106
107 fn enabled_for_all() -> bool {
108 true
109 }
110}
111
112pub trait FeatureFlagViewExt<V: 'static> {
113 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
114 where
115 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
116
117 fn when_flag_enabled<T: FeatureFlag>(
118 &mut self,
119 window: &mut Window,
120 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
121 );
122}
123
124impl<V> FeatureFlagViewExt<V> for Context<'_, V>
125where
126 V: 'static,
127{
128 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
129 where
130 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
131 {
132 self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
133 let feature_flags = cx.global::<FeatureFlags>();
134 callback(feature_flags.has_flag::<T>(), v, window, cx);
135 })
136 }
137
138 fn when_flag_enabled<T: FeatureFlag>(
139 &mut self,
140 window: &mut Window,
141 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
142 ) {
143 if self
144 .try_global::<FeatureFlags>()
145 .is_some_and(|f| f.has_flag::<T>())
146 {
147 self.defer_in(window, move |view, window, cx| {
148 callback(view, window, cx);
149 });
150 return;
151 }
152 let subscription = Rc::new(RefCell::new(None));
153 let inner = self.observe_global_in::<FeatureFlags>(window, {
154 let subscription = subscription.clone();
155 move |v, window, cx| {
156 let feature_flags = cx.global::<FeatureFlags>();
157 if feature_flags.has_flag::<T>() {
158 callback(v, window, cx);
159 subscription.take();
160 }
161 }
162 });
163 subscription.borrow_mut().replace(inner);
164 }
165}
166
167#[derive(Debug)]
168pub struct OnFlagsReady {
169 pub is_staff: bool,
170}
171
172pub trait FeatureFlagAppExt {
173 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
174
175 /// Waits for the specified feature flag to resolve, up to the given timeout.
176 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
177
178 fn update_flags(&mut self, staff: bool, flags: Vec<String>);
179 fn set_staff(&mut self, staff: bool);
180 fn has_flag<T: FeatureFlag>(&self) -> bool;
181 fn is_staff(&self) -> bool;
182
183 fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
184 where
185 F: FnMut(OnFlagsReady, &mut App) + 'static;
186
187 fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
188 where
189 F: FnMut(bool, &mut App) + 'static;
190}
191
192impl FeatureFlagAppExt for App {
193 fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
194 let feature_flags = self.default_global::<FeatureFlags>();
195 feature_flags.staff = staff;
196 feature_flags.flags = flags;
197 }
198
199 fn set_staff(&mut self, staff: bool) {
200 let feature_flags = self.default_global::<FeatureFlags>();
201 feature_flags.staff = staff;
202 }
203
204 fn has_flag<T: FeatureFlag>(&self) -> bool {
205 self.try_global::<FeatureFlags>()
206 .map(|flags| flags.has_flag::<T>())
207 .unwrap_or(T::enabled_for_all())
208 }
209
210 fn is_staff(&self) -> bool {
211 self.try_global::<FeatureFlags>()
212 .map(|flags| flags.staff)
213 .unwrap_or(false)
214 }
215
216 fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
217 where
218 F: FnMut(OnFlagsReady, &mut App) + 'static,
219 {
220 self.observe_global::<FeatureFlags>(move |cx| {
221 let feature_flags = cx.global::<FeatureFlags>();
222 callback(
223 OnFlagsReady {
224 is_staff: feature_flags.staff,
225 },
226 cx,
227 );
228 })
229 }
230
231 fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
232 where
233 F: FnMut(bool, &mut App) + 'static,
234 {
235 self.observe_global::<FeatureFlags>(move |cx| {
236 let feature_flags = cx.global::<FeatureFlags>();
237 callback(feature_flags.has_flag::<T>(), cx);
238 })
239 }
240
241 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
242 let (tx, rx) = oneshot::channel::<bool>();
243 let mut tx = Some(tx);
244 let subscription: Option<Subscription>;
245
246 match self.try_global::<FeatureFlags>() {
247 Some(feature_flags) => {
248 subscription = None;
249 tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
250 }
251 None => {
252 subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
253 let feature_flags = cx.global::<FeatureFlags>();
254 if let Some(tx) = tx.take() {
255 tx.send(feature_flags.has_flag::<T>()).ok();
256 }
257 }));
258 }
259 }
260
261 WaitForFlag(rx, subscription)
262 }
263
264 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
265 let wait_for_flag = self.wait_for_flag::<T>();
266
267 self.spawn(async move |_cx| {
268 let mut wait_for_flag = wait_for_flag.fuse();
269 let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
270
271 select_biased! {
272 is_enabled = wait_for_flag => is_enabled,
273 _ = timeout => false,
274 }
275 })
276 }
277}
278
279pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
280
281impl Future for WaitForFlag {
282 type Output = bool;
283
284 fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
285 self.0.poll_unpin(cx).map(|result| {
286 self.1.take();
287 result.unwrap_or(false)
288 })
289 }
290}