Bike4Mind β High-Level Architecture
1. Landscapeβ
β’ Mission β Bike4Mind (B4M) is a βcognetic workbenchβ: an AI-augmented environment for knowledge work, file handling, notebook-style chat, image generation and more.
β’ Core user journeys today
Β Β β Chat & Notebooks (aka Sessions)
Β Β β Mementos (personal memory objects)
Β Β β File / Project / Notebook browsing & sharing
Β Β β Credit / Subscription management
β’ Dynamic-UX vision β Let the user/agent co-create a bespoke, one-page βmini-appβ (e.g. an RPG character sheet) on-the-fly, fully wired to B4M data and tools.
2. Tech-Stack Snapshotβ
Frontend
β’ Next.js 14 (both app
& pages
folders)
β’ JOY UI (MUI Joy) for the design system
β’ Zustand + React context providers for state
β’ TanStack Query for server-state fetching
Backend / API
β’ Next.js API Routes under packages/client/pages/api/**
with an express-style wrapper baseApi()
(see packages/client/server/middlewares/baseApi.ts
lines 22-60)
β’ SST (Serverless Stack) v2: defines Lambda queues, cron jobs, WebSocket API, S3 buckets, etc. β largest config in root sst.config.ts
(~1 300 lines)
β’ Persistence β MongoDB via Mongoose (b4m-core/packages/core/database/src/utils/mongo.ts
lines 1-54)
Infra & DevOps
β’ AWS CDK through SST: VPC, CloudFront, Route53, SQS, Dynamo, Cron
β’ pnpm workspaces; linting via ESLint & Semgrep; CI via Seed.run + GitHub Actions
LLM / Agent Tooling
β’ Uses the official openai
npm SDK (no LangChain/AutoGen)
β’ Model registry & pricing tables in b4m-core/packages/core/common/models.ts
lines 1-160 handle OpenAI, Anthropic, Bedrock, Ollama, xAI, etc.
β’ SessionManager
orchestrates chat completions & image generation (packages/client/server/managers/sessionManager.ts
lines 1-200)
3. Repository Map (condensed)β
.
ββ packages/
β ββ client/ β Next.js app + server code
β β ββ pages/ β File-based routes & /api routes
β β ββ app/ β RSC & component library
β β ββ server/ β Lambda handlers, middlewares, utils
β ββ services/ β Shared TypeScript utilities
β ββ subscriber-fanout/ β SQS fan-out service (Docker/ECS)
β ββ database/ β Local Mongo helpers & seed
ββ b4m-core/
β ββ packages/core/
β ββ common/ β Shared enums, zod schemas, TS types
β ββ database/ β Mongoose models & utilities
β ββ services/ β Pure domain services (import, countersβ¦)
β ββ utils/ β Logger, SQS helper, etc.
ββ sst.config.ts β All AWS infra & routing glue
4. Core Domain Primitivesβ
Agent
β’ Lives mainly in packages/client/server/managers/sessionManager.ts
β’ Handles chat β OpenAI call β store reply β queue side-jobs (summaries, image gen)
Memento
β’ Memory objects (IMemento
) β see b4m-core/packages/core/common/types/entities/MementoTypes.ts
β’ Corresponding Mongoose model in b4m-core/packages/core/database/src/models/MementoModel.ts
File / AppFile
β’ Stored metadata + S3 paths; CRUD via /api/app-files/**
Project
β’ Aggregates Notebooks, Files, etc. β controllers in /api/projects/**
Notebook / Session
β’ Chat threads stored in Mongo sessions
collection β rich helper methods for share/fork/snippet.
Credit / Billing
β’ Stripe integration via routes /api/stripe/**
, models under b4m-core
Other entities β Users, Organizations, Invitations, Quests, Activities β follow the same repository pattern.
5. Current Data & Event Flowβ
Example edit-notebook happy-path:
Client Action β useApi
(axios in ApiContext
) injects JWT & idempotency β
API Route /api/sessions/update
β baseApi()
middleware (DB connect, auth, logger) β
Domain service sessionManager.updateSession
touches Mongo β
Success response β WebSocket fan-out (packages/client/server/websocket/**
) publishes change so subscribed clients update in < 1 s.
Errors surface via errorHandler
middleware and client-side toast.
6. State Management & React Patternsβ
β’ Provider bundle in _app.tsx
: ApiProvider β AccessToken β UserProvider β β¦
β’ TanStack Query + custom useSubscribeCollection
merges WS deltas.
β’ Long-lived client state in small, typed Zustand stores (useSidebar
, useLLM
, etc.).
β’ Auth-dependent components show an ExpiredSession
modal when context invalid.
7. Dynamic-UX Vision (current gaps)β
Nothing yet auto-generates React code or JSON-driven layouts. Desired flow:
- Chat command triggers agent tool-call.
- Agent emits
createDynamicView
event β persistsdynamic_views
Mongo model β enqueues SQS job. - Client receives WS event and renders via a schema-driven Joy-UI renderer.
Security, latency & sharing follow existing JWT + CASL + WebSocket patterns.
8. Rendering & Composition Strategy (today vs future)β
Today β Mostly CSR pages; some RSC under app/
; Joy UI components static.
Future β Agent produces JSON schema β validated β rendered by a thin Joy UI renderer; TypeScript safety via zod-to-ts generation.
9. Agent Pipeline (implemented)β
Chat prompt β SessionManager
builds OpenAI request (+ optional function-calls) β external API call
β’ Success: store message, fire SQS jobs (fabFileVectorize
, notebookSummarization
, β¦) β WS update
β’ Failure: logged via Winston-style Logger
, surfaces HTTP error to client.
10. Pain Points & Wishlistβ
β’ Migrate more context state to Zustand stores.
β’ Several TODO turn back on when we get these secrets in sst.config.ts
.
β’ Error surfacing is still rough in some axios interceptors.
β’ Dynamic layout/drag-drop builder not started.
β’ Need runtime validation for agent-generated views.
11. Constraints & Non-Goalsβ
β’ Coding rules enforced (auth-aware API calls, error boundaries, strict typing).
β’ sst.config.ts
sets custom domains & secrets but no hard geo-residency yet.
β’ Mobile/offline experiences currently out of scope β web-desktop first.
Key Take-aways for Dynamic-UX Implementationβ
- WebSocket foundation is already in place; pushing a
DynamicView
schema via existing topics is straightforward. - Extend
SessionManager
so the agent can emit/queue Dynamic-UI specs. - Client introduces
<DynamicViewRenderer viewId="β¦" />
with Joy-UI widgets. - Maintain type safety by generating zod schemas β
ts
interfaces. - Build a library of Joy-UI "frame components" (SpreadsheetGrid, AvatarRenderer, MarkdownBlock, β¦) that the agent can reference by name.
This shared context should support deeper design of fully agent-driven, chat-initialised Dynamic UIs within Bike4Mind.