Skip to main content

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:

  1. Chat command triggers agent tool-call.
  2. Agent emits createDynamicView event β†’ persists dynamic_views Mongo model β†’ enqueues SQS job.
  3. 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​

  1. WebSocket foundation is already in place; pushing a DynamicView schema via existing topics is straightforward.
  2. Extend SessionManager so the agent can emit/queue Dynamic-UI specs.
  3. Client introduces <DynamicViewRenderer viewId="…" /> with Joy-UI widgets.
  4. Maintain type safety by generating zod schemas β†’ ts interfaces.
  5. 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.