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