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

ProjectDefaultsSettings.tsx

584 lines23.5 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 type ModelSelection,
4 type WorktreeSubmodules,
5 managedRuntimeModeDenial,
6} from "@t3tools/contracts";
7import { createModelSelection } from "@t3tools/shared/model";
8import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
9import { useNavigate } from "@tanstack/react-router";
10​
11import { useClientSettings } from "../../hooks/useSettings";
12import {
13 defaultModelSelectionsAreMixed,
14 getCustomModelOptionsByInstance,
15 resolveEffectiveDefaultModelSelection,
16} from "../../modelSelection";
17import {
18 providerInstanceEntriesFor,
19 resolveDefaultProviderModelSelection,
20 resolveProjectDefaultProviderModelSelection,
21} from "../../providerInstances";
22import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
23import { firstManagedDenial } from "../../state/managedPolicy";
24import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
25import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
26import { ProviderModelPicker } from "../chat/ProviderModelPicker";
27import { runtimeModeConfig, runtimeModeOptions } from "../chat/runtimeModeConfig";
28import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
29import { TraitsPicker } from "../chat/TraitsPicker";
30import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31import { toastManager } from "../ui/toast";
32import { Switch } from "../ui/switch";
33import type { ProjectSettingsCategory } from "./ProjectSettingsPanel";
34import { searchableSetting } from "./settingsSearch";
35import { useSettingsScope } from "./SettingsScopeContext";
36import {
37 SETTINGS_PICKER_TRIGGER_CLASSNAME,
38 SettingResetButton,
39 SettingsRow,
40 SettingsSection,
41} from "./settingsLayout";
42import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
43import {
44 useScopedSettings,
45 useScopedSettingsMixed,
46 useScopedSettingSource,
47 useUpdateScopedSettings,
48} from "./useScopedSettings";
49​
50const WORKTREE_SUBMODULES_OPTIONS = ["recursive", "top-level", "none"] as const;
51function isWorktreeSubmodules(value: string | null): value is WorktreeSubmodules {
52 return value !== null && (WORKTREE_SUBMODULES_OPTIONS as readonly string[]).includes(value);
54​
55export function ProjectDefaultsSettings({ category }: { category: ProjectSettingsCategory }) {
56 const { scope, target, targets, connectedEnvironments } = useSettingsScope();
57 const settings = useScopedSettings();
58 const clientSettings = useClientSettings();
59 const updateSettings = useUpdateScopedSettings();
60 const navigate = useNavigate();
61 const { environments } = useEnvironments();
62 const providersByEnvironment = useEnvironmentProviders();
63 const representative = target
64 ? environments.find((environment) => environment.environmentId === target.environmentId)
65 : undefined;
66 const providers =
67 (representative?.serverConfig
68 ? providersByEnvironment.get(representative.environmentId)
69 : undefined) ?? EMPTY_SERVER_PROVIDERS;
70 const storedSelection =
71 settings.defaultModelSelection === null
72 ? resolveProjectDefaultProviderModelSelection(providers, settings, target?.projectId ?? null)
73 : resolveDefaultProviderModelSelection(providers, settings.defaultModelSelection);
74 const selection = storedSelection
75 ? resolveEffectiveDefaultModelSelection(settings, providers, storedSelection)
76 : null;
77 const entries = providerInstanceEntriesFor(providers, settings, target?.projectId ?? null);
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 = defaultModelSelectionsAreMixed(
86 clientSettings,
87 targets.map((candidate) => ({
88 projectId: candidate.projectId,
89 settings: candidate.settings,
90 providers: providersByEnvironment.get(candidate.environmentId) ?? EMPTY_SERVER_PROVIDERS,
91 })),
92 );
93 const automaticModel =
94 targets.length > 0 &&
95 targets.every((candidate) => candidate.settings.defaultModelSelection === null);
96 const mixedFallback = useScopedSettingsMixed(["fallbackModelSelection"]);
97 const fallbackSelection = settings.fallbackModelSelection ?? selection;
98 const fallbackEntry = entries.find((entry) => entry.instanceId === fallbackSelection?.instanceId);
99 const fallbackModelOptions = getCustomModelOptionsByInstance(
100 settings,
101 providers,
102 fallbackSelection?.instanceId,
103 fallbackSelection?.model,
104 );
105 const mixedPermissions = useScopedSettingsMixed(["defaultRuntimeMode"]);
106 const PermissionIcon = runtimeModeConfig[settings.defaultRuntimeMode].icon;
107 const mixedWorkspace = useScopedSettingsMixed(["defaultThreadEnvMode"]);
108 const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]);
109 const mixedAgentCredits = useScopedSettingsMixed(["removeAgentCreditsOnMerge"]);
110 const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]);
111 const modelSource = useScopedSettingSource(["defaultModelSelection"]);
112 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
113 const unavailable = connectedEnvironments.length === 0;
114 const effective = target
115 ? resolveProjectSettings(target.settings, null, null, null).settings
116 : null;
117​
118 const modelDisabledReason = useScopedModelDisabledReason(settings, entries);
119 const effortDisabledReason = selection
120 ? modelDisabledReason(selection.instanceId, selection.model)
121 : null;
122​
123 const setModel = (value: ModelSelection | null) => {
124 const reason = value ? modelDisabledReason(value.instanceId, value.model) : null;
125 if (reason) {
126 toastManager.add({ type: "error", title: "Default model not saved", description: reason });
127 return;
128 }
129 updateSettings({ defaultModelSelection: value });
130 };
131​
132 const modelRow = (
133 <SettingsRow
134 serverScoped
135 settingKeys={["defaultModelSelection"]}
136 mixed={mixedModel}
137 id="default-model"
138 title="Model"
139 description={
140 isProjectScope
141 ? "Model for new threads in this project."
142 : !unavailable && modelSource !== "project" && automaticModel
143 ? "Default model for new threads, selected automatically. Projects can override it."
144 : "Default model for new threads. Projects can override it."
145 }
146 status={
147 mixedModel
148 ? `${automaticModel ? "Automatic defaults differ." : "Defaults differ."} Select one environment or choose a shared model to edit effort.`
149 : effortDisabledReason
150 }
151 resetAction={
152 settings.defaultModelSelection !== null ? (
153 <SettingResetButton label="default model" onClick={() => setModel(null)} />
154 ) : null
155 }
156 control={
157 selection && activeEntry ? (
158 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
159 <ProviderModelPicker
160 environmentId={representative?.environmentId ?? null}
161 activeInstanceId={selection.instanceId}
162 model={selection.model}
163 lockedProvider={null}
164 instanceEntries={entries}
165 modelOptionsByInstance={modelOptions}
166 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
167 {...(mixedModel
168 ? { triggerLabel: automaticModel ? "Automatic (mixed)" : "Mixed" }
169 : {})}
170 getModelDisabledReason={modelDisabledReason}
171 onOpenProviderSetup={(instanceId) => {
172 if (representative)
173 void navigate({
174 to: "/settings/providers",
175 search: { environmentId: representative.environmentId, instanceId },
176 });
177 }}
178 onInstanceModelChange={(instanceId, model) =>
179 setModel(createModelSelection(instanceId, model))
180 }
181 />
182 {!mixedModel && !effortDisabledReason ? (
183 <TraitsPicker
184 provider={activeEntry.driverKind}
185 models={activeEntry.models}
186 model={selection.model}
187 modelOptions={selection.options ?? []}
188 allowPromptInjectedEffort={false}
189 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
190 onModelOptionsChange={(options) =>
191 setModel(createModelSelection(selection.instanceId, selection.model, options))
192 }
193 />
194 ) : null}
195 </div>
196 ) : (
197 <span className="text-sm text-muted-foreground">
198 {mixedModel ? "Mixed" : "No providers available"}
199 </span>
200 )
201 }
202 />
203 );
204 const workspaceRow = (
205 <SettingsRow
206 serverScoped
207 settingKeys={["defaultThreadEnvMode"]}
208 mixed={mixedWorkspace}
209 id={searchableSetting("new-threads").id}
210 title="Workspace"
211 description={
212 isProjectScope
213 ? "Where new threads in this project start."
214 : "Where new threads start. Projects and their t3.json can override it."
215 }
216 resetAction={
217 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
218 <SettingResetButton
219 label="default workspace"
220 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
221 />
222 ) : null
223 }
224 control={
225 <Select
226 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
227 onValueChange={(value) => {
228 if (value === "local" || value === "worktree")
229 updateSettings({ defaultThreadEnvMode: value });
230 }}
231 >
232 <SelectTrigger size="sm" aria-label="Default workspace">
233 <SelectValue>
234 {(value: string | null) =>
235 value === "local" || value === "worktree"
236 ? resolveEnvModeLabel(value)
237 : unavailable
238 ? "Unavailable"
239 : "Mixed"
240 }
241 </SelectValue>
242 </SelectTrigger>
243 <SelectPopup align="end" alignItemWithTrigger={false}>
244 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
245 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
246 </SelectPopup>
247 </Select>
248 }
249 />
250 );
251​
252 const fallbackRow = !isProjectScope ? (
253 <SettingsRow
254 serverScoped
255 settingKeys={["fallbackModelSelection"]}
256 mixed={mixedFallback}
257 {...searchableSetting("fallback-model")}
258 description="Used for new threads when the default model's provider is out of usage."
259 resetAction={
260 mixedFallback || settings.fallbackModelSelection !== null ? (
261 <SettingResetButton
262 label="fallback model"
263 onClick={() => updateSettings({ fallbackModelSelection: null })}
264 />
265 ) : null
266 }
267 control={
268 fallbackSelection ? (
269 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
270 <ProviderModelPicker
271 environmentId={representative?.environmentId ?? null}
272 activeInstanceId={fallbackSelection.instanceId}
273 model={fallbackSelection.model}
274 lockedProvider={null}
275 instanceEntries={entries}
276 modelOptionsByInstance={fallbackModelOptions}
277 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
278 triggerAriaLabel="Fallback model"
279 {...(mixedFallback
280 ? { triggerLabel: "Mixed" }
281 : settings.fallbackModelSelection === null
282 ? { triggerLabel: "None" }
283 : {})}
284 getModelDisabledReason={modelDisabledReason}
285 onInstanceModelChange={(instanceId, model) => {
286 const reason = modelDisabledReason(instanceId, model);
287 if (reason) {
288 toastManager.add({
289 type: "error",
290 title: "Fallback model not saved",
291 description: reason,
292 });
293 return;
294 }
295 updateSettings({ fallbackModelSelection: createModelSelection(instanceId, model) });
296 }}
297 />
298 {settings.fallbackModelSelection !== null && fallbackEntry && !mixedFallback ? (
299 <TraitsPicker
300 provider={fallbackEntry.driverKind}
301 models={fallbackEntry.models}
302 model={fallbackSelection.model}
303 modelOptions={fallbackSelection.options ?? []}
304 allowPromptInjectedEffort={false}
305 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
306 onModelOptionsChange={(options) =>
307 updateSettings({
308 fallbackModelSelection: createModelSelection(
309 fallbackSelection.instanceId,
310 fallbackSelection.model,
311 options,
312 ),
313 })
314 }
315 />
316 ) : null}
317 </div>
318 ) : (
319 <span className="text-sm text-muted-foreground">No providers available</span>
320 )
321 }
322 />
323 ) : null;
324​
325 return (
326 <SettingsSection
327 id={category === "source-control" ? "source-control-defaults" : "project-defaults"}
328 title={category === "source-control" ? "Repositories" : "New threads"}
329 >
330 {category === "project" ? (
331 <>
332 {modelRow}
333 {fallbackRow}
334 {workspaceRow}
335 </>
336 ) : category === "general" ? (
337 <>
338 {modelRow}
339 {fallbackRow}
340 <SettingsRow
341 serverScoped
342 settingKeys={["defaultRuntimeMode"]}
343 mixed={mixedPermissions}
344 {...searchableSetting("default-permissions")}
345 description={
346 isProjectScope
347 ? "Permissions for new threads in this project."
348 : "Default permissions for new threads. Projects can override them."
349 }
350 resetAction={
351 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
352 <SettingResetButton
353 label="default permissions"
354 onClick={() =>
355 updateSettings({
356 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
357 })
358 }
359 />
360 ) : null
361 }
362 control={
363 <Select
364 value={mixedPermissions ? null : settings.defaultRuntimeMode}
365 onValueChange={(value) => {
366 if (value) updateSettings({ defaultRuntimeMode: value });
367 }}
368 >
369 <SelectTrigger size="sm" aria-label="Default permissions">
370 {!mixedPermissions && (
371 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
372 )}
373 <SelectValue>
374 {mixedPermissions
375 ? "Mixed"
376 : runtimeModeConfig[settings.defaultRuntimeMode].label}
377 </SelectValue>
378 </SelectTrigger>
379 <SelectPopup align="end" alignItemWithTrigger={false}>
380 {runtimeModeOptions.map((mode) => {
381 const option = runtimeModeConfig[mode];
382 const Icon = option.icon;
383 const managedReason = firstManagedDenial(
384 connectedEnvironments.map(
385 (environment) => environment.serverConfig?.managedPolicy,
386 ),
387 (policy) => managedRuntimeModeDenial(policy, mode),
388 );
389 return (
390 <SelectItem
391 key={mode}
392 value={mode}
393 disabled={managedReason !== undefined}
394 className="min-w-64"
395 >
396 <div className="grid gap-0.5">
397 <span className="inline-flex items-center gap-1.5 font-medium">
398 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
399 {option.label}
400 </span>
401 <span className="text-xs leading-4 text-muted-foreground">
402 {managedReason ?? option.description}
403 </span>
404 </div>
405 </SelectItem>
406 );
407 })}
408 </SelectPopup>
409 </Select>
410 }
411 />
412 {workspaceRow}
413 </>
414 ) : (
415 <>
416 <SettingsRow
417 serverScoped
418 settingKeys={["defaultAutoPull"]}
419 mixed={mixedAutoPull}
420 id="automatic-pull"
421 title="Automatically pull"
422 description={
423 isProjectScope
424 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
425 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
426 }
427 resetAction={
428 settings.defaultAutoPull ? (
429 <SettingResetButton
430 label="default automatic pull"
431 tooltip="Reset automatic pull to off"
432 onClick={() => updateSettings({ defaultAutoPull: false })}
433 />
434 ) : null
435 }
436 control={
437 <Switch
438 aria-label="Default automatic pull"
439 mixed={mixedAutoPull}
440 checked={mixedAutoPull ? false : settings.defaultAutoPull}
441 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
442 />
443 }
444 />
445 <SettingsRow
446 serverScoped
447 settingKeys={["removeAgentCreditsOnMerge"]}
448 mixed={mixedAgentCredits}
449 {...searchableSetting("remove-agent-credits-on-merge")}
450 description="Remove recognized agent credit lines from merge and squash messages on hosts that support it, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits."
451 resetAction={
452 settings.removeAgentCreditsOnMerge ? (
453 <SettingResetButton
454 label="agent credit removal"
455 tooltip="Keep agent credits"
456 onClick={() => updateSettings({ removeAgentCreditsOnMerge: false })}
457 />
458 ) : null
459 }
460 control={
461 <Switch
462 aria-label="Remove agent credits when merging"
463 mixed={mixedAgentCredits}
464 checked={mixedAgentCredits ? false : settings.removeAgentCreditsOnMerge}
465 onCheckedChange={(enabled) =>
466 updateSettings({ removeAgentCreditsOnMerge: enabled })
467 }
468 />
469 }
470 />
471 <SettingsRow
472 serverScoped
473 settingKeys={["pullRequestMergeMethod"]}
474 mixed={mixedMergeMethod}
475 {...searchableSetting("pull-request-merge-method")}
476 description={
477 isProjectScope
478 ? "Pull requests in this project start with this method."
479 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
480 }
481 resetAction={
482 settings.pullRequestMergeMethod !== null ? (
483 <SettingResetButton
484 label="default merge method"
485 tooltip="Reset to last selected"
486 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
487 />
488 ) : null
489 }
490 control={
491 <Select
492 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
493 onValueChange={(value) => {
494 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
495 else if (value === "merge" || value === "squash" || value === "rebase")
496 updateSettings({ pullRequestMergeMethod: value });
497 }}
498 >
499 <SelectTrigger size="sm" aria-label="Default pull request merge method">
500 <SelectValue>
501 {(value: string | null) =>
502 value === "merge" || value === "squash" || value === "rebase"
503 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
504 : value === "last"
505 ? "Last selected"
506 : "Mixed"
507 }
508 </SelectValue>
509 </SelectTrigger>
510 <SelectPopup align="end" alignItemWithTrigger={false}>
511 <SelectItem value="last">Last selected</SelectItem>
512 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
513 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
514 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
515 </SelectPopup>
516 </Select>
517 }
518 />
519 </>
520 )}
521 </SettingsSection>
522 );
524​
525export function WorktreeSubmodulesRow() {
526 const { scope, target, connectedEnvironments } = useSettingsScope();
527 const settings = useScopedSettings();
528 const updateSettings = useUpdateScopedSettings();
529 const mixedSubmodules = useScopedSettingsMixed(["worktreeSubmodules"]);
530 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
531 const unavailable = connectedEnvironments.length === 0;
532 const effective = target
533 ? resolveProjectSettings(target.settings, null, null, null).settings
534 : null;
535​
536 return (
537 <SettingsRow
538 serverScoped
539 settingKeys={["worktreeSubmodules"]}
540 mixed={mixedSubmodules}
541 {...searchableSetting("worktree-submodules")}
542 description={
543 isProjectScope
544 ? "How new worktrees in this project populate git submodules."
545 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
546 }
547 resetAction={
548 !isProjectScope && settings.worktreeSubmodules !== null ? (
549 <SettingResetButton
550 label="worktree submodules"
551 onClick={() => updateSettings({ worktreeSubmodules: null })}
552 />
553 ) : null
554 }
555 control={
556 <Select
557 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
558 onValueChange={(value) => {
559 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
560 }}
561 >
562 <SelectTrigger size="sm" aria-label="Worktree submodules">
563 <SelectValue>
564 {(value: string | null) =>
565 isWorktreeSubmodules(value)
566 ? WORKTREE_SUBMODULES_LABELS[value]
567 : unavailable
568 ? "Unavailable"
569 : "Mixed"
570 }
571 </SelectValue>
572 </SelectTrigger>
573 <SelectPopup align="end" alignItemWithTrigger={false}>
574 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
575 <SelectItem key={option} value={option}>
576 {WORKTREE_SUBMODULES_LABELS[option]}
577 </SelectItem>
578 ))}
579 </SelectPopup>
580 </Select>
581 }
582 />
583 );