Project Workshop — DocuMind AI Frontend
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
Next.js 14 · TypeScript · Zustand · TanStack Query · Zod · shadcn/ui · Tailwind
Expected effort: 20–32 focused hours · Minimum meaningful tests: 24What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | / landing (hero/features/pricing) produces the specified behavior inside Pages & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | /dashboard (doc list/upload/recent) produces the specified behavior inside Pages & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | /documents/[id] (viewer + chat) produces the specified behavior inside Pages & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | /settings (profile/API keys/usage) produces the specified behavior inside Pages & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | drag-drop upload with TanStack Query progress mutation produces the specified behavior inside Core features | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | streaming chat with EventSource ReadableStream produces the specified behavior inside Core features | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | citation highlighting: click → scroll to PDF source chunk produces the specified behavior inside Core features | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | infinite scroll with useInfiniteQuery produces the specified behavior inside Core features | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | Zustand: active document/chat history/UI state produces the specified behavior inside State, validation & patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | Zod schemas for all forms produces the specified behavior inside State, validation & patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | React Hook Form + Zod on upload settings produces the specified behavior inside State, validation & patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | optimistic UI on message send (useOptimistic) produces the specified behavior inside State, validation & patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.5 | Server Actions for deletion + revalidatePath produces the specified behavior inside State, validation & patterns | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1app/2├── routes-or-app-router/3├── components/{ui,features,errors}/4├── hooks/5├── lib/{api,auth,schemas,query-keys}/6├── state/7├── styles/8├── tests/{unit,integration,e2e}/9└── package.jsonBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Pages & routing | / landing (hero/features/pricing); /dashboard (doc list/upload/recent); /documents/[id] (viewer + chat) | Demonstration plus focused tests |
| 2 | Core features | drag-drop upload with TanStack Query progress mutation; streaming chat with EventSource ReadableStream; citation highlighting: click → scroll to PDF source chunk | Demonstration plus focused tests |
| 3 | State, validation & patterns | Zustand: active document/chat history/UI state; Zod schemas for all forms; React Hook Form + Zod on upload settings | Demonstration plus focused tests |
| 4 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
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.Code 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. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Pages & routing | A client-only route guard or API response containing stored keys turns a frontend bug or XSS into account-wide credential theft. | Use clear save state, audit key creation/revocation, expose timezone/currency semantics for usage, and never return secret key material after creation. |
| 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 | A server action is still a public mutation surface; hidden buttons do not secure it. | Authenticate and authorize inside every action and use targeted invalidation. |
Engineering checklist for this stack
- To do: deliver reviewable vertical slices
- To do: keep authoritative and derived state distinct
- To do: make every external effect retry-safe
- To do: integrate security and observability before the final sprint
- To do: publish reproducible demo and failure evidence
Test strategy
Implement at least 24 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 16 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1import { render, screen } from '@testing-library/react';2import userEvent from '@testing-library/user-event';3
4it('shows a recoverable error when the mutation fails', async () => {5 server.use(http.post('/api/action', () => HttpResponse.json({ detail: 'failed' }, { status: 503 })));6 render(<Feature />);7 await userEvent.click(screen.getByRole('button', { name: /submit/i }));8 expect(await screen.findByRole('alert')).toHaveTextContent(/try again/i);9});Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?