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