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