Open History to see the last commit
1import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
2import { SymbolView } from "../../components/AppSymbol";
3import { AppText as Text } from "../../components/AppText";
4import {
5 type ResponseStreamingMode,
6 type ServerSettings,
7 type ServerSettingsPatch,
8 type ThreadEnvMode,
9 PROJECT_SCOPED_SERVER_SETTING_KEYS,
10 type ProjectScopedServerSettingKey,
11} from "@t3tools/contracts";
12import { useRef, useState, type ComponentProps } from "react";
13import { Alert, Platform, Pressable, View } from "react-native";
14import { useSafeAreaInsets } from "react-native-safe-area-context";
15
16import { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";
17import { serverEnvironment } from "../../state/server";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { SettingsScreen } from "./components/SettingsScreen";
20import {
21 AndroidSettingsEnvironmentFilter,
22 SettingsEnvironmentFilterHeader,
23} from "./components/SettingsEnvironmentFilterHeader";
24import { SettingsSection } from "./components/SettingsSection";
25import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
26import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
27import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
28import {
29 planMobileScopedSettingsClear,
30 planMobileScopedSettingsPatch,
31 resolveMobileSettingsTargets,
32 type ScopedMobileSettingsTarget,
33} from "./settings-scoped-server";
34
35type SettingsPage = "new-threads" | "source-control" | "agent-behavior" | "maintenance";
36
37const PAGE_TITLES: Record<SettingsPage, string> = {
38 "new-threads": "New threads",
39 "source-control": "Source control",
40 "agent-behavior": "Agent behavior",
41 maintenance: "Maintenance",
42};
43
44const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettingKey[]> = {
45 "new-threads": ["defaultThreadEnvMode", "defaultRuntimeMode"],
46 "source-control": ["defaultAutoPull", "newWorktreesStartFromOrigin"],
47 "agent-behavior": ["responseStreamingMode", "enableAgentBrowserAccess"],
48 maintenance: ["continueThreadsAfterServerUpdate"],
49};
50
51const WORKSPACE_CHOICES: ReadonlyArray<{
52 readonly mode: ThreadEnvMode;
53 readonly label: string;
54 readonly description: string;
55}> = [
56 {
57 mode: "local",
58 label: "Current checkout",
59 description: "Start new threads in the existing workspace.",
60 },
61 {
62 mode: "worktree",
63 label: "New worktree",
64 description: "Give each new thread a separate checkout.",
65 },
66];
67
68const STREAMING_CHOICES: ReadonlyArray<{
69 readonly mode: ResponseStreamingMode;
70 readonly label: string;
71 readonly description: string;
72}> = [
73 {
74 mode: "turn",
75 label: "After the turn",
76 description: "Show the answer when the agent finishes.",
77 },
78 {
79 mode: "paragraph",
80 label: "Finished paragraphs",
81 description: "Show each paragraph or code block as it completes.",
82 },
83 {
84 mode: "token",
85 label: "Token by token (legacy)",
86 description: "Repaint for every token; this can be slower.",
87 },
88];
89
90export function SettingsEnvironmentNewThreadsRouteScreen() {
91 return <ServerSettingsDetail page="new-threads" />;
92}
93
94export function SettingsEnvironmentSourceControlRouteScreen() {
95 return <ServerSettingsDetail page="source-control" />;
96}
97
98export function SettingsEnvironmentAgentBehaviorRouteScreen() {
99 return <ServerSettingsDetail page="agent-behavior" />;
100}
101
102export function SettingsEnvironmentMaintenanceRouteScreen() {
103 return <ServerSettingsDetail page="maintenance" />;
104}
105
106function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
107 const insets = useSafeAreaInsets();
108 const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
109 const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
110 const projectSelected = selectedProjectKey !== null;
111 const targets = resolveMobileSettingsTargets(
112 selectedTargets,
113 projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,
114 );
115 const [pendingWrites, setPendingWrites] = useState(0);
116 const writeInFlight = useRef(false);
117 const [pendingTargets, setPendingTargets] = useState<
118 readonly ScopedMobileSettingsTarget[] | null
119 >(null);
120 const displayTargets = pendingWrites > 0 && pendingTargets !== null ? pendingTargets : targets;
121 const hasConnectedSelection = targets.length > 0;
122 const reference = displayTargets[0] ?? null;
123 const uniform = <K extends keyof ServerSettings>(key: K): ServerSettings[K] | null => {
124 if (reference === null) return null;
125 const value = reference.settings[key];
126 return displayTargets.every((entry) => entry.settings[key] === value) ? value : null;
127 };
128 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
129 label: "environment settings update",
130 reportFailure: true,
131 });
132 const write = (patch: ServerSettingsPatch) => {
133 if (writeInFlight.current || !hasConnectedSelection) return;
134 const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch);
135 if (writes.length === 0) return;
136 writeInFlight.current = true;
137 setPendingTargets(targets);
138 setPendingWrites((count) => count + 1);
139 void Promise.allSettled(
140 writes.map((entry) =>
141 updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
142 ),
143 ).finally(() => {
144 writeInFlight.current = false;
145 setPendingTargets(null);
146 setPendingWrites((count) => count - 1);
147 });
148 };
149 const clearProjectOverrides = () => {
150 if (writeInFlight.current) return;
151 const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);
152 if (writes.length === 0) return;
153 writeInFlight.current = true;
154 setPendingTargets(targets);
155 setPendingWrites((count) => count + 1);
156 void Promise.allSettled(
157 writes.map((entry) =>
158 updateSettings({ environmentId: entry.environmentId, input: { patch: entry.patch } }),
159 ),
160 ).finally(() => {
161 writeInFlight.current = false;
162 setPendingTargets(null);
163 setPendingWrites((count) => count - 1);
164 });
165 };
166 const supportsProjectOverrides = targets.every(
167 (target) =>
168 target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,
169 );
170 const disabled =
171 pendingWrites > 0 || !hasConnectedSelection || (projectSelected && !supportsProjectOverrides);
172 const supportsContinuation = targets.every(
173 (target) =>
174 target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true,
175 );
176 const disabledFor = (key: string) =>
177 disabled ||
178 (projectSelected &&
179 !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(
180 key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],
181 ));
182
183 return (
184 <>
185 <SettingsEnvironmentFilterHeader />
186 <SettingsScreen
187 title={PAGE_TITLES[props.page]}
188 trailing={<AndroidSettingsEnvironmentFilter />}
189 >
190 <ScrollView
191 contentInsetAdjustmentBehavior="automatic"
192 showsVerticalScrollIndicator={false}
193 className="flex-1"
194 contentContainerClassName="gap-6 px-5 pt-4"
195 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
196 >
197 {!hasConnectedSelection || reference === null ? (
198 <Text className="px-2 text-base text-foreground-muted">
199 {projectSelected
200 ? "Select a project with a checkout on a connected environment."
201 : "Use the filter above to select a connected environment."}
202 </Text>
203 ) : (
204 <>
205 {projectSelected ? (
206 <SettingsProjectOverridesSection
207 projectLabel={selectedProject?.label ?? "Unavailable project"}
208 hasOverrides={targets.some((target) =>
209 PAGE_PROJECT_KEYS[props.page].some((key) => target.sources[key] === "project"),
210 )}
211 supportsOverrides={supportsProjectOverrides}
212 pending={pendingWrites > 0}
213 onClear={clearProjectOverrides}
214 />
215 ) : null}
216 {props.page === "new-threads" ? (
217 <>
218 <SettingsSection
219 title="Default workspace"
220 trailing={
221 pendingWrites === 0 && uniform("defaultThreadEnvMode") === null ? (
222 <MixedValuesLabel projectSelected={projectSelected} />
223 ) : null
224 }
225 >
226 {WORKSPACE_CHOICES.map((choice, index) => (
227 <ChoiceRow
228 key={choice.mode}
229 label={choice.label}
230 description={choice.description}
231 selected={uniform("defaultThreadEnvMode") === choice.mode}
232 separated={index > 0}
233 disabled={disabledFor("defaultThreadEnvMode")}
234 onPress={() => write({ defaultThreadEnvMode: choice.mode })}
235 />
236 ))}
237 </SettingsSection>
238 <SettingsSection
239 title="Default permissions"
240 trailing={
241 pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
242 <MixedValuesLabel projectSelected={projectSelected} />
243 ) : null
244 }
245 >
246 {RUNTIME_MODE_CHOICES.map((choice, index) => (
247 <ChoiceRow
248 key={choice.mode}
249 label={choice.label}
250 description={choice.description}
251 selected={uniform("defaultRuntimeMode") === choice.mode}
252 separated={index > 0}
253 disabled={disabledFor("defaultRuntimeMode")}
254 onPress={() => write({ defaultRuntimeMode: choice.mode })}
255 />
256 ))}
257 </SettingsSection>
258 </>
259 ) : null}
260
261 {props.page === "source-control" ? (
262 <>
263 <SettingsSection title="Default branch">
264 <FanoutSwitchRow
265 icon="arrow.down.circle"
266 label="Automatically pull"
267 subtitle="Keep the default branch current when there are no local changes."
268 value={uniform("defaultAutoPull")}
269 disabled={disabledFor("defaultAutoPull")}
270 onValueChange={(value) => write({ defaultAutoPull: value })}
271 />
272 </SettingsSection>
273 <SettingsSection title="Worktrees">
274 <FanoutSwitchRow
275 icon="arrow.triangle.branch"
276 label="Start from origin"
277 subtitle="Base new worktrees on the remote branch."
278 value={uniform("newWorktreesStartFromOrigin")}
279 disabled={disabledFor("newWorktreesStartFromOrigin")}
280 onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
281 />
282 </SettingsSection>
283 </>
284 ) : null}
285
286 {props.page === "agent-behavior" ? (
287 <>
288 <SettingsSection
289 title="Response streaming"
290 trailing={
291 pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
292 <MixedValuesLabel projectSelected={projectSelected} />
293 ) : null
294 }
295 >
296 {STREAMING_CHOICES.map((choice, index) => (
297 <ChoiceRow
298 key={choice.mode}
299 label={choice.label}
300 description={choice.description}
301 selected={uniform("responseStreamingMode") === choice.mode}
302 separated={index > 0}
303 disabled={disabledFor("responseStreamingMode")}
304 onPress={() => {
305 if (choice.mode !== "token") {
306 write({ responseStreamingMode: choice.mode });
307 return;
308 }
309 Alert.alert(
310 "Use legacy token streaming?",
311 "Repainting every token can make the app slower.",
312 [
313 { text: "Cancel", style: "cancel" },
314 {
315 text: "Use token streaming",
316 onPress: () => write({ responseStreamingMode: "token" }),
317 },
318 ],
319 );
320 }}
321 />
322 ))}
323 </SettingsSection>
324 <SettingsSection title="Preview browser">
325 <FanoutSwitchRow
326 icon="globe"
327 label="Agent browser access"
328 subtitle="Allow agents to use the in-app preview browser."
329 value={uniform("enableAgentBrowserAccess")}
330 disabled={disabledFor("enableAgentBrowserAccess")}
331 onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
332 />
333 </SettingsSection>
334 </>
335 ) : null}
336
337 {props.page === "maintenance" ? (
338 <SettingsSection title="Updates">
339 <FanoutSwitchRow
340 icon="arrow.clockwise"
341 label="Check provider updates"
342 subtitle={
343 projectSelected
344 ? "Environment-wide setting. Select All projects to change it."
345 : "Check installed provider CLIs for newer versions."
346 }
347 value={uniform("enableProviderUpdateChecks")}
348 disabled={disabledFor("enableProviderUpdateChecks")}
349 onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
350 />
351 <View className="border-t border-border-subtle">
352 <FanoutSwitchRow
353 icon="arrow.uturn.forward"
354 label="Continue after restart"
355 subtitle={
356 supportsContinuation
357 ? "Resume interrupted threads after an update or restart."
358 : "Update older servers to control restart continuation."
359 }
360 value={uniform("continueThreadsAfterServerUpdate")}
361 disabled={
362 disabledFor("continueThreadsAfterServerUpdate") || !supportsContinuation
363 }
364 onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}
365 />
366 </View>
367 </SettingsSection>
368 ) : null}
369 </>
370 )}
371 </ScrollView>
372 </SettingsScreen>
373 </>
374 );
375}
376
377function ChoiceRow(props: {
378 readonly label: string;
379 readonly description: string;
380 readonly selected: boolean;
381 readonly separated: boolean;
382 readonly disabled: boolean;
383 readonly onPress: () => void;
384}) {
385 return (
386 <Pressable
387 accessibilityRole="radio"
388 accessibilityState={{ checked: props.selected, disabled: props.disabled }}
389 className={
390 props.separated
391 ? "flex-row items-center gap-4 border-t border-border-subtle p-4 active:opacity-70"
392 : "flex-row items-center gap-4 p-4 active:opacity-70"
393 }
394 disabled={props.disabled}
395 onPress={props.onPress}
396 >
397 <View className="min-w-0 flex-1 gap-1">
398 <Text
399 className={
400 Platform.OS === "android" ? "text-base text-foreground" : "text-lg text-foreground"
401 }
402 >
403 {props.label}
404 </Text>
405 <Text className="text-sm leading-normal text-foreground-muted">{props.description}</Text>
406 </View>
407 {props.selected ? (
408 <SymbolView
409 name="checkmark"
410 size={18}
411 tintColorClassName="accent-icon"
412 type="monochrome"
413 weight="semibold"
414 />
415 ) : null}
416 </Pressable>
417 );
418}
419
420function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
421 return (
422 <Text
423 accessibilityLabel={
424 props.projectSelected
425 ? "Selected project checkouts use different values"
426 : "Selected environments use different values"
427 }
428 className="px-2 text-sm text-foreground-muted android:px-4"
429 >
430 Mixed
431 </Text>
432 );
433}
434
435function FanoutSwitchRow(props: {
436 readonly icon: ComponentProps<typeof SymbolView>["name"];
437 readonly label: string;
438 readonly subtitle: string;
439 readonly value: boolean | null;
440 readonly disabled: boolean;
441 readonly onValueChange: (value: boolean) => void;
442}) {
443 if (props.value !== null) {
444 return (
445 <SettingsSwitchRow
446 icon={props.icon}
447 label={props.label}
448 subtitle={props.subtitle}
449 value={props.value}
450 disabled={props.disabled}
451 onValueChange={props.onValueChange}
452 />
453 );
454 }
455
456 return (
457 <View className="flex-row items-center gap-4 p-4">
458 <SymbolView name={props.icon} size={22} tintColorClassName="accent-icon" />
459 <View className="min-w-0 flex-1 gap-1">
460 <Text className="text-lg text-foreground">{props.label}</Text>
461 <Text className="text-sm text-foreground-muted">{props.subtitle}</Text>
462 </View>
463 <Pressable
464 accessibilityLabel={`Set ${props.label} on for selected environments`}
465 accessibilityRole="button"
466 disabled={props.disabled}
467 className="rounded-full bg-subtle px-3 py-2 active:opacity-70 disabled:opacity-40"
468 onPress={() => props.onValueChange(true)}
469 >
470 <Text className="text-sm font-t3-medium text-foreground">Mixed · Set on</Text>
471 </Pressable>
472 </View>
473 );
474}