diff --git a/.env.example b/.env.example deleted file mode 100644 index cc0e24f8..00000000 --- a/.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# Slack Incoming Webhook URL — powers the footer contact form. -# Create one: https://api.slack.com/messaging/webhooks -# -# Local dev: copy this file to `.env.local` (gitignored) and fill in the URL. -# Production: add a repository secret named SLACK_WEBHOOK_URL. The Pages deploy -# workflow passes it in at build time as VITE_SLACK_WEBHOOK_URL. -# -# HEADS UP: Vite inlines VITE_* vars into the public JS bundle, so this URL is -# readable by anyone on the deployed site. If it gets abused, just regenerate -# the webhook in Slack (or switch to a serverless proxy that hides it). -VITE_SLACK_WEBHOOK_URL= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..68e86ce7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + services: + postgres: + image: pgvector/pgvector:pg16 + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: yk_test + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm run build + - name: Server integration tests + run: npm test -w @yk/server + env: + TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/yk_test diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 72bc9f2e..00000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Deploy to GitHub Pages - -on: - push: - branches: [master] - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: pages - cancel-in-progress: false - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: 20 - cache: npm - - - name: Install dependencies - run: npm ci - - - name: Build - run: npm run build - env: - VITE_SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - - - name: Setup Pages - uses: actions/configure-pages@v5 - - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - with: - path: ./docs - - deploy: - needs: build - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/CNAME b/CNAME deleted file mode 100644 index 8b137891..00000000 --- a/CNAME +++ /dev/null @@ -1 +0,0 @@ - diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 00000000..82ea2155 --- /dev/null +++ b/PLAN.md @@ -0,0 +1,93 @@ +# Ralph 리뉴얼: 설계와 진행 상황 + +> 브랜치: `claude/loving-tesla-8gvi1c` · 최종 갱신: 2026-11-15 +> 실행 방법과 배포 절차는 [README.md](./README.md)를 참고하세요. + +## 1. 컨셉 + +"스크롤해서 읽는 포트폴리오"에서 **"말을 거는 포트폴리오"**로 바꿉니다. +화면 전체가 초록색 글자에 검은 배경인 고전 터미널(DOS)이고, 위쪽의 **Ralph**(ASCII로 그린 거미형 로봇 비서)에게 +방문자가 질문하면 YK의 데이터로 답하고 관련 정보를 DOS 박스로 띄웁니다. +답할 수 없는 질문, 연락 요청, 협업 제안은 모두 **같은 Slack 웹훅**으로 YK에게 전달됩니다. + +## 2. 모노레포 구조 + +| 앱 | 역할 | 배포 | +|---|---|---| +| `apps/landing` | 원페이지 터미널: ASCII Ralph, 대화 로그, DOS 박스 | Vercel | +| `apps/admin` | 프로필, 이력, 프로젝트, 메모리, GitHub 연동, 인박스 관리 | Vercel | +| `apps/server` | Hono API: 채팅(Claude), RAG 메모리, Slack, 관리자 API | Railway (+ pgvector Postgres) | +| `packages/shared` | 세 앱이 공유하는 타입 | — | + +npm workspaces만 사용합니다(Turborepo 없음). 서버는 `tsx`로 TypeScript를 바로 실행합니다. + +## 3. Ralph 애니메이션 (v4: ASCII 거미 로봇) + +- **v1**(아이언맨 HUD), **v2**(WebGL 빛), **v3**(렌즈 스택)을 거쳐, Ralph를 **다리 6개 달린 거미 로봇**으로 ASCII 문자로 그립니다. +- 위에서 내려다본 구도라 앞다리는 위로, 가운데는 옆으로, 뒷다리는 아래로 퍼져서 다리가 서로 겹치지 않습니다. +- `hud/avatar/ralph.ts`는 (상태, 시간, 진폭) → 문자열 줄을 돌려주는 순수 함수입니다. 렌더러가 이걸 `
`에 약 15fps로 다시 찍어서 CLI 프로그램처럼 보입니다.
+- 글자 크기는 64×17 격자가 영역에 꽉 차도록 자동으로 맞춥니다.
+
+| 상태 | 동작 |
+|---|---|
+| idle | 몇 초마다 눈을 깜빡이고, 다리 하나씩 체중을 옮깁니다 |
+| listening | 눈이 커지고(`(@)`) 다리에 힘이 들어갑니다. 키를 누를 때마다 다리 하나가 톡 칩니다 |
+| thinking | 다리가 순서대로 두드리고, 머리 위에 `[... ]` 스피너가 돕니다 |
+| speaking | 좌우로 종종걸음(삼각 보행)을 칩니다. 진폭에 따라 눈 `(o)→(O)→(@)`, 입 `-..-→-==-→<==>`이 바뀌고, 등 줄무늬가 깜빡이고, 머리 옆에 `( )` 음파, 바닥에 먼지가 일어납니다 |
+| offline | 다리를 접고 주저앉습니다. 눈 `(x)`, `zZ` |
+
+- 화면 전체에 스캔라인, 비네트, 미세한 깜빡임이 들어갑니다. 폰트는 한글 픽셀 폰트 Galmuri Mono(직접 호스팅, OFL)입니다.
+- 대화는 터미널 로그로, 정보 패널은 DOS 이중선 박스로 표시합니다.
+- 번호 메뉴(`1`–`4`)와 명령어(`HELP`, `CLS`, `LANG KO|EN`, `VOICE`)를 지원하고, 부팅할 때 BIOS 스타일 문구가 나옵니다.
+- 놀이터: `/?avatar`에서 상태별 모션을 확인할 수 있습니다. 어드민 테마는 그대로이고, 이름만 Ralph입니다.
+- 코드에서는 비서를 `assistant`, 화면 속 캐릭터를 `avatar`라고 부릅니다(`useAssistant`, `Avatar`). 표시 이름 "Ralph"는 프로필 설정값입니다.
+
+**언어 규칙:** 기본은 영어입니다. 방문자가 한글로 쓰거나 한국어를 요청하면 UI 전체와 답변이 한국어로 바뀌고, 영어를 요청하면 다시 영어로 돌아옵니다. 클라이언트가 바꾼 언어를 서버에 함께 보내고, 프롬프트도 그 언어를 따릅니다.
+
+## 4. AI 동작 규칙
+
+- **모델:** Claude Haiku 5.5 (`effort: low`, 스트리밍). system prompt(페르소나, 프로필, 항목 인덱스)는 프롬프트 캐싱됩니다.
+- **사실성:** profile, entries, 검색된 context에 있는 사실만 말합니다.
+- **답할 수 없을 때:** "그 질문은 답하기 어려워요"라고 말하고 `report_unanswered`를 호출합니다. 질문은 인박스와 Slack(❓)으로 갑니다.
+- **연락 / 협업:** 이름과 연락처를 한 번 묻고 `leave_message`를 호출합니다. 인박스와 Slack(✉️ / 🤝)으로 갑니다.
+- **YK와 무관한 요청:** 정중하게 거절하며, 이 경우는 Slack으로 보내지 않습니다.
+- **학습 루프:** 관리자 인박스에서 답을 적으면 FAQ 항목이 되어 다음부터는 AI가 직접 답합니다.
+
+## 5. 메모리 (RAG)
+
+- **저장소:** Postgres + pgvector. `entries`(구조화된 이력), `memories`(자유 메모), 프로필을 청크로 나눠 `chunks`에 저장합니다.
+- **검색:** 벡터 유사도와 키워드 퍼지 검색(pg_trgm, 한국어 조사 제거)을 RRF로 합칩니다.
+- **임베딩:** 기본은 서버 안에서 돌리는 `multilingual-e5-small`입니다(무료, API 키 없음). Voyage AI로 바꿀 수 있습니다.
+- **임베딩 장애 시:** 자동으로 키워드 검색만으로 동작하고, 복구되면 빈 임베딩을 채웁니다.
+
+## 6. 남용 방지
+
+- IP당 분당 6회, 하루 60회
+- 전체 하루 3,000회
+- 메시지 전송은 IP당 하루 5회
+- 관리자 로그인은 15분에 10회
+- 관리자 인증: 비밀번호를 서명된 토큰(7일)으로 교환
+- Anthropic 콘솔에서 이 프로젝트 전용 키에 **월 사용 한도**를 설정하는 것을 권장합니다
+
+## 7. 진행 상황
+
+| 항목 | 상태 |
+|---|---|
+| 모노레포 전환, 기존 콘텐츠 시드 이관 | ✅ |
+| 서버: 스키마, 채팅 SSE, 툴 루프, Slack, 관리자 API, GitHub 가져오기 | ✅ |
+| 통합 테스트 6개 (실제 Postgres, 모의 Claude/Slack) | ✅ 통과 |
+| 랜딩: ASCII Ralph(v4), 터미널 로그, DOS 박스, 오프라인 모드, 영어 기본/한국어 자동 전환 | ✅ |
+| 어드민: 대시보드(비용 추정), 인박스, 프로필, 항목, 메모리(검색 테스트), GitHub | ✅ |
+| CI(타입체크, 빌드, 테스트), Railway/Vercel 설정 파일 | ✅ |
+| 실제 Claude API로 답변 품질 확인 | ⏳ API 키 필요 |
+| 로컬 임베딩 모델 실제 다운로드 확인 | ⏳ 배포 환경에서 확인 (개발 환경 네트워크 차단) |
+| GitHub 가져오기 실제 호출 확인 | ⏳ 배포 환경에서 확인 |
+| Railway / Vercel 배포, 도메인 결정 후 canonical / sitemap 갱신 | ⏳ |
+
+## 8. 다음 할 일
+
+1. 배포에 필요한 시크릿 준비: Anthropic API 키, Slack 웹훅, 관리자 비밀번호
+2. Railway(서버 + pgvector)와 Vercel 프로젝트 2개 생성
+3. 어드민에서 콘텐츠 보강: 프로젝트별 기간과 "어려웠던 문제 / 내린 결정", FAQ, 일하는 방식 메모
+4. 실제 대화로 답변 톤과 거절 기준 조정 (Profile → "Private notes")
+5. 도메인 결정: 현재 canonical은 `ykdhan.github.io`입니다. GitHub Pages 배포 워크플로는 제거했으므로, 기존 사이트는 마지막 배포본 그대로 유지됩니다.
diff --git a/README.md b/README.md
index a2b36595..a69e3064 100644
--- a/README.md
+++ b/README.md
@@ -1,49 +1,83 @@
-# YK — Portfolio
+# YK — Ralph
 
-Personal portfolio of **YK (Youngkwang Han)**, an AI-native fullstack developer.
-Live at **https://ykdhan.github.io**.
+Personal site of **YK (Youngkwang Han)**, rebuilt as a green-on-black terminal:
+visitors talk to **Ralph**, an AI assistant that answers from YK's own data, opens panels for
+projects and skills, and forwards anything it can't answer, plus contact and
+collaboration requests, to Slack.
 
-Dark, minimal, AI × cryptography aesthetic: fine grid, drifting aurora glows,
-and decrypt-style text scrambles.
-Fully bilingual (English default / 한국어) with a one-click toggle.
+```
+apps/
+  landing/   Vite + React · one-screen terminal with Ralph, an ASCII spider bot → Vercel
+  admin/     Vite + React · manage profile, entries, memory, GitHub, inbox → Vercel
+  server/    Node + Hono · chat (Claude), RAG memory, Slack, admin API     → Railway
+packages/
+  shared/    TypeScript types shared by all three
+```
 
-## Stack
+## How it works
 
-- **React 18 + TypeScript** (Vite) — no animation libraries, just CSS +
-  IntersectionObserver
-- Plain CSS design system with custom properties
-- Fonts: Space Grotesk (display) · JetBrains Mono (labels) · Pretendard (Korean)
+- **Chat**: `POST /api/chat` streams Server-Sent Events. Each question is matched
+  against memory (hybrid search: pgvector similarity plus fuzzy keyword search),
+  the hits are attached as context, and **Claude Haiku 5.5** answers. The system
+  prompt (persona, profile, entry index) is prompt-cached.
+- **Tools the model can call**
+  - `show_panel`: project, experience, stack, or contact panel next to the answer
+  - `report_unanswered`: when the data doesn't answer the question, Ralph says
+    so and the question goes to the inbox and Slack
+  - `leave_message`: contact or collaboration proposals, with name and contact,
+    to the inbox and Slack
+- **Memory**: entries (structured: experience, projects, skills, FAQ…), free-form
+  memories, and the profile are chunked and embedded. Embeddings run in-process
+  with `multilingual-e5-small` by default (free, Korean + English); Voyage AI is
+  optional. If embeddings are unavailable, search falls back to keywords.
+- **Closing the loop**: in the admin inbox, answering an unanswered question saves
+  it as an FAQ entry, so the assistant knows it next time.
+- **Ralph**: a six-legged spider robot drawn in ASCII and redrawn at ~15 fps like
+  a CLI program (`hud/avatar/ralph.ts` is a pure `state, time, level -> lines`
+  function). Idle: breathes, blinks, shifts a leg. Listening: eyes wide, a leg
+  taps per keystroke. Thinking: legs drum, spinner above. Speaking: scuttles side
+  to side; eyes and mouth follow the voice. Offline: legs folded, zZ. The text
+  stream becomes a speech-like amplitude envelope that drives Ralph and the
+  typing in sync. Optional browser TTS. Panels render as DOS boxes in the log.
+- **Language**: English by default. Writing in Korean (or asking for Korean)
+  switches the whole UI and the answers to Korean; asking for English switches back.
+- **Terminal**: numbered quick menu (type `1`–`4`), commands `HELP`, `CLS`,
+  `LANG KO|EN`, `VOICE`. Font: [Galmuri](https://github.com/quiple/galmuri)
+  (SIL OFL), self-hosted.
 
 ## Develop
 
+Requirements: Node 20+, Postgres 16 with `pgvector`.
+
 ```bash
 npm install
-npm run dev      # local dev server
-npm run build    # production build → ./docs
-npm run preview  # preview the production build
+cp apps/server/.env.example apps/server/.env   # fill in the values
+npm run dev:server    # http://localhost:8787  (migrates + seeds on first boot)
+npm run dev:landing   # http://localhost:5173  (/?avatar = motion playground)
+npm run dev:admin     # http://localhost:5174
 ```
 
-## Content
-
-Copy lives in [`src/i18n/strings.ts`](./src/i18n/strings.ts) and work/stack
-data in [`src/data/experience.ts`](./src/data/experience.ts), both as
-`{ en, ko }` pairs so the site stays in sync across languages.
-
-## Contact form
-
-The footer form posts to a Slack incoming webhook. Set `VITE_SLACK_WEBHOOK_URL`
-(see [`.env.example`](./.env.example)) — locally via `.env.local`, in production
-via the `SLACK_WEBHOOK_URL` repository secret used by the deploy workflow.
+```bash
+npm run typecheck
+npm run build
+TEST_DATABASE_URL=postgres://… npm test -w @yk/server   # integration tests (mocked Claude + Slack)
+```
 
-## SEO
+## Deploy
 
-- Language-aware `` / meta description, `hreflang` alternates
-  (`/` = en, `/?lang=ko` = ko), `robots.txt`, `sitemap.xml`
-- JSON-LD (`Person` + `WebSite`) structured data
-- Generated brand assets: `favicon.svg` / `favicon-32.png` /
-  `apple-touch-icon.png` and the OG thumbnail `images/og.png`
+**Server → Railway**
+1. Create a project with a **pgvector** Postgres (Railway template "pgvector").
+2. Add a service from this repo. In *Settings → Config-as-code*, point it to
+   `/apps/server/railway.json` (absolute path; it builds `apps/server/Dockerfile` from the repo root).
+3. Variables: `DATABASE_URL` (reference the Postgres service), `ANTHROPIC_API_KEY`,
+   `SLACK_WEBHOOK_URL`, `ADMIN_PASSWORD`, `SESSION_SECRET` (`openssl rand -hex 32`),
+   `CORS_ORIGINS` (the two Vercel URLs, comma separated). Optional: `GITHUB_TOKEN`,
+   `EMBEDDER`, `VOYAGE_API_KEY`.
+4. Optional: mount a volume at `/data` so the embedding model isn't re-downloaded on each deploy.
 
-## Deploy
+**Landing and admin → Vercel** (two projects, same repo)
+- Root directory `apps/landing` or `apps/admin`; framework Vite (from `vercel.json`).
+- Environment variable `VITE_API_URL` = the Railway service URL.
 
-Pushing to `master` triggers [`.github/workflows/deploy.yml`](./.github/workflows/deploy.yml),
-which runs `npm ci && npm run build` and publishes `./docs` to GitHub Pages.
+CI (`.github/workflows/ci.yml`) typechecks, builds, and runs the server tests
+against a pgvector service container on every push and PR.
diff --git a/apps/admin/.env.example b/apps/admin/.env.example
new file mode 100644
index 00000000..627f3a8d
--- /dev/null
+++ b/apps/admin/.env.example
@@ -0,0 +1,2 @@
+# Base URL of the API server (apps/server). No trailing slash.
+VITE_API_URL=http://localhost:8787
diff --git a/apps/admin/index.html b/apps/admin/index.html
new file mode 100644
index 00000000..073d6286
--- /dev/null
+++ b/apps/admin/index.html
@@ -0,0 +1,21 @@
+<!doctype html>
+<html lang="ko">
+  <head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <meta name="robots" content="noindex, nofollow" />
+    <meta name="color-scheme" content="dark" />
+    <title>Ralph Admin
+    
+    
+    
+    
+  
+  
+    
+ + + diff --git a/apps/admin/package.json b/apps/admin/package.json new file mode 100644 index 00000000..d0b06e7a --- /dev/null +++ b/apps/admin/package.json @@ -0,0 +1,24 @@ +{ + "name": "@yk/admin", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@yk/shared": "*", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@types/react": "^18.3.18", + "@types/react-dom": "^18.3.5", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.3", + "vite": "^5.4.14" + } +} diff --git a/public/favicon.svg b/apps/admin/public/favicon.svg similarity index 100% rename from public/favicon.svg rename to apps/admin/public/favicon.svg diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx new file mode 100644 index 00000000..30149744 --- /dev/null +++ b/apps/admin/src/App.tsx @@ -0,0 +1,108 @@ +import { useEffect, useState, type FormEvent } from "react"; +import { api, auth, setUnauthorizedHandler } from "./api"; +import { Toaster, toast } from "./ui"; +import Dashboard from "./pages/Dashboard"; +import Profile from "./pages/Profile"; +import Entries from "./pages/Entries"; +import Memory from "./pages/Memory"; +import Github from "./pages/Github"; +import Inbox from "./pages/Inbox"; + +const PAGES = { + dashboard: { label: "Dashboard", el: Dashboard }, + inbox: { label: "Inbox", el: Inbox }, + profile: { label: "Profile", el: Profile }, + entries: { label: "Entries", el: Entries }, + memory: { label: "Memory", el: Memory }, + github: { label: "GitHub", el: Github } +} as const; +type PageKey = keyof typeof PAGES; + +const fromHash = (): PageKey => { + const key = window.location.hash.replace(/^#\/?/, "") as PageKey; + return key in PAGES ? key : "dashboard"; +}; + +function Login({ onDone }: { onDone(): void }) { + const [password, setPassword] = useState(""); + const [busy, setBusy] = useState(false); + const submit = async (e: FormEvent) => { + e.preventDefault(); + setBusy(true); + try { + const { token } = await api<{ token: string }>("/admin/login", { method: "POST", body: { password } }); + auth.set(token); + onDone(); + } catch (err) { + toast((err as Error).message, true); + } finally { + setBusy(false); + } + }; + return ( +
+
+

Ralph Admin

+ setPassword(e.target.value)} + /> + + + ); +} + +export default function App() { + const [authed, setAuthed] = useState(!!auth.get()); + const [page, setPage] = useState(fromHash); + + useEffect(() => { + setUnauthorizedHandler(() => setAuthed(false)); + const onHash = () => setPage(fromHash()); + window.addEventListener("hashchange", onHash); + return () => window.removeEventListener("hashchange", onHash); + }, []); + + if (!authed) + return ( + <> + setAuthed(true)} /> + + + ); + + const Current = PAGES[page].el; + return ( +
+ +
+ +
+ +
+ ); +} diff --git a/apps/admin/src/api.ts b/apps/admin/src/api.ts new file mode 100644 index 00000000..f6c2ec6c --- /dev/null +++ b/apps/admin/src/api.ts @@ -0,0 +1,48 @@ +export const API_URL = (import.meta.env.VITE_API_URL ?? "http://localhost:8787").replace(/\/$/, ""); + +const KEY = "yk.admin.token"; + +export const auth = { + get: () => { + try { + return localStorage.getItem(KEY); + } catch { + return null; + } + }, + set: (token: string) => localStorage.setItem(KEY, token), + clear: () => localStorage.removeItem(KEY) +}; + +export class ApiError extends Error { + constructor(public status: number, message: string) { + super(message); + } +} + +let onUnauthorized = () => {}; +export const setUnauthorizedHandler = (fn: () => void) => (onUnauthorized = fn); + +export async function api(path: string, init: { method?: string; body?: unknown } = {}): Promise { + const res = await fetch(`${API_URL}/api${path}`, { + method: init.method ?? "GET", + headers: { + "content-type": "application/json", + ...(auth.get() ? { authorization: `Bearer ${auth.get()}` } : {}) + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body) + }); + if (res.status === 401 && path !== "/admin/login") { + auth.clear(); + onUnauthorized(); + } + const data = await res.json().catch(() => ({})); + if (!res.ok) { + const msg = + data?.issues?.map((i: { path: string[]; message: string }) => `${i.path.join(".")}: ${i.message}`).join(", ") || + data?.error || + `HTTP ${res.status}`; + throw new ApiError(res.status, msg); + } + return data as T; +} diff --git a/src/main.tsx b/apps/admin/src/main.tsx similarity index 58% rename from src/main.tsx rename to apps/admin/src/main.tsx index c9f40388..16958a20 100644 --- a/src/main.tsx +++ b/apps/admin/src/main.tsx @@ -1,13 +1,10 @@ import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; -import { LocaleProvider } from "./i18n/LocaleContext"; -import "./styles/global.css"; +import "./styles.css"; ReactDOM.createRoot(document.getElementById("root")!).render( - - - + ); diff --git a/apps/admin/src/pages/Dashboard.tsx b/apps/admin/src/pages/Dashboard.tsx new file mode 100644 index 00000000..ef95ab5b --- /dev/null +++ b/apps/admin/src/pages/Dashboard.tsx @@ -0,0 +1,116 @@ +import type { AdminStats } from "@yk/shared"; +import { api } from "../api"; +import { Page, State, useAction, useLoad } from "../ui"; + +// Claude Haiku 5.5 list prices per 1M tokens (prompts up to 100K). Cache reads +// are billed at roughly a tenth of the input price. Estimates only. +const PRICE = { input: 0.1, cached: 0.01, output: 0.5 }; + +const usd = (n: number) => `$${n.toFixed(n < 1 ? 4 : 2)}`; + +export default function Dashboard() { + const { data, error, loading, reload } = useLoad(() => api("/admin/stats")); + const { busy, run } = useAction(); + + const usage = data?.usage ?? []; + const cost = (u: AdminStats["usage"][number]) => + ((u.inputTokens * PRICE.input + u.cachedTokens * PRICE.cached + u.outputTokens * PRICE.output) / 1e6); + const total = usage.reduce((s, u) => s + cost(u), 0); + + return ( + + + + + } + > + + {data && ( + <> +
+ + New in inbox + {data.inboxNew} + + + Entries + {data.entries} + + + Memories + {data.memories} + +
+ Indexed chunks + + {data.embeddedChunks}/{data.chunks} + + embedded · {data.embedder} +
+
+ AI cost · 30 days (est.) + {usd(total)} + {usage.reduce((s, u) => s + u.requests, 0)} questions +
+
+ +

Daily usage

+ {usage.length === 0 ? ( +

No conversations yet.

+ ) : ( + + + + + + + + + + + + + {[...usage].reverse().map((u) => ( + + + + + + + + + ))} + +
DayQuestionsInputCachedOutputEst. cost
{u.day}{u.requests}{u.inputTokens.toLocaleString()}{u.cachedTokens.toLocaleString()}{u.outputTokens.toLocaleString()}{usd(cost(u))}
+ )} + + )} +
+ ); +} diff --git a/apps/admin/src/pages/Entries.tsx b/apps/admin/src/pages/Entries.tsx new file mode 100644 index 00000000..75df7173 --- /dev/null +++ b/apps/admin/src/pages/Entries.tsx @@ -0,0 +1,212 @@ +import { useMemo, useState } from "react"; +import type { Entry, EntryKind } from "@yk/shared"; +import { ENTRY_KINDS } from "@yk/shared"; +import { api } from "../api"; +import { Field, Page, State, formatLinks, parseLinks, splitList, useAction, useLoad } from "../ui"; + +type Draft = { + id?: string; + kind: EntryKind; + slug: string; + title: string; + subtitle: string; + period: string; + body: string; + tags: string; + links: string; + visible: boolean; + sort: number; +}; + +const blank = (kind: EntryKind): Draft => ({ + kind, + slug: "", + title: "", + subtitle: "", + period: "", + body: "", + tags: "", + links: "", + visible: true, + sort: 0 +}); + +const toDraft = (e: Entry): Draft => ({ + id: e.id, + kind: e.kind, + slug: e.slug, + title: e.title, + subtitle: e.subtitle, + period: e.period, + body: e.body, + tags: e.tags.join(", "), + links: formatLinks(e.links), + visible: e.visible, + sort: e.sort +}); + +const KIND_HINT: Record = { + experience: "Companies and roles", + project: "Things you built: shown as panels", + skill: "Groups of tools for the stack panel (tags = items)", + education: "Schools, courses, certificates", + award: "Recognition", + faq: "Your own answers to questions visitors ask" +}; + +export default function Entries() { + const { data, setData, error, loading } = useLoad(() => api("/admin/entries")); + const [kind, setKind] = useState("project"); + const [draft, setDraft] = useState(null); + const { busy, run } = useAction(); + + const list = useMemo(() => (data ?? []).filter((e) => e.kind === kind), [data, kind]); + const counts = useMemo( + () => Object.fromEntries(ENTRY_KINDS.map((k) => [k, (data ?? []).filter((e) => e.kind === k).length])), + [data] + ); + + const save = () => + draft && + run(async () => { + const body = { + kind: draft.kind, + slug: draft.slug, + title: draft.title, + subtitle: draft.subtitle, + period: draft.period, + body: draft.body, + tags: splitList(draft.tags), + links: parseLinks(draft.links), + visible: draft.visible, + sort: Number(draft.sort) || 0 + }; + const saved = draft.id + ? await api(`/admin/entries/${draft.id}`, { method: "PUT", body }) + : await api("/admin/entries", { method: "POST", body }); + setData((cur) => { + const rest = (cur ?? []).filter((e) => e.id !== saved.id); + return [...rest, saved].sort((a, b) => a.sort - b.sort); + }); + setKind(saved.kind); + setDraft(toDraft(saved)); + }, "Saved and indexed"); + + const remove = () => + draft?.id && + confirm(`Delete "${draft.title}"?`) && + run(async () => { + await api(`/admin/entries/${draft.id}`, { method: "DELETE" }); + setData((cur) => (cur ?? []).filter((e) => e.id !== draft.id)); + setDraft(null); + }, "Deleted"); + + const d = draft; + const set = (k: K, v: Draft[K]) => d && setDraft({ ...d, [k]: v }); + + return ( + setDraft(blank(kind))}> + New {kind} + + } + > +
+ {ENTRY_KINDS.map((k) => ( + + ))} +
+

{KIND_HINT[kind]}

+ + +
+
    + {list.map((e) => ( +
  • + +
  • + ))} + {list.length === 0 && !loading &&
  • Nothing here yet.
  • } +
+ + {d && ( +
+
+ + + + + set("slug", e.target.value)} /> + +
+ + set("title", e.target.value)} /> + + {d.kind !== "faq" && ( +
+ + set("subtitle", e.target.value)} /> + + + set("period", e.target.value)} /> + +
+ )} + +