Skip to content

refactor: unify fallback next json proxies#408

Merged
jerry609 merged 1 commit intodevfrom
refactor/pr13-next-json-fallback-proxies
Mar 15, 2026
Merged

refactor: unify fallback next json proxies#408
jerry609 merged 1 commit intodevfrom
refactor/pr13-next-json-fallback-proxies

Conversation

@jerry609
Copy link
Owner

@jerry609 jerry609 commented Mar 15, 2026

What changed

  • add cache support to the shared Next backend proxy helper so routes can preserve cache: "no-store"
  • migrate web/src/app/api/studio/cwd, web/src/app/api/studio/status, and web/src/app/api/research/paperscool/sessions/[sessionId] to the shared proxy helper
  • keep existing route-specific fallback contracts by expressing them through onError instead of inline fetch/try blocks
  • add focused route tests for studio fallback behavior and paperscool session no-store proxying

Why

  • continues the proxy cleanup from refactor: unify auth and sandbox next proxies #407 without mixing in streaming, binary download, or HTML fallback routes
  • removes three more hand-rolled backend fetch handlers while preserving their special behavior
  • leaves only the streaming/download/html special cases as remaining direct backend fetch routes

Validation

  • npx vitest run src/app/api/_utils/backend-proxy.test.ts src/app/api/_utils/auth-headers.test.ts src/app/api/papers/export/route.test.ts src/app/api/studio/cwd/route.test.ts src/app/api/studio/status/route.test.ts src/app/api/research/paperscool/sessions/[sessionId]/route.test.ts
  • npx eslint src/app/api/_utils/backend-proxy.ts src/app/api/_utils/backend-proxy.test.ts src/app/api/studio/cwd/route.ts src/app/api/studio/cwd/route.test.ts src/app/api/studio/status/route.ts src/app/api/studio/status/route.test.ts src/app/api/research/paperscool/sessions/[sessionId]/route.ts src/app/api/research/paperscool/sessions/[sessionId]/route.test.ts
  • npx tsc --noEmit
  • npm run build

Follow-up

  • remaining direct backend fetch routes are now down to 7, all in the streaming / binary / HTML-fallback bucket

Summary by CodeRabbit

  • New Features

    • Added cache directive support to the backend proxy layer for configurable caching behavior
    • Implemented fallback error responses for studio endpoints when backend requests fail
    • Centralized API proxy handling for research and studio routes
  • Tests

    • Added comprehensive unit tests for proxy functionality and API route handlers

Copilot AI review requested due to automatic review settings March 15, 2026 07:10
@vercel
Copy link

vercel bot commented Mar 15, 2026

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

Project Deployment Actions Updated (UTC)
paper-bot Ready Ready Preview, Comment Mar 15, 2026 7:33am

@coderabbitai
Copy link

coderabbitai bot commented Mar 15, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

The changes introduce caching support to the backend proxy utility and refactor three API route handlers to use the centralized proxy mechanism instead of direct fetch calls, ensuring consistent request forwarding and error handling across routes.

Changes

Cohort / File(s) Summary
Backend Proxy Enhancement
web/src/app/api/_utils/backend-proxy.ts, web/src/app/api/_utils/backend-proxy.test.ts
Added optional cache?: RequestCache field to ProxyOptions and forwarded it to upstream fetch calls. New test verifies cache directives are properly passed through to the upstream request.
Paperscool Session Route
web/src/app/api/research/paperscool/sessions/[sessionId]/route.ts, web/src/app/api/research/paperscool/sessions/[sessionId]/route.test.ts
Refactored GET handler to use proxyJson with cache: "no-store" option instead of direct fetch. Parameter renamed from _req to req. Added comprehensive test coverage verifying URL encoding and cache directives.
Studio CWD Route
web/src/app/api/studio/cwd/route.ts, web/src/app/api/studio/cwd/route.test.ts
Replaced direct fetch with proxyJson call, added req parameter to GET handler signature, implemented onError callback for fallback response with cwd and error details. Added test suite covering both proxy and error paths.
Studio Status Route
web/src/app/api/studio/status/route.ts, web/src/app/api/studio/status/route.test.ts
Replaced fetch logic with proxyJson delegation, updated GET signature to accept Request parameter, centralized error handling via onError callback returning 500 with fallback payload. Added test coverage including onError invocation verification.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A proxy hops through requests so fine,
With cache directives in every line,
From fetch to proxy, the routes align,
Error callbacks when things don't shine,
One utility to rule them all—how divine! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: unify fallback next json proxies' accurately and concisely describes the main objective of consolidating multiple route handlers to use a shared backend proxy utility with fallback support.

✏️ 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 refactor/pr13-next-json-fallback-proxies
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors several Next.js API routes to utilize a unified backend proxy helper. The primary goal is to centralize backend fetch logic, enhance maintainability, and ensure consistent handling of caching and error fallbacks across different API endpoints. This continues the effort to streamline backend interactions, reducing the number of custom fetch implementations and improving code consistency.

Highlights

  • Enhanced Backend Proxy Helper: Added cache support to the shared Next.js backend proxy helper, allowing routes to preserve specific cache directives like cache: "no-store".
  • Route Migration to Shared Proxy: Migrated three existing API routes: web/src/app/api/studio/cwd, web/src/app/api/studio/status, and web/src/app/api/research/paperscool/sessions/[sessionId] to utilize the unified backend-proxy helper.
  • Preserved Fallback Contracts: Maintained existing route-specific fallback behaviors by expressing them through the onError option of the shared proxy, replacing inline fetch/try blocks.
  • New Focused Tests: Introduced new, focused route tests to validate the studio fallback behavior and the paperscool session no-store proxying.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • web/src/app/api/_utils/backend-proxy.test.ts
    • Added a test case to verify that cache directives are correctly forwarded to the upstream request.
  • web/src/app/api/_utils/backend-proxy.ts
    • Introduced a cache option to the ProxyOptions type.
    • Modified fetchUpstream to pass the cache option to the underlying fetch call.
  • web/src/app/api/research/paperscool/sessions/[sessionId]/route.test.ts
    • Added a new test file to verify the paperscool session route correctly uses the proxyJson helper with no-store caching.
  • web/src/app/api/research/paperscool/sessions/[sessionId]/route.ts
    • Refactored the GET handler to use the proxyJson helper, replacing a manual fetch call and explicitly setting cache: "no-store".
  • web/src/app/api/studio/cwd/route.test.ts
    • Added a new test file to verify the studio/cwd route correctly uses the proxyJson helper and its onError fallback mechanism.
  • web/src/app/api/studio/cwd/route.ts
    • Refactored the GET handler to use the proxyJson helper, replacing a try-catch block with the onError option for fallback behavior.
  • web/src/app/api/studio/status/route.test.ts
    • Added a new test file to verify the studio/status route correctly uses the proxyJson helper and its onError fallback mechanism.
  • web/src/app/api/studio/status/route.ts
    • Refactored the GET handler to use the proxyJson helper, replacing a try-catch block with the onError option for fallback behavior.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Continues the proxy cleanup from #407 by migrating three more hand-rolled backend fetch handlers (studio/cwd, studio/status, paperscool/sessions/[sessionId]) to the shared proxyJson helper, adding cache support to the proxy layer, and preserving route-specific fallback behavior via onError.

Changes:

  • Added cache option to ProxyOptions and forwarded it to the upstream fetch call in backend-proxy.ts
  • Migrated studio/cwd, studio/status, and paperscool/sessions/[sessionId] routes to use proxyJson
  • Added focused tests for all three migrated routes and for the new cache-forwarding behavior

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated no comments.

Show a summary per file
File Description
web/src/app/api/_utils/backend-proxy.ts Added cache field to ProxyOptions and passed it through to fetch
web/src/app/api/_utils/backend-proxy.test.ts Test verifying cache directive is forwarded to upstream fetch
web/src/app/api/studio/status/route.ts Migrated to proxyJson with onError fallback
web/src/app/api/studio/status/route.test.ts New test for status route proxy + fallback
web/src/app/api/studio/cwd/route.ts Migrated to proxyJson with onError fallback
web/src/app/api/studio/cwd/route.test.ts New test for cwd route proxy + fallback
web/src/app/api/research/paperscool/sessions/[sessionId]/route.ts Migrated to proxyJson with cache: "no-store"
web/src/app/api/research/paperscool/sessions/[sessionId]/route.test.ts New test for paperscool session proxy

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great refactoring effort that unifies several backend proxy route handlers into a shared helper function. The introduction of cache support in proxyJson and its use in the paperscool session route is a good addition. Migrating the studio/cwd and studio/status routes to use the onError callback for their fallback logic significantly cleans up the code and makes it more declarative. The new tests are thorough and correctly validate the refactored logic, including the fallback behaviors. I have a couple of suggestions to further improve observability by adding logging in the new onError handlers.

Comment on lines +7 to +15
onError: () =>
Response.json(
{
cwd: process.env.HOME || "/tmp",
source: "fallback",
error: "Failed to get working directory from backend",
},
{ status: 200 },
),

Choose a reason for hiding this comment

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

medium

For better observability and easier debugging, it would be beneficial to log the error details provided by the onError context. The original implementation didn't log the error, but since you're refactoring to a more robust proxy helper, this is a good opportunity to add logging.

    onError: (context) => {
      console.error("Studio CWD proxy failed:", context.error)
      return Response.json(
        {
          cwd: process.env.HOME || "/tmp",
          source: "fallback",
          error: "Failed to get working directory from backend",
        },
        { status: 200 },
      )
    },

Comment on lines +7 to +15
onError: () =>
Response.json(
{
claude_cli: false,
error: "Failed to check Claude CLI status",
fallback: "anthropic_api",
},
{ status: 500 },
),

Choose a reason for hiding this comment

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

medium

Similar to the cwd route, it would be beneficial for observability to log the error details provided by the onError context here. This will help in debugging issues with the upstream service.

    onError: (context) => {
      console.error("Studio status proxy failed:", context.error)
      return Response.json(
        {
          claude_cli: false,
          error: "Failed to check Claude CLI status",
          fallback: "anthropic_api",
        },
        { status: 500 },
      )
    },

@jerry609 jerry609 changed the base branch from refactor/pr12-next-proxy-remaining to dev March 15, 2026 07:28
@jerry609 jerry609 force-pushed the refactor/pr13-next-json-fallback-proxies branch from 2462ff9 to 2310e36 Compare March 15, 2026 07:31
@sonarqubecloud
Copy link

@jerry609 jerry609 merged commit 5b33d08 into dev Mar 15, 2026
13 of 15 checks passed
@github-actions
Copy link

Vercel Preview

@jerry609 jerry609 deleted the refactor/pr13-next-json-fallback-proxies branch March 15, 2026 13:07
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