Skip to content

agent: copy one API endpoint (the simplest to copy) from the chat codebase to t - #285

Closed
sweetmantech wants to merge 1 commit into
testfrom
agent/copy-one-api-endpoint--the-sim-1773245094214
Closed

sweetmantech wants to merge 1 commit into
testfrom
agent/copy-one-api-endpoint--the-sim-1773245094214

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Automated PR from coding agent.

Summary by CodeRabbit

  • New Features
    • Added /api/ai/models endpoint to retrieve available AI models with improved error handling and real-time data fetching.

@vercel

vercel Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Mar 11, 2026 4:08pm

Request Review

@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new Next.js API route handler at /api/ai/models is introduced that proxies the getAvailableModels function and returns available AI models in JSON format. The endpoint enforces strict no-cache directives via force-dynamic, force-no-store, and revalidate = 0 to ensure fresh model data is always served. Includes error handling and structured logging.

Changes

Cohort / File(s) Summary
New AI Models Endpoint
app/api/ai/models/route.ts
New GET route handler that proxies getAvailableModels(), returns models in JSON, and enforces dynamic caching with error handling and logging.

Sequence Diagram

sequenceDiagram
    participant Client
    participant RouteHandler as GET /api/ai/models
    participant ModelsService as getAvailableModels()
    participant Response

    Client->>RouteHandler: Request available models
    RouteHandler->>ModelsService: Fetch available models
    alt Success
        ModelsService-->>RouteHandler: Return models array
        RouteHandler->>Response: 200 JSON (models)
    else Error
        ModelsService-->>RouteHandler: Throw error
        RouteHandler->>RouteHandler: Log error safely
        RouteHandler->>Response: 500 JSON (error message)
    end
    Response-->>Client: Response
Loading

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🤖 A gateway born to list the minds,
Fresh models served without the binds,
No cache to stale the flow,
Dynamic truth in every show! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Solid & Clean Code ❓ Inconclusive Unable to verify error handling flow for getAvailableModels without actual shell output showing method usage patterns and call context. Provide the actual shell command output containing getAvailableModels references to assess adherence to SOLID principles and error handling practices.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch agent/copy-one-api-endpoint--the-sim-1773245094214

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/api/ai/models/route.ts (1)

10-19: Add endpoint tests for both branches.

This new route should be covered with a success test and an error test that mocks getAvailableModels() failure. That would also pin the intended status code/body once the helper stops swallowing upstream exceptions. Based on learnings, "Applies to app/api/**/route.ts : Write tests for new API endpoints covering all success and error paths".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/api/ai/models/route.ts` around lines 10 - 19, Add two tests for the GET
handler in app/api/ai/models/route.ts: one that stubs getAvailableModels() to
resolve with a sample models array and asserts the endpoint returns status 200
and a JSON body containing { models }, and another that stubs
getAvailableModels() to throw/reject and asserts the endpoint returns status 500
and a JSON body containing { message } (matching the error.message when an Error
is thrown). In your test file (e.g., tests/api/ai/models.test.ts) import or
request the route handler, mock the getAvailableModels module (using your test
runner/mocking utilities) to control success/failure, and verify both response
status and body shape to lock in intended behavior for the GET function and the
getAvailableModels() error path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/api/ai/models/route.ts`:
- Around line 12-17: The route currently treats any empty array from
getAvailableModels() as success because the helper swallows gateway errors;
update getAvailableModels (in lib/ai/getAvailableModels.ts) to either rethrow on
gateway/network errors instead of returning [] or return a typed Result/Failure
object, and then modify this route handler (route.ts) to detect that failure and
return a non-200 Response (e.g., Response.json({ message }, { status: 500 }))
when the helper signals an error; ensure you reference getAvailableModels() when
changing behavior so the catch here actually receives thrown errors or inspects
the Result and returns the appropriate error response.
- Around line 10-24: Change the GET handler to require and validate auth before
calling getAvailableModels(): update the function signature to accept the
Request (e.g., export async function GET(req)) and call validateAuthContext(req)
at the top, returning an appropriate 401/403 Response.json if validation fails;
only after successful validateAuthContext() call getAvailableModels() and return
Response.json({ models }); keep the existing error handling and keep
dynamic/fetchCache/revalidate exports unchanged.

---

Nitpick comments:
In `@app/api/ai/models/route.ts`:
- Around line 10-19: Add two tests for the GET handler in
app/api/ai/models/route.ts: one that stubs getAvailableModels() to resolve with
a sample models array and asserts the endpoint returns status 200 and a JSON
body containing { models }, and another that stubs getAvailableModels() to
throw/reject and asserts the endpoint returns status 500 and a JSON body
containing { message } (matching the error.message when an Error is thrown). In
your test file (e.g., tests/api/ai/models.test.ts) import or request the route
handler, mock the getAvailableModels module (using your test runner/mocking
utilities) to control success/failure, and verify both response status and body
shape to lock in intended behavior for the GET function and the
getAvailableModels() error path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2f9b64eb-9537-41f7-bf76-06c082a5b831

📥 Commits

Reviewing files that changed from the base of the PR and between 6c5eda3 and 0a42862.

📒 Files selected for processing (1)
  • app/api/ai/models/route.ts

Comment on lines +10 to +24
export async function GET() {
try {
const models = await getAvailableModels();
return Response.json({ models });
} catch (error) {
console.error("/api/ai/models error", error);
const message = error instanceof Error ? error.message : "failed";
return Response.json({ message }, { status: 500 });
}
}

// Disable caching to always serve the latest model list.
export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
export const revalidate = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Require validateAuthContext() before fetching models.

This handler is unauthenticated right now. With Line 12 making a live gateway call and Lines 21-24 disabling caching, anonymous traffic can turn this into a direct upstream fan-out path. Change the signature to accept the request and validate auth before calling getAvailableModels(). As per coding guidelines, "Always use validateAuthContext() for authentication in API routes; it supports both x-api-key header and Authorization: Bearer token authentication".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/api/ai/models/route.ts` around lines 10 - 24, Change the GET handler to
require and validate auth before calling getAvailableModels(): update the
function signature to accept the Request (e.g., export async function GET(req))
and call validateAuthContext(req) at the top, returning an appropriate 401/403
Response.json if validation fails; only after successful validateAuthContext()
call getAvailableModels() and return Response.json({ models }); keep the
existing error handling and keep dynamic/fetchCache/revalidate exports
unchanged.

Comment on lines +12 to +17
const models = await getAvailableModels();
return Response.json({ models });
} catch (error) {
console.error("/api/ai/models error", error);
const message = error instanceof Error ? error.message : "failed";
return Response.json({ message }, { status: 500 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

The catch won't handle the main failure mode.

lib/ai/getAvailableModels.ts:9-16 catches gateway errors and returns [], so upstream outages still produce 200 { models: [] } here and never hit Line 15. Let the helper rethrow, or return a typed failure/result so this route can send a real non-200 response.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/api/ai/models/route.ts` around lines 12 - 17, The route currently treats
any empty array from getAvailableModels() as success because the helper swallows
gateway errors; update getAvailableModels (in lib/ai/getAvailableModels.ts) to
either rethrow on gateway/network errors instead of returning [] or return a
typed Result/Failure object, and then modify this route handler (route.ts) to
detect that failure and return a non-200 Response (e.g., Response.json({ message
}, { status: 500 })) when the helper signals an error; ensure you reference
getAvailableModels() when changing behavior so the catch here actually receives
thrown errors or inspects the Result and returns the appropriate error response.

Copy link
Copy Markdown
Contributor

Closing this unmerged PR as superseded in source by #498 (d3e049d0bdb091c4f8fa0ec8e0a5698ce0862182) and #519 (51723d70d402f388c367cbe0126b4af22b0daa73). The current GET /api/ai/models retains {models} and dynamic/no-store behavior, adds CORS, and sanitizes thrown errors. The helper can return an empty list after provider failure; this closure does not establish catalog freshness or deployed/provider/client acceptance, which remains with the existing model-catalog owner. Original head 0a4286263478a45dfda05524e780b6d571591c4b and test target are preserved; no merge or branch deletion.

@sswiftdrtv sswiftdrtv closed this Oct 25, 2026

This branch was successfully deployed

1 active deployment
Preview — 0a428626 Deployed Mar 11, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants