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

SettingsServerControlsRouteScreen.tsx

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