initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
node_modules
Dockerfile*
docker-compose*
.dockerignore
.git
.gitignore
README.md
LICENSE
.vscode
Makefile
helm-charts
.env
.editorconfig
.idea
coverage*
+39
View File
@@ -0,0 +1,39 @@
name: Bun Fullstack V2
on:
push:
branches: [main]
pull_request:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
build_and_test:
name: Build & Test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
+48
View File
@@ -0,0 +1,48 @@
name: Release
on:
push:
branches: ['main']
tags: ['v*']
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Set up Docker Buildx
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# Log in to Docker Hub
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: shumaione
password: ${{ secrets.DOCKERHUB_TOKEN }}
# Extract metadata (tags, labels) for Docker
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: shumaione/shumai
tags: |
type=semver,pattern={{version}}
type=ref,event=branch
# Build and push Docker image
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
platforms: linux/amd64,linux/arm64
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+13
View File
@@ -0,0 +1,13 @@
node_modules
.bun
dist
out
.DS_Store
*.log
.env
.env.*
.pi/agents/
data/
*.db
*.diff
*.orig
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.bun
src/generated
src/ui/components/ui
+7
View File
@@ -0,0 +1,7 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
+305
View File
@@ -0,0 +1,305 @@
# Developer Guide
We use a pull request–based workflow for all tasks.
## Workflow
Before starting any task, create and switch to a new feature branch:
```bash
git checkout -b <branch-name>
```
Complete the task on that branch.
After finishing the work and verifying that all checks pass:
1. Stage and commit your changes.
2. Push the branch to `origin`.
3. Open a pull request using the GitHub CLI.
```bash
git add .
git commit -m "<commit-message>"
git push origin <branch-name>
gh pr create --title "<pull-request-title>" --body "<pull-request-body>"
```
---
## Commit Messages
We follow the Conventional Commits specification.
Commit messages MUST be formatted as:
```text
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
Example:
```text
feat(auth): add OAuth login support
```
The commit contains the following structural elements, to communicate intent to the consumers of your library:
1. `fix:` a commit of the type `fix` patches a bug in your codebase.
2. `feat:` a commit of the type `feat` introduces a new feature to the codebase.
3. `BREAKING CHANGE:` a footer or `!` after the type/scope introduces a breaking API change.
4. Additional types are allowed (for example: `docs:`, `refactor:`, `test:`, `chore:`).
Write commit messages in the imperative mood and keep descriptions concise and specific.
Reference:
https://www.conventionalcommits.org/en/v1.0.0/#summary
---
## Pull Request Template
```md
## Summary
Briefly describe what this PR changes and why.
## Changes
- List the main updates made in this branch.
- Include any important implementation details.
## Verification
- Describe the checks or tests you ran.
- Include relevant outputs if applicable.
## Notes
Add any additional context, caveats, or follow-up work.
```
## Submission Rules
- **Strict Requirement**: A submission is considered complete **only** when there is a single final code state in which **all** of the following pass **simultaneously**:
- `bun run lint`
- `bun run format`
- `bun run typecheck`
- `bun run test`
- **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete.
- Fixes must be iterated until **no check causes any other check to fail**.
- **Type Safety**: The use of explicit `any` is strictly forbidden and will result in lint errors. You should use `unknown` instead when the type is not known. If you absolutely must use `any` due to a limitation (e.g. interacting with an untyped 3rd party library), you must add an eslint-disable comment (e.g., `// eslint-disable-next-line @typescript-eslint/no-explicit-any`) and include a comment directly above it clearly explaining _why_ we cannot be type-safe here.
- Do **not** submit intermediate states where some checks pass and others fail, even temporarily.
- **Cleanup Requirement**: Remove all verification related files (scripts, screenshots, `verification/` folder) before submit.
## Backend Architecture
The backend is built with:
- **Runtime**: Bun
- **Framework**: Hono
- **ORM**: Prisma (with Pgvector18)
- **Database**: Pgvector18
### Layered Architecture
We follow a strict layered architecture:
1. **API Layer (`src/api`)**: Handles HTTP requests, validation, and calls Service layer. **Do not access DB directly.**, **Do not return prisma object directly in api, use dto to avoid leak**
2. **DTO Layer (`src/dtos`)**: All dtos used in api, which also used by ui for type-safty.
3. **Service Layer (`src/services`)**: Contains business logic and interacts with the Database via Prisma.
4. **Data Layer (`src/db.ts`)**: Exports the Prisma Client instance.
### Service Layer Patterns
- **Instance Methods**: Define service logic as instance methods on a class, not static methods.
- **Singleton Export**: Export a singleton instance of the service class.
```typescript
export class MyService {
async doSomething() { ... }
}
export const myService = new MyService()
```
- **Usage**: Import and use the exported instance.
```typescript
import { myService } from '../services/myService'
await myService.doSomething()
```
### Hono API Definitions
- **Route Chaining**: Always define API routes using method chaining on a Hono instance. This ensures that the type definitions for inputs and outputs are correctly inferred and preserved in the exported type.
- **Export Pattern**: Export the chained route instance as the default export.
```typescript
const app = new Hono()
const route = app
.get('/', ...)
.post('/', ...)
export default route
```
- **Type Safety**: Use `zValidator` for request validation (query, json, form) to ensure full end-to-end type safety with the Hono RPC client.
## Frontend Architecture
The frontend is built with:
- **Runtime**: Bun (Bundler & Runner)
- **Framework**: React
- **Styling**: Tailwind CSS + Shadcn UI (Components)
### Development
- **Run Dev**: `bun --hot src/index.ts` (Runs on port 3000)
## Testing
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
### Test Maintenance Rule
- **Do not delete tests** unless the feature or code being tested is permanently removed from the codebase.
- When refactoring code, you must also refactor the corresponding tests to ensure they pass with the new implementation.
- This ensures we maintain regression coverage and do not silently break features.
### Service Tests
- Located in `src/services/*.test.ts`.
- For comprehensive testing against a real database instance, we use `Testcontainers` alongside a `PrismaTestingHelper` which wraps each test within an automatic PostgreSQL transaction rollback boundary.
- All service tests must use `setupTestDbHooks()` to initialize the database boundaries for each test suite inside the `describe` block. This automatically registers `beforeEach` and `afterEach` hooks to manage transaction state.
- Import `prisma` from `@/db` directly to interact with the database in tests. The testing helper automatically proxies it.
```typescript
import { describe, it, expect } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { teamService } from './team'
describe('TeamService', () => {
setupTestDbHooks()
it('works with db', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', password: 'pw' },
})
const team = await teamService.ensureDefaultTeam()
expect(team).toBeDefined()
expect(team.name).toBe('Default Team')
})
})
```
The `bunfig.toml` is configured to run `setup-tests.ts` automatically as a preload step. This initializes the `Testcontainers` PostgreSQL instance and applies migrations before the tests begin running.
### API Tests
- Located in `src/api/*.test.ts`.
- Mock the Service layer using `vi.spyOn(service, 'method')` or `vi.mock('@/services/myService')`.
- Verify that the API calls the Service methods correctly.
```typescript
import { describe, it, expect, vi } from 'vitest'
import { teamService } from '@/services/team/team'
import app from './team'
describe('Team API', () => {
it('calls service', async () => {
const mockEnsureDefaultTeam = vi
.spyOn(teamService, 'ensureDefaultTeam')
.mockResolvedValue({ id: '1', name: 'Default Team' } as any)
// ... test logic ...
expect(mockEnsureDefaultTeam).toHaveBeenCalled()
mockEnsureDefaultTeam.mockRestore()
})
})
```
## Prisma Configuration & Migrations
- Schema: `prisma/schema.prisma`
- Generated Client: `src/generated/prisma`
- Config: `prisma.config.ts` (Required for Prisma 7+)
### Migration Workflow
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
- Production: Use `bun --bun run prisma migrate deploy` to apply pending migrations in production environments.
### Commands
- Generate Client: `bun --bun run prisma generate`
- Apply Migrations (Dev): `bun --bun run prisma migrate dev`
- Deploy Migrations (Prod): `bun --bun run prisma migrate deploy`
## ID Generation & Sorting
- **ULID Default**: All models (except key-value stores like `Setting`) must use `@default(ulid())` for the `id` field in `schema.prisma`.
```prisma
model Example {
id String @id @default(ulid())
}
```
- **No Manual Assignment**: Do not manually generate or assign ULIDs in application code (e.g., `src/services/*.ts`) for creating database records. Let Prisma handle it via the schema default.
- Exception: File names generated by `FileService` may still use `ulid()` internally, but this is separate from the database ID.
- **Sorting**: All list APIs must order results by `id` descending (`orderBy: { id: 'desc' }`) to ensure consistent, time-based sorting (since ULIDs are sortable). Do not sort by `createdAt` as it is not indexed.
## Infinite Scroll & Pagination
- **Frontend**: Use the `useInfiniteScroll` hook for all list UIs.
- Located in `src/ui/hooks/use-infinite-scroll.ts`.
- Pass a `fetchData` function that accepts `page` and `limit`.
- **Backend**:
- Most list APIs support cursor pagination using opaque tokens (via `hyrumtoken` logic) using the `paginateQuery` helper function.
- Pass `PaginationParams` containing `first` (limit) and `after` (cursor).
- The default `limit` should be **20**.
- Always use the `paginateQuery` helper function from `src/services/pagination.ts` for consistent cursor pagination.
## Temporal Workflow & Activities
We use a custom workflow engine that supports both **Local** (polling-based) and **Temporal** (production-grade) execution.
### Architecture
1. **Workflows (`src/services/workflow/workflows`)**: Orchestrate multiple activities. They must be deterministic and compatible with Temporal's V8 isolate. Use `src/services/workflow/workflow-utils.ts` for environment-aware functions like `sleep` and `getActivities`.
2. **Activities (`src/services/workflow/activities`)**: Perform the actual work (DB updates, API calls, media processing). Grouped by domain (e.g., `ai.ts`, `transcode.ts`).
3. **Executors**:
- `LocalExecutor`: Polls the database for `pending` tasks and executes them directly.
- `TemporalExecutor`: Submits tasks to a Temporal cluster.
4. **Automatic Submission**: New `WorkflowTask` records are automatically submitted to the `WorkflowService` via a Prisma Client Extension defined in `src/db.ts`.
### Temporal Workflow Patterns
- **Definition**: Define workflows as exported async functions.
```typescript
export async function myWorkflow(task: WorkflowTask): Promise<void> {
const { activityA, activityB } = getActivities()
await activityA({ ... })
await activityB({ ... })
}
```
- **Registration**: All workflows must be exported from `src/services/workflow/workflows/index.ts` for Temporal worker registration.
- **Environment Compatibility**: Always use `getActivities()` from `workflow-utils.ts` to ensure the code works in both Local and Temporal environments.
- **Activity Access**: Activities should be accessed via `getActivities()` within a workflow. Do not call services directly inside a workflow function to maintain Temporal compatibility.
### Activity Patterns
- **Location**: Defined in `src/services/workflow/activities/<domain>.ts`.
- **Export**: Export individual activity functions and re-export them in `src/services/workflow/activities/index.ts`.
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database.
## Import conventions
- When importing across layers, always use absolute paths with the `@` alias for the root of the project (e.g. `import { AssetInfo } from '@/services/asset/models'`).
- For types that have been migrated from `@/ui/api/api`, use the equivalent types from the `src/services/<domain>/models.ts` instead.
- **DTO Naming**: Do not append the `Dto` suffix to types or interfaces (e.g. use `JoinRequest` instead of `JoinRequestDto`).
+47
View File
@@ -0,0 +1,47 @@
# Stage 1: Builder
FROM oven/bun:1 AS builder
WORKDIR /app
# Copy package files
COPY package.json bun.lock ./
COPY prisma ./prisma
# Install dependencies (including devDependencies for build tools)
RUN bun install --frozen-lockfile
# Copy source code
COPY . .
# Build API and Worker
RUN bun run build.ts
# Stage 2: Runner
FROM oven/bun:1 AS runner
WORKDIR /app
# Install ffmpeg/ffprobe
COPY --from=mwader/static-ffmpeg:8.1 /ffmpeg /usr/local/bin/
COPY --from=mwader/static-ffmpeg:8.1 /ffprobe /usr/local/bin/
# Copy sharp/img from builder (they are native and already installed)
COPY --from=builder /app/node_modules/sharp ./node_modules/sharp
COPY --from=builder /app/node_modules/@img ./node_modules/@img
# Manually install temporalio packages and prisma
# These need native bindings or CLI access in the runner environment
RUN bun add @temporalio/activity @temporalio/client @temporalio/worker @temporalio/workflow && \
bun add --dev --omit peer prisma
# Copy build artifacts and prisma config
COPY --from=builder /app/dist ./
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/prisma.config.ts.prod ./prisma.config.ts
# Expose port (Bun Hono defaults to 3000)
EXPOSE 3000
# Default command: run migrations and start API server
# Can be overridden to run workers: bun worker-cli.js [domain]
CMD ["sh", "-c", "bun prisma migrate deploy && bun index.js serve"]
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bun
import { temporalWorkflow } from './src/workflow/bun-temporal-plugin'
import { bunPluginPino } from 'bun-plugin-pino'
import tailwindPlugin from 'bun-plugin-tailwind'
import { existsSync } from 'fs'
import { rm } from 'fs/promises'
import { resolve } from 'path'
console.log('\n🚀 Starting build process...\n')
const outdir = 'dist'
if (existsSync(outdir)) {
console.log(`🗑️ Cleaning previous build at ${outdir}`)
await rm(outdir, { recursive: true, force: true })
}
await Bun.build({
entrypoints: ['./src/index.ts'],
target: 'bun',
outdir: outdir,
minify: false,
plugins: [
temporalWorkflow({
bundleOptions: {
webpackConfigHook: (config) => {
if (!config.resolve) config.resolve = {}
if (!config.resolve.alias) config.resolve.alias = {}
// @ts-ignore
config.resolve.alias['@'] = resolve(process.cwd(), 'src')
return config
},
},
}),
tailwindPlugin,
bunPluginPino({ transports: ['pino-pretty'] }),
],
external: [
'@temporalio/activity',
'@temporalio/client',
'@temporalio/worker',
'@temporalio/workflow',
],
// compile: {
// outfile: 'Shumai',
// autoloadBunfig: true,
// autoloadDotenv: true,
// autoloadTsconfig: true,
// autoloadPackageJson: true,
// },
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
publicPath: '/',
})
+3937
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
[serve.static]
plugins = ["bun-plugin-tailwind"]
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/ui/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/ui/components",
"utils": "@/ui/lib/utils",
"ui": "@/ui/components/ui",
"lib": "@/ui/lib",
"hooks": "@/ui/hooks"
},
"iconLibrary": "lucide"
}
+42
View File
@@ -0,0 +1,42 @@
services:
postgres:
image: pgvector/pgvector:pg18
container_name: shumai_postgres
environment:
POSTGRES_USER: shumai
POSTGRES_PASSWORD: shumai_password
POSTGRES_DB: shumai_db
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/18/docker
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
interval: 5s
timeout: 5s
retries: 5
shumai:
image: shumaione/shumai:main
container_name: shumai_app
ports:
- '3000:3000'
volumes:
- ../../data:/app/data
environment:
# Database Configuration
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
# S3 Configuration
STORAGE_BACKEND: local
# Better Auth
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
BETTER_AUTH_URL: https://staging.shumai.one/
depends_on:
postgres:
condition: service_healthy
volumes:
postgres_data:
+113
View File
@@ -0,0 +1,113 @@
services:
# --- Shumai Application Services ---
postgres:
image: pgvector/pgvector:pg18
container_name: shumai_postgres
environment:
POSTGRES_USER: shumai
POSTGRES_PASSWORD: shumai_password
POSTGRES_DB: shumai_db
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
interval: 5s
timeout: 5s
retries: 5
shumai:
image: shumaione/shumai:latest
build: ../../
container_name: shumai_app
ports:
- '3000:3000'
volumes:
- shumai_data:/app/data
environment:
DATABASE_URL: postgres://shumai:shumai_password@postgres:5432/shumai_db?search_path=public&sslmode=disable
STORAGE_BACKEND: local
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
BETTER_AUTH_URL: http://localhost:3000
WORKFLOW_EXECUTOR: temporal
TEMPORAL_ADDRESS: temporal:7233
depends_on:
postgres:
condition: service_healthy
temporal:
condition: service_healthy
shumai-agent:
image: shumaione/shumai:latest
build: ../../
container_name: shumai_agent_worker
command: ['bun', 'index.js', 'worker', 'agent']
volumes:
- shumai_data:/app/data
environment:
DATABASE_URL: postgres://shumai:shumai_password@postgres:5432/shumai_db?search_path=public&sslmode=disable
STORAGE_BACKEND: local
WORKFLOW_EXECUTOR: temporal
TEMPORAL_ADDRESS: temporal:7233
depends_on:
postgres:
condition: service_healthy
temporal:
condition: service_healthy
shumai-transcode:
image: shumaione/shumai:latest
build: ../../
container_name: shumai_transcode_worker
command: ['bun', 'index.js', 'worker', 'transcode']
volumes:
- shumai_data:/app/data
environment:
DATABASE_URL: postgres://shumai:shumai_password@postgres:5432/shumai_db?search_path=public&sslmode=disable
STORAGE_BACKEND: local
WORKFLOW_EXECUTOR: temporal
TEMPORAL_ADDRESS: temporal:7233
depends_on:
postgres:
condition: service_healthy
temporal:
condition: service_healthy
# --- Temporal Services ---
temporal:
image: temporalio/auto-setup:latest
container_name: temporal_server
environment:
- DB=postgres12
- DB_PORT=5432
- POSTGRES_USER=shumai
- POSTGRES_PWD=shumai_password
- POSTGRES_SEEDS=postgres
- BIND_ON_IP=0.0.0.0
ports:
- '7233:7233'
healthcheck:
test: ["CMD-SHELL", "temporal operator cluster health --address localhost:7233 || temporal operator cluster health --address $$(hostname -i):7233"]
interval: 5s
timeout: 5s
start_period: 30s
retries: 10
depends_on:
postgres:
condition: service_healthy
temporal-ui:
image: temporalio/ui:latest
container_name: temporal_ui
environment:
- TEMPORAL_ADDRESS=temporal:7233
ports:
- '8080:8080'
depends_on:
temporal:
condition: service_healthy
volumes:
postgres_data:
shumai_data:
+110
View File
@@ -0,0 +1,110 @@
import js from '@eslint/js'
import prettier from 'eslint-config-prettier'
import pluginReactConfig from 'eslint-plugin-react/configs/recommended.js'
import tseslint from 'typescript-eslint'
const baseNamingConvention = [
'error',
{
selector: 'property',
modifiers: ['requiresQuotes'],
format: null,
},
{
selector: 'objectLiteralProperty',
modifiers: ['requiresQuotes'],
format: null,
},
{
selector: ['property'],
format: ['strictCamelCase', 'UPPER_CASE'],
leadingUnderscore: 'allow',
filter: {
// Allow CSS variables, common HTTP headers, library-specific names, paths, and hyphenated/numeric keys
regex:
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature)$',
match: false,
},
},
{
selector: ['parameter'],
format: ['strictCamelCase', 'StrictPascalCase'],
leadingUnderscore: 'allow',
},
{
selector: ['accessor'],
format: ['strictCamelCase'],
},
{
selector: ['classProperty'],
format: ['strictCamelCase', 'UPPER_CASE'],
leadingUnderscore: 'allow',
},
{
selector: ['typeLike'],
format: ['StrictPascalCase'],
},
{
selector: 'typeParameter',
format: ['StrictPascalCase'],
prefix: ['T'],
},
{
selector: ['function'],
format: ['strictCamelCase', 'StrictPascalCase'],
leadingUnderscore: 'allow',
},
{
selector: ['classMethod'],
format: ['strictCamelCase'],
leadingUnderscore: 'allow',
},
{
selector: ['variable'],
format: ['strictCamelCase', 'StrictPascalCase', 'UPPER_CASE'],
leadingUnderscore: 'allow',
},
]
export default tseslint.config(
{
ignores: [
'**/dist/**',
'**/node_modules/**',
'**/src/generated/**',
'**/data/**',
'**/src/ui/components/ui/**',
],
},
js.configs.recommended,
...tseslint.configs.recommended,
prettier,
{
...pluginReactConfig,
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/naming-convention': baseNamingConvention,
},
},
{
files: ['**/*.test.ts', '**/*.test.tsx'],
rules: {
'@typescript-eslint/naming-convention': baseNamingConvention.map((q) => {
if (
typeof q === 'object' &&
(q.selector === 'property' ||
(Array.isArray(q.selector) && q.selector.includes('property'))) &&
Array.isArray(q.format)
) {
return {
...q,
format: [...q.format, 'StrictPascalCase'],
}
}
return q
}),
},
},
)
+161
View File
@@ -0,0 +1,161 @@
{
"name": "shumai",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "bun run --hot src/index.ts serve",
"typecheck": "tsc --noEmit",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"test": "bun --bun vitest run",
"format": "prettier --write .",
"db:migrate": "bun run prisma migrate dev",
"db:deploy": "bun run prisma migrate deploy",
"generate-providers": "bun run scripts/generate-builtin-providers.ts",
"worker": "bun src/index.ts worker",
"build": "bun run build.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1031.0",
"@aws-sdk/s3-request-presigner": "^3.1031.0",
"@dnd-kit/dom": "^0.4.0",
"@dnd-kit/react": "^0.4.0",
"@google/genai": "^1.50.1",
"@hono/zod-validator": "^0.7.6",
"@hookform/resolvers": "^3.10.0",
"@lexical/code": "^0.42.0",
"@lexical/link": "^0.42.0",
"@lexical/list": "^0.42.0",
"@lexical/markdown": "^0.42.0",
"@lexical/react": "^0.42.0",
"@lexical/rich-text": "^0.42.0",
"@lexical/selection": "^0.42.0",
"@lexical/table": "^0.42.0",
"@lexical/utils": "^0.42.0",
"@mariozechner/pi-ai": "^0.70.2",
"@mariozechner/pi-coding-agent": "^0.70.2",
"@prisma/adapter-pg": "^7.7.0",
"@prisma/client": "^7.7.0",
"@radix-ui/react-accordion": "1.2.2",
"@radix-ui/react-alert-dialog": "1.1.4",
"@radix-ui/react-aspect-ratio": "1.1.1",
"@radix-ui/react-avatar": "1.1.2",
"@radix-ui/react-checkbox": "1.1.3",
"@radix-ui/react-collapsible": "1.1.2",
"@radix-ui/react-context-menu": "2.2.4",
"@radix-ui/react-dialog": "1.1.4",
"@radix-ui/react-dropdown-menu": "2.1.4",
"@radix-ui/react-hover-card": "1.1.4",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-menubar": "1.1.4",
"@radix-ui/react-navigation-menu": "1.2.3",
"@radix-ui/react-popover": "1.1.4",
"@radix-ui/react-progress": "1.1.1",
"@radix-ui/react-radio-group": "1.2.2",
"@radix-ui/react-scroll-area": "1.2.2",
"@radix-ui/react-select": "2.1.4",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slider": "1.2.2",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "1.1.2",
"@radix-ui/react-tabs": "1.1.2",
"@radix-ui/react-toast": "1.2.4",
"@radix-ui/react-toggle": "1.1.1",
"@radix-ui/react-toggle-group": "1.1.1",
"@radix-ui/react-tooltip": "1.1.6",
"@sinclair/typebox": "^0.34.49",
"@swc/wasm": "^1.15.33",
"@tailwindcss/vite": "^4.1.17",
"@tanstack/react-form": "^1.32.0",
"@tanstack/react-query": "5.90.10",
"@tanstack/react-router": "^1.136.8",
"@tanstack/react-table": "^8.21.3",
"@temporalio/activity": "^1.16.1",
"@temporalio/client": "^1.16.1",
"@temporalio/worker": "^1.16.1",
"@temporalio/workflow": "^1.16.1",
"@vitejs/plugin-react": "^5.1.1",
"adm-zip": "^0.5.17",
"autoprefixer": "^10.4.20",
"better-auth": "^1.6.6",
"bun": "^1.3.13",
"bun-plugin-tailwind": "^0.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "1.0.4",
"date-fns": "^4.1.0",
"dotenv-expand": "^13.0.0",
"embla-carousel-react": "8.5.1",
"extract-zip": "^2.0.1",
"hono": "^4.12.14",
"input-otp": "1.4.1",
"install": "^0.13.0",
"jittered-fractional-indexing": "^1.0.1",
"jszip": "^3.10.1",
"konva": "^10.0.12",
"lexical": "^0.42.0",
"loader-utils": "^3.3.1",
"lucide-react": "^0.454.0",
"next-themes": "^0.4.6",
"openai": "^6.34.0",
"pg": "^8.20.0",
"pino": "^10.3.1",
"pino-pretty": "^13.1.3",
"radix-ui": "^1.4.3",
"react": "19.2.0",
"react-day-picker": "^10.0.0",
"react-dom": "19.2.0",
"react-hook-form": "^7.60.0",
"react-intersection-observer": "^10.0.0",
"react-konva": "^19.2.1",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^2.1.7",
"recharts": "2.15.4",
"sharp": "^0.34.5",
"sonner": "^1.7.4",
"tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7",
"ulid": "^3.0.2",
"use-image": "^1.1.4",
"uuid": "^13.0.0",
"uuidv7": "^1.2.1",
"vaul": "^0.9.9",
"video.js": "^8.23.4",
"vite": "^7.2.2",
"zod": "^4.3.6",
"zustand": "^5.0.8"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@tailwindcss/postcss": "^4.1.9",
"@tanstack/router-cli": "^1.136.8",
"@tanstack/router-plugin": "^1.136.8",
"@testcontainers/postgresql": "^11.14.0",
"@types/adm-zip": "^0.5.8",
"@types/bun": "^1.3.12",
"@types/extract-zip": "^2.0.3",
"@types/node": "^22",
"@types/pg": "^8.20.0",
"@types/react": "^19",
"@types/react-dom": "^19",
"bun-plugin-pino": "^1.5.0",
"bun-types": "^1.3.12",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-react": "^7.37.5",
"globals": "^16.5.0",
"orval": "7.14.0",
"postcss": "^8.5",
"prisma": "^7.7.0",
"prisma-json-types-generator": "^4.1.1",
"tailwindcss": "^4.2.2",
"testcontainers": "^11.14.0",
"tw-animate-css": "1.3.3",
"typescript": "^5.9.3",
"typescript-eslint": "^8.46.4",
"unplugin-auto-import": "^21.0.0",
"vite-tsconfig-paths": "^6.1.1",
"vitest": "^4.1.4"
}
}
+98
View File
@@ -0,0 +1,98 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
'@dnd-kit/core':
specifier: ^6.3.1
version: 6.3.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@dnd-kit/utilities':
specifier: ^3.2.2
version: 3.2.2(react@19.2.3)
packages:
'@dnd-kit/accessibility@3.1.1':
resolution:
{
integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==,
}
peerDependencies:
react: '>=16.8.0'
'@dnd-kit/core@6.3.1':
resolution:
{
integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==,
}
peerDependencies:
react: '>=16.8.0'
react-dom: '>=16.8.0'
'@dnd-kit/utilities@3.2.2':
resolution:
{
integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==,
}
peerDependencies:
react: '>=16.8.0'
react-dom@19.2.3:
resolution:
{
integrity: sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==,
}
peerDependencies:
react: ^19.2.3
react@19.2.3:
resolution:
{
integrity: sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==,
}
engines: { node: '>=0.10.0' }
scheduler@0.27.0:
resolution:
{
integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==,
}
tslib@2.8.1:
resolution:
{
integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==,
}
snapshots:
'@dnd-kit/accessibility@3.1.1(react@19.2.3)':
dependencies:
react: 19.2.3
tslib: 2.8.1
'@dnd-kit/core@6.3.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@dnd-kit/accessibility': 3.1.1(react@19.2.3)
'@dnd-kit/utilities': 3.2.2(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
tslib: 2.8.1
'@dnd-kit/utilities@3.2.2(react@19.2.3)':
dependencies:
react: 19.2.3
tslib: 2.8.1
react-dom@19.2.3(react@19.2.3):
dependencies:
react: 19.2.3
scheduler: 0.27.0
react@19.2.3: {}
scheduler@0.27.0: {}
tslib@2.8.1: {}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'prisma/config'
import { loadEnvConfig } from './src/env-loader'
loadEnvConfig(process.cwd())
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: process.env.DATABASE_URL,
},
})
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: process.env.DATABASE_URL,
},
})
@@ -0,0 +1,746 @@
-- CreateExtension
CREATE EXTENSION IF NOT EXISTS "vector";
-- CreateEnum
CREATE TYPE "UserType" AS ENUM ('human', 'agent');
-- CreateEnum
CREATE TYPE "AssetType" AS ENUM ('folder', 'file', 'share', 'root', 'attachment', 'version_stack', 'share_root', 'symlink');
-- CreateEnum
CREATE TYPE "AssetStatus" AS ENUM ('uploading', 'uploaded', 'processing', 'processed', 'trashed', 'removed');
-- CreateEnum
CREATE TYPE "InviteRole" AS ENUM ('editor', 'reviewer');
-- CreateEnum
CREATE TYPE "MetadataFieldScope" AS ENUM ('SYSTEM', 'TEAM', 'PROJECT');
-- CreateEnum
CREATE TYPE "NotificationType" AS ENUM ('comment_created', 'reply_created', 'mention', 'successful_file_uploaded', 'metadata_field_updated_status', 'new_user_join_team', 'new_user_join_project');
-- CreateEnum
CREATE TYPE "ProjectMemberRole" AS ENUM ('owner', 'editor', 'reviewer');
-- CreateEnum
CREATE TYPE "TaskType" AS ENUM ('upload');
-- CreateEnum
CREATE TYPE "TaskStatus" AS ENUM ('pending', 'uploading', 'completed', 'failed');
-- CreateEnum
CREATE TYPE "TeamMemberRole" AS ENUM ('owner', 'editor', 'reviewer');
-- CreateEnum
CREATE TYPE "TeamMemberScope" AS ENUM ('team', 'project');
-- CreateEnum
CREATE TYPE "WorkflowTaskType" AS ENUM ('transcode', 'ai_metadata_autofill', 'ai_transcription', 'chat', 'ai_embedding');
-- CreateEnum
CREATE TYPE "WorkflowTaskStatus" AS ENUM ('pending', 'processing', 'completed', 'failed');
-- CreateEnum
CREATE TYPE "AgentType" AS ENUM ('chat', 'autofill', 'embedding', 'transcription');
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"type" "UserType" NOT NULL DEFAULT 'human',
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"email_verified" BOOLEAN NOT NULL DEFAULT false,
"image" TEXT,
"password" TEXT,
"agent_settings" JSONB,
"guest_email" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sessions" (
"id" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"token" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"ip_address" TEXT,
"user_agent" TEXT,
"user_id" TEXT NOT NULL,
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "accounts" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"provider_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"access_token" TEXT,
"refresh_token" TEXT,
"id_token" TEXT,
"access_token_expires_at" TIMESTAMP(3),
"refresh_token_expires_at" TIMESTAMP(3),
"scope" TEXT,
"password" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "verifications" (
"id" TEXT NOT NULL,
"identifier" TEXT NOT NULL,
"value" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3),
CONSTRAINT "verifications_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "auth_tokens" (
"id" TEXT NOT NULL,
"access_token" TEXT NOT NULL,
"refresh_token" TEXT NOT NULL,
"access_token_expires_at" TIMESTAMP(3) NOT NULL,
"refresh_token_expires_at" TIMESTAMP(3) NOT NULL,
"user_id" TEXT NOT NULL,
CONSTRAINT "auth_tokens_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "teams" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"settings" JSONB DEFAULT '{}',
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"root_folder_id" TEXT,
CONSTRAINT "teams_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "skills" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"config" JSONB DEFAULT '{}',
"asset_id" TEXT NOT NULL,
"hash" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"team_id" TEXT NOT NULL,
CONSTRAINT "skills_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "team_members" (
"id" TEXT NOT NULL,
"role" "TeamMemberRole" NOT NULL,
"scope" "TeamMemberScope" NOT NULL DEFAULT 'team',
"team_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"last_read_notification_id" TEXT,
CONSTRAINT "team_members_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "projects" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"cover_image_key" TEXT,
"metadata_overrides" JSONB,
"enable_ai_autofill" BOOLEAN NOT NULL DEFAULT false,
"enable_ai_transcription" BOOLEAN NOT NULL DEFAULT false,
"enable_notification" BOOLEAN NOT NULL DEFAULT true,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"team_id" TEXT NOT NULL,
"root_folder_id" TEXT,
"share_root_id" TEXT,
CONSTRAINT "projects_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "project_members" (
"id" TEXT NOT NULL,
"role" "ProjectMemberRole" NOT NULL,
"project_id" TEXT NOT NULL,
"team_member_id" TEXT NOT NULL,
CONSTRAINT "project_members_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "share_links" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"expire_at" TIMESTAMP(3),
"password" TEXT,
"is_disabled" BOOLEAN NOT NULL DEFAULT false,
"default_sort_order" TEXT,
"field_visibility" JSONB,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"project_id" TEXT NOT NULL,
"root_folder_id" TEXT NOT NULL,
CONSTRAINT "share_links_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "assets" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL DEFAULT '',
"name_ngram" TEXT[] DEFAULT ARRAY[]::TEXT[],
"key" TEXT,
"type" "AssetType" NOT NULL,
"media_type" TEXT,
"file_count" INTEGER NOT NULL DEFAULT 0,
"size_byte" INTEGER NOT NULL DEFAULT 0,
"status" "AssetStatus" NOT NULL,
"transcode_task_id" TEXT,
"media" JSONB,
"removed" BOOLEAN NOT NULL DEFAULT false,
"deleted_at" TIMESTAMP(3),
"sort_index" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"parent_id" TEXT,
"target_id" TEXT,
"creator_id" TEXT,
"task_id" TEXT,
"project_id" TEXT,
CONSTRAINT "assets_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_metadata_values" (
"id" TEXT NOT NULL,
"asset_id" TEXT NOT NULL,
"field_id" TEXT NOT NULL,
"string_value" TEXT,
"number_value" DOUBLE PRECISION,
"boolean_value" BOOLEAN,
"json_value" JSONB,
"date_value" TIMESTAMP(3),
CONSTRAINT "asset_metadata_values_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_comments" (
"id" TEXT NOT NULL,
"message" TEXT,
"annotation" JSONB,
"second" DOUBLE PRECISION,
"is_ai" BOOLEAN NOT NULL DEFAULT false,
"bot_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"asset_id" TEXT NOT NULL,
"creator_id" TEXT,
"reply_to_id" TEXT,
CONSTRAINT "asset_comments_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_comment_attachments" (
"id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"comment_id" TEXT NOT NULL,
"asset_id" TEXT NOT NULL,
CONSTRAINT "asset_comment_attachments_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_embeddings" (
"id" TEXT NOT NULL,
"embedding" vector(1536),
"start_time" DOUBLE PRECISION,
"end_time" DOUBLE PRECISION,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"asset_id" TEXT NOT NULL,
CONSTRAINT "asset_embeddings_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "invites" (
"id" TEXT NOT NULL,
"code" TEXT NOT NULL,
"role" "InviteRole",
"used" BOOLEAN NOT NULL DEFAULT false,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"team_id" TEXT NOT NULL,
"project_id" TEXT,
"inviter_id" TEXT NOT NULL,
CONSTRAINT "invites_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "metadata_fields" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"scope" "MetadataFieldScope",
"config" JSONB,
"read_only" BOOLEAN NOT NULL DEFAULT false,
"ai_autofill" BOOLEAN NOT NULL DEFAULT false,
"description" TEXT NOT NULL DEFAULT '',
"team_id" TEXT,
"project_id" TEXT,
CONSTRAINT "metadata_fields_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "notifications" (
"id" TEXT NOT NULL,
"type" "NotificationType",
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"team_id" TEXT NOT NULL,
"project_id" TEXT,
"creator_id" TEXT,
"asset_id" TEXT,
"task_id" TEXT,
"user_id" TEXT,
CONSTRAINT "notifications_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "system_settings" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"value" JSONB,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "system_settings_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "tasks" (
"id" TEXT NOT NULL,
"type" "TaskType",
"status" "TaskStatus" NOT NULL DEFAULT 'pending',
"name" TEXT,
"total" INTEGER,
"uploaded" INTEGER NOT NULL DEFAULT 0,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"creator_id" TEXT,
CONSTRAINT "tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "workflow_tasks" (
"id" TEXT NOT NULL,
"uid" UUID NOT NULL,
"team_id" TEXT,
"project_id" TEXT,
"asset_id" TEXT NOT NULL,
"type" "WorkflowTaskType",
"status" "WorkflowTaskStatus",
"payload" JSONB,
"output" JSONB,
"heartbeat" TIMESTAMP(3),
"input_tokens" INTEGER NOT NULL DEFAULT 0,
"output_tokens" INTEGER NOT NULL DEFAULT 0,
"model" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "workflow_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "agents" (
"id" TEXT NOT NULL,
"type" "AgentType" NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"soul" TEXT,
"provider_id" TEXT,
"model_id" TEXT,
"config" JSONB NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "agents_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "agent_skills" (
"id" TEXT NOT NULL,
"agent_id" TEXT NOT NULL,
"skill_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "agent_skills_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "agent_sessions" (
"id" TEXT NOT NULL,
"agent_id" TEXT NOT NULL,
"user_id" TEXT,
"cwd" TEXT NOT NULL,
"leaf_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "agent_sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "agent_session_entries" (
"id" TEXT NOT NULL,
"session_id" TEXT NOT NULL,
"entry" JSONB NOT NULL,
CONSTRAINT "agent_session_entries_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "user_metadata" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"value" JSONB NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"user_id" TEXT NOT NULL,
"team_id" TEXT NOT NULL,
CONSTRAINT "user_metadata_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "models" (
"id" TEXT NOT NULL,
"model_id" TEXT NOT NULL,
"name" TEXT NOT NULL DEFAULT '',
"config" JSONB NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"provider_id" TEXT NOT NULL,
CONSTRAINT "models_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "providers" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"is_builtin" BOOLEAN NOT NULL DEFAULT false,
"config" JSONB NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"team_id" TEXT NOT NULL,
CONSTRAINT "providers_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "sessions_token_key" ON "sessions"("token");
-- CreateIndex
CREATE UNIQUE INDEX "auth_tokens_access_token_key" ON "auth_tokens"("access_token");
-- CreateIndex
CREATE UNIQUE INDEX "auth_tokens_refresh_token_key" ON "auth_tokens"("refresh_token");
-- CreateIndex
CREATE UNIQUE INDEX "teams_root_folder_id_key" ON "teams"("root_folder_id");
-- CreateIndex
CREATE UNIQUE INDEX "skills_team_id_name_key" ON "skills"("team_id", "name");
-- CreateIndex
CREATE UNIQUE INDEX "team_members_last_read_notification_id_key" ON "team_members"("last_read_notification_id");
-- CreateIndex
CREATE UNIQUE INDEX "team_members_team_id_user_id_key" ON "team_members"("team_id", "user_id");
-- CreateIndex
CREATE UNIQUE INDEX "projects_root_folder_id_key" ON "projects"("root_folder_id");
-- CreateIndex
CREATE UNIQUE INDEX "projects_share_root_id_key" ON "projects"("share_root_id");
-- CreateIndex
CREATE INDEX "projects_created_at_idx" ON "projects"("created_at");
-- CreateIndex
CREATE INDEX "projects_updated_at_idx" ON "projects"("updated_at");
-- CreateIndex
CREATE UNIQUE INDEX "project_members_project_id_team_member_id_key" ON "project_members"("project_id", "team_member_id");
-- CreateIndex
CREATE UNIQUE INDEX "share_links_root_folder_id_key" ON "share_links"("root_folder_id");
-- CreateIndex
CREATE INDEX "assets_type_idx" ON "assets"("type");
-- CreateIndex
CREATE INDEX "assets_status_idx" ON "assets"("status");
-- CreateIndex
CREATE INDEX "assets_created_at_idx" ON "assets"("created_at");
-- CreateIndex
CREATE INDEX "assets_updated_at_idx" ON "assets"("updated_at");
-- CreateIndex
CREATE INDEX "assets_sort_index_idx" ON "assets"("sort_index");
-- CreateIndex
CREATE INDEX "assets_removed_idx" ON "assets"("removed");
-- CreateIndex
CREATE INDEX "assets_deleted_at_idx" ON "assets"("deleted_at");
-- CreateIndex
CREATE INDEX "assets_name_ngram_idx" ON "assets" USING GIN ("name_ngram");
-- CreateIndex
CREATE UNIQUE INDEX "assets_parent_id_target_id_key" ON "assets"("parent_id", "target_id");
-- CreateIndex
CREATE INDEX "asset_metadata_values_number_value_idx" ON "asset_metadata_values"("number_value");
-- CreateIndex
CREATE INDEX "asset_metadata_values_string_value_idx" ON "asset_metadata_values"("string_value");
-- CreateIndex
CREATE INDEX "asset_metadata_values_boolean_value_idx" ON "asset_metadata_values"("boolean_value");
-- CreateIndex
CREATE INDEX "asset_metadata_values_date_value_idx" ON "asset_metadata_values"("date_value");
-- CreateIndex
CREATE INDEX "asset_metadata_values_json_value_idx" ON "asset_metadata_values" USING GIN ("json_value");
-- CreateIndex
CREATE UNIQUE INDEX "asset_metadata_values_asset_id_field_id_key" ON "asset_metadata_values"("asset_id", "field_id");
-- CreateIndex
CREATE UNIQUE INDEX "invites_code_key" ON "invites"("code");
-- CreateIndex
CREATE UNIQUE INDEX "metadata_fields_key_key" ON "metadata_fields"("key");
-- CreateIndex
CREATE UNIQUE INDEX "system_settings_key_key" ON "system_settings"("key");
-- CreateIndex
CREATE INDEX "system_settings_key_idx" ON "system_settings"("key");
-- CreateIndex
CREATE INDEX "workflow_tasks_status_heartbeat_idx" ON "workflow_tasks"("status", "heartbeat");
-- CreateIndex
CREATE INDEX "workflow_tasks_asset_id_type_idx" ON "workflow_tasks"("asset_id", "type");
-- CreateIndex
CREATE INDEX "workflow_tasks_team_id_idx" ON "workflow_tasks"("team_id");
-- CreateIndex
CREATE INDEX "workflow_tasks_project_id_idx" ON "workflow_tasks"("project_id");
-- CreateIndex
CREATE INDEX "workflow_tasks_type_idx" ON "workflow_tasks"("type");
-- CreateIndex
CREATE UNIQUE INDEX "agent_skills_agent_id_skill_id_key" ON "agent_skills"("agent_id", "skill_id");
-- CreateIndex
CREATE INDEX "agent_session_entries_session_id_idx" ON "agent_session_entries"("session_id");
-- CreateIndex
CREATE UNIQUE INDEX "user_metadata_user_id_team_id_key_key" ON "user_metadata"("user_id", "team_id", "key");
-- CreateIndex
CREATE UNIQUE INDEX "models_provider_id_model_id_key" ON "models"("provider_id", "model_id");
-- CreateIndex
CREATE UNIQUE INDEX "providers_team_id_name_key" ON "providers"("team_id", "name");
-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "auth_tokens" ADD CONSTRAINT "auth_tokens_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "teams" ADD CONSTRAINT "teams_root_folder_id_fkey" FOREIGN KEY ("root_folder_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "skills" ADD CONSTRAINT "skills_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "team_members" ADD CONSTRAINT "team_members_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "team_members" ADD CONSTRAINT "team_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "team_members" ADD CONSTRAINT "team_members_last_read_notification_id_fkey" FOREIGN KEY ("last_read_notification_id") REFERENCES "notifications"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "projects" ADD CONSTRAINT "projects_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "projects" ADD CONSTRAINT "projects_root_folder_id_fkey" FOREIGN KEY ("root_folder_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "projects" ADD CONSTRAINT "projects_share_root_id_fkey" FOREIGN KEY ("share_root_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "project_members" ADD CONSTRAINT "project_members_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "project_members" ADD CONSTRAINT "project_members_team_member_id_fkey" FOREIGN KEY ("team_member_id") REFERENCES "team_members"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "share_links" ADD CONSTRAINT "share_links_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "share_links" ADD CONSTRAINT "share_links_root_folder_id_fkey" FOREIGN KEY ("root_folder_id") REFERENCES "assets"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_parent_id_fkey" FOREIGN KEY ("parent_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_target_id_fkey" FOREIGN KEY ("target_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_metadata_values" ADD CONSTRAINT "asset_metadata_values_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_comments" ADD CONSTRAINT "asset_comments_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_comments" ADD CONSTRAINT "asset_comments_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_comments" ADD CONSTRAINT "asset_comments_reply_to_id_fkey" FOREIGN KEY ("reply_to_id") REFERENCES "asset_comments"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_comment_attachments" ADD CONSTRAINT "asset_comment_attachments_comment_id_fkey" FOREIGN KEY ("comment_id") REFERENCES "asset_comments"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_comment_attachments" ADD CONSTRAINT "asset_comment_attachments_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_embeddings" ADD CONSTRAINT "asset_embeddings_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "invites" ADD CONSTRAINT "invites_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "invites" ADD CONSTRAINT "invites_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "invites" ADD CONSTRAINT "invites_inviter_id_fkey" FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "metadata_fields" ADD CONSTRAINT "metadata_fields_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "metadata_fields" ADD CONSTRAINT "metadata_fields_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "tasks" ADD CONSTRAINT "tasks_creator_id_fkey" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agents" ADD CONSTRAINT "agents_id_fkey" FOREIGN KEY ("id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agents" ADD CONSTRAINT "agents_provider_id_fkey" FOREIGN KEY ("provider_id") REFERENCES "providers"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agents" ADD CONSTRAINT "agents_model_id_fkey" FOREIGN KEY ("model_id") REFERENCES "models"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agent_skills" ADD CONSTRAINT "agent_skills_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "agents"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agent_skills" ADD CONSTRAINT "agent_skills_skill_id_fkey" FOREIGN KEY ("skill_id") REFERENCES "skills"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agent_sessions" ADD CONSTRAINT "agent_sessions_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "agents"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agent_sessions" ADD CONSTRAINT "agent_sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agent_session_entries" ADD CONSTRAINT "agent_session_entries_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "agent_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "user_metadata" ADD CONSTRAINT "user_metadata_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "user_metadata" ADD CONSTRAINT "user_metadata_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "models" ADD CONSTRAINT "models_provider_id_fkey" FOREIGN KEY ("provider_id") REFERENCES "providers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "providers" ADD CONSTRAINT "providers_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `bot_id` on the `asset_comments` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "asset_comments" DROP COLUMN "bot_id",
ADD COLUMN "agent_id" TEXT;
@@ -0,0 +1,10 @@
/*
Warnings:
- You are about to drop the column `enable_ai_autofill` on the `projects` table. All the data in the column will be lost.
- You are about to drop the column `enable_ai_transcription` on the `projects` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "projects" DROP COLUMN "enable_ai_autofill",
DROP COLUMN "enable_ai_transcription";
@@ -0,0 +1,8 @@
/*
Warnings:
- You are about to drop the column `agent_id` on the `asset_comments` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "asset_comments" DROP COLUMN "agent_id";
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+710
View File
@@ -0,0 +1,710 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
previewFeatures = ["postgresqlExtensions"]
}
generator json {
provider = "prisma-json-types-generator"
allowAny = false
}
datasource db {
provider = "postgresql"
extensions = [vector]
}
// ----------------------------------------------------------------------
// Enums
// ----------------------------------------------------------------------
enum UserType {
human
agent
}
enum AssetType {
folder
file
share
root
attachment
version_stack
share_root
symlink
}
enum AssetStatus {
uploading
uploaded
processing
processed
trashed
removed
}
enum InviteRole {
editor
reviewer
}
enum MetadataFieldScope {
SYSTEM
TEAM
PROJECT
}
enum NotificationType {
comment_created
reply_created
mention
successful_file_uploaded
metadata_field_updated_status
new_user_join_team
new_user_join_project
}
enum ProjectMemberRole {
owner
editor
reviewer
}
enum TaskType {
upload
}
enum TaskStatus {
pending
uploading
completed
failed
}
enum TeamMemberRole {
owner
editor
reviewer
}
enum TeamMemberScope {
team
project
}
enum WorkflowTaskType {
transcode
ai_metadata_autofill
ai_transcription
chat
ai_embedding
}
enum WorkflowTaskStatus {
pending
processing
completed
failed
}
// ----------------------------------------------------------------------
// Models
// ----------------------------------------------------------------------
model User {
id String @id @default(ulid())
type UserType @default(human)
name String
email String @unique
emailVerified Boolean @default(false) @map("email_verified")
image String?
password String?
/// [AgentSettings]
agentSettings Json? @map("agent_settings")
guestEmail String? @map("guest_email")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assets Asset[] @relation("UserToAsset")
authTokens AuthToken[] @relation("UserToAuthToken")
tasks Task[] @relation("UserToTask")
teamMembers TeamMember[] @relation("UserToTeamMember")
comments AssetComment[] @relation("UserToAssetComment")
createdInvites Invite[] @relation("UserToInvite")
createdNotifications Notification[] @relation("UserToCreatedNotification")
notifications Notification[] @relation("UserToNotification")
sessions Session[]
accounts Account[]
agent Agent?
agentSessions AgentSession[]
userMetadata UserMetadata[] @relation("UserToUserMetadata")
@@map("users")
}
model Session {
id String @id @default(ulid())
expiresAt DateTime @map("expires_at")
token String @unique
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("sessions")
}
model Account {
id String @id @default(ulid())
accountId String @map("account_id")
providerId String @map("provider_id")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String? @map("access_token")
refreshToken String? @map("refresh_token")
idToken String? @map("id_token")
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
scope String?
password String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("accounts")
}
model Verification {
id String @id @default(ulid())
identifier String
value String
expiresAt DateTime @map("expires_at")
createdAt DateTime? @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt @map("updated_at")
@@map("verifications")
}
model AuthToken {
id String @id @default(ulid())
accessToken String @unique @map("access_token")
refreshToken String @unique @map("refresh_token")
accessTokenExpiresAt DateTime @map("access_token_expires_at")
refreshTokenExpiresAt DateTime @map("refresh_token_expires_at")
userId String @map("user_id")
user User @relation("UserToAuthToken", fields: [userId], references: [id])
@@map("auth_tokens")
}
model Team {
id String @id @default(ulid())
name String
/// [Settings]
settings Json? @default("{}")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
rootFolderId String? @unique @map("root_folder_id")
rootFolder Asset? @relation("TeamToRootFolder", fields: [rootFolderId], references: [id])
members TeamMember[] @relation("TeamToTeamMember")
projects Project[] @relation("TeamToProject")
metadataFields MetadataField[] @relation("TeamToMetadataField")
invites Invite[] @relation("TeamToInvite")
notifications Notification[] @relation("TeamToNotification")
userMetadata UserMetadata[] @relation("TeamToUserMetadata")
providers Provider[] @relation("TeamToProvider")
skills Skill[] @relation("TeamToSkill")
@@map("teams")
}
model Skill {
id String @id @default(ulid())
name String
description String?
/// [SkillConfig]
config Json? @default("{}")
assetId String @map("asset_id")
hash String @map("hash")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToSkill", fields: [teamId], references: [id], onDelete: Cascade)
agentSkills AgentSkill[]
@@unique([teamId, name])
@@map("skills")
}
model TeamMember {
id String @id @default(ulid())
role TeamMemberRole
scope TeamMemberScope @default(team)
teamId String @map("team_id")
team Team @relation("TeamToTeamMember", fields: [teamId], references: [id])
userId String @map("user_id")
user User @relation("UserToTeamMember", fields: [userId], references: [id], onDelete: Cascade)
projectMembers ProjectMember[] @relation("TeamMemberToProjectMember")
lastReadNotificationId String? @unique @map("last_read_notification_id")
lastReadNotification Notification? @relation("TeamMemberToLastReadNotification", fields: [lastReadNotificationId], references: [id])
@@map("team_members")
@@unique([teamId, userId], name: "teamIdUserId")
}
model Project {
id String @id @default(ulid())
name String
coverImageKey String? @map("cover_image_key")
/// [MetadataOverrides]
metadataOverrides Json? @map("metadata_overrides")
enableNotification Boolean @default(true) @map("enable_notification")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToProject", fields: [teamId], references: [id])
rootFolderId String? @unique @map("root_folder_id")
rootFolder Asset? @relation("ProjectToRootFolder", fields: [rootFolderId], references: [id])
shareRootId String? @unique @map("share_root_id")
shareRoot Asset? @relation("ProjectToShareRoot", fields: [shareRootId], references: [id])
members ProjectMember[] @relation("ProjectToProjectMember")
assets Asset[] @relation("ProjectToAsset")
metadataFields MetadataField[] @relation("ProjectToMetadataField")
invites Invite[] @relation("ProjectToInvite")
notifications Notification[] @relation("ProjectToNotification")
shareLinks ShareLink[] @relation("ProjectToShareLink")
@@map("projects")
@@index([createdAt])
@@index([updatedAt])
}
model ProjectMember {
id String @id @default(ulid())
role ProjectMemberRole
projectId String @map("project_id")
project Project @relation("ProjectToProjectMember", fields: [projectId], references: [id])
teamMemberId String @map("team_member_id")
teamMember TeamMember @relation("TeamMemberToProjectMember", fields: [teamMemberId], references: [id])
@@map("project_members")
@@unique([projectId, teamMemberId], name: "projectIdTeamMemberId")
}
model ShareLink {
id String @id @default(ulid())
name String
expireAt DateTime? @map("expire_at")
password String?
isDisabled Boolean @default(false) @map("is_disabled")
defaultSortOrder String? @map("default_sort_order")
/// [ShareLinkFieldVisibility]
fieldVisibility Json? @map("field_visibility")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
projectId String @map("project_id")
project Project @relation("ProjectToShareLink", fields: [projectId], references: [id])
rootFolderId String @unique @map("root_folder_id")
rootFolder Asset @relation("ShareLinkToRootFolder", fields: [rootFolderId], references: [id])
@@map("share_links")
}
model Asset {
id String @id @default(ulid())
name String @default("")
nameNgram String[] @default([]) @map("name_ngram")
key String?
type AssetType
mediaType String? @map("media_type")
fileCount Int @default(0) @map("file_count")
sizeByte Int @default(0) @map("size_byte")
status AssetStatus
transcodeTaskId String? @map("transcode_task_id")
/// [MediaInfo]
media Json?
removed Boolean @default(false)
deletedAt DateTime? @map("deleted_at")
sortIndex String? @map("sort_index")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
parentId String? @map("parent_id")
parent Asset? @relation("AssetChildren", fields: [parentId], references: [id])
children Asset[] @relation("AssetChildren")
targetId String? @map("target_id")
target Asset? @relation("SymlinkTarget", fields: [targetId], references: [id], onDelete: Cascade)
symlinks Asset[] @relation("SymlinkTarget")
metadataValues AssetMetadataValue[] @relation("AssetToMetadataValues")
creatorId String? @map("creator_id")
creator User? @relation("UserToAsset", fields: [creatorId], references: [id])
taskId String? @map("task_id")
task Task? @relation("TaskToAsset", fields: [taskId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToAsset", fields: [projectId], references: [id])
comments AssetComment[] @relation("AssetToComment")
commentAttachments AssetCommentAttachment[] @relation("AssetToCommentAttachment")
notifications Notification[] @relation("AssetToNotification")
embeddings AssetEmbedding[] @relation("AssetToEmbedding")
teamRootFolder Team? @relation("TeamToRootFolder")
projectRootFolder Project? @relation("ProjectToRootFolder")
projectShareRoot Project? @relation("ProjectToShareRoot")
shareLinkRootFolder ShareLink? @relation("ShareLinkToRootFolder")
@@map("assets")
@@index([type])
@@index([status])
@@index([createdAt])
@@index([updatedAt])
@@index([sortIndex])
@@index([removed])
@@index([deletedAt])
@@index([nameNgram], type: Gin)
@@unique([parentId, targetId], name: "parentIdTargetId")
}
model AssetMetadataValue {
id String @id @default(ulid())
assetId String @map("asset_id")
fieldId String @map("field_id") // key from MetadataField
stringValue String? @map("string_value")
numberValue Float? @map("number_value")
booleanValue Boolean? @map("boolean_value")
jsonValue Json? @map("json_value")
dateValue DateTime? @map("date_value")
asset Asset @relation("AssetToMetadataValues", fields: [assetId], references: [id], onDelete: Cascade)
@@unique([assetId, fieldId])
@@index([numberValue])
@@index([stringValue])
@@index([booleanValue])
@@index([dateValue])
@@index([jsonValue], type: Gin)
@@map("asset_metadata_values")
}
model AssetComment {
id String @id @default(ulid())
message String?
/// [AnnotationList]
annotation Json?
second Float?
isAi Boolean @default(false) @map("is_ai")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assetId String @map("asset_id")
asset Asset @relation("AssetToComment", fields: [assetId], references: [id])
creatorId String? @map("creator_id")
creator User? @relation("UserToAssetComment", fields: [creatorId], references: [id])
replyToId String? @map("reply_to_id")
replyTo AssetComment? @relation("CommentReplies", fields: [replyToId], references: [id])
replies AssetComment[] @relation("CommentReplies")
attachments AssetCommentAttachment[] @relation("CommentToAttachment")
@@map("asset_comments")
}
model AssetCommentAttachment {
id String @id @default(ulid())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
commentId String @map("comment_id")
comment AssetComment @relation("CommentToAttachment", fields: [commentId], references: [id])
assetId String @map("asset_id")
asset Asset @relation("AssetToCommentAttachment", fields: [assetId], references: [id])
@@map("asset_comment_attachments")
}
model AssetEmbedding {
id String @id @default(ulid())
embedding Unsupported("vector(1536)")?
startTime Float? @map("start_time")
endTime Float? @map("end_time")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
assetId String @map("asset_id")
asset Asset @relation("AssetToEmbedding", fields: [assetId], references: [id], onDelete: Cascade)
@@map("asset_embeddings")
}
model Invite {
id String @id @default(ulid())
code String @unique
role InviteRole?
used Boolean @default(false)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToInvite", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToInvite", fields: [projectId], references: [id])
inviterId String @map("inviter_id")
inviter User @relation("UserToInvite", fields: [inviterId], references: [id])
@@map("invites")
}
model MetadataField {
id String @id @default(ulid())
key String @unique
scope MetadataFieldScope?
/// [FieldConfig]
config Json?
readOnly Boolean @default(false) @map("read_only")
aiAutofill Boolean @default(false) @map("ai_autofill")
description String @default("")
teamId String? @map("team_id")
team Team? @relation("TeamToMetadataField", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToMetadataField", fields: [projectId], references: [id])
@@map("metadata_fields")
}
model Notification {
id String @id @default(ulid())
type NotificationType?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToNotification", fields: [teamId], references: [id])
projectId String? @map("project_id")
project Project? @relation("ProjectToNotification", fields: [projectId], references: [id])
creatorId String? @map("creator_id")
creator User? @relation("UserToCreatedNotification", fields: [creatorId], references: [id])
assetId String? @map("asset_id")
asset Asset? @relation("AssetToNotification", fields: [assetId], references: [id])
taskId String? @map("task_id")
task Task? @relation("TaskToNotification", fields: [taskId], references: [id])
userId String? @map("user_id")
user User? @relation("UserToNotification", fields: [userId], references: [id])
readByMembers TeamMember? @relation("TeamMemberToLastReadNotification")
@@map("notifications")
}
model SystemSettings {
id String @id @default(ulid())
key String @unique
/// [SystemSettingsValue]
value Json?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("system_settings")
@@index([key])
}
model Task {
id String @id @default(ulid())
type TaskType?
status TaskStatus @default(pending)
name String?
total Int?
uploaded Int @default(0)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
creatorId String? @map("creator_id")
creator User? @relation("UserToTask", fields: [creatorId], references: [id])
assets Asset[] @relation("TaskToAsset")
notifications Notification[] @relation("TaskToNotification")
@@map("tasks")
}
model WorkflowTask {
id String @id @default(ulid())
uid String @default(uuid()) @db.Uuid
teamId String? @map("team_id")
projectId String? @map("project_id")
assetId String @map("asset_id")
type WorkflowTaskType?
status WorkflowTaskStatus?
/// [WorkflowTaskPayload]
payload Json?
/// [WorkflowTaskOutput]
output Json?
heartbeat DateTime?
inputTokens Int @default(0) @map("input_tokens")
outputTokens Int @default(0) @map("output_tokens")
model String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("workflow_tasks")
@@index([status, heartbeat])
@@index([assetId, type])
@@index([teamId])
@@index([projectId])
@@index([type])
}
enum AgentType {
chat
autofill
embedding
transcription
}
model Agent {
id String @id
user User @relation(fields: [id], references: [id], onDelete: Cascade)
type AgentType
enabled Boolean @default(true)
soul String? @db.Text
providerId String? @map("provider_id")
provider Provider? @relation("ProviderToAgent", fields: [providerId], references: [id], onDelete: SetNull)
modelId String? @map("model_id")
modelRef Model? @relation("ModelToAgent", fields: [modelId], references: [id], onDelete: SetNull)
/// [AgentConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
agentSessions AgentSession[]
skills AgentSkill[]
@@map("agents")
}
model AgentSkill {
id String @id @default(ulid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
skillId String @map("skill_id")
skill Skill @relation(fields: [skillId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@unique([agentId, skillId])
@@map("agent_skills")
}
model AgentSession {
id String @id @default(ulid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
userId String? @map("user_id")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
cwd String
leafId String? @map("leaf_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
entries AgentSessionEntry[]
@@map("agent_sessions")
}
model AgentSessionEntry {
id String @id // Uses ULID generated by pi-coding-agent
sessionId String @map("session_id")
session AgentSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
/// [PiSessionEntry]
entry Json
@@map("agent_session_entries")
@@index([sessionId])
}
model UserMetadata {
id String @id @default(ulid())
key String
/// [UserMetadataValue]
value Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
userId String @map("user_id")
user User @relation("UserToUserMetadata", fields: [userId], references: [id], onDelete: Cascade)
teamId String @map("team_id")
team Team @relation("TeamToUserMetadata", fields: [teamId], references: [id], onDelete: Cascade)
@@unique([userId, teamId, key], name: "userIdTeamIdKey")
@@map("user_metadata")
}
model Model {
id String @id @default(ulid())
modelId String @map("model_id")
name String @default("")
/// [ModelConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
providerId String @map("provider_id")
provider Provider @relation("ProviderToModel", fields: [providerId], references: [id], onDelete: Cascade)
agents Agent[] @relation("ModelToAgent")
@@unique([providerId, modelId])
@@map("models")
}
model Provider {
id String @id @default(ulid())
name String
isBuiltin Boolean @default(false) @map("is_builtin")
/// [ProviderConfig]
config Json
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
teamId String @map("team_id")
team Team @relation("TeamToProvider", fields: [teamId], references: [id], onDelete: Cascade)
models Model[] @relation("ProviderToModel")
agents Agent[] @relation("ProviderToAgent")
@@unique([teamId, name])
@@map("providers")
}
@@ -0,0 +1,68 @@
import { describe, it, expect } from 'vitest'
import { sortProviders, PRIORITY_PROVIDERS } from './generate-builtin-providers'
describe('generate-builtin-providers sorting', () => {
it('should sort priority providers in correct order', () => {
const entries: [string, unknown][] = [
['anthropic', {}],
['openai', {}],
['google', {}],
]
const sorted = sortProviders([...entries])
expect(sorted[0][0]).toBe('openai')
expect(sorted[1][0]).toBe('anthropic')
expect(sorted[2][0]).toBe('google')
})
it('should place priority providers before non-priority ones', () => {
const entries: [string, unknown][] = [
['unknown-provider', {}],
['openai', {}],
['anthropic', {}],
]
const sorted = sortProviders([...entries])
expect(sorted[0][0]).toBe('openai')
expect(sorted[1][0]).toBe('anthropic')
expect(sorted[2][0]).toBe('unknown-provider')
})
it('should sort non-priority providers alphabetically', () => {
const entries: [string, unknown][] = [
['zebra', {}],
['alpha', {}],
['betty', {}],
]
const sorted = sortProviders([...entries])
expect(sorted[0][0]).toBe('alpha')
expect(sorted[1][0]).toBe('betty')
expect(sorted[2][0]).toBe('zebra')
})
it('should handle complex mixed lists correctly', () => {
const entries: [string, unknown][] = [
['zai', {}],
['mistral', {}],
['openai', {}],
['alpha', {}],
['google', {}],
]
const sorted = sortProviders([...entries])
// Expected order: openai (0), google (2), mistral (6), alpha (alpha < zai), zai
expect(sorted[0][0]).toBe('openai')
expect(sorted[1][0]).toBe('google')
expect(sorted[2][0]).toBe('mistral')
expect(sorted[3][0]).toBe('alpha')
expect(sorted[4][0]).toBe('zai')
})
it('should cover all priority providers in the correct order', () => {
const entries: [string, unknown][] = PRIORITY_PROVIDERS.map((p) => [p, {}])
// Shuffle the list
const shuffled = [...entries].sort(() => Math.random() - 0.5)
const sorted = sortProviders(shuffled)
for (let i = 0; i < PRIORITY_PROVIDERS.length; i++) {
expect(sorted[i][0]).toBe(PRIORITY_PROVIDERS[i])
}
})
})
+142
View File
@@ -0,0 +1,142 @@
import * as fs from 'fs'
import * as path from 'path'
export const PRIORITY_PROVIDERS = [
'openai',
'anthropic',
'google',
'deepseek',
'groq',
'openrouter',
'mistral',
'amazon-bedrock',
]
const envMap: Record<string, string> = {
openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY',
'github-copilot': 'COPILOT_GITHUB_TOKEN',
'azure-openai-responses': 'AZURE_OPENAI_API_KEY',
deepseek: 'DEEPSEEK_API_KEY',
google: 'GEMINI_API_KEY',
'google-vertex': 'GOOGLE_CLOUD_API_KEY',
groq: 'GROQ_API_KEY',
cerebras: 'CEREBRAS_API_KEY',
xai: 'XAI_API_KEY',
openrouter: 'OPENROUTER_API_KEY',
'vercel-ai-gateway': 'AI_GATEWAY_API_KEY',
zai: 'ZAI_API_KEY',
mistral: 'MISTRAL_API_KEY',
minimax: 'MINIMAX_API_KEY',
'minimax-cn': 'MINIMAX_CN_API_KEY',
moonshotai: 'MOONSHOT_API_KEY',
'moonshotai-cn': 'MOONSHOT_API_KEY',
huggingface: 'HF_TOKEN',
fireworks: 'FIREWORKS_API_KEY',
together: 'TOGETHER_API_KEY',
opencode: 'OPENCODE_API_KEY',
'opencode-go': 'OPENCODE_API_KEY',
'kimi-coding': 'KIMI_API_KEY',
'cloudflare-workers-ai': 'CLOUDFLARE_API_KEY',
'cloudflare-ai-gateway': 'CLOUDFLARE_API_KEY',
xiaomi: 'XIAOMI_API_KEY',
'xiaomi-token-plan-cn': 'XIAOMI_TOKEN_PLAN_CN_API_KEY',
'xiaomi-token-plan-ams': 'XIAOMI_TOKEN_PLAN_AMS_API_KEY',
'xiaomi-token-plan-sgp': 'XIAOMI_TOKEN_PLAN_SGP_API_KEY',
}
export function sortProviders(entries: [string, unknown][]): [string, unknown][] {
return entries.sort(([a], [b]) => {
const indexA = PRIORITY_PROVIDERS.indexOf(a)
const indexB = PRIORITY_PROVIDERS.indexOf(b)
if (indexA !== -1 && indexB !== -1) return indexA - indexB
if (indexA !== -1) return -1
if (indexB !== -1) return 1
return a.localeCompare(b)
})
}
async function sync() {
console.log('Fetching pi models from GitHub...')
const res = await fetch(
'https://raw.githubusercontent.com/earendil-works/pi/refs/heads/main/packages/ai/src/models.generated.ts',
)
if (!res.ok) {
throw new Error(`Failed to fetch pi models: ${res.statusText}`)
}
let text = await res.text()
console.log('Parsing models...')
// Remove imports
text = text.replace(/import\s+.*?from\s+['"].*?['"];?/g, '')
// Remove 'satisfies Model<...>'
text = text.replace(/satisfies\s+Model<[^>]+>/g, '')
// Write to a temporary file to import it
const tmpPath = path.join(process.cwd(), 'scripts', 'tmp-models.ts')
fs.writeFileSync(tmpPath, text)
try {
const { MODELS } = await import(tmpPath)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const providers: Record<string, any> = {}
const sortedEntries = sortProviders(Object.entries(MODELS))
for (const [providerName, models] of sortedEntries) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const modelList = Object.values(models as Record<string, any>)
if (modelList.length === 0) continue
const firstModel = modelList[0]
providers[providerName] = {
name: providerName,
config: {
api: firstModel.api,
baseUrl: firstModel.baseUrl,
apiKey: envMap[providerName] || '',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
models: modelList.map((m: any) => ({
modelId: m.id,
name: m.name,
config: {
api: m.api,
reasoning: m.reasoning,
input: m.input,
contextWindow: m.contextWindow,
maxTokens: m.maxTokens,
cost: m.cost,
},
})),
}
}
const generatedDir = path.join(process.cwd(), 'src', 'generated')
if (!fs.existsSync(generatedDir)) {
fs.mkdirSync(generatedDir, { recursive: true })
}
const outPath = path.join(generatedDir, 'providers.generated.ts')
const outContent = `// This file is auto-generated by scripts/generate-builtin-providers.ts
// Do not edit manually - run 'bun run generate-providers' to update
import type { ProviderConfig } from '@mariozechner/pi-coding-agent'
export const builtinProviders: Record<string, ProviderConfig> = ${JSON.stringify(providers, null, 2)} as unknown as Record<string, ProviderConfig>
`
fs.writeFileSync(outPath, outContent)
console.log(`Successfully generated builtin providers: ${outPath}`)
} finally {
if (fs.existsSync(tmpPath)) {
fs.unlinkSync(tmpPath)
}
}
}
sync().catch((err) => {
console.error(err)
process.exit(1)
})
+45
View File
@@ -0,0 +1,45 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setupTestDbHooks } from '@/db-test-hooks'
import { aiChatActivity } from './agent'
import { agentExecutor } from '../executor'
vi.mock('../executor', () => ({
agentExecutor: {
chatWithAgent: vi.fn(),
},
}))
describe('Agent Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should call aiChatActivity', async () => {
vi.mocked(agentExecutor.chatWithAgent).mockResolvedValue({
text: 'AI response',
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
sessionId: 'mock-session-id',
})
await aiChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
})
expect(agentExecutor.chatWithAgent).toHaveBeenCalledWith(
't1',
'b1',
'Hi',
[],
'',
undefined,
undefined,
)
})
})
+70
View File
@@ -0,0 +1,70 @@
import { agentExecutor, AutofillField } from '../executor'
import { prisma } from '@/db'
export interface AutofillAiParams {
teamId: string
images: string[]
fields: AutofillField[]
}
export async function autofillAiActivity(params: AutofillAiParams) {
const prompt = 'Analyze the provided images and extract metadata.'
return agentExecutor.autofill(params.teamId, prompt, params.images, params.fields)
}
export interface AiChatParams {
teamId: string
agentId: string
message: string
imageUrls: string[]
projectId: string
folderId: string
agentsInstruction?: string
sessionId?: string
userId?: string
}
export async function aiChatActivity(params: AiChatParams) {
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
return agentExecutor.chatWithAgent(
params.teamId,
params.agentId,
cleanMessage,
params.imageUrls,
params.agentsInstruction || '',
params.sessionId,
params.userId,
)
}
export interface CreateCommentParams {
assetId: string
message: string
isAi?: boolean
agentId?: string | null
replyToId?: string | null
}
export async function createCommentActivity(params: CreateCommentParams) {
return prisma.assetComment.create({
data: {
assetId: params.assetId,
message: params.message,
isAi: params.isAi ?? false,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId,
},
})
}
export interface UpdateCommentParams {
commentId: string
message: string
}
export async function updateCommentActivity(params: UpdateCommentParams) {
return prisma.assetComment.update({
where: { id: params.commentId },
data: { message: params.message },
})
}
+146
View File
@@ -0,0 +1,146 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { DatabaseSessionManager } from './database-session-manager'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
},
}))
describe('DatabaseSessionManager', () => {
setupTestDbHooks()
let agentId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'Test Agent', email: 'agent@test.com', type: 'agent' },
})
await prisma.agent.create({
data: {
id: user.id,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4o' },
},
})
agentId = user.id
})
it('creates a new session in DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
const sessionId = manager.getDbSessionId()
expect(sessionId).toBeDefined()
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session).toBeDefined()
expect(session?.agentId).toBe(agentId)
})
it('persists message entries to DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'user', content: 'Hello' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(1)
// In simplified schema, type/parentId are part of the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entry = entries[0].entry as any
expect(entry.type).toBe('message')
expect(entry.message.content).toBe('Hello')
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session?.leafId).toBe(entries[0].id)
})
it('loads existing session from DB', async () => {
const manager1 = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msgId = manager1.appendMessage({ role: 'user', content: 'Message 1' } as any)
await manager1.waitForSync()
const sessionId = manager1.getDbSessionId()
const manager2 = await DatabaseSessionManager.create({ agentId, sessionId })
expect(manager2.getDbSessionId()).toBe(sessionId)
expect(manager2.getLeafId()).toBe(msgId)
const context = manager2.buildSessionContext()
expect(context.messages).toHaveLength(1)
expect(context.messages[0].content).toBe('Message 1')
})
it('re-injects image data from S3', async () => {
const session = await prisma.agentSession.create({
data: { agentId, cwd: '/tmp' },
})
const entry = {
id: 'e1',
type: 'message',
message: {
role: 'toolResult',
content: [
{ type: 'image', data: '__S3_DATA__' },
],
details: { sourceKeys: ['key1'] },
},
}
await prisma.agentSessionEntry.create({
data: {
id: entry.id,
sessionId: session.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: entry as any,
},
})
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-image-data'),
contentType: 'image/png',
})
const manager = await DatabaseSessionManager.create({ agentId, sessionId: session.id })
const context = manager.buildSessionContext()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const reInjectedMessage = context.messages[0] as any
expect(reInjectedMessage.content[0].data).toBe(Buffer.from('fake-image-data').toString('base64'))
expect(s3Service.getObject).toHaveBeenCalledWith(expect.any(String), 'key1')
})
it('handles branching', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m1Id = manager.appendMessage({ role: 'user', content: 'M1' } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'assistant', content: 'A1' } as any)
await manager.waitForSync()
// Branch from M1
manager.branch(m1Id)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m2Id = manager.appendMessage({ role: 'user', content: 'M2' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(3)
const m2Entry = entries.find((e) => e.id === m2Id)
// parentId is now inside the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((m2Entry?.entry as any).parentId).toBe(m1Id)
const context = manager.buildSessionContext()
expect(context.messages).toHaveLength(2)
expect(context.messages[0].content).toBe('M1')
expect(context.messages[1].content).toBe('M2')
})
})
+136
View File
@@ -0,0 +1,136 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class DatabaseSessionManager extends (SessionManager as any) {
private dbSessionId: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private writeQueue: Promise<any> = Promise.resolve()
private constructor(sessionId: string, cwd: string) {
super(cwd, '', undefined, false) // persist = false, we handle it manually
this.dbSessionId = sessionId
}
static async create(params: {
agentId: string
userId?: string
sessionId?: string
cwd?: string
}): Promise<DatabaseSessionManager> {
const sessionId = params.sessionId
const cwd = params.cwd || process.cwd()
if (sessionId) {
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
include: { entries: { orderBy: { id: 'asc' } } },
})
if (!session) {
throw new Error(`Session ${sessionId} not found`)
}
const manager = new DatabaseSessionManager(sessionId, session.cwd)
// Load entries into in-memory SessionManager
for (const e of session.entries) {
const entry = e.entry
// Dynamically re-inject image data if it was stripped
if (entry.type === 'message' && entry.message.role === 'toolResult') {
const msg = entry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
for (const item of msg.content) {
if (item.type === 'image' && item.data === '__S3_DATA__' && sourceKeys[keyIdx]) {
const key = sourceKeys[keyIdx]
try {
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
item.data = buffer.toString('base64')
} catch (err) {
console.error(`Failed to re-inject image data for key ${key}:`, err)
}
keyIdx++
}
}
}
}
manager._appendEntry(entry, false) // false to avoid re-saving
}
return manager
} else {
const session = await prisma.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: cwd,
},
})
return new DatabaseSessionManager(session.id, cwd)
}
}
// Override _appendEntry to save to database
// Note: we use (manager as any)._appendEntry = ... in static factory if needed,
// but since we extend it, we can just define it here.
// We need to match the signature of the base class.
protected _appendEntry(entry: SessionEntry, shouldSave = true) {
// Call super._appendEntry (which is private, so we use the prototype)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const superAppendEntry = (SessionManager.prototype as any)['_appendEntry']
superAppendEntry.call(this, entry)
if (shouldSave) {
this.saveEntryToDb(entry)
}
}
private saveEntryToDb(entry: SessionEntry) {
this.writeQueue = this.writeQueue.then(async () => {
try {
// Deep clone to avoid stripping data from the in-memory session manager
const strippedEntry = JSON.parse(JSON.stringify(entry)) as SessionEntry
// Strip image data before saving to DB
if (strippedEntry.type === 'message' && strippedEntry.message.role === 'toolResult') {
const msg = strippedEntry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
msg.content.forEach((item) => {
if (item.type === 'image' && sourceKeys[keyIdx]) {
item.data = '__S3_DATA__'
keyIdx++
}
})
}
}
await prisma.agentSessionEntry.create({
data: {
id: strippedEntry.id,
sessionId: this.dbSessionId,
entry: strippedEntry,
},
})
await prisma.agentSession.update({
where: { id: this.dbSessionId },
data: { leafId: strippedEntry.id },
})
} catch (err) {
console.error('Failed to save session entry to DB:', err)
}
})
}
async waitForSync() {
await this.writeQueue
}
getDbSessionId() {
return this.dbSessionId
}
}
+250
View File
@@ -0,0 +1,250 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { agentExecutor, type AutofillField } from './executor'
import * as piAgent from '@mariozechner/pi-coding-agent'
vi.mock('@mariozechner/pi-coding-agent', async () => {
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
return {
...actual,
createAgentSession: vi.fn(),
}
})
const mockProviderConfig: PrismaJson.ProviderConfig = {
api: 'openai-completions',
baseUrl: 'http://localhost:11434/v1',
apiKey: 'test-key',
}
const mockModelConfig: PrismaJson.ModelConfig = {
reasoning: false,
input: ['text'],
contextWindow: 1000,
maxTokens: 1000,
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
},
}
describe('AgentExecutor', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('autofills with agent', async () => {
const team = await prisma.team.create({
data: {
name: 'Autofill Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'openai',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gpt-4',
name: 'GPT-4',
providerId: provider.id,
config: mockModelConfig,
},
})
await prisma.user.create({
data: {
name: 'Autofiller',
email: `autofiller-${Date.now()}@shumai.ai`,
type: 'agent',
agent: {
create: {
type: 'autofill',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'openai',
model: 'gpt-4',
},
},
},
teamMembers: {
create: {
teamId: team.id,
role: 'reviewer',
},
},
},
})
const mockSession = {
sendUserMessage: vi.fn().mockImplementation(async () => {
// Find the tool in the session's customTools and call its execute
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const tool = (mockSession as any).customTools.find(
(t: unknown) => (t as { name: string }).name === 'autofill_metadata',
)
if (tool) {
await tool.execute('call_1', { data: 1 })
}
}),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
getLastAssistantText: vi.fn().mockReturnValue('{"data": 1}'),
state: { tools: [], systemPrompt: '', messages: [] },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customTools: [] as any[],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockImplementation(async (config: any) => {
mockSession.customTools = config.customTools
return { session: mockSession }
})
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
const resp = await agentExecutor.autofill(team.id, 'extract data', [], fields)
expect(resp.text).toBe('{"data":1}')
expect(resp.usage.inputTokens).toBe(5)
})
it('chats with bot', async () => {
const team = await prisma.team.create({
data: {
name: 'Chat Bot Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: mockModelConfig,
},
})
await prisma.user.create({
data: {
name: 'Chatter',
email: `chatter-${Date.now()}@shumai.ai`,
type: 'agent',
agent: {
create: {
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'google',
model: 'gemini',
},
},
},
teamMembers: {
create: {
teamId: team.id,
role: 'reviewer',
},
},
},
})
const mockSession = {
sendUserMessage: vi.fn().mockResolvedValue(undefined),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
getLastAssistantText: vi.fn().mockReturnValue('mock text'),
state: { tools: [], systemPrompt: '', messages: [] },
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
const resp = await agentExecutor.chat(team.id, 'hello')
expect(resp.text).toBe('mock text')
})
it('chat with instruction', async () => {
const team = await prisma.team.create({
data: {
name: 'Pirate Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini-pro',
name: 'Gemini Pro',
providerId: provider.id,
config: mockModelConfig,
},
})
const botUser = await prisma.user.create({
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: botUser.id,
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
soul: 'You are a pirate',
config: {
provider: 'google',
model: 'gemini-pro',
},
},
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
})
const mockSession = {
sendUserMessage: vi.fn().mockResolvedValue(undefined),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
state: { tools: [], systemPrompt: '', messages: [] },
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
const resp = await agentExecutor.chatWithAgent(
team.id,
agent.id,
'hello',
[],
'Talk like a pirate',
)
expect(resp.text).toBe('Arr matey!')
expect(resp.usage.inputTokens).toBe(10)
expect(resp.usage.outputTokens).toBe(20)
})
})
+328
View File
@@ -0,0 +1,328 @@
import { prisma } from '@/db'
import { logger } from '@/logger'
import { s3Service } from '@/services/s3/s3'
import { getModel, type ImageContent, type TextContent } from '@mariozechner/pi-ai'
import {
AuthStorage,
createAgentSession,
DefaultResourceLoader,
ModelRegistry,
SessionManager,
SettingsManager,
defineTool,
} from '@mariozechner/pi-coding-agent'
import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs'
import * as path from 'path'
import { DatabaseSessionManager } from './database-session-manager'
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
import { readSkillTool } from './tools/read-skill'
import { Usage } from '@/services/ai/provider/provider'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Tool = any
export interface AutofillField {
id: string
config: PrismaJson.FieldConfig
description?: string | null
}
export class AgentExecutor {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
private async getTeam(teamId: string) {
return this.prismaClient.team.findUnique({
where: { id: teamId },
})
}
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
const agent = await this.prismaClient.agent.findFirst({
where: {
type: 'chat',
enabled: true,
user: {
teamMembers: {
some: { teamId },
},
},
},
})
if (!agent) {
throw new Error('no chat agent found for team')
}
const { text, usage } = await this.chatWithAgent(teamId, agent.id, prompt, [], '')
return { text, usage }
}
async chatWithAgent(
teamId: string,
agentId: string,
prompt: string,
images: string[],
agentsInstruction: string,
sessionId?: string,
userId?: string,
tools: Tool[] = [],
): Promise<{ text: string; usage: Usage; sessionId: string }> {
const t = await this.getTeam(teamId)
if (!t) throw new Error('failed to get team')
const agent = await this.prismaClient.agent.findUnique({
where: { id: agentId },
include: {
provider: true,
modelRef: true,
},
})
if (!agent) {
throw new Error(`agent ${agentId} not found`)
}
if (!agent.provider) throw new Error('agent has no provider configured')
if (!agent.modelRef) throw new Error('agent has no model configured')
const providerName = agent.provider.name
const modelId = agent.modelRef.modelId
const agentDir = path.join(process.cwd(), '.pi', 'agents', agent.id)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
const modelRegistry = ModelRegistry.create(authStorage)
modelRegistry.getAll()
// Fetch and register the required provider from database
const dbProviders = await this.prismaClient.provider.findMany({
where: { teamId, name: providerName },
include: { models: true },
})
for (const p of dbProviders) {
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
const config = {
...p.config,
models: p.models.map((m) => ({
...m.config,
id: m.modelId,
name: m.name || m.modelId,
})),
}
modelRegistry.registerProvider(p.name, config)
}
// Setup credentials
const dbProvider = dbProviders[0]
if (dbProvider?.config.apiKey) {
authStorage.set(providerName, { type: 'api_key', key: dbProvider.config.apiKey })
}
// Fetch team skills
const teamSkills = await this.prismaClient.skill.findMany({
where: { teamId },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const model = (getModel as any)(providerName, modelId)
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
const resourceLoader = new DefaultResourceLoader({
cwd: process.cwd(),
agentDir,
settingsManager,
systemPromptOverride: () => {
let systemPrompt = '你是shumai小助手。'
if (agentsInstruction) {
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
}
const modelConfig = agent.modelRef?.config as unknown as PrismaJson.ModelConfig
if (modelConfig?.input) {
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
}
if (teamSkills.length > 0) {
systemPrompt += '\n\nAvailable Skills:\n'
for (const s of teamSkills) {
systemPrompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
}
systemPrompt +=
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
}
return systemPrompt
},
noContextFiles: true,
})
await resourceLoader.reload()
const sessionManager = await DatabaseSessionManager.create({
agentId,
userId,
sessionId,
cwd: process.cwd(),
})
const { session } = await createAgentSession({
cwd: process.cwd(),
agentDir,
authStorage,
modelRegistry,
model,
resourceLoader,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sessionManager: sessionManager as any as SessionManager,
customTools: [analyzeAssetMediaTool, readSkillTool, ...tools],
})
const content: (TextContent | ImageContent)[] = []
if (agentsInstruction) {
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
}
content.push({ type: 'text', text: prompt })
if (images && images.length > 0) {
for (const key of images) {
const { buffer, contentType } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
key,
)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: contentType,
})
}
}
try {
await session.sendUserMessage(content)
session.state.messages.forEach((msg) => {
if (msg.role === 'toolResult') {
// For tool results, log details (metadata) instead of content (which may have large images)
const logMsg = { ...msg, content: undefined }
logger.debug(logMsg, 'agent message')
} else {
logger.debug(msg, 'agent message')
}
})
const stats = session.getSessionStats()
const text = session.getLastAssistantText() || ''
if (!text) {
const lastMessage = session.messages[session.messages.length - 1]
if (lastMessage && lastMessage.role === 'assistant' && lastMessage.errorMessage) {
throw new Error(`AI error: ${lastMessage.errorMessage}`)
}
}
const usage: Usage = {
model: modelId,
inputTokens: stats.tokens.input || 0,
outputTokens: stats.tokens.output || 0,
}
await sessionManager.waitForSync()
return { text, usage, sessionId: sessionManager.getDbSessionId() }
} finally {
// Cleanup handled by agent session if needed
}
}
async autofill(
teamId: string,
prompt: string,
images: string[],
fields: AutofillField[],
): Promise<{ text: string; usage: Usage }> {
const agent = await this.prismaClient.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: {
teamMembers: {
some: { teamId },
},
},
},
})
if (!agent) {
throw new Error('no autofill agent found for team')
}
const toolSchema = fieldsToTypeBoxSchema(fields)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let capturedData: any = null
const autofillTool = defineTool({
name: 'autofill_metadata',
label: 'Autofill Metadata',
description: 'Extract metadata from the images.',
parameters: toolSchema,
execute: async (_toolCallId, params) => {
capturedData = params
return {
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
details: {},
}
},
})
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
const { usage } = await this.chatWithAgent(
teamId,
agent.id,
fullPrompt,
images,
'',
undefined,
undefined,
[autofillTool],
)
return {
text: capturedData ? JSON.stringify(capturedData) : '{}',
usage,
}
}
}
export const agentExecutor = new AgentExecutor()
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
const properties: Record<string, TSchema> = {}
for (const f of fields) {
let schema: TSchema
switch (f.config.type) {
case 'text':
case 'longText':
schema = Type.String()
break
case 'number':
case 'rating':
schema = Type.Number()
break
case 'toggle':
schema = Type.Boolean()
break
case 'select':
schema = Type.String({
enum: f.config.select?.options?.map((o) => o.id) || [],
})
break
default:
schema = Type.String()
}
if (f.description) {
schema.description = f.description
}
properties[f.id] = schema
}
return Type.Object(properties)
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest'
import { fieldsToTypeBoxSchema, type AutofillField } from './executor'
describe('fieldsToTypeBoxSchema', () => {
it('converts text fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Title', type: 'text' }, description: 'The title' },
{ id: 'f2', config: { name: 'Desc', type: 'longText' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.description).toBe('The title')
expect(schema.properties.f2.type).toBe('string')
})
it('converts numeric fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Price', type: 'number' } },
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('number')
expect(schema.properties.f2.type).toBe('number')
})
it('converts toggle fields', () => {
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('boolean')
})
it('converts select fields with enums', () => {
const fields: AutofillField[] = [
{
id: 'f1',
config: {
name: 'Status',
type: 'select',
select: {
options: [
{ id: 'opt1', displayName: 'Option 1', color: 'red' },
{ id: 'opt2', displayName: 'Option 2', color: 'blue' },
],
},
},
},
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2'])
})
it('defaults to string for unknown types', () => {
const fields: AutofillField[] = [
// @ts-ignore
{ id: 'f1', config: { name: 'Unknown', type: 'invalid' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
})
})
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeAssetMediaTool } from './analyze-asset-media'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3')
describe('analyzeAssetMediaTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should analyze media by S3 key and return image content', async () => {
// Mock S3 with WEBP magic bytes
const buffer = Buffer.from([
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'image/webp' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/test.webp' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('image/webp')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.details as any).sourceKey).toBe('assets/test.webp')
})
it('should infer mimeType from content if S3 response has generic mimeType', async () => {
// Mock S3 with MP4 magic bytes
const buffer = Buffer.from([
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'application/octet-stream' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/no-extension-but-mp4' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('video/mp4')
})
it('should return error if S3 getObject fails', async () => {
// Mock S3 failure
vi.mocked(s3Service.getObject).mockRejectedValue(new Error('S3 error'))
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/non-existent' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const textContent = (result.content[0] as any).text
expect(textContent).toContain('Error analyzing media: S3 error')
})
})
+74
View File
@@ -0,0 +1,74 @@
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import { ImageContent, TextContent } from '@mariozechner/pi-ai'
import { detectSupportedMimeType } from '@/utils/mime'
const analyzeAssetMediaSchema = Type.Object({
key: Type.String({
description:
'The S3 key of the media file to analyze. This MUST be a key obtained from the asset media info.',
}),
})
export interface MediaAnalysisDetails {
sourceKey: string
}
export const analyzeAssetMediaTool = defineTool<
typeof analyzeAssetMediaSchema,
MediaAnalysisDetails
>({
name: 'analyze_asset_media',
label: 'Analyze Asset Media',
description:
'Retrieves and views the media content (images/video) by its S3 key. The key must be obtained from the asset media info provided in the context.',
parameters: analyzeAssetMediaSchema,
execute: async (_toolCallId, params) => {
try {
const { key } = params
if (!key) {
return {
content: [{ type: 'text', text: 'S3 key is required.' }],
details: { sourceKey: '' },
}
}
const bucket = process.env.S3_BUCKET || 'shumai'
const { buffer, contentType } = await s3Service.getObject(bucket, key)
const uint8Array = new Uint8Array(buffer)
let mimeType = contentType
if (mimeType === 'application/octet-stream') {
mimeType = detectSupportedMimeType(uint8Array) || 'application/octet-stream'
}
const content: (TextContent | ImageContent)[] = [
{
type: 'image',
data: buffer.toString('base64'),
mimeType,
},
]
return {
content,
details: {
sourceKey: key,
},
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error analyzing media: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { sourceKey: params.key || '' },
}
}
},
})
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { readSkillTool } from './read-skill'
import { s3Service } from '@/services/s3/s3'
import * as fs from 'fs'
vi.mock('@/services/s3/s3')
vi.mock('fs')
vi.mock('adm-zip', () => {
return {
default: class {
extractAllTo = vi.fn()
},
}
})
describe('readSkillTool', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should return error if skill not found', async () => {
const result = await readSkillTool.execute(
'1',
{ skillId: 'non-existent' },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toContain('not found')
})
it('should read skill from cache if hash matches', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Test Skill',
assetId: 'asset1',
hash: 'match-hash',
teamId: team.id,
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'match-hash'
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
return ''
})
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
expect(s3Service.getObject).not.toHaveBeenCalled()
})
it('should download and extract skill if cache missing or hash mismatch', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'New Skill',
assetId: 'asset1',
hash: 'new-hash',
teamId: team.id,
},
})
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
key: 'skills/skill.zip',
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return false
if (path.toString().endsWith('SKILL.md')) return true
return true
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({ buffer: Buffer.from('zipdata'), contentType: 'application/zip' })
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
expect(s3Service.getObject).toHaveBeenCalled()
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
})
})
+101
View File
@@ -0,0 +1,101 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import * as path from 'path'
import * as fs from 'fs'
import AdmZip from 'adm-zip'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
})
export const readSkillTool = defineTool<typeof readSkillSchema, { skillId: string }>({
name: 'read_skill',
label: 'Read Agent Skill',
description: 'Downloads and reads an agent skill to understand how to use it.',
parameters: readSkillSchema,
execute: async (_toolCallId, params) => {
try {
const skill = await prisma.skill.findUnique({
where: { id: params.skillId },
})
if (!skill) {
return {
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
details: { skillId: params.skillId },
}
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await prisma.asset.findUnique({
where: { id: skill.assetId },
})
if (!asset || !asset.key) {
throw new Error('Skill asset not found or has no key')
}
const { buffer: zipBuffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
return {
content: [
{
type: 'text',
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
},
],
details: { skillId: params.skillId },
}
}
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
return {
content: [{ type: 'text', text: skillMdContent }],
details: { skillId: params.skillId },
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error reading skill ${params.skillId}: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { skillId: params.skillId },
}
}
},
})
+203
View File
@@ -0,0 +1,203 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { aiAutofillMedia } from './ai-autofill'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
import * as workflowUtils from '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
describe('AIAutofill Workflow', () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
extractAiMetadataActivity: Object.assign(vi.fn(), {
_activityName: 'extractAiMetadataActivity',
}),
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
_activityName: 'getProjectAutofillFieldsActivity',
}),
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
updateAssetMetadataActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetMetadataActivity',
}),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
}
beforeEach(() => {
vi.clearAllMocks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.executeActivity as any).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(_queue: string, fn: any, ...args: any[]) => {
if (typeof fn !== 'function') {
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
}
return fn(...args)
},
)
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp',
})
})
it('should process AI autofill successfully', async () => {
const task: WorkflowTask = {
id: 'task-1',
assetId: 'asset-1',
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
output: null,
payload: {},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-1-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
key: 'test.mp4',
mediaType: 'video/mp4',
project: { id: 'proj-1', teamId: 'team-1' },
})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
])
mockActivities.autofillAiActivity.mockResolvedValue({
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
})
await aiAutofillMedia(task)
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
message: '__AUTOFILL__',
isAi: true,
agentId: 'default',
})
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
metadata: [{ key: 'field-1', value: 'Extracted Value' }],
})
})
it('should use agentId from payload if provided', async () => {
const task: WorkflowTask = {
id: 'task-1',
assetId: 'asset-1',
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
output: null,
payload: { agentId: 'real-agent-id' },
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-1-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
key: 'test.mp4',
mediaType: 'video/mp4',
project: { id: 'proj-1', teamId: 'team-1' },
})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
])
mockActivities.autofillAiActivity.mockResolvedValue({
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
})
await aiAutofillMedia(task)
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
message: '__AUTOFILL__',
isAi: true,
agentId: 'real-agent-id',
})
})
it('should handle failures and update task status with error', async () => {
const task: WorkflowTask = {
id: 'task-fail',
assetId: 'asset-1',
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
output: null,
payload: {},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-fail-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
mockActivities.getAssetActivity.mockRejectedValue(new Error('Asset missing'))
await expect(aiAutofillMedia(task)).rejects.toThrow('Asset missing')
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
commentId: 'placeholder-err',
message: expect.stringContaining('failed'),
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-fail',
status: WorkflowTaskStatus.failed,
output: { error: 'Asset missing' },
})
})
})
+192
View File
@@ -0,0 +1,192 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueAgent,
TaskQueueTranscode,
} from '@/workflow/workflow-utils'
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
extractAiMetadataActivity,
getProjectAutofillFieldsActivity,
autofillAiActivity,
updateTaskUsageActivity,
updateAssetMetadataActivity,
createCommentActivity,
updateCommentActivity,
getTranscodeWorkerQueueActivity,
getAgentWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let tmpDir: string | undefined
let transcodeWorkerQueue: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown>
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__AUTOFILL__',
isAi: true,
agentId: (payload?.agentId as string) || 'default',
})
placeholderCommentId = placeholder.id
// 1. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw new Error('Asset or project not found')
}
const teamId = asset.project.teamId
const projectId = asset.project.id
// 2. Prepare Data (Images)
const isImage = asset.mediaType?.startsWith('image/') || false
// Extraction requires FFmpeg, run on Transcode worker
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: asset.key || '',
})
const { filePath } = download
tmpDir = download.tmpDir
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
assetKey: asset.key || '',
filePath,
type: 'autofill',
isImage,
})
if (generatedFiles.length === 0) {
// If no images could be extracted, we can't do much
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No images could be extracted for analysis.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 3. Get Project Autofill Fields
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
if (fields.length === 0) {
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No autofill fields defined in project.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 4. Call AI Service
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
teamId,
images: generatedFiles,
fields: fields.map((f) => ({
id: f.id,
config: f.config as unknown as PrismaJson.FieldConfig,
description: f.description,
})),
})
if (aiResult.usage) {
// Update Usage
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// 6. Update Asset Metadata
const result = JSON.parse(aiResult.text)
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
key,
value,
}))
if (metadataUpdates.length > 0) {
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
assetId: asset.id,
metadata: metadataUpdates,
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed successfully.',
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
} finally {
if (tmpDir && transcodeWorkerQueue) {
try {
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
}
}
}
export const aiAutofillWorkflow = aiAutofillMedia
+222
View File
@@ -0,0 +1,222 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { aiChat } from './ai-chat'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
import * as workflowUtils from '@/workflow/workflow-utils'
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn().mockResolvedValue(undefined),
}
})
describe('AIChat Workflow', () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
extractAiMetadataActivity: Object.assign(vi.fn(), {
_activityName: 'extractAiMetadataActivity',
}),
aiChatActivity: Object.assign(vi.fn(), { _activityName: 'aiChatActivity' }),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
}
beforeEach(() => {
vi.clearAllMocks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.executeActivity as any).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(_queue: string, fn: any, ...args: any[]) => {
if (typeof fn !== 'function') {
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
}
return fn(...args)
},
)
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
})
it('should process AI chat successfully', async () => {
const task: WorkflowTask = {
id: 'task-1',
assetId: 'asset-1',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
userCommentId: 'comment-1',
agentId: 'bot-1',
projectId: 'proj-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
key: 'test.png',
mediaType: 'image/png',
project: { teamId: 'team-1', id: 'proj-1' },
})
mockActivities.getCommentActivity.mockResolvedValue({
id: 'comment-1',
message: 'Hello AI',
})
mockActivities.createCommentActivity.mockResolvedValue({
id: 'placeholder-1',
})
mockActivities.aiChatActivity.mockResolvedValue({
text: 'Hello Human',
usage: { inputTokens: 10, outputTokens: 20, model: 'gpt-4' },
})
await aiChat(task)
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1',
status: WorkflowTaskStatus.processing,
})
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
message: '__CHAT__',
isAi: true,
agentId: 'bot-1',
replyToId: 'comment-1',
})
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
commentId: 'placeholder-1',
message: 'Hello Human',
})
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
taskId: 'task-1',
inputTokens: 10,
outputTokens: 20,
model: 'gpt-4',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1',
status: WorkflowTaskStatus.completed,
output: { sessionId: undefined },
})
})
it('should attach AI response to thread root if triggering comment is a reply', async () => {
const task: WorkflowTask = {
id: 'task-nested',
assetId: 'asset-1',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
userCommentId: 'reply-1',
agentId: 'bot-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-nested',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-1',
project: { teamId: 'team-1', id: 'proj-1' },
})
mockActivities.getCommentActivity.mockResolvedValue({
id: 'reply-1',
replyToId: 'root-comment-id',
message: 'Nested reply message',
})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-nested' })
mockActivities.aiChatActivity.mockResolvedValue({
text: 'AI response to root',
})
await aiChat(task)
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
message: '__CHAT__',
isAi: true,
agentId: 'bot-1',
replyToId: 'root-comment-id', // MUST be root, not reply-1
})
})
it('should handle failures and update placeholder with error', async () => {
const task: WorkflowTask = {
id: 'task-fail',
assetId: 'asset-1',
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
output: null,
payload: {
userCommentId: 'comment-1',
agentId: 'bot-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.createCommentActivity.mockResolvedValue({
id: 'placeholder-err',
})
mockActivities.getAssetActivity.mockRejectedValue(new Error('DB Down'))
await expect(aiChat(task)).rejects.toThrow('DB Down')
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
commentId: 'placeholder-err',
message: expect.stringContaining('error'),
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-fail',
status: WorkflowTaskStatus.failed,
output: { error: 'DB Down' },
})
})
})
+150
View File
@@ -0,0 +1,150 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@/workflow/workflow-utils'
export async function aiChat(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
getCommentActivity,
aiChatActivity,
createCommentActivity,
updateCommentActivity,
updateTaskUsageActivity,
getAgentWorkerQueueActivity,
} = getActivities()
let placeholderCommentId: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload = task.payload as any
// 1. Get User Comment
const userCommentId = payload?.userCommentId
if (!userCommentId) throw new Error('userCommentId missing in payload')
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
if (!userComment) throw new Error('User comment not found')
// 2. Create Placeholder Comment
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
isAi: true,
agentId: payload?.agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
// 3. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw new Error('Asset or project not found')
}
const teamId = asset.project.teamId
// 4. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const userCommentWithAttachments = userComment as any
if (userCommentWithAttachments?.attachments) {
for (const att of userCommentWithAttachments.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.key) {
attachmentImageUrls.push(att.asset.key)
}
}
}
let instruction = `The user is discussing an asset with ID: ${asset.id}.`
if (asset.media) {
instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}`
}
instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
// 5. Call AI Chat
let folderId = ''
if (asset.type === 'folder') {
folderId = asset.id
} else if (asset.parentId) {
folderId = asset.parentId
}
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
teamId,
agentId: payload.agentId,
message: userComment.message || '',
imageUrls: attachmentImageUrls,
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId: payload.session_id,
userId: payload.userId,
})
// 6. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
})
// Also store sessionId in comment's metadata if we had such a field,
// but for now we just return it in task status.
}
// 7. Update Usage
if (aiResult.usage) {
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
output: { sessionId: aiResult.sessionId },
})
} catch (err) {
console.error(`AiChat failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
const errorMessage =
err instanceof Error && err.message.startsWith('AI error:')
? `AI error: ${err.message.substring(9)}`
: 'Sorry, I encountered an error while processing your request.'
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: errorMessage,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const aiChatWorkflow = aiChat
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentService } from '@/services/agent/agent'
import { authzService } from '@/services/authz/authz'
import app from './agent'
vi.mock('@/services/agent/agent')
vi.mock('@/services/authz/authz')
describe('Agent API', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
describe('GET /teams/:teamId/agents', () => {
it('returns list of agents', async () => {
const mockAgents = [
{
id: 'agent1',
user: { name: 'Bot 1', image: 'avatar1' },
type: 'chat',
providerId: 'prov1',
modelId: 'model1',
soul: 'Soul',
config: {
provider: 'prov1',
model: 'model1',
thinkingLevel: 'high',
systemPrompt: 'prompt',
},
skills: [],
},
]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(agentService.listAgents).mockResolvedValue(mockAgents as any)
const res = await app.request('/teams/team1/agents', {
headers: { 'Content-Type': 'application/json' },
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
expect(data[0].name).toBe('Bot 1')
expect(data[0].providerId).toBe('prov1')
})
})
describe('POST /teams/:teamId/agents', () => {
it('creates an agent', async () => {
const mockAgent = {
id: 'agent2',
user: { name: 'New Agent', image: 'avatar2' },
type: 'chat',
providerId: 'prov1',
modelId: 'model1',
soul: 'New Soul',
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
skills: [],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(agentService.createAgent).mockResolvedValue(mockAgent as any)
const res = await app.request('/teams/team1/agents', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'New Agent',
type: 'chat',
providerId: 'prov1',
modelId: 'model1',
thinkingLevel: 'low',
systemPrompt: 'p',
soul: 'New Soul',
skills: ['skill1'],
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.name).toBe('New Agent')
expect(data.soul).toBe('New Soul')
})
it('validates request', async () => {
const res = await app.request('/teams/team1/agents', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: '',
type: 'chat',
}),
})
expect(res.status).toBe(400)
})
})
describe('PUT /teams/:teamId/agents/:agentId', () => {
it('updates an agent', async () => {
const mockAgent = {
id: 'agent1',
user: { name: 'Updated Agent', image: 'avatar1' },
type: 'autofill',
providerId: 'prov1',
modelId: 'model1',
soul: 'Updated Soul',
config: { provider: 'prov1', model: 'model1' },
skills: [],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
const res = await app.request('/teams/team1/agents/agent1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Updated Agent',
type: 'autofill',
providerId: 'prov1',
modelId: 'model1',
soul: 'Updated Soul',
skills: [],
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.name).toBe('Updated Agent')
expect(data.soul).toBe('Updated Soul')
})
})
describe('DELETE /teams/:teamId/agents/:agentId', () => {
it('deletes an agent', async () => {
const res = await app.request('/teams/team1/agents/agent1', {
method: 'DELETE',
})
expect(res.status).toBe(204)
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
})
})
})
+151
View File
@@ -0,0 +1,151 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@/services/agent/agent'
import { authzService, Permission } from '@/services/authz/authz'
import {
createAgentRequestSchema,
updateAgentRequestSchema,
AgentInfo,
AgentType,
} from '@/dtos/agent'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/agents', async (c) => {
const teamId = c.req.param('teamId')
const userReq = c.get('user')
await authzService.hasPermission({
teamId,
user: userReq,
permission: Permission.Read,
})
const agents = await agentService.listAgents({ teamId })
const res: AgentInfo[] = agents.map((agent) => {
const config = agent.config as unknown as PrismaJson.AgentConfig
return {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
}
})
return c.json(res, 200)
})
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const userReq = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user: userReq,
permission: Permission.Admin,
})
const agent = await agentService.createAgent({
teamId,
...req,
})
if (!agent) throw new Error('failed to create agent')
const config = agent.config as unknown as PrismaJson.AgentConfig
const info: AgentInfo = {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
}
return c.json(info, 200)
})
.put(
'/teams/:teamId/agents/:agentId',
zValidator('json', updateAgentRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const agentId = c.req.param('agentId')
const userReq = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user: userReq,
permission: Permission.Admin,
})
const agent = await agentService.updateAgent({
agentId,
...req,
})
const config = agent.config as unknown as PrismaJson.AgentConfig
const info: AgentInfo = {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
}
return c.json(info, 200)
},
)
.delete('/teams/:teamId/agents/:agentId', async (c) => {
const teamId = c.req.param('teamId')
const agentId = c.req.param('agentId')
const userReq = c.get('user')
await authzService.hasPermission({
teamId,
user: userReq,
permission: Permission.Admin,
})
await agentService.deleteAgent({
agentId,
})
return new Response(null, { status: 204 })
})
export default route
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import attachmentRoute from './attachment'
import { assetService } from '@/services/asset/asset'
import { AssetType } from '@/generated/prisma/client'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/api/middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'user1', name: 'Test User' } as any)
await next()
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/services/s3/s3', () => ({
s3Service: {
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
},
}))
describe('Attachment API', () => {
const app = new Hono().use('*', authMiddleware).route('/', attachmentRoute)
beforeEach(() => {
vi.restoreAllMocks()
})
it('POST /projects/:projectId/attachments', async () => {
// We only need the id for this test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.spyOn(assetService, 'createAsset').mockResolvedValue({ id: 'asset1' } as any)
const res = await app.request('/projects/project1/attachments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
fileName: 'test.txt',
contentType: 'text/plain',
size: 100,
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.id).toBe('asset1')
expect(json.uploadUrl).toBe('http://mock-s3-url')
expect(assetService.createAsset).toHaveBeenCalledWith(
expect.objectContaining({
name: 'test.txt',
type: AssetType.attachment,
projectId: 'project1',
}),
)
})
})
+48
View File
@@ -0,0 +1,48 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { postAttachmentRequestSchema } from '@/dtos/asset'
import { assetService } from '@/services/asset/asset'
import { s3Service } from '@/services/s3/s3'
import { AssetType } from '@/generated/prisma/client'
import { ulid } from 'ulid'
import { authzService, Permission } from '@/services/authz/authz'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>().post(
'/projects/:projectId/attachments',
zValidator('json', postAttachmentRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Edit,
})
const key = `attachments/${ulid()}/${req.fileName}`
const assetInfo = await assetService.createAsset({
name: req.fileName,
type: AssetType.attachment,
projectId: projectId,
key: key,
sizeByte: req.size,
contentType: req.contentType,
creatorId: user.id,
})
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
return c.json({
id: assetInfo.id,
uploadUrl: uploadUrl,
})
},
)
export default route
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import authnRoute from './authn'
import { teamService } from '@/services/team/team'
describe('authn api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockGetSignupInfo: any
beforeEach(() => {
mockGetSignupInfo = vi.spyOn(teamService, 'getSignupInfo')
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /signup-info', async () => {
mockGetSignupInfo.mockResolvedValue({
userCount: 5,
enablePublicSignup: true,
})
const app = new Hono().route('/', authnRoute)
const res = await app.request('/signup-info')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
userCount: 5,
enablePublicSignup: true,
})
})
})
+49
View File
@@ -0,0 +1,49 @@
import { Hono } from 'hono'
import { teamService } from '@/services/team/team'
import { auth } from '@/services/auth/auth'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { prisma } from '@/db'
import { ulid } from 'ulid'
const app = new Hono()
const identifySchema = z.object({
username: z.string().min(1),
email: z.string().email(),
})
const route = app
.get('/signup-info', async (c) => {
const info = await teamService.getSignupInfo()
return c.json({
userCount: info.userCount,
enablePublicSignup: info.enablePublicSignup,
})
})
.get('/me', async (c) => {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
return c.json({ id: session?.user?.id ?? null })
})
.post('/identify', zValidator('json', identifySchema), async (c) => {
const { username, email } = c.req.valid('json')
const dummyEmail = `guest_${ulid()}@guest.local`
const user = await prisma.user.create({
data: {
name: username,
email: dummyEmail,
guestEmail: email,
type: 'human',
},
})
return c.json({ id: user.id })
})
.all('/auth/*', (c) => {
return auth.handler(c.req.raw)
})
export default route
+307
View File
@@ -0,0 +1,307 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import fileRoute from './file'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification'
import { s3Service } from '@/services/s3/s3'
import { authzService } from '@/services/authz/authz'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('file api', () => {
beforeEach(() => {
vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
vi.spyOn(assetService, 'getComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/files/:fileId', async () => {
vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id',
name: 'test-file',
sizeByte: 10,
fileCount: 1,
type: 'file',
status: 'active',
mediaType: 'image/jpeg',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('test-file')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
})
it('PUT /teams/:teamId/files/:fileId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id',
name: 'new-name',
sizeByte: 10,
fileCount: 1,
type: 'file',
status: 'active',
mediaType: 'image/jpeg',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-name' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
})
it('DELETE /teams/:teamId/files', async () => {
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }),
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
})
it('POST /teams/:teamId/files/restore', async () => {
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }),
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
})
it('POST /teams/:teamId/files/:fileId/comments', async () => {
vi.mocked(assetService.createComment).mockResolvedValue({
id: 'comment-id',
assetId: 'test-id',
message: 'hello',
annotations: null,
creator: { id: 'user1', name: 'user-name' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
isAi: false,
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
})
expect(res.status).toBe(201)
const json = await res.json()
expect(json.message).toBe('hello')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
expect(notificationService.create).toHaveBeenCalledWith({
type: 'comment_created',
teamId: 'test-team',
creatorId: 'user1',
assetId: 'test-id',
commentMessage: 'hello',
})
})
it('GET /teams/:teamId/files/:fileId/comments', async () => {
vi.mocked(assetService.listComments).mockResolvedValue({
data: [
{
id: 'comment-id',
assetId: 'test-id',
message: 'hello',
annotations: null,
creator: { id: 'user1', name: 'user-name' },
replies: [],
attachments: [],
mentions: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
isAi: false,
},
],
pageInfo: { cursor: 'cursor', total: 1 },
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/comments')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.data[0].message).toBe('hello')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
})
it('POST /teams/:teamId/files', async () => {
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
const formData = new FormData()
const file = new File(['test content'], 'test.jpg', { type: 'image/jpeg' })
formData.append('file', file)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files', {
method: 'POST',
body: formData,
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.key).toMatch(/^files\//)
expect(authzService.hasPermission).toHaveBeenCalledWith({
teamId: 'test-team',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
expect(s3Service.putObject).toHaveBeenCalled()
})
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/metadata', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(notificationService.create).toHaveBeenCalledWith({
type: 'metadata_field_updated_status',
teamId: 'test-team',
creatorId: 'user1',
assetId: 'test-id',
})
})
it('PATCH /teams/:teamId/files/:fileId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id',
name: 'test-file',
sizeByte: 10,
fileCount: 1,
type: 'file',
status: 'active',
mediaType: 'image/jpeg',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
const res = await app.request('/teams/test-team/files/test-id/order', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ beforeIndex: 'index-1' }),
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
beforeIndex: 'index-1',
})
})
})
+231
View File
@@ -0,0 +1,231 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
import { notificationService } from '@/services/notification/notification'
import { s3Service } from '@/services/s3/s3'
import {
updateFileRequestSchema,
updateAssetOrderRequestSchema,
deleteFilesRequestSchema,
restoreFilesRequestSchema,
createCommentRequestSchema,
uploadFileRequestSchema,
} from '@/dtos/asset'
import { updateAssetMetadataRequestSchema } from '@/dtos/metadata'
import { paginationParamsSchema } from '@/dtos/pagination'
import { ulid } from 'ulid'
import { z } from 'zod'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/files/:fileId', async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Read,
})
const asset = await assetService.getAsset({ assetId: fileId })
return c.json(asset)
})
.patch(
'/teams/:teamId/files/:fileId/order',
zValidator('json', updateAssetOrderRequestSchema),
async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Edit,
})
const updated = await assetService.updateAssetOrder(fileId, req)
return c.json(updated)
},
)
.put('/teams/:teamId/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Edit,
})
const updatedAsset = await assetService.updateAssetName({
id: fileId,
name: req.name,
})
return c.json(updatedAsset)
})
.delete('/teams/:teamId/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({
assetId: id,
user,
permission: Permission.Edit,
})
}
await assetService.deleteAssets(req.ids)
return c.body(null, 204)
})
.patch(
'/teams/:teamId/files/:fileId/metadata',
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Edit,
})
await metadataService.updateAssetMetadata(fileId, req)
const hasStatus = req.some((m) => m.key === 'status')
if (hasStatus) {
notificationService.create({
type: 'metadata_field_updated_status',
teamId,
creatorId: user.id,
assetId: fileId,
})
}
return c.json('')
},
)
.post(
'/teams/:teamId/files/:fileId/comments',
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Read,
})
const comment = await assetService.createComment({
assetId: fileId,
userId: user.id,
replyToId: req.replyToId,
message: req.message,
annotations: req.annotations,
second: req.second,
attachmentIds: req.attachmentIds,
})
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
notificationService.create({
type: notifType,
teamId,
creatorId: user.id,
assetId: fileId,
commentMessage: req.message,
})
return c.json(comment, 201)
},
)
.get(
'/teams/:teamId/files/:fileId/comments',
zValidator('query', paginationParamsSchema),
async (c) => {
const fileId = c.req.param('fileId')
const user = c.get('user')
const req = c.req.valid('query')
await authzService.hasPermission({
assetId: fileId,
user,
permission: Permission.Read,
})
const comments = await assetService.listComments(fileId, req)
return c.json(comments)
},
)
.get('/teams/:teamId/comments/:commentId', async (c) => {
const commentId = c.req.param('commentId')
const user = c.get('user')
const comment = await assetService.getComment(commentId)
await authzService.hasPermission({
assetId: comment.assetId,
user,
permission: Permission.Read,
})
return c.json(comment)
})
.post(
'/teams/:teamId/files/restore',
zValidator('json', restoreFilesRequestSchema),
async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({
assetId: id,
user,
permission: Permission.Edit,
})
}
await assetService.restoreAssets(req.ids)
return c.body(null, 204)
},
)
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const { file } = c.req.valid('form')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
if (file.size > 10 * 1024 * 1024) {
return c.json('file too large, max 10MB', 400)
}
const key = `files/${ulid()}`
const buffer = Buffer.from(await file.arrayBuffer())
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', key, buffer, file.size, file.type)
return c.json({ key })
})
export default route
+278
View File
@@ -0,0 +1,278 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import folderRoute from './folder'
import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search'
import { authzService } from '@/services/authz/authz'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('folder api', () => {
beforeEach(() => {
vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/folders/:folderId', async () => {
vi.mocked(assetService.getAsset).mockResolvedValue({
id: 'test-id',
name: 'test-folder',
sizeByte: 10,
fileCount: 1,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('test-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
})
it('PUT /teams/:teamId/folders/:folderId', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValue({
id: 'test-id',
name: 'new-name',
sizeByte: 10,
fileCount: 1,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-name' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-name')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
})
it('POST /teams/:teamId/folders', async () => {
vi.mocked(assetService.createAsset).mockResolvedValue({
id: 'new-id',
name: 'new-folder',
sizeByte: 0,
fileCount: 0,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('new-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'parent-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
})
it('GET /teams/:teamId/folders/:folderId/children', async () => {
vi.mocked(assetService.listChildren).mockResolvedValue({
data: [
{
id: 'child-id',
name: 'child-folder',
sizeByte: 0,
fileCount: 0,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
pageInfo: { total: 1, cursor: '' },
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/children?assetType=folder')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.data[0].name).toBe('child-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
})
it('DELETE /teams/:teamId/folders', async () => {
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }),
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
})
it('POST /teams/:teamId/folders/restore', async () => {
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: ['test-id'] }),
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
})
it('POST /teams/:teamId/folders/:folderId/search', async () => {
vi.mocked(searchService.search).mockResolvedValue({
data: [
{
id: 'result-id',
name: 'result-folder',
sizeByte: 0,
fileCount: 0,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
pageInfo: { total: 1, cursor: '' },
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
conditions: [{ field: 'name', operator: 'eq', value: 'result-folder' }],
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.data[0].name).toBe('result-folder')
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Read',
})
})
it('PATCH /teams/:teamId/folders/:folderId/order', async () => {
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
id: 'test-id',
name: 'test-folder',
sizeByte: 10,
fileCount: 1,
type: 'folder',
status: 'active',
mediaType: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
const res = await app.request('/teams/test-team/folders/test-id/order', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ beforeIndex: 'index-1' }),
})
expect(res.status).toBe(200)
expect(authzService.hasPermission).toHaveBeenCalledWith({
assetId: 'test-id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
beforeIndex: 'index-1',
})
})
})
+167
View File
@@ -0,0 +1,167 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset'
import { searchService } from '@/services/search/search'
import {
createFolderRequestSchema,
updateFolderRequestSchema,
deleteFoldersRequestSchema,
restoreFoldersRequestSchema,
} from '@/dtos/folder'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@/dtos/asset'
import { searchRequestSchema } from '@/dtos/search'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/folders', zValidator('json', createFolderRequestSchema), async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: req.parentId,
user,
permission: Permission.Edit,
})
const newAsset = await assetService.createAsset({
name: req.name,
parentId: req.parentId,
type: 'folder',
})
return c.json(newAsset)
})
.patch(
'/teams/:teamId/folders/:folderId/order',
zValidator('json', updateAssetOrderRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: folderId,
user,
permission: Permission.Edit,
})
const updated = await assetService.updateAssetOrder(folderId, req)
return c.json(updated)
},
)
.put(
'/teams/:teamId/folders/:folderId',
zValidator('json', updateFolderRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: folderId,
user,
permission: Permission.Edit,
})
const updatedAsset = await assetService.updateAssetName({
id: folderId,
name: req.name,
})
return c.json(updatedAsset)
},
)
.get('/teams/:teamId/folders/:folderId', async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
await authzService.hasPermission({
assetId: folderId,
user,
permission: Permission.Read,
})
const assetInfo = await assetService.getAsset({ assetId: folderId })
return c.json(assetInfo)
})
.get(
'/teams/:teamId/folders/:folderId/children',
zValidator('query', listChildrenRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('query')
await authzService.hasPermission({
assetId: folderId,
user,
permission: Permission.Read,
})
const resp = await assetService.listChildren({
assetId: folderId,
assetType: req.assetType,
sort: req.sort,
order: req.order,
})
return c.json(resp)
},
)
.delete('/teams/:teamId/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({
assetId: id,
user,
permission: Permission.Edit,
})
}
await assetService.deleteAssets(req.ids)
return c.body(null, 204)
})
.post(
'/teams/:teamId/folders/restore',
zValidator('json', restoreFoldersRequestSchema),
async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
for (const id of req.ids) {
await authzService.hasPermission({
assetId: id,
user,
permission: Permission.Edit,
})
}
await assetService.restoreAssets(req.ids)
return c.body(null, 204)
},
)
.post(
'/teams/:teamId/folders/:folderId/search',
zValidator('json', searchRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
assetId: folderId,
user,
permission: Permission.Read,
})
const result = await searchService.search(folderId, req)
return c.json(result)
},
)
export default route
+185
View File
@@ -0,0 +1,185 @@
import { describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import inviteRoute from './invite'
import publicInviteRoute from './public-invite'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/invite/invite', () => ({
inviteService: {
createTeamInvite: vi.fn(),
createProjectInvite: vi.fn(),
getInvite: vi.fn(),
consumeInvite: vi.fn(),
},
}))
vi.mock('@/services/notification/notification', () => ({
notificationService: {
create: vi.fn(),
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'u1', name: 'Test User' } as any)
await next()
},
}))
const getApp = () => {
const app = new Hono()
.route('/', publicInviteRoute)
.use('*', authMiddleware)
.route('/', inviteRoute)
return app
}
describe('Invite API', () => {
it('GET /invite/:code', async () => {
const app = getApp()
const { inviteService } = await import('@/services/invite/invite')
vi.mocked(inviteService.getInvite).mockResolvedValue({
code: 'code123',
teamId: 't1',
team: { name: 'My Team' },
inviter: { name: 'Inviter' },
role: 'editor',
used: false,
} as never)
const res = await app.request('/invite/code123')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
code: 'code123',
role: 'editor',
teamId: 't1',
teamName: 'My Team',
inviterName: 'Inviter',
isUsed: false,
})
})
it('POST /teams/:teamId/invite', async () => {
const app = getApp()
const { authzService } = await import('@/services/authz/authz')
const { inviteService } = await import('@/services/invite/invite')
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
code: 'test-code',
role: 'editor',
teamId: 't1',
team: { name: 'Team A' },
inviter: { name: 'Inviter' },
used: false,
} as never)
const res = await app.request('/teams/t1/invite', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer fake',
},
body: JSON.stringify({ role: 'editor' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
code: 'test-code',
role: 'editor',
teamId: 't1',
teamName: 'Team A',
inviterName: 'Inviter',
isUsed: false,
})
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
teamId: 't1',
role: 'editor',
inviterId: 'u1',
})
})
it('POST /projects/:projectId/invite', async () => {
const app = getApp()
const { authzService } = await import('@/services/authz/authz')
const { inviteService } = await import('@/services/invite/invite')
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
code: 'proj-code',
role: 'reviewer',
teamId: 't1',
team: { name: 'Team A' },
project: { id: 'p1', name: 'Project A' },
inviter: { name: 'Inviter' },
used: false,
} as never)
const res = await app.request('/projects/p1/invite', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer fake',
},
body: JSON.stringify({ role: 'reviewer' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
code: 'proj-code',
role: 'reviewer',
teamId: 't1',
teamName: 'Team A',
projectId: 'p1',
projectName: 'Project A',
inviterName: 'Inviter',
isUsed: false,
})
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
projectId: 'p1',
role: 'reviewer',
inviterId: 'u1',
})
})
it('POST /join (Team)', async () => {
const app = getApp()
const { inviteService } = await import('@/services/invite/invite')
const { notificationService } = await import('@/services/notification/notification')
vi.mocked(notificationService.create).mockResolvedValue(undefined as never)
vi.mocked(inviteService.getInvite).mockResolvedValue({
code: 'code123',
teamId: 't1',
team: { name: 'Team A' },
inviter: { name: 'Inviter' },
used: false,
} as never)
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as never)
const res = await app.request('/join', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer fake',
},
body: JSON.stringify({ code: 'code123' }),
})
expect(res.status).toBe(200)
expect(inviteService.consumeInvite).toHaveBeenCalledWith('code123', 'u1')
})
})
+111
View File
@@ -0,0 +1,111 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import {
createProjectInviteRequestSchema,
createTeamInviteRequestSchema,
joinRequestSchema,
InviteInfo,
} from '@/dtos/invite'
import { authzService, Permission } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapToInviteInfo = (inv: any): InviteInfo => {
const info: InviteInfo = {
code: inv.code,
role: inv.role!,
teamId: inv.teamId,
teamName: inv.team.name,
inviterName: inv.inviter.name,
isUsed: inv.used,
}
if (inv.project) {
info.projectId = inv.project.id
info.projectName = inv.project.name
}
return info
}
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/invite', zValidator('json', createTeamInviteRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const inv = await inviteService.createTeamInvite({
teamId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
role: req.role as any,
inviterId: user.id,
})
return c.json(mapToInviteInfo(inv))
})
.post(
'/projects/:projectId/invite',
zValidator('json', createProjectInviteRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
const inv = await inviteService.createProjectInvite({
projectId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
role: req.role as any,
inviterId: user.id,
})
return c.json(mapToInviteInfo(inv))
},
)
.post('/join', zValidator('json', joinRequestSchema), async (c) => {
const req = c.req.valid('json')
const user = c.get('user')
try {
const info = await inviteService.getInvite(req.code)
await inviteService.consumeInvite(req.code, user.id)
if (info.projectId) {
await notificationService.create({
type: NotificationType.new_user_join_project,
teamId: info.teamId,
projectId: info.projectId,
userId: user.id,
})
} else {
await notificationService.create({
type: NotificationType.new_user_join_team,
teamId: info.teamId,
userId: user.id,
})
}
return new Response(null, { status: 200 })
} catch {
return c.json({ error: 'Bad Request' }, 400)
}
})
export default route
+154
View File
@@ -0,0 +1,154 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import metadataRoute from './metadata'
import { metadataService } from '@/services/metadata/metadata'
import { Prisma } from '@/generated/prisma/client.ts'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('metadata api', () => {
beforeEach(() => {
vi.restoreAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/fields', async () => {
const mockField = {
key: 'field1',
scope: 'TEAM',
config: { name: 'Test Field', type: 'text' },
readOnly: false,
description: 'desc',
aiAutofill: true,
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
vi.spyOn(metadataService, 'listTeamFields').mockResolvedValue([mockField])
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/fields')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toHaveLength(1)
expect(json[0].id).toBe('field1')
expect(json[0].config.name).toBe('Test Field')
expect(json[0].aiAutofill).toBe(true)
})
it('POST /teams/:teamId/fields', async () => {
const mockField = {
key: 'newfield',
scope: 'TEAM',
config: { name: 'New Field', type: 'text' },
readOnly: false,
description: 'desc',
aiAutofill: true,
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
vi.spyOn(metadataService, 'createTeamField').mockResolvedValue(mockField)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/fields', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
config: { name: 'New Field', type: 'text' },
aiAutofill: true,
description: 'desc',
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.id).toBe('newfield')
})
it('GET /projects/:projectId/fields', async () => {
const mockField = {
key: 'field1',
scope: 'PROJECT',
config: { name: 'Project Field', type: 'text' },
readOnly: false,
description: 'desc',
aiAutofill: false,
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([
{ field: mockField, visible: true },
])
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/projects/p1/fields')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toHaveLength(1)
expect(json[0].id).toBe('field1')
expect(json[0].visible).toBe(true)
})
it('PATCH /projects/:projectId/fields/order', async () => {
vi.spyOn(metadataService, 'updateProjectFieldsOrder').mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/projects/p1/fields/order', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ fieldId: 'field1', visible: true }]),
})
expect(res.status).toBe(204)
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
{ fieldId: 'field1', visible: true },
])
})
it('DELETE /teams/:teamId/fields/:fieldId', async () => {
vi.spyOn(metadataService, 'deleteTeamField').mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/fields/f1', {
method: 'DELETE',
})
expect(res.status).toBe(204)
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
})
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
vi.spyOn(metadataService, 'updateAssetMetadata').mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
const res = await app.request('/teams/t1/files/f1/metadata', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ key: 'resolution_width', value: 1920 }]),
})
expect(res.status).toBe(204)
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith('f1', [
{ key: 'resolution_width', value: 1920 },
])
})
})
+194
View File
@@ -0,0 +1,194 @@
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
import { Hono } from 'hono'
import { metadataService } from '@/services/metadata/metadata'
import { authzService, Permission } from '@/services/authz/authz'
import {
createFieldRequestSchema,
updateFieldRequestSchema,
updateProjectFieldsOrderRequestSchema,
updateAssetMetadataRequestSchema,
FieldInfo,
} from '@/dtos/metadata'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
function toFieldInfo(
f: Prisma.MetadataFieldGetPayload<Record<string, never>>,
visible = false,
): FieldInfo {
return {
id: f.key,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: f.config as any,
scope: f.scope ?? '',
readOnly: f.readOnly,
visible: visible,
description: f.description,
aiAutofill: f.aiAutofill,
}
}
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const field = await metadataService.createTeamField(teamId, req)
return c.json(toFieldInfo(field))
})
.get('/teams/:teamId/fields', async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const fields = await metadataService.listTeamFields(teamId)
return c.json(fields.map((f) => toFieldInfo(f)))
})
.put(
'/teams/:teamId/fields/:fieldId',
zValidator('json', updateFieldRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const fieldId = c.req.param('fieldId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const field = await metadataService.updateTeamField(teamId, fieldId, req)
return c.json(toFieldInfo(field))
},
)
.delete('/teams/:teamId/fields/:fieldId', async (c) => {
const teamId = c.req.param('teamId')
const fieldId = c.req.param('fieldId')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
await metadataService.deleteTeamField(teamId, fieldId)
return new Response(null, { status: 204 })
})
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
const projectId = c.req.param('projectId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
const field = await metadataService.createProjectField(projectId, req)
return c.json(toFieldInfo(field))
})
.get('/projects/:projectId/fields', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
const fields = await metadataService.listProjectFields(user.id, projectId)
return c.json(fields.map((f) => toFieldInfo(f.field, f.visible)))
})
.patch(
'/projects/:projectId/fields/order',
zValidator('json', updateProjectFieldsOrderRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
return new Response(null, { status: 204 })
},
)
.put(
'/projects/:projectId/fields/:fieldId',
zValidator('json', updateFieldRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const fieldId = c.req.param('fieldId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
const field = await metadataService.updateProjectField(projectId, fieldId, req)
return c.json(toFieldInfo(field))
},
)
.delete('/projects/:projectId/fields/:fieldId', async (c) => {
const projectId = c.req.param('projectId')
const fieldId = c.req.param('fieldId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Admin,
})
await metadataService.deleteProjectField(projectId, fieldId)
return new Response(null, { status: 204 })
})
.patch(
'/teams/:teamId/files/:fileId/metadata',
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
async (c) => {
const teamId = c.req.param('teamId')
const fileId = c.req.param('fileId') // Actually maps to assetId
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
assetId: fileId,
user,
permission: Permission.Edit,
})
await metadataService.updateAssetMetadata(fileId, req)
return new Response(null, { status: 204 })
},
)
export default route
+35
View File
@@ -0,0 +1,35 @@
import type { Prisma } from '@/generated/prisma/client'
import { auth } from '@/services/auth/auth'
import { prisma } from '@/db'
import { createMiddleware } from 'hono/factory'
type User = Prisma.UserGetPayload<Record<string, never>>
export const authMiddleware = createMiddleware<{
Variables: {
user: User
}
}>(async (c, next) => {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
try {
const user = await prisma.user.findUnique({
where: { id: session.user.id },
})
if (!user) {
return c.json({ error: 'User not found' }, 401)
}
c.set('user', user)
await next()
} catch {
return c.json({ error: 'Authentication failed' }, 401)
}
})
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import notificationRoute from './notification'
import { notificationService } from '@/services/notification/notification'
import { authMiddleware } from '@/api/middleware/auth'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('notification api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockList: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockMarkRead: any
beforeEach(() => {
mockList = vi.fn()
mockMarkRead = vi.fn()
vi.spyOn(notificationService, 'list').mockImplementation(mockList)
vi.spyOn(notificationService, 'markRead').mockImplementation(mockMarkRead)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/notifications', async () => {
mockList.mockResolvedValue({
data: [{ id: 'n1', type: 'comment_created' }],
pageInfo: { total: 1, cursor: 'abc' },
})
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.pageInfo.total).toBe(1)
expect(json.pageInfo.cursor).toBe('abc')
expect(mockList).toHaveBeenCalledWith('t1', 'user1', {
unreadOnly: true,
after: undefined,
pageSize: 10,
})
})
it('POST /teams/:teamId/notifications/read', async () => {
mockMarkRead.mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
const res = await app.request('/teams/t1/notifications/read', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notificationId: 'n1' }),
})
expect(res.status).toBe(204)
expect(mockMarkRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
})
})
+64
View File
@@ -0,0 +1,64 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { notificationService } from '@/services/notification/notification'
import { authzService, Permission } from '@/services/authz/authz'
import {
listNotificationsRequestSchema,
markNotificationReadRequestSchema,
} from '@/dtos/notification'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get(
'/teams/:teamId/notifications',
zValidator('query', listNotificationsRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const req = c.req.valid('query')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const res = await notificationService.list(teamId, user.id, {
unreadOnly: req.unreadOnly,
after: req.after,
pageSize: req.pageSize,
})
// To align with Go struct casing, map pageInfo to page_info
return c.json({
data: res.data,
pageInfo: {
total: res.pageInfo.total,
cursor: res.pageInfo.cursor,
},
})
},
)
.post(
'/teams/:teamId/notifications/read',
zValidator('json', markNotificationReadRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
await notificationService.markRead(teamId, user.id, req.notificationId)
return new Response(null, { status: 204 })
},
)
export default route
+178
View File
@@ -0,0 +1,178 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import projectRoute from './project'
import { authMiddleware } from '@/api/middleware/auth'
import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset'
import { authzService } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('project api', () => {
let mockListProjects: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockCreateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetProjectTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockListProjectMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockReparentAssets: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => {
mockListProjects = vi.fn()
mockCreateProject = vi.fn()
mockUpdateProject = vi.fn()
mockGetProject = vi.fn()
mockGetProjectTeam = vi.fn()
mockListProjectMembers = vi.fn()
mockReparentAssets = vi.fn()
vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(projectService, 'listProjects').mockImplementation(mockListProjects)
vi.spyOn(projectService, 'createProject').mockImplementation(mockCreateProject)
vi.spyOn(projectService, 'updateProject').mockImplementation(mockUpdateProject)
vi.spyOn(projectService, 'getProject').mockImplementation(mockGetProject)
vi.spyOn(projectService, 'getProjectTeam').mockImplementation(mockGetProjectTeam)
vi.spyOn(projectService, 'listProjectMembers').mockImplementation(mockListProjectMembers)
vi.spyOn(assetService, 'reparentAssets').mockImplementation(mockReparentAssets)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/projects', async () => {
mockListProjects.mockResolvedValue({
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }],
pageInfo: { total: 100, cursor: 'abc' },
})
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/teams/t/projects?page_size=10')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.pageInfo.total).toBe(100)
expect(json.data[0].id).toBe('foo')
})
it('POST /teams/:teamId/projects', async () => {
mockCreateProject.mockResolvedValue({
id: 'foo',
name: 'foo.png',
coverImage: 'http://s3/bucket/key',
})
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/teams/t/projects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.id).toBe('foo')
expect(json.name).toBe('foo.png')
expect(json.coverImage).toBe('http://s3/bucket/key')
})
it('PUT /teams/:teamId/projects/:projectId', async () => {
mockUpdateProject.mockResolvedValue({
id: 'foo',
name: 'updated',
coverImage: 'http://s3/bucket/key',
})
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/teams/t/projects/foo', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'updated' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('updated')
})
it('GET /projects/:projectId', async () => {
mockGetProject.mockResolvedValue({
id: 'p',
name: 'foo.png',
rootFolder: 'root_folder_id',
})
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.rootFolder).toBe('root_folder_id')
expect(json.id).toBe('p')
})
it('GET /projects/:projectId/team', async () => {
mockGetProjectTeam.mockResolvedValue('teamId')
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p/team')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.teamId).toBe('teamId')
})
it('POST /projects/:projectId/reparent', async () => {
mockReparentAssets.mockResolvedValue(undefined)
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
const res = await app.request('/projects/p/reparent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newParentId: 'new_parent_id',
assetIds: ['asset_1', 'asset_2'],
}),
})
expect(res.status).toBe(204)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(1, {
assetId: 'new_parent_id',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(authzService.hasPermission).toHaveBeenNthCalledWith(2, {
assetId: 'asset_1',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(authzService.hasPermission).toHaveBeenNthCalledWith(3, {
assetId: 'asset_2',
user: { id: 'user1', name: 'Test User' },
permission: 'Edit',
})
expect(mockReparentAssets).toHaveBeenCalledWith({
newParentId: 'new_parent_id',
assetIds: ['asset_1', 'asset_2'],
creatorId: 'user1',
})
})
})
+192
View File
@@ -0,0 +1,192 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset'
import { reparentAssetsRequestSchema } from '@/dtos/asset'
import {
createProjectRequestSchema,
updateProjectRequestSchema,
listProjectsRequestSchema,
recentlyDeletedRequestSchema,
} from '@/dtos/project'
import { listMembersQuerySchema } from '@/dtos/team'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams/:teamId/projects', zValidator('json', createProjectRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Edit,
})
const newProject = await projectService.createProject(user, {
teamId,
...req,
})
return c.json(newProject)
})
.put(
'/teams/:teamId/projects/:projectId',
zValidator('json', updateProjectRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Edit,
})
const updatedProject = await projectService.updateProject({
projectId,
...req,
})
return c.json(updatedProject)
},
)
.get(
'/projects/:projectId/recently-deleted',
zValidator('query', recentlyDeletedRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
// STUB: AssetService is not migrated yet.
return c.json({ data: [], pageInfo: {} })
},
)
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('query')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const res = await projectService.listProjects({
teamId,
userId: user.id,
sortBy: req.sortBy,
sortDirection: req.sortDirection,
pagination: req,
})
return c.json({
data: res.data,
pageInfo: {
total: res.pageInfo.total,
cursor: res.pageInfo.cursor,
},
})
})
.get('/projects/:projectId', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
const p = await projectService.getProject(projectId)
return c.json(p)
})
.get('/projects/:projectId/team', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
const teamId = await projectService.getProjectTeam(projectId)
return c.json({ teamId })
})
.get('/projects/:projectId/members', zValidator('query', listMembersQuerySchema), async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const { includeAgents } = c.req.valid('query')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
const members = await projectService.listProjectMembers({
projectId,
includeAgents: includeAgents,
})
return c.json(members)
})
.get('/projects/:projectId/bots', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
// STUB: AgentService is not migrated yet.
return c.json([])
})
.post(
'/projects/:projectId/reparent',
zValidator('json', reparentAssetsRequestSchema),
async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
// Check Edit permission on target folder/project
await authzService.hasPermission({
assetId: req.newParentId,
user,
permission: Permission.Edit,
})
// Check Edit permission on all source assets
for (const assetId of req.assetIds) {
await authzService.hasPermission({
assetId,
user,
permission: Permission.Edit,
})
}
await assetService.reparentAssets({
...req,
creatorId: user.id,
})
return c.body(null, 204)
},
)
export default route
+158
View File
@@ -0,0 +1,158 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import providerRoute from './provider'
import { authMiddleware } from '@/api/middleware/auth'
import { providerService } from '@/services/provider/provider'
import { authzService } from '@/services/authz/authz'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('provider api', () => {
const app = new Hono().use('*', authMiddleware).route('/', providerRoute)
let mockListByTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockCreate: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdate: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockDelete: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => {
mockListByTeam = vi.spyOn(providerService, 'listByTeam')
mockCreate = vi.spyOn(providerService, 'create')
mockUpdate = vi.spyOn(providerService, 'update')
mockDelete = vi.spyOn(providerService, 'delete')
// Default to admin permission granted
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/providers returns providers', async () => {
mockListByTeam.mockResolvedValue([{ id: 'p1', name: 'openai', config: {} }])
const res = await app.request('/teams/t1/providers')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
expect(data[0].id).toBe('p1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
teamId: 't1',
permission: 'Admin',
}),
)
})
it('GET /teams/:teamId/providers/:id/models returns models', async () => {
const mockListModelsByProvider = vi.spyOn(providerService, 'listModelsByProvider')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockListModelsByProvider.mockResolvedValue([{ modelId: 'm1', name: 'model1' } as any])
const res = await app.request('/teams/t1/providers/p1/models')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
expect(data[0].modelId).toBe('m1')
expect(mockListModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
})
it('POST /teams/:teamId/providers creates provider', async () => {
const config = {
baseUrl: 'https://api.openai.com/v1',
api: 'openai-completions',
}
const models = [
{
modelId: 'gpt-4',
name: 'GPT-4',
config: {
api: 'openai-completions',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
]
mockCreate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
const res = await app.request('/teams/t1/providers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'openai', config, models }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.name).toBe('openai')
expect(mockCreate).toHaveBeenCalledWith('t1', 'openai', config, models)
})
it('PUT /teams/:teamId/providers/:id updates provider', async () => {
const config = {
baseUrl: 'https://new-url.com',
api: 'openai-completions',
}
const models = [
{
modelId: 'gpt-4',
name: 'GPT-4',
config: {
api: 'openai-completions',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
]
mockUpdate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
const res = await app.request('/teams/t1/providers/p1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ config, models }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.config.baseUrl).toBe('https://new-url.com')
expect(mockUpdate).toHaveBeenCalledWith('t1', 'p1', config, models)
})
it('DELETE /teams/:teamId/providers/:id deletes provider', async () => {
mockDelete.mockResolvedValue({ id: 'p1' })
const res = await app.request('/teams/t1/providers/p1', {
method: 'DELETE',
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.success).toBe(true)
expect(mockDelete).toHaveBeenCalledWith('t1', 'p1')
})
})
+90
View File
@@ -0,0 +1,90 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { authzService, Permission } from '@/services/authz/authz'
import { providerService } from '@/services/provider/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/providers', async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const providers = await providerService.listByTeam(teamId)
return c.json(providers)
})
.get('/teams/:teamId/providers/:id/models', async (c) => {
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const models = await providerService.listModelsByProvider(teamId, id)
return c.json(models)
})
.post('/teams/:teamId/providers', zValidator('json', createProviderRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const { name, config, models } = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const provider = await providerService.create(teamId, name, config, models)
return c.json(provider)
})
.put(
'/teams/:teamId/providers/:id',
zValidator('json', updateProviderRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const user = c.get('user')
const { config, models } = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const provider = await providerService.update(teamId, id, config, models)
return c.json(provider)
},
)
.delete('/teams/:teamId/providers/:id', async (c) => {
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const user = c.get('user')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
await providerService.delete(teamId, id)
return c.json({ success: true })
})
export default route
+36
View File
@@ -0,0 +1,36 @@
import { Hono } from 'hono'
import { inviteService } from '@/services/invite/invite'
import { InviteInfo } from '@/dtos/invite'
const app = new Hono()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapToInviteInfo = (inv: any): InviteInfo => {
const info: InviteInfo = {
code: inv.code,
role: inv.role!,
teamId: inv.teamId,
teamName: inv.team.name,
inviterName: inv.inviter.name,
isUsed: inv.used,
}
if (inv.project) {
info.projectId = inv.project.id
info.projectName = inv.project.name
}
return info
}
const route = app.get('/invite/:code', async (c) => {
const code = c.req.param('code')
try {
const inv = await inviteService.getInvite(code)
return c.json(mapToInviteInfo(inv))
} catch {
return c.json({ error: 'Not found' }, 404)
}
})
export default route
+250
View File
@@ -0,0 +1,250 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { shareService } from '@/services/share/share'
import { assetService } from '@/services/asset/asset'
import { paginationParamsSchema } from '@/dtos/pagination'
import { z } from 'zod'
import { metadataService } from '@/services/metadata/metadata'
import { FieldInfo } from '@/dtos/metadata'
import type { Prisma as PrismaType } from '@/generated/prisma/client'
import { auth } from '@/services/auth/auth'
import { prisma } from '@/db'
import { createCommentRequestSchema } from '@/dtos/asset'
import { notificationService } from '@/services/notification/notification'
const app = new Hono()
function toFieldInfo(
f: PrismaType.MetadataFieldGetPayload<Record<string, never>>,
visible = false,
): FieldInfo {
return {
id: f.key,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: f.config as any,
scope: f.scope ?? '',
readOnly: f.readOnly,
visible: visible,
description: f.description,
aiAutofill: f.aiAutofill,
}
}
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
assetType: z.string().optional(),
})
const route = app
.get('/shares/:shareId/info', async (c) => {
const shareId = c.req.param('shareId')
try {
const shareLink = await shareService.getShareLink(shareId)
return c.json({
id: shareLink.id,
name: shareLink.name,
expireAt: shareLink.expireAt,
isDisabled: shareLink.isDisabled,
isExpired: shareLink.isExpired,
hasPassword: shareLink.hasPassword,
rootFolderId: shareLink.rootFolderId,
projectId: shareLink.projectId,
})
} catch (err) {
return c.json({ error: (err as Error).message }, 404)
}
})
.get('/shares/:shareId/fields', async (c) => {
const shareId = c.req.param('shareId')
const password = c.req.header('x-share-password')
try {
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
return c.json(
fields
.filter((f) => fieldVisibility[f.field.key])
.map((f) => toFieldInfo(f.field, f.visible)),
)
} catch (err) {
const msg = (err as Error).message
if (msg === 'Invalid password for share link') {
return c.json({ error: 'Unauthorized' }, 401)
}
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
return c.json({ error: msg }, 403)
}
return c.json({ error: msg }, 500)
}
})
.get(
'/shares/:shareId/folders/:folderId/children',
zValidator('query', sharedChildrenRequestSchema),
async (c) => {
const folderId = c.req.param('folderId')
const password = c.req.header('x-share-password')
const req = c.req.valid('query')
try {
const shareLink = await shareService.verifyPublicAccess(folderId, password)
let sort: string | undefined
let order: string | undefined
if (shareLink.defaultSortOrder) {
const parts = shareLink.defaultSortOrder.split(':')
sort = parts[0]
order = parts[1]
}
const res = await assetService.listChildren({
...req,
assetId: folderId,
assetType: req.assetType || 'file',
sort,
order,
})
return c.json(res)
} catch (err) {
const msg = (err as Error).message
if (msg === 'Invalid password for share link') {
return c.json({ error: 'Unauthorized' }, 401)
}
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
return c.json({ error: msg }, 403)
}
return c.json({ error: msg }, 500)
}
},
)
.get('/shares/:shareId/files/:fileId', async (c) => {
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
try {
await shareService.verifyPublicAccess(fileId, password)
const asset = await assetService.getAsset({ assetId: fileId })
return c.json(asset)
} catch (err) {
const msg = (err as Error).message
if (msg === 'Invalid password for share link') {
return c.json({ error: 'Unauthorized' }, 401)
}
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
return c.json({ error: msg }, 403)
}
return c.json({ error: msg }, 500)
}
})
.get(
'/shares/:shareId/files/:fileId/comments',
zValidator('query', paginationParamsSchema),
async (c) => {
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const req = c.req.valid('query')
try {
await shareService.verifyPublicAccess(fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const res = await assetService.listComments(targetFileId, req)
return c.json(res)
} catch (err) {
const msg = (err as Error).message
if (msg === 'Invalid password for share link') {
return c.json({ error: 'Unauthorized' }, 401)
}
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
return c.json({ error: msg }, 403)
}
return c.json({ error: msg }, 500)
}
},
)
.post(
'/shares/:shareId/files/:fileId/comments',
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const guestUserId = c.req.header('x-guest-user-id')
const req = c.req.valid('json')
try {
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
const project = await prisma.project.findUnique({
where: { id: shareLink.projectId },
select: { teamId: true },
})
if (!project) {
throw new Error('Project not found')
}
// Identify user
let userId: string | null = null
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session?.user) {
userId = session.user.id
} else if (guestUserId) {
const guestUser = await prisma.user.findUnique({
where: { id: guestUserId },
})
if (guestUser) {
userId = guestUser.id
}
}
if (!userId) {
return c.json({ error: 'Unauthorized' }, 401)
}
const comment = await assetService.createComment({
assetId: targetFileId,
userId: userId,
replyToId: req.replyToId,
message: req.message,
annotations: req.annotations,
second: req.second,
attachmentIds: req.attachmentIds,
})
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
notificationService.create({
type: notifType,
teamId: project.teamId,
creatorId: userId,
assetId: targetFileId,
commentMessage: req.message,
})
return c.json(comment, 201)
} catch (err) {
const msg = (err as Error).message
if (msg === 'Invalid password for share link') {
return c.json({ error: 'Unauthorized' }, 401)
}
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
return c.json({ error: msg }, 403)
}
return c.json({ error: msg }, 500)
}
},
)
export default route
+54
View File
@@ -0,0 +1,54 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { s3Service } from '@/services/s3/s3'
import route from './s3'
import { Hono } from 'hono'
describe('S3 API', () => {
const app = new Hono().route('/files', route)
beforeEach(() => {
vi.clearAllMocks()
})
it('GET /files/:bucket/:key sets Content-Type', async () => {
const mockHead = vi.spyOn(s3Service, 'headObject').mockResolvedValue({
key: 'test.webp',
size: 100,
lastModified: new Date(),
contentType: 'image/webp',
eTag: '"test"',
})
const mockGet = vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'image/webp' })
const res = await app.request('/files/b1/test.webp')
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/webp')
expect(mockHead).toHaveBeenCalledWith('b1', 'test.webp')
expect(mockGet).toHaveBeenCalledWith('b1', 'test.webp')
})
it('GET /files/:bucket/:key handles missing contentType', async () => {
vi.spyOn(s3Service, 'headObject').mockResolvedValue({
key: 'test',
size: 100,
lastModified: new Date(),
contentType: 'application/octet-stream',
eTag: '"test"',
})
vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'application/octet-stream' })
const res = await app.request('/files/b1/test')
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
})
it('GET /files/:bucket/:key returns 404 if not found', async () => {
vi.spyOn(s3Service, 'headObject').mockRejectedValue(new Error('NoSuchKey'))
const res = await app.request('/files/b1/not-found')
expect(res.status).toBe(404)
})
})
+43
View File
@@ -0,0 +1,43 @@
import { Hono } from 'hono'
import { s3Service } from '@/services/s3/s3'
const route = new Hono()
.get('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
try {
const info = await s3Service.headObject(bucket, key)
const { buffer: data, contentType } = await s3Service.getObject(bucket, key)
if (contentType) {
c.header('Content-Type', contentType)
} else if (info.contentType) {
c.header('Content-Type', info.contentType)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return c.body(data as any)
} catch (e: unknown) {
const error = e as Error
if (error.message?.includes('NoSuchKey')) {
return c.text('Not Found', 404)
}
return c.text(error.message || 'Internal Server Error', 500)
}
})
.put('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
const body = await c.req.arrayBuffer()
try {
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
return c.text('OK')
} catch (e: unknown) {
const error = e as Error
return c.text(error.message || 'Internal Server Error', 500)
}
})
export default route
+202
View File
@@ -0,0 +1,202 @@
import { describe, expect, test, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import shareRoute from './share'
import publicShareRoute from './public-share'
import { authMiddleware } from '@/api/middleware/auth'
import { shareService } from '@/services/share/share'
import { assetService } from '@/services/asset/asset'
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'user1', name: 'Test User' } as any)
await next()
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
},
Permission: {
Read: 'read',
Edit: 'edit',
Admin: 'admin',
},
}))
describe('Share API', () => {
const app = new Hono()
.route('/', publicShareRoute)
.use('*', authMiddleware)
.route('/', shareRoute)
beforeEach(() => {
vi.restoreAllMocks()
})
// Public Routes
describe('GET /shares/:shareId/info', () => {
test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
name: 'Public Share',
isDisabled: false,
isExpired: false,
hasPassword: true,
rootFolderId: 'folder1',
projectId: 'project1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const res = await app.request('/shares/share1/info', {
method: 'GET',
})
expect(res.status).toBe(200)
const body = await res.json()
expect(body.name).toBe('Public Share')
expect(body.hasPassword).toBe(true)
})
})
describe('GET /shares/:shareId/folders/:folderId/children', () => {
test('Success', async () => {
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share1',
name: 'My Share',
isDisabled: false,
rootFolderId: 'folder1',
projectId: 'project1',
password: null,
expireAt: null,
defaultSortOrder: 'name:asc',
fieldVisibility: null,
createdAt: new Date(),
updatedAt: new Date(),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
data: [],
pageInfo: { total: 0, cursor: undefined },
})
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', {
method: 'GET',
headers: { 'x-share-password': 'pass' },
})
expect(res.status).toBe(200)
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
expect(assetService.listChildren).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'folder1',
assetType: 'file',
sort: 'name',
order: 'asc',
}),
)
})
})
// Protected Routes
describe('POST /teams/:teamId/projects/:projectId/shares', () => {
test('Success', async () => {
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
id: 'share1',
name: 'test-share',
isDisabled: false,
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const res = await app.request('/teams/team1/projects/project1/shares', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'My Share' }),
})
expect(res.status).toBe(200)
const body = await res.json()
expect(body.id).toBe('share1')
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
})
})
describe('GET /teams/:teamId/projects/:projectId/shares', () => {
test('Success', async () => {
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
data: [],
pageInfo: { total: 0, cursor: undefined },
})
const res = await app.request('/teams/team1/projects/project1/shares', {
method: 'GET',
})
expect(res.status).toBe(200)
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
expect.objectContaining({
projectId: 'project1',
}),
)
})
})
describe('GET /teams/:teamId/shares/:shareId', () => {
test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
name: 'test-share',
isDisabled: false,
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
const res = await app.request('/teams/team1/shares/share1', {
method: 'GET',
})
expect(res.status).toBe(200)
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
})
})
describe('POST /teams/:teamId/shares/:shareId/assets', () => {
test('Success', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
name: 'test-share',
isDisabled: false,
rootFolderId: 'root1',
projectId: 'project1',
isExpired: false,
hasPassword: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
const res = await app.request('/teams/team1/shares/share1/assets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetIds: ['asset1'] }),
})
expect(res.status).toBe(200)
const body = await res.json()
expect(body.addedCount).toBe(1)
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
})
})
})
+147
View File
@@ -0,0 +1,147 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { shareService } from '@/services/share/share'
import {
createShareLinkRequestSchema,
updateShareLinkRequestSchema,
listShareLinksRequestSchema,
addAssetToShareRequestSchema,
} from '@/dtos/share'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.post(
'/teams/:teamId/projects/:projectId/shares',
zValidator('json', createShareLinkRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Edit,
})
const shareLink = await shareService.createShareLink(projectId, req)
return c.json(shareLink)
},
)
.get(
'/teams/:teamId/projects/:projectId/shares',
zValidator('query', listShareLinksRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('query')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Read,
})
const res = await shareService.listProjectShareLinks({
...req,
projectId,
})
return c.json(res)
},
)
.get('/teams/:teamId/shares/:shareId', async (c) => {
const shareId = c.req.param('shareId')
const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({
projectId: shareLink.projectId,
user,
permission: Permission.Read,
})
return c.json(shareLink)
})
.put(
'/teams/:teamId/shares/:shareId',
zValidator('json', updateShareLinkRequestSchema),
async (c) => {
const shareId = c.req.param('shareId')
const user = c.get('user')
const req = c.req.valid('json')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({
projectId: shareLink.projectId,
user,
permission: Permission.Edit,
})
const updated = await shareService.updateShareLink(shareId, req)
return c.json(updated)
},
)
.delete('/teams/:teamId/shares/:shareId', async (c) => {
const shareId = c.req.param('shareId')
const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({
projectId: shareLink.projectId,
user,
permission: Permission.Edit,
})
await shareService.deleteShareLink(shareId)
return c.body(null, 204)
})
.post(
'/teams/:teamId/shares/:shareId/assets',
zValidator('json', addAssetToShareRequestSchema),
async (c) => {
const shareId = c.req.param('shareId')
const user = c.get('user')
const req = c.req.valid('json')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({
projectId: shareLink.projectId,
user,
permission: Permission.Edit,
})
// Also check if user has read permission on the source assets
for (const assetId of req.assetIds) {
await authzService.hasPermission({
assetId,
user,
permission: Permission.Read,
})
}
const addedCount = await shareService.addAssetToShare(shareId, req)
return c.json({ addedCount })
},
)
.delete('/teams/:teamId/shares/:shareId/assets/:assetId', async (c) => {
const shareId = c.req.param('shareId')
const assetId = c.req.param('assetId') // symlink asset id
const user = c.get('user')
const shareLink = await shareService.getShareLink(shareId)
await authzService.hasPermission({
projectId: shareLink.projectId,
user,
permission: Permission.Edit,
})
await shareService.removeAssetFromShare(shareId, assetId)
return c.body(null, 204)
})
export default route
+170
View File
@@ -0,0 +1,170 @@
import { describe, expect, test, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import skillRoute from './skill'
import { skillService } from '@/services/skill/skill'
import { authMiddleware } from '@/api/middleware/auth'
import { authzService } from '@/services/authz/authz'
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'user1', name: 'Test User' } as any)
await next()
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'read',
Edit: 'edit',
Admin: 'admin',
},
}))
describe('Skill API', () => {
const app = new Hono().use('*', authMiddleware).route('/', skillRoute)
beforeEach(() => {
vi.restoreAllMocks()
})
describe('GET /teams/:teamId/skills', () => {
test('Success', async () => {
const mockSkills = [
{
id: 'skill1',
name: 'Skill 1',
description: 'Desc 1',
config: null,
assetId: 'asset1',
hash: 'hash1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
]
vi.spyOn(skillService, 'listSkills').mockResolvedValue(mockSkills)
const res = await app.request('/teams/team1/skills', {
method: 'GET',
headers: { Authorization: 'Bearer test' },
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ skills: mockSkills })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({ permission: 'admin' }),
)
})
})
describe('POST /teams/:teamId/skills', () => {
test('Success with assetId', async () => {
const mockSkill = {
id: 'skill1',
name: 'Skill 1',
description: 'Desc 1',
config: null,
assetId: 'asset1',
hash: 'hash1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
const res = await app.request('/teams/team1/skills', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ assetId: 'asset1' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockSkill)
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
})
test('Success with githubUrl', async () => {
const mockSkill = {
id: 'skill1',
name: 'Skill 1',
description: 'Desc 1',
config: null,
assetId: 'asset1',
hash: 'hash1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
const res = await app.request('/teams/team1/skills', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ githubUrl: 'https://github.com/test/repo' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockSkill)
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
githubUrl: 'https://github.com/test/repo',
})
})
test('Forbidden without Admin permission', async () => {
vi.spyOn(authzService, 'hasPermission').mockRejectedValueOnce(new Error('Forbidden'))
const res = await app.request('/teams/team1/skills', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ assetId: 'asset1' }),
})
expect(res.status).toBe(500) // The app uses a global error handler that returns 500 for thrown errors in these tests
})
})
describe('DELETE /teams/:teamId/skills/:id', () => {
test('Success', async () => {
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
const res = await app.request('/teams/team1/skills/skill1', {
method: 'DELETE',
headers: { Authorization: 'Bearer test' },
})
expect(res.status).toBe(204)
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
})
})
describe('PATCH /teams/:teamId/skills/:id/config', () => {
test('Success', async () => {
const mockConfig = {
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
}
const mockSkill = {
id: 'skill1',
name: 'Skill 1',
description: 'Desc 1',
config: mockConfig,
assetId: 'asset1',
hash: 'hash1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
const res = await app.request('/teams/team1/skills/skill1/config', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({ config: mockConfig }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockSkill)
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
})
})
})
+79
View File
@@ -0,0 +1,79 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { skillService } from '@/services/skill/skill'
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.get('/teams/:teamId/skills', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const skills = await skillService.listSkills(teamId)
return c.json({ skills })
})
.post('/teams/:teamId/skills', zValidator('json', upsertSkillRequestSchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
try {
const skill = await skillService.upsertSkill(teamId, req)
return c.json(skill)
} catch (err: unknown) {
if (err instanceof Error && err.name === 'ConflictError') {
return c.json({ error: err.message }, 409)
}
throw err
}
})
.delete('/teams/:teamId/skills/:id', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const id = c.req.param('id')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
await skillService.deleteSkill(id)
return new Response(null, { status: 204 })
})
.patch(
'/teams/:teamId/skills/:id/config',
zValidator('json', updateSkillConfigRequestSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const skill = await skillService.updateSkillConfig(id, req.config)
return c.json(skill)
},
)
export default route
+187
View File
@@ -0,0 +1,187 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import teamRoute from './team'
import { authMiddleware } from '@/api/middleware/auth'
import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => {
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
mockGetMe = vi.spyOn(teamService, 'getMe')
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
mockGetSettings = vi.spyOn(teamService, 'getSettings')
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('POST /teams creates a new team', async () => {
const mockTeam = { id: 't1', name: 'New Team', updatedAt: new Date() }
mockCreateTeam.mockResolvedValue(mockTeam)
const res = await app.request('/teams', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'New Team',
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.id).toBe('t1')
expect(mockCreateTeam).toHaveBeenCalledWith(
expect.objectContaining({ id: 'user1' }),
expect.objectContaining({ name: 'New Team' }),
)
})
it('GET /teams returns user teams', async () => {
mockGetUserTeams.mockResolvedValue({
data: [{ id: 't1', name: 'User Team', updatedAt: new Date() }],
pageInfo: { total: 1, cursor: undefined },
})
const res = await app.request('/teams?first=10')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.data[0].id).toBe('t1')
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
})
it('POST /teams/:teamId/members joins team and sends notification', async () => {
mockJoinTeam.mockResolvedValue(undefined)
const res = await app.request('/teams/t1/members', { method: 'POST' })
expect(res.status).toBe(204)
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
expect(mockCreateNotification).toHaveBeenCalledWith(
expect.objectContaining({
type: 'new_user_join_team',
teamId: 't1',
userId: 'user1',
}),
)
})
it('GET /teams/:teamId/me returns user role in team', async () => {
mockGetMe.mockResolvedValue({ id: 'user1', name: 'Test User', role: 'owner' })
const res = await app.request('/teams/t1/me')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.role).toBe('owner')
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
})
it('GET /teams/:teamId/members returns members', async () => {
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
const res = await app.request('/teams/t1/members')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(1)
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
})
it('GET /teams/:teamId/settings returns settings', async () => {
mockGetSettings.mockResolvedValue({ someKey: 'some_value' })
const res = await app.request('/teams/t1/settings')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.someKey).toBe('some_value')
expect(mockGetSettings).toHaveBeenCalledWith('t1')
})
it('PATCH /teams/:teamId/settings updates settings', async () => {
mockUpdateSettings.mockResolvedValue({ someKey: 'new_value' })
const res = await app.request('/teams/t1/settings', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'someKey', value: 'new_value' }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.someKey).toBe('new_value')
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
})
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
mockListUserMetadata.mockResolvedValue([
{ key: 'key1', value: 'value1' },
{ key: 'key2', value: 'value2' },
])
const res = await app.request('/teams/t1/user-metadata')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveLength(2)
expect(data[0].key).toBe('key1')
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
})
it('PUT /teams/:teamId/user-metadata/:key upserts the metadata', async () => {
mockUpsertUserMetadata.mockResolvedValue({ key: 'key1', value: 'value1' })
const res = await app.request('/teams/t1/user-metadata/key1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: 'value1' }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.key).toBe('key1')
expect(data.value).toBe('value1')
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
})
})
+160
View File
@@ -0,0 +1,160 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission } from '@/services/authz/authz'
import { teamService } from '@/services/team/team'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import {
createTeamRequestSchema,
getUserTeamsRequestSchema,
updateTeamSettingsRequestSchema,
listMembersQuerySchema,
} from '@/dtos/team'
import { updateUserMetadataRequestSchema } from '@/dtos/user-metadata'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.post('/teams', zValidator('json', createTeamRequestSchema), async (c) => {
const user = c.get('user')
const req = c.req.valid('json')
const newTeam = await teamService.createTeam(user, req)
return c.json(newTeam)
})
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
const user = c.get('user')
const pg = c.req.valid('query')
const teams = await teamService.getUserTeams({
userId: user.id,
pagination: pg,
})
return c.json({
data: teams.data,
pageInfo: {
total: teams.pageInfo.total,
cursor: teams.pageInfo.cursor,
},
})
})
.post('/teams/:teamId/members', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await teamService.joinTeam({
teamId,
userId: user.id,
})
await notificationService.create({
type: NotificationType.new_user_join_team,
teamId,
userId: user.id,
})
return new Response(null, { status: 204 })
})
.get('/teams/:teamId/me', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const me = await teamService.getMe({
teamId,
user,
})
return c.json(me)
})
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const { includeAgents } = c.req.valid('query')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const members = await teamService.getTeamMembers({
teamId,
includeAgents: includeAgents,
})
return c.json(members)
})
.get('/teams/:teamId/settings', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const settings = await teamService.getSettings(teamId)
return c.json(settings)
})
.patch(
'/teams/:teamId/settings',
zValidator('json', updateTeamSettingsRequestSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Admin,
})
const settings = await teamService.updateSettings(teamId, req.key, req.value)
return c.json(settings)
},
)
.get('/teams/:teamId/user-metadata', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const metadata = await userMetadataService.listMetadata(user.id, teamId)
return c.json(metadata)
})
.put(
'/teams/:teamId/user-metadata/:key',
zValidator('json', updateUserMetadataRequestSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const key = c.req.param('key')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
user,
permission: Permission.Read,
})
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
return c.json({ key: metadata.key, value: metadata.value })
},
)
export default route
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import uploadRoute from './upload'
import { authMiddleware } from '@/api/middleware/auth'
import { uploadService } from '@/services/upload/upload'
import type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload'
import type { PaginatedData } from '@/services/pagination'
vi.mock('@/api/middleware/auth', () => ({
// We use any here because mocking Hono context and middleware
// with full type safety is overly complex for these unit tests.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.set('user', { id: 'user1', name: 'Test User' } as any)
await next()
},
}))
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/services/notification/notification', () => ({
notificationService: {
create: vi.fn().mockResolvedValue(undefined),
},
}))
describe('Upload API', () => {
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
beforeEach(() => {
vi.restoreAllMocks()
})
it('GET /teams/:teamId/upload/tasks', async () => {
// We mock the return value as it is only used for checking the call
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
data: [],
pageInfo: {},
} as unknown as PaginatedData<TaskInfo[]>)
const res = await app.request('/teams/team1/upload/tasks', {
headers: { Authorization: 'Bearer test' },
})
expect(res.status).toBe(200)
expect(uploadService.listUploadTasks).toHaveBeenCalled()
})
it('POST /teams/:teamId/upload/tasks', async () => {
// We mock the return value as it is only used for checking the call
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
taskId: 'task1',
presignedUrls: [],
} as unknown as CreateUploadTaskResponse)
const res = await app.request('/teams/team1/upload/tasks', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
parentId: 'parent1',
files: [],
}),
})
expect(res.status).toBe(200)
expect(uploadService.createUploadTask).toHaveBeenCalled()
})
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
const res = await app.request('/teams/team1/upload/tasks/task1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
fileId: 'file1',
}),
})
expect(res.status).toBe(200)
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
fileId: 'file1',
})
})
})
+101
View File
@@ -0,0 +1,101 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { uploadService } from '@/services/upload/upload'
import {
confirmFileUploadRequestSchema,
createUploadTaskRequestSchema,
localUploadQuerySchema,
} from '@/dtos/upload'
import { paginationParamsSchema } from '@/dtos/pagination'
import { authzService, Permission } from '@/services/authz/authz'
import { notificationService } from '@/services/notification/notification'
import { NotificationType } from '@/generated/prisma/client'
import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const route = new Hono<{ Variables: { user: User } }>()
.put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => {
const { bucket, key, Signature } = c.req.valid('query')
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
return c.text('Invalid signature', 403)
}
const contentType = c.req.header('Content-Type')
let buffer: Buffer
let size: number
let finalContentType = contentType
if (contentType?.includes('multipart/form-data')) {
const body = await c.req.parseBody()
const file = body['file'] as File
if (!file) {
return c.text('No file uploaded', 400)
}
buffer = Buffer.from(await file.arrayBuffer())
size = file.size
finalContentType = file.type || 'application/octet-stream'
} else {
const arrayBuffer = await c.req.arrayBuffer()
buffer = Buffer.from(arrayBuffer)
size = arrayBuffer.byteLength
}
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
return c.json({ success: true })
})
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
const user = c.get('user')
const params = c.req.valid('query')
const tasks = await uploadService.listUploadTasks(user.id, params)
return c.json(tasks)
})
.post(
'/teams/:teamId/upload/tasks',
zValidator('json', createUploadTaskRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
teamId,
assetId: req.parentId,
user,
permission: Permission.Edit,
})
const resp = await uploadService.createUploadTask(user.id, req)
return c.json(resp)
},
)
.patch(
'/teams/:teamId/upload/tasks/:taskId',
zValidator('json', confirmFileUploadRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const taskId = c.req.param('taskId')
const user = c.get('user')
const req = c.req.valid('json')
await uploadService.confirmFileUpload(user.id, taskId, req)
if (!req.errorMessage) {
await notificationService.create({
type: NotificationType.successful_file_uploaded,
teamId: teamId,
creatorId: user.id,
assetId: req.fileId,
taskId: taskId,
})
}
return c.json({ success: true })
},
)
export default route
+118
View File
@@ -0,0 +1,118 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import versionStackRoute from './versionStack'
import { authMiddleware } from '@/api/middleware/auth'
import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset'
vi.mock('@/services/authz/authz', () => ({
authzService: {
hasPermission: vi.fn(),
},
Permission: {
Read: 'Read',
Edit: 'Edit',
Admin: 'Admin',
},
}))
vi.mock('@/api/middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
describe('versionStack api', () => {
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => {
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
mockGetAsset = vi.spyOn(assetService, 'getAsset')
})
afterEach(() => {
vi.clearAllMocks()
})
describe('POST /projects/:projectID/version_stacks', () => {
it('should create a version stack and return asset info', async () => {
const mockStack = { id: 'stack1' }
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
mockCreateVersionStack.mockResolvedValue(mockStack)
mockGetAsset.mockResolvedValue(mockAssetInfo)
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileIds: ['f1', 'f2'] }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toEqual(mockAssetInfo)
expect(mockCreateVersionStack).toHaveBeenCalledWith({
projectId: 'p1',
creatorId: 'user1',
fileIds: ['f1', 'f2'],
})
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
})
it('should fail with validation error for invalid body', async () => {
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ wrongField: [] }),
})
expect(res.status).toBe(400)
expect(mockCreateVersionStack).not.toHaveBeenCalled()
})
})
describe('POST /projects/:projectID/version_stacks/:stackID/order', () => {
it('should change order and return 200', async () => {
mockChangeStackFileVersion.mockResolvedValue()
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
})
expect(res.status).toBe(200)
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
stackId: 'stack1',
fileId: 'f1',
beforeId: 'f2',
})
})
it('should fail with validation error for invalid body', async () => {
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileId: 'f1' }), // missing beforeId
})
expect(res.status).toBe(400)
expect(mockChangeStackFileVersion).not.toHaveBeenCalled()
})
})
})
+67
View File
@@ -0,0 +1,67 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { versionStackService } from '@/services/versionStack/versionStack'
import { assetService } from '@/services/asset/asset'
import { authzService, Permission } from '@/services/authz/authz'
import {
createVersionStackRequestSchema,
changeStackFileVersionRequestSchema,
} from '@/dtos/versionStack'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
const app = new Hono<{ Variables: { user: User } }>()
const route = app
.post(
'/projects/:projectID/version_stacks',
zValidator('json', createVersionStackRequestSchema),
async (c) => {
const projectId = c.req.param('projectID')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Edit,
})
const stack = await versionStackService.createVersionStack({
fileIds: req.fileIds,
projectId,
creatorId: user.id,
})
const stackInfo = await assetService.getAsset({ assetId: stack.id })
return c.json(stackInfo)
},
)
.post(
'/projects/:projectID/version_stacks/:stackID/order',
zValidator('json', changeStackFileVersionRequestSchema),
async (c) => {
const projectId = c.req.param('projectID')
const stackId = c.req.param('stackID')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
projectId,
user,
permission: Permission.Edit,
})
await versionStackService.changeStackFileVersion({
stackId,
fileId: req.fileId,
beforeId: req.beforeId,
})
return new Response(null, { status: 200 })
},
)
export default route
+106
View File
@@ -0,0 +1,106 @@
import index from '@/ui/index.html'
import type { Prisma } from '@/generated/prisma/client'
import { Hono } from 'hono'
import agentRoute from '@/api/agent'
import attachmentRoute from '@/api/attachment'
import authnRoute from '@/api/authn'
import fileRoute from '@/api/file'
import folderRoute from '@/api/folder'
import inviteRoute from '@/api/invite'
import metadataRoute from '@/api/metadata'
import { authMiddleware } from '@/api/middleware/auth'
import notificationRoute from '@/api/notification'
import projectRoute from '@/api/project'
import providerRoute from '@/api/provider'
import publicInviteRoute from '@/api/public-invite'
import publicShareRoute from '@/api/public-share'
import s3Route from '@/api/s3'
import shareRoute from '@/api/share'
import skillRoute from '@/api/skill'
import teamRoute from '@/api/team'
import uploadRoute from '@/api/upload'
import versionStackRoute from '@/api/versionStack'
import { metadataService } from '@/services/metadata/metadata'
import { workflowService } from '@/workflow/workflow'
type User = Prisma.UserGetPayload<Record<string, never>>
const app = new Hono()
const apiRoute = new Hono<{ Variables: { user: User } }>()
// Public Routes
.route('/', authnRoute)
.route('/', publicInviteRoute)
.route('/', publicShareRoute)
// Protected Routes
.use('*', authMiddleware)
.route('/', inviteRoute)
.route('/', providerRoute)
.route('/', notificationRoute)
.route('/', metadataRoute)
.route('/', projectRoute)
.route('/', teamRoute)
.route('/', versionStackRoute)
.route('/', fileRoute)
.route('/', folderRoute)
.route('/', agentRoute)
.route('/', attachmentRoute)
.route('/', uploadRoute)
.route('/', shareRoute)
.route('/', skillRoute)
app.route('/files', s3Route)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const apiAppRoute = app.route('/api', apiRoute)
export type AppType = typeof apiAppRoute
export async function run() {
// Start services
await metadataService.syncSystemFields().catch(console.error)
workflowService.start()
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
const args = process.argv.slice(2)
let workersOption = ''
for (let i = 0; i < args.length; i++) {
if (args[i] === '--workers') {
workersOption = args[i + 1] || ''
} else if (args[i].startsWith('--workers=')) {
workersOption = args[i].split('=')[1]
}
}
const queuesToStart = ['db_queue']
if (workersOption === 'agent' || workersOption === 'ai') {
queuesToStart.push('agent_queue')
} else if (workersOption === 'transcode') {
queuesToStart.push('transcode_queue')
} else if (workersOption === 'all') {
queuesToStart.push('agent_queue', 'transcode_queue')
}
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
}
const server = Bun.serve({
port: 3000,
fetch: app.fetch,
routes: {
// Serve index.html for root
'/': index,
// Proxy API requests to Hono
'/api/*': app.fetch,
'/files/*': app.fetch,
// Catch-all for SPA routing (fallback to index.html)
'/*': index,
},
development: process.env.NODE_ENV !== 'production',
})
console.log(`🚀 Server running at ${server.url}`)
}
+32
View File
@@ -0,0 +1,32 @@
import { workflowService } from '@/workflow/workflow'
import { TaskQueueAgent, TaskQueueTranscode } from '@/workflow/workflow-utils'
export async function run() {
const domain = process.argv[3]
if (!domain) {
console.error('Please specify a worker domain.')
console.log('Available domains: agent, transcode, all')
process.exit(1)
}
switch (domain) {
case 'agent':
case 'ai':
await workflowService.startWorkers(TaskQueueAgent)
break
case 'transcode':
await workflowService.startWorkers(TaskQueueTranscode)
break
case 'all':
await Promise.all([
workflowService.startWorkers(TaskQueueAgent),
workflowService.startWorkers(TaskQueueTranscode),
])
break
default:
console.error('Unknown domain: ' + domain)
console.log('Available domains: agent, transcode, all')
process.exit(1)
}
}
+12
View File
@@ -0,0 +1,12 @@
import { afterEach, beforeEach } from 'vitest'
import { getPrismaTestingHelper } from '@/db'
export function setupTestDbHooks() {
beforeEach(async () => {
await getPrismaTestingHelper().startNewTransaction()
})
afterEach(() => {
getPrismaTestingHelper().rollbackCurrentTransaction()
})
}
+96
View File
@@ -0,0 +1,96 @@
import { PrismaClient } from '@/generated/prisma/client'
import { PrismaTestingHelper } from '@/test-utils'
import { PrismaPg } from '@prisma/adapter-pg'
import { Pool } from 'pg'
import { generateNgrams } from '@/utils/ngram'
const isTest = process.env.NODE_ENV === 'test'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
// We use any here because PrismaTestingHelper is generic and the extended client type is complex
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let prismaTestingHelper: PrismaTestingHelper<any> | null = null
function createPrismaClient() {
const connectionString = process.env.DATABASE_URL
const pool = new Pool({ connectionString })
const adapter = new PrismaPg(pool)
const client = new PrismaClient({ adapter, log: ['error'] })
return client.$extends({
query: {
workflowTask: {
async create({ args, query }) {
const result = await query(args)
// Lazy load workflowService to avoid circular dependency
import('@/workflow/workflow').then((mod) => {
const service = mod?.workflowService
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const task = result as any
if (service && task.status === 'pending') {
// result is the created task, but the extension types are complex
service.submit(task).catch(console.error)
}
})
return result
},
},
asset: {
async create({ args, query }) {
if (typeof args.data.name === 'string') {
args.data.nameNgram = generateNgrams(args.data.name)
}
return query(args)
},
async update({ args, query }) {
if (typeof args.data.name === 'string') {
args.data.nameNgram = generateNgrams(args.data.name)
}
return query(args)
},
async upsert({ args, query }) {
if (typeof args.create.name === 'string') {
args.create.nameNgram = generateNgrams(args.create.name)
}
if (typeof args.update.name === 'string') {
args.update.nameNgram = generateNgrams(args.update.name)
}
return query(args)
},
async updateMany({ args, query }) {
if (typeof args.data.name === 'string') {
args.data.nameNgram = generateNgrams(args.data.name)
}
return query(args)
},
async createMany({ args, query }) {
if (Array.isArray(args.data)) {
for (const item of args.data) {
if (typeof item.name === 'string') {
item.nameNgram = generateNgrams(item.name)
}
}
}
return query(args)
},
},
},
})
}
export const prisma = (isTest
? getPrismaTestingHelper().getProxyClient()
: (globalForPrisma.prisma ?? createPrismaClient())) as unknown as PrismaClient
if (!isTest && process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
export function getPrismaTestingHelper() {
if (!prismaTestingHelper) {
prismaTestingHelper = new PrismaTestingHelper(createPrismaClient())
}
return prismaTestingHelper
}
+100
View File
@@ -0,0 +1,100 @@
import { z } from 'zod'
export const agentTypeSchema = z.enum(['chat', 'autofill', 'embedding', 'transcription'])
export type AgentType = z.infer<typeof agentTypeSchema>
export const agentSkillSchema = z.object({
id: z.string().optional(),
skillId: z.string(),
skill: z
.object({
id: z.string(),
name: z.string(),
})
.optional(),
})
export type AgentSkill = z.infer<typeof agentSkillSchema>
export const agentInfoSchema = z.object({
id: z.string(),
name: z.string(),
type: agentTypeSchema,
enabled: z.boolean(),
avatar: z.string().optional(),
providerId: z.string().optional(),
modelId: z.string().optional(),
thinkingLevel: z.string().optional().default(''),
systemPrompt: z.string().optional(),
soul: z.string().optional(),
skills: z.array(agentSkillSchema).optional(),
})
export type AgentInfo = z.infer<typeof agentInfoSchema>
const baseAgentRequest = z.object({
name: z.string().min(1),
type: agentTypeSchema,
enabled: z.boolean().optional().default(true),
avatar: z.string().optional(),
providerId: z.string().optional(),
modelId: z.string().optional(),
thinkingLevel: z.string().optional().default(''),
systemPrompt: z.string().optional(),
soul: z.string().optional(),
skills: z.array(z.string()).optional(),
})
export const createAgentRequestSchema = baseAgentRequest.superRefine((data, ctx) => {
if (data.type === 'chat' || data.type === 'autofill') {
if (!data.providerId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'providerId is required for chat/autofill agents',
path: ['providerId'],
})
}
if (!data.modelId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'modelId is required for chat/autofill agents',
path: ['modelId'],
})
}
}
})
export type CreateAgentRequest = z.infer<typeof createAgentRequestSchema>
export const updateAgentRequestSchema = baseAgentRequest.superRefine((data, ctx) => {
if (data.type === 'chat' || data.type === 'autofill') {
if (!data.providerId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'providerId is required for chat/autofill agents',
path: ['providerId'],
})
}
if (!data.modelId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'modelId is required for chat/autofill agents',
path: ['modelId'],
})
}
}
})
export type UpdateAgentRequest = z.infer<typeof updateAgentRequestSchema>
export interface CreateAgentParams extends CreateAgentRequest {
teamId: string
}
export interface UpdateAgentParams extends UpdateAgentRequest {
agentId: string
}
export interface DeleteAgentParams {
agentId: string
}
export interface ListAgentsParams {
teamId: string
}
+17
View File
@@ -0,0 +1,17 @@
import { z } from 'zod'
export enum AiProvider {
OpenAi = 'openai',
Google = 'google',
Anthropic = 'anthropic',
ElevenLabs = 'elevenlabs',
}
export const aiProviderSettingsSchema = z.object({
apiKey: z.string().optional(),
baseUrl: z.string().optional(),
chatModels: z.array(z.string()).optional(),
transcribeModels: z.array(z.string()).optional(),
})
export type AiProviderSettings = z.infer<typeof aiProviderSettingsSchema>
+261
View File
@@ -0,0 +1,261 @@
import { z } from 'zod'
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
export const assetInfoPaginatedListSchema = z.object({
data: z.array(z.lazy(() => assetInfoSchema)),
pageInfo: paginationPageInfoSchema,
})
export type AssetInfoPaginatedList = z.infer<typeof assetInfoPaginatedListSchema>
export const previewInfoSchema = z.object({
mediaType: z.string().nullable(),
thumbnailUrl: z.string().optional(),
originalHeight: z.number().optional(),
originalWidth: z.number().optional(),
spriteUrl: z.string().optional(),
})
export type PreviewInfo = z.infer<typeof previewInfoSchema>
export const childPreviewSchema = z.object({
type: z.string().nullable(),
preview: previewInfoSchema.nullable(),
})
export type ChildPreview = z.infer<typeof childPreviewSchema>
export const userInfoSchema = z.object({
id: z.string(),
name: z.string(),
})
export type UserInfo = z.infer<typeof userInfoSchema>
export const fieldValueInfoSchema = z.object({
fieldId: z.string(),
value: z.any(),
})
export type FieldValueInfo = z.infer<typeof fieldValueInfoSchema>
export const ancestorFolderSchema = z.object({
id: z.string(),
name: z.string(),
})
export type AncestorFolder = z.infer<typeof ancestorFolderSchema>
export const mediaMetadataSchema = z.object({
duration: z.number().optional(),
originalWidth: z.number().optional(),
originalHeight: z.number().optional(),
frameRate: z.number().optional(),
})
export type MediaMetadata = z.infer<typeof mediaMetadataSchema>
export const assetInfoSchema = z.object({
id: z.string(),
name: z.string(),
sizeByte: z.number(),
fileCount: z.number(),
type: z.string(),
targetType: z.string().optional().nullable(),
status: z.string(),
mediaType: z.string().nullable(),
latestChildren: z.array(childPreviewSchema).optional(),
preview: previewInfoSchema.nullable().optional(),
createdAt: z.string(),
updatedAt: z.string(),
deletedAt: z.string().nullable().optional(),
creator: userInfoSchema.nullable().optional(),
fieldValues: z.array(fieldValueInfoSchema).optional(),
sortIndex: z.string().optional().nullable(),
media: z
.object({
original: z.object({ downloadUrl: z.string(), key: z.string().optional() }).optional(),
videoTranscodes: z
.array(
z.object({
id: z.string(),
url: z.string(),
key: z.string(),
width: z.number(),
height: z.number(),
size: z.number(),
isRaw: z.boolean(),
}),
)
.optional(),
imageTranscodes: z
.array(
z.object({
id: z.string(),
url: z.string(),
key: z.string(),
width: z.number(),
height: z.number(),
size: z.number(),
isRaw: z.boolean(),
}),
)
.optional(),
videoPreview: z.object({ url: z.string(), key: z.string().optional() }).optional(),
mimeType: z.string().optional(),
metadata: mediaMetadataSchema.optional(),
})
.optional(),
ancestorFolders: z.array(ancestorFolderSchema).optional(),
})
export type AssetInfo = z.infer<typeof assetInfoSchema>
export const createAssetRequestSchema = z.object({
name: z.string(),
type: z.string(),
projectId: z.string().optional(),
parentId: z.string().optional(),
key: z.string().optional(),
sizeByte: z.number().optional(),
contentType: z.string().optional(),
creatorId: z.string().optional(),
})
export type CreateAssetRequest = z.infer<typeof createAssetRequestSchema>
export const getAssetRequestSchema = z.object({
assetId: z.string(),
})
export type GetAssetRequest = z.infer<typeof getAssetRequestSchema>
export const updateAssetNameRequestSchema = z.object({
id: z.string(),
name: z.string(),
})
export type UpdateAssetNameRequest = z.infer<typeof updateAssetNameRequestSchema>
export const listChildrenRequestSchema = z.object({
assetId: z.string().optional(),
assetType: z.string(),
projectId: z.string().optional(),
showRemoved: z.boolean().optional(),
prefix: z.string().optional(),
sort: z.string().optional(),
order: z.string().optional(),
// pagination props mixed in via merge
...paginationParamsSchema.shape,
})
export type ListChildrenRequest = z.infer<typeof listChildrenRequestSchema>
export const createCommentRequestSchema = z.object({
assetId: z.string(),
userId: z.string(),
replyToId: z.string().optional(),
message: z.string(),
annotations: z.any().optional(),
second: z.number().optional(),
attachmentIds: z.array(z.string()),
})
export type CreateCommentRequest = z.infer<typeof createCommentRequestSchema>
export const attachmentInfoSchema = z.object({
id: z.string(),
assetId: z.string(),
url: z.string(),
mediaType: z.string().nullable(),
})
export type AttachmentInfo = z.infer<typeof attachmentInfoSchema>
export type CommentInfo = {
id: string
assetId: string
message: string | null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
annotations: any
creator: UserInfo
replies: CommentInfo[]
attachments: AttachmentInfo[]
mentions: UserInfo[]
createdAt: string
updatedAt: string
isAi: boolean
}
export const commentInfoSchema: z.ZodType<CommentInfo> = z.object({
id: z.string(),
assetId: z.string(),
message: z.string().nullable(),
annotations: z.any(),
creator: userInfoSchema,
replies: z.array(z.lazy(() => commentInfoSchema)),
attachments: z.array(attachmentInfoSchema),
mentions: z.array(userInfoSchema),
createdAt: z.string(),
updatedAt: z.string(),
isAi: z.boolean(),
})
export const reparentAssetsRequestSchema = z.object({
newParentId: z.string(),
assetIds: z.array(z.string()),
creatorId: z.string().optional(),
})
export type ReparentAssetsRequest = z.infer<typeof reparentAssetsRequestSchema>
export const updateFileRequestSchema = z.object({
name: z.string(),
})
export type UpdateFileRequest = z.infer<typeof updateFileRequestSchema>
export const updateAssetOrderRequestSchema = z.object({
beforeIndex: z.string().optional(),
afterIndex: z.string().optional(),
})
export type UpdateAssetOrderRequest = z.infer<typeof updateAssetOrderRequestSchema>
export const deleteFilesRequestSchema = z.object({
ids: z.array(z.string()),
})
export type DeleteFilesRequest = z.infer<typeof deleteFilesRequestSchema>
export const restoreFilesRequestSchema = z.object({
ids: z.array(z.string()),
})
export type RestoreFilesRequest = z.infer<typeof restoreFilesRequestSchema>
export const uploadFileRequestSchema = z.object({
file: z.instanceof(File),
})
export type UploadFileRequest = z.infer<typeof uploadFileRequestSchema>
export const uploadTeamFileResponseSchema = z.object({
key: z.string(),
})
export type UploadTeamFileResponse = z.infer<typeof uploadTeamFileResponseSchema>
export interface ImageTranscode {
id: string
url: string
width: number
height: number
size: number
isRaw: boolean
}
export interface VideoTranscode {
id: string
url: string
width: number
height: number
size: number
isRaw: boolean
}
export const postAttachmentRequestSchema = z.object({
fileName: z.string(),
contentType: z.string(),
size: z.number(),
})
export type PostAttachmentRequest = z.infer<typeof postAttachmentRequestSchema>
export const postAttachmentResponseSchema = z.object({
id: z.string(),
uploadUrl: z.string(),
})
export type PostAttachmentResponse = z.infer<typeof postAttachmentResponseSchema>
+8
View File
@@ -0,0 +1,8 @@
import { z } from 'zod'
export const signupInfoResponseSchema = z.object({
userCount: z.number(),
enablePublicSignup: z.boolean(),
})
export type SignupInfoResponse = z.infer<typeof signupInfoResponseSchema>
+22
View File
@@ -0,0 +1,22 @@
import { z } from 'zod'
export const createFolderRequestSchema = z.object({
name: z.string(),
parentId: z.string(),
})
export type CreateFolderRequest = z.infer<typeof createFolderRequestSchema>
export const updateFolderRequestSchema = z.object({
name: z.string(),
})
export type UpdateFolderRequest = z.infer<typeof updateFolderRequestSchema>
export const deleteFoldersRequestSchema = z.object({
ids: z.array(z.string()),
})
export type DeleteFoldersRequest = z.infer<typeof deleteFoldersRequestSchema>
export const restoreFoldersRequestSchema = z.object({
ids: z.array(z.string()),
})
export type RestoreFoldersRequest = z.infer<typeof restoreFoldersRequestSchema>
+32
View File
@@ -0,0 +1,32 @@
import { z } from 'zod'
export const inviteInfoSchema = z.object({
code: z.string(),
role: z.enum(['editor', 'reviewer', 'owner']),
teamId: z.string(),
teamName: z.string(),
projectId: z.string().optional(),
projectName: z.string().optional(),
inviterName: z.string(),
isUsed: z.boolean(),
})
export type InviteInfo = z.infer<typeof inviteInfoSchema>
export const createTeamInviteRequestSchema = z.object({
role: z.enum(['editor', 'reviewer']),
})
export type CreateTeamInviteRequest = z.infer<typeof createTeamInviteRequestSchema>
export const createProjectInviteRequestSchema = z.object({
role: z.enum(['editor', 'reviewer']),
})
export type CreateProjectInviteRequest = z.infer<typeof createProjectInviteRequestSchema>
export const joinRequestSchema = z.object({
code: z.string(),
})
export type JoinRequest = z.infer<typeof joinRequestSchema>
+80
View File
@@ -0,0 +1,80 @@
import { z } from 'zod'
export const FieldType = {
text: 'text',
longText: 'longText',
select: 'select',
selectMulti: 'selectMulti',
rating: 'rating',
number: 'number',
toggle: 'toggle',
date: 'date',
} as const
export type FieldType = (typeof FieldType)[keyof typeof FieldType]
export const selectOptionSchema = z.object({
id: z.string(),
displayName: z.string(),
color: z.string().optional(),
})
export type SelectOption = z.infer<typeof selectOptionSchema>
export const fieldConfigSchema = z.object({
name: z.string(),
type: z.enum(['text', 'longText', 'select', 'selectMulti', 'rating', 'number', 'toggle', 'date']),
text: z.any().optional(),
longText: z.any().optional(),
select: z.any().optional(),
selectMulti: z.any().optional(),
rating: z.any().optional(),
number: z.any().optional(),
toggle: z.any().optional(),
date: z.any().optional(),
})
export const createFieldRequestSchema = z.object({
key: z.string().optional(),
label: z.string().optional(),
scope: z.string().optional(),
config: fieldConfigSchema,
aiAutofill: z.boolean().default(false),
description: z.string().default(''),
})
export type CreateFieldRequest = z.infer<typeof createFieldRequestSchema>
export const updateFieldRequestSchema = z.object({
label: z.string().optional(),
config: fieldConfigSchema,
aiAutofill: z.boolean().optional(),
description: z.string().optional(),
})
export type UpdateFieldRequest = z.infer<typeof updateFieldRequestSchema>
export const projectFieldOrderSchema = z.object({
fieldId: z.string(),
visible: z.boolean(),
})
export type ProjectFieldOrder = z.infer<typeof projectFieldOrderSchema>
export const updateProjectFieldsOrderRequestSchema = z.array(projectFieldOrderSchema)
export type UpdateProjectFieldsOrderRequest = z.infer<typeof updateProjectFieldsOrderRequestSchema>
export const updateAssetMetadataRequestSchema = z.object({
key: z.string(),
value: z.any(),
})
export type UpdateAssetMetadataRequest = z.infer<typeof updateAssetMetadataRequestSchema>
export const updateAssetMetadataRequestListSchema = z.array(updateAssetMetadataRequestSchema)
export const fieldInfoSchema = z.object({
id: z.string(),
config: fieldConfigSchema,
scope: z.string(),
readOnly: z.boolean(),
visible: z.boolean(),
description: z.string(),
aiAutofill: z.boolean(),
})
export type FieldInfo = z.infer<typeof fieldInfoSchema>
+75
View File
@@ -0,0 +1,75 @@
import { z } from 'zod'
import { NotificationType } from '@/generated/prisma/client'
export const teamUserInfoSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
role: z.string().optional(),
})
export type TeamUserInfo = z.infer<typeof teamUserInfoSchema>
export const entityInfoSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
})
export type EntityInfo = z.infer<typeof entityInfoSchema>
export const assetPreviewSchema = z.object({
id: z.string().optional(),
mediaType: z.string().optional(),
name: z.string().optional(),
preview: z.string().optional(),
})
export type AssetPreview = z.infer<typeof assetPreviewSchema>
export const notificationInfoSchema = z.object({
id: z.string().optional(),
creator: teamUserInfoSchema.optional(),
type: z.string().optional(),
team: entityInfoSchema.optional(),
project: entityInfoSchema.optional(),
asset: assetPreviewSchema.optional(),
user: teamUserInfoSchema.optional(),
createdAt: z.string().optional(),
isRead: z.boolean().optional(),
})
export type NotificationInfo = z.infer<typeof notificationInfoSchema>
export const listNotificationsRequestSchema = z.object({
unreadOnly: z
.union([z.boolean(), z.string()])
.transform((v) => v === true || v === 'true')
.optional(),
after: z.string().optional(),
pageSize: z.coerce.number().optional(),
})
export type ListNotificationsRequest = z.infer<typeof listNotificationsRequestSchema>
export const markNotificationReadRequestSchema = z.object({
notificationId: z.string().min(1),
})
export type MarkNotificationReadRequest = z.infer<typeof markNotificationReadRequestSchema>
// Service types
export interface CreateNotificationRequest {
type: NotificationType
teamId: string
projectId?: string
creatorId?: string
assetId?: string
taskId?: string
userId?: string
commentMessage?: string // For parsing mentions
}
export interface ListNotificationParams {
unreadOnly?: boolean
after?: string
pageSize?: number
}
+19
View File
@@ -0,0 +1,19 @@
import { z } from 'zod'
export const paginationPageInfoSchema = z.object({
cursor: z.string().optional(),
total: z.number().optional(),
})
export type PaginationPageInfo = z.infer<typeof paginationPageInfoSchema>
export const paginationParamsSchema = z.object({
first: z.coerce.number().optional(),
after: z.string().optional(),
includeCount: z
.union([z.boolean(), z.string()])
.transform((v) => v === true || v === 'true')
.optional(),
})
export type PaginationParams = z.infer<typeof paginationParamsSchema>
+99
View File
@@ -0,0 +1,99 @@
import { z } from 'zod'
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
export const createProjectRequestSchema = z.object({
name: z.string(),
coverImageKey: z.string().optional(),
enableNotification: z.boolean().default(false),
})
export type CreateProjectRequest = z.infer<typeof createProjectRequestSchema>
export const updateProjectRequestSchema = z.object({
name: z.string().optional(),
coverImageKey: z.string().optional(),
enableNotification: z.boolean().optional(),
})
export type UpdateProjectRequest = z.infer<typeof updateProjectRequestSchema>
export const projectInfoSchema = z.object({
id: z.string(),
name: z.string(),
rootFolder: z.string().optional(),
coverImage: z.string().optional(),
coverImageKey: z.string().optional(),
enableNotification: z.boolean(),
updatedAt: z.union([z.string(), z.date()]),
})
export type ProjectInfo = z.infer<typeof projectInfoSchema>
export const listProjectsRequestSchema = z
.object({
sortBy: z.string().optional(),
sortDirection: z.enum(['asc', 'desc']).optional(),
})
.merge(paginationParamsSchema)
export const listProjectsResponseSchema = z.object({
data: z.array(projectInfoSchema),
pageInfo: paginationPageInfoSchema,
})
export const getProjectTeamResponseSchema = z.object({
teamId: z.string(),
})
export type GetProjectTeamResponse = z.infer<typeof getProjectTeamResponseSchema>
export const projectUserInfoSchema = z.object({
id: z.string(),
name: z.string(),
role: z.string(),
})
export type ProjectUserInfo = z.infer<typeof projectUserInfoSchema>
export const botInfoSchema = z.object({
id: z.string(),
name: z.string(),
})
export type BotInfo = z.infer<typeof botInfoSchema>
export const recentlyDeletedRequestSchema = z
.object({
assetType: z.string(),
sort: z.enum(['createdAt', 'name', 'size']).optional(),
order: z.enum(['asc', 'desc']).optional(),
})
.merge(paginationParamsSchema)
// Service Layer Interfaces
export interface ServiceCreateProjectRequest {
teamId: string
name: string
coverImageKey?: string
enableNotification?: boolean
}
export interface ServiceUpdateProjectRequest {
projectId: string
name?: string
coverImageKey?: string
enableNotification?: boolean
}
export interface ServiceListProjectsRequest {
teamId: string
userId: string
sortBy?: string
sortDirection?: 'asc' | 'desc'
pagination: z.infer<typeof paginationParamsSchema>
}
export interface ServiceAddProjectMemberRequest {
projectId: string
userId: string
role: string
}
export interface ServiceListProjectMembersRequest {
projectId: string
includeAgents?: boolean
}
+59
View File
@@ -0,0 +1,59 @@
import { z } from 'zod'
export { z }
// We define a serializable version of ProviderConfig for our API and DB
// as the original ProviderConfig interface includes non-serializable fields (functions)
export const providerModelConfigSchema = z.object({
api: z.string().optional(),
reasoning: z.boolean().default(false),
input: z.array(z.enum(['text', 'image'])).default(['text']),
contextWindow: z.number().int().positive().default(128000),
maxTokens: z.number().int().positive().default(4096),
cost: z.object({
input: z.number().nonnegative().default(0),
output: z.number().nonnegative().default(0),
cacheRead: z.number().nonnegative().default(0),
cacheWrite: z.number().nonnegative().default(0),
}),
})
export const providerModelSchema = z.object({
id: z.string().optional(),
modelId: z.string().min(1, 'Model ID is required'),
name: z.string().min(0).default(''),
config: providerModelConfigSchema,
})
export const providerConfigSchema = z.object({
baseUrl: z.string().url('Must be a valid URL').optional().or(z.literal('')),
apiKey: z.string().optional().or(z.literal('')),
api: z.string().min(1, 'API Protocol is required'),
headers: z.record(z.string(), z.string()).optional(),
authHeader: z.boolean().optional(),
})
export type ProviderConfigSerializable = z.infer<typeof providerConfigSchema>
export const createProviderRequestSchema = z.object({
name: z.string().min(1, 'Provider name is required'),
config: providerConfigSchema,
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
})
export const updateProviderRequestSchema = z.object({
config: providerConfigSchema,
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
})
export const providerResponseSchema = z.object({
id: z.string(),
name: z.string(),
isBuiltin: z.boolean(),
config: providerConfigSchema,
models: z.array(providerModelSchema).optional(),
modelsCount: z.number().optional(),
createdAt: z.date(),
updatedAt: z.date(),
})
export type ProviderResponse = z.infer<typeof providerResponseSchema>
+7
View File
@@ -0,0 +1,7 @@
export interface ObjectInfo {
key: string
size: number
lastModified: Date
contentType: string
eTag: string
}
+59
View File
@@ -0,0 +1,59 @@
import { z } from 'zod'
import { paginationParamsSchema } from './pagination'
export const searchConditionOperatorSchema = z.enum([
'is',
'eq',
'neq',
'gt',
'gte',
'lt',
'lte',
'contains',
'notContains',
'isEmpty',
'isNotEmpty',
'in',
'notIn',
'hasAny',
'hasAll',
'hasNone',
'isWithin',
])
export type SearchConditionOperator = z.infer<typeof searchConditionOperatorSchema>
export const searchConditionSchema = z.object({
field: z.string(),
operator: searchConditionOperatorSchema,
value: z.any(),
})
export type SearchCondition = z.infer<typeof searchConditionSchema>
export const searchSortOrderSchema = z.enum(['asc', 'desc'])
export type SearchSortOrder = z.infer<typeof searchSortOrderSchema>
export const searchSortSchema = z.object({
field: z.string(),
order: searchSortOrderSchema,
})
export type SearchSort = z.infer<typeof searchSortSchema>
export const searchOperatorSchema = z.enum(['AND', 'OR'])
export type SearchOperator = z.infer<typeof searchOperatorSchema>
export const searchAssetTypeSchema = z.enum(['file', 'folder'])
export type SearchAssetType = z.infer<typeof searchAssetTypeSchema>
export const searchRequestSchema = z
.object({
operator: searchOperatorSchema.optional().default('AND'),
conditions: z.array(searchConditionSchema).optional().default([]),
sort: searchSortSchema.optional(),
assetType: searchAssetTypeSchema.optional(),
showSymlink: z.boolean().optional(),
recursively: z.boolean().optional().default(true),
query: z.string().optional(),
})
.merge(paginationParamsSchema)
export type SearchRequest = z.infer<typeof searchRequestSchema>
+52
View File
@@ -0,0 +1,52 @@
import { z } from 'zod'
import { paginationParamsSchema } from './pagination'
export interface ShareLinkInfo {
id: string
name: string
expireAt?: string
isDisabled: boolean
hasPassword: boolean
defaultSortOrder?: string
fieldVisibility?: Record<string, boolean>
rootFolderId: string
projectId: string
isExpired: boolean
createdAt: string
updatedAt: string
}
export const createShareLinkRequestSchema = z.object({
name: z.string().min(1),
expireAt: z.string().datetime().optional(),
password: z.string().optional(),
isDisabled: z.boolean().optional(),
defaultSortOrder: z.string().optional(),
})
export type CreateShareLinkRequest = z.infer<typeof createShareLinkRequestSchema>
export const updateShareLinkRequestSchema = z.object({
name: z.string().min(1).optional(),
expireAt: z.string().datetime().optional().nullable(),
password: z.string().optional().nullable(),
isDisabled: z.boolean().optional(),
defaultSortOrder: z.string().optional().nullable(),
fieldVisibility: z.record(z.string(), z.boolean()).optional().nullable(),
})
export type UpdateShareLinkRequest = z.infer<typeof updateShareLinkRequestSchema>
export const listShareLinksRequestSchema = paginationParamsSchema.extend({
projectId: z.string().optional(), // projectId can come from param
})
export type ListShareLinksRequest = z.infer<typeof listShareLinksRequestSchema> & {
projectId: string
}
export const addAssetToShareRequestSchema = z.object({
assetIds: z.array(z.string().min(1)).min(1),
})
export type AddAssetToShareRequest = z.infer<typeof addAssetToShareRequestSchema>
+37
View File
@@ -0,0 +1,37 @@
import { z } from 'zod'
export interface SkillInfo {
id: string
name: string
description: string | null
config: PrismaJson.SkillConfig | null
assetId: string
hash: string
createdAt: string
updatedAt: string
}
export const upsertSkillRequestSchema = z.object({
assetId: z.string().optional(),
githubUrl: z.string().optional(),
override: z.boolean().optional(),
})
export type UpsertSkillRequest = z.infer<typeof upsertSkillRequestSchema>
export const updateSkillConfigRequestSchema = z.object({
config: z.object({
environmentVariables: z.array(
z.object({
name: z.string(),
default: z.string().optional(),
}),
),
}),
})
export type UpdateSkillConfigRequest = z.infer<typeof updateSkillConfigRequestSchema>
export interface ListSkillsResponse {
skills: SkillInfo[]
}
+102
View File
@@ -0,0 +1,102 @@
import { z } from 'zod'
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
import { UserType } from '@/generated/prisma/enums'
export const createTeamRequestSchema = z.object({
name: z.string(),
})
export type CreateTeamRequest = z.infer<typeof createTeamRequestSchema>
export const teamInfoSchema = z.object({
id: z.string(),
name: z.string(),
rootFolder: z.string().optional(),
updatedAt: z.union([z.string(), z.date()]),
})
export type TeamInfo = z.infer<typeof teamInfoSchema>
export const getUserTeamsRequestSchema = paginationParamsSchema
export type GetUserTeamsRequest = z.infer<typeof getUserTeamsRequestSchema>
export const getUserTeamsResponseSchema = z.object({
data: z.array(teamInfoSchema),
pageInfo: paginationPageInfoSchema,
})
export type GetUserTeamsResponse = z.infer<typeof getUserTeamsResponseSchema>
export const joinTeamRequestSchema = z.object({
teamId: z.string(),
userId: z.string(),
})
export type JoinTeamRequest = z.infer<typeof joinTeamRequestSchema>
export const getMeResponseSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().optional(),
role: z.string(),
})
export type GetMeResponse = z.infer<typeof getMeResponseSchema>
export const userInfoSchema = z.object({
id: z.string(),
name: z.string(),
role: z.string(),
email: z.string().optional(),
type: z.nativeEnum(UserType).optional(),
})
export type UserInfo = z.infer<typeof userInfoSchema>
export const listMembersQuerySchema = z.object({
includeAgents: z
.string()
.optional()
.transform((v) => v === 'true'),
})
export const updateTeamSettingsRequestSchema = z.object({
key: z.string(),
value: z.any(),
})
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
export const VideoTranscodeStrategy = {
disable: 'disable',
single: 'single',
full: 'full',
} as const
export type VideoTranscodeStrategy =
(typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy]
export const ImageTranscodeStrategy = {
disable: 'disable',
single: 'single',
} as const
export type ImageTranscodeStrategy =
(typeof ImageTranscodeStrategy)[keyof typeof ImageTranscodeStrategy]
// Service Layer Interfaces
export interface ServiceCreateTeamRequest {
name: string
}
export interface ServiceGetUserTeamsRequest {
userId: string
pagination: z.infer<typeof paginationParamsSchema>
}
export interface ServiceJoinTeamRequest {
teamId: string
userId: string
}
export interface ServiceGetMeRequest {
teamId: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
user: any
}
export interface ServiceGetTeamMembersRequest {
teamId: string
includeAgents?: boolean
}
+67
View File
@@ -0,0 +1,67 @@
import { z } from 'zod'
export type FileNode = {
name: string
id: string
size: number
children: FileNode[]
type: string
mediaType?: string
}
export const fileNodeSchema: z.ZodType<FileNode> = z.lazy(() =>
z.object({
name: z.string(),
id: z.string(),
size: z.number(),
children: z.array(fileNodeSchema),
type: z.string(),
mediaType: z.string().optional(),
}),
)
export const createUploadTaskRequestSchema = z.object({
parentId: z.string(),
files: z.array(fileNodeSchema),
})
export type CreateUploadTaskRequest = z.infer<typeof createUploadTaskRequestSchema>
export const presignedUrlSchema = z.object({
id: z.string(),
fileId: z.string(),
url: z.string(),
})
export type PresignedUrl = z.infer<typeof presignedUrlSchema>
export const createUploadTaskResponseSchema = z.object({
taskId: z.string(),
presignedUrls: z.array(presignedUrlSchema),
})
export type CreateUploadTaskResponse = z.infer<typeof createUploadTaskResponseSchema>
export const confirmFileUploadRequestSchema = z.object({
fileId: z.string(),
errorMessage: z.string().optional(),
})
export type ConfirmFileUploadRequest = z.infer<typeof confirmFileUploadRequestSchema>
export const taskInfoSchema = z.object({
id: z.string(),
name: z.string(),
total: z.number(),
uploaded: z.number(),
createdAt: z.string(),
})
export type TaskInfo = z.infer<typeof taskInfoSchema>
export const localUploadQuerySchema = z.object({
bucket: z.string(),
key: z.string(),
Signature: z.string(),
})
export type LocalUploadQuery = z.infer<typeof localUploadQuerySchema>
export const localUploadBodySchema = z.object({
file: z.instanceof(File),
})
export type LocalUploadBody = z.infer<typeof localUploadBodySchema>
+15
View File
@@ -0,0 +1,15 @@
import { z } from 'zod'
export const userMetadataItemSchema = z.object({
key: z.string(),
value: z.unknown(),
})
export type UserMetadataItem = z.infer<typeof userMetadataItemSchema>
export const updateUserMetadataRequestSchema = z.object({
value: z.unknown(),
})
export type UpdateUserMetadataRequest = z.infer<typeof updateUserMetadataRequestSchema>
export const listUserMetadataResponseSchema = z.array(userMetadataItemSchema)
export type ListUserMetadataResponse = z.infer<typeof listUserMetadataResponseSchema>
+24
View File
@@ -0,0 +1,24 @@
import { z } from 'zod'
export const createVersionStackRequestSchema = z.object({
fileIds: z.array(z.string()),
})
export type CreateVersionStackRequest = z.infer<typeof createVersionStackRequestSchema>
export interface CreateVersionStackParams {
fileIds: string[]
projectId: string
creatorId: string
}
export const changeStackFileVersionRequestSchema = z.object({
fileId: z.string(),
beforeId: z.string(),
})
export type ChangeStackFileVersionRequest = z.infer<typeof changeStackFileVersionRequestSchema>
export interface ChangeStackFileVersionParams {
stackId: string
fileId: string
beforeId: string
}

Some files were not shown because too many files have changed in this diff Show More