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