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 {
21 RUNTIME_MODE_CHOICES,
22 withManagedRuntimeModeLimits,
23} from "../threads/thread-settings-options";
24import { SettingsScreen } from "./components/SettingsScreen";
25import {
26 useSettingsEnvironmentMenu,
27 SettingsEnvironmentFilterHeader,
28} from "./components/SettingsEnvironmentFilterHeader";
29import { BranchNamingSettings } from "./components/BranchNamingSettings";
30import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
31import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
32import { SettingsSection } from "./components/SettingsSection";
33import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
34import { SourceControlSignInSection } from "./components/SourceControlSignInSection";
35import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
36import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
37import { useSettingsWriter } from "./useSettingsWriter";
38import {
39 managedSettingReason,
40 planMobileScopedSettingsClear,
41 planMobileScopedSettingsPatch,
42 resolveMobileSettingsTargets,
43 uniformMobileSetting,
44 type ScopedMobileSettingsTarget,
45} from "./settings-scoped-server";
46import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
47import { AutoSettleSettingsRows } from "./ThreadSettingsSections";
48import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
49
50type SettingsPage = "threads" | "source-control" | "worktrees" | "maintenance";
51
52const PAGE_TITLES: Record<SettingsPage, string> = {
53 threads: "Threads",
54 "source-control": "Source control",
55 worktrees: "Worktrees",
56 maintenance: "Maintenance",
57};
58
59const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettingKey[]> = {
60 threads: [
61 "defaultThreadEnvMode",
62 "defaultRuntimeMode",
63 "responseStreamingMode",
64 "enableAgentBrowserAccess",
65 "sidebarAutoSettleOnMerge",
66 "sidebarAutoSettleAfterDays",
67 ],
68 "source-control": ["defaultAutoPull", "removeAgentCreditsOnMerge"],
69 worktrees: [
70 "newWorktreesStartFromOrigin",
71 "worktreeSubmodules",
72 "branchNamingMode",
73 "branchNamePrefix",
74 "branchNameInstructions",
75 ],
76 maintenance: ["continueThreadsAfterServerUpdate"],
77};
78
79const SUBMODULE_CHOICES: ReadonlyArray<{
80 readonly mode: WorktreeSubmodules | null;
81 readonly label: string;
82 readonly description: string;
83}> = [
84 {
85 mode: null,
86 label: "Inherit",
87 description: "Use the repository's t3.json, or initialize recursively.",
88 },
89 { mode: "recursive", label: "Recursive", description: "Initialize nested submodules too." },
90 {
91 mode: "top-level",
92 label: "Top level only",
93 description: "Skip submodules declared inside other submodules.",
94 },
95 { mode: "none", label: "Skip", description: "Leave submodules empty for a setup script." },
96];
97
98const WORKSPACE_CHOICES: ReadonlyArray<{
99 readonly mode: ThreadEnvMode | null;
100 readonly label: string;
101 readonly description: string;
102}> = [
103 {
104 mode: null,
105 label: "Inherit",
106 description: "Use the repository's t3.json, or the current checkout.",
107 },
108 {
109 mode: "local",
110 label: "Current checkout",
111 description: "Start new threads in the existing workspace.",
112 },
113 {
114 mode: "worktree",
115 label: "New worktree",
116 description: "Give each new thread a separate checkout.",
117 },
118];
119
120const STREAMING_CHOICES: ReadonlyArray<{
121 readonly mode: ResponseStreamingMode;
122 readonly label: string;
123 readonly description: string;
124}> = [
125 {
126 mode: "turn",
127 label: "After the turn",
128 description: "Show the answer when the agent finishes.",
129 },
130 {
131 mode: "paragraph",
132 label: "Finished paragraphs",
133 description: "Show each paragraph or code block as it completes.",
134 },
135];
136
137// Only servers with thread auto-settlement store these, so other targets get the rest of a patch.
138const AUTO_SETTLE_SETTING_KEYS: ReadonlySet<string> = new Set([
139 "sidebarAutoSettleOnMerge",
140 "sidebarAutoSettleAfterDays",
141 "autoResumeLimitedThreads",
142 "snoozeLimitedThreads",
143]);
144
145function planServerSettingsWrites(
146 targets: readonly ScopedMobileSettingsTarget[],
147 projectSelected: boolean,
148 patch: ServerSettingsPatch,
149) {
150 const capable = targets.filter((target) => supportsSharedSettingsSync(target.environment));
151 const others = targets.filter((target) => !supportsSharedSettingsSync(target.environment));
152 const othersPatch = Object.fromEntries(
153 Object.entries(patch).filter(([key]) => !AUTO_SETTLE_SETTING_KEYS.has(key)),
154 ) as ServerSettingsPatch;
155 return [
156 ...planMobileScopedSettingsPatch(capable, projectSelected, patch),
157 ...(Object.keys(othersPatch).length > 0
158 ? planMobileScopedSettingsPatch(others, projectSelected, othersPatch)
159 : []),
160 ];
161}
162
163export function SettingsThreadsRouteScreen() {
164 return <ServerSettingsDetail page="threads" />;
165}
166
167export function SettingsEnvironmentSourceControlRouteScreen() {
168 return <ServerSettingsDetail page="source-control" />;
169}
170
171export function SettingsWorktreesRouteScreen() {
172 return <ServerSettingsDetail page="worktrees" />;
173}
174
175export function SettingsEnvironmentMaintenanceRouteScreen() {
176 return <ServerSettingsDetail page="maintenance" />;
177}
178
179function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
180 const environmentMenu = useSettingsEnvironmentMenu();
181 const insets = useSafeAreaInsets();
182 const navigation = useNavigation();
183 const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
184 const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
185 const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope);
186 const projectSelected = selectedProjectKey !== null;
187 const targets = resolveMobileSettingsTargets(
188 selectedTargets,
189 projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null,
190 );
191 const [pendingWrites, setPendingWrites] = useState(0);
192 const writeInFlight = useRef(false);
193 // Closing views can save after controls disable; queue those patches behind the pending write.
194 const queuedPatch = useRef<{ key: string; patch: ServerSettingsPatch } | null>(null);
195 const targetsKey = targets
196 .map((target) => `${target.environment.environmentId}:${target.projectId}`)
197 .join(",");
198 const [pendingTargets, setPendingTargets] = useState<
199 readonly ScopedMobileSettingsTarget[] | null
200 >(null);
201 const canWriteSettings =
202 targets.length > 0 &&
203 targets.every((target) => writableEnvironments.has(target.environment.environmentId));
204 const displayTargets = pendingWrites > 0 && pendingTargets !== null ? pendingTargets : targets;
205 const hasConnectedSelection = targets.length > 0;
206 const reference = displayTargets[0] ?? null;
207 const uniform = <K extends keyof ServerSettings>(key: K) =>
208 uniformMobileSetting(displayTargets, key);
209 // `uniform` folds a real null into "mixed"; nullable keys need the distinction.
210 const isMixed = (key: keyof ServerSettings) =>
211 reference === null ||
212 displayTargets.some((entry) => entry.settings[key] !== reference.settings[key]);
213 const writeSettings = useSettingsWriter();
214 const write = (patch: ServerSettingsPatch) => {
215 if (writeInFlight.current) {
216 const queued = queuedPatch.current;
217 queuedPatch.current = {
218 key: targetsKey,
219 patch: queued?.key === targetsKey ? { ...queued.patch, ...patch } : patch,
220 };
221 return;
222 }
223 if (
224 !hasConnectedSelection ||
225 !targets.every((target) =>
226 readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
227 )
228 )
229 return;
230 const writes = planServerSettingsWrites(targets, projectSelected, patch);
231 if (writes.length === 0) return;
232 writeInFlight.current = true;
233 setPendingTargets(targets);
234 setPendingWrites((count) => count + 1);
235 void writeSettings(targets, writes).finally(() => {
236 writeInFlight.current = false;
237 setPendingTargets(null);
238 setPendingWrites((count) => count - 1);
239 const queued = queuedPatch.current;
240 queuedPatch.current = null;
241 // These targets may not show this write yet, so send it again with the
242 // queued patch; project overrides are replaced whole.
243 if (queued?.key === targetsKey) write({ ...patch, ...queued.patch });
244 });
245 };
246 const clearProjectOverrides = () => {
247 if (
248 writeInFlight.current ||
249 !targets.every((target) =>
250 readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
251 )
252 )
253 return;
254 const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);
255 if (writes.length === 0) return;
256 writeInFlight.current = true;
257 setPendingTargets(targets);
258 setPendingWrites((count) => count + 1);
259 void writeSettings(targets, writes).finally(() => {
260 writeInFlight.current = false;
261 // Resending a draft over these pre-clear targets would undo the clear.
262 queuedPatch.current = null;
263 setPendingTargets(null);
264 setPendingWrites((count) => count - 1);
265 });
266 };
267 const disabled = !canWriteSettings || pendingWrites > 0 || !hasConnectedSelection;
268 const managed = (...keys: string[]) => managedSettingReason(targets, ...keys);
269 // A locked row keeps its explanation and says who manages it.
270 const managedSubtitle = (key: string, subtitle: string) => {
271 const reason = managed(key);
272 return reason === undefined ? subtitle : `${subtitle} ${reason}`;
273 };
274 const runtimeModeChoices = withManagedRuntimeModeLimits(
275 RUNTIME_MODE_CHOICES,
276 targets.map((target) => target.environment.serverConfig.managedPolicy),
277 );
278 const disabledFor = (key: string) =>
279 disabled ||
280 managed(key) !== undefined ||
281 (projectSelected &&
282 !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(
283 key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],
284 ));
285
286 return (
287 <>
288 <SettingsEnvironmentFilterHeader />
289 <SettingsScreen title={PAGE_TITLES[props.page]} menus={[environmentMenu]}>
290 <ScrollView
291 contentInsetAdjustmentBehavior="automatic"
292 showsVerticalScrollIndicator={false}
293 className="flex-1"
294 contentContainerClassName="gap-6 px-5 pt-4"
295 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
296 >
297 {!hasConnectedSelection || reference === null ? (
298 <Text className="px-2 text-base text-foreground-muted">
299 {projectSelected
300 ? "Select a project with a checkout on a connected environment."
301 : "Use the filter above to select a connected environment."}
302 </Text>
303 ) : (
304 <>
305 <ManagedPolicyNotice targets={targets} />
306 {projectSelected ? (
307 <SettingsProjectOverridesSection
308 projectLabel={selectedProject?.label ?? "Unavailable project"}
309 hasOverrides={targets.some((target) =>
310 PAGE_PROJECT_KEYS[props.page].some((key) => target.sources[key] === "project"),
311 )}
312 pending={pendingWrites > 0}
313 disabled={!canWriteSettings}
314 onClear={clearProjectOverrides}
315 />
316 ) : null}
317 {props.page === "threads" ? (
318 <>
319 <SettingsSection
320 title="Default workspace"
321 footer={managed("defaultThreadEnvMode")}
322 trailing={
323 pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
324 <MixedValuesLabel projectSelected={projectSelected} />
325 ) : null
326 }
327 >
328 {WORKSPACE_CHOICES.filter(
329 (choice) => choice.mode !== null || !projectSelected,
330 ).map((choice, index) => (
331 <SettingsChoiceRow
332 key={choice.mode ?? "inherit"}
333 label={choice.label}
334 description={choice.description}
335 selected={
336 !isMixed("defaultThreadEnvMode") &&
337 uniform("defaultThreadEnvMode") === choice.mode
338 }
339 separated={index > 0}
340 disabled={disabledFor("defaultThreadEnvMode")}
341 onPress={() => write({ defaultThreadEnvMode: choice.mode })}
342 />
343 ))}
344 </SettingsSection>
345 <SettingsSection
346 title="Default permissions"
347 footer={managed("defaultRuntimeMode")}
348 trailing={
349 pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
350 <MixedValuesLabel projectSelected={projectSelected} />
351 ) : null
352 }
353 >
354 {runtimeModeChoices.map((choice, index) => (
355 <SettingsChoiceRow
356 key={choice.mode}
357 label={choice.label}
358 description={choice.disabledReason ?? choice.description}
359 selected={uniform("defaultRuntimeMode") === choice.mode}
360 separated={index > 0}
361 disabled={
362 disabledFor("defaultRuntimeMode") || choice.disabledReason !== undefined
363 }
364 onPress={() => write({ defaultRuntimeMode: choice.mode })}
365 />
366 ))}
367 </SettingsSection>
368 <SettingsSection
369 title="Response streaming"
370 footer={managed("responseStreamingMode")}
371 trailing={
372 pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
373 <MixedValuesLabel projectSelected={projectSelected} />
374 ) : null
375 }
376 >
377 {STREAMING_CHOICES.map((choice, index) => (
378 <SettingsChoiceRow
379 key={choice.mode}
380 label={choice.label}
381 description={choice.description}
382 selected={uniform("responseStreamingMode") === choice.mode}
383 separated={index > 0}
384 disabled={disabledFor("responseStreamingMode")}
385 onPress={() => write({ responseStreamingMode: choice.mode })}
386 />
387 ))}
388 </SettingsSection>
389 <SettingsSection title="Preview browser">
390 <SettingsSwitchRow
391 icon="globe"
392 label="Agent browser access"
393 subtitle={managedSubtitle(
394 "enableAgentBrowserAccess",
395 "Allow agents to use the in-app preview browser.",
396 )}
397 value={uniform("enableAgentBrowserAccess")}
398 disabled={disabledFor("enableAgentBrowserAccess")}
399 onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
400 />
401 </SettingsSection>
402 <AutoSettleSettingsRows write={write} pending={pendingWrites > 0} />
403 </>
404 ) : null}
405
406 {props.page === "source-control" ? (
407 <>
408 {projectSelected ? null : (
409 <SourceControlSignInSection
410 environments={selectedTargets}
411 canWrite={(environmentId) => writableEnvironments.has(environmentId)}
412 />
413 )}
414 <SettingsSection title="Pull requests">
415 <SettingsSwitchRow
416 icon={PullRequestGlyph.merged}
417 label="Remove agent credits when merging"
418 subtitle={managedSubtitle(
419 "removeAgentCreditsOnMerge",
420 "Remove recognized agent credits from merge and squash messages on hosts that support it, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits.",
421 )}
422 value={uniform("removeAgentCreditsOnMerge")}
423 disabled={disabledFor("removeAgentCreditsOnMerge")}
424 onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })}
425 />
426 </SettingsSection>
427 <SettingsSection title="Default branch">
428 <SettingsSwitchRow
429 icon="arrow.down.circle"
430 label="Automatically pull"
431 subtitle={managedSubtitle(
432 "defaultAutoPull",
433 "Keep the default branch current when there are no local changes.",
434 )}
435 value={uniform("defaultAutoPull")}
436 disabled={disabledFor("defaultAutoPull")}
437 onValueChange={(value) => write({ defaultAutoPull: value })}
438 />
439 </SettingsSection>
440 </>
441 ) : null}
442
443 {props.page === "worktrees" ? (
444 <>
445 <SettingsSection title="New worktrees">
446 <SettingsSwitchRow
447 icon="arrow.triangle.branch"
448 label="Start from remote"
449 subtitle={managedSubtitle(
450 "newWorktreesStartFromOrigin",
451 "Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing.",
452 )}
453 value={uniform("newWorktreesStartFromOrigin")}
454 disabled={disabledFor("newWorktreesStartFromOrigin")}
455 onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
456 />
457 </SettingsSection>
458 <SettingsSection
459 title="Worktree submodules"
460 footer={managed("worktreeSubmodules")}
461 trailing={
462 pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
463 <MixedValuesLabel projectSelected={projectSelected} />
464 ) : null
465 }
466 >
467 {SUBMODULE_CHOICES.filter(
468 (choice) => choice.mode !== null || !projectSelected,
469 ).map((choice, index) => (
470 <SettingsChoiceRow
471 key={choice.mode ?? "inherit"}
472 label={choice.label}
473 description={choice.description}
474 selected={
475 !isMixed("worktreeSubmodules") &&
476 uniform("worktreeSubmodules") === choice.mode
477 }
478 separated={index > 0}
479 disabled={disabledFor("worktreeSubmodules")}
480 onPress={() => write({ worktreeSubmodules: choice.mode })}
481 />
482 ))}
483 </SettingsSection>
484 <BranchNamingSettings
485 key={targetsKey}
486 mode={uniform("branchNamingMode")}
487 prefix={uniform("branchNamePrefix")}
488 instructions={uniform("branchNameInstructions")}
489 disabled={{
490 mode: disabledFor("branchNamingMode"),
491 prefix: disabledFor("branchNamePrefix"),
492 instructions: disabledFor("branchNameInstructions"),
493 }}
494 onChange={write}
495 />
496 </>
497 ) : null}
498
499 {props.page === "maintenance" ? (
500 <>
501 {!projectSelected ? (
502 <DatabaseStorageNotice
503 targets={selectedTargets.filter(
504 (target) =>
505 target.serverConfig.environment.capabilities.databaseStorage === true,
506 )}
507 />
508 ) : null}
509 {!projectSelected ? (
510 <SettingsSection title="Manage environments">
511 {selectedTargets.map((target) => (
512 <SettingsRow
513 key={target.environmentId}
514 icon="server.rack"
515 label={target.label}
516 value="Server and provider updates"
517 onPress={() =>
518 navigation.navigate("SettingsEnvironmentDetail", {
519 environmentId: target.environmentId,
520 })
521 }
522 />
523 ))}
524 </SettingsSection>
525 ) : null}
526 <SettingsSection title="Updates">
527 <SettingsSwitchRow
528 icon="arrow.clockwise"
529 label="Check provider updates"
530 subtitle={managedSubtitle(
531 "enableProviderUpdateChecks",
532 projectSelected
533 ? "Environment-wide setting. Select All projects to change it."
534 : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear.",
535 )}
536 value={uniform("enableProviderUpdateChecks")}
537 disabled={disabledFor("enableProviderUpdateChecks")}
538 onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
539 />
540 <View className="border-t border-border-subtle">
541 <SettingsSwitchRow
542 icon="arrow.uturn.forward"
543 label="Continue after restart"
544 subtitle={managedSubtitle(
545 "continueThreadsAfterServerUpdate",
546 "Resume interrupted threads after an update or restart.",
547 )}
548 value={uniform("continueThreadsAfterServerUpdate")}
549 disabled={disabledFor("continueThreadsAfterServerUpdate")}
550 onValueChange={(value) =>
551 write({ continueThreadsAfterServerUpdate: value })
552 }
553 />
554 </View>
555 </SettingsSection>
556 </>
557 ) : null}
558 </>
559 )}
560 </ScrollView>
561 </SettingsScreen>
562 </>
563 );
564}
565
566function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
567 return (
568 <Text
569 accessibilityLabel={
570 props.projectSelected
571 ? "Selected project checkouts use different values"
572 : "Selected environments use different values"
573 }
574 className="px-2 text-sm text-foreground-muted android:px-4"
575 >
576 Mixed
577 </Text>
578 );
579}
580
581/** Locked settings are refused when saved; say so before the user tries. */
582function ManagedPolicyNotice(props: { readonly targets: readonly ScopedMobileSettingsTarget[] }) {
583 const organizations = [
584 ...new Set(
585 props.targets.flatMap((target) => {
586 const policy = target.environment.serverConfig.managedPolicy;
587 return policy !== undefined && policy.lockedSettings.length > 0
588 ? [policy.organization]
589 : [];
590 }),
591 ),
592 ];
593 if (organizations.length === 0) return null;
594 return (
595 <Text className="px-2 text-sm text-foreground-muted android:px-4">
596 Some settings are managed by {organizations.join(", ")} and cannot be changed here.
597 </Text>
598 );
599}