][]`; Schema::sanitizeOverrides() drops a * row whose fields are all empty, so clearing a row's inputs removes the override. */ final class SettingsPage { public const SLUG = 'alpaca-bot-settings'; public const GROUP = 'alpaca_bot'; /** The last input of the form. A post of the option that arrives without it was cut short by PHP. */ public const END_MARKER = 'alpaca_bot_settings_end'; public function __construct(private Store $store, private ModelCatalog $catalog) {} /** On admin_init: the setting, its sections (one page id per tab) and its fields. */ public function register(): void { register_setting(self::GROUP, Plugin::OPTION, [ 'type' => 'array', 'sanitize_callback' => static function (mixed $input): array { $stored = get_option(Plugin::OPTION, []); $stored = is_array($stored) ? $stored : []; if (self::postIsTruncated()) { add_settings_error(Plugin::OPTION, 'truncated', __('Nothing was saved: the form was longer than PHP accepts in one request (max_input_vars), so its end never arrived. Raise max_input_vars in php.ini, or set per-model overrides through the REST API.', 'alpaca-bot')); $input = []; } return Schema::sanitize(is_array($input) ? $input : [], $stored); }, 'default' => Schema::defaults(), ]); foreach (Schema::sections() as $id => $section) { add_settings_section('alpaca_bot_' . $id, $section['label'], static function () use ($section): void { echo '

' . esc_html($section['description']) . '

'; }, self::page($id)); } foreach (Schema::fields() as $key => $f) { // A checkbox carries its own label (its row title is blank, and a label_for there // would be an empty second label); a table has no single control to point a label at. $args = in_array($f['type'], ['array', 'boolean', 'checkbox-list'], true) ? [] : ['label_for' => Fields::id($key)]; add_settings_field('alpaca_bot_' . $key, $f['type'] === 'boolean' ? '' : $f['label'], function () use ($key, $f): void { echo $key === 'models.overrides' ? $this->renderOverrides() : Fields::render($key, $f, $this->store->get($key)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Fields escapes every attribute and text node. }, self::page($f['section']), 'alpaca_bot_' . $f['section'], $args); } } /** The menu page callback: tabs, the active section's fields, every other section hidden. */ public function render(): void { $sections = Schema::sections(); $active = $this->activeTab(); echo '

' . esc_html__('Alpaca Bot Settings', 'alpaca-bot') . '

'; // No setting argument: options.php files "Settings saved." under 'general', and a page // outside the Settings menu has to show those itself. settings_errors(); echo '
'; settings_fields(self::GROUP); // The carry-over before the visible tab: what PHP's max_input_vars cuts is the tail, so // the tail is the last rows of an overrides table, never the key or the URL. The marker // is the last input of all; a post without it was cut, and the sanitize callback refuses it. foreach (Schema::fields() as $key => $f) { if ($f['section'] !== $active) { echo Fields::hidden($key, $this->store->get($key)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in Fields. } } do_settings_sections(self::page($active)); printf('', esc_attr(self::END_MARKER)); submit_button(); echo '
'; } /** * True for a form post of the option that lacks the END_MARKER input render() prints last: * PHP dropped the tail (max_input_vars, 1000 by default, with no notice to userland) and what * arrived is not the form. Any other caller of the sanitize callback (the REST route, WP-CLI, * a test) posts nothing and is never refused. options.php verified the nonce before the * callback ran; this reads only whether the form reached its end. */ private static function postIsTruncated(): bool { return isset($_POST[Plugin::OPTION]) && !isset($_POST[self::END_MARKER]); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified by options.php; see the docblock. } /** `?tab=` when it names a section, else the first one. sanitize_key() bounds what is echoed back into the tab links. */ public function activeTab(): string { $sections = Schema::sections(); $requested = isset($_GET['tab']) && is_string($_GET['tab']) ? sanitize_key($_GET['tab']) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read only, selects a tab. return isset($sections[$requested]) ? $requested : (string) array_key_first($sections); } /** The Settings API page id for one section: what do_settings_sections() is asked for. */ private static function page(string $section): string { return self::SLUG . '-' . $section; } /** * The page's screen id, which is also its `admin_enqueue_scripts` hook suffix: what HelpTabs * and Assets gate on. * * Not a constant. Core derives a *submenu* screen's id from the parent's menu *title*, * translated — `add_menu_page()` stores `sanitize_title($menu_title)` in * `$admin_page_hooks[$slug]` and `get_plugin_page_hookname()` uses it as the prefix * (wp-admin/includes/plugin.php:1397, :2140-2158) — so on a locale that translates * "Alpaca Bot" this page is not `alpaca-bot_page_alpaca-bot-settings` at all, and a * hard-coded id once lost all four help tabs there. The top-level page is unaffected: its * own slug is in `$admin_page_hooks`, which takes the `toplevel` branch of the same function * and never reads the title, which is why Assets::HOOK can be a constant. * * So the id is asked of the function core built it with, rather than spelled again here. * Both callers run after menu.php has filled `$admin_page_hooks` (wp-admin/admin.php:163): * `current_screen` fires from set_current_screen() at admin.php:217, and * `admin_enqueue_scripts` from admin-header.php:123, which admin.php requires at :244 for a * page registered with a callback, as this one is (Menu), and at :292 for one backed by a * plugin file; wp-admin/includes/plugin.php is loaded by then. The guard is for a caller * that is not an admin request (a test), where the untranslated form is the right answer * anyway. */ public static function screen(): string { return function_exists('get_plugin_page_hookname') ? get_plugin_page_hookname(self::SLUG, Menu::SLUG) : 'alpaca-bot_page_' . self::SLUG; } /** * The overrides table, its columns labelled as the global fields they override. Placeholders * show the global value a blank cell falls back to, except the system prompt's: that global * is multi-line and lives on the Chat tab, so the caption names it instead. A model with a * stored override that the catalog no longer lists still gets a row, so the override can be * seen and cleared rather than carried invisibly. * * The table is a `widefat` inside a Settings API row, where core's forms.css reaches its * cells (Assets::OVERRIDES_CSS says how); `div.ab-overrides` around it is what the rules * Assets adds inline hang off, and it scrolls sideways where the row is narrower than six * columns. The captions stay outside it, so that scrollbar is under the table and not under * two paragraphs. * * The last column overrides no global field: `tools` overrides the model catalog's * capability flag, which is not a setting, so its heading is its own word and its control is * a three-state select rather than a text cell. The empty state has to be a real option an * operator can go back to, which is why it is a select and not a checkbox: a checkbox has * two states and the third one, "whatever the catalog says", is the default. */ private function renderOverrides(): string { $fields = Schema::fields(); $overrides = $this->store->get('models.overrides', []); $overrides = is_array($overrides) ? $overrides : []; $ids = array_map(static fn($m): string => $m->id, $this->catalog->all()); foreach (array_keys($overrides) as $id) { if (is_string($id) && !in_array($id, $ids, true)) { $ids[] = $id; } } if ($ids === []) { return '

' . esc_html__('No models reported by the provider yet. Check the Provider tab.', 'alpaca-bot') . '

'; } $rows = ''; foreach ($ids as $id) { $o = is_array($overrides[$id] ?? null) ? $overrides[$id] : []; $cell = function (string $field, string $type, string $class, string $extra = '') use ($id, $o): string { $value = $o[$field] ?? ''; return sprintf( '', $type, $class, esc_attr(Plugin::OPTION . '[models.overrides][' . $id . '][' . $field . ']'), esc_attr(is_scalar($value) ? (string) $value : ''), $extra, ); }; $placeholder = fn(string $key): string => ' placeholder="' . esc_attr((string) $this->store->get($key)) . '"'; // Unreadable is inherit, as it is for every other cell ($cell above, // Store::toolsOverride()): a row a filter or a hand edit left holding an array must // render, not warn. $stored = is_scalar($o['tools'] ?? null) ? (string) $o['tools'] : ''; $tools = '' . ''; } $head = '' . esc_html__('Model', 'alpaca-bot') . ''; foreach (['models.temperature', 'models.num_ctx', 'models.keep_alive', 'chat.system_prompt'] as $key) { $head .= '' . esc_html($fields[$key]['label']) . ''; } $head .= '' . esc_html__('Tools', 'alpaca-bot') . ''; return '
' . $head . '' . $rows . '
' . '

' . esc_html__('A blank cell uses the global value: the fields above for temperature, context window and keep alive, and the system prompt on the Chat tab. A model-level system prompt replaces the global one for that model.', 'alpaca-bot') . '

' . '

' . esc_html__('Tools decides whether this model is offered the tools enabled on the Tools tab. Leave it on the model default unless the model misbehaves: some models accept tools and then write the tool call out as text in the reply instead of calling it, and turning tools off for that model gives a plain answer instead. Turn them on for a model you know can call tools that is not being offered them; if no tools are enabled on the Tools tab, this model gets none either way.', 'alpaca-bot') . '

'; } /** * The three states of the per-model `tools` cell, in the order the select offers them: * inherit first, under the empty value Schema::sanitizeOverrides() stores nothing for. * * @return array stored value => label */ private static function toolsStates(): array { return [ '' => __('Model default', 'alpaca-bot'), Schema::TOOLS_ON => __('Always on', 'alpaca-bot'), Schema::TOOLS_OFF => __('Always off', 'alpaca-bot'), ]; } }