Skip to content
This repository was archived by the owner on Oct 1, 2026. It is now read-only.

Fix demo dev mode farm ID mismatch - #4

Merged
codybmenefee merged 16 commits into
mainfrom
dev
Feb 1, 2026
Merged

codybmenefee merged 16 commits into
mainfrom
dev

Conversation

@codybmenefee

Copy link
Copy Markdown
Owner

Summary

  • Fix farm ID mismatch where dev mode mutations targeted farm-1 but queries used demo-farm-{SESSION}
  • Add historical rotation simulation for realistic demo data generation
  • Production demo mode unchanged - visitors still get isolated demo farm copies

Test plan

  • Dev mode: /demo page loads and uses farm-1 directly
  • Dev mode: "Regenerate Demo History" updates sections across multiple paddocks
  • TypeScript compiles without errors

🤖 Generated with Claude Code

codybmenefee and others added 16 commits January 29, 2026 11:18
- Add rotationFrequency field to FarmSettings (default: 1 day)
- Add slider in Threshold Settings (range 1-10 days)
- Show warning when value exceeds 5 days for parasite control
- Update schema, mappers, and defaults across frontend/backend

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…rom Convex

The trigger was showing the Convex farm name while dropdown items used
Clerk org names, causing a mismatch when they diverged. Now consistently
uses Clerk org name (source of truth) for both.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Replace technical metrics (NDVI, confidence scores) with plain-language
information. New 3-tier layout: stats row with map thumbnail and grass
quality badge, expandable reasoning section, and binary approve/reject
actions.

- Add grassQuality utility for NDVI to quality mapping (prime/ready/recovering/resting)
- Add GrassQualityBadge, DaysRemainingIndicator, ExpandableReasoning components
- Simplify BriefCard and ApprovedState to match new design
- Remove debug reset button

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Simplify onboarding by removing the "Total Area" field from the Farm Setup
step. Users will draw their paddocks on the map anyway, making this input
redundant. Auto-set areaUnit to 'acres' during onboarding since geocoding
is US-only.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Users can now report bugs via a modal accessible from the header.
Reports are stored in Convex and automatically create GitHub issues
with appropriate labels for category and severity.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add subscription fields to users table (subscriptionStatus, subscriptionId, etc.)
- Add getUserSubscription query and syncUserSubscription mutation
- Update webhook handler to support user-based billing events (B2C)
- Create /subscribe route with Clerk PricingTable component
- Add paywall check in _app.tsx before onboarding
- Add VITE_PAYWALL_ENABLED env var to toggle paywall (disabled by default)

Clerk's has() function doesn't reliably detect free plans, so paywall
can be disabled in dev. In production with paid plans, enable via env var.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Make sidebar settings link context-aware so demo users go to /demo/settings
instead of /settings. Remove all "free account" messaging since free access
is only available in dev mode.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Simplifies the demo header by removing the demo banner and replacing
the profile avatar dropdown with a direct green "Sign Up" button.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Make sidebar navigation demo-aware so History and Analytics buttons
route to /demo/history and /demo/analytics when in demo mode.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement a localStorage layer for public demo users that intercepts
all writes. When VITE_DEV_AUTH=true, writes go to Convex (for developers
setting up demo data). When not set, writes go to localStorage (for
public demo users), with edits surviving page refresh.

New files:
- lib/demo/isDemoDevMode.ts - Check for dev auth mode
- lib/demo/demoLocalStorage.ts - localStorage CRUD helpers
- lib/demo/DemoGeometryProvider.tsx - Intercepts geometry writes
- lib/demo/useDemoFarmSettings.ts - Demo-aware settings hook
- lib/demo/useDemoObservations.ts - Demo-aware observations hooks
- components/demo/DemoDevToolsDropdown.tsx - Dev tools for demo mode

Also adds "Backdate Sections (-1 day)" tool to dev tools dropdowns
for simulating passage of time when testing demo scenarios.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Demo improvements:
- Add historical grazing sections for East Ridge paddock to demonstrate
  progressive strip grazing pattern (2 executed sections)
- Grant professional tier access to demo farms for full feature showcase
- Add updateSectionDate mutation for dev tools
- Remove demo settings banner (settings now persist via localStorage)

Map centering fix:
- Compute initial map center from paddock bounds instead of farm geometry
- More reliable when farm boundary is out of sync with paddock locations

Refactoring:
- Switch useFarmSettings to use useFarmContext instead of useFarm
- Add updateSectionMetadata to geometry context types

Migrations:
- Add deleteBadFarmSettings migration
- Add updateDemoGeometries migration

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Enable editing individual section dates through the SectionEditDrawer
when in dev mode (VITE_DEV_AUTH=true). This allows testing historical
grazing patterns without using the bulk backdate sections tool.

- Add date picker to SectionEditDrawer (visible in edit mode for dev)
- Wire up handleSectionMetadataChange in DemoGeometryProvider
- Implement updateSectionMetadata in GeometryContext

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add forceStart prop to TutorialProvider that starts the tutorial
regardless of completion status. Use a ref to track if we've already
force-started so the tutorial closes properly when completed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update agent prompts to prioritize adjacency over NDVI targeting. The system
prompt now uses numbered priorities with "ADJACENCY FIRST" and "NDVI SECOND",
and the drawing instructions use emphatic language ("CRITICAL", "MUST share
an edge") to prevent the agent from placing non-adjacent sections.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Prevent the map from resetting its view during geometry editing by:
- Removing paddocks and farmGeometry from map init effect dependencies
- Caching initial map center in a ref to maintain referential stability
- Removing initialSectionFeature from focus effect dependencies so it only
  triggers on section ID change, not geometry updates
- Adding safety guards for map operations during component unmounting

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
In dev mode (VITE_DEV_AUTH=true), the demo page was experiencing a farm ID
mismatch where mutations targeted farm-1 but queries used demo-farm-{SESSION}.
This caused "Regenerate Demo History" to update the wrong farm's data.

Changes:
- DemoAuthProvider: Return organizationId='farm-1' in dev mode (no demo session)
- DemoFarmProvider: Query farm-1 directly in dev mode
- demo.tsx: Handle dev mode where demoSessionId is null
- useDemoSeeding: Skip seeding in dev mode, query farm-1 directly
- convex/demo.ts: Add historical rotation simulation for realistic demo data

Production demo mode is unchanged - visitors still get isolated demo farm copies.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@codybmenefee
codybmenefee merged commit b7340a5 into main Feb 1, 2026
3 checks passed
@greptile-apps

greptile-apps Bot commented Feb 1, 2026

Copy link
Copy Markdown

Greptile Overview

Greptile Summary

Fixed critical farm ID mismatch where dev mode mutations targeted farm-1 but queries used demo-farm-{SESSION}, causing data inconsistencies. Added comprehensive historical rotation simulation that generates realistic 14-day grazing history with progressive strip grazing patterns, NDVI recovery modeling, and proper rest period tracking.

Key Changes:

  • Introduced isDemoDevMode flag to distinguish developer mode (edits persistent farm-1) from public demo mode (isolated per-session farms)
  • Updated DemoFarmProvider and DemoGeometryProvider to query farm-1 directly in dev mode instead of session-specific demo farms
  • Added generateHistoricalDemoData() function that simulates realistic rotation sequences with paddock strip generation, rest period tracking, and NDVI recovery
  • Replaced copyFarmData() with copyFarmBaseData() that excludes plans/events (now generated dynamically)
  • Added regenerateDemoHistory mutation for dev workflow to refresh demo data
  • Replaced synthetic geometries with real Columbia, TN paddock coordinates
  • Added dev tools dropdown with history regeneration controls

Confidence Score: 4/5

  • Safe to merge with minor considerations around strip generation edge cases
  • The core fix for farm ID mismatch is sound and well-architected. Historical rotation simulation logic is comprehensive with proper NDVI modeling. Minor edge case in strip clipping could produce unexpected results for complex geometries, but unlikely to cause issues with current paddock shapes.
  • Pay close attention to app/convex/demo.ts for the strip generation logic in generatePaddockStrips()

Important Files Changed

Filename Overview
app/convex/demo.ts Added historical rotation simulation with strip grazing logic and NDVI recovery modeling
app/src/lib/demo/isDemoDevMode.ts New file - simple check for VITE_DEV_AUTH environment variable
app/src/lib/demo/DemoGeometryProvider.tsx Routes geometry changes to Convex (dev mode) or localStorage (public demo) based on isDemoDevMode
app/src/lib/farm/DemoFarmProvider.tsx Fixed to query farm-1 directly in dev mode instead of demo farm copy
app/convex/seedData.ts Replaced synthetic geometries with real Columbia, TN paddock coordinates
app/src/components/demo/DemoDevToolsDropdown.tsx New dev tools dropdown with regenerate history and demo date controls
app/src/lib/convex/useDemoSeeding.ts Skip seeding in dev mode, query farm-1 directly instead of demo farm copy

Sequence Diagram

sequenceDiagram
    participant User
    participant Demo Route
    participant Config Check
    participant DemoFarmProvider
    participant DemoGeometryProvider
    participant Convex
    participant localStorage

    User->>Demo Route: Visit /demo page
    Demo Route->>Config Check: Check dev mode setting
    
    alt Developer Mode Enabled
        Config Check-->>Demo Route: Dev mode active
        Demo Route->>DemoFarmProvider: Initialize
        DemoFarmProvider->>Convex: Query farm-1 directly
        Convex-->>DemoFarmProvider: Return farm-1 data
        Demo Route->>DemoGeometryProvider: Initialize
        DemoGeometryProvider->>Convex: Query paddocks/sections for farm-1
        Convex-->>DemoGeometryProvider: Return geometries
        
        Note over DemoGeometryProvider,Convex: Mutations write to farm-1 in Convex<br/>(persistent demo source data)
        
    else Public Demo Mode
        Config Check-->>Demo Route: Public mode active
        Demo Route->>DemoFarmProvider: Initialize with session ID
        DemoFarmProvider->>Convex: Query demo-farm-SESSION
        
        alt Demo farm not found
            Convex->>Convex: seedDemoFarm()<br/>Copy base from farm-1<br/>Generate historical rotation data
            Convex-->>DemoFarmProvider: Return new demo farm
        else Demo farm exists
            Convex-->>DemoFarmProvider: Return existing demo farm
        end
        
        Demo Route->>DemoGeometryProvider: Initialize
        DemoGeometryProvider->>Convex: Query base data for demo-farm-SESSION
        Convex-->>DemoGeometryProvider: Return base geometries
        DemoGeometryProvider->>localStorage: Check for user overrides
        localStorage-->>DemoGeometryProvider: Return edits if any
        
        Note over DemoGeometryProvider,localStorage: Mutations write to localStorage<br/>(ephemeral per-session overrides)
    end
    
    DemoGeometryProvider-->>Demo Route: Ready with merged data
    Demo Route-->>User: Render demo interface
Loading

@greptile-apps greptile-apps 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.

7 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread app/convex/demo.ts
Comment on lines +129 to +147
}

const clipped = intersect(featureCollection([stripFeature, paddockGeometry]))

if (clipped && clipped.geometry.type === 'Polygon') {
strips.push(clipped.geometry as Polygon)
} else if (clipped && clipped.geometry.type === 'MultiPolygon') {
// If clipping produces multiple polygons, take the largest one
let bestArea = 0
let bestPolygon: Polygon | null = null

for (const coords of clipped.geometry.coordinates) {
const candidate = polygon(coords)
const candidateArea = area(candidate)
if (candidateArea > bestArea) {
bestArea = candidateArea
bestPolygon = { type: 'Polygon', coordinates: coords }
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When intersect() produces a MultiPolygon, only the largest polygon is kept. For paddocks with complex shapes (concave or with holes), strips could miss portions of the paddock area. Consider whether this is acceptable for the rectangular paddock geometries currently in use.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/convex/demo.ts
Line: 129:147

Comment:
When `intersect()` produces a `MultiPolygon`, only the largest polygon is kept. For paddocks with complex shapes (concave or with holes), strips could miss portions of the paddock area. Consider whether this is acceptable for the rectangular paddock geometries currently in use.

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.

This branch was previously deployed

1 inactive deployment
openPasture / development — 276a1872 Deployed Feb 1, 2026 by railway-app[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant