Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsServerControlsRouteScreen.tsx

601 lines24.7 KB

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 AndroidSettingsEnvironmentFilter,
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 ];
162​
163export function SettingsThreadsRouteScreen() {
164 return <ServerSettingsDetail page="threads" />;
166​
167export function SettingsEnvironmentSourceControlRouteScreen() {
168 return <ServerSettingsDetail page="source-control" />;
170​
171export function SettingsWorktreesRouteScreen() {
172 return <ServerSettingsDetail page="worktrees" />;
174​
175export function SettingsEnvironmentMaintenanceRouteScreen() {
176 return <ServerSettingsDetail page="maintenance" />;
178​
179function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
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 <>
287 <SettingsEnvironmentFilterHeader />
288 <SettingsScreen
289 title={PAGE_TITLES[props.page]}
290 trailing={<AndroidSettingsEnvironmentFilter />}
291 >
292 <ScrollView
293 contentInsetAdjustmentBehavior="automatic"
294 showsVerticalScrollIndicator={false}
295 className="flex-1"
296 contentContainerClassName="gap-6 px-5 pt-4"
297 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
298 >
299 {!hasConnectedSelection || reference === null ? (
300 <Text className="px-2 text-base text-foreground-muted">
301 {projectSelected
302 ? "Select a project with a checkout on a connected environment."
303 : "Use the filter above to select a connected environment."}
304 </Text>
305 ) : (
306 <>
307 <ManagedPolicyNotice targets={targets} />
308 {projectSelected ? (
309 <SettingsProjectOverridesSection
310 projectLabel={selectedProject?.label ?? "Unavailable project"}
311 hasOverrides={targets.some((target) =>
312 PAGE_PROJECT_KEYS[props.page].some((key) => target.sources[key] === "project"),
313 )}
314 pending={pendingWrites > 0}
315 disabled={!canWriteSettings}
316 onClear={clearProjectOverrides}
317 />
318 ) : null}
319 {props.page === "threads" ? (
320 <>
321 <SettingsSection
322 title="Default workspace"
323 footer={managed("defaultThreadEnvMode")}
324 trailing={
325 pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
326 <MixedValuesLabel projectSelected={projectSelected} />
327 ) : null
328 }
329 >
330 {WORKSPACE_CHOICES.filter(
331 (choice) => choice.mode !== null || !projectSelected,
332 ).map((choice, index) => (
333 <SettingsChoiceRow
334 key={choice.mode ?? "inherit"}
335 label={choice.label}
336 description={choice.description}
337 selected={
338 !isMixed("defaultThreadEnvMode") &&
339 uniform("defaultThreadEnvMode") === choice.mode
340 }
341 separated={index > 0}
342 disabled={disabledFor("defaultThreadEnvMode")}
343 onPress={() => write({ defaultThreadEnvMode: choice.mode })}
344 />
345 ))}
346 </SettingsSection>
347 <SettingsSection
348 title="Default permissions"
349 footer={managed("defaultRuntimeMode")}
350 trailing={
351 pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
352 <MixedValuesLabel projectSelected={projectSelected} />
353 ) : null
354 }
355 >
356 {runtimeModeChoices.map((choice, index) => (
357 <SettingsChoiceRow
358 key={choice.mode}
359 label={choice.label}
360 description={choice.disabledReason ?? choice.description}
361 selected={uniform("defaultRuntimeMode") === choice.mode}
362 separated={index > 0}
363 disabled={
364 disabledFor("defaultRuntimeMode") || choice.disabledReason !== undefined
365 }
366 onPress={() => write({ defaultRuntimeMode: choice.mode })}
367 />
368 ))}
369 </SettingsSection>
370 <SettingsSection
371 title="Response streaming"
372 footer={managed("responseStreamingMode")}
373 trailing={
374 pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
375 <MixedValuesLabel projectSelected={projectSelected} />
376 ) : null
377 }
378 >
379 {STREAMING_CHOICES.map((choice, index) => (
380 <SettingsChoiceRow
381 key={choice.mode}
382 label={choice.label}
383 description={choice.description}
384 selected={uniform("responseStreamingMode") === choice.mode}
385 separated={index > 0}
386 disabled={disabledFor("responseStreamingMode")}
387 onPress={() => write({ responseStreamingMode: choice.mode })}
388 />
389 ))}
390 </SettingsSection>
391 <SettingsSection title="Preview browser">
392 <SettingsSwitchRow
393 icon="globe"
394 label="Agent browser access"
395 subtitle={managedSubtitle(
396 "enableAgentBrowserAccess",
397 "Allow agents to use the in-app preview browser.",
398 )}
399 value={uniform("enableAgentBrowserAccess")}
400 disabled={disabledFor("enableAgentBrowserAccess")}
401 onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
402 />
403 </SettingsSection>
404 <AutoSettleSettingsRows write={write} pending={pendingWrites > 0} />
405 </>
406 ) : null}
407​
408 {props.page === "source-control" ? (
409 <>
410 {projectSelected ? null : (
411 <SourceControlSignInSection
412 environments={selectedTargets}
413 canWrite={(environmentId) => writableEnvironments.has(environmentId)}
414 />
415 )}
416 <SettingsSection title="Pull requests">
417 <SettingsSwitchRow
418 icon={PullRequestGlyph.merged}
419 label="Remove agent credits when merging"
420 subtitle={managedSubtitle(
421 "removeAgentCreditsOnMerge",
422 "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.",
423 )}
424 value={uniform("removeAgentCreditsOnMerge")}
425 disabled={disabledFor("removeAgentCreditsOnMerge")}
426 onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })}
427 />
428 </SettingsSection>
429 <SettingsSection title="Default branch">
430 <SettingsSwitchRow
431 icon="arrow.down.circle"
432 label="Automatically pull"
433 subtitle={managedSubtitle(
434 "defaultAutoPull",
435 "Keep the default branch current when there are no local changes.",
436 )}
437 value={uniform("defaultAutoPull")}
438 disabled={disabledFor("defaultAutoPull")}
439 onValueChange={(value) => write({ defaultAutoPull: value })}
440 />
441 </SettingsSection>
442 </>
443 ) : null}
444​
445 {props.page === "worktrees" ? (
446 <>
447 <SettingsSection title="New worktrees">
448 <SettingsSwitchRow
449 icon="arrow.triangle.branch"
450 label="Start from remote"
451 subtitle={managedSubtitle(
452 "newWorktreesStartFromOrigin",
453 "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.",
454 )}
455 value={uniform("newWorktreesStartFromOrigin")}
456 disabled={disabledFor("newWorktreesStartFromOrigin")}
457 onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
458 />
459 </SettingsSection>
460 <SettingsSection
461 title="Worktree submodules"
462 footer={managed("worktreeSubmodules")}
463 trailing={
464 pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
465 <MixedValuesLabel projectSelected={projectSelected} />
466 ) : null
467 }
468 >
469 {SUBMODULE_CHOICES.filter(
470 (choice) => choice.mode !== null || !projectSelected,
471 ).map((choice, index) => (
472 <SettingsChoiceRow
473 key={choice.mode ?? "inherit"}
474 label={choice.label}
475 description={choice.description}
476 selected={
477 !isMixed("worktreeSubmodules") &&
478 uniform("worktreeSubmodules") === choice.mode
479 }
480 separated={index > 0}
481 disabled={disabledFor("worktreeSubmodules")}
482 onPress={() => write({ worktreeSubmodules: choice.mode })}
483 />
484 ))}
485 </SettingsSection>
486 <BranchNamingSettings
487 key={targetsKey}
488 mode={uniform("branchNamingMode")}
489 prefix={uniform("branchNamePrefix")}
490 instructions={uniform("branchNameInstructions")}
491 disabled={{
492 mode: disabledFor("branchNamingMode"),
493 prefix: disabledFor("branchNamePrefix"),
494 instructions: disabledFor("branchNameInstructions"),
495 }}
496 onChange={write}
497 />
498 </>
499 ) : null}
500​
501 {props.page === "maintenance" ? (
502 <>
503 {!projectSelected ? (
504 <DatabaseStorageNotice
505 targets={selectedTargets.filter(
506 (target) =>
507 target.serverConfig.environment.capabilities.databaseStorage === true,
508 )}
509 />
510 ) : null}
511 {!projectSelected ? (
512 <SettingsSection title="Manage environments">
513 {selectedTargets.map((target) => (
514 <SettingsRow
515 key={target.environmentId}
516 icon="server.rack"
517 label={target.label}
518 value="Server and provider updates"
519 onPress={() =>
520 navigation.navigate("SettingsEnvironmentDetail", {
521 environmentId: target.environmentId,
522 })
523 }
524 />
525 ))}
526 </SettingsSection>
527 ) : null}
528 <SettingsSection title="Updates">
529 <SettingsSwitchRow
530 icon="arrow.clockwise"
531 label="Check provider updates"
532 subtitle={managedSubtitle(
533 "enableProviderUpdateChecks",
534 projectSelected
535 ? "Environment-wide setting. Select All projects to change it."
536 : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear.",
537 )}
538 value={uniform("enableProviderUpdateChecks")}
539 disabled={disabledFor("enableProviderUpdateChecks")}
540 onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
541 />
542 <View className="border-t border-border-subtle">
543 <SettingsSwitchRow
544 icon="arrow.uturn.forward"
545 label="Continue after restart"
546 subtitle={managedSubtitle(
547 "continueThreadsAfterServerUpdate",
548 "Resume interrupted threads after an update or restart.",
549 )}
550 value={uniform("continueThreadsAfterServerUpdate")}
551 disabled={disabledFor("continueThreadsAfterServerUpdate")}
552 onValueChange={(value) =>
553 write({ continueThreadsAfterServerUpdate: value })
554 }
555 />
556 </View>
557 </SettingsSection>
558 </>
559 ) : null}
560 </>
561 )}
562 </ScrollView>
563 </SettingsScreen>
564 </>
565 );
567​
568function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
569 return (
570 <Text
571 accessibilityLabel={
572 props.projectSelected
573 ? "Selected project checkouts use different values"
574 : "Selected environments use different values"
575 }
576 className="px-2 text-sm text-foreground-muted android:px-4"
577 >
578 Mixed
579 </Text>
580 );
582​
583/** Locked settings are refused when saved; say so before the user tries. */
584function ManagedPolicyNotice(props: { readonly targets: readonly ScopedMobileSettingsTarget[] }) {
585 const organizations = [
586 ...new Set(
587 props.targets.flatMap((target) => {
588 const policy = target.environment.serverConfig.managedPolicy;
589 return policy !== undefined && policy.lockedSettings.length > 0
590 ? [policy.organization]
591 : [];
592 }),
593 ),
594 ];
595 if (organizations.length === 0) return null;
596 return (
597 <Text className="px-2 text-sm text-foreground-muted android:px-4">
598 Some settings are managed by {organizations.join(", ")} and cannot be changed here.
599 </Text>
600 );