feat: add AI agent workspace (#3062)

* chore(ai): remove local AI store now that providers live server-side

The Zustand-based useAIStore has been replaced by the server-side
aiProviders oRPC router (encrypted credentials persisted in DB).
Delete the dead store + tests, drop the ./store export, and remove
zustand/immer deps which are no longer referenced anywhere in
packages/ai/src/.

* feat(agent): archive/delete actions and read-only state for agent threads

- Backend: mark archived threads as read-only in threads.get and reject
  messages.send with CONFLICT when the thread is archived.
- Frontend: render archived threads in the sidebar with muted styling and
  an Archived badge; add a per-thread dropdown menu in the chat header
  with Archive (non-destructive) and Delete (with confirmation); show a
  read-only banner above the message list that disambiguates archived
  vs. missing-resource causes; suppress the Retry and Stop buttons in
  read-only mode.
- Tests: new packages/api/src/services/agent.test.ts covering the
  archived-thread isReadOnly flag and the archived-thread send refusal.

* fix(agent): abort run on archive and verify ownership before deleting thread

- threads.archive: before flipping status, abort any in-flight run controller
  and clear the active-run state on the thread; cleanup failures are logged
  but do not block the status update.
- threads.delete: assert thread ownership via getThread before destructive
  work so an authenticated user cannot wipe another user's attachment rows
  by passing a foreign threadId.

Adds focused tests for both behaviors.

* feat(agent): display patch diffs and surface revert conflicts

Render apply_resume_patch tool messages with a status-aware card (applied/
reverted/conflicted), expandable operation list, and a Revert button that
correctly handles RESUME_VERSION_CONFLICT responses. Adds unit tests for
the inverse-patch builder and the agentService.actions.revert flow.

* chore(agent): remove out-of-scope attachment tests accidentally added in Task 6

The Task 6 commit (73ef1acca) accidentally re-introduced three attachment-
related tests that belong to a separate task:

- `buildAttachmentModelParts > converts text, image, supported binary, and
  unsupported attachments into model parts`
- `agentService.messages.send > persists the user message with file UI parts
  and links selected attachments to it` (was failing — the `ToolLoopAgent`
  mock is not callable as a constructor)
- `agentService.messages.send > rejects attachments that are missing, foreign,
  or already linked before persisting a message`

These were likely re-added during a stash recovery and were not requested
for Task 6, whose scope was limited to the `agentService.actions.revert`
flow. Remove them along with the helpers/fixtures (`buildAttachment`,
`buildActiveThread`, `selectWhereResult`, `selectOrderByResult`) that they
were the only consumers of. `selectLimitResult` is preserved because it is
used by the revert tests.

* chore(agent): configure runtime dependencies

* feat(db): add agent workspace schema

* feat(api): add agent backend services

* feat(web): add agent workspace UI

* chore(agent): remove legacy builder assistant

* test(agent): make agent stream mocks constructible

* chore(web): remove unused resume replacement hook

* feat(api): add unsafe AI base URL flag

* chore(dev): expose local services in compose

* fix(web): normalize resume preview gaps

* feat(api): improve agent tool handling

* feat(web): polish agent workspace UI

* chore: update dependencies

* fix(api,web): address PR review feedback for agent workspace

Security/correctness:
- Restrict AI provider URLs to http/https even in unsafe mode
- Stop exposing Redis on host network by default
- Make .env.local optional and drop app profile in compose.dev.yml
- Store agent attachments with private ACL on S3
- Reset provider test status when provider/model/baseURL changes
- Decouple non-agent AI endpoints from REDIS_URL requirement
- Fix JSON Patch add inverse for existing object members
- Wrap resume patch + agent action insert in db transaction
- Validate partialMessage at runtime and rate-limit attachment uploads
- Add unique index on agent_messages (thread_id, sequence)

UX/bugs:
- Mark agent thread route as ssr: false and guard SSE chunk parsing
- Show config-specific banner only on known configuration error
- Gate AI provider checks behind loading state in resume import
- Fix relative-time formatter blank gap between 45-59 seconds
- Clarify thread delete confirmation message

Polish:
- Raise ENCRYPTION_SECRET minimum to 32 characters
- Bucket AI rate limits by resumeId/threadId/messageId
- Trim form values before submitting AI provider config
- Use single key identifier and nullish-coalesce baseURL display

* fix: address ai agent review feedback

* fix: preserve mobile agent chat state

* docs: add ai agent workspace guides

* feat: introduce design system for Reactive Resume
This commit is contained in:
Amruth Pillai
2026-05-14 15:00:04 +02:00
committed by GitHub
parent 22c60c64b6
commit 6d8d8f6e55
115 changed files with 15623 additions and 2123 deletions
@@ -4,6 +4,7 @@ import { useLingui } from "@lingui/react";
import { Trans } from "@lingui/react/macro";
import {
BrainIcon,
ChatCircleDotsIcon,
GearSixIcon,
KeyIcon,
ReadCvLogoIcon,
@@ -46,6 +47,11 @@ const appSidebarItems = [
label: msg`Resumes`,
href: "/dashboard/resumes",
},
{
icon: <ChatCircleDotsIcon />,
label: msg`Agents`,
href: "/agent",
},
] as const satisfies SidebarItem[];
const settingsSidebarItems = [
@@ -1,238 +1,355 @@
import type { AIProvider } from "@reactive-resume/ai/types";
import type { ComboboxOption } from "@/components/ui/combobox";
import type { RouterOutput } from "@/libs/orpc/client";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { CheckCircleIcon, InfoIcon, XCircleIcon } from "@phosphor-icons/react";
import { useMutation } from "@tanstack/react-query";
import { useMemo } from "react";
import { ORPCError } from "@orpc/client";
import { CheckCircleIcon, KeyIcon, PlusIcon, TrashIcon, WarningCircleIcon, XCircleIcon } from "@phosphor-icons/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { useAIStore } from "@reactive-resume/ai/store";
import { AI_PROVIDER_DEFAULT_BASE_URLS } from "@reactive-resume/ai/types";
import { Badge } from "@reactive-resume/ui/components/badge";
import { Button } from "@reactive-resume/ui/components/button";
import { Input } from "@reactive-resume/ui/components/input";
import { Label } from "@reactive-resume/ui/components/label";
import { Spinner } from "@reactive-resume/ui/components/spinner";
import { Switch } from "@reactive-resume/ui/components/switch";
import { cn } from "@reactive-resume/utils/style";
import { Combobox } from "@/components/ui/combobox";
import { getOrpcErrorMessage } from "@/libs/error-message";
import { orpc } from "@/libs/orpc/client";
type SavedProvider = RouterOutput["aiProviders"]["list"][number];
type AIProviderOption = ComboboxOption<AIProvider> & { defaultBaseURL: string };
const providerOptions: AIProviderOption[] = [
{
value: "openai",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "OpenAI",
}),
label: t`OpenAI`,
keywords: ["openai", "gpt", "chatgpt"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.openai,
},
{
value: "anthropic",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "Anthropic Claude",
}),
label: t`Anthropic Claude`,
keywords: ["anthropic", "claude", "ai"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.anthropic,
},
{
value: "gemini",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "Google Gemini",
}),
keywords: ["gemini", "google", "bard"],
label: t`Google Gemini`,
keywords: ["gemini", "google"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.gemini,
},
{
value: "vercel-ai-gateway",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "Vercel AI Gateway",
}),
label: t`Vercel AI Gateway`,
keywords: ["vercel", "gateway", "ai"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS["vercel-ai-gateway"],
},
{
value: "openrouter",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "OpenRouter",
}),
keywords: ["openrouter", "router", "multi", "proxy"],
label: t`OpenRouter`,
keywords: ["openrouter", "router"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.openrouter,
},
{
value: "ollama",
label: t({
comment: "AI provider option label in dashboard AI settings",
message: "Ollama",
}),
keywords: ["ollama", "ai", "local"],
label: t`Ollama`,
keywords: ["ollama", "local"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS.ollama,
},
{
value: "openai-compatible",
label: t`OpenAI-compatible`,
keywords: ["compatible", "custom", "gateway"],
defaultBaseURL: AI_PROVIDER_DEFAULT_BASE_URLS["openai-compatible"],
},
];
function AIForm() {
const { set, model, apiKey, baseURL, provider, enabled, testStatus } = useAIStore();
const emptyForm = {
label: "",
provider: "openai" as AIProvider,
model: "",
baseURL: "",
apiKey: "",
};
const selectedOption = useMemo(() => {
return providerOptions.find((option) => option.value === provider);
}, [provider]);
const canTestConnection = model.trim().length > 0 && apiKey.trim().length > 0;
const { mutate: testConnection, isPending: isTesting } = useMutation(orpc.ai.testConnection.mutationOptions());
const handleProviderChange = (value: AIProvider | null) => {
if (!value) return;
set((draft) => {
draft.provider = value;
});
};
const handleTestConnection = () => {
if (!canTestConnection) return;
testConnection(
{ provider, model: model.trim(), apiKey: apiKey.trim(), baseURL: baseURL.trim() },
{
onSuccess: (data) => {
set((draft) => {
draft.testStatus = data ? "success" : "failure";
});
},
onError: (error) => {
set((draft) => {
draft.testStatus = "failure";
});
toast.error(
getOrpcErrorMessage(error, {
byCode: {
BAD_REQUEST: t({
comment: "Error shown when AI provider credentials or base URL are invalid in AI settings",
message: "Invalid AI provider configuration. Please check your settings.",
}),
BAD_GATEWAY: t({
comment: "Error shown when the configured AI provider cannot be reached during connection test",
message: "Could not reach the AI provider. Please try again.",
}),
},
fallback: t({
comment: "Fallback toast when testing AI provider connection fails",
message: "Failed to test AI provider connection. Please try again.",
}),
}),
);
},
},
function statusBadge(provider: SavedProvider) {
if (provider.testStatus === "success") {
return (
<Badge className="bg-emerald-600 text-white">
<Trans>Tested</Trans>
</Badge>
);
};
}
if (provider.testStatus === "failure") {
return (
<Badge variant="destructive">
<Trans>Failed</Trans>
</Badge>
);
}
return (
<Badge variant="secondary">
<Trans>Untested</Trans>
</Badge>
);
}
function providerLabel(provider: AIProvider) {
return providerOptions.find((option) => option.value === provider)?.label ?? provider;
}
function isAiProviderConfigError(error: unknown) {
if (error instanceof ORPCError && error.code === "PRECONDITION_FAILED") return true;
if (!error || typeof error !== "object") return false;
const status = (error as { status?: unknown; code?: unknown }).status ?? (error as { code?: unknown }).code;
return status === "PRECONDITION_FAILED" || status === 412;
}
function ProviderRow({ provider }: { provider: SavedProvider }) {
const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: orpc.aiProviders.list.queryKey() });
const { mutate: testProvider, isPending: isTesting } = useMutation(orpc.aiProviders.test.mutationOptions());
const { mutate: updateProvider, isPending: isUpdating } = useMutation(orpc.aiProviders.update.mutationOptions());
const { mutate: deleteProvider, isPending: isDeleting } = useMutation(orpc.aiProviders.delete.mutationOptions());
const isMutating = isTesting || isUpdating || isDeleting;
return (
<div className="grid gap-6 sm:grid-cols-2">
<div className="flex flex-col gap-y-2">
<Label htmlFor="ai-provider">
<Trans>Provider</Trans>
</Label>
<Combobox
id="ai-provider"
value={provider}
disabled={enabled}
options={providerOptions}
onValueChange={handleProviderChange}
/>
</div>
<div className="flex flex-col gap-y-2">
<Label htmlFor="ai-model">
<Trans>Model</Trans>
</Label>
<Input
id="ai-model"
name="ai-model"
type="text"
value={model}
disabled={enabled}
onChange={(e) =>
set((draft) => {
draft.model = e.target.value;
})
}
placeholder={t({
comment: "Example model-name placeholder in AI settings",
message: "e.g., gpt-4, claude-3-opus, gemini-pro",
})}
autoCorrect="off"
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
/>
</div>
<div className="flex flex-col gap-y-2 sm:col-span-2">
<Label htmlFor="ai-api-key">
<Trans>API Key</Trans>
</Label>
<Input
id="ai-api-key"
name="ai-api-key"
type="password"
value={apiKey}
disabled={enabled}
onChange={(e) =>
set((draft) => {
draft.apiKey = e.target.value;
})
}
autoCorrect="off"
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
data-lpignore="true"
data-bwignore="true"
data-1p-ignore="true"
/>
</div>
<div className="flex flex-col gap-y-2 sm:col-span-2">
<Label htmlFor="ai-base-url">
<Trans>Base URL (Optional)</Trans>
</Label>
<Input
id="ai-base-url"
name="ai-base-url"
type="url"
value={baseURL}
disabled={enabled}
placeholder={selectedOption?.defaultBaseURL}
onChange={(e) =>
set((draft) => {
draft.baseURL = e.target.value;
})
}
autoCorrect="off"
autoComplete="off"
spellCheck="false"
autoCapitalize="off"
/>
</div>
<div>
<Button variant="outline" disabled={isTesting || enabled || !canTestConnection} onClick={handleTestConnection}>
{isTesting ? (
<Spinner />
) : testStatus === "success" ? (
<CheckCircleIcon className="text-emerald-500" />
) : testStatus === "failure" ? (
<XCircleIcon className="text-rose-500" />
<div className="grid gap-4 rounded-md border bg-card p-4 md:grid-cols-[1fr_auto]">
<div className="min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<h3 className="truncate font-semibold">{provider.label}</h3>
{statusBadge(provider)}
{provider.enabled ? (
<Badge variant="outline">
<Trans>Enabled</Trans>
</Badge>
) : null}
<Trans>Test Connection</Trans>
</div>
<div className="grid gap-1 text-muted-foreground text-sm">
<p>
{providerLabel(provider.provider)} · {provider.model}
</p>
<p className="truncate">{provider.baseURL ?? AI_PROVIDER_DEFAULT_BASE_URLS[provider.provider]}</p>
<p>
<Trans>Key</Trans>: {provider.apiKeyPreview}
</p>
{provider.testError ? <p className="text-rose-600">{provider.testError}</p> : null}
</div>
</div>
<div className="flex items-center gap-2 md:justify-end">
<div className="flex items-center gap-2 pe-2">
<Switch
checked={provider.enabled}
disabled={provider.testStatus !== "success" || isMutating}
onCheckedChange={(enabled) =>
updateProvider(
{ id: provider.id, enabled },
{
onSuccess: () => void invalidate(),
onError: (error) =>
toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to update provider.` })),
},
)
}
/>
<span className="text-muted-foreground text-sm">
<Trans>Use</Trans>
</span>
</div>
<Button
variant="outline"
disabled={isMutating}
onClick={() =>
testProvider(
{ id: provider.id },
{
onSuccess: (response) => {
if (response.testStatus === "success") {
toast.success(t`Provider connection verified.`);
} else {
toast.error(response.testError ?? t`Could not verify provider connection.`);
}
void invalidate();
},
onError: (error) => {
toast.error(getOrpcErrorMessage(error, { fallback: t`Could not verify provider connection.` }));
void invalidate();
},
},
)
}
>
{isTesting ? <Spinner /> : provider.testStatus === "success" ? <CheckCircleIcon /> : <WarningCircleIcon />}
<Trans>Test</Trans>
</Button>
<Button
size="icon"
variant="ghost"
disabled={isMutating}
onClick={() =>
deleteProvider(
{ id: provider.id },
{
onSuccess: () => void invalidate(),
onError: (error) =>
toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to delete provider.` })),
},
)
}
>
<TrashIcon />
<span className="sr-only">
<Trans>Delete provider</Trans>
</span>
</Button>
</div>
</div>
);
}
function CreateProviderForm() {
const queryClient = useQueryClient();
const [form, setForm] = useState(emptyForm);
const selectedOption = useMemo(
() => providerOptions.find((option) => option.value === form.provider),
[form.provider],
);
const canCreate = form.label.trim() && form.model.trim() && form.apiKey.trim();
const { mutate: createProvider, isPending } = useMutation(orpc.aiProviders.create.mutationOptions());
return (
<div className="rounded-md border bg-card p-4">
<div className="mb-4 flex items-center gap-2">
<div className="grid size-8 place-items-center rounded-md bg-primary/10 text-primary">
<PlusIcon />
</div>
<h3 className="font-semibold">
<Trans>Add Provider</Trans>
</h3>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="ai-label">
<Trans>Label</Trans>
</Label>
<Input
id="ai-label"
value={form.label}
onChange={(event) => setForm((current) => ({ ...current, label: event.target.value }))}
placeholder={t`Work OpenAI`}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ai-provider">
<Trans>Provider</Trans>
</Label>
<Combobox
id="ai-provider"
value={form.provider}
showClear={false}
options={providerOptions}
onValueChange={(provider) => {
if (!provider) return;
setForm((current) => ({ ...current, provider }));
}}
/>
</div>
<div className="space-y-2">
<Label htmlFor="ai-model">
<Trans>Model</Trans>
</Label>
<Input
id="ai-model"
value={form.model}
onChange={(event) => setForm((current) => ({ ...current, model: event.target.value }))}
placeholder={t`gpt-4.1`}
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
/>
</div>
<div className="space-y-2">
<Label htmlFor="ai-base-url">
<Trans>Base URL</Trans>
</Label>
<Input
id="ai-base-url"
type="url"
value={form.baseURL}
onChange={(event) => setForm((current) => ({ ...current, baseURL: event.target.value }))}
placeholder={selectedOption?.defaultBaseURL || t`https://gateway.example.com/v1`}
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="ai-api-key">
<Trans>API Key</Trans>
</Label>
<Input
id="ai-api-key"
type="password"
value={form.apiKey}
onChange={(event) => setForm((current) => ({ ...current, apiKey: event.target.value }))}
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
data-lpignore="true"
data-bwignore="true"
data-1p-ignore="true"
/>
</div>
</div>
<div className="mt-4 flex justify-end">
<Button
disabled={!canCreate || isPending}
onClick={() =>
createProvider(
{
label: form.label.trim(),
provider: form.provider,
model: form.model.trim(),
baseURL: form.baseURL.trim(),
apiKey: form.apiKey.trim(),
},
{
onSuccess: () => {
setForm(emptyForm);
toast.success(t`AI provider saved. Test it before use.`);
void queryClient.invalidateQueries({ queryKey: orpc.aiProviders.list.queryKey() });
},
onError: (error) =>
toast.error(
getOrpcErrorMessage(error, {
byCode: {
PRECONDITION_FAILED: t`AI providers require REDIS_URL and ENCRYPTION_SECRET to be configured.`,
BAD_REQUEST: t`Invalid AI provider configuration.`,
},
fallback: t`Failed to save AI provider.`,
}),
),
},
)
}
>
{isPending ? <Spinner /> : <KeyIcon />}
<Trans>Save Provider</Trans>
</Button>
</div>
</div>
@@ -240,48 +357,71 @@ function AIForm() {
}
export function AISettingsSection() {
const aiEnabled = useAIStore((state) => state.enabled);
const canEnableAI = useAIStore((state) => state.canEnable());
const setAIEnabled = useAIStore((state) => state.setEnabled);
const { data: providers, isLoading, error } = useQuery(orpc.aiProviders.list.queryOptions());
const hasUsableProvider = providers?.some((provider) => provider.enabled && provider.testStatus === "success");
const isConfigError = isAiProviderConfigError(error);
return (
<section className="grid gap-6">
<h2 className="font-semibold text-lg">
<Trans>Artificial Intelligence</Trans>
</h2>
<div className="flex items-start gap-4 rounded-md border bg-popover p-6">
<div className="rounded-md bg-primary/10 p-2.5">
<InfoIcon className="text-primary" size={24} />
</div>
<div className="flex-1 space-y-2">
<h3 className="font-semibold">
<Trans>Your data is stored locally</Trans>
</h3>
<p className="text-muted-foreground leading-relaxed">
<Trans>
Everything entered here is stored locally on your browser. Your data is only sent to the server when
making a request to the AI provider, and is never stored or logged on our servers.
</Trans>
<div className="flex items-center justify-between gap-4">
<div>
<h2 className="font-semibold text-lg">
<Trans>AI Providers</Trans>
</h2>
<p className="text-muted-foreground text-sm">
<Trans>API keys are encrypted on the server and never shown again after saving.</Trans>
</p>
</div>
<p className="flex items-center gap-2 text-sm">
{hasUsableProvider ? (
<CheckCircleIcon className="text-emerald-600" />
) : (
<XCircleIcon className="text-rose-600" />
)}
<span className={cn(hasUsableProvider ? "text-emerald-700" : "text-muted-foreground")}>
{hasUsableProvider ? <Trans>Agent ready</Trans> : <Trans>No tested provider</Trans>}
</span>
</p>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="enable-ai">
<Trans>Enable AI Features</Trans>
</Label>
<Switch id="enable-ai" checked={aiEnabled} disabled={!canEnableAI} onCheckedChange={setAIEnabled} />
{error ? (
<div
className={cn(
"rounded-md border p-4 text-sm",
isConfigError
? "border-amber-300 bg-amber-50 text-amber-950 dark:bg-amber-950/20 dark:text-amber-200"
: "border-rose-300 bg-rose-50 text-rose-950 dark:bg-rose-950/20 dark:text-rose-200",
)}
>
{isConfigError ? (
<Trans>AI provider management is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.</Trans>
) : (
<Trans>AI provider management is unavailable. Please try again.</Trans>
)}
</div>
) : null}
{error ? null : <CreateProviderForm />}
<div className="grid gap-3">
{isLoading ? (
<div className="flex items-center gap-2 text-muted-foreground text-sm">
<Spinner />
<Trans>Loading providers...</Trans>
</div>
) : null}
{providers?.length === 0 ? (
<div className="rounded-md border border-dashed p-6 text-center text-muted-foreground text-sm">
<Trans>Add and test a provider before starting an agent thread.</Trans>
</div>
) : null}
{providers?.map((provider) => (
<ProviderRow key={provider.id} provider={provider} />
))}
</div>
<p className="flex items-center gap-x-2">
{aiEnabled ? <CheckCircleIcon className="text-emerald-500" /> : <XCircleIcon className="text-rose-500" />}
{aiEnabled ? <Trans>Enabled</Trans> : <Trans>Disabled</Trans>}
</p>
<AIForm />
</section>
);
}
@@ -26,7 +26,7 @@ function RouteComponent() {
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, ease: "easeOut" }}
className="grid max-w-xl gap-8 will-change-[transform,opacity]"
className="grid max-w-4xl gap-8 will-change-[transform,opacity]"
>
<AISettingsSection />
</motion.div>