Make every ride an adventure. Bostie turns Boston's MBTA into a city exploration game: plan a real route, collect a stamp at every station you ride through, let Gemini verify the landmarks you photograph, and play three little Boston games while you wait for the train.
Built for two hackathon tracks: Transit Gamification and Best Use of Gemini API.
- Mobile-first web app. On a phone it fills the screen; on a desktop it runs inside an interactive iPhone frame.
- Five tabs: Map (the adventure map, with Plan a ride and Explore Boston), Ride, Discover, Trips and Passport. Scanning and Bostie's Favourite are optional quests reached from Discover.
- Demo Mode is separate: only when it is on do the judge walkthrough, the gold next-step strip and the live log of Gemini calls appear. Regular visitors get a clean interface.
- No account, no install. A guest's progress is stored on the device (and mirrored to Supabase when configured).
npm install
cp .env.example .env.local # add GEMINI_API_KEY; everything else is optional
npm run dev # http://localhost:3000The app runs with only GEMINI_API_KEY. Without it, transit, the map, stamps and the passport still work; scanning and Bostie Drawing show an error, and Bostie Guessing hints fall back to offline cues. Bostie Guessing answers and Bostie Parkour need no AI at all.
| Area | What is real | Notes |
|---|---|---|
| Route planning | Station network and stop order come from the MBTA V3 API (snapshot in src/data/network.json). Routes are computed by Dijkstra over (station, line) states with a transfer penalty. |
The MBTA API has no trip planner. Ride times are estimated from distance and labelled as such. |
| Location search | Type any address or place on Ride. A server route finds where it is (Google Places when GOOGLE_MAPS_API_KEY is set, otherwise OpenStreetMap via Photon, no key). Bostie then picks the station with the lowest train-plus-walk time and plans the MBTA trip. |
The search only locates the place. Routing is the app's own planner; nothing is generated by a model. |
| Fares and how to pay | MBTA's published one-way fares, transfer policy, accepted payment methods and reduced-fare rules, read from mbta.com and kept in one config file. Shown on route cards and in a fare summary before you start a journey. | Information only: no tickets are sold and no payments are taken. Computed by code, never by Gemini. |
| Arrivals and alerts | Live MBTA V3 predictions and service alerts through cached server routes. | Labelled Live MBTA. If the API fails the UI says so; it never invents times. |
| Demo mode | A scripted Harvard → Central → Kendall/MIT → Charles/MGH → Park Street ride with simulated departures and position. | Always labelled Demo data. Gemini calls in demo mode are real. |
| Landmark scanner | One multimodal Gemini call: photo + player position + a 20-landmark catalogue with visual cues and reference notes → schema-constrained JSON. | Deterministic checks decide whether a stamp is granted (see below). |
| Bostie's Favourite | Three optional games. Bostie Guessing: five photos, four answers each, a hint that removes two, or answer on the map. Bostie Drawing: sketch a landmark or symbol and Gemini says how recognizable it is. Bostie Parkour: a 3D run (three.js) where each obstacle asks a question with six seconds to answer; 3, 5, 7 or 10 obstacles. | Right answers, scores and XP are all code. Each game pays XP for the first 5 plays a day. Parkour's questions about people are a written list with a source link each (src/data/trivia.ts). Drawings are never stored. Sounds are generated in the browser and start muted. |
| Gamification | XP ledger, 12 levels, streaks, 10 achievements, 148 stamps. (Challenges were removed from the app; the engine still supports them.) | One pure engine (src/lib/gamification.ts); every reward is an idempotent transaction. |
| Passport | Stamp collection with search and filters, line completion, badges, journey and discovery history, saved places, XP ledger. | |
| Route planning | Searchable stations and places; step-by-step list (walk, board, ride, change, walk); the MBTA's own direction names and destinations; departures limited to trains that reach your stop, with the platform; up to three subway alternatives, plus bus and Commuter Rail routes from Google when available. | Departures are badged Live MBTA, Scheduled (timetable, when the MBTA has no predictions for the station) or Demo data. Google routes need the Routes API enabled on GOOGLE_MAPS_API_KEY; without it only Bostie's own routes show. Bus and Commuter Rail routes are information only (no guidance or stamps), and their fares come from the MBTA fare table, never from Google. |
| Get-off alerts | A warning when the stop to get off at is next, and again on arriving, shown as a banner on any screen (including inside a game) and, with the switch on, as a phone notification when Bostie is in the background. Works in Automatic and Manual mode. | No server sends these: the page raises them while it is still running (src/lib/alerts.ts, public/sw.js), so a phone that has fully closed the tab gets nothing. With no position to go on, a backup warning is timed from when the rider boarded and says it is an estimate. iPhone needs Bostie added to the Home Screen for notifications. |
| Trips | A fifth tab for planning a day (or up to three) around Boston. Social-to-Trip: a YouTube link, a video (8 still frames taken on the phone) or screenshots; Gemini names the places. Plan it for me: Gemini drafts days from interests, budget and time. Build it myself: search and add places. The itinerary shows the day on the map, arrival times, whether each stop is open then, the walk or T ride between stops, drag-to-reorder, Optimize, an overview with costs, and saved trips. | Gemini only proposes names. Every place is verified with Google Places (OpenStreetMap when Google is not set up) and must be in Greater Boston, or it is dropped and listed as left out. Order, travel and times are computed by code from the MBTA network data; T fares are the published ones. Place costs appear only where Google lists a price range. TikTok and Instagram links cannot be opened by a server, so those use the video or screenshot route. Trips has its own store (bostie-trips-v1) and no XP; tripHooks in src/lib/trips.ts is the hook for a later integration. |
| Sharing, My day and heat map | After a landmark stamp, Share this discovery draws a 9:16 picture from the rider's photo and hands it to the phone's share menu (Instagram, Facebook, anything installed); elsewhere it saves the image. Passport → My day lists today's places, shows a heat map (All time / Today) and shares a picture of the day: a street map with a numbered pin for each place in order, and the stamps earned (sample: docs/samples/share-day.png). |
A website cannot post into another app directly, so the rider picks the app. The scan photo is used once and never stored. In Automatic mode the GPS route is saved on the device only (never synced), capped at 4,000 points, and cleared from Passport → Settings → Clear history. The shared day picture shows the exact route, and says so before sharing. |
| Adventure map (home) | Stations, lines, landmarks, saved places, position, suggested walk, active journey. | Google Maps when a key is set. Otherwise OpenStreetMap street tiles with Bostie's lines and markers drawn on top; if tiles cannot load it falls back to a labelled schematic. |
| Explore Boston (Discover) | Choose a start and interests; get destination cards with the nearest station, travel time, why it fits, Get directions and Save. | Deterministic: places come from the catalogue and travel times from the route planner. The price shown on a card is a labelled estimate. No quest required. |
- The active journey lives in one place:
journeyinsrc/lib/store.ts, saved inlocalStorage(tquest-v1). It holds the journey id, the chosen route (station ids, legs and stops), the stage, the leg and stop index, Automatic or Manual mode, the start and end places, andupdatedAt. No keys or tokens are stored. - Only four things change it: a step (
advanceJourney, from a tap or from live location), choosing a route or mode while planning,endJourney, and starting a replacement, which asks first (pending,ReplaceJourney). A journey still on the Plan screen is replaced without asking, because it has not started. - Games never touch it. They record plays as events (
reward) and keep their own screen state. Opening, restarting or finishing a game leaves the journey as it was. Automatic mode and get-off alerts run app-wide (useJourneyRunner,useGetOffAlertsin the shell), so they continue inside a game. - Back from a game (
src/lib/gameReturn.ts): opening a game from the journey screen records that insessionStorage. The game's Back button then goes back one step in browser history, which is the journey, so repeated visits never pile up history. A game opened from the games screen goes back to the games screen. Either way a "Journey active" banner offers Return to Journey; hiding it does not end the journey. - On return the journey screen fetches departures and alerts again; nothing cached is shown as current. A journey restored from an earlier visit is checked against the network data (
repairJourney): if its route no longer fits, the same trip is re-planned and the stage kept where possible. - Trips is separate:
src/lib/trips.tshas its own store and storage key. Its only link to the rest is "Ride it", which starts an ordinary journey to that stop.
Gemini does the things only a model can do, and is never trusted with the things code should decide.
1. Landmark recognition (src/app/api/scan/route.ts), image + text → JSON
Gemini receives the photo, the player's position (GPS or simulated, with distance to each landmark) and the landmark catalogue. It returns a recognition status, ranked candidates with reasons, the visual evidence it actually saw, a history summary written only from the supplied notes, and a recommendation. Then code decides:
- the id must exist in the catalogue;
- status must be
recognizedand the recommendationunlock; - at least two pieces of visual evidence;
- the top-ranked candidate must be the same landmark, at
highlikelihood; - location sets the reward: within 1 km (or the demo position) earns full XP, otherwise the stamp is "photo-only" for half XP.
An uncertain or failed scan grants nothing and asks for a better photo. The photo is processed in memory and never stored.
2. Bostie's Favourite (src/app/api/game/*)
- Hints (text → JSON): a clue for the photo in Bostie Guessing, written from the catalogue's reference notes. Every hint passes an answer-leak check; a leaking hint is replaced with a curated cue.
- Sketch judge (image + text → JSON): looks at a Bostie Drawing sketch with the subject's key features and returns a 0 to 100 recognizability score, the features it can see, the ones missing, and one line of encouragement. The server clamps and validates the score, refuses near-empty canvases before calling the model, and maps the score to XP by fixed bands. Text inside a drawing is treated as part of the picture, never as an instruction.
Every response is constrained with a JSON schema and re-validated with zod (src/lib/server/gemini.ts). Calls go through a model chain (default gemini-3.5-flash-lite, then gemini-3.1-flash-lite) that falls through on overload or timeout. All four endpoints have a non-AI fallback, so the game stays playable if Gemini is down.
Showcase panel. Each real call is logged with model, input modality, grounding context, the validated structured output, what code did with it, and latency. On desktop it is the right-hand panel; on a phone, tap "Gemini activity". No keys, photos or hidden reasoning are shown, and mocked or offline responses never appear in it.
src/
app/
page.tsx, explore/, scan/, play/, passport/, journey/ screens (client components)
api/scan, api/game/{guess,hint,debrief} Gemini routes (server only)
api/mbta/{predictions,alerts} cached MBTA V3 proxies
components/
shell/ iPhone frame, tab bar, reward reveals, demo guide, Gemini showcase
map/ CityMap: Google Maps backend + schematic SVG backend
passport/ passport sections
lib/
gamification.ts events + XP ledger → levels, stamps, streaks, achievements, challenges (pure)
game.ts Bostie's Favourite rules: questions, scoring, daily XP limit (pure)
network.ts MBTA network + route planner (pure)
store.ts zustand store, persisted to localStorage; journey state machine
contracts.ts zod schemas shared by routes and client
server/ Gemini client, rate limiting, MBTA cache
sync.ts optional Supabase mirror
data/
places.ts curated ground truth: 20 landmarks, 8 stations, 5 neighbourhoods
network.json generated from the MBTA API (npm run data:network)
wiki.json licensed Commons photos + credits (npm run data:photos)
supabase/ schema, RLS, idempotent sync function, generated seed
tests/ Playwright: logic, mocked end-to-end, opt-in real API
Decisions worth knowing:
- State is two append-only logs: events (what happened) and an XP ledger keyed by transaction id. Stamps, level, streak, line progress and statistics are derived, so they cannot drift, and replaying an event is a no-op. That is the duplicate-reward guarantee.
- Station stamps are collected by riding through. There is no GPS underground, so the rider confirms each stop. Stamps record how they were collected (ride, demo).
- No rarity tiers are shown. Stamps are simply collected or locked. An internal tier still picks each stamp's ink colour.
- Streaks count any activity, including a game round, on the player's local calendar day, and forgive one rest day. Nobody has to make an unnecessary trip.
- Cache Components is off (
next.config.ts): every screen reads the player's local progress, so there is no server-rendered content to cache.
src/data/fares.ts is the single source for prices, transfer rules and payment methods, and src/lib/fares.ts is the deterministic engine that prices a trip from it.
- Sources (all checked on 21 November 2026): fares overview, subway, bus, Commuter Rail and its zone table, ferry, transfers, reduced fares, contactless.
- What the engine knows: subway and bus fares (adult and reduced), every Commuter Rail zone and interzone price, the four ferry fare groups, and the transfer pilot that began on 1 September 2026 (within two hours, pay only the highest-priced of subway, bus and ferry when using the same card or device; no transfers with cash; Commuter Rail tickets never include one).
- What the app shows: Bostie's planner covers rapid transit, so every planned journey is a subway-fare trip: one fare however many lines you change between. Route cards show the fare beside time, changes and the next train; the fare summary adds the breakdown, ways to pay, reduced and free fares, passes, and links to MBTA's pages for bus, Commuter Rail and ferry tickets.
- When data is missing the quote is marked
estimateorunavailableand the interface says so. Commuter Rail interzone fares are always marked as estimates, because MBTA publishes the prices but not the zone-counting rule on that page. - To update after a fare change: re-read the pages above, edit
src/data/fares.ts(includingFARES_VERIFIED_ON) and runnpm test; the logic tests pin the published prices.
| Name | Required | Purpose |
|---|---|---|
GEMINI_API_KEY |
for AI | Server only. From AI Studio. |
GEMINI_MODEL |
no | Text model override. Default gemini-3.5-flash-lite. |
GEMINI_VISION_MODEL |
no | Model for photo recognition only, e.g. a larger Flash model. Falls back automatically. |
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY |
no | Enables Google Maps in Explore and Pin Drop. Restrict it by HTTP referrer and to the Maps JavaScript API. |
GOOGLE_MAPS_API_KEY |
no | Server-side Google Maps Platform key with Places API (New) enabled. Switches address and place search to Google. An AI Studio (Gemini) key does not work here. |
MBTA_API_KEY |
recommended | Free at api-v3.mbta.com. Keyless access is 20 requests/minute. |
NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY |
no | Enables the cloud mirror of guest progress. |
- Create a project at supabase.com.
- In the SQL editor run
supabase/migrations/0001_init.sql, thensupabase/seed.sql. - Authentication → Sign In / Providers → enable Allow anonymous sign-ins.
- Set the two
NEXT_PUBLIC_SUPABASE_*variables and restart.
Guests are signed in anonymously; progress is pushed through sync_progress(), which inserts with on conflict do nothing under row-level security. The mirror is one-directional (device → cloud). npm run data:seed regenerates the seed from the app's own data.
npm i -g vercel
vercel link
vercel env add GEMINI_API_KEY production # and any optional variables
vercel --prodOr import the GitHub repository in the Vercel dashboard and add the same variables under Settings → Environment Variables. No other configuration is needed: API routes are serverless functions, nothing is written to disk, and camera and geolocation work because Vercel serves HTTPS.
npx playwright install chromium # once
npm test # 33 logic tests + 11 flows at phone and desktop size
npm run test:real # opt-in: live Gemini recognition, judging and hints
node scripts/smoke-scan.mjs http://localhost:3000 # quick live scan checknpm test builds and serves the production app, mocks Gemini, MBTA and Wikimedia, and covers: the whole judge demo, duplicate-stamp prevention, uncertain and failed scans, wrong guesses, hints, Gemini outage, pin-drop scoring, live and failed transit data, transfers, navigation, layout overflow, the desktop frame and fullscreen toggle, saved places and demo reset. Screenshots land in screenshots/.
Open the site on a laptop, tap Start exploring, and switch Demo mode on at the top right (on a phone: Passport → Settings → Demo mode). The first time each screen appears, its features are highlighted one at a time with a short description beside them (tap Next, or Skip tips to turn them off). The Guide button replays the highlights for the current screen. The gold strip in the app and the left panel tick off each demo step.
All of that wording lives in one file, src/lib/guide.ts. A feature is linked to its highlight by a data-tour attribute. When the app changes, edit that file, bump GUIDE_VERSION (returning visitors then see the revised highlights once) and run npm test: the tests fail, naming the highlight, if one no longer finds its feature or a button label has changed.
- Map: the adventure map with your level and the two main actions. Tap Plan a ride: the search-first Ride screen opens with shortcuts (map, home, work, alerts), popular or recent stations, and departures labelled Demo data. Tap Park Street to plan the trip from Harvard, or type any station, line or landmark.
- Route: one Red Line leg, four stops, estimated time, and the fare ($2.40) with the ways to pay. Open Fare breakdown and how to pay to see the detail and the link to MBTA's fares. Start journey, then I am at the station.
- Waiting: under Play while you wait, tap Bostie Guessing and play a round of five photos. Then try Bostie Drawing (watch the sketch judge call appear in the Gemini panel) and Bostie Parkour from the games screen.
- Back to the journey (the demo strip at the top takes you there): My train is here stamps Harvard. Confirm Central, Kendall/MIT, Charles/MGH and Park Street. Five stamps, the Red Line Explorer badge, a few level-ups.
- Explore nearby lists landmarks around Park Street. Open Scan (the gold strip takes you there), tap the State House sample photo (or upload your own, or use the camera). A real Gemini call verifies it; the verification checks are listed under the result.
- Complete journey, then Open passport: stamps, badges, line progress, the journal and the XP ledger.
- Reset demo progress (left panel, or Passport → Reset all progress) returns to a clean state.
Turn demo mode off to see live MBTA predictions and real geolocation.
- "Gemini could not analyse this photo": check
GEMINI_API_KEYand the server log; lines starting[gemini]name the model and error. A 503 means the model is overloaded; the chain should already have fallen through. - Departures say Offline: the MBTA API is unreachable or rate-limited. Add
MBTA_API_KEY. - Map says "Schematic map": the street tiles could not load (offline, or the tile server refused). The app still works on the schematic.
- Camera will not start: browsers only allow camera access on HTTPS or localhost. Use the upload button otherwise.
- Stuck state: Passport → Reset all progress, or clear the site's storage.
- The Google Maps backend was written without a key to test against. The built-in map uses OpenStreetMap's community tile server, which has a fair-use policy: fine for a demo, not for real traffic.
- Address and place search uses OpenStreetMap data through Photon's public server unless a Google Maps key is set; the Google path is written but untested (no key). Walking times at the far end are straight-line estimates, and the map does not yet draw the walk.
- Explore Boston recommendations are rule-based (interest match, then travel time). Gemini is not involved there yet.
- Supabase SQL was verified in an in-memory Postgres with stand-ins for Supabase auth, not against a live project. The mirror does not pull progress onto a second device.
- Fares are a snapshot of mbta.com on 21 November 2026 and do not update themselves. Bus, Commuter Rail and ferry fares are in the engine and tested, but no journey uses them yet because routing is rapid transit only. Passes and fare capping are described, not calculated.
- Station visits are self-confirmed; there is no anti-cheat beyond the scanner's checks. Rewards are computed on the device and trusted by the mirror.
- Rate limiting and MBTA caching are per server instance.
- The historical-photo game mode, Gemini Live voice and AI-generated challenges were left out. The challenge model already carries a
source: "ai"field for the last one. - Transit lines on the schematic map are straight station-to-station segments.
Transit data: MBTA V3 API. Map: © OpenStreetMap contributors. Photos: Wikimedia Commons, each shown with its author and licence and linked to its source (src/data/wiki.json). Typefaces: Libre Caslon Text and Hanken Grotesk.