U2INVEST / CURRENT_PROJECT_PRD.md
DasbootU9607
feat: initial clean commit
0001f12

U2INVEST Current Product PRD

1. Executive Summary

U2INVEST is a three-pillar financial product that combines:

  1. Knowledge Academy
  2. Trading Lab
  3. U2CHAT AI assistant

The current implementation is a Flask-served single-page web app with:

  • one primary frontend file: templates/index.html
  • one primary backend/API file: web_app.py
  • a LangGraph agent workflow: agent_graph.py
  • stock/RAG tools: tools.py
  • a Chroma-backed PDF knowledge pipeline: vector_store.py
  • a CLI-style agent test entrypoint: main.py

This PRD is not a concept document. It is a product-truth document for the current repository. It extracts the actual functions, features, states, gaps, and upgrade paths so the whole UI can be rebuilt without losing product scope.

2. Product Vision

Help beginner and intermediate investors learn investing, practice safely, and ask an AI assistant for analysis inside one integrated product.

2.1 Commercial Website Vision

U2INVEST should not behave only like an internal demo app or portfolio prototype. As a commercial web product, it should also present itself like a credible business:

  • discoverable
  • trustworthy
  • contactable
  • explainable
  • legally defensible
  • conversion-oriented

That means the final product should include both:

  • the product application layer
  • the public business/marketing/sales website layer

3. Rebuild Objective

Rebuild the entire UI while preserving the full current functional scope, making the product:

  • simpler
  • calmer
  • more premium
  • more structurally consistent
  • more maintainable
  • more trustworthy as a product

The rebuild should not accidentally reduce scope. It should preserve the current breadth of Academy, Lab, and U2CHAT while fixing partial features and surfacing hidden capabilities.

The rebuild should also expand the current landing shell into a proper commercial website experience with public-facing business, sales, trust, and contact functionality.

4. Target Users and Core Jobs

Primary users

  • Beginner investors who want structured financial education
  • Early-stage self-directed investors who want a safe trading simulator
  • Users who want an AI assistant to explain stocks, market concepts, and strategies

Secondary users

  • Recruiters or reviewers evaluating product thinking and technical execution
  • Users who want a local finance-learning demo with AI and charts
  • Prospective customers evaluating whether to trust or buy the product
  • Business partners, media contacts, and inbound collaborators
  • Prospective hires or stakeholders evaluating the company and product credibility

Core jobs to be done

  • "Teach me the fundamentals of investing."
  • "Let me practice trading without risking money."
  • "Help me analyze a stock with live data and research context."
  • "Give me a workspace where learning, simulation, and AI analysis connect."
  • "Help me understand what this company/product is and whether I should trust it."
  • "Give me a clear way to contact the business, book a demo, or start using the product."
  • "Show me enough credibility, legal clarity, and product value to convert me into a lead or customer."

5. Current System Map

Product shell

  • Flask serves a single-page frontend shell
  • SPA-like view switching happens in the browser through showView()
  • A browser session receives a generated user_id

Core product surfaces

  • Landing page
  • Knowledge Academy
  • Trading Lab
  • U2CHAT
  • Public business/marketing website layer, currently only minimally represented by the landing page

AI and data layer

  • LLM access is configured through ChatOpenAI using a DeepSeek-style OpenAI-compatible API
  • LangGraph manages reasoning plus tool routing
  • SQLite persists LangGraph checkpoints
  • AkShare provides live stock data when available
  • Chroma stores local knowledge-base embeddings
  • PDFs in knowledge/ power retrieval

Deployment layer

  • Local Python execution
  • Dockerfile
  • docker-compose.yml
  • .env configuration

6. Detailed Current Feature Inventory

6.1 Landing and Global Navigation

User-facing features

  • Fixed top navigation with logo and links to Academy, Lab, and U2CHAT
  • Branded landing hero with product tagline
  • Three large entry cards for the three product pillars
  • In-browser view switching without page reload

Supporting frontend functions

  • showView(v)

Supporting backend functions

  • index()

Current status

  • Implemented

Current gaps

  • No deep links for major product surfaces
  • No browser-history-aware routing
  • No route-level loading state
  • No persistent "last visited workspace" behavior
  • No commercial footer
  • No contact information surface
  • No social links
  • No company/about section
  • No trust or proof section
  • No demo, signup, or lead-capture CTA flow
  • No legal links or disclosures in the public shell

6.2 Knowledge Academy

Current content model

The Academy currently includes 50 hardcoded modules in ACADEMY_DATA. Each module includes:

  • id
  • parent
  • cat
  • difficulty
  • name
  • video
  • source
  • views
  • completed
  • ratings
  • video_intro
  • outcomes
  • takeaways

User-facing features currently implemented

  • Academy landing view
  • Grid view of all modules
  • Category label on module cards
  • Module view counts on cards
  • Completion badge on cards
  • Lesson overlay panel
  • Embedded YouTube lesson video
  • Lesson intro copy
  • Outcomes list
  • Takeaways list
  • Completion state CTA
  • Comments thread
  • Comment replies
  • Comment sorting: Top / Newest
  • Share modal
  • Share actions for WhatsApp, Facebook, X, LinkedIn, email, copy link
  • Visual roadmap mode
  • Curated roadmap mode: "Designed By U2INVEST"
  • Custom roadmap mode: "You to Design"
  • Custom roadmap actions:
    • add node
    • drag node
    • connect nodes
    • break link
    • delete node
  • Toast notifications
  • Confirmation modal for roadmap destructive actions

Frontend functions powering Academy

  • loadData()
  • openModule(id)
  • openShare()
  • closeShare()
  • copyLink()
  • renderComments(list)
  • replyAt(user, commentId)
  • replyToReply(user, parentCommentId)
  • cancelReply()
  • postComment()
  • setRoadmapMode(mode)
  • initRoadmap()
  • dragstarted(event, d)
  • dragged(event, d)
  • dragended(event, d)
  • renderCustomRoadmap(g, svg)
  • resetPorts()
  • openConfirm(title, desc, onOk, onCancel)
  • openNodeModal()
  • closeNodeModal()
  • addCustomNode()
  • switchAcademy(tab)
  • closeModule()
  • renderStatusBox(isDone)
  • toggleStatus(isDone)
  • sortComments(type)
  • showToast(msg)

Backend/API functions powering Academy

  • get_academy()
  • get_course(cid)
  • post_comment()
  • like_comment_main()
  • like_reply_unique()
  • toggle_complete()
  • rate_course()

What is fully implemented

  • Module browsing
  • Module overlay experience
  • Comment posting and replies
  • Completion toggle
  • Average rating display
  • Curated roadmap rendering
  • Custom roadmap editing in current browser session

What is partial or latent

  • parent exists in the data model but is not used as the real prerequisite structure in the UI
  • source exists in the data model but is not surfaced in the UI
  • difficulty is used in roadmap coloring but not clearly surfaced elsewhere
  • rate_course() exists in the backend, but there is no visible rating submission UI in the current frontend
  • like_comment_main() and like_reply_unique() exist in the backend, but the frontend references toggleLike() and toggleReplyLike() handlers that do not exist
  • Comment dislike icons are visual only and do not trigger anything
  • Share URLs point to /module/<id>, but that route is not implemented in Flask

Known Academy issues to carry into the rebuild plan

  • Comment like buttons are visible but broken because the JS handlers are missing
  • Rating is display-only in the current UI
  • Shared module URLs are not truly deep-linkable
  • Comment timestamps are rendered as hardcoded "2 hours ago" / "1 hour ago" strings, not real relative times
  • Academy progress, comments, and ratings are stored in runtime memory only
  • Academy progress is not per-user durable data
  • Academy state is globally mutable on the server
  • get_course(cid) does not guard missing IDs cleanly before .copy()
  • Custom roadmap state is not persisted to local storage or backend
  • The auto roadmap is a generated visualization, not a precise prerequisite map

Academy advancement opportunities

  • Make progress, comments, ratings, and custom roadmap persistent
  • Convert parent into a true learning dependency graph
  • Add search, filter, and sorting across modules
  • Add difficulty badges and progress percentages
  • Surface lesson source and instructor credibility more clearly
  • Add note-taking, bookmarks, and study highlights
  • Add quizzes, checkpoints, and completion scoring
  • Add user-specific learning plans and recommended next lessons
  • Add proper rating submission UI and review aggregation
  • Add moderation, abuse control, and comment reporting if community features stay
  • Add actual shareable deep links and direct-open module routes

6.3 Trading Lab

Current product concept

The Lab is a paper-trading workspace for A-share-style stock simulation, with a separate beginner guide path.

User-facing features currently implemented

  • Lab gateway with two paths:
    • advanced dashboard
    • beginner guide
  • Beginner guide step flow with 3 educational steps
  • Stock pool grouped by sectors:
    • Popular
    • Tech
    • Energy
    • Finance
  • Quote cards for stocks in the selected sector
  • Stock selection for chart/trade context
  • K-line chart area
  • Trade ticket with symbol, price, shares, and total
  • Buy action
  • Sell action
  • Holdings panel
  • History panel container
  • Portfolio stats:
    • Total Assets
    • Cash
    • Profit
    • Return
  • Reset portfolio
  • Refresh dashboard

Data model and business rules

  • Starting cash: $100,000
  • Holdings are tracked per symbol
  • Trade history is stored on buy/sell
  • Buy checks available cash
  • Sell checks whether holdings exist and whether the user has enough shares
  • Frontend requires minimum 100 shares

Frontend functions powering Trading Lab

  • loadLabData()
  • loadSectorStocks()
  • selectStock(stock)
  • initKlineChart()
  • loadKlineData(symbol, days = 60)
  • calculateTotal()
  • executeTrade(action)
  • updatePortfolioUI()
  • resetPortfolio()
  • refreshLab()
  • updateGuideUI()
  • nextGuideStep()
  • prevGuideStep()
  • setLabView(view)

Backend/API functions powering Trading Lab

  • get_stock_pool()
  • get_real_quote()
  • get_kline_data()
  • get_portfolio()
  • execute_trade()
  • reset_portfolio()
  • get_market_data()

What is fully implemented

  • Gateway flow between beginner and advanced entry
  • Beginner guide progression
  • Sector-based stock list loading
  • Quote retrieval with live-data fallback behavior
  • K-line retrieval with live-data fallback behavior
  • Paper buy/sell execution
  • Cash/holdings update logic
  • Portfolio reset

What is partial or latent

  • Trade history is stored in backend state but not rendered into the visible history-list
  • Return stat exists in the UI but is not updated in updatePortfolioUI()
  • Time-range buttons 60D, 120D, 250D are visible, but changeTimeRange() does not exist
  • get_market_data() exists as a synthetic endpoint but is not used by the current main UI
  • user_portfolio.json exists in the repo but is not used by the current app

Known Trading Lab issues to carry into the rebuild plan

  • Stock selection uses event.currentTarget without passing event, so the behavior is fragile
  • Portfolio value is calculated from average cost basis, not live mark-to-market pricing
  • Profit shown is therefore not true unrealized P&L
  • Return shown is currently a placeholder
  • History panel is currently a placeholder
  • Backend trusts the client-supplied execution price in /api/lab/trade
  • No watchlist, compare view, or market context around a selected stock
  • No order types beyond instant buy/sell
  • No slippage, fees, order status, or risk feedback
  • Lab state is per-session in memory only and resets on server restart

Trading Lab advancement opportunities

  • Implement live mark-to-market portfolio valuation
  • Render complete transaction history with timestamps and realized/unrealized P&L
  • Implement changeTimeRange() and persist selected chart interval
  • Add watchlists and favorite symbols
  • Add news and fundamentals side panels for the selected stock
  • Add comparison mode across multiple stocks
  • Add educational hints tied to user actions
  • Add more order types: market, limit, stop, stop-limit
  • Add simulated fees, taxes, and slippage
  • Add portfolio allocation visualization and performance analytics
  • Add saved paper accounts and multiple portfolios
  • Make the server authoritative for pricing instead of trusting client price input

6.4 U2CHAT

Current product concept

U2CHAT is a financial assistant that combines:

  • LLM reasoning
  • tool calling
  • local knowledge retrieval
  • stock-related quick context selection
  • inline chart rendering in chat

User-facing features currently implemented

  • Dedicated chat workspace
  • Sidebar with recent sessions
  • New chat action
  • Session reload from sidebar
  • Clear current chat
  • Quick stock-select chips by sector
  • Selected-stock chip strip
  • Prompt input with auto-resize
  • Enter to send
  • Shift+Enter for newline
  • Stop button state during generation
  • Assistant/user message bubbles
  • Simple markdown-like rendering for headings and bullets
  • Inline chart rendering from json-chart blocks
  • Empty state for no conversation

Frontend functions powering U2CHAT

  • loadAgentData()
  • loadAgentStocks()
  • addStockToChat(stock)
  • updateSelectedStocks()
  • removeStock(i)
  • sendMessage()
  • updateSendButtonState()
  • addMessageToUI(role, content, tools = [])
  • renderChart(containerId, data)
  • loadChatSessions()
  • loadChatSession(sessionId)
  • clearChat()
  • newChat()
  • handleAgentKey(e)
  • autoResize(t)

Backend/API functions powering U2CHAT

  • agent_chat()
  • get_chat_sessions()
  • get_chat_history()
  • clear_chat_history()

Agent workflow functions

  • AgentState
  • call_model(state)
  • route_logic(state)

Agent tools

  • get_realtime_quote(symbol)
  • get_stock_news(symbol)
  • get_historical_kline(symbol)
  • get_fundamental_data(symbol)
  • query_knowledge_base(query)

What is fully implemented

  • Chat session creation
  • Session title generation from the first message
  • Session history retrieval while the server is running
  • LangGraph-based tool routing
  • LLM response generation
  • Inline chart rendering from model-generated JSON blocks
  • Sector-based quick stock selection
  • PDF-based retrieval tool availability

What is partial or latent

  • agent_chat() internally iterates stock_agent_app.stream(...), but the frontend does not receive true streaming output; it waits for the final JSON response
  • Tool call metadata is collected as tools_used, but the frontend does not surface it
  • The "stop" button aborts the browser request, but there is no backend cancellation mechanism
  • Chat persistence is split:
    • visible session metadata and messages are in memory
    • LangGraph checkpoints are in SQLite
  • Quick stock selection adds stock text into the prompt, but does not create structured chat context objects

Known U2CHAT issues to carry into the rebuild plan

  • If the server restarts, the sidebar session list and visible session history are lost
  • SQLite checkpoints survive, but the current UI model does not reconnect to them cleanly
  • renderChart() supports simple line/bar assumptions only
  • The system prompt mandates structured English responses, but the UI does not visibly explain the assistant's answer format
  • The app stores tool call names and args, not a clear user-facing execution trace
  • No citation/source cards are shown for RAG output
  • No streaming token UI or stepwise reasoning trace is exposed
  • addMessageToUI() injects rendered HTML directly, which should be treated carefully in a full rebuild

U2CHAT advancement opportunities

  • Add true streaming responses to the UI
  • Add server-side cancellation or job interruption support
  • Surface tool usage, tool results, and sources visibly
  • Show retrieval sources with document titles and snippets
  • Add follow-up suggestions and prompt shortcuts
  • Add chart cards, ticker cards, and fundamentals cards as structured UI blocks
  • Add conversation search, pinning, renaming, and grouping
  • Add better state recovery after refresh and restart
  • Add a dedicated research mode, beginner mode, and fast quote mode
  • Add file upload and portfolio-aware chat once persistence exists

6.5 Shared and Platform Features

Current shared UX/system features

  • Toast notification surface
  • Confirmation modal
  • Custom-node modal
  • Session-based user_id
  • Environment-variable-based secret key
  • Broad CORS enablement
  • Dockerfile
  • Docker Compose mounts for:
    • chroma_db
    • checkpoints.sqlite

AI/knowledge infrastructure features

  • PDF discovery across knowledge/ recursively
  • Empty retriever fallback if no PDFs exist
  • PDF loading with PyPDFLoader
  • Content deduplication by MD5 hash
  • Metadata enrichment for source tracking
  • Chunking with overlap
  • Persistent Chroma vector store
  • Incremental addition when new files appear
  • Retriever configured with k=5

Developer and demo features

  • CLI interactive session in main.py
  • Synthetic market endpoint get_market_data()

Current platform gaps

  • No authentication layer
  • No persistent database for Academy or Lab user state
  • No test suite in the current repo
  • No analytics or product instrumentation
  • Frontend is monolithic and globally stateful
  • Vector-store refresh logic detects new files, but not modified/deleted files robustly

6.6 Commercial Website and Business Layer

Current product reality

The current repo has a landing page, branding, and product-entry navigation, but it does not yet function like a complete commercial business website.

Current business-site features actually present

  • logo and brand mark
  • positioning tagline
  • top navigation
  • high-level entry points into the three product pillars

Commercial website features required for a professional business product

This section defines the required public-facing website layer that should exist alongside the product application.

A. Global brand and navigation requirements

  • public homepage
  • consistent header navigation
  • clear primary CTA
  • secondary CTA for contact/demo/learn more
  • professional footer
  • company identity and copyright area
  • social links
  • legal links
  • contact links
  • app entry / sign in / get started entry points

B. Marketing and sales page requirements

  • homepage with clear value proposition
  • product overview page
  • feature overview sections for Academy, Lab, and U2CHAT
  • use-case or solution sections
  • pricing page or pricing inquiry flow
  • demo-request flow
  • FAQ page or FAQ section
  • about/company page
  • contact page
  • resources/blog/news section
  • optional case studies/testimonials page

C. Trust and credibility requirements

  • social proof or customer logos
  • testimonials or endorsements
  • team/founder credibility
  • explanation of product methodology
  • explanation of data sources
  • privacy and security positioning
  • financial education / not-financial-advice disclaimers where relevant
  • risk disclosure for finance-related content and simulation features
  • transparent explanation of what is live data vs simulated vs educational

D. Lead generation and conversion requirements

  • contact form
  • demo-booking form
  • newsletter/signup capture
  • waitlist or get-started capture
  • strong CTA system across the site
  • success / thank-you states after form submission
  • lead routing to email/CRM
  • downloadable asset or resource capture if content marketing is used

E. Social and communication requirements

  • LinkedIn link
  • X/Twitter link if used
  • GitHub link if relevant to brand/company presence
  • YouTube or media channel link if educational content is part of go-to-market
  • business email contact
  • optional phone number
  • optional business address or registered business location
  • press / partnership contact path

F. Legal, compliance, and policy requirements

  • privacy policy
  • terms of service
  • cookie policy
  • disclaimer
  • risk disclosure
  • acceptable-use policy if user-generated content or AI chat remains public-facing
  • accessibility statement
  • data and AI usage disclosure

G. SEO, discoverability, and content requirements

  • page titles and meta descriptions
  • Open Graph / social preview metadata
  • sitemap
  • robots configuration
  • structured data where useful
  • clean semantic headings
  • internal linking strategy
  • indexable product explainer content
  • resource/blog structure if SEO is part of acquisition

H. Analytics, sales operations, and support requirements

  • page analytics
  • CTA click tracking
  • form conversion tracking
  • attribution tracking
  • CRM or inbox integration for inbound leads
  • contact management flow
  • support/help contact path
  • error/success instrumentation for forms and CTAs

I. Finance-product-specific commercial requirements

  • clear statement of educational vs advisory scope
  • data freshness / source disclaimers
  • simulation disclaimers for the Trading Lab
  • AI-answer limitations and responsible-use language
  • clear explanation of whether the platform gives education, research assistance, or actionable advice

Current status

  • mostly missing

Known commercial website gaps in the current repo

  • no footer with business information
  • no contact page or contact form
  • no social links
  • no about/company page
  • no pricing or demo request flow
  • no lead-capture forms
  • no testimonials, customer proof, or trust content
  • no legal pages
  • no cookie/privacy consent flow
  • no support/help path
  • no SEO-oriented public content structure
  • no analytics or conversion tracking
  • no finance-specific commercial disclaimers in the public website shell

Commercial website advancement opportunities

  • turn the landing page into a true commercial homepage
  • create a full footer and public information architecture
  • add contact, demo, and get-started flows
  • add proof, trust, and authority sections
  • add legal/compliance surface suitable for a finance-related product
  • add SEO and content marketing structure
  • add analytics and CRM integration
  • add conversion-focused CTA system across the entire public experience

See COMMERCIAL_WEBSITE_SITEMAP_AND_PAGE_SPEC.md for the concrete sitemap, page-by-page public website specification, CTA architecture, footer requirements, form requirements, and lead funnel design.

7. Complete Engineering Function Inventory

This section is the full code-level function inventory for rebuild planning.

7.1 web_app.py

  • index(): serve the main SPA and initialize session['user_id']
  • get_academy(): return the full Academy module list
  • get_course(cid): return a specific course plus computed average rating and comments
  • post_comment(): create top-level comments or replies
  • like_comment_main(): increment/decrement comment like count
  • like_reply_unique(): increment/decrement reply like count
  • toggle_complete(): set lesson completion state
  • rate_course(): append a rating and return the updated average
  • get_market_data(): return synthetic OHLCV-style market data
  • get_stock_pool(): return grouped stock symbol lists
  • get_real_quote(): return live or simulated quote data for one or more symbols
  • get_kline_data(): return live or simulated historical daily K-line data
  • get_portfolio(): return current user's simulated portfolio
  • execute_trade(): execute a paper buy or sell
  • reset_portfolio(): restore paper portfolio to default starting cash
  • agent_chat(): create/load a chat session, invoke the agent, save the assistant response
  • get_chat_sessions(): return chat-session list sorted by timestamp
  • get_chat_history(): return messages for one chat session
  • clear_chat_history(): clear one session or all sessions for the current user

7.2 agent_graph.py

  • AgentState: typed graph state definition for message history
  • call_model(state): run the LLM with the system prompt plus tools
  • route_logic(state): send the flow either to tool execution or to END

Agent graph behavior

  • LLM model: deepseek-chat
  • Temperature: 0
  • System prompt rules:
    • English only
    • concise headings and bullets
    • no **bold** emphasis inside prose
    • emit json-chart blocks for stock analysis visuals
    • respond with a structured market-analysis template

7.3 tools.py

  • get_realtime_quote(symbol): fetch latest price, change, high, low
  • get_stock_news(symbol): fetch latest headlines
  • get_historical_kline(symbol): fetch last 60 daily data points and return JSON string
  • get_fundamental_data(symbol): fetch PE, PB, and ROE-style metrics
  • query_knowledge_base(query): retrieve relevant PDF text snippets

7.4 vector_store.py

  • build_vector_db(persist_directory, knowledge_base_path): build or load the vector store and return a retriever

Internal behavior inside build_vector_db()

  • create empty knowledge directory if missing
  • return empty retriever if no PDFs exist
  • recursively discover PDFs
  • load PDFs
  • deduplicate by content hash
  • attach source metadata
  • split text into chunks
  • build or load persistent Chroma DB
  • incrementally add documents if new files are detected
  • return retriever configured with k=5

7.5 main.py

  • start_interactive_session(): run a CLI chat session against the LangGraph app

7.6 templates/index.html frontend functions

Global shell

  • showView(v)

Academy

  • loadData()
  • openModule(id)
  • openShare()
  • closeShare()
  • copyLink()
  • renderComments(list)
  • replyAt(user, commentId)
  • replyToReply(user, parentCommentId)
  • cancelReply()
  • postComment()
  • setRoadmapMode(mode)
  • initRoadmap()
  • dragstarted(event, d)
  • dragged(event, d)
  • dragended(event, d)
  • renderCustomRoadmap(g, svg)
  • resetPorts()
  • openConfirm(title, desc, onOk, onCancel)
  • openNodeModal()
  • closeNodeModal()
  • addCustomNode()
  • switchAcademy(tab)
  • closeModule()
  • renderStatusBox(isDone)
  • toggleStatus(isDone)
  • sortComments(type)
  • showToast(msg)

Trading Lab

  • loadLabData()
  • loadSectorStocks()
  • selectStock(stock)
  • initKlineChart()
  • loadKlineData(symbol, days = 60)
  • calculateTotal()
  • executeTrade(action)
  • updatePortfolioUI()
  • resetPortfolio()
  • refreshLab()
  • updateGuideUI()
  • nextGuideStep()
  • prevGuideStep()
  • setLabView(view)

U2CHAT

  • loadAgentData()
  • loadAgentStocks()
  • addStockToChat(stock)
  • updateSelectedStocks()
  • removeStock(i)
  • sendMessage()
  • updateSendButtonState()
  • addMessageToUI(role, content, tools = [])
  • renderChart(containerId, data)
  • loadChatSessions()
  • loadChatSession(sessionId)
  • clearChat()
  • newChat()
  • handleAgentKey(e)
  • autoResize(t)

7.7 UI handlers currently referenced but missing

  • toggleLike(...)
  • toggleReplyLike(...)
  • changeTimeRange(...)

These missing handlers are currently important product gaps because visible UI controls already depend on them.

8. Current Data, Persistence, and State Boundaries

Browser/session state

  • Flask session stores user_id

Academy state

  • Module catalog is hardcoded in memory
  • Completion flags mutate in server memory
  • Ratings mutate in server memory
  • Comments mutate in server memory
  • Academy state is shared globally in the process, not persisted per user

Trading Lab state

  • Portfolio is stored in a defaultdict
  • State is keyed by user_id
  • State is not persisted across server restarts

Chat state

  • Visible session list and session messages are stored in CHAT_SESSIONS
  • LangGraph thread memory is stored in checkpoints.sqlite
  • These two sources of truth are not unified

Knowledge base state

  • Vector DB persists in chroma_db
  • Knowledge documents live in knowledge/
  • Retriever creation currently happens at import/startup time

Important persistence implications

  • Academy feels persistent only while the process is running
  • Lab feels persistent only while the process is running
  • U2CHAT appears partially persistent because LangGraph checkpoints survive, but the visible session list does not

9. UI Rebuild Product Requirements

The UI rebuild should preserve current scope while correcting the current architecture and interaction quality.

Preserve these product surfaces

  • Landing page
  • Public commercial website layer
  • Knowledge Academy
  • Trading Lab
  • U2CHAT
  • Lesson overlay
  • Share modal
  • Roadmap modes
  • Beginner guide
  • Chat session sidebar

Preserve these interaction capabilities

  • Module browsing
  • Lesson detail opening
  • Comment/reply posting
  • Completion toggling
  • Custom roadmap editing
  • Stock browsing by sector
  • Quote and chart loading
  • Paper trade execution
  • Chat session creation and reopening
  • AI chart rendering in chat
  • clear contact and conversion entry paths once added

Rebuild requirements

  • Move away from the current single-file frontend architecture
  • Introduce a clean design system with reusable tokens and components
  • Make navigation, overlays, and workspaces consistent across the three pillars
  • Add a real public business-site information architecture, not only an app shell
  • Add proper loading, empty, error, success, and disabled states
  • Make the app fully responsive on desktop and mobile
  • Add visible keyboard focus states
  • Reduce reliance on global mutable frontend state
  • Add proper deep-linking strategy for major views and modules
  • Preserve D3 and ECharts capabilities while improving presentation
  • Keep the UI minimalist, but not scope-reductive

Commercial website requirements

  • Add a professional homepage that can sell the product clearly
  • Add a full footer with contact, social, legal, and business links
  • Add contact and demo-request flows
  • Add visible trust and credibility sections
  • Add public-facing about/company context
  • Add legal/policy/disclaimer surfaces
  • Add conversion-focused CTA hierarchy
  • Add SEO-ready page structure and metadata strategy
  • Add support/help and business inquiry pathways
  • Make the site feel commercially credible, not only visually polished

Rebuild-specific UX requirements

  • The Academy should feel like a premium reading and learning workspace
  • The Lab should feel like a calm, trustworthy simulation workspace
  • U2CHAT should feel like a premium research assistant workspace
  • Shared visual language should be coherent across all three
  • The public-facing business website should feel credible enough for sales, partnerships, and commercial trust-building

10. Feature and Function Advancement Roadmap

10.1 Academy advancements

  • Use the existing parent field to model real lesson progression
  • Add saved user progress and user-specific completion history
  • Add rating submission UI and actual review summaries
  • Add comment likes, reply likes, and moderation tooling
  • Add search, category filters, difficulty filters, and completion filters
  • Surface lesson source, instructor, and credibility context
  • Add note-taking, bookmarks, highlights, and exportable study plans
  • Add quizzes and assessments after lessons
  • Add progress dashboards and learning streaks
  • Make custom roadmap saveable and shareable

10.2 Trading Lab advancements

  • Implement fully working chart time ranges
  • Render transaction history in the dashboard
  • Calculate live portfolio value from current quotes
  • Show realized and unrealized P&L separately
  • Add watchlists, alerts, and favorite stocks
  • Add order types beyond immediate buy/sell
  • Add slippage, fees, and tax simulation options
  • Add risk metrics and portfolio allocation visuals
  • Add contextual educational guidance during trading actions
  • Add saved paper accounts and multiple simulation profiles
  • Support richer data panels such as news, fundamentals, and peer comparison

10.3 U2CHAT advancements

  • Stream responses progressively instead of returning one final blob
  • Add backend-supported cancellation
  • Surface tool execution trace and tool outputs
  • Add citations and source cards for knowledge-base answers
  • Add structured cards for quotes, fundamentals, and charts
  • Add pinned conversations, search, rename, and foldering
  • Add suggested prompts and follow-up actions
  • Make recent sessions and history durable
  • Add beginner/expert assistant modes
  • Add portfolio-aware or watchlist-aware analysis once persistence exists

10.4 Data and platform advancements

  • Unify Academy, Lab, and Chat persistence in one durable store
  • Add proper user accounts and auth if the product goes beyond demo use
  • Make vector-store refresh detect modified and deleted PDFs
  • Move vector initialization away from blocking import-time startup where appropriate
  • Add analytics and product telemetry
  • Add a test suite for backend logic and core frontend flows
  • Add config separation for dev/staging/prod
  • Harden secret management and deployment defaults

10.5 Frontend architecture advancements

  • Break the current monolith into reusable components or modular views
  • Move styles and scripts into versioned static assets
  • Introduce design tokens and a consistent component library
  • Introduce cleaner state boundaries between Academy, Lab, and U2CHAT
  • Add proper routing and deep links
  • Add safer message rendering and sanitization strategy
  • Add better chart wrappers and reusable data cards

10.6 Commercial website advancements

  • Build a proper homepage with commercial messaging and conversion hierarchy
  • Add product overview, about, contact, FAQ, and pricing/demo surfaces
  • Add a professional footer with contact, social, legal, and support links
  • Add lead capture forms with CRM or email routing
  • Add testimonials, credibility markers, and product-proof sections
  • Add resource/content marketing structure for SEO and inbound acquisition
  • Add business-grade analytics and conversion tracking
  • Add finance-specific public disclaimers and risk disclosures
  • Add newsletter, waitlist, or demo-booking flows depending on go-to-market model
  • Add support/help center and business inquiry routing

11. Recommended Rebuild Phases

Phase 0: Truth-preserving inventory

  • Freeze current scope
  • Preserve all current product surfaces
  • Map implemented, partial, latent, and broken features

Phase 1: Design system and app shell

  • Rebuild the global shell, navigation, typography, surfaces, and spacing system
  • Rebuild both the commercial website shell and the product app shell
  • Rebuild page layout structure for Academy, Lab, and U2CHAT
  • Preserve current backend API contracts

Phase 2: Feature completion

  • Finish missing handlers
  • Finish partial Lab panels
  • Finish comment likes and ratings UI
  • Finish deep links and route behavior
  • Add public commercial pages and CTA flows

Phase 3: Persistence and intelligence

  • Unify persistence
  • Add true streaming and tool/source display
  • Make roadmap, chat, and paper portfolios durable

Phase 4: Product maturity

  • Add richer analysis features
  • Add personalization
  • Add moderation, analytics, and operational hardening
  • Add business analytics, CRM integration, SEO content, and commercial operations support

12. Success Criteria for the Rebuild

The rebuild is successful if a user can:

  • understand what U2INVEST is as a company/product before entering the app
  • understand the three product pillars immediately
  • move between Academy, Lab, and U2CHAT without cognitive friction
  • use every currently visible control without hitting dead or partial functionality
  • complete Academy learning flows and see trustworthy progress
  • use the Lab as a coherent paper-trading workspace
  • use U2CHAT as a believable research assistant with visible evidence and structure
  • find contact, social, legal, and trust information easily
  • submit a business inquiry, contact request, or demo request cleanly
  • recover state more reliably across refreshes and restarts

The rebuild is especially successful if it preserves scope while making the product feel more premium, more coherent, and more maintainable than the current single-file implementation.

13. Highest-Priority Truths To Preserve

  • U2INVEST is not only an AI chat app
  • U2INVEST is not only an in-app product; it also needs a public commercial website layer
  • The product is intentionally a three-part system: learn, practice, analyze
  • The Academy, Lab, and U2CHAT should remain connected but distinct
  • The rebuild should increase clarity and quality, not reduce functionality
  • The current code already contains more product scope than the current UI communicates