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

SettingsServerControlsRouteScreen.tsx

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