Building An AI Chat Interface In Public: Live Travel & Maps, a 3D Chemistry Lab, Async Media, and How We Cut Startup Payloads by 99%
Notes from the past few weeks of building ARPA Chat solo, from live flights and routes, and a 3D Bohr atom lab, to non-blocking async images & videos, a 0-token intent router, and addressing the real GCP/Firebase/React b
Notes from the past few weeks of building ARPA Chat solo, from live flights and routes, and a 3D Bohr atom lab, to non-blocking async images & videos, a 0-token intent router, and addressing the real GCP/Firebase/React bugs we hit along the way.
Quick update from the trenches on what I've been building on ARPA Chat over the past few weeks.
Since my last post, a ton of real usage and honest user feedback pushed us to stop tinkering with abstract ideas and actually fix the day-to-day friction people hit when using an AI workspace every day. Some of this was brand-new stuff I'd been wanting to build for a while, like live travel cards, real routing maps, and our first interactive Education app, and of course a big chunk of it was unglamorous engineering work to make the whole thing feel fast, calm, and reliable instead of janky.
I talked to dozens of people on Reddit and direct DMs from our users and realized that they cared less about new features, and more about seamless, smooth, fast ui/ux. I mean, take Gemini for example, even when it takes quite some time to load it does it smoothly, has loading animations, basic elements are ready to use out of the gate, even while the app is loading, eg. you can start typing your prompt and by the time the app is up, you can hit it, etc. These things look basic and trivial, but it is exactly the Y/N factors that decide whether users actually use your app daily or just try it once.
Here's the full rundown of what changed, why we built it, the technical challenges we hit along the way, and generic patterns you can steal if you're building on GCP, Firebase, Python/FastAPI, and React.
1. Inline Travel Cards โ Real Flights, Stays & eSIM
One of the most annoying things about planning a trip with an AI is getting a wall of hallucinated flight prices and dead links, so I wanted to fix that properly, at least to a point it feels more intuitive and helpful that just a list of pinpoints and a good luck note.
Now when you ask about flights, hotels, or a multi-city trip, the chat renders an interactive Travel Card directly inline:
-
Real flight search with airline logos, flight numbers, exact airports, durations, and
Cheapest/Fastestbadgesโplus a[One-way | Round-trip]toggle and multi-leg tabs if you're doing something like Thessaloniki โ London โ Zurich. - Curated stays with real hotel photography, an independent check-in/out calendar, and worldwide city/airport autocomplete.
- Airalo eSIM links tucked neatly into the card so you don't have to hunt for travel data separately.
- Zero-lag tab switching via session caching, and older travel cards auto-collapse as you keep planning so your chat doesn't turn into an endless stack of heavy widgets.
How It Works: Let the LLM Pick the Params, Let Your Backend Fetch the Prices
The biggest trap when adding travel or commerce to an AI app is asking the LLM to output prices or URLs. Even with web search, prices go stale in minutes. Our rule was simple: the LLM only emits the search parameters (origin, destination, dates, legs), and the frontend hydrates live data through a cached backend proxy.
If a specific date has zero cached fares on an aggregator API, a 3-stage waterfall (exact date โ flexible month โ cheapest upcoming) prevents empty "No flights found" dead ends:
# Generic FastAPI pattern: 3-stage resilient fare lookup with TTL cache
async def fetch_flights_resilient(origin: str, dest: str, date: str):
cache_key = f"{origin}:{dest}:{date}"
if cached := ttl_cache.get(cache_key):
return cached
# Stage 1: exact date -> Stage 2: same month -> Stage 3: cheapest upcoming
for params in [
{"origin": origin, "destination": dest, "departure_at": date},
{"origin": origin, "destination": dest, "departure_at": date[:7]},
{"origin": origin, "destination": dest},
]:
results = await upstream_flight_api(params)
if results:
ttl_cache.set(cache_key, results, ttl_seconds=900)
return results
return []
On the React side, keeping a tiny sessionStorage cache keyed by origin+dest+date means switching between Flight / Stays / Multi-leg tabs or hitting F5 feels instant and cuts redundant API calls.
2. Ripping Out Hardcoded Maps (Real Routes, Live POIs & a Better Weather Card)
Our old map card had a dirty secret: it had hundreds of lines of hardcoded local coordinates that kept overriding actual places with generic downtown pins. We ripped all of that out and rebuilt it properly.
Now when you ask how to get from A to B or ask about a specific neighborhood or cafe:
- You get real A โ B routes with interactive
[Walk | Drive | Transit]toggles. - Specific venues pin to their exact street address instead of dropping a pin in the middle of the city.
- A new
HOT:bar surfaces top curated picks or live nearby spots (Sights, Dining, Hotels, Stores, Parks) powered by real geocoding and Overpass POI data, cached cleanly so reloads don't hammer anything. - We also tightened the prompt rules so asking "Tell me about Thessaloniki's history" gives you clean prose instead of spamming a map card you didn't ask for, and upgraded our inline Weather Card into its own modular component with pastel condition icons, metric pills, a clickable multi-day prognosis strip, and condition-aware follow-up pills.
How It Works: Caching Free Geocoding & Balancing Noisy POI Data
Public geocoding (Nominatim) and POI APIs (Overpass) are awesome, but they will throttle you fast if every client hits them directlyโand raw Overpass results are noisy (50 ATMs and 2 cafes).
The clean fix is a thin backend aggregator that:
- Geocodes the area once and caches it for 30 minutes in memory.
- Buckets POIs into balanced categories (
dining,sights,parks,stores,hotels) so one category never dominates. - Enforces strict prompt disambiguation so the LLM only emits a
mapblock for routes or specific places, never for general history/culture questions.
# Generic POI category balancer (prevents 15 restaurants crowding out sights/parks)
def balance_pois(raw_pois: list[dict], max_per_category: int = 3) -> list[dict]:
buckets: dict[str, list[dict]] = {}
for poi in sorted(raw_pois, key=lambda p: p.get("prominence", 0), reverse=True):
cat = poi.get("category", "sights")
if len(buckets.get(cat, [])) < max_per_category:
buckets.setdefault(cat, []).append(poi)
return [item for group in buckets.values() for item in group]
3. Passwordless PWA Login & Killing Popup Spam Across the App
A bunch of people using the installed iOS/Android PWA told us login felt clunky, especially when email links bounced them out of the standalone PWA into Safari and broke the flow.
So we built passwordless email sign-in alongside Google Sign-In:
- Enter any email (iCloud, Proton, Outlook, whatever) and you get a clean email with both a direct one-click Magic Link and a 6-digit code right in the subject and body.
- On mobile PWA, you never have to leave the appโjust type the 6 digits and it auto-verifies.
- Behind the scenes we kept it tight: sliding-window rate limits, salted SHA-256 hashed single-use OTPs with a 10-minute expiry, brute-force lockout, and we fixed a sneaky iOS standalone IndexedDB deadlock on OTP login.
- We also fixed the PWA install bannerโand applied the exact same anti-spam rulebook across the whole app: clicking X stays dismissed until re-login, Later snoozes cleanly (48h for PWA, 5 days for Persona after a 2h grace period), Location is strictly opt-in from Settings or triggered only when you ask a local query without naming a city, and Notifications never stack popups or show pre-signup history to new users (capping the modal to the last 3 + a Changelog link).
How It Works: Beating the iOS PWA Auth Sandbox & Cross-Tab Snoozing
If you're using Firebase Auth inside an installed iOS PWA, email links open in Safariโwhich has a completely separate localStorage / IndexedDB sandbox from the standalone PWA! Issuing a short-lived 6-digit OTP alongside the Magic Link lets the user stay inside the PWA, verify the code on your backend, and receive a Firebase Custom Token (auth.create_custom_token(uid)) to call signInWithCustomToken() cleanly.
# Generic OTP generation & constant-time verification (never store plaintext OTPs)
import hashlib, hmac, secrets
def create_otp_record(email: str):
code = f"{secrets.randbelow(1_000_000):06d}"
salt = secrets.token_hex(16)
digest = hashlib.sha256(f"{salt}:{code}".encode()).hexdigest()
return code, {"salt": salt, "hash": digest, "attempts": 0, "expiresAt": time.time() + 600}
def verify_otp(code: str, record: dict) -> bool:
expected = hashlib.sha256(f"{record['salt']}:{code}".encode()).hexdigest()
return hmac.compare_digest(expected, record["hash"])
And for any dismissible UI prompt (PWA install, onboarding quizzes, etc.), avoid sessionStorageโit resets every time a user opens a new tab. Use localStorage with two distinct keys (snooze_until timestamp for "Later" vs. dismissed_until_reauth cleared on sign-out for "X") plus a window.addEventListener('storage', ...) listener so dismissing in Tab A immediately hides it in Tab B.
4. Split-Screen Education Apps โ Starting With a 3D Chemistry Lab
We already had Chess Arena running in our resizable split-screen workspace (APP | SPLIT | CHAT on mobile, draggable panels on desktop). The natural next question was: what else is genuinely better when you have a live interactive canvas sitting right next to your companion?
Our answer was an Education drawer in the toolbarโwith Chemistry Class as the first live module (and placeholders laid out for Physics, Math, Quantum, and Bio down the line).
- It's a lazy-loaded, interactive 118-element Periodic Table with family filters, search, and panel-clamped hover cards.
- Clicking any element drops down a specimen board with a real Three.js 3D WebGL Bohr Atom you can orbit and zoom with your mouse or finger, showing electron shells, physical properties, abundance, and real-world industrial supply chains.
- With Auto-Ask AI enabled, clicking an element immediately sends a contextual prompt to your companion so they break down the science and real-world uses right beside the 3D atom, followed by clickable follow-up pills.
How It Works: Keeping a 3D Canvas in Sync With Chat (Without Leaking WebGL Memory)
Two gotchas hit us immediately when embedding an interactive app beside an AI chat:
-
Stale React state race conditions: If a user clicks an element and you immediately call
sendMessage(), React'ssetState(selectedElement)hasn't committed yetโso the chat request goes out without the element context! Passing an explicit synchronousappContextOverrideparameter tosendMessage(prompt, { appId, context: snapshot })eliminates that race completely. - WebGL memory leaks: Every time a user switches from Helium to Gold or closes the split panel, Three.js geometries, materials, and renderers must be disposed cleanly or mobile Safari crashes after ~10 clicks.
// Generic React + Three.js cleanup & ResizeObserver pattern for resizable split panels
useEffect(() => {
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
container.appendChild(renderer.domElement);
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
if (width > 0 && height > 0) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
});
observer.observe(container);
return () => {
observer.disconnect();
scene.traverse((obj: any) => {
obj.geometry?.dispose?.();
obj.material?.dispose?.();
});
renderer.dispose();
renderer.domElement.remove();
};
}, [elementId]);
5. Going Nuclear on Markdown, LaTeX & Streaming Glitches
Once people started using Chemistry Class, coding, and finance prompts heavily, all the classic LLM formatting bugs showed up at once:
- Price ranges like
$2,000 and $3,000were getting eaten byremark-mathand rendered as broken italic LaTeX. - Single backslashes in JSON like
\beta,\frac,\nabla, or\textwere getting mangled byJSON.parseinto control characters (\b,\f,\n,\t). - Early streaming chunks occasionally flashed raw
[{"type":"markdown"...JSON syntax, and stopping a response mid-stream could leave a half-open card behind. - Sometimes the model would forget to open its JSON array and dump plain prose followed by
},{"type":"image",...}]at the end.
We went nuclear on the rendering pipeline and fixed all of it end-to-end:
- Wrote a code-span-safe currency vs. LaTeX disambiguator and pre-parse LaTeX backslash protector so
$2,000โ$3,000stays crisp text while$E = mc^2$,$$...$$,\(...\), and\[...\]render cleanly in KaTeX. - Rebuilt streaming with a string-aware balanced brace scanner +
requestAnimationFramebatching so prose, syntax-highlighted code, tables (row-by-row), and lists (item-by-item) stream live with zero JSON flickerโand hitting Stop cleanly salvages everything generated so far. - Switched to a persistent streaming UTF-8 decoder (no more broken Greek characters or emojis split across TCP chunks) and added anti-buffering headers on Cloud Run.
- Made table columns proportional to content, added inline markdown/math inside table cells, upgraded Copy response to copy clean Markdown instead of raw JSON, and added dual-layer (frontend + backend) healing so malformed JSONโincluding those dangling
},{"type":...}]tailsโnever leaks onto the screen or poisons follow-up turns.
How It Works: Three Streaming Bugs Every AI Frontend Eventually Hits
If you stream structured JSON blocks + Markdown + LaTeX from an LLM, you will hit these three bugs eventually:
-
UTF-8 multi-byte tearing: Calling
new TextDecoder().decode(chunk)per chunk corrupts emojis or Greek/CJK characters split across packet boundaries. Always instantiate one decoder outside the loop and pass{ stream: true }:
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) {
buffer += decoder.decode(); // flush trailing bytes
break;
}
buffer += decoder.decode(value, { stream: true });
}
-
LaTeX backslash collisions inside JSON: In JSON,
\t,\n,\f,\b,\rare valid escape sequencesโso\text,\nabla,\frac,\beta,\rhosilently turn into tabs/newlines/form-feeds unless you double-escape known LaTeX commands beforeJSON.parse. -
Cloud Run / Nginx proxy buffering: Even with FastAPI
StreamingResponse, proxies love buffering small chunks unless you explicitly send:
return StreamingResponse(
token_generator(),
media_type="text/plain; charset=utf-8",
headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"},
)
6. Cutting Startup Payloads by 99% & Never Locking the Input Box Again
This was a huge quality-of-life fix. Previously, opening the dashboard fetched your settings first, then fetched every single message of every single conversation before unlocking the screen. If you had 200 chats, you were downloading megabytes of old messages just to render the sidebar. And after sending your first message in a new chat, the input box stayed locked while the backend waited for the model to generate a chat title.
Here's what we changed:
-
Lightweight sidebar summaries:
GET /conversations?summary=truenow uses Firestore field projection to fetch only metadata (title,timestamp,pinned,hasUnread,agent,messageCount). In our benchmarks, that cut startup payload size by ~99% (from ~7.4 MB down to ~72 KB on 500 convos). Messages load on demand when you click a chat, and full-text search moved to an on-demand/conversations/searchendpoint. -
Instant SWR cache + parallel boot: Settings and conversation summaries now hydrate immediately from a
uid-scopedlocalStoragecache (purged cleanly on sign-out) while fresh data revalidates in parallel in the background. Warm refreshes feel practically instant. - Always-typeable composer: You can now type your next thought freely while the app is connecting, streaming, generating media, or savingโyour draft stays intact and unlocks to send the moment it's ready.
- Non-blocking titles: New chats save right away with a provisional title and patch the AI-generated title quietly in the background, killing that annoying 1โ2 second post-stream freeze.
- New empty-state showcase: Instead of showing dimmed, unclickable prompt cards while syncing, the empty state shows quick capability tips while connecting, then opens into 6 clean tabsโAsk, Speak, Dream, Play, Learn, Filesโeach with a one-click trigger (and compact enough to fit cleanly on mobile without clipping).
How It Works: Firestore Field Projections + Instant SWR Hydration
If you store chat arrays inside Firestore conversation documents, calling .stream() downloads the entire document body over the wire even if your sidebar only renders title and timestamp. Firestore's server-side .select([...]) projection drops the heavy messages array before serialization:
# Generic Firestore projection: ~99% smaller sidebar startup payload
query = (
db.collection("users").document(uid).collection("conversations")
.order_by("timestamp", direction=firestore.Query.DESCENDING)
.select(["title", "timestamp", "pinned", "hasUnread", "agent", "messageCount"])
)
Pair that on the React side with Promise.allSettled([fetchSettings(), fetchSummaries()]) and a tiny uid-keyed localStorage SWR cache (strip any messages array before caching, cap at ~150 items, and purge on sign-out so shared devices never leak state). And never put disabled={isStreaming} on your <textarea>โonly gate the Submit handler so users can always draft their next message!
7. Async Images & Videos You Can Actually Chat Through
Video generation has been running asynchronously in the background for a whileโyou get a processing card immediately, you can keep chatting, switch threads, or hit F5, and you get a clickable toast + a pulsating blue unread dot on the sidebar when it's done.
Users asked why images still made them sit there and wait, and pointed out two subtle annoyances:
- After generating a video or image, the Dream Engine button stayed toggled onโso your next normal chat message accidentally tried to generate another video or image.
- If you generated an image in a thread and later asked for a totally unrelated video, the video generator was forcefully grabbing that earlier image as a reference frame.
So we unified the whole Dream Engine flow:
-
Images are now fully async too: Submitting an image drops an immediate
image_pendingprocessing card into chat, runs in the background, swaps into place via real-time Firestore listeners (useAsyncJobs), lights up the sidebar unread dot + clickable "Dream Engine Image Ready" toast + an ephemeral bell entry (derived from unread state with zero extra DB writes) if you switched chats, and automatically refunds your quota if anything fails. - Concurrent chat safety: Chatting while an image or video finishes mid-stream now syncs from authoritative message refs + atomic Firestore patches so neither turn ever overwrites the other.
- Auto-deselect on dispatch: The moment your image or video job is queued, Dream Engine mode resets back to normal chat automatically so you can keep talking right away.
-
Smart reference priority:
- Explicitly attaching, dropping, or pasting a photo always takes top priority for both image remixes and image-to-video.
- Without an attachment, both Image mode and Video mode run standalone by default, and only inherit the previous chat image when you explicitly ask to edit/remix ("change the sky to lilac", "add rain") or animate it ("animate this image", "turn the previous image into a video"). Under the hood, the backend safely downloads and base64-encodes chat GCS URLs with MIME detection and SSRF checks so follow-ups never crash on raw URLs.
How It Works: Fixing the Stale-Closure Race Between Streams and Realtime Listeners
This was one of the sneakiest bugs we caught during our sweep. Picture this timeline:
- User triggers an async image โ
messageshas[user1, image_pending(id=M2)]. - User immediately sends a normal chat message while the image is still rendering.
sendMessage()starts streaming, capturing[user1, image_pending(id=M2)]in its React closure. - Mid-stream, the background image finishes! Firestore
onSnapshotswapsM2fromimage_pendingโ completedimage. - One second later,
sendMessage()finishes streaming and saves[...staleMessages, user2, ai2]โaccidentally overwriting the completed image back toimage_pending!
The fix is simple and applies to any React app mixing streaming + real-time listeners: keep a synchronous messagesRef updated inside your setMessages wrapper, and always persist from messagesRef.current (and use Firestore transactions on the backend to patch only the target messageId):
// Generic React pattern: keep a synchronous ref mirror so async listeners & streams never clobber each other
const messagesRef = useRef<Message[]>([]);
const setMessages = useCallback((updater: Message[] | ((prev: Message[]) => Message[])) => {
const next = typeof updater === 'function' ? updater(messagesRef.current) : updater;
messagesRef.current = next;
setMessagesState(next);
}, []);
// Inside sendMessage() after stream completes:
await saveConversation(convoId, [...messagesRef.current]); // ALWAYS includes mid-stream async job updates!
8. A Zero-Token Intent Router (So Nobody Has to Hunt for Toolbar Icons)
The last big piece was realizing people shouldn't have to remember which tiny toolbar icon does what.
We built a deterministic, zero-token client-side Intent Router (runs in ~0.015 ms per message, zero extra LLM calls) that only steps in when your intent is unambiguous:
- Say "create an image of a neon lighthouse in Santorini" โ automatically triggers Dream Engine Image mode.
- Say "make a video of waves crashing on cliffs" or "animate this image with gentle wind" โ automatically triggers Dream Engine Video mode.
- Say "can we chat with voice?" โ launches Live Voice Mode.
- Say "let's play chess" โ opens Chess Arena.
- Say "can you show me helium atoms?" โ opens Chemistry Class straight onto Helium and fires the native Helium element breakdown with full 3D lab context.
And just as importantly, we tuned it for 0% false positives on capability questions or everyday phrasing. Asking "can you make videos?", "can you help me with chemistry?", "iron out the bugs in my Python script", or "draw me a conclusion" stays in normal chatโand we gave all three companions a tiny, clean awareness of their built-in workspace tools so they never act surprised about what they can do.
How It Works: Why We Skipped a Router LLM for Deterministic Client Matching
A lot of teams put a small "router LLM" in front of every message to decide which tool to open. The problem? It adds 300โ700 ms of latency to every single casual message, burns extra tokens, and still misfires on capability questions.
For deterministic UI actions (opening a split-screen app, toggling voice, switching to image/video mode), precision-first client-side matching runs in microseconds at zero cost. The secret is building an adversarial negative test matrix firstโmaking sure bare capability questions and homonyms ("Iron out the bugs", "Lead me through this", "Draw a conclusion") always return null:
// Generic precision-first intent router pattern (0ms latency, 0 tokens)
function detectToolIntent(raw: string): ToolIntent | null {
const text = raw.trim();
// 1. Always exit early on bare capability questions ("Can you make videos?")
if (/^(can|could|do|will)\s+you\s+(make|create|generate)\s+(images?|videos?)\s*\??$/i.test(text)) {
return null;
}
// 2. Require an explicit action verb + target payload before hijacking normal chat
if (/(?:create|generate|make)\s+(?:an?\s+)?(?:image|photo)\s+(?:of|showing)\s+.{3,}/i.test(text)) {
return { type: 'image', prompt: text };
}
return null; // Default: let normal chat handle it
}
The Quick Rundown (Everything That Landed)
If you just want the quick scannable rundown of what landed across the stack:
- Chat, Formatting & Input: Zero-flicker progressive streaming with LaTeX/currency disambiguation, proportional tables, clean Markdown copy, disabled forced auto-scroll during streaming, always-typeable composer, Enter-for-newline on mobile, over-limit-only character counter, consistent toolbar disabled states, and 6 interactive empty-state spotlights (Ask ยท Speak ยท Dream ยท Play ยท Learn ยท Files).
- Dream Engine & Voice: Non-blocking async image & 10-second video generation (with refresh immunity, unread sidebar dots, ephemeral bell entries, clickable ready toasts, and auto-refunds), auto-deselecting mode controls, smart standalone-by-default reference guards for both image remixes and image-to-video, async downloads with spinner/toast feedback, and native Live bidirectional WebSocket voice.
-
Apps, Cards & Intent Routing: Zero-token client-side intent router, new Education drawer launching with Chemistry Class (118-element Periodic Table + 3D WebGL Bohr Atom), overhauled Chess Arena, live Travel Cards (flights, stays, eSIM), rebuilt Dynamic Maps (real A โ B routes +
HOT:Area Intelligence), and a modular Weather Card with multi-day prognosis and condition-aware follow-up pills. -
Auth, Speed & Anti-Spam UX: Passwordless Magic Link + 6-digit PWA code sign-in, 99% smaller sidebar startup payloads with
uid-scoped SWR caching and on-demand search, floating unified split-screen nav bars, mobile back-gesture overlay dismissal, and non-spammy opt-in lifecycles for Location, Persona Discovery, PWA install, and Notifications. -
Backend, SEO & Trust: Modern async streaming engine, tailored per-companion defaults, Firebase-backed async jobs & mailing, automated frontend/backend stress suites, updated Privacy/Terms/Agents pages, and full SEO/AI-index coverage (
llms.txt,llms-full.txt,robots.txt,sitemap.xml).
Want the full breakdown of every update? Check out the live release log at arpa.chat/changelog.
What We're Tinkering With Next
On our near-term list:
- Live Voice tool calling: Bringing the same tool routing into active Live Voice sessions via native function calling so you can speak "make an image of..." or "open Chemistry on Gold" hands-free.
- Deploy-safe async job reaper: Auto-recovering and refunding any in-flight background job if a Cloud Run revision rolls out mid-render.
- More Education labs: Physics, Math, Quantum, and Bio alongside Chemistry Class.
Thanks to everyone who has been testing, breaking things, and sending brutally honest feedbackโalmost every fix in this batch came directly from someone hitting a real edge case in chat. If you try any of the new stuff on arpa.chat and spot anything weird, drop a comment and let me know!
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.






