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