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