initial commit
This commit is contained in:
8
.dockerignore
Normal file
8
.dockerignore
Normal file
@@ -0,0 +1,8 @@
|
||||
.git
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
packages/*/dist
|
||||
packages/backend/.env.local
|
||||
*.log
|
||||
.vscode
|
||||
.idea
|
||||
86
.gitea/workflows/main.yaml
Normal file
86
.gitea/workflows/main.yaml
Normal file
@@ -0,0 +1,86 @@
|
||||
name: Recommender Build and Deploy (internal)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch: {}
|
||||
|
||||
env:
|
||||
REGISTRY_HOST: git.ivanch.me
|
||||
REGISTRY_USERNAME: ivanch
|
||||
IMAGE: ${{ env.REGISTRY_HOST }}/ivanch/recommender
|
||||
KUBE_CONFIG: ${{ secrets.KUBE_CONFIG }}
|
||||
|
||||
jobs:
|
||||
build_recommender:
|
||||
name: Build Recommender Image
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Log in to Container Registry
|
||||
run: |
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" \
|
||||
| docker login "${{ env.REGISTRY_HOST }}" \
|
||||
-u "${{ env.REGISTRY_USERNAME }}" \
|
||||
--password-stdin
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and Push Multi-Arch Image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
push: true
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ env.IMAGE }}:latest
|
||||
|
||||
deploy_recommender:
|
||||
name: Deploy Recommender (internal)
|
||||
runs-on: ubuntu-amd64
|
||||
needs: build_recommender
|
||||
steps:
|
||||
- name: Check KUBE_CONFIG validity
|
||||
run: |
|
||||
if [ -z "${KUBE_CONFIG}" ] || [ "${KUBE_CONFIG}" = "" ] || [ "${KUBE_CONFIG// }" = "" ]; then
|
||||
echo "KUBE_CONFIG is not set or is empty."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Download and install dependencies
|
||||
run: |
|
||||
apt-get update -y
|
||||
apt-get install -y curl
|
||||
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
|
||||
install -m 0755 kubectl /usr/local/bin/kubectl
|
||||
kubectl version --client
|
||||
|
||||
- name: Set up kubeconfig
|
||||
run: |
|
||||
cd deploy
|
||||
echo "$KUBE_CONFIG" > kubeconfig.yaml
|
||||
env:
|
||||
KUBE_CONFIG: ${{ env.KUBE_CONFIG }}
|
||||
|
||||
- name: Check connection to cluster
|
||||
run: |
|
||||
cd deploy
|
||||
kubectl --kubeconfig=kubeconfig.yaml cluster-info
|
||||
|
||||
- name: Apply Recommender deployment
|
||||
run: |
|
||||
cd deploy
|
||||
kubectl --kubeconfig=kubeconfig.yaml apply -f recommender.yaml
|
||||
|
||||
- name: Rollout restart
|
||||
run: |
|
||||
cd deploy
|
||||
kubectl --kubeconfig=kubeconfig.yaml rollout restart deployment recommender -n media
|
||||
27
.gitignore
vendored
Normal file
27
.gitignore
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
dist-ssr/
|
||||
|
||||
# Environment secrets — use .env.local for real values, never commit secrets
|
||||
.env.local
|
||||
*.local
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# Editor
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea/
|
||||
.DS_Store
|
||||
.claude/
|
||||
documents/
|
||||
|
||||
# OS
|
||||
Thumbs.db
|
||||
50
Dockerfile
Normal file
50
Dockerfile
Normal file
@@ -0,0 +1,50 @@
|
||||
# ─── Stage 1: Install all workspace dependencies ─────────────────────────────
|
||||
FROM node:22-slim AS deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY packages/backend/package.json ./packages/backend/package.json
|
||||
COPY packages/frontend/package.json ./packages/frontend/package.json
|
||||
|
||||
RUN npm ci --ignore-scripts
|
||||
|
||||
# ─── Stage 2: Build the Preact frontend ──────────────────────────────────────
|
||||
FROM deps AS build-frontend
|
||||
|
||||
COPY packages/frontend/ ./packages/frontend/
|
||||
|
||||
RUN npm run build -w frontend
|
||||
|
||||
# ─── Stage 3: Runtime image ───────────────────────────────────────────────────
|
||||
FROM node:22-slim AS runtime
|
||||
|
||||
# Install Nginx
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends nginx \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# --- Backend ---
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY --from=deps /app/packages/backend/node_modules ./packages/backend/node_modules
|
||||
COPY packages/backend/ ./packages/backend/
|
||||
|
||||
# --- Frontend static files ---
|
||||
COPY --from=build-frontend /app/packages/frontend/dist /usr/share/nginx/html
|
||||
|
||||
# --- Nginx config ---
|
||||
COPY nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# --- Entrypoint ---
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
# DATABASE_URL and OPENAI_API_KEY must be set when running the container.
|
||||
ENV PORT=3000
|
||||
ENV DATABASE_URL=postgres://user:password@localhost:5432/recommender
|
||||
ENV OPENAI_API_KEY=your-openai-api-key-here
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
24
README.md
Normal file
24
README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# Recommender
|
||||
|
||||
A pure TypeScript monolith AI agent application that will recommend TV shows based on a very customized user profile and input.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- **packages/frontend**: Preact application powered by Vite and TypeScript.
|
||||
- **packages/backend**: Fastify server utilizing Drizzle ORM and the official OpenAI SDK.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Install dependencies**:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. **Configure Environment**:
|
||||
Ensure `packages/backend/.env` exists with your database and AI settings.
|
||||
|
||||
3. **Run the application**:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
This will concurrently start the frontend development server and the backend API.
|
||||
72
deploy/recommender.yaml
Normal file
72
deploy/recommender.yaml
Normal file
@@ -0,0 +1,72 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: recommender
|
||||
namespace: media
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: recommender
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: recommender
|
||||
spec:
|
||||
containers:
|
||||
- name: recommender
|
||||
image: git.ivanch.me/ivanch/recommender:latest
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
env:
|
||||
- name: OPENAI_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: recommender-secrets
|
||||
key: OPENAI_API_KEY
|
||||
- name: DATABASE_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: recommender-secrets
|
||||
key: DATABASE_URL
|
||||
resources:
|
||||
requests:
|
||||
memory: "256Mi"
|
||||
cpu: "500m"
|
||||
limits:
|
||||
memory: "512Mi"
|
||||
cpu: "1"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: recommender
|
||||
namespace: media
|
||||
spec:
|
||||
selector:
|
||||
app: recommender
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: recommender
|
||||
namespace: media
|
||||
labels:
|
||||
app.kubernetes.io/name: recommender
|
||||
spec:
|
||||
ingressClassName: nginx
|
||||
rules:
|
||||
- host: "recommender.haven"
|
||||
http:
|
||||
paths:
|
||||
- path: "/"
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: recommender
|
||||
port:
|
||||
number: 80
|
||||
8
entrypoint.sh
Normal file
8
entrypoint.sh
Normal file
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Start Nginx in the background
|
||||
nginx &
|
||||
|
||||
# Start the Node.js backend
|
||||
exec node /app/node_modules/.bin/tsx /app/packages/backend/src/index.ts
|
||||
27
nginx.conf
Normal file
27
nginx.conf
Normal file
@@ -0,0 +1,27 @@
|
||||
events {}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
# Reverse-proxy /api/* -> Fastify backend (strips the /api prefix)
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:3000/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Serve Preact static build — SPA fallback to index.html
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
}
|
||||
4479
package-lock.json
generated
Normal file
4479
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
package.json
Normal file
21
package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "recommender",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"dev": "concurrently -n \"backend,frontend\" -c \"bgBlue.bold,bgCyan.bold\" \"npm run dev -w backend\" \"npm run dev -w frontend\""
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"private": "true",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.2.1"
|
||||
}
|
||||
}
|
||||
6
packages/backend/.env
Normal file
6
packages/backend/.env
Normal file
@@ -0,0 +1,6 @@
|
||||
# Copy this file to .env.local and fill in the real values.
|
||||
# .env.local is gitignored and will override these defaults.
|
||||
# In production / Docker, supply these as environment variables.
|
||||
|
||||
DATABASE_URL=postgres://user:password@localhost:5432/recommender
|
||||
OPENAI_API_KEY=your-openai-api-key-here
|
||||
13
packages/backend/drizzle.config.ts
Normal file
13
packages/backend/drizzle.config.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'drizzle-kit';
|
||||
import * as dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export default defineConfig({
|
||||
schema: './src/db/schema.ts',
|
||||
out: './drizzle',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: process.env['DATABASE_URL'] ?? 'postgres://user:password@localhost:5432/recommender',
|
||||
},
|
||||
});
|
||||
27
packages/backend/package.json
Normal file
27
packages/backend/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"dev": "tsx watch src/index.ts"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"dotenv": "^17.3.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"fastify": "^5.8.4",
|
||||
"openai": "^6.32.0",
|
||||
"postgres": "^3.4.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.0",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
21
packages/backend/src/agent.ts
Normal file
21
packages/backend/src/agent.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import OpenAI from 'openai';
|
||||
import * as dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
export const openai = new OpenAI({
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
});
|
||||
|
||||
export async function askAgent(prompt: string) {
|
||||
try {
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-5.4',
|
||||
service_tier: 'flex',
|
||||
messages: [{ role: 'user', content: prompt }],
|
||||
});
|
||||
return response!.choices![0]!.message!.content;
|
||||
} catch (err) {
|
||||
console.error('Agent endpoint dummy error:', err instanceof Error ? err.message : err);
|
||||
return 'Agent is in dummy mode or encountered an error.';
|
||||
}
|
||||
}
|
||||
66
packages/backend/src/agents/curator.ts
Normal file
66
packages/backend/src/agents/curator.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { openai } from '../agent.js';
|
||||
import type { InterpreterOutput, RankingOutput, CuratorOutput } from '../types/agents.js';
|
||||
|
||||
export async function runCurator(
|
||||
ranking: RankingOutput,
|
||||
interpreter: InterpreterOutput,
|
||||
): Promise<CuratorOutput[]> {
|
||||
const allShows = [
|
||||
...ranking.definitely_like.map((t) => ({ title: t, category: 'Definitely Like' as const })),
|
||||
...ranking.might_like.map((t) => ({ title: t, category: 'Might Like' as const })),
|
||||
...ranking.questionable.map((t) => ({ title: t, category: 'Questionable' as const })),
|
||||
...ranking.will_not_like.map((t) => ({ title: t, category: 'Will Not Like' as const })),
|
||||
];
|
||||
|
||||
if (allShows.length === 0) return [];
|
||||
|
||||
const showList = allShows
|
||||
.map((s) => `- "${s.title}" (${s.category})`)
|
||||
.join('\n');
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-5.4-mini',
|
||||
temperature: 0.5,
|
||||
service_tier: 'flex',
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: `You are a TV show recommendation curator. For each show, write a concise 1-2 sentence explanation of why it was assigned to its category based on the user's preferences.
|
||||
|
||||
Your output MUST be valid JSON:
|
||||
{
|
||||
"shows": [
|
||||
{
|
||||
"title": string,
|
||||
"explanation": string,
|
||||
"category": "Definitely Like" | "Might Like" | "Questionable" | "Will Not Like"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Rules:
|
||||
- Preserve the exact title and category as given
|
||||
- Keep explanations concise (1-2 sentences max)
|
||||
- Reference specific user preferences in the explanation
|
||||
- Be honest — explain why "Questionable" or "Will Not Like" shows got that rating`,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `User preferences summary:
|
||||
Liked: ${JSON.stringify(interpreter.liked)}
|
||||
Themes: ${JSON.stringify(interpreter.themes)}
|
||||
Tone: ${JSON.stringify(interpreter.tone)}
|
||||
Character preferences: ${JSON.stringify(interpreter.character_preferences)}
|
||||
Avoid: ${JSON.stringify(interpreter.avoid)}
|
||||
|
||||
Shows to describe:
|
||||
${showList}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content ?? '{"shows":[]}';
|
||||
const result = JSON.parse(content) as { shows: CuratorOutput[] };
|
||||
return result.shows ?? [];
|
||||
}
|
||||
56
packages/backend/src/agents/interpreter.ts
Normal file
56
packages/backend/src/agents/interpreter.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { openai } from '../agent.js';
|
||||
import type { InterpreterOutput } from '../types/agents.js';
|
||||
|
||||
interface InterpreterInput {
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
feedback_context?: string;
|
||||
}
|
||||
|
||||
export async function runInterpreter(input: InterpreterInput): Promise<InterpreterOutput> {
|
||||
const feedbackSection = input.feedback_context
|
||||
? `\n\nUser Feedback Context (incorporate into preferences):\n${input.feedback_context}`
|
||||
: '';
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-5.4-mini',
|
||||
temperature: 0.2,
|
||||
service_tier: 'flex',
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: `You are a TV show preference interpreter. Transform raw user input into structured, normalized preferences.
|
||||
|
||||
Your output MUST be valid JSON matching this schema:
|
||||
{
|
||||
"liked": string[], // shows the user likes
|
||||
"disliked": string[], // shows the user dislikes
|
||||
"themes": string[], // normalized themes (e.g. "spy" -> "espionage")
|
||||
"character_preferences": string[], // character types they prefer
|
||||
"tone": string[], // tone descriptors (e.g. "serious", "grounded", "dark")
|
||||
"avoid": string[] // things to explicitly avoid
|
||||
}
|
||||
|
||||
Rules:
|
||||
- Extract implicit preferences from the main prompt
|
||||
- Normalize terminology (e.g. "spy" → "espionage", "cop show" → "police procedural")
|
||||
- Detect and resolve contradictions (prefer explicit over implicit)
|
||||
- Do NOT assume anything not stated or clearly implied
|
||||
- Be specific and concrete, not vague`,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Main prompt: ${input.main_prompt}
|
||||
Liked shows: ${input.liked_shows || '(none)'}
|
||||
Disliked shows: ${input.disliked_shows || '(none)'}
|
||||
Themes and requirements: ${input.themes || '(none)'}${feedbackSection}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content ?? '{}';
|
||||
return JSON.parse(content) as InterpreterOutput;
|
||||
}
|
||||
83
packages/backend/src/agents/ranking.ts
Normal file
83
packages/backend/src/agents/ranking.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { openai } from '../agent.js';
|
||||
import type { InterpreterOutput, RetrievalOutput, RankingOutput } from '../types/agents.js';
|
||||
|
||||
export async function runRanking(
|
||||
interpreter: InterpreterOutput,
|
||||
retrieval: RetrievalOutput,
|
||||
): Promise<RankingOutput> {
|
||||
// Phase 1: Pre-filter — remove avoidance violations
|
||||
const avoidList = interpreter.avoid.map((a) => a.toLowerCase());
|
||||
const filtered = retrieval.candidates.filter((c) => {
|
||||
const text = (c.title + ' ' + c.reason).toLowerCase();
|
||||
return !avoidList.some((a) => text.includes(a));
|
||||
});
|
||||
|
||||
// Phase 2: Chunked ranking — split into groups of ~15
|
||||
const CHUNK_SIZE = 15;
|
||||
const chunks: typeof filtered[] = [];
|
||||
for (let i = 0; i < filtered.length; i += CHUNK_SIZE) {
|
||||
chunks.push(filtered.slice(i, i + CHUNK_SIZE));
|
||||
}
|
||||
|
||||
const allBuckets: RankingOutput = {
|
||||
definitely_like: [],
|
||||
might_like: [],
|
||||
questionable: [],
|
||||
will_not_like: [],
|
||||
};
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const chunkTitles = chunk.map((c) => `- ${c.title}: ${c.reason}`).join('\n');
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-5.4',
|
||||
temperature: 0.2,
|
||||
service_tier: 'flex',
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: `You are a TV show ranking critic. Assign each show to exactly one of four confidence buckets based on how well it matches the user's preferences.
|
||||
|
||||
Buckets:
|
||||
- "definitely_like": Near-perfect match to all preferences
|
||||
- "might_like": Strong match to most preferences
|
||||
- "questionable": Partial alignment, some aspects don't match
|
||||
- "will_not_like": Likely mismatch, conflicts with preferences or avoidance criteria
|
||||
|
||||
Your output MUST be valid JSON:
|
||||
{
|
||||
"definitely_like": string[],
|
||||
"might_like": string[],
|
||||
"questionable": string[],
|
||||
"will_not_like": string[]
|
||||
}
|
||||
|
||||
Every show in the input must appear in exactly one bucket. Use the title exactly as given.`,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `User preferences:
|
||||
Liked shows: ${JSON.stringify(interpreter.liked)}
|
||||
Themes: ${JSON.stringify(interpreter.themes)}
|
||||
Character preferences: ${JSON.stringify(interpreter.character_preferences)}
|
||||
Tone: ${JSON.stringify(interpreter.tone)}
|
||||
Avoid: ${JSON.stringify(interpreter.avoid)}
|
||||
|
||||
Rank these shows:
|
||||
${chunkTitles}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content ?? '{}';
|
||||
const chunkResult = JSON.parse(content) as Partial<RankingOutput>;
|
||||
|
||||
allBuckets.definitely_like.push(...(chunkResult.definitely_like ?? []));
|
||||
allBuckets.might_like.push(...(chunkResult.might_like ?? []));
|
||||
allBuckets.questionable.push(...(chunkResult.questionable ?? []));
|
||||
allBuckets.will_not_like.push(...(chunkResult.will_not_like ?? []));
|
||||
}
|
||||
|
||||
return allBuckets;
|
||||
}
|
||||
47
packages/backend/src/agents/retrieval.ts
Normal file
47
packages/backend/src/agents/retrieval.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { openai } from '../agent.js';
|
||||
import type { InterpreterOutput, RetrievalOutput } from '../types/agents.js';
|
||||
|
||||
export async function runRetrieval(input: InterpreterOutput): Promise<RetrievalOutput> {
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-5.4',
|
||||
temperature: 0.9,
|
||||
service_tier: 'flex',
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: `You are a TV show candidate generator. Your goal is to brainstorm a LARGE, DIVERSE pool of 60–80 TV show candidates that match the user's structured preferences.
|
||||
|
||||
Your output MUST be valid JSON matching this schema:
|
||||
{
|
||||
"candidates": [
|
||||
{ "title": string, "reason": string }
|
||||
]
|
||||
}
|
||||
|
||||
Rules:
|
||||
- Include both well-known and obscure shows
|
||||
- Prioritize RECALL over precision — it's better to include too many than too few
|
||||
- Each "reason" should briefly explain why the show matches the preferences
|
||||
- Avoid duplicates
|
||||
- Include shows from different decades, countries, and networks
|
||||
- Aim for 60–80 candidates minimum`,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Structured preferences:
|
||||
Liked shows: ${JSON.stringify(input.liked)}
|
||||
Disliked shows: ${JSON.stringify(input.disliked)}
|
||||
Themes: ${JSON.stringify(input.themes)}
|
||||
Character preferences: ${JSON.stringify(input.character_preferences)}
|
||||
Tone: ${JSON.stringify(input.tone)}
|
||||
Avoid: ${JSON.stringify(input.avoid)}
|
||||
|
||||
Generate a large, diverse pool of TV show candidates.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content ?? '{"candidates":[]}';
|
||||
return JSON.parse(content) as RetrievalOutput;
|
||||
}
|
||||
9
packages/backend/src/db.ts
Normal file
9
packages/backend/src/db.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const connectionString = process.env.DATABASE_URL || 'postgres://user:password@iris.haven:5432/recommender';
|
||||
export const client = postgres(connectionString);
|
||||
export const db = drizzle(client);
|
||||
2
packages/backend/src/db/index.ts
Normal file
2
packages/backend/src/db/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { db, client } from '../db.js';
|
||||
export * as schema from './schema.js';
|
||||
26
packages/backend/src/db/schema.ts
Normal file
26
packages/backend/src/db/schema.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { pgTable, uuid, text, jsonb, timestamp, integer, uniqueIndex } from 'drizzle-orm/pg-core';
|
||||
import type { CuratorOutput } from '../types/agents.js';
|
||||
|
||||
export const recommendations = pgTable('recommendations', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
title: text('title').notNull(),
|
||||
main_prompt: text('main_prompt').notNull(),
|
||||
liked_shows: text('liked_shows').notNull().default(''),
|
||||
disliked_shows: text('disliked_shows').notNull().default(''),
|
||||
themes: text('themes').notNull().default(''),
|
||||
recommendations: jsonb('recommendations').$type<CuratorOutput[]>(),
|
||||
status: text('status').notNull().default('pending'),
|
||||
created_at: timestamp('created_at').defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const feedback = pgTable(
|
||||
'feedback',
|
||||
{
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
tv_show_name: text('tv_show_name').notNull(),
|
||||
stars: integer('stars').notNull(),
|
||||
feedback: text('feedback').notNull().default(''),
|
||||
created_at: timestamp('created_at').defaultNow().notNull(),
|
||||
},
|
||||
(table) => [uniqueIndex('feedback_tv_show_name_idx').on(table.tv_show_name)],
|
||||
);
|
||||
36
packages/backend/src/index.ts
Normal file
36
packages/backend/src/index.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import Fastify from 'fastify';
|
||||
import * as dotenv from 'dotenv';
|
||||
import recommendationsRoute from './routes/recommendations.js';
|
||||
import feedbackRoute from './routes/feedback.js';
|
||||
|
||||
// Load .env first, then .env.local
|
||||
// env vars set on the container take precedence over both files
|
||||
dotenv.config();
|
||||
dotenv.config({ path: '.env.local', override: true });
|
||||
|
||||
const fastify = Fastify({ logger: true });
|
||||
|
||||
// CORS — allow frontend dev server and production
|
||||
fastify.addHook('onRequest', async (_req, reply) => {
|
||||
reply.header('Access-Control-Allow-Origin', '*');
|
||||
reply.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
||||
reply.header('Access-Control-Allow-Headers', 'Content-Type');
|
||||
});
|
||||
|
||||
fastify.options('*', async (_req, reply) => {
|
||||
return reply.send();
|
||||
});
|
||||
|
||||
// Body parsing is included in Fastify by default for JSON
|
||||
await fastify.register(recommendationsRoute);
|
||||
await fastify.register(feedbackRoute);
|
||||
|
||||
const port = Number(process.env['PORT'] ?? 3000);
|
||||
|
||||
try {
|
||||
await fastify.listen({ port, host: '0.0.0.0' });
|
||||
console.log(`Backend listening on http://localhost:${port}`);
|
||||
} catch (err) {
|
||||
fastify.log.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
118
packages/backend/src/pipelines/recommendation.ts
Normal file
118
packages/backend/src/pipelines/recommendation.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db } from '../db.js';
|
||||
import { recommendations } from '../db/schema.js';
|
||||
import { runInterpreter } from '../agents/interpreter.js';
|
||||
import { runRetrieval } from '../agents/retrieval.js';
|
||||
import { runRanking } from '../agents/ranking.js';
|
||||
import { runCurator } from '../agents/curator.js';
|
||||
import type { CuratorOutput, SSEEvent } from '../types/agents.js';
|
||||
|
||||
type RecommendationRecord = typeof recommendations.$inferSelect;
|
||||
|
||||
function log(recId: string, msg: string, data?: unknown) {
|
||||
const ts = new Date().toISOString();
|
||||
if (data !== undefined) {
|
||||
console.log(`[pipeline] [${ts}] [${recId}] ${msg}`, data);
|
||||
} else {
|
||||
console.log(`[pipeline] [${ts}] [${recId}] ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function runPipeline(
|
||||
rec: RecommendationRecord,
|
||||
sseWrite: (event: SSEEvent) => void,
|
||||
feedbackContext?: string,
|
||||
): Promise<CuratorOutput[]> {
|
||||
let currentStage: SSEEvent['stage'] = 'interpreter';
|
||||
const startTime = Date.now();
|
||||
|
||||
log(rec.id, `Starting pipeline for "${rec.title}"${feedbackContext ? ' (with feedback context)' : ''}`);
|
||||
|
||||
try {
|
||||
// Set status to running
|
||||
log(rec.id, 'Setting status → running');
|
||||
await db
|
||||
.update(recommendations)
|
||||
.set({ status: 'running' })
|
||||
.where(eq(recommendations.id, rec.id));
|
||||
|
||||
// --- Interpreter ---
|
||||
currentStage = 'interpreter';
|
||||
log(rec.id, 'Interpreter: start');
|
||||
sseWrite({ stage: 'interpreter', status: 'start' });
|
||||
const t0 = Date.now();
|
||||
const interpreterOutput = await runInterpreter({
|
||||
main_prompt: rec.main_prompt,
|
||||
liked_shows: rec.liked_shows,
|
||||
disliked_shows: rec.disliked_shows,
|
||||
themes: rec.themes,
|
||||
...(feedbackContext !== undefined ? { feedback_context: feedbackContext } : {}),
|
||||
});
|
||||
log(rec.id, `Interpreter: done (${Date.now() - t0}ms)`, {
|
||||
liked: interpreterOutput.liked,
|
||||
disliked: interpreterOutput.disliked,
|
||||
themes: interpreterOutput.themes,
|
||||
tone: interpreterOutput.tone,
|
||||
avoid: interpreterOutput.avoid,
|
||||
});
|
||||
sseWrite({ stage: 'interpreter', status: 'done', data: interpreterOutput });
|
||||
|
||||
// --- Retrieval ---
|
||||
currentStage = 'retrieval';
|
||||
log(rec.id, 'Retrieval: start');
|
||||
sseWrite({ stage: 'retrieval', status: 'start' });
|
||||
const t1 = Date.now();
|
||||
const retrievalOutput = await runRetrieval(interpreterOutput);
|
||||
log(rec.id, `Retrieval: done (${Date.now() - t1}ms) — ${retrievalOutput.candidates.length} candidates`, {
|
||||
titles: retrievalOutput.candidates.map((c) => c.title),
|
||||
});
|
||||
sseWrite({ stage: 'retrieval', status: 'done', data: retrievalOutput });
|
||||
|
||||
// --- Ranking ---
|
||||
currentStage = 'ranking';
|
||||
log(rec.id, 'Ranking: start');
|
||||
sseWrite({ stage: 'ranking', status: 'start' });
|
||||
const t2 = Date.now();
|
||||
const rankingOutput = await runRanking(interpreterOutput, retrievalOutput);
|
||||
log(rec.id, `Ranking: done (${Date.now() - t2}ms)`, {
|
||||
definitely_like: rankingOutput.definitely_like.length,
|
||||
might_like: rankingOutput.might_like.length,
|
||||
questionable: rankingOutput.questionable.length,
|
||||
will_not_like: rankingOutput.will_not_like.length,
|
||||
});
|
||||
sseWrite({ stage: 'ranking', status: 'done', data: rankingOutput });
|
||||
|
||||
// --- Curator ---
|
||||
currentStage = 'curator';
|
||||
log(rec.id, 'Curator: start');
|
||||
sseWrite({ stage: 'curator', status: 'start' });
|
||||
const t3 = Date.now();
|
||||
const curatorOutput = await runCurator(rankingOutput, interpreterOutput);
|
||||
log(rec.id, `Curator: done (${Date.now() - t3}ms) — ${curatorOutput.length} shows curated`);
|
||||
sseWrite({ stage: 'curator', status: 'done', data: curatorOutput });
|
||||
|
||||
// Save results to DB
|
||||
log(rec.id, 'Saving results to DB');
|
||||
await db
|
||||
.update(recommendations)
|
||||
.set({ recommendations: curatorOutput, status: 'done' })
|
||||
.where(eq(recommendations.id, rec.id));
|
||||
|
||||
sseWrite({ stage: 'complete', status: 'done' });
|
||||
|
||||
log(rec.id, `Pipeline complete (total: ${Date.now() - startTime}ms)`);
|
||||
return curatorOutput;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
log(rec.id, `Pipeline error at stage "${currentStage}": ${message}`);
|
||||
|
||||
sseWrite({ stage: currentStage, status: 'error', data: { message } });
|
||||
|
||||
await db
|
||||
.update(recommendations)
|
||||
.set({ status: 'error' })
|
||||
.where(eq(recommendations.id, rec.id));
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
38
packages/backend/src/routes/feedback.ts
Normal file
38
packages/backend/src/routes/feedback.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db } from '../db.js';
|
||||
import { feedback } from '../db/schema.js';
|
||||
|
||||
export default async function feedbackRoute(fastify: FastifyInstance) {
|
||||
// POST /feedback — upsert by tv_show_name
|
||||
fastify.post('/feedback', async (request, reply) => {
|
||||
const body = request.body as {
|
||||
tv_show_name: string;
|
||||
stars: number;
|
||||
feedback?: string;
|
||||
};
|
||||
|
||||
await db
|
||||
.insert(feedback)
|
||||
.values({
|
||||
tv_show_name: body.tv_show_name,
|
||||
stars: body.stars,
|
||||
feedback: body.feedback ?? '',
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: feedback.tv_show_name,
|
||||
set: {
|
||||
stars: body.stars,
|
||||
feedback: body.feedback ?? '',
|
||||
},
|
||||
});
|
||||
|
||||
return reply.code(201).send({ ok: true });
|
||||
});
|
||||
|
||||
// GET /feedback — return all feedback entries
|
||||
fastify.get('/feedback', async (_request, reply) => {
|
||||
const rows = await db.select().from(feedback);
|
||||
return reply.send(rows);
|
||||
});
|
||||
}
|
||||
124
packages/backend/src/routes/recommendations.ts
Normal file
124
packages/backend/src/routes/recommendations.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { eq, desc } from 'drizzle-orm';
|
||||
import { db } from '../db.js';
|
||||
import { recommendations, feedback } from '../db/schema.js';
|
||||
import { runPipeline } from '../pipelines/recommendation.js';
|
||||
import type { SSEEvent } from '../types/agents.js';
|
||||
|
||||
export default async function recommendationsRoute(fastify: FastifyInstance) {
|
||||
// POST /recommendations — create record, return { id }
|
||||
fastify.post('/recommendations', async (request, reply) => {
|
||||
const body = request.body as {
|
||||
main_prompt: string;
|
||||
liked_shows?: string;
|
||||
disliked_shows?: string;
|
||||
themes?: string;
|
||||
};
|
||||
|
||||
const title = (body.main_prompt ?? '')
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.slice(0, 5)
|
||||
.join(' ');
|
||||
|
||||
const [rec] = await db
|
||||
.insert(recommendations)
|
||||
.values({
|
||||
title: title || 'Untitled',
|
||||
main_prompt: body.main_prompt ?? '',
|
||||
liked_shows: body.liked_shows ?? '',
|
||||
disliked_shows: body.disliked_shows ?? '',
|
||||
themes: body.themes ?? '',
|
||||
status: 'pending',
|
||||
})
|
||||
.returning({ id: recommendations.id });
|
||||
|
||||
return reply.code(201).send({ id: rec?.id });
|
||||
});
|
||||
|
||||
// GET /recommendations — list all
|
||||
fastify.get('/recommendations', async (_request, reply) => {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: recommendations.id,
|
||||
title: recommendations.title,
|
||||
status: recommendations.status,
|
||||
created_at: recommendations.created_at,
|
||||
})
|
||||
.from(recommendations)
|
||||
.orderBy(desc(recommendations.created_at));
|
||||
return reply.send(rows);
|
||||
});
|
||||
|
||||
// GET /recommendations/:id — full record
|
||||
fastify.get('/recommendations/:id', async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const [rec] = await db
|
||||
.select()
|
||||
.from(recommendations)
|
||||
.where(eq(recommendations.id, id));
|
||||
|
||||
if (!rec) return reply.code(404).send({ error: 'Not found' });
|
||||
return reply.send(rec);
|
||||
});
|
||||
|
||||
// GET /recommendations/:id/stream — SSE pipeline stream
|
||||
// Always fetches all current feedback and injects if present (supports rerank flow)
|
||||
fastify.get('/recommendations/:id/stream', async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const [rec] = await db
|
||||
.select()
|
||||
.from(recommendations)
|
||||
.where(eq(recommendations.id, id));
|
||||
|
||||
if (!rec) return reply.code(404).send({ error: 'Not found' });
|
||||
|
||||
// Load all feedback to potentially inject as context
|
||||
const feedbackRows = await db.select().from(feedback);
|
||||
const feedbackContext =
|
||||
feedbackRows.length > 0
|
||||
? feedbackRows
|
||||
.map(
|
||||
(f) =>
|
||||
`Show: "${f.tv_show_name}" — Rating: ${f.stars}/3 stars${f.feedback ? ` — Comment: ${f.feedback}` : ''}`,
|
||||
)
|
||||
.join('\n')
|
||||
: undefined;
|
||||
|
||||
// Set SSE headers and hijack
|
||||
reply.raw.setHeader('Content-Type', 'text/event-stream');
|
||||
reply.raw.setHeader('Cache-Control', 'no-cache');
|
||||
reply.raw.setHeader('Connection', 'keep-alive');
|
||||
reply.raw.setHeader('Access-Control-Allow-Origin', '*');
|
||||
reply.raw.flushHeaders();
|
||||
reply.hijack();
|
||||
|
||||
const sseWrite = (event: SSEEvent) => {
|
||||
reply.raw.write(`data: ${JSON.stringify(event)}\n\n`);
|
||||
};
|
||||
|
||||
try {
|
||||
await runPipeline(rec, sseWrite, feedbackContext);
|
||||
} finally {
|
||||
reply.raw.end();
|
||||
}
|
||||
});
|
||||
|
||||
// POST /recommendations/:id/rerank — reset status so client can re-open SSE stream
|
||||
fastify.post('/recommendations/:id/rerank', async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const [rec] = await db
|
||||
.select({ id: recommendations.id })
|
||||
.from(recommendations)
|
||||
.where(eq(recommendations.id, id));
|
||||
|
||||
if (!rec) return reply.code(404).send({ error: 'Not found' });
|
||||
|
||||
await db
|
||||
.update(recommendations)
|
||||
.set({ status: 'pending' })
|
||||
.where(eq(recommendations.id, id));
|
||||
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
}
|
||||
41
packages/backend/src/types/agents.ts
Normal file
41
packages/backend/src/types/agents.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export interface InterpreterOutput {
|
||||
liked: string[];
|
||||
disliked: string[];
|
||||
themes: string[];
|
||||
character_preferences: string[];
|
||||
tone: string[];
|
||||
avoid: string[];
|
||||
}
|
||||
|
||||
export interface RetrievalCandidate {
|
||||
title: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface RetrievalOutput {
|
||||
candidates: RetrievalCandidate[];
|
||||
}
|
||||
|
||||
export interface RankingOutput {
|
||||
definitely_like: string[];
|
||||
might_like: string[];
|
||||
questionable: string[];
|
||||
will_not_like: string[];
|
||||
}
|
||||
|
||||
export type CuratorCategory = 'Definitely Like' | 'Might Like' | 'Questionable' | 'Will Not Like';
|
||||
|
||||
export interface CuratorOutput {
|
||||
title: string;
|
||||
explanation: string;
|
||||
category: CuratorCategory;
|
||||
}
|
||||
|
||||
export type PipelineStage = 'interpreter' | 'retrieval' | 'ranking' | 'curator' | 'complete';
|
||||
export type SSEStatus = 'start' | 'done' | 'error';
|
||||
|
||||
export interface SSEEvent {
|
||||
stage: PipelineStage;
|
||||
status: SSEStatus;
|
||||
data?: unknown;
|
||||
}
|
||||
44
packages/backend/tsconfig.json
Normal file
44
packages/backend/tsconfig.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
// Visit https://aka.ms/tsconfig to read more about this file
|
||||
"compilerOptions": {
|
||||
// File Layout
|
||||
// "rootDir": "./src",
|
||||
// "outDir": "./dist",
|
||||
|
||||
// Environment Settings
|
||||
// See also https://aka.ms/tsconfig/module
|
||||
"module": "nodenext",
|
||||
"target": "esnext",
|
||||
"types": [],
|
||||
// For nodejs:
|
||||
// "lib": ["esnext"],
|
||||
// "types": ["node"],
|
||||
// and npm install -D @types/node
|
||||
|
||||
// Other Outputs
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
|
||||
// Stricter Typechecking Options
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
|
||||
// Style Options
|
||||
// "noImplicitReturns": true,
|
||||
// "noImplicitOverride": true,
|
||||
// "noUnusedLocals": true,
|
||||
// "noUnusedParameters": true,
|
||||
// "noFallthroughCasesInSwitch": true,
|
||||
// "noPropertyAccessFromIndexSignature": true,
|
||||
|
||||
// Recommended Options
|
||||
"strict": true,
|
||||
"jsx": "react-jsx",
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
"moduleDetection": "force",
|
||||
"skipLibCheck": true,
|
||||
}
|
||||
}
|
||||
24
packages/frontend/.gitignore
vendored
Normal file
24
packages/frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
13
packages/frontend/index.html
Normal file
13
packages/frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
20
packages/frontend/package.json
Normal file
20
packages/frontend/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"preact": "^10.29.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2.10.4",
|
||||
"@types/node": "^24.12.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8.0.1"
|
||||
}
|
||||
}
|
||||
1
packages/frontend/public/favicon.svg
Normal file
1
packages/frontend/public/favicon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
24
packages/frontend/public/icons.svg
Normal file
24
packages/frontend/public/icons.svg
Normal file
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
54
packages/frontend/src/api/client.ts
Normal file
54
packages/frontend/src/api/client.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { Recommendation, RecommendationSummary, FeedbackEntry } from '../types/index.js';
|
||||
|
||||
const BASE = '/api';
|
||||
|
||||
async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...options,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`HTTP ${res.status}: ${text}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export function createRecommendation(body: {
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
}): Promise<{ id: string }> {
|
||||
return request('/recommendations', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
export function listRecommendations(): Promise<RecommendationSummary[]> {
|
||||
return request('/recommendations');
|
||||
}
|
||||
|
||||
export function getRecommendation(id: string): Promise<Recommendation> {
|
||||
return request(`/recommendations/${id}`);
|
||||
}
|
||||
|
||||
export function rerankRecommendation(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/recommendations/${id}/rerank`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function submitFeedback(body: {
|
||||
tv_show_name: string;
|
||||
stars: number;
|
||||
feedback?: string;
|
||||
}): Promise<{ ok: boolean }> {
|
||||
return request('/feedback', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
export function getFeedback(): Promise<FeedbackEntry[]> {
|
||||
return request('/feedback');
|
||||
}
|
||||
1
packages/frontend/src/app.css
Normal file
1
packages/frontend/src/app.css
Normal file
@@ -0,0 +1 @@
|
||||
/* App-level styles are in index.css */
|
||||
5
packages/frontend/src/app.tsx
Normal file
5
packages/frontend/src/app.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Home } from './pages/Home.js';
|
||||
|
||||
export function App() {
|
||||
return <Home />;
|
||||
}
|
||||
BIN
packages/frontend/src/assets/hero.png
Normal file
BIN
packages/frontend/src/assets/hero.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
1
packages/frontend/src/assets/preact.svg
Normal file
1
packages/frontend/src/assets/preact.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="27.68" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 296"><path fill="#673AB8" d="m128 0l128 73.9v147.8l-128 73.9L0 221.7V73.9z"></path><path fill="#FFF" d="M34.865 220.478c17.016 21.78 71.095 5.185 122.15-34.704c51.055-39.888 80.24-88.345 63.224-110.126c-17.017-21.78-71.095-5.184-122.15 34.704c-51.055 39.89-80.24 88.346-63.224 110.126Zm7.27-5.68c-5.644-7.222-3.178-21.402 7.573-39.253c11.322-18.797 30.541-39.548 54.06-57.923c23.52-18.375 48.303-32.004 69.281-38.442c19.922-6.113 34.277-5.075 39.92 2.148c5.644 7.223 3.178 21.403-7.573 39.254c-11.322 18.797-30.541 39.547-54.06 57.923c-23.52 18.375-48.304 32.004-69.281 38.441c-19.922 6.114-34.277 5.076-39.92-2.147Z"></path><path fill="#FFF" d="M220.239 220.478c17.017-21.78-12.169-70.237-63.224-110.126C105.96 70.464 51.88 53.868 34.865 75.648c-17.017 21.78 12.169 70.238 63.224 110.126c51.055 39.889 105.133 56.485 122.15 34.704Zm-7.27-5.68c-5.643 7.224-19.998 8.262-39.92 2.148c-20.978-6.437-45.761-20.066-69.28-38.441c-23.52-18.376-42.74-39.126-54.06-57.923c-10.752-17.851-13.218-32.03-7.575-39.254c5.644-7.223 19.999-8.261 39.92-2.148c20.978 6.438 45.762 20.067 69.281 38.442c23.52 18.375 42.739 39.126 54.06 57.923c10.752 17.85 13.218 32.03 7.574 39.254Z"></path><path fill="#FFF" d="M127.552 167.667c10.827 0 19.603-8.777 19.603-19.604c0-10.826-8.776-19.603-19.603-19.603c-10.827 0-19.604 8.777-19.604 19.603c0 10.827 8.777 19.604 19.604 19.604Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
1
packages/frontend/src/assets/vite.svg
Normal file
1
packages/frontend/src/assets/vite.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
115
packages/frontend/src/components/NewRecommendationModal.tsx
Normal file
115
packages/frontend/src/components/NewRecommendationModal.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
|
||||
interface NewRecommendationModalProps {
|
||||
onClose: () => void;
|
||||
onSubmit: (body: {
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
}) => Promise<void>;
|
||||
}
|
||||
|
||||
export function NewRecommendationModal({ onClose, onSubmit }: NewRecommendationModalProps) {
|
||||
const [mainPrompt, setMainPrompt] = useState('');
|
||||
const [likedShows, setLikedShows] = useState('');
|
||||
const [dislikedShows, setDislikedShows] = useState('');
|
||||
const [themes, setThemes] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: Event) => {
|
||||
e.preventDefault();
|
||||
if (!mainPrompt.trim()) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await onSubmit({
|
||||
main_prompt: mainPrompt.trim(),
|
||||
liked_shows: likedShows.trim(),
|
||||
disliked_shows: dislikedShows.trim(),
|
||||
themes: themes.trim(),
|
||||
});
|
||||
onClose();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBackdropClick = (e: MouseEvent) => {
|
||||
if ((e.target as HTMLElement).classList.contains('modal-backdrop')) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div class="modal-backdrop" onClick={handleBackdropClick}>
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h2>New Recommendation</h2>
|
||||
<button class="modal-close" onClick={onClose} aria-label="Close">×</button>
|
||||
</div>
|
||||
|
||||
<form class="modal-form" onSubmit={handleSubmit}>
|
||||
<div class="form-group">
|
||||
<label for="main-prompt">What are you looking for?</label>
|
||||
<textarea
|
||||
id="main-prompt"
|
||||
class="form-textarea"
|
||||
placeholder="Describe what you want to watch. Be as specific as you like — mood, themes, setting, what you've enjoyed before..."
|
||||
value={mainPrompt}
|
||||
onInput={(e) => setMainPrompt((e.target as HTMLTextAreaElement).value)}
|
||||
rows={5}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="liked-shows">Shows you liked</label>
|
||||
<input
|
||||
id="liked-shows"
|
||||
type="text"
|
||||
class="form-input"
|
||||
placeholder="e.g. Breaking Bad, The Wire"
|
||||
value={likedShows}
|
||||
onInput={(e) => setLikedShows((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="disliked-shows">Shows you disliked</label>
|
||||
<input
|
||||
id="disliked-shows"
|
||||
type="text"
|
||||
class="form-input"
|
||||
placeholder="e.g. Game of Thrones"
|
||||
value={dislikedShows}
|
||||
onInput={(e) => setDislikedShows((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="themes">Themes and requirements</label>
|
||||
<input
|
||||
id="themes"
|
||||
type="text"
|
||||
class="form-input"
|
||||
placeholder="e.g. dramatic setting, historical, sci-fi, etc."
|
||||
value={themes}
|
||||
onInput={(e) => setThemes((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" onClick={onClose} disabled={loading}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" class="btn-primary" disabled={loading || !mainPrompt.trim()}>
|
||||
{loading ? 'Starting…' : 'Get Recommendations'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
41
packages/frontend/src/components/PipelineProgress.tsx
Normal file
41
packages/frontend/src/components/PipelineProgress.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { StageMap, StageStatus } from '../types/index.js';
|
||||
|
||||
const STAGES: { key: keyof StageMap; label: string }[] = [
|
||||
{ key: 'interpreter', label: 'Interpreting Preferences' },
|
||||
{ key: 'retrieval', label: 'Generating Candidates' },
|
||||
{ key: 'ranking', label: 'Ranking Shows' },
|
||||
{ key: 'curator', label: 'Curating Results' },
|
||||
];
|
||||
|
||||
interface PipelineProgressProps {
|
||||
stages: StageMap;
|
||||
}
|
||||
|
||||
function StageIcon({ status }: { status: StageStatus }) {
|
||||
switch (status) {
|
||||
case 'done':
|
||||
return <span class="stage-icon stage-done">✓</span>;
|
||||
case 'error':
|
||||
return <span class="stage-icon stage-error">✗</span>;
|
||||
case 'running':
|
||||
return <span class="stage-icon stage-running spinner">⟳</span>;
|
||||
default:
|
||||
return <span class="stage-icon stage-pending">○</span>;
|
||||
}
|
||||
}
|
||||
|
||||
export function PipelineProgress({ stages }: PipelineProgressProps) {
|
||||
return (
|
||||
<div class="pipeline-progress">
|
||||
<h3 class="pipeline-title">Generating Recommendations…</h3>
|
||||
<ul class="pipeline-steps">
|
||||
{STAGES.map(({ key, label }) => (
|
||||
<li key={key} class={`pipeline-step pipeline-step--${stages[key]}`}>
|
||||
<StageIcon status={stages[key]} />
|
||||
<span class="pipeline-step-label">{label}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
85
packages/frontend/src/components/RecommendationCard.tsx
Normal file
85
packages/frontend/src/components/RecommendationCard.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import type { CuratorOutput, CuratorCategory } from '../types/index.js';
|
||||
|
||||
interface RecommendationCardProps {
|
||||
show: CuratorOutput;
|
||||
existingFeedback?: { stars: number; feedback: string };
|
||||
onFeedback: (tv_show_name: string, stars: number, feedback: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const CATEGORY_COLORS: Record<CuratorCategory, string> = {
|
||||
'Definitely Like': 'badge-green',
|
||||
'Might Like': 'badge-blue',
|
||||
'Questionable': 'badge-yellow',
|
||||
'Will Not Like': 'badge-red',
|
||||
};
|
||||
|
||||
export function RecommendationCard({ show, existingFeedback, onFeedback }: RecommendationCardProps) {
|
||||
const [selectedStars, setSelectedStars] = useState(existingFeedback?.stars ?? 0);
|
||||
const [comment, setComment] = useState(existingFeedback?.feedback ?? '');
|
||||
const [showComment, setShowComment] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(!!existingFeedback);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleStarClick = (stars: number) => {
|
||||
setSelectedStars(stars);
|
||||
setShowComment(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedStars) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await onFeedback(show.title, selectedStars, comment);
|
||||
setSubmitted(true);
|
||||
setShowComment(false);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<span class={`badge ${CATEGORY_COLORS[show.category]}`}>{show.category}</span>
|
||||
<h3 class="card-title">{show.title}</h3>
|
||||
</div>
|
||||
<p class="card-explanation">{show.explanation}</p>
|
||||
|
||||
<div class="card-feedback">
|
||||
<div class="star-rating">
|
||||
{[1, 2, 3].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
class={`star-btn${selectedStars >= star ? ' star-active' : ''}`}
|
||||
onClick={() => handleStarClick(star)}
|
||||
aria-label={`Rate ${star} star${star > 1 ? 's' : ''}`}
|
||||
>
|
||||
{selectedStars >= star ? '★' : '☆'}
|
||||
</button>
|
||||
))}
|
||||
{submitted && <span class="feedback-saved">Saved</span>}
|
||||
</div>
|
||||
|
||||
{showComment && !submitted && (
|
||||
<div class="comment-area">
|
||||
<textarea
|
||||
class="form-textarea comment-input"
|
||||
placeholder="Optional comment…"
|
||||
value={comment}
|
||||
onInput={(e) => setComment((e.target as HTMLTextAreaElement).value)}
|
||||
rows={2}
|
||||
/>
|
||||
<button
|
||||
class="btn-primary btn-sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={saving || !selectedStars}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save Feedback'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
60
packages/frontend/src/components/Sidebar.tsx
Normal file
60
packages/frontend/src/components/Sidebar.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import type { RecommendationSummary } from '../types/index.js';
|
||||
|
||||
interface SidebarProps {
|
||||
list: RecommendationSummary[];
|
||||
selectedId: string | null;
|
||||
onSelect: (id: string) => void;
|
||||
onNewClick: () => void;
|
||||
}
|
||||
|
||||
function statusIcon(status: RecommendationSummary['status']): string {
|
||||
switch (status) {
|
||||
case 'done': return '✓';
|
||||
case 'error': return '✗';
|
||||
case 'running': return '⟳';
|
||||
default: return '…';
|
||||
}
|
||||
}
|
||||
|
||||
function statusClass(status: RecommendationSummary['status']): string {
|
||||
switch (status) {
|
||||
case 'done': return 'status-done';
|
||||
case 'error': return 'status-error';
|
||||
case 'running': return 'status-running';
|
||||
default: return 'status-pending';
|
||||
}
|
||||
}
|
||||
|
||||
export function Sidebar({ list, selectedId, onSelect, onNewClick }: SidebarProps) {
|
||||
return (
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<span class="sidebar-title">Recommender</span>
|
||||
</div>
|
||||
|
||||
<button class="btn-new" onClick={onNewClick}>
|
||||
+ New Recommendation
|
||||
</button>
|
||||
|
||||
<div class="sidebar-section-label">History</div>
|
||||
|
||||
<ul class="sidebar-list">
|
||||
{list.length === 0 && (
|
||||
<li class="sidebar-empty">No recommendations yet</li>
|
||||
)}
|
||||
{list.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
class={`sidebar-item${selectedId === item.id ? ' selected' : ''}`}
|
||||
onClick={() => onSelect(item.id)}
|
||||
>
|
||||
<span class={`sidebar-icon ${statusClass(item.status)}`}>
|
||||
{statusIcon(item.status)}
|
||||
</span>
|
||||
<span class="sidebar-item-title">{item.title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
83
packages/frontend/src/hooks/useRecommendations.ts
Normal file
83
packages/frontend/src/hooks/useRecommendations.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { useState, useEffect, useCallback } from 'preact/hooks';
|
||||
import type { RecommendationSummary, FeedbackEntry } from '../types/index.js';
|
||||
import {
|
||||
listRecommendations,
|
||||
createRecommendation,
|
||||
rerankRecommendation,
|
||||
submitFeedback,
|
||||
getFeedback,
|
||||
} from '../api/client.js';
|
||||
|
||||
export function useRecommendations() {
|
||||
const [list, setList] = useState<RecommendationSummary[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState<FeedbackEntry[]>([]);
|
||||
|
||||
const refreshList = useCallback(async () => {
|
||||
const rows = await listRecommendations();
|
||||
setList(rows);
|
||||
}, []);
|
||||
|
||||
const refreshFeedback = useCallback(async () => {
|
||||
const rows = await getFeedback();
|
||||
setFeedback(rows);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshList();
|
||||
void refreshFeedback();
|
||||
}, [refreshList, refreshFeedback]);
|
||||
|
||||
const createNew = useCallback(
|
||||
async (body: {
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
}) => {
|
||||
const { id } = await createRecommendation(body);
|
||||
await refreshList();
|
||||
setSelectedId(id);
|
||||
return id;
|
||||
},
|
||||
[refreshList],
|
||||
);
|
||||
|
||||
const rerank = useCallback(
|
||||
async (id: string) => {
|
||||
await rerankRecommendation(id);
|
||||
// Update local list to show pending status
|
||||
setList((prev) =>
|
||||
prev.map((r) => (r.id === id ? { ...r, status: 'pending' as const } : r)),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleSubmitFeedback = useCallback(
|
||||
async (body: { tv_show_name: string; stars: number; feedback?: string }) => {
|
||||
await submitFeedback(body);
|
||||
await refreshFeedback();
|
||||
},
|
||||
[refreshFeedback],
|
||||
);
|
||||
|
||||
const updateStatus = useCallback(
|
||||
(id: string, status: RecommendationSummary['status']) => {
|
||||
setList((prev) => prev.map((r) => (r.id === id ? { ...r, status } : r)));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
list,
|
||||
selectedId,
|
||||
feedback,
|
||||
setSelectedId,
|
||||
createNew,
|
||||
rerank,
|
||||
submitFeedback: handleSubmitFeedback,
|
||||
updateStatus,
|
||||
refreshList,
|
||||
};
|
||||
}
|
||||
49
packages/frontend/src/hooks/useSSE.ts
Normal file
49
packages/frontend/src/hooks/useSSE.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useRef } from 'preact/hooks';
|
||||
import type { SSEEvent } from '../types/index.js';
|
||||
|
||||
export function useSSE(
|
||||
url: string | null,
|
||||
onEvent: (event: SSEEvent) => void,
|
||||
): { close: () => void } {
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
const onEventRef = useRef(onEvent);
|
||||
onEventRef.current = onEvent;
|
||||
|
||||
useEffect(() => {
|
||||
if (!url) return;
|
||||
|
||||
const es = new EventSource(url);
|
||||
esRef.current = es;
|
||||
|
||||
es.onmessage = (e: MessageEvent) => {
|
||||
try {
|
||||
const event = JSON.parse(e.data as string) as SSEEvent;
|
||||
onEventRef.current(event);
|
||||
|
||||
if (event.stage === 'complete' || event.status === 'error') {
|
||||
es.close();
|
||||
esRef.current = null;
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
es.close();
|
||||
esRef.current = null;
|
||||
};
|
||||
|
||||
return () => {
|
||||
es.close();
|
||||
esRef.current = null;
|
||||
};
|
||||
}, [url]);
|
||||
|
||||
return {
|
||||
close: () => {
|
||||
esRef.current?.close();
|
||||
esRef.current = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
558
packages/frontend/src/index.css
Normal file
558
packages/frontend/src/index.css
Normal file
@@ -0,0 +1,558 @@
|
||||
*, *::before, *::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:root {
|
||||
--bg: #0f1117;
|
||||
--bg-surface: #1a1d27;
|
||||
--bg-surface-2: #222535;
|
||||
--bg-surface-3: #2a2e42;
|
||||
--border: #2e3248;
|
||||
--text: #e2e4ed;
|
||||
--text-muted: #8a8fa8;
|
||||
--text-dim: #5a5f77;
|
||||
--accent: #6366f1;
|
||||
--accent-hover: #4f52d9;
|
||||
--accent-dim: rgba(99, 102, 241, 0.15);
|
||||
--green: #22c55e;
|
||||
--blue: #3b82f6;
|
||||
--yellow: #eab308;
|
||||
--red: #ef4444;
|
||||
--radius: 8px;
|
||||
--radius-sm: 4px;
|
||||
--sidebar-width: 260px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 14px;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
html, body, #app {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Layout ────────────────────────────────────────────── */
|
||||
|
||||
.layout {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
/* ── Sidebar ────────────────────────────────────────────── */
|
||||
|
||||
.sidebar {
|
||||
width: var(--sidebar-width);
|
||||
background: var(--bg-surface);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 20px 16px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.btn-new {
|
||||
margin: 12px;
|
||||
padding: 10px 14px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.btn-new:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.sidebar-section-label {
|
||||
padding: 8px 16px 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.sidebar-list {
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
padding: 4px 8px 8px;
|
||||
}
|
||||
|
||||
.sidebar-empty {
|
||||
padding: 8px;
|
||||
color: var(--text-dim);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
transition: background 0.1s, color 0.1s;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.sidebar-item:hover {
|
||||
background: var(--bg-surface-2);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.sidebar-item.selected {
|
||||
background: var(--accent-dim);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.sidebar-icon {
|
||||
font-size: 12px;
|
||||
width: 16px;
|
||||
text-align: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-done { color: var(--green); }
|
||||
.status-error { color: var(--red); }
|
||||
.status-running { color: var(--accent); }
|
||||
.status-pending { color: var(--text-dim); }
|
||||
|
||||
.sidebar-item-title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ── Main content areas ─────────────────────────────────── */
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
gap: 12px;
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-state h2 {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.content-area {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.rec-title {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.error-state {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.error-state h2 {
|
||||
color: var(--red);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.error-state p {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* ── Pipeline Progress ──────────────────────────────────── */
|
||||
|
||||
.pipeline-progress {
|
||||
padding: 40px 0;
|
||||
}
|
||||
|
||||
.pipeline-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.pipeline-steps {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.pipeline-step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.pipeline-step--running {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-dim);
|
||||
}
|
||||
|
||||
.pipeline-step--done {
|
||||
border-color: rgba(34, 197, 94, 0.3);
|
||||
background: rgba(34, 197, 94, 0.05);
|
||||
}
|
||||
|
||||
.pipeline-step--error {
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
background: rgba(239, 68, 68, 0.05);
|
||||
}
|
||||
|
||||
.stage-icon {
|
||||
font-size: 16px;
|
||||
width: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stage-done { color: var(--green); }
|
||||
.stage-error { color: var(--red); }
|
||||
.stage-running { color: var(--accent); }
|
||||
.stage-pending { color: var(--text-dim); }
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.pipeline-step-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ── Cards ─────────────────────────────────────────────── */
|
||||
|
||||
.cards-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
border-color: var(--bg-surface-3);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
padding: 2px 8px;
|
||||
border-radius: 100px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.badge-green { background: rgba(34,197,94,0.15); color: #4ade80; }
|
||||
.badge-blue { background: rgba(59,130,246,0.15); color: #60a5fa; }
|
||||
.badge-yellow{ background: rgba(234,179,8,0.15); color: #facc15; }
|
||||
.badge-red { background: rgba(239,68,68,0.15); color: #f87171; }
|
||||
|
||||
.card-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.card-explanation {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.5;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.card-feedback {
|
||||
border-top: 1px solid var(--border);
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
.star-rating {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.star-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
color: var(--text-dim);
|
||||
padding: 0 2px;
|
||||
transition: color 0.1s, transform 0.1s;
|
||||
}
|
||||
|
||||
.star-btn:hover,
|
||||
.star-btn.star-active {
|
||||
color: var(--yellow);
|
||||
}
|
||||
|
||||
.star-btn:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.feedback-saved {
|
||||
margin-left: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--green);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.comment-area {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.comment-input {
|
||||
font-size: 13px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
/* ── Rerank Button ──────────────────────────────────────── */
|
||||
|
||||
.rerank-section {
|
||||
padding: 16px 0 32px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.btn-rerank {
|
||||
padding: 12px 28px;
|
||||
background: var(--bg-surface-2);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.btn-rerank:hover:not(:disabled) {
|
||||
background: var(--bg-surface-3);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.btn-rerank:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ── Buttons ────────────────────────────────────────────── */
|
||||
|
||||
.btn-primary {
|
||||
padding: 10px 20px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary.btn-sm {
|
||||
padding: 6px 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
padding: 10px 20px;
|
||||
background: var(--bg-surface-2);
|
||||
color: var(--text-muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: var(--bg-surface-3);
|
||||
}
|
||||
|
||||
/* ── Modal ──────────────────────────────────────────────── */
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
width: 540px;
|
||||
max-width: 96vw;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px 20px 0;
|
||||
}
|
||||
|
||||
.modal-header h2 {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modal-close {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 22px;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.modal-close:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.modal-form {
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.form-input,
|
||||
.form-textarea {
|
||||
background: var(--bg-surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text);
|
||||
font-size: 14px;
|
||||
padding: 10px 12px;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
font-family: inherit;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.form-input:focus,
|
||||
.form-textarea:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.form-textarea {
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
5
packages/frontend/src/main.tsx
Normal file
5
packages/frontend/src/main.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { render } from 'preact'
|
||||
import './index.css'
|
||||
import { App } from './app.tsx'
|
||||
|
||||
render(<App />, document.getElementById('app')!)
|
||||
192
packages/frontend/src/pages/Home.tsx
Normal file
192
packages/frontend/src/pages/Home.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
import { useState, useCallback, useEffect } from 'preact/hooks';
|
||||
import { Sidebar } from '../components/Sidebar.js';
|
||||
import { NewRecommendationModal } from '../components/NewRecommendationModal.js';
|
||||
import { PipelineProgress } from '../components/PipelineProgress.js';
|
||||
import { RecommendationCard } from '../components/RecommendationCard.js';
|
||||
import { useRecommendations } from '../hooks/useRecommendations.js';
|
||||
import { useSSE } from '../hooks/useSSE.js';
|
||||
import { getRecommendation } from '../api/client.js';
|
||||
import type { Recommendation, SSEEvent, StageMap, PipelineStage } from '../types/index.js';
|
||||
|
||||
const DEFAULT_STAGES: StageMap = {
|
||||
interpreter: 'pending',
|
||||
retrieval: 'pending',
|
||||
ranking: 'pending',
|
||||
curator: 'pending',
|
||||
};
|
||||
|
||||
const STAGE_ORDER: (keyof StageMap)[] = ['interpreter', 'retrieval', 'ranking', 'curator'];
|
||||
|
||||
export function Home() {
|
||||
const {
|
||||
list,
|
||||
selectedId,
|
||||
feedback,
|
||||
setSelectedId,
|
||||
createNew,
|
||||
rerank,
|
||||
submitFeedback,
|
||||
updateStatus,
|
||||
refreshList,
|
||||
} = useRecommendations();
|
||||
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [selectedRec, setSelectedRec] = useState<Recommendation | null>(null);
|
||||
const [stages, setStages] = useState<StageMap>(DEFAULT_STAGES);
|
||||
const [sseUrl, setSseUrl] = useState<string | null>(null);
|
||||
|
||||
// Load full recommendation when selected
|
||||
useEffect(() => {
|
||||
if (!selectedId) {
|
||||
setSelectedRec(null);
|
||||
return;
|
||||
}
|
||||
void getRecommendation(selectedId).then((rec) => {
|
||||
setSelectedRec(rec);
|
||||
// If already running or pending, open SSE
|
||||
if (rec.status === 'running' || rec.status === 'pending') {
|
||||
setStages(DEFAULT_STAGES);
|
||||
setSseUrl(`/api/recommendations/${selectedId}/stream`);
|
||||
}
|
||||
});
|
||||
}, [selectedId]);
|
||||
|
||||
const handleSSEEvent = useCallback(
|
||||
(event: SSEEvent) => {
|
||||
if (!selectedId) return;
|
||||
|
||||
if (event.stage !== 'complete') {
|
||||
const stageKey = event.stage as keyof StageMap;
|
||||
if (STAGE_ORDER.includes(stageKey)) {
|
||||
setStages((prev) => ({
|
||||
...prev,
|
||||
[stageKey]: event.status === 'start' ? 'running' : event.status === 'done' ? 'done' : 'error',
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (event.stage === 'complete' && event.status === 'done') {
|
||||
setSseUrl(null);
|
||||
updateStatus(selectedId, 'done');
|
||||
// Reload full recommendation to get results
|
||||
void getRecommendation(selectedId).then(setSelectedRec);
|
||||
void refreshList();
|
||||
}
|
||||
|
||||
if (event.status === 'error') {
|
||||
setSseUrl(null);
|
||||
updateStatus(selectedId, 'error');
|
||||
const stageKey = event.stage as PipelineStage;
|
||||
if (stageKey !== 'complete') {
|
||||
setStages((prev) => ({ ...prev, [stageKey as keyof StageMap]: 'error' }));
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectedId, updateStatus, refreshList],
|
||||
);
|
||||
|
||||
useSSE(sseUrl, handleSSEEvent);
|
||||
|
||||
const handleSelect = (id: string) => {
|
||||
setSseUrl(null);
|
||||
setStages(DEFAULT_STAGES);
|
||||
setSelectedId(id);
|
||||
};
|
||||
|
||||
const handleCreateNew = async (body: {
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
}) => {
|
||||
const id = await createNew(body);
|
||||
setStages(DEFAULT_STAGES);
|
||||
setSseUrl(`/api/recommendations/${id}/stream`);
|
||||
};
|
||||
|
||||
const handleRerank = async () => {
|
||||
if (!selectedId) return;
|
||||
await rerank(selectedId);
|
||||
setStages(DEFAULT_STAGES);
|
||||
setSseUrl(`/api/recommendations/${selectedId}/stream`);
|
||||
setSelectedRec((prev) => (prev ? { ...prev, status: 'pending' } : null));
|
||||
};
|
||||
|
||||
const isRunning =
|
||||
selectedRec?.status === 'running' || selectedRec?.status === 'pending' || !!sseUrl;
|
||||
|
||||
const feedbackMap = new Map(feedback.map((f) => [f.tv_show_name, f]));
|
||||
|
||||
return (
|
||||
<div class="layout">
|
||||
<Sidebar
|
||||
list={list}
|
||||
selectedId={selectedId}
|
||||
onSelect={handleSelect}
|
||||
onNewClick={() => setShowModal(true)}
|
||||
/>
|
||||
|
||||
<main class="main-content">
|
||||
{!selectedId && (
|
||||
<div class="empty-state">
|
||||
<h2>TV Show Recommender</h2>
|
||||
<p>Click <strong>+ New Recommendation</strong> to get started.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedId && isRunning && (
|
||||
<div class="content-area">
|
||||
<PipelineProgress stages={stages} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedId && !isRunning && selectedRec?.status === 'done' && selectedRec.recommendations && (
|
||||
<div class="content-area">
|
||||
<h2 class="rec-title">{selectedRec.title}</h2>
|
||||
|
||||
<div class="cards-grid">
|
||||
{selectedRec.recommendations.map((show) => (
|
||||
<RecommendationCard
|
||||
key={show.title}
|
||||
show={show}
|
||||
existingFeedback={feedbackMap.get(show.title)}
|
||||
onFeedback={async (name, stars, comment) => {
|
||||
await submitFeedback({ tv_show_name: name, stars, feedback: comment });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div class="rerank-section">
|
||||
<button
|
||||
class="btn-rerank"
|
||||
onClick={handleRerank}
|
||||
disabled={feedback.length === 0}
|
||||
title={feedback.length === 0 ? 'Rate at least one show to enable re-ranking' : 'Re-rank based on your feedback'}
|
||||
>
|
||||
Re-rank with Feedback {feedback.length > 0 ? `(${feedback.length} rated)` : ''}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedId && !isRunning && selectedRec?.status === 'error' && (
|
||||
<div class="content-area error-state">
|
||||
<h2>Something went wrong</h2>
|
||||
<p>The pipeline encountered an error. You can try again by clicking Re-rank.</p>
|
||||
<button class="btn-primary" onClick={handleRerank}>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{showModal && (
|
||||
<NewRecommendationModal
|
||||
onClose={() => setShowModal(false)}
|
||||
onSubmit={handleCreateNew}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
packages/frontend/src/types/index.ts
Normal file
49
packages/frontend/src/types/index.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export type CuratorCategory = 'Definitely Like' | 'Might Like' | 'Questionable' | 'Will Not Like';
|
||||
|
||||
export interface CuratorOutput {
|
||||
title: string;
|
||||
explanation: string;
|
||||
category: CuratorCategory;
|
||||
}
|
||||
|
||||
export type RecommendationStatus = 'pending' | 'running' | 'done' | 'error';
|
||||
|
||||
export interface Recommendation {
|
||||
id: string;
|
||||
title: string;
|
||||
main_prompt: string;
|
||||
liked_shows: string;
|
||||
disliked_shows: string;
|
||||
themes: string;
|
||||
recommendations: CuratorOutput[] | null;
|
||||
status: RecommendationStatus;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface RecommendationSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
status: RecommendationStatus;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface FeedbackEntry {
|
||||
id: string;
|
||||
tv_show_name: string;
|
||||
stars: number;
|
||||
feedback: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export type PipelineStage = 'interpreter' | 'retrieval' | 'ranking' | 'curator' | 'complete';
|
||||
export type SSEStatus = 'start' | 'done' | 'error';
|
||||
|
||||
export interface SSEEvent {
|
||||
stage: PipelineStage;
|
||||
status: SSEStatus;
|
||||
data?: unknown;
|
||||
}
|
||||
|
||||
export type StageStatus = 'pending' | 'running' | 'done' | 'error';
|
||||
|
||||
export type StageMap = Record<Exclude<PipelineStage, 'complete'>, StageStatus>;
|
||||
33
packages/frontend/tsconfig.app.json
Normal file
33
packages/frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/preact/compat/"],
|
||||
"react-dom": ["./node_modules/preact/compat/"]
|
||||
},
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
packages/frontend/tsconfig.json
Normal file
7
packages/frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
packages/frontend/tsconfig.node.json
Normal file
26
packages/frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
16
packages/frontend/vite.config.ts
Normal file
16
packages/frontend/vite.config.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import preact from '@preact/preset-vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [preact()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
rewrite: (path) => path.replace(/^\/api/, ''),
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user