mirror of
https://github.com/AmruthPillai/Reactive-Resume.git
synced 2026-07-23 00:13:36 +10:00
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:
+11
-9
@@ -16,7 +16,7 @@
|
||||
"lingui:extract": "lingui extract --clean --overwrite"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/react": "^3.0.182",
|
||||
"@ai-sdk/react": "^3.0.184",
|
||||
"@base-ui/react": "^1.4.1",
|
||||
"@better-auth/api-key": "^1.6.11",
|
||||
"@better-auth/infra": "^0.2.8",
|
||||
@@ -54,17 +54,18 @@
|
||||
"@tanstack/react-router": "^1.169.2",
|
||||
"@tanstack/react-router-ssr-query": "^1.166.12",
|
||||
"@tanstack/react-start": "^1.167.65",
|
||||
"@tiptap/extension-color": "^3.23.2",
|
||||
"@tiptap/extension-highlight": "^3.23.2",
|
||||
"@tiptap/extension-table": "^3.23.2",
|
||||
"@tiptap/extension-text-align": "^3.23.2",
|
||||
"@tiptap/extension-text-style": "^3.23.2",
|
||||
"@tiptap/pm": "^3.23.2",
|
||||
"@tiptap/react": "^3.23.2",
|
||||
"@tiptap/starter-kit": "^3.23.2",
|
||||
"@tiptap/extension-color": "^3.23.4",
|
||||
"@tiptap/extension-highlight": "^3.23.4",
|
||||
"@tiptap/extension-table": "^3.23.4",
|
||||
"@tiptap/extension-text-align": "^3.23.4",
|
||||
"@tiptap/extension-text-style": "^3.23.4",
|
||||
"@tiptap/pm": "^3.23.4",
|
||||
"@tiptap/react": "^3.23.4",
|
||||
"@tiptap/starter-kit": "^3.23.4",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@uiw/color-convert": "^2.10.1",
|
||||
"@uiw/react-color-colorful": "^2.10.1",
|
||||
"ai": "^6.0.182",
|
||||
"better-auth": "1.6.11",
|
||||
"cmdk": "^1.1.1",
|
||||
"drizzle-orm": "1.0.0-rc.2",
|
||||
@@ -78,6 +79,7 @@
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^4.11.1",
|
||||
"react-window": "^2.2.7",
|
||||
"react-zoom-pan-pinch": "^4.0.3",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import {
|
||||
ChatCircleDotsIcon,
|
||||
GearIcon,
|
||||
HouseSimpleIcon,
|
||||
KeyIcon,
|
||||
@@ -44,6 +45,16 @@ export function NavigationCommandGroup() {
|
||||
<Trans>Resumes</Trans>
|
||||
</CommandItem>
|
||||
|
||||
<CommandItem
|
||||
disabled={!session}
|
||||
keywords={[t`Agent`, t`Artificial Intelligence`]}
|
||||
value="navigation.agent"
|
||||
onSelect={() => onNavigate("/agent")}
|
||||
>
|
||||
<ChatCircleDotsIcon />
|
||||
<Trans>Agent</Trans>
|
||||
</CommandItem>
|
||||
|
||||
<CommandItem
|
||||
disabled={!session}
|
||||
keywords={[t`Settings`]}
|
||||
|
||||
@@ -280,20 +280,6 @@ export function usePatchResume() {
|
||||
return useResumeStore((state) => state.patchResume);
|
||||
}
|
||||
|
||||
export function useReplaceResumeFromServer() {
|
||||
const queryClient = useQueryClient();
|
||||
const replaceResumeFromServer = useResumeStore((state) => state.replaceResumeFromServer);
|
||||
|
||||
return useCallback(
|
||||
(resume: Resume) => {
|
||||
bindRuntimeQueryClient(resume.id, queryClient);
|
||||
queryClient.setQueryData(getResumeQueryKey(resume.id), resume);
|
||||
replaceResumeFromServer(resume);
|
||||
},
|
||||
[queryClient, replaceResumeFromServer],
|
||||
);
|
||||
}
|
||||
|
||||
function useBuilderResumeSelector<T>(selector: (resume: Resume) => T): T | undefined {
|
||||
const params = useParams({ strict: false }) as { resumeId?: string };
|
||||
const resumeId = params.resumeId;
|
||||
|
||||
@@ -93,20 +93,14 @@ describe("ResumePreviewClient", () => {
|
||||
previewMock.builderResumeData = resumeDataWithPageCount(3);
|
||||
previewMock.toBlob.mockImplementation(() => new Promise<Blob>(() => {}));
|
||||
|
||||
render(<ResumePreviewClient pageGap="1rem" pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />);
|
||||
render(<ResumePreviewClient pageGap={16} pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />);
|
||||
|
||||
expect(screen.getAllByRole("img", { name: /Loading resume page/ })).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("renders from explicit resume data when no builder resume is active", async () => {
|
||||
render(
|
||||
<ResumePreviewClient
|
||||
data={sampleResumeData}
|
||||
pageGap="1rem"
|
||||
pageLayout="vertical"
|
||||
pageScale={1.25}
|
||||
showPageNumbers={false}
|
||||
/>,
|
||||
<ResumePreviewClient data={sampleResumeData} pageLayout="vertical" pageScale={1.25} showPageNumbers={false} />,
|
||||
);
|
||||
|
||||
expect(await screen.findByRole("img", { name: "Resume page 1 of 1" })).toBeTruthy();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import type { PreviewPageSize, ResolvedResumePreviewProps } from "./preview.shared";
|
||||
import { pdf } from "@react-pdf/renderer";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
@@ -6,7 +7,7 @@ import { cn } from "@reactive-resume/utils/style";
|
||||
import { useLocalizedResumeDocument } from "@/libs/resume/pdf-document";
|
||||
import { useResumeData } from "./builder-resume-draft";
|
||||
import { PdfCanvasDocument, PdfCanvasPage } from "./pdf-canvas";
|
||||
import { getResumePreviewPageCount, ResumePreviewLoader } from "./preview.shared";
|
||||
import { getResumePreviewGapValue, getResumePreviewPageCount, ResumePreviewLoader } from "./preview.shared";
|
||||
|
||||
type PreviewPdf = {
|
||||
file: Blob;
|
||||
@@ -84,7 +85,7 @@ const removePreviewLayer = (layers: PreviewPdf[], layerId: number) => layers.fil
|
||||
export function ResumePreviewClient({
|
||||
className,
|
||||
data,
|
||||
pageGap,
|
||||
pageGap = 16,
|
||||
pageLayout,
|
||||
pageScale,
|
||||
pageClassName,
|
||||
@@ -133,6 +134,7 @@ export function ResumePreviewClient({
|
||||
if (!resumeData) return null;
|
||||
|
||||
const visiblePdf = getActivePreviewLayer(previewLayers);
|
||||
const resolvedPageGap = getResumePreviewGapValue(pageGap);
|
||||
|
||||
if (!visiblePdf) {
|
||||
return (
|
||||
@@ -154,8 +156,8 @@ export function ResumePreviewClient({
|
||||
<motion.div
|
||||
key={visiblePdf.id}
|
||||
aria-hidden={visiblePdf.phase !== "active"}
|
||||
style={{ "--resume-preview-page-gap": resolvedPageGap } as CSSProperties}
|
||||
className={cn("col-start-1 row-start-1", visiblePdf.phase !== "active" && "pointer-events-none")}
|
||||
style={{ "--resume-preview-page-gap": pageGap } as React.CSSProperties}
|
||||
initial={{ opacity: visiblePdf.phase === "active" ? 1 : 0 }}
|
||||
animate={{ opacity: visiblePdf.phase === "active" ? 1 : 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_PDF_PAGE_SIZE,
|
||||
getPreviewCanvasScale,
|
||||
getResumePreviewGapValue,
|
||||
getScaledPreviewPageSize,
|
||||
normalizeResumePreviewProps,
|
||||
} from "./preview.shared";
|
||||
@@ -12,7 +13,7 @@ describe("normalizeResumePreviewProps", () => {
|
||||
it("applies the documented defaults when fields are omitted", () => {
|
||||
const result = normalizeResumePreviewProps({});
|
||||
expect(result).toMatchObject({
|
||||
pageGap: 40,
|
||||
pageGap: 16,
|
||||
pageLayout: "horizontal",
|
||||
pageScale: 1,
|
||||
showPageNumbers: false,
|
||||
@@ -52,6 +53,20 @@ describe("getScaledPreviewPageSize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getResumePreviewGapValue", () => {
|
||||
it("adds px units for numeric custom-property gap values", () => {
|
||||
expect(getResumePreviewGapValue(96)).toBe("96px");
|
||||
});
|
||||
|
||||
it("preserves explicit zero gap", () => {
|
||||
expect(getResumePreviewGapValue(0)).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves string gap values", () => {
|
||||
expect(getResumePreviewGapValue("1rem")).toBe("1rem");
|
||||
});
|
||||
});
|
||||
|
||||
const setDevicePixelRatio = (value: number) => {
|
||||
Object.defineProperty(window, "devicePixelRatio", {
|
||||
writable: true,
|
||||
|
||||
@@ -29,6 +29,14 @@ describe("ResumePreviewLoader", () => {
|
||||
|
||||
expect(screen.getAllByRole("img", { name: /Loading resume page/ })).toHaveLength(pageCount);
|
||||
});
|
||||
|
||||
it("writes numeric page gaps as valid CSS custom-property lengths", () => {
|
||||
const { container } = render(<ResumePreviewLoader pageGap={96} />);
|
||||
|
||||
expect((container.firstElementChild as HTMLElement).style.getPropertyValue("--resume-preview-page-gap")).toBe(
|
||||
"96px",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getResumePreviewPageCount", () => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ResumeData } from "@reactive-resume/schema/resume/data";
|
||||
import type { CSSProperties } from "react";
|
||||
import { Spinner } from "@reactive-resume/ui/components/spinner";
|
||||
import { cn } from "@reactive-resume/utils/style";
|
||||
|
||||
export type ResumePreviewProps = {
|
||||
className?: string;
|
||||
data?: ResumeData;
|
||||
pageGap?: React.CSSProperties["gap"];
|
||||
pageGap?: CSSProperties["gap"];
|
||||
pageLayout?: "horizontal" | "vertical";
|
||||
pageScale?: number;
|
||||
pageClassName?: string;
|
||||
@@ -13,7 +14,6 @@ export type ResumePreviewProps = {
|
||||
};
|
||||
|
||||
export type ResolvedResumePreviewProps = ResumePreviewProps & {
|
||||
pageGap: React.CSSProperties["gap"];
|
||||
pageLayout: "horizontal" | "vertical";
|
||||
pageScale: number;
|
||||
showPageNumbers: boolean;
|
||||
@@ -26,7 +26,7 @@ export type PreviewPageSize = {
|
||||
|
||||
type ResumePreviewLoaderProps = Pick<ResumePreviewProps, "pageClassName" | "showPageNumbers"> & {
|
||||
pageCount?: number;
|
||||
pageGap?: React.CSSProperties["gap"];
|
||||
pageGap?: CSSProperties["gap"];
|
||||
pageLayout?: "horizontal" | "vertical";
|
||||
pageScale?: number;
|
||||
};
|
||||
@@ -39,7 +39,7 @@ export const DEFAULT_PDF_PAGE_SIZE: PreviewPageSize = {
|
||||
};
|
||||
|
||||
export const normalizeResumePreviewProps = ({
|
||||
pageGap = 40,
|
||||
pageGap = 16,
|
||||
pageLayout = "horizontal",
|
||||
pageScale = 1,
|
||||
showPageNumbers = false,
|
||||
@@ -67,25 +67,29 @@ export const getScaledPreviewPageSize = (pageSize: PreviewPageSize, pageScale: n
|
||||
width: pageSize.width * pageScale,
|
||||
});
|
||||
|
||||
export const getResumePreviewGapValue = (pageGap: CSSProperties["gap"]) =>
|
||||
typeof pageGap === "number" && pageGap !== 0 ? `${pageGap}px` : pageGap;
|
||||
|
||||
export const getResumePreviewPageCount = (data?: ResumeData) => Math.max(1, data?.metadata.layout.pages.length ?? 1);
|
||||
|
||||
export function ResumePreviewLoader({
|
||||
pageCount = 1,
|
||||
pageClassName,
|
||||
pageGap = 40,
|
||||
pageGap = 16,
|
||||
pageLayout = "horizontal",
|
||||
pageScale = 1,
|
||||
showPageNumbers = false,
|
||||
}: ResumePreviewLoaderProps) {
|
||||
const pageSize = getScaledPreviewPageSize(DEFAULT_PDF_PAGE_SIZE, pageScale);
|
||||
const resolvedPageGap = getResumePreviewGapValue(pageGap);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{ "--resume-preview-page-gap": resolvedPageGap } as CSSProperties}
|
||||
className={cn(
|
||||
"flex justify-start gap-(--resume-preview-page-gap)",
|
||||
pageLayout === "horizontal" ? "flex-row items-start" : "flex-col items-center",
|
||||
)}
|
||||
style={{ "--resume-preview-page-gap": pageGap } as React.CSSProperties}
|
||||
>
|
||||
{Array.from({ length: pageCount }, (_, index) => {
|
||||
const pageNumber = index + 1;
|
||||
|
||||
@@ -4,12 +4,11 @@ import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { DownloadSimpleIcon, FileIcon, UploadSimpleIcon } from "@phosphor-icons/react";
|
||||
import { useStore } from "@tanstack/react-form";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import z from "zod";
|
||||
import { useAIStore } from "@reactive-resume/ai/store";
|
||||
import { JSONResumeImporter } from "@reactive-resume/import/json-resume";
|
||||
import { ReactiveResumeJSONImporter } from "@reactive-resume/import/reactive-resume-json";
|
||||
import { ReactiveResumeV4JSONImporter } from "@reactive-resume/import/reactive-resume-v4-json";
|
||||
@@ -91,7 +90,6 @@ function fileToBase64(file: File): Promise<string> {
|
||||
|
||||
export function ImportResumeDialog(_: DialogProps<"resume.import">) {
|
||||
const navigate = useNavigate();
|
||||
const { enabled: isAIEnabled, provider, model, apiKey, baseURL } = useAIStore();
|
||||
const closeDialog = useDialogStore((state) => state.closeDialog);
|
||||
|
||||
const prevTypeRef = useRef<string>("");
|
||||
@@ -99,6 +97,8 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
|
||||
const { mutateAsync: importResume } = useMutation(orpc.resume.import.mutationOptions());
|
||||
const { data: aiProviders, isLoading: isLoadingAiProviders } = useQuery(orpc.aiProviders.list.queryOptions());
|
||||
const hasAIProvider = aiProviders?.some((provider) => provider.enabled && provider.testStatus === "success") ?? false;
|
||||
|
||||
const form = useAppForm({
|
||||
defaultValues: {
|
||||
@@ -137,23 +137,21 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {
|
||||
}
|
||||
|
||||
if (value.type === "pdf") {
|
||||
if (!isAIEnabled)
|
||||
throw new Error(t`This feature requires AI Integration to be enabled. Please enable it in the settings.`);
|
||||
if (isLoadingAiProviders) throw new Error(t`Loading AI providers. Please try again in a moment.`);
|
||||
if (!hasAIProvider)
|
||||
throw new Error(t`This feature requires a tested AI provider. Please add one in the settings.`);
|
||||
|
||||
const base64 = await fileToBase64(value.file);
|
||||
|
||||
data = await client.ai.parsePdf({
|
||||
provider,
|
||||
model,
|
||||
apiKey,
|
||||
baseURL,
|
||||
file: { name: value.file.name, data: base64 },
|
||||
});
|
||||
}
|
||||
|
||||
if (value.type === "docx") {
|
||||
if (!isAIEnabled)
|
||||
throw new Error(t`This feature requires AI Integration to be enabled. Please enable it in the settings.`);
|
||||
if (isLoadingAiProviders) throw new Error(t`Loading AI providers. Please try again in a moment.`);
|
||||
if (!hasAIProvider)
|
||||
throw new Error(t`This feature requires a tested AI provider. Please add one in the settings.`);
|
||||
|
||||
const base64 = await fileToBase64(value.file);
|
||||
|
||||
@@ -163,10 +161,6 @@ export function ImportResumeDialog(_: DialogProps<"resume.import">) {
|
||||
: ("application/vnd.openxmlformats-officedocument.wordprocessingml.document" as const);
|
||||
|
||||
data = await client.ai.parseDocx({
|
||||
provider,
|
||||
model,
|
||||
apiKey,
|
||||
baseURL,
|
||||
mediaType,
|
||||
file: { name: value.file.name, data: base64 },
|
||||
});
|
||||
|
||||
@@ -12,10 +12,12 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SchemaDotjsonRouteImport } from './routes/schema[.]json'
|
||||
import { Route as DashboardRouteRouteImport } from './routes/dashboard/route'
|
||||
import { Route as AuthRouteRouteImport } from './routes/auth/route'
|
||||
import { Route as AgentRouteRouteImport } from './routes/agent/route'
|
||||
import { Route as HomeRouteRouteImport } from './routes/_home/route'
|
||||
import { Route as McpIndexRouteImport } from './routes/mcp/index'
|
||||
import { Route as DashboardIndexRouteImport } from './routes/dashboard/index'
|
||||
import { Route as AuthIndexRouteImport } from './routes/auth/index'
|
||||
import { Route as AgentIndexRouteImport } from './routes/agent/index'
|
||||
import { Route as HomeIndexRouteImport } from './routes/_home/index'
|
||||
import { Route as TemplatesSplatRouteImport } from './routes/templates/$'
|
||||
import { Route as AuthVerify2faBackupRouteImport } from './routes/auth/verify-2fa-backup'
|
||||
@@ -27,6 +29,8 @@ import { Route as AuthOauthRouteImport } from './routes/auth/oauth'
|
||||
import { Route as AuthLoginRouteImport } from './routes/auth/login'
|
||||
import { Route as AuthForgotPasswordRouteImport } from './routes/auth/forgot-password'
|
||||
import { Route as ApiHealthRouteImport } from './routes/api/health'
|
||||
import { Route as AgentNewRouteImport } from './routes/agent/new'
|
||||
import { Route as AgentThreadIdRouteImport } from './routes/agent/$threadId'
|
||||
import { Route as DotwellKnownOpenidConfigurationRouteImport } from './routes/[.]well-known/openid-configuration'
|
||||
import { Route as DotwellKnownOauthProtectedResourceRouteImport } from './routes/[.]well-known/oauth-protected-resource'
|
||||
import { Route as DotwellKnownOauthAuthorizationServerRouteImport } from './routes/[.]well-known/oauth-authorization-server'
|
||||
@@ -66,6 +70,11 @@ const AuthRouteRoute = AuthRouteRouteImport.update({
|
||||
path: '/auth',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AgentRouteRoute = AgentRouteRouteImport.update({
|
||||
id: '/agent',
|
||||
path: '/agent',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const HomeRouteRoute = HomeRouteRouteImport.update({
|
||||
id: '/_home',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
@@ -85,6 +94,11 @@ const AuthIndexRoute = AuthIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => AuthRouteRoute,
|
||||
} as any)
|
||||
const AgentIndexRoute = AgentIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => AgentRouteRoute,
|
||||
} as any)
|
||||
const HomeIndexRoute = HomeIndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
@@ -140,6 +154,16 @@ const ApiHealthRoute = ApiHealthRouteImport.update({
|
||||
path: '/api/health',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AgentNewRoute = AgentNewRouteImport.update({
|
||||
id: '/new',
|
||||
path: '/new',
|
||||
getParentRoute: () => AgentRouteRoute,
|
||||
} as any)
|
||||
const AgentThreadIdRoute = AgentThreadIdRouteImport.update({
|
||||
id: '/$threadId',
|
||||
path: '/$threadId',
|
||||
getParentRoute: () => AgentRouteRoute,
|
||||
} as any)
|
||||
const DotwellKnownOpenidConfigurationRoute =
|
||||
DotwellKnownOpenidConfigurationRouteImport.update({
|
||||
id: '/.well-known/openid-configuration',
|
||||
@@ -271,6 +295,7 @@ const ApiUploadsUserIdSplatRoute = ApiUploadsUserIdSplatRouteImport.update({
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof HomeIndexRoute
|
||||
'/agent': typeof AgentRouteRouteWithChildren
|
||||
'/auth': typeof AuthRouteRouteWithChildren
|
||||
'/dashboard': typeof DashboardRouteRouteWithChildren
|
||||
'/schema.json': typeof SchemaDotjsonRoute
|
||||
@@ -280,6 +305,8 @@ export interface FileRoutesByFullPath {
|
||||
'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren
|
||||
'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren
|
||||
'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute
|
||||
'/agent/$threadId': typeof AgentThreadIdRoute
|
||||
'/agent/new': typeof AgentNewRoute
|
||||
'/api/health': typeof ApiHealthRoute
|
||||
'/auth/forgot-password': typeof AuthForgotPasswordRoute
|
||||
'/auth/login': typeof AuthLoginRoute
|
||||
@@ -290,6 +317,7 @@ export interface FileRoutesByFullPath {
|
||||
'/auth/verify-2fa': typeof AuthVerify2faRoute
|
||||
'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute
|
||||
'/templates/$': typeof TemplatesSplatRoute
|
||||
'/agent/': typeof AgentIndexRoute
|
||||
'/auth/': typeof AuthIndexRoute
|
||||
'/dashboard/': typeof DashboardIndexRoute
|
||||
'/mcp/': typeof McpIndexRoute
|
||||
@@ -318,6 +346,8 @@ export interface FileRoutesByTo {
|
||||
'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren
|
||||
'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren
|
||||
'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute
|
||||
'/agent/$threadId': typeof AgentThreadIdRoute
|
||||
'/agent/new': typeof AgentNewRoute
|
||||
'/api/health': typeof ApiHealthRoute
|
||||
'/auth/forgot-password': typeof AuthForgotPasswordRoute
|
||||
'/auth/login': typeof AuthLoginRoute
|
||||
@@ -329,6 +359,7 @@ export interface FileRoutesByTo {
|
||||
'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute
|
||||
'/templates/$': typeof TemplatesSplatRoute
|
||||
'/': typeof HomeIndexRoute
|
||||
'/agent': typeof AgentIndexRoute
|
||||
'/auth': typeof AuthIndexRoute
|
||||
'/dashboard': typeof DashboardIndexRoute
|
||||
'/mcp': typeof McpIndexRoute
|
||||
@@ -353,6 +384,7 @@ export interface FileRoutesByTo {
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_home': typeof HomeRouteRouteWithChildren
|
||||
'/agent': typeof AgentRouteRouteWithChildren
|
||||
'/auth': typeof AuthRouteRouteWithChildren
|
||||
'/dashboard': typeof DashboardRouteRouteWithChildren
|
||||
'/schema.json': typeof SchemaDotjsonRoute
|
||||
@@ -362,6 +394,8 @@ export interface FileRoutesById {
|
||||
'/.well-known/oauth-authorization-server': typeof DotwellKnownOauthAuthorizationServerRouteWithChildren
|
||||
'/.well-known/oauth-protected-resource': typeof DotwellKnownOauthProtectedResourceRouteWithChildren
|
||||
'/.well-known/openid-configuration': typeof DotwellKnownOpenidConfigurationRoute
|
||||
'/agent/$threadId': typeof AgentThreadIdRoute
|
||||
'/agent/new': typeof AgentNewRoute
|
||||
'/api/health': typeof ApiHealthRoute
|
||||
'/auth/forgot-password': typeof AuthForgotPasswordRoute
|
||||
'/auth/login': typeof AuthLoginRoute
|
||||
@@ -373,6 +407,7 @@ export interface FileRoutesById {
|
||||
'/auth/verify-2fa-backup': typeof AuthVerify2faBackupRoute
|
||||
'/templates/$': typeof TemplatesSplatRoute
|
||||
'/_home/': typeof HomeIndexRoute
|
||||
'/agent/': typeof AgentIndexRoute
|
||||
'/auth/': typeof AuthIndexRoute
|
||||
'/dashboard/': typeof DashboardIndexRoute
|
||||
'/mcp/': typeof McpIndexRoute
|
||||
@@ -398,6 +433,7 @@ export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/agent'
|
||||
| '/auth'
|
||||
| '/dashboard'
|
||||
| '/schema.json'
|
||||
@@ -407,6 +443,8 @@ export interface FileRouteTypes {
|
||||
| '/.well-known/oauth-authorization-server'
|
||||
| '/.well-known/oauth-protected-resource'
|
||||
| '/.well-known/openid-configuration'
|
||||
| '/agent/$threadId'
|
||||
| '/agent/new'
|
||||
| '/api/health'
|
||||
| '/auth/forgot-password'
|
||||
| '/auth/login'
|
||||
@@ -417,6 +455,7 @@ export interface FileRouteTypes {
|
||||
| '/auth/verify-2fa'
|
||||
| '/auth/verify-2fa-backup'
|
||||
| '/templates/$'
|
||||
| '/agent/'
|
||||
| '/auth/'
|
||||
| '/dashboard/'
|
||||
| '/mcp/'
|
||||
@@ -445,6 +484,8 @@ export interface FileRouteTypes {
|
||||
| '/.well-known/oauth-authorization-server'
|
||||
| '/.well-known/oauth-protected-resource'
|
||||
| '/.well-known/openid-configuration'
|
||||
| '/agent/$threadId'
|
||||
| '/agent/new'
|
||||
| '/api/health'
|
||||
| '/auth/forgot-password'
|
||||
| '/auth/login'
|
||||
@@ -456,6 +497,7 @@ export interface FileRouteTypes {
|
||||
| '/auth/verify-2fa-backup'
|
||||
| '/templates/$'
|
||||
| '/'
|
||||
| '/agent'
|
||||
| '/auth'
|
||||
| '/dashboard'
|
||||
| '/mcp'
|
||||
@@ -479,6 +521,7 @@ export interface FileRouteTypes {
|
||||
id:
|
||||
| '__root__'
|
||||
| '/_home'
|
||||
| '/agent'
|
||||
| '/auth'
|
||||
| '/dashboard'
|
||||
| '/schema.json'
|
||||
@@ -488,6 +531,8 @@ export interface FileRouteTypes {
|
||||
| '/.well-known/oauth-authorization-server'
|
||||
| '/.well-known/oauth-protected-resource'
|
||||
| '/.well-known/openid-configuration'
|
||||
| '/agent/$threadId'
|
||||
| '/agent/new'
|
||||
| '/api/health'
|
||||
| '/auth/forgot-password'
|
||||
| '/auth/login'
|
||||
@@ -499,6 +544,7 @@ export interface FileRouteTypes {
|
||||
| '/auth/verify-2fa-backup'
|
||||
| '/templates/$'
|
||||
| '/_home/'
|
||||
| '/agent/'
|
||||
| '/auth/'
|
||||
| '/dashboard/'
|
||||
| '/mcp/'
|
||||
@@ -523,6 +569,7 @@ export interface FileRouteTypes {
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
HomeRouteRoute: typeof HomeRouteRouteWithChildren
|
||||
AgentRouteRoute: typeof AgentRouteRouteWithChildren
|
||||
AuthRouteRoute: typeof AuthRouteRouteWithChildren
|
||||
DashboardRouteRoute: typeof DashboardRouteRouteWithChildren
|
||||
SchemaDotjsonRoute: typeof SchemaDotjsonRoute
|
||||
@@ -566,6 +613,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthRouteRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/agent': {
|
||||
id: '/agent'
|
||||
path: '/agent'
|
||||
fullPath: '/agent'
|
||||
preLoaderRoute: typeof AgentRouteRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_home': {
|
||||
id: '/_home'
|
||||
path: ''
|
||||
@@ -594,6 +648,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthIndexRouteImport
|
||||
parentRoute: typeof AuthRouteRoute
|
||||
}
|
||||
'/agent/': {
|
||||
id: '/agent/'
|
||||
path: '/'
|
||||
fullPath: '/agent/'
|
||||
preLoaderRoute: typeof AgentIndexRouteImport
|
||||
parentRoute: typeof AgentRouteRoute
|
||||
}
|
||||
'/_home/': {
|
||||
id: '/_home/'
|
||||
path: '/'
|
||||
@@ -671,6 +732,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ApiHealthRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/agent/new': {
|
||||
id: '/agent/new'
|
||||
path: '/new'
|
||||
fullPath: '/agent/new'
|
||||
preLoaderRoute: typeof AgentNewRouteImport
|
||||
parentRoute: typeof AgentRouteRoute
|
||||
}
|
||||
'/agent/$threadId': {
|
||||
id: '/agent/$threadId'
|
||||
path: '/$threadId'
|
||||
fullPath: '/agent/$threadId'
|
||||
preLoaderRoute: typeof AgentThreadIdRouteImport
|
||||
parentRoute: typeof AgentRouteRoute
|
||||
}
|
||||
'/.well-known/openid-configuration': {
|
||||
id: '/.well-known/openid-configuration'
|
||||
path: '/.well-known/openid-configuration'
|
||||
@@ -847,6 +922,22 @@ const HomeRouteRouteWithChildren = HomeRouteRoute._addFileChildren(
|
||||
HomeRouteRouteChildren,
|
||||
)
|
||||
|
||||
interface AgentRouteRouteChildren {
|
||||
AgentThreadIdRoute: typeof AgentThreadIdRoute
|
||||
AgentNewRoute: typeof AgentNewRoute
|
||||
AgentIndexRoute: typeof AgentIndexRoute
|
||||
}
|
||||
|
||||
const AgentRouteRouteChildren: AgentRouteRouteChildren = {
|
||||
AgentThreadIdRoute: AgentThreadIdRoute,
|
||||
AgentNewRoute: AgentNewRoute,
|
||||
AgentIndexRoute: AgentIndexRoute,
|
||||
}
|
||||
|
||||
const AgentRouteRouteWithChildren = AgentRouteRoute._addFileChildren(
|
||||
AgentRouteRouteChildren,
|
||||
)
|
||||
|
||||
interface AuthRouteRouteChildren {
|
||||
AuthForgotPasswordRoute: typeof AuthForgotPasswordRoute
|
||||
AuthLoginRoute: typeof AuthLoginRoute
|
||||
@@ -948,6 +1039,7 @@ const DotwellKnownOauthProtectedResourceRouteWithChildren =
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
HomeRouteRoute: HomeRouteRouteWithChildren,
|
||||
AgentRouteRoute: AgentRouteRouteWithChildren,
|
||||
AuthRouteRoute: AuthRouteRouteWithChildren,
|
||||
DashboardRouteRoute: DashboardRouteRouteWithChildren,
|
||||
SchemaDotjsonRoute: SchemaDotjsonRoute,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
attachmentIdsFromTransportBody,
|
||||
attachmentToFilePart,
|
||||
buildAgentChatSubmission,
|
||||
} from "./-helpers/chat-attachments";
|
||||
|
||||
describe("agent chat attachment helpers", () => {
|
||||
it("builds safe UI file parts without embedding file bytes", () => {
|
||||
expect(attachmentToFilePart({ id: "attachment-1", filename: "resume.pdf", mediaType: "application/pdf" })).toEqual({
|
||||
type: "file",
|
||||
url: "agent-attachment:attachment-1",
|
||||
mediaType: "application/pdf",
|
||||
filename: "resume.pdf",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts only string attachment IDs from transport body metadata", () => {
|
||||
expect(attachmentIdsFromTransportBody({ attachmentIds: ["a", 1, "b", null] })).toEqual(["a", "b"]);
|
||||
expect(attachmentIdsFromTransportBody({ attachmentIds: "a" })).toBeUndefined();
|
||||
expect(attachmentIdsFromTransportBody(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps attachment IDs in transport metadata while sending file parts in the UI message", () => {
|
||||
const submission = buildAgentChatSubmission(" Tailor this ", [
|
||||
{ id: "attachment-1", filename: "job.txt", mediaType: "text/plain" },
|
||||
{ id: "attachment-2", filename: "portfolio.png", mediaType: "image/png" },
|
||||
]);
|
||||
|
||||
expect(submission).toEqual({
|
||||
message: {
|
||||
text: "Tailor this",
|
||||
files: [
|
||||
{
|
||||
type: "file",
|
||||
url: "agent-attachment:attachment-1",
|
||||
mediaType: "text/plain",
|
||||
filename: "job.txt",
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
url: "agent-attachment:attachment-2",
|
||||
mediaType: "image/png",
|
||||
filename: "portfolio.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
options: { body: { attachmentIds: ["attachment-1", "attachment-2"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("supports attachment-only submissions", () => {
|
||||
const submission = buildAgentChatSubmission(" ", [
|
||||
{ id: "attachment-1", filename: "job.txt", mediaType: "text/plain" },
|
||||
]);
|
||||
|
||||
expect(submission.message).toEqual({
|
||||
files: [
|
||||
{
|
||||
type: "file",
|
||||
url: "agent-attachment:attachment-1",
|
||||
mediaType: "text/plain",
|
||||
filename: "job.txt",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(submission.options).toEqual({ body: { attachmentIds: ["attachment-1"] } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import type { AIProvider } from "@reactive-resume/ai/types";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { ArrowRightIcon, ChatCircleDotsIcon, FilePlusIcon, GearSixIcon } from "@phosphor-icons/react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useIsClient } from "usehooks-ts";
|
||||
import { Badge } from "@reactive-resume/ui/components/badge";
|
||||
import { Button } from "@reactive-resume/ui/components/button";
|
||||
import { Label } from "@reactive-resume/ui/components/label";
|
||||
import { Spinner } from "@reactive-resume/ui/components/spinner";
|
||||
import { Combobox } from "@/components/ui/combobox";
|
||||
import { getOrpcErrorMessage } from "@/libs/error-message";
|
||||
import { orpc } from "@/libs/orpc/client";
|
||||
|
||||
function providerLabel(provider: { label: string; provider: AIProvider; model: string }) {
|
||||
return `${provider.label} · ${provider.provider} · ${provider.model}`;
|
||||
}
|
||||
|
||||
function isAgentConfigError(error: unknown) {
|
||||
if (!error || typeof error !== "object") return false;
|
||||
const message = (error as { message?: unknown }).message;
|
||||
const status = (error as { status?: unknown; code?: unknown }).status ?? (error as { code?: unknown }).code;
|
||||
if (status === "PRECONDITION_FAILED" || status === 412) return true;
|
||||
return typeof message === "string" && /REDIS_URL|ENCRYPTION_SECRET/.test(message);
|
||||
}
|
||||
|
||||
export function NewThreadSetup({ resumeId }: { resumeId?: string }) {
|
||||
const isClient = useIsClient();
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
data: providers,
|
||||
isLoading: isLoadingProviders,
|
||||
error: providersError,
|
||||
} = useQuery(orpc.aiProviders.list.queryOptions());
|
||||
const { data: resumes, isLoading: isLoadingResumes } = useQuery(
|
||||
orpc.resume.list.queryOptions({ input: { sort: "lastUpdatedAt", tags: [] } }),
|
||||
);
|
||||
const { mutate: createThread, isPending } = useMutation(orpc.agent.threads.create.mutationOptions());
|
||||
|
||||
const usableProviders = useMemo(
|
||||
() => providers?.filter((provider) => provider.enabled && provider.testStatus === "success") ?? [],
|
||||
[providers],
|
||||
);
|
||||
const [aiProviderId, setAiProviderId] = useState<string | null>(null);
|
||||
const [sourceResumeId, setSourceResumeId] = useState<string | null>(resumeId ?? null);
|
||||
|
||||
useEffect(() => {
|
||||
if (aiProviderId || usableProviders.length === 0) return;
|
||||
setAiProviderId(usableProviders[0]?.id ?? null);
|
||||
}, [aiProviderId, usableProviders]);
|
||||
|
||||
useEffect(() => {
|
||||
setSourceResumeId(resumeId ?? null);
|
||||
}, [resumeId]);
|
||||
|
||||
const providerOptions = usableProviders.map((provider) => ({
|
||||
value: provider.id,
|
||||
label: providerLabel(provider),
|
||||
keywords: [provider.label, provider.provider, provider.model],
|
||||
}));
|
||||
|
||||
const resumeOptions = [
|
||||
{ value: "__scratch__", label: t`Create from scratch` },
|
||||
...(resumes?.map((resume) => ({
|
||||
value: resume.id,
|
||||
label: resume.name,
|
||||
keywords: [resume.name, resume.slug, ...resume.tags],
|
||||
})) ?? []),
|
||||
];
|
||||
|
||||
const selectedResumeValue = sourceResumeId ?? "__scratch__";
|
||||
const canCreate = !!aiProviderId && usableProviders.length > 0;
|
||||
|
||||
if (!isClient) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto grid w-full max-w-4xl gap-6 self-center p-4 lg:p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="grid size-12 shrink-0 place-items-center rounded-md border bg-card shadow-sm lg:size-14">
|
||||
<ChatCircleDotsIcon className="size-6 text-foreground" weight="fill" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="font-semibold text-3xl tracking-tight lg:text-4xl">
|
||||
<Trans>Start a thread</Trans>
|
||||
</h1>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
<Trans>Choose a model and resume draft.</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{providersError ? (
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 p-4 text-amber-950 text-sm dark:bg-amber-950/20 dark:text-amber-200">
|
||||
{isAgentConfigError(providersError) ? (
|
||||
<Trans>AI agent setup is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.</Trans>
|
||||
) : (
|
||||
<Trans>AI agent setup is unavailable right now. Please try again in a moment.</Trans>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="rounded-md border bg-card p-4 shadow-sm lg:p-6">
|
||||
<div className="grid gap-x-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="relative isolate min-h-32 overflow-hidden rounded-md p-1 lg:p-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-7 right-1 -z-10 select-none font-black text-8xl text-foreground/[0.045] leading-none lg:-top-10 lg:right-3 lg:text-[8rem]"
|
||||
>
|
||||
1
|
||||
</span>
|
||||
<div className="space-y-3">
|
||||
<Label>
|
||||
<Trans>Select an agent model</Trans>
|
||||
</Label>
|
||||
<Combobox
|
||||
value={aiProviderId}
|
||||
options={providerOptions}
|
||||
disabled={isLoadingProviders || providerOptions.length === 0}
|
||||
placeholder={isLoadingProviders ? t`Loading providers...` : t`Select a tested provider`}
|
||||
onValueChange={setAiProviderId}
|
||||
/>
|
||||
{providerOptions.length === 0 && !isLoadingProviders ? (
|
||||
<div className="flex flex-col gap-3 rounded-md border border-dashed p-3 text-sm lg:flex-row lg:items-center lg:justify-between">
|
||||
<span className="text-muted-foreground">
|
||||
<Trans>Add and test a provider before starting a thread.</Trans>
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
nativeButton={false}
|
||||
render={<Link to="/dashboard/settings/integrations" />}
|
||||
>
|
||||
<GearSixIcon />
|
||||
<Trans>Settings</Trans>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative isolate min-h-32 overflow-hidden rounded-md p-1 lg:p-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-7 right-1 -z-10 select-none font-black text-8xl text-foreground/[0.045] leading-none lg:-top-10 lg:right-3 lg:text-[8rem]"
|
||||
>
|
||||
2
|
||||
</span>
|
||||
<div className="space-y-3">
|
||||
<Label>
|
||||
<Trans>Select a resume</Trans>
|
||||
</Label>
|
||||
<Combobox
|
||||
value={selectedResumeValue}
|
||||
showClear={false}
|
||||
options={resumeOptions}
|
||||
disabled={isLoadingResumes}
|
||||
placeholder={isLoadingResumes ? t`Loading resumes...` : t`Choose a resume`}
|
||||
onValueChange={(value) => setSourceResumeId(value && value !== "__scratch__" ? value : null)}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-2 text-muted-foreground text-sm">
|
||||
<Badge variant="secondary" className="h-7 gap-1.5 rounded-md px-2">
|
||||
<FilePlusIcon />
|
||||
{sourceResumeId ? <Trans>Duplicate as AI Draft</Trans> : <Trans>Blank draft</Trans>}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex border-t pt-5 lg:justify-end">
|
||||
<Button
|
||||
size="lg"
|
||||
className="h-11 w-full gap-2 px-5 lg:w-auto"
|
||||
disabled={!canCreate || isPending}
|
||||
onClick={() =>
|
||||
createThread(
|
||||
{
|
||||
...(aiProviderId ? { aiProviderId } : {}),
|
||||
...(sourceResumeId ? { sourceResumeId } : {}),
|
||||
},
|
||||
{
|
||||
onSuccess: (thread) => {
|
||||
void navigate({ to: "/agent/$threadId", params: { threadId: thread.id } });
|
||||
},
|
||||
onError: (error) =>
|
||||
toast.error(
|
||||
getOrpcErrorMessage(error, {
|
||||
byCode: {
|
||||
PRECONDITION_FAILED: t`AI agent setup is unavailable until REDIS_URL and ENCRYPTION_SECRET are configured.`,
|
||||
BAD_REQUEST: t`Select a tested provider before starting a thread.`,
|
||||
},
|
||||
fallback: t`Failed to start agent thread.`,
|
||||
}),
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
<Trans>Start Thread</Trans>
|
||||
{isPending ? <Spinner /> : <ArrowRightIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import type { RouterOutput } from "@/libs/orpc/client";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { useLingui } from "@lingui/react";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
ChatCircleDotsIcon,
|
||||
DotsThreeVerticalIcon,
|
||||
PlusIcon,
|
||||
TrashIcon,
|
||||
} from "@phosphor-icons/react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@reactive-resume/ui/components/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@reactive-resume/ui/components/dropdown-menu";
|
||||
import { ScrollArea } from "@reactive-resume/ui/components/scroll-area";
|
||||
import { cn } from "@reactive-resume/utils/style";
|
||||
import { useConfirm } from "@/hooks/use-confirm";
|
||||
import { getOrpcErrorMessage } from "@/libs/error-message";
|
||||
import { orpc } from "@/libs/orpc/client";
|
||||
|
||||
type AgentThreadSummary = RouterOutput["agent"]["threads"]["list"][number];
|
||||
|
||||
function formatRelativeTime(value: Date | string, locale: string) {
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
const diffMs = date.getTime() - Date.now();
|
||||
const absMs = Math.abs(diffMs);
|
||||
const divisions: Array<{ amount: number; unit: Intl.RelativeTimeFormatUnit }> = [
|
||||
{ amount: 31_536_000_000, unit: "year" },
|
||||
{ amount: 2_592_000_000, unit: "month" },
|
||||
{ amount: 604_800_000, unit: "week" },
|
||||
{ amount: 86_400_000, unit: "day" },
|
||||
{ amount: 3_600_000, unit: "hour" },
|
||||
{ amount: 60_000, unit: "minute" },
|
||||
];
|
||||
|
||||
if (absMs < 60_000) return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(0, "second");
|
||||
|
||||
const division = divisions.find((candidate) => absMs >= candidate.amount);
|
||||
if (!division) return "";
|
||||
|
||||
return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(
|
||||
Math.round(diffMs / division.amount),
|
||||
division.unit,
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadActions({ thread, activeThreadId }: { thread: AgentThreadSummary; activeThreadId: string | null }) {
|
||||
const navigate = useNavigate();
|
||||
const confirm = useConfirm();
|
||||
const queryClient = useQueryClient();
|
||||
const archiveMutation = useMutation(orpc.agent.threads.archive.mutationOptions());
|
||||
const deleteMutation = useMutation(orpc.agent.threads.delete.mutationOptions());
|
||||
const isArchived = thread.status === "archived";
|
||||
|
||||
const handleArchive = () => {
|
||||
archiveMutation.mutate(
|
||||
{ id: thread.id },
|
||||
{
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() });
|
||||
if (activeThreadId === thread.id) {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: orpc.agent.threads.get.queryKey({ input: { id: thread.id } }),
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: (error) => toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to archive thread.` })),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
const confirmed = await confirm(t`Delete this agent thread?`, {
|
||||
description: t`This action cannot be undone. Messages and thread attachments will be removed.`,
|
||||
});
|
||||
|
||||
if (!confirmed) return;
|
||||
|
||||
deleteMutation.mutate(
|
||||
{ id: thread.id },
|
||||
{
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: orpc.agent.threads.list.queryKey() });
|
||||
if (activeThreadId === thread.id) void navigate({ to: "/agent" });
|
||||
},
|
||||
onError: (error) => toast.error(getOrpcErrorMessage(error, { fallback: t`Failed to delete thread.` })),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="absolute end-1.5 top-2 opacity-60 transition-opacity hover:opacity-100 focus-visible:opacity-100 group-hover/thread:opacity-100 aria-expanded:opacity-100"
|
||||
>
|
||||
<DotsThreeVerticalIcon />
|
||||
<span className="sr-only">
|
||||
<Trans>Thread actions</Trans>
|
||||
</span>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DropdownMenuContent align="end">
|
||||
{!isArchived ? (
|
||||
<DropdownMenuItem disabled={archiveMutation.isPending} onClick={handleArchive}>
|
||||
<ArchiveIcon />
|
||||
<Trans>Archive</Trans>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<DropdownMenuItem variant="destructive" disabled={deleteMutation.isPending} onClick={() => void handleDelete()}>
|
||||
<TrashIcon />
|
||||
<Trans>Delete</Trans>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadRow({ thread, activeThreadId }: { thread: AgentThreadSummary; activeThreadId: string | null }) {
|
||||
const { i18n } = useLingui();
|
||||
const isActive = thread.id === activeThreadId;
|
||||
const isArchived = thread.status === "archived";
|
||||
const title = thread.title === thread.resumeName ? t`New thread` : thread.title;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group/thread relative rounded-md transition-colors hover:bg-accent",
|
||||
isActive && "bg-accent",
|
||||
isArchived && "opacity-60",
|
||||
)}
|
||||
>
|
||||
<Link
|
||||
to="/agent/$threadId"
|
||||
params={{ threadId: thread.id }}
|
||||
className="block min-w-0 rounded-md px-3 py-2 pe-10 text-sm outline-hidden ring-ring focus-visible:ring-2"
|
||||
>
|
||||
<div className="truncate font-medium">{title}</div>
|
||||
<div className="truncate text-muted-foreground text-xs">
|
||||
{formatRelativeTime(thread.lastMessageAt, i18n.locale)}
|
||||
</div>
|
||||
</Link>
|
||||
<ThreadActions thread={thread} activeThreadId={activeThreadId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AgentThreadSidebar({
|
||||
activeThreadId = null,
|
||||
className,
|
||||
}: {
|
||||
activeThreadId?: string | null;
|
||||
className?: string;
|
||||
}) {
|
||||
const { data: threads, isLoading } = useQuery(orpc.agent.threads.list.queryOptions());
|
||||
|
||||
return (
|
||||
<aside className={cn("flex h-full min-h-0 flex-col border-e bg-muted/30", className)}>
|
||||
<div className="flex h-14 shrink-0 items-center justify-between gap-3 border-b px-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ChatCircleDotsIcon className="shrink-0" />
|
||||
<div className="min-w-0 truncate font-semibold">
|
||||
<Trans>Threads</Trans>
|
||||
</div>
|
||||
</div>
|
||||
<Button size="icon-sm" variant="ghost" nativeButton={false} render={<Link to="/dashboard/resumes" />}>
|
||||
<ArrowLeftIcon />
|
||||
<span className="sr-only">
|
||||
<Trans>Back to resumes</Trans>
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="space-y-1 p-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mb-2 w-full justify-start border border-dashed bg-background/40 text-muted-foreground hover:text-foreground"
|
||||
nativeButton={false}
|
||||
render={<Link to="/agent/new" />}
|
||||
>
|
||||
<PlusIcon />
|
||||
<Trans>New thread</Trans>
|
||||
</Button>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="px-3 py-2 text-muted-foreground text-sm">
|
||||
<Trans>Loading threads...</Trans>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{threads?.length === 0 ? (
|
||||
<div className="rounded-md border border-dashed p-3 text-muted-foreground text-sm">
|
||||
<Trans>No threads yet.</Trans>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{threads?.map((thread) => (
|
||||
<ThreadRow key={thread.id} thread={thread} activeThreadId={activeThreadId} />
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { FileUIPart } from "ai";
|
||||
|
||||
export type ChatAttachment = {
|
||||
id: string;
|
||||
filename: string;
|
||||
mediaType: string;
|
||||
};
|
||||
|
||||
export function attachmentToFilePart(attachment: ChatAttachment): FileUIPart {
|
||||
return {
|
||||
type: "file",
|
||||
url: `agent-attachment:${attachment.id}`,
|
||||
mediaType: attachment.mediaType,
|
||||
filename: attachment.filename,
|
||||
};
|
||||
}
|
||||
|
||||
export function attachmentIdsFromTransportBody(body: object | undefined) {
|
||||
return body && "attachmentIds" in body && Array.isArray(body.attachmentIds)
|
||||
? body.attachmentIds.filter((id): id is string => typeof id === "string")
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function buildAgentChatSubmission(text: string, pendingAttachments: ChatAttachment[]) {
|
||||
const trimmedText = text.trim();
|
||||
const files = pendingAttachments.map(attachmentToFilePart);
|
||||
const attachmentIds = pendingAttachments.map((attachment) => attachment.id);
|
||||
const options = { body: { attachmentIds } };
|
||||
|
||||
if (trimmedText) {
|
||||
return {
|
||||
message: files.length > 0 ? { text: trimmedText, files } : { text: trimmedText },
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
return { message: { files }, options };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { ArrowRightIcon, ChatCircleDotsIcon } from "@phosphor-icons/react";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { Button } from "@reactive-resume/ui/components/button";
|
||||
import { AgentThreadSidebar } from "./-components/thread-sidebar";
|
||||
|
||||
export const Route = createFileRoute("/agent/")({
|
||||
component: RouteComponent,
|
||||
});
|
||||
|
||||
function RouteComponent() {
|
||||
return (
|
||||
<div className="flex h-svh bg-background">
|
||||
<div className="w-72 shrink-0">
|
||||
<AgentThreadSidebar />
|
||||
</div>
|
||||
|
||||
<main className="grid min-w-0 flex-1 place-items-center p-6">
|
||||
<div className="w-full max-w-xl rounded-md border bg-card p-6 shadow-sm">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="grid size-11 shrink-0 place-items-center rounded-md border bg-background">
|
||||
<ChatCircleDotsIcon className="size-5" weight="fill" />
|
||||
</div>
|
||||
<div className="min-w-0 space-y-2">
|
||||
<h1 className="font-semibold text-2xl tracking-tight">
|
||||
<Trans>Select a thread</Trans>
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
<Trans>Choose an existing conversation from the sidebar, or start a new draft-focused thread.</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end border-t pt-4">
|
||||
<Button nativeButton={false} render={<Link to="/agent/new" />}>
|
||||
<ArrowRightIcon />
|
||||
<Trans>Start new thread</Trans>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import z from "zod";
|
||||
import { NewThreadSetup } from "./-components/new-thread-setup";
|
||||
import { AgentThreadSidebar } from "./-components/thread-sidebar";
|
||||
|
||||
const searchSchema = z.object({ resumeId: z.string().optional() });
|
||||
|
||||
export const Route = createFileRoute("/agent/new")({
|
||||
component: RouteComponent,
|
||||
validateSearch: searchSchema,
|
||||
});
|
||||
|
||||
function RouteComponent() {
|
||||
const { resumeId } = Route.useSearch();
|
||||
|
||||
return (
|
||||
<div className="flex h-svh bg-background">
|
||||
<div className="w-72 shrink-0">
|
||||
<AgentThreadSidebar />
|
||||
</div>
|
||||
|
||||
<main className="grid min-w-0 flex-1 overflow-auto">
|
||||
<NewThreadSetup resumeId={resumeId} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
|
||||
|
||||
export const Route = createFileRoute("/agent")({
|
||||
component: RouteComponent,
|
||||
beforeLoad: async ({ context }) => {
|
||||
if (!context.session) throw redirect({ to: "/auth/login", replace: true });
|
||||
return { session: context.session };
|
||||
},
|
||||
});
|
||||
|
||||
function RouteComponent() {
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useBuilderAssistantStore } from "./assistant-store";
|
||||
|
||||
afterEach(() => useBuilderAssistantStore.setState({ isOpen: false }));
|
||||
|
||||
describe("useBuilderAssistantStore", () => {
|
||||
it("starts closed", () => {
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("setOpen overrides the open state directly", () => {
|
||||
useBuilderAssistantStore.getState().setOpen(true);
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(true);
|
||||
|
||||
useBuilderAssistantStore.getState().setOpen(false);
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("toggleOpen flips the state", () => {
|
||||
const { toggleOpen } = useBuilderAssistantStore.getState();
|
||||
|
||||
toggleOpen();
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(true);
|
||||
|
||||
toggleOpen();
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import { create } from "zustand/react";
|
||||
|
||||
type BuilderAssistantStore = {
|
||||
isOpen: boolean;
|
||||
setOpen: (isOpen: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
};
|
||||
|
||||
export const useBuilderAssistantStore = create<BuilderAssistantStore>((set) => ({
|
||||
isOpen: false,
|
||||
setOpen: (isOpen) => set({ isOpen }),
|
||||
toggleOpen: () => set((state) => ({ isOpen: !state.isOpen })),
|
||||
}));
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ import {
|
||||
MagnifyingGlassMinusIcon,
|
||||
MagnifyingGlassPlusIcon,
|
||||
} from "@phosphor-icons/react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { motion } from "motion/react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useControls } from "react-zoom-pan-pinch";
|
||||
@@ -27,7 +28,6 @@ import { cn } from "@reactive-resume/utils/style";
|
||||
import { useCurrentResume } from "@/components/resume/builder-resume-draft";
|
||||
import { authClient } from "@/libs/auth/client";
|
||||
import { createResumePdfBlob } from "@/libs/resume/pdf-document";
|
||||
import { useBuilderAssistantStore } from "./assistant-store";
|
||||
|
||||
type BuilderDockProps = {
|
||||
pageLayout: BuilderPreviewPageLayout;
|
||||
@@ -37,13 +37,12 @@ type BuilderDockProps = {
|
||||
export function BuilderDock({ pageLayout, onTogglePageLayout }: BuilderDockProps) {
|
||||
const { data: session } = authClient.useSession();
|
||||
const resume = useCurrentResume();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [_, copyToClipboard] = useCopyToClipboard();
|
||||
const { zoomIn, zoomOut, centerView } = useControls();
|
||||
|
||||
const [isPrinting, setIsPrinting] = useState(false);
|
||||
const isAssistantOpen = useBuilderAssistantStore((state) => state.isOpen);
|
||||
const toggleAssistant = useBuilderAssistantStore((state) => state.toggleOpen);
|
||||
|
||||
const publicUrl = useMemo(() => {
|
||||
if (!session?.user.username || !resume?.slug) return "";
|
||||
@@ -114,9 +113,11 @@ export function BuilderDock({ pageLayout, onTogglePageLayout }: BuilderDockProps
|
||||
/>
|
||||
<DockIcon
|
||||
icon={ChatCircleDotsIcon}
|
||||
title={isAssistantOpen ? t`Close AI assistant` : t`Open AI assistant`}
|
||||
onClick={toggleAssistant}
|
||||
active={isAssistantOpen}
|
||||
title={t`Open AI agent`}
|
||||
onClick={() => {
|
||||
if (!resume) return;
|
||||
void navigate({ to: "/agent/new", search: { resumeId: resume.id } });
|
||||
}}
|
||||
/>
|
||||
<div className="mx-1 h-8 w-px bg-border" />
|
||||
<DockIcon icon={LinkSimpleIcon} title={t`Copy URL`} onClick={() => onCopyUrl()} />
|
||||
|
||||
@@ -28,7 +28,7 @@ export function PreviewPage() {
|
||||
wheel={{ step: 0.001 }}
|
||||
>
|
||||
<TransformComponent wrapperClass="h-full! w-full!">
|
||||
<ResumePreview pageGap="2rem" pageLayout={pageLayout} showPageNumbers />
|
||||
<ResumePreview showPageNumbers pageLayout={pageLayout} />
|
||||
</TransformComponent>
|
||||
|
||||
<BuilderDock
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Link } from "@tanstack/react-router";
|
||||
import { useMemo } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { match } from "ts-pattern";
|
||||
import { useAIStore } from "@reactive-resume/ai/store";
|
||||
import { Alert, AlertDescription } from "@reactive-resume/ui/components/alert";
|
||||
import { Badge } from "@reactive-resume/ui/components/badge";
|
||||
import { Button } from "@reactive-resume/ui/components/button";
|
||||
@@ -50,13 +49,11 @@ export function ResumeAnalysisSectionBuilder() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const resume = useResume();
|
||||
const aiEnabled = useAIStore((state) => state.enabled);
|
||||
const aiProvider = useAIStore((state) => state.provider);
|
||||
const aiModel = useAIStore((state) => state.model);
|
||||
const aiApiKey = useAIStore((state) => state.apiKey);
|
||||
const aiBaseURL = useAIStore((state) => state.baseURL);
|
||||
|
||||
const resumeId = resume?.id ?? "";
|
||||
const providersQuery = useQuery(orpc.aiProviders.list.queryOptions());
|
||||
const aiEnabled =
|
||||
providersQuery.data?.some((provider) => provider.enabled && provider.testStatus === "success") ?? false;
|
||||
|
||||
const analysisQuery = useQuery({
|
||||
...orpc.resume.analysis.getById.queryOptions({ input: { id: resumeId } }),
|
||||
@@ -106,12 +103,7 @@ export function ResumeAnalysisSectionBuilder() {
|
||||
if (!resume) return;
|
||||
|
||||
analyzeResume({
|
||||
provider: aiProvider,
|
||||
model: aiModel,
|
||||
apiKey: aiApiKey,
|
||||
baseURL: aiBaseURL,
|
||||
resumeId: resume.id,
|
||||
resumeData: resume.data,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
} from "@/components/resume/builder-resume-draft";
|
||||
import { useIsMobile } from "@/hooks/use-mobile";
|
||||
import { orpc } from "@/libs/orpc/client";
|
||||
import { BuilderAssistant } from "./-components/assistant";
|
||||
import { BuilderHeader } from "./-components/header";
|
||||
import { BuilderSidebarLeft } from "./-sidebar/left";
|
||||
import { BuilderSidebarRight } from "./-sidebar/right";
|
||||
@@ -168,8 +167,6 @@ function BuilderLayoutShell({ initialLayout }: BuilderLayoutShellProps) {
|
||||
<BuilderSidebarRight />
|
||||
</ResizablePanel>
|
||||
</ResizableGroup>
|
||||
|
||||
<BuilderAssistant />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user