Skip to content

Conversation

@ngoiyaeric
Copy link
Collaborator

@ngoiyaeric ngoiyaeric commented Oct 2, 2025

User description

This commit introduces a new asynchronous agent, geojsonEnricher, responsible for processing textual responses and extracting structured geospatial data.

Key changes:

  • Created a new geojsonEnricher agent in lib/agents/geojson-enricher.tsx.
  • Defined new TypeScript interfaces for LocationResponse, MapCommand, and GeoJSON objects in lib/types/custom.ts.
  • Integrated the new agent into the main application workflow in app/actions.tsx.
  • Added a LocationResponseHandler component to update the map state via the MapDataContext.
  • Updated the Mapbox component to render GeoJSON data and execute map commands.

PR Type

Enhancement


Description

  • Add GeoJSON enrichment agent for geospatial data extraction

  • Integrate map visualization with GeoJSON rendering capabilities

  • Create location response handler for map state management

  • Define TypeScript interfaces for geospatial data structures


Diagram Walkthrough

flowchart LR
  A["Text Response"] --> B["GeoJSON Enricher Agent"]
  B --> C["LocationResponse"]
  C --> D["LocationResponseHandler"]
  D --> E["MapDataContext"]
  E --> F["Mapbox Component"]
  F --> G["Rendered Map with GeoJSON"]
Loading

File Walkthrough

Relevant files
Enhancement
custom.ts
Define geospatial TypeScript interfaces                                   

lib/types/custom.ts

  • Define TypeScript interfaces for geospatial data structures
  • Add LocationResponse, MapCommand, and GeoJSON types
  • Support Point, LineString, and Polygon geometries
+33/-0   
actions.tsx
Integrate GeoJSON enrichment into main workflow                   

app/actions.tsx

  • Import and integrate geojsonEnricher agent
  • Add LocationResponseHandler component integration
  • Process location responses in submit workflow
  • Handle geojsonEnrichment tool output in UI state
+39/-1   
mapbox-map.tsx
Add GeoJSON rendering and map command execution                   

components/map/mapbox-map.tsx

  • Add GeoJSON data rendering with points and lines layers
  • Implement map command execution (flyTo, easeTo, fitBounds)
  • Handle dynamic source and layer management
  • Clear commands after execution to prevent re-triggering
+78/-0   
geojson-enricher.tsx
Create GeoJSON enrichment agent                                                   

lib/agents/geojson-enricher.tsx

  • Create new agent for extracting geospatial data from text
  • Implement specialized prompt for GeoJSON and map command extraction
  • Handle JSON parsing with error fallback
  • Return structured LocationResponse objects
+66/-0   
map-data-context.tsx
Extend map context with geospatial data                                   

components/map/map-data-context.tsx

  • Add geojson and mapCommands fields to MapData interface
  • Import required types from custom types module
+6/-0     
location-response-handler.tsx
Create location response handler component                             

components/map/location-response-handler.tsx

  • Create component to handle location response updates
  • Update map context with GeoJSON and map commands
  • Implement side-effect only component (no UI rendering)
+28/-0   
Dependencies
package.json
Update dependencies for geospatial features                           

package.json

  • Add @radix-ui/react-select, nanoid, and zod dependencies
  • Update existing package versions
  • Remove QCX dependency reference
+8/-6     

Summary by CodeRabbit

  • New Features

    • AI answers are enriched with structured location data and accompanying text; enriched text is shown in the UI and full enrichment output is available for map handling.
    • Map now visualizes GeoJSON features (points & lines) and executes actions (flyTo, easeTo, fitBounds) from responses; map actions are consumed once.
  • Improvements

    • Enrichment failures gracefully fallback to original answer without map data.
  • Chores

    • Added deps: @radix-ui/react-select, nanoid, zod; updated pg, TypeScript typings and build memory for Next.js.

This commit introduces a new asynchronous agent, `geojsonEnricher`, responsible for processing textual responses and extracting structured geospatial data.

Key changes:
- Created a new `geojsonEnricher` agent in `lib/agents/geojson-enricher.tsx`.
- Defined new TypeScript interfaces for `LocationResponse`, `MapCommand`, and GeoJSON objects in `lib/types/custom.ts`.
- Integrated the new agent into the main application workflow in `app/actions.tsx`.
- Added a `LocationResponseHandler` component to update the map state via the `MapDataContext`.
- Updated the `Mapbox` component to render GeoJSON data and execute map commands.
@charliecreates charliecreates bot requested a review from CharlieHelps October 2, 2025 09:55
@vercel
Copy link

vercel bot commented Oct 2, 2025

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

Project Deployment Preview Comments Updated (UTC)
qcx Ready Ready Preview Comment Oct 7, 2025 3:41am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

Walkthrough

Adds GeoJSON enrichment: new agent and types, integrates enrichment into submit flow, emits a geojsonEnrichment tool output, renders location responses via LocationResponseHandler which updates shared map context, and updates Mapbox rendering to consume geojson and map commands. Also updates dependencies.

Changes

Cohort / File(s) Summary
App integration: enrichment + UI state
app/actions.tsx
Calls geojsonEnricher after obtaining an AI answer, stores locationResponse, emits a geojsonEnrichment tool output, and reconstructs UI by rendering LocationResponseHandler for validated toolOutput; uses PartialRelated for related queries streamable value.
GeoJSON enrichment agent & types
lib/agents/geojson-enricher.tsx, lib/types/custom.ts
Adds geojsonEnricher(researcherResponse) that prompts the LLM to produce a LocationResponse JSON (text, geojson FeatureCollection or null, map_commands or null), streams/parses output, and returns a fallback LocationResponse on error. Adds exported interfaces: MapCommand, GeoJSONGeometry, GeoJSONFeature, GeoJSONFeatureCollection, LocationResponse.
Map context and side-effect handler
components/map/map-data-context.tsx, components/map/location-response-handler.tsx
Extends MapData with optional geojson and mapCommands. Adds LocationResponseHandler React client component that merges incoming locationResponse.geojson and mapCommands into shared map data via setMapData (side-effect only, renders null).
Map rendering and commands
components/map/mapbox-map.tsx
When mapData.geojson exists, creates/updates a GeoJSON source and point/line layers; removes them when absent. Processes mapData.mapCommands (flyTo, easeTo, fitBounds), executes commands, then clears mapCommands.
Dependency updates & build
package.json
Adds @radix-ui/react-select, nanoid, zod; bumps pg, @types/node, @types/react, and typescript; increases memory for Next.js build script.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant A as App (submit)
  participant L as LLM (researcher)
  participant G as geojsonEnricher
  participant UI as UI State
  participant H as LocationResponseHandler
  participant C as MapDataContext
  participant M as MapboxMap

  U->>A: Submit prompt
  A->>L: Generate answer (text)
  L-->>A: answer
  A->>G: geojsonEnricher(answer)
  G-->>A: LocationResponse (text, geojson?, map_commands?)
  A->>UI: Append assistant message + toolOutput `geojsonEnrichment`
  UI->>H: Render LocationResponseHandler with validated toolOutput
  H->>C: setMapData({ geojson, mapCommands })
  C-->>M: mapData updated
  alt geojson present
    M->>M: Create/update GeoJSON source & point/line layers
  else geojson absent
    M->>M: Remove geojson layers/source if present
  end
  alt mapCommands present
    M->>M: Execute flyTo/easeTo/fitBounds
    M->>C: Clear mapCommands
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • CharlieHelps

Poem

I hop through data, maps unfurl,
I stitch your text to lines and pearl.
GeoJSON crumbs in whiskered paws,
I nudge the map and clear the laws.
A tiny rabbit charts the way—hooray! 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 clearly and succinctly describes the primary change—adding a GeoJSON enrichment agent—without extraneous details or file listings, and it accurately reflects the main feature introduced in the pull request. It follows the guideline of being a short, single sentence that highlights the most important change. Therefore, it effectively communicates the purpose of the PR to teammates scanning the history.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/geojson-enrichment-agent

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.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@charliecreates
Copy link

charliecreates bot commented Oct 2, 2025

  1. The introduction of the geojsonEnricher agent is a positive feature for enhancing geospatial data extraction. The design is clear, and the integration touches all the necessary components.
  2. The new TypeScript types in lib/types/custom.ts make the structure of geospatial data explicit. It’s good to see strong typing here. Double-check that those interfaces cover all possible variants of GeoJSON you expect to encounter (e.g., properties, complex FeatureCollections).
  3. The LocationResponseHandler component is a welcome addition for updating map state, but it would be helpful to see additional error handling/logging in case of unexpected data.
  4. The update to Mapbox to render GeoJSON and handle map commands appears well-structured, but please ensure that the rendering logic handles edge cases, like empty or invalid features.
  5. App-level integration (app/actions.tsx) looks appropriate but consider isolating complex logic into smaller, testable functions for maintainability.
  6. There are multiple lockfile updates (bun.lockb, pnpm-lock.yaml). Be sure only the correct lockfile is present and committed to avoid install issues.
  7. Consider adding unit or integration tests for the new agent and its TypeScript types, especially for edge geospatial scenarios.

Overall, great progress expanding the application’s geospatial functionality. With a couple more tests and error-handling tweaks, this will be even more robust.

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 2, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
Unvalidated LLM output

Description: Unvalidated JSON from an LLM is parsed and then propagated to the app, enabling potential
prototype pollution or unexpected map command execution without schema validation or
command allowlisting.
geojson-enricher.tsx [48-56]

Referred Code
const { text } = await streamText({
  model,
  messages,
  maxTokens: 2048,
});

// Assuming the LLM returns a valid JSON string, parse it.
const enrichedData = JSON.parse(text) as LocationResponse;
return enrichedData;
Unvalidated map commands

Description: Arbitrary map commands from external data are executed (flyTo, easeTo, fitBounds) without
validation or bounds checks, allowing abusive parameter values that can cause DoS-like
behavior or reveal internal state.
mapbox-map.tsx [580-599]

Referred Code
if (!map.current || !mapData.mapCommands || mapData.mapCommands.length === 0) return;

const mapInstance = map.current;

mapData.mapCommands.forEach(command => {
  switch (command.command) {
    case 'flyTo':
      mapInstance.flyTo(command.params);
      break;
    case 'easeTo':
      mapInstance.easeTo(command.params);
      break;
    case 'fitBounds':
      mapInstance.fitBounds(command.params, command.params.options || {});
      break;
    default:
      console.warn(`Unknown map command: ${command.command}`);
  }
});
Unvalidated GeoJSON input

Description: GeoJSON data from untrusted LLM output is injected into the map without schema validation,
risking large or malformed payloads that could trigger performance issues or parser
vulnerabilities.
mapbox-map.tsx [529-575]

Referred Code
if (!map.current) return;

const mapInstance = map.current;
const source = mapInstance.getSource('geojson-data');

// If GeoJSON data is present, add or update the source and layers
if (mapData.geojson) {
  if (source) {
    (source as mapboxgl.GeoJSONSource).setData(mapData.geojson);
  } else {
    mapInstance.addSource('geojson-data', {
      type: 'geojson',
      data: mapData.geojson,
    });

    // Add layer for points
    mapInstance.addLayer({
      id: 'geojson-points',
      type: 'circle',
      source: 'geojson-data',
      paint: {


 ... (clipped 26 lines)
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 2, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix incorrect fitBounds method usage
Suggestion Impact:The commit updated the fitBounds call to destructure bounds and options from command.params and pass them separately, aligning with the suggested fix (without the extra validation/logging).

code diff:

@@ -590,7 +590,8 @@
           mapInstance.easeTo(command.params);
           break;
         case 'fitBounds':
-          mapInstance.fitBounds(command.params, command.params.options || {});
+          const { bounds, options } = command.params;
+          mapInstance.fitBounds(bounds, options || {});
           break;

Correct the fitBounds method call by passing command.params.bounds and
command.params.options as separate arguments, as the current implementation
passes the entire params object incorrectly.

components/map/mapbox-map.tsx [592-594]

 case 'fitBounds':
-  mapInstance.fitBounds(command.params, command.params.options || {});
+  // The 'params' object for fitBounds should have a 'bounds' property.
+  if ('bounds' in command.params) {
+    mapInstance.fitBounds(command.params.bounds, command.params.options || {});
+  } else {
+    console.warn(`Invalid 'fitBounds' command: 'bounds' property is missing in params.`);
+  }
   break;

[Suggestion processed]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a runtime error where fitBounds is called with incorrect arguments, and it provides a correct implementation that aligns with the Mapbox GL JS API.

High
Improve robustness of JSON parsing
Suggestion Impact:The commit added logic to strip markdown code fences from the LLM response before calling JSON.parse, improving robustness similarly to the suggestion (though using regex for code fences rather than scanning for braces).

code diff:

     // Assuming the LLM returns a valid JSON string, parse it.
-    const enrichedData = JSON.parse(text) as LocationResponse;
+    let responseText = await text;
+
+    // Strip markdown code fences if present
+    const jsonMatch = responseText.match(/```(json)?\n([\s\S]*?)\n```/);
+    if (jsonMatch && jsonMatch[2]) {
+      responseText = jsonMatch[2].trim();
+    }
+
+    const enrichedData = JSON.parse(responseText) as LocationResponse;

To improve parsing robustness, extract the JSON object from the raw LLM response
text before parsing, as the response may contain extra text or markdown.

lib/agents/geojson-enricher.tsx [54-56]

-// Assuming the LLM returns a valid JSON string, parse it.
-const enrichedData = JSON.parse(text) as LocationResponse;
+// Extract the JSON object from the text response.
+const jsonStart = text.indexOf('{');
+const jsonEnd = text.lastIndexOf('}');
+if (jsonStart === -1 || jsonEnd === -1) {
+  throw new Error('No JSON object found in the LLM response.');
+}
+const jsonString = text.substring(jsonStart, jsonEnd + 1);
+
+// Parse the extracted JSON string.
+const enrichedData = JSON.parse(jsonString) as LocationResponse;
 return enrichedData;

[Suggestion processed]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that direct JSON.parse on LLM output is fragile and proposes a robust method to extract the JSON string, significantly improving the reliability of the feature.

Medium
Improve GeoJSON type safety

Refactor the GeoJSONGeometry interface into a discriminated union to enforce
that each geometry type has the correct corresponding coordinates structure,
improving type safety.

lib/types/custom.ts [7-11]

-// Defines the structure for the geometry part of a GeoJSON feature.
-export interface GeoJSONGeometry {
-  type: 'Point' | 'LineString' | 'Polygon'; // Can be extended with other GeoJSON geometry types
-  coordinates: number[] | number[][] | number[][][];
-}
+// Defines the structure for specific GeoJSON geometry types.
+type PointGeometry = {
+  type: 'Point';
+  coordinates: number[];
+};
 
+type LineStringGeometry = {
+  type: 'LineString';
+  coordinates: number[][];
+};
+
+type PolygonGeometry = {
+  type: 'Polygon';
+  coordinates: number[][][];
+};
+
+// Defines the structure for the geometry part of a GeoJSON feature using a discriminated union.
+export type GeoJSONGeometry = PointGeometry | LineStringGeometry | PolygonGeometry;
+
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a type safety weakness and proposes a discriminated union, which is the idiomatic and safer way to model this data structure in TypeScript, improving code quality and robustness.

Low
General
Prevent unnecessary component re-renders

To prevent unnecessary re-renders, add a deep comparison check inside the
useEffect hook to ensure setMapData is only called when the locationResponse
data has actually changed.

components/map/location-response-handler.tsx [14-24]

+// Custom hook to get the previous value of a prop or state
+function usePrevious<T>(value: T): T | undefined {
+  const ref = useRef<T>();
+  useEffect(() => {
+    ref.current = value;
+  });
+  return ref.current;
+}
+
+// ... inside LocationResponseHandler component
+const { setMapData } = useMapData();
+const prevLocationResponse = usePrevious(locationResponse);
+
 useEffect(() => {
-  if (locationResponse) {
+  // Prevent unnecessary updates if the response has not changed.
+  // A deep equality check is needed for objects.
+  if (locationResponse && JSON.stringify(locationResponse) !== JSON.stringify(prevLocationResponse)) {
     const { geojson, map_commands } = locationResponse;
-    console.log('LocationResponseHandler: Received data', locationResponse);
+    console.log('LocationResponseHandler: Received new data', locationResponse);
     setMapData(prevData => ({
       ...prevData,
       geojson: geojson,
       mapCommands: map_commands,
     }));
   }
-}, [locationResponse, setMapData]);
+}, [locationResponse, prevLocationResponse, setMapData]);

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion offers a valid performance optimization to prevent unnecessary re-renders, but its impact is moderate as it addresses a potential, not a definite, performance issue.

Low
  • Update

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6d0e1 and dea29ee.

⛔ Files ignored due to path filters (2)
  • bun.lockb is excluded by !**/bun.lockb
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • app/actions.tsx (6 hunks)
  • components/map/location-response-handler.tsx (1 hunks)
  • components/map/map-data-context.tsx (2 hunks)
  • components/map/mapbox-map.tsx (1 hunks)
  • lib/agents/geojson-enricher.tsx (1 hunks)
  • lib/types/custom.ts (1 hunks)
  • package.json (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
lib/agents/geojson-enricher.tsx (2)
lib/types/custom.ts (1)
  • LocationResponse (29-33)
lib/utils/index.ts (1)
  • getModel (19-62)
components/map/location-response-handler.tsx (4)
lib/types/custom.ts (1)
  • LocationResponse (29-33)
components/map/map-data-context.tsx (1)
  • useMapData (42-48)
components/map/map-query-handler.tsx (4)
  • useMapData (30-83)
  • toolOutput (33-74)
  • McpResponseData (8-16)
  • prevData (39-49)
lib/agents/tools/geospatial.tsx (1)
  • McpResponse (22-25)
components/map/map-data-context.tsx (1)
lib/types/custom.ts (2)
  • GeoJSONFeatureCollection (23-26)
  • MapCommand (2-5)
app/actions.tsx (5)
lib/agents/geojson-enricher.tsx (1)
  • geojsonEnricher (36-66)
components/map/location-response-handler.tsx (1)
  • LocationResponseHandler (11-28)
lib/agents/tools/geospatial.tsx (3)
  • uiStream (144-269)
  • McpResponse (22-25)
  • Location (15-20)
components/map/map-query-handler.tsx (3)
  • toolOutput (33-74)
  • useMapData (30-83)
  • prevData (39-49)
lib/agents/tools/index.tsx (1)
  • ToolProps (14-39)
🔇 Additional comments (5)
lib/agents/geojson-enricher.tsx (3)

1-3: LGTM!

Imports are correctly typed and used appropriately throughout the file.


39-45: LGTM!

Model initialization and message construction are correct. The type assertion is safe given getModel() always returns a LanguageModel-compatible object.


57-65: LGTM!

Error handling is appropriate: the function logs the error and returns a safe fallback with the original text, ensuring graceful degradation if enrichment fails.

app/actions.tsx (2)

15-15: LGTM!

Import statement is correct and the function is properly used at line 301.


29-29: LGTM!

Import statement is correct and the component is used at lines 556 and 591.

Comment on lines 585 to 599
switch (command.command) {
case 'flyTo':
mapInstance.flyTo(command.params);
break;
case 'easeTo':
mapInstance.easeTo(command.params);
break;
case 'fitBounds':
mapInstance.fitBounds(command.params, command.params.options || {});
break;
default:
console.warn(`Unknown map command: ${command.command}`);
}
});

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix fitBounds parameter handling.

fitBounds expects the bounds object/array as its first argument, but we’re passing the entire params object (which also carries options). With the current call, Mapbox receives an invalid bounds value and throws before any command executes. Destructure the payload and pass bounds separately:

-        case 'fitBounds':
-          mapInstance.fitBounds(command.params, command.params.options || {});
-          break;
+        case 'fitBounds': {
+          const { bounds, options } = command.params ?? {};
+          if (!bounds) {
+            console.warn('fitBounds command missing bounds payload');
+            break;
+          }
+          mapInstance.fitBounds(bounds, options ?? {});
+          break;
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch (command.command) {
case 'flyTo':
mapInstance.flyTo(command.params);
break;
case 'easeTo':
mapInstance.easeTo(command.params);
break;
case 'fitBounds':
mapInstance.fitBounds(command.params, command.params.options || {});
break;
default:
console.warn(`Unknown map command: ${command.command}`);
}
});
switch (command.command) {
case 'flyTo':
mapInstance.flyTo(command.params);
break;
case 'easeTo':
mapInstance.easeTo(command.params);
break;
case 'fitBounds': {
const { bounds, options } = command.params ?? {};
if (!bounds) {
console.warn('fitBounds command missing bounds payload');
break;
}
mapInstance.fitBounds(bounds, options ?? {});
break;
}
default:
console.warn(`Unknown map command: ${command.command}`);
}
🤖 Prompt for AI Agents
In components/map/mapbox-map.tsx around lines 585 to 599, the fitBounds call is
passing the entire params object (which contains both bounds and options) as the
first argument causing Mapbox to receive an invalid bounds value; destructure
command.params into bounds and options (e.g., const { bounds, options } =
command.params) and call mapInstance.fitBounds(bounds, options || {}) so bounds
is passed as the first parameter and options as the second, handling a missing
options object by defaulting to an empty object.

@ngoiyaeric
Copy link
Collaborator Author

@coderabbitai generate unit tests

@ngoiyaeric
Copy link
Collaborator Author

@coderabbitai the code is not building

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

echo "=== Checking package.json for syntax errors ==="
cat package.json | jq '.' > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✓ package.json is valid JSON"
else
    echo "✗ package.json has syntax errors"
fi

echo -e "\n=== Checking TypeScript files for syntax issues ==="

echo -e "\n--- Checking lib/types/custom.ts ---"
cat lib/types/custom.ts

echo -e "\n--- Checking lib/agents/geojson-enricher.tsx ---"
cat lib/agents/geojson-enricher.tsx

echo -e "\n--- Checking components/map/location-response-handler.tsx ---"
cat components/map/location-response-handler.tsx

echo -e "\n--- Checking components/map/map-data-context.tsx ---"
cat components/map/map-data-context.tsx

echo -e "\n--- Checking app/actions.tsx for import issues ---"
head -50 app/actions.tsx

echo -e "\n=== Checking for missing dependencies or imports ==="
echo "Checking if getModel is imported/exported..."
rg -n "export.*getModel" --type=ts --type=tsx

echo -e "\nChecking if LocationResponse type is properly exported..."
rg -n "export.*LocationResponse" lib/types/custom.ts

echo -e "\n=== Checking tsconfig.json ==="
if [ -f tsconfig.json ]; then
    cat tsconfig.json
else
    echo "tsconfig.json not found"
fi

Length of output: 9590


@ngoiyaeric, I found the build issue! There's a syntax error in lib/agents/geojson-enricher.tsx on Line 2.

The Problem

The import statement is missing a space between } and from:

import { getModel }from '../utils';
//                  ↑ missing space here

The Fix

Change Line 2 in lib/agents/geojson-enricher.tsx from:

import { getModel }from '../utils';

to:

import { getModel } from '../utils';

This is a simple typo that will prevent TypeScript from compiling. Once you add the space, the build should succeed.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

Unit Test Generation failed: CodeRabbit timed out while planning changes for components/map/map-data-context.test.tsx. Skipping this file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

✅ Actions performed

Unit Test Generation started...

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

Unit Test Generation failed: CodeRabbit timed out while planning changes for components/map/location-response-handler.test.tsx. Skipping this file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

✅ Actions performed

Unit Test Generation started...

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

Unit Test Generation failed: CodeRabbit timed out while planning changes for app/actions.test.tsx. Skipping this file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2025

✅ Actions performed

Unit Test Generation started...

This commit introduces a new asynchronous agent, `geojsonEnricher`, responsible for processing textual responses and extracting structured geospatial data.

Key changes:
- Created a new `geojsonEnricher` agent in `lib/agents/geojson-enricher.tsx`.
- Defined new TypeScript interfaces for `LocationResponse`, `MapCommand`, and GeoJSON objects in `lib/types/custom.ts`.
- Integrated the new agent into the main application workflow in `app/actions.tsx` with robust error handling.
- Added a `LocationResponseHandler` component to update the map state via the `MapDataContext`.
- Updated the `Mapbox` component to render GeoJSON data and execute map commands.

NOTE: The application build is currently failing due to a persistent 'JavaScript heap out of memory' error. This appears to be a pre-existing issue with the repository's dependencies or build configuration that could not be resolved. The feature code is complete, but the build itself will need to be addressed separately.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/actions.tsx (1)

539-548: Wrap related case in a block to satisfy no-switch-declarations.

Declaring const relatedQueries = … directly under the case triggers Biome’s noSwitchDeclarations error because the binding leaks into other branches. Enclose the case 'related' body in braces (or extract to a helper) so the declaration stays scoped to that branch.

♻️ Duplicate comments (1)
components/map/mapbox-map.tsx (1)

585-595: Guard fitBounds params before destructuring.

command.params can be undefined when enrichment returns a malformed or partial command. Destructuring it directly throws and prevents later commands from running. Add a clause block, validate bounds, and bail early if missing.

-        case 'fitBounds':
-          const { bounds, options } = command.params;
-          mapInstance.fitBounds(bounds, options || {});
-          break;
+        case 'fitBounds': {
+          const params = command.params ?? {};
+          const { bounds, options } = params as {
+            bounds?: mapboxgl.FitBoundsLike;
+            options?: mapboxgl.FitBoundsOptions;
+          };
+          if (!bounds) {
+            console.warn('fitBounds command missing bounds payload', command);
+            break;
+          }
+          mapInstance.fitBounds(bounds, options ?? {});
+          break;
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dea29ee and a5fa68f.

⛔ Files ignored due to path filters (1)
  • bun.lockb is excluded by !**/bun.lockb
📒 Files selected for processing (4)
  • app/actions.tsx (7 hunks)
  • components/map/mapbox-map.tsx (1 hunks)
  • lib/agents/geojson-enricher.tsx (1 hunks)
  • package.json (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
components/map/mapbox-map.tsx (2)
components/map/map-data-context.tsx (1)
  • MapData (7-17)
components/map/map-query-handler.tsx (4)
  • prevData (39-49)
  • prevData (53-57)
  • toolOutput (33-74)
  • useMapData (30-83)
lib/agents/geojson-enricher.tsx (2)
lib/types/custom.ts (1)
  • LocationResponse (29-33)
lib/utils/index.ts (1)
  • getModel (19-62)
app/actions.tsx (3)
lib/agents/geojson-enricher.tsx (1)
  • geojsonEnricher (37-75)
lib/schema/related.tsx (1)
  • PartialRelated (13-13)
components/map/location-response-handler.tsx (1)
  • LocationResponseHandler (11-28)
🪛 Biome (2.1.2)
components/map/mapbox-map.tsx

[error] 593-593: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

app/actions.tsx

[error] 539-539: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

@@ -0,0 +1,75 @@
import { CoreMessage, LanguageModel, streamText } from 'ai';
import { getModel }from '../utils';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix import spacing to restore build.

The statement currently reads import { getModel }from '../utils'; which is invalid syntax and matches the build failure reported by CI. Insert the missing space:

-import { getModel }from '../utils';
+import { getModel } from '../utils';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { getModel }from '../utils';
import { getModel } from '../utils';
🤖 Prompt for AI Agents
In lib/agents/geojson-enricher.tsx around line 2, the import statement lacks a
space between the named import and the from keyword causing a syntax error;
update the import to add the missing space so it reads with proper spacing
between the closing brace and the from keyword (e.g., ensure "import { getModel
} from '../utils';"), save the file and run the build/lint to confirm the fix.

@ngoiyaeric
Copy link
Collaborator Author

@coderabbitai review pr

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 13, 2025

@ngoiyaeric, I'll review the PR changes for you.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ngoiyaeric ngoiyaeric added Map Backend Issues on schema and database Agent labels Oct 13, 2025
Copy link
Collaborator Author

@ngoiyaeric ngoiyaeric left a comment

Choose a reason for hiding this comment

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

I think there should be a zod schema for the GeoJson parsing to improve its precision.

@ngoiyaeric ngoiyaeric added the 1.0.0 Standard release label Oct 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.0.0 Standard release Agent Backend Issues on schema and database Map Review effort 3/5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants