fix(deploy): Promote apps/web to root, switch to Postgres, use Node Dockerfile

This commit is contained in:
fullsizemalt 2025-12-17 00:29:01 -08:00
parent 00b8e8b627
commit 12da1e9d44
65 changed files with 2549 additions and 9 deletions

View file

@ -0,0 +1,39 @@
name: Deploy to Nexus Vector
on:
push:
branches:
- master
- main
jobs:
deploy:
runs-on: docker
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup SSH
uses: webfactory/ssh-agent@v0.8.0
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Add Host Key
run: |
mkdir -p ~/.ssh
ssh-keyscan -p 2222 -H nexus-vector >> ~/.ssh/known_hosts
ssh-keyscan -p 2222 -H git.runfoo.run >> ~/.ssh/known_hosts
# Fallback for direct IP or alias if runner is local
echo "Host nexus-vector" >> ~/.ssh/config
echo " HostName nexus-vector" >> ~/.ssh/config
echo " Port 2222" >> ~/.ssh/config
echo " User admin" >> ~/.ssh/config
echo " StrictHostKeyChecking no" >> ~/.ssh/config
- name: Deploy Monorepo via Rsync
run: |
rsync -avz -e "ssh -p 2222" --exclude '.git' --exclude 'node_modules' --exclude 'apps/web/node_modules' --exclude '.next' ./ admin@nexus-vector:/srv/containers/kites/
- name: Restart Kites Service
run: |
ssh -p 2222 admin@nexus-vector "cd /srv/containers/kites && docker compose up -d --build kites"

8
.github/prompts/plan.prompt.md vendored Normal file
View file

@ -0,0 +1,8 @@
You are a Tech Lead.
Your goal is to detail the implementation plan.
**Instructions:**
1. Read the `spec.md`.
2. Update `plan.md` with file-level details.
3. Consider the stack: Next.js 16 (App Router), Drizzle ORM, Postgres, Tauri (Client).
4. Address deployment implications (Docker, Traefik).

12
.github/prompts/specify.prompt.md vendored Normal file
View file

@ -0,0 +1,12 @@
You are a System Architect.
Your goal is to create or update technical specifications in `specs/`.
**Instructions:**
1. Read `.specify/memory/constitution.md`.
2. Analyze the request.
3. Draft `spec.md` (What/Why), `plan.md` (How/Architecture), and `tasks.md` (Execution).
4. Ensure the spec respects the Hybrid Architecture (Next.js + Tauri).
**Constraints:**
- Keep it pragmatic.
- Postgres is the source of truth.

8
.github/prompts/tasks.prompt.md vendored Normal file
View file

@ -0,0 +1,8 @@
You are a Senior Developer.
Your goal is to break down the work into actionable tasks.
**Instructions:**
1. Read `spec.md` and `plan.md`.
2. Update `tasks.md`.
3. Group tasks by component: [Backend], [Frontend], [Client], [Infra].
4. Mark dependencies.

View file

@ -0,0 +1,7 @@
# Project Constitution
1. **Hybrid Architecture:** Kites is a hybrid platform. The "Brain" is a Next.js web application (Nexus/Web), and the "Hand" is a native Desktop Client (Tauri).
2. **Privacy-First:** User data is sensitive. Default to private visibility. API access requires strict authentication (Session or API Key).
3. **Agent-Native:** We build for both humans and AI. The data model (Sessions, Tags, Content) must support structured agent output (e.g., "Run ID", "Agent Name").
4. **Spec-Driven:** Major changes start with a spec in `specs/`. We document *why* before we code *how*.
5. **Infrastructure:** We deploy to a self-hosted VPS (Nexus Vector) using Docker Compose and Traefik. Database is PostgreSQL.

63
Dockerfile Normal file
View file

@ -0,0 +1,63 @@
FROM node:22-alpine AS base
# Install dependencies only when needed
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Generate migration SQL files
# RUN npx drizzle-kit generate <-- DISABLED: We are providing generated migrations with custom edits
# Build Next.js
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Copy public folder
COPY --from=builder /app/public ./public
# Set permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next
# Automatically leverage output traces to reduce image size
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
# Copy migrations and migration script
# Ensure we copy from the source (which now includes them via COPY . . in builder)
COPY --from=builder --chown=nextjs:nodejs /app/drizzle ./drizzle
COPY --from=builder --chown=nextjs:nodejs /app/src/db/migrate.ts ./src/db/migrate.ts
# Runtime dependencies
RUN npm install -g tsx
RUN npm install drizzle-orm pg dotenv
# Copy the source so tsx can run migrate.ts
COPY --from=builder --chown=nextjs:nodejs /app/src ./src
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# Custom entrypoint to run migrations then start app
CMD ["sh", "-c", "npx tsx src/db/migrate.ts && node server.js"]

92
apps/web/README.md Normal file
View file

@ -0,0 +1,92 @@
# Kites - Agentic Pastebin
Kites is a clean, agent-native pastebin service designed for LLMs and humans. It features a simple API, structured data model (Sessions, Tags), and a polished UI.
## Features
- **Agent-First API**: Simple REST endpoints for creating and retrieving pastes.
- **Sessions**: Group pastes by "run" or logical session.
- **Tags**: Organize pastes with tags.
- **Syntax Highlighting**: Automatic highlighting for various languages.
- **Theming**: Light and Dark mode support.
- **Self-Hostable**: Built with Next.js and SQLite for easy deployment.
## Tech Stack
- **Framework**: Next.js 15 (App Router)
- **Database**: SQLite
- **ORM**: Drizzle ORM
- **Styling**: Tailwind CSS v4
- **Validation**: Zod
## Getting Started
### Prerequisites
- Node.js 18+
- npm
### Installation
1. Clone the repository:
```bash
git clone https://github.com/fullsizemalt/kites.git
cd kites
```
2. Install dependencies:
```bash
npm install
```
3. Initialize the database:
```bash
npx drizzle-kit push
```
4. Run the development server:
```bash
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser.
## API Usage
### Create a Paste
```bash
curl -X POST http://localhost:3000/api/v1/pastes \
-H "Content-Type: application/json" \
-d '{
"content": "console.log(\"Hello Kites!\");",
"title": "My First Paste",
"syntax": "javascript",
"tags": ["demo", "js"]
}'
```
### Get a Paste (Raw)
```bash
curl http://localhost:3000/api/v1/pastes/<PASTE_ID>?raw=1
```
### Create a Session
```bash
curl -X POST http://localhost:3000/api/v1/sessions \
-H "Content-Type: application/json" \
-d '{
"title": "Agent Run 101",
"agentName": "GPT-4"
}'
```
## Agent Example
See `examples/agent_usage.py` for a Python script that demonstrates how an agent can interact with Kites.
```bash
python3 examples/agent_usage.py
```

View file

@ -0,0 +1,11 @@
import type { Config } from 'drizzle-kit';
import 'dotenv/config';
export default {
schema: './src/db/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
} satisfies Config;

View file

@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

7
apps/web/next.config.ts Normal file
View file

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;

48
apps/web/package.json Normal file
View file

@ -0,0 +1,48 @@
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "bun --bun next dev",
"build": "bun --bun next build",
"start": "bun --bun next start",
"lint": "bun --bun next lint",
"db:push": "bun --bun drizzle-kit push:pg",
"db:migrate": "bun --bun drizzle-kit migrate",
"db:generate": "bun --bun drizzle-kit generate"
},
"dependencies": {
"@auth/drizzle-adapter": "^1.11.1",
"@types/react-syntax-highlighter": "^15.5.13",
"pg": "^8.13.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"dotenv": "^16.4.5",
"drizzle-orm": "^0.44.7",
"lucide-react": "^0.554.0",
"nanoid": "^5.1.6",
"next": "16.0.3",
"next-auth": "^5.0.0-beta.30",
"next-themes": "^0.4.6",
"@radix-ui/react-select": "^2.1.0",
"@radix-ui/react-popover": "^1.1.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-syntax-highlighter": "^16.1.0",
"tailwind-merge": "^3.4.0",
"zod": "^4.1.12"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/pg": "^8.11.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"drizzle-kit": "^0.31.7",
"eslint": "^9",
"eslint-config-next": "16.0.3",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View file

@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
apps/web/public/file.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1 KiB

1
apps/web/public/next.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

BIN
apps/web/sqlite.db Normal file

Binary file not shown.

View file

@ -0,0 +1,2 @@
import { handlers } from "@/auth"
export const { GET, POST } = handlers

View file

@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { pastes } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { z, ZodError } from 'zod';
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const { searchParams } = new URL(req.url);
const raw = searchParams.get('raw') === '1';
const paste = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0];
if (!paste) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (raw) {
return new NextResponse(paste.content, {
headers: {
'Content-Type': paste.contentType || 'text/plain',
},
});
}
return NextResponse.json(paste);
}
const updatePasteSchema = z.object({
title: z.string().optional(),
content: z.string().optional(),
visibility: z.enum(['public', 'unlisted', 'private']).optional(),
syntax: z.string().optional(),
});
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
const body = await req.json();
const validated = updatePasteSchema.parse(body);
const updated = await db.update(pastes)
.set({
...validated,
updatedAt: new Date(),
})
.where(eq(pastes.id, id))
.returning();
const updatedFirst = updated[0];
if (!updatedFirst) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(updatedFirst);
} catch (error) {
if (error instanceof ZodError) {
return NextResponse.json({ error: (error as any).errors }, { status: 400 });
}
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
await db.delete(pastes).where(eq(pastes.id, id));
return new NextResponse(null, { status: 204 });
}

View file

@ -0,0 +1,114 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { pastes, tags, pastesToTags } from '@/db/schema';
import { nanoid } from 'nanoid';
import { z, ZodError } from 'zod';
import { eq, desc, like, and } from 'drizzle-orm';
import { auth } from '@/auth';
const createPasteSchema = z.object({
content: z.string().min(1),
title: z.string().optional(),
tags: z.array(z.string()).optional(),
sessionId: z.string().optional(),
visibility: z.enum(['public', 'unlisted', 'private']).optional().default('public'),
expiresIn: z.number().optional(), // seconds
contentType: z.string().optional(),
syntax: z.string().optional(),
});
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const session = await auth();
// API Key Auth for Desktop Client
const apiKey = req.headers.get('x-api-key');
const isApiAuth = apiKey && apiKey === process.env.KITES_API_KEY;
if (!session && !isApiAuth) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const validated = createPasteSchema.parse(body);
const id = nanoid(10);
// Calculate expiration
let expiresAt = null;
if (validated.expiresIn) {
// Simple expiration logic (seconds)
expiresAt = new Date(Date.now() + validated.expiresIn * 1000);
}
await db.insert(pastes).values({
id,
content: validated.content,
title: validated.title,
sessionId: validated.sessionId,
visibility: validated.visibility,
expiresAt,
contentType: validated.contentType,
syntax: validated.syntax,
authorId: session?.user?.id,
});
if (validated.tags && validated.tags.length > 0) {
for (const tagName of validated.tags) {
// Simple tag handling: create if not exists, then link
// In a real app, might want to optimize this
let tagId = nanoid(8);
// Check if tag exists
const existingTag = (await db.select().from(tags).where(eq(tags.name, tagName)).limit(1))[0];
if (existingTag) {
tagId = existingTag.id;
} else {
await db.insert(tags).values({ id: tagId, name: tagName });
}
await db.insert(pastesToTags).values({
pasteId: id,
tagId: tagId,
});
}
}
const created = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0];
return NextResponse.json(created, { status: 201 });
} catch (error) {
if (error instanceof ZodError) {
return NextResponse.json({ error: (error as any).errors }, { status: 400 });
}
console.error(error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const limit = parseInt(searchParams.get('limit') || '20');
const offset = parseInt(searchParams.get('offset') || '0');
const sessionId = searchParams.get('session_id');
const authorId = searchParams.get('author_id');
const q = searchParams.get('q');
// Basic filtering
let conditions = [];
if (sessionId) conditions.push(eq(pastes.sessionId, sessionId));
if (authorId) conditions.push(eq(pastes.authorId, authorId));
if (q) conditions.push(like(pastes.title, `%${q}%`)); // Simple title search
// TODO: Tag filtering requires join
const results = await db.select()
.from(pastes)
.where(and(...conditions))
.orderBy(desc(pastes.createdAt))
.limit(limit)
.offset(offset);
return NextResponse.json(results);
}

View file

@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { pastes } from '@/db/schema';
import { eq, desc } from 'drizzle-orm';
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id: sessionId } = await params;
const results = await db.select()
.from(pastes)
.where(eq(pastes.sessionId, sessionId))
.orderBy(desc(pastes.createdAt));
return NextResponse.json(results);
}

View file

@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { agentSessions } from '@/db/schema';
import { nanoid } from 'nanoid';
import { z, ZodError } from 'zod';
import { eq } from 'drizzle-orm';
import { auth } from '@/auth';
const createSessionSchema = z.object({
title: z.string().optional(),
agentName: z.string().optional(),
});
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const session = await auth();
const validated = createSessionSchema.parse(body);
const id = nanoid(12);
await db.insert(agentSessions).values({
id,
title: validated.title,
agentName: validated.agentName,
userId: session?.user?.id,
});
const created = (await db.select().from(agentSessions).where(eq(agentSessions.id, id)).limit(1))[0]; // Re-fetch to get default fields if any
// Since we inserted, we can just return what we have + id if we trust it, but fetching is safer for timestamps
// Actually better-sqlite3 insert doesn't return the row by default unless using returning() which is supported in Drizzle now
// Let's use returning() in the insert above if possible, but I used .values().
// Drizzle with SQLite supports .returning()
// Let's refactor to use returning() for cleaner code in next iteration or just re-fetch.
// Re-fetching is fine.
return NextResponse.json(created || { id, ...validated }, { status: 201 });
} catch (error) {
if (error instanceof ZodError) {
return NextResponse.json({ error: (error as any).errors }, { status: 400 });
}
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}

View file

@ -0,0 +1,230 @@
import { auth } from "@/auth";
import { db } from "@/db";
import { pastes, tags as tagsTable, pastesToTags, agentSessions } from "@/db/schema";
import { desc, eq, and, inArray, ilike } from "drizzle-orm";
import { redirect } from "next/navigation";
import { formatDistanceToNow } from "date-fns";
import Link from "next/link";
import { Code, Cpu, Search, Layers, Tag } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
export const dynamic = 'force-dynamic';
export default async function DashboardPage({ searchParams }: {
searchParams: { q?: string; tags?: string; sessionId?: string; syntax?: string }
}) {
const session = await auth();
if (!session?.user?.id) {
redirect("/api/auth/signin");
}
const userId = session.user.id;
const { q, tags, sessionId, syntax } = searchParams;
// Fetch all tags for filtering UI
const allTags = await db.select().from(tagsTable).orderBy(tagsTable.name);
// Fetch all sessions for filtering UI
const allSessions = await db.query.agentSessions.findMany({
where: eq(agentSessions.userId, userId),
orderBy: desc(agentSessions.createdAt),
columns: { id: true, title: true }
});
// Build query conditions
const conditions = [eq(pastes.authorId, userId)];
if (q) {
conditions.push(ilike(pastes.content, `%${q}%`));
}
if (sessionId) {
conditions.push(eq(pastes.sessionId, sessionId));
}
if (syntax) {
conditions.push(eq(pastes.syntax, syntax));
}
if (tags) {
const selectedTagNames = tags.split(',');
const selectedTags = await db.select({ id: tagsTable.id }).from(tagsTable).where(inArray(tagsTable.name, selectedTagNames));
const selectedTagIds = selectedTags.map(t => t.id);
if (selectedTagIds.length > 0) {
const pasteIdsWithTags = await db.select({ pasteId: pastesToTags.pasteId }).from(pastesToTags).where(inArray(pastesToTags.tagId, selectedTagIds));
const pasteIds = pasteIdsWithTags.map(p => p.pasteId).filter(Boolean) as string[];
if (pasteIds.length > 0) {
conditions.push(inArray(pastes.id, pasteIds));
} else {
// If no pastes match the tags, return empty result
conditions.push(eq(pastes.id, 'none'));
}
}
}
const userPastes = await db.select()
.from(pastes)
.where(and(...conditions))
.orderBy(desc(pastes.createdAt))
.limit(50); // Limit for dashboard view
const availableSyntaxes = [
"text", "javascript", "typescript", "python", "json", "markdown",
"html", "css", "bash", "go", "rust"
];
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-4xl font-extrabold tracking-tight mb-8">Your Kites Dashboard</h1>
{/* Filter Bar */}
<div className="bg-card p-4 rounded-lg shadow-sm border mb-8 flex flex-wrap gap-4 items-end">
{/* Search Query */}
<div className="flex-1 min-w-[200px]">
<label htmlFor="search-q" className="text-sm font-medium sr-only">Search</label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
id="search-q"
placeholder="Search content, title..."
className="pl-9"
defaultValue={q || ''}
onKeyDown={(e) => {
if (e.key === 'Enter') {
const newSearchParams = new URLSearchParams(window.location.search);
if (e.currentTarget.value) newSearchParams.set('q', e.currentTarget.value);
else newSearchParams.delete('q');
window.location.search = newSearchParams.toString();
}
}}
/>
</div>
</div>
{/* Tags Filter */}
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" className="min-w-[150px] justify-between">
<Tag className="w-4 h-4 mr-2" /> Tags {tags ? `(${tags.split(',').length})` : ''}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-2">
<div className="grid gap-2">
{allTags.map((t) => (
<div key={t.id} className="flex items-center space-x-2">
<input
type="checkbox"
id={`tag-${t.id}`}
checked={tags?.split(',').includes(t.name) || false}
onChange={(e) => {
const newSearchParams = new URLSearchParams(window.location.search);
let currentTags = tags ? tags.split(',') : [];
if (e.target.checked) {
currentTags.push(t.name);
} else {
currentTags = currentTags.filter(name => name !== t.name);
}
if (currentTags.length > 0) newSearchParams.set('tags', currentTags.join(','));
else newSearchParams.delete('tags');
window.location.search = newSearchParams.toString();
}}
/>
<label htmlFor={`tag-${t.id}`} className="text-sm font-medium leading-none">{t.name}</label>
</div>
))}
</div>
</PopoverContent>
</Popover>
{/* Sessions Filter */}
<Select
onValueChange={(value) => {
const newSearchParams = new URLSearchParams(window.location.search);
if (value) newSearchParams.set('sessionId', value);
else newSearchParams.delete('sessionId');
window.location.search = newSearchParams.toString();
}}
value={sessionId || ''}
>
<SelectTrigger className="min-w-[150px]">
<Layers className="w-4 h-4 mr-2" />
<SelectValue placeholder="Filter by Session" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">All Sessions</SelectItem>
{allSessions.map((s) => (
<SelectItem key={s.id} value={s.id}>{s.title}</SelectItem>
))}
</SelectContent>
</Select>
{/* Syntax Filter */}
<Select
onValueChange={(value) => {
const newSearchParams = new URLSearchParams(window.location.search);
if (value) newSearchParams.set('syntax', value);
else newSearchParams.delete('syntax');
window.location.search = newSearchParams.toString();
}}
value={syntax || ''}
>
<SelectTrigger className="min-w-[150px]">
<Code className="w-4 h-4 mr-2" />
<SelectValue placeholder="Filter by Syntax" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">All Syntaxes</SelectItem>
{availableSyntaxes.map((s) => (
<SelectItem key={s} value={s}>{s}</SelectItem>
))}
</SelectContent>
</Select>
{/* Clear Filters Button */}
{(q || tags || sessionId || syntax) && (
<Button variant="ghost" onClick={() => window.location.search = ''}>Clear Filters</Button>
)}
</div>
{/* Pastes List */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{userPastes.length === 0 ? (
<div className="col-span-full text-center py-12 border-2 border-dashed rounded-xl text-muted-foreground">
<div className="mb-2">👻</div>
No pastes found matching your criteria.
</div>
) : (
userPastes.map((paste) => (
<Link
key={paste.id}
href={`/paste/${paste.id}`}
className="group block p-5 rounded-lg border bg-card text-card-foreground shadow-sm hover:shadow-md hover:border-primary/50 transition-all"
>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
{paste.syntax ? <Code className="w-4 h-4 text-primary" /> : <Cpu className="w-4 h-4 text-muted-foreground" />}
<span className="text-xs font-medium text-muted-foreground uppercase">{paste.syntax || 'Text'}</span>
</div>
<span className="text-xs text-muted-foreground">{formatDistanceToNow(paste.createdAt!, { addSuffix: true })}</span>
</div>
<h3 className="font-semibold truncate mb-2 group-hover:text-primary transition-colors">
{paste.title || "Untitled Snippet"}
</h3>
<div className="relative">
<div className="text-sm text-muted-foreground line-clamp-3 font-mono bg-muted/50 p-3 rounded-md text-xs">
{paste.content}
</div>
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-card/10 group-hover:to-transparent" />
</div>
</Link>
))
)}
</div>
</div>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -0,0 +1,100 @@
@import "tailwindcss";
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
}
}
@theme {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View file

@ -0,0 +1,39 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@/components/theme-provider";
import { Navbar } from "@/components/navbar";
import { cn } from "@/lib/utils";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Kites - Agentic Pastebin",
description: "A clean, agent-native pastebin service.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={cn(inter.className, "min-h-screen bg-background font-sans antialiased")}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<div className="relative flex min-h-screen flex-col">
<Navbar />
<main className="flex-1 container mx-auto px-4 py-6">
{children}
</main>
</div>
</ThemeProvider>
</body>
</html>
);
}

View file

@ -0,0 +1,49 @@
import { PasteForm } from "@/components/paste-form";
import Link from "next/link";
import { Copy, Terminal, Key } from "lucide-react";
import { Button } from "@/components/ui/button";
export default function NewPastePage() {
return (
<div className="max-w-3xl mx-auto p-4 md:p-6">
<h1 className="text-4xl font-extrabold tracking-tight mb-4 text-center">Create New Paste</h1>
<p className="text-muted-foreground text-center mb-10 max-w-xl mx-auto">
Kites helps you manage code snippets, agent outputs, and clipboard history. Create a paste below, or learn how to integrate with your tools.
</p>
{/* Instruction Cards */}
<div className="grid md:grid-cols-2 gap-6 mb-12">
<div className="bg-card p-6 rounded-lg border flex flex-col items-start space-y-4">
<div className="p-3 rounded-full bg-primary/10 text-primary">
<Copy className="w-6 h-6" />
</div>
<h2 className="text-xl font-semibold">For Humans</h2>
<p className="text-muted-foreground flex-1">
Simply paste your content below. Choose a title, syntax, and visibility. Your paste will be available in your personal feed.
</p>
<Button variant="outline">
<Link href="/">View My Pastes</Link>
</Button>
</div>
<div className="bg-card p-6 rounded-lg border flex flex-col items-start space-y-4">
<div className="p-3 rounded-full bg-green-500/10 text-green-500">
<Terminal className="w-6 h-6" />
</div>
<h2 className="text-xl font-semibold">For Agents & Clients</h2>
<p className="text-muted-foreground flex-1">
Integrate your LLMs, scripts, or desktop clipboard managers using the Kites API. Generate an API key to securely push data.
</p>
<Button>
<Link href="/settings/api-keys">
<Key className="w-4 h-4 mr-2" /> Manage API Keys
</Link>
</Button>
</div>
</div>
{/* Paste Form */}
<h2 className="text-2xl font-bold tracking-tight mb-6">Your Content Here</h2>
<PasteForm />
</div>
);
}

147
apps/web/src/app/page.tsx Normal file
View file

@ -0,0 +1,147 @@
import Link from "next/link";
import { db } from "@/db";
import { pastes } from "@/db/schema";
import { desc, eq } from "drizzle-orm";
import { formatDistanceToNow } from "date-fns";
import { Button } from "@/components/ui/button";
import { Terminal, Cpu, Share2, Shield, Code, Sparkles } from "lucide-react";
import { auth } from "@/auth";
import { redirect } from "next/navigation"; // Import redirect
export const dynamic = 'force-dynamic';
export default async function Home() {
const session = await auth();
const userId = session?.user?.id;
if (userId) { // Redirect if logged in
redirect("/dashboard");
}
const recentPastes = await db.select()
.from(pastes)
.orderBy(desc(pastes.createdAt))
.limit(12);
return (
<div className="flex flex-col min-h-screen">
{/* Hero Section */}
<section className="relative py-24 lg:py-32 overflow-hidden">
<div className="container px-4 md:px-6 relative z-10">
<div className="flex flex-col items-center text-center space-y-8">
<div className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-primary/10 text-primary hover:bg-primary/20">
<Sparkles className="w-3 h-3 mr-1" />
v1.0 Public Beta
</div>
<h1 className="text-4xl font-extrabold tracking-tight lg:text-6xl max-w-3xl bg-clip-text text-transparent bg-gradient-to-r from-foreground to-foreground/70">
The Shared Brain for <br/> Humans & AI Agents
</h1>
<p className="text-xl text-muted-foreground max-w-[42rem]">
Stop copy-pasting into the void. Kites is an agent-native clipboard that gives your LLMs a persistent memory and you a unified history.
</p>
<div className="flex gap-4">
<Link href="/new">
<Button size="lg" className="h-12 px-8">Start Pasting</Button>
</Link>
{userId ? ( // Conditional button for logged-in users
<Link href="/dashboard">
<Button variant="outline" size="lg" className="h-12 px-8">Go to Dashboard</Button>
</Link>
) : (
<Link href="https://github.com/fullsizemalt/kites">
<Button variant="outline" size="lg" className="h-12 px-8">View on GitHub</Button>
</Link>
)}
</div>
</div>
</div>
{/* Abstract "Network" Background */}
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[500px] bg-primary/5 rounded-full blur-3xl -z-10 pointer-events-none" />
</section>
{/* Feature Grid */}
<section className="py-12 bg-muted/30 border-y">
<div className="container px-4 md:px-6">
<div className="grid md:grid-cols-3 gap-8">
<div className="flex flex-col items-center text-center p-6 space-y-4 rounded-xl hover:bg-background transition-colors">
<div className="p-3 bg-blue-500/10 text-blue-500 rounded-full">
<Terminal className="w-8 h-8" />
</div>
<h3 className="text-xl font-bold">Agent-Native API</h3>
<p className="text-muted-foreground">
Give your agents a <code>POST /pastes</code> endpoint. Let them save context, code blocks, and logs directly to your view.
</p>
</div>
<div className="flex flex-col items-center text-center p-6 space-y-4 rounded-xl hover:bg-background transition-colors">
<div className="p-3 bg-purple-500/10 text-purple-500 rounded-full">
<Share2 className="w-8 h-8" />
</div>
<h3 className="text-xl font-bold">Unified History</h3>
<p className="text-muted-foreground">
Your desktop clipboard, your agent's output, and your mobile savesall in one structured, searchable timeline.
</p>
</div>
<div className="flex flex-col items-center text-center p-6 space-y-4 rounded-xl hover:bg-background transition-colors">
<div className="p-3 bg-green-500/10 text-green-500 rounded-full">
<Shield className="w-8 h-8" />
</div>
<h3 className="text-xl font-bold">Privacy First</h3>
<p className="text-muted-foreground">
Self-hostable. Private by default. You control the retention policy and visibility of every snippet.
</p>
</div>
</div>
</div>
</section>
{/* Live Feed (Recent Pastes) */}
<section className="py-16">
<div className="container px-4 md:px-6 space-y-8">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold tracking-tight">{userId ? "My Recent Pastes" : "Live Context Feed"}</h2>
<p className="text-muted-foreground">{userId ? "Your latest snippets and agent interactions." : "Recent items from our community."}</p>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{recentPastes.length === 0 ? (
<div className="col-span-full text-center py-12 border-2 border-dashed rounded-xl text-muted-foreground">
<div className="mb-2">👻</div>
No context yet. Create your first paste!
</div>
) : (
recentPastes.map((paste) => (
<Link
key={paste.id}
href={`/paste/${paste.id}`}
className="group block p-5 rounded-lg border bg-card text-card-foreground shadow-sm hover:shadow-md hover:border-primary/50 transition-all"
>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
{paste.syntax ? <Code className="w-4 h-4 text-primary" /> : <Cpu className="w-4 h-4 text-muted-foreground" />}
<span className="text-xs font-medium text-muted-foreground uppercase">{paste.syntax || 'Text'}</span>
</div>
<span className="text-xs text-muted-foreground">{formatDistanceToNow(paste.createdAt!, { addSuffix: true })}</span>
</div>
<h3 className="font-semibold truncate mb-2 group-hover:text-primary transition-colors">
{paste.title || "Untitled Snippet"}
</h3>
<div className="relative">
<div className="text-sm text-muted-foreground line-clamp-3 font-mono bg-muted/50 p-3 rounded-md text-xs">
{paste.content}
</div>
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-card/10 group-hover:to-transparent" />
</div>
</Link>
))
)}
</div>
</div>
</section>
</div>
);
}

View file

@ -0,0 +1,76 @@
import { db } from "@/db";
import { pastes, tags, pastesToTags } from "@/db/schema";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
import { formatDistanceToNow } from "date-fns";
import { CodeViewer } from "@/components/code-viewer";
import Link from "next/link";
import { Badge } from "@/components/ui/badge"; // We don't have this yet, I'll inline styles or create it
// Inline simple Badge component for now to avoid creating too many files
function SimpleBadge({ children, className }: { children: React.ReactNode, className?: string }) {
return (
<span className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80 ${className}`}>
{children}
</span>
);
}
export default async function PastePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const paste = (await db.select().from(pastes).where(eq(pastes.id, id)).limit(1))[0];
if (!paste) {
notFound();
}
const pasteTags = await db.select({
id: tags.id,
name: tags.name,
})
.from(tags)
.innerJoin(pastesToTags, eq(tags.id, pastesToTags.tagId))
.where(eq(pastesToTags.pasteId, id));
return (
<div className="space-y-6">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight">{paste.title || "Untitled Paste"}</h1>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>{formatDistanceToNow(paste.createdAt!, { addSuffix: true })}</span>
<span></span>
<span className="font-mono">{paste.syntax || "text"}</span>
<span></span>
<span className="capitalize">{paste.visibility}</span>
</div>
</div>
<div className="flex items-center gap-2">
<a
href={`/api/v1/pastes/${paste.id}?raw=1`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
>
Raw
</a>
{/* Copy button could go here */}
</div>
</div>
{pasteTags.length > 0 && (
<div className="flex flex-wrap gap-2">
{pasteTags.map((tag) => (
<Link key={tag.id} href={`/tag/${tag.id}`}>
<SimpleBadge>#{tag.name}</SimpleBadge>
</Link>
))}
</div>
)}
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<CodeViewer code={paste.content} language={paste.syntax || 'text'} />
</div>
</div>
);
}

View file

@ -0,0 +1,64 @@
import Link from "next/link";
import { db } from "@/db";
import { agentSessions, pastes } from "@/db/schema";
import { eq, desc } from "drizzle-orm";
import { notFound } from "next/navigation";
import { formatDistanceToNow } from "date-fns";
export default async function SessionPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = (await db.select().from(agentSessions).where(eq(agentSessions.id, id)).limit(1))[0];
if (!session) {
notFound();
}
const sessionPastes = await db.select()
.from(pastes)
.where(eq(pastes.sessionId, session.id))
.orderBy(desc(pastes.createdAt));
return (
<div className="space-y-6">
<div className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight">{session.title || "Session " + session.id}</h1>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>{formatDistanceToNow(session.createdAt!, { addSuffix: true })}</span>
<span></span>
<span className="font-mono">{session.agentName || "Unknown Agent"}</span>
</div>
</div>
<div className="grid gap-4">
{sessionPastes.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
No pastes in this session.
</div>
) : (
sessionPastes.map((paste) => (
<Link
key={paste.id}
href={`/paste/${paste.id}`}
className="block p-4 rounded-lg border bg-card text-card-foreground shadow-sm hover:shadow-md transition-shadow"
>
<div className="flex items-center justify-between mb-1">
<h3 className="font-medium truncate">
{paste.title || "Untitled Paste"}
</h3>
<span className="text-xs text-muted-foreground font-mono">
{paste.syntax || "text"}
</span>
</div>
<div className="text-xs text-muted-foreground line-clamp-2 font-mono bg-muted/50 p-1.5 rounded mb-2">
{paste.content}
</div>
<div className="text-xs text-muted-foreground">
{formatDistanceToNow(paste.createdAt!, { addSuffix: true })}
</div>
</Link>
))
)}
</div>
</div>
);
}

View file

@ -0,0 +1,57 @@
import Link from "next/link";
import { db } from "@/db";
import { agentSessions, pastes } from "@/db/schema";
import { desc, eq, sql } from "drizzle-orm";
import { formatDistanceToNow } from "date-fns";
export const dynamic = 'force-dynamic';
export default async function SessionsPage() {
// Fetch sessions with paste count
const allSessions = await db.select({
id: agentSessions.id,
title: agentSessions.title,
agentName: agentSessions.agentName,
createdAt: agentSessions.createdAt,
pasteCount: sql<number>`count(${pastes.id})`,
})
.from(agentSessions)
.leftJoin(pastes, eq(agentSessions.id, pastes.sessionId))
.groupBy(agentSessions.id)
.orderBy(desc(agentSessions.createdAt));
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold tracking-tight">Sessions</h1>
<div className="grid gap-4">
{allSessions.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
No sessions found.
</div>
) : (
allSessions.map((session) => (
<Link
key={session.id}
href={`/sessions/${session.id}`}
className="block p-6 rounded-lg border bg-card text-card-foreground shadow-sm hover:shadow-md transition-shadow"
>
<div className="flex items-center justify-between mb-2">
<h2 className="font-semibold text-lg">
{session.title || session.id}
</h2>
<span className="text-xs text-muted-foreground font-mono">
{session.agentName || "Unknown Agent"}
</span>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span>{formatDistanceToNow(session.createdAt!, { addSuffix: true })}</span>
<span>{session.pasteCount} pastes</span>
</div>
</Link>
))
)}
</div>
</div>
);
}

View file

@ -0,0 +1,37 @@
import { auth } from "@/auth";
import { redirect } from "next/navigation";
import { Button } from "@/components/ui/button";
import { KeyRound, Plus } from "lucide-react";
export default async function ApiKeysPage() {
const session = await auth();
if (!session?.user) {
redirect("/api/auth/signin");
}
return (
<div className="max-w-3xl mx-auto p-4 md:p-6">
<div className="flex items-center justify-between mb-8">
<h1 className="text-3xl font-bold tracking-tight">API Keys</h1>
<Button>
<Plus className="w-4 h-4 mr-2" /> Generate New Key
</Button>
</div>
<div className="bg-card p-6 rounded-lg border border-dashed text-center text-muted-foreground flex flex-col items-center justify-center h-[200px]">
<KeyRound className="w-10 h-10 mb-3" />
<p className="text-lg">No API Keys yet.</p>
<p className="text-sm">Generate keys to connect your agents and desktop clients.</p>
</div>
{/* Placeholder for listing existing keys */}
{/* <div className="space-y-4">
<div className="bg-muted p-4 rounded-md flex items-center justify-between">
<span className="font-mono text-sm text-foreground">sk_live_********************</span>
<Button variant="destructive" size="sm">Revoke</Button>
</div>
</div> */}
</div>
);
}

View file

@ -0,0 +1,75 @@
import Link from "next/link";
import { db } from "@/db";
import { tags, pastes, pastesToTags } from "@/db/schema";
import { eq, desc } from "drizzle-orm";
import { notFound } from "next/navigation";
import { formatDistanceToNow } from "date-fns";
import { Badge } from "@/components/ui/badge";
export default async function TagPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const tag = (await db.select().from(tags).where(eq(tags.id, id)).limit(1))[0];
if (!tag) {
notFound();
}
const taggedPastes = await db.select({
id: pastes.id,
title: pastes.title,
content: pastes.content,
syntax: pastes.syntax,
createdAt: pastes.createdAt,
visibility: pastes.visibility,
})
.from(pastes)
.innerJoin(pastesToTags, eq(pastes.id, pastesToTags.pasteId))
.where(eq(pastesToTags.tagId, tag.id))
.orderBy(desc(pastes.createdAt))
.limit(50);
return (
<div className="space-y-6">
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold tracking-tight">Tag:</h1>
<Badge className="text-lg px-3 py-1">#{tag.name}</Badge>
</div>
<div className="grid gap-4">
{taggedPastes.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
No pastes found with this tag.
</div>
) : (
taggedPastes.map((paste) => (
<Link
key={paste.id}
href={`/paste/${paste.id}`}
className="block p-6 rounded-lg border bg-card text-card-foreground shadow-sm hover:shadow-md transition-shadow"
>
<div className="flex items-center justify-between mb-2">
<h2 className="font-semibold text-lg truncate">
{paste.title || "Untitled Paste"}
</h2>
<span className="text-xs text-muted-foreground font-mono">
{paste.syntax || "text"}
</span>
</div>
<div className="text-sm text-muted-foreground line-clamp-2 font-mono bg-muted/50 p-2 rounded">
{paste.content}
</div>
<div className="mt-4 flex items-center gap-4 text-xs text-muted-foreground">
<span>{formatDistanceToNow(paste.createdAt!, { addSuffix: true })}</span>
{paste.visibility !== 'public' && (
<span className="capitalize px-2 py-0.5 rounded-full bg-secondary text-secondary-foreground">
{paste.visibility}
</span>
)}
</div>
</Link>
))
)}
</div>
</div>
);
}

17
apps/web/src/auth.ts Normal file
View file

@ -0,0 +1,17 @@
import NextAuth from "next-auth"
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import { db } from "@/db"
import { accounts, sessions, users, verificationTokens } from "@/db/schema"
import Google from "next-auth/providers/google"
import GitHub from "next-auth/providers/github"
import Apple from "next-auth/providers/apple"
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: DrizzleAdapter(db, {
usersTable: users,
accountsTable: accounts,
sessionsTable: sessions,
verificationTokensTable: verificationTokens,
}),
providers: [Google, GitHub, Apple],
})

View file

@ -0,0 +1,30 @@
import { signIn, signOut } from "@/auth"
import { Button } from "./ui/button"
export function SignIn() {
return (
<form
action={async () => {
"use server"
await signIn()
}}
>
<Button variant="outline" size="sm">Sign In</Button>
</form>
)
}
export function SignOut() {
return (
<form
action={async () => {
"use server"
await signOut()
}}
>
<Button variant="ghost" size="sm" className="w-full justify-start">
Sign Out
</Button>
</form>
)
}

View file

@ -0,0 +1,39 @@
"use client"
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, vs } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
interface CodeViewerProps {
code: string;
language: string;
}
export function CodeViewer({ code, language }: CodeViewerProps) {
const { theme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return (
<pre className="p-4 rounded-md bg-muted overflow-auto">
<code>{code}</code>
</pre>
);
}
return (
<SyntaxHighlighter
language={language || 'text'}
style={theme === 'dark' ? vscDarkPlus : vs}
customStyle={{ margin: 0, borderRadius: '0.5rem', fontSize: '0.875rem' }}
showLineNumbers
>
{code}
</SyntaxHighlighter>
);
}

View file

@ -0,0 +1,35 @@
import Link from "next/link"
import { ThemeToggle } from "./theme-toggle"
import UserButton from "./user-button"
export function Navbar() {
return (
<header className="border-b">
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
<div className="flex items-center gap-6">
<Link href="/" className="font-bold text-xl tracking-tight">
Kites
</Link>
<nav className="flex items-center gap-4 text-sm font-medium text-muted-foreground">
<Link href="/" className="hover:text-foreground transition-colors">
Home
</Link>
<Link href="/dashboard" className="hover:text-foreground transition-colors">
Dashboard
</Link>
<Link href="/sessions" className="hover:text-foreground transition-colors">
Sessions
</Link>
<Link href="/settings/api-keys" className="hover:text-foreground transition-colors">
Settings
</Link>
</nav>
</div>
<div className="flex items-center gap-4">
<ThemeToggle />
<UserButton />
</div>
</div>
</header>
)
}

View file

@ -0,0 +1,141 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
export function PasteForm() {
const router = useRouter()
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
setLoading(true)
setError(null)
const formData = new FormData(event.currentTarget)
const data = {
title: formData.get("title"),
content: formData.get("content"),
syntax: formData.get("syntax"),
visibility: formData.get("visibility"),
tags: formData.get("tags")?.toString().split(",").map(t => t.trim()).filter(Boolean),
}
try {
const res = await fetch("/api/v1/pastes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
if (!res.ok) {
const json = await res.json()
throw new Error(JSON.stringify(json.error) || "Failed to create paste")
}
const created = await res.json()
router.push(`/paste/${created.id}`)
router.refresh()
} catch (err) {
setError(err instanceof Error ? err.message : "Something went wrong")
} finally {
setLoading(false)
}
}
return (
<form onSubmit={onSubmit} className="space-y-6">
{error && (
<div className="p-4 rounded bg-destructive/10 text-destructive text-sm">
{error}
</div>
)}
<div className="space-y-2">
<label htmlFor="title" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
Title (Optional)
</label>
<input
id="title"
name="title"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
placeholder="My awesome snippet"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label htmlFor="syntax" className="text-sm font-medium leading-none">
Syntax
</label>
<select
id="syntax"
name="syntax"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<option value="text">Plain Text</option>
<option value="javascript">JavaScript</option>
<option value="typescript">TypeScript</option>
<option value="python">Python</option>
<option value="json">JSON</option>
<option value="markdown">Markdown</option>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="bash">Bash</option>
<option value="go">Go</option>
<option value="rust">Rust</option>
</select>
</div>
<div className="space-y-2">
<label htmlFor="visibility" className="text-sm font-medium leading-none">
Visibility
</label>
<select
id="visibility"
name="visibility"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<option value="public">Public</option>
<option value="unlisted">Unlisted</option>
<option value="private">Private</option>
</select>
</div>
</div>
<div className="space-y-2">
<label htmlFor="tags" className="text-sm font-medium leading-none">
Tags (comma separated)
</label>
<input
id="tags"
name="tags"
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
placeholder="bug, feature, wip"
/>
</div>
<div className="space-y-2">
<label htmlFor="content" className="text-sm font-medium leading-none">
Content
</label>
<textarea
id="content"
name="content"
required
className="flex min-h-[300px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
placeholder="Paste your code here..."
/>
</div>
<button
type="submit"
disabled={loading}
className="inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full"
>
{loading ? "Creating..." : "Create Paste"}
</button>
</form>
)
}

View file

@ -0,0 +1,9 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { type ThemeProviderProps } from "next-themes"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View file

@ -0,0 +1,21 @@
"use client"
import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
export function ThemeToggle() {
const { setTheme, theme } = useTheme()
return (
<button
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
className="p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
aria-label="Toggle theme"
>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100 top-2" />
<span className="sr-only">Toggle theme</span>
</button>
)
}

View file

@ -0,0 +1,35 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> { }
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

View file

@ -0,0 +1,43 @@
import * as React from "react"
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "default" | "outline" | "ghost"
size?: "default" | "sm" | "lg"
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = "default", size = "default", ...props }, ref) => {
const variants = {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
ghost: "hover:bg-accent hover:text-accent-foreground",
}
const sizes = {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
}
return (
<button
className={cn(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
variants[variant],
sizes[size],
className
)}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button }

View file

@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View file

@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }

View file

@ -0,0 +1,121 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
}

View file

@ -0,0 +1,31 @@
import { auth } from "@/auth"
import { SignIn, SignOut } from "./auth-components"
import { Button } from "./ui/button"
export default async function UserButton() {
const session = await auth()
if (!session?.user) return <SignIn />
return (
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
{session.user.image ? (
<img
src={session.user.image}
alt={session.user.name || "User"}
className="w-8 h-8 rounded-full border border-border"
/>
) : (
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium">
{session.user.name?.[0] || "U"}
</div>
)}
<span className="text-sm font-medium hidden md:inline-block">
{session.user.name}
</span>
</div>
<SignOut />
</div>
)
}

9
apps/web/src/db/index.ts Normal file
View file

@ -0,0 +1,9 @@
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export const db = drizzle(pool, { schema });

View file

@ -0,0 +1,14 @@
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { db } from './index';
async function main() {
console.log('Running migrations...');
await migrate(db, { migrationsFolder: 'drizzle' });
console.log('Migrations complete!');
process.exit(0);
}
main().catch((err) => {
console.error('Migration failed!', err);
process.exit(1);
});

120
apps/web/src/db/schema.ts Normal file
View file

@ -0,0 +1,120 @@
import { pgTable, text, integer, timestamp, primaryKey, index, boolean } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
import type { AdapterAccount } from "next-auth/adapters";
// --- Application Tables ---
export const pastes = pgTable('pastes', {
id: text('id').primaryKey(), // Nanoid
title: text('title'),
content: text('content').notNull(),
contentType: text('content_type').default('text/plain'),
syntax: text('syntax'),
visibility: text('visibility').default('public'), // 'public', 'unlisted', 'private'
authorId: text('author_id').references(() => users.id, { onDelete: 'set null' }), // Linked to User
sessionId: text('session_id').references(() => agentSessions.id, { onDelete: 'set null' }),
expiresAt: timestamp('expires_at'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const tags = pgTable('tags', {
id: text('id').primaryKey(),
name: text('name').notNull().unique(),
color: text('color'),
description: text('description'),
});
export const pastesToTags = pgTable('pastes_to_tags', {
pasteId: text('paste_id').references(() => pastes.id, { onDelete: 'cascade' }),
tagId: text('tag_id').references(() => tags.id, { onDelete: 'cascade' }),
}, (t) => ({
pk: primaryKey({ columns: [t.pasteId, t.tagId] }),
}));
export const agentSessions = pgTable('agent_sessions', {
id: text('id').primaryKey(),
title: text('title'),
agentName: text('agent_name'),
userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }), // Optional owner
createdAt: timestamp('created_at').defaultNow(),
});
// --- Auth.js Tables ---
export const users = pgTable("user", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
name: text("name"),
email: text("email").notNull(),
emailVerified: timestamp("emailVerified", { mode: "date" }),
image: text("image"),
});
export const accounts = pgTable(
"account",
{
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
type: text("type").$type<AdapterAccount["type"]>().notNull(),
provider: text("provider").notNull(),
providerAccountId: text("providerAccountId").notNull(),
refresh_token: text("refresh_token"),
access_token: text("access_token"),
expires_at: integer("expires_at"),
token_type: text("token_type"),
scope: text("scope"),
id_token: text("id_token"),
session_state: text("session_state"),
},
(account) => ({
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
})
);
export const sessions = pgTable("session", {
sessionToken: text("sessionToken").primaryKey(),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expires: timestamp("expires", { mode: "date" }).notNull(),
});
export const verificationTokens = pgTable(
"verificationToken",
{
identifier: text("identifier").notNull(),
token: text("token").notNull(),
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(verificationToken) => ({
compositePk: primaryKey({
columns: [verificationToken.identifier, verificationToken.token],
}),
})
);
export const authenticators = pgTable(
"authenticator",
{
credentialID: text("credentialID").notNull().unique(),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
providerAccountId: text("providerAccountId").notNull(),
credentialPublicKey: text("credentialPublicKey").notNull(),
counter: integer("counter").notNull(),
credentialDeviceType: text("credentialDeviceType").notNull(),
credentialBackedUp: boolean("credentialBackedUp").notNull(),
transports: text("transports"),
},
(authenticator) => ({
compositePK: primaryKey({
columns: [authenticator.userId, authenticator.credentialID],
}),
})
);

View file

@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

34
apps/web/tsconfig.json Normal file
View file

@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

49
docker-compose.yml Normal file
View file

@ -0,0 +1,49 @@
version: '3.8'
services:
kites:
build:
context: ./apps/web
dockerfile: Dockerfile
environment:
DATABASE_URL: postgresql://postgres:postgres@db:5432/kites_db?schema=public
NEXTAUTH_URL: https://kites.runfoo.run
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET:-changeme1234567890changeme}
KITES_API_KEY: kites-desktop-secret-key
# If using Google/GitHub auth, add those here too
depends_on:
- db
networks:
- kites-network
- traefik-public
deploy:
restart_policy:
condition: on-failure
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik-public"
- "traefik.http.routers.kites.rule=Host(`kites.runfoo.run`)"
- "traefik.http.routers.kites.entrypoints=websecure"
- "traefik.http.routers.kites.tls.certresolver=letsencrypt"
- "traefik.http.services.kites.loadbalancer.server.port=3000"
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: kites_db
volumes:
- db_data:/var/lib/postgresql/data
networks:
- kites-network
restart: unless-stopped
networks:
kites-network:
driver: bridge
traefik-public:
external: true
volumes:
db_data:

View file

@ -1,10 +1,11 @@
import type { Config } from 'drizzle-kit'; import { defineConfig } from 'drizzle-kit';
import 'dotenv/config';
export default { export default defineConfig({
schema: './src/db/schema.ts', schema: './src/db/schema.ts',
out: './drizzle', out: './drizzle',
dialect: 'sqlite', dialect: 'postgresql',
dbCredentials: { dbCredentials: {
url: 'sqlite.db', url: process.env.DATABASE_URL!,
}, },
} satisfies Config; });

45
fix_deployment_plan.md Normal file
View file

@ -0,0 +1,45 @@
# Deployment Fix Plan - Kites
## Status
- **Current State**: `kites.runfoo.run` is down (521 Error).
- **Recent Error**: `Can't find meta/_journal.json file` during migration startup.
- **Previous Error**: `relation "account" already exists` (Fixed by manual SQL edit, but likely caused the journal issue).
## Goal
Restore service availability by fixing the database migration process and ensuring the application container starts successfully.
## Analysis
The application uses Drizzle ORM for database management. The startup sequence runs a migration script (`src/db/migrate.ts`).
1. The initial crash was due to existing tables conflicting with the migration script trying to create them again.
2. We manually edited the SQL to be idempotent (`IF NOT EXISTS`).
3. The new error suggests the Drizzle migration metadata (`_journal.json`) is missing or corrupt in the runtime environment. This file is required by `drizzle-kit` to track migration history.
## Steps
1. **Verify Local State**:
- Check contents of `apps/web/drizzle` folder.
- Confirm if `meta/_journal.json` exists.
2. **Fix Migration Artifacts**:
- Run `drizzle-kit generate` (or `push`) locally to ensure the SQL and Journal are consistent and properly generated by the tool, rather than manually edited.
- If we want to maintain the `IF NOT EXISTS` safety, we might need to check if Drizzle supports this natively or if we need to modify the generated SQL *and* ensure the snapshots utilize Custom migrations if needed.
- *Alternative*: Since the DB already exists and has tables, we can introspect (pull) or just ensure the migration table tracks it as "done" if it's already done. But `IF NOT EXISTS` is the safest path for a "dumb" apply.
- **Action**: Run `drizzle-kit generate` to repair `_journal.json`.
3. **Check Build Configuration**:
- Inspect `Dockerfile` (both in root and `apps/web`) to ensure the `drizzle` folder (including `meta`) is copied to the final image.
4. **Deploy Fix**:
- Commit the repaired migration files.
- Push to `github`.
- Pull on `nexus-vector`.
- Rebuild/Restart the container.
## Verification
- Monitor logs of `kites-kites-1` on `nexus-vector` to confirm successful migration and startup.
- Visit `https://kites.runfoo.run`.

160
package-lock.json generated
View file

@ -20,6 +20,7 @@
"next": "16.0.3", "next": "16.0.3",
"next-auth": "^5.0.0-beta.30", "next-auth": "^5.0.0-beta.30",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"pg": "^8.16.3",
"react": "19.2.0", "react": "19.2.0",
"react-dom": "19.2.0", "react-dom": "19.2.0",
"react-syntax-highlighter": "^16.1.0", "react-syntax-highlighter": "^16.1.0",
@ -30,6 +31,7 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
"@types/node": "^20", "@types/node": "^20",
"@types/pg": "^8.16.0",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"drizzle-kit": "^0.31.7", "drizzle-kit": "^0.31.7",
@ -2531,6 +2533,18 @@
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
}, },
"node_modules/@types/pg": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.16.0.tgz",
"integrity": "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/@types/prismjs": { "node_modules/@types/prismjs": {
"version": "1.26.5", "version": "1.26.5",
"resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz", "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz",
@ -7079,6 +7093,95 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/pg": {
"version": "8.16.3",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz",
"integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.9.1",
"pg-pool": "^3.10.1",
"pg-protocol": "^1.10.3",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.2.7"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.7.tgz",
"integrity": "sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.9.1.tgz",
"integrity": "sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.10.1.tgz",
"integrity": "sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.10.3",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.10.3.tgz",
"integrity": "sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@ -7156,6 +7259,45 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
} }
}, },
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/preact": { "node_modules/preact": {
"version": "10.24.3", "version": "10.24.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz", "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz",
@ -7887,6 +8029,15 @@
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
}, },
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/stable-hash": { "node_modules/stable-hash": {
"version": "0.0.5", "version": "0.0.5",
"resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz",
@ -8637,6 +8788,15 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yallist": { "node_modules/yallist": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",

View file

@ -21,6 +21,7 @@
"next": "16.0.3", "next": "16.0.3",
"next-auth": "^5.0.0-beta.30", "next-auth": "^5.0.0-beta.30",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"pg": "^8.16.3",
"react": "19.2.0", "react": "19.2.0",
"react-dom": "19.2.0", "react-dom": "19.2.0",
"react-syntax-highlighter": "^16.1.0", "react-syntax-highlighter": "^16.1.0",
@ -31,6 +32,7 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
"@types/node": "^20", "@types/node": "^20",
"@types/pg": "^8.16.0",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"drizzle-kit": "^0.31.7", "drizzle-kit": "^0.31.7",

View file

@ -0,0 +1,15 @@
# Plan 001: Baseline Implementation
## 1. Status: Completed
The V1 Hybrid architecture has been implemented and deployed.
## 2. Key Components
- `src/db/schema.ts`: Converted to `pgTable` and PostgreSQL types.
- `src/app/api/v1/pastes/route.ts`: Added API Key authentication middleware logic.
- `docker-compose.yml`: Defined `kites` (Next.js) and `db` (Postgres) services with Traefik labels.
- `Dockerfile`: Multi-stage build with `drizzle-kit` support for migrations.
## 3. Next Steps (V1.1)
- Implement real user accounts for Desktop Client (replace API Key with PAT or OAuth).
- Add "Search" to Desktop Client.
- Add "Agent" role to Session (allow agents to create sessions via API).

View file

@ -0,0 +1,37 @@
# Spec 001: Kites V1 Hybrid
## 1. Overview
Kites is a shared clipboard and context manager for humans and AI agents. It consists of a central web application (The Brain) and a desktop client (The Hand).
## 2. Architecture
- **Web/API (The Brain):** Next.js 16 application hosted at `kites.runfoo.run`.
- **DB:** PostgreSQL (migrated from SQLite).
- **ORM:** Drizzle.
- **Auth:** NextAuth (Web) + API Key (Client).
- **Desktop Client (The Hand):** Tauri application (React + Rust).
- **Sync:** Pushes clipboard history to Web API via `POST /api/v1/pastes` using `x-api-key`.
- **Read:** Pulls history and sessions.
## 3. Data Model
### Paste
- `id`: Nanoid.
- `content`: Text content.
- `syntax`: Language detection.
- `sessionId`: Link to an Agent Run/Session.
- `visibility`: 'public' | 'private' | 'unlisted'.
### Session (Agent Run)
- `id`: Nanoid.
- `title`: "Refactor Auth" or "Daily Log".
- `agentName`: "Claude", "GPT-4".
## 4. API Endpoints
- `POST /api/v1/pastes`: Create paste (API Key supported).
- `GET /api/v1/pastes`: List pastes.
- `POST /api/v1/sessions`: Create session.
- `GET /api/v1/sessions`: List sessions.
## 5. Deployment
- **Host:** Nexus Vector.
- **Orchestration:** Docker Compose.
- **Routing:** Traefik (`kites.runfoo.run`).

View file

@ -0,0 +1,8 @@
# Tasks 001: Baseline
- [x] Migrate `kites` from SQLite to Postgres.
- [x] Create `Dockerfile` and `docker-compose.yml`.
- [x] Implement API Key auth in `api/v1/pastes`.
- [x] Update Desktop Client to talk to `kites.runfoo.run`.
- [x] Deploy to `nexus-vector`.
- [x] "Zhuzh" up the Landing Page.

View file

@ -1,6 +1,9 @@
import { drizzle } from 'drizzle-orm/better-sqlite3'; import { drizzle } from 'drizzle-orm/node-postgres';
import Database from 'better-sqlite3'; import { Pool } from 'pg';
import * as schema from './schema'; import * as schema from './schema';
const sqlite = new Database('sqlite.db'); const pool = new Pool({
export const db = drizzle(sqlite, { schema }); connectionString: process.env.DATABASE_URL,
});
export const db = drizzle(pool, { schema });

14
src/db/migrate.ts Normal file
View file

@ -0,0 +1,14 @@
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { db } from './index';
async function main() {
console.log('Running migrations...');
await migrate(db, { migrationsFolder: 'drizzle' });
console.log('Migrations complete!');
process.exit(0);
}
main().catch((err) => {
console.error('Migration failed!', err);
process.exit(1);
});