12 KiB
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:
git checkout -b <branch-name>
Complete the task on that branch.
After finishing the work and verifying that all checks pass:
- Stage and commit your changes.
- Push the branch to
origin. - Open a pull request using the GitHub CLI.
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:
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
Example:
feat(auth): add OAuth login support
The commit contains the following structural elements, to communicate intent to the consumers of your library:
fix:a commit of the typefixpatches a bug in your codebase.feat:a commit of the typefeatintroduces a new feature to the codebase.BREAKING CHANGE:a footer or!after the type/scope introduces a breaking API change.- 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
## 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 lintbun run formatbun run typecheckbun 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
anyis strictly forbidden and will result in lint errors. You should useunknowninstead when the type is not known. If you absolutely must useanydue 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:
- 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 - DTO Layer (
src/dtos): All dtos used in api, which also used by ui for type-safty. - Service Layer (
src/services): Contains business logic and interacts with the Database via Prisma. - 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.
export class MyService { async doSomething() { ... } } export const myService = new MyService() - Usage: Import and use the exported instance.
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.
const app = new Hono() const route = app .get('/', ...) .post('/', ...) export default route - Type Safety: Use
zValidatorfor 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
Testcontainersalongside aPrismaTestingHelperwhich 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 thedescribeblock. This automatically registersbeforeEachandafterEachhooks to manage transaction state. - Import
prismafrom@/dbdirectly to interact with the database in tests. The testing helper automatically proxies it.
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')orvi.mock('@/services/myService'). - Verify that the API calls the Service methods correctly.
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 devto create and apply migrations during development. - Production: Use
bun --bun run prisma migrate deployto 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 theidfield inschema.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
FileServicemay still useulid()internally, but this is separate from the database ID.
- Exception: File names generated by
- Sorting: All list APIs must order results by
iddescending (orderBy: { id: 'desc' }) to ensure consistent, time-based sorting (since ULIDs are sortable). Do not sort bycreatedAtas it is not indexed.
Infinite Scroll & Pagination
- Frontend: Use the
useInfiniteScrollhook for all list UIs.- Located in
src/ui/hooks/use-infinite-scroll.ts. - Pass a
fetchDatafunction that acceptspageandlimit.
- Located in
- Backend:
- Most list APIs support cursor pagination using opaque tokens (via
hyrumtokenlogic) using thepaginateQueryhelper function. - Pass
PaginationParamscontainingfirst(limit) andafter(cursor). - The default
limitshould be 20. - Always use the
paginateQueryhelper function fromsrc/services/pagination.tsfor consistent cursor pagination.
- Most list APIs support cursor pagination using opaque tokens (via
Temporal Workflow & Activities
We use a custom workflow engine that supports both Local (polling-based) and Temporal (production-grade) execution.
Architecture
- Workflows (
src/services/workflow/workflows): Orchestrate multiple activities. They must be deterministic and compatible with Temporal's V8 isolate. Usesrc/services/workflow/workflow-utils.tsfor environment-aware functions likesleepandgetActivities. - Activities (
src/services/workflow/activities): Perform the actual work (DB updates, API calls, media processing). Grouped by domain (e.g.,ai.ts,transcode.ts). - Executors:
LocalExecutor: Polls the database forpendingtasks and executes them directly.TemporalExecutor: Submits tasks to a Temporal cluster.
- Automatic Submission: New
WorkflowTaskrecords are automatically submitted to theWorkflowServicevia a Prisma Client Extension defined insrc/db.ts.
Temporal Workflow Patterns
- Definition: Define workflows as exported async functions.
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.tsfor Temporal worker registration. - Environment Compatibility: Always use
getActivities()fromworkflow-utils.tsto 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 thesrc/services/<domain>/models.tsinstead. - DTO Naming: Do not append the
Dtosuffix to types or interfaces (e.g. useJoinRequestinstead ofJoinRequestDto).