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

SettingsServerControlsRouteScreen.tsx

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