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

ThreadSettingsSections.tsx

406 lines15.6 KB

1import { T, useGT, msg, useMessages } from "gt-react-native";
2import { Button } from "../../components/ui/Button";
3import {
4 type AgentFeedbackMode,
5 AuthSettingsWriteScope,
6 isManagedSettingPath,
7 type ServerSettingsPatch,
8} from "@t3tools/contracts";
9import { useEnvironmentsWithScope } from "../../state/session";
10import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
11import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
12import { useAtomValue } from "@effect/atom-react";
13import { AsyncResult } from "effect/reactivity";
14import type { ComponentProps } from "react";
15import { View } from "react-native";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17​
18import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
19import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
20import { AppText as Text } from "../../components/ui/AppText";
21import { useEnvironments } from "../../state/environments";
22import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
26import { SettingsSection } from "./components/SettingsSection";
27import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
28import { SettingsScreen } from "./components/SettingsScreen";
29import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
30import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
31import {
32 managedSettingReason,
33 resolveMobileSettingsTargets,
34 uniformMobileSetting,
35} from "./settings-scoped-server";
36​
37export function SettingsLabsRouteScreen() {
38 const gt = useGT();
39 const insets = useSafeAreaInsets();
40​
41 return (
42 <SettingsScreen title={gt`Labs`}>
43 <ScrollView
44 contentInsetAdjustmentBehavior="automatic"
45 showsVerticalScrollIndicator={false}
46 className="flex-1"
47 contentContainerClassName="gap-6 px-5 pt-4"
48 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
49 >
50 <MachineBetaSection
51 title={gt`Linked environments`}
52 icon="link"
53 capability="peerLinks"
54 setting="linkedEnvironmentsEnabled"
55 description={gt`Let agents on a machine work on your other machines, and theirs on it. Turn it on for each machine. While off, nothing new starts over a link; running tasks finish.`}
56 />
57 <MachineBetaSection
58 title={gt`Fast worktree checkout`}
59 icon="bolt.circle"
60 capability="fastWorktreeCheckout"
61 setting="fastWorktreeCheckout"
62 description={gt`On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.`}
63 />
64 <AgentFeedbackSection />
65 </ScrollView>
66 </SettingsScreen>
67 );
69​
70const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 7;
71​
72/**
73 * Usage-limit and auto-settle rows. The Threads page owns their writes, so they share its queue
74 * with the page's other project overrides, and their project override reset.
75 */
76export function AutoSettleSettingsRows(props: {
77 readonly write: (patch: ServerSettingsPatch) => void;
78 readonly pending: boolean;
79}) {
80 const gt = useGT();
81 const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
82 const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
83 const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope);
84 const projectSelected = selectedProjectKey !== null;
85​
86 const projectMembers = projectSelected
87 ? (selectedProject?.members.map((member) => member.project) ?? [])
88 : null;
89 const displayTargets = resolveMobileSettingsTargets(
90 selectedTargets.filter(supportsSharedSettingsSync),
91 projectMembers,
92 );
93 // The page saves to all its targets, so any read-only one blocks the save.
94 const canWriteSettings =
95 displayTargets.length > 0 &&
96 resolveMobileSettingsTargets(selectedTargets, projectMembers).every((target) =>
97 writableEnvironments.has(target.environment.environmentId),
98 );
99 const reference = displayTargets[0] ?? null;
100 const referenceSettings = reference?.settings ?? null;
101​
102 if (reference === null || referenceSettings === null) {
103 return null;
104 }
105​
106 const writeToAll = (
107 patch: Partial<AutoSettleSettings> & {
108 autoResumeLimitedThreads?: boolean;
109 snoozeLimitedThreads?: boolean;
110 },
111 ) => props.write(patch);
112​
113 const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync(
114 {
115 environmentId: reference.environment.environmentId,
116 projectId: reference.projectId,
117 settings: referenceSettings,
118 },
119 displayTargets.map((target) => ({
120 environmentId: target.environment.environmentId,
121 projectId: target.projectId,
122 label: target.environment.label,
123 settings: target.settings,
124 })),
125 );
126​
127 const disabled = !canWriteSettings || props.pending;
128 const disabledFor = (...keys: string[]) =>
129 disabled || managedSettingReason(displayTargets, keys) !== undefined;
130 const afterDays = referenceSettings.sidebarAutoSettleAfterDays;
131​
132 return (
133 <View className="gap-6">
134 {!projectSelected ? (
135 <SettingsSection title={gt`Usage limits`}>
136 <SettingsSwitchRow
137 icon="clock"
138 label={gt`Resume after usage limits`}
139 subtitle={gt`Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.`}
140 value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")}
141 disabled={disabledFor("autoResumeLimitedThreads")}
142 onValueChange={(value) => writeToAll({ autoResumeLimitedThreads: value })}
143 />
144 <SettingsSwitchRow
145 icon="clock"
146 label={gt`Snooze until limits reset`}
147 subtitle={gt`Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.`}
148 value={uniformMobileSetting(displayTargets, "snoozeLimitedThreads")}
149 disabled={disabledFor("snoozeLimitedThreads")}
150 onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })}
151 />
152 </SettingsSection>
153 ) : null}
154 <SettingsSection title={gt`Auto-settle`}>
155 <SettingsSwitchRow
156 icon="arrow.triangle.branch"
157 label={gt`Auto-settle merged threads`}
158 value={referenceSettings.sidebarAutoSettleOnMerge}
159 disabled={disabledFor("sidebarAutoSettleOnMerge")}
160 onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}
161 />
162 <SettingsSwitchRow
163 icon="clock"
164 label={gt`Auto-settle inactive threads`}
165 value={afterDays !== null}
166 disabled={disabledFor("sidebarAutoSettleAfterDays")}
167 onValueChange={(value) =>
168 writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })
169 }
170 />
171 {afterDays !== null ? (
172 <View className="flex-row items-center gap-4 px-4 py-4 android:min-h-14 android:py-3">
173 <View className="w-[22px] android:w-6" />
174 <Text className="flex-1 text-foreground text-lg android:text-base">
175 <T>Inactive days</T>
176 </Text>
177 <AutoSettleDaysField
178 value={afterDays}
179 disabled={disabledFor("sidebarAutoSettleAfterDays")}
180 onValueChange={(value) => writeToAll({ sidebarAutoSettleAfterDays: value })}
181 />
182 </View>
183 ) : null}
184 </SettingsSection>
185 {!props.pending && mismatches.length > 0 ? (
186 <SettingsSection title={gt`Across environments`}>
187 <View className="gap-3 p-4">
188 <Text className="text-base text-foreground">
189 <T>Auto-settle defaults differ</T>
190 </Text>
191 <Text className="text-sm text-foreground-muted">
192 {mismatches.map((mismatch) => mismatch.label).join(", ")}
193 </Text>
194 <Button
195 label={gt`Apply auto-settle defaults`}
196 tone="secondary"
197 disabled={disabledFor("sidebarAutoSettleOnMerge", "sidebarAutoSettleAfterDays")}
198 onPress={() => writeToAll(autoSettlePatch)}
199 />
200 </View>
201 </SettingsSection>
202 ) : null}
203 </View>
204 );
206​
207export function WorkingSectionSettings() {
208 const gt = useGT();
209 const savePreferences = useAtomCommand(saveMobilePreferences);
210 const preferences = useAtomValue(mobilePreferencesAtom);
211 const workingShelfEnabled =
212 AsyncResult.isSuccess(preferences) && preferences.value.workingShelfEnabled !== false;
213​
214 return (
215 <View className="gap-3">
216 <SettingsSection title={gt`Sidebar`}>
217 <SettingsSwitchRow
218 icon="bolt.circle"
219 label={gt`Working section`}
220 value={workingShelfEnabled}
221 onValueChange={(value) => {
222 void savePreferences({ workingShelfEnabled: value });
223 }}
224 />
225 </SettingsSection>
226 <Text className="px-2 text-sm text-foreground-muted">
227 <T>
228 Fold working and monitoring threads into a Working section. They return to the top of the
229 list when they need you. While this is on, active threads are ordered by time and cannot
230 be moved.
231 </T>
232 </Text>
233 </View>
234 );
236​
237export function NewThreadSettingsSection() {
238 const gt = useGT();
239 const savePreferences = useAtomCommand(saveMobilePreferences);
240 const preferences = useAtomValue(mobilePreferencesAtom);
241 const useLastProject =
242 AsyncResult.isSuccess(preferences) && preferences.value.useLastProjectForNewThreads !== false;
243​
244 return (
245 <SettingsSection title={gt`New threads`}>
246 <SettingsSwitchRow
247 icon="square.and.pencil"
248 label={gt`Use last project`}
249 subtitle={gt`Start new threads in the last project you used on this device.`}
250 value={useLastProject}
251 onValueChange={(value) => {
252 void savePreferences({ useLastProjectForNewThreads: value });
253 }}
254 />
255 </SettingsSection>
256 );
258​
259type MachineBetaSetting = "linkedEnvironmentsEnabled" | "fastWorktreeCheckout";
260​
261const AGENT_FEEDBACK_CHOICES: ReadonlyArray<{
262 readonly mode: AgentFeedbackMode;
263 readonly label: string;
264 readonly description: string;
265}> = [
266 { mode: "off", label: msg("Off"), description: msg("Agents send no feedback to the T3 team.") },
267 {
268 mode: "on-request",
269 label: msg("When I ask"),
270 description: msg("When you ask, you see a short report and send it if you approve."),
271 },
272 {
273 mode: "auto",
274 label: msg("Automatic"),
275 description: msg("Agents also report T3 Code problems they hit on their own."),
276 },
277];
278​
279/** One choice list per connected machine that offers it, since each machine's own setting decides. */
280function AgentFeedbackSection() {
281 const gt = useGT();
282 const m = useMessages();
283 const { environments } = useEnvironments();
284 const supported = environments.filter(
285 (environment) =>
286 environment.connection.phase === "connected" &&
287 environment.serverConfig?.environment.capabilities.agentFeedback === true,
288 );
289 const writable = useEnvironmentsWithScope(supported, AuthSettingsWriteScope);
290 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
291 label: "agentFeedback beta update",
292 reportFailure: true,
293 });
294 if (supported.length === 0) return null;
295 return (
296 <View className="gap-3">
297 {supported.map((environment) => {
298 const policy = environment.serverConfig?.managedPolicy;
299 const managed = isManagedSettingPath(policy, "agentFeedback");
300 const mode = environment.serverConfig?.settings.agentFeedback.mode;
301 return (
302 <SettingsSection
303 key={environment.environmentId}
304 title={
305 supported.length === 1
306 ? gt`Beta: Agent feedback`
307 : gt`Beta: Agent feedback · ${{ label: environment.label }}`
308 }
309 {...(managed
310 ? { footer: gt`Managed by ${{ organization: policy?.organization }}.` }
311 : {})}
312 >
313 {AGENT_FEEDBACK_CHOICES.map((choice, index) => (
314 <SettingsChoiceRow
315 key={choice.mode}
316 label={m(choice.label)}
317 description={m(choice.description)}
318 selected={mode === choice.mode}
319 separated={index > 0}
320 disabled={managed || !writable.has(environment.environmentId)}
321 onPress={() =>
322 void updateSettings({
323 environmentId: environment.environmentId,
324 input: { patch: { agentFeedback: { mode: choice.mode } } },
325 })
326 }
327 />
328 ))}
329 </SettingsSection>
330 );
331 })}
332 <Text className="px-2 text-sm text-foreground-muted">
333 <T>
334 Reports go to the T3 team. A report you ask for is shown to you first in a card, with an
335 outline of recent turns. Turn on Include the conversation there to add the messages of the
336 turns the report is about.
337 </T>
338 </Text>
339 </View>
340 );
342​
343/** One switch per connected machine that offers the beta, since each machine's own setting decides. */
344function MachineBetaSection({
345 title,
346 icon,
347 capability,
348 setting,
349 description,
350}: {
351 readonly title: string;
352 readonly icon: ComponentProps<typeof SettingsSwitchRow>["icon"];
353 readonly capability: "peerLinks" | "fastWorktreeCheckout";
354 readonly setting: MachineBetaSetting;
355 readonly description: string;
356}) {
357 const gt = useGT();
358 const { environments } = useEnvironments();
359 const supported = environments.filter(
360 (environment) =>
361 environment.connection.phase === "connected" &&
362 environment.serverConfig?.environment.capabilities[capability] === true,
363 );
364 const writable = useEnvironmentsWithScope(supported, AuthSettingsWriteScope);
365 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
366 label: `${setting} beta update`,
367 reportFailure: true,
368 });
369 if (supported.length === 0) return null;
370 return (
371 <View className="gap-3">
372 <SettingsSection title={gt`Beta: ${{ feature: title }}`}>
373 {supported.map((environment) => {
374 const policy = environment.serverConfig?.managedPolicy;
375 const managed = isManagedSettingPath(policy, setting);
376 return (
377 <SettingsSwitchRow
378 key={environment.environmentId}
379 icon={icon}
380 label={environment.label}
381 {...(managed
382 ? {
383 subtitle: gt`Managed by ${{ organization: policy?.organization }}.`,
384 }
385 : {})}
386 value={environment.serverConfig?.settings[setting] === true}
387 disabled={managed || !writable.has(environment.environmentId)}
388 onValueChange={(value) =>
389 void updateSettings({
390 environmentId: environment.environmentId,
391 input: {
392 patch:
393 setting === "linkedEnvironmentsEnabled"
394 ? { linkedEnvironmentsEnabled: value }
395 : { fastWorktreeCheckout: value },
396 },
397 })
398 }
399 />
400 );
401 })}
402 </SettingsSection>
403 <Text className="px-2 text-sm text-foreground-muted">{description}</Text>
404 </View>
405 );