Skip to content
304 linesCodeBlameRaw
1import { ChevronRight, History, UsersRound } from "lucide-react";
2import { useState } from "react";
3import { Form, data, redirect, useNavigation, useOutletContext } from "react-router";
4
5import type { AgentVersion, NewWorkspaceAgent, WorkspaceAgent } from "@g1t/contracts";
6
7import type { Route } from "./+types/profile";
8import { AgentForm } from "../../../components/agents-mode";
9import { type BuilderAnswer, PersonalNotice, RedraftBox } from "../../../components/agents/builder";
10import { readOrNull } from "../../../components/agents/actions.server";
11import { versionChanges } from "../../../components/agents/format";
12import { TimeAgo } from "../../../components/ui";
13import { Alert } from "../../../components/ui/alert";
14import { Button } from "../../../components/ui/button";
15import { Card } from "../../../components/ui/card";
16import { isOrchestrator } from "../../../components/orchestrator";
17import { readAgentForm } from "../../../lib/agent-form";
18import { docs, workspaceAgents } from "../../../lib/services.server";
19import { wholeDollars } from "../../../lib/money";
20import { agentTeamsFor, changeAgentTeam } from "../../../lib/agent-teams.server";
21import { AgentTeamsEditor } from "../../../components/teams";
22import { assertSameOrigin, requireUser, roleIn } from "../../../lib/session.server";
23
24/** The teams it is on (and may join), and its saved versions. */
25export async function loader({ params, context, request }: Route.LoaderArgs) {
26 const viewer = requireUser(context, request);
27 const role = roleIn(viewer, params.owner);
28 const [teams, versions, spaces, effortCosts] = await Promise.all([
29 workspaceAgents
30 .get(params.owner.toLowerCase(), params.handle.toLowerCase(), viewer)
31 .then((found) => (found.ok && found.value.scope !== "personal" ? agentTeamsFor(viewer, params.owner.toLowerCase(), found.value.id) : null))
32 .catch(() => null),
33 readOrNull(workspaceAgents.versions(params.owner.toLowerCase(), params.handle.toLowerCase(), viewer)),
34 readingSpaces(params.owner.toLowerCase(), viewer),
35 // What each effort level has cost it, beside the control.
36 readOrNull(workspaceAgents.effortCosts(params.owner.toLowerCase(), params.handle.toLowerCase(), viewer)),
37 ]);
38 return {
39 teams,
40 slug: params.owner.toLowerCase(),
41 versions,
42 spaces,
43 effortCosts,
44 owner: role === "owner",
45 viewerId: viewer.id,
46 };
47}
48
49/** The Docs spaces the viewer can read, for an agent's required reading; none when Docs can't say. */
50async function readingSpaces(slug: string, viewer: Parameters<typeof docs.sidebar>[1]): Promise<{ id: string; name: string; kind: string }[]> {
51 const sidebar = await docs.sidebar(slug, viewer).catch(() => null);
52 return sidebar?.ok ? sidebar.value.spaces.filter((space) => !space.archived_at).map((space) => ({ id: space.id, name: space.name, kind: space.kind })) : [];
53}
54
55
56/** Saving makes a new version; every run records which one it ran. */
57export async function action({ params, context, request }: Route.ActionArgs) {
58 assertSameOrigin(request);
59 const viewer = requireUser(context, request);
60 const slug = params.owner.toLowerCase();
61 if (!roleIn(viewer, slug)) throw data(null, { status: 404 });
62 const form = await request.formData();
63 const handle = params.handle.toLowerCase();
64 const intent = String(form.get("intent") ?? "");
65 // Its teams: the team's own add and remove, from here.
66 const changed = await changeAgentTeam(form, viewer, slug, handle);
67 if (changed) return { teamChange: changed };
68 // "Tell <name> what to change": drafted, shown, and saved only when they say so.
69 if (intent === "redraft") {
70 const drafted = await workspaceAgents.redraft(slug, handle, viewer, String(form.get("request") ?? "")).catch(() => null);
71 if (!drafted) return { intent, ok: false, error: "The agents service didn't answer. Try again in a moment." } satisfies BuilderAnswer;
72 return (drafted.ok ? { intent, ok: true, redraft: drafted.value } : { intent, ok: false, error: drafted.error.message }) satisfies BuilderAnswer;
73 }
74 if (intent === "apply") {
75 let changes: Partial<NewWorkspaceAgent> = {};
76 try {
77 changes = JSON.parse(String(form.get("changes") ?? "{}")) as Partial<NewWorkspaceAgent>;
78 } catch {
79 return { errors: { form: "The change couldn't be read. Draft it again." }, saved: false };
80 }
81 // Drafted from one version: if someone saved another since, it is drafted again rather than laid over theirs.
82 const current = await workspaceAgents.get(slug, handle, viewer).catch(() => null);
83 if (current?.ok && String(current.value.version) !== String(form.get("from_version"))) {
84 return { errors: { form: `@${handle} was changed since this was drafted. Draft the change again.` }, saved: false };
85 }
86 const saved = await workspaceAgents.update(slug, handle, viewer, changes).catch(() => null);
87 if (!saved) return { errors: { form: "The agents service didn't answer. Try again in a moment." }, saved: false };
88 if (!saved.ok) return { errors: { [saved.error.code === "conflict" ? "handle" : "form"]: saved.error.message }, saved: false };
89 if (saved.value.handle !== handle) throw redirect(`/${slug}/-/agents/${saved.value.handle}/profile`);
90 return { errors: undefined, saved: true };
91 }
92 // Owners make a personal agent the workspace's: the same handle, a new agent.
93 if (intent === "promote") {
94 const promoted = await workspaceAgents.promote(slug, handle, viewer).catch(() => null);
95 if (!promoted) return { errors: { form: "The agents service didn't answer. Try again in a moment." }, saved: false };
96 if (!promoted.ok) return { errors: { form: promoted.error.message }, saved: false };
97 throw redirect(`/${slug}/-/agents/${promoted.value.handle}/profile`);
98 }
99 // Archiving keeps the agent's history (runs, replies, spend) but takes it
100 // out of chat and frees its handle. g1t itself can't be archived.
101 if (form.get("intent") === "archive") {
102 const archived = await workspaceAgents.archive(slug, params.handle.toLowerCase(), viewer).catch(() => null);
103 if (!archived) return { errors: { form: "The agents service didn't answer. Try again in a moment." }, saved: false };
104 if (!archived.ok) return { errors: { form: archived.error.message }, saved: false };
105 throw redirect(`/${slug}/-/agents`);
106 }
107 const read = readAgentForm(form, { orchestrator: params.handle.toLowerCase() === "g1t" });
108 if (!read.ok) return { errors: read.errors, saved: false };
109 const saved = await workspaceAgents.update(slug, params.handle.toLowerCase(), viewer, read.input).catch(() => null);
110 if (!saved) return { errors: { form: "The agents service didn't answer. Try again in a moment." }, saved: false };
111 if (!saved.ok) return { errors: { [saved.error.code === "conflict" ? "handle" : "form"]: saved.error.message }, saved: false };
112 // A new handle is a new address.
113 if (saved.value.handle !== params.handle.toLowerCase()) throw redirect(`/${slug}/-/agents/${saved.value.handle}/profile`);
114 return { errors: undefined, saved: true };
115}
116
117export default function Profile({ loaderData, actionData }: Route.ComponentProps) {
118 const agent = useOutletContext<WorkspaceAgent>();
119 const errors = actionData && "errors" in actionData ? (actionData.errors as Record<string, string> | undefined) : undefined;
120 const personal = agent.scope === "personal";
121 const mine = personal && agent.personal_owner_id === loaderData.viewerId;
122 // Who may change it: owners a workspace agent, its member a personal one.
123 const mayChange = personal ? mine : loaderData.owner;
124 return (
125 <>
126 {personal && <PersonalNotice agent={agent} owner={loaderData.owner} mine={mine} />}
127 {mayChange && <RedraftBox agent={agent} />}
128 {!isOrchestrator(agent) && (
129 <Card asChild className="mb-8 p-4">
130 <section aria-labelledby="agent-teams">
131 <h2 id="agent-teams" className="flex items-center gap-2 text-sm font-medium">
132 <UsersRound size={14} className="text-faint" />
133 Teams
134 </h2>
135 <p className="mt-0.5 mb-3 text-xs text-faint">On teams like anyone: owners and a team&apos;s maintainers add it and take it off.</p>
136 <AgentTeamsEditor
137 slug={loaderData.slug}
138 name={agent.display_name}
139 teams={loaderData.teams}
140 personal={personal}
141 change={actionData && "teamChange" in actionData ? actionData.teamChange : null}
142 />
143 </section>
144 </Card>
145 )}
146 {actionData && "saved" in actionData && actionData.saved && (
147 <p role="status" className="mb-6 rounded-lg border border-success/30 bg-success/10 px-4 py-2.5 text-sm text-success">
148 Saved as version {agent.version}.
149 </p>
150 )}
151 {errors?.form && (
152 <Alert asChild className="mb-6 px-4 py-3">
153 <p>{errors.form}</p>
154 </Alert>
155 )}
156 {/* A member's personal agent is theirs to change; owners promote or archive it. */}
157 {(!personal || mine) && (
158 <AgentForm
159 draft={agent}
160 errors={errors}
161 submit="Save changes"
162 intent="update"
163 formKey={`${agent.id}:${agent.version}`}
164 locked={isOrchestrator(agent)}
165 personal={personal}
166 spaces={loaderData.spaces}
167 effortCosts={loaderData.effortCosts}
168 seed={agent.avatar_seed || agent.id}
169 />
170 )}
171 {loaderData.versions && loaderData.versions.length > 0 && <Versions versions={loaderData.versions} current={agent.version} />}
172 {!isOrchestrator(agent) && <Archive name={agent.display_name} />}
173 </>
174 );
175}
176
177/** Retiring an agent: asked twice, since it leaves every channel at once. */
178function Archive({ name }: { name: string }) {
179 const [asking, setAsking] = useState(false);
180 const busy = useNavigation().formData?.get("intent") === "archive";
181 return (
182 <section className="mt-12 border-t border-line pt-8 md:grid md:grid-cols-[14rem_1fr] md:gap-10">
183 <div className="mb-4 md:mb-0">
184 <h2 className="text-sm font-semibold text-fg">Archive</h2>
185 <p className="mt-1 text-sm text-muted">Retire this agent. Owners can, and a member their own personal agent.</p>
186 </div>
187 <div>
188 <p className="text-sm text-muted">
189 {name} stops answering, leaves every channel and DM, and its handle is free to use again. Its runs, replies and spend stay in
190 the audit log and on Usage.
191 </p>
192 {asking ? (
193 <Form method="post" className="mt-4 flex flex-wrap items-center gap-3">
194 <input type="hidden" name="intent" value="archive" />
195 <Button
196 type="submit"
197 disabled={busy}
198 variant="destructive"
199 className="rounded-lg border-danger/50 bg-danger/15 px-4 hover:bg-danger/25 disabled:opacity-60"
200 >
201 {busy ? "Archiving…" : `Archive ${name}`}
202 </Button>
203 <Button type="button" onClick={() => setAsking(false)} variant="ghost" className="px-2 font-normal">
204 Keep {name}
205 </Button>
206 </Form>
207 ) : (
208 <Button
209 type="button"
210 onClick={() => setAsking(true)}
211 variant="outline"
212 className="mt-4 rounded-lg px-4 text-muted hover:border-danger/50 hover:text-danger font-normal"
213 >
214 Archive agent…
215 </Button>
216 )}
217 </div>
218 </section>
219 );
220}
221
222/**
223 * Every saved version of the agent, newest first: who saved it, when, and
224 * what changed from the one before. Each run and reply records the version
225 * it ran with.
226 */
227function Versions({ versions, current }: { versions: AgentVersion[]; current: number }) {
228 const [open, setOpen] = useState(false);
229 const sorted = [...versions].sort((a, b) => b.version - a.version);
230 const shown = open ? sorted : sorted.slice(0, 3);
231 return (
232 <section className="mt-12 border-t border-line pt-8 md:grid md:grid-cols-[14rem_1fr] md:gap-10">
233 <div className="mb-4 md:mb-0">
234 <h2 className="flex items-center gap-2 text-sm font-semibold text-fg">
235 <History size={14} className="text-faint" />
236 Version history
237 </h2>
238 <p className="mt-1 text-sm text-muted">Every save is a new version. Sessions and replies record the one they ran with.</p>
239 </div>
240 <div>
241 <Card asChild className="divide-y divide-line/60 overflow-hidden">
242 <ol>
243 {shown.map((version) => {
244 const before = sorted.find((v) => v.version < version.version) ?? null;
245 const definition = version.definition as Record<string, unknown>;
246 return (
247 <li key={version.version} className="px-4 py-3">
248 <details className="group">
249 <summary className="flex cursor-pointer list-none items-center gap-3 text-sm [&::-webkit-details-marker]:hidden">
250 <ChevronRight size={14} className="shrink-0 text-faint transition-transform group-open:rotate-90" />
251 <span className="font-medium tabular-nums">Version {version.version}</span>
252 {version.version === current && <span className="rounded-full bg-accent/15 px-1.5 py-px text-[0.6875rem] font-medium text-accent">Current</span>}
253 <span className="min-w-0 grow truncate text-muted">
254 {before ? versionChanges(before.definition as Record<string, unknown>, definition) : version.version === 1 ? "Created" : "Saved"}
255 </span>
256 <span className="shrink-0 text-xs text-faint">
257 @{version.changed_by} · <TimeAgo at={version.created_at} />
258 </span>
259 </summary>
260 <dl className="mt-3 grid gap-x-6 gap-y-2 pl-7 text-xs sm:grid-cols-2">
261 {summaryOf(definition).map(([label, value]) => (
262 <div key={label} className="min-w-0">
263 <dt className="text-faint">{label}</dt>
264 <dd className="mt-0.5 line-clamp-3 text-fg-soft">{value}</dd>
265 </div>
266 ))}
267 </dl>
268 </details>
269 </li>
270 );
271 })}
272 </ol>
273 </Card>
274 {sorted.length > 3 && (
275 <Button type="button" onClick={() => setOpen(!open)} variant="link" size="inline" className="mt-3 text-sm text-muted hover:text-fg font-normal">
276 {open ? "Show fewer" : `Show all ${sorted.length} versions`}
277 </Button>
278 )}
279 </div>
280 </section>
281 );
282}
283
284/** A saved definition, in a few lines. */
285function summaryOf(definition: Record<string, unknown>): [string, string][] {
286 const out: [string, string][] = [];
287 const text = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null);
288 const name = text(definition.display_name);
289 if (name) out.push(["Name", `${name}${text(definition.handle) ? ` (@${definition.handle})` : ""}`]);
290 const title = text(definition.title) ?? text(definition.role);
291 if (title) out.push(["Role", title]);
292 const job = text(definition.instructions);
293 if (job) out.push(["Job", job]);
294 const voice = text(definition.personality_preset);
295 if (voice) out.push(["Personality", [voice, text(definition.personality)].filter(Boolean).join(" · ")]);
296 const budget = definition.budget as { monthly_micros?: number | null; task_micros?: number | null } | undefined;
297 if (budget && (budget.monthly_micros != null || budget.task_micros != null)) {
298 const dollars = wholeDollars;
299 out.push(["Budget", [budget.monthly_micros != null ? `${dollars(budget.monthly_micros)} a month` : null, budget.task_micros != null ? `${dollars(budget.task_micros)} a session` : null].filter(Boolean).join(", ")]);
300 }
301 const duties = Array.isArray(definition.responsibilities) ? (definition.responsibilities as string[]) : [];
302 if (duties.length > 0) out.push(["Responsibilities", duties.join("; ")]);
303 return out;
304}