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").map_or(false, |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
59/// Controls the values of various feature flags for the Agent launch.
60///
61/// Change this to `true` when we're ready to build the release candidate.
62const AGENT_LAUNCH: bool = false;
63
64pub struct Assistant2FeatureFlag;
65
66impl FeatureFlag for Assistant2FeatureFlag {
67 const NAME: &'static str = "assistant2";
68
69 fn enabled_for_all() -> bool {
70 AGENT_LAUNCH
71 }
72}
73
74pub struct AgentStreamEditsFeatureFlag;
75
76impl FeatureFlag for AgentStreamEditsFeatureFlag {
77 const NAME: &'static str = "agent-stream-edits";
78
79 fn enabled_for_all() -> bool {
80 AGENT_LAUNCH
81 }
82}
83
84pub struct NewBillingFeatureFlag;
85
86impl FeatureFlag for NewBillingFeatureFlag {
87 const NAME: &'static str = "new-billing";
88
89 fn enabled_for_all() -> bool {
90 AGENT_LAUNCH
91 }
92}
93
94pub struct PredictEditsRateCompletionsFeatureFlag;
95impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
96 const NAME: &'static str = "predict-edits-rate-completions";
97}
98
99pub struct LlmClosedBetaFeatureFlag {}
100impl FeatureFlag for LlmClosedBetaFeatureFlag {
101 const NAME: &'static str = "llm-closed-beta";
102}
103
104pub struct ZedProFeatureFlag {}
105impl FeatureFlag for ZedProFeatureFlag {
106 const NAME: &'static str = "zed-pro";
107}
108
109pub struct NotebookFeatureFlag;
110
111impl FeatureFlag for NotebookFeatureFlag {
112 const NAME: &'static str = "notebooks";
113}
114
115pub struct DebuggerFeatureFlag {}
116impl FeatureFlag for DebuggerFeatureFlag {
117 const NAME: &'static str = "debugger";
118}
119
120pub struct ThreadAutoCaptureFeatureFlag {}
121impl FeatureFlag for ThreadAutoCaptureFeatureFlag {
122 const NAME: &'static str = "thread-auto-capture";
123
124 fn enabled_for_staff() -> bool {
125 false
126 }
127}
128
129pub trait FeatureFlagViewExt<V: 'static> {
130 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
131 where
132 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
133
134 fn when_flag_enabled<T: FeatureFlag>(
135 &mut self,
136 window: &mut Window,
137 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
138 );
139}
140
141impl<V> FeatureFlagViewExt<V> for Context<'_, V>
142where
143 V: 'static,
144{
145 fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
146 where
147 F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
148 {
149 self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
150 let feature_flags = cx.global::<FeatureFlags>();
151 callback(feature_flags.has_flag::<T>(), v, window, cx);
152 })
153 }
154
155 fn when_flag_enabled<T: FeatureFlag>(
156 &mut self,
157 window: &mut Window,
158 callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
159 ) {
160 if self
161 .try_global::<FeatureFlags>()
162 .is_some_and(|f| f.has_flag::<T>())
163 {
164 self.defer_in(window, move |view, window, cx| {
165 callback(view, window, cx);
166 });
167 return;
168 }
169 let subscription = Rc::new(RefCell::new(None));
170 let inner = self.observe_global_in::<FeatureFlags>(window, {
171 let subscription = subscription.clone();
172 move |v, window, cx| {
173 let feature_flags = cx.global::<FeatureFlags>();
174 if feature_flags.has_flag::<T>() {
175 callback(v, window, cx);
176 subscription.take();
177 }
178 }
179 });
180 subscription.borrow_mut().replace(inner);
181 }
182}
183
184pub trait FeatureFlagAppExt {
185 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
186
187 /// Waits for the specified feature flag to resolve, up to the given timeout.
188 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
189
190 fn update_flags(&mut self, staff: bool, flags: Vec<String>);
191 fn set_staff(&mut self, staff: bool);
192 fn has_flag<T: FeatureFlag>(&self) -> bool;
193 fn is_staff(&self) -> bool;
194
195 fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
196 where
197 F: FnMut(bool, &mut App) + 'static;
198}
199
200impl FeatureFlagAppExt for App {
201 fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
202 let feature_flags = self.default_global::<FeatureFlags>();
203 feature_flags.staff = staff;
204 feature_flags.flags = flags;
205 }
206
207 fn set_staff(&mut self, staff: bool) {
208 let feature_flags = self.default_global::<FeatureFlags>();
209 feature_flags.staff = staff;
210 }
211
212 fn has_flag<T: FeatureFlag>(&self) -> bool {
213 self.try_global::<FeatureFlags>()
214 .map(|flags| flags.has_flag::<T>())
215 .unwrap_or(false)
216 }
217
218 fn is_staff(&self) -> bool {
219 self.try_global::<FeatureFlags>()
220 .map(|flags| flags.staff)
221 .unwrap_or(false)
222 }
223
224 fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
225 where
226 F: FnMut(bool, &mut App) + 'static,
227 {
228 self.observe_global::<FeatureFlags>(move |cx| {
229 let feature_flags = cx.global::<FeatureFlags>();
230 callback(feature_flags.has_flag::<T>(), cx);
231 })
232 }
233
234 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
235 let (tx, rx) = oneshot::channel::<bool>();
236 let mut tx = Some(tx);
237 let subscription: Option<Subscription>;
238
239 match self.try_global::<FeatureFlags>() {
240 Some(feature_flags) => {
241 subscription = None;
242 tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
243 }
244 None => {
245 subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
246 let feature_flags = cx.global::<FeatureFlags>();
247 if let Some(tx) = tx.take() {
248 tx.send(feature_flags.has_flag::<T>()).ok();
249 }
250 }));
251 }
252 }
253
254 WaitForFlag(rx, subscription)
255 }
256
257 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
258 let wait_for_flag = self.wait_for_flag::<T>();
259
260 self.spawn(async move |_cx| {
261 let mut wait_for_flag = wait_for_flag.fuse();
262 let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
263
264 select_biased! {
265 is_enabled = wait_for_flag => is_enabled,
266 _ = timeout => false,
267 }
268 })
269 }
270}
271
272pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
273
274impl Future for WaitForFlag {
275 type Output = bool;
276
277 fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
278 self.0.poll_unpin(cx).map(|result| {
279 self.1.take();
280 result.unwrap_or(false)
281 })
282 }
283}