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