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