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