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 mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]);
83 const modelSource = useScopedSettingSource(["defaultModelSelection"]);
84 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
85 const unavailable = connectedEnvironments.length === 0;
86 // File-backed keys show their effective value; the target already carries
87 // the checkout's t3.json, and a null file here only fills the built-in.
88 // The reset arrow beside the title clears the tier (SettingsRow handles a
89 // project override, the environment value is cleared here), so the picker
90 // has no "inherit" item.
91 const effective = target
92 ? resolveProjectSettings(target.settings, null, null, null).settings
93 : null;
94
95 function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
96 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
97 for (const candidate of targets) {
98 const environment = environments.find(
99 (entry) => entry.environmentId === candidate.environmentId,
100 );
101 const config = environment?.serverConfig;
102 if (!config) continue;
103 const entry = applyProviderInstanceSettings(
104 deriveProviderInstanceEntries(config.providers),
105 candidate.settings,
106 ).find((option) => option.instanceId === instanceId);
107 const options = getCustomModelOptionsByInstance(
108 { ...settings, ...candidate.settings },
109 config.providers,
110 ).get(instanceId);
111 if (
112 !entry?.enabled ||
113 !entry.isAvailable ||
114 entry.driverKind !== sourceEntry?.driverKind ||
115 !options?.some((option) => option.slug === model && !option.isUnavailable)
116 ) {
117 return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
118 }
119 }
120 return null;
121 }
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 : "Default model for new threads. Projects can override it."
143 }
144 status={
145 unavailable || mixedModel || modelSource === "project"
146 ? undefined
147 : settings.defaultModelSelection === null
148 ? "Automatic"
149 : undefined
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 activeInstanceId={selection.instanceId}
161 model={selection.model}
162 lockedProvider={null}
163 instanceEntries={entries}
164 modelOptionsByInstance={modelOptions}
165 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
166 {...(mixedModel ? { triggerLabel: "Mixed" } : {})}
167 getModelDisabledReason={modelDisabledReason}
168 onOpenProviderSetup={(instanceId) => {
169 if (representative)
170 void navigate({
171 to: "/settings/providers",
172 search: { environmentId: representative.environmentId, instanceId },
173 });
174 }}
175 onInstanceModelChange={(instanceId, model) =>
176 setModel(createModelSelection(instanceId, model))
177 }
178 />
179 {!mixedModel ? (
180 <TraitsPicker
181 provider={activeEntry.driverKind}
182 models={activeEntry.models}
183 model={selection.model}
184 prompt=""
185 onPromptChange={() => {}}
186 modelOptions={selection.options ?? []}
187 allowPromptInjectedEffort={false}
188 planModeEnabled={settings.planModeEnabled}
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">No providers available</span>
198 )
199 }
200 />
201 );
202 const workspaceRow = (
203 <SettingsRow
204 serverScoped
205 settingKeys={["defaultThreadEnvMode"]}
206 mixed={mixedWorkspace}
207 id={searchableSetting("new-threads").id}
208 title="Workspace"
209 description={
210 isProjectScope
211 ? "Where new threads in this project start."
212 : "Where new threads start. Projects and their t3.json can override it."
213 }
214 resetAction={
215 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
216 <SettingResetButton
217 label="default workspace"
218 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
219 />
220 ) : null
221 }
222 control={
223 <Select
224 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
225 onValueChange={(value) => {
226 if (value === "local" || value === "worktree")
227 updateSettings({ defaultThreadEnvMode: value });
228 }}
229 >
230 <SelectTrigger size="sm" aria-label="Default workspace">
231 <SelectValue>
232 {(value: string | null) =>
233 value === "local" || value === "worktree"
234 ? resolveEnvModeLabel(value)
235 : unavailable
236 ? "Unavailable"
237 : "Mixed"
238 }
239 </SelectValue>
240 </SelectTrigger>
241 <SelectPopup align="end" alignItemWithTrigger={false}>
242 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
243 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
244 </SelectPopup>
245 </Select>
246 }
247 />
248 );
249
250 return (
251 <SettingsSection
252 id={
253 category === "general" || category === "project"
254 ? "project-defaults"
255 : category === "integrations"
256 ? "browser-access"
257 : "source-control-defaults"
258 }
259 title={
260 category === "general" || category === "project"
261 ? "New threads"
262 : category === "integrations"
263 ? "Browser"
264 : "Repositories"
265 }
266 >
267 {category === "project" ? (
268 <>
269 {modelRow}
270 {workspaceRow}
271 </>
272 ) : category === "general" ? (
273 <>
274 {modelRow}
275 <SettingsRow
276 serverScoped
277 settingKeys={["defaultRuntimeMode"]}
278 mixed={mixedPermissions}
279 {...searchableSetting("default-permissions")}
280 description={
281 isProjectScope
282 ? "Permissions for new threads in this project."
283 : "Default permissions for new threads. Projects can override them."
284 }
285 resetAction={
286 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
287 <SettingResetButton
288 label="default permissions"
289 onClick={() =>
290 updateSettings({
291 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
292 })
293 }
294 />
295 ) : null
296 }
297 control={
298 <Select
299 value={mixedPermissions ? null : settings.defaultRuntimeMode}
300 onValueChange={(value) => {
301 if (value) updateSettings({ defaultRuntimeMode: value });
302 }}
303 >
304 <SelectTrigger size="sm" aria-label="Default permissions">
305 {!mixedPermissions && (
306 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
307 )}
308 <SelectValue>
309 {mixedPermissions
310 ? "Mixed"
311 : runtimeModeConfig[settings.defaultRuntimeMode].label}
312 </SelectValue>
313 </SelectTrigger>
314 <SelectPopup align="end" alignItemWithTrigger={false}>
315 {runtimeModeOptions.map((mode) => {
316 const option = runtimeModeConfig[mode];
317 const Icon = option.icon;
318 return (
319 <SelectItem key={mode} value={mode} className="min-w-64">
320 <div className="grid gap-0.5">
321 <span className="inline-flex items-center gap-1.5 font-medium">
322 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
323 {option.label}
324 </span>
325 <span className="text-xs leading-4 text-muted-foreground">
326 {option.description}
327 </span>
328 </div>
329 </SelectItem>
330 );
331 })}
332 </SelectPopup>
333 </Select>
334 }
335 />
336 {workspaceRow}
337 <SettingsRow
338 serverScoped
339 settingKeys={["worktreeSubmodules"]}
340 mixed={mixedSubmodules}
341 {...searchableSetting("worktree-submodules")}
342 description={
343 isProjectScope
344 ? "How new worktrees in this project populate git submodules."
345 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
346 }
347 resetAction={
348 !isProjectScope && settings.worktreeSubmodules !== null ? (
349 <SettingResetButton
350 label="worktree submodules"
351 onClick={() => updateSettings({ worktreeSubmodules: null })}
352 />
353 ) : null
354 }
355 control={
356 <Select
357 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
358 onValueChange={(value) => {
359 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
360 }}
361 >
362 <SelectTrigger size="sm" aria-label="Worktree submodules">
363 <SelectValue>
364 {(value: string | null) =>
365 isWorktreeSubmodules(value)
366 ? WORKTREE_SUBMODULES_LABELS[value]
367 : unavailable
368 ? "Unavailable"
369 : "Mixed"
370 }
371 </SelectValue>
372 </SelectTrigger>
373 <SelectPopup align="end" alignItemWithTrigger={false}>
374 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
375 <SelectItem key={option} value={option}>
376 {WORKTREE_SUBMODULES_LABELS[option]}
377 </SelectItem>
378 ))}
379 </SelectPopup>
380 </Select>
381 }
382 />
383 </>
384 ) : category === "source-control" ? (
385 <>
386 <SettingsRow
387 serverScoped
388 settingKeys={["defaultAutoPull"]}
389 mixed={mixedAutoPull}
390 id="automatic-pull"
391 title="Automatically pull"
392 description={
393 isProjectScope
394 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
395 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
396 }
397 resetAction={
398 settings.defaultAutoPull ? (
399 <SettingResetButton
400 label="default automatic pull"
401 tooltip="Reset automatic pull to off"
402 onClick={() => updateSettings({ defaultAutoPull: false })}
403 />
404 ) : null
405 }
406 control={
407 <Switch
408 aria-label="Default automatic pull"
409 mixed={mixedAutoPull}
410 checked={mixedAutoPull ? false : settings.defaultAutoPull}
411 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
412 />
413 }
414 />
415 <SettingsRow
416 serverScoped
417 settingKeys={["pullRequestMergeMethod"]}
418 mixed={mixedMergeMethod}
419 {...searchableSetting("pull-request-merge-method")}
420 description={
421 isProjectScope
422 ? "Pull requests in this project start with this method."
423 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
424 }
425 resetAction={
426 settings.pullRequestMergeMethod !== null ? (
427 <SettingResetButton
428 label="default merge method"
429 tooltip="Reset to last selected"
430 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
431 />
432 ) : null
433 }
434 control={
435 <Select
436 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
437 onValueChange={(value) => {
438 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
439 else if (value === "merge" || value === "squash" || value === "rebase")
440 updateSettings({ pullRequestMergeMethod: value });
441 }}
442 >
443 <SelectTrigger size="sm" aria-label="Default pull request merge method">
444 <SelectValue>
445 {(value: string | null) =>
446 value === "merge" || value === "squash" || value === "rebase"
447 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
448 : value === "last"
449 ? "Last selected"
450 : "Mixed"
451 }
452 </SelectValue>
453 </SelectTrigger>
454 <SelectPopup align="end" alignItemWithTrigger={false}>
455 <SelectItem value="last">Last selected</SelectItem>
456 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
457 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
458 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
459 </SelectPopup>
460 </Select>
461 }
462 />
463 </>
464 ) : (
465 <>
466 <SettingsRow
467 serverScoped
468 settingKeys={["enableAgentBrowserAccess"]}
469 mixed={mixedBrowser}
470 id={searchableSetting("agent-browser-access").id}
471 title="Agent browser access"
472 description={
473 isProjectScope
474 ? "Allow agents in this project to use the shared browser. Applies when the agent session next starts."
475 : "Allow agents to use the shared browser. Projects can override it."
476 }
477 resetAction={
478 settings.enableAgentBrowserAccess !==
479 DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
480 <SettingResetButton
481 label="default browser access"
482 onClick={() =>
483 updateSettings({
484 enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
485 })
486 }
487 />
488 ) : null
489 }
490 control={
491 <Switch
492 aria-label="Agent browser access"
493 mixed={mixedBrowser}
494 checked={mixedBrowser ? false : settings.enableAgentBrowserAccess}
495 onCheckedChange={(enabled) => updateSettings({ enableAgentBrowserAccess: enabled })}
496 />
497 }
498 />
499 </>
500 )}
501 </SettingsSection>
502 );
503}