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

ProjectDefaultsSettings.tsx

505 lines20.2 KB

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);
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 triggerVariant="outline"
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 triggerVariant="outline"
191 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
192 onModelOptionsChange={(options) =>
193 setModel(createModelSelection(selection.instanceId, selection.model, options))
194 }
195 />
196 ) : null}
197 </div>
198 ) : (
199 <span className="text-sm text-muted-foreground">No providers available</span>
200 )
201 }
202 />
203 );
204 const workspaceRow = (
205 <SettingsRow
206 serverScoped
207 settingKeys={["defaultThreadEnvMode"]}
208 mixed={mixedWorkspace}
209 id={searchableSetting("new-threads").id}
210 title="Workspace"
211 description={
212 isProjectScope
213 ? "Where new threads in this project start."
214 : "Where new threads start. Projects and their t3.json can override it."
215 }
216 resetAction={
217 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
218 <SettingResetButton
219 label="default workspace"
220 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
221 />
222 ) : null
223 }
224 control={
225 <Select
226 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
227 onValueChange={(value) => {
228 if (value === "local" || value === "worktree")
229 updateSettings({ defaultThreadEnvMode: value });
230 }}
231 >
232 <SelectTrigger size="sm" aria-label="Default workspace">
233 <SelectValue>
234 {(value: string | null) =>
235 value === "local" || value === "worktree"
236 ? resolveEnvModeLabel(value)
237 : unavailable
238 ? "Unavailable"
239 : "Mixed"
240 }
241 </SelectValue>
242 </SelectTrigger>
243 <SelectPopup align="end" alignItemWithTrigger={false}>
244 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
245 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
246 </SelectPopup>
247 </Select>
248 }
249 />
250 );
251​
252 return (
253 <SettingsSection
254 id={
255 category === "general" || category === "project"
256 ? "project-defaults"
257 : category === "integrations"
258 ? "browser-access"
259 : "source-control-defaults"
260 }
261 title={
262 category === "general" || category === "project"
263 ? "New threads"
264 : category === "integrations"
265 ? "Browser"
266 : "Repositories"
267 }
268 >
269 {category === "project" ? (
270 <>
271 {modelRow}
272 {workspaceRow}
273 </>
274 ) : category === "general" ? (
275 <>
276 {modelRow}
277 <SettingsRow
278 serverScoped
279 settingKeys={["defaultRuntimeMode"]}
280 mixed={mixedPermissions}
281 {...searchableSetting("default-permissions")}
282 description={
283 isProjectScope
284 ? "Permissions for new threads in this project."
285 : "Default permissions for new threads. Projects can override them."
286 }
287 resetAction={
288 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
289 <SettingResetButton
290 label="default permissions"
291 onClick={() =>
292 updateSettings({
293 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
294 })
295 }
296 />
297 ) : null
298 }
299 control={
300 <Select
301 value={mixedPermissions ? null : settings.defaultRuntimeMode}
302 onValueChange={(value) => {
303 if (value) updateSettings({ defaultRuntimeMode: value });
304 }}
305 >
306 <SelectTrigger size="sm" aria-label="Default permissions">
307 {!mixedPermissions && (
308 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
309 )}
310 <SelectValue>
311 {mixedPermissions
312 ? "Mixed"
313 : runtimeModeConfig[settings.defaultRuntimeMode].label}
314 </SelectValue>
315 </SelectTrigger>
316 <SelectPopup align="end" alignItemWithTrigger={false}>
317 {runtimeModeOptions.map((mode) => {
318 const option = runtimeModeConfig[mode];
319 const Icon = option.icon;
320 return (
321 <SelectItem key={mode} value={mode} className="min-w-64">
322 <div className="grid gap-0.5">
323 <span className="inline-flex items-center gap-1.5 font-medium">
324 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
325 {option.label}
326 </span>
327 <span className="text-xs leading-4 text-muted-foreground">
328 {option.description}
329 </span>
330 </div>
331 </SelectItem>
332 );
333 })}
334 </SelectPopup>
335 </Select>
336 }
337 />
338 {workspaceRow}
339 <SettingsRow
340 serverScoped
341 settingKeys={["worktreeSubmodules"]}
342 mixed={mixedSubmodules}
343 {...searchableSetting("worktree-submodules")}
344 description={
345 isProjectScope
346 ? "How new worktrees in this project populate git submodules."
347 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
348 }
349 resetAction={
350 !isProjectScope && settings.worktreeSubmodules !== null ? (
351 <SettingResetButton
352 label="worktree submodules"
353 onClick={() => updateSettings({ worktreeSubmodules: null })}
354 />
355 ) : null
356 }
357 control={
358 <Select
359 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
360 onValueChange={(value) => {
361 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
362 }}
363 >
364 <SelectTrigger size="sm" aria-label="Worktree submodules">
365 <SelectValue>
366 {(value: string | null) =>
367 isWorktreeSubmodules(value)
368 ? WORKTREE_SUBMODULES_LABELS[value]
369 : unavailable
370 ? "Unavailable"
371 : "Mixed"
372 }
373 </SelectValue>
374 </SelectTrigger>
375 <SelectPopup align="end" alignItemWithTrigger={false}>
376 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
377 <SelectItem key={option} value={option}>
378 {WORKTREE_SUBMODULES_LABELS[option]}
379 </SelectItem>
380 ))}
381 </SelectPopup>
382 </Select>
383 }
384 />
385 </>
386 ) : category === "source-control" ? (
387 <>
388 <SettingsRow
389 serverScoped
390 settingKeys={["defaultAutoPull"]}
391 mixed={mixedAutoPull}
392 id="automatic-pull"
393 title="Automatically pull"
394 description={
395 isProjectScope
396 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
397 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
398 }
399 resetAction={
400 settings.defaultAutoPull ? (
401 <SettingResetButton
402 label="default automatic pull"
403 tooltip="Reset automatic pull to off"
404 onClick={() => updateSettings({ defaultAutoPull: false })}
405 />
406 ) : null
407 }
408 control={
409 <Switch
410 aria-label="Default automatic pull"
411 mixed={mixedAutoPull}
412 checked={mixedAutoPull ? false : settings.defaultAutoPull}
413 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
414 />
415 }
416 />
417 <SettingsRow
418 serverScoped
419 settingKeys={["pullRequestMergeMethod"]}
420 mixed={mixedMergeMethod}
421 {...searchableSetting("pull-request-merge-method")}
422 description={
423 isProjectScope
424 ? "Pull requests in this project start with this method."
425 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
426 }
427 resetAction={
428 settings.pullRequestMergeMethod !== null ? (
429 <SettingResetButton
430 label="default merge method"
431 tooltip="Reset to last selected"
432 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
433 />
434 ) : null
435 }
436 control={
437 <Select
438 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
439 onValueChange={(value) => {
440 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
441 else if (value === "merge" || value === "squash" || value === "rebase")
442 updateSettings({ pullRequestMergeMethod: value });
443 }}
444 >
445 <SelectTrigger size="sm" aria-label="Default pull request merge method">
446 <SelectValue>
447 {(value: string | null) =>
448 value === "merge" || value === "squash" || value === "rebase"
449 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
450 : value === "last"
451 ? "Last selected"
452 : "Mixed"
453 }
454 </SelectValue>
455 </SelectTrigger>
456 <SelectPopup align="end" alignItemWithTrigger={false}>
457 <SelectItem value="last">Last selected</SelectItem>
458 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
459 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
460 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
461 </SelectPopup>
462 </Select>
463 }
464 />
465 </>
466 ) : (
467 <>
468 <SettingsRow
469 serverScoped
470 settingKeys={["enableAgentBrowserAccess"]}
471 mixed={mixedBrowser}
472 id={searchableSetting("agent-browser-access").id}
473 title="Agent browser access"
474 description={
475 isProjectScope
476 ? "Allow agents in this project to use the shared browser. Applies when the agent session next starts."
477 : "Allow agents to use the shared browser. Projects can override it."
478 }
479 resetAction={
480 settings.enableAgentBrowserAccess !==
481 DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
482 <SettingResetButton
483 label="default browser access"
484 onClick={() =>
485 updateSettings({
486 enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
487 })
488 }
489 />
490 ) : null
491 }
492 control={
493 <Switch
494 aria-label="Agent browser access"
495 mixed={mixedBrowser}
496 checked={mixedBrowser ? false : settings.enableAgentBrowserAccess}
497 onCheckedChange={(enabled) => updateSettings({ enableAgentBrowserAccess: enabled })}
498 />
499 }
500 />
501 </>
502 )}
503 </SettingsSection>
504 );