# All files / src/components/agents AgentManager.tsx

98.75% Statements 158/160
94.87% Branches 37/39
88.88% Functions 8/9
98.75% Lines 158/160

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

    1x

    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x

    1x
    21x
    21x
    20x
    18x
    21x
    4x
    4x
    17x
    17x

    11x
    11x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    11x
    11x
    11x
    11x
    11x

    11x

    1x
    11x
    11x
    11x
    11x
    11x
    11x
    11x
    11x
    11x

    11x
    1x
    1x
    1x
    1x

    1x

    11x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x

    1x

    11x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x

    7x
    7x
    7x
    7x

    7x
    7x

    7x
    7x
    7x

    7x

    2x
    2x

    4x
    4x
    4x
    4x

    4x

    4x
    1x
    1x

    1x
    1x

    4x
    4x
    4x
    4x
    4x
    4x

    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x

    4x
    4x

    4x
    4x
    4x

    4x
     /**
     * AgentManager — presentational create form and read-only detail view for
     * standing agents (#1417, Phase 0). Pure: it takes data plus callbacks and
     * never touches the router or `useGrackle`.
     *
     * @module
     */

    import { useState, type FormEvent, type JSX } from "react";
    import type { AgentData, PersonaData } from "../../hooks/types.js";
    import { Button } from "../display/Button.js";
    import styles from "./AgentManager.module.scss";

    /** Props for {@link AgentManager}. */
    export interface AgentManagerProps {
      /** All agents (used to resolve the one named by `agentId` in view mode). */
      agents: AgentData[];
      /** Personas available to be chosen as the primary persona. */
      personas: PersonaData[];
      /** When set and found in `agents`, render the read-only view; else create form. */
      agentId?: string;
      /**
       * True while the parent's agent list is still loading. Suppresses the
       * not-found view while a route-matched `agentId` may still arrive, so the
       * user never briefly sees "Agent not found" between mount and first fetch.
       */
      agentsLoading?: boolean;
      /** Create a new agent. Called only in create mode. */
      onCreate: (name: string, avatar: string, primaryPersonaId: string) => void;
      /** Delete the viewed agent. Called only in view mode. */
      onDelete: (id: string) => void;
      /** Navigate away (after create/delete, or via the back affordance). */
      onNavigateBack: () => void;
    }

    /**
     * Allowed `data:` URI subtypes for inline avatars. Excludes `svg+xml`, which
     * can embed `<script>`/event-handler payloads — modern browsers don't execute
     * scripts inside SVGs rendered via `<img>`, but CodeQL flags the flow anyway
     * (`js/xss-through-dom`), and there's no real UX cost to dropping SVG support
     * for a paste-an-image-string avatar field.
     */
    const SAFE_DATA_IMAGE_PREFIXES: readonly string[] = [
      "data:image/png;",
      "data:image/jpeg;",
      "data:image/gif;",
      "data:image/webp;",
    ];

    /**
     * True when the avatar string points to a renderable image source. Allows
     * `http(s)://`, root-relative paths, and a fixed allow-list of safe `data:`
     * image MIME types; anything else (other `data:` schemes, `javascript:`,
     * `vbscript:`, etc.) falls through to the inline-glyph branch instead of
     * becoming an `<img src>`. See CodeQL alerts #26 and #27.
     */
    export function isImageAvatar(avatar: string): boolean {
      if (
        avatar.startsWith("http://") ||
        avatar.startsWith("https://") ||
        (avatar.startsWith("/") && !avatar.startsWith("//"))
      ) {
        return true;
      }
      return SAFE_DATA_IMAGE_PREFIXES.some((p) => avatar.startsWith(p));
    }

    /** Render an agent's avatar: image, emoji glyph, or a name-derived monogram. */
    function AvatarPreview({ name, avatar }: { name: string; avatar: string }): JSX.Element {
      if (avatar && isImageAvatar(avatar)) {
        return (
          <img
            className={styles.avatar}
            src={avatar}
            alt=""
            referrerPolicy="no-referrer"
            loading="lazy"
            data-testid="agent-avatar-image"
          />
        );
      }
      const glyph = avatar || (name.trim().charAt(0) || "?").toUpperCase();
      return (
        <span className={styles.avatar} aria-hidden="true" data-testid="agent-avatar-glyph">
          {glyph}
        </span>
      );
    }

    /**
     * Create form (no `agentId`) or read-only detail view (valid `agentId`).
     */
    export function AgentManager({
      agents,
      personas,
      agentId,
      agentsLoading = false,
      onCreate,
      onDelete,
      onNavigateBack,
    }: AgentManagerProps): JSX.Element {
      const agent = agentId ? agents.find((a) => a.id === agentId) : undefined;

      // ── Loading view ────────────────────────────────────────────────────────
      // Suppress the not-found / create branches while the parent's agent list is
      // still loading, so the user never sees a "not found" flash before the
      // matching agent arrives.
      if (agentId && !agent && agentsLoading) {
        return (
          <div className={styles.container} data-testid="agent-loading">
            <p className={styles.placeholder}>Loading…</p>
          </div>
        );
      }

      // ── Not-found view ───────────────────────────────────────────────────────
      // If the route names an `agentId` but it doesn't exist (deleted, bad URL),
      // show an explicit not-found state instead of falling through to the create
      // form — otherwise the URL `/agents/:gone` looks identical to `/agents/new`.
      if (agentId && !agent) {
        return (
          <div className={styles.container} data-testid="agent-not-found">
            <h1 className={styles.title}>Agent not found</h1>
            <p className={styles.placeholder}>
              No agent exists with id <code>{agentId}</code>.
            </p>
            <div className={styles.actions}>
              <Button variant="ghost" onClick={onNavigateBack} data-testid="agent-back">
                Back
              </Button>
            </div>
          </div>
        );
      }

      // ── Read-only view ───────────────────────────────────────────────────────
      if (agentId && agent) {
        const persona = personas.find((p) => p.id === agent.primaryPersonaId);
        return (
          <div className={styles.container} data-testid="agent-view">
            <div className={styles.header}>
              <AvatarPreview name={agent.name} avatar={agent.avatar} />
              <h1 className={styles.title} data-testid="agent-name">
                {agent.name}
              </h1>
            </div>
            <dl className={styles.fields}>
              <dt>Primary persona</dt>
              <dd data-testid="agent-persona">
                {persona ? persona.name : agent.primaryPersonaId || "(none)"}
              </dd>
            </dl>
            <section className={styles.history} data-testid="agent-history">
              <h2 className={styles.sectionTitle}>History</h2>
              <p className={styles.placeholder}>
                This agent has no lifecycle yet. Activity will appear here once standing agents can run.
              </p>
            </section>
            <div className={styles.actions}>
              <Button variant="ghost" onClick={onNavigateBack} data-testid="agent-back">
                Back
              </Button>
              <Button variant="danger" onClick={() => onDelete(agent.id)} data-testid="agent-delete">
                Delete
              </Button>
            </div>
          </div>
        );
      }

      // ── Create form ──────────────────────────────────────────────────────────
      return <AgentCreateForm personas={personas} onCreate={onCreate} onCancel={onNavigateBack} />;
    }

    /** Props for the internal create form. */
    interface AgentCreateFormProps {
      personas: PersonaData[];
      onCreate: (name: string, avatar: string, primaryPersonaId: string) => void;
      onCancel: () => void;
    }

    /** Controlled create form for a new agent. */
    function AgentCreateForm({ personas, onCreate, onCancel }: AgentCreateFormProps): JSX.Element {
      const [name, setName] = useState("");
      const [avatar, setAvatar] = useState("");
      const [primaryPersonaId, setPrimaryPersonaId] = useState("");

      const canSubmit = name.trim().length > 0;

      const handleSubmit = (e: FormEvent): void => {
        e.preventDefault();
        if (!canSubmit) {
          return;
        }
        onCreate(name.trim(), avatar.trim(), primaryPersonaId);
      };

      return (
        <form className={styles.container} onSubmit={handleSubmit} data-testid="agent-create-form">
          <div className={styles.header}>
            <AvatarPreview name={name || "?"} avatar={avatar} />
            <h1 className={styles.title}>Create Agent</h1>
          </div>

          <label className={styles.label} htmlFor="agent-name-input">
            Name
          </label>
          <input
            id="agent-name-input"
            className={styles.input}
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Refactor Bot"
            data-testid="agent-name-input"
            autoFocus
          />

          <label className={styles.label} htmlFor="agent-avatar-input">
            Avatar <span className={styles.hint}>(emoji, URL, or data URI)</span>
          </label>
          <input
            id="agent-avatar-input"
            className={styles.input}
            value={avatar}
            onChange={(e) => setAvatar(e.target.value)}
            placeholder="(optional)"
            data-testid="agent-avatar-input"
          />

          <label className={styles.label} htmlFor="agent-persona-select">
            Primary persona
          </label>
          <select
            id="agent-persona-select"
            className={styles.input}
            value={primaryPersonaId}
            onChange={(e) => setPrimaryPersonaId(e.target.value)}
            data-testid="agent-persona-select"
          >
            <option value="">(none)</option>
            {personas.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>

          <div className={styles.actions}>
            <Button variant="ghost" type="button" onClick={onCancel} data-testid="agent-cancel">
              Cancel
            </Button>
            <Button variant="primary" type="submit" disabled={!canSubmit} data-testid="agent-submit">
              Create Agent
            </Button>
          </div>
        </form>
      );
    }