Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 type ModelSelection,
4 type ProviderInstanceId,
5 type WorktreeSubmodules,
6} from "@t3tools/contracts";
7import { createModelSelection } from "@t3tools/shared/model";
8import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
9import { useNavigate } from "@tanstack/react-router";
10
11import { getCustomModelOptionsByInstance } from "../../modelSelection";
12import {
13 applyProviderInstanceSettings,
14 deriveProviderInstanceEntries,
15 resolveDefaultProviderModelSelection,
16 sortProviderInstanceEntries,
17} from "../../providerInstances";
18import { useEnvironments } from "../../state/environments";
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 type { ProjectSettingsCategory } from "./ProjectSettingsPanel";
29import { searchableSetting } from "./settingsSearch";
30import { useSettingsScope } from "./SettingsScopeContext";
31import {
32 SETTINGS_PICKER_TRIGGER_CLASSNAME,
33 SettingResetButton,
34 SettingsRow,
35 SettingsSection,
36} from "./settingsLayout";
37import {
38 useScopedSettings,
39 useScopedSettingsMixed,
40 useScopedSettingSource,
41 useUpdateScopedSettings,
42} from "./useScopedSettings";
43
44/**
45 * Rows for the settings a project may override. The same rows edit
46 * environment defaults at an environment scope and project overrides at a
47 * project or checkout scope; the scoped hooks route the write.
48 */
49const WORKTREE_SUBMODULES_OPTIONS = ["recursive", "top-level", "none"] as const;
50function isWorktreeSubmodules(value: string | null): value is WorktreeSubmodules {
51 return value !== null && (WORKTREE_SUBMODULES_OPTIONS as readonly string[]).includes(value);
52}
53
54export function ProjectDefaultsSettings({ category }: { category: ProjectSettingsCategory }) {
55 const { scope, target, targets, connectedEnvironments } = useSettingsScope();
56 const settings = useScopedSettings();
57 const updateSettings = useUpdateScopedSettings();
58 const navigate = useNavigate();
59 const { environments } = useEnvironments();
60 const representative = target
61 ? environments.find((environment) => environment.environmentId === target.environmentId)
62 : undefined;
63 const providers = representative?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS;
64 const selection = resolveDefaultProviderModelSelection(providers, settings.defaultModelSelection);
65 const entries = sortProviderInstanceEntries(
66 applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
67 );
68 const modelOptions = getCustomModelOptionsByInstance(
69 settings,
70 providers,
71 selection?.instanceId,
72 selection?.model,
73 );
74 const activeEntry = entries.find((entry) => entry.instanceId === selection?.instanceId);
75 const mixedModel = useScopedSettingsMixed(["defaultModelSelection"]);
76 const mixedPermissions = useScopedSettingsMixed(["defaultRuntimeMode"]);
77 const PermissionIcon = runtimeModeConfig[settings.defaultRuntimeMode].icon;
78 const mixedWorkspace = useScopedSettingsMixed(["defaultThreadEnvMode"]);
79 const mixedSubmodules = useScopedSettingsMixed(["worktreeSubmodules"]);
80 const mixedBrowser = useScopedSettingsMixed(["enableAgentBrowserAccess"]);
81 const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]);
82 const mixedAgentCredits = useScopedSettingsMixed(["removeAgentCreditsOnMerge"]);
83 const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]);
84 const modelSource = useScopedSettingSource(["defaultModelSelection"]);
85 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
86 const unavailable = connectedEnvironments.length === 0;
87 // File-backed keys show their effective value; the target already carries
88 // the checkout's t3.json, and a null file here only fills the built-in.
89 // The reset arrow beside the title clears the tier (SettingsRow handles a
90 // project override, the environment value is cleared here), so the picker
91 // has no "inherit" item.
92 const effective = target
93 ? resolveProjectSettings(target.settings, null, null, null).settings
94 : null;
95
96 function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
97 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
98 for (const candidate of targets) {
99 const environment = environments.find(
100 (entry) => entry.environmentId === candidate.environmentId,
101 );
102 const config = environment?.serverConfig;
103 if (!config) continue;
104 const entry = applyProviderInstanceSettings(
105 deriveProviderInstanceEntries(config.providers),
106 candidate.settings,
107 ).find((option) => option.instanceId === instanceId);
108 const options = getCustomModelOptionsByInstance(
109 { ...settings, ...candidate.settings },
110 config.providers,
111 ).get(instanceId);
112 if (
113 !entry?.enabled ||
114 !entry.isAvailable ||
115 entry.driverKind !== sourceEntry?.driverKind ||
116 !options?.some((option) => option.slug === model && !option.isUnavailable)
117 ) {
118 return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
119 }
120 }
121 return null;
122 }
123
124 const setModel = (value: ModelSelection | null) => {
125 const reason = value ? modelDisabledReason(value.instanceId, value.model) : null;
126 if (reason) {
127 toastManager.add({ type: "error", title: "Default model not saved", description: reason });
128 return;
129 }
130 updateSettings({ defaultModelSelection: value });
131 };
132
133 const modelRow = (
134 <SettingsRow
135 serverScoped
136 settingKeys={["defaultModelSelection"]}
137 mixed={mixedModel}
138 id="default-model"
139 title="Model"
140 description={
141 isProjectScope
142 ? "Model for new threads in this project."
143 : "Default model for new threads. Projects can override it."
144 }
145 status={
146 unavailable || mixedModel || modelSource === "project"
147 ? undefined
148 : settings.defaultModelSelection === null
149 ? "Automatic"
150 : undefined
151 }
152 resetAction={
153 settings.defaultModelSelection !== null ? (
154 <SettingResetButton label="default model" onClick={() => setModel(null)} />
155 ) : null
156 }
157 control={
158 selection && activeEntry ? (
159 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
160 <ProviderModelPicker
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 ? { triggerLabel: "Mixed" } : {})}
168 getModelDisabledReason={modelDisabledReason}
169 onOpenProviderSetup={(instanceId) => {
170 if (representative)
171 void navigate({
172 to: "/settings/providers",
173 search: { environmentId: representative.environmentId, instanceId },
174 });
175 }}
176 onInstanceModelChange={(instanceId, model) =>
177 setModel(createModelSelection(instanceId, model))
178 }
179 />
180 {!mixedModel ? (
181 <TraitsPicker
182 provider={activeEntry.driverKind}
183 models={activeEntry.models}
184 model={selection.model}
185 prompt=""
186 onPromptChange={() => {}}
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">No providers available</span>
199 )
200 }
201 />
202 );
203 const workspaceRow = (
204 <SettingsRow
205 serverScoped
206 settingKeys={["defaultThreadEnvMode"]}
207 mixed={mixedWorkspace}
208 id={searchableSetting("new-threads").id}
209 title="Workspace"
210 description={
211 isProjectScope
212 ? "Where new threads in this project start."
213 : "Where new threads start. Projects and their t3.json can override it."
214 }
215 resetAction={
216 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
217 <SettingResetButton
218 label="default workspace"
219 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
220 />
221 ) : null
222 }
223 control={
224 <Select
225 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
226 onValueChange={(value) => {
227 if (value === "local" || value === "worktree")
228 updateSettings({ defaultThreadEnvMode: value });
229 }}
230 >
231 <SelectTrigger size="sm" aria-label="Default workspace">
232 <SelectValue>
233 {(value: string | null) =>
234 value === "local" || value === "worktree"
235 ? resolveEnvModeLabel(value)
236 : unavailable
237 ? "Unavailable"
238 : "Mixed"
239 }
240 </SelectValue>
241 </SelectTrigger>
242 <SelectPopup align="end" alignItemWithTrigger={false}>
243 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
244 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
245 </SelectPopup>
246 </Select>
247 }
248 />
249 );
250
251 return (
252 <SettingsSection
253 id={
254 category === "general" || category === "project"
255 ? "project-defaults"
256 : category === "integrations"
257 ? "browser-access"
258 : "source-control-defaults"
259 }
260 title={
261 category === "general" || category === "project"
262 ? "New threads"
263 : category === "integrations"
264 ? "Browser"
265 : "Repositories"
266 }
267 >
268 {category === "project" ? (
269 <>
270 {modelRow}
271 {workspaceRow}
272 </>
273 ) : category === "general" ? (
274 <>
275 {modelRow}
276 <SettingsRow
277 serverScoped
278 settingKeys={["defaultRuntimeMode"]}
279 mixed={mixedPermissions}
280 {...searchableSetting("default-permissions")}
281 description={
282 isProjectScope
283 ? "Permissions for new threads in this project."
284 : "Default permissions for new threads. Projects can override them."
285 }
286 resetAction={
287 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
288 <SettingResetButton
289 label="default permissions"
290 onClick={() =>
291 updateSettings({
292 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
293 })
294 }
295 />
296 ) : null
297 }
298 control={
299 <Select
300 value={mixedPermissions ? null : settings.defaultRuntimeMode}
301 onValueChange={(value) => {
302 if (value) updateSettings({ defaultRuntimeMode: value });
303 }}
304 >
305 <SelectTrigger size="sm" aria-label="Default permissions">
306 {!mixedPermissions && (
307 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
308 )}
309 <SelectValue>
310 {mixedPermissions
311 ? "Mixed"
312 : runtimeModeConfig[settings.defaultRuntimeMode].label}
313 </SelectValue>
314 </SelectTrigger>
315 <SelectPopup align="end" alignItemWithTrigger={false}>
316 {runtimeModeOptions.map((mode) => {
317 const option = runtimeModeConfig[mode];
318 const Icon = option.icon;
319 return (
320 <SelectItem key={mode} value={mode} className="min-w-64">
321 <div className="grid gap-0.5">
322 <span className="inline-flex items-center gap-1.5 font-medium">
323 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
324 {option.label}
325 </span>
326 <span className="text-xs leading-4 text-muted-foreground">
327 {option.description}
328 </span>
329 </div>
330 </SelectItem>
331 );
332 })}
333 </SelectPopup>
334 </Select>
335 }
336 />
337 {workspaceRow}
338 <SettingsRow
339 serverScoped
340 settingKeys={["worktreeSubmodules"]}
341 mixed={mixedSubmodules}
342 {...searchableSetting("worktree-submodules")}
343 description={
344 isProjectScope
345 ? "How new worktrees in this project populate git submodules."
346 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
347 }
348 resetAction={
349 !isProjectScope && settings.worktreeSubmodules !== null ? (
350 <SettingResetButton
351 label="worktree submodules"
352 onClick={() => updateSettings({ worktreeSubmodules: null })}
353 />
354 ) : null
355 }
356 control={
357 <Select
358 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
359 onValueChange={(value) => {
360 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
361 }}
362 >
363 <SelectTrigger size="sm" aria-label="Worktree submodules">
364 <SelectValue>
365 {(value: string | null) =>
366 isWorktreeSubmodules(value)
367 ? WORKTREE_SUBMODULES_LABELS[value]
368 : unavailable
369 ? "Unavailable"
370 : "Mixed"
371 }
372 </SelectValue>
373 </SelectTrigger>
374 <SelectPopup align="end" alignItemWithTrigger={false}>
375 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
376 <SelectItem key={option} value={option}>
377 {WORKTREE_SUBMODULES_LABELS[option]}
378 </SelectItem>
379 ))}
380 </SelectPopup>
381 </Select>
382 }
383 />
384 </>
385 ) : category === "source-control" ? (
386 <>
387 <SettingsRow
388 serverScoped
389 settingKeys={["defaultAutoPull"]}
390 mixed={mixedAutoPull}
391 id="automatic-pull"
392 title="Automatically pull"
393 description={
394 isProjectScope
395 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
396 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
397 }
398 resetAction={
399 settings.defaultAutoPull ? (
400 <SettingResetButton
401 label="default automatic pull"
402 tooltip="Reset automatic pull to off"
403 onClick={() => updateSettings({ defaultAutoPull: false })}
404 />
405 ) : null
406 }
407 control={
408 <Switch
409 aria-label="Default automatic pull"
410 mixed={mixedAutoPull}
411 checked={mixedAutoPull ? false : settings.defaultAutoPull}
412 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
413 />
414 }
415 />
416 <SettingsRow
417 serverScoped
418 settingKeys={["removeAgentCreditsOnMerge"]}
419 mixed={mixedAgentCredits}
420 {...searchableSetting("remove-agent-credits-on-merge")}
421 description="Remove recognized agent credit lines from GitHub merge and squash messages, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits."
422 resetAction={
423 settings.removeAgentCreditsOnMerge ? (
424 <SettingResetButton
425 label="agent credit removal"
426 tooltip="Keep agent credits"
427 onClick={() => updateSettings({ removeAgentCreditsOnMerge: false })}
428 />
429 ) : null
430 }
431 control={
432 <Switch
433 aria-label="Remove agent credits when merging"
434 mixed={mixedAgentCredits}
435 checked={mixedAgentCredits ? false : settings.removeAgentCreditsOnMerge}
436 onCheckedChange={(enabled) =>
437 updateSettings({ removeAgentCreditsOnMerge: enabled })
438 }
439 />
440 }
441 />
442 <SettingsRow
443 serverScoped
444 settingKeys={["pullRequestMergeMethod"]}
445 mixed={mixedMergeMethod}
446 {...searchableSetting("pull-request-merge-method")}
447 description={
448 isProjectScope
449 ? "Pull requests in this project start with this method."
450 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
451 }
452 resetAction={
453 settings.pullRequestMergeMethod !== null ? (
454 <SettingResetButton
455 label="default merge method"
456 tooltip="Reset to last selected"
457 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
458 />
459 ) : null
460 }
461 control={
462 <Select
463 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
464 onValueChange={(value) => {
465 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
466 else if (value === "merge" || value === "squash" || value === "rebase")
467 updateSettings({ pullRequestMergeMethod: value });
468 }}
469 >
470 <SelectTrigger size="sm" aria-label="Default pull request merge method">
471 <SelectValue>
472 {(value: string | null) =>
473 value === "merge" || value === "squash" || value === "rebase"
474 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
475 : value === "last"
476 ? "Last selected"
477 : "Mixed"
478 }
479 </SelectValue>
480 </SelectTrigger>
481 <SelectPopup align="end" alignItemWithTrigger={false}>
482 <SelectItem value="last">Last selected</SelectItem>
483 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
484 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
485 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
486 </SelectPopup>
487 </Select>
488 }
489 />
490 </>
491 ) : (
492 <>
493 <SettingsRow
494 serverScoped
495 settingKeys={["enableAgentBrowserAccess"]}
496 mixed={mixedBrowser}
497 id={searchableSetting("agent-browser-access").id}
498 title="Agent browser access"
499 description={
500 isProjectScope
501 ? "Allow agents in this project to use the shared browser. Applies when the agent session next starts."
502 : "Allow agents to use the shared browser. Projects can override it."
503 }
504 resetAction={
505 settings.enableAgentBrowserAccess !==
506 DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
507 <SettingResetButton
508 label="default browser access"
509 onClick={() =>
510 updateSettings({
511 enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
512 })
513 }
514 />
515 ) : null
516 }
517 control={
518 <Switch
519 aria-label="Agent browser access"
520 mixed={mixedBrowser}
521 checked={mixedBrowser ? false : settings.enableAgentBrowserAccess}
522 onCheckedChange={(enabled) => updateSettings({ enableAgentBrowserAccess: enabled })}
523 />
524 }
525 />
526 </>
527 )}
528 </SettingsSection>
529 );
530}