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