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