feat: managed policy for organization-wide T3 Code configuration #27197
Mergedjuliusmarmingemerged 54 commits into
main fromrefs/pull/27197/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/ipc/methods/window.ts line 83OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -72,8 +73,11 @@7273 }),7374 });747576+/** Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read, stops them. */7577 export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({7678 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,7779 result: Schema.Boolean,7880 handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () {79- return isRelayTracingEnabled(yield* HostProcess.Environment);81+ if (!isRelayTracingEnabled(yield* HostProcess.Environment)) return false;82+ const { platform } = yield* DesktopEnvironment.DesktopEnvironment;83+ return yield* readManagedPolicyFile(managedPolicyPath(platform)).pipe(apps/server/src/policy/managedProviders.ts line 263Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +195,21 @@195+ instance: ProviderInstanceConfig,196+ rule: DriverRule,197+): ProviderInstanceConfig => {198+ const config = { ...configRecord(instance) };199+ for (const field of rule.config) {200+ const value = pinnedValue(rule.pin, field);201+ if (value === undefined) delete config[field];202+ else config[field] = value;203+ }204+ for (const field of rule.fill) {205+ if (configValue(instance, field) === undefined) config[field] = rule.pin?.[field];206+ }207+ const pinnedEnvironment = (rule.pin?.environment ?? []).map((variable) => ({208+ name: variable.name,209+ value: variable.value,210+ sensitive: false,211+ }));212+ const environment =213+ rule.environment === "all" ? pinnedEnvironment : [...(instance.environment ?? [])];214+ if (rule.environment !== "all") {215+ for (const pinned of pinnedEnvironment) {apps/server/src/cli/policy.ts line 51OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ lines.push("", "Limits:", JSON.stringify(rest, null, 2));32+ }33+ return `${lines.join("\n")}\n`;34+};35+36+const showCommand = Command.make("show").pipe(37+ Command.withDescription("Show the policy that applies to T3 Code on this machine."),38+ Command.withHandler(() =>39+ ManagedPolicy.ManagedPolicy.pipe(40+ Effect.flatMap((policy) => Console.log(describePolicy(policy))),41+ Effect.provide(ManagedPolicy.layer),42+ ),43+ ),44+);45+46+const checkCommand = Command.make("check", {47+ file: Argument.String("file").pipe(Argument.withDescription("Policy file to validate.")),48+}).pipe(49+ Command.withDescription("Validate a policy file before deploying it."),50+ Command.withHandler(({ file }) =>51+ ManagedPolicy.load(file).pipe(Effect.flatMap((policy) => Console.log(describePolicy(policy)))),apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx line 493OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -454,4 +488,6 @@454488 mode={uniform("branchNamingMode")}455489 prefix={uniform("branchNamePrefix")}456490 instructions={uniform("branchNameInstructions")}457- disabled={disabledFor("branchNamingMode")}491+ disabled={492+ disabledFor("branchNamingMode") ||493+ managed("branchNamePrefix", "branchNameInstructions") !== undefinedapps/server/src/orchestration-v2/Orchestrator.ts line 1561OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1521,3 +1557,5 @@15211557 if (15221558 worktreeMissing ||15231559 instanceDisabledForProject ||1560+ // The thread sits above the policy's ceiling; the queue resumes once its mode is lowered.1561+ isRuntimeModeAbove(projection.thread.runtimeMode, runtimeModeCeiling?.maxRuntimeMode) ||apps/server/src/policy/managedSettings.ts line 383Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +229,21 @@229+230+ const defaultsTree = defaults.reduce<unknown>(231+ (tree, entry) => setPath(tree, entry.segments, entry.value),232+ {},233+ );234+ const lockEntries: ReadonlyArray<Lock> = locks.map((entry) => ({235+ ...entry,236+ decodedValue: getPath(decoded.value, entry.segments),237+ }));238+ const lockedPaths = locks.map((entry) => entry.path);239+ const lockCache = new WeakMap<ServerSettings, ServerSettings>();240+241+ const applyLocks = (current: ServerSettings): ServerSettings => {242+ if (locks.length === 0 && maxRuntimeMode === undefined) return current;243+ const cached = lockCache.get(current);244+ if (cached !== undefined) return cached;245+ const locked =246+ locks.length === 0247+ ? current248+ : // Validated against the built-in defaults above, so a failure here is a bug, not bad input.249+ decodeSettings(apps/server/src/policy/managedSettings.ts line 291OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +271,21 @@271+ // Re-sending a stored value the lock overrides changes nothing on disk, but it is still272+ // an attempt to change what the user sees.273+ lockTargets(patch, entry).some((target) => {274+ const value = getPath(patch, target);275+ return value !== undefined && !jsonEqual(value, entry.decodedValue);276+ }) ||277+ lockTargets(after, entry).some((target) => {278+ const value = getPath(after, target);279+ // Removing a project's override of a locked key is harmless; the lock applies either way.280+ return (281+ value !== undefined &&282+ !jsonEqual(value, getPath(before, target)) &&283+ !jsonEqual(value, entry.value)284+ );285+ }),286+ );287+ if (changed !== undefined) return { _tag: "Locked", path: changed.path };288+ const kept = locks.reduce<unknown>(289+ (tree, entry) =>290+ lockTargets(tree, entry).reduce<unknown>(291+ (result, target) => setPath(result, target, getPath(before, target)),@@ -593,4 +632,4 @@593632 const writeSettingsAtomically = Effect.fnUntraced(594633 function* (settings: ServerSettings) {595634 const sparseSettingsJson = yield* encodeServerSettingsJson(596- stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},635+ stripDefaultServerSettings(settings, managed.defaults) ?? {},apps/server/src/serverSettings.ts line 1156Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1006,4 +1049,17 @@10061049 }10071050 const updated = yield* update(current);10081051 const persisted = yield* persistSettingsSecrets(current, updated);1009- const next = yield* normalizeServerSettings(persisted.settings);1052+ const vetted = managed.vetWrite(1053+ current,1054+ yield* normalizeServerSettings(persisted.settings),1055+ patch,1056+ );1057+ if (vetted._tag === "Locked") {1058+ return yield* new ServerSettingsError({1059+ settingsPath,1060+ operation: "write-managed-setting",1061+ managedSetting: vetted.path,1062+ managedBy: managedPolicy?.organization,1063+ });1064+ }1065+ const vettedProviders = managedProviders.vetWrite(current, vetted.settings);apps/server/src/serverSettings.ts lines 450 to 450OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -415,8 +432,19 @@432+ const selection = settings.textGenerationModelSelection;433+ return isModelSelectionProviderEnabled(settings, selection) &&434+ selectionSupportsTextGeneration(settings, selection) &&435+ isDriverAllowed(436+ settings.providerInstances[selection.instanceId]?.driver ??437+ ProviderDriverKind.make(selection.instanceId),438+ )415439 ? settings416- : fallbackTextGenerationProvider(settings);440+ : fallbackTextGenerationProvider(settings, isDriverAllowed);417441 }418442419-function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {443+function fallbackTextGenerationProvider(444+ settings: ServerSettings,445+ isDriverAllowed: DriverAllowed,446+): ServerSettings {420447 const fallback = fallbackTextGenerationModelSelection(421448 settings.providerInstances,422449 (instanceId, driver) =>450+ isDriverAllowed(driver) &&@@ -165,4 +167,16 @@165167166168 const [wizardStep, setWizardStep] = useState(0);167169 const [addingChatGptAccount, setAddingChatGptAccount] = useState(false);168- const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);170+ // Drivers the administrator's policy leaves out are not offered at all.171+ const managedPolicy = useManagedPolicy(environmentId);172+ const featuredDriverOptions = FEATURED_DRIVER_OPTIONS.filter((option) =>173+ isManagedDriverAllowed(managedPolicy, option.driverKind),174+ );175+ const moreDriverOptions = MORE_DRIVER_OPTIONS.filter((option) =>176+ isManagedDriverAllowed(managedPolicy, option.driverKind),177+ );178+ const acpRegistryAllowed = isManagedDriverAllowed(managedPolicy, ACP_REGISTRY_DRIVER_KIND);179+ const [driver, setDriver] = useState<ProviderDriverKind>(180+ () =>181+ (featuredDriverOptions[0] ?? moreDriverOptions[0])?.driverKind ??182+ (acpRegistryAllowed ? ACP_REGISTRY_DRIVER_KIND : DEFAULT_DRIVER_KIND),apps/web/src/components/sidebar/updateEverything.logic.ts lines 101 to 105OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -88,3 +94,12 @@8894 skip("already updating");8995 continue;9096 }97+ // The server refuses these with the same message; say so before the run instead of after.98+ const policy = config.managedPolicy;99+ const managedDenial =100+ managedUpdatesDenial(policy) ??101+ (policy !== undefined &&102+ policy.limits?.updates?.allowNightly === false &&103+ cliReleaseChannelOf(targetVersion) !== "stable"104+ ? managedUpdatesMessage(policy.organization)105+ : undefined);apps/web/src/components/settings/ProviderInstanceCard.tsx lines 1299 to 1302Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1183,3 +1210,8 @@11831210 idPrefix={`provider-instance-${instanceId}`}11841211 onCommit={updateEnvironmentField}11851212 onRemove={removeEnvironmentField}1213+ managedReason={1214+ instanceLocks?.environmentNames.has(field.name)1215+ ? instanceLocks.reason1216+ : undefined1217+ }
- apps/desktop/src/updates/DesktopUpdates.ts line 1137Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1088,3 +1127,4 @@10881127 provider: "generic",10891128 url: `http://localhost:${config.mockUpdateServerPort}`,10901129 } as ElectronUpdater.ElectronUpdaterFeedUrl);1130+ } else if (policy.feedUrl !== undefined) {
- apps/server/src/policy/managedProviders.ts line 439OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +419,21 @@419+ const kept: ProviderInstanceConfig = {420+ ...envelope,421+ ...(Object.keys(config).length === 0 && stored?.config === undefined ? {} : { config }),422+ ...(environment.length === 0 ? {} : { environment }),423+ };424+ // A default instance the client echoed back with only pinned values stays implicit.425+ const echoedDefault =426+ stored === undefined &&427+ instanceId === defaultInstanceIdForDriver(next.driver) &&428+ Object.keys(kept).length === 1;429+ return { _tag: "Kept", instance: echoedDefault ? undefined : kept };430+ };431+432+ const vetWrite = (current: ServerSettings, next: ServerSettings): ProviderWriteVerdict => {433+ const providerInstances: Record<string, ProviderInstanceConfig> = {};434+ for (const [instanceId, instance] of Object.entries(next.providerInstances)) {435+ const stored = current.providerInstances[instanceId as ProviderInstanceId];436+ if (437+ !isDriverAllowed(instance.driver) &&438+ resolveProviderInstanceEnabled(instance) &&439+ JSON.stringify(stored) !== JSON.stringify(instance)apps/server/src/policy/managedSettings.ts line 312OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +292,21 @@292+ ),293+ encodeSettings(current),294+ ),295+ );296+ const result =297+ maxRuntimeMode === undefined ? locked : clampDefaultRuntimeModes(locked, maxRuntimeMode);298+ lockCache.set(current, result);299+ return result;300+ };301+302+ const vetWrite: ManagedSettings["vetWrite"] = (current, next, patch) => {303+ if (locks.length === 0) return { _tag: "Allowed", settings: next };304+ const before = encodeSettings(current);305+ const after = encodeSettings(next);306+ const changed = lockEntries.find(307+ (entry) =>308+ // Re-sending a stored value the lock overrides changes nothing on disk, but it is still309+ // an attempt to change what the user sees.310+ lockTargets(patch, entry).some((target) => {311+ const value = getPath(patch, target);312+ return value !== undefined && !jsonEqual(value, entry.decodedValue);apps/server/src/policy/managedProviders.ts line 367OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +347,21 @@347+ const vetEnvironment = (348+ instanceId: string,349+ stored: ProviderInstanceConfig | undefined,350+ next: ProviderInstanceConfig,351+ rule: DriverRule,352+ ):353+ | Locked354+ | {355+ readonly _tag: "Kept";356+ readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;357+ } => {358+ const pinned = rule.pin?.environment ?? [];359+ const storedVariable = (name: string) =>360+ stored?.environment?.find((existing) => existing.name === name);361+ const echoed = (variable: ProviderInstanceEnvironmentVariable) =>362+ !variable.sensitive &&363+ pinned.some((pin) => pin.name === variable.name && pin.value === variable.value);364+ if (rule.environment === "all") {365+ // Only the pinned variables were shown, so the user's own stay as stored.366+ for (const variable of next.environment ?? []) {367+ if (echoed(variable) || sameVariable(variable, storedVariable(variable.name))) continue;
- @@ -449,3 +472,11 @@449472 );450473 });451474475+ // Without nightly, an install on that channel stays put until its user picks stable: moving it476+ // silently would be a downgrade nobody asked for, and checking nightly would break the policy.477+ const channelBlockedReason = (channel: DesktopUpdateChannel): Option.Option<string> =>478+ channel === "nightly" && !policy.allowNightly479+ ? Option.some(480+ `${policy.message ?? "Nightly updates are turned off on this machine."} Switch to the stable channel to keep getting updates.`,481+ )482+ : Option.none();apps/server/src/cli/policy.ts lines 50 to 52OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+ }33+ return `${lines.join("\n")}\n`;34+};35+36+const showCommand = Command.make("show").pipe(37+ Command.withDescription("Show the policy that applies to T3 Code on this machine."),38+ Command.withHandler(() =>39+ ManagedPolicy.ManagedPolicy.pipe(40+ Effect.flatMap((policy) => Console.log(describePolicy(policy))),41+ Effect.provide(ManagedPolicy.layer),42+ ),43+ ),44+);45+46+const checkCommand = Command.make("check", {47+ file: Argument.String("file").pipe(Argument.withDescription("Policy file to validate.")),48+}).pipe(49+ Command.withDescription("Validate a policy file before deploying it."),50+ Command.withHandler(({ file }) =>51+ ManagedPolicy.load(file).pipe(Effect.flatMap((policy) => Console.log(describePolicy(policy)))),52+ ),apps/server/src/orchestration-v2/Orchestrator.ts lines 13429 to 13435Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -12918,4 +12984,10 @@1291812984 ),1291912985 Effect.catch((cause) =>1292012986 Effect.gen(function* () {12921- if (cause._tag === "OrchestratorThreadAboveModeLimitError") return yield* cause;12987+ // Refusals depend on modes the user can change; a recorded rejection would block the retry.12988+ if (12989+ cause._tag === "OrchestratorThreadAboveModeLimitError" ||12990+ cause._tag === "OrchestratorRuntimeModeAboveCeilingError"12991+ ) {12992+ return yield* cause;12993+ }apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1209 to 1218Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1127,3 +1149,17 @@11271149 const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(11281150 "ScheduledTaskService.upsert",11291151 )(function* (input) {1152+ if (input.schedule.type === "webhook" && webhookPolicyBlock !== undefined) {1153+ return yield* taskError(1154+ webhookPolicyBlock,1155+ input.id === undefined ? {} : { taskId: input.id },1156+ );1157+ }1158+ // Refused on save rather than at run time; a disabled task can still be saved, so one1159+ // stored above the ceiling can be turned off before its mode is lowered.1160+ const modeDenial = input.enabled1161+ ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)1162+ : undefined;1163+ if (modeDenial !== undefined) {1164+ return yield* taskError(modeDenial, input.id === undefined ? {} : { taskId: input.id });1165+ }apps/server/src/ws.ts lines 1834 to 1836Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1785,3 +1785,6 @@17851785 otlpLogsEnabled: config.otlpLogsUrl !== undefined,17861786 },17871787 settings,1788+ ...(serverSettings.managedPolicy === undefined1789+ ? {}1790+ : { managedPolicy: serverSettings.managedPolicy }),apps/web/src/components/ManagedPolicy.tsx lines 23 to 29Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+/**8+ * A control an administrator's policy turns off: shown inert, with the policy's reason on hover9+ * and focus. Without a reason it renders the control untouched.10+ */11+export function ManagedControl({12+ reason,13+ children,14+}: {15+ reason: string | undefined;16+ children: ReactNode;17+}) {18+ if (reason === undefined) return children;19+ return (20+ <Tooltip>21+ <TooltipTrigger22+ render={23+ <span24+ tabIndex={0}25+ aria-label={reason}26+ className="inline-flex rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"27+ />
- apps/server/src/policy/managedProviders.ts line 233Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +182,21 @@182+ * `environment`: `all` runs with only pinned variables, `locked` lets them win, `fill` fills gaps.183+ */184+interface DriverRule {185+ readonly pin: ManagedProviderInstance | undefined;186+ readonly config: ReadonlyArray<string>;187+ readonly fill: ReadonlyArray<PinnedConfigField>;188+ readonly environment: "all" | "locked" | "fill";189+}190+191+const pinnedValue = (pin: ManagedProviderInstance | undefined, field: string): unknown =>192+ pin === undefined ? undefined : (pin as Record<string, unknown>)[field];193+194+const overlayInstance = (195+ instance: ProviderInstanceConfig,196+ rule: DriverRule,197+): ProviderInstanceConfig => {198+ const config = { ...configRecord(instance) };199+ for (const field of rule.config) {200+ const value = pinnedValue(rule.pin, field);201+ if (value === undefined) delete config[field];202+ else config[field] = value;
- apps/web/src/components/settings/updateTrackSwitch.logic.ts line 69OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -48,3 +53,17 @@4853 : (local.message ?? `This app found no build of ${input.version} to install.`),4954 };5055 }56+57+/**58+ * Whether this app stays put while connected machines move. Its updater is off for a .deb install59+ * or without a feed, and under a policy without nightly while it runs nightly; moving to Stable60+ * ends that last case, so it switches itself then.61+ */62+export function localUpdaterStaysPut(63+ state: Pick<DesktopUpdateState, "enabled"> | null | undefined,64+ target: DesktopUpdateChannel,65+ localPolicy: ManagedPolicySummary | undefined,66+): boolean {67+ const updates = localPolicy?.limits?.updates;68+ const offOnlyForNightly =69+ target === "latest" && updates?.allowNightly === false && updates.mode !== "off";
- packages/shared/src/managedPolicyFile.ts line 136OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(117+ Effect.mapError(118+ (cause) =>119+ new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),120+ ),121+ );122+ if (converted.exitCode !== 0) {123+ return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });124+ }125+ return { source: path, document: yield* decodeDocument(path, converted.stdout) };126+ }127+ if (platform === "win32") {128+ const path = WINDOWS_POLICY_KEY;129+ const queried = yield* run(REG, ["query", path, "/v", "Policy", "/reg:64"]).pipe(130+ Effect.mapError(131+ (cause) =>132+ new ManagedPolicyFileError({ path, reason: "the registry cannot be read", cause }),133+ ),134+ );135+ // reg exits 1 when the key or value does not exist.136+ if (queried.exitCode === 1) return undefined;
- packages/shared/src/managedPolicyFile.ts lines 107 to 126OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ if (platform === "darwin") {107+ const path = MACOS_MANAGED_PREFERENCES_PATH;108+ const exists = yield* (yield* FileSystem.FileSystem)109+ .exists(path)110+ .pipe(111+ Effect.mapError(112+ (cause) =>113+ new ManagedPolicyFileError({ path, reason: "the profile cannot be checked", cause }),114+ ),115+ );116+ if (!exists) return undefined;117+ const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(118+ Effect.mapError(119+ (cause) =>120+ new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),121+ ),122+ );123+ if (converted.exitCode !== 0) {124+ return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });125+ }126+ return { source: path, document: yield* decodeDocument(path, converted.stdout) };
- packages/shared/src/managedPolicyFile.ts line 232Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +92,21 @@92+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;93+ const handle = yield* spawner.spawn(94+ ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }),95+ );96+ const [stdout, exitCode] = yield* Effect.all(97+ [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],98+ { concurrency: 2 },99+ );100+ return { stdout, exitCode: Number(exitCode) };101+}, Effect.scoped);102+103+/** The JSON in `reg query` output for the `Policy` value, or undefined when it has none. */104+function parseRegistryPolicy(output: string): string | undefined {105+ const match = /^\s*Policy\s+REG_SZ\s+(.*?)\s*$/m.exec(output);106+ return match?.[1];107+}108+109+const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));110+const decodeForcedExit = Schema.decodeUnknownExit(111+ Schema.Struct({112+ Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),packages/shared/src/managedPolicyFile.ts lines 123 to 124OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+function parseRegistryPolicy(output: string): string | undefined {105+ const match = /^\s*Policy\s+REG_SZ\s+(.*?)\s*$/m.exec(output);106+ return match?.[1];107+}108+109+const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));110+const decodeForcedExit = Schema.decodeUnknownExit(111+ Schema.Struct({112+ Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),113+ }),114+);115+116+/**117+ * Installed managed preferences hold the profile's keys directly, but MCX-style profiles keep118+ * them under `Forced[0].mcx_preference_settings`; read either rather than refuse a valid profile.119+ */120+function unwrapForced(json: string): unknown {121+ const parsed = decodeJsonExit(json);122+ if (Exit.isFailure(parsed)) return json;123+ const forced = decodeForcedExit(parsed.value);124+ return Exit.isSuccess(forced) ? forced.value.Forced[0].mcx_preference_settings : parsed.value;
- @@ -0,0 +86,21 @@86+const NOTHING_TO_CLOSE: ReadonlySet<TailscaleStderrDiagnostic | undefined> = new Set([87+ "not-running",88+ "not-logged-in",89+]);90+91+/**92+ * Turns off Tailscale Serve that forwards to `port`, such as one `t3 pair --tailscale` left from93+ * before the policy. Runs before the server binds, and fails when such a mapping stays on or94+ * Tailscale's answer cannot be read. Without the CLI, or with Tailscale down or logged out,95+ * nothing forwards, so nothing is closed.96+ */97+export const closeTailscaleServeTo = Effect.fn("managedLimits.closeTailscaleServeTo")(function* (98+ policy: PolicyDocument,99+ port: number,100+) {101+ if (allowsRemoteClients(policy)) return;102+ const servePorts = yield* readTailscaleServePortsProxyingTo(port).pipe(103+ Effect.catchTags({104+ // Only a CLI that is not there; one that will not run might still front a daemon.105+ TailscaleCommandSpawnError: (error) =>106+ isMissingCli(error.cause) ? Effect.succeed([]) : Effect.fail(error),@@ -906,6 +910,17 @@906910 runtimeMode,907911 selectedProviderEntry?.snapshot.supportedRuntimeModes,908912 );909- const compatibleRuntimeModeOptions = runtimeModeOptions.filter((option) =>910- compatibleRuntimeModes.includes(option.mode),911- );913+ // Modes above an administrator's ceiling stay listed, disabled with the reason.914+ const managedPolicy = useManagedPolicy(environmentId);915+ const compatibleRuntimeModeOptions = runtimeModeOptions916+ .filter((option) => compatibleRuntimeModes.includes(option.mode))917+ .map((option) => {918+ const disabledReason = managedRuntimeModeDenial(managedPolicy, option.mode);919+ return disabledReason === undefined ? option : { ...option, disabledReason };920+ });921+ // A thread or draft already above the ceiling would be refused; offer the broadest mode left.922+ const runtimeModeCeilingDenial = managedRuntimeModeDenial(managedPolicy, compatibleRuntimeMode);923+ const runtimeModeCeilingFallback =924+ runtimeModeCeilingDenial === undefined925+ ? undefined926+ : clampManagedRuntimeMode(managedPolicy, compatibleRuntimeMode, compatibleRuntimeModes);@@ -0,0 +10,21 @@10+import * as Exit from "effect/Exit";11+import * as Schema from "effect/Schema";12+13+const encodeSettings = Schema.encodeSync(ServerSettings);14+const decodeSettings = Schema.decodeUnknownSync(ServerSettings);15+const decodeSettingsExit = Schema.decodeUnknownExit(ServerSettings);16+17+/** Project overrides mirror these top-level keys, so a lock on one applies inside each project. */18+const PROJECT_OVERRIDE_KEYS: ReadonlySet<string> = new Set(19+ Object.keys(ProjectSettingsOverrides.fields),20+);21+/** Per-project stores; admins lock the top-level key and the lock reaches every project. */22+const UNMANAGEABLE_KEYS: ReadonlySet<string> = new Set([23+ "projectSettingsOverrides",24+ "projectAgentBrowserAccessOverrides",25+ "projectAutoPullOverrides",26+ "projectScriptOverrides",27+]);28+29+/** Legacy settings the server derives from another on every write; manage that one instead. */30+const DERIVED_FROM: ReadonlyMap<string, string> = new Map([
- @@ -0,0 +299,21 @@299+ return { _tag: "Invalid", reason: `"${driver}" in instances is not a known provider` };300+ }301+ const unsupported = pinnedFields(pin).find((field) => !known.configFields.has(field));302+ if (unsupported !== undefined) {303+ return {304+ _tag: "Invalid",305+ reason: `the ${known.label} provider has no ${unsupported} setting`,306+ };307+ }308+ const names = (pin.environment ?? []).map((variable) => variableKey(variable.name));309+ if (new Set(names).size !== names.length) {310+ return { _tag: "Invalid", reason: `instances.${driver}.environment repeats a variable` };311+ }312+ pins.set(driver, pin);313+ }314+315+ const rules = new Map<ProviderDriverKind, DriverRule>();316+ for (const [driver, known] of KNOWN_DRIVERS) {317+ const pin = pins.get(driver);318+ const bypasses = pin === undefined ? [] : Object.keys(PIN_BYPASS_FIELDS.get(driver) ?? {});319+ if (maxRuntimeMode !== undefined) {
- apps/web/src/components/settings/ProviderSettingsForm.tsx line 700Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -681,3 +687,4 @@681687 idPrefix={idPrefix}682688 variant={variant}683689 onChange={onChange}690+ managedReason={managed?.keys.has(field.key) ? managed.reason : undefined}apps/server/src/serverSettings.ts line 757Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -698,4 +754,4 @@698754 );699755700756 const loadSettingsFromDisk = Effect.gen(function* () {701- let settings = DEFAULT_SERVER_SETTINGS;757+ let settings = managed.defaults;@@ -427,3 +434,4 @@427434 {rows.length > 0 ? (428435 <div className="mt-3 min-w-0 space-y-2 pb-2">429436 {rows.map((variable, index) => {437+ if (props.managed?.names.has(variable.name)) {apps/web/src/components/settings/ScheduledTasksSettings.tsx line 1667Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1636,7 +1648,19 @@16361648 ) : null}16371649 <Toggle value="interval">Every interval</Toggle>1638- <Toggle value="webhook">On webhook</Toggle>1650+ <Toggle1651+ value="webhook"1652+ disabled={webhookDenial !== undefined && draft.scheduleMode !== "webhook"}1653+ >1654+ On webhook1655+ </Toggle>16391656 </ToggleGroup>16401657 </div>164116581642- {draft.scheduleMode === "webhook" ? (1659+ {webhookDenial !== undefined ? (1660+ <ManagedNotice>1661+ {draft.scheduleMode === "webhook"1662+ ? `${webhookDenial} Switch this task to a time or an interval, or turn it off, to save it.`1663+ : webhookDenial}1664+ </ManagedNotice>1665+ ) : null}1666+ {draft.scheduleMode === "webhook" &&
juliusmarminge merged thisd897d3f
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed