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

SettingsServerControlsRouteScreen.tsx

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