Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

51.6 KB
Raw Blame
import { useId, useState } from 'react';
import { Plus, X, ChevronUp, ChevronDown } from 'lucide-react';
import Pill from '../ui/Pill';
import ProviderModelSelector from '../ProviderModelSelector';
import {
  REVIEWER_OPTIONS,
  REVIEW_STOP_MODES,
  DEFAULT_REVIEW_STOP_MODE,
  MAX_REVIEW_USERNAMES,
  MAX_REVIEWER_MAX_ROUNDS,
  MAX_REVIEWER_MODEL_LENGTH,
  MODEL_SELECTABLE_REVIEWERS,
  cleanReviewUsername,
  normalizeReviewUsernames,
  reviewerEffortLevels,
  reviewerLabel,
  sanitizeReviewerModelInput
} from './constants';
import { isToolFreeReviewer, prioritizeToolFreeReviewers } from '../../../../server/lib/reviewerConfig.js';
import { effortLevelsForProvider, effectiveModelFor, isTuiProvider } from '../../utils/providers';
import { isApplyCapableReviewer, isProviderReviewer, normalizeReviewerSlug } from '../../lib/reviewerPins';
import { getNavPageForPath } from '../../../../server/lib/navManifest.js';
// The SAME map the readiness cards link by (`LOCAL_RUNTIMES[*].manageUrl` reads
// from it), taken from the server leaf rather than mirrored — the mirror is what
// #7414 had to chase. Imported here because these hints must name the page that
// actually manages each backend: Ollama and LM Studio are pulled and started
// from the Model Library, while MTPLX's server and checkpoints are a Runtimes
// card.
import { LOCAL_RUNTIME_MANAGE_URLS } from '../../../../server/lib/modelPinMembership.js';

// Resolved once at module load, not per render: the routes are constants, and
// only the (usually absent) empty-state hint reads the result.
const LOCAL_BACKEND_MANAGE_PAGES = Object.fromEntries(
  Object.entries(LOCAL_RUNTIME_MANAGE_URLS).map(([id, path]) => [id, getNavPageForPath(path)?.breadcrumb]),
);

const normalizeReviewerValue = (value) => normalizeReviewerSlug(value);

// The Model dropdown's "type an id instead" entry. Carries a `[`/`]` pair on
// purpose: `sanitizeReviewerModelInput` strips both, so this string can never
// arrive from the free-text input and be mistaken for a stored pin — and the
// server drops any id containing them, so it could not have been persisted by an
// older build either.
const CUSTOM_MODEL_OPTION = '[custom]';

// Shared row grid, one template for the header and every row so their columns
// cannot drift apart. The wide form keeps minimum tracks for order, provider,
// model, effort, optional, max, and remove — together ~32rem, so the collapse is
// keyed to a CONTAINER query (`@4xl`), not a viewport one: this picker also
// renders inside a narrow dashboard tile on a wide screen, where a viewport
// `sm:` was unconditionally true and forced the wide grid into a ~250px column.
// Below `@4xl` a row collapses to a stacked 2-column label/value block, so a
// narrow container never scrolls horizontally. The header is wide-only — in the
// stacked form each cell carries its own inline label, since a header far above
// a stacked row doesn't associate.
const WIDE_TRACKS = '@4xl:grid-cols-[auto_minmax(5rem,1fr)_minmax(8rem,2fr)_minmax(7rem,1fr)_auto_3.25rem_auto]';
const ROW_CLASS = `min-w-0 grid grid-cols-[auto_minmax(0,1fr)] ${WIDE_TRACKS} items-center gap-x-2 gap-y-1 px-1.5 py-1.5 rounded border border-port-border bg-port-bg @4xl:border-transparent @4xl:bg-transparent @4xl:py-0.5 @4xl:rounded-none`;
const CELL_LABEL_CLASS = '@4xl:hidden text-[10px] uppercase tracking-wide text-gray-400';
const HEADER_CLASS = `hidden @4xl:grid ${WIDE_TRACKS} items-center gap-x-2 px-1.5 text-[10px] uppercase tracking-wide text-gray-400`;

/**
 * Ordered multi-reviewer picker, rendered as one row per reviewer with the five
 * per-reviewer controls as columns: **Provider | Model | Effort | Optional | Max
 * Iterations** (#3133). Add configured providers or standalone backends from
 * their pickers (one pick adds), reorder with the arrows within each service/standalone boundary, remove with ✕. Maps to slashdo's
 * `--review-with a,b,c` plus the stop-mode / `--reviewer-applies` flags.
 *
 * A second "GitHub reviewers" table collects arbitrary usernames (e.g.
 * `@CodeReviewbot`) requested as PR reviewers to gate the merge — appended to
 * `--review-with` as `@user` tokens after the keyed reviewers. Those rows have no
 * Model cell: a username reviewer is a human or a GitHub App, not a model-taking
 * backend (slashdo rejects `@login[…]` for the same reason).
 *
 * Per-row controls, each mapping to one slashdo per-entry token feature:
 * - **Model** → the `[<model>]` selector (or, for a CLI reviewer the follow-up
 *   agent invokes directly, `<reviewer> --model <id>`). Only rendered for
 *   MODEL_SELECTABLE_REVIEWERS. The option lists are OWNED BY THE CALLER (see
 *   `modelOptions`) so this component does no fetching.
 * - **Effort** → the reviewer's reasoning-effort tier, emitted as slashdo's
 *   `~effort=<level>` entry suffix and, where PortOS spells the invocation out
 *   itself, as the flag that CLI actually takes: `claude --effort high` /
 *   `codex -c model_reasoning_effort=high`, `"effort"` in the
 *   `/api/code-review/local` body for a local reviewer, and — for `cursor`,
 *   whose CLI has no `--effort` flag at all — folded into the model id as
 *   Cursor's own variant syntax (`--model gpt-5[effort=max]`), which needs the
 *   row's Model cell filled in to have anything to attach to. Only rendered for
 *   EFFORT_SELECTABLE_REVIEWERS, and each row offers only the levels its own CLI
 *   accepts (`agy` rejects `--effort max`).
 * - **Optional** → the `~opt` non-blocking marker.
 * - **Max Iterations** → the numeric `~max=<n>` round cap (blank = slashdo's
 *   built-in default, `0` = loop until clean).
 *
 * Controlled: emits the next shape via onChange so the parent can store
 * `reviewers` / `usernames` / `optionalReviewers` / `reviewerModels` /
 * `reviewerEfforts` / `reviewerMaxRounds` / `reviewStopMode` / `reviewerApplies`
 * however it persists them.
 *
 * `defaults` is the resolved fallback the parent seeded the props from (the
 * install-wide Code Review Defaults, as token-keyed maps for the pins). When
 * provided, `emit()` OMITS any key whose value is deep-equal to
 * `defaults[key]` — a field the user never touched stays absent from the
 * payload, which is exactly what `resolveReviewerConfig` reads as "inherit".
 * Without it the picker would freeze the defaults-of-that-moment into a
 * permanent task override on first touch (#6208). Omit the prop where a full
 * emit is correct — the surface that edits the defaults themselves has no
 * fallback to inherit from.
 *
 * Absent keeps meaning inherit and an explicitly-empty value keeps meaning
 * "clear": the comparison is against the resolved default, never against
 * emptiness, so `{}` / `[]` equal only a matching default and are otherwise
 * emitted as a real override that clears it. (One key is exempt: the server
 * drops an empty `reviewers` list before persisting, so `reviewers: []`
 * resolves to the default chain either way — pre-existing server behavior.)
 *
 * Known trade-off: the diff is against the CURRENT default, so an override
 * that happens to equal it (e.g. set before the default changed to match) is
 * indistinguishable from "never touched" and reverts to inherit the next time
 * any other field is edited. The effective reviewers are unchanged at that
 * moment — the pin only stops shadowing future default changes.
 *
 * `modelOptions` is the resolved model-picker data, shaped like
 * `useReviewerModelOptions()`'s return: `{ optionsByReviewer, defaultModels,
 * freeText, unavailable, providerDisabled, loaded }`. Callers keep owning their
 * own `api.getLocalLlmStatus` / `api.getProviders` fetches (that's what the hook
 * is for) — passing nothing degrades every Model cell to a free-text input, which
 * is still fully usable, rather than hiding the column.
 *
 * `showRunFlags={false}` hides the stop-mode select and the "reviewer applies
 * fixes" checkbox for surfaces that can't honor them — the `/do:next` claim
 * flows substitute a reviewer CSV into their prompt and have no slashdo flag
 * string, so rendering those two controls there would be a knob wired to
 * nothing. The reviewer list itself still applies.
 *
 * `installed` is a per-reviewer-slug install probe from the Code Review
 * Defaults endpoint (`GET /api/code-review/defaults`'s `installed` field,
 * #3606) — `{ claude: true, antigravity: false, ... }`. Only an explicit
 * `false` counts as missing; `undefined` (not a CLI reviewer, or the caller
 * didn't fetch it) says nothing.
 *
 * `providerReviewUnsupported` is the same endpoint's provider-backed counterpart
 * (#7660) — `{ 'provider:<id>': 'REVIEWER_UNSUPPORTED' }`, present ONLY for a
 * provider that has no runnable review transport (for example, a missing CLI command). A capable
 * provider is absent rather than `false`, so a caller that never fetched it and
 * a machine where nothing is wrong both read `undefined`. Warn-only like the
 * rest: without it, such a reviewer is only discovered as a review gate that
 * never clears.
 *
 * Together with `modelOptions.providerDisabled`, that describes which reviewers
 * can run on this machine. Configured providers use the shared provider selector;
 * standalone backends use a compact local/CLI picker labeled with unavailability. Missing/disabled saved
 * rows remain editable with actionable warnings. `showReviewers`, `showUsernames`
 * and `renderReviewer` let the tier editor compose these same rows and controls
 * without introducing fallback-group fields to task-local overrides.
 */
export default function ReviewerPicker({
  reviewers = [],
  usernames = [],
  optionalReviewers = [],
  reviewerMaxRounds = {},
  reviewerModels = {},
  reviewerEfforts = {},
  modelOptions = null,
  installed = null,
  providerReviewUnsupported = null,
  stopMode = DEFAULT_REVIEW_STOP_MODE,
  reviewerApplies = false,
  defaults = null,
  onChange,
  disabled = false,
  showRunFlags = true,
  showReviewers = true,
  showUsernames = true,
  renderReviewer = (_token, row) => row,
}) {
  const id = useId();
  const [effortNotice, setEffortNotice] = useState('');
  const providerRecords = modelOptions?.providers || [];
  // A review runs its provider headless (CLI or API), never through an
  // interactive TUI session, so TUI records are not offered as new reviewers.
  // A TUI reviewer saved earlier keeps its row and label.
  const reviewerProviderOptions = providerRecords.filter(provider => !isTuiProvider(provider));
  const labelFor = (token) => isProviderReviewer(token)
    ? providerRecords.find(provider => `provider:${provider.id}` === token)?.name || token.slice(9)
    : reviewerLabel(token);
  const [usernameInput, setUsernameInput] = useState('');
  const [usernameError, setUsernameError] = useState('');
  // Reviewers whose Model cell the user switched to free text by picking the
  // "Custom…" entry. Lowercased tokens, matching the case-insensitive keying the
  // pin maps use. Purely presentational — nothing is stored until an id is typed,
  // so this never has to round-trip through `onChange`.
  const [customModelTokens, setCustomModelTokens] = useState(() => new Set());
  const isCustomModel = (token) => customModelTokens.has(token.toLowerCase());
  const setCustomModel = (token, on) => setCustomModelTokens((prev) => {
    const next = new Set(prev);
    if (on) next.add(token.toLowerCase()); else next.delete(token.toLowerCase());
    return next;
  });
  // Render the parent's list (de-duped, order-preserving) so display === stored
  // state for valid input while staying robust to malformed/legacy duplicates —
  // dupes would otherwise collide on the `key={value}` below and corrupt
  // reorder/remove. An empty list shows the opt-in hint and lets the user clear
  // the chain entirely; no reviewer is silently inferred from the active AI
  // provider.
  const selected = Array.isArray(reviewers) ? [...new Set(reviewers.map(normalizeReviewerValue))] : [];
  const orderedSelected = prioritizeToolFreeReviewers(selected);
  const addable = REVIEWER_OPTIONS.filter(o => !selected.includes(o.value));
  const addableProviders = reviewerProviderOptions.filter(provider => provider.enabled !== false && !selected.includes(`provider:${provider.id}`));
  // Only codex is offered the editing pass: slashdo forces every other local
  // reviewer back to review-only and reverts what it wrote, so showing the toggle
  // for agy/grok/cursor would ask the user to grant write access for nothing.
  const hasApplyCapableReviewer = selected.some(isApplyCapableReviewer);
  const selectedUsernames = normalizeReviewUsernames(usernames);
  const atMaxUsernames = selectedUsernames.length >= MAX_REVIEW_USERNAMES;
  // Optional (non-blocking) reviewers — emitted with slashdo's `~opt` suffix.
  // Each token mirrors an emitted `--review-with` token: a keyed slug or `@user`,
  // so membership is a plain lookup (server `normalizeOptionalReviewers` owns the
  // authoritative shape; this is the display mirror).
  const optionalTokens = Array.isArray(optionalReviewers) ? [...new Set(optionalReviewers.map(String))] : [];
  const optionalSet = new Set(optionalTokens.map(t => t.toLowerCase()));
  const isOptional = (token) => optionalSet.has(token.toLowerCase());
  const withoutToken = (token) => optionalTokens.filter(t => t.toLowerCase() !== token.toLowerCase());
  // Shared shape for the three token-keyed maps below (`~max=<n>` caps, model
  // pins, effort pins). All key on the same emitted `--review-with` token and all
  // need the same case-insensitive read / key-preserving delete, so the lookup
  // helpers are generated once rather than written three times.
  const asMap = (value) => (value && typeof value === 'object' && !Array.isArray(value)) ? value : {};
  const keyedLookup = (map) => ({
    get: (token) => {
      const key = Object.keys(map).find(k => k.toLowerCase() === token.toLowerCase());
      return key === undefined ? undefined : map[key];
    },
    without: (token) => Object.fromEntries(
      Object.entries(map).filter(([k]) => k.toLowerCase() !== token.toLowerCase())
    )
  });
  // Per-reviewer `~max=<n>` round caps, keyed by the same emitted token. Absent
  // key = no cap requested (slashdo's built-in default stands); `0` = loop until
  // clean. The two must never collapse, so the input renders '' for absent and
  // clearing it DELETES the key rather than writing 0 (server
  // `normalizeReviewerMaxRounds` owns the authoritative shape).
  const maxRoundsMap = asMap(reviewerMaxRounds);
  const maxRounds = keyedLookup(maxRoundsMap);
  // Per-reviewer model pins, same token keying. Absent key = "let that reviewer
  // pick its own default", which is NOT an empty string — so clearing the field
  // DELETES the key rather than persisting `''` (a `--model ` with no id).
  const modelsMap = asMap(reviewerModels);
  const models = keyedLookup(modelsMap);
  // Per-reviewer reasoning-effort pins, same token keying and same absent-vs-empty
  // contract as the model pins: no key = "let that reviewer think however it
  // normally does", so clearing the select DELETES the key rather than writing `''`.
  const effortsMap = asMap(reviewerEfforts);
  const efforts = keyedLookup(effortsMap);
  // Why this reviewer can't run here, or null when nothing says it can't.
  //
  // Three independent signals, all warn-only and each reported only when the
  // caller actually fetched them — a reviewer stays selectable and selected
  // either way, since the checks are local-machine-only and a federated peer
  // (or a later install / a flip in Settings) may satisfy them:
  //
  // - `installed[token] === false` — the CLI binary isn't on PATH. Only an
  //   explicit `false` counts; `undefined` covers both "not a CLI reviewer"
  //   (copilot/@username) and "caller didn't fetch `installed`".
  // - `unavailable[token] === true` — a LOCAL backend (LM Studio / Ollama) that
  //   didn't answer its probe. This is the ONLY availability signal those three
  //   get: their reviews hit the daemon's base URL directly, so a same-named
  //   provider record's on/off switch says nothing about them (the hook exempts
  //   them from `providerDisabled` for that reason).
  // - `providerDisabled[token]` — every provider record fronting that binary is
  //   switched off on this install, so the user has said they don't use it. A
  //   `/api/providers` that failed or hasn't landed reports nothing (see the
  //   hook), so this never fires on a slow page.
  const unavailability = (token) => {
    if (isProviderReviewer(token)) {
      const provider = providerRecords.find(record => `provider:${record.id}` === token);
      if (modelOptions?.loaded && modelOptions?.providersLoaded !== false && !provider) return { label: 'missing', title: 'This reviewer provider is no longer configured on this machine.' };
      if (provider?.enabled === false) return { label: 'disabled', title: 'Enable this provider in AI Providers before running its review.' };
      // Last, so a missing or switched-off provider keeps its more specific
      // word: this one is about a provider that IS configured and enabled and
      // still could never answer a review.
      if (providerReviewUnsupported?.[token]) {
        return {
          label: "can't review",
          title: `${labelFor(token)} has no command configured, so it cannot run a review. Set its command or switch it to API mode in AI Providers.`
        };
      }
      return null;
    }
    if (installed?.[token] === false) {
      return {
        label: 'not installed',
        title: `${labelFor(token)}'s CLI binary wasn't found on this machine. It still runs (federation-wide config), but the review loop here will report it unsatisfied until it's installed.`
      };
    }
    // A local backend answers from its own daemon, so the live probe — not a
    // provider record — is what says whether it can review. `=== true` keeps a
    // pre-fetch render (undefined) from accusing a healthy backend.
    if (modelOptions?.unavailable?.[token] === true) {
      const backendPage = LOCAL_BACKEND_MANAGE_PAGES[token];
      return {
        label: 'not running',
        title: `${labelFor(token)} isn't answering on this machine${backendPage ? ` — start its server from ${backendPage}` : ''}. It still runs (federation-wide config), but a review here won't complete until it's up.`
      };
    }
    if (modelOptions?.providerDisabled?.[token]) {
      return {
        label: 'disabled',
        title: `${labelFor(token)}'s provider records are all switched off in Settings → AI Providers, so this machine isn't set up to use it. Adding it still works — the review loop spawns its CLI directly, and a federated peer may have it enabled.`
      };
    }
    return null;
  };
  const renderUnavailableBadge = (token) => {
    const reason = unavailability(token);
    return reason && (
      <Pill tone="warning" size="xs" className="shrink-0" title={reason.title}>
        {reason.label}
      </Pill>
    );
  };
  // Case-insensitive equality for the token lists (reviewer slugs are already
  // lowercased; GitHub usernames are case-insensitive). Order matters ONLY for
  // `reviewers` — the chain runs in click order — so the username lists compare
  // as sorted sets; otherwise a same-membership reorder would over-emit.
  const listsEqual = (a, b, ordered) => {
    if (!Array.isArray(a) || !Array.isArray(b)) return a === b;
    if (a.length !== b.length) return false;
    const left = a.map((value) => String(value).toLowerCase());
    const right = b.map((value) => String(value).toLowerCase());
    if (!ordered) {
      left.sort();
      right.sort();
    }
    return left.every((value, index) => value === right[index]);
  };
  // Case-insensitive-key equality for the token-keyed pin maps. Values compare
  // strictly: `0` (loop until clean) must never equal absent, and `{}` equals
  // only a matching default so an explicit clear is still emitted.
  const mapsEqual = (a, b) => {
    const entries = (map) => {
      if (!map || typeof map !== 'object' || Array.isArray(map)) return map;
      return Object.entries(map)
        .map(([key, value]) => [key.toLowerCase(), value])
        .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0));
    };
    const left = entries(a);
    const right = entries(b);
    if (!Array.isArray(left) || !Array.isArray(right)) return left === right;
    if (left.length !== right.length) return false;
    return left.every(([key, value], index) => right[index][0] === key && right[index][1] === value);
  };
  const equalsBaseline = (key, value, baseline) => {
    if (key === 'reviewers') return listsEqual(value, baseline, true);
    if (key === 'usernames' || key === 'optionalReviewers') return listsEqual(value, baseline, false);
    if (key === 'reviewerMaxRounds' || key === 'reviewerModels' || key === 'reviewerEfforts') return mapsEqual(value, baseline);
    return value === baseline;
  };

  const emit = (next) => {
    const full = {
      reviewers: selected,
      usernames: selectedUsernames,
      optionalReviewers: optionalTokens,
      reviewerMaxRounds: maxRoundsMap,
      reviewerModels: modelsMap,
      reviewerEfforts: effortsMap,
      stopMode,
      reviewerApplies,
      ...next
    };
    // No baseline (the surface editing the defaults themselves): full snapshot,
    // exactly as before.
    if (!defaults || typeof defaults !== 'object') {
      onChange?.(full);
      return;
    }
    const partial = {};
    for (const key of Object.keys(full)) {
      if (!equalsBaseline(key, full[key], defaults[key])) partial[key] = full[key];
    }
    onChange?.(partial);
  };

  const toggleOptional = (token) => emit({
    optionalReviewers: isOptional(token) ? withoutToken(token) : [...optionalTokens, token]
  });

  // Blank clears the cap entirely (back to slashdo's built-in default). The two
  // out-of-range directions are deliberately NOT symmetric, because only one of
  // them can change what the value MEANS:
  //  - A negative or non-integer entry is REJECTED (the emit is skipped, so the
  //    controlled input snaps back). Coercing it would land on `0`, which is
  //    slashdo's "loop until clean" — turning a typo into an unlimited loop, the
  //    exact absent-vs-0 collapse the server's normalizer refuses.
  //  - A value above the ceiling clamps DOWN to it. That can only ever shrink a
  //    budget, never make it unlimited, and it matches the input's `max`.
  const setMaxRounds = (token, raw) => {
    if (raw === '') {
      emit({ reviewerMaxRounds: maxRounds.without(token) });
      return;
    }
    const parsed = Number(raw);
    if (!Number.isInteger(parsed) || parsed < 0) return;
    const capped = Math.min(parsed, MAX_REVIEWER_MAX_ROUNDS);
    emit({ reviewerMaxRounds: { ...maxRounds.without(token), [token]: capped } });
  };

  // Blank (or whitespace-only) clears the pin so the reviewer falls back to its
  // own default — the DELETE, not an empty-string write, because `''` is not a
  // model id the reviewer could run. Mirrors the server normalizer, which drops a
  // blank value rather than persisting it.
  //
  // Structural characters (`[`, `]`, `,`, line breaks) are stripped first: they'd
  // corrupt the emitted `[<model>]` selector and the server drops any id carrying
  // one, so accepting them here would show the user a pin that never persists.
  const setModel = (token, raw) => {
    const model = sanitizeReviewerModelInput(raw).trim();
    const next = { reviewerModels: { ...models.without(token), ...(model ? { [token]: model } : {}) } };
    const provider = providerRecords.find(record => `provider:${record.id}` === token);
    const effort = efforts.get(token);
    setEffortNotice('');
    if (provider && effort && !effortLevelsForProvider(provider, effectiveModelFor(provider, model))?.includes(effort)) {
      next.reviewerEfforts = efforts.without(token);
      setEffortNotice(`Reasoning effort for ${labelFor(token)} was cleared because the new model does not support ${effort}. Choose a supported effort or keep the provider default.`);
    }
    emit(next);
  };

  // Blank clears the pin so the reviewer reasons at its own default — the DELETE,
  // not an empty-string write, same absent-vs-empty contract as setModel.
  //
  // No sanitizing pass (unlike setModel, whose input is free text): the value can
  // only be one of the exact levels renderEffortCell rendered, and the one
  // out-of-ladder option it renders is already the selected value, so picking it
  // fires no change.
  const setEffort = (token, level) => {
    setEffortNotice('');
    emit({ reviewerEfforts: level ? { ...efforts.without(token), [token]: level } : efforts.without(token) });
  };

  // The "this reviewer has no such control" cell, shared by the Model and Effort
  // columns so both read identically when the pin doesn't apply.
  const renderNoPinCell = (title) => (
    <span className="text-[11px] text-gray-400" title={title}>—</span>
  );

  // The closed-list pin `<select>` behind both the Effort column and the Model
  // column's local-backend variant. They share one non-obvious contract: a stored
  // value that is no longer in `options` (pinned on another machine, or before a
  // CLI dropped a tier / a model was uninstalled) STILL gets an `<option>` — a
  // select whose value isn't in its list renders blank and reads as "unset" while
  // the value is in fact stored. `staleSuffix` names why it's absent; `setClass`
  // differs only so the two columns stay visually distinguishable — passed as a
  // COMPLETE class string, never interpolated, or Tailwind's scanner won't emit it.
  //
  // `trailingOption` appends one non-model entry after the list (the Model
  // column's "Custom…" escape). It is a UI action, not a pin — the caller's
  // `onChange` recognizes its sentinel value and never stores it.
  const renderPinSelect = ({ selectId, value, options, onChange, ariaLabel, title, staleSuffix, setClass, maxWidthClass, trailingOption = null }) => (
    <select
      id={selectId}
      value={value}
      disabled={disabled}
      onChange={(e) => onChange(e.target.value)}
      aria-label={ariaLabel}
      title={title}
      className={`w-full min-w-0 ${maxWidthClass} px-1.5 py-0.5 text-[11px] font-mono rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${value
        ? setClass
        : 'text-gray-500 border-port-border/60'}`}
    >
      <option value="">— default —</option>
      {value && !options.includes(value) && <option value={value}>{value} {staleSuffix}</option>}
      {options.map((option) => <option key={option} value={option}>{option}</option>)}
      {trailingOption && <option value={trailingOption.value}>{trailingOption.label}</option>}
    </select>
  );

  // The Effort cell uses the configured provider catalog for provider identities
  // and the built-in reviewer ladder for legacy CLI tokens.
  //
  // The ladder is narrowed by the row's PINNED MODEL where the CLI validates the
  // pair: `agy` rejects `gemini-3.1-pro --effort medium`, so offering `medium`
  // there would store and emit an invocation it refuses (#3733). The narrowing
  // needs the provider catalog, which the caller already fetched — falling back to
  // the static ladder when it didn't, so a caller that passes no `modelOptions`
  // keeps a working (just unnarrowed) select rather than losing the cell.
  const renderEffortCell = (token) => {
    const subject = labelFor(token);
    const stored = efforts.get(token) ?? '';
    const provider = providerRecords.find(record => `provider:${record.id}` === token);
    const levels = isProviderReviewer(token)
      ? effortLevelsForProvider(provider, effectiveModelFor(provider, models.get(token))) || []
      : modelOptions?.modelEffortLevels?.(token, models.get(token)) ?? reviewerEffortLevels(token, models.get(token)) ?? [];
    // A pinned model whose catalog lists NO tiers still renders the select when
    // something is stored, so a pin made before the model changed (or on another
    // machine) stays visible and clearable rather than vanishing behind the dash.
    if (!levels.length && !stored) return renderNoPinCell(`${subject}'s pinned model offers no reasoning-effort tiers`);
    // Cursor's level is a PARAMETER OF ITS MODEL ID (`gpt-5[effort=max]`) — its
    // CLI has no `--effort` flag — so a level with no Model pin has nothing to
    // attach to and is dropped when the invocation is built. Say so here rather
    // than let the row display a tier the review will not run at.
    const cursorNeedsModel = normalizeReviewerValue(token) === 'cursor' && !models.get(token);
    return renderPinSelect({
      selectId: `${id}-effort-${token}`,
      value: stored,
      options: levels,
      onChange: (level) => setEffort(token, level),
      ariaLabel: `Reasoning effort for ${subject}`,
      title: cursorNeedsModel
        ? `${subject} carries its reasoning effort inside the model id, so pin a Model too — a tier with no model is not passed to the CLI.`
        : stored && !levels.includes(stored)
        ? `${subject}'s selected model does not support ${stored} reasoning effort. Choose a supported effort or clear the pin before running a review.`
        : stored
        ? `${subject} reviews at ${stored} reasoning effort. Choose "default" to let it decide.`
        : `${subject} reasons at its own default. Pick a tier to make it think harder (slower, pricier) or lighter.`,
      staleSuffix: '(unsupported)',
      setClass: 'text-port-accent-2 border-port-accent-2/50',
      maxWidthClass: 'max-w-[8rem]'
    });
  };

  // The `~opt` non-blocking toggle rendered on every reviewer/username row.
  // `subject` is the human name used in the aria-label; `title` is the (row-
  // kind-specific) hover copy the caller resolves.
  const renderOptToggle = (token, subject, title) => (
    <button
      type="button"
      disabled={disabled}
      onClick={() => toggleOptional(token)}
      title={title}
      className={`min-h-9 min-w-9 text-xs font-mono leading-none px-1 py-0.5 rounded border ${isOptional(token)
        ? 'text-port-warning border-port-warning/50 bg-port-warning/10'
        : 'text-gray-400 border-transparent hover:text-gray-300 hover:border-port-border'} disabled:opacity-40`}
      aria-pressed={isOptional(token)}
      aria-label={isOptional(token) ? `Make ${subject} blocking` : `Make ${subject} non-blocking`}
    >
      ~opt
    </button>
  );

  // The `~max=<n>` round-cap input rendered on every reviewer/username row.
  // Blank means "no cap" — the number input's empty string is the sentinel for an
  // absent key, distinct from a typed `0` (loop until clean).
  const renderMaxRounds = (token, subject) => {
    const value = maxRounds.get(token);
    const inputId = `${id}-max-${token}`;
    return (
      <input
        id={inputId}
        type="number"
        inputMode="numeric"
        min={0}
        max={MAX_REVIEWER_MAX_ROUNDS}
        step={1}
        disabled={disabled}
        value={value === undefined ? '' : value}
        placeholder="–"
        onChange={(e) => setMaxRounds(token, e.target.value)}
        aria-label={`Max review rounds for ${subject}`}
        title={value === undefined
          ? `${subject} uses slashdo's built-in round cap. Enter a number to cap its review → fix → re-review cycles (0 = loop until clean).`
          : value === 0
            ? `${subject} loops until clean (~max=0), bounded by slashdo's safety guardrail. Clear to restore the built-in cap.`
            : `${subject} runs at most ${value} review round${value === 1 ? '' : 's'} (~max=${value}). Clear to restore the built-in cap.`}
        className={`w-12 px-1 py-0.5 text-[11px] font-mono leading-none text-center rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${value === undefined
          ? 'text-gray-500 border-port-border/60 hover:border-port-border'
          : 'text-port-accent-2 border-port-accent-2/50'}`}
      />
    );
  };

  // The Model cell. Only MODEL_SELECTABLE_REVIEWERS get one — copilot has no CLI
  // and a `@username` reviewer is a person/bot, so neither takes a model.
  //
  // Every reviewer with a resolved catalog renders a `<select>`: the ids are
  // known, and a dropdown is how the rest of this table's pins are set. What
  // differs between the two reviewer kinds is the ESCAPE HATCH, not the control:
  //
  // - A probed local backend's installed-model list is authoritative (the server
  //   asked the running daemon), so its select is closed — an id it doesn't list
  //   isn't installed.
  // - A CLI reviewer's catalog is a stored snapshot, and an Ollama-backed
  //   `claude` or a Bedrock-form id can be anything the environment provides, so
  //   its select carries a trailing "Custom…" entry that swaps the cell for a
  //   free-text input (with the same ids offered as a `<datalist>`). Clearing
  //   that input returns the cell to the dropdown. A CLI reviewer whose catalog
  //   resolved EMPTY (grok/kimi/opencode ship only a configured-default sentinel)
  //   starts in the free-text form directly — a select of nothing is a dead
  //   control — and so does a row already pinned to an id outside the catalog, so
  //   that pin stays editable rather than reading as an unpickable oddity.
  //
  // `loaded` gates the "nothing installed" messaging so a pre-fetch render
  // doesn't accuse a healthy backend of being empty.
  const renderModelCell = (token) => {
    if (!MODEL_SELECTABLE_REVIEWERS.includes(token) && !isProviderReviewer(token)) return renderNoPinCell(`${labelFor(token)} takes no model`);
    const backendPage = LOCAL_BACKEND_MANAGE_PAGES[token];
    const subject = labelFor(token);
    const pinnedValue = models.get(token);
    const value = pinnedValue ?? '';
    const defaultModel = modelOptions?.defaultModels?.[token] || '';
    const options = modelOptions?.optionsByReviewer?.[token] || [];
    const inputId = `${id}-model-${token}`;
    const listId = `${id}-modellist-${token}`;
    // Whether this reviewer may carry an id its catalog doesn't list at all.
    const acceptsTypedId = modelOptions?.freeText?.[token] !== false;
    // Why a local backend has no options, so the empty state says the useful
    // thing instead of a bare "default" placeholder. Only meaningful once the
    // probe settled — before that, an empty list is "not fetched yet", not a fact.
    const emptyHint = (options.length === 0 && modelOptions?.loaded)
      ? (modelOptions?.unavailable?.[token]
          ? `${subject} isn't reachable${backendPage ? ` — start it from ${backendPage}` : ''} to list its models. You can still type an id.`
          : `No ${subject} models listed${backendPage ? ` — add one in ${backendPage}` : ''}, or type an id.`)
      : null;
    // A closed select over nothing would be a dead control, so a reviewer with no
    // resolved options falls back to free text whichever kind it is: better a
    // typed id than no way to set one at all.
    const freeText = acceptsTypedId
      ? (options.length === 0 || isCustomModel(token) || (Boolean(value) && !options.includes(value)))
      : options.length === 0;

    if (!freeText) {
      return renderPinSelect({
        selectId: inputId,
        value: value || (defaultModel && options.includes(defaultModel) ? defaultModel : ''),
        options,
        onChange: (model) => {
          // The escape hatch is a UI mode, not an id — never store the sentinel.
          if (model === CUSTOM_MODEL_OPTION) { setCustomModel(token, true); return; }
          setModel(token, model);
        },
        ariaLabel: `Model for ${subject}`,
        title: value
          ? `${subject} reviews with ${value}. Choose "default" to let it pick.`
          : defaultModel
            ? `${subject} uses ${defaultModel} by default. Choose another model to pin it for this run.`
          : `${subject} uses the model configured for its backend. Pick one to pin it for this run.`,
        staleSuffix: '(not installed)',
        setClass: 'text-port-accent border-port-accent/50',
        maxWidthClass: 'max-w-[190px]',
        // Only a reviewer that can run an id outside its catalog gets the escape.
        trailingOption: acceptsTypedId ? { value: CUSTOM_MODEL_OPTION, label: 'Custom…' } : null
      });
    }

    // "Custom…" was picked with nothing pinned yet — start empty so the field
    // reads as the blank the user is about to fill, not as an id already in play.
    const inputValue = value || (isCustomModel(token) ? '' : defaultModel);
    return (
      <>
        <input
          id={inputId}
          type="text"
          list={options.length ? listId : undefined}
          value={inputValue}
          disabled={disabled}
          maxLength={MAX_REVIEWER_MODEL_LENGTH}
          placeholder={defaultModel ? `${defaultModel} (default)` : 'default'}
          onChange={(e) => setModel(token, e.target.value)}
          // Leaving the field with nothing pinned is how the user backs out of
          // Custom…: with no id to keep, the catalog dropdown is the more useful
          // control. Deliberately on blur rather than on an empty onChange —
          // clearing the field to retype an id would otherwise swap the control
          // out from under the cursor mid-edit.
          onBlur={() => { if (!value && options.length) setCustomModel(token, false); }}
          aria-label={`Model for ${subject}`}
          title={value
            ? `${subject} reviews with ${value}. Clear to let it use its own default.`
            : (options.length
              ? `Type an id ${subject} accepts. Leave it empty to go back to its listed models.`
              : (defaultModel
                ? `${subject} uses ${defaultModel} by default. Type an id to pin one.`
                : (emptyHint || `${subject} uses its own default model. Type an id to pin one.`)))}
          className={`w-full min-w-0 max-w-[190px] px-1.5 py-0.5 text-[11px] font-mono rounded border bg-port-bg min-h-[28px] disabled:opacity-40 focus:outline-none focus:border-port-accent ${value
            ? 'text-port-accent border-port-accent/50'
            : 'text-gray-500 border-port-border/60'}`}
        />
        {options.length > 0 && (
          <datalist id={listId}>
            {options.map((m) => <option key={m} value={m}>{m}</option>)}
          </datalist>
        )}
      </>
    );
  };

  const addUsername = () => {
    const entries = usernameInput.split(/[\s,]+/).map(value => value.trim()).filter(Boolean);
    const invalid = entries.filter(value => !cleanReviewUsername(value));
    if (!entries.length || invalid.length) {
      setUsernameError(invalid.length
        ? `Invalid reviewer names: ${invalid.join(', ')}. No names were added.`
        : 'Enter a valid GitHub or GitLab username (letters, numbers, hyphens, underscores, dots; optional org/team).');
      return;
    }
    // Validate the whole batch before normalizing: the normalizer deliberately
    // drops invalid values and caps the roster, which would hide a partial add.
    const incoming = entries.map(cleanReviewUsername);
    const uniqueCount = new Set([...selectedUsernames, ...incoming].map(value => value.toLowerCase())).size;
    if (uniqueCount > MAX_REVIEW_USERNAMES) {
      setUsernameError(`At most ${MAX_REVIEW_USERNAMES} reviewer usernames. No names were added.`);
      return;
    }
    const next = normalizeReviewUsernames([...selectedUsernames, ...incoming]);
    if (next.length === selectedUsernames.length) {
      setUsernameInput('');
      setUsernameError('Already added.');
      return;
    }
    emit({ usernames: next });
    setUsernameInput('');
    setUsernameError('');
  };
  const removeUsername = (value) => emit({
    usernames: selectedUsernames.filter(u => u !== value),
    optionalReviewers: withoutToken(`@${value}`),
    reviewerMaxRounds: maxRounds.without(`@${value}`),
    // A username row has no Model cell, but prune anyway: a hand-edited settings
    // file (or a future reviewer that gains one) must not leave an orphan pin.
    reviewerModels: models.without(`@${value}`),
    reviewerEfforts: efforts.without(`@${value}`)
  });

  const add = (value) => {
    if (!value || selected.includes(value)) return;
    emit({ reviewers: prioritizeToolFreeReviewers([...selected, value]) });
  };
  const remove = (value) => emit({
    reviewers: selected.filter(r => r !== value),
    optionalReviewers: withoutToken(value),
    reviewerMaxRounds: maxRounds.without(value),
    reviewerModels: models.without(value),
    reviewerEfforts: efforts.without(value)
  });
  const move = (index, delta) => {
    const target = index + delta;
    if (target < 0 || target >= selected.length) return;
    if (isToolFreeReviewer(orderedSelected[index]) !== isToolFreeReviewer(orderedSelected[target])) return;
    const next = [...orderedSelected];
    [next[index], next[target]] = [next[target], next[index]];
    emit({ reviewers: next });
  };

  return (
    <div className="@container flex flex-col gap-2 w-full">
      {showReviewers && (
        <div className="flex flex-col sm:flex-row sm:items-end gap-2 min-w-0">
          <div className="w-full sm:w-64 max-w-full">
            <ProviderModelSelector
              dense
              label="Add AI provider"
              providers={addableProviders}
              selectedProviderId=""
              onProviderChange={providerId => add(providerId && `provider:${providerId}`)}
              emptyProviderOption={modelOptions?.loaded === false ? 'Loading…' : '+ Provider'}
              compose={false}
              highlightVision={false}
              loading={modelOptions?.loaded === false}
              disabled={disabled}
            />
          </div>
          {addable.length > 0 && (
            <div className="w-full sm:w-48 max-w-full">
              <label htmlFor={`${id}-legacy`} className="block mb-1 text-xs text-gray-500">Add local / CLI</label>
              <select
                id={`${id}-legacy`}
                value=""
                disabled={disabled}
                onChange={event => add(event.target.value)}
                className="w-full min-h-9 px-2 bg-port-bg border border-port-border rounded text-xs text-gray-300 focus:border-port-accent focus:outline-none disabled:opacity-50"
              >
                <option value="">+ Local / CLI</option>
                {addable.map(option => <option key={option.value} value={option.value}>{option.label}{unavailability(option.value) ? ` (${unavailability(option.value).label})` : ''}</option>)}
              </select>
            </div>
          )}
          {modelOptions?.providersLoaded === false && modelOptions?.loaded && <p role="alert" className="text-xs text-port-warning">Provider list unavailable. Reload to retry.</p>}
        </div>
      )}
      {effortNotice && <p role="status" className="text-xs text-port-warning">{effortNotice}</p>}
      {showReviewers && <div className="flex flex-col gap-1">
        {selected.length > 0 && (
          <>
            <div className={HEADER_CLASS} aria-hidden="true">
              <span>#</span>
              <span>Provider</span>
              <span>Model</span>
              <span>Effort</span>
              <span>Optional</span>
              <span className="text-center">Max</span>
              <span className="sr-only">Remove</span>
            </div>
            <div className="flex flex-col gap-1.5 @4xl:gap-0.5">
              {orderedSelected.map((value, index) => renderReviewer(value, (
                <div
                  key={value}
                  className={ROW_CLASS}
                  title={REVIEWER_OPTIONS.find(o => o.value === value)?.description}
                >
                  <div className="flex items-center gap-0.5 col-span-2 @4xl:col-span-1">
                    <span className="text-port-accent font-mono text-xs">{index + 1}.</span>
                    <button
                      type="button"
                      disabled={disabled || index === 0 || isToolFreeReviewer(value) !== isToolFreeReviewer(orderedSelected[index - 1])}
                      onClick={() => move(index, -1)}
                      className="min-h-9 min-w-9 flex items-center justify-center text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
                      aria-label={`Move ${labelFor(value)} earlier`}
                    >
                      <ChevronUp size={12} />
                    </button>
                    <button
                      type="button"
                      disabled={disabled || index === orderedSelected.length - 1 || isToolFreeReviewer(value) !== isToolFreeReviewer(orderedSelected[index + 1])}
                      onClick={() => move(index, 1)}
                      className="min-h-9 min-w-9 flex items-center justify-center text-gray-500 hover:text-white disabled:opacity-30 disabled:hover:text-gray-500"
                      aria-label={`Move ${labelFor(value)} later`}
                    >
                      <ChevronDown size={12} />
                    </button>
                  </div>
                  <span className="flex items-center gap-1 min-w-0 col-span-2 @4xl:col-span-1">
                    <span className="text-xs text-gray-300 break-words">{labelFor(value)}</span>
                    {renderUnavailableBadge(value)}
                  </span>
                  <span className={CELL_LABEL_CLASS}>Model</span>
                  <div className="min-w-0">{renderModelCell(value)}</div>
                  <span className={CELL_LABEL_CLASS}>Effort</span>
                  <div className="min-w-0">{renderEffortCell(value)}</div>
                  <span className={CELL_LABEL_CLASS}>Optional</span>
                  <div>
                    {renderOptToggle(value, labelFor(value), isOptional(value)
                      ? `${labelFor(value)} is non-blocking (~opt): an inconclusive verdict from it won't block the merge. Click to make it blocking.`
                      : `${labelFor(value)} gates the merge. Click to make it non-blocking (~opt) — its inconclusive verdicts won't block the merge (a hard failure still does).`)}
                  </div>
                  <span className={CELL_LABEL_CLASS}>Max iterations</span>
                  <div>{renderMaxRounds(value, labelFor(value))}</div>
                  <div className="col-span-2 @4xl:col-span-1 justify-self-end">
                    <button
                      type="button"
                      disabled={disabled}
                      onClick={() => remove(value)}
                      className="min-h-9 min-w-9 flex items-center justify-center text-gray-500 hover:text-port-error"
                      aria-label={`Remove ${labelFor(value)}`}
                    >
                      <X size={12} />
                    </button>
                  </div>
                  {unavailability(value) && <p className="col-span-2 @4xl:col-span-7 text-xs text-port-warning break-words">{unavailability(value).title}</p>}
                </div>
              )))}
            </div>
          </>
        )}
        {selected.length === 0 && (
          <span className="text-xs text-gray-400 italic">None</span>
        )}
      </div>}

      {/* GitHub reviewer usernames — arbitrary PR reviewers (bots/humans) that
          gate the merge. Appended to `--review-with` as `@user` tokens. Same row
          grid as the keyed reviewers so the columns line up, minus reorder (their
          order is fixed after the keyed list) and minus a Model cell. */}
      {showUsernames && <div className="flex flex-col gap-1.5 pt-1 border-t border-port-border/50">
        <span className="text-xs text-gray-500">People &amp; bots (GitHub/GitLab)</span>
        {selectedUsernames.length > 0 ? (
          <div className="flex flex-col gap-1.5 @4xl:gap-0.5">
            {selectedUsernames.map((value) => (
              <div
                key={value}
                className={ROW_CLASS}
                title="GitHub/GitLab username requested as a PR/MR reviewer to gate the merge"
              >
                <span className="text-port-accent font-mono text-xs col-span-2 @4xl:col-span-1">@</span>
                <span className="text-xs text-gray-300 col-span-2 @4xl:col-span-1 truncate">{value}</span>
                <span className="hidden @4xl:block" />
                <span className="hidden @4xl:block" />
                <span className={CELL_LABEL_CLASS}>Optional</span>
                <div>
                  {renderOptToggle(`@${value}`, `@${value}`, isOptional(`@${value}`)
                    ? `@${value} is non-blocking (~opt): if it never submits a review, the merge isn't blocked. Click to make it blocking.`
                    : `@${value} gates the merge. Click to make it non-blocking (~opt) — a missing/timed-out review from it won't block the merge.`)}
                </div>
                <span className={CELL_LABEL_CLASS}>Max iterations</span>
                <div>{renderMaxRounds(`@${value}`, `@${value}`)}</div>
                <div className="col-span-2 @4xl:col-span-1 justify-self-end">
                  <button
                    type="button"
                    disabled={disabled}
                    onClick={() => removeUsername(value)}
                    className="min-h-9 min-w-9 flex items-center justify-center text-gray-500 hover:text-port-error"
                    aria-label={`Remove @${value}`}
                  >
                    <X size={12} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : null}
        <div className="flex items-center gap-1.5">
          <span className="text-xs text-gray-400 font-mono">@</span>
          <input
            id={`${id}-username`}
            type="text"
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
            value={usernameInput}
            disabled={disabled || atMaxUsernames}
            placeholder="username"
            aria-label="Add a GitHub/GitLab reviewer username"
            onChange={(e) => { setUsernameInput(e.target.value); if (usernameError) setUsernameError(''); }}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addUsername(); } }}
            className="flex-1 min-w-0 max-w-[200px] px-2 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-9 focus:border-port-accent focus:outline-none disabled:opacity-50"
          />
          <button
            type="button"
            disabled={disabled || !usernameInput.trim() || atMaxUsernames}
            onClick={addUsername}
            aria-label="Add reviewer username"
            className="inline-flex items-center gap-1 px-2 min-h-9 bg-transparent border border-port-border rounded text-xs text-gray-400 hover:text-white hover:border-port-accent disabled:opacity-50"
          >
            <Plus size={11} />
            Add
          </button>
        </div>
        {usernameError && <span role="alert" className="text-xs text-port-error">{usernameError}</span>}
      </div>}

      {showRunFlags && selected.length >= 2 && (
        <div className="flex items-center gap-2">
          <label htmlFor={`${id}-stopmode`} className="text-xs text-gray-500">Stop mode:</label>
          <select
            id={`${id}-stopmode`}
            value={stopMode}
            disabled={disabled}
            onChange={e => emit({ stopMode: e.target.value })}
            className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px]"
          >
            {REVIEW_STOP_MODES.map(m => (
              <option key={m.value} value={m.value} title={m.description}>{m.label}</option>
            ))}
          </select>
        </div>
      )}

      {showRunFlags && hasApplyCapableReviewer && (
        <label htmlFor={`${id}-applies`} className="flex items-center gap-2 cursor-pointer select-none text-xs text-gray-500">
          <input
            id={`${id}-applies`}
            type="checkbox"
            checked={reviewerApplies}
            disabled={disabled}
            onChange={e => emit({ reviewerApplies: e.target.checked })}
            className="w-3.5 h-3.5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0"
          />
          Reviewer applies fixes (Codex edits the working tree; every other reviewer stays review-only)
        </label>
      )}
    </div>
  );
}