diff --git a/apps/mobile/src/features/settings/ProviderProfilesSettings.tsx b/apps/mobile/src/features/settings/ProviderProfilesSettings.tsx new file mode 100644 index 0000000000000..11d1532cf96c9 --- /dev/null +++ b/apps/mobile/src/features/settings/ProviderProfilesSettings.tsx @@ -0,0 +1,361 @@ +import { + AuthProvidersManageScope, + AuthSettingsWriteScope, + isManagedDriverAllowed, + resolveProjectProviderInstanceEnabled, + type EnvironmentId, + type ProjectId, + type ProviderProfile, + type ServerProvider, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useRef, useState } from "react"; +import { View } from "react-native"; + +import { AppText as Text, AppTextInput } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import * as Dialog from "../../components/ui/Dialog"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { uuidv4 } from "../../lib/uuid"; +import { serverEnvironment } from "../../state/server"; +import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import type { SettingsTarget } from "./settings-environment-filter"; +import { SettingsSection } from "./components/SettingsSection"; +import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; + +function useProfileSettingsWrite(environmentId: EnvironmentId) { + const [pending, setPending] = useState(false); + const pendingRef = useRef(false); + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { + label: "provider profile update", + reportFailure: true, + }); + const write = async (patch: ServerSettingsPatch): Promise => { + if ( + pendingRef.current || + !readEnvironmentScope(environmentId, AuthSettingsWriteScope) || + !readEnvironmentScope(environmentId, AuthProvidersManageScope) + ) { + return false; + } + pendingRef.current = true; + setPending(true); + const result = await updateSettings({ environmentId, input: { patch } }); + pendingRef.current = false; + setPending(false); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert("Could not save provider profile", String(error)); + } + return false; + } + return true; + }; + return { write, pending }; +} + +export function ProjectProviderProfileSection(props: { + readonly environment: SettingsTarget | undefined; + readonly projectId: ProjectId; + readonly checkoutLabel: string; + readonly showCheckoutLabel: boolean; +}) { + if (!props.environment) { + return ( + + + Connect this checkout to view its provider profile. + + + ); + } + return ; +} + +function ConnectedProjectProviderProfileSection(props: { + readonly environment: SettingsTarget; + readonly projectId: ProjectId; + readonly checkoutLabel: string; + readonly showCheckoutLabel: boolean; +}) { + const { environment, projectId } = props; + const allowed = useEnvironmentScope(environment.environmentId, AuthSettingsWriteScope); + const canManageProviders = useEnvironmentScope( + environment.environmentId, + AuthProvidersManageScope, + ); + const { write, pending } = useProfileSettingsWrite(environment.environmentId); + const { providerProfiles, projectProfiles } = environment.serverConfig.settings.trogonStack; + const selectedId = projectProfiles[projectId] ?? null; + const needsProfile = + selectedId === null && + environment.serverConfig.settings.trogonStack.projectsRequiringProfile?.[projectId] === true; + const choices = Object.entries(providerProfiles).sort((left, right) => + left[1].name.localeCompare(right[1].name), + ); + const select = (profileId: string | null) => { + const save = () => { + void write({ trogonStack: { projectProfiles: { [projectId]: profileId } } }); + }; + if (profileId === selectedId) return; + if (selectedId === null && profileId !== null) { + save(); + return; + } + Dialog.confirm({ + title: profileId === null ? "Remove provider profile?" : "Change provider profile?", + message: + profileId === null + ? needsProfile + ? "Removing the assignment blocks providers until another profile is assigned. Existing thread context is not erased." + : "Removing the assignment returns this project to legacy, unrestricted provider access. Existing thread context is not erased." + : "Changing this assignment does not remove existing thread context.", + confirmText: profileId === null ? "Remove profile" : "Change profile", + onConfirm: save, + }); + }; + + return ( + + + {props.showCheckoutLabel ? ( + {props.checkoutLabel} + ) : null} + + {selectedId === null + ? needsProfile + ? "Profile required: providers are blocked until you assign one." + : "Legacy project: providers are not restricted by a profile." + : providerProfiles[selectedId] + ? "Only the selected profile's provider instances are available for future turns. Existing thread context is unchanged." + : "Assigned profile is missing. No provider instances are allowed until you select a profile."} + + + select(null)} + /> + {choices.map(([id, profile]) => ( + select(id)} + /> + ))} + {choices.length === 0 ? ( + + Add a provider profile in Provider settings before assigning this project. + + ) : null} + + ); +} + +export function ProviderProfilesSection(props: { + readonly environment: SettingsTarget; + readonly providers: ReadonlyArray; +}) { + const { environment } = props; + const [name, setName] = useState(""); + const allowed = useEnvironmentScope(environment.environmentId, AuthSettingsWriteScope); + const canManageProviders = useEnvironmentScope( + environment.environmentId, + AuthProvidersManageScope, + ); + const { write, pending } = useProfileSettingsWrite(environment.environmentId); + const profiles = environment.serverConfig.settings.trogonStack.providerProfiles; + const create = async () => { + const nextName = name.trim(); + if ( + !nextName || + Object.values(profiles).some( + (profile) => profile.name.toLowerCase() === nextName.toLowerCase(), + ) + ) { + Dialog.alert("Choose a unique profile name"); + return; + } + // A reused id would silently rebind projects still pointing at a deleted profile. + const profileId = uuidv4(); + const saved = await write({ + trogonStack: { + providerProfiles: { [profileId]: { name: nextName, providerInstanceIds: [] } }, + }, + }); + if (saved) setName(""); + }; + + return ( + + + + Profiles allow only selected provider instances. New providers stay off until added to a + profile. + + void create()} + /> + + } + /> ); diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx index a8d2efe7e04db..35680adf01f8f 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx @@ -5,6 +5,7 @@ import type { } from "@t3tools/client-runtime/state/projects"; import { AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, DEFAULT_SERVER_SETTINGS, EnvironmentId, @@ -12,6 +13,7 @@ import { ProviderInstanceId, type AuthEnvironmentScope, type AuthSessionState, + type ServerSettingsPatch, } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; @@ -50,6 +52,7 @@ const state = vi.hoisted(() => ({ input: DeleteProjectInput; }) => Promise> >(), + updateSettings: vi.fn<(patch: ServerSettingsPatch) => void>(), confirm: vi.fn<() => Promise>(), releaseUploads: vi.fn(), clearDraft: vi.fn(), @@ -112,6 +115,10 @@ vi.mock(import("~/hooks/useSettings"), async (original) => ({ ...(await original()), useClientSettings: ((selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) => selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS) as never, + useEnvironmentSettings: ((id: EnvironmentId) => + environments.find((environment) => environment.environmentId === id)?.serverConfig.settings ?? + DEFAULT_SERVER_SETTINGS) as never, + useUpdateEnvironmentSettings: (() => state.updateSettings) as never, })); vi.mock(import("~/localApi"), async (original) => ({ ...(await original()), @@ -189,6 +196,8 @@ function deferred() { function setup() { vi.clearAllMocks(); + for (const environment of environments) + environment.serverConfig.settings = DEFAULT_SERVER_SETTINGS; state.sessions.clear(); for (const id of [primaryId, remoteId]) state.sessions.set(id, Atom.make(writable()).pipe(Atom.keepAlive)); @@ -363,6 +372,39 @@ describe("project organization", () => { }); }); +describe("project provider profile", () => { + it("labels a pending project and assigns it with a targeted settings patch", async () => { + setup(); + await grant( + primaryId, + AsyncResult.success( + session([AuthOrchestrationOperateScope, AuthSettingsWriteScope, AuthProvidersManageScope]), + ), + ); + const projectId = state.projects.find((project) => project.environmentId === primaryId)!.id; + environments[0]!.serverConfig.settings = { + ...DEFAULT_SERVER_SETTINGS, + trogonStack: { + ...DEFAULT_SERVER_SETTINGS.trogonStack, + providerProfiles: { company: { name: "Company", providerInstanceIds: [instanceId] } }, + projectsRequiringProfile: { [projectId]: true }, + }, + }; + + await using screen = await mountPanel({ machine: primaryId }); + await expect + .element(screen.getByText("Blocked until you pick a profile.").first()) + .toBeVisible(); + await userEvent.click(screen.getByRole("combobox", { name: "Provider profile" })); + await userEvent.click(page.getByRole("option", { name: "Company" })); + + expect(state.updateSettings).toHaveBeenCalledWith( + { trogonStack: { projectProfiles: { [projectId]: "company" } } }, + expect.any(Object), + ); + }); +}); + describe("project settings permissions", () => { it("disables shared edits when any member lacks project access", async () => { setup(); diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index cc5ceba8984ee..2c1258455b982 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -50,6 +50,7 @@ import { ProjectFaviconPickerDialog, } from "./ProjectFaviconPickerDialog"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; +import { ProjectProviderProfileAssignment } from "./ProviderProfilesSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; import { defaultProjectIcon, @@ -712,6 +713,21 @@ function ProjectDetail({ ) : null} + + {group.memberProjects.map((member) => ( + 1 + ? { + title: `Provider profile · ${member.environmentLabel ?? member.environmentId} · ${member.workspaceRoot}`, + } + : {})} + /> + ))} + {checkoutChoices} diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index e71ff5eeead80..55383c29469a5 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -687,6 +687,7 @@ interface ProviderInstanceCardProps { readonly headerAction?: ReactNode | undefined; readonly setup?: ReactNode; readonly runtime?: ReactNode; + readonly profiles?: ReactNode; readonly hiddenModels: ReadonlyArray; readonly favoriteModels: ReadonlyArray; readonly modelOrder: ReadonlyArray; @@ -761,6 +762,7 @@ export function ProviderInstanceCard({ headerAction, setup, runtime, + profiles, hiddenModels, favoriteModels, modelOrder, @@ -1338,6 +1340,7 @@ export function ProviderInstanceCard({ } /> + {mode === "editor" ? profiles : null} {setup || environmentFields.length > 0 ? ( diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.browser.test.tsx b/apps/web/src/components/settings/ProviderProfilesSettings.browser.test.tsx new file mode 100644 index 0000000000000..ee674ed199e2d --- /dev/null +++ b/apps/web/src/components/settings/ProviderProfilesSettings.browser.test.tsx @@ -0,0 +1,127 @@ +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type ServerSettings, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import { ProviderInstanceProfiles, ProviderProfilesView } from "./ProviderProfilesSettings"; + +const instanceId = ProviderInstanceId.make("company-codex"); +const projectId = ProjectId.make("client"); +const options = [{ instanceId, label: "Company Codex" }]; +const projects = [{ id: projectId, title: "client", workspaceRoot: "/work/client" }]; +const settings: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [instanceId]: { driver: ProviderDriverKind.make("codex"), displayName: "Company Codex" }, + }, + trogonStack: { + providerProfiles: { company: { name: "Company", providerInstanceIds: [] } }, + projectProfiles: { [projectId]: "company" }, + projectsRequiringProfile: {}, + }, +}; + +it("sends targeted patches when renaming a profile", async () => { + const onPatch = vi.fn((_: ServerSettingsPatch, options?: { onSaved?: () => void }) => + options?.onSaved?.(), + ); + await using screen = await render( + , + ); + + expect(screen.getByText(/Used by client\./)).toBeVisible(); + await screen.getByRole("button", { name: "More actions for Company" }).click(); + await screen.getByRole("menuitem", { name: "Rename" }).click(); + await screen.getByRole("textbox", { name: "Profile name" }).fill("New name"); + await screen.getByRole("button", { name: "Save" }).click(); + expect(onPatch).toHaveBeenLastCalledWith( + { + trogonStack: { providerProfiles: { company: { name: "New name", providerInstanceIds: [] } } }, + }, + expect.any(Object), + ); +}); + +it("adds an instance to a profile from the instance's own settings", async () => { + const onPatch = vi.fn((_: ServerSettingsPatch, options?: { onSaved?: () => void }) => + options?.onSaved?.(), + ); + await using screen = await render( + , + ); + + await screen.getByRole("button", { name: "Profiles: No profiles" }).click(); + await screen.getByRole("menuitemcheckbox", { name: "Company" }).click(); + expect(onPatch).toHaveBeenLastCalledWith( + { + trogonStack: { + providerProfiles: { company: { name: "Company", providerInstanceIds: [instanceId] } }, + }, + }, + expect.any(Object), + ); +}); + +it("starts new profiles with no allowed providers", async () => { + const onPatch = vi.fn((_: ServerSettingsPatch, options?: { onSaved?: () => void }) => + options?.onSaved?.(), + ); + await using screen = await render( + , + ); + + await screen.getByRole("textbox", { name: "New provider profile name" }).fill("Personal"); + await screen.getByRole("button", { name: "Create" }).click(); + const [patch] = onPatch.mock.lastCall!; + expect(Object.values(patch.trogonStack?.providerProfiles ?? {})).toEqual([ + { name: "Personal", providerInstanceIds: [] }, + ]); + expect(Object.keys(patch.trogonStack?.providerProfiles ?? {})).toHaveLength(1); +}); + +it("assigns a project to a profile or removes its profile", async () => { + const onPatch = vi.fn((_: ServerSettingsPatch, options?: { onSaved?: () => void }) => + options?.onSaved?.(), + ); + await using screen = await render( + , + ); + + expect(screen.getByText("Can use no providers. Add some to Company.")).toBeVisible(); + await screen.getByRole("combobox", { name: "Provider profile for client" }).click(); + await screen.getByRole("option", { name: "No profile" }).click(); + expect(onPatch).toHaveBeenLastCalledWith( + { trogonStack: { projectProfiles: { [projectId]: null } } }, + expect.any(Object), + ); +}); diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.tsx b/apps/web/src/components/settings/ProviderProfilesSettings.tsx new file mode 100644 index 0000000000000..cad9deeeacb91 --- /dev/null +++ b/apps/web/src/components/settings/ProviderProfilesSettings.tsx @@ -0,0 +1,521 @@ +import { + AuthProvidersManageScope, + AuthSettingsWriteScope, + type EnvironmentId, + type ProjectId, + type ProviderInstanceId, + type ProviderProfile, + type ServerSettings, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { ChevronDownIcon, MoreVertical, PlusIcon } from "lucide-react"; +import { useState } from "react"; + +import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings"; +import { randomUUID } from "../../lib/utils"; +import { ensureLocalApi } from "../../localApi"; +import { useProjects } from "../../state/entities"; +import { useEnvironmentScope } from "../../state/session"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Menu, MenuCheckboxItem, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { useProviderInstanceOptions } from "./providerInstanceRows"; +import { + profileNameTaken, + profileProviderLabels, + profileInUse, + profileUsageText, + projectDisplayTitles, + projectProfileDescription, + removeProfilePatch, + setProfilePatch, + setProjectProfilePatch, + sortedProfiles, + toggleProfileInstance, + type ProviderInstanceOption, +} from "./providerProfiles.logic"; +import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; + +type SettingsWriter = ( + patch: ServerSettingsPatch, + options?: { readonly onSaved?: () => void; readonly onFailed?: () => void }, +) => void; + +const NO_PROFILE = "__no_provider_profile__"; + +export function ProviderInstanceProfiles({ + settings, + instanceId, + disabled, + onPatch, +}: { + settings: ServerSettings; + instanceId: ProviderInstanceId; + disabled: boolean; + onPatch: SettingsWriter; +}) { + const [saving, setSaving] = useState(false); + const profiles = sortedProfiles(settings); + if (profiles.length === 0) return null; + const selected = profiles + .filter(([, profile]) => profile.providerInstanceIds.includes(instanceId)) + .map(([, profile]) => profile.name); + const label = selected.length ? selected.join(", ") : "No profiles"; + return ( + + } + aria-label={`Profiles: ${label}`} + disabled={disabled} + > + {label} + + + + {profiles.map(([profileId, profile]) => ( + { + setSaving(true); + onPatch( + setProfilePatch(profileId, toggleProfileInstance(profile, instanceId, checked)), + { onSaved: () => setSaving(false), onFailed: () => setSaving(false) }, + ); + }} + > + {profile.name} + + ))} + + + } + /> + ); +} + +function RenameProfileDialog({ + settings, + profileId, + profile, + onSave, + onClose, +}: { + settings: ServerSettings; + profileId: string; + profile: ProviderProfile; + onSave: (name: string) => void; + onClose: () => void; +}) { + const [name, setName] = useState(profile.name); + const trimmed = name.trim(); + const taken = profileNameTaken(settings, trimmed, profileId); + const valid = trimmed !== "" && trimmed !== profile.name && !taken; + return ( + !open && onClose()}> + +
{ + event.preventDefault(); + if (valid) onSave(trimmed); + }} + > + + Rename profile + + +
+ setName(event.currentTarget.value)} + /> + {taken ? ( +

+ Another profile already has that name. +

+ ) : null} +
+
+ + + + +
+
+
+ ); +} + +function ProfileRow({ + settings, + profileId, + profile, + usage, + options, + disabled, + onPatch, +}: { + settings: ServerSettings; + profileId: string; + profile: ProviderProfile; + usage: string; + options: ReadonlyArray; + disabled: boolean; + onPatch: SettingsWriter; +}) { + const [saving, setSaving] = useState(false); + const [renaming, setRenaming] = useState(false); + const save = (patch: ServerSettingsPatch, onSaved?: () => void) => { + setSaving(true); + onPatch(patch, { + onSaved: () => { + setSaving(false); + onSaved?.(); + }, + onFailed: () => setSaving(false), + }); + }; + const labels = profileProviderLabels(profile, options); + const buttonLabel = labels.length ? labels.join(", ") : "No providers"; + const inUse = profileInUse(settings, profileId); + const known = new Set(options.map(({ instanceId }) => instanceId)); + const removedIds = profile.providerInstanceIds.filter((instanceId) => !known.has(instanceId)); + const remove = async () => { + const confirmed = await ensureLocalApi().dialogs.confirm( + `Delete the ${profile.name} provider profile?`, + { variant: "destructive" }, + ); + if (confirmed) save(removeProfilePatch(profileId)); + }; + const setMember = (instanceId: ProviderInstanceId, checked: boolean) => + save(setProfilePatch(profileId, toggleProfileInstance(profile, instanceId, checked))); + + return ( + + + } + aria-label={`Providers for ${profile.name}: ${buttonLabel}`} + disabled={disabled} + > + {buttonLabel} + + + + {options.map(({ instanceId, label }) => ( + setMember(instanceId, checked)} + > + {label} + + ))} + {removedIds.map((instanceId) => ( + setMember(instanceId, checked)} + > + {instanceId} (removed) + + ))} + + + + + } + disabled={disabled || saving} + > + + + + setRenaming(true)}>Rename + void remove()}> + Delete + + + + {renaming ? ( + setRenaming(false)} + onSave={(name) => + save(setProfilePatch(profileId, { ...profile, name }), () => setRenaming(false)) + } + /> + ) : null} + + } + /> + ); +} + +function NewProfileRow({ + settings, + disabled, + onPatch, +}: { + settings: ServerSettings; + disabled: boolean; + onPatch: SettingsWriter; +}) { + const [newName, setNewName] = useState(""); + const [creating, setCreating] = useState(false); + const name = newName.trim(); + const taken = profileNameTaken(settings, name); + const create = () => { + if (!name || taken || creating) return; + setCreating(true); + onPatch(setProfilePatch(randomUUID(), { name, providerInstanceIds: [] }), { + onSaved: () => { + setNewName(""); + setCreating(false); + }, + onFailed: () => setCreating(false), + }); + }; + return ( + + setNewName(event.currentTarget.value)} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") create(); + }} + /> + + + } + /> + ); +} + +function ProjectProfileRow({ + settings, + projectId, + title, + ariaLabel, + options, + disabled, + onPatch, +}: { + settings: ServerSettings; + projectId: ProjectId; + title: string; + ariaLabel: string; + options: ReadonlyArray; + disabled: boolean; + onPatch: SettingsWriter; +}) { + const [saving, setSaving] = useState(false); + const profileId = settings.trogonStack.projectProfiles[projectId]; + const profile = + profileId === undefined ? undefined : settings.trogonStack.providerProfiles[profileId]; + return ( + + + + } + /> + ); +} + +function useProfileWriteAccess(environmentId: EnvironmentId) { + const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope); + const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); + return canWriteSettings && canManageProviders; +} + +export function ProjectProviderProfileAssignment({ + environmentId, + projectId, + title = "Provider profile", + available = true, +}: { + environmentId: EnvironmentId; + projectId: ProjectId; + title?: string; + available?: boolean; +}) { + const settings = useEnvironmentSettings(environmentId); + const options = useProviderInstanceOptions(environmentId); + const canWrite = useProfileWriteAccess(environmentId); + const updateSettings = useUpdateEnvironmentSettings(environmentId); + return ( + + ); +} + +export function ProviderProfilesView({ + settings, + options, + projects, + disabled, + onPatch, +}: { + settings: ServerSettings; + options: ReadonlyArray; + projects: ReadonlyArray<{ id: ProjectId; title: string; workspaceRoot: string }>; + disabled: boolean; + onPatch: SettingsWriter; +}) { + const titles = projectDisplayTitles(projects); + const projectRows = projects + .map((project) => ({ id: project.id, title: titles.get(project.id) ?? project.title })) + .toSorted((left, right) => left.title.localeCompare(right.title)); + + return ( + +

+ A profile is a group of providers. A project on a profile can only use the providers in that + group. +

+ {disabled ? ( +

+ You do not have permission to change provider profiles on this environment. +

+ ) : null} + + + {sortedProfiles(settings).map(([profileId, profile]) => ( + + ))} + + + {projectRows.length === 0 ? ( +

No projects yet.

+ ) : ( + projectRows.map((project) => ( + + )) + )} +
+
+ ); +} + +export function ProviderProfilesPage({ environmentId }: { environmentId: EnvironmentId }) { + const settings = useEnvironmentSettings(environmentId); + const options = useProviderInstanceOptions(environmentId); + const canWrite = useProfileWriteAccess(environmentId); + const updateSettings = useUpdateEnvironmentSettings(environmentId); + const projects = useProjects().filter((project) => project.environmentId === environmentId); + return ( + + ); +} diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index c3cf285980147..cbaa7db260f39 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -24,6 +24,7 @@ import { type ProviderInstanceConfig, type ProviderInstanceId, type ServerProvider, + type ServerSettings, resolveEnvironmentMachineKind, resolveProjectProviderInstanceEnabled, resolveProviderInstanceEnabled, @@ -99,6 +100,12 @@ import { useSecretSources } from "./SecretSourceInput"; import { TextGeneratorsSettings } from "./TextGeneratorsSettings"; import { UsageProviderSettings } from "./UsageProviderSettings"; import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection"; +import { ProviderInstanceProfiles } from "./ProviderProfilesSettings"; +import { + buildProviderInstanceRows, + providerInstanceName, + type ProviderInstanceRowData, +} from "./providerInstanceRows"; import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection"; import { CodexSetupSection, CodexManagedRuntimeFields } from "./CodexSetupSection"; import { readCodexSetupMode } from "./CodexSetupSection.logic"; @@ -130,14 +137,6 @@ import { resolveSelectedProviderEnvironmentId, } from "./ProviderSettingsPanel.logic"; -function providerInstanceName(instance: ProviderInstanceConfig): string { - return ( - instance.displayName?.trim() || - providerClients.get(instance.driver)?.label || - String(instance.driver) - ); -} - async function confirmProviderInstanceRemoval( question: string, consequence = "", @@ -163,11 +162,6 @@ function providerConfigString(config: unknown, key: string): string | null { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; } -const PROVIDER_SETTINGS = providerClients.definitions.map((definition) => ({ - provider: definition.driverKind, - hasDefaultInstance: definition.hasDefaultInstance !== false, -})); - function configuredBinaryPath(config: unknown): string { if (config === null || typeof config !== "object" || !("binaryPath" in config)) return ""; return typeof config.binaryPath === "string" ? config.binaryPath.trim() : ""; @@ -553,6 +547,7 @@ export function EnvironmentProviderSettings({ const canAddProvider = !readOnly && managedPolicy?.limits?.providers?.allowedDrivers?.length !== 0; const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope); + const canManageProfiles = useEnvironmentScope(environmentId, AuthProvidersManageScope); const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope); const updateSettings = useUpdateEnvironmentSettings(environmentId); const updateModelPreferences = useUpdateEnvironmentModelPreferences(environmentId); @@ -615,14 +610,6 @@ export function EnvironmentProviderSettings({ }, ); - const visibleProviderSettings = PROVIDER_SETTINGS.filter( - (providerSettings) => - providerSettings.provider !== "cursor" || - serverProviders.some( - (provider) => - provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")), - ), - ); const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings); const providerHealthPreset = getBackgroundActivityPresetSettings( resolvedBackgroundActivity.profile, @@ -700,80 +687,7 @@ export function EnvironmentProviderSettings({ }, ); - interface InstanceRow { - readonly instanceId: ProviderInstanceId; - /** Undefined for a default slot the user never configured. */ - readonly explicitInstance: ProviderInstanceConfig | undefined; - readonly driver: ProviderDriverKind; - readonly isDefault: boolean; - readonly isDirty?: boolean; - } - - const instancesByDriver = new Map< - ProviderDriverKind, - Array<[ProviderInstanceId, ProviderInstanceConfig]> - >(); - for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) { - const driver = instance.driver; - const list = instancesByDriver.get(driver) ?? []; - list.push([rawId as ProviderInstanceId, instance]); - instancesByDriver.set(driver, list); - } - - const defaultSlotIdsBySource = new Set( - visibleProviderSettings.map((providerSettings) => - String(defaultInstanceIdForDriver(providerSettings.provider)), - ), - ); - - const rows: InstanceRow[] = []; - const visibleDriverKinds = new Set( - visibleProviderSettings.map((providerSettings) => providerSettings.provider), - ); - - for (const providerSettings of visibleProviderSettings) { - const driver = providerSettings.provider; - const defaultInstanceId = defaultInstanceIdForDriver(driver); - const explicitInstance = settings.providerInstances?.[defaultInstanceId]; - const isDirty = explicitInstance !== undefined; - const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined; - if ( - hasDefaultSlot && - (driver === "codex" || - driver === "claudeAgent" || - isDirty || - resolveProviderInstanceEnabled(explicitInstance ?? { driver }) || - defaultInstanceId === targetInstanceId) - ) { - rows.push({ - instanceId: defaultInstanceId, - explicitInstance, - driver, - isDefault: true, - isDirty, - }); - } - for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) { - if (id === defaultInstanceId) continue; - rows.push({ - instanceId: id, - explicitInstance: instance, - driver: instance.driver, - isDefault: false, - }); - } - } - for (const [driver, list] of instancesByDriver) { - if (visibleDriverKinds.has(driver)) continue; - for (const [id, instance] of list) { - rows.push({ - instanceId: id, - explicitInstance: instance, - driver: instance.driver, - isDefault: defaultSlotIdsBySource.has(String(id)), - }); - } - } + const rows = buildProviderInstanceRows(settings, serverProviders, targetInstanceId); const targetInstanceMissing = targetInstanceId !== undefined && @@ -924,14 +838,19 @@ export function EnvironmentProviderSettings({ updateModelPreferences: stableUpdateModelPreferences, toggleModelFavorite: stableToggleModelFavorite, selectInstance: setSelectedInstanceId, + patchSettings: updateSettings, }; // resolveModelPreferences falls back to a fresh `[]`; keep it stable for the rows. const favorites = settings.favorites.length > 0 ? settings.favorites : NO_FAVORITES; const representativeProjectId = projectIds[0]; - const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => { + const renderProviderInstance = (row: ProviderInstanceRowData, mode: "list" | "editor") => { const showProjectOverride = - representativeProjectId !== undefined && supportsProjectProviderOverrides; + representativeProjectId !== undefined && + supportsProjectProviderOverrides && + projectIds.every( + (projectId) => settings.trogonStack.projectProfiles[projectId] === undefined, + ); return ( ); }; @@ -1215,6 +1136,7 @@ interface ProviderInstanceRowActions { readonly updateModelPreferences: ReturnType; readonly toggleModelFavorite: ReturnType; readonly selectInstance: (instanceId: ProviderInstanceId) => void; + readonly patchSettings: ReturnType; } const NO_MODELS: ReadonlyArray = []; @@ -1240,6 +1162,8 @@ function ProviderInstanceRow({ modelPreferences, favorites, actions, + profileSettings, + profilesDisabled, }: { readonly environmentId: EnvironmentId; readonly environmentLabel: string; @@ -1262,6 +1186,8 @@ function ProviderInstanceRow({ | undefined; readonly favorites: UnifiedSettings["favorites"]; readonly actions: ProviderInstanceRowActions; + readonly profileSettings: ServerSettings | undefined; + readonly profilesDisabled: boolean; }) { const allProjects = useProjects(); const secretSources = useSecretSources(environmentId); @@ -1327,6 +1253,16 @@ function ProviderInstanceRow({ ) : undefined } canWriteSettings={canWriteSettings} + profiles={ + profileSettings ? ( + + ) : null + } setup={ mode === "editor" && driver === "antigravity" ? ( > = { "/settings/diagnostics": "/settings/maintenance", + "/settings/provider-profiles": "/settings/labs", "/settings/open-source-licenses": "/settings/about", }; diff --git a/apps/web/src/components/settings/providerInstanceRows.ts b/apps/web/src/components/settings/providerInstanceRows.ts new file mode 100644 index 0000000000000..93b3f6aefb24b --- /dev/null +++ b/apps/web/src/components/settings/providerInstanceRows.ts @@ -0,0 +1,143 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + defaultInstanceIdForDriver, + type EnvironmentId, + ProviderDriverKind, + type ProviderInstanceConfig, + type ProviderInstanceId, + type ServerProvider, + type ServerSettings, + resolveProviderInstanceEnabled, +} from "@t3tools/contracts"; + +import { useEnvironmentSettings } from "../../hooks/useSettings"; +import { providersIgnoringCheckedAtAtom } from "../../state/server"; +import { providerClients } from "./providerDriverMeta"; +import type { ProviderInstanceOption } from "./providerProfiles.logic"; + +export interface ProviderInstanceRowData { + readonly instanceId: ProviderInstanceId; + /** Undefined for a default slot the user never configured. */ + readonly explicitInstance: ProviderInstanceConfig | undefined; + readonly driver: ProviderDriverKind; + readonly isDefault: boolean; + readonly isDirty?: boolean; +} + +export function providerInstanceName(instance: ProviderInstanceConfig): string { + return ( + instance.displayName?.trim() || + providerClients.get(instance.driver)?.label || + String(instance.driver) + ); +} + +const PROVIDER_SETTINGS = providerClients.definitions.map((definition) => ({ + provider: definition.driverKind, + hasDefaultInstance: definition.hasDefaultInstance !== false, +})); + +/** The provider instances the Providers list shows, in its order. */ +export function buildProviderInstanceRows( + settings: Pick, + serverProviders: ReadonlyArray, + targetInstanceId?: ProviderInstanceId, +): ProviderInstanceRowData[] { + const visibleProviderSettings = PROVIDER_SETTINGS.filter( + (providerSettings) => + providerSettings.provider !== "cursor" || + serverProviders.some( + (provider) => + provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")), + ), + ); + const instancesByDriver = new Map< + ProviderDriverKind, + Array<[ProviderInstanceId, ProviderInstanceConfig]> + >(); + for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) { + const driver = instance.driver; + const list = instancesByDriver.get(driver) ?? []; + list.push([rawId as ProviderInstanceId, instance]); + instancesByDriver.set(driver, list); + } + + const defaultSlotIdsBySource = new Set( + visibleProviderSettings.map((providerSettings) => + String(defaultInstanceIdForDriver(providerSettings.provider)), + ), + ); + + const rows: ProviderInstanceRowData[] = []; + const visibleDriverKinds = new Set( + visibleProviderSettings.map((providerSettings) => providerSettings.provider), + ); + + for (const providerSettings of visibleProviderSettings) { + const driver = providerSettings.provider; + const defaultInstanceId = defaultInstanceIdForDriver(driver); + const explicitInstance = settings.providerInstances?.[defaultInstanceId]; + const isDirty = explicitInstance !== undefined; + const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined; + if ( + hasDefaultSlot && + (driver === "codex" || + driver === "claudeAgent" || + isDirty || + resolveProviderInstanceEnabled(explicitInstance ?? { driver }) || + defaultInstanceId === targetInstanceId) + ) { + rows.push({ + instanceId: defaultInstanceId, + explicitInstance, + driver, + isDefault: true, + isDirty, + }); + } + for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) { + if (id === defaultInstanceId) continue; + rows.push({ + instanceId: id, + explicitInstance: instance, + driver: instance.driver, + isDefault: false, + }); + } + } + for (const [driver, list] of instancesByDriver) { + if (visibleDriverKinds.has(driver)) continue; + for (const [id, instance] of list) { + rows.push({ + instanceId: id, + explicitInstance: instance, + driver: instance.driver, + isDefault: defaultSlotIdsBySource.has(String(id)), + }); + } + } + return rows; +} + +function providerInstanceOptions( + rows: ReadonlyArray, + serverProviders: ReadonlyArray, +): ProviderInstanceOption[] { + return rows.map((row) => ({ + instanceId: row.instanceId, + label: + serverProviders + .find((candidate) => candidate.instanceId === row.instanceId) + ?.displayName?.trim() || + providerInstanceName(row.explicitInstance ?? { driver: row.driver }), + })); +} + +export function useProviderInstanceOptions(environmentId: EnvironmentId) { + const settings = useEnvironmentSettings(environmentId); + const serverProviders = useAtomValue(providersIgnoringCheckedAtAtom(environmentId)); + return providerInstanceOptions( + buildProviderInstanceRows(settings, serverProviders), + serverProviders, + ); +} diff --git a/apps/web/src/components/settings/providerProfiles.logic.test.ts b/apps/web/src/components/settings/providerProfiles.logic.test.ts new file mode 100644 index 0000000000000..8fca713c2e11b --- /dev/null +++ b/apps/web/src/components/settings/providerProfiles.logic.test.ts @@ -0,0 +1,129 @@ +import { ProjectId, ProviderInstanceId, type ServerSettings } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + profileNameTaken, + profileInUse, + profileUsageText, + projectDisplayTitles, + projectProfileDescription, + removeProfilePatch, + setProfilePatch, + setProjectProfilePatch, + toggleProfileInstance, +} from "./providerProfiles.logic"; + +const projectId = ProjectId.make("work"); +const instanceId = ProviderInstanceId.make("company-codex"); +const profile = { name: "Company", providerInstanceIds: [instanceId] }; + +describe("provider profile patches", () => { + it("upserts a single profile and toggles only its named provider instances", () => { + expect(setProfilePatch("company", profile)).toEqual({ + trogonStack: { providerProfiles: { company: profile } }, + }); + expect(toggleProfileInstance(profile, instanceId, true)).toEqual(profile); + expect(toggleProfileInstance(profile, instanceId, false)).toEqual({ + ...profile, + providerInstanceIds: [], + }); + expect( + toggleProfileInstance({ ...profile, providerInstanceIds: [] }, instanceId, true), + ).toEqual(profile); + }); + + it("assigns or unassigns one project without replacing other assignments", () => { + expect(setProjectProfilePatch(projectId, "company")).toEqual({ + trogonStack: { projectProfiles: { [projectId]: "company" } }, + }); + expect(setProjectProfilePatch(projectId, null)).toEqual({ + trogonStack: { projectProfiles: { [projectId]: null } }, + }); + }); + + it("removes a profile without restoring unrestricted access to assigned projects", () => { + const settings = { + trogonStack: { + providerProfiles: { + company: profile, + personal: { name: "Personal", providerInstanceIds: [] }, + }, + projectProfiles: { + [projectId]: "company", + [ProjectId.make("other")]: "personal", + [ProjectId.make("missing")]: "deleted", + }, + projectsRequiringProfile: { [projectId]: true }, + }, + } satisfies Pick; + + expect(removeProfilePatch("company")).toEqual({ + trogonStack: { + providerProfiles: { company: null }, + }, + }); + const options = [{ instanceId, label: "Company Codex" }]; + const description = (value: Pick, id: string) => + projectProfileDescription(value, ProjectId.make(id), options); + expect(description(settings, projectId)).toBe("Can use Company Codex."); + expect(description(settings, "other")).toBe("Can use no providers. Add some to Personal."); + expect(description(settings, "missing")).toBe( + "Its profile was deleted. Blocked until you pick another.", + ); + expect(description(settings, "new")).toBe("Not restricted. Can use every provider."); + expect( + description( + { + trogonStack: { + ...settings.trogonStack, + projectsRequiringProfile: { [ProjectId.make("new")]: true }, + }, + }, + "new", + ), + ).toBe("Blocked until you pick a profile."); + expect(projectProfileDescription(settings, projectId, [])).toBe( + "Can use company-codex (removed).", + ); + }); + + it("words who uses a profile, tells apart same-named projects, and rejects duplicate names", () => { + const usage = { + trogonStack: { + providerProfiles: { company: profile }, + projectProfiles: { + [ProjectId.make("w")]: "company", + [ProjectId.make("t")]: "company", + [ProjectId.make("gone")]: "company", + }, + projectsRequiringProfile: {}, + }, + }; + const known = new Map([ + [ProjectId.make("w"), "website"], + [ProjectId.make("t"), "t3code"], + ]); + expect(profileUsageText(usage, "personal", known)).toBe("No project uses it yet."); + expect(profileUsageText(usage, "company", known)).toBe( + "Used by t3code, website, 1 other project. Move them to another profile to delete this one.", + ); + expect(profileInUse(usage, "company")).toBe(true); + expect(profileInUse(usage, "personal")).toBe(false); + const titles = projectDisplayTitles([ + { id: ProjectId.make("a"), title: "app", workspaceRoot: "/one/app" }, + { id: ProjectId.make("b"), title: "app", workspaceRoot: "/two/app" }, + { id: ProjectId.make("c"), title: "site", workspaceRoot: "/site" }, + ]); + expect([...titles.values()]).toEqual(["app (/one/app)", "app (/two/app)", "site"]); + const settings = { + trogonStack: { + providerProfiles: { company: profile }, + projectProfiles: {}, + projectsRequiringProfile: {}, + }, + }; + expect(profileNameTaken(settings, " company ")).toBe(true); + expect(profileNameTaken(settings, "Company", "company")).toBe(false); + expect(profileNameTaken(settings, "Personal")).toBe(false); + }); +}); diff --git a/apps/web/src/components/settings/providerProfiles.logic.ts b/apps/web/src/components/settings/providerProfiles.logic.ts new file mode 100644 index 0000000000000..5a7ed769e2992 --- /dev/null +++ b/apps/web/src/components/settings/providerProfiles.logic.ts @@ -0,0 +1,140 @@ +import type { + ProjectId, + ProviderInstanceId, + ProviderProfile, + ServerSettings, + ServerSettingsPatch, +} from "@t3tools/contracts"; + +export function setProfilePatch(profileId: string, profile: ProviderProfile): ServerSettingsPatch { + return { trogonStack: { providerProfiles: { [profileId]: profile } } }; +} + +export function setProjectProfilePatch( + projectId: ProjectId, + profileId: string | null, +): ServerSettingsPatch { + return { trogonStack: { projectProfiles: { [projectId]: profileId } } }; +} + +export function toggleProfileInstance( + profile: ProviderProfile, + instanceId: ProviderInstanceId, + allowed: boolean, +): ProviderProfile { + const included = profile.providerInstanceIds.includes(instanceId); + if (included === allowed) return profile; + return { + ...profile, + providerInstanceIds: allowed + ? [...profile.providerInstanceIds, instanceId] + : profile.providerInstanceIds.filter((candidate) => candidate !== instanceId), + }; +} + +export function removeProfilePatch(profileId: string): ServerSettingsPatch { + return { trogonStack: { providerProfiles: { [profileId]: null } } }; +} + +export interface ProviderInstanceOption { + readonly instanceId: ProviderInstanceId; + readonly label: string; +} + +type ProfileSettings = Pick; + +export function sortedProfiles(settings: ProfileSettings) { + return Object.entries(settings.trogonStack.providerProfiles).toSorted((left, right) => + left[1].name.localeCompare(right[1].name), + ); +} + +export function profileNameTaken( + settings: ProfileSettings, + name: string, + exceptProfileId?: string, +): boolean { + const wanted = name.trim().toLowerCase(); + return Object.entries(settings.trogonStack.providerProfiles).some( + ([profileId, profile]) => + profileId !== exceptProfileId && profile.name.trim().toLowerCase() === wanted, + ); +} + +export function profileProviderLabels( + profile: ProviderProfile, + options: ReadonlyArray, +): string[] { + const known = new Set(options.map(({ instanceId }) => instanceId)); + return [ + ...options + .filter(({ instanceId }) => profile.providerInstanceIds.includes(instanceId)) + .map(({ label }) => label), + ...profile.providerInstanceIds + .filter((instanceId) => !known.has(instanceId)) + .map((instanceId) => `${instanceId} (removed)`), + ]; +} + +export function profileUsageText( + settings: ProfileSettings, + profileId: string, + titles: ReadonlyMap, +): string { + const assigned = Object.entries(settings.trogonStack.projectProfiles) + .filter(([, assignedId]) => assignedId === profileId) + .map(([projectId]) => titles.get(projectId as ProjectId)); + if (assigned.length === 0) return "No project uses it yet."; + const known = assigned + .filter((title) => title !== undefined) + .toSorted((left, right) => left.localeCompare(right)); + const hidden = assigned.length - known.length; + const names = + hidden > 0 ? [...known, `${hidden} other project${hidden === 1 ? "" : "s"}`] : known; + return `Used by ${names.join(", ")}. Move them to another profile to delete this one.`; +} + +export function profileInUse(settings: ProfileSettings, profileId: string): boolean { + return Object.values(settings.trogonStack.projectProfiles).includes(profileId); +} + +/** Titles as the user knows the projects; checkouts sharing a title also show their folder. */ +export function projectDisplayTitles( + projects: ReadonlyArray<{ + readonly id: ProjectId; + readonly title: string; + readonly workspaceRoot: string; + }>, +): Map { + const counts = new Map(); + for (const { title } of projects) counts.set(title, (counts.get(title) ?? 0) + 1); + return new Map( + projects.map(({ id, title, workspaceRoot }) => [ + id, + (counts.get(title) ?? 0) > 1 ? `${title} (${workspaceRoot})` : title, + ]), + ); +} + +export function projectProfileDescription( + settings: ProfileSettings, + projectId: ProjectId, + options: ReadonlyArray, +): string { + const profileId = settings.trogonStack.projectProfiles[projectId]; + if (profileId === undefined) { + return projectRequiresProfile(settings, projectId) + ? "Blocked until you pick a profile." + : "Not restricted. Can use every provider."; + } + const profile = settings.trogonStack.providerProfiles[profileId]; + if (!profile) return "Its profile was deleted. Blocked until you pick another."; + const labels = profileProviderLabels(profile, options); + return labels.length + ? `Can use ${labels.join(", ")}.` + : `Can use no providers. Add some to ${profile.name}.`; +} + +function projectRequiresProfile(settings: ProfileSettings, projectId: ProjectId): boolean { + return settings.trogonStack.projectsRequiringProfile[projectId] === true; +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index f77a72cbc12b2..5c20e363a2f5e 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -27,6 +27,7 @@ export type SettingsPath = | "/settings/keybindings" | "/settings/snap-shot" | "/settings/providers" + | "/settings/provider-profiles" | "/settings/threads" | "/settings/browser" | "/settings/devices" @@ -102,6 +103,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = { "/settings/keybindings": msg("Keybindings"), "/settings/snap-shot": msg("SnapShots"), "/settings/providers": msg("Providers"), + "/settings/provider-profiles": msg("Provider profiles"), "/settings/threads": msg("Threads"), "/settings/browser": msg("Browser"), "/settings/devices": msg("Devices"), @@ -283,6 +285,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/projects", searchTerms: ["name icon emoji image checkout remove delete"], }, + { + id: "project-provider-profile", + title: "Project provider profile", + to: "/settings/projects", + searchTerms: ["assign provider profile project company personal access separation"], + }, { id: "default-model", title: "Default model", @@ -985,6 +993,21 @@ export const SETTINGS_SEARCH_ITEMS = [ "agents cli codex claude cursor grok fx kiro opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume", ], }, + { + id: "provider-profiles", + title: "Provider profiles", + to: "/settings/labs", + searchTerms: ["company personal providers group allowlist separation project policy"], + providerSettingsOnly: true, + }, + { + id: "provider-profiles-projects", + title: "Project provider profiles", + to: "/settings/provider-profiles", + targetId: "provider-profiles-projects", + searchTerms: ["assign profile project company personal access separation"], + providerSettingsOnly: true, + }, { id: "usage-providers", title: "Usage providers", @@ -1392,6 +1415,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly { it("uses this computer's settings and keeps agents that failed to load with the found ones", () => { const acpRegistry = ProviderDriverKind.make("acpRegistry"); - const settings: Pick = { + const settings: Pick< + ServerSettings, + "providerInstances" | "projectSettingsOverrides" | "trogonStack" + > = { + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, providerInstances: { [ProviderInstanceId.make("pi")]: { driver: ProviderDriverKind.make("pi") }, [ProviderInstanceId.make("registry")]: { driver: acpRegistry }, diff --git a/apps/web/src/onboarding/welcomePage.logic.ts b/apps/web/src/onboarding/welcomePage.logic.ts index acde259ad0d5d..c28cbd27dada5 100644 --- a/apps/web/src/onboarding/welcomePage.logic.ts +++ b/apps/web/src/onboarding/welcomePage.logic.ts @@ -12,7 +12,10 @@ import { import { getOnboardingProviderState } from "./providerReadiness.logic"; -type ComputerSettings = Pick; +type ComputerSettings = Pick< + ServerSettings, + "providerInstances" | "projectSettingsOverrides" | "trogonStack" +>; // Ready agents first, then ones that need a sign-in or a look. Never ranked by vendor. const FOUND_ORDER = { ready: 0, signIn: 1, attention: 2 } as const; diff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.ts index 891f3312ae833..a5e8bbb278bbd 100644 --- a/apps/web/src/providerInstances.test.ts +++ b/apps/web/src/providerInstances.test.ts @@ -1,5 +1,6 @@ import { DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_SERVER_SETTINGS, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -88,6 +89,7 @@ describe("applyProviderInstanceSettings", () => { }, }, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -109,6 +111,7 @@ describe("applyProviderInstanceSettings", () => { { providerInstances: {}, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -136,6 +139,7 @@ describe("applyProviderInstanceSettings", () => { }, }, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -153,6 +157,7 @@ describe("applyProviderInstanceSettings", () => { { providerInstances: {}, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -553,6 +558,7 @@ describe("provider icon metadata", () => { { providerInstances: { [instanceId]: { driver, enabled: true, config: registryConfig } }, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -570,6 +576,7 @@ describe("provider icon metadata", () => { }, }, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); @@ -583,6 +590,7 @@ describe("provider icon metadata", () => { { providerInstances: { [instanceId]: { driver, enabled: true, config: registryConfig } }, projectSettingsOverrides: {}, + trogonStack: DEFAULT_SERVER_SETTINGS.trogonStack, }, null, ); diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index fa4cd69a75dc5..7423fc93413d8 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -118,7 +118,7 @@ export function brandProviderInstanceEntries( /** projectId applies project overrides; explicit null uses machine settings. */ export function applyProviderInstanceSettings( entries: ReadonlyArray, - settings: Pick, + settings: Pick, projectId: ProjectId | null, ): ReadonlyArray { return entries.map((entry) => { @@ -161,7 +161,7 @@ function applyProviderInstanceBranding( /** Picker order: each driver's default instance first, then its custom instances. */ export function providerInstanceEntriesFor( providers: ReadonlyArray, - settings: Pick, + settings: Pick, projectId: ProjectId | null, ): ReadonlyArray { return pipe( diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 1b93b3966b4ef..ff389c9324504 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -32,6 +32,7 @@ import { Route as ChatSettingsSnapShotRouteImport } from './routes/_chat.setting import { Route as ChatSettingsSecretsRouteImport } from './routes/_chat.settings.secrets' import { Route as ChatSettingsScheduledTasksRouteImport } from './routes/_chat.settings.scheduled-tasks' import { Route as ChatSettingsProvidersRouteImport } from './routes/_chat.settings.providers' +import { Route as ChatSettingsProviderProfilesRouteImport } from './routes/_chat.settings.provider-profiles' import { Route as ChatSettingsProjectsRouteImport } from './routes/_chat.settings.projects' import { Route as ChatSettingsOpenSourceLicensesRouteImport } from './routes/_chat.settings.open-source-licenses' import { Route as ChatSettingsMaintenanceRouteImport } from './routes/_chat.settings.maintenance' @@ -170,6 +171,12 @@ const ChatSettingsProvidersRoute = ChatSettingsProvidersRouteImport.update({ path: '/providers', getParentRoute: () => ChatSettingsRoute, } as any) +const ChatSettingsProviderProfilesRoute = + ChatSettingsProviderProfilesRouteImport.update({ + id: '/provider-profiles', + path: '/provider-profiles', + getParentRoute: () => ChatSettingsRoute, + } as any) const ChatSettingsProjectsRoute = ChatSettingsProjectsRouteImport.update({ id: '/projects', path: '/projects', @@ -307,6 +314,7 @@ export interface FileRoutesByFullPath { '/settings/maintenance': typeof ChatSettingsMaintenanceRoute '/settings/open-source-licenses': typeof ChatSettingsOpenSourceLicensesRoute '/settings/projects': typeof ChatSettingsProjectsRoute + '/settings/provider-profiles': typeof ChatSettingsProviderProfilesRoute '/settings/providers': typeof ChatSettingsProvidersRoute '/settings/scheduled-tasks': typeof ChatSettingsScheduledTasksRoute '/settings/secrets': typeof ChatSettingsSecretsRoute @@ -351,6 +359,7 @@ export interface FileRoutesByTo { '/settings/maintenance': typeof ChatSettingsMaintenanceRoute '/settings/open-source-licenses': typeof ChatSettingsOpenSourceLicensesRoute '/settings/projects': typeof ChatSettingsProjectsRoute + '/settings/provider-profiles': typeof ChatSettingsProviderProfilesRoute '/settings/providers': typeof ChatSettingsProvidersRoute '/settings/scheduled-tasks': typeof ChatSettingsScheduledTasksRoute '/settings/secrets': typeof ChatSettingsSecretsRoute @@ -397,6 +406,7 @@ export interface FileRoutesById { '/_chat/settings/maintenance': typeof ChatSettingsMaintenanceRoute '/_chat/settings/open-source-licenses': typeof ChatSettingsOpenSourceLicensesRoute '/_chat/settings/projects': typeof ChatSettingsProjectsRoute + '/_chat/settings/provider-profiles': typeof ChatSettingsProviderProfilesRoute '/_chat/settings/providers': typeof ChatSettingsProvidersRoute '/_chat/settings/scheduled-tasks': typeof ChatSettingsScheduledTasksRoute '/_chat/settings/secrets': typeof ChatSettingsSecretsRoute @@ -443,6 +453,7 @@ export interface FileRouteTypes { | '/settings/maintenance' | '/settings/open-source-licenses' | '/settings/projects' + | '/settings/provider-profiles' | '/settings/providers' | '/settings/scheduled-tasks' | '/settings/secrets' @@ -487,6 +498,7 @@ export interface FileRouteTypes { | '/settings/maintenance' | '/settings/open-source-licenses' | '/settings/projects' + | '/settings/provider-profiles' | '/settings/providers' | '/settings/scheduled-tasks' | '/settings/secrets' @@ -532,6 +544,7 @@ export interface FileRouteTypes { | '/_chat/settings/maintenance' | '/_chat/settings/open-source-licenses' | '/_chat/settings/projects' + | '/_chat/settings/provider-profiles' | '/_chat/settings/providers' | '/_chat/settings/scheduled-tasks' | '/_chat/settings/secrets' @@ -719,6 +732,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatSettingsProvidersRouteImport parentRoute: typeof ChatSettingsRoute } + '/_chat/settings/provider-profiles': { + id: '/_chat/settings/provider-profiles' + path: '/provider-profiles' + fullPath: '/settings/provider-profiles' + preLoaderRoute: typeof ChatSettingsProviderProfilesRouteImport + parentRoute: typeof ChatSettingsRoute + } '/_chat/settings/projects': { id: '/_chat/settings/projects' path: '/projects' @@ -881,6 +901,7 @@ interface ChatSettingsRouteChildren { ChatSettingsMaintenanceRoute: typeof ChatSettingsMaintenanceRoute ChatSettingsOpenSourceLicensesRoute: typeof ChatSettingsOpenSourceLicensesRoute ChatSettingsProjectsRoute: typeof ChatSettingsProjectsRoute + ChatSettingsProviderProfilesRoute: typeof ChatSettingsProviderProfilesRoute ChatSettingsProvidersRoute: typeof ChatSettingsProvidersRoute ChatSettingsScheduledTasksRoute: typeof ChatSettingsScheduledTasksRoute ChatSettingsSecretsRoute: typeof ChatSettingsSecretsRoute @@ -911,6 +932,7 @@ const ChatSettingsRouteChildren: ChatSettingsRouteChildren = { ChatSettingsMaintenanceRoute: ChatSettingsMaintenanceRoute, ChatSettingsOpenSourceLicensesRoute: ChatSettingsOpenSourceLicensesRoute, ChatSettingsProjectsRoute: ChatSettingsProjectsRoute, + ChatSettingsProviderProfilesRoute: ChatSettingsProviderProfilesRoute, ChatSettingsProvidersRoute: ChatSettingsProvidersRoute, ChatSettingsScheduledTasksRoute: ChatSettingsScheduledTasksRoute, ChatSettingsSecretsRoute: ChatSettingsSecretsRoute, diff --git a/apps/web/src/routes/_chat.settings.provider-profiles.tsx b/apps/web/src/routes/_chat.settings.provider-profiles.tsx new file mode 100644 index 0000000000000..f8af4981b50d8 --- /dev/null +++ b/apps/web/src/routes/_chat.settings.provider-profiles.tsx @@ -0,0 +1,22 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { ProviderProfilesPage } from "../components/settings/ProviderProfilesSettings"; +import { useSettingsScope } from "../components/settings/SettingsScopeContext"; + +function SettingsProviderProfilesRoute() { + const { environment, scope } = useSettingsScope(); + if (!environment) { + return ( +

+ {scope.kind === "environment" + ? `Reconnect ${scope.label} to set up its provider profiles.` + : "Connect an environment to set up its provider profiles."} +

+ ); + } + return ; +} + +export const Route = createFileRoute("/_chat/settings/provider-profiles")({ + component: SettingsProviderProfilesRoute, +}); diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index 20f65d45c7a5b..722653f0099c2 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -111,7 +111,9 @@ function SettingsContentLayout() { const location = useLocation(); const { search, environment } = useSettingsScope(); const contentScopeKey = - location.pathname === "/settings/diagnostics" || location.pathname === "/settings/providers" + location.pathname === "/settings/diagnostics" || + location.pathname === "/settings/providers" || + location.pathname === "/settings/provider-profiles" ? environment?.environmentId : JSON.stringify(search); const [restoreSignal, setRestoreSignal] = useState(0); diff --git a/apps/web/src/textGenerators.ts b/apps/web/src/textGenerators.ts index fa7941d150e18..2e7b483a33ae7 100644 --- a/apps/web/src/textGenerators.ts +++ b/apps/web/src/textGenerators.ts @@ -279,7 +279,7 @@ export function useTextGenerationTargets(input: { readonly environmentId: EnvironmentId | null; readonly settings: Pick< ServerSettings, - "providerInstances" | "projectSettingsOverrides" | "textGenerators" + "providerInstances" | "projectSettingsOverrides" | "textGenerators" | "trogonStack" >; readonly providers: ReadonlyArray; readonly projectId: ProjectId | null; diff --git a/docs/fork/0038-provider-profiles-keep-projects-apart.md b/docs/fork/0038-provider-profiles-keep-projects-apart.md new file mode 100644 index 0000000000000..717fc3afd7ba3 --- /dev/null +++ b/docs/fork/0038-provider-profiles-keep-projects-apart.md @@ -0,0 +1,39 @@ +# 0038: Provider profiles keep projects apart + +- PR: [TrogonStack/t3code#237](https://github.com/TrogonStack/t3code/pull/237) +- Status: active + +## What you can do now + +- Name a set of allowed provider instances once, such as Personal or one per company, and assign + it to a project instead of switching providers on and off project by project. +- Trust that a project only runs on its profile's instances. Anything else is left out of the + model picker and refused by the server, including turns the server starts on its own. +- Add a provider instance without it leaking into existing work. A new instance belongs to no + profile until you add it, and removing an instance removes it from every profile. +- Start new projects safely. Once a profile exists, a new project cannot run a provider until it + is assigned one. Projects from before the first profile keep working as they did until you + assign them. +- Manage profiles, their providers, and each project's profile from one Provider profiles page, + opened from Labs in settings on web and desktop, and from provider and project settings on mobile. + +## Why + +Some work cannot share models or accounts across companies for legal reasons. Per-project +provider switches made that a checklist to repeat for every new project and every new provider, +and one missed switch was enough to break the separation. A profile states the boundary once and +the project inherits it. + +## Upstream considerations + +Worth proposing as an idea first: upstream already has per-project provider switches, and a +profile is a named, reusable form of the same rule. The open product questions are whether a +project with no profile should be blocked once any profile exists, and whether a profile should +follow a thread delegated to another environment. + +The rebase burden is moderate. The profile data lives in the fork's own settings block, but the +rule is checked wherever a provider is resolved and where a turn starts, and upstream changes +those paths often. A sync that adds a new way to start a turn or pick a provider needs the profile +check carried to it. On web, the list of providers the Providers page shows moved out of that page +into its own module so the profiles page offers the same ones; upstream edits to that list need +carrying over. diff --git a/docs/fork/README.md b/docs/fork/README.md index 880ee9a9ea309..ed9f4d806c460 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -49,3 +49,5 @@ active, [#17](https://github.com/TrogonStack/t3code/pull/17) active, [#87](https://github.com/TrogonStack/t3code/pull/87) - **0037** [Generated files start folded in a pull request's diff](./0037-generated-files-start-folded.md) active, [#219](https://github.com/TrogonStack/t3code/pull/219) +- **0038** [Provider profiles keep projects apart](./0038-provider-profiles-keep-projects-apart.md) + active, [#237](https://github.com/TrogonStack/t3code/pull/237) diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 899640ad23590..d69302e7e29d8 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -197,6 +197,29 @@ itself, or **Skip** to leave them for a setup script. It resolves in the same or workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out applies when the project and environment are both on **Inherit**. +## Provider profiles + +A provider profile is a named list of the provider instances a project may use. Use one per +company or account boundary, such as Personal and Company A, when a project must never run on +another boundary's models. + +Create and manage profiles in **Settings → Labs → Provider profiles → Manage profiles**. There you choose each profile's +providers, rename or delete it, and pick a profile for each project. You can also choose a +provider's profiles from the provider's own settings under **Profiles**, and a project's profile +in **Settings → Projects** under **Provider profile**. Each environment keeps its own profiles and +assignments. + +- A project with a profile can only use that profile's instances, for agent turns and for text + generation alike. Other instances are hidden from its model picker and refused by the server. +- A provider instance you add later belongs to no profile until you choose one in its settings. +- Once at least one profile exists, a new project cannot run providers until you assign it one. + Projects that existed before stay unrestricted until you assign them. +- A profile can be deleted only when no project uses it. Removing a provider instance also + removes it from every profile. + +Changing a project's profile affects future turns. It does not erase context an existing thread +already holds. + ## Worktree location New worktrees go in the `worktrees` folder of the T3 home directory. To put them somewhere else, diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 1db913e38ba3b..53fab7d47a667 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -488,6 +488,31 @@ describe("resolveProjectProviderInstanceEnabled", () => { }; expect(resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)).toBe(false); }); + + it("limits an assigned project to its profile even when a project override enables another instance", () => { + const settings = decodeServerSettings({ + providerInstances: { + [instanceId]: { driver: "codex", enabled: true }, + claude_work: { driver: "claudeAgent", enabled: true }, + }, + projectSettingsOverrides: { + [projectId]: { providerInstances: { claude_work: { enabled: true } } }, + }, + trogonStack: { + providerProfiles: { personal: { name: "Personal", providerInstanceIds: [instanceId] } }, + projectProfiles: { [projectId]: "personal" }, + }, + }); + expect(resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)).toBe(true); + expect( + resolveProjectProviderInstanceEnabled( + settings, + projectId, + ProviderInstanceId.make("claude_work"), + ), + ).toBe(false); + expect(encodeServerSettings(settings)).toHaveProperty("trogonStack"); + }); }); describe("requiredScopesForProjectMutation", () => { diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b58c1d59de1df..a7d702afcb810 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1359,7 +1359,29 @@ export const CloudSpeechCredentials = Schema.Struct({ openrouter: CloudSpeechCredential, }); +export const ProviderProfile = Schema.Struct({ + name: TrimmedNonEmptyString, + providerInstanceIds: Schema.Array(ProviderInstanceId), +}); +export type ProviderProfile = typeof ProviderProfile.Type; + +export const TrogonStackSettings = Schema.Struct({ + providerProfiles: Schema.Record(TrimmedNonEmptyString, ProviderProfile).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + projectProfiles: Schema.Record(ProjectId, TrimmedNonEmptyString).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + projectsRequiringProfile: Schema.Record(ProjectId, Schema.Boolean).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), +}); +export type TrogonStackSettings = typeof TrogonStackSettings.Type; + export const ServerSettings = Schema.Struct({ + trogonStack: TrogonStackSettings.pipe( + Schema.withDecodingDefault(Effect.succeed(Schema.decodeSync(TrogonStackSettings)({}))), + ), // Null means unmigrated; empty is authoritative and must not resurrect cleared preferences. favorites: Schema.NullOr(ModelFavorites).pipe(Schema.withDecodingDefault(Effect.succeed(null))), providerModelPreferences: Schema.NullOr(ProviderModelPreferences).pipe( @@ -1636,10 +1658,12 @@ export const resolveProviderInstanceEnabled = ( }; export const resolveProjectProviderInstanceEnabled = ( - settings: Pick, + settings: Pick & + Pick, projectId: ProjectId | null, instanceId: ProviderInstanceId, ): boolean => { + if (!isProviderInstanceAllowedByProfile(settings, projectId, instanceId)) return false; const override = projectId === null ? undefined @@ -1653,6 +1677,21 @@ export const resolveProjectProviderInstanceEnabled = ( : isUnconfiguredDefaultInstanceEnabled(instanceId); }; +export const isProviderInstanceAllowedByProfile = ( + settings: Pick, + projectId: ProjectId | null, + instanceId: ProviderInstanceId, +): boolean => { + if (projectId === null) return true; + const profileId = settings.trogonStack.projectProfiles[projectId]; + if (profileId === undefined) + return settings.trogonStack.projectsRequiringProfile[projectId] !== true; + return ( + settings.trogonStack.providerProfiles[profileId]?.providerInstanceIds.includes(instanceId) ?? + false + ); +}; + /** The text generator a selection names, if any; it takes precedence over a provider instance. */ export const textGeneratorForSelection = ( settings: Pick, @@ -1667,12 +1706,14 @@ export const resolveTextGenerationSelectionEnabled = ( settings: Pick< ServerSettings, "providerInstances" | "projectSettingsOverrides" | "textGenerators" - >, + > & + Pick, projectId: ProjectId | null, instanceId: ProviderInstanceId, ): boolean => - textGeneratorForSelection(settings, instanceId)?.enabled ?? - resolveProjectProviderInstanceEnabled(settings, projectId, instanceId); + isProviderInstanceAllowedByProfile(settings, projectId, instanceId) && + (textGeneratorForSelection(settings, instanceId)?.enabled ?? + resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)); const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings); @@ -1794,6 +1835,19 @@ const ModelSelectionPatch = Schema.Struct({ }); export const ServerSettingsPatch = Schema.Struct({ + trogonStack: Schema.optionalKey( + Schema.Struct({ + providerProfiles: Schema.optionalKey( + Schema.Record(TrimmedNonEmptyString, Schema.NullOr(ProviderProfile)), + ), + projectProfiles: Schema.optionalKey( + Schema.Record(ProjectId, Schema.NullOr(TrimmedNonEmptyString)), + ), + projectsRequiringProfile: Schema.optionalKey( + Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)), + ), + }), + ), setModelFavorites: Schema.optionalKey( Schema.Array(Schema.Struct({ ...ModelFavorite.fields, favorite: Schema.Boolean })), ), @@ -1998,6 +2052,9 @@ export function requiredScopesForServerSettingsPatch( if (value === undefined) continue; if (key === "requireConnectDeviceApproval") { changesAccess = true; + } else if (key === "trogonStack") { + changesProviders = true; + changesSettings = true; } else if ( key === "providers" || key === "providerInstances" || diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index 5cf8770b33e4b..f755fd244234e 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -91,6 +91,31 @@ describe("fallbackTextGenerationModelSelection", () => { }); describe("serverSettings helpers", () => { + it("updates profile entries without replacing other profiles or project assignments", () => { + const projectId = ProjectId.make("project-1"); + const otherProjectId = ProjectId.make("project-2"); + const codexId = ProviderInstanceId.make("codex"); + const initial = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + trogonStack: { + providerProfiles: { + personal: { name: "Personal", providerInstanceIds: [codexId] }, + work: { name: "Work", providerInstanceIds: [] }, + }, + projectProfiles: { [projectId]: "work", [otherProjectId]: "personal" }, + }, + }); + const updated = applyServerSettingsPatch(initial, { + trogonStack: { + providerProfiles: { work: null }, + projectProfiles: { [projectId]: null }, + }, + }); + expect(updated.trogonStack.providerProfiles).toEqual({ + personal: { name: "Personal", providerInstanceIds: [codexId] }, + }); + expect(updated.trogonStack.projectProfiles).toEqual({ [otherProjectId]: "personal" }); + }); + it("translates a shipped client's idle compaction switch into a mode", () => { const off = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { idleCompaction: "off" }); expect([off.idleCompaction, off.compactIdleThreads]).toEqual(["off", false]); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 023c6eb74333e..323d24ea16ccc 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -383,6 +383,20 @@ function patchedIdleCompaction( return globalIdleCompaction(current) === "off" ? "off" : "onReturn"; } +function applyNullableEntries( + current: Readonly>, + patch: Readonly> | undefined, +): Record { + const next = { ...current } as Record; + if (patch === undefined) return next; + for (const key of Object.keys(patch) as Key[]) { + const value = patch[key]; + if (value === null) delete next[key]; + else if (value !== undefined) next[key] = value; + } + return next; +} + export function applyServerSettingsPatch( current: ServerSettings, rawPatch: ServerSettingsPatch, @@ -409,6 +423,7 @@ export function applyServerSettingsPatch( usageModelAliases: usageModelAliasesPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, + trogonStack: trogonStackPatch, projectAgentBrowserAccessOverrides: _legacyBrowserAccess, projectAutoPullOverrides: _legacyAutoPull, projectScriptOverrides: _legacyScripts, @@ -506,6 +521,24 @@ export function applyServerSettingsPatch( ...next, favorites, providerModelPreferences: nextModelPreferences, + ...(trogonStackPatch === undefined + ? {} + : { + trogonStack: { + providerProfiles: applyNullableEntries( + current.trogonStack.providerProfiles, + trogonStackPatch.providerProfiles, + ), + projectProfiles: applyNullableEntries( + current.trogonStack.projectProfiles, + trogonStackPatch.projectProfiles, + ), + projectsRequiringProfile: applyNullableEntries( + current.trogonStack.projectsRequiringProfile, + trogonStackPatch.projectsRequiringProfile, + ), + }, + }), ...(worktreeCleanupPatch === undefined ? {} : {