SPB Git

Repository Public

Agents.tsx 8.9 KB 132 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/social-web/src/screens/settings/Agents.tsx9 * Module           : screens10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useState } from 'react';43import { get, post } from '../../../../shared/api.ts';44import { usePrefs } from '../../prefs.tsx';45import { brandQuery, useSession } from '../../session.tsx';46import { Link } from '../../router.tsx';47import type { AgentRun, AgentRunResult } from '../../types.ts';48import { ActionStatus, Await, Empty, Field, Hash, JsonView, KV, Notice, Panel, TableWrap, Tag, useAction, useLoad } from '../../ui/core.tsx';4950type AgentsRes = { agents: { name: string; mission: string; authority: string; provider: string }[]; providers: { claude: { configured: boolean; model: string }; mlx: { configured: boolean; model: string; baseUrl: string } }; budget: { monthlyUsd: number; perRunUsd: number; spentThisMonthUsd: number } };51const RUNNABLE = ['director', 'copywriter', 'analytics', 'product', 'supervisor'] as const;5253export function RunResult({ r }: { r: AgentRunResult }) {54  const { t, tl, num } = usePrefs();55  const created: string[] = Array.isArray(r.output?.createdDraftIds) ? r.output.createdDraftIds : [];56  return (57    <div className="note note-info" role="status">58      <p><strong>{tl('agent', r.agent)}</strong> <Tag prefix="runStatus" value={r.status} /> <span className="small">{t('ag.authority')} {tl('authority', r.authority)}</span></p>59      {r.error ? <p><code>{r.error}</code></p> : null}60      {r.llm ? <p className="small">{t('ck.model')} <code>{r.llm.model || '—'}</code> · <code>{r.llm.status}</code> · {num(r.llm.costUsd, { style: 'currency', currency: 'USD', maximumFractionDigits: 4 })}</p> : <p className="small">{t('ag.noModel')}</p>}61      {created.length ? <p>{t('ag.createdDrafts')} {created.map((id, i) => <span key={id}>{i ? ' · ' : ''}<Link to={`/content/${id}`}>{t('ag.draft', { n: i + 1 })}</Link></span>)}</p> : null}62      {r.output !== null && r.output !== undefined ? <details><summary>{t('c.rawOutput')}</summary><JsonView value={r.output} /></details> : null}63    </div>64  );65}6667export function Agents() {68  const { t, tl, num } = usePrefs();69  const s = useSession();70  const d = useLoad(() => get<AgentsRes>('/v1/agents'), []);71  const [f, setF] = useState({ agent: 'director' as (typeof RUNNABLE)[number], brandId: s.brandId, instruction: '' });72  const [res, setRes] = useState<AgentRunResult | null>(null);73  const a = useAction();74  const usd = (n: number) => num(n, { style: 'currency', currency: 'USD', maximumFractionDigits: 2 });75  const run = async () => { setRes(null); const r = await a.run(() => post<AgentRunResult>('/v1/agents/run', { agent: f.agent, brandId: f.brandId || null, instruction: f.instruction })); if (r) { setRes(r); d.reload(); } };76  const yes = (b: boolean) => <Tag prefix="ag.conf" value={b ? 'yes' : 'no'} tone={b ? 'ok' : 'alert'} />;77  return (78    <Await of={d}>{(x) => (<>79      <Panel title={t('ag.providers')}>80        <p className="small">{t('ag.providersLead')}</p>81        <KV rows={[82          ['Claude', <>{yes(x.providers.claude.configured)} <code>{x.providers.claude.model || '—'}</code></>],83          ['MLX', <>{yes(x.providers.mlx.configured)} <code>{x.providers.mlx.model || '—'}</code> <span className="small">{x.providers.mlx.baseUrl}</span></>],84          [t('ag.budgetMonth'), usd(x.budget.monthlyUsd)],85          [t('ag.budgetRun'), usd(x.budget.perRunUsd)],86          [t('ag.spent'), <strong>{num(Number(x.budget.spentThisMonthUsd), { style: 'currency', currency: 'USD', maximumFractionDigits: 4 })}</strong>],87        ]} />88        {!x.providers.claude.configured && !x.providers.mlx.configured ? <Notice tone="warn"><p>{t('ag.noneConfigured')}</p></Notice> : null}89      </Panel>90      <Panel title={t('ag.list')}>91        <p className="small">{t('ag.listLead')}</p>92        <TableWrap caption={t('ag.list')}>93          <thead><tr><th scope="col">{t('ag.agent')}</th><th scope="col">{t('ag.mission')}</th><th scope="col">{t('ag.authority')}</th><th scope="col">{t('ag.provider')}</th></tr></thead>94          <tbody>{x.agents.map((g) => <tr key={g.name}><th scope="row">{tl('agent', g.name)}</th><td>{g.mission}</td><td>{tl('authority', g.authority)}</td><td>{g.provider === 'none' ? t('ag.providerNone') : <><code>{g.provider}</code> {g.provider === 'claude' || g.provider === 'mlx' ? yes(x.providers[g.provider].configured) : null}</>}</td></tr>)}</tbody>95        </TableWrap>96      </Panel>97      <Panel title={t('ag.run')}>98        <p className="small">{t('ag.runLead')}</p>99        <form className="form" onSubmit={(e) => { e.preventDefault(); void run(); }}>100          <div className="form-grid">101            <Field label={t('ag.agent')}><select value={f.agent} onChange={(e) => setF({ ...f, agent: e.target.value as (typeof RUNNABLE)[number] })}>{RUNNABLE.map((n) => <option key={n} value={n}>{tl('agent', n)}</option>)}</select></Field>102            <Field label={f.agent === 'supervisor' ? `${t('c.brand')} (${t('c.optional')})` : t('c.brand')}><select value={f.brandId} onChange={(e) => setF({ ...f, brandId: e.target.value })} required={f.agent !== 'supervisor'}><option value="">{t('c.select')}</option>{s.brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</select></Field>103            <Field label={f.agent === 'copywriter' ? t('ag.brief') : `${t('ag.instruction')} (${t('c.optional')})`} wide><textarea value={f.instruction} onChange={(e) => setF({ ...f, instruction: e.target.value })} rows={3} maxLength={4000} /></Field>104          </div>105          <div className="row"><button type="submit" disabled={a.busy}>{t('ag.runGo')}</button></div>106          <ActionStatus a={a} />107        </form>108        {res ? <RunResult r={res} /> : null}109      </Panel>110    </>)}</Await>111  );112}113114export function AgentRuns() {115  const { t, tl, dt, num } = usePrefs();116  const s = useSession();117  const d = useLoad(() => get<{ runs: AgentRun[] }>(`/v1/agent-runs${brandQuery(s.brandId)}`), [s.brandId]);118  return (119    <Panel title={t('ar.title')} actions={<button type="button" onClick={d.reload} disabled={d.loading}>{t('c.reload')}</button>}>120      <Await of={d}>{(x) => x.runs.length === 0 ? <Empty>{t('ar.empty')}</Empty> : (121        <TableWrap caption={t('ar.title')}>122          <thead><tr><th scope="col">{t('ar.started')}</th><th scope="col">{t('ag.agent')}</th><th scope="col">{t('c.status')}</th><th scope="col">{t('c.brand')}</th><th scope="col">{t('ag.provider')}</th><th scope="col" className="num">{t('ar.tokens')}</th><th scope="col" className="num">{t('ar.cost')}</th><th scope="col">{t('ar.target')}</th><th scope="col">{t('c.details')}</th></tr></thead>123          <tbody>{x.runs.map((r) => (124            <tr key={r.id}><td>{dt(r.started_at)}</td><th scope="row">{tl('agent', r.agent)}</th><td><Tag prefix="runStatus" value={r.status} /></td><td>{s.brandById(r.brand_id)?.name ?? '—'}</td><td><code>{r.provider}</code>{r.model ? <> <span className="small">{r.model}</span></> : null}</td><td className="num">{num(r.tokens_in)} / {num(r.tokens_out)}</td><td className="num">{num(Number(r.cost_usd), { style: 'currency', currency: 'USD', maximumFractionDigits: 5 })}</td><td>{r.target_kind ? <><code>{r.target_kind}</code> <Hash value={r.target_id} /></> : '—'}</td>125              <td>{r.error ? <p><code>{r.error}</code></p> : null}{r.output !== null && r.output !== undefined ? <details><summary>{t('c.rawOutput')}</summary><JsonView value={r.output} /></details> : r.error ? null : '—'}</td></tr>126          ))}</tbody>127        </TableWrap>128      )}</Await>129    </Panel>130  );131}132
Files main
Menu

Theme