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

SettingsServerControlsRouteScreen.tsx

484 lines19.8 KB

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