From 56ab1782c77c71cca1ea1c25568075dab513cc28 Mon Sep 17 00:00:00 2001 From: Leonid Meleshin Date: Sun, 5 Jul 2026 23:35:36 +0200 Subject: [PATCH 01/12] =?UTF-8?q?feat:=20prompt=20library=20=E2=80=94=20sa?= =?UTF-8?q?ved=20prompts=20with=20`/`=20composer=20access?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reusable prompt templates inserted in the composer by typing `/` — the roadmap v0.5 slash-commands seed in its genuinely-useful form (validated by Open WebUI, which has the same `/` prompt menu). - `prompts` table (owner-scoped, FORCE RLS, UNIQUE(user_id, name), migration 0015) + `/api/v1/me/prompts` CRUD, mirroring memories. `name` is a slug (^[A-Za-z0-9_-]+$ DB CHECK) so `/` is unambiguous; a duplicate name is a real 409 (DB unique + a 23505-walking catch — stricter than the memories pre-check). - Settings section to manage prompts; a `/` autocomplete menu in the chat composer to insert them. Two-reviewer round hardened the composer: - trigger is `^/(\S+)$` — bare `/` never opens the menu, so a literal `/` message still sends (the adversarial literal-send trap); - prefix matching is case-insensitive; - only BARE Enter selects (Shift+Enter falls through to a newline); - the list comes from one shared usePromptsQuery() (fetched once, filtered per keystroke, invalidated by a settings edit). The core-composer change is minimal + backward-compatible: PromptInputTextarea now calls a passed onKeyDown first and bails on preventDefault — before, a passed handler silently clobbered Enter-to-send. Carved out of experiment/overnight-loop-3 as an independent PR. Also adds the missing `prompts-rls.integration` invocation to `scripts/rls-test.sh` (the harness previously only ran `chats-rls.integration`, so this suite was never exercised), and adds `sonner` as a direct `apps/web` dependency for the settings section's `toast()` calls (the shared `@workspace/ui` sonner wrapper only re-exports ``, matching upstream shadcn/ui convention). Verified: 5 prompts RLS integration cases (owner CRUD, cross-tenant denied, per-user unique name / same-name-across-users allowed, slug + content CHECKs) + pure-trigger and web service cases, api + web typecheck/lint/unit tests clean, migration 0015 + drizzle-kit check clean. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 4 + apps/api/AGENTS.md | 2 +- apps/api/scripts/rls-test.sh | 3 + apps/api/src/chats/chats.module.ts | 3 +- apps/api/src/chats/dto/prompts.dto.ts | 79 + apps/api/src/chats/me-prompts.controller.ts | 147 ++ apps/api/src/chats/prompts-repository.ts | 94 ++ .../src/chats/prompts-rls.integration.spec.ts | 142 ++ .../migrations/0015_futuristic_liz_osborn.sql | 16 + .../src/db/migrations/meta/0015_snapshot.json | 1423 +++++++++++++++++ apps/api/src/db/migrations/meta/_journal.json | 7 + apps/api/src/db/schema/index.ts | 1 + apps/api/src/db/schema/prompts.ts | 67 + apps/web/app/(chat)/components/chat-page.tsx | 9 + .../(chat)/components/prompt-command-menu.tsx | 86 + .../settings/components/prompts-section.tsx | 170 ++ apps/web/app/(chat)/settings/page.tsx | 2 + .../components/components/ai/prompt-input.tsx | 8 + .../web/lib/services/prompts/matching.test.ts | 38 + apps/web/lib/services/prompts/matching.ts | 24 + apps/web/lib/services/prompts/queries.test.ts | 62 + apps/web/lib/services/prompts/queries.ts | 84 + apps/web/package.json | 1 + .../specs/2026-07-03-prompt-library-design.md | 92 ++ pnpm-lock.yaml | 3 + 25 files changed, 2565 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/chats/dto/prompts.dto.ts create mode 100644 apps/api/src/chats/me-prompts.controller.ts create mode 100644 apps/api/src/chats/prompts-repository.ts create mode 100644 apps/api/src/chats/prompts-rls.integration.spec.ts create mode 100644 apps/api/src/db/migrations/0015_futuristic_liz_osborn.sql create mode 100644 apps/api/src/db/migrations/meta/0015_snapshot.json create mode 100644 apps/api/src/db/schema/prompts.ts create mode 100644 apps/web/app/(chat)/components/prompt-command-menu.tsx create mode 100644 apps/web/app/(chat)/settings/components/prompts-section.tsx create mode 100644 apps/web/lib/services/prompts/matching.test.ts create mode 100644 apps/web/lib/services/prompts/matching.ts create mode 100644 apps/web/lib/services/prompts/queries.test.ts create mode 100644 apps/web/lib/services/prompts/queries.ts create mode 100644 docs/superpowers/specs/2026-07-03-prompt-library-design.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e907ca1b..d6f32a1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ _Reverse-chronological record of shipped work — features, fixes, and chores. Newest first._ +# 2026-07-05 + +- Prompt library — saved, reusable prompt templates inserted in the composer by typing `/` (the roadmap v0.5 slash-commands seed, in its genuinely-useful form; validated by Open WebUI, which has the same `/` prompt menu). A `prompts` table (owner-scoped, FORCE RLS, `UNIQUE(user_id, name)`, migration 0015) + `/api/v1/me/prompts` CRUD (GET/POST/PATCH/DELETE), mirroring the memories pattern — the `name` is a slug (`^[A-Za-z0-9_-]+$`, DB CHECK) so `/` is unambiguous, and a duplicate name is a real 409 (DB unique + a `23505`-walking catch, stricter than the memories pre-check). Manage prompts in Settings; insert them in a chat via a `/` autocomplete menu. A two-reviewer round hardened the composer: the trigger is `^/(\S+)$` — bare `/` never opens the menu, so a literal `/` message still sends (the adversarial reviewer's literal-send trap); prefix matching is case-insensitive; only BARE Enter selects (Shift+Enter falls through to a newline); the menu list comes from a single shared `usePromptsQuery()` (fetched once, filtered per keystroke, invalidated by a settings edit). The core-composer change is minimal + backward-compatible: `PromptInputTextarea` now calls a passed `onKeyDown` first and bails if it `preventDefault`ed (before that, a passed handler silently clobbered Enter-to-send). Verified: 5 prompts RLS integration cases (owner CRUD, cross-tenant denied, per-user unique name but same-name-across-users allowed, slug + content CHECKs), plus pure-trigger and web service cases, prompts route in openapi.json, api + web build/lint/tsc clean. + # 2026-07-04 - Fixed `pnpm --filter web dev` in git worktrees after the Next 16/Turbopack upgrade: the script now launches Next from the monorepo root with `apps/web` as the project directory, avoiding Turbopack's mixed-root module graph that made authenticated chat pages fail with `Cannot find module '@workspace/ui/globals.css'` while unauthenticated/login routes still appeared healthy. diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md index 3a6eb183..46dee663 100644 --- a/apps/api/AGENTS.md +++ b/apps/api/AGENTS.md @@ -58,4 +58,4 @@ Migrations run as a **non-superuser `app` role that owns the schema** (provision - `apps/api/src/db` is the **sole** schema; `apps/web` owns no database. - Linting is oxlint with type-aware rules (`.oxlintrc.json`, `options.typeAware`) running on **tsgo** (TypeScript 7). tsgo rejects `baseUrl`, so `tsconfig.json` must not reintroduce it, and global test/node types are declared explicitly via `"types": ["node", "jest"]` (tsgo does not auto-include `@types/*` under pnpm the way tsc does). Formatting is prettier (`pnpm format`), checked in CI via the root `format:check` — it is no longer an ESLint rule. -- Migrations are `drizzle-kit`-generated (`0005`+). Hand-authored exceptions: `0004` (the PoC → multi-tenant transition — drizzle-kit's interactive column-rename can't be driven non-interactively; `FORCE ROW LEVEL SECURITY` is hand-maintained here too, Drizzle can't express it), `0006` (the sessions hashing migration carries a manual `DELETE FROM sessions` — raw tokens can't be carried into the hashed-at-rest model), `0010` (the nullable-title migration carries a manual `UPDATE` backfilling old default-literal titles to NULL, and drops a spurious generated DROP/CREATE of the unchanged `sessions_user_created_idx`), `0011` (the durable-runs migration hand-appends `FORCE ROW LEVEL SECURITY` for `runs`/`run_events` — Drizzle emits ENABLE only — and hand-reorders the composite-key unique indexes before the FKs that reference them), `0012` (the single-flight migration carries a manual `UPDATE` cancelling all but the newest non-terminal run per chat — the partial unique index cannot be created over duplicates — plus matching `run.cancelled` events, applied inside a NO FORCE RLS window since migrations run as the owning role), and `0013` (the `in_reply_to` reply-integrity trigger, #73 — Drizzle can't express triggers). `drizzle-kit check` passes for all. Re-add the manual steps if you ever regenerate these. +- Migrations are `drizzle-kit`-generated (`0005`+). Hand-authored exceptions: `0004` (the PoC → multi-tenant transition — drizzle-kit's interactive column-rename can't be driven non-interactively; `FORCE ROW LEVEL SECURITY` is hand-maintained here too, Drizzle can't express it), `0006` (the sessions hashing migration carries a manual `DELETE FROM sessions` — raw tokens can't be carried into the hashed-at-rest model), `0010` (the nullable-title migration carries a manual `UPDATE` backfilling old default-literal titles to NULL, and drops a spurious generated DROP/CREATE of the unchanged `sessions_user_created_idx`), `0011` (the durable-runs migration hand-appends `FORCE ROW LEVEL SECURITY` for `runs`/`run_events` — Drizzle emits ENABLE only — and hand-reorders the composite-key unique indexes before the FKs that reference them), `0012` (the single-flight migration carries a manual `UPDATE` cancelling all but the newest non-terminal run per chat — the partial unique index cannot be created over duplicates — plus matching `run.cancelled` events, applied inside a NO FORCE RLS window since migrations run as the owning role), `0013` (the `in_reply_to` reply-integrity trigger, #73 — Drizzle can't express triggers), and `0015` (the prompt-library migration hand-appends `FORCE ROW LEVEL SECURITY` for `prompts`, same pattern as `0004`/`0011`). `drizzle-kit check` passes for all. Re-add the manual steps if you ever regenerate these. diff --git a/apps/api/scripts/rls-test.sh b/apps/api/scripts/rls-test.sh index 8542bb38..582573f9 100755 --- a/apps/api/scripts/rls-test.sh +++ b/apps/api/scripts/rls-test.sh @@ -57,6 +57,9 @@ echo "▶ applying migrations as 'app' (so app owns every table)" echo "▶ running RLS integration suite as 'app'" ( cd "$API_DIR" && TEST_DATABASE_URL="$APP_URL" pnpm exec jest chats-rls.integration --silent=false ) +echo "▶ running prompts RLS integration suite as 'app'" +( cd "$API_DIR" && TEST_DATABASE_URL="$APP_URL" pnpm exec jest prompts-rls.integration --silent=false ) + echo "▶ running queue integration suite (pg-boss on the same throwaway Postgres)" ( cd "$API_DIR" && TEST_DATABASE_URL="$APP_URL" pnpm exec jest queue.integration --silent=false ) diff --git a/apps/api/src/chats/chats.module.ts b/apps/api/src/chats/chats.module.ts index a1f3dd9a..fdfc3945 100644 --- a/apps/api/src/chats/chats.module.ts +++ b/apps/api/src/chats/chats.module.ts @@ -6,6 +6,7 @@ import { RunsModule } from '../runs/runs.module'; import { ChatLoopService } from './chat-loop.service'; import { ChatsController } from './chats.controller'; import { ChatsService } from './chats.service'; +import { MePromptsController } from './me-prompts.controller'; // HTTP endpoints are safe to expose only because SessionAuthGuard derives the tenant // identity from a verified session. Controllers must never accept ownerUserId from @@ -17,7 +18,7 @@ import { ChatsService } from './chats.service'; // queues, workers, compaction, or titling. @Module({ imports: [AuthModule, ModelsModule, RunsModule, RunWorkerModule], - controllers: [ChatsController], + controllers: [ChatsController, MePromptsController], providers: [ChatsService, ChatLoopService], exports: [ChatsService], }) diff --git a/apps/api/src/chats/dto/prompts.dto.ts b/apps/api/src/chats/dto/prompts.dto.ts new file mode 100644 index 00000000..7293037e --- /dev/null +++ b/apps/api/src/chats/dto/prompts.dto.ts @@ -0,0 +1,79 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { + IsOptional, + IsString, + Matches, + MaxLength, + MinLength, +} from 'class-validator'; + +import { + PROMPT_CONTENT_MAX, + PROMPT_NAME_MAX, + type Prompt, +} from '../../db/schema'; + +// The slash trigger: a slug (no whitespace/slashes) so `/` is exact. +const NAME_PATTERN = /^[A-Za-z0-9_-]+$/; +const NAME_MESSAGE = + 'name must be a slug: letters, digits, underscore or hyphen (no spaces)'; + +export class CreatePromptDto { + @ApiProperty({ maxLength: PROMPT_NAME_MAX, pattern: NAME_PATTERN.source }) + @IsString() + @Matches(NAME_PATTERN, { message: NAME_MESSAGE }) + @MaxLength(PROMPT_NAME_MAX) + name!: string; + + @ApiProperty({ minLength: 1, maxLength: PROMPT_CONTENT_MAX }) + @IsString() + @MinLength(1) + @MaxLength(PROMPT_CONTENT_MAX) + content!: string; +} + +export class UpdatePromptDto { + @ApiPropertyOptional({ + maxLength: PROMPT_NAME_MAX, + pattern: NAME_PATTERN.source, + }) + @IsOptional() + @IsString() + @Matches(NAME_PATTERN, { message: NAME_MESSAGE }) + @MaxLength(PROMPT_NAME_MAX) + name?: string; + + @ApiPropertyOptional({ minLength: 1, maxLength: PROMPT_CONTENT_MAX }) + @IsOptional() + @IsString() + @MinLength(1) + @MaxLength(PROMPT_CONTENT_MAX) + content?: string; +} + +export class PromptResponse { + @ApiProperty({ format: 'uuid' }) + id!: string; + + @ApiProperty({ maxLength: PROMPT_NAME_MAX }) + name!: string; + + @ApiProperty({ maxLength: PROMPT_CONTENT_MAX }) + content!: string; + + @ApiProperty({ format: 'date-time' }) + createdAt!: Date; + + @ApiProperty({ format: 'date-time' }) + updatedAt!: Date; +} + +export function toPromptResponse(prompt: Prompt): PromptResponse { + return { + id: prompt.id, + name: prompt.name, + content: prompt.content, + createdAt: prompt.createdAt, + updatedAt: prompt.updatedAt, + }; +} diff --git a/apps/api/src/chats/me-prompts.controller.ts b/apps/api/src/chats/me-prompts.controller.ts new file mode 100644 index 00000000..a27abcdc --- /dev/null +++ b/apps/api/src/chats/me-prompts.controller.ts @@ -0,0 +1,147 @@ +import { + Body, + ConflictException, + Controller, + Delete, + Get, + HttpCode, + NotFoundException, + Param, + ParseUUIDPipe, + Patch, + Post, +} from '@nestjs/common'; +import { + ApiBearerAuth, + ApiConflictResponse, + ApiCookieAuth, + ApiCreatedResponse, + ApiNoContentResponse, + ApiNotFoundResponse, + ApiOkResponse, + ApiParam, + ApiTags, + ApiUnauthorizedResponse, +} from '@nestjs/swagger'; + +import { CurrentUser } from '../auth/auth-context'; +import { TenantDbService } from '../db/tenant-db.service'; +import { + PROMPT_MAX_PER_USER, + PromptsRepository, + isPromptNameConflict, +} from './prompts-repository'; +import { + CreatePromptDto, + PromptResponse, + UpdatePromptDto, + toPromptResponse, +} from './dto/prompts.dto'; + +/** + * User-facing management of saved prompts — the caller's reusable `/` + * templates. Own-scope only (RLS `prompts_owner` scopes every op to the caller; + * `user_id` is the seatbelt). A duplicate `/name` (per user) is a 409. + */ +@ApiTags('me') +@ApiBearerAuth('bearer') +@ApiCookieAuth('cookie') +@Controller('api/v1/me/prompts') +export class MePromptsController { + constructor(private readonly tenantDb: TenantDbService) {} + + @Get() + @ApiOkResponse({ type: [PromptResponse] }) + @ApiUnauthorizedResponse() + async list(@CurrentUser() userId: string): Promise { + const rows = await this.tenantDb.runAs(userId, (tx) => + new PromptsRepository(tx).list(userId), + ); + return rows.map(toPromptResponse); + } + + @Post() + @ApiCreatedResponse({ type: PromptResponse }) + @ApiConflictResponse({ + description: 'Duplicate name, or at the per-user prompt cap', + }) + @ApiUnauthorizedResponse() + async create( + @CurrentUser() userId: string, + @Body() dto: CreatePromptDto, + ): Promise { + const content = dto.content.trim(); + try { + const created = await this.tenantDb.runAs(userId, async (tx) => { + const repo = new PromptsRepository(tx); + if ((await repo.countByUser(userId)) >= PROMPT_MAX_PER_USER) { + throw new ConflictException( + `Prompt limit reached (${PROMPT_MAX_PER_USER}).`, + ); + } + return repo.create(userId, dto.name, content); + }); + return toPromptResponse(created); + } catch (error) { + if (isPromptNameConflict(error)) { + throw new ConflictException( + `A prompt named "${dto.name}" already exists.`, + ); + } + throw error; + } + } + + @Patch(':id') + @ApiParam({ name: 'id', format: 'uuid' }) + @ApiOkResponse({ type: PromptResponse }) + @ApiConflictResponse({ + description: 'Rename collides with an existing prompt', + }) + @ApiNotFoundResponse({ description: 'Unknown or cross-tenant prompt' }) + @ApiUnauthorizedResponse() + async update( + @CurrentUser() userId: string, + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdatePromptDto, + ): Promise { + const patch = { + ...(dto.name !== undefined ? { name: dto.name } : {}), + ...(dto.content !== undefined ? { content: dto.content.trim() } : {}), + }; + try { + const updated = await this.tenantDb.runAs(userId, (tx) => + new PromptsRepository(tx).update(id, userId, patch), + ); + if (!updated) { + throw new NotFoundException(`Prompt ${id} not found`); + } + return toPromptResponse(updated); + } catch (error) { + if (isPromptNameConflict(error)) { + throw new ConflictException( + `A prompt named "${dto.name}" already exists.`, + ); + } + throw error; + } + } + + @Delete(':id') + @HttpCode(204) + @ApiParam({ name: 'id', format: 'uuid' }) + @ApiNoContentResponse() + @ApiNotFoundResponse({ description: 'Unknown or cross-tenant prompt' }) + @ApiUnauthorizedResponse() + async remove( + @CurrentUser() userId: string, + @Param('id', ParseUUIDPipe) id: string, + ): Promise { + const deleted = await this.tenantDb.runAs(userId, (tx) => + new PromptsRepository(tx).delete(id, userId), + ); + if (!deleted) { + throw new NotFoundException(`Prompt ${id} not found`); + } + } +} diff --git a/apps/api/src/chats/prompts-repository.ts b/apps/api/src/chats/prompts-repository.ts new file mode 100644 index 00000000..0d9c1b27 --- /dev/null +++ b/apps/api/src/chats/prompts-repository.ts @@ -0,0 +1,94 @@ +import { and, asc, eq, sql } from 'drizzle-orm'; +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; + +import * as schema from '../db/schema'; +import { prompts, type Prompt } from '../db/schema'; + +type Db = PostgresJsDatabase; + +/** Upper bound on saved prompts per user — a library, not a dumping ground. */ +export const PROMPT_MAX_PER_USER = 100; + +/** + * A Postgres unique_violation (23505) — the `prompts_user_name_idx` collision + * (a duplicate `/name` for the same user). Walks the cause chain (drizzle wraps + * the postgres.js error). Mapped to 409 by the controller. + */ +export function isPromptNameConflict(error: unknown): boolean { + let cursor: unknown = error; + while (cursor instanceof Error || (cursor && typeof cursor === 'object')) { + if ((cursor as { code?: unknown }).code === '23505') { + return true; + } + cursor = (cursor as { cause?: unknown }).cause; + if (cursor === undefined || cursor === null) { + break; + } + } + return false; +} + +/** Owner-scoped access to a user's saved prompts (RLS is the primary guard). */ +export class PromptsRepository { + constructor(private readonly db: Db) {} + + /** The user's prompts, name-ordered. */ + async list(userId: string): Promise { + return this.db + .select() + .from(prompts) + .where(eq(prompts.userId, userId)) + .orderBy(asc(prompts.name)); + } + + async countByUser(userId: string): Promise { + const [row] = await this.db + .select({ n: sql`count(*)::int` }) + .from(prompts) + .where(eq(prompts.userId, userId)); + return row?.n ?? 0; + } + + async create(userId: string, name: string, content: string): Promise { + const [created] = await this.db + .insert(prompts) + .values({ userId, name, content }) + .returning(); + return created; + } + + /** Patch name/content, owner-scoped. Undefined when not found / not owned. */ + async update( + id: string, + userId: string, + patch: { name?: string; content?: string }, + ): Promise { + const fields = { + ...(patch.name !== undefined ? { name: patch.name } : {}), + ...(patch.content !== undefined ? { content: patch.content } : {}), + }; + if (Object.keys(fields).length === 0) { + const [row] = await this.db + .select() + .from(prompts) + .where(and(eq(prompts.id, id), eq(prompts.userId, userId))) + .limit(1); + return row; + } + const [updated] = await this.db + .update(prompts) + .set({ ...fields, updatedAt: new Date() }) + .where(and(eq(prompts.id, id), eq(prompts.userId, userId))) + .returning(); + return updated; + } + + /** Delete by id, owner-scoped. True iff a row was removed (→ 404). */ + async delete(id: string, userId: string): Promise { + const deleted = await this.db + .delete(prompts) + .where(and(eq(prompts.id, id), eq(prompts.userId, userId))) + .returning({ id: prompts.id }); + return deleted.length > 0; + } +} diff --git a/apps/api/src/chats/prompts-rls.integration.spec.ts b/apps/api/src/chats/prompts-rls.integration.spec.ts new file mode 100644 index 00000000..e84e6fd7 --- /dev/null +++ b/apps/api/src/chats/prompts-rls.integration.spec.ts @@ -0,0 +1,142 @@ +/** + * Prompt library RLS integration test — owner-scoped CRUD under FORCE RLS: + * - a user CRUDs their own prompts; a cross-tenant read/update/delete is denied; + * - UNIQUE(user_id, name) rejects a per-user duplicate but ALLOWS the same name + * across users; the name-slug + content CHECKs hold. + * + * TEST_DATABASE_URL-gated; run by scripts/rls-test.sh. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import { drizzle } from 'drizzle-orm/postgres-js'; + +import * as schema from '../db/schema'; +import { TenantDbService, type Db } from '../db/tenant-db.service'; +import { PromptsRepository, isPromptNameConflict } from './prompts-repository'; + +const TEST_DB_URL = process.env['TEST_DATABASE_URL']; +const describeIfDb = TEST_DB_URL ? describe : describe.skip; +type SqlClient = any; + +describeIfDb('prompt library RLS + constraints', () => { + let sql: SqlClient; + let db: Db; + let tenantDb: TenantDbService; + let a: string; + let b: string; + + beforeAll(async () => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const postgres = require('postgres'); + const connect = postgres.default ?? postgres; + const ssl = /sslmode=require/.test(TEST_DB_URL!) ? 'require' : false; + sql = connect(TEST_DB_URL!, { ssl, max: 5 }); + db = drizzle(sql, { schema }); + tenantDb = new TenantDbService(db); + a = crypto.randomUUID(); + b = crypto.randomUUID(); + for (const id of [a, b]) { + await sql`INSERT INTO users (id, name, email) VALUES (${id}, 'P', ${`p-${id}@t.com`})`; + } + }); + + afterAll(async () => { + if (sql) { + await sql`DELETE FROM users WHERE id IN (${a}, ${b})`; + await sql.end(); + } + }); + + it('owner CRUD round-trips (create, list, update, delete)', async () => { + const created = await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'summarize', 'Summarize: '), + ); + expect(created.name).toBe('summarize'); + + const listed = await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).list(a), + ); + expect(listed.map((p) => p.name)).toContain('summarize'); + + const updated = await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).update(created.id, a, { + content: 'Summarize concisely: ', + }), + ); + expect(updated?.content).toBe('Summarize concisely: '); + + expect( + await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).delete(created.id, a), + ), + ).toBe(true); + }); + + it('a duplicate name for the SAME user is rejected; the SAME name for a DIFFERENT user is allowed', async () => { + await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'dup', 'A body'), + ); + // Same user, same name → unique violation. + let conflict: unknown; + try { + await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'dup', 'A body 2'), + ); + } catch (error) { + conflict = error; + } + expect(isPromptNameConflict(conflict)).toBe(true); + // Different user, same name → fine (namespaced per user). + const bPrompt = await tenantDb.runAs(b, (tx) => + new PromptsRepository(tx).create(b, 'dup', 'B body'), + ); + expect(bPrompt.name).toBe('dup'); + }); + + it('a cross-tenant read / update / delete is denied (RLS)', async () => { + const mine = await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'private', 'my body'), + ); + // B lists → does not see A's prompt. + const bList = await tenantDb.runAs(b, (tx) => + new PromptsRepository(tx).list(b), + ); + expect(bList.some((p) => p.id === mine.id)).toBe(false); + // B update / delete → no-op (RLS scopes to owner). + expect( + await tenantDb.runAs(b, (tx) => + new PromptsRepository(tx).update(mine.id, b, { content: 'hacked' }), + ), + ).toBeUndefined(); + expect( + await tenantDb.runAs(b, (tx) => + new PromptsRepository(tx).delete(mine.id, b), + ), + ).toBe(false); + // A's prompt survives unchanged. + const survivor = await tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).list(a), + ); + expect(survivor.find((p) => p.id === mine.id)?.content).toBe('my body'); + }); + + it('the name-slug CHECK rejects whitespace/slashes (so /name matching is exact)', async () => { + await expect( + tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'bad name', 'body'), + ), + ).rejects.toThrow(); + }); + + it('the content CHECK rejects an oversized body', async () => { + await expect( + tenantDb.runAs(a, (tx) => + new PromptsRepository(tx).create(a, 'toobig', 'x'.repeat(8001)), + ), + ).rejects.toThrow(); + }); +}); diff --git a/apps/api/src/db/migrations/0015_futuristic_liz_osborn.sql b/apps/api/src/db/migrations/0015_futuristic_liz_osborn.sql new file mode 100644 index 00000000..b07bcf89 --- /dev/null +++ b/apps/api/src/db/migrations/0015_futuristic_liz_osborn.sql @@ -0,0 +1,16 @@ +CREATE TABLE "prompts" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" text NOT NULL, + "name" text NOT NULL, + "content" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "prompts_name_slug" CHECK ("prompts"."name" ~ '^[A-Za-z0-9_-]{1,64}$'), + CONSTRAINT "prompts_content_len" CHECK (char_length("prompts"."content") BETWEEN 1 AND 8000) +); +--> statement-breakpoint +ALTER TABLE "prompts" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "prompts" FORCE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "prompts" ADD CONSTRAINT "prompts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "prompts_user_name_idx" ON "prompts" USING btree ("user_id","name");--> statement-breakpoint +CREATE POLICY "prompts_owner" ON "prompts" AS PERMISSIVE FOR ALL TO public USING (user_id = current_setting('app.current_user_id', true)); \ No newline at end of file diff --git a/apps/api/src/db/migrations/meta/0015_snapshot.json b/apps/api/src/db/migrations/meta/0015_snapshot.json new file mode 100644 index 00000000..3f44db06 --- /dev/null +++ b/apps/api/src/db/migrations/meta/0015_snapshot.json @@ -0,0 +1,1423 @@ +{ + "id": "ef1f5fee-480e-49ee-8f3d-f01675cb8a25", + "prevId": "f338e800-651a-4e42-a86c-cfb5a21ddfb7", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.accounts": { + "name": "accounts", + "schema": "", + "columns": { + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_account_id": { + "name": "provider_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "token_type": { + "name": "token_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_state": { + "name": "session_state", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "accounts_userId_users_id_fk": { + "name": "accounts_userId_users_id_fk", + "tableFrom": "accounts", + "tableTo": "users", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.authenticators": { + "name": "authenticators", + "schema": "", + "columns": { + "credential_id": { + "name": "credential_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_account_id": { + "name": "provider_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_public_key": { + "name": "credential_public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "counter": { + "name": "counter", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "credential_device_type": { + "name": "credential_device_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credential_backed_up": { + "name": "credential_backed_up", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "transports": { + "name": "transports", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "authenticators_user_id_users_id_fk": { + "name": "authenticators_user_id_users_id_fk", + "tableFrom": "authenticators", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "authenticators_credential_id_unique": { + "name": "authenticators_credential_id_unique", + "nullsNotDistinct": false, + "columns": [ + "credential_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires": { + "name": "expires", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ip": { + "name": "ip", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "sessions_token_hash_unique": { + "name": "sessions_token_hash_unique", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sessions_user_created_idx": { + "name": "sessions_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sessions_user_expires_idx": { + "name": "sessions_user_expires_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sessions_expires_idx": { + "name": "sessions_expires_idx", + "columns": [ + { + "expression": "expires", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sessions_last_seen_at_idx": { + "name": "sessions_last_seen_at_idx", + "columns": [ + { + "expression": "last_seen_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_verified": { + "name": "email_verified", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification_tokens": { + "name": "verification_tokens", + "schema": "", + "columns": { + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires": { + "name": "expires", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chats": { + "name": "chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "chat_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chats_owner_updated_idx": { + "name": "chats_owner_updated_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chats_id_owner_user_id_unique_idx": { + "name": "chats_id_owner_user_id_unique_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chats_owner_user_id_users_id_fk": { + "name": "chats_owner_user_id_users_id_fk", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "owner_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "chats_owner": { + "name": "chats_owner", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "public" + ], + "using": "owner_user_id = current_setting('app.current_user_id', true)" + } + }, + "checkConstraints": {}, + "isRLSEnabled": true + }, + "public.compactions": { + "name": "compactions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "upto_seq": { + "name": "upto_seq", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage": { + "name": "usage", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "compactions_chat_upto_seq_idx": { + "name": "compactions_chat_upto_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "upto_seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "compactions_id_chat_id_unique_idx": { + "name": "compactions_id_chat_id_unique_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "compactions_chat_id_chats_id_fk": { + "name": "compactions_chat_id_chats_id_fk", + "tableFrom": "compactions", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "compactions_parent_id_compactions_id_fk": { + "name": "compactions_parent_id_compactions_id_fk", + "tableFrom": "compactions", + "tableTo": "compactions", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "compactions_parent_id_chat_id_fk": { + "name": "compactions_parent_id_chat_id_fk", + "tableFrom": "compactions", + "tableTo": "compactions", + "columnsFrom": [ + "parent_id", + "chat_id" + ], + "columnsTo": [ + "id", + "chat_id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "compactions_owner": { + "name": "compactions_owner", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "public" + ], + "using": "chat_id IN (\n SELECT id FROM chats\n WHERE owner_user_id = current_setting('app.current_user_id', true)\n )" + } + }, + "checkConstraints": {}, + "isRLSEnabled": true + }, + "public.messages": { + "name": "messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "seq": { + "name": "seq", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "identity": { + "type": "always", + "name": "messages_seq_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "role": { + "name": "role", + "type": "message_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "sender_user_id": { + "name": "sender_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parts": { + "name": "parts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "attachments": { + "name": "attachments", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "usage": { + "name": "usage", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "in_reply_to": { + "name": "in_reply_to", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "messages_chat_created_idx": { + "name": "messages_chat_created_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_chat_seq_idx": { + "name": "messages_chat_seq_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_in_reply_to_unique_idx": { + "name": "messages_in_reply_to_unique_idx", + "columns": [ + { + "expression": "in_reply_to", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_id_chat_id_unique_idx": { + "name": "messages_id_chat_id_unique_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_chat_id_chats_id_fk": { + "name": "messages_chat_id_chats_id_fk", + "tableFrom": "messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_sender_user_id_users_id_fk": { + "name": "messages_sender_user_id_users_id_fk", + "tableFrom": "messages", + "tableTo": "users", + "columnsFrom": [ + "sender_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "messages_in_reply_to_messages_id_fk": { + "name": "messages_in_reply_to_messages_id_fk", + "tableFrom": "messages", + "tableTo": "messages", + "columnsFrom": [ + "in_reply_to" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "messages_owner": { + "name": "messages_owner", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "public" + ], + "using": "chat_id IN (\n SELECT id FROM chats\n WHERE owner_user_id = current_setting('app.current_user_id', true)\n )" + } + }, + "checkConstraints": {}, + "isRLSEnabled": true + }, + "public.run_events": { + "name": "run_events", + "schema": "", + "columns": { + "sequence": { + "name": "sequence", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "run_events_sequence_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "run_events_run_sequence_idx": { + "name": "run_events_run_sequence_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sequence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "run_events_run_id_runs_id_fk": { + "name": "run_events_run_id_runs_id_fk", + "tableFrom": "run_events", + "tableTo": "runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "run_events_owner_select": { + "name": "run_events_owner_select", + "as": "PERMISSIVE", + "for": "SELECT", + "to": [ + "public" + ], + "using": "run_id IN (\n SELECT runs.id FROM runs\n INNER JOIN chats ON chats.id = runs.chat_id\n WHERE chats.owner_user_id = current_setting('app.current_user_id', true)\n )" + }, + "run_events_owner_insert": { + "name": "run_events_owner_insert", + "as": "PERMISSIVE", + "for": "INSERT", + "to": [ + "public" + ], + "withCheck": "run_id IN (\n SELECT runs.id FROM runs\n INNER JOIN chats ON chats.id = runs.chat_id\n WHERE chats.owner_user_id = current_setting('app.current_user_id', true)\n )" + } + }, + "checkConstraints": {}, + "isRLSEnabled": true + }, + "public.runs": { + "name": "runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "worker_id": { + "name": "worker_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "runs_chat_created_idx": { + "name": "runs_chat_created_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "runs_user_status_idx": { + "name": "runs_user_status_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "runs_chat_inflight_unique": { + "name": "runs_chat_inflight_unique", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "status NOT IN ('completed', 'failed', 'cancelled', 'expired')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "runs_chat_id_chats_id_fk": { + "name": "runs_chat_id_chats_id_fk", + "tableFrom": "runs", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runs_message_id_messages_id_fk": { + "name": "runs_message_id_messages_id_fk", + "tableFrom": "runs", + "tableTo": "messages", + "columnsFrom": [ + "message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "runs_user_id_users_id_fk": { + "name": "runs_user_id_users_id_fk", + "tableFrom": "runs", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runs_chat_id_user_id_fk": { + "name": "runs_chat_id_user_id_fk", + "tableFrom": "runs", + "tableTo": "chats", + "columnsFrom": [ + "chat_id", + "user_id" + ], + "columnsTo": [ + "id", + "owner_user_id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "runs_message_id_chat_id_fk": { + "name": "runs_message_id_chat_id_fk", + "tableFrom": "runs", + "tableTo": "messages", + "columnsFrom": [ + "message_id", + "chat_id" + ], + "columnsTo": [ + "id", + "chat_id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "runs_owner": { + "name": "runs_owner", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "public" + ], + "using": "chat_id IN (\n SELECT id FROM chats\n WHERE owner_user_id = current_setting('app.current_user_id', true)\n )" + } + }, + "checkConstraints": {}, + "isRLSEnabled": true + }, + "public.prompts": { + "name": "prompts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "prompts_user_name_idx": { + "name": "prompts_user_name_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "prompts_user_id_users_id_fk": { + "name": "prompts_user_id_users_id_fk", + "tableFrom": "prompts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "prompts_owner": { + "name": "prompts_owner", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "public" + ], + "using": "user_id = current_setting('app.current_user_id', true)" + } + }, + "checkConstraints": { + "prompts_name_slug": { + "name": "prompts_name_slug", + "value": "\"prompts\".\"name\" ~ '^[A-Za-z0-9_-]{1,64}$'" + }, + "prompts_content_len": { + "name": "prompts_content_len", + "value": "char_length(\"prompts\".\"content\") BETWEEN 1 AND 8000" + } + }, + "isRLSEnabled": true + } + }, + "enums": { + "public.chat_visibility": { + "name": "chat_visibility", + "schema": "public", + "values": [ + "private", + "public" + ] + }, + "public.message_role": { + "name": "message_role", + "schema": "public", + "values": [ + "user", + "assistant", + "system", + "tool" + ] + }, + "public.run_status": { + "name": "run_status", + "schema": "public", + "values": [ + "queued", + "resolving_config", + "retrieving_context", + "planning", + "waiting_for_approval", + "running_model", + "running_tool", + "running_sandbox", + "updating_artifact", + "summarizing", + "completed", + "failed", + "cancelled", + "expired" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/api/src/db/migrations/meta/_journal.json b/apps/api/src/db/migrations/meta/_journal.json index 67395777..af95ba52 100644 --- a/apps/api/src/db/migrations/meta/_journal.json +++ b/apps/api/src/db/migrations/meta/_journal.json @@ -106,6 +106,13 @@ "when": 1783255441287, "tag": "0014_glamorous_speed_demon", "breakpoints": true + }, + { + "idx": 15, + "version": "7", + "when": 1783286931302, + "tag": "0015_futuristic_liz_osborn", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/api/src/db/schema/index.ts b/apps/api/src/db/schema/index.ts index f7358d07..883e06f4 100644 --- a/apps/api/src/db/schema/index.ts +++ b/apps/api/src/db/schema/index.ts @@ -1,2 +1,3 @@ export * from './auth'; export * from './chats'; +export * from './prompts'; diff --git a/apps/api/src/db/schema/prompts.ts b/apps/api/src/db/schema/prompts.ts new file mode 100644 index 00000000..331beb6e --- /dev/null +++ b/apps/api/src/db/schema/prompts.ts @@ -0,0 +1,67 @@ +import { InferSelectModel } from 'drizzle-orm'; +import { sql } from 'drizzle-orm'; +import { + check, + pgPolicy, + pgTable, + text, + timestamp, + uniqueIndex, + uuid, +} from 'drizzle-orm/pg-core'; + +import { users } from './auth'; + +/** + * A saved prompt template — the user's reusable prompt, inserted in the + * composer by typing `/` (roadmap v0.5 slash-commands seed). User-scoped: + * the tenant boundary, like `memories.user_id`. + * + * RLS: `prompts_owner` (`user_id = current_setting('app.current_user_id')`). + * `.enableRLS()` emits only ENABLE; the migration ALSO hand-issues + * `FORCE ROW LEVEL SECURITY` (Drizzle can't express FORCE — the documented + * pattern shared with chats/messages/memories; re-add it if regenerating). + * + * `name` is the slash trigger, so it is a slug (no whitespace/slashes) — + * `/` must be unambiguous; UNIQUE per user. Bounds are DB CHECKs + * (defense-in-depth beyond the DTO). + */ +export const PROMPT_NAME_MAX = 64; +export const PROMPT_CONTENT_MAX = 8000; + +export const prompts = pgTable( + 'prompts', + { + id: uuid('id').primaryKey().defaultRandom(), + // text — FK to users.id which is text (NextAuth convention). + userId: text('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + name: text('name').notNull(), + content: text('content').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow(), + }, + (t) => [ + // `/` must be unambiguous per user. + uniqueIndex('prompts_user_name_idx').on(t.userId, t.name), + check( + 'prompts_name_slug', + // Slug only — no whitespace/slashes, so `/` matching is exact. + sql`${t.name} ~ '^[A-Za-z0-9_-]{1,${sql.raw(String(PROMPT_NAME_MAX))}}$'`, + ), + check( + 'prompts_content_len', + sql`char_length(${t.content}) BETWEEN 1 AND ${sql.raw(String(PROMPT_CONTENT_MAX))}`, + ), + pgPolicy('prompts_owner', { + using: sql`user_id = current_setting('app.current_user_id', true)`, + }), + ], +).enableRLS(); + +export type Prompt = InferSelectModel; diff --git a/apps/web/app/(chat)/components/chat-page.tsx b/apps/web/app/(chat)/components/chat-page.tsx index 51b94326..ac9d7352 100644 --- a/apps/web/app/(chat)/components/chat-page.tsx +++ b/apps/web/app/(chat)/components/chat-page.tsx @@ -50,6 +50,7 @@ import { } from "@/lib/services/chat/queries"; import { safeRandomUUID } from "@/lib/uuid"; import { useQueryClient } from "@tanstack/react-query"; +import { usePromptMenu } from "./prompt-command-menu"; export type ChatPageProps = { chatId?: string; @@ -166,6 +167,12 @@ function ChatSessionContent({ const [input, setInput] = useState(""); const [sendError, setSendError] = useState(null); + // `/`-triggered saved-prompt menu for the composer (roadmap v0.5 slash seed). + const { onKeyDown: promptMenuKeyDown, menu: promptMenu } = usePromptMenu({ + input, + onInsert: setInput, + }); + const router = useRouter(); const queryClient = useQueryClient(); const { draftChatId, recordSentDraft, setActiveChatId, setDraftChatId } = @@ -367,11 +374,13 @@ function ChatSessionContent({
+ {promptMenu} setInput(e.target.value)} + onKeyDown={promptMenuKeyDown} placeholder="What would you like to know?" autoFocus /> diff --git a/apps/web/app/(chat)/components/prompt-command-menu.tsx b/apps/web/app/(chat)/components/prompt-command-menu.tsx new file mode 100644 index 00000000..e1ed65a9 --- /dev/null +++ b/apps/web/app/(chat)/components/prompt-command-menu.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { useEffect, useState, type KeyboardEvent, type ReactNode } from "react"; + +import { usePromptsQuery } from "@/lib/services/prompts/queries"; +import { matchingPrompts } from "@/lib/services/prompts/matching"; + +/** + * The `/`-triggered prompt menu for the composer. Returns an `onKeyDown` to pass + * to the textarea (intercepts Arrow/Enter/Escape ONLY while the menu is open — + * bare Enter selects, Shift+Enter is left alone for a newline) and the rendered + * menu (or null). Selecting a prompt replaces the composer input with its body. + */ +export function usePromptMenu({ + input, + onInsert, +}: { + input: string; + onInsert: (content: string) => void; +}): { onKeyDown: (e: KeyboardEvent) => void; menu: ReactNode } { + const { data: prompts = [] } = usePromptsQuery(); + const [highlighted, setHighlighted] = useState(0); + // Escape dismisses the menu for the CURRENT input; any edit reopens it. + const [dismissedFor, setDismissedFor] = useState(null); + + const matches = matchingPrompts(input, prompts); + const open = matches !== null && input !== dismissedFor; + const list = open ? matches : null; + + useEffect(() => { + setHighlighted(0); + }, [input]); + + const select = (content: string) => { + onInsert(content); + setDismissedFor(null); + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (!list) return; + if (e.key === "ArrowDown") { + e.preventDefault(); + setHighlighted((i) => Math.min(i + 1, list.length - 1)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setHighlighted((i) => Math.max(i - 1, 0)); + } else if (e.key === "Enter" && !e.shiftKey) { + // Only BARE Enter selects; Shift+Enter falls through to a newline. + e.preventDefault(); + const chosen = list[highlighted] ?? list[0]; + if (chosen) select(chosen.content); + } else if (e.key === "Escape") { + e.preventDefault(); + setDismissedFor(input); + } + }; + + const menu = list ? ( +
+ {list.map((prompt, i) => ( + + ))} +
+ ) : null; + + return { onKeyDown, menu }; +} diff --git a/apps/web/app/(chat)/settings/components/prompts-section.tsx b/apps/web/app/(chat)/settings/components/prompts-section.tsx new file mode 100644 index 00000000..eaf1e779 --- /dev/null +++ b/apps/web/app/(chat)/settings/components/prompts-section.tsx @@ -0,0 +1,170 @@ +"use client"; + +import { useState } from "react"; + +import { Button } from "@workspace/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@workspace/ui/components/card"; +import { Input } from "@workspace/ui/components/input"; +import { Skeleton } from "@workspace/ui/components/skeleton"; +import { Textarea } from "@workspace/ui/components/textarea"; +import { toast } from "sonner"; +import { PencilIcon, Trash2Icon } from "lucide-react"; + +import { + PROMPT_CONTENT_MAX, + useCreatePrompt, + useDeletePrompt, + usePromptsQuery, + useUpdatePrompt, +} from "@/lib/services/prompts/queries"; + +const NAME_OK = /^[A-Za-z0-9_-]+$/; + +/** + * Manage saved prompts — reusable templates inserted in the composer by typing + * `/`. Name is a slug (no spaces) so the trigger is unambiguous. + */ +export function PromptsSection() { + const { data: prompts, isLoading } = usePromptsQuery(); + const create = useCreatePrompt(); + const update = useUpdatePrompt(); + const remove = useDeletePrompt(); + + const [editingId, setEditingId] = useState(null); + const [name, setName] = useState(""); + const [content, setContent] = useState(""); + + const nameOk = NAME_OK.test(name); + const contentOk = + content.trim().length > 0 && content.length <= PROMPT_CONTENT_MAX; + const pending = create.isPending || update.isPending; + + const reset = () => { + setEditingId(null); + setName(""); + setContent(""); + }; + + const startEdit = (p: { id: string; name: string; content: string }) => { + setEditingId(p.id); + setName(p.name); + setContent(p.content); + }; + + const onSave = () => { + if (!nameOk || !contentOk) return; + const onError = () => + toast.error( + `Couldn't save "/${name}" — the name may already be taken.`, + ); + if (editingId) { + update.mutate( + { id: editingId, patch: { name, content: content.trim() } }, + { onSuccess: reset, onError }, + ); + } else { + create.mutate( + { name, content: content.trim() }, + { onSuccess: reset, onError }, + ); + } + }; + + return ( + + + Prompts + + Reusable prompt templates. Insert one in a chat by typing{" "} + /name. + + + +
+ setName(e.target.value)} + placeholder="name (e.g. summarize)" + aria-label="Prompt name" + /> + {name.length > 0 && !nameOk && ( +

+ Use letters, digits, underscore or hyphen — no spaces. +

+ )} +