Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
fix(ai,ui): real OpenRouter key verification, verifier timeouts, provider error mapping, and legible dark destructive red
Khuram Niazb57e0d3f5b4b
diff --git a/__tests__/agentErrors.spec.ts b/__tests__/agentErrors.spec.tsindex 0260521..55abc27 100644--- a/__tests__/agentErrors.spec.ts+++ b/__tests__/agentErrors.spec.ts@@ -1,5 +1,18 @@import { mapAgentError } from "@/lib/agent/errors";-import { NoSuchToolError, InvalidToolInputError } from "ai";+import {+ NoSuchToolError,+ InvalidToolInputError,+ APICallError,+ RetryError,+} from "ai";++const apiCallError = (statusCode: number, message = "Provider returned error") =>+ new APICallError({+ message,+ url: "https://openrouter.ai/api/v1/responses",+ requestBodyValues: {},+ statusCode,+ });describe("mapAgentError", () => {it("never echoes an unmapped error's message", () => {@@ -32,6 +45,55 @@ describe("mapAgentError", () => {expect(mapped).toMatch(/settings/i);});+ it("names the rate limit and the model on a 429", () => {+ const mapped = mapAgentError(apiCallError(429), {+ provider: "openrouter",+ model: "qwen/qwen3.8-27b:free",+ });+ expect(mapped).toMatch(/rate-limited/i);+ expect(mapped).toMatch(/qwen\/qwen3\.8-27b:free/);+ });++ it("sees the status through the RetryError the SDK throws after retries", () => {+ const wrapped = new RetryError({+ message: "Failed after 3 attempts. Last error: Provider returned error",+ reason: "maxRetriesExceeded",+ errors: [apiCallError(429)],+ });+ expect(mapAgentError(wrapped, { provider: "openrouter" })).toMatch(+ /rate-limited/i,+ );+ });++ it("points a rejected key at Settings on a 401", () => {+ const mapped = mapAgentError(apiCallError(401, "User not found."), {+ provider: "openrouter",+ });+ expect(mapped).toMatch(/rejected the API key/i);+ expect(mapped).toMatch(/settings/i);+ });++ it("does not echo the provider's body on a mapped status", () => {+ const marker = "user_39CAXN1SLbb8LlFuJ4uyCKjcXWB";+ const mapped = mapAgentError(apiCallError(429, `limit hit ${marker}`), {+ provider: "openrouter",+ });+ expect(mapped).not.toContain(marker);+ });++ it("maps OpenRouter's tool-routing 404 to the tool-support message", () => {+ const mapped = mapAgentError(+ apiCallError(+ 404,+ 'No endpoints found that support tool use. Try disabling "add_job".',+ ),+ { provider: "openrouter", model: "nvidia/nemotron-3.5-content-safety" },+ );+ expect(mapped).toMatch(/cannot use tools/i);+ expect(mapped).toMatch(/nemotron/);+ expect(mapped).toMatch(/settings/i);+ });+it("maps a stale approval to a message naming Clear as the remedy", () => {const stale = Object.assign(new Error("no tool call found"), {name: "AI_ToolCallNotFoundForApprovalError",diff --git a/__tests__/provider-registry-server.spec.ts b/__tests__/provider-registry-server.spec.tsindex 8ab668f..968eb3a 100644--- a/__tests__/provider-registry-server.spec.ts+++ b/__tests__/provider-registry-server.spec.ts@@ -21,11 +21,36 @@ describe("PROVIDER_VERIFIERS – openrouter", () => {expect(result).toEqual({ success: true });expect(global.fetch).toHaveBeenCalledWith(+ "https://openrouter.ai/api/v1/key",+ {+ headers: { Authorization: "Bearer sk-or-valid" },+ signal: expect.any(AbortSignal),+ },+ );+ });++ // /models is public, so verifying against it passed any string+ it("verifies against the authenticated endpoint, not public /models", async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 });++ await PROVIDER_VERIFIERS.openrouter("sk-or-valid");++ expect(global.fetch).not.toHaveBeenCalledWith("https://openrouter.ai/api/v1/models",- { headers: { Authorization: "Bearer sk-or-valid" } },+ expect.anything(),);});+ it("aborts the request on a timeout signal", async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 });++ await PROVIDER_VERIFIERS.openrouter("sk-or-key");++ const { signal } = (global.fetch as any).mock.calls[0][1];+ expect(signal).toBeInstanceOf(AbortSignal);+ expect(signal.aborted).toBe(false);+ });+it("returns 'Invalid API key' error on 401", async () => {global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 401 });@@ -68,6 +93,17 @@ describe("PROVIDER_VERIFIERS – openrouter", () => {}),);});++ it("blocks the save on a non-401 failure, surfacing the status", async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 429 });++ const result = await PROVIDER_VERIFIERS.openrouter("sk-or-key");++ expect(result).toEqual({+ success: false,+ error: "OpenRouter returned 429",+ });+ });});describe("PROVIDER_FACTORIES – openrouter", () => {diff --git a/__tests__/verify-api-key-route.spec.ts b/__tests__/verify-api-key-route.spec.tsindex 64ed565..372e2bf 100644--- a/__tests__/verify-api-key-route.spec.ts+++ b/__tests__/verify-api-key-route.spec.ts@@ -61,14 +61,39 @@ describe("POST /api/settings/api-keys/verify", () => {expect(mockVerifier).toHaveBeenCalledWith("sk-live");});- it("maps connection failures to a friendly message", async () => {+ it("reports a connection failure as unreachable, not a bad key", async () => {mockVerifier.mockRejectedValue(new Error("fetch failed"));const res = await POST(req({ provider: "openai", key: "sk-live" }));const data = await res.json();expect(data.success).toBe(false);- expect(data.error).toBe("Cannot connect to openai service");+ expect(data.reason).toBe("unreachable");+ expect(data.error).toContain("Could not reach openai");+ expect(data.error).toContain("not checked");+ });++ it.each(["ENOTFOUND openrouter.ai", "EAI_AGAIN", "connect ECONNREFUSED"])(+ "treats %s as unreachable",+ async (message) => {+ mockVerifier.mockRejectedValue(new Error(message));++ const res = await POST(req({ provider: "openai", key: "sk-live" }));++ expect((await res.json()).reason).toBe("unreachable");+ },+ );++ it("treats a verifier timeout as unreachable", async () => {+ const timeout = new Error("The operation was aborted due to timeout");+ timeout.name = "TimeoutError";+ mockVerifier.mockRejectedValue(timeout);++ const res = await POST(req({ provider: "openai", key: "sk-live" }));+ const data = await res.json();++ expect(data.success).toBe(false);+ expect(data.reason).toBe("unreachable");});it("passes through other verifier error messages", async () => {@@ -79,5 +104,6 @@ describe("POST /api/settings/api-keys/verify", () => {expect(data.success).toBe(false);expect(data.error).toBe("Invalid API key");+ expect(data.reason).toBeUndefined();});});diff --git a/src/app/api/settings/api-keys/verify/route.ts b/src/app/api/settings/api-keys/verify/route.tsindex 4afd425..2269e04 100644--- a/src/app/api/settings/api-keys/verify/route.ts+++ b/src/app/api/settings/api-keys/verify/route.ts@@ -30,11 +30,20 @@ export async function POST(req: NextRequest) {return NextResponse.json(result);} catch (error) {const message = error instanceof Error ? error.message : "Verification failed";- return NextResponse.json({- success: false,- error: message.includes("fetch failed") || message.includes("ECONNREFUSED")- ? `Cannot connect to ${provider} service`- : message,- });+ const unreachable =+ (error instanceof Error && error.name === "TimeoutError") ||+ /fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(message);++ // The request never reached the provider, so the key is still unchecked.+ // Saying "verification failed" here reads as a rejected key instead.+ if (unreachable) {+ return NextResponse.json({+ success: false,+ reason: "unreachable",+ error: `Could not reach ${provider} — the key was not checked. Check the server's network and DNS access; note that Node's fetch ignores HTTP_PROXY / HTTPS_PROXY.`,+ });+ }++ return NextResponse.json({ success: false, error: message });}}diff --git a/src/app/globals.css b/src/app/globals.cssindex 3a7f055..46e279d 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -17,6 +17,7 @@--color-secondary: hsl(var(--secondary));--color-secondary-foreground: hsl(var(--secondary-foreground));--color-destructive: hsl(var(--destructive));+ --color-destructive-bg: hsl(var(--destructive-bg));--color-destructive-foreground: hsl(var(--destructive-foreground));--color-muted: hsl(var(--muted));--color-muted-foreground: hsl(var(--muted-foreground));@@ -70,6 +71,7 @@--accent: 210 40% 96.1%;--accent-foreground: 222.2 47.4% 11.2%;--destructive: 0 84.2% 60.2%;+ --destructive-bg: 0 84.2% 60.2%;--destructive-foreground: 210 40% 98%;--border: 214.3 31.8% 91.4%;--input: 214.3 31.8% 91.4%;@@ -97,7 +99,10 @@--muted-foreground: 215 20.2% 65.1%;--accent: 217.2 32.6% 17.5%;--accent-foreground: 210 40% 98%;- --destructive: 0 62.8% 40.6%;+ /* destructive text needs lightening on a near-black card (2.5:1 before) */+ /* the fill keeps the darker red so white button text stays readable */+ --destructive: 0 84.2% 60.2%;+ --destructive-bg: 0 62.8% 40.6%;--destructive-foreground: 210 40% 98%;--border: 217.2 32.6% 23.5%;--input: 217.2 32.6% 21.5%;diff --git a/src/components/automations/AutomationList.tsx b/src/components/automations/AutomationList.tsxindex 3eb155f..565951d 100644--- a/src/components/automations/AutomationList.tsx+++ b/src/components/automations/AutomationList.tsx@@ -340,7 +340,7 @@ export function AutomationList({<AlertDialogActiononClick={handleDelete}disabled={isDeleting}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90">{isDeleting ? "Deleting..." : "Delete"}</AlertDialogAction>diff --git a/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsx b/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsxindex f7cc902..be99a21 100644--- a/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsx+++ b/src/components/automations/automation-detail-container/AutomationDetailDialogs.tsx@@ -78,7 +78,7 @@ export function AutomationDetailDialogs({<AlertDialogActiononClick={onDelete}disabled={isDeleting}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90">{isDeleting ? "Deleting..." : "Delete"}</AlertDialogAction>diff --git a/src/components/profile/SkillsSectionCard.tsx b/src/components/profile/SkillsSectionCard.tsxindex dace487..805a5f3 100644--- a/src/components/profile/SkillsSectionCard.tsx+++ b/src/components/profile/SkillsSectionCard.tsx@@ -82,7 +82,7 @@ function SkillsSectionCard({<AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90"onClick={onDelete}>Deletediff --git a/src/components/profile/resume-container/ResumeDialogs.tsx b/src/components/profile/resume-container/ResumeDialogs.tsxindex 22abea8..f7fd37c 100644--- a/src/components/profile/resume-container/ResumeDialogs.tsx+++ b/src/components/profile/resume-container/ResumeDialogs.tsx@@ -98,7 +98,7 @@ export function DiscardImportDialog({<AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90"onClick={onConfirm}>Discard importdiff --git a/src/components/questions/QuestionCard.tsx b/src/components/questions/QuestionCard.tsxindex 9c31230..9e995e9 100644--- a/src/components/questions/QuestionCard.tsx+++ b/src/components/questions/QuestionCard.tsx@@ -132,7 +132,7 @@ export function QuestionCard({<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActiononClick={() => onDelete(question.id)}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90">Delete</AlertDialogAction>diff --git a/src/components/settings/ApiKeySettings.tsx b/src/components/settings/ApiKeySettings.tsxindex 4a92b70..e49b205 100644--- a/src/components/settings/ApiKeySettings.tsx+++ b/src/components/settings/ApiKeySettings.tsx@@ -120,7 +120,11 @@ function ApiKeySettings() {const verifyData = await verifyRes.json();if (!verifyData.success) {- toastError(verifyData.error || "Could not verify the key", "Verification failed");+ const title =+ verifyData.reason === "unreachable"+ ? `Cannot reach ${PROVIDERS.find((p) => p.id === provider)?.name ?? provider}`+ : "Verification failed";+ toastError(verifyData.error || "Could not verify the key", title);return;}diff --git a/src/components/settings/DataSettings.tsx b/src/components/settings/DataSettings.tsxindex 810c3fe..548650e 100644--- a/src/components/settings/DataSettings.tsx+++ b/src/components/settings/DataSettings.tsx@@ -357,7 +357,7 @@ export default function DataSettings() {<AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ className="bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90"onClick={runImport}>Delete everything and importdiff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsxindex add9dd3..63c47b6 100644--- a/src/components/ui/badge.tsx+++ b/src/components/ui/badge.tsx@@ -13,7 +13,7 @@ const badgeVariants = cva(secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:- "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",+ "border-transparent bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/80",outline: "text-foreground",},},diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex ec4cf64..2f2b5d0 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -11,7 +11,7 @@ const buttonVariants = cva(variant: {default: "bg-primary text-primary-foreground hover:bg-primary/90",destructive:- "bg-destructive text-destructive-foreground hover:bg-destructive/90",+ "bg-destructive-bg text-destructive-foreground hover:bg-destructive-bg/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:diff --git a/src/lib/agent/errors.ts b/src/lib/agent/errors.tsindex b8ad44d..f13e006 100644--- a/src/lib/agent/errors.ts+++ b/src/lib/agent/errors.ts@@ -1,7 +1,9 @@import {+ APICallError,InvalidToolApprovalError,InvalidToolInputError,NoSuchToolError,+ RetryError,ToolCallNotFoundForApprovalError,} from "ai";import { AIUnavailableError } from "@/lib/ai";@@ -21,6 +23,14 @@ function nameOf(error: unknown): string {return error instanceof Error ? error.name : "";}+// A retryable status arrives wrapped: the SDK exhausts its retries and throws+// a RetryError whose lastError carries the provider's status code.+function statusOf(error: unknown): number | undefined {+ if (RetryError.isInstance?.(error)) return statusOf(error.lastError);+ if (APICallError.isInstance?.(error)) return error.statusCode;+ return undefined;+}+/*** One mapping shared by the route's pre-stream catch and by* toUIMessageStreamResponse's onError, so the same failure reads the same on@@ -63,16 +73,27 @@ export function mapAgentError(return `Cannot reach ${provider}. Make sure the service is running, or switch provider in Settings.`;}+ const status = statusOf(error);++ if (status === 429) {+ return `${provider}${model ? ` / ${model}` : ""} is rate-limited right now. Wait a moment and ask again, or pick another model in Settings.`;+ }++ if (status === 401) {+ return `${provider} rejected the API key. Re-save it in Settings.`;+ }++ // OpenRouter phrases this as a 404 from its tool-compatibility routing stepif (- /does not support tools|tool (use|calling) (is )?not supported|no tools support/i.test(+ /does not support tools|no endpoints found that support tool|tool (use|calling) (is )?not supported|no tools support/i.test(message,)) {- return `${provider}${model ? ` / ${model}` : ""} cannot use tools, so it cannot add a job. Pick a tool-capable model in Settings.`;+ return `${provider}${model ? ` / ${model}` : ""} cannot use tools, so it cannot review a resume, match a job, write a cover letter or add a job. Pick a tool-capable model in Settings.`;}if (NoSuchToolError.isInstance?.(error) || /NoSuchTool/i.test(name)) {- return "The model asked for a tool that does not exist here. It only has one: adding a job.";+ return "The model asked for a tool that does not exist here. Try rephrasing your request.";}if (diff --git a/src/lib/ai/provider-registry.server.ts b/src/lib/ai/provider-registry.server.tsindex c527739..3910d21 100644--- a/src/lib/ai/provider-registry.server.ts+++ b/src/lib/ai/provider-registry.server.ts@@ -26,6 +26,7 @@ export const PROVIDER_VERIFIERS: Record<openai: async (key) => {const res = await fetch("https://api.openai.com/v1/models", {headers: { Authorization: `Bearer ${key}` },+ signal: AbortSignal.timeout(APP_CONSTANTS.AI_VERIFY_TIMEOUT_MS),});if (!res.ok)return {@@ -38,9 +39,12 @@ export const PROVIDER_VERIFIERS: Record<return { success: true };},+ // /api/v1/key is the authenticated endpoint. /models is public and answers+ // 200 to any key, so verifying against it passes anything pasted in.openrouter: async (key) => {- const res = await fetch("https://openrouter.ai/api/v1/models", {+ const res = await fetch("https://openrouter.ai/api/v1/key", {headers: { Authorization: `Bearer ${key}` },+ signal: AbortSignal.timeout(APP_CONSTANTS.AI_VERIFY_TIMEOUT_MS),});if (!res.ok)return {@@ -56,6 +60,7 @@ export const PROVIDER_VERIFIERS: Record<deepseek: async (key) => {const res = await fetch("https://api.deepseek.com/models", {headers: { Authorization: `Bearer ${key}` },+ signal: AbortSignal.timeout(APP_CONSTANTS.AI_VERIFY_TIMEOUT_MS),});if (!res.ok)return {@@ -106,6 +111,7 @@ export const PROVIDER_VERIFIERS: Record<gemini: async (key) => {const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${key}`,+ { signal: AbortSignal.timeout(APP_CONSTANTS.AI_VERIFY_TIMEOUT_MS) },);if (!res.ok)return {diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 408ff8a..81a63be 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -57,6 +57,10 @@ export const APP_CONSTANTS = {collapsed: { rail: "w-14", contentOffset: "sm:pl-14" },},+ // Cloud API-key verification timeout. Without it a black-holed TLS+ // handshake (VPN MTU mismatch) leaves the Verify button spinning forever.+ AI_VERIFY_TIMEOUT_MS: 10_000,+// Ollama API timeoutsAI_OLLAMA_LIST_TIMEOUT_MS: 5_000,AI_OLLAMA_GENERATE_TIMEOUT_MS: 10_000,