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

ProjectDefaultsSettings.tsx

586 lines23.6 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 planModeEnabled={settings.planModeEnabled}
190 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
191 onModelOptionsChange={(options) =>
192 setModel(createModelSelection(selection.instanceId, selection.model, options))
193 }
194 />
195 ) : null}
196 </div>
197 ) : (
198 <span className="text-sm text-muted-foreground">
199 {mixedModel ? "Mixed" : "No providers available"}
200 </span>
201 )
202 }
203 />
204 );
205 const workspaceRow = (
206 <SettingsRow
207 serverScoped
208 settingKeys={["defaultThreadEnvMode"]}
209 mixed={mixedWorkspace}
210 id={searchableSetting("new-threads").id}
211 title="Workspace"
212 description={
213 isProjectScope
214 ? "Where new threads in this project start."
215 : "Where new threads start. Projects and their t3.json can override it."
216 }
217 resetAction={
218 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
219 <SettingResetButton
220 label="default workspace"
221 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
222 />
223 ) : null
224 }
225 control={
226 <Select
227 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
228 onValueChange={(value) => {
229 if (value === "local" || value === "worktree")
230 updateSettings({ defaultThreadEnvMode: value });
231 }}
232 >
233 <SelectTrigger size="sm" aria-label="Default workspace">
234 <SelectValue>
235 {(value: string | null) =>
236 value === "local" || value === "worktree"
237 ? resolveEnvModeLabel(value)
238 : unavailable
239 ? "Unavailable"
240 : "Mixed"
241 }
242 </SelectValue>
243 </SelectTrigger>
244 <SelectPopup align="end" alignItemWithTrigger={false}>
245 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
246 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
247 </SelectPopup>
248 </Select>
249 }
250 />
251 );
252​
253 const fallbackRow = !isProjectScope ? (
254 <SettingsRow
255 serverScoped
256 settingKeys={["fallbackModelSelection"]}
257 mixed={mixedFallback}
258 {...searchableSetting("fallback-model")}
259 description="Used for new threads when the default model's provider is out of usage."
260 resetAction={
261 mixedFallback || settings.fallbackModelSelection !== null ? (
262 <SettingResetButton
263 label="fallback model"
264 onClick={() => updateSettings({ fallbackModelSelection: null })}
265 />
266 ) : null
267 }
268 control={
269 fallbackSelection ? (
270 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
271 <ProviderModelPicker
272 environmentId={representative?.environmentId ?? null}
273 activeInstanceId={fallbackSelection.instanceId}
274 model={fallbackSelection.model}
275 lockedProvider={null}
276 instanceEntries={entries}
277 modelOptionsByInstance={fallbackModelOptions}
278 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
279 triggerAriaLabel="Fallback model"
280 {...(mixedFallback
281 ? { triggerLabel: "Mixed" }
282 : settings.fallbackModelSelection === null
283 ? { triggerLabel: "None" }
284 : {})}
285 getModelDisabledReason={modelDisabledReason}
286 onInstanceModelChange={(instanceId, model) => {
287 const reason = modelDisabledReason(instanceId, model);
288 if (reason) {
289 toastManager.add({
290 type: "error",
291 title: "Fallback model not saved",
292 description: reason,
293 });
294 return;
295 }
296 updateSettings({ fallbackModelSelection: createModelSelection(instanceId, model) });
297 }}
298 />
299 {settings.fallbackModelSelection !== null && fallbackEntry && !mixedFallback ? (
300 <TraitsPicker
301 provider={fallbackEntry.driverKind}
302 models={fallbackEntry.models}
303 model={fallbackSelection.model}
304 modelOptions={fallbackSelection.options ?? []}
305 allowPromptInjectedEffort={false}
306 planModeEnabled={settings.planModeEnabled}
307 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
308 onModelOptionsChange={(options) =>
309 updateSettings({
310 fallbackModelSelection: createModelSelection(
311 fallbackSelection.instanceId,
312 fallbackSelection.model,
313 options,
314 ),
315 })
316 }
317 />
318 ) : null}
319 </div>
320 ) : (
321 <span className="text-sm text-muted-foreground">No providers available</span>
322 )
323 }
324 />
325 ) : null;
326​
327 return (
328 <SettingsSection
329 id={category === "source-control" ? "source-control-defaults" : "project-defaults"}
330 title={category === "source-control" ? "Repositories" : "New threads"}
331 >
332 {category === "project" ? (
333 <>
334 {modelRow}
335 {fallbackRow}
336 {workspaceRow}
337 </>
338 ) : category === "general" ? (
339 <>
340 {modelRow}
341 {fallbackRow}
342 <SettingsRow
343 serverScoped
344 settingKeys={["defaultRuntimeMode"]}
345 mixed={mixedPermissions}
346 {...searchableSetting("default-permissions")}
347 description={
348 isProjectScope
349 ? "Permissions for new threads in this project."
350 : "Default permissions for new threads. Projects can override them."
351 }
352 resetAction={
353 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
354 <SettingResetButton
355 label="default permissions"
356 onClick={() =>
357 updateSettings({
358 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
359 })
360 }
361 />
362 ) : null
363 }
364 control={
365 <Select
366 value={mixedPermissions ? null : settings.defaultRuntimeMode}
367 onValueChange={(value) => {
368 if (value) updateSettings({ defaultRuntimeMode: value });
369 }}
370 >
371 <SelectTrigger size="sm" aria-label="Default permissions">
372 {!mixedPermissions && (
373 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
374 )}
375 <SelectValue>
376 {mixedPermissions
377 ? "Mixed"
378 : runtimeModeConfig[settings.defaultRuntimeMode].label}
379 </SelectValue>
380 </SelectTrigger>
381 <SelectPopup align="end" alignItemWithTrigger={false}>
382 {runtimeModeOptions.map((mode) => {
383 const option = runtimeModeConfig[mode];
384 const Icon = option.icon;
385 const managedReason = firstManagedDenial(
386 connectedEnvironments.map(
387 (environment) => environment.serverConfig?.managedPolicy,
388 ),
389 (policy) => managedRuntimeModeDenial(policy, mode),
390 );
391 return (
392 <SelectItem
393 key={mode}
394 value={mode}
395 disabled={managedReason !== undefined}
396 className="min-w-64"
397 >
398 <div className="grid gap-0.5">
399 <span className="inline-flex items-center gap-1.5 font-medium">
400 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
401 {option.label}
402 </span>
403 <span className="text-xs leading-4 text-muted-foreground">
404 {managedReason ?? option.description}
405 </span>
406 </div>
407 </SelectItem>
408 );
409 })}
410 </SelectPopup>
411 </Select>
412 }
413 />
414 {workspaceRow}
415 </>
416 ) : (
417 <>
418 <SettingsRow
419 serverScoped
420 settingKeys={["defaultAutoPull"]}
421 mixed={mixedAutoPull}
422 id="automatic-pull"
423 title="Automatically pull"
424 description={
425 isProjectScope
426 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
427 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
428 }
429 resetAction={
430 settings.defaultAutoPull ? (
431 <SettingResetButton
432 label="default automatic pull"
433 tooltip="Reset automatic pull to off"
434 onClick={() => updateSettings({ defaultAutoPull: false })}
435 />
436 ) : null
437 }
438 control={
439 <Switch
440 aria-label="Default automatic pull"
441 mixed={mixedAutoPull}
442 checked={mixedAutoPull ? false : settings.defaultAutoPull}
443 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
444 />
445 }
446 />
447 <SettingsRow
448 serverScoped
449 settingKeys={["removeAgentCreditsOnMerge"]}
450 mixed={mixedAgentCredits}
451 {...searchableSetting("remove-agent-credits-on-merge")}
452 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."
453 resetAction={
454 settings.removeAgentCreditsOnMerge ? (
455 <SettingResetButton
456 label="agent credit removal"
457 tooltip="Keep agent credits"
458 onClick={() => updateSettings({ removeAgentCreditsOnMerge: false })}
459 />
460 ) : null
461 }
462 control={
463 <Switch
464 aria-label="Remove agent credits when merging"
465 mixed={mixedAgentCredits}
466 checked={mixedAgentCredits ? false : settings.removeAgentCreditsOnMerge}
467 onCheckedChange={(enabled) =>
468 updateSettings({ removeAgentCreditsOnMerge: enabled })
469 }
470 />
471 }
472 />
473 <SettingsRow
474 serverScoped
475 settingKeys={["pullRequestMergeMethod"]}
476 mixed={mixedMergeMethod}
477 {...searchableSetting("pull-request-merge-method")}
478 description={
479 isProjectScope
480 ? "Pull requests in this project start with this method."
481 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
482 }
483 resetAction={
484 settings.pullRequestMergeMethod !== null ? (
485 <SettingResetButton
486 label="default merge method"
487 tooltip="Reset to last selected"
488 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
489 />
490 ) : null
491 }
492 control={
493 <Select
494 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
495 onValueChange={(value) => {
496 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
497 else if (value === "merge" || value === "squash" || value === "rebase")
498 updateSettings({ pullRequestMergeMethod: value });
499 }}
500 >
501 <SelectTrigger size="sm" aria-label="Default pull request merge method">
502 <SelectValue>
503 {(value: string | null) =>
504 value === "merge" || value === "squash" || value === "rebase"
505 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
506 : value === "last"
507 ? "Last selected"
508 : "Mixed"
509 }
510 </SelectValue>
511 </SelectTrigger>
512 <SelectPopup align="end" alignItemWithTrigger={false}>
513 <SelectItem value="last">Last selected</SelectItem>
514 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
515 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
516 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
517 </SelectPopup>
518 </Select>
519 }
520 />
521 </>
522 )}
523 </SettingsSection>
524 );
526​
527export function WorktreeSubmodulesRow() {
528 const { scope, target, connectedEnvironments } = useSettingsScope();
529 const settings = useScopedSettings();
530 const updateSettings = useUpdateScopedSettings();
531 const mixedSubmodules = useScopedSettingsMixed(["worktreeSubmodules"]);
532 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
533 const unavailable = connectedEnvironments.length === 0;
534 const effective = target
535 ? resolveProjectSettings(target.settings, null, null, null).settings
536 : null;
537​
538 return (
539 <SettingsRow
540 serverScoped
541 settingKeys={["worktreeSubmodules"]}
542 mixed={mixedSubmodules}
543 {...searchableSetting("worktree-submodules")}
544 description={
545 isProjectScope
546 ? "How new worktrees in this project populate git submodules."
547 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
548 }
549 resetAction={
550 !isProjectScope && settings.worktreeSubmodules !== null ? (
551 <SettingResetButton
552 label="worktree submodules"
553 onClick={() => updateSettings({ worktreeSubmodules: null })}
554 />
555 ) : null
556 }
557 control={
558 <Select
559 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
560 onValueChange={(value) => {
561 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
562 }}
563 >
564 <SelectTrigger size="sm" aria-label="Worktree submodules">
565 <SelectValue>
566 {(value: string | null) =>
567 isWorktreeSubmodules(value)
568 ? WORKTREE_SUBMODULES_LABELS[value]
569 : unavailable
570 ? "Unavailable"
571 : "Mixed"
572 }
573 </SelectValue>
574 </SelectTrigger>
575 <SelectPopup align="end" alignItemWithTrigger={false}>
576 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
577 <SelectItem key={option} value={option}>
578 {WORKTREE_SUBMODULES_LABELS[option]}
579 </SelectItem>
580 ))}
581 </SelectPopup>
582 </Select>
583 }
584 />
585 );