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 ZedProFeatureFlag {}
70impl FeatureFlag for ZedProFeatureFlag {
71 const NAME: &'static str = "zed-pro";
72}
73
74pub struct NotebookFeatureFlag;
75
76impl FeatureFlag for NotebookFeatureFlag {
77 const NAME: &'static str = "notebooks";
78}
79
80pub struct PanicFeatureFlag;
81
82impl FeatureFlag for PanicFeatureFlag {
83 const NAME: &'static str = "panic";
84}
85
86pub struct JjUiFeatureFlag {}
87
88impl FeatureFlag for JjUiFeatureFlag {
89 const NAME: &'static str = "jj-ui";
90}
91
92pub struct GeminiAndNativeFeatureFlag;
93
94impl FeatureFlag for GeminiAndNativeFeatureFlag {
95 // This was previously called "acp".
96 //
97 // We renamed it because existing builds used it to enable the Claude Code
98 // integration too, and we'd like to turn Gemini/Native on in new builds
99 // without enabling Claude Code in old builds.
100 const NAME: &'static str = "gemini-and-native";
101}
102
103pub struct ClaudeCodeFeatureFlag;
104
105impl FeatureFlag for ClaudeCodeFeatureFlag {
106 const NAME: &'static str = "claude-code";
107}
108
109pub trait FeatureFlagViewExt<V: 'static> {
110 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
111 where
112 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
113
114 fn when_flag_enabled<T: FeatureFlag>(
115 &mut self,
116 window: &mut Window,
117 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
118 );
119}
120
121impl<V> FeatureFlagViewExt<V> for Context<'_, V>
122where
123 V: 'static,
124{
125 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
126 where
127 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
128 {
129 self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
130 let feature_flags = cx.global::<FeatureFlags>();
131 callback(feature_flags.has_flag::<T>(), v, window, cx);
132 })
133 }
134
135 fn when_flag_enabled<T: FeatureFlag>(
136 &mut self,
137 window: &mut Window,
138 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
139 ) {
140 if self
141 .try_global::<FeatureFlags>()
142 .is_some_and(|f| f.has_flag::<T>())
143 {
144 self.defer_in(window, move |view, window, cx| {
145 callback(view, window, cx);
146 });
147 return;
148 }
149 let subscription = Rc::new(RefCell::new(None));
150 let inner = self.observe_global_in::<FeatureFlags>(window, {
151 let subscription = subscription.clone();
152 move |v, window, cx| {
153 let feature_flags = cx.global::<FeatureFlags>();
154 if feature_flags.has_flag::<T>() {
155 callback(v, window, cx);
156 subscription.take();
157 }
158 }
159 });
160 subscription.borrow_mut().replace(inner);
161 }
162}
163
164#[derive(Debug)]
165pub struct OnFlagsReady {
166 pub is_staff: bool,
167}
168
169pub trait FeatureFlagAppExt {
170 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
171
172 /// Waits for the specified feature flag to resolve, up to the given timeout.
173 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
174
175 fn update_flags(&mut self, staff: bool, flags: Vec<String>);
176 fn set_staff(&mut self, staff: bool);
177 fn has_flag<T: FeatureFlag>(&self) -> bool;
178 fn is_staff(&self) -> bool;
179
180 fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
181 where
182 F: FnMut(OnFlagsReady, &mut App) + 'static;
183
184 fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
185 where
186 F: FnMut(bool, &mut App) + 'static;
187}
188
189impl FeatureFlagAppExt for App {
190 fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
191 let feature_flags = self.default_global::<FeatureFlags>();
192 feature_flags.staff = staff;
193 feature_flags.flags = flags;
194 }
195
196 fn set_staff(&mut self, staff: bool) {
197 let feature_flags = self.default_global::<FeatureFlags>();
198 feature_flags.staff = staff;
199 }
200
201 fn has_flag<T: FeatureFlag>(&self) -> bool {
202 self.try_global::<FeatureFlags>()
203 .map(|flags| flags.has_flag::<T>())
204 .unwrap_or(false)
205 }
206
207 fn is_staff(&self) -> bool {
208 self.try_global::<FeatureFlags>()
209 .map(|flags| flags.staff)
210 .unwrap_or(false)
211 }
212
213 fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
214 where
215 F: FnMut(OnFlagsReady, &mut App) + 'static,
216 {
217 self.observe_global::<FeatureFlags>(move |cx| {
218 let feature_flags = cx.global::<FeatureFlags>();
219 callback(
220 OnFlagsReady {
221 is_staff: feature_flags.staff,
222 },
223 cx,
224 );
225 })
226 }
227
228 fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
229 where
230 F: FnMut(bool, &mut App) + 'static,
231 {
232 self.observe_global::<FeatureFlags>(move |cx| {
233 let feature_flags = cx.global::<FeatureFlags>();
234 callback(feature_flags.has_flag::<T>(), cx);
235 })
236 }
237
238 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
239 let (tx, rx) = oneshot::channel::<bool>();
240 let mut tx = Some(tx);
241 let subscription: Option<Subscription>;
242
243 match self.try_global::<FeatureFlags>() {
244 Some(feature_flags) => {
245 subscription = None;
246 tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
247 }
248 None => {
249 subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
250 let feature_flags = cx.global::<FeatureFlags>();
251 if let Some(tx) = tx.take() {
252 tx.send(feature_flags.has_flag::<T>()).ok();
253 }
254 }));
255 }
256 }
257
258 WaitForFlag(rx, subscription)
259 }
260
261 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
262 let wait_for_flag = self.wait_for_flag::<T>();
263
264 self.spawn(async move |_cx| {
265 let mut wait_for_flag = wait_for_flag.fuse();
266 let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
267
268 select_biased! {
269 is_enabled = wait_for_flag => is_enabled,
270 _ = timeout => false,
271 }
272 })
273 }
274}
275
276pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
277
278impl Future for WaitForFlag {
279 type Output = bool;
280
281 fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
282 self.0.poll_unpin(cx).map(|result| {
283 self.1.take();
284 result.unwrap_or(false)
285 })
286 }
287}