All files / src/components/settings SettingsPage.tsx

77.19% Statements 264/342
74.07% Branches 20/27
25% Functions 8/32
77.19% Lines 264/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 5501x                                                   1x   3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x       3x 3x 3x 3x 3x           3x 3x     3x 3x 3x 3x 3x           3x   6x 6x 6x 6x         6x 6x 6x 6x 6x 6x 6x       6x 6x 6x 6x 6x 6x 6x         6x 6x 6x 6x   6x   6x 6x     6x 6x 6x 6x 6x           6x                                                                           1x 1x   1x   1x 11x 11x 11x   11x 11x 11x 11x 11x   11x   11x 2x 2x 2x   2x   11x 1x 1x 1x 1x 1x   11x 1x 1x   11x                         11x   11x                                 11x                   11x   11x                                 11x                   11x 2x   2x 2x 2x 1x 1x 1x 1x 1x 1x     1x 2x   11x   11x 4x 4x 4x     4x   11x 1x 1x 1x 1x 1x 1x         1x   6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 11x 11x 11x 11x 11x         11x 11x       11x 11x 11x 11x 11x       11x 11x 11x 11x 11x       11x 11x 1x 1x 1x         11x 11x 11x 11x 11x 11x                   11x 11x 11x 11x 11x       11x 11x 11x 11x 11x 11x 11x 1x 5x   11x       11x 11x 11x     11x 11x 11x 11x 11x 2x     11x 11x 11x 11x           11x 1x 1x 1x         11x 11x 11x 11x 11x 11x                 11x 11x 11x 11x 11x         11x 11x 11x 11x 11x     11x 6x 6x 6x         11x 11x 11x 11x                 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x       11x 11x     11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x       11x 11x         11x  
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  createModelProfile,
  createProvider,
  deleteModelProfile,
  deleteProvider,
  fetchConfigBootstrap,
  setActiveModelProfile,
  updateModelProfile,
  updateProvider,
} from "../../api";
import { ApiError } from "../../api";
import type {
  ConfigBootstrapPayload,
  ModelProfileView,
  CommandView,
  ProviderView,
} from "../../types";
import { LoadingSpinner } from "../shared/LoadingSpinner";
import { DeleteConfirmModal } from "./DeleteConfirmModal";
import type { ProfilePayload } from "./ModelProfileModal";
import { ModelProfileModal } from "./ModelProfileModal";
import type { ProviderPayload } from "./ProviderModal";
import { ProviderModal } from "./ProviderModal";
 
// ── Card sub-components ──────────────────────────────────────────────────────
 
function ProviderCard({
  provider,
  onEdit,
  onDelete,
}: {
  provider: ProviderView;
  onEdit: () => void;
  onDelete: () => void;
}) {
  return (
    <div className="settings-item">
      <div className="settings-item__info">
        <div className="settings-item__name">{provider.name}</div>
        <div className="settings-item__id">{provider.id}</div>
        <div className="settings-item__meta">
          <span className="settings-item__tag">{provider.kind}</span>
          {provider.has_secret && (
            <span className="settings-item__tag settings-item__tag--success">
              {provider.secret_source === "env_var"
                ? (provider.secret_env_var ?? "env var")
                : "key: set"}
            </span>
          )}
          {provider.responses_url && (
            <span
              className="settings-item__tag"
              title={provider.responses_url}
            >
              custom responses URL
            </span>
          )}
          {provider.generic_api_url && (
            <span
              className="settings-item__tag"
              title={provider.generic_api_url}
            >
              custom API URL
            </span>
          )}
        </div>
      </div>
      <div className="settings-item__actions">
        <button type="button" className="btn btn--ghost btn--sm" onClick={onEdit}>
          Edit
        </button>
        <button
          type="button"
          className="btn btn--ghost-danger btn--sm"
          onClick={onDelete}
        >
          Delete
        </button>
      </div>
    </div>
  );
}
 
function ProfileCard({
  profile,
  onEdit,
  onDelete,
}: {
  profile: ModelProfileView;
  onEdit: () => void;
  onDelete: () => void;
}) {
  const r = profile.resolved_runtime;
  const runtimeParts: string[] = [r.model];
  if (r.reasoning_effort && r.reasoning_effort !== "none") {
    runtimeParts.push(r.reasoning_effort);
  }
  if (r.service_tier) {
    runtimeParts.push(r.service_tier);
  }
 
  return (
    <div className="settings-item">
      <div className="settings-item__info">
        <div className="settings-item__name">
          {profile.name}
          {profile.is_active_default && (
            <span className="settings-item__tag settings-item__tag--accent">
              default
            </span>
          )}
        </div>
        <div className="settings-item__id">{profile.id}</div>
        <div className="settings-item__meta">
          <span className="settings-item__tag">{profile.provider.name}</span>
          <span className="settings-item__tag">{profile.provider.kind}</span>
        </div>
        <div className="runtime-summary">{runtimeParts.join(" · ")}</div>
      </div>
      <div className="settings-item__actions">
        <button type="button" className="btn btn--ghost btn--sm" onClick={onEdit}>
          Edit
        </button>
        <button
          type="button"
          className="btn btn--ghost-danger btn--sm"
          onClick={onDelete}
        >
          Delete
        </button>
      </div>
    </div>
  );
}
 
function CommandCard({
  command,
}: {
  command: CommandView;
}) {
  return (
    <div className="settings-item settings-item--command">
      <div className="settings-item__info">
        <div className="settings-item__name">{command.name}</div>
        <div className="settings-item__id">{command.id}</div>
        <div className="settings-item__meta">
          <span className="settings-item__tag settings-item__tag--accent">
            {command.slash_alias}
          </span>
          <span className="settings-item__tag">{command.path}</span>
        </div>
        {command.description && (
          <div className="settings-item__summary">{command.description}</div>
        )}
        <pre className="settings-item__instructions">{command.instructions}</pre>
      </div>
    </div>
  );
}
 
// ── Modal state discriminated union ─────────────────────────────────────────
 
type ModalState =
  | { type: "none" }
  | { type: "create-provider" }
  | { type: "edit-provider"; provider: ProviderView }
  | { type: "delete-provider"; provider: ProviderView }
  | { type: "create-profile" }
  | { type: "edit-profile"; profile: ModelProfileView }
  | { type: "delete-profile"; profile: ModelProfileView };
 
const STALE_MESSAGE =
  "Settings were changed while you were editing. Please review and resubmit.";
 
// ── SettingsPage ─────────────────────────────────────────────────────────────
 
export function SettingsPage() {
  const queryClient = useQueryClient();
  const [modal, setModal] = useState<ModalState>({ type: "none" });
  const [pageError, setPageError] = useState<string | null>(null);
 
  const configQuery = useQuery({
    queryKey: ["config-bootstrap"],
    queryFn: fetchConfigBootstrap,
    staleTime: 30_000,
  });
 
  // ── Helpers ────────────────────────────────────────────────────────────────
 
  function getRevision(): string {
    return (
      queryClient.getQueryData<ConfigBootstrapPayload>(["config-bootstrap"])
        ?.config_revision ?? ""
    );
  }
 
  async function invalidateBoth() {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ["config-bootstrap"] }),
      queryClient.invalidateQueries({ queryKey: ["bootstrap"] }),
    ]);
  }
 
  function handleStale() {
    void queryClient.refetchQueries({ queryKey: ["config-bootstrap"] });
  }
 
  function wrapStale(err: unknown): never {
    if (err instanceof ApiError && err.status === 409) {
      if (err.message.includes("Config has changed")) {
        handleStale();
        throw new Error(STALE_MESSAGE);
      }
      // Business-logic conflict (e.g. "still references it") – surface
      // the real backend message so the user knows what to fix.
      throw err;
    }
    throw err;
  }
 
  // ── Provider handlers ──────────────────────────────────────────────────────
 
  async function saveProvider(
    payload: ProviderPayload,
    existingId?: string,
  ): Promise<void> {
    try {
      if (existingId) {
        await updateProvider(existingId, payload, getRevision());
      } else {
        await createProvider(payload, getRevision());
      }
      await invalidateBoth();
      setModal({ type: "none" });
    } catch (err) {
      wrapStale(err);
    }
  }
 
  async function deleteProviderById(providerId: string): Promise<void> {
    try {
      await deleteProvider(providerId, getRevision());
      await invalidateBoth();
      setModal({ type: "none" });
    } catch (err) {
      wrapStale(err);
    }
  }
 
  // ── Profile handlers ───────────────────────────────────────────────────────
 
  async function saveProfile(
    payload: ProfilePayload,
    existingId?: string,
  ): Promise<void> {
    try {
      if (existingId) {
        await updateModelProfile(existingId, payload, getRevision());
      } else {
        await createModelProfile(payload, getRevision());
      }
      await invalidateBoth();
      setModal({ type: "none" });
    } catch (err) {
      wrapStale(err);
    }
  }
 
  async function deleteProfileById(profileId: string): Promise<void> {
    try {
      await deleteModelProfile(profileId, getRevision());
      await invalidateBoth();
      setModal({ type: "none" });
    } catch (err) {
      wrapStale(err);
    }
  }
 
  async function handleSetActiveProfile(
    profileId: string | null,
  ): Promise<void> {
    setPageError(null);
    try {
      await setActiveModelProfile(profileId, getRevision());
      await invalidateBoth();
    } catch (err) {
      if (err instanceof ApiError && err.status === 409) {
        handleStale();
        setPageError(STALE_MESSAGE);
      } else {
        setPageError((err as Error).message);
      }
    }
  }
 
  // ── Render ─────────────────────────────────────────────────────────────────
 
  if (configQuery.isLoading) {
    return (
      <div className="center-spinner">
        <LoadingSpinner size="lg" />
      </div>
    );
  }
 
  if (configQuery.isError || !configQuery.data) {
    return (
      <div className="settings-page">
        <div className="settings-page__inner">
          <div className="settings-error-banner">
            Failed to load settings:{" "}
            {(configQuery.error as Error)?.message ?? "Unknown error"}
          </div>
        </div>
      </div>
    );
  }
 
  const {
    providers,
    model_profiles,
    commands,
    active_profile_id,
    options,
  } = configQuery.data;
 
  return (
    <div className="settings-page">
      <div className="settings-page__inner">
        {model_profiles.length === 0 && (
          <div className="settings-inline-note settings-onboarding-guide">
            <strong>First-time setup:</strong> To start using the app, complete these steps:
            <ol>
              <li>Add a provider with your API credentials</li>
              <li>Create a model profile that uses that provider</li>
            </ol>
          </div>
        )}
 
        {pageError && (
          <div className="settings-error-banner">{pageError}</div>
        )}
 
        {/* ── Providers panel ── */}
        <div className="settings-panel">
          <div className="settings-panel__header">
            <div>
              <div className="settings-panel__title">Providers</div>
              <div className="settings-panel__subtitle">
                LLM provider connections and credentials
              </div>
            </div>
            <button
              type="button"
              className="btn btn--primary"
              onClick={() => setModal({ type: "create-provider" })}
            >
              + Add Provider
            </button>
          </div>
          <div className="settings-panel__body">
            {providers.length === 0 ? (
              <div className="empty-state">
                <div className="empty-state__title">No providers configured</div>
                <div className="empty-state__description">
                  Add a provider to start using model profiles.
                </div>
              </div>
            ) : (
              providers.map((p) => (
                <ProviderCard
                  key={p.id}
                  provider={p}
                  onEdit={() => setModal({ type: "edit-provider", provider: p })}
                  onDelete={() =>
                    setModal({ type: "delete-provider", provider: p })
                  }
                />
              ))
            )}
          </div>
        </div>
 
        {/* ── Model Profiles panel ── */}
        <div className="settings-panel">
          <div className="settings-panel__header">
            <div>
              <div className="settings-panel__title">Model Profiles</div>
              <div className="settings-panel__subtitle">
                Runtime configuration combining a provider with model settings
              </div>
            </div>
            <button
              type="button"
              className="btn btn--primary"
              onClick={() => setModal({ type: "create-profile" })}
              disabled={providers.length === 0}
              title={
                providers.length === 0
                  ? "Add a provider first"
                  : undefined
              }
            >
              Add Profile
            </button>
          </div>
          <div className="settings-panel__body">
            <div className="active-profile-control">
              <span className="active-profile-control__label">
                Active default
              </span>
              <select
                name="active-profile"
                className="active-profile-control__select"
                value={active_profile_id ?? ""}
                onChange={(e) =>
                  void handleSetActiveProfile(e.target.value || null)
                }
              >
                <option value="">No default</option>
                {model_profiles.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name}
                  </option>
                ))}
              </select>
            </div>
 
            {model_profiles.length === 0 ? (
              <div className="empty-state">
                <div className="empty-state__title">No profiles configured</div>
                <div className="empty-state__description">
                  Add a model profile to configure runtime settings.
                </div>
              </div>
            ) : (
              model_profiles.map((p) => (
                <ProfileCard
                  key={p.id}
                  profile={p}
                  onEdit={() => setModal({ type: "edit-profile", profile: p })}
                  onDelete={() =>
                    setModal({ type: "delete-profile", profile: p })
                  }
                />
              ))
            )}
          </div>
        </div>
 
        <div className="settings-panel">
          <div className="settings-panel__header">
            <div>
              <div className="settings-panel__title">Commands</div>
              <div className="settings-panel__subtitle">
                Project command files for single-turn prompt presets
              </div>
            </div>
          </div>
          <div className="settings-panel__body">
            <div className="settings-inline-note">
              Add Markdown files under <code>.agents/commands/</code>; a file
              like <code>.agents/commands/review.md</code> becomes{" "}
              <code>/review</code>.
            </div>
 
            {commands.length === 0 ? (
              <div className="empty-state">
                <div className="empty-state__title">No commands found</div>
                <div className="empty-state__description">
                  Add project command files under .agents/commands/.
                </div>
              </div>
            ) : (
              commands.map((command) => (
                <CommandCard
                  key={command.id}
                  command={command}
                />
              ))
            )}
          </div>
        </div>
      </div>
 
      {/* ── Modals ── */}
      {modal.type === "create-provider" && (
        <ProviderModal
          options={options}
          onSave={(payload) => saveProvider(payload)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
      {modal.type === "edit-provider" && (
        <ProviderModal
          provider={modal.provider}
          options={options}
          onSave={(payload) => saveProvider(payload, modal.provider.id)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
      {modal.type === "delete-provider" && (
        <DeleteConfirmModal
          title="Delete Provider"
          body={
            <>
              Delete provider <strong>{modal.provider.name}</strong>? This
              cannot be undone.
            </>
          }
          onConfirm={() => deleteProviderById(modal.provider.id)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
      {modal.type === "create-profile" && (
        <ModelProfileModal
          providers={providers}
          options={options}
          onSave={(payload) => saveProfile(payload)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
      {modal.type === "edit-profile" && (
        <ModelProfileModal
          profile={modal.profile}
          providers={providers}
          options={options}
          onSave={(payload) => saveProfile(payload, modal.profile.id)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
      {modal.type === "delete-profile" && (
        <DeleteConfirmModal
          title="Delete Profile"
          body={
            <>
              Delete profile <strong>{modal.profile.name}</strong>? This cannot
              be undone.
            </>
          }
          onConfirm={() => deleteProfileById(modal.profile.id)}
          onClose={() => setModal({ type: "none" })}
        />
      )}
    </div>
  );
}