feat(settings): per-integration Test button with live API checks

Each integration card now has a Test button that re-runs its
connectivity check on demand and updates the badge in place.

- Refactors checkIntegrationStatus into checkIntegration(name) so a
  single integration can be tested without firing the others.
- Adds POST /api/settings/test for the on-demand check.
- Replaces the "key exists ⇒ connected" placeholder for Tavily,
  Gemini, and Nextdoor with real API calls (Tavily search, Gemini
  models list, Nextdoor advertiser fetch). 401/403 surface as
  "Invalid API key" / "Token expired or invalid" so a stale
  credential is obvious instead of pretending to be healthy.
- Fixes Postiz auth header (was Bearer, the rest of the codebase
  passes the API key bare — matches lib/postiz.ts now).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Trey T
2026-05-03 21:03:16 -05:00
parent 63698333ff
commit 55fb221faa
3 changed files with 203 additions and 87 deletions
+49 -2
View File
@@ -12,7 +12,7 @@ import {
CardHeader, CardHeader,
CardTitle, CardTitle,
} from "@/components/ui/card"; } from "@/components/ui/card";
import { CheckCircle2, XCircle, Loader2, ExternalLink } from "lucide-react"; import { CheckCircle2, XCircle, Loader2, ExternalLink, FlaskConical } from "lucide-react";
interface SettingsGroup { interface SettingsGroup {
name: string; name: string;
@@ -110,6 +110,7 @@ export default function SettingsPage() {
const [saving, setSaving] = useState<string | null>(null); const [saving, setSaving] = useState<string | null>(null);
const [saved, setSaved] = useState<string | null>(null); const [saved, setSaved] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [testing, setTesting] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
fetch("/api/settings?status=true") fetch("/api/settings?status=true")
@@ -159,6 +160,27 @@ export default function SettingsPage() {
return status[key] || { connected: false, error: "Unknown" }; return status[key] || { connected: false, error: "Unknown" };
} }
async function handleTest(group: SettingsGroup) {
const integration = group.name.toLowerCase();
setTesting(integration);
try {
const res = await fetch("/api/settings/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ integration }),
});
const result = await res.json();
setStatus((prev) => ({ ...prev, [integration]: result }));
} catch {
setStatus((prev) => ({
...prev,
[integration]: { connected: false, error: "Test request failed" },
}));
} finally {
setTesting(null);
}
}
if (loading) { if (loading) {
return ( return (
<div className="flex items-center justify-center py-20"> <div className="flex items-center justify-center py-20">
@@ -179,6 +201,8 @@ export default function SettingsPage() {
{SETTINGS_GROUPS.map((group) => { {SETTINGS_GROUPS.map((group) => {
const groupStatus = getGroupStatus(group); const groupStatus = getGroupStatus(group);
const integrationKey = group.name.toLowerCase();
const isTesting = testing === integrationKey;
return ( return (
<Card key={group.name}> <Card key={group.name}>
@@ -186,7 +210,15 @@ export default function SettingsPage() {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<CardTitle>{group.name}</CardTitle> <CardTitle>{group.name}</CardTitle>
{groupStatus.connected ? ( {isTesting ? (
<Badge
variant="outline"
className="text-blue-600 border-blue-200 bg-blue-50"
>
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
Testing
</Badge>
) : groupStatus.connected ? (
<Badge <Badge
variant="outline" variant="outline"
className="text-green-600 border-green-200 bg-green-50" className="text-green-600 border-green-200 bg-green-50"
@@ -204,6 +236,20 @@ export default function SettingsPage() {
</Badge> </Badge>
)} )}
</div> </div>
<div className="flex items-center gap-3">
<Button
variant="outline"
size="sm"
onClick={() => handleTest(group)}
disabled={isTesting}
>
{isTesting ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<FlaskConical className="h-3.5 w-3.5 mr-1" />
)}
{isTesting ? "" : "Test"}
</Button>
<a <a
href={group.docsUrl} href={group.docsUrl}
target="_blank" target="_blank"
@@ -214,6 +260,7 @@ export default function SettingsPage() {
<ExternalLink className="h-3 w-3" /> <ExternalLink className="h-3 w-3" />
</a> </a>
</div> </div>
</div>
<CardDescription>{group.description}</CardDescription> <CardDescription>{group.description}</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
+19
View File
@@ -0,0 +1,19 @@
import { auth } from "@/lib/auth";
import { checkIntegration, type IntegrationName } from "@/lib/settings";
const VALID: IntegrationName[] = ["claude", "postiz", "tavily", "gemini", "nextdoor"];
export async function POST(request: Request) {
const session = await auth();
if (!session) return new Response("Unauthorized", { status: 401 });
const body = await request.json().catch(() => ({}));
const name = body?.integration as IntegrationName | undefined;
if (!name || !VALID.includes(name)) {
return Response.json({ error: "integration must be one of: " + VALID.join(", ") }, { status: 400 });
}
const status = await checkIntegration(name);
return Response.json(status);
}
+93 -43
View File
@@ -102,16 +102,27 @@ export async function saveSetting(key: SettingKey, value: string) {
}); });
} }
/** export type IntegrationName = "claude" | "postiz" | "tavily" | "gemini" | "nextdoor";
* Check connectivity status for each integration. export type IntegrationStatus = { connected: boolean; error?: string };
*/
export async function checkIntegrationStatus(): Promise<Record<string, { connected: boolean; error?: string }>> {
const settings = await getAllSettings();
const status: Record<string, { connected: boolean; error?: string }> = {};
// Claude OAuth token — validate by hitting the messages API with a 1-token call. function errorMessage(e: unknown): string {
// A valid OAuth token returns 200; an expired/invalid one returns 401. if (e instanceof Error) {
if (settings.CLAUDE_CODE_OAUTH_TOKEN) { if (e.name === "TimeoutError" || e.name === "AbortError") return "Timed out";
return e.message;
}
return "Connection failed";
}
/**
* Live-test a single integration by making a real API call.
*/
export async function checkIntegration(name: IntegrationName): Promise<IntegrationStatus> {
const settings = await getAllSettings();
switch (name) {
case "claude": {
// OAuth token — validate by hitting the messages API with a 1-token call.
if (!settings.CLAUDE_CODE_OAUTH_TOKEN) return { connected: false, error: "Not configured" };
try { try {
const res = await fetch("https://api.anthropic.com/v1/messages", { const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST", method: "POST",
@@ -128,56 +139,95 @@ export async function checkIntegrationStatus(): Promise<Record<string, { connect
}), }),
signal: AbortSignal.timeout(10000), signal: AbortSignal.timeout(10000),
}); });
if (res.ok) { if (res.ok) return { connected: true };
status.claude = { connected: true }; if (res.status === 401) return { connected: false, error: "Token expired or invalid" };
} else if (res.status === 401) { return { connected: false, error: `HTTP ${res.status}` };
status.claude = { connected: false, error: "Token expired or invalid" };
} else {
status.claude = { connected: false, error: `HTTP ${res.status}` };
}
} catch (e) { } catch (e) {
status.claude = { connected: false, error: e instanceof Error ? e.message : "Connection failed" }; return { connected: false, error: errorMessage(e) };
} }
} else {
status.claude = { connected: false, error: "Not configured" };
} }
// Postiz case "postiz": {
if (settings.POSTIZ_URL && settings.POSTIZ_API_KEY) { if (!settings.POSTIZ_URL || !settings.POSTIZ_API_KEY) return { connected: false, error: "Not configured" };
try { try {
const res = await fetch(`${settings.POSTIZ_URL}/public/v1/integrations`, { const res = await fetch(`${settings.POSTIZ_URL}/public/v1/integrations`, {
headers: { Authorization: `Bearer ${settings.POSTIZ_API_KEY}` }, headers: { Authorization: settings.POSTIZ_API_KEY },
signal: AbortSignal.timeout(5000), signal: AbortSignal.timeout(5000),
}); });
status.postiz = { connected: res.ok }; if (res.ok) return { connected: true };
if (!res.ok) status.postiz.error = `HTTP ${res.status}`; return { connected: false, error: `HTTP ${res.status}` };
} catch (e) { } catch (e) {
status.postiz = { connected: false, error: e instanceof Error ? e.message : "Connection failed" }; return { connected: false, error: errorMessage(e) };
} }
} else {
status.postiz = { connected: false, error: "Not configured" };
} }
// Tavily case "tavily": {
if (settings.TAVILY_API_KEY) { if (!settings.TAVILY_API_KEY) return { connected: false, error: "Not configured" };
status.tavily = { connected: true }; // No ping endpoint, just check if key exists try {
} else { const res = await fetch("https://api.tavily.com/search", {
status.tavily = { connected: false, error: "Not configured" }; method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: settings.TAVILY_API_KEY,
query: "ping",
max_results: 1,
}),
signal: AbortSignal.timeout(8000),
});
if (res.ok) return { connected: true };
if (res.status === 401 || res.status === 403) return { connected: false, error: "Invalid API key" };
return { connected: false, error: `HTTP ${res.status}` };
} catch (e) {
return { connected: false, error: errorMessage(e) };
}
} }
// Gemini case "gemini": {
if (settings.GEMINI_API_KEY) { if (!settings.GEMINI_API_KEY) return { connected: false, error: "Not configured" };
status.gemini = { connected: true }; try {
} else { const res = await fetch(
status.gemini = { connected: false, error: "Not configured" }; `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(settings.GEMINI_API_KEY)}`,
{ signal: AbortSignal.timeout(8000) }
);
if (res.ok) return { connected: true };
if (res.status === 400 || res.status === 403) return { connected: false, error: "Invalid API key" };
return { connected: false, error: `HTTP ${res.status}` };
} catch (e) {
return { connected: false, error: errorMessage(e) };
}
} }
// Nextdoor case "nextdoor": {
if (settings.NEXTDOOR_API_TOKEN && settings.NEXTDOOR_ADVERTISER_ID) { if (!settings.NEXTDOOR_API_TOKEN || !settings.NEXTDOOR_ADVERTISER_ID) {
status.nextdoor = { connected: true }; return { connected: false, error: "Not configured" };
} else { }
status.nextdoor = { connected: false, error: "Not configured" }; try {
const res = await fetch(
`https://api.nextdoor.com/v1/advertiser/${encodeURIComponent(settings.NEXTDOOR_ADVERTISER_ID)}`,
{
headers: { Authorization: `Bearer ${settings.NEXTDOOR_API_TOKEN}` },
signal: AbortSignal.timeout(8000),
}
);
if (res.ok) return { connected: true };
if (res.status === 401 || res.status === 403) return { connected: false, error: "Token expired or invalid" };
if (res.status === 404) return { connected: false, error: "Advertiser ID not found" };
return { connected: false, error: `HTTP ${res.status}` };
} catch (e) {
return { connected: false, error: errorMessage(e) };
}
}
}
} }
return status; const ALL_INTEGRATIONS: IntegrationName[] = ["claude", "postiz", "tavily", "gemini", "nextdoor"];
/**
* Check connectivity status for every integration in parallel.
*/
export async function checkIntegrationStatus(): Promise<Record<string, IntegrationStatus>> {
const results = await Promise.all(
ALL_INTEGRATIONS.map(async (name) => [name, await checkIntegration(name)] as const)
);
return Object.fromEntries(results);
} }