{"slug":"business/FRONTEND_LAYERED_STACK","title":"IntegrateWise — FrontEnd Layered Stack","section":"business","sectionLabel":"Business","status":"unclassified","type":"document","path":"business/FRONTEND_LAYERED_STACK.mdx","bytes":24344,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n## Systems View × User View\n\n**Version:** 3.7\n**Date:** June 2026\n**Status:** Architecture Locked\n\n---\n\n## Executive Summary\n\n> **Systems View:** A Next.js SPA deployed to Cloudflare Pages, consuming a Gateway API, rendering role/department/industry-hydrated workbenches through a design-token-driven component system, with state managed via React hooks + Zustand, data fetched through SWR, and real-time updates via WebSockets (Durable Objects).\n\n> **User View:** A calm, precise workspace that adapts to who you are. No clutter. No generic dashboards. Every view is filtered through your role, your department, your industry. The AI speaks first. The UI gets out of the way.\n\n---\n\n# PART I: SYSTEMS VIEW\n\n## How the Frontend Engine Runs\n\n---\n\n## 1. The Stack\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                              DEPLOYMENT                                      │\n│  Cloudflare Pages (Static + Edge Functions)                                  │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                       │\n│  │   Static    │  │   Edge      │  │   Asset     │                       │\n│  │   Assets    │  │   Functions │  │   Optimization │                       │\n│  │  (JS/CSS)   │  │  (API routes)│  │  (Images/Fonts)│                       │\n│  └─────────────┘  └─────────────┘  └─────────────┘                       │\n└─────────────────────────────────────────────────────────────────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                           BUILD PIPELINE                                     │\n│  Next.js 14 (App Router) → Turborepo → pnpm → Cloudflare Adapter           │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐       │\n│  │   TypeScript│  │   Tailwind  │  │   Vite      │  │   Wrangler  │       │\n│  │   (Strict)  │  │   CSS       │  │   (Dev)     │  │   (Deploy)  │       │\n│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘       │\n└─────────────────────────────────────────────────────────────────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         APPLICATION LAYER                                    │\n│                                                                              │\n│  ┌─────────────────────────────────────────────────────────────────────┐   │\n│  │                         APP SHELL                                     │   │\n│  │   Auth Guard · Header (Tenant) · Nav (Role×Dept) · Sidebar · Main     │   │\n│  └─────────────────────────────────────────────────────────────────────┘   │\n│                                                                              │\n│  ┌─────────────────────────────────────────────────────────────────────┐   │\n│  │                       WORKBENCH LAYERS                              │   │\n│  │  L0  OnboardingShell    → 4-step wizard (Profile/Goals/Connect/Hydrate)│   │\n│  │  L1  UserWorkbench      → Role×Dept×Industry hydrated shell           │   │\n│  │  L2  IntelligenceOverlay → Signals, briefs, insights panel           │   │\n│  │  L3  TwinWorkbench      → Chat interface, reasoning display          │   │\n│  │  L4  KnowledgeWorkbench → Memory hub, search, organizational graph   │   │\n│  │  L5  OperationsWorkbench → Proposals queue, situations, triage       │   │\n│  │  L6  ExecutionWorkbench  → Ready/running/audit handoff panel          │   │\n│  │  L7  GovernanceWorkbench → Pending review, decided, policies         │   │\n│  └─────────────────────────────────────────────────────────────────────┘   │\n│                                                                              │\n│  ┌─────────────────────────────────────────────────────────────────────┐   │\n│  │  SHARED COMPONENTS: Card · Table · Form · Modal · Toast · Chart ·     │   │\n│  │  Timeline · EmptyState (honest) · LoadingSkeleton                     │   │\n│  └─────────────────────────────────────────────────────────────────────┘   │\n└─────────────────────────────────────────────────────────────────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         STATE & DATA LAYER                                   │\n│  Zustand (Auth/Tenant/UI/Preferences) · SWR (fetch/cache/revalidate) ·       │\n│  WebSocket (DO events: signals/proposals/execution) · React Context          │\n│  (ProjectionContext — Single Authority)                                      │\n└─────────────────────────────────────────────────────────────────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                         DESIGN SYSTEM                                        │\n│  Tokens (CSS Vars) · Components (Radix UI) · Icons (Lucide) · Layout (Grid)  │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## 2. Monorepo Package Structure (Frontend)\n\n```\nintegratewise-live/\n├── apps/\n│   └── web/                          # Next.js 14 SPA\n│       ├── src/\n│       │   ├── app/                  # App Router (layout, pages, loading)\n│       │   │   ├── (auth)/         # Auth layout (login, register)\n│       │   │   ├── (onboarding)/   # Onboarding layout (L0)\n│       │   │   ├── (workspace)/    # Workspace layout (L1-L7)\n│       │   │   │   ├── engineering/# Engineering workbench (L1 build)\n│       │   │   │   ├── sales/      # Sales workbench (L1 grow)\n│       │   │   │   ├── operations/ # Operations workbench (L1 run)\n│       │   │   │   ├── twin/       # Twin interface (L3)\n│       │   │   │   ├── memory/     # Memory hub (L4)\n│       │   │   │   ├── proposals/  # Proposals queue (L5)\n│       │   │   │   ├── execution/  # Execution panel (L6)\n│       │   │   │   └── governance/ # Governance dashboard (L7)\n│       │   │   ├── api/            # Edge API routes (proxy to Gateway)\n│       │   │   └── layout.tsx      # Root layout with auth guard\n│       │   ├── components/         # app-shell / workbench / shared / twin / onboarding\n│       │   ├── hooks/              # useAuth / useProjection / useTenant / useTwin / ...\n│       │   ├── stores/             # authStore / uiStore / projectionStore / twinStore\n│       │   ├── lib/                # api (SWR) / websocket / validators / constants\n│       │   └── types/              # api / projection / twin / workbench\n│       ├── tailwind.config.ts\n│       ├── next.config.js\n│       └── wrangler.toml\n│\n├── packages/\n│   ├── design-tokens/              # THE source of truth (colors/typography/spacing/radii/shadows)\n│   ├── shared-types/               # Cross-package TypeScript (spine/projection/api)\n│   └── ui-components/              # primitives / composed / patterns\n│\n└── turbo.json\n```\n\n---\n\n## 3. The Design Token System\n\n### 3.1 Color Palette\n\n```typescript\n  primary: { blue: \"#4356A9\", navy: \"#232D42\", pink: \"#EB4F72\" },\n  background: {\n    base: \"#EDEEF0\",\n    card: \"#FFFFFF\",\n    elevated: \"#F8F9FA\",\n    overlay: \"rgba(35, 45, 66, 0.08)\",\n  },\n  text: { primary: \"#232D42\", secondary: \"#5A6578\", tertiary: \"#8B95A5\", inverse: \"#FFFFFF\" },\n  semantic: { success: \"#22C55E\", warning: \"#F59E0B\", error: \"#EF4444\", info: \"#3B82F6\" },\n  department: {\n    engineering: { accent: \"#4356A9\", bg: \"#F0F4FF\" },\n    sales: { accent: \"#EB4F72\", bg: \"#FEF2F2\" },\n    operations: { accent: \"#232D42\", bg: \"#F1F5F9\" },\n    cross: { accent: \"#8B5CF6\", bg: \"#F5F3FF\" },\n  },\n  connector: {\n    connected: \"#22C55E\",\n    connecting: \"#F59E0B\",\n    disconnected: \"#8B95A5\",\n    error: \"#EF4444\",\n  },\n} as const;\n```\n\n### 3.2 Typography\n\n```typescript\n  fontFamily: {\n    sans: \"Inter, system-ui, sans-serif\",\n    display: \"Poppins, Inter, sans-serif\",\n    mono: \"IBM Plex Mono, monospace\",\n  },\n  scale: {\n    \"2xs\": \"0.625rem\",\n    xs: \"0.75rem\",\n    sm: \"0.875rem\",\n    base: \"1rem\",\n    lg: \"1.125rem\",\n    xl: \"1.25rem\",\n    \"2xl\": \"1.5rem\",\n    \"3xl\": \"1.875rem\",\n    \"4xl\": \"2.25rem\",\n  },\n  weight: { normal: 400, medium: 500, semibold: 600, bold: 700 },\n  lineHeight: { tight: 1.25, normal: 1.5, relaxed: 1.75 },\n} as const;\n```\n\n### 3.3 Spacing, Radii, Shadows\n\n```typescript\n// 4px base grid; layout: maxWidth 1440px, sidebar 280px, header 64px, gutter 24px\n// radii: sm 4px (inputs) · md 8px (cards) · lg 12px (panels) · xl 16px (hero) · full 9999px (pills)\n// shadows: FLAT — no 3D, no gradients. sm/md/lg subtle elevation + focus ring (primary blue)\n```\n\n---\n\n## 4. Component Architecture\n\n### 4.1 The Three Tiers\n\n```\nTIER 3: PATTERNS    → EmptyState (honest) · DataTable · FormBuilder · OnboardingStepWizard ·\n                      ProposalReviewCard · ExecutionTimeline\nTIER 2: COMPOSITES  → Card · Modal · Toast · Tabs · Breadcrumb · Dropdown · Pagination · Tooltip · Badge\nTIER 1: PRIMITIVES  → Button · Input · Select · Avatar · Switch · Textarea · Checkbox · Radio · Label\n                      (Radix UI base + design tokens)\n```\n\n### 4.2 The Empty State Rule\n\nEvery data-dependent component has an honest empty state. No fabricated data. No placeholder charts.\n\n```tsx\n<EmptyState\n  icon={<GitHubIcon />}\n  title=\"No engineering data yet\"\n  description=\"Connect GitHub to see repository health, pull requests, and team activity.\"\n  action={<Button onClick={openConnectorTray}>Connect GitHub</Button>}\n  secondary=\"It takes about 2 hours to load your first data.\"\n/>\n```\n\n### 4.3 The Loading State Rule\n\nSkeleton screens, not spinners. Skeletons match the final layout.\n\n```tsx\n<TableSkeleton rows={5} columns={[\"Repository\", \"Status\", \"Last Activity\", \"Health\"]} />\n```\n\n---\n\n## 5. State Management\n\n### 5.1 The Single Authority (ProjectionContext)\n\n```typescript\n// stores/projectionStore.ts — one role/department/industry value, set once per session\ninterface ProjectionState {\n  role: string | null;\n  department: string | null;\n  industry: string | null;\n  depthMatrix: DepthMatrix | null;\n  twinTier: string | null;\n  entitlements: string[];\n  setProjection: (context: ProjectionContext) => void;\n  clearProjection: () => void;\n}\n```\n\n### 5.2 The Single Authority Hook\n\n```typescript\n// hooks/useProjection.ts — fetch /api/v1/workspace/profile ONCE, dedupe 1h, no focus revalidate\n  const { role, department, industry, setProjection } = useProjectionStore();\n  const { data, error } = useSWR(\"/api/v1/workspace/profile\", apiFetcher, {\n    revalidateOnFocus: false,\n    revalidateOnReconnect: false,\n    dedupingInterval: 3600000,\n  });\n  useEffect(() => {\n    if (data?.projection) setProjection(data.projection);\n  }, [data, setProjection]);\n  return { role, department, industry, isLoading: !data && !error };\n}\n```\n\n### 5.3 Tenant-Scoped Data Fetching\n\n```typescript\n// lib/api.ts — every request carries Bearer token + X-Tenant-ID to the Gateway\n  const token = useAuthStore.getState().token;\n  const tenant = useAuthStore.getState().tenantId;\n  const res = await fetch(`${process.env.NEXT_PUBLIC_GATEWAY_URL}${url}`, {\n    headers: {\n      Authorization: `Bearer ${token}`,\n      \"X-Tenant-ID\": tenant,\n      \"Content-Type\": \"application/json\",\n    },\n  });\n  if (!res.ok) throw new Error(`API error: ${res.status}`);\n  return res.json();\n};\n```\n\n---\n\n## 6. Data Fetching Strategy\n\n### 6.1 SWR Configuration\n\nStale-while-revalidate: show cached data immediately, refresh in background. No polling by default.\nRevalidate on focus + reconnect. Dedupe within 2s. Retry failed requests 3×. Tenant-scoped cache key.\n\n### 6.2 Real-Time Updates (WebSocket)\n\n```typescript\n// lib/websocket.ts — connect to the tenant Durable Object; invalidate SWR caches on push\nthis.ws = new WebSocket(`wss://gateway.integratewise.ai/ws/${tenantId}?token=${token}`);\n// signal:new → mutate('/api/v1/signals') + toast\n// proposal:created → mutate('/api/v1/proposals') + toast\n// execution:completed → mutate('/api/v1/executions') + toast.success\n// memory:promoted → mutate('/api/v1/memory')\n```\n\n---\n\n## 7. The Gateway Proxy Pattern\n\nThe frontend never calls external APIs directly. All requests go through the Gateway.\n\n```\nFrontend SPA (Pages) → /api/v1/* Edge Routes → Cloudflare Gateway Worker → Internal Services → D1 / Queues / DO / Vectorize\n```\n\n| Without Proxy                   | With Proxy                  |\n| ------------------------------- | --------------------------- |\n| CORS issues                     | No CORS (same origin)       |\n| Token exposed in browser        | Token in edge function only |\n| Direct service URLs in frontend | Single Gateway URL          |\n| No request logging              | Centralized audit log       |\n| No rate limiting                | Gateway-enforced quotas     |\n\n---\n\n## 8. Authentication Flow\n\n```\nUser Login → Auth Service (Worker) → JWT (RS256) + Refresh Token\n  → httpOnly secure sameSite=strict cookies\nEvery Request: Edge Function reads cookie → validates JWT → adds X-Tenant-ID → proxies to Gateway\nToken Refresh (silent): 401 → Edge Function uses refresh token → new JWT → retries → user never sees logout\n```\n\n---\n\n## 9. Build & Deploy Pipeline\n\n```\nDeveloper Push → GitHub Actions\n  1. Typecheck (tsc --noEmit)\n  2. Lint (eslint + prettier)\n  3. Unit Tests (vitest)\n  4. Build (next build)\n  5. E2E Tests (Playwright)\n  6. Deploy to Cloudflare Pages (wrangler)\n→ Cloudflare Pages → Global Edge (300+ locations)\n```\n\n```bash\n# .env.local (development)\nNEXT_PUBLIC_GATEWAY_URL=https://gateway.integratewise.ai\nNEXT_PUBLIC_WS_URL=wss://gateway.integratewise.ai/ws\nNEXT_PUBLIC_APP_VERSION=3.7.0\n```\n\n---\n\n# PART II: USER VIEW\n\n## How People See and Interact\n\n---\n\n## 1. The Visual Philosophy\n\n> **\"Calm, precise intelligence plumbing for complex enterprise stacks.\"**\n\n| Principle        | What It Means                                          | What It Rejects                                         |\n| ---------------- | ------------------------------------------------------ | ------------------------------------------------------- |\n| **Calm**         | Low cognitive load. Whitespace. Breathing room.        | Dense dashboards, information overload, alert fatigue   |\n| **Precise**      | Every pixel has purpose. No decoration.                | Gradients, 3D effects, heavy shadows, ornamental icons  |\n| **Intelligence** | The UI reveals insight, not just data.                 | Raw tables, unprocessed metrics, disconnected numbers   |\n| **Plumbing**     | The infrastructure is invisible. The value is visible. | Technical jargon, implementation details, system status |\n\n```\n✅ Flat vectors (no gradients)        ✅ Grid-aligned diagrams\n✅ Simple lines and nodes (no 3D)     ✅ Minimal whitespace (no clutter)\n✅ Rounded rectangles                  ✅ Inter + Poppins + IBM Plex Mono\n✅ #4356A9 blue, #232D42 navy, #EB4F72 pink (no rainbow palettes)\n```\n\n---\n\n## 2. The App Shell\n\n- **Header (always visible):** Logo · Command-K global search · Signals badge · Profile + tenant · Settings\n- **Navigation (Role × Department):** filtered by role; the user's department is expanded + highlighted\n- **Sidebar (contextual):** adapts to the active workbench (repos+filters in Engineering, pipelines+stages in Sales)\n\n---\n\n## 3. The Workbench Layers (L1–L7)\n\n- **L1 User Workbench (shell):** cards with counts + actions (no raw tables on overview); human-readable signals; \"last updated\" timestamp; honest empty states.\n- **L2 Intelligence Overlay (brief):** department-grouped morning brief panel; each item has a clear action/dismiss; the brief IS the summary.\n- **L3 Twin Workbench:** Twin speaks first; every answer has sources; proposals embedded in chat; sources link to Spine entities (\"Sources: GitHub (build_data) — last synced 2 min ago\").\n- **L4 Knowledge Workbench (Memory):** searchable (not browsable); scope visible (org/team/personal); confidence score transparent; evidence linked; \"Formed: X ago\" shows compounding.\n- **L5 Operations Workbench (Proposals):** proposals as cards; reasoning visible; evidence linked; 5 actions (Approve/Reject/Modify/Delegate/Schedule); no auto-execute, no \"approve all\".\n- **L6 Execution Workbench (Monitor):** running executions prominent; each links to the external tool; completed collapsed; failed highlighted + auditable.\n- **L7 Governance Workbench (Audit):** decisions countable/trendable; policies visible+editable; audit trail exportable; every decision links back to the proposal.\n\n---\n\n## 4. The Onboarding Experience (L0)\n\n4 steps, not 10. Role/department/industry as visual cards. Connector tray scored and limited to 5.\nProgress is honest (no fabricated completion). \"You can start exploring\" — the user is never blocked.\n\n```\nStep 1 Welcome → Step 2 Identity (Role/Dept/Industry) → Step 3 Goals →\nStep 4 Connectors (5 recommended, OAuth via Nango) → Step 5 Hydration (honest progress) → Workspace\n```\n\n---\n\n# PART III: THE BRIDGE\n\n## How Frontend Enables the User Experience\n\n| User Action        | Frontend System                          | Backend Call                               | Technology             |\n| ------------------ | ---------------------------------------- | ------------------------------------------ | ---------------------- |\n| \"Log in\"           | Auth Guard → Zustand authStore           | POST /api/v1/auth/login                    | JWT, Cloudflare Access |\n| \"Select role\"      | Onboarding Step Wizard → projectionStore | POST /api/v1/workspace/initialize          | Gateway → D1           |\n| \"Connect GitHub\"   | Connector Tray → OAuth popup             | Nango OAuth → Token vault                  | Nango, Gateway         |\n| \"See workspace\"    | useProjection() → SWR → Layout render    | GET /api/v1/workspace/profile              | SWR, D1                |\n| \"Ask Twin\"         | Chat Input → useTwin() → WebSocket       | POST /api/v1/twin/chat → DO Session        | WebSocket, Workers AI  |\n| \"Get brief\"        | Brief Panel → SWR revalidate             | GET /api/v1/twin/brief                     | SWR, D1                |\n| \"Approve proposal\" | Proposal Card → Button → Toast           | POST /api/v1/proposals/:id/approve → Queue | Queue, Governance DO   |\n| \"View execution\"   | Execution Timeline → SWR                 | GET /api/v1/executions                     | SWR, D1                |\n| \"Search memory\"    | Memory Search → Vectorize query          | GET /api/v1/memory?q=                      | Vectorize, D1          |\n| \"Get signal\"       | WebSocket push → Toast                   | DO Event → WebSocket                       | DO, WebSocket          |\n\n---\n\n## The Frontend Promise\n\n> **Systems View:** Every user action flows through a typed, cached, real-time pipeline. State is predictable. Data is tenant-scoped. UI is token-driven. No direct API calls. No unvalidated state.\n\n> **User View:** The interface adapts to who I am. It loads fast. It updates in real-time. It never lies about data freshness. It never shows fabricated data. It gets out of the way so I can work.\n\n> **The Bridge:** The same design system that makes the UI calm and precise (flat vectors, rounded rectangles, honest empty states) is what makes the frontend architecture maintainable and predictable (design tokens, component tiers, single authority).\n\n---\n\n_This document is the canonical frontend architecture of IntegrateWise v3.7. It specifies both the engine (Systems View) and the experience (User View), with the bridge between them._\n\n---\n\n## Appendix: Doc ↔ Code Reconciliation (as of 2026-06-15)\n\n> This doc is the **canonical/target** frontend architecture. Reconcile these deltas with the\n> running code over time rather than treating them as drift.\n\n- **Framework:** `apps/web` currently builds as a **Vite + React SPA** (`import.meta.env.VITE_*`,\n  `pnpm run dev`), not Next.js App Router. Update whichever is authoritative.\n- **Auth token transport:** the running app stores the gateway RS256 JWT in `localStorage` (`iw_at`)\n  and sends it as a `Bearer` header (see `apps/web/src/lib/auth-manager.ts`); this doc's httpOnly-cookie\n  model is the target.\n- **Gateway base URL:** dev points at `gateway.dev.integratewise.ai` via `apps/web/.env.local`.\n- **Onboarding flow** matches `OnboardingFlow.tsx` (Welcome → Profile → Goals → Connectors → AILoader →\n  WorkplaceLoading → workspace).\n"}