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

ProjectDefaultsSettings.tsx

474 lines18.7 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 DEFAULT_SERVER_SETTINGS,
4 type EnvironmentId,
5 type ModelSelection,
6 type ProviderInstanceId,
7 type ServerSettingsPatch,
8} from "@t3tools/contracts";
9import { createModelSelection } from "@t3tools/shared/model";
10import { useNavigate } from "@tanstack/react-router";
11import { useRef, useState } from "react";
12import { Trash2Icon } from "lucide-react";
13​
14import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
15import { getCustomModelOptionsByInstance } from "../../modelSelection";
16import {
17 applyProviderInstanceSettings,
18 deriveProviderInstanceEntries,
19 resolveDefaultProviderModelSelection,
20 sortProviderInstanceEntries,
21} from "../../providerInstances";
22import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
23import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { resolveEnvModeLabel } from "../BranchToolbar.logic";
26import { ProviderModelPicker } from "../chat/ProviderModelPicker";
27import { TraitsPicker } from "../chat/TraitsPicker";
28import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
29import { toastManager } from "../ui/toast";
30import { Switch } from "../ui/switch";
31import { Button } from "../ui/button";
32import { Input } from "../ui/input";
33import { PROJECT_GROUPING_MODE_LABELS } from "./ProjectSettingsPanel";
34import { ProjectDefaultActionsSettings } from "./ProjectDefaultActionsSettings";
35import { searchableSetting } from "./settingsSearch";
36import {
37 SETTINGS_PICKER_TRIGGER_CLASSNAME,
38 SettingResetButton,
39 SettingsPageContainer,
40 SettingsRow,
41 SettingsSection,
42} from "./settingsLayout";
43​
44/** Defaults are written only to the machines selected on the projects settings page. */
45export function ProjectDefaultsSettings({
46 environmentId,
47}: {
48 environmentId: EnvironmentId | null;
49}) {
50 const { environments } = useEnvironments();
51 const primaryEnvironmentId = usePrimaryEnvironmentId();
52 const clientSettings = useClientSettings();
53 const updateClientSettings = useUpdateClientSettings();
54 const navigate = useNavigate();
55 const updateSettings = useAtomCommand(
56 serverEnvironment.updateSettings,
57 "project defaults update",
58 );
59 const savingRef = useRef(new Set<string>());
60 const [saving, setSaving] = useState<ReadonlySet<string>>(new Set());
61 const scoped = environments.filter(
62 (environment) => environmentId === null || environment.environmentId === environmentId,
63 );
64 const targets = scoped.filter(
65 (environment) =>
66 environment.connection.phase === "connected" && environment.serverConfig !== null,
67 );
68 const representative =
69 targets.find((environment) => environment.environmentId === primaryEnvironmentId) ?? targets[0];
70 const serverSettings = representative?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS;
71 const providers = representative?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
72 const settings = { ...serverSettings, ...clientSettings };
73 const storedSelection = serverSettings.defaultModelSelection;
74 const selection = resolveDefaultProviderModelSelection(providers, storedSelection);
75 const entries = sortProviderInstanceEntries(
76 applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
77 );
78 const modelOptions = getCustomModelOptionsByInstance(
79 settings,
80 providers,
81 selection?.instanceId,
82 selection?.model,
83 );
84 const activeEntry = entries.find((entry) => entry.instanceId === selection?.instanceId);
85 const mixedModel = targets.some(
86 (target) =>
87 JSON.stringify(target.serverConfig?.settings.defaultModelSelection) !==
88 JSON.stringify(storedSelection),
89 );
90 const mixedWorkspace = targets.some(
91 (target) =>
92 target.serverConfig?.settings.defaultThreadEnvMode !== serverSettings.defaultThreadEnvMode,
93 );
94 const mixedBrowser = targets.some(
95 (target) =>
96 target.serverConfig?.settings.enableAgentBrowserAccess !==
97 serverSettings.enableAgentBrowserAccess,
98 );
99 const disabled = (key: keyof ServerSettingsPatch) => targets.length === 0 || saving.has(key);
100 const mixedAutoPull = targets.some(
101 (target) => target.serverConfig?.settings.defaultAutoPull !== serverSettings.defaultAutoPull,
102 );
103​
104 function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
105 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
106 for (const target of targets) {
107 const config = target.serverConfig;
108 if (!config) continue;
109 const entry = applyProviderInstanceSettings(
110 deriveProviderInstanceEntries(config.providers),
111 config.settings,
112 ).find((candidate) => candidate.instanceId === instanceId);
113 const options = getCustomModelOptionsByInstance(
114 { ...config.settings, ...clientSettings },
115 config.providers,
116 ).get(instanceId);
117 if (
118 !entry?.enabled ||
119 !entry.isAvailable ||
120 entry.driverKind !== sourceEntry?.driverKind ||
121 !options?.some((option) => option.slug === model && !option.isUnavailable)
122 ) {
123 return `This model is unavailable on ${target.label}. Select that machine to choose its default separately.`;
124 }
125 }
126 return null;
127 }
128​
129 async function save(patch: ServerSettingsPatch) {
130 const keys = Object.keys(patch);
131 if (targets.length === 0 || keys.some((key) => savingRef.current.has(key))) return;
132 const nextModel = patch.defaultModelSelection;
133 const reason = nextModel ? modelDisabledReason(nextModel.instanceId, nextModel.model) : null;
134 if (reason) {
135 toastManager.add({ type: "error", title: "Default model not saved", description: reason });
136 return;
137 }
138 for (const key of keys) savingRef.current.add(key);
139 setSaving(new Set(savingRef.current));
140 try {
141 const results = await Promise.all(
142 targets.map((target) =>
143 updateSettings({ environmentId: target.environmentId, input: { patch } }),
144 ),
145 );
146 const failedTargets = targets.filter((_, index) => results[index]?._tag === "Failure");
147 if (failedTargets.length > 0) {
148 toastManager.add({
149 type: "error",
150 title: "Project defaults not saved on every machine",
151 description: `Could not update ${failedTargets.map((target) => target.label).join(", ")}. Other machines may have saved the change.`,
152 });
153 }
154 } finally {
155 for (const key of keys) savingRef.current.delete(key);
156 setSaving(new Set(savingRef.current));
157 }
158 }
159​
160 const setModel = (value: ModelSelection | null) => void save({ defaultModelSelection: value });
161 return (
162 <SettingsPageContainer>
163 <SettingsSection
164 id={searchableSetting("project-defaults").id}
165 title="Project defaults"
166 hideTitle
167 >
168 <SettingsRow
169 title="Name"
170 aria-disabled
171 description="Select a project to change its name."
172 control={
173 <Input
174 size="sm"
175 className="w-full sm:w-64"
176 aria-label="Project name"
177 placeholder="Select a project"
178 disabled
179 />
180 }
181 />
182 <SettingsRow
183 title="Project icon"
184 aria-disabled
185 description="Select a project to change its icon."
186 control={
187 <div className="flex items-center gap-2">
188 <Button size="sm" variant="outline" disabled>
189 Choose icon
190 </Button>
191 <Button size="sm" variant="outline" disabled>
192 Choose file
193 </Button>
194 </div>
195 }
196 />
197 {scoped.length > targets.length || targets.length === 0 ? (
198 <p role="status" className="px-4 py-3 text-sm text-muted-foreground">
199 {targets.length === 0
200 ? "Connect a machine to change its project defaults."
201 : "Changes apply to connected machines only. Offline machines keep their current defaults."}
202 </p>
203 ) : null}
204 <SettingsRow
205 title="Model"
206 description="Default model for new threads. Projects can override it."
207 status={
208 targets.length === 0
209 ? undefined
210 : mixedModel
211 ? "Differs by machine"
212 : storedSelection === null
213 ? "Automatic"
214 : undefined
215 }
216 resetAction={
217 storedSelection !== null || mixedModel ? (
218 <SettingResetButton
219 label="default model"
220 disabled={disabled("defaultModelSelection")}
221 onClick={() => setModel(null)}
222 />
223 ) : null
224 }
225 control={
226 selection && activeEntry ? (
227 <fieldset
228 disabled={disabled("defaultModelSelection")}
229 className="flex min-w-0 flex-wrap items-center justify-end gap-1.5 disabled:opacity-50"
230 >
231 <ProviderModelPicker
232 activeInstanceId={selection.instanceId}
233 model={selection.model}
234 lockedProvider={null}
235 instanceEntries={entries}
236 modelOptionsByInstance={modelOptions}
237 disabled={disabled("defaultModelSelection")}
238 triggerVariant="outline"
239 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
240 getModelDisabledReason={modelDisabledReason}
241 onOpenProviderSetup={(instanceId) => {
242 if (representative)
243 void navigate({
244 to: "/settings/providers",
245 search: { environmentId: representative.environmentId, instanceId },
246 });
247 }}
248 onInstanceModelChange={(instanceId, model) =>
249 setModel(createModelSelection(instanceId, model))
250 }
251 />
252 {!mixedModel ? (
253 <TraitsPicker
254 provider={activeEntry.driverKind}
255 models={activeEntry.models}
256 model={selection.model}
257 prompt=""
258 onPromptChange={() => {}}
259 modelOptions={selection.options ?? []}
260 allowPromptInjectedEffort={false}
261 planModeEnabled={settings.planModeEnabled}
262 triggerVariant="outline"
263 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
264 onModelOptionsChange={(options) =>
265 setModel(createModelSelection(selection.instanceId, selection.model, options))
266 }
267 />
268 ) : null}
269 </fieldset>
270 ) : (
271 <span className="text-sm text-muted-foreground">No providers available</span>
272 )
273 }
274 />
275 <SettingsRow
276 id={searchableSetting("new-threads").id}
277 title="Workspace"
278 description="Where new threads start, unless overridden by the project or t3.json."
279 resetAction={
280 mixedWorkspace ||
281 serverSettings.defaultThreadEnvMode !== DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode ? (
282 <SettingResetButton
283 label="default workspace"
284 disabled={disabled("defaultThreadEnvMode")}
285 onClick={() =>
286 void save({ defaultThreadEnvMode: DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode })
287 }
288 />
289 ) : null
290 }
291 control={
292 <Select
293 disabled={disabled("defaultThreadEnvMode")}
294 value={mixedWorkspace ? "mixed" : serverSettings.defaultThreadEnvMode}
295 onValueChange={(value) => {
296 if (value === "local" || value === "worktree")
297 void save({ defaultThreadEnvMode: value });
298 }}
299 >
300 <SelectTrigger size="sm" aria-label="Default workspace">
301 <SelectValue>
302 {targets.length === 0
303 ? "Unavailable"
304 : mixedWorkspace
305 ? "Differs by machine"
306 : resolveEnvModeLabel(serverSettings.defaultThreadEnvMode)}
307 </SelectValue>
308 </SelectTrigger>
309 <SelectPopup align="end" alignItemWithTrigger={false}>
310 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
311 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
312 </SelectPopup>
313 </Select>
314 }
315 />
316 <SettingsRow
317 title="Automatically pull"
318 description="Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
319 status={mixedAutoPull ? "Differs by machine" : undefined}
320 resetAction={
321 serverSettings.defaultAutoPull || mixedAutoPull ? (
322 <SettingResetButton
323 label="default automatic pull"
324 tooltip="Reset automatic pull to off"
325 disabled={disabled("defaultAutoPull")}
326 onClick={() => void save({ defaultAutoPull: false })}
327 />
328 ) : null
329 }
330 control={
331 <Switch
332 aria-label="Default automatic pull"
333 checked={serverSettings.defaultAutoPull}
334 disabled={disabled("defaultAutoPull")}
335 onCheckedChange={(enabled) => void save({ defaultAutoPull: enabled })}
336 />
337 }
338 />
339 <SettingsRow
340 id={searchableSetting("agent-browser-access").id}
341 title="Agent browser access"
342 description="Allow agents to use the shared browser. Projects can override it."
343 resetAction={
344 mixedBrowser ||
345 serverSettings.enableAgentBrowserAccess !==
346 DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
347 <SettingResetButton
348 label="default browser access"
349 disabled={disabled("enableAgentBrowserAccess")}
350 onClick={() =>
351 void save({
352 enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
353 })
354 }
355 />
356 ) : null
357 }
358 control={
359 <Select
360 disabled={disabled("enableAgentBrowserAccess")}
361 value={
362 mixedBrowser
363 ? "mixed"
364 : serverSettings.enableAgentBrowserAccess
365 ? "enabled"
366 : "disabled"
367 }
368 onValueChange={(value) => {
369 if (value === "enabled" || value === "disabled")
370 void save({ enableAgentBrowserAccess: value === "enabled" });
371 }}
372 >
373 <SelectTrigger size="sm" aria-label="Default agent browser access">
374 <SelectValue>
375 {targets.length === 0
376 ? "Unavailable"
377 : mixedBrowser
378 ? "Differs by machine"
379 : serverSettings.enableAgentBrowserAccess
380 ? "Enabled"
381 : "Disabled"}
382 </SelectValue>
383 </SelectTrigger>
384 <SelectPopup align="end" alignItemWithTrigger={false}>
385 <SelectItem value="enabled">Enabled</SelectItem>
386 <SelectItem value="disabled">Disabled</SelectItem>
387 </SelectPopup>
388 </Select>
389 }
390 />
391 </SettingsSection>
392 <SettingsSection title="Checkout">
393 <SettingsRow
394 title="Checkout"
395 aria-disabled
396 description="Select a project to choose one of its checkouts."
397 control={
398 <Select disabled>
399 <SelectTrigger size="sm" aria-label="Checkout">
400 <SelectValue placeholder="Select a project" />
401 </SelectTrigger>
402 </Select>
403 }
404 />
405 <SettingsRow
406 title="Project grouping"
407 description="Default grouping across all machines in this client. Individual checkout overrides are preserved."
408 resetAction={
409 clientSettings.sidebarProjectGroupingMode !==
410 DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode ? (
411 <SettingResetButton
412 label="default project grouping"
413 onClick={() =>
414 void updateClientSettings({
415 sidebarProjectGroupingMode: DEFAULT_CLIENT_SETTINGS.sidebarProjectGroupingMode,
416 })
417 }
418 />
419 ) : null
420 }
421 control={
422 <Select
423 value={clientSettings.sidebarProjectGroupingMode}
424 onValueChange={(value) => {
425 if (value === "repository" || value === "repository_path" || value === "separate")
426 void updateClientSettings({ sidebarProjectGroupingMode: value });
427 }}
428 >
429 <SelectTrigger size="sm" aria-label="Default project grouping">
430 <SelectValue>
431 {PROJECT_GROUPING_MODE_LABELS[clientSettings.sidebarProjectGroupingMode]}
432 </SelectValue>
433 </SelectTrigger>
434 <SelectPopup align="end" alignItemWithTrigger={false}>
435 <SelectItem value="repository">
436 {PROJECT_GROUPING_MODE_LABELS.repository}
437 </SelectItem>
438 <SelectItem value="repository_path">
439 {PROJECT_GROUPING_MODE_LABELS.repository_path}
440 </SelectItem>
441 <SelectItem value="separate">{PROJECT_GROUPING_MODE_LABELS.separate}</SelectItem>
442 </SelectPopup>
443 </Select>
444 }
445 />
446 <SettingsRow
447 title="Remove checkout"
448 aria-disabled
449 description="Select a project to remove one of its checkouts."
450 control={
451 <Button size="sm" variant="destructive-outline" disabled>
452 <Trash2Icon className="size-3.5" />
453 Remove checkout
454 </Button>
455 }
456 />
457 </SettingsSection>
458 <ProjectDefaultActionsSettings environmentId={environmentId} />
459 <SettingsSection title="Danger">
460 <SettingsRow
461 title="Remove project"
462 aria-disabled
463 description="Select a project to remove its entries and threads. Files on disk are not touched."
464 control={
465 <Button size="sm" variant="destructive-outline" disabled>
466 <Trash2Icon />
467 Remove project
468 </Button>
469 }
470 />
471 </SettingsSection>
472 </SettingsPageContainer>
473 );