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