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

SettingsServerControlsRouteScreen.tsx

522 lines21.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 { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";
21import { SettingsScreen } from "./components/SettingsScreen";
22import {
23 AndroidSettingsEnvironmentFilter,
24 SettingsEnvironmentFilterHeader,
25} from "./components/SettingsEnvironmentFilterHeader";
26import { BranchNamingSettings } from "./components/BranchNamingSettings";
27import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
28import { SettingsChoiceRow } from "./components/SettingsChoiceRow";
29import { SettingsSection } from "./components/SettingsSection";
30import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
31import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection";
32import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
33import { useSettingsWriter } from "./useSettingsWriter";
34import {
35 planMobileScopedSettingsClear,
36 planMobileScopedSettingsPatch,
37 resolveMobileSettingsTargets,
38 uniformMobileSetting,
39 type ScopedMobileSettingsTarget,
40} from "./settings-scoped-server";
41import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
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 // A closing view can still save its drafts while a write is pending, after
154 // the controls disabled. Those patches run once the current write settles.
155 const queuedPatch = useRef<{ key: string; patch: ServerSettingsPatch } | null>(null);
156 const targetsKey = targets
157 .map((target) => `${target.environment.environmentId}:${target.projectId}`)
158 .join(",");
159 const [pendingTargets, setPendingTargets] = useState<
160 readonly ScopedMobileSettingsTarget[] | null
161 >(null);
162 const canWriteSettings =
163 targets.length > 0 &&
164 targets.every((target) => writableEnvironments.has(target.environment.environmentId));
165 const displayTargets = pendingWrites > 0 && pendingTargets !== null ? pendingTargets : targets;
166 const hasConnectedSelection = targets.length > 0;
167 const reference = displayTargets[0] ?? null;
168 const uniform = <K extends keyof ServerSettings>(key: K) =>
169 uniformMobileSetting(displayTargets, key);
170 // `uniform` folds a real null into "mixed"; nullable keys need the distinction.
171 const isMixed = (key: keyof ServerSettings) =>
172 reference === null ||
173 displayTargets.some((entry) => entry.settings[key] !== reference.settings[key]);
174 const writeSettings = useSettingsWriter();
175 const write = (patch: ServerSettingsPatch) => {
176 if (writeInFlight.current) {
177 const queued = queuedPatch.current;
178 queuedPatch.current = {
179 key: targetsKey,
180 patch: queued?.key === targetsKey ? { ...queued.patch, ...patch } : patch,
181 };
182 return;
183 }
184 if (
185 !hasConnectedSelection ||
186 !targets.every((target) =>
187 readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
188 )
189 )
190 return;
191 const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch);
192 if (writes.length === 0) return;
193 writeInFlight.current = true;
194 setPendingTargets(targets);
195 setPendingWrites((count) => count + 1);
196 void writeSettings(targets, writes).finally(() => {
197 writeInFlight.current = false;
198 setPendingTargets(null);
199 setPendingWrites((count) => count - 1);
200 const queued = queuedPatch.current;
201 queuedPatch.current = null;
202 // These targets may not show this write yet, so send it again with the
203 // queued patch; project overrides are replaced whole.
204 if (queued?.key === targetsKey) write({ ...patch, ...queued.patch });
205 });
206 };
207 const clearProjectOverrides = () => {
208 if (
209 writeInFlight.current ||
210 !targets.every((target) =>
211 readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
212 )
213 )
214 return;
215 const writes = planMobileScopedSettingsClear(targets, PAGE_PROJECT_KEYS[props.page]);
216 if (writes.length === 0) return;
217 writeInFlight.current = true;
218 setPendingTargets(targets);
219 setPendingWrites((count) => count + 1);
220 void writeSettings(targets, writes).finally(() => {
221 writeInFlight.current = false;
222 // Resending a draft over these pre-clear targets would undo the clear.
223 queuedPatch.current = null;
224 setPendingTargets(null);
225 setPendingWrites((count) => count - 1);
226 });
227 };
228 const supportsProjectOverrides = targets.every(
229 (target) =>
230 target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true,
231 );
232 const disabled =
233 !canWriteSettings ||
234 pendingWrites > 0 ||
235 !hasConnectedSelection ||
236 (projectSelected && !supportsProjectOverrides);
237 const supportsContinuation = targets.every(
238 (target) =>
239 target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true,
240 );
241 const disabledFor = (key: string) =>
242 disabled ||
243 (projectSelected &&
244 !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(
245 key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],
246 ));
247​
248 return (
249 <>
250 <SettingsEnvironmentFilterHeader />
251 <SettingsScreen
252 title={PAGE_TITLES[props.page]}
253 trailing={<AndroidSettingsEnvironmentFilter />}
254 >
255 <ScrollView
256 contentInsetAdjustmentBehavior="automatic"
257 showsVerticalScrollIndicator={false}
258 className="flex-1"
259 contentContainerClassName="gap-6 px-5 pt-4"
260 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
261 >
262 {!hasConnectedSelection || reference === null ? (
263 <Text className="px-2 text-base text-foreground-muted">
264 {projectSelected
265 ? "Select a project with a checkout on a connected environment."
266 : "Use the filter above to select a connected environment."}
267 </Text>
268 ) : (
269 <>
270 {projectSelected ? (
271 <SettingsProjectOverridesSection
272 projectLabel={selectedProject?.label ?? "Unavailable project"}
273 hasOverrides={targets.some((target) =>
274 PAGE_PROJECT_KEYS[props.page].some((key) => target.sources[key] === "project"),
275 )}
276 supportsOverrides={supportsProjectOverrides}
277 pending={pendingWrites > 0}
278 disabled={!canWriteSettings}
279 onClear={clearProjectOverrides}
280 />
281 ) : null}
282 {props.page === "new-threads" ? (
283 <>
284 <SettingsSection
285 title="Default workspace"
286 trailing={
287 pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
288 <MixedValuesLabel projectSelected={projectSelected} />
289 ) : null
290 }
291 >
292 {WORKSPACE_CHOICES.filter(
293 (choice) => choice.mode !== null || !projectSelected,
294 ).map((choice, index) => (
295 <SettingsChoiceRow
296 key={choice.mode ?? "inherit"}
297 label={choice.label}
298 description={choice.description}
299 selected={
300 !isMixed("defaultThreadEnvMode") &&
301 uniform("defaultThreadEnvMode") === choice.mode
302 }
303 separated={index > 0}
304 disabled={disabledFor("defaultThreadEnvMode")}
305 onPress={() => write({ defaultThreadEnvMode: choice.mode })}
306 />
307 ))}
308 </SettingsSection>
309 <SettingsSection
310 title="Worktree submodules"
311 trailing={
312 pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
313 <MixedValuesLabel projectSelected={projectSelected} />
314 ) : null
315 }
316 >
317 {SUBMODULE_CHOICES.filter(
318 (choice) => choice.mode !== null || !projectSelected,
319 ).map((choice, index) => (
320 <SettingsChoiceRow
321 key={choice.mode ?? "inherit"}
322 label={choice.label}
323 description={choice.description}
324 selected={
325 !isMixed("worktreeSubmodules") &&
326 uniform("worktreeSubmodules") === choice.mode
327 }
328 separated={index > 0}
329 disabled={disabledFor("worktreeSubmodules")}
330 onPress={() => write({ worktreeSubmodules: choice.mode })}
331 />
332 ))}
333 </SettingsSection>
334 <SettingsSection
335 title="Default permissions"
336 trailing={
337 pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
338 <MixedValuesLabel projectSelected={projectSelected} />
339 ) : null
340 }
341 >
342 {RUNTIME_MODE_CHOICES.map((choice, index) => (
343 <SettingsChoiceRow
344 key={choice.mode}
345 label={choice.label}
346 description={choice.description}
347 selected={uniform("defaultRuntimeMode") === choice.mode}
348 separated={index > 0}
349 disabled={disabledFor("defaultRuntimeMode")}
350 onPress={() => write({ defaultRuntimeMode: choice.mode })}
351 />
352 ))}
353 </SettingsSection>
354 </>
355 ) : null}
356​
357 {props.page === "source-control" ? (
358 <>
359 <BranchNamingSettings
360 key={targetsKey}
361 mode={uniform("branchNamingMode")}
362 prefix={uniform("branchNamePrefix")}
363 instructions={uniform("branchNameInstructions")}
364 disabled={disabledFor("branchNamingMode")}
365 onChange={write}
366 />
367 <SettingsSection title="Pull requests">
368 <SettingsSwitchRow
369 icon={PullRequestGlyph.merged}
370 label="Remove agent credits when merging"
371 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."
372 value={uniform("removeAgentCreditsOnMerge")}
373 disabled={disabledFor("removeAgentCreditsOnMerge")}
374 onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })}
375 />
376 </SettingsSection>
377 <SettingsSection title="Default branch">
378 <SettingsSwitchRow
379 icon="arrow.down.circle"
380 label="Automatically pull"
381 subtitle="Keep the default branch current when there are no local changes."
382 value={uniform("defaultAutoPull")}
383 disabled={disabledFor("defaultAutoPull")}
384 onValueChange={(value) => write({ defaultAutoPull: value })}
385 />
386 </SettingsSection>
387 <SettingsSection title="Worktrees">
388 <SettingsSwitchRow
389 icon="arrow.triangle.branch"
390 label="Start from remote"
391 subtitle="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."
392 value={uniform("newWorktreesStartFromOrigin")}
393 disabled={disabledFor("newWorktreesStartFromOrigin")}
394 onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
395 />
396 </SettingsSection>
397 </>
398 ) : null}
399​
400 {props.page === "agent-behavior" ? (
401 <>
402 <SettingsSection
403 title="Response streaming"
404 trailing={
405 pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
406 <MixedValuesLabel projectSelected={projectSelected} />
407 ) : null
408 }
409 >
410 {STREAMING_CHOICES.map((choice, index) => (
411 <SettingsChoiceRow
412 key={choice.mode}
413 label={choice.label}
414 description={choice.description}
415 selected={uniform("responseStreamingMode") === choice.mode}
416 separated={index > 0}
417 disabled={disabledFor("responseStreamingMode")}
418 onPress={() => write({ responseStreamingMode: choice.mode })}
419 />
420 ))}
421 </SettingsSection>
422 <SettingsSection title="Preview browser">
423 <SettingsSwitchRow
424 icon="globe"
425 label="Agent browser access"
426 subtitle="Allow agents to use the in-app preview browser."
427 value={uniform("enableAgentBrowserAccess")}
428 disabled={disabledFor("enableAgentBrowserAccess")}
429 onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
430 />
431 </SettingsSection>
432 </>
433 ) : null}
434​
435 {props.page === "maintenance" ? (
436 <>
437 {!projectSelected &&
438 selectedTargets
439 .filter(
440 (target) =>
441 target.serverConfig.environment.capabilities.databaseStorage === true,
442 )
443 .map((target) => (
444 <DatabaseStorageNotice key={target.environmentId} target={target} />
445 ))}
446 {!projectSelected ? (
447 <SettingsSection title="Manage environments">
448 {selectedTargets.map((target) => (
449 <SettingsRow
450 key={target.environmentId}
451 icon="server.rack"
452 label={target.label}
453 value="Server and provider updates"
454 onPress={() =>
455 navigation.navigate("SettingsSheet", {
456 screen: "SettingsContent",
457 params: {
458 screen: "SettingsEnvironmentDetail",
459 params: { environmentId: target.environmentId },
460 },
461 })
462 }
463 />
464 ))}
465 </SettingsSection>
466 ) : null}
467 <SettingsSection title="Updates">
468 <SettingsSwitchRow
469 icon="arrow.clockwise"
470 label="Check provider updates"
471 subtitle={
472 projectSelected
473 ? "Environment-wide setting. Select All projects to change it."
474 : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear."
475 }
476 value={uniform("enableProviderUpdateChecks")}
477 disabled={disabledFor("enableProviderUpdateChecks")}
478 onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
479 />
480 <View className="border-t border-border-subtle">
481 <SettingsSwitchRow
482 icon="arrow.uturn.forward"
483 label="Continue after restart"
484 subtitle={
485 supportsContinuation
486 ? "Resume interrupted threads after an update or restart."
487 : "Update older servers to control restart continuation."
488 }
489 value={uniform("continueThreadsAfterServerUpdate")}
490 disabled={
491 disabledFor("continueThreadsAfterServerUpdate") || !supportsContinuation
492 }
493 onValueChange={(value) =>
494 write({ continueThreadsAfterServerUpdate: value })
495 }
496 />
497 </View>
498 </SettingsSection>
499 </>
500 ) : null}
501 </>
502 )}
503 </ScrollView>
504 </SettingsScreen>
505 </>
506 );
508​
509function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
510 return (
511 <Text
512 accessibilityLabel={
513 props.projectSelected
514 ? "Selected project checkouts use different values"
515 : "Selected environments use different values"
516 }
517 className="px-2 text-sm text-foreground-muted android:px-4"
518 >
519 Mixed
520 </Text>
521 );