CAPSTONE: DocuMind Frontend
This capstone chapter designs a typed document workspace with upload progress, streaming chat, citation-to-source navigation, infinite data, optimistic interaction, accessible failure states, and measurable performance.
- Explain Pages & routing by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Core features by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain State, validation & patterns by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
How to use this chapter
For CAPSTONE: DocuMind Frontend, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the capstone learning arc appropriate to this subject.
The problem this chapter solves
This capstone chapter designs a typed document workspace with upload progress, streaming chat, citation-to-source navigation, infinite data, optimistic interaction, accessible failure states, and measurable performance.
Declarative components make UI updates predictable and composable while the ecosystem handles routing, caching, forms, validation, and build optimization.
Learning outcomes
- Explain Pages & routing by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Core features by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain State, validation & patterns by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
A render computes an element tree. Reconciliation compares identities and schedules DOM work; commit applies changes and effects. State setters enqueue updates, and React may batch, interrupt, or repeat rendering. Effects run after commit and therefore synchronize with external systems rather than calculate render data. In CAPSTONE: DocuMind Frontend, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- A user or server response schedules a state, cache, or navigation update; React calls affected components to compute a new element tree.
- Reconciliation compares element type, position, and key to preserve or replace component identity and its hook state.
- The commit phase applies DOM changes; layout work and passive effects run in their defined phases, cleaning up the previous external subscription first.
- Server Components or route handlers perform server work, while client boundaries hydrate serializable props and streaming segments reveal completed UI incrementally.
- Tests assert accessible output, loading/error/empty states, cleanup, cancellation, stale-response protection, and render or bundle performance.
Memory and performance lens
Hook state is associated with a component's position and identity in the rendered tree. Closures capture values from one render. Unremoved listeners, timers, subscriptions, object URLs, and caches can retain memory after the visible UI changes. For CAPSTONE: DocuMind Frontend, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning CAPSTONE: DocuMind Frontend, measure end-to-end correctness under representative load, tail latency, saturation, duplicate/lost effects, recovery time, security denials, and cost rather than optimizing from source-code appearance.
1. Pages & routing
The Pages & routing unit begins with / landing (hero/features/pricing): The public landing route explains the product, demonstrates trustworthy capabilities, presents pricing accurately, and gives keyboard-accessible paths to sign in or begin. Optimize for fast meaningful content, semantic headings, honest claims, responsive layout, and measurable conversion without blocking accessibility or privacy. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The vertical slice: Pages & routing
| Concept | Meaning | Engineering decision |
|---|---|---|
| / landing (hero/features/pricing) | The public landing route explains the product, demonstrates trustworthy capabilities, presents pricing accurately, and gives keyboard-accessible paths to sign in or begin. | Optimize for fast meaningful content, semantic headings, honest claims, responsive layout, and measurable conversion without blocking accessibility or privacy. |
| /dashboard (doc list/upload/recent) | The authenticated dashboard owns the user's document overview, upload entry point, recent activity, quotas, and recoverable loading/empty/error states. | Use cursor pagination, accessible file input alternatives, optimistic UI only for reversible state, and explicit processing status for asynchronous ingestion. |
| /documents/[id] (viewer + chat) | The document workspace combines an authorized source viewer with streaming chat and citations that let the user inspect the evidence behind each answer. | Keep viewer and chat state coordinated by stable document/version IDs, make sources keyboard reachable, and preserve partial output plus retry after stream failure. |
| /settings (profile/API keys/usage) | The settings route separates profile preferences, credential management, and usage/billing views because each has different sensitivity, validation, and confirmation needs. | Use clear save state, audit key creation/revocation, expose timezone/currency semantics for usage, and never return secret key material after creation. |
Ownership across the system: Pages & routing
/ landing (hero/features/pricing). Next.js can render mostly static server content, stream slower personalized fragments only when needed, and attach client JavaScript solely to interactive controls. Metadata and structured content support sharing and search.
/dashboard (doc list/upload/recent). The server route verifies the session and fetches an initial bounded page; client components manage drag/drop and progress, while TanStack Query or equivalent owns server-state revalidation and mutation results.
/documents/[id] (viewer + chat). The route validates the document ID and tenant on the server, loads metadata, then client boundaries handle page navigation, cancelable streams, and citation focus. Citation identifiers resolve to immutable page/section/span metadata.
/settings (profile/API keys/usage). The server authenticates and scopes every read; mutations use reauthentication or confirmation for high-impact actions. Newly created API keys are displayed once, stored only as hashes server-side, and later identified by safe prefixes.
Read these as one system: / landing (hero/features/pricing) establishes the starting contract, /dashboard (doc list/upload/recent) changes how that contract is executed or represented, and /settings (profile/API keys/usage) exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Integration risks: Pages & routing
| Risk | Why it matters |
|---|---|
| / landing (hero/features/pricing) | Shipping the entire landing page as a client bundle or hiding essential information inside animation increases load time and excludes users. |
| /dashboard (doc list/upload/recent) | Rendering another tenant's cached list or treating upload acceptance as completed ingestion leaks data and misleads users. |
| /documents/[id] (viewer + chat) | Highlighting by stale character offsets or trusting citation HTML can point to the wrong evidence or create an injection vulnerability. |
| /settings (profile/API keys/usage) | A client-only route guard or API response containing stored keys turns a frontend bug or XSS into account-wide credential theft. |
Sprint submission: Pages & routing
- Foundation: implement or demonstrate / landing (hero/features/pricing) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine / landing (hero/features/pricing) with /dashboard (doc list/upload/recent). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for /settings (profile/API keys/usage). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Core features
The Core features unit begins with drag-drop upload with TanStack Query progress mutation: The DocuMind frontend coordinates bounded uploads, streaming chat, citation navigation, document state, and failure recovery through typed client/server contracts. Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The vertical slice: Core features
| Concept | Meaning | Engineering decision |
|---|---|---|
| drag-drop upload with TanStack Query progress mutation | The DocuMind frontend coordinates bounded uploads, streaming chat, citation navigation, document state, and failure recovery through typed client/server contracts. | Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. |
| streaming chat with EventSource ReadableStream | The DocuMind frontend coordinates bounded uploads, streaming chat, citation navigation, document state, and failure recovery through typed client/server contracts. | Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. |
| citation highlighting: click → scroll to PDF source chunk | The DocuMind frontend coordinates bounded uploads, streaming chat, citation navigation, document state, and failure recovery through typed client/server contracts. | Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. |
| infinite scroll with useInfiniteQuery | The DocuMind frontend coordinates bounded uploads, streaming chat, citation navigation, document state, and failure recovery through typed client/server contracts. | Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. |
Ownership across the system: Core features
drag-drop upload with TanStack Query progress mutation. Upload and chat transports emit incremental progress; state updates are reconciled into the UI; abort signals, reconnect logic, and server-confirmed identities prevent stale streams from mutating the wrong conversation.
streaming chat with EventSource ReadableStream. Upload and chat transports emit incremental progress; state updates are reconciled into the UI; abort signals, reconnect logic, and server-confirmed identities prevent stale streams from mutating the wrong conversation.
citation highlighting: click → scroll to PDF source chunk. Upload and chat transports emit incremental progress; state updates are reconciled into the UI; abort signals, reconnect logic, and server-confirmed identities prevent stale streams from mutating the wrong conversation.
infinite scroll with useInfiniteQuery. Upload and chat transports emit incremental progress; state updates are reconciled into the UI; abort signals, reconnect logic, and server-confirmed identities prevent stale streams from mutating the wrong conversation.
Read these as one system: drag-drop upload with TanStack Query progress mutation establishes the starting contract, streaming chat with EventSource ReadableStream changes how that contract is executed or represented, and infinite scroll with useInfiniteQuery exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Implementation checkpoint: Core features
1type CitationHighlightingClickScrollToPdf_Props = { id: string };2
3export function CitationHighlightingClickScrollToPdf_({ id }: CitationHighlightingClickScrollToPdf_Props) {4 const [status, setStatus] = useState<'idle' | 'ready' | 'error'>('idle');5 return <section data-entity-id={id} data-status={status}>{status}</section>;6}This Core features slice makes drag-drop upload with TanStack Query progress mutation observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward infinite scroll with useInfiniteQuery, predict its behavior for empty, invalid, repeated, and large input.
Integration risks: Core features
| Risk | Why it matters |
|---|---|
| drag-drop upload with TanStack Query progress mutation | A browser ReadableStream is not an LLM API abstraction by itself; duplicated listeners and unbounded buffers cause memory and ordering defects. |
| streaming chat with EventSource ReadableStream | A browser ReadableStream is not an LLM API abstraction by itself; duplicated listeners and unbounded buffers cause memory and ordering defects. |
| citation highlighting: click → scroll to PDF source chunk | A browser ReadableStream is not an LLM API abstraction by itself; duplicated listeners and unbounded buffers cause memory and ordering defects. |
| infinite scroll with useInfiniteQuery | A browser ReadableStream is not an LLM API abstraction by itself; duplicated listeners and unbounded buffers cause memory and ordering defects. |
Sprint submission: Core features
- Foundation: implement or demonstrate drag-drop upload with TanStack Query progress mutation with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine drag-drop upload with TanStack Query progress mutation with streaming chat with EventSource ReadableStream. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for infinite scroll with useInfiniteQuery. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. State, validation & patterns
The State, validation & patterns unit begins with Zustand: active document/chat history/UI state: A Zustand store can coordinate cross-route client state such as the selected document and ephemeral UI preferences, while server-owned document and chat data remains in the query/cache layer. Keep the store small, normalize identities, use narrow selectors, and avoid duplicating authoritative API responses that already have a server-state owner. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The vertical slice: State, validation & patterns
| Concept | Meaning | Engineering decision |
|---|---|---|
| Zustand: active document/chat history/UI state | A Zustand store can coordinate cross-route client state such as the selected document and ephemeral UI preferences, while server-owned document and chat data remains in the query/cache layer. | Keep the store small, normalize identities, use narrow selectors, and avoid duplicating authoritative API responses that already have a server-state owner. |
| Zod schemas for all forms | TanStack Query manages asynchronous server-state lifecycles; Zod validates runtime data; React Hook Form minimizes form re-renders. | Validate API responses as well as forms and design stable key factories. |
| React Hook Form + Zod on upload settings | TanStack Query manages asynchronous server-state lifecycles; Zod validates runtime data; React Hook Form minimizes form re-renders. | Validate API responses as well as forms and design stable key factories. |
| optimistic UI on message send (useOptimistic) | Redux Toolkit standardizes immutable reducers, actions, middleware, and normalized global state; RTK Query manages cached server data. | Use Redux for cross-feature client state and the query layer for remote data. |
| Server Actions for deletion + revalidatePath | Server Actions are server-executed mutations referenced by UI forms; cache directives and revalidation define when rendered or fetched data becomes fresh. | Authenticate and authorize inside every action and use targeted invalidation. |
Ownership across the system: State, validation & patterns
Zustand: active document/chat history/UI state. Components subscribe to selector results; store actions immutably update state and notify only relevant subscribers. Persistence middleware serializes chosen fields, so hydration and schema versioning are explicit concerns.
Zod schemas for all forms. A structured query key identifies a cache entry; stale time controls freshness, mutation callbacks update or invalidate it, and page parameters drive infinite queries.
React Hook Form + Zod on upload settings. A structured query key identifies a cache entry; stale time controls freshness, mutation callbacks update or invalidate it, and page parameters drive infinite queries.
optimistic UI on message send (useOptimistic). Immer records mutations against a draft and produces immutable updates. Query cache keys derive from endpoint and arguments; tags drive invalidation.
Server Actions for deletion + revalidatePath. An action receives serialized input, executes with server credentials, and can invalidate paths/tags. Streaming sends completed route segments as they become available.
Read these as one system: Zustand: active document/chat history/UI state establishes the starting contract, Zod schemas for all forms changes how that contract is executed or represented, and Server Actions for deletion + revalidatePath exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Integration risks: State, validation & patterns
| Risk | Why it matters |
|---|---|
| Zustand: active document/chat history/UI state | Putting every chat message, request result, and component flag in one global store creates stale copies, broad rerenders, and difficult logout/tenant cleanup. |
| Zod schemas for all forms | A query cache is not durable business state, and optimistic updates require rollback snapshots. |
| React Hook Form + Zod on upload settings | A query cache is not durable business state, and optimistic updates require rollback snapshots. |
| optimistic UI on message send (useOptimistic) | Do not mirror query data into slices or invalidate every tag after every mutation. |
| Server Actions for deletion + revalidatePath | A server action is still a public mutation surface; hidden buttons do not secure it. |
Sprint submission: State, validation & patterns
- Foundation: implement or demonstrate Zustand: active document/chat history/UI state with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Zustand: active document/chat history/UI state with Zod schemas for all forms. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Server Actions for deletion + revalidatePath. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1export function useStreamingAnswer(documentId: string) {2 const [state, setState] = useState({ text: '', citations: [] as Citation[], status: 'idle' });3
4 const ask = useCallback(async (question: string) => {5 setState({ text: '', citations: [], status: 'streaming' });6 const response = await fetch('/api/documents/' + documentId + '/chat', {7 method: 'POST', body: JSON.stringify({ question }), headers: { 'content-type': 'application/json' },8 });9 if (!response.ok || !response.body) throw new Error('chat failed');10 for await (const event of parseSSE(response.body)) {11 if (event.type === 'token') setState(current => ({ ...current, text: current.text + event.value }));12 if (event.type === 'citation') setState(current => ({ ...current, citations: [...current.citations, event.value] }));13 }14 setState(current => ({ ...current, status: 'complete' }));15 }, [documentId]);16
17 return { ...state, ask };18}Expected result
1Text renders incrementally; citation events retain source metadata for click-to-document navigation.Line-by-line reading
| Line | Code | Explanation | ||
|---|---|---|---|---|
| 1 | export function useStreamingAnswer(documentId: string) { | Implements the next tsx statement in the example's data flow. | ||
| 2 | const [state, setState] = useState({ text: '', citations: [] as Citation[], status: 'idle' }); | Binds a JavaScript value used by the component or operation. | ||
| 4 | const ask = useCallback(async (question: string) => { | Binds a JavaScript value used by the component or operation. | ||
| 5 | setState({ text: '', citations: [], status: 'streaming' }); | Implements the next tsx statement in the example's data flow. | ||
| 6 | const response = await fetch('/api/documents/' + documentId + '/chat', { | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. | ||
| 7 | method: 'POST', body: JSON.stringify({ question }), headers: { 'content-type': 'application/json' }, | Implements the next tsx statement in the example's data flow. | ||
| 8 | }); | Implements the next tsx statement in the example's data flow. | ||
| 9 | `if (!response.ok \ | \ | !response.body) throw new Error('chat failed');` | Evaluates the condition and enters this branch only when it is truthy. |
| 10 | for await (const event of parseSSE(response.body)) { | Consumes the iterable one item at a time through the iterator protocol. | ||
| 11 | if (event.type === 'token') setState(current => ({ ...current, text: current.text + event.value })); | Evaluates the condition and enters this branch only when it is truthy. | ||
| 12 | if (event.type === 'citation') setState(current => ({ ...current, citations: [...current.citations, event.value] })); | Evaluates the condition and enters this branch only when it is truthy. | ||
| 13 | } | Implements the next tsx statement in the example's data flow. | ||
| 14 | setState(current => ({ ...current, status: 'complete' })); | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | ||
| 15 | }, [documentId]); | Implements the next tsx statement in the example's data flow. | ||
| 17 | return { ...state, ask }; | Returns the observable result to the caller and ends this invocation. | ||
| 18 | } | Implements the next tsx statement in the example's data flow. |
Step-by-step execution
- A user or server response schedules a state, cache, or navigation update; React calls affected components to compute a new element tree.
- Reconciliation compares element type, position, and key to preserve or replace component identity and its hook state.
- The commit phase applies DOM changes; layout work and passive effects run in their defined phases, cleaning up the previous external subscription first.
- Server Components or route handlers perform server work, while client boundaries hydrate serializable props and streaming segments reveal completed UI incrementally.
- Tests assert accessible output, loading/error/empty states, cleanup, cancellation, stale-response protection, and render or bundle performance.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Pages & routing | Shipping the entire landing page as a client bundle or hiding essential information inside animation increases load time and excludes users. | Optimize for fast meaningful content, semantic headings, honest claims, responsive layout, and measurable conversion without blocking accessibility or privacy. |
| Core features | A browser ReadableStream is not an LLM API abstraction by itself; duplicated listeners and unbounded buffers cause memory and ordering defects. | Parse runtime payloads, cap retained stream history, expose cancellation and retry, and preserve source provenance from citation to viewer location. |
| State, validation & patterns | Putting every chat message, request result, and component flag in one global store creates stale copies, broad rerenders, and difficult logout/tenant cleanup. | Keep the store small, normalize identities, use narrow selectors, and avoid duplicating authoritative API responses that already have a server-state owner. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the DocuMind AI Frontend project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Pages & routing: / landing (hero/features/pricing)
- To do: Pages & routing: /dashboard (doc list/upload/recent)
- To do: Pages & routing: /documents/[id] (viewer + chat)
- To do: Pages & routing: /settings (profile/API keys/usage)
- To do: Core features: drag-drop upload with TanStack Query progress mutation
- To do: Core features: streaming chat with EventSource ReadableStream
- To do: Core features: citation highlighting: click → scroll to PDF source chunk
- To do: Core features: infinite scroll with useInfiniteQuery
- To do: State, validation & patterns: Zustand: active document/chat history/UI state
- To do: State, validation & patterns: Zod schemas for all forms
- To do: State, validation & patterns: React Hook Form + Zod on upload settings
- To do: State, validation & patterns: optimistic UI on message send (useOptimistic)
- To do: State, validation & patterns: Server Actions for deletion + revalidatePath
Quick revision
- Pages & routing: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Core features: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- State, validation & patterns: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?