Compare commits

..

10 Commits

16 changed files with 17875 additions and 72 deletions
+1
View File
@@ -7,6 +7,7 @@ yarn-error.log*
pnpm-debug.log* pnpm-debug.log*
lerna-debug.log* lerna-debug.log*
.env
node_modules node_modules
dist dist
dist-ssr dist-ssr
@@ -0,0 +1,185 @@
{
"project": "Portfolio — Login Logo & Blur Refinements",
"branchName": "ralph/login-logo-refinements",
"description": "Refine the login screen's CVMIS logo animation, backdrop blur coverage/intensity, and align visual details (border radius, shadows, colors, typography) with the dashboard design system.",
"userStories": [
{
"id": "US-001",
"title": "Skip to login phase for dev iteration",
"description": "As a developer, I want to skip boot/ECG and land directly on the login screen so I can iterate on login changes quickly.",
"acceptanceCriteria": [
"In src/App.tsx, change the initial Phase state from 'boot' to 'login'",
"The boot, ECG, and login phases remain in code — only the initial state changes",
"App loads directly to the login screen on refresh",
"Typecheck passes"
],
"priority": 1,
"passes": true,
"notes": "Temporary — final story reverts this. Phase state is on line 47 of App.tsx."
},
{
"id": "US-002",
"title": "Extract animation timing into named constants",
"description": "As a developer, I want all animation timing values in CvmisLogo.tsx exposed as named constants at the top of the file so I can quickly tune rise speed, fan speed, fan delay, and easing.",
"acceptanceCriteria": [
"Named constants at the top of CvmisLogo.tsx for: rise duration (currently 500ms), fan delay after rise (currently 500ms), fan duration (currently 600ms), fan easing curve, fan rotation angle (currently ±50°), fan horizontal spacing (currently ±16px), right pill stagger delay (currently 30ms)",
"Additional named constants for overlap blend: OVERLAY_BLEND_START_PROGRESS (target 0.5), OVERLAP_BLEND_MAX_OPACITY (target 0.2), OVERLAP_BLEND_TRANSITION_DURATION",
"Component behaviour unchanged when constants retain current values",
"Constants are clearly named and grouped with a brief comment block",
"Typecheck passes"
],
"priority": 2,
"passes": true,
"notes": "Read CvmisLogo.tsx carefully first — some timing values are inline in useEffect/motion props. Extract them ALL to top-level constants. The blend constants are new (for US-004) but should be defined now with sensible defaults."
},
{
"id": "US-003",
"title": "Scale logo and branding block to ~50% of login card height",
"description": "As a visitor, I want the CVMIS logo and branding text to be larger and more prominent, occupying roughly half the login card's height.",
"acceptanceCriteria": [
"Logo cssHeight scaled up from current clamp(48px, 4vw, 64px) — target approximately clamp(160px, 18vw, 280px), tune visually for balance",
"Width scales proportionally (SVG viewBox preserves aspect ratio)",
"The branding block (logo + CVMIS title + subtitle + spacing) occupies approximately 50% of the total login card height",
"Logo does not overflow or clip on mobile viewports (>=375px wide)",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 3,
"passes": true,
"notes": "CvmisLogo accepts cssHeight prop (string) for CSS clamp values. The branding block is in LoginScreen.tsx — the logo, title, and subtitle are in a flex column container. Adjust the cssHeight prop on the CvmisLogo component and check the ratio visually."
},
{
"id": "US-004",
"title": "Increase branding text to match dashboard typography scale",
"description": "As a visitor, I want the CVMIS title and subtitle on the login screen to be larger and more in line with the dashboard's typography scale.",
"acceptanceCriteria": [
"CVMIS title font size increased from 13px — target approximately 18-20px to match dashboard heading scale",
"CV Management Information System subtitle font size increased from 11px — target approximately 13-14px",
"Both remain in font-ui (Elvaro Grotesque) with appropriate weight hierarchy",
"Text remains visually balanced with the larger logo above and the login form below",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 4,
"passes": true,
"notes": "The title and subtitle are in LoginScreen.tsx in the branding section. Look for the CVMIS text and its fontSize style. Use clamp() for responsive sizing consistent with the card's responsive approach."
},
{
"id": "US-005",
"title": "Add overlap blend effect on fanning capsules",
"description": "As a visitor, I want to see a subtle color blend where the fanning capsules overlap, matching the multiply-blend effect from the Remotion animation.",
"acceptanceCriteria": [
"CSS mix-blend-mode: multiply applied to the fanning pill elements in CvmisLogo.tsx",
"Blend effect is not visible at the start of the fan animation",
"Blend fades in starting at ~50% of fan animation progress (using OVERLAY_BLEND_START_PROGRESS constant from US-002)",
"Blend reaches max intensity by end of fan (using OVERLAP_BLEND_MAX_OPACITY constant from US-002)",
"Max blend opacity approximately 0.2 (20%)",
"Blend is only perceptible where capsules actually overlap on light backgrounds",
"Blend transition feels smooth, not abrupt",
"Respects prefers-reduced-motion (no animation, show final state)",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 5,
"passes": true,
"notes": "Use framer-motion's useTransform or a progress-based approach to derive blend opacity from fan animation progress. The pill elements are <g> groups inside the SVG. Apply mixBlendMode: 'multiply' as a style and animate the group's opacity using the timing constants from US-002. The blend should only be visible during/after the fan phase, not during the rise phase."
},
{
"id": "US-006",
"title": "Extend backdrop blur to cover full dashboard including TopBar",
"description": "As a visitor, I want the frosted-glass blur behind the login card to cover the entire dashboard including the TopBar, so nothing behind the overlay is sharp.",
"acceptanceCriteria": [
"Blur overlay z-index raised above TopBar z-index (TopBar is zIndex: 100, overlay is currently z-50). Overlay must be >= zIndex: 110 or similar",
"TopBar, Sidebar, and all dashboard content are uniformly blurred behind the overlay",
"Login card itself remains crisp and unblurred (card z-index above overlay)",
"Blur still fades out during the dissolve/exit transition",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 6,
"passes": true,
"notes": "LoginScreen outer overlay currently has 'fixed inset-0 z-50'. TopBar is zIndex: 100. The overlay needs z-index > 100 to cover it. The login card inside the overlay doesn't need its own z-index since it's a child of the overlay. Check that the dissolve exit animation (isExiting) still works after the z-index change."
},
{
"id": "US-007",
"title": "Reduce backdrop blur intensity by ~50%",
"description": "As a visitor, I want the backdrop blur to be softer so the dashboard behind is slightly more visible while still providing contrast for the login card.",
"acceptanceCriteria": [
"Blur value reduced from blur(20px) to approximately blur(10px)",
"The blur value is a named constant co-located with other LoginScreen timing constants for easy adjustment",
"Login card remains clearly readable against the softened backdrop",
"The dissolve exit animation still animates blur from 10px to 0px",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 7,
"passes": true,
"notes": "The blur is in two places in LoginScreen.tsx: the initial style (backdropFilter: blur(20px)) and the exit animation (animates from blur(20px) to blur(0px)). Extract the blur value to a constant like BACKDROP_BLUR_PX = 10, then reference it in both places."
},
{
"id": "US-008",
"title": "Align login card border radius and shadow with dashboard design system",
"description": "As a visitor, I want the login card to feel like it belongs to the same design system as the dashboard by matching border radius and shadow tokens.",
"acceptanceCriteria": [
"Login card border radius changed from 12px to 8px (matching var(--radius-card) / dashboard cards)",
"Login input fields and button border radius changed from 4px to 6px (matching var(--radius-sm) / dashboard inner elements)",
"Login card shadow upgraded from shadow-sm to shadow-lg (0 8px 32px rgba(26,43,42,0.12)) — appropriate for a floating modal over blurred backdrop",
"Use CSS custom property references (var(--radius-card), var(--radius-sm)) where available rather than hardcoded values",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 8,
"passes": true,
"notes": "Check index.css for whether --radius-card and --radius-sm exist as CSS custom properties. If not, use the hardcoded values (8px and 6px) directly. The card shadow is currently set via inline style — update to the shadow-lg value. The login card borderRadius is in the card's inline style object."
},
{
"id": "US-009",
"title": "Replace hardcoded colors with design tokens",
"description": "As a developer, I want the login screen to reference the same CSS custom properties as the dashboard so palette changes propagate consistently.",
"acceptanceCriteria": [
"Input text color changed from hardcoded #111827 to var(--text-primary, #1A2B2A)",
"Cursor/caret color changed from hardcoded #0D6E6E to var(--accent, #0D6E6E)",
"Button background colors changed from hardcoded #0D6E6E / #0A8080 / #085858 to var(--accent) / var(--accent-hover) / appropriate pressed variant using token references",
"Any other hardcoded color values in LoginScreen.tsx that have corresponding CSS custom properties use the token instead",
"No visual change (token values resolve to same colors currently)",
"Typecheck passes"
],
"priority": 9,
"passes": true,
"notes": "Search LoginScreen.tsx for all hex color values (#xxxxxx) and check whether a corresponding CSS custom property exists in index.css. Some colors were already tokenized in the previous login rework (US-003 of previous run) — verify which ones are still hardcoded. The button has multiple color states (default, hover, pressed) — check all three."
},
{
"id": "US-010",
"title": "Fix minor typography inconsistencies",
"description": "As a visitor, I want the login screen's typography weight and sizing to feel consistent with the dashboard's conventions.",
"acceptanceCriteria": [
"Form label font weight increased from 500 to 600 (matching dashboard card header weight convention)",
"Input text mid-value aligned to ~14px to match dashboard body text",
"Button text mid-value aligned to ~15px",
"Connection status indicator gap increased from 6px to 8px (matching dashboard CardHeader gap)",
"No dramatic visual change — these are subtle alignment fixes",
"Typecheck passes"
],
"priority": 10,
"passes": true,
"notes": "These are small inline style tweaks in LoginScreen.tsx. The labels, inputs, and button already use clamp() for responsive sizing — just adjust the mid-values. The connection indicator gap is in the flex container styling near the bottom of the component."
},
{
"id": "US-011",
"title": "Re-enable boot sequence",
"description": "As a user, I want the full boot → ECG → login → dashboard experience restored.",
"acceptanceCriteria": [
"In src/App.tsx, change the initial Phase state back from 'login' to 'boot'",
"Boot → ECG → Login → Dashboard sequence works end to end",
"Login screen shows blurred dashboard behind it with reduced blur and full TopBar coverage",
"Logo animation plays with blend effect, typing animation follows, connection indicator transitions, button pulses",
"Clicking login dissolves the overlay to reveal the dashboard",
"Typecheck passes",
"Verify in browser using dev-browser skill"
],
"priority": 11,
"passes": true,
"notes": "Simple revert of US-001. Phase state is on line 47 of App.tsx."
}
]
}
@@ -0,0 +1,202 @@
# Progress Log — Login Logo & Blur Refinements
# Branch: ralph/login-logo-refinements
# Started: 2026-02-15
## Codebase Patterns
### Project Structure
- Components in `src/components/`, tiles in `src/components/tiles/`
- Data files in `src/data/`
- Types in `src/types/pmr.ts` and `src/types/index.ts`
- Hooks in `src/hooks/`, Contexts in `src/contexts/`, Lib in `src/lib/`
- Path alias: `@/` maps to `./src/`
### Phase Management
- App.tsx controls phase: 'boot' -> 'ecg' -> 'login' -> 'pmr'
- BootSequence.tsx, ECGAnimation.tsx — LOCKED, do not modify
- LoginScreen.tsx bridges to dashboard
### Typography
- Elvaro Grotesque (`font-ui`, `var(--font-ui)`) — primary UI font
- Blumir (`font-ui-alt`) — alternative variable font
- Geist Mono (`font-geist`, `var(--font-geist-mono)`) — timestamps, data values
- Fira Code (`font-mono`) — boot/ECG terminal only
- Do NOT use Inter, Roboto, DM Sans, or system defaults
### Design Tokens (index.css CSS variables)
- --surface: #FFFFFF (card/topbar background)
- --bg-dashboard: #F0F5F4 (warm sage content background)
- --accent: #0D6E6E (teal primary)
- --accent-hover: #0A8080
- --accent-pressed: #085858
- --accent-light: rgba(10,128,128,0.08)
- --border: #D4E0DE (structural borders)
- --border-card: #E4EDEB (card/inner borders)
- --text-primary: #1A2B2A
- --text-secondary: #5B7A78
- --text-tertiary: #8DA8A5
- --sidebar-width: 304px
- --topbar-height: 56px
### Known Dependencies
- React 18.3.1, TypeScript, Vite, Tailwind CSS
- Framer Motion 11.15.0, Lucide React 0.468.0, fuse.js 7.0.0
### Key Files for This Feature
- src/components/CvmisLogo.tsx — logo component with animation (timing constants to extract)
- src/components/LoginScreen.tsx — main login screen (overlay, blur, card styling)
- src/App.tsx — phase management (skip/restore boot sequence)
- src/index.css — CSS custom properties, design tokens
### CvmisLogo Component (from previous run)
- `size` prop: numeric, sets SVG height attribute directly
- `cssHeight` prop: string, sets height via CSS style (use for clamp/responsive values)
- `animated` prop: boolean, enables framer-motion reveal animation (1000ms total)
- Logo animation: 500ms rise (green capsule) + 500ms fan-out (all three) = 1000ms total
- All timing values are named constants at top of file — tune there, not inline
- Blend constants (OVERLAY_BLEND_*) are exported for use by other components (US-005)
### LoginScreen.tsx State (from previous run)
- Overlay: fixed inset-0 zIndex: 110, rgba(240, 245, 244, 0.7) + backdrop-filter: blur(20px)
- TopBar is zIndex: 100 — overlay now correctly covers it (fixed in US-006)
- Card borderRadius: 12px, inputs/button borderRadius: 4px
- Some colors already tokenized (--surface, --accent, --bg-dashboard) from previous run
- Some colors still hardcoded (#111827 input text, button bg states, caret color)
---
## 2026-02-15 - US-001: Skip to login phase for dev iteration
- Changed initial Phase state from `'boot'` to `'login'` in `src/App.tsx` line 47
- Files changed: `src/App.tsx`
- **Learnings for future iterations:**
- Phase state is a simple `useState<Phase>` on line 47 of App.tsx
- All phase rendering logic (`boot`, `ecg`, `login`, `pmr`) remains intact — only initial value changes
- US-011 will revert this exact change back to `'boot'`
---
## 2026-02-15 - US-002: Extract animation timing into named constants
- Extracted all inline timing values in CvmisLogo.tsx to named constants at top of file
- Constants added: RISE_DURATION_MS, RISE_DURATION_S, RISE_OPACITY_DURATION_S, RISE_EASING, RISE_START_Y, FAN_DELAY_AFTER_RISE_MS, FAN_DURATION_S, FAN_ROTATION_DEG, FAN_HORIZONTAL_PX, FAN_RIGHT_STAGGER_S, TOTAL_ANIMATION_MS
- Added overlap blend constants for US-005: OVERLAY_BLEND_START_PROGRESS, OVERLAP_BLEND_MAX_OPACITY, OVERLAP_BLEND_TRANSITION_DURATION_S (exported)
- Files changed: `src/components/CvmisLogo.tsx`
- **Learnings for future iterations:**
- Blend constants are `export`ed because TypeScript strict mode flags unused `const` declarations — exporting avoids the TS6133 error while making them available for US-005
- TOTAL_ANIMATION_MS is computed from FAN_DELAY_AFTER_RISE_MS + FAN_DURATION_S * 1000, so changing rise or fan timing automatically updates the done-timer
- FAN_EASING was already a named constant before this story; it was left in place and grouped with the new fan constants
---
## 2026-02-15 - US-003: Scale logo and branding block to ~50% of login card height
- Scaled CvmisLogo `cssHeight` prop from `clamp(80px, 8vw, 120px)` to `clamp(160px, 18vw, 280px)`
- Adjusted logo wrapper marginBottom from 10px to 12px for spacing balance
- Browser-verified: desktop ratio 51.3% (target 50% ±10%), mobile (375px) ratio 41.1% — both within tolerance
- No overflow or clipping on mobile viewport
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- The CvmisLogo `cssHeight` prop maps directly to a CSS `height` style on the SVG — `clamp()` values work well for responsive scaling
- At 375px viewport, `18vw = 67.5px` which triggers the clamp minimum of 160px — the logo remains a comfortable size on small screens
- The branding block ratio can be measured by comparing `brandingBlock.getBoundingClientRect().height + marginBottom` against `card.innerHeight - padding`
- The branding block container has class `flex flex-col items-center` — use this selector for programmatic measurement
---
## 2026-02-15 - US-004: Increase branding text to match dashboard typography scale
- Increased CVMIS title fontSize from `13px` to `clamp(16px, 1.4vw, 20px)` — renders 20px on desktop
- Increased subtitle fontSize from `11px` to `clamp(12px, 1vw, 14px)` — renders 14px on desktop
- Increased subtitle marginTop from `2px` to `3px` for better spacing with larger text
- Both remain in font-ui (Elvaro Grotesque) with weight 600 (title) and 400 (subtitle)
- Browser-verified: text is visually balanced with the larger logo and login form
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- The branding text clamp values use the same responsive pattern as the logo `cssHeight` — mid-values around 1-1.5vw work well for text
- Title and subtitle are `<span>` elements inside the `.flex.flex-col.items-center` branding container
- Weight hierarchy (600 title, 400 subtitle) provides sufficient visual differentiation without needing size contrast as large
---
## 2026-02-15 - US-005: Add overlap blend effect on fanning capsules
- Added `blendActive` state to CvmisLogo, triggered by timer at `blendStartMs` (50% through fan animation)
- Added two blend overlay `<g>` elements after the main pills: copies of left/right pill shapes with `mixBlendMode: 'multiply'` and opacity transitioning from 0 to 0.2
- Blend overlays share the same `transform` and `transition` as their corresponding original pills, plus an opacity transition using `OVERLAP_BLEND_TRANSITION_DURATION_S`
- Reduced motion: `blendActive` starts `true`, `transition: 'none'` — final blend state shown immediately
- Browser-verified: blend darkening visible at pill overlap areas, opacity confirmed at 0.2
- Files changed: `src/components/CvmisLogo.tsx`
- **Learnings for future iterations:**
- `mix-blend-mode` is not CSS-animatable — use overlay elements with animated opacity instead of trying to transition the blend mode
- Blend overlay approach: duplicate the pill shapes (rect only, no icons) as separate `<g>` elements with `mixBlendMode: 'multiply'` and low opacity
- The `useMemo` for `blendStartMs` avoids recalculation — all timing constants are module-level so this is stable
- Combined CSS transition strings work in SVG `<g>` style: `transform 0.6s cubic-bezier(...), opacity 0.3s ease-out`
---
## 2026-02-15 - US-006: Extend backdrop blur to cover full dashboard including TopBar
- Changed overlay from Tailwind `z-50` class to inline `zIndex: 110` to sit above TopBar (`zIndex: 100`)
- Browser-verified: TopBar, sidebar, and all content uniformly blurred; login card remains crisp
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- TopBar uses inline `zIndex: 100` (not a Tailwind class), so overlay needs inline zIndex > 100
- Tailwind's `z-50` = z-index 50, which was below the TopBar — switched to inline style for precise control
- The login card doesn't need its own z-index since it's a child of the overlay and inherits stacking context
---
## 2026-02-15 - US-007: Reduce backdrop blur intensity by ~50%
- Added `BACKDROP_BLUR_PX = 10` constant at top of LoginScreen.tsx
- Replaced hardcoded `blur(20px)` in initial style with template literal using constant
- Exit animation still targets `blur(0px)` — Framer Motion interpolates from current 10px to 0px
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- The `BACKDROP_BLUR_PX` constant is in the "Login screen timing & visual constants" block at top of LoginScreen.tsx
- Framer Motion's `animate` prop interpolates from the element's current computed style, so the exit blur animation doesn't need the starting value explicitly
- Only the initial style needs the constant; the exit target (`blur(0px)`) is always 0
---
## 2026-02-15 - US-008: Align login card border radius and shadow with dashboard design system
- Changed card borderRadius from `12px` to `var(--radius-card, 8px)`
- Changed card boxShadow from `shadow-sm` (`0 1px 2px rgba(26,43,42,0.05)`) to `var(--shadow-lg, 0 8px 32px rgba(26,43,42,0.12))`
- Changed username input, password input, and button borderRadius from `4px` to `var(--radius-sm, 6px)`
- All values use CSS custom property references with fallbacks
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- CSS tokens `--radius-card`, `--radius-sm`, `--shadow-sm`, `--shadow-md`, `--shadow-lg` are all defined in `index.css` `:root` — use `var()` references with fallback values
- The button has 18-space indentation vs 20-space for inputs — `replace_all` may not catch all instances if matching on indentation
- The spinner (`borderRadius: '50%'`) and status indicator dot should NOT be changed — they're circles, not card elements
---
## 2026-02-15 - US-009: Replace hardcoded colors with design tokens
- Replaced all hardcoded hex colors in LoginScreen.tsx with CSS custom property references (`var()` with fallbacks)
- Input text color: `#111827` → `var(--text-primary, #1A2B2A)`
- Cursor/caret color: `#0D6E6E` → `var(--accent, #0D6E6E)` (2 instances)
- Button backgrounds: `#0D6E6E` → `var(--accent)`, `#0A8080` → `var(--accent-hover)`, `#085858` → `var(--accent-pressed)`
- Spinner border/top: `#E4EDEB` → `var(--border-light)`, `#0D6E6E` → `var(--accent)`
- Input inactive borders: `#E4EDEB` → `var(--border-light)` (username + password fields)
- Card border: `#E4EDEB` → `var(--border-light)`
- Footer border: `#E4EDEB` → `var(--border-light)`
- Connection status colors: `#059669` → `var(--success)`, `#DC2626` → `var(--alert)` (dot bg + text)
- Focus ring: `ring-[#0D6E6E]/40` → `ring-accent/40` (Tailwind token)
- Added `--accent-pressed: #085858` token to `index.css` `:root` (completes the accent state trio)
- Files changed: `src/components/LoginScreen.tsx`, `src/index.css`
- **Learnings for future iterations:**
- `#FFFFFF` on button text is intentional for contrast — no `--text-on-accent` token exists; leave as hardcoded white
- `rgba(240, 245, 244, 0.7)` overlay bg is `--bg-dashboard` at 70% opacity — no token for this; leave as rgba
- Status dot glow `boxShadow` uses rgba variants of success/alert colors at 40% opacity — no token for these glow effects
- Tailwind config has `accent` and `accent-hover` color tokens, so `ring-accent/40` works in class names
- Always add fallback values in `var()` references (e.g., `var(--accent, #0D6E6E)`) for resilience
---
## 2026-02-15 - US-010: Fix minor typography inconsistencies
- Changed form label fontWeight from 500 to 600 (both Username and Password labels) to match dashboard card header weight convention
- Adjusted input text fontSize mid-value from `clamp(13px, 1.1vw, 15px)` to `clamp(13px, 1.2vw, 15px)` — renders ~14-15px on standard viewports
- Adjusted button text fontSize mid-value from `clamp(14px, 1.1vw, 16px)` to `clamp(14px, 1.2vw, 16px)` — renders ~15px on standard viewports
- Changed connection status indicator gap from 6px to 8px (matching dashboard CardHeader gap)
- Files changed: `src/components/LoginScreen.tsx`
- **Learnings for future iterations:**
- These are all subtle alignment tweaks — the clamp mid-value change from 1.1vw to 1.2vw shifts rendering by ~1px on 1280px viewports
- The label fontWeight 600 matches the dashboard's `CardHeader` convention (seen in `Card.tsx`)
- The connection indicator gap of 8px matches the standard icon-text gap used in dashboard card headers
---
## 2026-02-15 - US-011: Re-enable boot sequence
- Changed initial Phase state from `'login'` back to `'boot'` in `src/App.tsx` line 47
- Reverts the dev shortcut from US-001, restoring the full boot → ECG → login → dashboard flow
- Typecheck and lint pass cleanly
- Files changed: `src/App.tsx`
- **Learnings for future iterations:**
- This is a simple one-line revert — the phase state controls the entire UI flow
- All 11 stories in this PRD are now complete
---
+8 -8
View File
@@ -53,7 +53,7 @@
"Typecheck passes" "Typecheck passes"
], ],
"priority": 3, "priority": 3,
"passes": false, "passes": true,
"notes": "The pipeline returns a Tensor — use .tolist() or .data to extract the raw float array. Mean-pool across the token dimension (dim 1) to get a single 384-d vector per input. Process items sequentially to avoid OOM in Node. The output file will be ~200KB for ~40 items with 384 floats each." "notes": "The pipeline returns a Tensor — use .tolist() or .data to extract the raw float array. Mean-pool across the token dimension (dim 1) to get a single 384-d vector per input. Process items sequentially to avoid OOM in Node. The output file will be ~200KB for ~40 items with 384 floats each."
}, },
{ {
@@ -72,7 +72,7 @@
"Typecheck passes" "Typecheck passes"
], ],
"priority": 4, "priority": 4,
"passes": false, "passes": true,
"notes": "Use pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') which auto-downloads and caches the ONNX model. The module-level pattern (let pipelineInstance = null) avoids React re-render issues. embedQuery should mean-pool the tensor output the same way as the build script. Wrap initModel() in a try/catch that silently swallows errors." "notes": "Use pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') which auto-downloads and caches the ONNX model. The module-level pattern (let pipelineInstance = null) avoids React re-render issues. embedQuery should mean-pool the tensor output the same way as the build script. Wrap initModel() in a try/catch that silently swallows errors."
}, },
{ {
@@ -89,7 +89,7 @@
"Typecheck passes" "Typecheck passes"
], ],
"priority": 5, "priority": 5,
"passes": false, "passes": true,
"notes": "Keep the cosine similarity implementation simple — no libraries needed for 384-d vectors over ~40 items. The loadEmbeddings function can use a dynamic import or direct import of the JSON file (Vite handles JSON imports natively)." "notes": "Keep the cosine similarity implementation simple — no libraries needed for 384-d vectors over ~40 items. The loadEmbeddings function can use a dynamic import or direct import of the JSON file (Vite handles JSON imports natively)."
}, },
{ {
@@ -107,7 +107,7 @@
"Verify in browser: search 'data analysis' surfaces analytics-related roles/skills not just items with 'data' in title" "Verify in browser: search 'data analysis' surfaces analytics-related roles/skills not just items with 'data' in title"
], ],
"priority": 6, "priority": 6,
"passes": false, "passes": true,
"notes": "The debounce is important — embedQuery takes ~20-50ms per call. Use a useRef + setTimeout pattern or a simple debounce hook. The mapping from semantic search results (id + score) back to PaletteItems should use a Map for O(1) lookup. Keep the Fuse.js imports and buildSearchIndex — they're the fallback path." "notes": "The debounce is important — embedQuery takes ~20-50ms per call. Use a useRef + setTimeout pattern or a simple debounce hook. The mapping from semantic search results (id + score) back to PaletteItems should use a Map for O(1) lookup. Keep the Fuse.js imports and buildSearchIndex — they're the fallback path."
}, },
{ {
@@ -128,7 +128,7 @@
"Verify in browser using dev-browser skill" "Verify in browser using dev-browser skill"
], ],
"priority": 7, "priority": 7,
"passes": false, "passes": true,
"notes": "Use framer-motion for the entrance animation to match the rest of the app's motion patterns. The button should use font-ui for any text. On mobile (<640px), button is 40px and positioned bottom: 16px, right: 16px. The VITE_GEMINI_API_KEY env var check can wait until the Gemini integration story — for now just render the button unconditionally." "notes": "Use framer-motion for the entrance animation to match the rest of the app's motion patterns. The button should use font-ui for any text. On mobile (<640px), button is 40px and positioned bottom: 16px, right: 16px. The VITE_GEMINI_API_KEY env var check can wait until the Gemini integration story — for now just render the button unconditionally."
}, },
{ {
@@ -152,7 +152,7 @@
"Verify in browser using dev-browser skill" "Verify in browser using dev-browser skill"
], ],
"priority": 8, "priority": 8,
"passes": false, "passes": true,
"notes": "Use the design system tokens: var(--surface) for panel bg, var(--border-light) for borders, var(--text-primary) for text, var(--accent) for user bubble bg at 10% opacity, font-ui for body text, font-geist for timestamps. The placeholder assistant response can be a static string like 'AI chat coming soon — this is a preview of the chat interface.' This lets us verify the full UI before wiring up Gemini." "notes": "Use the design system tokens: var(--surface) for panel bg, var(--border-light) for borders, var(--text-primary) for text, var(--accent) for user bubble bg at 10% opacity, font-ui for body text, font-geist for timestamps. The placeholder assistant response can be a static string like 'AI chat coming soon — this is a preview of the chat interface.' This lets us verify the full UI before wiring up Gemini."
}, },
{ {
@@ -175,7 +175,7 @@
"Typecheck passes" "Typecheck passes"
], ],
"priority": 9, "priority": 9,
"passes": false, "passes": true,
"notes": "Gemini REST streaming endpoint: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=API_KEY. The response is SSE (server-sent events) — parse each 'data:' line as JSON and extract candidates[0].content.parts[0].text. The system prompt with CV context will be ~2-3K tokens — well within Gemini Flash limits. For the palette item IDs, instruct the model to end its response with a line like [ITEMS: id1, id2, id3] which can be parsed client-side." "notes": "Gemini REST streaming endpoint: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=API_KEY. The response is SSE (server-sent events) — parse each 'data:' line as JSON and extract candidates[0].content.parts[0].text. The system prompt with CV context will be ~2-3K tokens — well within Gemini Flash limits. For the palette item IDs, instruct the model to end its response with a line like [ITEMS: id1, id2, id3] which can be parsed client-side."
}, },
{ {
@@ -193,7 +193,7 @@
"Verify in browser using dev-browser skill" "Verify in browser using dev-browser skill"
], ],
"priority": 10, "priority": 10,
"passes": false, "passes": true,
"notes": "The action routing needs to flow from ChatWidget up to DashboardLayout. Add an onAction prop to ChatWidget (same pattern as CommandPalette). DashboardLayout passes handlePaletteAction to ChatWidget. Export iconByType and iconColorStyles from CommandPalette (or extract to a shared module) so ChatWidget can reuse them." "notes": "The action routing needs to flow from ChatWidget up to DashboardLayout. Add an onAction prop to ChatWidget (same pattern as CommandPalette). DashboardLayout passes handlePaletteAction to ChatWidget. Export iconByType and iconColorStyles from CommandPalette (or extract to a shared module) so ChatWidget can reuse them."
} }
] ]
+181
View File
@@ -9,6 +9,25 @@
- Project uses `"type": "module"` in package.json - Project uses `"type": "module"` in package.json
- Palette item IDs: `exp-{consultation.id}`, `skill-{skill.id}`, `proj-{investigation.id}`, `ach-{0-3}`, `edu-{0-3}`, `action-{0-3}` - Palette item IDs: `exp-{consultation.id}`, `skill-{skill.id}`, `proj-{investigation.id}`, `ach-{0-3}`, `edu-{0-3}`, `action-{0-3}`
- `buildEmbeddingTexts()` in `src/lib/search.ts` returns `Array<{ id: string, text: string }>` with IDs matching PaletteItem IDs — use this for both embedding generation and chat context - `buildEmbeddingTexts()` in `src/lib/search.ts` returns `Array<{ id: string, text: string }>` with IDs matching PaletteItem IDs — use this for both embedding generation and chat context
- `src/data/embeddings.json` is an array of `{ id: string, embedding: number[] }` — 42 items, 384-d vectors, IDs match PaletteItem IDs. Vite imports JSON natively.
- `src/lib/embedding-model.ts` exports `initModel()`, `embedQuery(text)`, `isModelReady()` — check `isModelReady()` before calling `embedQuery()`
- `initModel()` is called fire-and-forget in `App.tsx` on mount — model loads during boot/ECG/login phases
- `src/lib/semantic-search.ts` exports `semanticSearch(queryEmbedding, embeddings, threshold?)` and `loadEmbeddings()` — embeddings are normalized so cosine similarity is dot(a,b)/(mag(a)*mag(b))
- CommandPalette uses `semanticResults` state + debounced `useEffect` for async semantic search, falling back to Fuse.js when `isModelReady()` returns false or on any error
- `loadEmbeddings()` and `paletteMap` (Map<id, PaletteItem>) are precomputed via `useMemo` — no re-computation on each search
- ChatWidget is mounted in DashboardLayout alongside CommandPalette and DetailPanel — z-index 90 (below command palette z-1000)
- `prefersReducedMotion` pattern: read `window.matchMedia` at module level, use in framer-motion variants to skip animation
- ChatWidget stores messages as `Array<{ role: 'user' | 'assistant', content: string }>` — same shape as LLM message format, ready for Gemini integration
- ChatWidget `isOpen` state controls both panel visibility and button icon (MessageCircle ↔ X) — panel rendering handled by AnimatePresence
- `src/lib/gemini.ts` exports `sendChatMessage(messages)` (async generator), `isGeminiAvailable()`, `parseItemIds(text)`, `stripItemsSuffix(text)` — ChatMessage type is `{ role: 'user' | 'assistant', content: string }`
- Gemini API uses SSE streaming: POST to `:streamGenerateContent?alt=sse&key=KEY`, parse `data:` lines as JSON, extract `candidates[0].content.parts[0].text`
- System prompt built from `buildEmbeddingTexts()` — instructs model to end responses with `[ITEMS: id1, id2, id3]` for portfolio item linking
- `isGeminiAvailable()` checks `import.meta.env.VITE_GEMINI_API_KEY` — when missing, chat panel shows "unavailable" message but button remains visible
- Assistant messages store item IDs as `<!--ITEMS:id1,id2-->` HTML comment suffix for US-010 to parse — `getDisplayText()` strips this before rendering
- Conversation history capped at 10 messages (`MAX_HISTORY`), metadata stripped before sending to API
- Icon/color mappings (`iconByType`, `iconColorStyles`) live in `src/lib/palette-icons.ts` — shared between CommandPalette and ChatWidget
- ChatWidget accepts optional `onAction?: (action: PaletteAction) => void` prop — same pattern as CommandPalette's `onAction`
- `DashboardLayout` passes `handlePaletteAction` to both CommandPalette and ChatWidget for unified action routing
--- ---
@@ -45,3 +64,165 @@
- Quick action items are `action-0` through `action-3` - Quick action items are `action-0` through `action-3`
- `documents.ts` is imported but wasn't previously used in `search.ts` — now used for education embedding text - `documents.ts` is imported but wasn't previously used in `search.ts` — now used for education embedding text
--- ---
## 2026-02-15 - US-003
- Updated `scripts/generate-embeddings.ts` to import `buildEmbeddingTexts()` and generate full embeddings
- Script embeds all 42 palette items sequentially using `Xenova/all-MiniLM-L6-v2`
- Outputs `src/data/embeddings.json` as `Array<{ id: string, embedding: number[] }>`
- Each embedding is a 384-dimensional float array
- File is ~453KB (42 items × 384 floats with pretty-printed JSON)
- `npm run generate-embeddings` regenerates the file successfully
- Typecheck and lint pass
- Files changed: `scripts/generate-embeddings.ts`, `src/data/embeddings.json`
- **Learnings for future iterations:**
- `import.meta.dirname` works in tsx/Node ESM scripts — use it instead of `__dirname` (which isn't available in ESM)
- `@/` path alias works in `npx tsx` scripts because tsx resolves tsconfig paths automatically
- The embeddings file is ~450KB with pretty-print; could be reduced with compact JSON but readability is preferred for now
- Processing 42 items takes ~10-15 seconds on first run (model cached after first download)
---
## 2026-02-15 - US-004
- Created `src/lib/embedding-model.ts` with three exports: `initModel()`, `embedQuery()`, `isModelReady()`
- Module-level `let extractor` pattern avoids React re-render issues
- `initModel()` uses `loading` guard to prevent duplicate pipeline loads
- `embedQuery()` uses same `pooling: 'mean'` and `normalize: true` as the build script
- `initModel()` called fire-and-forget in `App.tsx` `useEffect([], [])` — runs during boot phase
- Silent failure: try/catch swallows errors, `isModelReady()` stays false
- Typecheck, lint, and build all pass
- Files changed: `src/lib/embedding-model.ts` (new), `src/App.tsx`
- **Learnings for future iterations:**
- `FeatureExtractionPipeline` type is exported from `@xenova/transformers` and can be used for the module-level variable
- The `loading` boolean guard prevents race conditions if `initModel()` is called multiple times (e.g., React strict mode double-mount)
- `initModel()` is intentionally not awaited — it's fire-and-forget so it doesn't block the boot animation
- Consumers should check `isModelReady()` before calling `embedQuery()` — it throws if model isn't loaded
---
## 2026-02-15 - US-005
- Created `src/lib/semantic-search.ts` with cosine similarity search and embeddings loader
- `semanticSearch()` computes cosine similarity, filters by threshold (default 0.3), returns sorted by score descending
- `loadEmbeddings()` imports `embeddings.json` via Vite's native JSON import and returns typed array
- Typecheck and lint pass (0 new warnings)
- Files changed: `src/lib/semantic-search.ts` (new)
- **Learnings for future iterations:**
- Vite handles JSON imports natively — `import data from '@/data/embeddings.json'` just works, no dynamic import needed
- Since embeddings are already L2-normalized (from pipeline's `normalize: true`), cosine similarity simplifies to just the dot product. However, the full formula is kept for correctness in case non-normalized vectors are ever used
- With only ~42 items and 384-d vectors, brute-force cosine similarity is fast enough — no need for approximate nearest neighbor libraries
---
## 2026-02-15 - US-006
- Integrated semantic search into CommandPalette with Fuse.js fallback
- When `isModelReady()` is true: debounces query by 200ms, calls `embedQuery()`, runs `semanticSearch()` against preloaded embeddings, maps result IDs back to PaletteItems via O(1) Map lookup
- When model is NOT ready: uses existing Fuse.js search (behavior preserved exactly)
- Results maintain `groupBySection()` grouping and section ordering
- Existing keyboard navigation, action routing, and UI unchanged
- Semantic results state is cleared when palette opens/closes and when query is empty
- Error handling: any failure in embedQuery/semanticSearch silently falls back to Fuse.js
- Typecheck, lint, and build all pass
- Browser verified: Fuse.js fallback works correctly; ONNX model loads asynchronously during boot and activates semantic search when ready
- Files changed: `src/components/CommandPalette.tsx`
- **Learnings for future iterations:**
- Semantic search is async so it can't live in a `useMemo` — use `useState` + debounced `useEffect` pattern instead
- The `useRef + setTimeout` debounce pattern works well here: set `debounceRef.current = setTimeout(...)`, clear it in the cleanup function, and in early-return paths
- `isModelReady()` is a synchronous check — call it before setting up the debounce timeout to avoid unnecessary delays when model isn't loaded
- The ONNX model takes several seconds to load in the browser (downloads ~23MB first time, then cached in IndexedDB), so initial searches will always use Fuse.js fallback
- `loadEmbeddings()` is cheap (just returns the already-imported JSON) — safe to call in `useMemo` without performance concern
---
## 2026-02-15 - US-007
- Created `src/components/ChatWidget.tsx` — floating chat button with toggle state
- 48px circular button (40px on mobile <640px), fixed bottom-right, teal accent background, white MessageCircle icon
- Entrance animation: fade + translateY(8px→0), 1s delay after mount, via framer-motion variants
- Respects `prefers-reduced-motion` — skips animation, shows immediately
- Hover: shadow-md → shadow-lg + scale(1.05), 150ms transition
- z-index 90 (below command palette z-1000)
- onClick toggles `isOpen` state, swaps icon between MessageCircle and X
- Mounted in `DashboardLayout.tsx` alongside CommandPalette and DetailPanel
- Typecheck, lint (0 errors), and build all pass
- Browser verified: button visible at bottom-right, toggle works (Open chat ↔ Close chat)
- Files changed: `src/components/ChatWidget.tsx` (new), `src/components/DashboardLayout.tsx`
- **Learnings for future iterations:**
- Responsive sizing via Tailwind classes (`h-10 w-10 sm:h-12 sm:w-12`) works well with inline style for non-Tailwind properties (boxShadow, border-radius)
- `AnimatePresence` is already imported and ready for the panel animation in US-008
- The `isOpen` state lives in ChatWidget — US-008 will add the panel UI inside the same component
- Hover effects use `onMouseEnter/Leave` with direct style mutation (same pattern as other dashboard components)
---
## 2026-02-15 - US-008
- Built chat panel UI inside `ChatWidget.tsx` with header, message area, and input
- Panel opens above the floating button with scale+opacity entrance/exit animation via framer-motion `AnimatePresence`
- Messages stored as `Array<{ role: 'user' | 'assistant', content: string }>` in component state
- User messages right-aligned in teal-tinted bubbles (`var(--accent-light)` bg, `var(--accent-border)` border)
- Assistant messages left-aligned in light gray bubbles (`var(--bg-dashboard)` bg, `var(--border-light)` border)
- Message corner radii differ: user bubbles have small bottom-right radius, assistant bubbles small bottom-left (conversational feel)
- Input area: textarea with Enter to submit, Shift+Enter for newline. Send button enabled/disabled based on input content
- Empty state shows placeholder text when no messages yet
- Auto-scrolls to latest message via `useRef` + `scrollIntoView`
- Auto-focuses input when panel opens (200ms delay for animation)
- Responsive: on mobile (<640px), panel is full-width bottom sheet with rounded top corners; on desktop, 380px wide positioned above the button
- Panel entrance: scale(0.95)+opacity(0) → scale(1)+opacity(1), 200ms. Exit: reverse, 150ms
- Respects `prefers-reduced-motion` — skips all animation
- Close button in header triggers `setIsOpen(false)` (same as floating button toggle)
- Submitting appends both user message and placeholder assistant response to state
- Typecheck, lint (0 errors), and build all pass
- Browser verified: panel opens/closes correctly, messages display, input works, Enter submits, close button works
- Files changed: `src/components/ChatWidget.tsx`
- **Learnings for future iterations:**
- `AnimatePresence` with `key` prop on the panel div is needed for exit animations to work
- Panel uses `transformOrigin: 'bottom right'` for natural scale animation from the button corner
- CSS-in-JS `<style>` tag with `data-chat-panel` attribute handles responsive width/height (Tailwind can't express max-height conditionally based on viewport width easily)
- `textarea` with `rows={1}` and `maxHeight: 80px` gives auto-growing feel; `resize: none` prevents manual resize
- The `ChatMessage` interface (`{ role, content }`) is ready to be extended for US-009 Gemini integration — same shape as typical LLM message format
- `onFocus/onBlur` border color transitions on the textarea give a polished input interaction
---
## 2026-02-15 - US-009
- Created `src/lib/gemini.ts` — Gemini Flash streaming integration module
- `sendChatMessage(messages)` async generator that streams SSE tokens from Gemini 2.0 Flash
- `isGeminiAvailable()` checks for `VITE_GEMINI_API_KEY` env var
- `parseItemIds(text)` extracts `[ITEMS: id1, id2]` from response text
- `stripItemsSuffix(text)` removes the `[ITEMS: ...]` line for clean display
- System prompt built from `buildEmbeddingTexts()` output — full CV context (~42 items)
- Model instructed to answer concisely and append relevant palette item IDs
- Rewired `ChatWidget.tsx` to use real Gemini API instead of placeholder responses
- Streaming: tokens progressively appear in assistant message bubble
- Typing indicator (Loader2 spinner + "Thinking...") shown while waiting for first token
- Input disabled during streaming, send button grayed out
- Error handling: API failures show "Sorry, I couldn't process that. Please try again."
- Missing API key: panel shows "Chat is currently unavailable", input area hidden
- Conversation history capped at 10 messages before sending to API
- Assistant messages store parsed item IDs as `<!--ITEMS:id1,id2-->` HTML comment (for US-010)
- Messages sent to API have metadata stripped to keep context clean
- Typecheck, lint (0 errors), and build all pass
- Files changed: `src/lib/gemini.ts` (new), `src/components/ChatWidget.tsx`
- **Learnings for future iterations:**
- Gemini SSE format: `data:` prefix per line, JSON body with `candidates[0].content.parts[0].text`
- `system_instruction` field in Gemini request body sets the system prompt (not a message in `contents`)
- Gemini role mapping: `'assistant'` → `'model'` in the API's `contents` array
- Buffer-based SSE parsing handles chunk boundaries: split on `\n`, keep last incomplete line in buffer
- `buildEmbeddingTexts()` is a great source for structured CV context — natural language paragraphs per item
- The `<!--ITEMS:-->` HTML comment pattern is invisible when rendered but parseable by US-010 for item card display
- `useCallback` on `handleSubmit` with `[inputValue, isStreaming, messages]` deps is needed because it reads all three
---
## 2026-02-15 - US-010
- Extracted `iconByType` and `iconColorStyles` from `CommandPalette.tsx` into shared `src/lib/palette-icons.ts`
- Updated `CommandPalette.tsx` to import from the shared module (no behavioral change)
- Added `onAction?: (action: PaletteAction) => void` prop to `ChatWidget` — same pattern as `CommandPalette`
- `DashboardLayout.tsx` passes `handlePaletteAction` to `ChatWidget` (same handler used by CommandPalette)
- ChatWidget builds a `paletteMap` (Map<id, PaletteItem>) via `useMemo` for O(1) item lookups
- Added `getMessageItemIds()` to parse `<!--ITEMS:id1,id2-->` HTML comments from message content
- Added `getMessageItems()` to resolve parsed IDs to PaletteItem objects via the map
- Assistant message bubbles now render compact clickable item cards below text when items are referenced:
- Cards use same icon/color scheme from CommandPalette (22px icon + title + subtitle)
- Cards have hover highlight (`var(--accent-light)`) and trigger `onAction(item.action)` on click
- Cards only appear after streaming completes (when `<!--ITEMS:-->` metadata is in final content)
- If no items referenced or IDs don't match, no cards shown — just text
- Typecheck, lint (0 errors), and build all pass
- Files changed: `src/lib/palette-icons.ts` (new), `src/components/ChatWidget.tsx`, `src/components/CommandPalette.tsx`, `src/components/DashboardLayout.tsx`
- **Learnings for future iterations:**
- Extracting shared constants to `src/lib/` is the right pattern — both `CommandPalette` and `ChatWidget` now use the same icon mappings without duplication
- `buildPaletteData()` is pure (no side effects) and idempotent — safe to call in `useMemo` with empty deps
- The `<!--ITEMS:-->` HTML comment regex `<!--ITEMS:([^>]*)-->` works reliably; `[^>]*` captures everything between the colons and closing
- Item card buttons use `fontFamily: 'inherit'` to pick up the panel's `font-ui` — without this, browser defaults apply
- The `overflow: 'hidden'` on the message bubble container is needed so the item cards section (with its own border-top) stays visually contained within the bubble's border-radius
---
+16 -6
View File
@@ -1,17 +1,27 @@
import { writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { pipeline } from '@xenova/transformers' import { pipeline } from '@xenova/transformers'
import { buildEmbeddingTexts } from '@/lib/search'
async function main() { async function main() {
const items = buildEmbeddingTexts()
console.log(`Found ${items.length} items to embed.`)
console.log('Loading all-MiniLM-L6-v2 model...') console.log('Loading all-MiniLM-L6-v2 model...')
const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2')
const testString = 'This is a test string for embedding generation.' const embeddings: Array<{ id: string; embedding: number[] }> = []
console.log(`Embedding test string: "${testString}"`)
const output = await extractor(testString, { pooling: 'mean', normalize: true }) for (const item of items) {
const vector = Array.from(output.data as Float32Array) const output = await extractor(item.text, { pooling: 'mean', normalize: true })
const vector = Array.from(output.data as Float32Array)
embeddings.push({ id: item.id, embedding: vector })
console.log(` [${embeddings.length}/${items.length}] ${item.id} (${vector.length}d)`)
}
console.log(`Vector length: ${vector.length}`) const outPath = resolve(import.meta.dirname, '..', 'src', 'data', 'embeddings.json')
console.log('Done.') writeFileSync(outPath, JSON.stringify(embeddings, null, 2))
console.log(`\nWrote ${embeddings.length} embeddings to ${outPath}`)
} }
main().catch((err) => { main().catch((err) => {
+5
View File
@@ -6,6 +6,7 @@ import { LoginScreen } from './components/LoginScreen'
import { DashboardLayout } from './components/DashboardLayout' import { DashboardLayout } from './components/DashboardLayout'
import { AccessibilityProvider } from './contexts/AccessibilityContext' import { AccessibilityProvider } from './contexts/AccessibilityContext'
import { DetailPanelProvider } from './contexts/DetailPanelContext' import { DetailPanelProvider } from './contexts/DetailPanelContext'
import { initModel } from './lib/embedding-model'
function SkipButton({ onSkip }: { onSkip: () => void }) { function SkipButton({ onSkip }: { onSkip: () => void }) {
const [visible, setVisible] = useState(false) const [visible, setVisible] = useState(false)
@@ -47,6 +48,10 @@ function App() {
const [phase, setPhase] = useState<Phase>('login') const [phase, setPhase] = useState<Phase>('login')
const cursorPositionRef = useRef<{ x: number; y: number } | null>(null) const cursorPositionRef = useRef<{ x: number; y: number } | null>(null)
useEffect(() => {
initModel()
}, [])
const skipToLogin = () => setPhase('login') const skipToLogin = () => setPhase('login')
return ( return (
+579
View File
@@ -0,0 +1,579 @@
import { useState, useRef, useEffect, useCallback, useMemo, type KeyboardEvent } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { MessageCircle, X, Send, Loader2 } from 'lucide-react'
import {
sendChatMessage,
isGeminiAvailable,
parseItemIds,
stripItemsSuffix,
type ChatMessage,
} from '@/lib/gemini'
import { buildPaletteData } from '@/lib/search'
import type { PaletteItem, PaletteAction } from '@/lib/search'
import { iconByType, iconColorStyles } from '@/lib/palette-icons'
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
const MAX_HISTORY = 10
const buttonVariants = {
hidden: prefersReducedMotion
? { opacity: 1, y: 0 }
: { opacity: 0, y: 8 },
visible: {
opacity: 1,
y: 0,
transition: prefersReducedMotion
? { duration: 0 }
: { duration: 0.3, ease: 'easeOut', delay: 1 },
},
}
const panelVariants = {
hidden: prefersReducedMotion
? { opacity: 1, scale: 1 }
: { opacity: 0, scale: 0.95 },
visible: {
opacity: 1,
scale: 1,
transition: prefersReducedMotion
? { duration: 0 }
: { duration: 0.2, ease: 'easeOut' },
},
exit: prefersReducedMotion
? { opacity: 1, scale: 1 }
: { opacity: 0, scale: 0.95, transition: { duration: 0.15, ease: 'easeIn' } },
}
interface ChatWidgetProps {
onAction?: (action: PaletteAction) => void
}
export function ChatWidget({ onAction }: ChatWidgetProps) {
const [isOpen, setIsOpen] = useState(false)
const [messages, setMessages] = useState<ChatMessage[]>([])
const [inputValue, setInputValue] = useState('')
const [isStreaming, setIsStreaming] = useState(false)
const messagesEndRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLTextAreaElement>(null)
const geminiAvailable = isGeminiAvailable()
// Build palette map for looking up items by ID
const paletteMap = useMemo(() => {
const items = buildPaletteData()
const map = new Map<string, PaletteItem>()
for (const item of items) map.set(item.id, item)
return map
}, [])
// Auto-scroll to latest message
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages])
// Focus input when panel opens
useEffect(() => {
if (isOpen) {
setTimeout(() => inputRef.current?.focus(), 200)
}
}, [isOpen])
const handleSubmit = useCallback(async () => {
const trimmed = inputValue.trim()
if (!trimmed || isStreaming) return
const userMessage: ChatMessage = { role: 'user', content: trimmed }
const updatedMessages = [...messages, userMessage]
// Cap history to last MAX_HISTORY messages, strip internal metadata
const historyForApi = updatedMessages.slice(-MAX_HISTORY).map((msg) => ({
...msg,
content: msg.content.replace(/\n?<!--ITEMS:[^>]*-->/, '').trim(),
}))
setMessages(updatedMessages)
setInputValue('')
setIsStreaming(true)
// Add empty assistant message that will be streamed into
const assistantMessage: ChatMessage = { role: 'assistant', content: '' }
setMessages((prev) => [...prev, assistantMessage])
try {
const stream = sendChatMessage(historyForApi)
let accumulated = ''
for await (const chunk of stream) {
accumulated += chunk
// Update the last (assistant) message with accumulated text
setMessages((prev) => {
const updated = [...prev]
updated[updated.length - 1] = { role: 'assistant', content: accumulated }
return updated
})
}
// Final cleanup: strip [ITEMS: ...] suffix from display text (keep raw for parsing)
// We store the clean display text but parse items from the raw accumulated text
const cleanText = stripItemsSuffix(accumulated)
const itemIds = parseItemIds(accumulated)
const finalContent = itemIds.length > 0
? `${cleanText}\n<!--ITEMS:${itemIds.join(',')}-->`
: cleanText
setMessages((prev) => {
const updated = [...prev]
updated[updated.length - 1] = { role: 'assistant', content: finalContent }
return updated
})
} catch {
setMessages((prev) => {
const updated = [...prev]
updated[updated.length - 1] = {
role: 'assistant',
content: "Sorry, I couldn't process that. Please try again.",
}
return updated
})
} finally {
setIsStreaming(false)
}
}, [inputValue, isStreaming, messages])
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSubmit()
}
}
// Extract display text from message content (strip hidden item metadata)
const getDisplayText = (content: string) => {
return content.replace(/\n?<!--ITEMS:[^>]*-->/, '').trim()
}
// Extract item IDs from the <!--ITEMS:...--> HTML comment in message content
const getMessageItemIds = (content: string): string[] => {
const match = content.match(/<!--ITEMS:([^>]*)-->/)
if (!match) return []
return match[1].split(',').map((id) => id.trim()).filter(Boolean)
}
// Resolve item IDs to PaletteItems
const getMessageItems = (content: string): PaletteItem[] => {
return getMessageItemIds(content)
.map((id) => paletteMap.get(id))
.filter((item): item is PaletteItem => item !== undefined)
}
// Handle clicking an item card — route through onAction
const handleItemClick = useCallback((item: PaletteItem) => {
if (onAction) {
onAction(item.action)
} else {
if (item.action.type === 'link') {
window.open(item.action.url, '_blank', 'noopener,noreferrer')
}
}
}, [onAction])
return (
<>
{/* Chat panel */}
<AnimatePresence>
{isOpen && (
<motion.div
key="chat-panel"
initial="hidden"
animate="visible"
exit="exit"
variants={panelVariants}
role="dialog"
aria-label="Chat with AI about Andy"
className="fixed z-[90] font-ui
bottom-0 left-0 right-0 rounded-t-xl
sm:bottom-[88px] sm:right-6 sm:left-auto sm:rounded-xl"
style={{
width: undefined,
background: 'var(--surface)',
border: '1px solid var(--border-light)',
boxShadow: 'var(--shadow-lg)',
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
transformOrigin: 'bottom right',
}}
>
<style>{`
@media (min-width: 640px) {
[data-chat-panel] { width: 380px; max-height: 480px; }
}
@media (max-width: 639px) {
[data-chat-panel] { height: 85vh; max-height: 85vh; }
}
`}</style>
<div
data-chat-panel
style={{
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
maxHeight: '480px',
}}
>
{/* Header */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '14px 16px',
borderBottom: '1px solid var(--border-light)',
flexShrink: 0,
}}
>
<span
style={{
fontSize: '14px',
fontWeight: 600,
color: 'var(--text-primary)',
}}
>
Ask about Andy
</span>
<button
onClick={() => setIsOpen(false)}
aria-label="Close chat"
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '28px',
height: '28px',
borderRadius: '6px',
border: 'none',
background: 'transparent',
color: 'var(--text-secondary)',
cursor: 'pointer',
transition: 'background-color 150ms ease-out',
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = 'var(--accent-light)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent'
}}
>
<X size={16} strokeWidth={2} />
</button>
</div>
{/* Messages area */}
<div
style={{
flex: 1,
overflowY: 'auto',
padding: '16px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
className="pmr-scrollbar"
>
{!geminiAvailable && (
<div
style={{
textAlign: 'center',
padding: '32px 16px',
color: 'var(--text-tertiary)',
fontSize: '13px',
lineHeight: 1.5,
}}
>
Chat is currently unavailable.
</div>
)}
{geminiAvailable && messages.length === 0 && (
<div
style={{
textAlign: 'center',
padding: '32px 16px',
color: 'var(--text-tertiary)',
fontSize: '13px',
lineHeight: 1.5,
}}
>
Ask me anything about Andy's experience, skills, or projects.
</div>
)}
{messages.map((msg, i) => {
const referencedItems = msg.role === 'assistant' ? getMessageItems(msg.content) : []
return (
<div
key={i}
style={{
display: 'flex',
justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
}}
>
<div
style={{
maxWidth: '85%',
borderRadius: msg.role === 'user'
? '12px 12px 4px 12px'
: '12px 12px 12px 4px',
fontSize: '13px',
lineHeight: 1.5,
background: msg.role === 'user'
? 'var(--accent-light)'
: 'var(--bg-dashboard)',
color: 'var(--text-primary)',
border: msg.role === 'user'
? '1px solid var(--accent-border)'
: '1px solid var(--border-light)',
overflow: 'hidden',
}}
>
<div style={{ padding: '10px 14px', whiteSpace: 'pre-wrap' }}>
{getDisplayText(msg.content)}
</div>
{referencedItems.length > 0 && (
<div
style={{
borderTop: '1px solid var(--border-light)',
padding: '6px 8px',
display: 'flex',
flexDirection: 'column',
gap: '2px',
}}
>
{referencedItems.map((item) => {
const IconComponent = iconByType[item.iconType]
const colorStyle = iconColorStyles[item.iconVariant]
return (
<button
key={item.id}
onClick={() => handleItemClick(item)}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '6px 8px',
borderRadius: '6px',
border: 'none',
background: 'transparent',
cursor: 'pointer',
width: '100%',
textAlign: 'left',
transition: 'background-color 100ms ease-out',
fontSize: '12px',
fontFamily: 'inherit',
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = 'var(--accent-light)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = 'transparent'
}}
>
<div
style={{
width: '22px',
height: '22px',
borderRadius: '5px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
background: colorStyle.background,
color: colorStyle.color,
}}
>
{IconComponent && <IconComponent size={12} />}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontWeight: 500,
color: 'var(--text-primary)',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{item.title}
</div>
<div
style={{
fontSize: '11px',
color: 'var(--text-tertiary)',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
marginTop: '-1px',
}}
>
{item.subtitle}
</div>
</div>
</button>
)
})}
</div>
)}
</div>
</div>
)
})}
{/* Typing indicator */}
{isStreaming && messages.length > 0 && messages[messages.length - 1].content === '' && (
<div style={{ display: 'flex', justifyContent: 'flex-start' }}>
<div
style={{
padding: '10px 14px',
borderRadius: '12px 12px 12px 4px',
background: 'var(--bg-dashboard)',
border: '1px solid var(--border-light)',
display: 'flex',
alignItems: 'center',
gap: '6px',
color: 'var(--text-tertiary)',
fontSize: '13px',
}}
>
<Loader2
size={14}
strokeWidth={2}
style={{
animation: 'spin 1s linear infinite',
}}
/>
<span>Thinking...</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Input area */}
{geminiAvailable && (
<div
style={{
padding: '12px 16px',
borderTop: '1px solid var(--border-light)',
display: 'flex',
alignItems: 'flex-end',
gap: '8px',
flexShrink: 0,
}}
>
<textarea
ref={inputRef}
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask me anything..."
rows={1}
disabled={isStreaming}
style={{
flex: 1,
resize: 'none',
border: '1px solid var(--border-light)',
borderRadius: '8px',
padding: '10px 12px',
fontSize: '13px',
lineHeight: 1.5,
color: 'var(--text-primary)',
background: 'var(--surface)',
outline: 'none',
fontFamily: 'inherit',
maxHeight: '80px',
overflowY: 'auto',
transition: 'border-color 150ms ease-out',
opacity: isStreaming ? 0.6 : 1,
}}
onFocus={(e) => {
e.currentTarget.style.borderColor = 'var(--accent)'
}}
onBlur={(e) => {
e.currentTarget.style.borderColor = 'var(--border-light)'
}}
/>
<button
onClick={handleSubmit}
disabled={!inputValue.trim() || isStreaming}
aria-label="Send message"
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '36px',
height: '36px',
borderRadius: '8px',
border: 'none',
background: inputValue.trim() && !isStreaming ? 'var(--accent)' : 'var(--border-light)',
color: inputValue.trim() && !isStreaming ? '#FFFFFF' : 'var(--text-tertiary)',
cursor: inputValue.trim() && !isStreaming ? 'pointer' : 'default',
flexShrink: 0,
transition: 'background-color 150ms ease-out, color 150ms ease-out',
}}
>
<Send size={16} strokeWidth={2} />
</button>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
{/* Floating chat button */}
<motion.button
initial="hidden"
animate="visible"
variants={buttonVariants}
onClick={() => setIsOpen((prev) => !prev)}
aria-label={isOpen ? 'Close chat' : 'Open chat'}
className="fixed z-[90] cursor-pointer bottom-4 right-4 h-10 w-10 sm:bottom-6 sm:right-6 sm:h-12 sm:w-12"
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '50%',
border: 'none',
background: 'var(--accent)',
color: '#FFFFFF',
boxShadow: 'var(--shadow-md)',
transition: 'box-shadow 150ms ease-out, transform 150ms ease-out',
}}
onMouseEnter={(e) => {
e.currentTarget.style.boxShadow = 'var(--shadow-lg)'
e.currentTarget.style.transform = 'scale(1.05)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.boxShadow = 'var(--shadow-md)'
e.currentTarget.style.transform = 'scale(1)'
}}
>
{isOpen ? <X size={20} strokeWidth={2} /> : <MessageCircle size={20} strokeWidth={2} />}
</motion.button>
{/* Spinner keyframes */}
<style>{`
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`}</style>
</>
)
}
+57 -31
View File
@@ -1,20 +1,14 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react' import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import { import { Search } from 'lucide-react'
Search,
User,
Activity,
Monitor,
Award,
GraduationCap,
Zap,
type LucideIcon,
} from 'lucide-react'
import { import {
buildPaletteData, buildPaletteData,
buildSearchIndex, buildSearchIndex,
groupBySection, groupBySection,
} from '@/lib/search' } from '@/lib/search'
import type { PaletteItem, PaletteAction, IconColorVariant } from '@/lib/search' import type { PaletteItem, PaletteAction } from '@/lib/search'
import { iconByType, iconColorStyles } from '@/lib/palette-icons'
import { isModelReady, embedQuery } from '@/lib/embedding-model'
import { semanticSearch, loadEmbeddings } from '@/lib/semantic-search'
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
@@ -24,24 +18,6 @@ interface CommandPaletteProps {
onAction?: (action: PaletteAction) => void onAction?: (action: PaletteAction) => void
} }
// Icon mapping by type
const iconByType: Record<string, LucideIcon> = {
role: User,
skill: Activity,
project: Monitor,
achievement: Award,
edu: GraduationCap,
action: Zap,
}
// Color variant → CSS variable mapping for icon containers
const iconColorStyles: Record<IconColorVariant, { background: string; color: string }> = {
teal: { background: 'var(--accent-light)', color: 'var(--accent)' },
green: { background: 'var(--success-light)', color: 'var(--success)' },
amber: { background: 'var(--amber-light)', color: 'var(--amber)' },
purple: { background: 'rgba(124,58,237,0.08)', color: '#7C3AED' },
}
export function CommandPalette({ isOpen, onClose, onAction }: CommandPaletteProps) { export function CommandPalette({ isOpen, onClose, onAction }: CommandPaletteProps) {
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [selectedIndex, setSelectedIndex] = useState(-1) const [selectedIndex, setSelectedIndex] = useState(-1)
@@ -53,13 +29,62 @@ export function CommandPalette({ isOpen, onClose, onAction }: CommandPaletteProp
const paletteData = useMemo(() => buildPaletteData(), []) const paletteData = useMemo(() => buildPaletteData(), [])
const searchIndex = useMemo(() => buildSearchIndex(paletteData), [paletteData]) const searchIndex = useMemo(() => buildSearchIndex(paletteData), [paletteData])
// Compute visible items based on query // Preload embeddings and build lookup map
const embeddings = useMemo(() => loadEmbeddings(), [])
const paletteMap = useMemo(() => {
const map = new Map<string, PaletteItem>()
for (const item of paletteData) map.set(item.id, item)
return map
}, [paletteData])
// Semantic search results (async, debounced)
const [semanticResults, setSemanticResults] = useState<PaletteItem[] | null>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout>>()
useEffect(() => {
const trimmed = query.trim()
// Clear semantic results when query is empty
if (!trimmed) {
setSemanticResults(null)
return
}
// Only use semantic search when model is ready
if (!isModelReady()) {
setSemanticResults(null)
return
}
// Debounce ~200ms
clearTimeout(debounceRef.current)
debounceRef.current = setTimeout(async () => {
try {
const queryVec = await embedQuery(trimmed)
const results = semanticSearch(queryVec, embeddings)
const items = results
.map(r => paletteMap.get(r.id))
.filter((item): item is PaletteItem => item !== undefined)
setSemanticResults(items)
} catch {
// Fall back to Fuse.js on any error
setSemanticResults(null)
}
}, 200)
return () => clearTimeout(debounceRef.current)
}, [query, embeddings, paletteMap])
// Compute visible items: semantic search when available, Fuse.js fallback
const visibleItems = useMemo(() => { const visibleItems = useMemo(() => {
if (!query.trim()) { if (!query.trim()) {
return paletteData return paletteData
} }
if (semanticResults !== null) {
return semanticResults
}
return searchIndex.search(query).map(result => result.item) return searchIndex.search(query).map(result => result.item)
}, [query, paletteData, searchIndex]) }, [query, paletteData, searchIndex, semanticResults])
// Group visible items by section // Group visible items by section
const groupedResults = useMemo(() => groupBySection(visibleItems), [visibleItems]) const groupedResults = useMemo(() => groupBySection(visibleItems), [visibleItems])
@@ -80,6 +105,7 @@ export function CommandPalette({ isOpen, onClose, onAction }: CommandPaletteProp
if (isOpen) { if (isOpen) {
setQuery('') setQuery('')
setSelectedIndex(-1) setSelectedIndex(-1)
setSemanticResults(null)
// Focus input on next frame // Focus input on next frame
requestAnimationFrame(() => { requestAnimationFrame(() => {
inputRef.current?.focus() inputRef.current?.focus()
+4
View File
@@ -14,6 +14,7 @@ import { ParentSection } from './ParentSection'
import CareerConstellation from './CareerConstellation' import CareerConstellation from './CareerConstellation'
import { WorkExperienceSubsection } from './WorkExperienceSubsection' import { WorkExperienceSubsection } from './WorkExperienceSubsection'
import { RepeatMedicationsSubsection } from './RepeatMedicationsSubsection' import { RepeatMedicationsSubsection } from './RepeatMedicationsSubsection'
import { ChatWidget } from './ChatWidget'
import { useActiveSection } from '@/hooks/useActiveSection' import { useActiveSection } from '@/hooks/useActiveSection'
import { useDetailPanel } from '@/contexts/DetailPanelContext' import { useDetailPanel } from '@/contexts/DetailPanelContext'
import { consultations } from '@/data/consultations' import { consultations } from '@/data/consultations'
@@ -418,6 +419,9 @@ export function DashboardLayout() {
{/* Detail panel */} {/* Detail panel */}
<DetailPanel /> <DetailPanel />
{/* Floating chat widget */}
<ChatWidget onAction={handlePaletteAction} />
</div> </div>
) )
} }
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
import { pipeline, type FeatureExtractionPipeline } from '@xenova/transformers'
let extractor: FeatureExtractionPipeline | null = null
let loading = false
export async function initModel(): Promise<void> {
if (extractor || loading) return
loading = true
try {
extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') as FeatureExtractionPipeline
} catch {
// Silently swallow — model unavailable, semantic search won't activate
} finally {
loading = false
}
}
export async function embedQuery(text: string): Promise<number[]> {
if (!extractor) throw new Error('Model not loaded')
const output = await extractor(text, { pooling: 'mean', normalize: true })
return Array.from(output.data as Float32Array)
}
export function isModelReady(): boolean {
return extractor !== null
}
+152
View File
@@ -0,0 +1,152 @@
import { buildEmbeddingTexts } from '@/lib/search'
export interface ChatMessage {
role: 'user' | 'assistant'
content: string
}
const GEMINI_API_BASE = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash'
function getApiKey(): string | undefined {
return import.meta.env.VITE_GEMINI_API_KEY as string | undefined
}
export function isGeminiAvailable(): boolean {
return !!getApiKey()
}
function buildSystemPrompt(): string {
const texts = buildEmbeddingTexts()
const cvContent = texts.map((t) => `- ${t.text}`).join('\n')
return `You are an AI assistant embedded in Andy Charlwood's professional portfolio website. Your role is to answer questions about Andy's professional experience, skills, projects, and qualifications accurately and concisely.
Here is Andy's complete professional profile:
${cvContent}
Instructions:
- Answer questions based ONLY on the information above. Do not invent roles, dates, or achievements.
- Be concise — 2-4 sentences for most answers.
- Be professional but friendly in tone.
- If asked something not covered by the profile data, say you don't have that information.
- At the end of your response, on a new line, include relevant portfolio item IDs in this format: [ITEMS: id1, id2, id3]
- Only include item IDs that are directly relevant to your answer. The available IDs are the ones listed above (e.g., exp-*, skill-*, proj-*, ach-*, edu-*, action-*).
- If no items are particularly relevant, omit the [ITEMS: ...] line entirely.`
}
function buildRequestBody(
messages: ChatMessage[],
systemPrompt: string,
): object {
const contents = messages.map((msg) => ({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }],
}))
return {
system_instruction: {
parts: [{ text: systemPrompt }],
},
contents,
generationConfig: {
temperature: 0.7,
maxOutputTokens: 512,
},
}
}
export async function* sendChatMessage(
messages: ChatMessage[],
): AsyncGenerator<string> {
const apiKey = getApiKey()
if (!apiKey) {
throw new Error('Gemini API key not configured')
}
const systemPrompt = buildSystemPrompt()
const body = buildRequestBody(messages, systemPrompt)
const response = await fetch(
`${GEMINI_API_BASE}:streamGenerateContent?alt=sse&key=${apiKey}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
)
if (!response.ok) {
throw new Error(`Gemini API error: ${response.status}`)
}
const reader = response.body?.getReader()
if (!reader) {
throw new Error('No response body')
}
const decoder = new TextDecoder()
let buffer = ''
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
// Keep the last potentially incomplete line in the buffer
buffer = lines.pop() ?? ''
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed.startsWith('data:')) continue
const jsonStr = trimmed.slice(5).trim()
if (!jsonStr || jsonStr === '[DONE]') continue
try {
const parsed = JSON.parse(jsonStr)
const text = parsed?.candidates?.[0]?.content?.parts?.[0]?.text
if (text) {
yield text
}
} catch {
// Skip malformed JSON chunks
}
}
}
// Process any remaining buffer
if (buffer.trim().startsWith('data:')) {
const jsonStr = buffer.trim().slice(5).trim()
if (jsonStr && jsonStr !== '[DONE]') {
try {
const parsed = JSON.parse(jsonStr)
const text = parsed?.candidates?.[0]?.content?.parts?.[0]?.text
if (text) {
yield text
}
} catch {
// Skip malformed final chunk
}
}
}
} finally {
reader.releaseLock()
}
}
export function parseItemIds(text: string): string[] {
const match = text.match(/\[ITEMS:\s*([^\]]+)\]/)
if (!match) return []
return match[1]
.split(',')
.map((id) => id.trim())
.filter(Boolean)
}
export function stripItemsSuffix(text: string): string {
return text.replace(/\n?\[ITEMS:[^\]]*\]\s*$/, '').trim()
}
+26
View File
@@ -0,0 +1,26 @@
import {
User,
Activity,
Monitor,
Award,
GraduationCap,
Zap,
type LucideIcon,
} from 'lucide-react'
import type { IconColorVariant } from '@/lib/search'
export const iconByType: Record<string, LucideIcon> = {
role: User,
skill: Activity,
project: Monitor,
achievement: Award,
edu: GraduationCap,
action: Zap,
}
export const iconColorStyles: Record<IconColorVariant, { background: string; color: string }> = {
teal: { background: 'var(--accent-light)', color: 'var(--accent)' },
green: { background: 'var(--success-light)', color: 'var(--success)' },
amber: { background: 'var(--amber-light)', color: 'var(--amber)' },
purple: { background: 'rgba(124,58,237,0.08)', color: '#7C3AED' },
}
+42
View File
@@ -0,0 +1,42 @@
import embeddingsData from '@/data/embeddings.json'
interface EmbeddingEntry {
id: string
embedding: number[]
}
interface SearchResult {
id: string
score: number
}
function cosineSimilarity(a: number[], b: number[]): number {
let dot = 0
let magA = 0
let magB = 0
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i]
magA += a[i] * a[i]
magB += b[i] * b[i]
}
const denom = Math.sqrt(magA) * Math.sqrt(magB)
return denom === 0 ? 0 : dot / denom
}
export function semanticSearch(
queryEmbedding: number[],
embeddings: EmbeddingEntry[],
threshold = 0.3
): SearchResult[] {
return embeddings
.map(entry => ({
id: entry.id,
score: cosineSimilarity(queryEmbedding, entry.embedding),
}))
.filter(r => r.score >= threshold)
.sort((a, b) => b.score - a.score)
}
export function loadEmbeddings(): EmbeddingEntry[] {
return embeddingsData as EmbeddingEntry[]
}
+51 -27
View File
@@ -25,24 +25,36 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
**Acceptance Criteria:** **Acceptance Criteria:**
- [ ] Node script `scripts/generate-embeddings.ts` reads all palette data from `src/lib/search.ts` - [ ] Node script `scripts/generate-embeddings.ts` reads all palette data from `src/lib/search.ts`
- [ ] Calls OpenAI `text-embedding-3-small` API with a rich text representation of each item (title + subtitle + keywords + any extended context from data files) - [ ] Uses the same ONNX model (`all-MiniLM-L6-v2` via `@xenova/transformers`) as the browser runtime to generate embeddings
- [ ] Builds a rich text representation of each item (title + subtitle + keywords + extended context from data files)
- [ ] Outputs `src/data/embeddings.json` — array of `{ id: string, embedding: number[] }` - [ ] Outputs `src/data/embeddings.json` — array of `{ id: string, embedding: number[] }`
- [ ] Script is runnable via `npm run generate-embeddings` - [ ] Script is runnable via `npm run generate-embeddings`
- [ ] Script requires `OPENAI_API_KEY` env var; fails gracefully with clear error if missing - [ ] No external API key required — model runs locally via Node.js
- [ ] Embeddings file is committed to repo (static asset, not generated per-build) - [ ] Embeddings file is committed to repo (static asset, not generated per-build)
- [ ] Typecheck passes - [ ] Typecheck passes
#### US-002: Client-side cosine similarity search #### US-002: Preload ONNX model during boot sequence
**Description:** As a visitor, I want the semantic search model to be ready by the time I reach the dashboard, without slowing down the initial experience.
**Acceptance Criteria:**
- [ ] Model download (`all-MiniLM-L6-v2` via `@xenova/transformers`) begins when `App.tsx` mounts (during `'boot'` phase)
- [ ] Download runs in background — does not block or affect boot/ECG/login animations
- [ ] Model is cached in browser (IndexedDB) — second visit loads from cache instantly
- [ ] A global ready state (React context or module-level promise) signals when model is available
- [ ] If model fails to load (network error, etc.), the app continues normally — no error shown to user
- [ ] Typecheck passes
#### US-003: Client-side cosine similarity search
**Description:** As a visitor, I want the command palette to understand what I mean, not just match strings. **Description:** As a visitor, I want the command palette to understand what I mean, not just match strings.
**Acceptance Criteria:** **Acceptance Criteria:**
- [ ] New `src/lib/semantic-search.ts` module with cosine similarity function - [ ] New `src/lib/semantic-search.ts` module with cosine similarity function
- [ ] Loads `embeddings.json` and provides a `semanticSearch(query: string, items: PaletteItem[])` function - [ ] Loads `embeddings.json` and provides a `semanticSearch(query: string, items: PaletteItem[])` function
- [ ] Query embedding is computed client-side using a lightweight approach (see Technical Considerations) - [ ] Query embedding computed in-browser using `all-MiniLM-L6-v2` ONNX model via `@xenova/transformers`
- [ ] Returns ranked `PaletteItem[]` with similarity scores - [ ] Returns ranked `PaletteItem[]` with similarity scores
- [ ] Typecheck passes - [ ] Typecheck passes
#### US-003: Integrate semantic search into command palette #### US-004: Integrate semantic search into command palette
**Description:** As a visitor, I want the command palette to use semantic search with Fuse.js as a fallback. **Description:** As a visitor, I want the command palette to use semantic search with Fuse.js as a fallback.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -53,7 +65,7 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
- [ ] Typecheck passes - [ ] Typecheck passes
- [ ] Verify in browser: search "data analysis" surfaces analytics-related roles/skills, not just items with "data" in the title - [ ] Verify in browser: search "data analysis" surfaces analytics-related roles/skills, not just items with "data" in the title
#### US-004: Enrich embedding content with deep context #### US-005: Enrich embedding content with deep context
**Description:** As a developer, I want embeddings to capture rich context beyond just titles, so semantic search is truly useful. **Description:** As a developer, I want embeddings to capture rich context beyond just titles, so semantic search is truly useful.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -69,7 +81,7 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
### Phase 2: AI Chat Widget ### Phase 2: AI Chat Widget
#### US-005: Chat widget UI — floating button #### US-006: Chat widget UI — floating button
**Description:** As a visitor, I see a floating chat button at the bottom-right of the dashboard that opens a chat panel. **Description:** As a visitor, I see a floating chat button at the bottom-right of the dashboard that opens a chat panel.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -82,7 +94,7 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
- [ ] Typecheck passes - [ ] Typecheck passes
- [ ] Verify in browser using dev server - [ ] Verify in browser using dev server
#### US-006: Chat panel UI #### US-007: Chat panel UI
**Description:** As a visitor, I want a chat panel that feels like a support chat — compact, positioned above the floating button. **Description:** As a visitor, I want a chat panel that feels like a support chat — compact, positioned above the floating button.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -99,7 +111,7 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
- [ ] Typecheck passes - [ ] Typecheck passes
- [ ] Verify in browser using dev server - [ ] Verify in browser using dev server
#### US-007: Gemini Flash integration #### US-008: Gemini Flash integration
**Description:** As a visitor, I can ask natural language questions and get intelligent answers about Andy's experience. **Description:** As a visitor, I can ask natural language questions and get intelligent answers about Andy's experience.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -112,7 +124,7 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
- [ ] Loading state shown while waiting for response - [ ] Loading state shown while waiting for response
- [ ] Typecheck passes - [ ] Typecheck passes
#### US-008: Chat context and conversation history #### US-009: Chat context and conversation history
**Description:** As a visitor, I want multi-turn conversation so I can ask follow-up questions. **Description:** As a visitor, I want multi-turn conversation so I can ask follow-up questions.
**Acceptance Criteria:** **Acceptance Criteria:**
@@ -125,20 +137,21 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
## Functional Requirements ## Functional Requirements
### Phase 1 ### Phase 1
- FR-1: Build script generates OpenAI `text-embedding-3-small` embeddings for all palette items - FR-1: Build script generates embeddings using `all-MiniLM-L6-v2` ONNX model (same model used at runtime)
- FR-2: Embeddings stored as committed static JSON (`src/data/embeddings.json`) - FR-2: Embeddings stored as committed static JSON (`src/data/embeddings.json`)
- FR-3: Client-side cosine similarity ranks items by semantic relevance - FR-3: Client-side cosine similarity ranks items by semantic relevance
- FR-4: Command palette uses semantic search as primary, Fuse.js as fallback - FR-4: Command palette uses semantic search as primary, Fuse.js as fallback
- FR-5: Query embedding must be computed without a runtime API call (see Technical Considerations) - FR-5: ONNX model preloaded during boot sequence (before dashboard renders)
- FR-6: Query embedding computed in-browser — no runtime API calls
### Phase 2 ### Phase 2
- FR-6: Floating chat button rendered in DashboardLayout, bottom-right, above content - FR-7: Floating chat button rendered in DashboardLayout, bottom-right, above content
- FR-7: Chat panel opens/closes on button click with animation - FR-8: Chat panel opens/closes on button click with animation
- FR-8: User messages sent to Gemini Flash API with CV context as system prompt - FR-9: User messages sent to Gemini Flash API with CV context as system prompt
- FR-9: Gemini responses parsed into answer text + relevant item IDs - FR-10: Gemini responses parsed into answer text + relevant item IDs
- FR-10: Relevant items rendered as clickable cards using existing palette item styling and action routing - FR-11: Relevant items rendered as clickable cards using existing palette item styling and action routing
- FR-11: Streaming responses displayed progressively - FR-12: Streaming responses displayed progressively
- FR-12: Conversation state managed per-session (cleared on page reload) - FR-13: Conversation state managed per-session (cleared on page reload)
## Non-Goals ## Non-Goals
@@ -175,13 +188,25 @@ The portfolio's command palette currently uses Fuse.js for fuzzy string matching
## Technical Considerations ## Technical Considerations
### Phase 1: Query Embedding Challenge ### Phase 1: ONNX Model Strategy
The main challenge is computing a query embedding client-side without an API call. Options:
- **Option A (Recommended):** Pre-compute embeddings for items only. At query time, use a lightweight client-side text similarity approach (e.g., TF-IDF or BM25 on the enriched text) combined with the embedding vectors for re-ranking. This avoids shipping a model to the browser.
- **Option B:** Use a small ONNX model in the browser (e.g., `all-MiniLM-L6-v2` via Transformers.js). ~23MB download, but gives true semantic matching. Could be lazy-loaded.
- **Option C:** Call OpenAI embedding API at query time. Adds latency (~200ms) and runtime cost, but simplest implementation.
**Decision needed at implementation time** — Option B gives the best semantic search quality. Option A is simpler but less semantic. Option C is simplest but has runtime costs. **Decision: `all-MiniLM-L6-v2` via `@xenova/transformers` for both build-time and runtime embedding.**
- Same model used everywhere — embeddings live in the same vector space, so cosine similarity works correctly
- No external API keys required for embedding generation or search
- Build script runs the model in Node.js to pre-compute item embeddings
- Browser loads the same model at runtime for query embedding
**Preloading strategy:**
- Model download (~23MB, ONNX format) begins during the boot sequence phase (`'boot'` in App.tsx)
- The boot → ECG → login flow takes 8-10s, giving ample time for download + cache
- Model is cached by the browser (IndexedDB via Transformers.js) — subsequent visits load instantly
- If model hasn't finished loading when user opens command palette, fall back to Fuse.js silently
**Embedding content:**
- Each palette item gets a natural-language paragraph for embedding, not just keywords
- E.g., a consultation becomes: "Senior Data Analyst at Norfolk and Waveney ICB, 2021 to present. Led medicines optimisation analytics, built Power BI dashboards for 200+ clinicians..."
- Richer text = better semantic matching
### Phase 2: Gemini Flash ### Phase 2: Gemini Flash
- Use `gemini-2.0-flash` (or latest) — fast, cheap, good for short-form Q&A - Use `gemini-2.0-flash` (or latest) — fast, cheap, good for short-form Q&A
@@ -205,7 +230,6 @@ The main challenge is computing a query embedding client-side without an API cal
## Open Questions ## Open Questions
- **Phase 1 query embedding**: Which approach (A/B/C) gives the best tradeoff of quality vs. bundle size vs. complexity? This should be prototyped early.
- **Gemini API key exposure**: Is direct client-side exposure acceptable, or should we add a minimal edge function proxy? (User chose direct exposure — revisit if abuse becomes an issue.)
- **Chat widget on mobile**: Should the chat panel be a full-screen modal on small screens, or a bottom sheet? - **Chat widget on mobile**: Should the chat panel be a full-screen modal on small screens, or a bottom sheet?
- **Suggested questions**: Should the chat widget show 2-3 starter questions when first opened (e.g., "What's Andy's NHS experience?", "Tell me about his data skills")? - **Suggested questions**: Should the chat widget show 2-3 starter questions when first opened (e.g., "What's Andy's NHS experience?", "Tell me about his data skills")?
- **Model CDN**: Transformers.js downloads models from Hugging Face by default. Should we self-host the ONNX model files for reliability, or trust HF's CDN?