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

SettingsServerControlsRouteScreen.tsx

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