This file provides guidance to AI coding agents when working with code in this repository.
Flood is a modern web UI for various torrent clients (rTorrent, qBittorrent, Transmission, Deluge) with multi-user and multi-client support. Built with TypeScript, React, MobX, and Node.js/Fastify.
# After EVERY few edits (catches issues immediately):
pnpm run check-types # TypeScript compilation check - RUN THIS OFTEN!
pnpm run lint # ESLint with TypeScript rules (max warnings: 0)
# Before committing any changes:
pnpm run format-source # Prettier auto-fix all files (prettier -w .)
pnpm run check-source-formatting # Verify formatting is correct (prettier -c .)
pnpm run build # Ensure production build works (panda codegen + build)
pnpm run test # Run tests to catch regressions
# Note: lint-staged runs automatically on git commits via Husky hooks- TypeScript errors compound - One type error can cascade into dozens
- Lint errors block CI - PR will fail if linting fails
- Build failures are expensive - Finding issues after large changes is painful
- Small, validated changes - Easier to debug and review
- Make small, focused changes (< 50 lines)
- Run
pnpm run check-typesimmediately - Fix any type errors before continuing
- Run
pnpm run lintafter each component/function - Test the specific feature you changed
- Only then move to the next change
# Package Manager: pnpm (v11.5.2) is the project's package manager
pnpm install --frozen-lockfile # Install dependencies with lockfile
pnpm run build # Build production (rolldown for server, Vite for client)
pnpm start # Start production server (node --enable-source-maps dist/index.js)
pnpm start -- --port 8080 # With custom options (pass args after --)pnpm run start:development:server # Server with tsx watch mode (hot reload via tsx watch)
pnpm run start:development:client # Client Vite dev server (port 4200, with Panda CSS watch)
# Run both in separate terminals for full development environmentFrontend Development Tips:
- Client auto-proxies API calls to server (default: http://127.0.0.1:3000)
- HMR (Hot Module Replacement) enabled for instant updates
- React Refresh preserves component state during edits
- Source maps enabled for debugging
pnpm test # Run all Vitest integration tests (spawns real torrent clients!)
pnpm test:watch # Watch mode with Vitest
pnpm test -- --project rtorrent server/routes/api/torrents.test.ts # Run a specific server test against rTorrent
pnpm run test-storybook # Run Storybook interaction tests
pnpm run test-storybook # Run Storybook interaction tests
# Test specific torrent clients (runs relevant Vitest project):
pnpm test -- --project rtorrent
pnpm test -- --project qbittorrent
pnpm test -- --project transmission
pnpm test -- --project authNote:
vitest.config.mtsonly configures backend (server/) integration test projects. The frontend (client/) does not use Vitest — frontend tests are covered by Storybook interaction tests (pnpm run test-storybook). Do not add Vitest projects or.test.tsunit tests for client code.
- MobX with decorators for reactive state
- Computed values for derived state (filtered/sorted torrents)
- Fast-json-patch for efficient diff updates from server
- Pattern:
makeAutoObservable(this)in store constructors
- Server-Sent Events at
/api/activity-stream - Server sends either:
TORRENT_LIST_FULL_UPDATE- Complete torrent listTORRENT_LIST_DIFF_CHANGE- JSON Patch operations array
- Client applies patches directly to MobX stores
- Connection auto-retries on failure (retry: 500ms)
- Keep-alive pings every 500ms
- Server tracks previous state per connection for efficient diffs
All API endpoints use Zod schemas for validation:
fastify.route({
...,
schema: {
body: RequestBodySchema,
},
...,
})Flood provides an OpenAPI specification and interactive Swagger UI:
- OpenAPI spec: Available at
/api/openapi.json - Swagger UI: Interactive API documentation at
/api/docs/ - All endpoints are documented with Zod schemas that generate OpenAPI schemas
- Uses
@fastify/swaggerwithfastify-type-provider-zodfor automatic schema generation
- Located in
~/.local/share/flood/by default users.db- User accounts with argon2 hashed passwordssettings.db- User settings- Auto-compaction enabled
- Server: rolldown bundles to single file (
dist/index.js) with source maps - Client: Vite with code splitting, CSS extraction, asset optimization
- Assets: Static files copied to
dist/assets/ - CSS: Panda CSS generates styled-system via
panda codegen
{
"bracketSpacing": false,
"printWidth": 120,
"singleQuote": true,
"trailingComma": "all"
}- Use
node:prefix for Node.js builtins (node:fs,node:path) - Simple import sorting enforced (except in client code for CRA parity)
- Path aliases configured in tsconfig.json:
@client/*→client/src/javascript/*@server/*→server/*@shared/*→shared/*
- Strict mode enabled
- Unused vars with
_prefix are allowed _idunderscore allowed for database IDs
Each client in /server/services/[client]/ follows this pattern:
clientRequestManager.ts- Handles protocol-specific communicationclientGatewayService.ts- Implements common interfaceutil/torrentPropertiesUtil.ts- Normalizes client-specific data
Protocol Details:
- rTorrent: SCGI with XML-RPC or JSON-RPC (checks capability)
- qBittorrent: REST API with cookie-based session
- Transmission: JSON-RPC with session tokens
- Deluge: Rencode protocol over TCP
- JWT tokens issued on login, stored in httpOnly cookies
- Passport.js validates tokens via
passport-jwtstrategy - Token contains username + issued-at timestamp
- User lookup verifies token hasn't been issued before password change
- CRITICAL: Flood must have same filesystem view as torrent client
- Path
/downloads/fileto torrent client =/downloads/fileto Flood - Cannot be
/mnt/different/downloads/file- operations will fail - Use
--allowedpathto restrict file access
- JSON message catalogs in
/client/src/javascript/i18n/strings/ - Lazy-loaded based on user preference
- Lingui catalogs are loaded and compiled through
@lingui/vite-plugin; - Only modify
en.json— all other locale files are generated from a translation platform and should never be edited directly
Integration tests spawn actual torrent clients:
- Creates temporary directory with config
- Starts rTorrent/qBittorrent/Transmission
- Tests against real client behavior
- Cleans up processes after tests
- 20-second timeouts for client startup
- SSE stream testing via PassThrough streams
- Mocks HTTP requests with axios-mock-adapter
- The backends use fastify as http framework.
- Server tracks previous torrent state per connection
- Sends JSON Patch operations for changes
- Reduces bandwidth for large torrent lists
- rTorrent adapter uses PQueue (concurrency: 1)
- Prevents SCGI connection issues
- Other clients handle concurrent requests
- Tags cannot contain commas (used as delimiter)
- Enforced via Zod regex:
/^[^,]*$/
- Only available for specific torrent client versions
- Feature detection happens at runtime
- Located in OS temp directory
- Used for torrent creation, file downloads
- Auto-cleaned on server restart
Contains:
users.db- User databasesettings.db- User settingstemp/- Temporary files
For reverse proxy setups:
/apps/flood- Serves at subdirectory- Must not have trailing slash in config
- Affects all HTTP endpoints and asset paths
NODE_ENV=development- Enables dev features
- Create
/server/services/NewClient/directory - Implement
clientGatewayService.tsextendingBaseService- Run
pnpm run check-typesafter implementing each method
- Run
- Add connection settings schema in
/shared/schema/ClientConnectionSettings.ts- Run
pnpm run check-typesto verify schema integration
- Run
- Update service factory in
/server/services/index.ts - Run
pnpm run buildto ensure everything compiles - Run
pnpm testto verify no regressions
- Define Zod schema in
/shared/schema/api/- Run
pnpm run check-typesafter schema definition
- Run
- Add route handler in
/server/routes/api/- Run
pnpm run lintto check route implementation
- Run
- Create action in
/client/src/javascript/actions/- Run
pnpm run check-typesto verify client-server contract
- Run
- Update TypeScript types in
/shared/types/api/ - Run
pnpm run buildbefore testing the endpoint - Test the endpoint manually, then run
pnpm test
- Update type in
/shared/types/Torrent.ts- Run
pnpm run check-typesimmediately - this affects many files!
- Run
- Fix all TypeScript errors before proceeding
- Modify normalizers in each client's
torrentPropertiesUtil.ts- Run
pnpm run check-typesafter each client adapter
- Run
- Update torrent list columns if needed
- Run
pnpm run buildto verify production build - Run
pnpm testto ensure client adapters still work
- TypeScript errors? Run
pnpm run check-typesand fix from top to bottom - Lint errors? Run
pnpm run lint- most are auto-fixable withpnpm run format-source - Build fails? Check both server (rolldown) and client (Vite) output
- Tests fail? Run specific test file with
pnpm test -- path/to/test - Panda CSS issues? Run
panda codegento regenerate styled-system
- Server-side debugging: VS Code launch config included
- Client-side: Use React DevTools + MobX DevTools
- SSE stream: Check Network tab for
/api/activity-stream - SCGI issues: Enable
NODE_ENV=developmentfor verbose logs
- Each user gets their own service instances (torrent client, settings, etc.)
- Services are bootstrapped on user login, destroyed on logout
- Cross-service communication via service references
- Event-driven updates via
onServicesUpdated()callbacks
- Adaptive polling rates based on active SSE connections
- Client connection health monitoring with auto-retry
- rTorrent: Single-threaded request queue (PQueue concurrency: 1)
- Other clients: Concurrent request handling
# Start both for full development:
npm run start:development:server # Backend on port 3000 (tsx watch mode)
pnpm run start:development:client # Frontend on port 4200 (Vite dev server)
# Frontend proxies API calls to backend (configurable):
npm run start:development:client -- --proxy http://localhost:3000Key Frontend Technologies:
- React 18 with hooks and functional components
- MobX 6 for reactive state management (with decorators)
- Panda CSS for styling (replaced Emotion)
- React Router 6 for routing
- Lingui v5 for internationalization
npm run storybook # Launch Storybook on port 6006
npm run build-storybook # Build static Storybook
npm run test-storybook # Run Storybook testsStorybook Architecture:
- Stories located in
client/src/javascript/components/**/*.stories.tsx - Webpack aliases configured for
@client/and@shared/paths - Full CSS module support matching production Vite config
- Storybook uses Vite to match the application build
Storybook replaces real actions with mocks at build time using a custom Vite plugin in .storybook/main.ts:
// In .storybook/main.ts
{
name: 'storybook-mock-action-modules',
enforce: 'pre',
resolveId(id: string, _importer: string | undefined) {
// Intercept @client/actions/* imports and redirect to mocks
const cleanId = id.split('?')[0];
for (const moduleName of MOCKED_ACTION_MODULES) {
const aliasPath = `@client/actions/${moduleName}`;
const realPath = path.resolve(realActionsDir, `${moduleName}.ts`);
if (cleanId === aliasPath || cleanId === realPath) {
return path.resolve(mockDir, `${moduleName}.ts`);
}
}
return undefined;
},
}This ensures all imports of actions are replaced with mock implementations.
// .storybook/mocks/MockStateStore.ts
class MockStateStore {
private state: MockState = {
torrents: {...TORRENT_STATES},
settings: {...MOCK_FLOOD_SETTINGS},
// ... other state
};
setState(updates: Partial<MockState>): void {
/* ... */
}
reset(): void {
/* ... */
}
}Key Pattern: Single source of truth for all mock data that:
- Provides preset torrent states (downloading, seeding, stopped, error)
- Manages settings and UI state
- Simulates real-time updates without network calls
const setupTorrent = (torrentState, viewSize = 'expanded') => ({
loaders: [
async () => {
mockStateStore.reset();
mockStateStore.setState({
torrents: {[torrentState.hash]: torrentState},
settings: {torrentListViewSize: viewSize},
});
FloodActions.startActivityStream(); // Triggers mock data load
},
],
});Mock actions simulate real behavior without network calls:
// .storybook/mocks/FloodActions.ts
startActivityStream() {
const state = mockStateStore.getState();
// Simulate full torrent update
TorrentStore.handleTorrentListFullUpdate(state.torrents);
UIStore.satisfyDependency('torrent-list');
// Simulate settings update
SettingStore.handleSettingsFetchSuccess(state.settings);
// Compute and send taxonomy
TorrentFilterStore.handleTorrentTaxonomyFullUpdate(taxonomy);
}12 MobX Stores managing different domains:
TorrentStore- Torrent list and selection stateSettingStore- User preferences and UI settingsUIStore- UI state and dependency trackingTransferDataStore- Transfer rates and historyTorrentFilterStore- Filtering and taxonomyAuthStore- Authentication stateClientStatusStore- Torrent client connectionNotificationStore- System notificationsFeedStore- RSS feed managementDiskUsageStore- Disk usage monitoringConfigStore- Application configurationAlertStore- User alerts and messages
Store Pattern:
class Store {
constructor() {
makeAutoObservable(this); // Auto-observable for all properties
}
@computed get derivedValue() {
/* ... */
}
@action updateValue() {
/* ... */
}
}-
Create Stories for New Components:
- Test different states (loading, error, empty, full)
- Test both expanded and condensed views
- Test dark/light themes
-
Use Mock State Store:
- Reset state between stories
- Provide realistic test data
- Simulate user interactions
-
Test with Storybook Play Functions:
play: async ({canvasElement}) => { const canvas = within(canvasElement); const element = await canvas.findByRole('button'); expect(element).toBeInTheDocument(); };
-
CSS Modules Pattern:
- Use
.module.scssfor component styles - Import as
stylesobject - Apply with
className={styles.className}
- Use
-
Panda CSS for New Components:
- Use styled-system utilities
- Run
panda codegenafter config changes - Located in
client/src/javascript/styled-system/
- Small changes, frequent validation - This codebase has strict TypeScript
- Run
pnpm run check-typesafter every change - Seriously, every change - CI will reject your PR if lint/types/tests fail
- When in doubt, validate - Better to check too often than debug for hours