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

SettingsServerControlsRouteScreen.tsx

475 lines18.0 KB

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