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