Skip to content
refs
History
237 lines · 11.9 KBRaw
1import type { AgentRunView, HostedAgent, HostedAgents, ModelProvider } from "@refs/backend/contract";
2import { AgentAvatar, Ago, Badge, Banner, Button, Empty, Input, InputArea, LayerCard, LinkButton, Select } from "@refs/design-system";
3import { CheckCircleIcon, CircleNotchIcon, PlusIcon, RobotIcon, WarningCircleIcon } from "@refs/design-system/icons";
4import { AppLink } from "./link";
5import { useState } from "react";
6import { Form, redirect, useNavigation } from "react-router";
7import { failed, formText } from "../lib/session";
8
9const PROVIDERS: Record<"" | ModelProvider, { label: string; example: string }> = {
10 "": { label: "Workers AI (default)", example: "" },
11 anthropic: { label: "Anthropic", example: "claude-sonnet-5-5" },
12 openai: { label: "OpenAI", example: "gpt-5.5" },
13 openrouter: { label: "OpenRouter", example: "anthropic/claude-sonnet-5-5" },
14};
15
16const SCOPE_LABEL: Record<HostedAgent["scope"], string> = { builtin: "Built in", namespace: "Shared", repo: "This repository" };
17
18export type Level = "namespace" | "repo";
19
20/** Handles the save and remove forms of an agents page, then goes back to the list. */
21export async function agentsAction(agents: HostedAgents, request: Request, back: string) {
22 const form = await request.formData();
23 const intent = formText(form, "intent");
24 const outcome =
25 intent === "save"
26 ? await agents.save({
27 handle: formText(form, "handle"),
28 description: formText(form, "description"),
29 instructions: String(form.get("instructions") ?? ""),
30 provider: formText(form, "provider"),
31 model: formText(form, "model"),
32 key: String(form.get("key") ?? ""),
33 })
34 : intent === "remove"
35 ? await agents.remove(formText(form, "handle"))
36 : null;
37 if (!outcome) return failed({ code: "invalid", message: "Unknown action." }, {});
38 return outcome.ok ? redirect(back) : failed(outcome.problem, {});
39}
40
41/** The agent being edited: `?edit=new` for a new one, `?edit=<handle>` for one in the list. */
42export function editingFrom(request: Request, list: readonly HostedAgent[], level: Level): { agent: HostedAgent | null; fresh: boolean } | null {
43 const edit = new URL(request.url).searchParams.get("edit");
44 if (!edit) return null;
45 if (edit === "new") return { agent: null, fresh: true };
46 const agent = list.find((entry) => entry.handle === edit && (entry.scope === level || !entry.replaced)) ?? null;
47 return agent ? { agent, fresh: agent.scope !== level } : null;
48}
49
50export function HostedAgentsPage({ list, canEdit, level, editing, error }: { list: readonly HostedAgent[]; canEdit: boolean; level: Level; editing: ReturnType<typeof editingFrom>; error: string | null }) {
51 return (
52 <div className="flex max-w-4xl flex-col gap-5">
53 {error && <Banner variant="error" description={error} />}
54 {canEdit && editing ? (
55 <AgentEditor key={editing.agent?.handle ?? "new"} agent={editing.agent} customizing={editing.fresh && editing.agent !== null} level={level} />
56 ) : (
57 canEdit && (
58 <div>
59 <LinkButton href="?edit=new" variant="secondary" icon={<PlusIcon size={16} />}>
60 Add agent
61 </LinkButton>
62 </div>
63 )
64 )}
65 <LayerCard className="divide-y divide-hairline">
66 {list.map((agent) => (
67 <AgentRow key={`${agent.scope}:${agent.handle}`} agent={agent} canEdit={canEdit} level={level} />
68 ))}
69 </LayerCard>
70 </div>
71 );
72}
73
74function modelLabel(agent: HostedAgent): string {
75 return agent.model ? `${PROVIDERS[agent.model.provider].label} · ${agent.model.model} · key ending in ${agent.model.keyHint}` : "GLM-5.3 on Workers AI";
76}
77
78function AgentRow({ agent, canEdit, level }: { agent: HostedAgent; canEdit: boolean; level: Level }) {
79 const own = agent.scope === level;
80 return (
81 <div className={`flex flex-wrap items-center gap-3 p-4 ${agent.replaced ? "opacity-60" : ""}`}>
82 <AgentAvatar name={agent.handle} size="base" />
83 <div className="flex min-w-0 flex-1 flex-col gap-0.5">
84 <span className="flex flex-wrap items-center gap-2">
85 <span className="font-medium">@{agent.handle}</span>
86 <Badge variant="outline">{SCOPE_LABEL[agent.scope]}</Badge>
87 {agent.replaced && <span className="text-compact text-muted">Replaced here</span>}
88 </span>
89 {agent.description && <span className="text-compact text-muted">{agent.description}</span>}
90 <span className="text-xs text-faint">{modelLabel(agent)}</span>
91 </div>
92 {canEdit && own && (
93 <div className="flex gap-2">
94 <LinkButton href={`?edit=${agent.handle}`} variant="secondary" size="sm">
95 Edit
96 </LinkButton>
97 <Form method="post" className="inline-flex">
98 <input type="hidden" name="intent" value="remove" />
99 <input type="hidden" name="handle" value={agent.handle} />
100 <Button type="submit" variant="secondary-destructive" size="sm">
101 Remove
102 </Button>
103 </Form>
104 </div>
105 )}
106 {canEdit && !own && !agent.replaced && (
107 <LinkButton href={`?edit=${agent.handle}`} variant="secondary" size="sm">
108 Customize
109 </LinkButton>
110 )}
111 </div>
112 );
113}
114
115function AgentEditor({ agent, customizing, level }: { agent: HostedAgent | null; customizing: boolean; level: Level }) {
116 const navigation = useNavigation();
117 const saving = navigation.state === "submitting" && navigation.formData?.get("intent") === "save";
118 const saved = agent && !customizing ? agent.model : null;
119 const [provider, setProvider] = useState<"" | ModelProvider>(saved?.provider ?? "");
120 const title = !agent ? "Add agent" : customizing ? `Customize @${agent.handle} for this ${level === "repo" ? "repository" : "namespace"}` : `Edit @${agent.handle}`;
121 return (
122 <LayerCard className="p-4">
123 <Form method="post" className="flex flex-col gap-4" autoComplete="off">
124 <h2 className="m-0 text-base font-semibold">{title}</h2>
125 {customizing && <p className="m-0 text-compact text-muted">Your copy replaces @{agent!.handle} here. Remove it to go back to the original.</p>}
126 <input type="hidden" name="intent" value="save" />
127 <div className="flex flex-wrap gap-3">
128 <div className="min-w-48 flex-1">
129 <Input label="Handle" name="handle" defaultValue={agent?.handle ?? ""} readOnly={agent !== null} placeholder="For example, security" description="People mention the agent as @handle." maxLength={32} required />
130 </div>
131 <div className="min-w-60 flex-[2]">
132 <Input label="Description" name="description" defaultValue={agent?.description ?? ""} placeholder="What the agent does, in one line" maxLength={200} />
133 </div>
134 </div>
135 <InputArea label="Instructions" name="instructions" defaultValue={agent?.instructions ?? ""} rows={10} description="What the agent does when someone mentions it. It can read the code and the code map, and it answers with one comment." maxLength={8000} required />
136 <div className="flex flex-wrap gap-3">
137 <Select label="Model" name="provider" value={provider} onValueChange={(value) => setProvider(value as "" | ModelProvider)} items={Object.fromEntries(Object.entries(PROVIDERS).map(([value, entry]) => [value, entry.label]))} />
138 {provider && (
139 <div className="min-w-60 flex-1">
140 <Input label="Model ID" name="model" defaultValue={saved?.provider === provider ? saved.model : ""} placeholder={`For example, ${PROVIDERS[provider].example}`} maxLength={200} required />
141 </div>
142 )}
143 </div>
144 {provider ? (
145 <Input
146 label="API key"
147 name="key"
148 type="password"
149 placeholder={saved?.provider === provider ? `Saved key ending in ${saved.keyHint}` : undefined}
150 description={`${saved?.provider === provider ? "Leave empty to keep the saved key. " : ""}refs tests the key with one short request, then stores it encrypted. No one can read it back. Each run of this agent uses this key.`}
151 maxLength={500}
152 />
153 ) : (
154 <p className="m-0 text-compact text-muted">The agent runs GLM-5.3 on Workers AI, and refs pays for it.</p>
155 )}
156 <div className="flex gap-2">
157 <Button type="submit" variant="primary" loading={saving}>
158 Save agent
159 </Button>
160 <LinkButton href="?" variant="secondary">
161 Cancel
162 </LinkButton>
163 </div>
164 </Form>
165 </LayerCard>
166 );
167}
168
169const RUN_TEXT: Record<AgentRunView["state"], string> = { working: "is working", answered: "answered", failed: "did not finish" };
170
171/** The recent runs of the repository's agents. A run that still works shows each step as it lands. */
172export function AgentActivity({ runs, repo, open, now }: { runs: readonly AgentRunView[]; repo: string; open: string | null; now: number }) {
173 return (
174 <section className="flex max-w-4xl flex-col gap-3">
175 <h2 className="m-0 text-base font-semibold">Activity</h2>
176 {runs.length === 0 ? (
177 <LayerCard>
178 <Empty size="sm" icon={<RobotIcon size={24} />} title="No agent runs yet" description="Mention an agent on a pull request, or add an agent job to .refs/ci.yml." />
179 </LayerCard>
180 ) : (
181 <LayerCard className="divide-y divide-hairline">
182 {runs.map((run) => (
183 <div key={run.session} className="flex flex-col gap-2 p-4">
184 <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
185 <RunIcon state={run.state} />
186 <AgentAvatar name={run.handle} size="xs" />
187 <span className="font-medium">@{run.handle}</span>
188 <span className="text-muted">{RUN_TEXT[run.state]}</span>
189 {run.pull !== null && (
190 <AppLink href={`/${repo}/pulls/${run.pull}`} className="text-accent-text">
191 on #{run.pull}
192 </AppLink>
193 )}
194 {run.via === "ci" && <Badge variant="outline">CI</Badge>}
195 <span className="text-compact text-faint">
196 for {run.person} · <Ago at={run.startedAt} now={now} />
197 </span>
198 </div>
199 {run.summary && run.state !== "working" && <p className="m-0 text-compact text-muted [overflow-wrap:anywhere]">{run.summary}</p>}
200 {run.steps ? (
201 <RunSteps steps={run.steps} working={run.state === "working"} />
202 ) : null}
203 {run.state !== "working" && (
204 <AppLink href={open === run.session ? "?" : `?run=${run.session}`} className="text-compact text-accent-text">
205 {open === run.session ? "Hide thinking" : "Show thinking"}
206 </AppLink>
207 )}
208 </div>
209 ))}
210 </LayerCard>
211 )}
212 </section>
213 );
214}
215
216function RunSteps({ steps, working }: { steps: NonNullable<AgentRunView["steps"]>; working: boolean }) {
217 if (!steps.length) return <p className="m-0 text-compact text-muted">{working ? "Reading the pull request…" : "This run recorded no steps."}</p>;
218 return (
219 <ol className="m-0 flex list-none flex-col gap-2 rounded-control bg-sunken p-3">
220 {steps.map((step) => (
221 <li key={step.step} className="flex flex-col gap-1">
222 <span className="text-xs font-medium text-muted">
223 Step {step.step}
224 {step.tools.length ? ` · ${step.tools.join(" · ")}` : " · writing the answer"}
225 </span>
226 {step.thinking && <p className="m-0 line-clamp-4 text-compact whitespace-pre-wrap text-faint [overflow-wrap:anywhere]">{step.thinking}</p>}
227 </li>
228 ))}
229 </ol>
230 );
231}
232
233function RunIcon({ state }: { state: AgentRunView["state"] }) {
234 if (state === "answered") return <CheckCircleIcon size={14} className="text-success" />;
235 if (state === "failed") return <WarningCircleIcon size={14} className="text-danger" />;
236 return <CircleNotchIcon size={14} className="animate-spin motion-reduce:animate-none" />;
237}