Frontend architecture
The frontend is a Next.js 14 App Router app in TypeScript, in frontend/src. It is a thin, fast client over the backend API: no server-side data layer of its own, just pages and components that call /api and render.
Stack
| Concern | Choice |
|---|---|
| Framework | Next.js 14 (App Router), React 18 |
| Language | TypeScript |
| Styling | Tailwind CSS with a project design system in app/globals.css |
| Animation | Framer Motion |
| Data fetching | Hand-written fetch wrappers in lib/api.ts with component state (@tanstack/react-query is installed but unused); the inventory table is virtualized with TanStack Virtual |
| Icons | lucide-react |
| Error tracking | Sentry (@sentry/nextjs): sentry.client.config.ts, sentry.server.config.ts and sentry.edge.config.ts at the frontend root, loaded by src/instrumentation.ts; app/global-error.tsx reports render crashes. Off unless a DSN is set. See error tracking. |
| Analytics and telemetry | PostHog (components/PostHogProvider.tsx) and optional OpenTelemetry browser traces (components/TelemetryProvider.tsx, lib/telemetry.ts), both off by default |
| Build/run | next dev (port 3000 locally), next start in production (standalone output) |
Routing map
| Route | File | Purpose |
|---|---|---|
/ | app/page.tsx | Entry; routes the user into the app or to login. |
/dashboard | app/dashboard/page.tsx | The team's claims, per-claim usage, and headline stat cards (claims, items, processing speed); status tabs (All plus one per claim status, with counts, kept in ?status=; logic in lib/claimStatusTabs.mjs); a Source column (components/ClaimSourceBadge.tsx, icon plus label, sortable, searchable and filterable from a list); create a claim. The Usage column (and its filter, sort and search) is hidden for teams with the enterprise flag (features.enterprise from /api/auth/me), since they are never charged credits. Source labels and the usage rule live in lib/claimGrid.mjs; both helper test files run from backend/tests/test_claims_grid_frontend.py. Columns, filters and saved views: the column catalog, per-type filter operators (ruleMatches), drag reorder, resize clamps and the "unsaved changes" comparison live in lib/claimColumns.mjs (tests in lib/claimColumns.test.mjs). Each header (components/claims-grid/ColumnHeader.tsx) sorts on click, opens a menu (sort, a filter suited to the column via FilterEditor.tsx, Hide column), drags onto another header to reorder and resizes from its right edge. ColumnsMenu.tsx (framer-motion Reorder) shows, hides and orders columns; ViewsMenu.tsx opens, saves, renames, deletes views and sets dashboard.default_view_id. The open view is kept in ?view=. Each view row has a pin button: pinned views become custom dashboards nested under Dashboard in the sidebar (components/Sidebar.tsx, lib/dashboards.tsx, components/ManageDashboardsModal.tsx). On open the page reads the dashboard.* settings from /api/config/effective. My assignments only saves dashboard.my_assignments_only. Assigned To opens components/ReassignDialog.tsx (people from /api/claims/assignable-users only); Tags opens components/TagsDialog.tsx (tag the selection, and manage tags with tags.manage). Controls follow user.permissions from /api/auth/me (can() in lib/auth.tsx). See configuration and access. |
/claims/[id] | app/claims/[id]/page.tsx | A claim: its rooms (a wrapping card grid folded after two rows, or a compact list; components/ClaimRoomViews.tsx, choice remembered per browser in localStorage cv:claim-room-layout), details, submission history (components/SubmissionsCard.tsx: date, items, photos, claim key, submission id, processing time), and submit. Send for Estimation disables once every item is submitted; audio-only items show a neutral "no photo to send" note instead of a warning. |
/rooms/[id] | app/rooms/[id]/page.tsx | A room: upload media, list jobs, review room inventory. A room with scoping photos or videos also gets a Room photos tab (components/RoomPhotosTab.tsx, hidden when there are none, with a count) and a room cover beside its name. ?tab=room-photos opens the page on that tab, which is where a cover click anywhere lands. |
/jobs/[id] | app/jobs/[id]/page.tsx | A job: processing progress and its inventory. |
/settings | app/settings/page.tsx | Tabs: Profile (time zone, theme), Automation (auto-approval rules), Prompts (AI prompts), and Team & Access (components/settings/: level defaults, people, access profiles, organization structure) for holders of settings.manage_team or settings.manage_org. ?tab=access opens it directly. |
/integrations | app/integrations/page.tsx | The other Contents products the team can open (ContentsEstimationCard, opens Contents Estimation already signed in) and the media sources it pulls from (IntegrationsCard: the ContentsCapture connection and import). |
/changelog | app/changelog/page.tsx | Customer changelog, rendered from src/content/changelog/customer.md. The sidebar item shows a dot while there are unseen entries (localStorage). |
/updates | app/updates/page.tsx | Internal release log (admins only), rendered from src/content/changelog/internal.md; same unseen-dot behavior. Note the gate is UI-only: the markdown ships in the client bundle. |
/admin | app/admin/page.tsx | Internal admin dashboard (admins only): system-wide health across all teams. Overview tab (live stats, range-scoped credits and AI cost, last 10 jobs, claims, jobs, team leaderboard), Teams tab (per-team component visibility with global defaults; training ships hidden), Activity Log tab (all teams, team filter), Media tab (browse and play every upload), and Training tab (components/training/AdminTrainingPanel.tsx: the module library and TrainingModuleBuilder, required-training assignments per level, and the compliance report with exemptions). |
/logs | app/logs/page.tsx | Pipeline Logs (admins only). Item lookup tab (default, components/ItemLookupPanel.tsx): find a claim by number, id, or insured, search its items by any attribute, and expand an item to see its attributes, the AI calls that mention it (highlighted, model reply pretty-printed), the upload's other calls, and the log lines naming it; ?claim= and ?item= in the URL make a lookup shareable. Jobs tab: every job system-wide with detailed logs, filters, grouping, plus per-job Mark failed (dismiss a stuck job with a refund) and Delete (hard-delete with confirm). API Requests tab (components/ApiRequestsPanel.tsx): OpenRouter calls grouped by job with per-job totals (requests, cost, time), searchable by job/claim/filename and filterable by company/user, expanding to per-call request/response JSON with an open-in-OpenRouter link. |
/training, /training/missions/[key], /training/modules/[key] | app/training/* | The training hub, the mission runner, and a training module (its lessons played step by step on the learner's own sandbox claims, then a knowledge check). Hidden (nav and page) when the admin switches the training component off for the team. See training. |
/verify/[code] | app/verify/[code]/page.tsx | Public certificate verification (no sign-in). |
/insured/[token] | app/insured/[token]/page.tsx | The homeowner's own inventory link (no sign-in; calls /api/public/insured/... through lib/insuredApi.ts, components in components/insured/). See Insured inventory link. |
/help, /help/[slug] | app/help/* | The in-app Help Center. |
/login, /logout, /auth/callback | app/* | The SSO flow. |
error.tsx, global-error.tsx, not-found.tsx | app/* | Error and 404 pages. global-error.tsx catches a crash in the root layout itself and reports it to Sentry. |
template.tsx | app/template.tsx | Re-mounts on every navigation to give each page a short fade and slide in. |
A client-side SSE proxy route also exists at app/api/jobs/[id]/stream/route.ts to relay the backend stream during local development.
Dates and times format through lib/datetime.ts, which shows every timestamp in the user's chosen time zone (Settings > Profile, stored on the user row) or the browser's local zone by default. Do not call toLocaleString with a hardcoded zone.
Changelogs are markdown files in src/content/changelog/ imported as raw strings (a webpack rule in next.config.js), parsed by lib/changelog.ts (## YYYY-MM-DD - [New|Improved|Fixed] Title, an optional summary line, then optional bullets) and rendered by components/ChangelogFeed.tsx as cards grouped under a date heading, with kind pills, a month dropdown and a search box across the top. The kind tag is optional in the parser so an untagged entry still renders (as Improved) instead of dropping off the page. Customer entries are capped at two lines and one change each; internal entries deliberately are not. Updating them on every product commit is a hard rule in CLAUDE.md. The footer (components/Footer.tsx) shows the team's credit balance and a Buy credits button (on prepaid-billing instances, moved here from the old top bar), the copyright line, and the build's commit hash (linking to /changelog) and date from NEXT_PUBLIC_COMMIT_SHA / NEXT_PUBLIC_COMMIT_TIME, which docker-compose bakes in at build time. Video playback goes through components/MediaFrame.tsx, which reserves a 16:9 box with a logo placeholder and spinner so pages never shift while media loads.
The app shell
app/layout.tsx mounts three side-effect components (ThemeSync, TelemetryProvider, SessionGuard), then nests four context providers around the shell:
components/PostHogProvider.tsxinitialises product analytics and wires page views and user identity. It is a no-op when no PostHog key is configured (the default), so it is invisible until analytics is turned on. The same login and logout transitions set and clear the Sentry user (id and team only, no PII).components/SessionGuard.tsxwrapswindow.fetchonce so any401from/api/*(other than the auth endpoints) hands off tohandleSessionExpiredinlib/session.ts, which records a Sentry breadcrumb and a PostHog event and sends the user to the login screen./api/public/*is excluded too, and the public insured endpoints never answer401as a second line of defence.AppShellalso mountstraining/TrainingGateBanner(the required-training warning and lock notice) andtraining/ChatBubble(the help chat and guide player).components/AppShell.tsxis the frame: the responsive sidebar and the content column. There is no desktop top bar: the team's credit balance now lives in the footer (Footertakes abillingprop), and the content column's left margin follows the sidebar's collapsed width. On mobile a slim top bar carries only the hamburger + logo.components/ProductSwitcher.tsxis the brand block in the top left corner of the sidebar (and the mobile top bar). It shows the ContentsVision plain lockup (the endorsed lockup, with "BY ADJUST SQUARE", is for lockups at least 40px tall, so sign-in and the public home use that and the sidebar does not). Clicking it opens an animated menu. Each product row is that product's kit mark: ContentsCapture orange, ContentsEstimation blue, ContentsVision violet. The menu jumps to ContentsCapture (admin console) or ContentsEstimation in the same tab, or back to the Dashboard. Links come fromlib/productLinks.mjs, picked by the page's hostname so each deployment links to its own siblings: production, stage,sgk(sgk.contentsvision.comlinks tosgk.contentsestimation.comandsgk-admin.contentscapture.com) andstage-sgk. The optional build-time overridesNEXT_PUBLIC_CONTENTSESTIMATION_URLandNEXT_PUBLIC_CONTENTSCAPTURE_ADMIN_URLwin when set. On an Enterprise deployment the menu lists only the products the signed-in person can open and adds Guides and training (the ContentsEstimation Start page):switcherMenu()in the same file readsuser.product_accessfrom/api/auth/me, and the addresses in that record win over the hostname table. With no record it shows all three products as before. See product access. Unit tests:lib/productLinks.test.mjs, run frombackend/tests/test_product_switcher.py.components/Sidebar.tsxis the left nav with the product switcher, an environment badge (hidden in production, amber for stage, violet for local), and the signed-in user with a sign-out button. On desktop the rail is collapsible to an icon strip via a toggle above the user chip; the choice persists in thecv_nav_collapsedcookie through a shareduseSyncExternalStorestore (lib/navCollapsed.ts) that both the sidebar (its width) andAppShell(the content margin) read, so a toggle re-renders them together. Collapse applies at thexlbreakpoint only; the mobile drawer is always full width. It also renders the Logs, Updates and Admin tabs, but only whenuseAuth().user?.is_adminis true (the allowlisted operators). Hiding it is cosmetic; the/adminpage and its API enforce access on their own (see authentication).- The environment comes from
NEXT_PUBLIC_APP_ENVviagetAppEnv()inlayout.tsx.
The API client
All backend calls go through lib/api.ts. There is no axios or generated client; it is hand-written fetch/XMLHttpRequest wrappers.
- Auth header:
actorHeaders()reads the token fromlocalStorage(cv_auth_token) and addsAuthorization: Bearer <token>to every request;apiFetch()is the drop-infetchwrapper that attaches it. - Base URL: everything is relative to
/api, which nginx (prod) or the Next proxy (dev) routes to the backend. - Uploads: video/photo/audio uploads use
XMLHttpRequestso a real upload-progress percentage can drive the UI. - Errors: failed calls try to surface the backend's
detailmessage so users see something meaningful. - Streaming:
subscribeToJobProgressopens anEventSourceto the job stream and dispatchesprogress,log, andmetricscallbacks.
// lib/api.ts: every call attaches the token
function actorHeaders(): Record<string, string> {
const token = getAuthToken() // localStorage 'cv_auth_token'
return token ? { Authorization: `Bearer ${token}` } : {}
}
Authentication on the client
lib/auth.tsx provides AuthProvider/useAuth. On mount it restores a saved session from localStorage, and if none exists (and the user did not just log out) it probes /api/auth/me in case a same-subdomain AdjustSquare cookie is present. The login redirect, token exchange at /auth/callback, and logout are covered in authentication.
Real-time job progress
When a job is processing, the page subscribes to the SSE stream and updates components/ProcessingStatus.tsx live: an animated progress bar, the current stage text, and a scrolling log. When the stream sends complete, the UI swaps to the inventory.
Component map
| Area | Components |
|---|---|
| Shell & nav | AppShell, Sidebar, ProductSwitcher, ModalShell, ModalPortal |
| Dashboard | claims-grid/* (ColumnHeader, ColumnsMenu, FilterEditor, ViewsMenu, TagChip), ManageDashboardsModal, ReassignDialog, TagsDialog, ClaimStatusBadge, ClaimStatusDialog, ClaimSourceBadge, FloatingBulkBar, ContentsEstimationImportModal, CaptureArrivalsNotice |
| Claims & rooms | CreateClaimModal, CreateRoomModal, ClaimRoomViews, RoomCover, RoomPhotosTab, ReorderRoomsModal, RoomUpload, InviteInsuredModal, ImportContentsListModal |
| Upload | RoomUpload (one drop area for any media mix), ConfirmUploadsModal, ConfirmProcessModal, InsufficientCreditsModal, GroupPhotosModal, SegmentPhotoModal, UnprocessedMediaModal |
| Training | app/training (hub + mission runner), app/verify/[code] (public certificate page), TrainingTour (spotlight tours), TrainingTracker (floating mission task list), TrainingBadgeIcon, training/GuideWindow (the movable, resizable, zoomable window every training surface uses), training/ChatBubble (help chat bubble and guide player), training/TrainingGateBanner, training/AdminTrainingPanel and training/TrainingModuleBuilder (the admin Training tab) |
| Processing | ProcessingStatus, JobCompletionChime |
| Review | InventoryTable, ItemPhotosModal, ItemModal, AddItemModal, FrameCropModal, ClaimDuplicatesModal, ReviewMode, TranscriptPanel, VideoPlayer |
| Submit | SendToMenu, SubmitClaimModal (Adjust Square), SendToContentsEstimationModal, SubmissionsCard |
| Settings & integrations | PromptsCard, automation UI, settings/* (AccessSettings, DefaultsCard, PeopleCard, ProfilesCard, OrgStructureCard), IntegrationsCard, CaptureImportModal, ContentsEstimationCard |
| Admin | AdminTeamsPanel, ImpersonatePanel, ItemLookupPanel, ApiRequestsPanel |
| Helpers | StyledSelect, ConfirmModal, HelpArticleBody, guides/GuideSpotlight |
Helper libraries: lib/media.ts (upload classification: extension lists, classifyFile, folder traversal for drag-and-drop), lib/confidence.ts (confidence buckets and colors), lib/sourceTag.ts (video/photo/audio badges), lib/automationSettings.tsx (auto-approval context), lib/chime.ts (the completion sound), hooks/useEscapeToClose.ts.
The design system
The visual language lives in frontend/src/app/globals.css as a set of component classes (.btn-primary, .card, .as-input, .as-table, .pill-*, .eyebrow, motion primitives). Product color is the Contents family kit: ContentsVision violet #8A6FF8 (gradient #A897FF to #6A4CF0), ContentsCapture orange #FF7410, ContentsEstimation blue #1E8CF2. The CSS variables --product-* are the source of truth, and the brand ramp (buttons, links, focus) is anchored on the ContentsVision gradient end #6A4CF0 so white text stays readable. Marks are the kit files in frontend/public/brand/, not redrawn.
Shared tokens (design continuity)
ContentsVision, ContentsEstimation and ContentsCapture share one set of design tokens and differ only in brand colour (AS-1614, epic AS-1606). In frontend/tailwind.config.js and the top of globals.css:
| Token | Value |
|---|---|
| Brand colour | brand-50 to brand-900 (--c-brand-*), the violet ramp. It used to be a blue-* ramp that rendered violet; stock Tailwind blue is not used, and backend/tests/test_design_foundations.py fails on any blue-* class. |
| Semantic roles | success-* (green), warn-* (amber), danger-* (red), ai-* (violet), each with 50, 100, 500, 600, 800 plus DEFAULT (500) and soft (50). They read the same variables as green / amber / red / violet, whose five steps are the ContentsCapture admin console hexes: 50 tint, 100 stronger tint, 500 accent, 600 pressed, 800 text on a tint. |
| Fonts | Inter Tight (font-sans, and font-display, which is now a weight, not a typeface) and JetBrains Mono (font-mono). Instrument Serif is no longer loaded. |
| Type scale | The kit scale: text-xs 11px, sm 13px, base 15px, md 17px, lg 20px, xl 24px, 2xl 32px (line height 1.45 up to md, 1.25 above). This is not stock Tailwind, so text-sm is 13px. Hand typed sizes that equal a step (text-[13px], text-[12.5px]) were replaced by the step; text-[12px] and other off-scale sizes remain. |
| Focus ring | --shadow-focus / shadow-focus: 3px brand at 22%, on every focusable control including .as-input. |
| Motion | CSS: --ease-standard (cubic-bezier(0.2, 0.7, 0.2, 1), Tailwind ease-standard) and --dur-fast / --dur-base / --dur-slow (140 / 220 / 320ms, Tailwind duration-fast / base / slow). Framer Motion: EASE ([0.2, 0, 0, 1]), DUR and spring from src/lib/motion.ts. |
Icons are still inline heroicons paths; moving to lucide-react at stroke 1.5 is the next step of AS-1614. The handbook you are reading uses Inter Tight and JetBrains Mono like the app, plus Instrument Serif for its own display headings, and the same violet so the two surfaces feel like one product.
Light and dark themes
Every Tailwind colour reads a CSS variable (--c-slate-700, --c-brand-500, ...). The light values sit on :root at the top of globals.css, the dark values on html[data-theme="dark"]. The data-theme="dark" attribute on <html> (the same mechanism ContentsEstimation uses; it was the dark class before AS-1614) is set by the Light / Dark / System choice in Settings > Profile, stored per browser in the cv_theme cookie (default Light). Tailwind's darkMode is ['selector', '[data-theme="dark"]'], so dark: variants follow the same attribute. lib/themeCore.mjs holds the pure rules and the inline pre-paint script used in app/layout.tsx; lib/theme.ts holds the React hook and <ThemeSync />, which follows OS changes while on System.
bg-slate-700/800/900 stay dark in both themes (toasts, tooltips, log consoles, photo viewers), and the light palette is restored inside them so their light text keeps reading. text-white and border-white always stay white. Use palette classes in new UI; a literal hex colour will not switch with the theme, so pair it with a dark: variant.
The project has firm UI and motion rules (use the design-system classes, never a native <select>, animate everything in and out with Framer Motion). They are summarized in engineering conventions and live in full in the repo's CLAUDE.md.
The Help Center
In-app help is content-driven. Articles are TypeScript modules in frontend/src/content/help/ (one file per article, registered in articles.ts), rendered by app/help/[slug]/page.tsx through components/HelpArticleBody.tsx. The house style: short verb-first headings, terse steps, screenshots, and a path that always starts from the Dashboard. This is distinct from the handbook (this Docusaurus site), which documents how the system works rather than how to perform a task in the UI.
Screenshots render at full column width without ever being stretched past their own pixels, and step-by-step articles can carry a playable guide ("Walk me through it"): lib/guides.tsx (GuideProvider, mounted in app/layout.tsx) plus components/guides/GuideSpotlight.tsx and components/training/ChatBubble.tsx (mounted in AppShell) navigate to each step, spotlight the element tagged data-guide="...", and advance on the real click or input. See Help Center and playable guides.