@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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