mirror of
https://github.com/soconnor0919/hristudio.git
synced 2026-03-24 03:37:51 -04:00
Compare commits
15 Commits
20d6d3de1a
...
3270e3f8fe
| Author | SHA1 | Date | |
|---|---|---|---|
| 3270e3f8fe | |||
| bfd1924897 | |||
| 0827a791c6 | |||
| ecf0ab9103 | |||
| 49e0df016a | |||
| 8529d0ef89 | |||
| 67ad904f62 | |||
| 519e6a2606 | |||
| b353ef7c9f | |||
| cbd31e9aa4 | |||
| 37feea8df3 | |||
| cf3597881b | |||
|
|
add3380307 | ||
|
|
79bb298756 | ||
|
|
a5762ec935 |
48
README.md
48
README.md
@@ -64,16 +64,15 @@ bun dev
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **Framework**: Next.js 15 with App Router and React 19 RC
|
||||
- **Framework**: Next.js 15 (16.x compatible) with App Router and React 19
|
||||
- **Language**: TypeScript (strict mode) - 100% type safety throughout
|
||||
- **Database**: PostgreSQL with Drizzle ORM for type-safe operations
|
||||
- **Authentication**: NextAuth.js v5 with database sessions and JWT
|
||||
- **Authentication**: Better Auth with database sessions
|
||||
- **API**: tRPC for end-to-end type-safe client-server communication
|
||||
- **UI**: Tailwind CSS + shadcn/ui (built on Radix UI primitives)
|
||||
- **Storage**: Cloudflare R2 (S3-compatible) for media files
|
||||
- **Deployment**: Vercel serverless platform with Edge Runtime
|
||||
- **Real-time**: WebSocket with polling fallback for trial execution
|
||||
- **Package Manager**: Bun exclusively
|
||||
- **Real-time**: WebSocket with Edge Runtime compatibility
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -203,14 +202,11 @@ src/
|
||||
|
||||
Comprehensive documentation available in the `docs/` folder:
|
||||
|
||||
- **[Quick Reference](docs/quick-reference.md)**: 5-minute setup guide and essential commands
|
||||
- **[Project Overview](docs/project-overview.md)**: Complete feature overview and architecture
|
||||
- **[Implementation Details](docs/implementation-details.md)**: Architecture decisions and patterns
|
||||
- **[Database Schema](docs/database-schema.md)**: Complete PostgreSQL schema documentation
|
||||
- **[API Routes](docs/api-routes.md)**: Comprehensive tRPC API reference
|
||||
- **[Core Blocks System](docs/core-blocks-system.md)**: Repository-based block architecture
|
||||
- **[Plugin System](docs/plugin-system-implementation-guide.md)**: Robot integration guide
|
||||
- **[Project Status](docs/project-status.md)**: Current completion status (98% complete)
|
||||
- **[Quick Reference](docs/quick-reference.md)**: Essential commands and setup
|
||||
- **[Implementation Guide](docs/implementation-guide.md)**: Technical implementation details
|
||||
- **[Project Status](docs/project-status.md)**: Current development state
|
||||
- **[NAO6 Integration](docs/nao6-quick-reference.md)**: Robot setup and commands
|
||||
- **[Archive](docs/_archive/)**: Historical documentation (outdated)
|
||||
|
||||
## Research Paper
|
||||
|
||||
@@ -234,19 +230,39 @@ Full paper available at: [docs/paper.md](docs/paper.md)
|
||||
- **4 User Roles**: Complete role-based access control
|
||||
- **Plugin System**: Extensible robot integration architecture
|
||||
- **Trial System**: Unified design with real-time execution capabilities
|
||||
- **WebSocket Ready**: Real-time trial updates with polling fallback
|
||||
- **Docker Integration**: NAO6 deployment via docker-compose
|
||||
- **Conditional Branching**: Experiment flow with wizard choices and convergence paths
|
||||
|
||||
## NAO6 Robot Integration
|
||||
|
||||
Complete NAO6 robot integration is available in the separate **[nao6-hristudio-integration](../nao6-hristudio-integration/)** repository.
|
||||
|
||||
### Features
|
||||
- Complete ROS2 driver integration for NAO V6.0
|
||||
- Complete ROS2 Humble driver integration for NAO V6.0
|
||||
- Docker-based deployment with three services: nao_driver, ros_bridge, ros_api
|
||||
- WebSocket communication via rosbridge
|
||||
- 9 robot actions: speech, movement, gestures, sensors, LEDs
|
||||
- 14 robot actions: speech, movement, gestures, sensors, LEDs, animations
|
||||
- Real-time control from wizard interface
|
||||
- Production-ready with NAOqi 2.8.7.4
|
||||
- Production-ready with NAOqi 2.8.7.4, ROS2 Humble
|
||||
|
||||
### Quick Start
|
||||
### Docker Deployment
|
||||
```bash
|
||||
# Start NAO integration
|
||||
cd nao6-hristudio-integration
|
||||
docker compose up -d
|
||||
|
||||
# Start HRIStudio
|
||||
cd ~/Documents/Projects/hristudio
|
||||
bun dev
|
||||
|
||||
# Access
|
||||
# - HRIStudio: http://localhost:3000
|
||||
# - Test page: http://localhost:3000/nao-test
|
||||
# - rosbridge: ws://localhost:9090
|
||||
```
|
||||
|
||||
### Quick Start Commands
|
||||
```bash
|
||||
# Start NAO integration
|
||||
cd ~/naoqi_ros2_ws
|
||||
|
||||
116
bun.lock
116
bun.lock
@@ -61,14 +61,14 @@
|
||||
"js-cookie": "^3.0.5",
|
||||
"lucide-react": "^0.536.0",
|
||||
"minio": "^8.0.6",
|
||||
"next": "^16.1.6",
|
||||
"next": "16.2.1",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"next-themes": "^0.4.6",
|
||||
"postgres": "^3.4.8",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.2.4",
|
||||
"react": "19.2.4",
|
||||
"react-day-picker": "^9.13.2",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-resizable-panels": "^3.0.6",
|
||||
"react-signature-canvas": "^1.1.0-alpha.2",
|
||||
@@ -90,12 +90,12 @@
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20.19.33",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"drizzle-kit": "^0.30.6",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-config-next": "^15.5.12",
|
||||
"eslint-config-next": "16.2.1",
|
||||
"eslint-plugin-drizzle": "^0.2.3",
|
||||
"postcss": "^8.5.6",
|
||||
"prettier": "^3.8.1",
|
||||
@@ -115,6 +115,10 @@
|
||||
"sharp",
|
||||
"unrs-resolver",
|
||||
],
|
||||
"overrides": {
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
},
|
||||
"packages": {
|
||||
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
|
||||
|
||||
@@ -208,8 +212,40 @@
|
||||
|
||||
"@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.3", "", {}, "sha512-oLvsaPMTBejkkmHhjf09xTgk71mOqyr/409NKhRIL08If7AhVfUsJhVsx386uJaqNd42v9kWamQ9lFbkoC2dYw=="],
|
||||
|
||||
"@babel/code-frame": ["@babel/code-frame@7.29.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
|
||||
"@babel/compat-data": ["@babel/compat-data@7.29.0", "", {}, "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg=="],
|
||||
|
||||
"@babel/core": ["@babel/core@7.29.0", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-compilation-targets": "^7.28.6", "@babel/helper-module-transforms": "^7.28.6", "@babel/helpers": "^7.28.6", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/traverse": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA=="],
|
||||
|
||||
"@babel/generator": ["@babel/generator@7.29.1", "", { "dependencies": { "@babel/parser": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw=="],
|
||||
|
||||
"@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.28.6", "", { "dependencies": { "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA=="],
|
||||
|
||||
"@babel/helper-globals": ["@babel/helper-globals@7.28.0", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="],
|
||||
|
||||
"@babel/helper-module-imports": ["@babel/helper-module-imports@7.28.6", "", { "dependencies": { "@babel/traverse": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw=="],
|
||||
|
||||
"@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.28.6", "", { "dependencies": { "@babel/helper-module-imports": "^7.28.6", "@babel/helper-validator-identifier": "^7.28.5", "@babel/traverse": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA=="],
|
||||
|
||||
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
|
||||
|
||||
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
|
||||
|
||||
"@babel/helper-validator-option": ["@babel/helper-validator-option@7.27.1", "", {}, "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg=="],
|
||||
|
||||
"@babel/helpers": ["@babel/helpers@7.29.2", "", { "dependencies": { "@babel/template": "^7.28.6", "@babel/types": "^7.29.0" } }, "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw=="],
|
||||
|
||||
"@babel/parser": ["@babel/parser@7.29.2", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="],
|
||||
|
||||
"@babel/runtime": ["@babel/runtime@7.28.6", "", {}, "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA=="],
|
||||
|
||||
"@babel/template": ["@babel/template@7.28.6", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="],
|
||||
|
||||
"@babel/traverse": ["@babel/traverse@7.29.0", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="],
|
||||
|
||||
"@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
|
||||
|
||||
"@better-auth/core": ["@better-auth/core@1.5.5", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.3.1", "@better-fetch/fetch": "1.1.21", "@cloudflare/workers-types": ">=4", "better-call": "1.3.2", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types"] }, "sha512-1oR/2jAp821Dcf67kQYHUoyNcdc1TcShfw4QMK0YTVntuRES5mUOyvEJql5T6eIuLfaqaN4LOF78l0FtF66HXA=="],
|
||||
|
||||
"@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0", "drizzle-orm": ">=0.41.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-HAi9xAP40oDt48QZeYBFTcmg3vt1Jik90GwoRIfangd7VGbxesIIDBJSnvwMbZ52GBIc6+V4FRw9lasNiNrPfw=="],
|
||||
@@ -402,25 +438,25 @@
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@0.2.12", "", { "dependencies": { "@emnapi/core": "^1.4.3", "@emnapi/runtime": "^1.4.3", "@tybys/wasm-util": "^0.10.0" } }, "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ=="],
|
||||
|
||||
"@next/env": ["@next/env@16.1.6", "", {}, "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ=="],
|
||||
"@next/env": ["@next/env@16.2.1", "", {}, "sha512-n8P/HCkIWW+gVal2Z8XqXJ6aB3J0tuM29OcHpCsobWlChH/SITBs1DFBk/HajgrwDkqqBXPbuUuzgDvUekREPg=="],
|
||||
|
||||
"@next/eslint-plugin-next": ["@next/eslint-plugin-next@15.5.12", "", { "dependencies": { "fast-glob": "3.3.1" } }, "sha512-+ZRSDFTv4aC96aMb5E41rMjysx8ApkryevnvEYZvPZO52KvkqP5rNExLUXJFr9P4s0f3oqNQR6vopCZsPWKDcQ=="],
|
||||
"@next/eslint-plugin-next": ["@next/eslint-plugin-next@16.2.1", "", { "dependencies": { "fast-glob": "3.3.1" } }, "sha512-r0epZGo24eT4g08jJlg2OEryBphXqO8aL18oajoTKLzHJ6jVr6P6FI58DLMug04MwD3j8Fj0YK0slyzneKVyzA=="],
|
||||
|
||||
"@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.1.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wTzYulosJr/6nFnqGW7FrG3jfUUlEf8UjGA0/pyypJl42ExdVgC6xJgcXQ+V8QFn6niSG2Pb8+MIG1mZr2vczw=="],
|
||||
"@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@16.2.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BwZ8w8YTaSEr2HIuXLMLxIdElNMPvY9fLqb20LX9A9OMGtJilhHLbCL3ggyd0TwjmMcTxi0XXt+ur1vWUoxj2Q=="],
|
||||
|
||||
"@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.1.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-BLFPYPDO+MNJsiDWbeVzqvYd4NyuRrEYVB5k2N3JfWncuHAy2IVwMAOlVQDFjj+krkWzhY2apvmekMkfQR0CUQ=="],
|
||||
"@next/swc-darwin-x64": ["@next/swc-darwin-x64@16.2.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-/vrcE6iQSJq3uL3VGVHiXeaKbn8Es10DGTGRJnRZlkNQQk3kaNtAJg8Y6xuAlrx/6INKVjkfi5rY0iEXorZ6uA=="],
|
||||
|
||||
"@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.1.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-OJYkCd5pj/QloBvoEcJ2XiMnlJkRv9idWA/j0ugSuA34gMT6f5b7vOiCQHVRpvStoZUknhl6/UxOXL4OwtdaBw=="],
|
||||
"@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@16.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-uLn+0BK+C31LTVbQ/QU+UaVrV0rRSJQ8RfniQAHPghDdgE+SlroYqcmFnO5iNjNfVWCyKZHYrs3Nl0mUzWxbBw=="],
|
||||
|
||||
"@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.1.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-S4J2v+8tT3NIO9u2q+S0G5KdvNDjXfAv06OhfOzNDaBn5rw84DGXWndOEB7d5/x852A20sW1M56vhC/tRVbccQ=="],
|
||||
"@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@16.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-ssKq6iMRnHdnycGp9hCuGnXJZ0YPr4/wNwrfE5DbmvEcgl9+yv97/Kq3TPVDfYome1SW5geciLB9aiEqKXQjlQ=="],
|
||||
|
||||
"@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.1.6", "", { "os": "linux", "cpu": "x64" }, "sha512-2eEBDkFlMMNQnkTyPBhQOAyn2qMxyG2eE7GPH2WIDGEpEILcBPI/jdSv4t6xupSP+ot/jkfrCShLAa7+ZUPcJQ=="],
|
||||
"@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@16.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-HQm7SrHRELJ30T1TSmT706IWovFFSRGxfgUkyWJZF/RKBMdbdRWJuFrcpDdE5vy9UXjFOx6L3mRdqH04Mmx0hg=="],
|
||||
|
||||
"@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.1.6", "", { "os": "linux", "cpu": "x64" }, "sha512-oicJwRlyOoZXVlxmIMaTq7f8pN9QNbdes0q2FXfRsPhfCi8n8JmOZJm5oo1pwDaFbnnD421rVU409M3evFbIqg=="],
|
||||
"@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@16.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-aV2iUaC/5HGEpbBkE+4B8aHIudoOy5DYekAKOMSHoIYQ66y/wIVeaRx8MS2ZMdxe/HIXlMho4ubdZs/J8441Tg=="],
|
||||
|
||||
"@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.1.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-gQmm8izDTPgs+DCWH22kcDmuUp7NyiJgEl18bcr8irXA5N2m2O+JQIr6f3ct42GOs9c0h8QF3L5SzIxcYAAXXw=="],
|
||||
"@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@16.2.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-IXdNgiDHaSk0ZUJ+xp0OQTdTgnpx1RCfRTalhn3cjOP+IddTMINwA7DXZrwTmGDO8SUr5q2hdP/du4DcrB1GxA=="],
|
||||
|
||||
"@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.1.6", "", { "os": "win32", "cpu": "x64" }, "sha512-NRfO39AIrzBnixKbjuo2YiYhB6o9d8v/ymU9m/Xk8cyVk+k7XylniXkHwjs4s70wedVffc6bQNbufk5v0xEm0A=="],
|
||||
"@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.2.1", "", { "os": "win32", "cpu": "x64" }, "sha512-qvU+3a39Hay+ieIztkGSbF7+mccbbg1Tk25hc4JDylf8IHjYmY/Zm64Qq1602yPyQqvie+vf5T/uPwNxDNIoeg=="],
|
||||
|
||||
"@noble/ciphers": ["@noble/ciphers@2.1.1", "", {}, "sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw=="],
|
||||
|
||||
@@ -612,8 +648,6 @@
|
||||
|
||||
"@rtsao/scc": ["@rtsao/scc@1.1.0", "", {}, "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g=="],
|
||||
|
||||
"@rushstack/eslint-patch": ["@rushstack/eslint-patch@1.12.0", "", {}, "sha512-5EwMtOqvJMMa3HbmxLlF74e+3/HhwBTMcvt3nqVJgGCozO6hzIPOBlwm8mGVNR9SN2IJpxSnlxczyDjcn7qIyw=="],
|
||||
|
||||
"@shadcn/ui": ["@shadcn/ui@0.0.4", "", { "dependencies": { "chalk": "5.2.0", "commander": "^10.0.0", "execa": "^7.0.0", "fs-extra": "^11.1.0", "node-fetch": "^3.3.0", "ora": "^6.1.2", "prompts": "^2.4.2", "zod": "^3.20.2" }, "bin": { "ui": "dist/index.js" } }, "sha512-0dtu/5ApsOZ24qgaZwtif8jVwqol7a4m1x5AxPuM1k5wxhqU7t/qEfBGtaSki1R8VlbTQfCj5PAlO45NKCa7Gg=="],
|
||||
|
||||
"@smithy/abort-controller": ["@smithy/abort-controller@4.2.8", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-peuVfkYHAmS5ybKxWcfraK7WBBP0J+rkfUcbHJJKQ4ir3UAUNQI+Y4Vt/PqSzGqgloJ5O1dk7+WzNL8wcCSXbw=="],
|
||||
@@ -1034,6 +1068,8 @@
|
||||
|
||||
"browser-or-node": ["browser-or-node@2.1.1", "", {}, "sha512-8CVjaLJGuSKMVTxJ2DpBl5XnlNDiT4cQFeuCJJrvJmts9YrTZDizTX7PjC2s6W4x+MBGZeEY6dGMrF04/6Hgqg=="],
|
||||
|
||||
"browserslist": ["browserslist@4.28.1", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
|
||||
|
||||
"bson": ["bson@7.2.0", "", {}, "sha512-YCEo7KjMlbNlyHhz7zAZNDpIpQbd+wOEHJYezv0nMYTn4x31eIUM2yomNNubclAt63dObUzKHWsBLJ9QcZNSnQ=="],
|
||||
|
||||
"buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
|
||||
@@ -1082,6 +1118,8 @@
|
||||
|
||||
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
|
||||
|
||||
"convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
|
||||
|
||||
"copy-anything": ["copy-anything@4.0.5", "", { "dependencies": { "is-what": "^5.2.0" } }, "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA=="],
|
||||
|
||||
"core-js": ["core-js@3.48.0", "", {}, "sha512-zpEHTy1fjTMZCKLHUZoVeylt9XrzaIN2rbPXEt0k+q7JE5CkCZdo6bNq55bn24a69CH7ErAVLKijxJja4fw+UQ=="],
|
||||
@@ -1140,6 +1178,8 @@
|
||||
|
||||
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"electron-to-chromium": ["electron-to-chromium@1.5.321", "", {}, "sha512-L2C7Q279W2D/J4PLZLk7sebOILDSWos7bMsMNN06rK482umHUrh/3lM8G7IlHFOYip2oAg5nha1rCMxr/rs6ZQ=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.19.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.0" } }, "sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg=="],
|
||||
@@ -1170,11 +1210,13 @@
|
||||
|
||||
"esbuild-register": ["esbuild-register@3.6.0", "", { "dependencies": { "debug": "^4.3.4" }, "peerDependencies": { "esbuild": ">=0.12 <1" } }, "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg=="],
|
||||
|
||||
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
|
||||
|
||||
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
|
||||
|
||||
"eslint": ["eslint@9.39.2", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.21.1", "@eslint/config-helpers": "^0.4.2", "@eslint/core": "^0.17.0", "@eslint/eslintrc": "^3.3.1", "@eslint/js": "9.39.2", "@eslint/plugin-kit": "^0.4.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.4.0", "eslint-visitor-keys": "^4.2.1", "espree": "^10.4.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw=="],
|
||||
|
||||
"eslint-config-next": ["eslint-config-next@15.5.12", "", { "dependencies": { "@next/eslint-plugin-next": "15.5.12", "@rushstack/eslint-patch": "^1.10.3", "@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", "@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.31.0", "eslint-plugin-jsx-a11y": "^6.10.0", "eslint-plugin-react": "^7.37.0", "eslint-plugin-react-hooks": "^5.0.0" }, "peerDependencies": { "eslint": "^7.23.0 || ^8.0.0 || ^9.0.0", "typescript": ">=3.3.1" }, "optionalPeers": ["typescript"] }, "sha512-ktW3XLfd+ztEltY5scJNjxjHwtKWk6vU2iwzZqSN09UsbBmMeE/cVlJ1yESg6Yx5LW7p/Z8WzUAgYXGLEmGIpg=="],
|
||||
"eslint-config-next": ["eslint-config-next@16.2.1", "", { "dependencies": { "@next/eslint-plugin-next": "16.2.1", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", "eslint-plugin-jsx-a11y": "^6.10.0", "eslint-plugin-react": "^7.37.0", "eslint-plugin-react-hooks": "^7.0.0", "globals": "16.4.0", "typescript-eslint": "^8.46.0" }, "peerDependencies": { "eslint": ">=9.0.0", "typescript": ">=3.3.1" }, "optionalPeers": ["typescript"] }, "sha512-qhabwjQZ1Mk53XzXvmogf8KQ0tG0CQXF0CZ56+2/lVhmObgmaqj7x5A1DSrWdZd3kwI7GTPGUjFne+krRxYmFg=="],
|
||||
|
||||
"eslint-import-resolver-node": ["eslint-import-resolver-node@0.3.9", "", { "dependencies": { "debug": "^3.2.7", "is-core-module": "^2.13.0", "resolve": "^1.22.4" } }, "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g=="],
|
||||
|
||||
@@ -1190,7 +1232,7 @@
|
||||
|
||||
"eslint-plugin-react": ["eslint-plugin-react@7.37.5", "", { "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", "array.prototype.flatmap": "^1.3.3", "array.prototype.tosorted": "^1.1.4", "doctrine": "^2.1.0", "es-iterator-helpers": "^1.2.1", "estraverse": "^5.3.0", "hasown": "^2.0.2", "jsx-ast-utils": "^2.4.1 || ^3.0.0", "minimatch": "^3.1.2", "object.entries": "^1.1.9", "object.fromentries": "^2.0.8", "object.values": "^1.2.1", "prop-types": "^15.8.1", "resolve": "^2.0.0-next.5", "semver": "^6.3.1", "string.prototype.matchall": "^4.0.12", "string.prototype.repeat": "^1.0.0" }, "peerDependencies": { "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA=="],
|
||||
|
||||
"eslint-plugin-react-hooks": ["eslint-plugin-react-hooks@5.2.0", "", { "peerDependencies": { "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" } }, "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg=="],
|
||||
"eslint-plugin-react-hooks": ["eslint-plugin-react-hooks@7.0.1", "", { "dependencies": { "@babel/core": "^7.24.4", "@babel/parser": "^7.24.4", "hermes-parser": "^0.25.1", "zod": "^3.25.0 || ^4.0.0", "zod-validation-error": "^3.5.0 || ^4.0.0" }, "peerDependencies": { "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" } }, "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA=="],
|
||||
|
||||
"eslint-scope": ["eslint-scope@8.4.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="],
|
||||
|
||||
@@ -1264,6 +1306,8 @@
|
||||
|
||||
"gel": ["gel@2.1.1", "", { "dependencies": { "@petamoriken/float16": "^3.8.7", "debug": "^4.3.4", "env-paths": "^3.0.0", "semver": "^7.6.2", "shell-quote": "^1.8.1", "which": "^4.0.0" }, "bin": { "gel": "dist/cli.mjs" } }, "sha512-Newg9X7mRYskoBjSw70l1YnJ/ZGbq64VPyR821H5WVkTGpHG2O0mQILxCeUhxdYERLFY9B4tUyKLyf3uMTjtKw=="],
|
||||
|
||||
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
|
||||
|
||||
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
|
||||
|
||||
"get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],
|
||||
@@ -1300,6 +1344,10 @@
|
||||
|
||||
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"hermes-estree": ["hermes-estree@0.25.1", "", {}, "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw=="],
|
||||
|
||||
"hermes-parser": ["hermes-parser@0.25.1", "", { "dependencies": { "hermes-estree": "0.25.1" } }, "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA=="],
|
||||
|
||||
"html2canvas": ["html2canvas@1.4.1", "", { "dependencies": { "css-line-break": "^2.1.0", "text-segmentation": "^1.0.3" } }, "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA=="],
|
||||
|
||||
"html2pdf.js": ["html2pdf.js@0.14.0", "", { "dependencies": { "dompurify": "^3.3.1", "html2canvas": "^1.0.0", "jspdf": "^4.0.0" } }, "sha512-yvNJgE/8yru2UeGflkPdjW8YEY+nDH5X7/2WG4uiuSCwYiCp8PZ8EKNiTAa6HxJ1NjC51fZSIEq6xld5CADKBQ=="],
|
||||
@@ -1400,6 +1448,8 @@
|
||||
|
||||
"js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
|
||||
|
||||
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||
|
||||
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
|
||||
|
||||
"json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
|
||||
@@ -1464,6 +1514,8 @@
|
||||
|
||||
"loose-envify": ["loose-envify@1.4.0", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
|
||||
|
||||
"lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lucide-react": ["lucide-react@0.536.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-2PgvNa9v+qz4Jt/ni8vPLt4jwoFybXHuubQT8fv4iCW5TjDxkbZjNZZHa485ad73NSEn/jdsEtU57eE1g+ma8A=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
@@ -1510,7 +1562,7 @@
|
||||
|
||||
"natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
|
||||
|
||||
"next": ["next@16.1.6", "", { "dependencies": { "@next/env": "16.1.6", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.8.3", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.1.6", "@next/swc-darwin-x64": "16.1.6", "@next/swc-linux-arm64-gnu": "16.1.6", "@next/swc-linux-arm64-musl": "16.1.6", "@next/swc-linux-x64-gnu": "16.1.6", "@next/swc-linux-x64-musl": "16.1.6", "@next/swc-win32-arm64-msvc": "16.1.6", "@next/swc-win32-x64-msvc": "16.1.6", "sharp": "^0.34.4" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw=="],
|
||||
"next": ["next@16.2.1", "", { "dependencies": { "@next/env": "16.2.1", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.2.1", "@next/swc-darwin-x64": "16.2.1", "@next/swc-linux-arm64-gnu": "16.2.1", "@next/swc-linux-arm64-musl": "16.2.1", "@next/swc-linux-x64-gnu": "16.2.1", "@next/swc-linux-x64-musl": "16.2.1", "@next/swc-win32-arm64-msvc": "16.2.1", "@next/swc-win32-x64-msvc": "16.2.1", "sharp": "^0.34.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-VaChzNL7o9rbfdt60HUj8tev4m6d7iC1igAy157526+cJlXOQu5LzsBXNT+xaJnTP/k+utSX5vMv7m0G+zKH+Q=="],
|
||||
|
||||
"next-auth": ["next-auth@5.0.0-beta.30", "", { "dependencies": { "@auth/core": "0.41.0" }, "peerDependencies": { "@simplewebauthn/browser": "^9.0.1", "@simplewebauthn/server": "^9.0.2", "next": "^14.0.0-0 || ^15.0.0 || ^16.0.0", "nodemailer": "^7.0.7", "react": "^18.2.0 || ^19.0.0" }, "optionalPeers": ["@simplewebauthn/browser", "@simplewebauthn/server", "nodemailer"] }, "sha512-+c51gquM3F6nMVmoAusRJ7RIoY0K4Ts9HCCwyy/BRoe4mp3msZpOzYMyb5LAYc1wSo74PMQkGDcaghIO7W6Xjg=="],
|
||||
|
||||
@@ -1520,6 +1572,8 @@
|
||||
|
||||
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
|
||||
|
||||
"node-releases": ["node-releases@2.0.36", "", {}, "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA=="],
|
||||
|
||||
"npm-run-path": ["npm-run-path@5.3.0", "", { "dependencies": { "path-key": "^4.0.0" } }, "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ=="],
|
||||
|
||||
"oauth4webapi": ["oauth4webapi@3.6.1", "", {}, "sha512-b39+drVyA4aNUptFOhkkmGWnG/BE7dT29SW/8PVYElqp7j/DBqzm5SS1G+MUD07XlTcBOAG+6Cb/35Cx2kHIuQ=="],
|
||||
@@ -1866,6 +1920,8 @@
|
||||
|
||||
"unrs-resolver": ["unrs-resolver@1.11.1", "", { "dependencies": { "napi-postinstall": "^0.3.0" }, "optionalDependencies": { "@unrs/resolver-binding-android-arm-eabi": "1.11.1", "@unrs/resolver-binding-android-arm64": "1.11.1", "@unrs/resolver-binding-darwin-arm64": "1.11.1", "@unrs/resolver-binding-darwin-x64": "1.11.1", "@unrs/resolver-binding-freebsd-x64": "1.11.1", "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", "@unrs/resolver-binding-linux-x64-musl": "1.11.1", "@unrs/resolver-binding-wasm32-wasi": "1.11.1", "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" } }, "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg=="],
|
||||
|
||||
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
|
||||
|
||||
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
|
||||
|
||||
"use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
|
||||
@@ -1918,10 +1974,14 @@
|
||||
|
||||
"xmlbuilder": ["xmlbuilder@11.0.1", "", {}, "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA=="],
|
||||
|
||||
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||
|
||||
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
|
||||
|
||||
"zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
|
||||
|
||||
"zod-validation-error": ["zod-validation-error@4.0.2", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ=="],
|
||||
|
||||
"zustand": ["zustand@4.5.7", "", { "dependencies": { "use-sync-external-store": "^1.2.2" }, "peerDependencies": { "@types/react": ">=16.8", "immer": ">=9.0.6", "react": ">=16.8" }, "optionalPeers": ["@types/react", "immer", "react"] }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],
|
||||
|
||||
"@auth/core/jose": ["jose@6.0.12", "", {}, "sha512-T8xypXs8CpmiIi78k0E+Lk7T2zlK4zDyg+o1CZ4AkOHgDg98ogdP2BeZ61lTFKFyoEwJ9RgAgN+SdM3iPgNonQ=="],
|
||||
@@ -1946,6 +2006,16 @@
|
||||
|
||||
"@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.3.4", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-EFd6afGmXlCx8H8WTZHhAoDaWaGyuIBoZJ2mknrNxug+aZKjkp0a0dlars9Izl+jF+7Gu1/5f/2h68cQpe0IiA=="],
|
||||
|
||||
"@babel/core/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"@babel/core/json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
|
||||
|
||||
"@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@babel/traverse/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
|
||||
|
||||
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
||||
@@ -2028,10 +2098,14 @@
|
||||
|
||||
"@typescript-eslint/typescript-estree/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
|
||||
|
||||
"browserslist/caniuse-lite": ["caniuse-lite@1.0.30001780", "", {}, "sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ=="],
|
||||
|
||||
"cmdk/@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.14", "", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.10", "@radix-ui/react-focus-guards": "1.1.2", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+CpweKjqpzTmwRwcYECQcNYbI8V9VSQt0SNFKeEBLgfucbsLssU6Ppq7wUdNXEGb573bMjFhVjKVll8rmV6zMw=="],
|
||||
|
||||
"cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"eslint-config-next/globals": ["globals@16.4.0", "", {}, "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw=="],
|
||||
|
||||
"eslint-import-resolver-node/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="],
|
||||
|
||||
"eslint-import-resolver-typescript/tinyglobby": ["tinyglobby@0.2.14", "", { "dependencies": { "fdir": "^6.4.4", "picomatch": "^4.0.2" } }, "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ=="],
|
||||
|
||||
@@ -36,8 +36,8 @@ services:
|
||||
entrypoint: >
|
||||
/bin/sh -c "
|
||||
/usr/bin/mc alias set myminio http://minio:9000 minioadmin minioadmin;
|
||||
/usr/bin/mc mb myminio/hristudio;
|
||||
/usr/bin/mc anonymous set public myminio/hristudio;
|
||||
/usr/bin/mc mb myminio/hristudio-data;
|
||||
/usr/bin/mc anonymous set public myminio/hristudio-data;
|
||||
exit 0;
|
||||
"
|
||||
|
||||
|
||||
439
docs/README.md
439
docs/README.md
@@ -1,307 +1,174 @@
|
||||
# HRIStudio Documentation
|
||||
|
||||
Welcome to the comprehensive documentation for HRIStudio - a web-based platform for standardizing and improving Wizard of Oz (WoZ) studies in Human-Robot Interaction research.
|
||||
HRIStudio is a web-based Wizard-of-Oz platform for Human-Robot Interaction research.
|
||||
|
||||
## 📚 Documentation Overview
|
||||
## Quick Links
|
||||
|
||||
This documentation suite provides everything needed to understand, build, deploy, and maintain HRIStudio. It's designed for AI agents, developers, and technical teams implementing the platform.
|
||||
| Document | Description |
|
||||
|----------|-------------|
|
||||
| **[Quick Reference](quick-reference.md)** | Essential commands, setup, troubleshooting |
|
||||
| **[Project Status](project-status.md)** | Current development state (March 2026) |
|
||||
| **[Implementation Guide](implementation-guide.md)** | Full technical implementation |
|
||||
| **[NAO6 Integration](nao6-quick-reference.md)** | Robot setup and commands |
|
||||
|
||||
### **🚀 Quick Start**
|
||||
|
||||
**New to HRIStudio?** Start here:
|
||||
1. **[Quick Reference](./quick-reference.md)** - 5-minute setup and key concepts
|
||||
2. **[Project Overview](./project-overview.md)** - Complete feature overview and goals
|
||||
3. **[Implementation Guide](./implementation-guide.md)** - Step-by-step technical implementation
|
||||
|
||||
### **📋 Core Documentation** (8 Files)
|
||||
|
||||
#### **Project Specifications**
|
||||
1. **[Project Overview](./project-overview.md)**
|
||||
- Executive summary and project goals
|
||||
- Core features and system architecture
|
||||
- User roles and permissions
|
||||
- Technology stack overview
|
||||
- Key concepts and success metrics
|
||||
|
||||
2. **[Feature Requirements](./feature-requirements.md)**
|
||||
- Detailed user stories and acceptance criteria
|
||||
- Functional requirements by module
|
||||
- Non-functional requirements
|
||||
- UI/UX specifications
|
||||
- Integration requirements
|
||||
|
||||
#### **Technical Implementation**
|
||||
3. **[Database Schema](./database-schema.md)**
|
||||
- Complete PostgreSQL schema with Drizzle ORM
|
||||
- Table definitions and relationships
|
||||
- Indexes and performance optimizations
|
||||
- Views and stored procedures
|
||||
- Migration guidelines
|
||||
|
||||
4. **[API Routes](./api-routes.md)**
|
||||
- Comprehensive tRPC route documentation
|
||||
- Request/response schemas
|
||||
- Authentication requirements
|
||||
- WebSocket events
|
||||
- Rate limiting and error handling
|
||||
|
||||
5. **[Core Blocks System](./core-blocks-system.md)**
|
||||
- Repository-based plugin architecture
|
||||
- 26 essential blocks across 4 categories
|
||||
- Event triggers, wizard actions, control flow, observation
|
||||
- Block loading and validation system
|
||||
- Integration with experiment designer
|
||||
|
||||
6. **[Plugin System Implementation](./plugin-system-implementation-guide.md)**
|
||||
- Robot plugin architecture and development
|
||||
- Repository management and trust levels
|
||||
- Plugin installation and configuration
|
||||
- Action definitions and parameter schemas
|
||||
- ROS2 integration patterns
|
||||
|
||||
7. **[Implementation Guide](./implementation-guide.md)**
|
||||
- Step-by-step technical implementation
|
||||
- Code examples and patterns
|
||||
- Frontend and backend architecture
|
||||
- Real-time features implementation
|
||||
- Testing strategies
|
||||
|
||||
8. **[Implementation Details](./implementation-details.md)**
|
||||
- Architecture decisions and rationale
|
||||
- Unified editor experiences (significant code reduction)
|
||||
- DataTable migration achievements
|
||||
- Development database and seed system
|
||||
- Performance optimization strategies
|
||||
|
||||
#### **Operations & Deployment**
|
||||
9. **[Deployment & Operations](./deployment-operations.md)**
|
||||
- Infrastructure requirements
|
||||
- Vercel deployment strategies
|
||||
- Monitoring and observability
|
||||
- Backup and recovery procedures
|
||||
- Security operations
|
||||
|
||||
10. **[ROS2 Integration](./ros2-integration.md)**
|
||||
- rosbridge WebSocket architecture
|
||||
- Client-side ROS connection management
|
||||
- Message type definitions
|
||||
- Robot plugin implementation
|
||||
- Security considerations for robot communication
|
||||
|
||||
### **📊 Project Status**
|
||||
|
||||
11. **[Project Status](./project-status.md)**
|
||||
- Overall completion status (complete)
|
||||
- Implementation progress by feature
|
||||
- Sprint planning and development velocity
|
||||
- Production readiness assessment
|
||||
- Core blocks system completion
|
||||
|
||||
12. **[Quick Reference](./quick-reference.md)**
|
||||
- 5-minute setup guide
|
||||
- Essential commands and patterns
|
||||
- API reference and common workflows
|
||||
- Core blocks system overview
|
||||
- Key concepts and architecture overview
|
||||
|
||||
13. **[Work in Progress](./work_in_progress.md)**
|
||||
- Recent changes and improvements
|
||||
- Core blocks system implementation
|
||||
- Plugin architecture enhancements
|
||||
- Panel-based wizard interface (matching experiment designer)
|
||||
- Technical debt resolution
|
||||
- UI/UX enhancements
|
||||
|
||||
### **🤖 Robot Integration Guides**
|
||||
|
||||
14. **[NAO6 Complete Integration Guide](./nao6-integration-complete-guide.md)** - Comprehensive NAO6 setup, troubleshooting, and production deployment
|
||||
15. **[NAO6 Quick Reference](./nao6-quick-reference.md)** - Essential commands and troubleshooting for NAO6 integration
|
||||
16. **[NAO6 ROS2 Setup](./nao6-ros2-setup.md)** - Basic NAO6 ROS2 driver installation guide
|
||||
|
||||
### **📖 Academic References**
|
||||
|
||||
17. **[Research Paper](./root.tex)** - Academic LaTeX document
|
||||
18. **[Bibliography](./refs.bib)** - Research references
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Documentation Structure Benefits**
|
||||
|
||||
### **Streamlined Organization**
|
||||
- **Consolidated documentation** - Easier navigation and maintenance
|
||||
- **Logical progression** - From overview → implementation → deployment
|
||||
- **Consolidated achievements** - All progress tracking in unified documents
|
||||
- **Clear entry points** - Quick reference for immediate needs
|
||||
|
||||
### **Comprehensive Coverage**
|
||||
- **Complete technical specs** - Database, API, and implementation details
|
||||
- **Step-by-step guidance** - From project setup to production deployment
|
||||
- **Real-world examples** - Code patterns and configuration samples
|
||||
- **Performance insights** - Optimization strategies and benchmark results
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **Getting Started Paths**
|
||||
|
||||
### **For Developers**
|
||||
1. **[Quick Reference](./quick-reference.md)** - Immediate setup and key commands
|
||||
2. **[Implementation Guide](./implementation-guide.md)** - Technical implementation steps
|
||||
3. **[Database Schema](./database-schema.md)** - Data model understanding
|
||||
4. **[API Routes](./api-routes.md)** - Backend integration
|
||||
|
||||
### **For Project Managers**
|
||||
1. **[Project Overview](./project-overview.md)** - Complete feature understanding
|
||||
2. **[Project Status](./project-status.md)** - Current progress and roadmap
|
||||
3. **[Feature Requirements](./feature-requirements.md)** - Detailed specifications
|
||||
4. **[Deployment & Operations](./deployment-operations.md)** - Infrastructure planning
|
||||
|
||||
### **For Researchers**
|
||||
1. **[Project Overview](./project-overview.md)** - Research platform capabilities
|
||||
2. **[Feature Requirements](./feature-requirements.md)** - User workflows and features
|
||||
3. **[NAO6 Quick Reference](./nao6-quick-reference.md)** - Essential NAO6 robot control commands
|
||||
4. **[ROS2 Integration](./ros2-integration.md)** - Robot platform integration
|
||||
5. **[Research Paper](./root.tex)** - Academic context and methodology
|
||||
|
||||
### **For Robot Integration**
|
||||
1. **[NAO6 Complete Integration Guide](./nao6-integration-complete-guide.md)** - Full NAO6 setup and troubleshooting
|
||||
2. **[NAO6 Quick Reference](./nao6-quick-reference.md)** - Essential commands and quick fixes
|
||||
3. **[ROS2 Integration](./ros2-integration.md)** - General robot integration patterns
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ **Prerequisites**
|
||||
|
||||
### **Development Environment**
|
||||
- **[Bun](https://bun.sh)** - Package manager and runtime
|
||||
- **[PostgreSQL](https://postgresql.org)** 15+ - Primary database
|
||||
- **[Docker](https://docker.com)** - Containerized development (optional)
|
||||
|
||||
### **Production Deployment**
|
||||
- **[Vercel](https://vercel.com)** account - Serverless deployment platform
|
||||
- **PostgreSQL** database - Vercel Postgres or external provider
|
||||
- **[Cloudflare R2](https://cloudflare.com/products/r2/)** - S3-compatible storage
|
||||
|
||||
---
|
||||
|
||||
## ⚡ **Quick Setup (5 Minutes)**
|
||||
## Getting Started
|
||||
|
||||
### 1. Clone & Install
|
||||
```bash
|
||||
# Clone and install
|
||||
git clone <repo-url> hristudio
|
||||
git clone https://github.com/soconnor0919/hristudio.git
|
||||
cd hristudio
|
||||
git submodule update --init --recursive
|
||||
bun install
|
||||
|
||||
# Start database
|
||||
bun run docker:up
|
||||
|
||||
# Setup database and seed data
|
||||
bun db:push
|
||||
bun db:seed
|
||||
|
||||
# Start development
|
||||
bun dev
|
||||
```
|
||||
|
||||
**Default Login**: `sean@soconnor.dev` / `password123`
|
||||
### 2. Start Database
|
||||
```bash
|
||||
bun run docker:up
|
||||
bun db:push
|
||||
bun db:seed
|
||||
```
|
||||
|
||||
---
|
||||
### 3. Start Application
|
||||
```bash
|
||||
bun dev
|
||||
# Visit http://localhost:3000
|
||||
# Login: sean@soconnor.dev / password123
|
||||
```
|
||||
|
||||
## 📋 **Key Features Overview**
|
||||
### 4. Start NAO6 Robot (optional)
|
||||
```bash
|
||||
cd ~/Documents/Projects/nao6-hristudio-integration
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Current Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ HRIStudio Platform │
|
||||
├──────────────────────────────────────────────────────────┤
|
||||
│ UI Layer (Next.js + React + shadcn/ui) │
|
||||
│ ├── Experiment Designer (drag-and-drop) │
|
||||
│ ├── Wizard Interface (real-time trial execution) │
|
||||
│ └── Observer/Participant Views │
|
||||
├──────────────────────────────────────────────────────────┤
|
||||
│ Logic Layer (tRPC + Better Auth) │
|
||||
│ ├── 12 tRPC routers (studies, experiments, trials...) │
|
||||
│ ├── Role-based authentication (4 roles) │
|
||||
│ └── WebSocket for real-time updates │
|
||||
├──────────────────────────────────────────────────────────┤
|
||||
│ Data Layer (PostgreSQL + Drizzle ORM) │
|
||||
│ ├── 31 tables with complete relationships │
|
||||
│ ├── Plugin system with identifier-based lookup │
|
||||
│ └── Comprehensive event logging │
|
||||
├──────────────────────────────────────────────────────────┤
|
||||
│ Robot Integration (ROS2 via WebSocket) │
|
||||
│ Docker: nao_driver, ros_bridge, ros_api │
|
||||
│ Plugin identifier: "nao6-ros2" │
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### **Research Workflow Support**
|
||||
- **Hierarchical Structure**: Study → Experiment → Trial → Step → Action
|
||||
- **Visual Experiment Designer**: Repository-based plugin architecture with 26 core blocks
|
||||
- **Core Block Categories**: Events, wizard actions, control flow, observation blocks
|
||||
- **Real-time Trial Execution**: Live wizard control with data capture
|
||||
- **Multi-role Collaboration**: Administrator, Researcher, Wizard, Observer
|
||||
- **Comprehensive Data Management**: Synchronized multi-modal capture
|
||||
- **Visual Designer**: 26+ core blocks (events, wizard actions, control flow, observation)
|
||||
- **Conditional Branching**: Wizard choices with convergence paths
|
||||
- **WebSocket Real-time**: Trial updates with auto-reconnect
|
||||
- **Plugin System**: Robot-agnostic via identifier lookup
|
||||
- **Docker NAO6**: Three-service ROS2 integration
|
||||
- **Forms System**: Consent forms, surveys, questionnaires with templates
|
||||
- **Role-based Access**: Owner, Researcher, Wizard, Observer permissions
|
||||
|
||||
### **Technical Excellence**
|
||||
- **Full Type Safety**: End-to-end TypeScript with strict mode
|
||||
- **Production Ready**: Vercel deployment with Edge Runtime
|
||||
- **Performance Optimized**: Database indexes and query optimization
|
||||
- **Security First**: Role-based access control throughout
|
||||
- **Modern Stack**: Next.js 15, tRPC, Drizzle ORM, shadcn/ui
|
||||
- **Consistent Architecture**: Panel-based interfaces across visual programming tools
|
||||
## System Components
|
||||
|
||||
### **Development Experience**
|
||||
- **Unified Components**: Significant reduction in code duplication
|
||||
- **Panel Architecture**: 90% code sharing between experiment designer and wizard interface
|
||||
- **Consolidated Wizard**: 3-panel design with trial controls, horizontal timeline, and unified robot controls
|
||||
- **Enterprise DataTables**: Advanced filtering, export, pagination
|
||||
- **Comprehensive Testing**: Realistic seed data with complete scenarios
|
||||
- **Developer Friendly**: Clear patterns and extensive documentation
|
||||
### Backend (src/server/)
|
||||
- `api/routers/` - 13 tRPC routers (studies, experiments, trials, participants, forms, etc.)
|
||||
- `db/schema.ts` - Drizzle schema (33 tables)
|
||||
- `services/trial-execution.ts` - Trial execution engine
|
||||
- `services/websocket-manager.ts` - Real-time connections
|
||||
|
||||
### **Robot Integration**
|
||||
- **NAO6 Full Support**: Complete ROS2 integration with movement, speech, and sensor control
|
||||
- **Real-time Control**: WebSocket-based robot control through web interface
|
||||
- **Safety Features**: Emergency stops, movement limits, and comprehensive monitoring
|
||||
- **Production Ready**: Tested with NAO V6.0 / NAOqi 2.8.7.4 / ROS2 Humble
|
||||
- **Troubleshooting Guides**: Complete documentation for setup and problem resolution
|
||||
### Frontend (src/)
|
||||
- `app/` - Next.js App Router pages
|
||||
- `components/trials/wizard/` - Wizard interface
|
||||
- `components/trials/forms/` - Form builder and viewer
|
||||
- `hooks/useWebSocket.ts` - Real-time trial updates
|
||||
- `lib/ros/wizard-ros-service.ts` - Robot control
|
||||
|
||||
## Plugin Identifier System
|
||||
|
||||
```typescript
|
||||
// Plugins table has:
|
||||
// - identifier: "nao6-ros2" (unique, machine-readable)
|
||||
// - name: "NAO6 Robot (ROS2 Integration)" (display)
|
||||
|
||||
// Lookup order in trial execution:
|
||||
1. Look up by identifier (e.g., "nao6-ros2")
|
||||
2. Fall back to name (e.g., "NAO6 Robot")
|
||||
3. Return null if not found
|
||||
```
|
||||
|
||||
## Branching Flow
|
||||
|
||||
```
|
||||
Step 3 (Comprehension Check)
|
||||
└── wizard_wait_for_response
|
||||
├── "Correct" → nextStepId = step4a.id
|
||||
└── "Incorrect" → nextStepId = step4b.id
|
||||
|
||||
Step 4a/4b (Branch A/B)
|
||||
└── conditions.nextStepId: step5.id → converge
|
||||
|
||||
Step 5 (Story Continues)
|
||||
└── Linear progression to conclusion
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
```bash
|
||||
# Make changes
|
||||
# ...
|
||||
|
||||
# Validate
|
||||
bun typecheck
|
||||
bun lint
|
||||
|
||||
# Push schema (if changed)
|
||||
bun db:push
|
||||
|
||||
# Reseed (if data changed)
|
||||
bun db:seed
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Build errors | `rm -rf .next && bun build` |
|
||||
| DB issues | `bun db:push --force && bun db:seed` |
|
||||
| Type errors | Check `bun typecheck` output |
|
||||
| WebSocket fails | Verify port 3001 available |
|
||||
|
||||
## External Resources
|
||||
|
||||
- [Thesis (honors-thesis)](https://github.com/soconnor0919/honors-thesis)
|
||||
- [NAO6 Integration](https://github.com/soconnor0919/nao6-hristudio-integration)
|
||||
- [Robot Plugins](https://github.com/soconnor0919/robot-plugins)
|
||||
|
||||
## File Index
|
||||
|
||||
### Primary Documentation
|
||||
- `README.md` - Project overview
|
||||
- `docs/README.md` - This file
|
||||
- `docs/quick-reference.md` - Commands & setup
|
||||
- `docs/nao6-quick-reference.md` - NAO6 commands
|
||||
|
||||
### Technical Documentation
|
||||
- `docs/implementation-guide.md` - Full technical implementation
|
||||
- `docs/project-status.md` - Development status
|
||||
|
||||
### Archive (Historical)
|
||||
- `docs/_archive/` - Old documentation (outdated but preserved)
|
||||
|
||||
---
|
||||
|
||||
## 🎊 **Project Status: Production Ready**
|
||||
|
||||
**Current Completion**: Complete ✅
|
||||
**Status**: Ready for immediate deployment
|
||||
**Active Work**: Experiment designer enhancement
|
||||
|
||||
### **Completed Achievements**
|
||||
- ✅ **Complete Backend** - Full API coverage with 11 tRPC routers
|
||||
- ✅ **Professional UI** - Unified experiences with shadcn/ui components
|
||||
- ✅ **Type Safety** - Zero TypeScript errors in production code
|
||||
- ✅ **Database Schema** - 31 tables with comprehensive relationships
|
||||
- ✅ **Authentication** - Role-based access control system
|
||||
- ✅ **Visual Designer** - Repository-based plugin architecture
|
||||
- ✅ **Consolidated Wizard Interface** - 3-panel design with horizontal timeline and unified robot controls
|
||||
- ✅ **Core Blocks System** - 26 blocks across events, wizard, control, observation
|
||||
- ✅ **Plugin Architecture** - Unified system for core blocks and robot actions
|
||||
- ✅ **Development Environment** - Realistic test data and scenarios
|
||||
- ✅ **NAO6 Robot Integration** - Full ROS2 integration with comprehensive control and monitoring
|
||||
- ✅ **Intelligent Control Flow** - Loops with implicit approval, branching, parallel execution
|
||||
|
||||
---
|
||||
|
||||
## 📞 **Support and Resources**
|
||||
|
||||
### **Documentation Quality**
|
||||
This documentation is comprehensive and self-contained. For implementation:
|
||||
1. **Start with Quick Reference** for immediate setup
|
||||
2. **Follow Implementation Guide** for step-by-step development
|
||||
3. **Reference Technical Specs** for detailed implementation
|
||||
4. **Check Project Status** for current progress and roadmap
|
||||
|
||||
### **Key Integration Points**
|
||||
- **Authentication**: NextAuth.js v5 with database sessions
|
||||
- **File Storage**: Cloudflare R2 with presigned URLs
|
||||
- **Real-time**: WebSocket with Edge Runtime compatibility
|
||||
- **Robot Control**: ROS2 via rosbridge WebSocket protocol
|
||||
- **Caching**: Vercel KV for serverless-compatible caching
|
||||
- **Monitoring**: Vercel Analytics and structured logging
|
||||
|
||||
---
|
||||
|
||||
## 🏆 **Success Criteria**
|
||||
|
||||
The platform is considered production-ready when:
|
||||
- ✅ All features from requirements are implemented
|
||||
- ✅ All API routes are functional and documented
|
||||
- ✅ Database schema matches specification exactly
|
||||
- ✅ Real-time features work reliably
|
||||
- ✅ Security requirements are met
|
||||
- ✅ Performance targets are achieved
|
||||
- ✅ Type safety is complete throughout
|
||||
|
||||
**All success criteria have been met. HRIStudio is ready for production deployment with full NAO6 robot integration support.**
|
||||
|
||||
---
|
||||
|
||||
## 📝 **Documentation Maintenance**
|
||||
|
||||
- **Version**: 2.0.0 (Streamlined)
|
||||
- **Last Updated**: December 2024
|
||||
- **Target Platform**: HRIStudio v1.0
|
||||
- **Structure**: Consolidated for clarity and maintainability
|
||||
|
||||
This documentation represents a complete, streamlined specification for building and deploying HRIStudio. Every technical decision has been carefully considered to create a robust, scalable platform for HRI research.
|
||||
**Last Updated**: March 22, 2026
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Overview
|
||||
|
||||
This guide provides step-by-step technical instructions for implementing HRIStudio using the T3 stack with Next.js, tRPC, Drizzle ORM, NextAuth.js v5, and supporting infrastructure.
|
||||
This guide provides step-by-step technical instructions for implementing HRIStudio using the T3 stack with Next.js, tRPC, Drizzle ORM, Better Auth, and supporting infrastructure.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -25,7 +25,14 @@ This guide provides step-by-step technical instructions for implementing HRIStud
|
||||
### 1. Initialize Project
|
||||
|
||||
```bash
|
||||
# Create new Next.js project with T3 stack
|
||||
# Clone repository (includes robot-plugins as submodule)
|
||||
git clone https://github.com/soconnor0919/hristudio.git
|
||||
cd hristudio
|
||||
|
||||
# Initialize submodules
|
||||
git submodule update --init --recursive
|
||||
|
||||
# Or create from scratch with T3 stack:
|
||||
bunx create-t3-app@latest hristudio \
|
||||
--nextjs \
|
||||
--tailwind \
|
||||
|
||||
@@ -27,10 +27,15 @@ bun dev
|
||||
|
||||
| Service | Port | Description |
|
||||
|---------|------|-------------|
|
||||
| nao_driver | - | NAOqi driver node |
|
||||
| nao_driver | - | NAOqi driver + robot init |
|
||||
| ros_bridge | 9090 | WebSocket bridge |
|
||||
| ros_api | - | ROS API services |
|
||||
|
||||
**Auto-initialization**: On Docker startup, `init_robot.sh` runs automatically via SSH to:
|
||||
- Wake up the robot (`ALMotion.wakeUp`)
|
||||
- Disable autonomous life (`ALAutonomousLife.setState disabled`)
|
||||
- Ensure robot is ready for commands
|
||||
|
||||
## ROS Topics
|
||||
|
||||
**Commands (Publish to these):**
|
||||
@@ -52,6 +57,21 @@ bun dev
|
||||
/info - Robot info
|
||||
```
|
||||
|
||||
## Robot Actions (HRIStudio)
|
||||
|
||||
When actions are triggered via the wizard interface, they publish to these topics:
|
||||
|
||||
| Action | Topic | Message Type |
|
||||
|--------|-------|--------------|
|
||||
| say | `/speech` | `std_msgs/String` |
|
||||
| say_with_emotion | `/speech` | `std_msgs/String` (with NAOqi markup) |
|
||||
| wave_goodbye | `/speech` | `std_msgs/String` + gesture |
|
||||
| walk | `/cmd_vel` | `geometry_msgs/Twist` |
|
||||
| turn | `/cmd_vel` | `geometry_msgs/Twist` |
|
||||
| move_to_posture | `/service/robot_pose` | `naoqi_bridge_msgs/SetRobotPose` |
|
||||
| play_animation | `/animation` | `std_msgs/String` |
|
||||
| set_eye_leds | `/leds/eyes` | `std_msgs/ColorRGBA` |
|
||||
|
||||
## Manual Control
|
||||
|
||||
### Test Connectivity
|
||||
|
||||
@@ -1,402 +1,189 @@
|
||||
# HRIStudio Project Status
|
||||
|
||||
## 🎯 **Current Status: Production Ready**
|
||||
## Current Status: Active Development
|
||||
|
||||
**Project Version**: 1.0.0
|
||||
**Last Updated**: December 2024
|
||||
**Overall Completion**: Complete ✅
|
||||
**Status**: Ready for Production Deployment
|
||||
|
||||
### **🎉 Recent Major Achievement: Wizard Interface Multi-View Implementation Complete**
|
||||
Successfully implemented role-based trial execution interface with Wizard, Observer, and Participant views. Fixed layout issues and eliminated route duplication for clean, production-ready trial execution system.
|
||||
**Last Updated**: March 2026
|
||||
**Overall Completion**: 98%
|
||||
**Status**: Thesis research phase
|
||||
|
||||
---
|
||||
|
||||
## 📊 **Executive Summary**
|
||||
## Executive Summary
|
||||
|
||||
HRIStudio has successfully completed all major development milestones and achieved production readiness. The platform provides a comprehensive, type-safe, and user-friendly environment for conducting Wizard of Oz studies in Human-Robot Interaction research.
|
||||
HRIStudio is a complete platform for Wizard-of-Oz HRI research. Key milestones achieved:
|
||||
|
||||
### **Key Achievements**
|
||||
- ✅ **Complete Backend Infrastructure** - Full API with 12 tRPC routers
|
||||
- ✅ **Complete Frontend Implementation** - Professional UI with unified experiences
|
||||
- ✅ **Full Type Safety** - Zero TypeScript errors in production code
|
||||
- ✅ **Complete Authentication** - Role-based access control system
|
||||
- ✅ **Visual Experiment Designer** - Repository-based plugin architecture
|
||||
- ✅ **Core Blocks System** - 26 blocks across 4 categories (events, wizard, control, observation)
|
||||
- ✅ **Production Database** - 31 tables with comprehensive relationships
|
||||
- ✅ **Development Environment** - Realistic seed data and testing scenarios
|
||||
- ✅ **Trial System Overhaul** - Unified EntityView patterns with real-time execution
|
||||
- ✅ **WebSocket Integration** - Real-time updates with polling fallback
|
||||
- ✅ **Route Consolidation** - Study-scoped architecture with eliminated duplicate components
|
||||
- ✅ **Multi-View Trial Interface** - Role-based Wizard, Observer, and Participant views for thesis research
|
||||
- ✅ **Dashboard Resolution** - Fixed routing issues and implemented proper layout structure
|
||||
### Recent Updates (March 2026)
|
||||
- ✅ WebSocket real-time trial updates implemented
|
||||
- ✅ Better Auth migration complete (replaced NextAuth.js)
|
||||
- ✅ Docker integration for NAO6 (3 services: nao_driver, ros_bridge, ros_api)
|
||||
- ✅ Conditional branching with wizard choices and convergence
|
||||
- ✅ 14 NAO6 robot actions (speech, movement, gestures, sensors, LEDs, animations)
|
||||
- ✅ Plugin identifier system for clean plugin lookup
|
||||
- ✅ Seed script with branching experiment structure
|
||||
|
||||
### Key Achievements
|
||||
- ✅ Complete backend with 12 tRPC routers
|
||||
- ✅ Professional UI with unified experiences
|
||||
- ✅ Full TypeScript coverage (strict mode)
|
||||
- ✅ Role-based access control (4 roles)
|
||||
- ✅ 31 database tables with relationships
|
||||
- ✅ Experiment designer with 26+ core blocks
|
||||
- ✅ Real-time trial execution wizard interface
|
||||
- ✅ NAO6 robot integration via ROS2 Humble
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ **Implementation Status by Feature**
|
||||
## Architecture
|
||||
|
||||
### **Core Infrastructure** ✅ **Complete**
|
||||
### Three-Layer Architecture
|
||||
|
||||
#### **Plugin Architecture** ✅ **Complete**
|
||||
- **Core Blocks System**: Repository-based architecture with 26 essential blocks
|
||||
- **Robot Plugin Integration**: Unified plugin loading for robot actions
|
||||
- **Repository Management**: Admin tools for plugin repositories and trust levels
|
||||
- **Plugin Store**: Study-scoped plugin installation and configuration
|
||||
- **Block Categories**: Events, wizard actions, control flow, observation blocks
|
||||
- **Type Safety**: Full TypeScript support for all plugin definitions
|
||||
- **Documentation**: Complete guides for core blocks and robot plugins
|
||||
|
||||
|
||||
**Database Schema**
|
||||
- ✅ 31 tables covering all research workflows
|
||||
- ✅ Complete relationships with foreign keys and indexes
|
||||
- ✅ Audit logging and soft deletes implemented
|
||||
- ✅ Performance optimizations with strategic indexing
|
||||
- ✅ JSONB support for flexible metadata storage
|
||||
|
||||
**API Infrastructure**
|
||||
- ✅ 12 tRPC routers providing comprehensive functionality
|
||||
- ✅ Type-safe with Zod validation throughout
|
||||
- ✅ Role-based authorization on all endpoints
|
||||
- ✅ Comprehensive error handling and validation
|
||||
- ✅ Optimistic updates and real-time subscriptions ready
|
||||
|
||||
**Authentication & Authorization**
|
||||
- ✅ NextAuth.js v5 with database sessions
|
||||
- ✅ 4 system roles: Administrator, Researcher, Wizard, Observer
|
||||
- ✅ Role-based middleware protecting all routes
|
||||
- ✅ User profile management with password changes
|
||||
- ✅ Admin dashboard for user and role management
|
||||
|
||||
### **User Interface** ✅ **Complete**
|
||||
|
||||
**Core UI Framework**
|
||||
- ✅ shadcn/ui integration with custom theme
|
||||
- ✅ Responsive design across all screen sizes
|
||||
- ✅ Accessibility compliance (WCAG 2.1 AA)
|
||||
- ✅ Loading states and comprehensive error boundaries
|
||||
- ✅ Form validation with react-hook-form + Zod
|
||||
|
||||
**Major Interface Components**
|
||||
- ✅ Dashboard with role-based navigation
|
||||
- ✅ Authentication pages (signin/signup/profile)
|
||||
- ✅ Study management with team collaboration
|
||||
- ✅ Visual experiment designer with drag-and-drop
|
||||
- ✅ Participant management and consent tracking
|
||||
- ✅ Trial execution and monitoring interfaces
|
||||
- ✅ Data tables with advanced filtering and export
|
||||
|
||||
### **Key Feature Implementations** ✅ **Complete**
|
||||
|
||||
**Visual Experiment Designer**
|
||||
- ✅ Professional drag-and-drop interface
|
||||
- ✅ 4 step types: Wizard Action, Robot Action, Parallel Steps, Conditional Branch
|
||||
- ✅ Real-time saving with conflict resolution
|
||||
- ✅ Parameter configuration framework
|
||||
- ✅ Professional UI with loading states and error handling
|
||||
|
||||
**Unified Editor Experiences**
|
||||
- ✅ Significant reduction in form-related code duplication
|
||||
- ✅ Consistent EntityForm component across all entities
|
||||
- ✅ Standardized validation and error handling
|
||||
- ✅ Context-aware creation for nested workflows
|
||||
- ✅ Progressive workflow guidance with next steps
|
||||
|
||||
**DataTable System**
|
||||
- ✅ Unified DataTable component with enterprise features
|
||||
- ✅ Server-side filtering, sorting, and pagination
|
||||
- ✅ Column visibility controls and export functionality
|
||||
- ✅ Responsive design with proper overflow handling
|
||||
- ✅ Consistent experience across all entity lists
|
||||
|
||||
**Robot Integration Framework**
|
||||
- ✅ Plugin system for extensible robot support
|
||||
- ✅ RESTful API and ROS2 integration via WebSocket
|
||||
- ✅ Type-safe action definitions and parameter schemas
|
||||
- ✅ Connection testing and health monitoring
|
||||
|
||||
---
|
||||
|
||||
## 🎊 **Major Development Achievements**
|
||||
|
||||
### **Code Quality Excellence**
|
||||
- **Type Safety**: Complete TypeScript coverage with strict mode
|
||||
- **Code Reduction**: Significant decrease in form-related duplication
|
||||
- **Performance**: Optimized database queries and client bundles
|
||||
- **Security**: Comprehensive role-based access control
|
||||
- **Testing**: Unit, integration, and E2E testing frameworks ready
|
||||
|
||||
### **User Experience Innovation**
|
||||
- **Consistent Interface**: Unified patterns across all features
|
||||
- **Professional Design**: Enterprise-grade UI components
|
||||
- **Accessibility**: WCAG 2.1 AA compliance throughout
|
||||
- **Responsive**: Mobile-friendly across all screen sizes
|
||||
- **Intuitive Workflows**: Clear progression from study to trial execution
|
||||
|
||||
### **Development Infrastructure**
|
||||
- **Comprehensive Seed Data**: 3 studies, 8 participants, 5 experiments, 7 trials
|
||||
- **Realistic Test Scenarios**: Elementary education, elderly care, navigation trust
|
||||
- **Development Database**: Instant setup with `bun db:seed`
|
||||
- **Documentation**: Complete technical and user documentation
|
||||
|
||||
---
|
||||
|
||||
## ✅ **Trial System Overhaul - COMPLETE**
|
||||
|
||||
### **Visual Design Standardization**
|
||||
- **EntityView Integration**: All trial pages now use unified EntityView patterns
|
||||
- **Consistent Headers**: Standard EntityViewHeader with icons, status badges, and actions
|
||||
- **Sidebar Layout**: Professional EntityViewSidebar with organized information panels
|
||||
- **Breadcrumb Integration**: Proper navigation context throughout trial workflow
|
||||
|
||||
### **Wizard Interface Redesign**
|
||||
- **Panel-Based Architecture**: Adopted PanelsContainer system from experiment designer
|
||||
- **Three-Panel Layout**: Left (controls), Center (execution), Right (monitoring)
|
||||
- **Breadcrumb Navigation**: Proper navigation hierarchy matching platform standards
|
||||
- **Component Reuse**: 90% code sharing with experiment designer patterns
|
||||
- **Real-time Status**: Clean connection indicators without UI flashing
|
||||
- **Resizable Panels**: Drag-to-resize functionality with overflow containment
|
||||
|
||||
### **Component Unification**
|
||||
- **ActionControls**: Updated to match unified component interface patterns
|
||||
- **ParticipantInfo**: Streamlined for sidebar display with essential information
|
||||
- **EventsLogSidebar**: New component for real-time event monitoring
|
||||
- **RobotStatus**: Integrated mock robot simulation for development testing
|
||||
|
||||
### **Technical Improvements**
|
||||
- **WebSocket Stability**: Enhanced connection handling with polling fallback
|
||||
- **Error Management**: Improved development mode error handling without UI flashing
|
||||
- **Type Safety**: Complete TypeScript compatibility across all trial components
|
||||
- **State Management**: Simplified trial state updates and real-time synchronization
|
||||
|
||||
### **Production Capabilities**
|
||||
- **Mock Robot Integration**: Complete simulation for development and testing
|
||||
- **Real-time Execution**: WebSocket-based live updates with automatic fallback
|
||||
- **Data Capture**: Comprehensive event logging and trial progression tracking
|
||||
- **Role-based Access**: Proper wizard, researcher, and observer role enforcement
|
||||
|
||||
---
|
||||
|
||||
## ✅ **Experiment Designer Redesign - COMPLETE**
|
||||
|
||||
### **Development Status**
|
||||
**Priority**: High
|
||||
**Target**: Enhanced visual programming capabilities
|
||||
**Status**: ✅ Complete
|
||||
|
||||
**Completed Enhancements**:
|
||||
- ✅ Enhanced visual programming interface with modern iconography
|
||||
- ✅ Advanced step configuration with parameter editing
|
||||
- ✅ Real-time validation with comprehensive error detection
|
||||
- ✅ Deterministic hashing for reproducibility
|
||||
- ✅ Plugin drift detection and signature tracking
|
||||
- ✅ Modern drag-and-drop interface with @dnd-kit
|
||||
- ✅ Type-safe state management with Zustand
|
||||
- ✅ Export/import functionality with integrity verification
|
||||
|
||||
### **Technical Implementation**
|
||||
```typescript
|
||||
// Completed step configuration interface
|
||||
interface StepConfiguration {
|
||||
type: 'wizard_action' | 'robot_action' | 'parallel' | 'conditional' | 'timer' | 'loop';
|
||||
parameters: StepParameters;
|
||||
validation: ValidationRules;
|
||||
dependencies: StepDependency[];
|
||||
}
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ User Interface Layer │
|
||||
│ ├── Experiment Designer (visual programming) │
|
||||
│ ├── Wizard Interface (trial execution) │
|
||||
│ ├── Observer View (live monitoring) │
|
||||
│ └── Participant View (thesis study) │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ Data Management Layer │
|
||||
│ ├── PostgreSQL + Drizzle ORM │
|
||||
│ ├── tRPC API (12 routers) │
|
||||
│ └── Better Auth (role-based auth) │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ Robot Integration Layer │
|
||||
│ ├── Plugin system (robot-agnostic) │
|
||||
│ ├── ROS2 via rosbridge WebSocket │
|
||||
│ └── Docker deployment (nao_driver, ros_bridge) │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### **Key Fixes Applied**
|
||||
- ✅ **Step Addition Bug**: Fixed JSX structure and type import issues
|
||||
- ✅ **TypeScript Compilation**: All type errors resolved
|
||||
- ✅ **Drag and Drop**: Fully functional with DndContext properly configured
|
||||
- ✅ **State Management**: Zustand store working correctly with all actions
|
||||
- ✅ **UI Layout**: Three-panel layout with Action Library, Step Flow, and Properties
|
||||
### Plugin Identifier System
|
||||
|
||||
```
|
||||
plugins table:
|
||||
- id: UUID (primary key)
|
||||
- identifier: varchar (unique, e.g. "nao6-ros2")
|
||||
- name: varchar (display, e.g. "NAO6 Robot (ROS2)")
|
||||
- robotId: UUID (optional FK to robots)
|
||||
- actionDefinitions: JSONB
|
||||
|
||||
actions table:
|
||||
- type: "plugin.action" (e.g., "nao6-ros2.say_with_emotion")
|
||||
- pluginId: varchar (references plugins.identifier)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 **Sprint Planning & Progress**
|
||||
## Branching Flow
|
||||
|
||||
### **Current Sprint (February 2025)**
|
||||
**Theme**: Production Deployment Preparation
|
||||
Experiment steps support conditional branching with wizard choices:
|
||||
|
||||
**Goals**:
|
||||
1. ✅ Complete experiment designer redesign
|
||||
2. ✅ Fix step addition functionality
|
||||
3. ✅ Resolve TypeScript compilation issues
|
||||
4. ⏳ Final code quality improvements
|
||||
```
|
||||
Step 3 (Comprehension Check)
|
||||
└── wizard_wait_for_response
|
||||
├── Click "Correct" → setLastResponse("Correct") → nextStepId=step4a
|
||||
└── Click "Incorrect" → setLastResponse("Incorrect") → nextStepId=step4b
|
||||
|
||||
**Sprint Metrics**:
|
||||
- **Story Points**: 34 total
|
||||
- **Completed**: 30 points
|
||||
- **In Progress**: 4 points
|
||||
- **Planned**: 0 points
|
||||
Step 4a/4b (Branches)
|
||||
└── conditions.nextStepId: step5.id → convergence point
|
||||
|
||||
### **Development Velocity**
|
||||
- **Sprint 1**: 28 story points completed
|
||||
- **Sprint 2**: 32 story points completed
|
||||
- **Sprint 3**: 34 story points completed
|
||||
- **Sprint 4**: 30 story points completed (current)
|
||||
- **Average**: 31.0 story points per sprint
|
||||
|
||||
### **Quality Metrics**
|
||||
- **Critical Bugs**: Zero (all step addition issues resolved)
|
||||
- **Code Coverage**: High coverage maintained across all components
|
||||
- **Build Time**: Consistently under 3 minutes
|
||||
- **TypeScript Errors**: Zero in production code
|
||||
- **Designer Functionality**: 100% operational
|
||||
Step 5 (Story Continues)
|
||||
└── Linear progression to Step 6
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Success Criteria Validation**
|
||||
## NAO6 Robot Actions (14 total)
|
||||
|
||||
### **Technical Requirements** ✅ **Met**
|
||||
- ✅ End-to-end type safety throughout platform
|
||||
- ✅ Role-based access control with 4 distinct roles
|
||||
- ✅ Comprehensive API covering all research workflows
|
||||
- ✅ Visual experiment designer with drag-and-drop interface
|
||||
- ✅ Real-time trial execution framework ready
|
||||
- ✅ Scalable architecture built for research teams
|
||||
|
||||
### **User Experience Goals** ✅ **Met**
|
||||
- ✅ Intuitive interface following modern design principles
|
||||
- ✅ Consistent experience across all features
|
||||
- ✅ Responsive design working on all devices
|
||||
- ✅ Accessibility compliance for inclusive research
|
||||
- ✅ Professional appearance suitable for academic use
|
||||
|
||||
### **Research Workflow Support** ✅ **Met**
|
||||
- ✅ Hierarchical study structure (Study → Experiment → Trial → Step → Action)
|
||||
- ✅ Multi-role collaboration with proper permissions
|
||||
- ✅ Comprehensive data capture for all trial activities
|
||||
- ✅ Flexible robot integration supporting multiple platforms
|
||||
- ✅ Data analysis and export capabilities
|
||||
| Category | Actions |
|
||||
|----------|---------|
|
||||
| Speech | say, say_with_emotion, wave_goodbye |
|
||||
| Movement | walk, turn, move_to_posture |
|
||||
| Gestures | play_animation, gesture |
|
||||
| Sensors | get_sensors, bumper_state, touch_state |
|
||||
| LEDs | set_eye_leds, set_breathing_lights |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **Production Readiness**
|
||||
## Tech Stack
|
||||
|
||||
### **Deployment Checklist** ✅ **Complete**
|
||||
- ✅ Environment variables configured for Vercel
|
||||
- ✅ Database migrations ready for production
|
||||
- ✅ Security headers and CSRF protection configured
|
||||
- ✅ Error tracking and performance monitoring setup
|
||||
- ✅ Build process optimized for Edge Runtime
|
||||
- ✅ Static assets and CDN configuration ready
|
||||
|
||||
### **Performance Validation** ✅ **Passed**
|
||||
- ✅ Page load time < 2 seconds (Currently optimal)
|
||||
- ✅ API response time < 200ms (Currently optimal)
|
||||
- ✅ Database query time < 50ms (Currently optimal)
|
||||
- ✅ Build completes in < 3 minutes (Currently optimal)
|
||||
- ✅ Zero TypeScript compilation errors
|
||||
- ✅ All ESLint rules passing
|
||||
|
||||
### **Security Validation** ✅ **Verified**
|
||||
- ✅ Role-based access control at all levels
|
||||
- ✅ Input validation and sanitization comprehensive
|
||||
- ✅ SQL injection protection via Drizzle ORM
|
||||
- ✅ XSS prevention with proper content handling
|
||||
- ✅ Secure session management with NextAuth.js
|
||||
- ✅ Audit logging for all sensitive operations
|
||||
| Component | Technology | Version |
|
||||
|-----------|------------|---------|
|
||||
| Framework | Next.js | 15-16.x |
|
||||
| Language | TypeScript | 5.x (strict) |
|
||||
| Database | PostgreSQL | 14+ |
|
||||
| ORM | Drizzle | latest |
|
||||
| Auth | NextAuth.js | v5 |
|
||||
| API | tRPC | latest |
|
||||
| UI | Tailwind + shadcn/ui | latest |
|
||||
| Real-time | WebSocket | with polling fallback |
|
||||
| Robot | ROS2 Humble | via rosbridge |
|
||||
| Package Manager | Bun | latest |
|
||||
|
||||
---
|
||||
|
||||
## 📈 **Platform Capabilities**
|
||||
## Development Status
|
||||
|
||||
### **Research Workflow Support**
|
||||
- **Study Management**: Complete lifecycle from creation to analysis
|
||||
- **Team Collaboration**: Multi-user support with role-based permissions
|
||||
- **Experiment Design**: Visual programming interface for protocol creation
|
||||
- **Trial Execution**: Panel-based wizard interface matching experiment designer architecture
|
||||
- **Real-time Updates**: WebSocket integration with intelligent polling fallback
|
||||
- **Data Capture**: Synchronized multi-modal data streams with comprehensive event logging
|
||||
- **Robot Integration**: Plugin-based support for multiple platforms
|
||||
### Completed Features
|
||||
| Feature | Status | Notes |
|
||||
|---------|--------|-------|
|
||||
| Database Schema | ✅ | 31 tables |
|
||||
| Authentication | ✅ | 4 roles |
|
||||
| Experiment Designer | ✅ | 26+ blocks |
|
||||
| Wizard Interface | ✅ | 3-panel design |
|
||||
| Real-time Updates | ✅ | WebSocket |
|
||||
| Plugin System | ✅ | Robot-agnostic |
|
||||
| NAO6 Integration | ✅ | Docker deployment |
|
||||
| Conditional Branching | ✅ | Wizard choices |
|
||||
| Mock Robot | ✅ | Development mode |
|
||||
|
||||
### **Technical Capabilities**
|
||||
- **Scalability**: Architecture supporting large research institutions
|
||||
- **Performance**: Optimized for concurrent multi-user environments
|
||||
- **Security**: Research-grade data protection and access control
|
||||
- **Flexibility**: Customizable workflows for diverse methodologies
|
||||
- **Integration**: Robot platform agnostic with plugin architecture
|
||||
- **Compliance**: Research ethics and data protection compliance
|
||||
### Known Issues
|
||||
| Issue | Status | Notes |
|
||||
|-------|--------|-------|
|
||||
| robots.executeSystemAction | Known error | Fallback works |
|
||||
|
||||
---
|
||||
|
||||
## 🔮 **Roadmap & Future Work**
|
||||
## SSH Deployment Commands
|
||||
|
||||
### **Immediate Priorities** (Next 30 days)
|
||||
- **Wizard Interface Development** - Complete rebuild of trial execution interface
|
||||
- **Robot Control Implementation** - NAO6 integration with WebSocket communication
|
||||
- **Trial Execution Engine** - Step-by-step protocol execution with real-time data capture
|
||||
- **User Experience Testing** - Validate study-scoped workflows with target users
|
||||
```bash
|
||||
# Local development
|
||||
bun dev
|
||||
|
||||
### **Short-term Goals** (Next 60 days)
|
||||
- **IRB Application Preparation** - Complete documentation and study protocols
|
||||
- **Reference Experiment Implementation** - Well-documented HRI experiment for comparison study
|
||||
- **Training Materials Development** - Comprehensive materials for both HRIStudio and Choregraphe
|
||||
- **Platform Validation** - Extensive testing and reliability verification
|
||||
# Database
|
||||
bun db:push # Push schema changes
|
||||
bun db:seed # Seed with test data
|
||||
bun run docker:up # Start PostgreSQL
|
||||
|
||||
### **Long-term Vision** (Next 90+ days)
|
||||
- **User Study Execution** - Comparative study with 10-12 non-engineering participants
|
||||
- **Thesis Research Completion** - Data analysis and academic paper preparation
|
||||
- **Platform Refinement** - Post-study improvements based on real user feedback
|
||||
- **Community Release** - Open source release for broader HRI research community
|
||||
# Quality
|
||||
bun typecheck # TypeScript validation
|
||||
bun lint # ESLint
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎊 **Project Success Declaration**
|
||||
## Thesis Timeline
|
||||
|
||||
**HRIStudio is officially ready for production deployment.**
|
||||
Current phase: **March 2026** - Implementation complete, preparing user study
|
||||
|
||||
### **Completion Summary**
|
||||
The platform successfully provides researchers with a comprehensive, professional, and scientifically rigorous environment for conducting Wizard of Oz studies in Human-Robot Interaction research. All major development goals have been achieved, including the complete modernization of the experiment designer with advanced visual programming capabilities and the successful consolidation of routes into a logical study-scoped architecture. Quality standards have been exceeded, and the system is prepared for thesis research and eventual community use.
|
||||
|
||||
### **Key Success Metrics**
|
||||
- **Development Velocity**: Consistently meeting sprint goals with 30+ story points
|
||||
- **Code Quality**: Zero production TypeScript errors, fully functional designer
|
||||
- **Architecture Quality**: Clean study-scoped hierarchy with eliminated code duplication
|
||||
- **User Experience**: Intuitive navigation flow from studies to entity management
|
||||
- **Route Health**: All routes functional with proper error handling and helpful redirects
|
||||
- **User Experience**: Professional, accessible, consistent interface with modern UX
|
||||
- **Performance**: All benchmarks exceeded, sub-100ms hash computation
|
||||
- **Security**: Comprehensive protection and compliance
|
||||
- **Documentation**: Complete technical and user guides
|
||||
- **Designer Functionality**: 100% operational with step addition working perfectly
|
||||
|
||||
### **Ready For**
|
||||
- ✅ Immediate Vercel deployment
|
||||
- ✅ Research team onboarding
|
||||
- ✅ Academic pilot studies
|
||||
- ✅ Full production research use
|
||||
- ✅ Institutional deployment
|
||||
|
||||
**The development team has successfully delivered a world-class platform that will advance Human-Robot Interaction research by providing standardized, reproducible, and efficient tools for conducting high-quality scientific studies.**
|
||||
| Phase | Status | Date |
|
||||
|-------|--------|------|
|
||||
| Proposal | ✅ | Sept 2025 |
|
||||
| IRB Application | ✅ | Dec 2025 |
|
||||
| Implementation | ✅ | Feb 2026 |
|
||||
| User Study | 🔄 In Progress | Mar-Apr 2026 |
|
||||
| Defense | Scheduled | April 2026 |
|
||||
|
||||
---
|
||||
|
||||
## 🔧 **Development Notes**
|
||||
## Next Steps
|
||||
|
||||
### **Technical Debt Status**
|
||||
- **High Priority**: None identified
|
||||
- **Medium Priority**: Minor database query optimizations possible
|
||||
- **Low Priority**: Some older components could benefit from modern React patterns
|
||||
|
||||
### **Development Restrictions**
|
||||
Following Vercel Edge Runtime compatibility:
|
||||
- ❌ No development servers during implementation sessions
|
||||
- ❌ No Drizzle Studio during development work
|
||||
- ✅ Use `bun db:push` for schema changes
|
||||
- ✅ Use `bun typecheck` for validation
|
||||
- ✅ Use `bun build` for production testing
|
||||
|
||||
### **Quality Gates**
|
||||
- ✅ All TypeScript compilation errors resolved
|
||||
- ✅ All ESLint rules passing with autofix enabled
|
||||
- ✅ All Prettier formatting applied consistently
|
||||
- ✅ No security vulnerabilities detected
|
||||
- ✅ Performance benchmarks met
|
||||
- ✅ Accessibility standards validated
|
||||
1. Complete user study (10-12 participants)
|
||||
2. Data analysis and thesis writing
|
||||
3. Final defense April 2026
|
||||
4. Open source release
|
||||
|
||||
---
|
||||
|
||||
*This document consolidates all project status, progress tracking, and achievement documentation. It serves as the single source of truth for HRIStudio's development state and production readiness.*
|
||||
*Last Updated: March 22, 2026*
|
||||
@@ -107,7 +107,7 @@ This work addresses a significant bottleneck in HRI research. By creating HRIStu
|
||||
\hline
|
||||
September & Finalize and submit this proposal (Due: Sept. 20).
|
||||
|
||||
Submit IRB application for the user study. \\
|
||||
Submit IRB application for the study. \\
|
||||
\hline
|
||||
Oct -- Nov & Complete final implementation of core HRIStudio features.
|
||||
|
||||
@@ -119,13 +119,15 @@ Begin recruiting participants. \\
|
||||
\hline
|
||||
\multicolumn{2}{|l|}{\textbf{Spring 2026: Execution, Analysis, and Writing}} \\
|
||||
\hline
|
||||
Jan -- Feb & Upon receiving IRB approval, conduct all user study sessions. \\
|
||||
Jan -- Feb & Run pilot tests with platform.
|
||||
|
||||
Refine based on testing feedback. \\
|
||||
\hline
|
||||
March & Analyze all data from the user study.
|
||||
March & Execute user study sessions (10-12 participants).
|
||||
|
||||
Draft Results and Discussion sections.
|
||||
Analyze data from the user study.
|
||||
|
||||
Submit ``Intent to Defend'' form (Due: March 1). \\
|
||||
Draft Results and Discussion sections. \\
|
||||
\hline
|
||||
April & Submit completed thesis draft to the defense committee (Due: April 1).
|
||||
|
||||
|
||||
@@ -1,599 +1,166 @@
|
||||
# HRIStudio Quick Reference Guide
|
||||
|
||||
## 🚀 **Getting Started (5 Minutes)**
|
||||
## Quick Setup
|
||||
|
||||
### Prerequisites
|
||||
- [Bun](https://bun.sh) (package manager)
|
||||
- [PostgreSQL](https://postgresql.org) 14+
|
||||
- [Docker](https://docker.com) (optional)
|
||||
|
||||
### Quick Setup
|
||||
```bash
|
||||
# Clone and install
|
||||
git clone <repo-url> hristudio
|
||||
# Clone with submodules
|
||||
git clone https://github.com/soconnor0919/hristudio.git
|
||||
cd hristudio
|
||||
git submodule update --init --recursive
|
||||
|
||||
# Install and setup
|
||||
bun install
|
||||
|
||||
# Start database
|
||||
bun run docker:up
|
||||
|
||||
# Setup database
|
||||
bun db:push
|
||||
bun db:seed
|
||||
|
||||
# Single command now syncs all repositories:
|
||||
# - Core blocks from localhost:3000/hristudio-core
|
||||
# - Robot plugins from https://repo.hristudio.com
|
||||
|
||||
# Start development
|
||||
# Start
|
||||
bun dev
|
||||
```
|
||||
|
||||
### Default Login
|
||||
- **Admin**: `sean@soconnor.dev` / `password123`
|
||||
- **Researcher**: `alice.rodriguez@university.edu` / `password123`
|
||||
- **Wizard**: `emily.watson@lab.edu` / `password123`
|
||||
**Login**: `sean@soconnor.dev` / `password123`
|
||||
|
||||
---
|
||||
|
||||
## 📁 **Project Structure**
|
||||
## Key Concepts
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Next.js App Router pages
|
||||
│ ├── (auth)/ # Authentication pages
|
||||
│ ├── (dashboard)/ # Main application
|
||||
│ └── api/ # API routes
|
||||
├── components/ # UI components
|
||||
│ ├── ui/ # shadcn/ui components
|
||||
│ ├── experiments/ # Feature components
|
||||
│ ├── studies/
|
||||
│ ├── participants/
|
||||
│ └── trials/
|
||||
├── server/ # Backend code
|
||||
│ ├── api/routers/ # tRPC routers
|
||||
│ ├── auth/ # NextAuth config
|
||||
│ └── db/ # Database schema
|
||||
└── lib/ # Utilities
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Key Concepts**
|
||||
|
||||
### Hierarchical Structure
|
||||
### Hierarchy
|
||||
```
|
||||
Study → Experiment → Trial → Step → Action
|
||||
```
|
||||
|
||||
### User Roles
|
||||
- **Administrator**: Full system access
|
||||
- **Researcher**: Create studies, design experiments
|
||||
- **Wizard**: Execute trials, control robots
|
||||
- **Observer**: Read-only access
|
||||
### User Roles (Study-level)
|
||||
- **Owner**: Full study control, manage members
|
||||
- **Researcher**: Design experiments, manage participants
|
||||
- **Wizard**: Execute trials, control robot during sessions
|
||||
- **Observer**: Read-only access to study data
|
||||
|
||||
### Core Workflows
|
||||
1. **Study Creation** → Team setup → Participant recruitment
|
||||
2. **Experiment Design** → Visual designer → Protocol validation
|
||||
3. **Trial Execution** → Wizard interface → Data capture
|
||||
4. **Data Analysis** → Export → Insights
|
||||
### Plugin Identifier System
|
||||
- `identifier`: Machine-readable key (e.g., `nao6-ros2`)
|
||||
- `name`: Display name (e.g., `NAO6 Robot (ROS2 Integration)`)
|
||||
- Lookup order: identifier → name → fallback
|
||||
|
||||
---
|
||||
|
||||
## 🛠 **Development Commands**
|
||||
## Development Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `bun dev` | Start development server |
|
||||
| `bun build` | Build for production |
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `bun dev` | Start dev server |
|
||||
| `bun build` | Production build |
|
||||
| `bun typecheck` | TypeScript validation |
|
||||
| `bun lint` | Code quality checks |
|
||||
| `bun db:push` | Push schema changes |
|
||||
| `bun db:seed` | Seed data & sync repositories |
|
||||
| `bun db:studio` | Open database GUI |
|
||||
| `bun db:seed` | Seed data + sync plugins + forms |
|
||||
| `bun run docker:up` | Start PostgreSQL + MinIO |
|
||||
|
||||
## Forms System
|
||||
|
||||
### Form Types
|
||||
- **Consent**: Legal/IRB consent documents with signature fields
|
||||
- **Survey**: Multi-question questionnaires (ratings, multiple choice)
|
||||
- **Questionnaire**: Custom data collection forms
|
||||
|
||||
### Templates (seeded by default)
|
||||
- Informed Consent - Standard consent template
|
||||
- Post-Session Survey - Participant feedback form
|
||||
- Demographics - Basic demographic collection
|
||||
|
||||
### Routes
|
||||
- `/studies/[id]/forms` - List forms
|
||||
- `/studies/[id]/forms/new` - Create form (from template or scratch)
|
||||
- `/studies/[id]/forms/[formId]` - View/edit form, preview, responses
|
||||
|
||||
---
|
||||
|
||||
## 🌐 **API Reference**
|
||||
## NAO6 Robot Docker
|
||||
|
||||
### Base URL
|
||||
```
|
||||
http://localhost:3000/api/trpc/
|
||||
```
|
||||
|
||||
### Key Routers
|
||||
- **`auth`**: Login, logout, registration
|
||||
- **`studies`**: CRUD operations, team management
|
||||
- **`experiments`**: Design, configuration, validation
|
||||
- **`participants`**: Registration, consent, demographics
|
||||
- **`trials`**: Execution, monitoring, data capture, real-time control
|
||||
- **`robots`**: Integration, communication, actions, plugins
|
||||
- **`dashboard`**: Overview stats, recent activity, study progress
|
||||
- **`admin`**: Repository management, system settings
|
||||
|
||||
---
|
||||
|
||||
## 🤖 NAO6 Docker Integration
|
||||
|
||||
### Quick Start
|
||||
```bash
|
||||
cd ~/Documents/Projects/nao6-hristudio-integration
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Robot automatically wakes up and disables autonomous life on startup.
|
||||
**Services**: nao_driver, ros_bridge (:9090), ros_api
|
||||
|
||||
**Topics**:
|
||||
- `/speech` - TTS
|
||||
- `/cmd_vel` - Movement
|
||||
- `/leds/eyes` - LEDs
|
||||
|
||||
---
|
||||
|
||||
## Architecture Layers
|
||||
|
||||
### ROS Topics
|
||||
```
|
||||
/speech - Text-to-speech
|
||||
/cmd_vel - Movement commands
|
||||
/joint_angles - Joint position control
|
||||
/camera/front/image_raw
|
||||
/camera/bottom/image_raw
|
||||
/imu/torso
|
||||
/bumper
|
||||
/{hand,head}_touch
|
||||
/sonar/{left,right}
|
||||
/info
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
- Plugin identifier: `nao6-ros2`
|
||||
- Plugin name: `NAO6 Robot (ROS2 Integration)`
|
||||
- Action types: `nao6-ros2.say_with_emotion`, `nao6-ros2.move_arm`, etc.
|
||||
|
||||
See [nao6-quick-reference.md](./nao6-quick-reference.md) for full details.
|
||||
|
||||
### Example Usage
|
||||
```typescript
|
||||
// Get user's studies
|
||||
const studies = api.studies.getUserStudies.useQuery();
|
||||
|
||||
// Create new experiment
|
||||
const createExperiment = api.experiments.create.useMutation();
|
||||
┌─────────────────────────────────────┐
|
||||
│ UI: Design / Execute / Playback │
|
||||
├─────────────────────────────────────┤
|
||||
│ Server: tRPC, Auth, Trial Logic │
|
||||
├─────────────────────────────────────┤
|
||||
│ Data: PostgreSQL, File Storage │
|
||||
│ Robot: ROS2 via WebSocket │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🗄️ **Database Quick Reference**
|
||||
## WebSocket Architecture
|
||||
|
||||
- **Trial Updates**: `ws://localhost:3001/api/websocket`
|
||||
- **ROS Bridge**: `ws://localhost:9090` (rosbridge)
|
||||
- **Real-time**: Auto-reconnect with exponential backoff
|
||||
- **Message Types**: trial_event, trial_status, connection_established
|
||||
|
||||
---
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Core Tables
|
||||
```sql
|
||||
users -- Authentication & profiles
|
||||
studies -- Research projects
|
||||
experiments -- Protocol templates
|
||||
participants -- Study participants
|
||||
trials -- Experiment instances
|
||||
steps -- Experiment phases
|
||||
trial_events -- Execution logs
|
||||
robots -- Available platforms
|
||||
```
|
||||
- `users` - Authentication
|
||||
- `studies` - Research projects
|
||||
- `experiments` - Protocol templates
|
||||
- `trials` - Execution instances
|
||||
- `steps` - Experiment phases
|
||||
- `actions` - Atomic tasks
|
||||
- `plugins` - Robot integrations (identifier column)
|
||||
- `trial_events` - Execution logs
|
||||
|
||||
---
|
||||
|
||||
## Route Structure
|
||||
|
||||
### Key Relationships
|
||||
```
|
||||
studies → experiments → trials
|
||||
studies → participants
|
||||
trials → trial_events
|
||||
experiments → steps
|
||||
/dashboard - Global overview
|
||||
/studies - Study list
|
||||
/studies/[id] - Study details
|
||||
/studies/[id]/experiments
|
||||
/studies/[id]/trials
|
||||
/studies/[id]/participants
|
||||
/trials/[id]/wizard - Trial execution
|
||||
/experiments/[id]/designer - Visual editor
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 **UI Components**
|
||||
## Troubleshooting
|
||||
|
||||
**Build errors**: `rm -rf .next && bun build`
|
||||
|
||||
**Database reset**: `bun db:push --force && bun db:seed`
|
||||
|
||||
**Check types**: `bun typecheck`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Trial System Quick Reference**
|
||||
## Plugin System
|
||||
|
||||
### Trial Workflow
|
||||
```
|
||||
1. Create Study → 2. Design Experiment → 3. Add Participants → 4. Schedule Trial → 5. Execute with Wizard Interface → 6. Analyze Results
|
||||
```
|
||||
|
||||
### Key Trial Pages
|
||||
- **`/studies/[id]/trials`**: List trials for specific study
|
||||
- **`/trials/[id]`**: Individual trial details and management
|
||||
- **`/trials/[id]/wizard`**: Panel-based real-time execution interface
|
||||
- **`/trials/[id]/analysis`**: Post-trial data analysis
|
||||
|
||||
### Trial Status Flow
|
||||
```
|
||||
scheduled → in_progress → completed
|
||||
↘ aborted
|
||||
↘ failed
|
||||
```
|
||||
|
||||
### Wizard Interface Architecture (Panel-Based)
|
||||
The wizard interface uses the same proven panel system as the experiment designer:
|
||||
|
||||
#### **Layout Components**
|
||||
- **PageHeader**: Consistent navigation with breadcrumbs
|
||||
- **PanelsContainer**: Three-panel resizable layout
|
||||
- **Proper Navigation**: Dashboard → Studies → [Study] → Trials → [Trial] → Wizard Control
|
||||
|
||||
#### **Panel Organization**
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ PageHeader: Wizard Control │
|
||||
├──────────┬─────────────────────────┬────────────────────┤
|
||||
│ Left │ Center │ Right │
|
||||
│ Panel │ Panel │ Panel │
|
||||
│ │ │ │
|
||||
│ Trial │ Current Step │ Robot Status │
|
||||
│ Controls │ & Wizard Actions │ Participant Info │
|
||||
│ Step │ │ Live Events │
|
||||
│ List │ │ Connection Status │
|
||||
└──────────┴─────────────────────────┴────────────────────┘
|
||||
```
|
||||
|
||||
#### **Panel Features**
|
||||
- **Left Panel**: Trial controls, status, step navigation
|
||||
- **Center Panel**: Main execution area with current step and wizard actions
|
||||
- **Right Panel**: Real-time monitoring and context information
|
||||
- **Resizable**: Drag separators to adjust panel sizes
|
||||
- **Overflow Contained**: No page-level scrolling, internal panel scrolling
|
||||
|
||||
### Technical Features
|
||||
- **Real-time Control**: Step-by-step protocol execution
|
||||
- **WebSocket Integration**: Live updates with polling fallback
|
||||
- **Component Reuse**: 90% code sharing with experiment designer
|
||||
- **Type Safety**: Complete TypeScript compatibility
|
||||
- **Mock Robot System**: TurtleBot3 simulation ready for development
|
||||
|
||||
---
|
||||
|
||||
### Layout Components
|
||||
```typescript
|
||||
// Page wrapper with navigation
|
||||
<PageLayout title="Studies" description="Manage research studies">
|
||||
<StudiesTable />
|
||||
</PageLayout>
|
||||
// Loading a plugin by identifier
|
||||
const plugin = await trialExecution.loadPlugin("nao6-ros2");
|
||||
|
||||
// Entity forms (unified pattern)
|
||||
<EntityForm
|
||||
mode="create"
|
||||
entityName="Study"
|
||||
form={form}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
|
||||
// Data tables (consistent across entities)
|
||||
<DataTable
|
||||
columns={studiesColumns}
|
||||
data={studies}
|
||||
searchKey="name"
|
||||
/>
|
||||
```
|
||||
|
||||
### Form Patterns
|
||||
```typescript
|
||||
// Standard form setup
|
||||
const form = useForm<StudyFormData>({
|
||||
resolver: zodResolver(studySchema),
|
||||
defaultValues: { /* ... */ }
|
||||
});
|
||||
|
||||
// Unified submission
|
||||
const onSubmit = async (data: StudyFormData) => {
|
||||
await createStudy.mutateAsync(data);
|
||||
router.push(`/studies/${result.id}`);
|
||||
};
|
||||
// Action execution
|
||||
await robot.execute("nao6-ros2.say_with_emotion", { text: "Hello" });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Route Structure**
|
||||
|
||||
### Study-Scoped Architecture
|
||||
All study-dependent functionality flows through studies for complete organizational consistency:
|
||||
|
||||
```
|
||||
Platform Routes (Global):
|
||||
/dashboard # Global overview with study filtering
|
||||
/studies # Study management hub
|
||||
/profile # User account management
|
||||
/admin # System administration
|
||||
|
||||
Study-Scoped Routes (All Study-Dependent):
|
||||
/studies/[id] # Study details and overview
|
||||
/studies/[id]/participants # Study participants
|
||||
/studies/[id]/trials # Study trials
|
||||
/studies/[id]/experiments # Study experiment protocols
|
||||
/studies/[id]/plugins # Study robot plugins
|
||||
/studies/[id]/analytics # Study analytics
|
||||
|
||||
Individual Entity Routes (Cross-Study):
|
||||
/trials/[id] # Individual trial details
|
||||
/trials/[id]/wizard # Trial execution interface (TO BE BUILT)
|
||||
/experiments/[id] # Individual experiment details
|
||||
/experiments/[id]/designer # Visual experiment designer
|
||||
|
||||
Helpful Redirects (User Guidance):
|
||||
/participants # → Study selection guidance
|
||||
/trials # → Study selection guidance
|
||||
/experiments # → Study selection guidance
|
||||
/plugins # → Study selection guidance
|
||||
/analytics # → Study selection guidance
|
||||
```
|
||||
|
||||
### Architecture Benefits
|
||||
- **Complete Consistency**: All study-dependent functionality properly scoped
|
||||
- **Clear Mental Model**: Platform-level vs study-level separation
|
||||
- **No Duplication**: Single source of truth for each functionality
|
||||
- **User-Friendly**: Helpful guidance for moved functionality
|
||||
|
||||
## 🔐 **Authentication**
|
||||
|
||||
### Protecting Routes
|
||||
```typescript
|
||||
// Middleware protection
|
||||
export default withAuth(
|
||||
function middleware(request) {
|
||||
// Route logic
|
||||
},
|
||||
{
|
||||
callbacks: {
|
||||
authorized: ({ token }) => !!token,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Component protection
|
||||
const { data: session, status } = useSession();
|
||||
if (status === "loading") return <Loading />;
|
||||
if (!session) return <SignIn />;
|
||||
```
|
||||
|
||||
### Role Checking
|
||||
```typescript
|
||||
// Server-side
|
||||
ctx.session.user.role === "administrator"
|
||||
|
||||
// Client-side
|
||||
import { useSession } from "next-auth/react";
|
||||
const hasRole = (role: string) => session?.user.role === role;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🤖 **Robot Integration**
|
||||
|
||||
### Core Block System
|
||||
```typescript
|
||||
// Core blocks loaded from local repository during development
|
||||
// Repository sync: localhost:3000/hristudio-core → database
|
||||
|
||||
// Block categories (27 total blocks in 4 groups):
|
||||
// - Events (4): when_trial_starts, when_participant_speaks, etc.
|
||||
// - Wizard Actions (6): wizard_say, wizard_gesture, etc.
|
||||
// - Control Flow (8): wait, repeat, if_condition, etc.
|
||||
// - Observation (9): observe_behavior, record_audio, etc.
|
||||
```
|
||||
|
||||
### Plugin Repository System
|
||||
```typescript
|
||||
// Repository sync (admin only)
|
||||
await api.admin.repositories.sync.mutate({ id: repoId });
|
||||
|
||||
// Plugin installation
|
||||
await api.robots.plugins.install.mutate({
|
||||
studyId: 'study-id',
|
||||
pluginId: 'plugin-id'
|
||||
});
|
||||
|
||||
// Get study plugins
|
||||
const plugins = api.robots.plugins.getStudyPlugins.useQuery({
|
||||
studyId: selectedStudyId
|
||||
});
|
||||
```
|
||||
|
||||
### Plugin Structure
|
||||
```typescript
|
||||
interface Plugin {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
trustLevel: 'official' | 'verified' | 'community';
|
||||
actionDefinitions: RobotAction[];
|
||||
metadata: {
|
||||
platform: string;
|
||||
category: string;
|
||||
repositoryId: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Repository Integration
|
||||
- **Robot Plugins**: `https://repo.hristudio.com` (live)
|
||||
- **Core Blocks**: `localhost:3000/hristudio-core` (development)
|
||||
- **Auto-sync**: Integrated into `bun db:seed` command
|
||||
- **Plugin Store**: Browse → Install → Use in experiments
|
||||
|
||||
---
|
||||
|
||||
## 📊 **Common Patterns**
|
||||
|
||||
### Error Handling
|
||||
```typescript
|
||||
try {
|
||||
await mutation.mutateAsync(data);
|
||||
toast.success("Success!");
|
||||
router.push("/success-page");
|
||||
} catch (error) {
|
||||
setError(error.message);
|
||||
toast.error("Failed to save");
|
||||
}
|
||||
```
|
||||
|
||||
### Loading States
|
||||
```typescript
|
||||
const { data, isLoading, error } = api.studies.getAll.useQuery();
|
||||
|
||||
if (isLoading) return <Skeleton />;
|
||||
if (error) return <ErrorMessage error={error} />;
|
||||
return <DataTable data={data} />;
|
||||
```
|
||||
|
||||
### Form Validation
|
||||
```typescript
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, "Name required"),
|
||||
description: z.string().min(10, "Description too short"),
|
||||
duration: z.number().min(5, "Minimum 5 minutes")
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **Deployment**
|
||||
|
||||
### Vercel Deployment
|
||||
```bash
|
||||
# Install Vercel CLI
|
||||
bun add -g vercel
|
||||
|
||||
# Deploy
|
||||
vercel --prod
|
||||
|
||||
# Environment variables
|
||||
vercel env add DATABASE_URL
|
||||
vercel env add NEXTAUTH_SECRET
|
||||
vercel env add CLOUDFLARE_R2_*
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
```bash
|
||||
# Required
|
||||
DATABASE_URL=postgresql://...
|
||||
NEXTAUTH_URL=https://your-domain.com
|
||||
NEXTAUTH_SECRET=your-secret
|
||||
|
||||
# Storage
|
||||
CLOUDFLARE_R2_ACCOUNT_ID=...
|
||||
CLOUDFLARE_R2_ACCESS_KEY_ID=...
|
||||
CLOUDFLARE_R2_SECRET_ACCESS_KEY=...
|
||||
CLOUDFLARE_R2_BUCKET_NAME=hristudio-files
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Experiment Designer — Quick Tips
|
||||
|
||||
- Panels layout
|
||||
- Uses Tailwind-first grid via `PanelsContainer` with fraction-based columns (no hardcoded px).
|
||||
- Left/Center/Right panels are minmax(0, …) columns to prevent horizontal overflow.
|
||||
- Status bar lives inside the bordered container; no gap below the panels.
|
||||
|
||||
- Resizing (no persistence)
|
||||
- Drag separators between Left↔Center and Center↔Right to resize panels.
|
||||
- Fractions are clamped (min/max) to keep panels usable and avoid page overflow.
|
||||
- Keyboard on handles: Arrow keys to resize; Shift+Arrow for larger steps.
|
||||
|
||||
- Overflow rules (no page-level X scroll)
|
||||
- Root containers: `overflow-hidden`, `min-h-0`.
|
||||
- Each panel wrapper: `min-w-0 overflow-hidden`.
|
||||
- Each panel content: `overflow-y-auto overflow-x-hidden` (scroll inside the panel).
|
||||
- If X scroll appears, clamp the offending child (truncate, `break-words`, `overflow-x-hidden`).
|
||||
|
||||
- Action Library scroll
|
||||
- Search/categories header and footer are fixed; the list uses internal scroll (`ScrollArea` with `flex-1`).
|
||||
- Long lists never scroll the page — only the panel.
|
||||
|
||||
- Inspector tabs (shadcn/ui)
|
||||
- Single Tabs root controls both header and content.
|
||||
- TabsList uses simple grid or inline-flex; triggers are plain `TabsTrigger`.
|
||||
- Active state is styled globally (via `globals.css`) using Radix `data-state="active"`.
|
||||
|
||||
## 🔧 **Troubleshooting**
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Build Errors**
|
||||
```bash
|
||||
# Clear cache and rebuild
|
||||
rm -rf .next
|
||||
bun run build
|
||||
```
|
||||
|
||||
**Database Issues**
|
||||
```bash
|
||||
# Reset database
|
||||
bun db:push --force
|
||||
bun db:seed
|
||||
```
|
||||
|
||||
**TypeScript Errors**
|
||||
```bash
|
||||
# Check types
|
||||
bun typecheck
|
||||
|
||||
# Common fixes
|
||||
# - Check imports
|
||||
# - Verify API return types
|
||||
# - Update schema types
|
||||
```
|
||||
|
||||
### Performance Tips
|
||||
- Use React Server Components where possible
|
||||
- Implement proper pagination for large datasets
|
||||
- Add database indexes for frequently queried fields
|
||||
- Use optimistic updates for better UX
|
||||
|
||||
---
|
||||
|
||||
## 📚 **Further Reading**
|
||||
|
||||
### Documentation Files
|
||||
- **[Project Overview](./project-overview.md)**: Complete feature overview
|
||||
- **[Implementation Details](./implementation-details.md)**: Architecture decisions and patterns
|
||||
- **[Database Schema](./database-schema.md)**: Complete database documentation
|
||||
- **[API Routes](./api-routes.md)**: Comprehensive API reference
|
||||
- **[Core Blocks System](./core-blocks-system.md)**: Repository-based block architecture
|
||||
- **[Plugin System Guide](./plugin-system-implementation-guide.md)**: Robot integration guide
|
||||
- **[Project Status](./project-status.md)**: Current development status
|
||||
- **[Work in Progress](./work_in_progress.md)**: Recent changes and active development
|
||||
|
||||
### External Resources
|
||||
- [Next.js Documentation](https://nextjs.org/docs)
|
||||
- [tRPC Documentation](https://trpc.io/docs)
|
||||
- [Drizzle ORM Guide](https://orm.drizzle.team/docs)
|
||||
- [shadcn/ui Components](https://ui.shadcn.com)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Quick Tips**
|
||||
### Quick Tips
|
||||
|
||||
### Development Workflow
|
||||
1. Always run `bun typecheck` before commits
|
||||
2. Use the unified `EntityForm` for all CRUD operations
|
||||
3. Follow the established component patterns
|
||||
4. Add proper error boundaries for new features
|
||||
5. Test with multiple user roles
|
||||
6. Use single `bun db:seed` for complete setup
|
||||
|
||||
### Code Standards
|
||||
- Use TypeScript strict mode
|
||||
- Prefer Server Components over Client Components
|
||||
- Implement proper error handling
|
||||
- Add loading states for all async operations
|
||||
- Use Zod for input validation
|
||||
|
||||
### Best Practices
|
||||
- Keep components focused and composable
|
||||
- Use the established file naming conventions
|
||||
- Implement proper RBAC for new features
|
||||
- Add comprehensive logging for debugging
|
||||
- Follow accessibility guidelines (WCAG 2.1 AA)
|
||||
- Use repository-based plugins instead of hardcoded robot actions
|
||||
- Test plugin installation/uninstallation in different studies
|
||||
|
||||
### Route Architecture
|
||||
- **Study-Scoped**: All entity management flows through studies
|
||||
- **Individual Entities**: Trial/experiment details maintain separate routes
|
||||
- **Helpful Redirects**: Old routes guide users to new locations
|
||||
- **Consistent Navigation**: Breadcrumbs reflect the study → entity hierarchy
|
||||
|
||||
---
|
||||
|
||||
*This quick reference covers the most commonly needed information for HRIStudio development. For detailed implementation guidance, refer to the comprehensive documentation files.*
|
||||
Last updated: March 2026
|
||||
@@ -5,6 +5,9 @@
|
||||
import "./src/env.js";
|
||||
|
||||
/** @type {import("next").NextConfig} */
|
||||
const config = {};
|
||||
const nextConfig = {
|
||||
// Mark server-only packages as external to prevent bundling in client
|
||||
serverExternalPackages: ["postgres", "minio", "child_process"],
|
||||
};
|
||||
|
||||
export default config;
|
||||
export default nextConfig;
|
||||
|
||||
21
package.json
21
package.json
@@ -11,7 +11,8 @@
|
||||
"db:push": "drizzle-kit push",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"db:seed": "bun db:push && bun scripts/seed-dev.ts",
|
||||
"dev": "next dev --turbo",
|
||||
"dev": "bun run ws-server.ts & next dev --turbo",
|
||||
"dev:ws": "bun run ws-server.ts",
|
||||
"docker:up": "if [ \"$(uname)\" = \"Darwin\" ]; then colima start; fi && docker compose up -d",
|
||||
"docker:down": "docker compose down && if [ \"$(uname)\" = \"Darwin\" ]; then colima stop; fi",
|
||||
"format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
|
||||
@@ -79,14 +80,14 @@
|
||||
"js-cookie": "^3.0.5",
|
||||
"lucide-react": "^0.536.0",
|
||||
"minio": "^8.0.6",
|
||||
"next": "^16.1.6",
|
||||
"next": "16.2.1",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"next-themes": "^0.4.6",
|
||||
"postgres": "^3.4.8",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.2.4",
|
||||
"react": "19.2.4",
|
||||
"react-day-picker": "^9.13.2",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-resizable-panels": "^3.0.6",
|
||||
"react-signature-canvas": "^1.1.0-alpha.2",
|
||||
@@ -108,12 +109,12 @@
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20.19.33",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"drizzle-kit": "^0.30.6",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-config-next": "^15.5.12",
|
||||
"eslint-config-next": "16.2.1",
|
||||
"eslint-plugin-drizzle": "^0.2.3",
|
||||
"postcss": "^8.5.6",
|
||||
"prettier": "^3.8.1",
|
||||
@@ -133,5 +134,9 @@
|
||||
"esbuild",
|
||||
"sharp",
|
||||
"unrs-resolver"
|
||||
]
|
||||
],
|
||||
"overrides": {
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3"
|
||||
}
|
||||
}
|
||||
Submodule robot-plugins updated: ff48567918...d772aecc54
@@ -42,7 +42,7 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await caller.experiments.get({ id: exp.id });
|
||||
const result = await caller.experiments!.get({ id: exp.id });
|
||||
|
||||
console.log(`✅ Fetched experiment: ${result.name} (${result.id})`);
|
||||
|
||||
|
||||
@@ -223,6 +223,98 @@ async function main() {
|
||||
{ studyId: study!.id, userId: researcherUser!.id, role: "researcher" },
|
||||
]);
|
||||
|
||||
// Create Forms & Templates
|
||||
console.log("📝 Creating forms and templates...");
|
||||
|
||||
// Templates (system-wide templates)
|
||||
const [consentTemplate] = await db
|
||||
.insert(schema.forms)
|
||||
.values({
|
||||
studyId: study!.id,
|
||||
type: "consent",
|
||||
title: "Standard Informed Consent",
|
||||
description: "A comprehensive informed consent document template for HRI research studies.",
|
||||
isTemplate: true,
|
||||
templateName: "Informed Consent",
|
||||
fields: [
|
||||
{ id: "1", type: "text", label: "Study Title", required: true },
|
||||
{ id: "2", type: "text", label: "Principal Investigator Name", required: true },
|
||||
{ id: "3", type: "text", label: "Institution", required: true },
|
||||
{ id: "4", type: "textarea", label: "Purpose of the Study", required: true },
|
||||
{ id: "5", type: "textarea", label: "Procedures", required: true },
|
||||
{ id: "6", type: "textarea", label: "Risks and Benefits", required: true },
|
||||
{ id: "7", type: "textarea", label: "Confidentiality", required: true },
|
||||
{ id: "8", type: "yes_no", label: "I consent to participate in this study", required: true },
|
||||
{ id: "9", type: "signature", label: "Participant Signature", required: true },
|
||||
],
|
||||
settings: {},
|
||||
createdBy: adminUser.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const [surveyTemplate] = await db
|
||||
.insert(schema.forms)
|
||||
.values({
|
||||
studyId: study!.id,
|
||||
type: "survey",
|
||||
title: "Post-Session Questionnaire",
|
||||
description: "Standard questionnaire to collect participant feedback after HRI sessions.",
|
||||
isTemplate: true,
|
||||
templateName: "Post-Session Survey",
|
||||
fields: [
|
||||
{ id: "1", type: "rating", label: "How engaging was the robot?", required: true, settings: { scale: 5 } },
|
||||
{ id: "2", type: "rating", label: "How understandable was the robot's speech?", required: true, settings: { scale: 5 } },
|
||||
{ id: "3", type: "rating", label: "How natural did the interaction feel?", required: true, settings: { scale: 5 } },
|
||||
{ id: "4", type: "multiple_choice", label: "Did the robot respond appropriately to your actions?", required: true, options: ["Yes, always", "Yes, mostly", "Sometimes", "Rarely", "No"] },
|
||||
{ id: "5", type: "textarea", label: "What did you like most about the interaction?", required: false },
|
||||
{ id: "6", type: "textarea", label: "What could be improved?", required: false },
|
||||
],
|
||||
settings: {},
|
||||
createdBy: adminUser.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const [questionnaireTemplate] = await db
|
||||
.insert(schema.forms)
|
||||
.values({
|
||||
studyId: study!.id,
|
||||
type: "questionnaire",
|
||||
title: "Demographics Form",
|
||||
description: "Basic demographic information collection form.",
|
||||
isTemplate: true,
|
||||
templateName: "Demographics",
|
||||
fields: [
|
||||
{ id: "1", type: "text", label: "Age", required: true },
|
||||
{ id: "2", type: "multiple_choice", label: "Gender", required: true, options: ["Male", "Female", "Non-binary", "Prefer not to say"] },
|
||||
{ id: "3", type: "multiple_choice", label: "Experience with robots", required: true, options: ["None", "A little", "Moderate", "Extensive"] },
|
||||
{ id: "4", type: "multiple_choice", label: "Experience with HRI research", required: true, options: ["Never participated", "Participated once", "Participated several times"] },
|
||||
],
|
||||
settings: {},
|
||||
createdBy: adminUser.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Study-specific form (not a template)
|
||||
const [consentForm] = await db
|
||||
.insert(schema.forms)
|
||||
.values({
|
||||
studyId: study!.id,
|
||||
type: "consent",
|
||||
title: "Interactive Storyteller Consent",
|
||||
description: "Consent form for the Comparative WoZ Study - Interactive Storyteller scenario.",
|
||||
active: true,
|
||||
fields: [
|
||||
{ id: "1", type: "text", label: "Participant Name", required: true },
|
||||
{ id: "2", type: "date", label: "Date", required: true },
|
||||
{ id: "3", type: "textarea", label: "I understand that I will interact with a robot storyteller and may be asked to respond to questions.", required: true },
|
||||
{ id: "4", type: "yes_no", label: "I consent to participate in this study", required: true },
|
||||
{ id: "5", type: "signature", label: "Signature", required: true },
|
||||
],
|
||||
settings: {},
|
||||
createdBy: adminUser.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Insert System Plugins
|
||||
const [corePlugin] = await db
|
||||
.insert(schema.plugins)
|
||||
|
||||
@@ -1,10 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import { PasswordChangeForm } from "~/components/profile/password-change-form";
|
||||
import { ProfileEditForm } from "~/components/profile/profile-edit-form";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import Link from "next/link";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
import { format } from "date-fns";
|
||||
import {
|
||||
User,
|
||||
Mail,
|
||||
Shield,
|
||||
Lock,
|
||||
Settings,
|
||||
Building,
|
||||
Calendar,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
Save,
|
||||
X,
|
||||
Crown,
|
||||
FlaskConical,
|
||||
Eye,
|
||||
UserCheck,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -12,192 +37,375 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { PageHeader } from "~/components/ui/page-header";
|
||||
import { useBreadcrumbsEffect } from "~/components/ui/breadcrumb-provider";
|
||||
import { formatRole, getRoleDescription } from "~/lib/auth-client";
|
||||
import { User, Shield, Download, Trash2, Lock, UserCog } from "lucide-react";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { api } from "~/trpc/react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
|
||||
interface ProfileUser {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string;
|
||||
image: string | null;
|
||||
roles?: Array<{
|
||||
role: "administrator" | "researcher" | "wizard" | "observer";
|
||||
grantedAt: Date;
|
||||
grantedBy: string | null;
|
||||
}>;
|
||||
interface Membership {
|
||||
studyId: string;
|
||||
role: string;
|
||||
joinedAt: Date;
|
||||
}
|
||||
|
||||
function ProfileContent({ user }: { user: ProfileUser }) {
|
||||
function getMemberRole(memberships: Membership[], studyId: string): string {
|
||||
const membership = memberships.find((m) => m.studyId === studyId);
|
||||
return membership?.role ?? "observer";
|
||||
}
|
||||
|
||||
function ProfilePageContent() {
|
||||
const { data: session } = useSession();
|
||||
const utils = api.useUtils();
|
||||
const [isEditing, setIsEditing] = React.useState(false);
|
||||
const [name, setName] = React.useState(session?.user?.name ?? "");
|
||||
const [email, setEmail] = React.useState(session?.user?.email ?? "");
|
||||
const [passwordOpen, setPasswordOpen] = React.useState(false);
|
||||
const [currentPassword, setCurrentPassword] = React.useState("");
|
||||
const [newPassword, setNewPassword] = React.useState("");
|
||||
const [confirmPassword, setConfirmPassword] = React.useState("");
|
||||
|
||||
const { data: userData } = api.users.get.useQuery(
|
||||
{ id: session?.user?.id ?? "" },
|
||||
{ enabled: !!session?.user?.id },
|
||||
);
|
||||
|
||||
const { data: userStudies } = api.studies.list.useQuery({
|
||||
memberOnly: true,
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
const { data: membershipsData } = api.studies.getMyMemberships.useQuery();
|
||||
|
||||
const studyMemberships = membershipsData ?? [];
|
||||
|
||||
const updateProfile = api.users.update.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Profile updated successfully");
|
||||
void utils.users.get.invalidate();
|
||||
setIsEditing(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to update profile", { description: error.message });
|
||||
},
|
||||
});
|
||||
|
||||
const changePassword = api.users.changePassword.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Password changed successfully");
|
||||
setPasswordOpen(false);
|
||||
setCurrentPassword("");
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to change password", { description: error.message });
|
||||
},
|
||||
});
|
||||
|
||||
const handleSave = () => {
|
||||
if (!name.trim()) {
|
||||
toast.error("Name is required");
|
||||
return;
|
||||
}
|
||||
updateProfile.mutate({ id: session?.user?.id ?? "", name, email });
|
||||
};
|
||||
|
||||
const handlePasswordChange = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (newPassword !== confirmPassword) {
|
||||
toast.error("Passwords don't match");
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
toast.error("Password must be at least 8 characters");
|
||||
return;
|
||||
}
|
||||
changePassword.mutate({
|
||||
currentPassword,
|
||||
newPassword,
|
||||
});
|
||||
};
|
||||
|
||||
const user = userData ?? session?.user;
|
||||
const roles = (userData as any)?.systemRoles ?? [];
|
||||
const initials = (user?.name ?? user?.email ?? "U").charAt(0).toUpperCase();
|
||||
|
||||
return (
|
||||
<div className="animate-in fade-in space-y-8 duration-500">
|
||||
<PageHeader
|
||||
title={user.name ?? "User"}
|
||||
description={user.email}
|
||||
icon={User}
|
||||
badges={[
|
||||
{ label: `ID: ${user.id}`, variant: "outline" },
|
||||
...(user.roles?.map((r) => ({
|
||||
label: formatRole(r.role),
|
||||
variant: "secondary" as const,
|
||||
})) ?? []),
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
|
||||
{/* Main Content (Left Column) */}
|
||||
<div className="space-y-8 lg:col-span-2">
|
||||
{/* Personal Information */}
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 border-b pb-2">
|
||||
<User className="text-primary h-5 w-5" />
|
||||
<h3 className="text-lg font-semibold">Personal Information</h3>
|
||||
</div>
|
||||
<Card className="border-border/60 hover:border-border transition-colors">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Contact Details</CardTitle>
|
||||
<CardDescription>
|
||||
Update your public profile information
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ProfileEditForm
|
||||
user={{
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
image: user.image,
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Security */}
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 border-b pb-2">
|
||||
<Lock className="text-primary h-5 w-5" />
|
||||
<h3 className="text-lg font-semibold">Security</h3>
|
||||
</div>
|
||||
<Card className="border-border/60 hover:border-border transition-colors">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Password</CardTitle>
|
||||
<CardDescription>
|
||||
Ensure your account stays secure
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<PasswordChangeForm />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* Sidebar (Right Column) */}
|
||||
<div className="space-y-8">
|
||||
{/* Permissions */}
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 border-b pb-2">
|
||||
<Shield className="text-primary h-5 w-5" />
|
||||
<h3 className="text-lg font-semibold">Permissions</h3>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
{user.roles && user.roles.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{user.roles.map((roleInfo, index) => (
|
||||
<div key={index} className="space-y-2">
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
{formatRole(roleInfo.role)}
|
||||
</span>
|
||||
<span className="text-muted-foreground bg-muted rounded px-1.5 py-0.5 text-[10px]">
|
||||
Since{" "}
|
||||
{new Date(roleInfo.grantedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs leading-relaxed">
|
||||
{getRoleDescription(roleInfo.role)}
|
||||
</p>
|
||||
{index < (user.roles?.length || 0) - 1 && (
|
||||
<Separator className="my-2" />
|
||||
)}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary text-xl font-bold text-primary-foreground">
|
||||
{initials}
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{user?.name ?? "User"}</h1>
|
||||
<p className="text-muted-foreground">{user?.email}</p>
|
||||
{roles.length > 0 && (
|
||||
<div className="mt-1 flex gap-2">
|
||||
{roles.map((role: any) => (
|
||||
<Badge key={role.role} variant="secondary" className="text-xs">
|
||||
{role.role}
|
||||
</Badge>
|
||||
))}
|
||||
<div className="text-muted-foreground mt-4 rounded-lg border border-blue-100 bg-blue-50/50 p-3 text-xs dark:border-blue-900/30 dark:bg-blue-900/10">
|
||||
<div className="text-primary mb-1 flex items-center gap-2 font-medium">
|
||||
<Shield className="h-3 w-3" />
|
||||
<span>Role Management</span>
|
||||
</div>
|
||||
System roles are managed by administrators. Contact
|
||||
support if you need access adjustments.
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsEditing(false)}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={updateProfile.isPending}>
|
||||
{updateProfile.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<div className="py-4 text-center">
|
||||
<p className="text-sm font-medium">No Roles Assigned</p>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
Contact an admin to request access.
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save Changes
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="outline" onClick={() => setIsEditing(true)}>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Edit Profile
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Left Column - Profile Info */}
|
||||
<div className="space-y-6 lg:col-span-2">
|
||||
{/* Personal Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<User className="h-5 w-5 text-primary" />
|
||||
Personal Information
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Your public profile information
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Full Name</Label>
|
||||
{isEditing ? (
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Your name"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 rounded-md border bg-muted/50 p-2">
|
||||
<User className="text-muted-foreground h-4 w-4" />
|
||||
<span>{name || "Not set"}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email Address</Label>
|
||||
{isEditing ? (
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 rounded-md border bg-muted/50 p-2">
|
||||
<Mail className="text-muted-foreground h-4 w-4" />
|
||||
<span>{email}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>User ID</Label>
|
||||
<div className="rounded-md border bg-muted/50 p-2 font-mono text-sm">
|
||||
{user?.id ?? session?.user?.id}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5 text-primary" />
|
||||
Recent Activity
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Your recent actions across the platform
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center">
|
||||
<Calendar className="text-muted-foreground/50 mb-3 h-12 w-12" />
|
||||
<p className="font-medium">No recent activity</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Your recent actions will appear here
|
||||
</p>
|
||||
<Button size="sm" variant="outline" className="mt-3 w-full">
|
||||
Request Access
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Right Column - Settings */}
|
||||
<div className="space-y-6">
|
||||
{/* Security */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-primary" />
|
||||
Security
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Lock className="text-muted-foreground h-4 w-4" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Password</p>
|
||||
<p className="text-muted-foreground text-xs">Last changed: Never</p>
|
||||
</div>
|
||||
</div>
|
||||
<Dialog open={passwordOpen} onOpenChange={setPasswordOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
Change
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change Password</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter your current password and choose a new one.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handlePasswordChange} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="current">Current Password</Label>
|
||||
<Input
|
||||
id="current"
|
||||
type="password"
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new">New Password</Label>
|
||||
<Input
|
||||
id="new"
|
||||
type="password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm">Confirm Password</Label>
|
||||
<Input
|
||||
id="confirm"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setPasswordOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={changePassword.isPending}>
|
||||
{changePassword.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Change Password
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="rounded-lg border bg-destructive/5 p-3">
|
||||
<p className="text-sm font-medium text-destructive">Danger Zone</p>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
Account deletion is not available. Contact an administrator for assistance.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Studies Access */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Building className="h-5 w-5 text-primary" />
|
||||
Studies Access
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Studies you have access to
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{userStudies?.studies.slice(0, 5).map((study) => (
|
||||
<Link
|
||||
key={study.id}
|
||||
href={`/studies/${study.id}`}
|
||||
className="hover:bg-accent/50 flex items-center justify-between rounded-md border p-3 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
|
||||
<span className="text-xs font-medium text-primary">
|
||||
{(study.name ?? "S").charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{study.name}</p>
|
||||
<p className="text-muted-foreground text-xs capitalize">
|
||||
{getMemberRole(studyMemberships, study.id)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
</Link>
|
||||
))}
|
||||
{(!userStudies?.studies.length) && (
|
||||
<div className="flex flex-col items-center justify-center py-4 text-center">
|
||||
<Building className="text-muted-foreground/50 mb-2 h-8 w-8" />
|
||||
<p className="text-sm">No studies yet</p>
|
||||
<Button variant="link" size="sm" asChild className="mt-1">
|
||||
<Link href="/studies/new">Create a study</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{userStudies && userStudies.studies.length > 5 && (
|
||||
<Button variant="ghost" size="sm" asChild className="w-full">
|
||||
<Link href="/studies">
|
||||
View all {userStudies.studies.length} studies <ChevronRight className="ml-1 h-3 w-3" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Data & Privacy */}
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 border-b pb-2">
|
||||
<Download className="text-primary h-5 w-5" />
|
||||
<h3 className="text-lg font-semibold">Data & Privacy</h3>
|
||||
</div>
|
||||
|
||||
<Card className="border-destructive/10 bg-destructive/5 overflow-hidden">
|
||||
<CardContent className="space-y-4 pt-6">
|
||||
<div>
|
||||
<h4 className="mb-1 text-sm font-semibold">Export Data</h4>
|
||||
<p className="text-muted-foreground mb-3 text-xs">
|
||||
Download a copy of your personal data.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="bg-background w-full"
|
||||
disabled
|
||||
>
|
||||
<Download className="mr-2 h-3 w-3" />
|
||||
Download Archive
|
||||
</Button>
|
||||
</div>
|
||||
<Separator className="bg-destructive/10" />
|
||||
<div>
|
||||
<h4 className="text-destructive mb-1 text-sm font-semibold">
|
||||
Delete Account
|
||||
</h4>
|
||||
<p className="text-muted-foreground mb-3 text-xs">
|
||||
This action is irreversible.
|
||||
</p>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
disabled
|
||||
>
|
||||
<Trash2 className="mr-2 h-3 w-3" />
|
||||
Delete Account
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -206,22 +414,11 @@ function ProfileContent({ user }: { user: ProfileUser }) {
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { data: session, isPending } = useSession();
|
||||
const { data: userData, isPending: isUserPending } = api.auth.me.useQuery(
|
||||
undefined,
|
||||
{
|
||||
enabled: !!session?.user,
|
||||
},
|
||||
);
|
||||
|
||||
useBreadcrumbsEffect([
|
||||
{ label: "Dashboard", href: "/dashboard" },
|
||||
{ label: "Profile" },
|
||||
]);
|
||||
|
||||
if (isPending || isUserPending) {
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="text-muted-foreground animate-pulse p-8">
|
||||
Loading profile...
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="text-muted-foreground h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -230,13 +427,5 @@ export default function ProfilePage() {
|
||||
redirect("/auth/signin");
|
||||
}
|
||||
|
||||
const user: ProfileUser = {
|
||||
id: session.user.id,
|
||||
name: userData?.name ?? session.user.name ?? null,
|
||||
email: userData?.email ?? session.user.email,
|
||||
image: userData?.image ?? session.user.image ?? null,
|
||||
roles: userData?.systemRoles as ProfileUser["roles"],
|
||||
};
|
||||
|
||||
return <ProfileContent user={user} />;
|
||||
return <ProfilePageContent />;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ import type {
|
||||
} from "~/lib/experiment-designer/types";
|
||||
import { api } from "~/trpc/server";
|
||||
import { DesignerPageClient } from "./DesignerPageClient";
|
||||
import { db } from "~/server/db";
|
||||
import { studyPlugins, plugins } from "~/server/db/schema";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
|
||||
interface ExperimentDesignerPageProps {
|
||||
params: Promise<{
|
||||
@@ -74,10 +77,20 @@ export default async function ExperimentDesignerPage({
|
||||
actionDefinitions: Array<{ id: string }> | null;
|
||||
};
|
||||
};
|
||||
const rawInstalledPluginsUnknown: unknown =
|
||||
await api.robots.plugins.getStudyPlugins({
|
||||
studyId: experiment.study.id,
|
||||
});
|
||||
const installedPluginsResult = await db
|
||||
.select({
|
||||
plugin: {
|
||||
id: plugins.id,
|
||||
name: plugins.name,
|
||||
version: plugins.version,
|
||||
actionDefinitions: plugins.actionDefinitions,
|
||||
},
|
||||
})
|
||||
.from(studyPlugins)
|
||||
.innerJoin(plugins, eq(studyPlugins.pluginId, plugins.id))
|
||||
.where(eq(studyPlugins.studyId, experiment.study.id))
|
||||
.orderBy(desc(studyPlugins.installedAt));
|
||||
const rawInstalledPluginsUnknown = installedPluginsResult;
|
||||
|
||||
function asRecord(v: unknown): Record<string, unknown> | null {
|
||||
return v && typeof v === "object"
|
||||
|
||||
@@ -31,6 +31,8 @@ export default function StudyExperimentsPage() {
|
||||
}
|
||||
}, [studyId, selectedStudyId, setSelectedStudyId]);
|
||||
|
||||
const canManage = study?.userRole === "owner" || study?.userRole === "researcher";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
@@ -38,12 +40,14 @@ export default function StudyExperimentsPage() {
|
||||
description="Design and manage experiment protocols for this study"
|
||||
icon={FlaskConical}
|
||||
actions={
|
||||
canManage ? (
|
||||
<Button asChild>
|
||||
<a href={`/studies/${studyId}/experiments/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Experiment
|
||||
</a>
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
506
src/app/(dashboard)/studies/[id]/forms/[formId]/page.tsx
Normal file
506
src/app/(dashboard)/studies/[id]/forms/[formId]/page.tsx
Normal file
@@ -0,0 +1,506 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
FileText,
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Trash2,
|
||||
GripVertical,
|
||||
FileSignature,
|
||||
ClipboardList,
|
||||
FileQuestion,
|
||||
Save,
|
||||
Eye,
|
||||
Edit2,
|
||||
Users,
|
||||
CheckCircle,
|
||||
} from "lucide-react";
|
||||
import { useBreadcrumbsEffect } from "~/components/ui/breadcrumb-provider";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Field {
|
||||
id: string;
|
||||
type: string;
|
||||
label: string;
|
||||
required: boolean;
|
||||
options?: string[];
|
||||
settings?: Record<string, any>;
|
||||
}
|
||||
|
||||
const fieldTypes = [
|
||||
{ value: "text", label: "Text (short)", icon: "📝" },
|
||||
{ value: "textarea", label: "Text (long)", icon: "📄" },
|
||||
{ value: "multiple_choice", label: "Multiple Choice", icon: "☑️" },
|
||||
{ value: "checkbox", label: "Checkbox", icon: "✅" },
|
||||
{ value: "rating", label: "Rating Scale", icon: "⭐" },
|
||||
{ value: "yes_no", label: "Yes/No", icon: "✔️" },
|
||||
{ value: "date", label: "Date", icon: "📅" },
|
||||
{ value: "signature", label: "Signature", icon: "✍️" },
|
||||
];
|
||||
|
||||
const formTypeIcons = {
|
||||
consent: FileSignature,
|
||||
survey: ClipboardList,
|
||||
questionnaire: FileQuestion,
|
||||
};
|
||||
|
||||
const statusColors = {
|
||||
pending: "bg-yellow-100 text-yellow-700",
|
||||
completed: "bg-green-100 text-green-700",
|
||||
rejected: "bg-red-100 text-red-700",
|
||||
};
|
||||
|
||||
interface FormViewPageProps {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
formId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function FormViewPage({ params }: FormViewPageProps) {
|
||||
const { data: session } = useSession();
|
||||
const router = useRouter();
|
||||
const utils = api.useUtils();
|
||||
const [resolvedParams, setResolvedParams] = useState<{ id: string; formId: string } | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [fields, setFields] = useState<Field[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const resolveParams = async () => {
|
||||
const resolved = await params;
|
||||
setResolvedParams(resolved);
|
||||
};
|
||||
void resolveParams();
|
||||
}, [params]);
|
||||
|
||||
const { data: study } = api.studies.get.useQuery(
|
||||
{ id: resolvedParams?.id ?? "" },
|
||||
{ enabled: !!resolvedParams?.id },
|
||||
);
|
||||
|
||||
const { data: form, isLoading } = api.forms.get.useQuery(
|
||||
{ id: resolvedParams?.formId ?? "" },
|
||||
{ enabled: !!resolvedParams?.formId },
|
||||
);
|
||||
|
||||
const { data: responsesData } = api.forms.getResponses.useQuery(
|
||||
{ formId: resolvedParams?.formId ?? "", limit: 50 },
|
||||
{ enabled: !!resolvedParams?.formId },
|
||||
);
|
||||
|
||||
const userRole = (study as any)?.userRole;
|
||||
const canManage = userRole === "owner" || userRole === "researcher";
|
||||
|
||||
const updateForm = api.forms.update.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Form updated successfully!");
|
||||
setIsEditing(false);
|
||||
void utils.forms.get.invalidate({ id: resolvedParams?.formId });
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to update form", { description: error.message });
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (form) {
|
||||
setTitle(form.title);
|
||||
setDescription(form.description || "");
|
||||
setFields((form.fields as Field[]) || []);
|
||||
}
|
||||
}, [form]);
|
||||
|
||||
useBreadcrumbsEffect([
|
||||
{ label: "Dashboard", href: "/dashboard" },
|
||||
{ label: "Studies", href: "/studies" },
|
||||
{ label: study?.name ?? "Study", href: `/studies/${resolvedParams?.id}` },
|
||||
{ label: "Forms", href: `/studies/${resolvedParams?.id}/forms` },
|
||||
{ label: form?.title ?? "Form" },
|
||||
]);
|
||||
|
||||
if (!session?.user) {
|
||||
return notFound();
|
||||
}
|
||||
|
||||
if (isLoading || !form) return <div>Loading...</div>;
|
||||
|
||||
const TypeIcon = formTypeIcons[form.type as keyof typeof formTypeIcons] || FileText;
|
||||
const responses = responsesData?.responses ?? [];
|
||||
|
||||
const addField = (type: string) => {
|
||||
const newField: Field = {
|
||||
id: crypto.randomUUID(),
|
||||
type,
|
||||
label: `New ${fieldTypes.find(f => f.value === type)?.label || "Field"}`,
|
||||
required: false,
|
||||
options: type === "multiple_choice" ? ["Option 1", "Option 2"] : undefined,
|
||||
};
|
||||
setFields([...fields, newField]);
|
||||
};
|
||||
|
||||
const removeField = (id: string) => {
|
||||
setFields(fields.filter(f => f.id !== id));
|
||||
};
|
||||
|
||||
const updateField = (id: string, updates: Partial<Field>) => {
|
||||
setFields(fields.map(f => f.id === id ? { ...f, ...updates } : f));
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
updateForm.mutate({
|
||||
id: form.id,
|
||||
title,
|
||||
description,
|
||||
fields,
|
||||
settings: form.settings as Record<string, any>,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/studies/${resolvedParams?.id}/forms`}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back
|
||||
</Link>
|
||||
</Button>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<TypeIcon className="h-5 w-5 text-muted-foreground" />
|
||||
<h1 className="text-2xl font-bold">{form.title}</h1>
|
||||
{form.active && (
|
||||
<Badge variant="default" className="text-xs">Active</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm capitalize">
|
||||
{form.type} • Version {form.version}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{canManage && (
|
||||
<div className="flex gap-2">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsEditing(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={updateForm.isPending}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
Save Changes
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={() => setIsEditing(true)}>
|
||||
<Edit2 className="mr-2 h-4 w-4" />
|
||||
Edit Form
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="fields" className="space-y-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="fields">Fields</TabsTrigger>
|
||||
<TabsTrigger value="preview">Preview</TabsTrigger>
|
||||
<TabsTrigger value="responses">
|
||||
Responses ({responses.length})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="fields">
|
||||
{isEditing ? (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle>Form Fields</CardTitle>
|
||||
<Select onValueChange={addField}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Add field..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{fieldTypes.map((type) => (
|
||||
<SelectItem key={type.value} value={type.value}>
|
||||
<span className="mr-2">{type.icon}</span>
|
||||
{type.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{fields.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
|
||||
<FileText className="mb-2 h-8 w-8" />
|
||||
<p>No fields added yet</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{fields.map((field) => (
|
||||
<div
|
||||
key={field.id}
|
||||
className="flex items-start gap-3 rounded-lg border p-4"
|
||||
>
|
||||
<div className="flex cursor-grab items-center text-muted-foreground">
|
||||
<GripVertical className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{fieldTypes.find(f => f.value === field.type)?.icon}{" "}
|
||||
{fieldTypes.find(f => f.value === field.type)?.label}
|
||||
</Badge>
|
||||
<Input
|
||||
value={field.label}
|
||||
onChange={(e) => updateField(field.id, { label: e.target.value })}
|
||||
placeholder="Field label"
|
||||
className="flex-1"
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={field.required}
|
||||
onChange={(e) => updateField(field.id, { required: e.target.checked })}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
Required
|
||||
</label>
|
||||
</div>
|
||||
{field.type === "multiple_choice" && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Options</Label>
|
||||
{field.options?.map((opt, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={opt}
|
||||
onChange={(e) => {
|
||||
const newOptions = [...(field.options || [])];
|
||||
newOptions[i] = e.target.value;
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
placeholder={`Option ${i + 1}`}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
const newOptions = field.options?.filter((_, idx) => idx !== i);
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const newOptions = [...(field.options || []), `Option ${(field.options?.length || 0) + 1}`];
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
Add Option
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeField(field.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Form Fields</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{fields.length === 0 ? (
|
||||
<p className="text-muted-foreground">No fields defined</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="flex items-center gap-3 rounded-lg border p-3">
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs">
|
||||
{index + 1}
|
||||
</span>
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">{field.label}</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{fieldTypes.find(f => f.value === field.type)?.label}
|
||||
{field.required && " • Required"}
|
||||
{field.type === "multiple_choice" && ` • ${field.options?.length} options`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="preview">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Form Preview</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">{title}</h2>
|
||||
{description && <p className="text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
{fields.length === 0 ? (
|
||||
<p className="text-muted-foreground">No fields to preview</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="space-y-2">
|
||||
<Label>
|
||||
{index + 1}. {field.label}
|
||||
{field.required && <span className="text-destructive"> *</span>}
|
||||
</Label>
|
||||
{field.type === "text" && (
|
||||
<Input placeholder="Enter your response..." disabled />
|
||||
)}
|
||||
{field.type === "textarea" && (
|
||||
<Textarea placeholder="Enter your response..." disabled />
|
||||
)}
|
||||
{field.type === "multiple_choice" && (
|
||||
<div className="space-y-2">
|
||||
{field.options?.map((opt, i) => (
|
||||
<label key={i} className="flex items-center gap-2">
|
||||
<input type="radio" disabled /> {opt}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{field.type === "checkbox" && (
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" disabled /> Yes
|
||||
</label>
|
||||
)}
|
||||
{field.type === "yes_no" && (
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" disabled /> Yes
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" disabled /> No
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{field.type === "rating" && (
|
||||
<div className="flex gap-2">
|
||||
{Array.from({ length: field.settings?.scale || 5 }, (_, i) => (
|
||||
<button key={i} type="button" className="h-8 w-8 rounded border disabled" disabled>
|
||||
{i + 1}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{field.type === "date" && (
|
||||
<Input type="date" disabled />
|
||||
)}
|
||||
{field.type === "signature" && (
|
||||
<div className="h-24 rounded border bg-muted/50 flex items-center justify-center text-muted-foreground">
|
||||
Signature pad (disabled in preview)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="responses">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Form Responses</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{responses.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
|
||||
<Users className="mb-2 h-8 w-8" />
|
||||
<p>No responses yet</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{responses.map((response) => (
|
||||
<div key={response.id} className="rounded-lg border p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">
|
||||
{response.participant?.name || response.participant?.participantCode || "Unknown"}
|
||||
</span>
|
||||
</div>
|
||||
<Badge className={`text-xs ${statusColors[response.status as keyof typeof statusColors]}`}>
|
||||
{response.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
{Object.entries(response.responses as Record<string, any>).map(([key, value]) => (
|
||||
<div key={key} className="flex gap-2">
|
||||
<span className="text-muted-foreground">{key}:</span>
|
||||
<span>{String(value)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{response.signedAt && (
|
||||
<div className="mt-2 pt-2 border-t text-xs text-muted-foreground">
|
||||
Signed: {new Date(response.signedAt).toLocaleString()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
410
src/app/(dashboard)/studies/[id]/forms/new/page.tsx
Normal file
410
src/app/(dashboard)/studies/[id]/forms/new/page.tsx
Normal file
@@ -0,0 +1,410 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
FileText,
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Trash2,
|
||||
GripVertical,
|
||||
FileSignature,
|
||||
ClipboardList,
|
||||
FileQuestion,
|
||||
Save,
|
||||
Copy,
|
||||
LayoutTemplate,
|
||||
} from "lucide-react";
|
||||
import { useBreadcrumbsEffect } from "~/components/ui/breadcrumb-provider";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Field {
|
||||
id: string;
|
||||
type: string;
|
||||
label: string;
|
||||
required: boolean;
|
||||
options?: string[];
|
||||
settings?: Record<string, any>;
|
||||
}
|
||||
|
||||
const fieldTypes = [
|
||||
{ value: "text", label: "Text (short)", icon: "📝" },
|
||||
{ value: "textarea", label: "Text (long)", icon: "📄" },
|
||||
{ value: "multiple_choice", label: "Multiple Choice", icon: "☑️" },
|
||||
{ value: "checkbox", label: "Checkbox", icon: "✅" },
|
||||
{ value: "rating", label: "Rating Scale", icon: "⭐" },
|
||||
{ value: "yes_no", label: "Yes/No", icon: "✔️" },
|
||||
{ value: "date", label: "Date", icon: "📅" },
|
||||
{ value: "signature", label: "Signature", icon: "✍️" },
|
||||
];
|
||||
|
||||
const formTypes = [
|
||||
{ value: "consent", label: "Consent Form", icon: FileSignature, description: "Legal/IRB consent documents" },
|
||||
{ value: "survey", label: "Survey", icon: ClipboardList, description: "Multi-question questionnaires" },
|
||||
{ value: "questionnaire", label: "Questionnaire", icon: FileQuestion, description: "Custom data collection forms" },
|
||||
];
|
||||
|
||||
export default function NewFormPage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const { data: session } = useSession();
|
||||
const utils = api.useUtils();
|
||||
|
||||
const studyId = typeof params.id === "string" ? params.id : "";
|
||||
|
||||
const [formType, setFormType] = useState<string>("");
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [fields, setFields] = useState<Field[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const { data: study } = api.studies.get.useQuery(
|
||||
{ id: studyId },
|
||||
{ enabled: !!studyId },
|
||||
);
|
||||
|
||||
const { data: templates } = api.forms.listTemplates.useQuery();
|
||||
|
||||
const createFromTemplate = api.forms.createFromTemplate.useMutation({
|
||||
onSuccess: (data) => {
|
||||
toast.success("Form created from template!");
|
||||
router.push(`/studies/${studyId}/forms/${data.id}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to create from template", { description: error.message });
|
||||
},
|
||||
});
|
||||
|
||||
const createForm = api.forms.create.useMutation({
|
||||
onSuccess: (data) => {
|
||||
toast.success("Form created successfully!");
|
||||
router.push(`/studies/${studyId}/forms/${data.id}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to create form", { description: error.message });
|
||||
setIsSubmitting(false);
|
||||
},
|
||||
});
|
||||
|
||||
useBreadcrumbsEffect([
|
||||
{ label: "Dashboard", href: "/dashboard" },
|
||||
{ label: "Studies", href: "/studies" },
|
||||
{ label: study?.name ?? "Study", href: `/studies/${studyId}` },
|
||||
{ label: "Forms", href: `/studies/${studyId}/forms` },
|
||||
{ label: "Create Form" },
|
||||
]);
|
||||
|
||||
if (!session?.user) {
|
||||
return notFound();
|
||||
}
|
||||
|
||||
const addField = (type: string) => {
|
||||
const newField: Field = {
|
||||
id: crypto.randomUUID(),
|
||||
type,
|
||||
label: `New ${fieldTypes.find(f => f.value === type)?.label || "Field"}`,
|
||||
required: false,
|
||||
options: type === "multiple_choice" ? ["Option 1", "Option 2"] : undefined,
|
||||
};
|
||||
setFields([...fields, newField]);
|
||||
};
|
||||
|
||||
const removeField = (id: string) => {
|
||||
setFields(fields.filter(f => f.id !== id));
|
||||
};
|
||||
|
||||
const updateField = (id: string, updates: Partial<Field>) => {
|
||||
setFields(fields.map(f => f.id === id ? { ...f, ...updates } : f));
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formType || !title) {
|
||||
toast.error("Please select a form type and enter a title");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
createForm.mutate({
|
||||
studyId,
|
||||
type: formType as "consent" | "survey" | "questionnaire",
|
||||
title,
|
||||
description,
|
||||
fields,
|
||||
settings: {},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href={`/studies/${studyId}/forms`}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Create New Form</h1>
|
||||
<p className="text-muted-foreground">Design a consent form, survey, or questionnaire</p>
|
||||
</div>
|
||||
|
||||
{templates && templates.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<LayoutTemplate className="h-5 w-5" />
|
||||
Start from Template
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{templates.map((template) => {
|
||||
const TypeIcon = formTypes.find(t => t.value === template.type)?.icon || FileText;
|
||||
return (
|
||||
<button
|
||||
key={template.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
createFromTemplate.mutate({
|
||||
studyId,
|
||||
templateId: template.id,
|
||||
});
|
||||
}}
|
||||
disabled={createFromTemplate.isPending}
|
||||
className="flex flex-col items-start rounded-lg border p-4 text-left transition-all hover:bg-muted/50 disabled:opacity-50"
|
||||
>
|
||||
<TypeIcon className="mb-2 h-5 w-5 text-muted-foreground" />
|
||||
<span className="font-medium">{template.templateName}</span>
|
||||
<span className="text-muted-foreground text-xs capitalize">{template.type}</span>
|
||||
<span className="text-muted-foreground text-xs mt-1 line-clamp-2">
|
||||
{template.description}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-4 text-center text-sm text-muted-foreground">
|
||||
Or design from scratch below
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Form Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Form Type</Label>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{formTypes.map((type) => (
|
||||
<button
|
||||
key={type.value}
|
||||
type="button"
|
||||
onClick={() => setFormType(type.value)}
|
||||
className={`flex flex-col items-start rounded-lg border p-4 text-left transition-all hover:bg-muted/50 ${
|
||||
formType === type.value
|
||||
? "border-primary bg-primary/5 ring-1 ring-primary"
|
||||
: "border-border"
|
||||
}`}
|
||||
>
|
||||
<type.icon className={`mb-2 h-5 w-5 ${formType === type.value ? "text-primary" : "text-muted-foreground"}`} />
|
||||
<span className="font-medium">{type.label}</span>
|
||||
<span className="text-muted-foreground text-xs">{type.description}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title">Title</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Enter form title"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description (optional)</Label>
|
||||
<Input
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Brief description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle>Form Fields</CardTitle>
|
||||
<Select onValueChange={addField}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Add field..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{fieldTypes.map((type) => (
|
||||
<SelectItem key={type.value} value={type.value}>
|
||||
<span className="mr-2">{type.icon}</span>
|
||||
{type.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{fields.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center text-muted-foreground">
|
||||
<FileText className="mb-2 h-8 w-8" />
|
||||
<p>No fields added yet</p>
|
||||
<p className="text-sm">Use the dropdown above to add fields</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{fields.map((field, index) => (
|
||||
<div
|
||||
key={field.id}
|
||||
className="flex items-start gap-3 rounded-lg border p-4"
|
||||
>
|
||||
<div className="flex cursor-grab items-center text-muted-foreground">
|
||||
<GripVertical className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{fieldTypes.find(f => f.value === field.type)?.icon}{" "}
|
||||
{fieldTypes.find(f => f.value === field.type)?.label}
|
||||
</Badge>
|
||||
<Input
|
||||
value={field.label}
|
||||
onChange={(e) => updateField(field.id, { label: e.target.value })}
|
||||
placeholder="Field label"
|
||||
className="flex-1"
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={field.required}
|
||||
onChange={(e) => updateField(field.id, { required: e.target.checked })}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
Required
|
||||
</label>
|
||||
</div>
|
||||
{field.type === "multiple_choice" && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Options</Label>
|
||||
{field.options?.map((opt, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={opt}
|
||||
onChange={(e) => {
|
||||
const newOptions = [...(field.options || [])];
|
||||
newOptions[i] = e.target.value;
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
placeholder={`Option ${i + 1}`}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
const newOptions = field.options?.filter((_, idx) => idx !== i);
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const newOptions = [...(field.options || []), `Option ${(field.options?.length || 0) + 1}`];
|
||||
updateField(field.id, { options: newOptions });
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
Add Option
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{field.type === "rating" && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>Scale:</span>
|
||||
<Select
|
||||
value={field.settings?.scale?.toString() || "5"}
|
||||
onValueChange={(val) => updateField(field.id, { settings: { scale: parseInt(val) } })}
|
||||
>
|
||||
<SelectTrigger className="w-[100px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">1-5</SelectItem>
|
||||
<SelectItem value="7">1-7</SelectItem>
|
||||
<SelectItem value="10">1-10</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeField(field.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/studies/${studyId}/forms`}>Cancel</Link>
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting || !formType || !title}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{isSubmitting ? "Creating..." : "Create Form"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,131 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
FileText,
|
||||
Loader2,
|
||||
Plus,
|
||||
Download,
|
||||
Edit2,
|
||||
Search,
|
||||
ClipboardList,
|
||||
FileQuestion,
|
||||
FileSignature,
|
||||
MoreHorizontal,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Eye,
|
||||
Save,
|
||||
CheckCircle,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
EntityView,
|
||||
EntityViewHeader,
|
||||
EntityViewSection,
|
||||
EmptyState,
|
||||
} from "~/components/ui/entity-view";
|
||||
import { useBreadcrumbsEffect } from "~/components/ui/breadcrumb-provider";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
import { PageHeader } from "~/components/ui/page-header";
|
||||
import { useEditor, EditorContent } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import { Markdown } from "tiptap-markdown";
|
||||
import { Table } from "@tiptap/extension-table";
|
||||
import { TableRow } from "@tiptap/extension-table-row";
|
||||
import { TableCell } from "@tiptap/extension-table-cell";
|
||||
import { TableHeader } from "@tiptap/extension-table-header";
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
List,
|
||||
ListOrdered,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Quote,
|
||||
Table as TableIcon,
|
||||
} from "lucide-react";
|
||||
import { downloadPdfFromHtml } from "~/lib/pdf-generator";
|
||||
|
||||
const Toolbar = ({ editor }: { editor: any }) => {
|
||||
if (!editor) {
|
||||
return null;
|
||||
}
|
||||
const formTypeIcons = {
|
||||
consent: FileSignature,
|
||||
survey: ClipboardList,
|
||||
questionnaire: FileQuestion,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-input flex flex-wrap items-center gap-1 rounded-tl-md rounded-tr-md border bg-transparent p-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleBold().run()}
|
||||
disabled={!editor.can().chain().focus().toggleBold().run()}
|
||||
className={editor.isActive("bold") ? "bg-muted" : ""}
|
||||
>
|
||||
<Bold className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleItalic().run()}
|
||||
disabled={!editor.can().chain().focus().toggleItalic().run()}
|
||||
className={editor.isActive("italic") ? "bg-muted" : ""}
|
||||
>
|
||||
<Italic className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="bg-border mx-1 h-6 w-[1px]" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
|
||||
className={editor.isActive("heading", { level: 1 }) ? "bg-muted" : ""}
|
||||
>
|
||||
<Heading1 className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
|
||||
className={editor.isActive("heading", { level: 2 }) ? "bg-muted" : ""}
|
||||
>
|
||||
<Heading2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="bg-border mx-1 h-6 w-[1px]" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleBulletList().run()}
|
||||
className={editor.isActive("bulletList") ? "bg-muted" : ""}
|
||||
>
|
||||
<List className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleOrderedList().run()}
|
||||
className={editor.isActive("orderedList") ? "bg-muted" : ""}
|
||||
>
|
||||
<ListOrdered className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => editor.chain().focus().toggleBlockquote().run()}
|
||||
className={editor.isActive("blockquote") ? "bg-muted" : ""}
|
||||
>
|
||||
<Quote className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="bg-border mx-1 h-6 w-[1px]" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
|
||||
.run()
|
||||
}
|
||||
>
|
||||
<TableIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
const formTypeColors = {
|
||||
consent: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
|
||||
survey: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
|
||||
questionnaire: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400",
|
||||
};
|
||||
|
||||
interface StudyFormsPageProps {
|
||||
@@ -136,11 +53,10 @@ interface StudyFormsPageProps {
|
||||
|
||||
export default function StudyFormsPage({ params }: StudyFormsPageProps) {
|
||||
const { data: session } = useSession();
|
||||
const router = useRouter();
|
||||
const utils = api.useUtils();
|
||||
const [resolvedParams, setResolvedParams] = useState<{ id: string } | null>(
|
||||
null,
|
||||
);
|
||||
const [editorTarget, setEditorTarget] = useState<string>("");
|
||||
const [resolvedParams, setResolvedParams] = useState<{ id: string } | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const resolveParams = async () => {
|
||||
@@ -155,91 +71,33 @@ export default function StudyFormsPage({ params }: StudyFormsPageProps) {
|
||||
{ enabled: !!resolvedParams?.id },
|
||||
);
|
||||
|
||||
const { data: activeConsentForm, refetch: refetchConsentForm } =
|
||||
api.studies.getActiveConsentForm.useQuery(
|
||||
{ studyId: resolvedParams?.id ?? "" },
|
||||
const { data: formsData, isLoading } = api.forms.list.useQuery(
|
||||
{ studyId: resolvedParams?.id ?? "", search: search || undefined },
|
||||
{ enabled: !!resolvedParams?.id },
|
||||
);
|
||||
|
||||
// Only sync once when form loads to avoid resetting user edits
|
||||
useEffect(() => {
|
||||
if (activeConsentForm && !editorTarget) {
|
||||
setEditorTarget(activeConsentForm.content);
|
||||
}
|
||||
}, [activeConsentForm, editorTarget]);
|
||||
const userRole = (study as any)?.userRole;
|
||||
const canManage = userRole === "owner" || userRole === "researcher";
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Table.configure({
|
||||
resizable: true,
|
||||
}),
|
||||
TableRow,
|
||||
TableHeader,
|
||||
TableCell,
|
||||
Markdown.configure({
|
||||
transformPastedText: true,
|
||||
}),
|
||||
],
|
||||
content: editorTarget || "",
|
||||
immediatelyRender: false,
|
||||
onUpdate: ({ editor }) => {
|
||||
// @ts-ignore
|
||||
setEditorTarget(editor.storage.markdown.getMarkdown());
|
||||
},
|
||||
});
|
||||
|
||||
// Sync Tiptap when editorTarget is set (e.g., from DB) but make sure not to overwrite active edits
|
||||
useEffect(() => {
|
||||
if (editor && editorTarget && editor.isEmpty) {
|
||||
editor.commands.setContent(editorTarget);
|
||||
}
|
||||
}, [editorTarget, editor]);
|
||||
|
||||
const generateConsentMutation = api.studies.generateConsentForm.useMutation({
|
||||
onSuccess: (data) => {
|
||||
toast.success("Default Consent Form Generated!");
|
||||
setEditorTarget(data.content);
|
||||
editor?.commands.setContent(data.content);
|
||||
void refetchConsentForm();
|
||||
void utils.studies.getActivity.invalidate({
|
||||
studyId: resolvedParams?.id ?? "",
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Error generating consent form", {
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const updateConsentMutation = api.studies.updateConsentForm.useMutation({
|
||||
const deleteMutation = api.forms.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Consent Form Saved Successfully!");
|
||||
void refetchConsentForm();
|
||||
void utils.studies.getActivity.invalidate({
|
||||
studyId: resolvedParams?.id ?? "",
|
||||
});
|
||||
toast.success("Form deleted successfully");
|
||||
void utils.forms.list.invalidate({ studyId: resolvedParams?.id });
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Error saving consent form", { description: error.message });
|
||||
toast.error("Failed to delete form", { description: error.message });
|
||||
},
|
||||
});
|
||||
|
||||
const handleDownloadConsent = async () => {
|
||||
if (!activeConsentForm || !study || !editor) return;
|
||||
|
||||
try {
|
||||
toast.loading("Generating Document...", { id: "pdf-gen" });
|
||||
await downloadPdfFromHtml(editor.getHTML(), {
|
||||
filename: `Consent_Form_${study.name.replace(/\s+/g, "_")}_v${activeConsentForm.version}.pdf`,
|
||||
const setActiveMutation = api.forms.setActive.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Form set as active");
|
||||
void utils.forms.list.invalidate({ studyId: resolvedParams?.id });
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to set active", { description: error.message });
|
||||
},
|
||||
});
|
||||
toast.success("Document Downloaded Successfully!", { id: "pdf-gen" });
|
||||
} catch (error) {
|
||||
toast.error("Error generating PDF", { id: "pdf-gen" });
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
useBreadcrumbsEffect([
|
||||
{ label: "Dashboard", href: "/dashboard" },
|
||||
@@ -254,116 +112,145 @@ export default function StudyFormsPage({ params }: StudyFormsPageProps) {
|
||||
|
||||
if (!study) return <div>Loading...</div>;
|
||||
|
||||
const forms = formsData?.forms ?? [];
|
||||
|
||||
return (
|
||||
<EntityView>
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="Study Forms"
|
||||
description="Manage consent forms and future questionnaires for this study"
|
||||
title="Forms"
|
||||
description="Manage consent forms, surveys, and questionnaires for this study"
|
||||
icon={FileText}
|
||||
actions={
|
||||
canManage && (
|
||||
<Button asChild>
|
||||
<Link href={`/studies/${resolvedParams?.id}/forms/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Form
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-8">
|
||||
<EntityViewSection
|
||||
title="Consent Document"
|
||||
icon="FileText"
|
||||
description="Design and manage the consent form that participants must sign before participating in your trials."
|
||||
actions={
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
generateConsentMutation.mutate({ studyId: study.id })
|
||||
}
|
||||
disabled={
|
||||
generateConsentMutation.isPending ||
|
||||
updateConsentMutation.isPending
|
||||
}
|
||||
>
|
||||
{generateConsentMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
{forms.length === 0 && !isLoading ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<FileText className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Forms Yet</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Create consent forms, surveys, or questionnaires to collect data from participants
|
||||
</p>
|
||||
{canManage && (
|
||||
<Button asChild>
|
||||
<Link href={`/studies/${resolvedParams?.id}/forms/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Generate Default Template
|
||||
Create Your First Form
|
||||
</Link>
|
||||
</Button>
|
||||
{activeConsentForm && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
updateConsentMutation.mutate({
|
||||
studyId: study.id,
|
||||
content: editorTarget,
|
||||
})
|
||||
}
|
||||
disabled={
|
||||
updateConsentMutation.isPending ||
|
||||
editorTarget === activeConsentForm.content
|
||||
}
|
||||
>
|
||||
{updateConsentMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save Changes
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{activeConsentForm ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm leading-none font-medium">
|
||||
{activeConsentForm.title}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
v{activeConsentForm.version} • Status: Active
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search forms..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{forms.map((form) => {
|
||||
const TypeIcon = formTypeIcons[form.type as keyof typeof formTypeIcons] || FileText;
|
||||
const typeColor = formTypeColors[form.type as keyof typeof formTypeColors] || "bg-gray-100";
|
||||
const isActive = form.active;
|
||||
|
||||
return (
|
||||
<Card key={form.id} className="overflow-hidden">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`rounded-md p-2 ${typeColor}`}>
|
||||
<TypeIcon className="h-4 w-4" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base">{form.title}</CardTitle>
|
||||
<p className="text-muted-foreground text-xs capitalize">
|
||||
{form.type}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleDownloadConsent}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download PDF
|
||||
</Button>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-green-50 text-green-700 hover:bg-green-50"
|
||||
>
|
||||
</div>
|
||||
{isActive && (
|
||||
<Badge variant="default" className="text-xs">
|
||||
Active
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/30 border-border flex w-full justify-center overflow-hidden rounded-md border p-8">
|
||||
<div className="dark:bg-card ring-border flex w-full max-w-4xl flex-col rounded-sm bg-white shadow-xl ring-1">
|
||||
<div className="border-border bg-muted/50 dark:bg-muted/10 border-b">
|
||||
<Toolbar editor={editor} />
|
||||
</div>
|
||||
<div className="editor-container dark:bg-card min-h-[850px] bg-white px-16 py-20 text-sm">
|
||||
<EditorContent
|
||||
editor={editor}
|
||||
className="prose prose-sm dark:prose-invert h-full max-w-none outline-none focus:outline-none focus-visible:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon="FileText"
|
||||
title="No Consent Form"
|
||||
description="Generate a boilerplate consent form for this study to download and collect signatures."
|
||||
/>
|
||||
)}
|
||||
</EntityViewSection>
|
||||
</div>
|
||||
</EntityView>
|
||||
</CardHeader>
|
||||
<CardContent className="pb-3">
|
||||
{form.description && (
|
||||
<p className="text-muted-foreground text-sm line-clamp-2 mb-3">
|
||||
{form.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>v{form.version}</span>
|
||||
<span>{(form as any)._count?.responses ?? 0} responses</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
<div className="flex items-center justify-between border-t bg-muted/30 px-4 py-2">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link href={`/studies/${resolvedParams?.id}/forms/${form.id}`}>
|
||||
<Eye className="mr-1 h-3 w-3" />
|
||||
View
|
||||
</Link>
|
||||
</Button>
|
||||
{canManage && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/studies/${resolvedParams?.id}/forms/${form.id}/edit`}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
{!isActive && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setActiveMutation.mutate({ id: form.id })}
|
||||
>
|
||||
<CheckCircle className="mr-2 h-4 w-4" />
|
||||
Set Active
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (confirm("Are you sure you want to delete this form?")) {
|
||||
deleteMutation.mutate({ id: form.id });
|
||||
}
|
||||
}}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { PageHeader } from "~/components/ui/page-header";
|
||||
import { useBreadcrumbsEffect } from "~/components/ui/breadcrumb-provider";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { api } from "~/trpc/react";
|
||||
import { AddMemberDialog } from "~/components/studies/add-member-dialog";
|
||||
|
||||
interface StudyDetailPageProps {
|
||||
params: Promise<{
|
||||
@@ -59,6 +60,7 @@ type Study = {
|
||||
irbProtocol: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
userRole?: string;
|
||||
};
|
||||
|
||||
type Member = {
|
||||
@@ -156,6 +158,10 @@ export default function StudyDetailPage({ params }: StudyDetailPageProps) {
|
||||
).length;
|
||||
const totalTrials = trials.length;
|
||||
|
||||
const userRole = (studyData as any)?.userRole;
|
||||
const canManage = userRole === "owner" || userRole === "researcher";
|
||||
const canRunTrials = userRole === "owner" || userRole === "researcher" || userRole === "wizard";
|
||||
|
||||
const stats = {
|
||||
experiments: experiments.length,
|
||||
totalTrials: totalTrials,
|
||||
@@ -181,18 +187,22 @@ export default function StudyDetailPage({ params }: StudyDetailPageProps) {
|
||||
]}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
{canManage && (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/studies/${study.id}/edit`}>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Edit Study
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{canManage && (
|
||||
<Button asChild>
|
||||
<Link href={`/studies/${study.id}/experiments/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Experiment
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
@@ -234,12 +244,14 @@ export default function StudyDetailPage({ params }: StudyDetailPageProps) {
|
||||
icon="FlaskConical"
|
||||
description="Design and manage experimental protocols for this study"
|
||||
actions={
|
||||
canManage ? (
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href={`/studies/${study.id}/experiments/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Experiment
|
||||
</Link>
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{experiments.length === 0 ? (
|
||||
@@ -391,10 +403,14 @@ export default function StudyDetailPage({ params }: StudyDetailPageProps) {
|
||||
icon="Users"
|
||||
description={`${members.length} team member${members.length !== 1 ? "s" : ""}`}
|
||||
actions={
|
||||
canManage ? (
|
||||
<AddMemberDialog studyId={study.id}>
|
||||
<Button variant="outline" size="sm">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Invite
|
||||
Manage
|
||||
</Button>
|
||||
</AddMemberDialog>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
|
||||
@@ -31,6 +31,8 @@ export default function StudyParticipantsPage() {
|
||||
}
|
||||
}, [studyId, selectedStudyId, setSelectedStudyId]);
|
||||
|
||||
const canManage = study?.userRole === "owner" || study?.userRole === "researcher";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
@@ -38,12 +40,14 @@ export default function StudyParticipantsPage() {
|
||||
description="Manage participant registration, consent, and trial assignments for this study"
|
||||
icon={Users}
|
||||
actions={
|
||||
canManage ? (
|
||||
<Button asChild>
|
||||
<a href={`/studies/${studyId}/participants/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Participant
|
||||
</a>
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ export default function StudyTrialsPage() {
|
||||
}
|
||||
}, [studyId, selectedStudyId, setSelectedStudyId]);
|
||||
|
||||
const canRun = ["owner", "researcher", "wizard"].includes(study?.userRole ?? "");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
@@ -39,12 +41,14 @@ export default function StudyTrialsPage() {
|
||||
description="Manage trial execution, scheduling, and data collection for this study"
|
||||
icon={TestTube}
|
||||
actions={
|
||||
canRun ? (
|
||||
<Button asChild>
|
||||
<Link href={`/studies/${studyId}/trials/new`}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Schedule Trial
|
||||
</Link>
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
118
src/app/api/robots/command/route.ts
Normal file
118
src/app/api/robots/command/route.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "~/lib/auth";
|
||||
import { db } from "~/server/db";
|
||||
import { studyMembers } from "~/server/db/schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { exec } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth.api.getSession({
|
||||
headers: request.headers,
|
||||
});
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { action, studyId, robotId, parameters } = body;
|
||||
|
||||
// Verify user has access to the study
|
||||
const membership = await db.query.studyMembers.findFirst({
|
||||
where: and(
|
||||
eq(studyMembers.studyId, studyId),
|
||||
eq(studyMembers.userId, session.user.id),
|
||||
),
|
||||
});
|
||||
|
||||
if (!membership || !["owner", "researcher"].includes(membership.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Insufficient permissions" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const robotIp =
|
||||
process.env.NAO_ROBOT_IP || process.env.NAO_IP || "134.82.159.168";
|
||||
const password = process.env.NAO_PASSWORD || "robolab";
|
||||
|
||||
switch (action) {
|
||||
case "initialize": {
|
||||
console.log(`[Robots API] Initializing robot at ${robotIp}`);
|
||||
|
||||
const disableAlCmd = `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no "nao@${robotIp}" "python2 -c \\"import sys; sys.path.append('/opt/aldebaran/lib/python2.7/site-packages'); import naoqi; al = naoqi.ALProxy('ALAutonomousLife', '127.0.0.1', 9559); al.setState('disabled')\\""`;
|
||||
|
||||
const wakeUpCmd = `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no "nao@${robotIp}" "python2 -c \\"import sys; sys.path.append('/opt/aldebaran/lib/python2.7/site-packages'); import naoqi; m = naoqi.ALProxy('ALMotion', '127.0.0.1', 9559); m.wakeUp()\\""`;
|
||||
|
||||
await execAsync(disableAlCmd).catch((e) =>
|
||||
console.warn("AL disable failed (non-critical/already disabled):", e),
|
||||
);
|
||||
|
||||
await execAsync(wakeUpCmd);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
case "executeSystemAction": {
|
||||
const { id, parameters: actionParams } = parameters ?? {};
|
||||
console.log(`[Robots API] Executing system action ${id}`);
|
||||
|
||||
let command = "";
|
||||
|
||||
switch (id) {
|
||||
case "say_with_emotion":
|
||||
case "say_text_with_emotion": {
|
||||
const text = String(actionParams?.text || "Hello");
|
||||
const emotion = String(actionParams?.emotion || "happy");
|
||||
const tag =
|
||||
emotion === "happy"
|
||||
? "^joyful"
|
||||
: emotion === "sad"
|
||||
? "^sad"
|
||||
: emotion === "thinking"
|
||||
? "^thoughtful"
|
||||
: "^joyful";
|
||||
|
||||
command = `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no "nao@${robotIp}" "python2 -c \\"import sys; sys.path.append('/opt/aldebaran/lib/python2.7/site-packages'); import naoqi; s = naoqi.ALProxy('ALAnimatedSpeech', '127.0.0.1', 9559); s.say('${tag} ${text.replace(/'/g, "\\'")}')\\""`;
|
||||
break;
|
||||
}
|
||||
|
||||
case "wake_up":
|
||||
command = `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no "nao@${robotIp}" "python2 -c \\"import sys; sys.path.append('/opt/aldebaran/lib/python2.7/site-packages'); import naoqi; m = naoqi.ALProxy('ALMotion', '127.0.0.1', 9559); m.wakeUp()\\""`;
|
||||
break;
|
||||
|
||||
case "rest":
|
||||
command = `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no "nao@${robotIp}" "python2 -c \\"import sys; sys.path.append('/opt/aldebaran/lib/python2.7/site-packages'); import naoqi; m = naoqi.ALProxy('ALMotion', '127.0.0.1', 9559); m.rest()\\""`;
|
||||
break;
|
||||
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ error: `System action ${id} not implemented` },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
await execAsync(command);
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
default:
|
||||
return NextResponse.json(
|
||||
{ error: `Unknown action: ${action}` },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[Robots API] Error:", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : "Internal server error",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
135
src/app/api/websocket/route.ts
Normal file
135
src/app/api/websocket/route.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { headers } from "next/headers";
|
||||
import { wsManager } from "~/server/services/websocket-manager";
|
||||
import { auth } from "~/lib/auth";
|
||||
|
||||
const clientConnections = new Map<
|
||||
string,
|
||||
{ socket: WebSocket; clientId: string }
|
||||
>();
|
||||
|
||||
function generateClientId(): string {
|
||||
return `ws_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
}
|
||||
|
||||
export const runtime = "edge";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const url = new URL(request.url);
|
||||
const trialId = url.searchParams.get("trialId");
|
||||
const token = url.searchParams.get("token");
|
||||
|
||||
if (!trialId) {
|
||||
return new Response("Missing trialId parameter", { status: 400 });
|
||||
}
|
||||
|
||||
let userId: string | null = null;
|
||||
|
||||
try {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
}
|
||||
} catch {
|
||||
if (!token) {
|
||||
return new Response("Authentication required", { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenData = JSON.parse(atob(token));
|
||||
userId = tokenData.userId;
|
||||
} catch {
|
||||
return new Response("Invalid token", { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
const pair = new WebSocketPair();
|
||||
const clientId = generateClientId();
|
||||
const serverWebSocket = Object.values(pair)[0] as WebSocket;
|
||||
|
||||
clientConnections.set(clientId, { socket: serverWebSocket, clientId });
|
||||
|
||||
await wsManager.subscribe(clientId, serverWebSocket, trialId, userId);
|
||||
|
||||
serverWebSocket.accept();
|
||||
|
||||
serverWebSocket.addEventListener("message", async (event) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data as string);
|
||||
|
||||
switch (message.type) {
|
||||
case "heartbeat":
|
||||
wsManager.sendToClient(clientId, {
|
||||
type: "heartbeat_response",
|
||||
data: { timestamp: Date.now() },
|
||||
});
|
||||
break;
|
||||
|
||||
case "request_trial_status": {
|
||||
const status = await wsManager.getTrialStatus(trialId);
|
||||
wsManager.sendToClient(clientId, {
|
||||
type: "trial_status",
|
||||
data: {
|
||||
trial: status?.trial ?? null,
|
||||
current_step_index: status?.currentStepIndex ?? 0,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "request_trial_events": {
|
||||
const events = await wsManager.getTrialEvents(
|
||||
trialId,
|
||||
message.data?.limit ?? 100,
|
||||
);
|
||||
wsManager.sendToClient(clientId, {
|
||||
type: "trial_events_snapshot",
|
||||
data: { events, timestamp: Date.now() },
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "ping":
|
||||
wsManager.sendToClient(clientId, {
|
||||
type: "pong",
|
||||
data: { timestamp: Date.now() },
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log(
|
||||
`[WS] Unknown message type from client ${clientId}:`,
|
||||
message.type,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[WS] Error processing message from ${clientId}:`, error);
|
||||
}
|
||||
});
|
||||
|
||||
serverWebSocket.addEventListener("close", () => {
|
||||
wsManager.unsubscribe(clientId);
|
||||
clientConnections.delete(clientId);
|
||||
});
|
||||
|
||||
serverWebSocket.addEventListener("error", (error) => {
|
||||
console.error(`[WS] Error for client ${clientId}:`, error);
|
||||
wsManager.unsubscribe(clientId);
|
||||
clientConnections.delete(clientId);
|
||||
});
|
||||
|
||||
return new Response(null, {
|
||||
status: 101,
|
||||
webSocket: serverWebSocket,
|
||||
} as ResponseInit);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface WebSocket {
|
||||
accept(): void;
|
||||
}
|
||||
}
|
||||
@@ -2,484 +2,317 @@
|
||||
|
||||
import * as React from "react";
|
||||
import Link from "next/link";
|
||||
import { format } from "date-fns";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import {
|
||||
Activity,
|
||||
ArrowRight,
|
||||
Calendar,
|
||||
CheckCircle,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
FlaskConical,
|
||||
HelpCircle,
|
||||
LayoutDashboard,
|
||||
MoreHorizontal,
|
||||
Play,
|
||||
PlayCircle,
|
||||
Plus,
|
||||
Search,
|
||||
Settings,
|
||||
Activity,
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
Users,
|
||||
Radio,
|
||||
Gamepad2,
|
||||
AlertTriangle,
|
||||
FlaskConical,
|
||||
ChevronRight,
|
||||
Bot,
|
||||
User,
|
||||
MessageSquare,
|
||||
Radio,
|
||||
Building,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import { Progress } from "~/components/ui/progress";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { PageHeader } from "~/components/ui/page-layout";
|
||||
import { api } from "~/trpc/react";
|
||||
import { useTour } from "~/components/onboarding/TourProvider";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { startTour } = useTour();
|
||||
const { data: session } = useSession();
|
||||
const [studyFilter, setStudyFilter] = React.useState<string | null>(null);
|
||||
const userName = session?.user?.name ?? "Researcher";
|
||||
|
||||
// --- Data Fetching ---
|
||||
const { data: userStudiesData } = api.studies.list.useQuery({
|
||||
const { data: userStudies } = api.studies.list.useQuery({
|
||||
memberOnly: true,
|
||||
limit: 100,
|
||||
limit: 10,
|
||||
});
|
||||
const userStudies = userStudiesData?.studies ?? [];
|
||||
|
||||
const { data: stats } = api.dashboard.getStats.useQuery({
|
||||
studyId: studyFilter ?? undefined,
|
||||
const { data: recentTrials } = api.trials.list.useQuery({
|
||||
limit: 5,
|
||||
});
|
||||
|
||||
const { data: liveTrials } = api.dashboard.getLiveTrials.useQuery(
|
||||
{ studyId: studyFilter ?? undefined },
|
||||
{},
|
||||
{ refetchInterval: 5000 },
|
||||
);
|
||||
|
||||
const { data: recentActivity } = api.dashboard.getRecentActivity.useQuery({
|
||||
limit: 15,
|
||||
studyId: studyFilter ?? undefined,
|
||||
});
|
||||
const { data: stats } = api.dashboard.getStats.useQuery({});
|
||||
|
||||
const { data: studyProgress } = api.dashboard.getStudyProgress.useQuery({
|
||||
limit: 5,
|
||||
studyId: studyFilter ?? undefined,
|
||||
});
|
||||
|
||||
const userName = session?.user?.name ?? "Researcher";
|
||||
|
||||
const getWelcomeMessage = () => {
|
||||
const greeting = (() => {
|
||||
const hour = new Date().getHours();
|
||||
let greeting = "Good evening";
|
||||
if (hour < 12) greeting = "Good morning";
|
||||
else if (hour < 18) greeting = "Good afternoon";
|
||||
if (hour < 12) return "Good morning";
|
||||
if (hour < 18) return "Good afternoon";
|
||||
return "Good evening";
|
||||
})();
|
||||
|
||||
return `${greeting}, ${userName.split(" ")[0]}`;
|
||||
};
|
||||
const firstStudy = userStudies?.studies?.[0];
|
||||
|
||||
return (
|
||||
<div className="animate-in fade-in space-y-8 duration-500">
|
||||
{/* Header Section */}
|
||||
<div
|
||||
id="dashboard-header"
|
||||
className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between"
|
||||
>
|
||||
<div>
|
||||
<h1 className="text-foreground text-3xl font-bold tracking-tight">
|
||||
{getWelcomeMessage()}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Here's what's happening with your research today.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => startTour("dashboard")}
|
||||
title="Start Tour"
|
||||
>
|
||||
<HelpCircle className="h-5 w-5" />
|
||||
</Button>
|
||||
<Select
|
||||
value={studyFilter ?? "all"}
|
||||
onValueChange={(value) =>
|
||||
setStudyFilter(value === "all" ? null : value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="bg-background w-[200px]">
|
||||
<SelectValue placeholder="All Studies" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Studies</SelectItem>
|
||||
{userStudies.map((study) => (
|
||||
<SelectItem key={study.id} value={study.id}>
|
||||
{study.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button id="tour-new-study" asChild>
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<PageHeader
|
||||
title={`${greeting}, ${userName.split(" ")[0]}`}
|
||||
description="Ready to run your next session?"
|
||||
icon={Bot}
|
||||
actions={
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/studies/new">
|
||||
<Plus className="mr-2 h-4 w-4" /> New Study
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Study
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild className="glow-teal">
|
||||
<Link href={firstStudy?.id ? `/studies/${firstStudy.id}/trials/new` : "/studies/new"}>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
Start Trial
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Main Stats Grid */}
|
||||
<div
|
||||
id="tour-dashboard-stats"
|
||||
className="grid gap-4 md:grid-cols-2 lg:grid-cols-4"
|
||||
>
|
||||
<StatsCard
|
||||
title="Active Trials"
|
||||
{/* Live Trials Banner */}
|
||||
{liveTrials && liveTrials.length > 0 && (
|
||||
<div className="bg-destructive/10 border-border flex items-center gap-4 rounded-lg border p-4">
|
||||
<div className="relative">
|
||||
<Radio className="h-8 w-8 text-destructive animate-pulse" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="font-semibold">
|
||||
{liveTrials.length} Active Session{liveTrials.length > 1 ? "s" : ""}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{liveTrials.map((t) => t.participantCode).join(", ")}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" asChild>
|
||||
<Link href={`/studies/${liveTrials?.[0]?.studyId}/trials/${liveTrials?.[0]?.id}/wizard`}>
|
||||
View <ChevronRight className="ml-1 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats Row */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<StatCard
|
||||
label="Active Trials"
|
||||
value={stats?.activeTrials ?? 0}
|
||||
icon={Activity}
|
||||
description="Currently running sessions"
|
||||
iconColor="text-emerald-500"
|
||||
color="teal"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Completed Today"
|
||||
<StatCard
|
||||
label="Completed Today"
|
||||
value={stats?.completedToday ?? 0}
|
||||
icon={CheckCircle}
|
||||
description="Successful completions"
|
||||
iconColor="text-blue-500"
|
||||
icon={CheckCircle2}
|
||||
color="emerald"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Scheduled"
|
||||
<StatCard
|
||||
label="Total Studies"
|
||||
value={userStudies?.studies?.length ?? 0}
|
||||
icon={FlaskConical}
|
||||
color="blue"
|
||||
/>
|
||||
<StatCard
|
||||
label="Scheduled"
|
||||
value={stats?.scheduledTrials ?? 0}
|
||||
icon={Calendar}
|
||||
description="Upcoming sessions"
|
||||
iconColor="text-violet-500"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Total Interventions"
|
||||
value={stats?.totalInterventions ?? 0}
|
||||
icon={Gamepad2}
|
||||
description="Wizard manual overrides"
|
||||
iconColor="text-orange-500"
|
||||
icon={Clock}
|
||||
color="violet"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Center & Recent Activity */}
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
|
||||
{/* Quick Actions Card */}
|
||||
<Card className="from-primary/5 to-background border-primary/20 col-span-3 h-fit bg-gradient-to-br">
|
||||
<CardHeader>
|
||||
<CardTitle>Quick Actions</CardTitle>
|
||||
<CardDescription>Common tasks to get you started</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-primary/20 hover:border-primary/50 hover:bg-primary/5 group h-auto justify-start px-4 py-4"
|
||||
asChild
|
||||
>
|
||||
<Link href="/studies/new">
|
||||
<div className="bg-primary/10 group-hover:bg-primary/20 mr-4 rounded-full p-2 transition-colors">
|
||||
{/* Main Grid */}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Studies List */}
|
||||
<div className="bg-card rounded-lg border lg:col-span-2">
|
||||
<div className="flex items-center justify-between border-b px-6 py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<FlaskConical className="text-primary h-5 w-5" />
|
||||
<h2 className="font-semibold">Your Studies</h2>
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<div className="font-semibold">Create New Study</div>
|
||||
<div className="text-muted-foreground text-xs font-normal">
|
||||
Design a new experiment protocol
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="text-muted-foreground group-hover:text-primary ml-auto h-4 w-4 opacity-0 transition-all group-hover:opacity-100" />
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="group h-auto justify-start px-4 py-4"
|
||||
asChild
|
||||
>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href="/studies">
|
||||
<div className="bg-secondary mr-4 rounded-full p-2">
|
||||
<Search className="text-foreground h-5 w-5" />
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<div className="font-semibold">Browse Studies</div>
|
||||
<div className="text-muted-foreground text-xs font-normal">
|
||||
Find and manage existing studies
|
||||
</div>
|
||||
</div>
|
||||
View all <ChevronRight className="ml-1 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="group h-auto justify-start px-4 py-4"
|
||||
asChild
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<div className="space-y-3">
|
||||
{userStudies?.studies?.slice(0, 5).map((study) => (
|
||||
<Link
|
||||
key={study.id}
|
||||
href={`/studies/${study.id}`}
|
||||
className="hover:bg-accent/50 group flex items-center justify-between rounded-lg border p-4 transition-colors"
|
||||
>
|
||||
<Link href="/trials">
|
||||
<div className="mr-4 rounded-full bg-emerald-500/10 p-2">
|
||||
<Activity className="h-5 w-5 text-emerald-600" />
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
|
||||
<Bot className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<div className="font-semibold">Monitor Active Trials</div>
|
||||
<div className="text-muted-foreground text-xs font-normal">
|
||||
Jump into the Wizard Interface
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Activity Card */}
|
||||
<Card
|
||||
id="tour-recent-activity"
|
||||
className="border-muted/40 col-span-4 shadow-sm"
|
||||
>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
<CardDescription>
|
||||
Your latest interactions across the platform
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ScrollArea className="h-[400px] pr-4">
|
||||
<div className="space-y-4">
|
||||
{recentActivity?.map((activity) => {
|
||||
let eventColor = "bg-primary/30 ring-background";
|
||||
let Icon = Activity;
|
||||
if (activity.type === "trial_started") {
|
||||
eventColor = "bg-blue-500 ring-blue-100 dark:ring-blue-900";
|
||||
Icon = PlayCircle;
|
||||
} else if (activity.type === "trial_completed") {
|
||||
eventColor =
|
||||
"bg-green-500 ring-green-100 dark:ring-green-900";
|
||||
Icon = CheckCircle;
|
||||
} else if (activity.type === "error") {
|
||||
eventColor = "bg-red-500 ring-red-100 dark:ring-red-900";
|
||||
Icon = AlertTriangle;
|
||||
} else if (activity.type === "intervention") {
|
||||
eventColor =
|
||||
"bg-orange-500 ring-orange-100 dark:ring-orange-900";
|
||||
Icon = Gamepad2;
|
||||
} else if (activity.type === "annotation") {
|
||||
eventColor =
|
||||
"bg-yellow-500 ring-yellow-100 dark:ring-yellow-900";
|
||||
Icon = MessageSquare;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={activity.id}
|
||||
className="border-muted-foreground/20 relative border-l pb-4 pl-6 last:border-0"
|
||||
>
|
||||
<span
|
||||
className={`absolute top-0 left-[-9px] flex h-4 w-4 items-center justify-center rounded-full ring-4 ${eventColor}`}
|
||||
>
|
||||
<Icon className="h-2.5 w-2.5 text-white" />
|
||||
</span>
|
||||
<div className="mb-0.5 text-sm leading-none font-medium">
|
||||
{activity.title}
|
||||
</div>
|
||||
<div className="text-muted-foreground mb-1 text-xs">
|
||||
{activity.description}
|
||||
</div>
|
||||
<div className="text-muted-foreground/70 font-mono text-[10px] uppercase">
|
||||
{formatDistanceToNow(new Date(activity.time), {
|
||||
addSuffix: true,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!recentActivity?.length && (
|
||||
<div className="text-muted-foreground flex flex-col items-center justify-center py-8 text-center">
|
||||
<Clock className="mb-3 h-10 w-10 opacity-20" />
|
||||
<p>No recent activity recorded.</p>
|
||||
<p className="mt-1 text-xs">
|
||||
Start a trial to see experiment events stream here.
|
||||
<div>
|
||||
<p className="font-semibold group-hover:text-primary">
|
||||
{study.name}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{study.status === "active" ? (
|
||||
<span className="text-emerald-600 dark:text-emerald-400">Active</span>
|
||||
) : (
|
||||
<span>{study.status}</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-muted-foreground group-hover:text-primary" />
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{!userStudies?.studies?.length && (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Bot className="text-muted-foreground/50 mb-4 h-16 w-16" />
|
||||
<p className="font-medium">No studies yet</p>
|
||||
<p className="text-muted-foreground mb-4 text-sm">
|
||||
Create your first study to get started
|
||||
</p>
|
||||
<Button asChild>
|
||||
<Link href="/studies/new">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Study
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Links & Recent */}
|
||||
<div className="space-y-6">
|
||||
{/* Quick Actions */}
|
||||
<div className="bg-card rounded-lg border">
|
||||
<div className="border-b px-6 py-4">
|
||||
<h2 className="font-semibold">Quick Actions</h2>
|
||||
</div>
|
||||
<div className="space-y-2 p-4">
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href="/studies/new">
|
||||
<Plus className="mr-3 h-4 w-4" />
|
||||
Create New Study
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={firstStudy?.id ? `/studies/${firstStudy.id}/experiments/new` : "/studies"}>
|
||||
<FlaskConical className="mr-3 h-4 w-4" />
|
||||
Design Experiment
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={firstStudy?.id ? `/studies/${firstStudy.id}/participants/new` : "/studies"}>
|
||||
<Users className="mr-3 h-4 w-4" />
|
||||
Add Participant
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={firstStudy?.id ? `/studies/${firstStudy.id}/trials/new` : "/studies"}>
|
||||
<Play className="mr-3 h-4 w-4" />
|
||||
Start Trial
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Trials */}
|
||||
<div className="bg-card rounded-lg border">
|
||||
<div className="flex items-center justify-between border-b px-6 py-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
<h2 className="font-semibold">Recent Trials</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<ScrollArea className="h-[200px]">
|
||||
<div className="space-y-3">
|
||||
{recentTrials?.slice(0, 5).map((trial) => (
|
||||
<Link
|
||||
key={trial.id}
|
||||
href={`/studies/${trial.experiment.studyId}/trials/${trial.id}`}
|
||||
className="hover:bg-accent/50 block rounded-md border p-3 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">{trial.participant.participantCode}</span>
|
||||
<Badge
|
||||
variant={
|
||||
trial.status === "completed"
|
||||
? "default"
|
||||
: trial.status === "in_progress"
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
className="text-xs"
|
||||
>
|
||||
{trial.status.replace("_", " ")}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{trial.experiment.name}
|
||||
</p>
|
||||
{trial.completedAt && (
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{formatDistanceToNow(new Date(trial.completedAt), { addSuffix: true })}
|
||||
</p>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{!recentTrials?.length && (
|
||||
<p className="text-muted-foreground py-4 text-center text-sm">
|
||||
No trials yet
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
|
||||
{/* Live Trials */}
|
||||
<Card
|
||||
id="tour-live-trials"
|
||||
className={`${liveTrials && liveTrials.length > 0 ? "border-primary bg-primary/5 shadow-sm" : "border-muted/40"} col-span-4 transition-colors duration-500`}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
Live Sessions
|
||||
{liveTrials && liveTrials.length > 0 && (
|
||||
<span className="relative flex h-3 w-3">
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-75"></span>
|
||||
<span className="relative inline-flex h-3 w-3 rounded-full bg-red-500"></span>
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Currently running trials in the Wizard interface
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href="/trials">
|
||||
View All <ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!liveTrials?.length ? (
|
||||
<div className="border-muted-foreground/30 animate-in fade-in-50 bg-background/50 flex h-[150px] flex-col items-center justify-center rounded-md border border-dashed text-center">
|
||||
<Radio className="text-muted-foreground/50 mb-2 h-8 w-8" />
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No trials are currently running.
|
||||
</p>
|
||||
<Button variant="link" size="sm" asChild className="mt-1">
|
||||
<Link href="/trials">Start a Trial</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{liveTrials.map((trial) => (
|
||||
<div
|
||||
key={trial.id}
|
||||
className="border-primary/20 bg-background flex items-center justify-between rounded-lg border p-3 shadow-sm transition-all duration-200 hover:shadow"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-400">
|
||||
<Radio className="h-5 w-5 animate-pulse" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{trial.participantCode}
|
||||
<span className="text-muted-foreground ml-2 text-xs font-normal">
|
||||
• {trial.experimentName}
|
||||
</span>
|
||||
</p>
|
||||
<div className="text-muted-foreground flex items-center gap-2 text-xs">
|
||||
<Clock className="h-3 w-3" />
|
||||
Started{" "}
|
||||
{trial.startedAt
|
||||
? formatDistanceToNow(new Date(trial.startedAt), {
|
||||
addSuffix: true,
|
||||
})
|
||||
: "just now"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-primary hover:bg-primary/90 gap-2"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/wizard/${trial.id}`}>
|
||||
<Play className="h-3.5 w-3.5" /> Spectate / Jump In
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Study Progress */}
|
||||
<Card className="border-muted/40 col-span-3 shadow-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Study Progress</CardTitle>
|
||||
<CardDescription>
|
||||
Completion tracking for active studies
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{studyProgress?.map((study) => (
|
||||
<div key={study.id} className="space-y-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="font-medium">{study.name}</div>
|
||||
<div className="text-muted-foreground">
|
||||
{study.participants} / {study.totalParticipants}{" "}
|
||||
Participants
|
||||
</div>
|
||||
</div>
|
||||
<Progress value={study.progress} className="h-2" />
|
||||
</div>
|
||||
))}
|
||||
{!studyProgress?.length && (
|
||||
<p className="text-muted-foreground py-4 text-center text-sm">
|
||||
No active studies to track.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatsCard({
|
||||
title,
|
||||
function StatCard({
|
||||
label,
|
||||
value,
|
||||
icon: Icon,
|
||||
description,
|
||||
trend,
|
||||
iconColor,
|
||||
color,
|
||||
}: {
|
||||
title: string;
|
||||
value: string | number;
|
||||
label: string;
|
||||
value: number;
|
||||
icon: React.ElementType;
|
||||
description: string;
|
||||
trend?: string;
|
||||
iconColor?: string;
|
||||
color: "teal" | "emerald" | "blue" | "violet";
|
||||
}) {
|
||||
const colorClasses = {
|
||||
teal: "bg-primary/10 text-primary",
|
||||
emerald: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
|
||||
blue: "bg-blue-500/10 text-blue-600 dark:text-blue-400",
|
||||
violet: "bg-violet-500/10 text-violet-600 dark:text-violet-400",
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border-muted/40 hover:border-primary/20 shadow-sm transition-all duration-200 hover:shadow-md">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">{title}</CardTitle>
|
||||
<Icon className={`h-4 w-4 ${iconColor || "text-muted-foreground"}`} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{value}</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{description}
|
||||
{trend && (
|
||||
<span className="ml-1 font-medium text-green-600 dark:text-green-400">
|
||||
{trend}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="bg-card rounded-lg border p-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className={`rounded-full p-3 ${colorClasses[color]}`}>
|
||||
<Icon className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-3xl font-bold">{value}</p>
|
||||
<p className="text-muted-foreground text-sm">{label}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ export function DesignerRoot({
|
||||
},
|
||||
});
|
||||
|
||||
const { data: studyPluginsRaw } = api.robots.plugins.getStudyPlugins.useQuery(
|
||||
const { data: studyPluginsRaw } = api.studies.getStudyPlugins.useQuery(
|
||||
{ studyId: experiment?.studyId ?? "" },
|
||||
{ enabled: !!experiment?.studyId },
|
||||
);
|
||||
|
||||
@@ -197,8 +197,7 @@ export function PluginStoreBrowse() {
|
||||
) as { data: Array<{ id: string; url: string; name: string }> | undefined };
|
||||
|
||||
// Get installed plugins for current study
|
||||
const { data: installedPlugins } =
|
||||
api.robots.plugins.getStudyPlugins.useQuery(
|
||||
const { data: installedPlugins } = api.studies.getStudyPlugins.useQuery(
|
||||
{
|
||||
studyId: selectedStudyId!,
|
||||
},
|
||||
@@ -212,7 +211,7 @@ export function PluginStoreBrowse() {
|
||||
data: availablePlugins,
|
||||
isLoading,
|
||||
error,
|
||||
} = api.robots.plugins.list.useQuery(
|
||||
} = api.plugins.list.useQuery(
|
||||
{
|
||||
status:
|
||||
statusFilter === "all"
|
||||
@@ -228,12 +227,12 @@ export function PluginStoreBrowse() {
|
||||
|
||||
const utils = api.useUtils();
|
||||
|
||||
const installPluginMutation = api.robots.plugins.install.useMutation({
|
||||
const installPluginMutation = api.plugins.install.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Plugin installed successfully!");
|
||||
// Invalidate both plugin queries to refresh the UI
|
||||
void utils.robots.plugins.list.invalidate();
|
||||
void utils.robots.plugins.getStudyPlugins.invalidate();
|
||||
void utils.plugins.list.invalidate();
|
||||
void utils.studies.getStudyPlugins.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message || "Failed to install plugin");
|
||||
@@ -430,7 +429,7 @@ export function PluginStoreBrowse() {
|
||||
"An error occurred while loading the plugin store."}
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => void utils.robots.plugins.list.refetch()}
|
||||
onClick={() => void utils.plugins.list.refetch()}
|
||||
variant="outline"
|
||||
>
|
||||
Try Again
|
||||
|
||||
@@ -90,12 +90,12 @@ function PluginActionsCell({ plugin }: { plugin: Plugin }) {
|
||||
const { selectedStudyId } = useStudyContext();
|
||||
const utils = api.useUtils();
|
||||
|
||||
const uninstallMutation = api.robots.plugins.uninstall.useMutation({
|
||||
const uninstallMutation = api.plugins.uninstall.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Plugin uninstalled successfully");
|
||||
// Invalidate plugin queries to refresh the UI
|
||||
void utils.robots.plugins.getStudyPlugins.invalidate();
|
||||
void utils.robots.plugins.list.invalidate();
|
||||
void utils.studies.getStudyPlugins.invalidate();
|
||||
void utils.plugins.list.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message || "Failed to uninstall plugin");
|
||||
|
||||
@@ -28,7 +28,7 @@ export function PluginsDataTable() {
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = api.robots.plugins.getStudyPlugins.useQuery(
|
||||
} = api.studies.getStudyPlugins.useQuery(
|
||||
{
|
||||
studyId: selectedStudyId!,
|
||||
},
|
||||
|
||||
195
src/components/studies/add-member-dialog.tsx
Normal file
195
src/components/studies/add-member-dialog.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "~/components/ui/dialog";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { Plus, Loader2, Trash2, Shield, UserMinus } from "lucide-react";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
|
||||
interface Member {
|
||||
id: string;
|
||||
userId: string;
|
||||
role: string;
|
||||
user: {
|
||||
name: string | null;
|
||||
email: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AddMemberDialogProps {
|
||||
studyId: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AddMemberDialog({ studyId, children }: AddMemberDialogProps) {
|
||||
const utils = api.useUtils();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [email, setEmail] = React.useState("");
|
||||
const [role, setRole] = React.useState<string>("researcher");
|
||||
|
||||
const { data: membersData } = api.studies.getMembers.useQuery({ studyId });
|
||||
|
||||
const addMember = api.studies.addMember.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Member added successfully");
|
||||
void utils.studies.getMembers.invalidate();
|
||||
setEmail("");
|
||||
setRole("researcher");
|
||||
setOpen(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message || "Failed to add member");
|
||||
},
|
||||
});
|
||||
|
||||
const removeMember = api.studies.removeMember.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success("Member removed");
|
||||
void utils.studies.getMembers.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message || "Failed to remove member");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!email || !role) return;
|
||||
addMember.mutate({ studyId, email, role: role as "researcher" | "wizard" | "observer" });
|
||||
};
|
||||
|
||||
const handleRemove = (memberId: string, memberName: string | null) => {
|
||||
if (confirm(`Remove ${memberName ?? memberId} from this study?`)) {
|
||||
removeMember.mutate({ studyId, memberId });
|
||||
}
|
||||
};
|
||||
|
||||
const members = membersData ?? [];
|
||||
const currentUser = members.find((m) => m.userId);
|
||||
const isOwner = currentUser?.role === "owner";
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children ?? (
|
||||
<Button size="sm">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Member
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Manage Team Members</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add researchers, wizards, or observers to collaborate on this study.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Current Members */}
|
||||
<div className="max-h-[200px] space-y-2 overflow-y-auto">
|
||||
{members.map((member) => (
|
||||
<div
|
||||
key={member.id}
|
||||
className="flex items-center justify-between rounded-lg border p-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
|
||||
<span className="text-sm font-medium text-primary">
|
||||
{(member.user.name ?? member.user.email).charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{member.user.name ?? member.user.email}
|
||||
{member.role === "owner" && (
|
||||
<Shield className="ml-2 inline h-3 w-3 text-amber-500" />
|
||||
)}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs capitalize">{member.role}</p>
|
||||
</div>
|
||||
</div>
|
||||
{isOwner && member.role !== "owner" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemove(member.id, member.user.name)}
|
||||
disabled={removeMember.isPending}
|
||||
>
|
||||
<UserMinus className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email Address</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="researcher@university.edu"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="role">Role</Label>
|
||||
<Select value={role} onValueChange={setRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="researcher">Researcher</SelectItem>
|
||||
<SelectItem value="wizard">Wizard</SelectItem>
|
||||
<SelectItem value="observer">Observer</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
Researchers can design experiments, Wizards execute trials, Observers have read-only access.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={addMember.isPending}>
|
||||
{addMember.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Add Member
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -163,6 +163,11 @@ export function TrialForm({ mode, trialId, studyId }: TrialFormProps) {
|
||||
const form = useForm<TrialFormData>({
|
||||
resolver: zodResolver(trialSchema),
|
||||
defaultValues: {
|
||||
experimentId: "" as any,
|
||||
participantId: "" as any,
|
||||
scheduledAt: new Date(),
|
||||
wizardId: undefined,
|
||||
notes: "",
|
||||
sessionNumber: 1,
|
||||
},
|
||||
});
|
||||
@@ -347,7 +352,7 @@ export function TrialForm({ mode, trialId, studyId }: TrialFormProps) {
|
||||
<FormField>
|
||||
<Label htmlFor="experimentId">Experiment *</Label>
|
||||
<Select
|
||||
value={form.watch("experimentId")}
|
||||
value={form.watch("experimentId") ?? ""}
|
||||
onValueChange={(value) => form.setValue("experimentId", value)}
|
||||
disabled={experimentsLoading || mode === "edit"}
|
||||
>
|
||||
@@ -387,7 +392,7 @@ export function TrialForm({ mode, trialId, studyId }: TrialFormProps) {
|
||||
<FormField>
|
||||
<Label htmlFor="participantId">Participant *</Label>
|
||||
<Select
|
||||
value={form.watch("participantId")}
|
||||
value={form.watch("participantId") ?? ""}
|
||||
onValueChange={(value) => form.setValue("participantId", value)}
|
||||
disabled={participantsLoading || mode === "edit"}
|
||||
>
|
||||
|
||||
@@ -182,7 +182,7 @@ export function RobotActionsPanel({
|
||||
|
||||
// Get installed plugins for the study
|
||||
const { data: plugins = [], isLoading } =
|
||||
api.robots.plugins.getStudyPlugins.useQuery({
|
||||
api.studies.getStudyPlugins.useQuery({
|
||||
studyId,
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import { WebcamPanel } from "./panels/WebcamPanel";
|
||||
import { TrialStatusBar } from "./panels/TrialStatusBar";
|
||||
import { api } from "~/trpc/react";
|
||||
import { useWizardRos } from "~/hooks/useWizardRos";
|
||||
import { useTrialWebSocket, type TrialEvent } from "~/hooks/useWebSocket";
|
||||
import { toast } from "sonner";
|
||||
import { useTour } from "~/components/onboarding/TourProvider";
|
||||
|
||||
@@ -166,19 +167,36 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
},
|
||||
});
|
||||
|
||||
// Robot initialization mutation (for startup routine)
|
||||
const initializeRobotMutation = api.robots.plugins.initialize.useMutation({
|
||||
onSuccess: () => {
|
||||
const [isInitializing, setIsInitializing] = useState(false);
|
||||
|
||||
const initializeRobot = async () => {
|
||||
setIsInitializing(true);
|
||||
try {
|
||||
const response = await fetch("/api/robots/command", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "initialize",
|
||||
studyId: trial?.experiment.studyId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || "Failed to initialize robot");
|
||||
}
|
||||
|
||||
toast.success("Robot initialized", {
|
||||
description: "Autonomous Life disabled and robot awake.",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
} catch (error: any) {
|
||||
toast.error("Robot initialization failed", {
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
setIsInitializing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Log robot action mutation (for client-side execution)
|
||||
const logRobotActionMutation = api.trials.logRobotAction.useMutation({
|
||||
@@ -187,8 +205,34 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
},
|
||||
});
|
||||
|
||||
const executeSystemActionMutation =
|
||||
api.robots.plugins.executeSystemAction.useMutation();
|
||||
const executeSystemAction = async (
|
||||
actionId: string,
|
||||
params?: Record<string, unknown>,
|
||||
) => {
|
||||
setIsExecutingAction(true);
|
||||
try {
|
||||
const response = await fetch("/api/robots/command", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "executeSystemAction",
|
||||
studyId: trial?.experiment.studyId,
|
||||
parameters: { id: actionId, parameters: params },
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || "Failed to execute action");
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
throw error;
|
||||
} finally {
|
||||
setIsExecutingAction(false);
|
||||
}
|
||||
};
|
||||
const [isCompleting, setIsCompleting] = useState(false);
|
||||
|
||||
// Map database step types to component step types
|
||||
@@ -235,10 +279,7 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
autoConnect: true,
|
||||
onSystemAction: async (actionId, parameters) => {
|
||||
console.log(`[Wizard] Executing system action: ${actionId}`, parameters);
|
||||
await executeSystemActionMutation.mutateAsync({
|
||||
id: actionId,
|
||||
parameters,
|
||||
});
|
||||
await executeSystemAction(actionId, parameters);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -252,59 +293,65 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
[setAutonomousLifeRaw],
|
||||
);
|
||||
|
||||
// Use polling for trial status updates (no trial WebSocket server exists)
|
||||
const { data: pollingData } = api.trials.get.useQuery(
|
||||
{ id: trial.id },
|
||||
{
|
||||
refetchInterval: trial.status === "in_progress" ? 5000 : 15000,
|
||||
staleTime: 2000,
|
||||
refetchOnWindowFocus: false,
|
||||
// Trial WebSocket for real-time updates
|
||||
const {
|
||||
isConnected: wsConnected,
|
||||
connectionError: wsError,
|
||||
trialEvents: wsTrialEvents,
|
||||
currentTrialStatus,
|
||||
addLocalEvent,
|
||||
} = useTrialWebSocket(trial.id, {
|
||||
onStatusChange: (status) => {
|
||||
// Update local trial state when WebSocket reports status changes
|
||||
setTrial((prev) => ({
|
||||
...prev,
|
||||
status: status.status,
|
||||
startedAt: status.startedAt
|
||||
? new Date(status.startedAt)
|
||||
: prev.startedAt,
|
||||
completedAt: status.completedAt
|
||||
? new Date(status.completedAt)
|
||||
: prev.completedAt,
|
||||
}));
|
||||
},
|
||||
);
|
||||
|
||||
// Poll for trial events
|
||||
const { data: fetchedEvents } = api.trials.getEvents.useQuery(
|
||||
{ trialId: trial.id, limit: 100 },
|
||||
{
|
||||
refetchInterval: 3000,
|
||||
staleTime: 1000,
|
||||
onTrialEvent: (event) => {
|
||||
// Optionally show toast for new events
|
||||
if (event.eventType === "trial_started") {
|
||||
toast.info("Trial started");
|
||||
} else if (event.eventType === "trial_completed") {
|
||||
toast.info("Trial completed");
|
||||
} else if (event.eventType === "trial_aborted") {
|
||||
toast.warning("Trial aborted");
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// Update local trial state from polling only if changed
|
||||
// Update trial state from WebSocket status
|
||||
useEffect(() => {
|
||||
if (pollingData && JSON.stringify(pollingData) !== JSON.stringify(trial)) {
|
||||
// Only update if specific fields we care about have changed to avoid
|
||||
// unnecessary re-renders that might cause UI flashing
|
||||
if (
|
||||
pollingData.status !== trial.status ||
|
||||
pollingData.startedAt?.getTime() !== trial.startedAt?.getTime() ||
|
||||
pollingData.completedAt?.getTime() !== trial.completedAt?.getTime()
|
||||
) {
|
||||
if (currentTrialStatus) {
|
||||
setTrial((prev) => {
|
||||
// Double check inside setter to be safe
|
||||
if (
|
||||
prev.status === pollingData.status &&
|
||||
prev.startedAt?.getTime() === pollingData.startedAt?.getTime() &&
|
||||
prev.completedAt?.getTime() === pollingData.completedAt?.getTime()
|
||||
prev.status === currentTrialStatus.status &&
|
||||
prev.startedAt?.getTime() ===
|
||||
new Date(currentTrialStatus.startedAt ?? "").getTime() &&
|
||||
prev.completedAt?.getTime() ===
|
||||
new Date(currentTrialStatus.completedAt ?? "").getTime()
|
||||
) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
status: pollingData.status,
|
||||
startedAt: pollingData.startedAt
|
||||
? new Date(pollingData.startedAt)
|
||||
status: currentTrialStatus.status,
|
||||
startedAt: currentTrialStatus.startedAt
|
||||
? new Date(currentTrialStatus.startedAt)
|
||||
: prev.startedAt,
|
||||
completedAt: pollingData.completedAt
|
||||
? new Date(pollingData.completedAt)
|
||||
completedAt: currentTrialStatus.completedAt
|
||||
? new Date(currentTrialStatus.completedAt)
|
||||
: prev.completedAt,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pollingData]);
|
||||
}, [currentTrialStatus]);
|
||||
|
||||
// Auto-start trial on mount if scheduled
|
||||
useEffect(() => {
|
||||
@@ -313,7 +360,7 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
}
|
||||
}, []); // Run once on mount
|
||||
|
||||
// Trial events from robot actions
|
||||
// Trial events from WebSocket (and initial load)
|
||||
const trialEvents = useMemo<
|
||||
Array<{
|
||||
type: string;
|
||||
@@ -322,8 +369,8 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
message?: string;
|
||||
}>
|
||||
>(() => {
|
||||
return (fetchedEvents ?? [])
|
||||
.map((event) => {
|
||||
return (wsTrialEvents ?? [])
|
||||
.map((event: TrialEvent) => {
|
||||
let message: string | undefined;
|
||||
const eventData = event.data as any;
|
||||
|
||||
@@ -364,7 +411,7 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime()); // Newest first
|
||||
}, [fetchedEvents]);
|
||||
}, [wsTrialEvents]);
|
||||
|
||||
// Transform experiment steps to component format
|
||||
const steps: StepData[] = useMemo(
|
||||
@@ -542,7 +589,7 @@ export const WizardInterface = React.memo(function WizardInterface({
|
||||
"[WizardInterface] Triggering robot initialization:",
|
||||
trial.experiment.robotId,
|
||||
);
|
||||
initializeRobotMutation.mutate({ id: trial.experiment.robotId });
|
||||
await initializeRobot();
|
||||
}
|
||||
|
||||
toast.success("Trial started successfully");
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
|
||||
import { useSession } from "~/lib/auth-client";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
@@ -56,10 +54,42 @@ interface TrialActionExecutedMessage {
|
||||
interface InterventionLoggedMessage {
|
||||
type: "intervention_logged";
|
||||
data: {
|
||||
intervention?: unknown;
|
||||
timestamp: number;
|
||||
} & Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface TrialEventMessage {
|
||||
type: "trial_event";
|
||||
data: {
|
||||
event: unknown;
|
||||
timestamp: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface TrialEventsSnapshotMessage {
|
||||
type: "trial_events_snapshot";
|
||||
data: {
|
||||
events: unknown[];
|
||||
timestamp: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface AnnotationAddedMessage {
|
||||
type: "annotation_added";
|
||||
data: {
|
||||
annotation: unknown;
|
||||
timestamp: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PongMessage {
|
||||
type: "pong";
|
||||
data: {
|
||||
timestamp: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface StepChangedMessage {
|
||||
type: "step_changed";
|
||||
data: {
|
||||
@@ -83,6 +113,10 @@ type KnownInboundMessage =
|
||||
| TrialStatusMessage
|
||||
| TrialActionExecutedMessage
|
||||
| InterventionLoggedMessage
|
||||
| TrialEventMessage
|
||||
| TrialEventsSnapshotMessage
|
||||
| AnnotationAddedMessage
|
||||
| PongMessage
|
||||
| StepChangedMessage
|
||||
| ErrorMessage;
|
||||
|
||||
@@ -98,18 +132,247 @@ export interface OutgoingMessage {
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UseWebSocketOptions {
|
||||
interface Subscription {
|
||||
trialId: string;
|
||||
onMessage?: (message: WebSocketMessage) => void;
|
||||
onConnect?: () => void;
|
||||
onDisconnect?: () => void;
|
||||
onError?: (error: Event) => void;
|
||||
reconnectAttempts?: number;
|
||||
reconnectInterval?: number;
|
||||
heartbeatInterval?: number;
|
||||
}
|
||||
|
||||
export interface UseWebSocketReturn {
|
||||
interface GlobalWSState {
|
||||
isConnected: boolean;
|
||||
isConnecting: boolean;
|
||||
connectionError: string | null;
|
||||
lastMessage: WebSocketMessage | null;
|
||||
}
|
||||
|
||||
type StateListener = (state: GlobalWSState) => void;
|
||||
|
||||
class GlobalWebSocketManager {
|
||||
private ws: WebSocket | null = null;
|
||||
private subscriptions: Map<string, Subscription> = new Map();
|
||||
private stateListeners: Set<StateListener> = new Set();
|
||||
private sessionRef: { user: { id: string } } | null = null;
|
||||
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private attemptCount = 0;
|
||||
private maxAttempts = 5;
|
||||
|
||||
private state: GlobalWSState = {
|
||||
isConnected: false,
|
||||
isConnecting: false,
|
||||
connectionError: null,
|
||||
lastMessage: null,
|
||||
};
|
||||
|
||||
private setState(partial: Partial<GlobalWSState>) {
|
||||
this.state = { ...this.state, ...partial };
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
private notifyListeners() {
|
||||
this.stateListeners.forEach((listener) => listener(this.state));
|
||||
}
|
||||
|
||||
subscribe(
|
||||
session: { user: { id: string } } | null,
|
||||
subscription: Subscription,
|
||||
) {
|
||||
this.sessionRef = session;
|
||||
this.subscriptions.set(subscription.trialId, subscription);
|
||||
|
||||
if (this.subscriptions.size === 1 && !this.ws) {
|
||||
this.connect();
|
||||
}
|
||||
|
||||
return () => {
|
||||
this.subscriptions.delete(subscription.trialId);
|
||||
// Don't auto-disconnect - keep global connection alive
|
||||
};
|
||||
}
|
||||
|
||||
sendMessage(message: OutgoingMessage) {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (
|
||||
this.ws?.readyState === WebSocket.CONNECTING ||
|
||||
this.ws?.readyState === WebSocket.OPEN
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.sessionRef?.user) {
|
||||
this.setState({ connectionError: "No session", isConnecting: false });
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({ isConnecting: true, connectionError: null });
|
||||
|
||||
const token = btoa(JSON.stringify({ userId: this.sessionRef.user.id }));
|
||||
const wsPort = process.env.NEXT_PUBLIC_WS_PORT || "3001";
|
||||
|
||||
// Collect all trial IDs from subscriptions
|
||||
const trialIds = Array.from(this.subscriptions.keys());
|
||||
const trialIdParam = trialIds.length > 0 ? `&trialId=${trialIds[0]}` : "";
|
||||
const url = `ws://${typeof window !== "undefined" ? window.location.hostname : "localhost"}:${wsPort}/api/websocket?token=${token}${trialIdParam}`;
|
||||
|
||||
try {
|
||||
this.ws = new WebSocket(url);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log("[GlobalWS] Connected");
|
||||
this.setState({ isConnected: true, isConnecting: false });
|
||||
this.attemptCount = 0;
|
||||
this.startHeartbeat();
|
||||
|
||||
// Subscribe to all subscribed trials
|
||||
this.subscriptions.forEach((sub) => {
|
||||
this.ws?.send(
|
||||
JSON.stringify({
|
||||
type: "subscribe",
|
||||
data: { trialId: sub.trialId },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
this.subscriptions.forEach((sub) => sub.onConnect?.());
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data) as WebSocketMessage;
|
||||
this.setState({ lastMessage: message });
|
||||
|
||||
if (message.type === "connection_established") {
|
||||
const data = (message as ConnectionEstablishedMessage).data;
|
||||
const sub = this.subscriptions.get(data.trialId);
|
||||
if (sub) {
|
||||
sub.onMessage?.(message);
|
||||
}
|
||||
} else if (
|
||||
message.type === "trial_event" ||
|
||||
message.type === "trial_status"
|
||||
) {
|
||||
const data = (message as TrialEventMessage).data;
|
||||
const event = data.event as { trialId?: string };
|
||||
if (event?.trialId) {
|
||||
const sub = this.subscriptions.get(event.trialId);
|
||||
sub?.onMessage?.(message);
|
||||
}
|
||||
} else {
|
||||
// Broadcast to all subscriptions
|
||||
this.subscriptions.forEach((sub) => sub.onMessage?.(message));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[GlobalWS] Failed to parse message:", error);
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onclose = (event) => {
|
||||
console.log("[GlobalWS] Disconnected:", event.code);
|
||||
this.setState({ isConnected: false, isConnecting: false });
|
||||
this.stopHeartbeat();
|
||||
this.subscriptions.forEach((sub) => sub.onDisconnect?.());
|
||||
|
||||
// Auto-reconnect if not intentionally closed
|
||||
if (event.code !== 1000 && this.subscriptions.size > 0) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (error) => {
|
||||
console.error("[GlobalWS] Error:", error);
|
||||
this.setState({
|
||||
connectionError: "Connection error",
|
||||
isConnecting: false,
|
||||
});
|
||||
this.subscriptions.forEach((sub) =>
|
||||
sub.onError?.(new Event("ws_error")),
|
||||
);
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[GlobalWS] Failed to create:", error);
|
||||
this.setState({
|
||||
connectionError: "Failed to create connection",
|
||||
isConnecting: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
if (this.reconnectTimeout) {
|
||||
clearTimeout(this.reconnectTimeout);
|
||||
this.reconnectTimeout = null;
|
||||
}
|
||||
this.stopHeartbeat();
|
||||
if (this.ws) {
|
||||
this.ws.close(1000, "Manual disconnect");
|
||||
this.ws = null;
|
||||
}
|
||||
this.setState({ isConnected: false, isConnecting: false });
|
||||
}
|
||||
|
||||
private startHeartbeat() {
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify({ type: "heartbeat", data: {} }));
|
||||
}
|
||||
}, 30000);
|
||||
}
|
||||
|
||||
private stopHeartbeat() {
|
||||
if (this.heartbeatInterval) {
|
||||
clearInterval(this.heartbeatInterval);
|
||||
this.heartbeatInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (this.attemptCount >= this.maxAttempts) {
|
||||
this.setState({ connectionError: "Max reconnection attempts reached" });
|
||||
return;
|
||||
}
|
||||
|
||||
const delay = Math.min(30000, 1000 * Math.pow(1.5, this.attemptCount));
|
||||
this.attemptCount++;
|
||||
|
||||
console.log(
|
||||
`[GlobalWS] Reconnecting in ${delay}ms (attempt ${this.attemptCount})`,
|
||||
);
|
||||
|
||||
this.reconnectTimeout = setTimeout(() => {
|
||||
if (this.subscriptions.size > 0) {
|
||||
this.connect();
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
getState(): GlobalWSState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
addListener(listener: StateListener) {
|
||||
this.stateListeners.add(listener);
|
||||
return () => this.stateListeners.delete(listener);
|
||||
}
|
||||
}
|
||||
|
||||
const globalWS = new GlobalWebSocketManager();
|
||||
|
||||
export interface UseGlobalWebSocketOptions {
|
||||
trialId: string;
|
||||
onMessage?: (message: WebSocketMessage) => void;
|
||||
onConnect?: () => void;
|
||||
onDisconnect?: () => void;
|
||||
onError?: (error: Event) => void;
|
||||
}
|
||||
|
||||
export interface UseGlobalWebSocketReturn {
|
||||
isConnected: boolean;
|
||||
isConnecting: boolean;
|
||||
connectionError: string | null;
|
||||
@@ -119,333 +382,66 @@ export interface UseWebSocketReturn {
|
||||
lastMessage: WebSocketMessage | null;
|
||||
}
|
||||
|
||||
export function useWebSocket({
|
||||
export function useGlobalWebSocket({
|
||||
trialId,
|
||||
onMessage,
|
||||
onConnect,
|
||||
onDisconnect,
|
||||
onError,
|
||||
reconnectAttempts = 5,
|
||||
reconnectInterval = 3000,
|
||||
heartbeatInterval = 30000,
|
||||
}: UseWebSocketOptions): UseWebSocketReturn {
|
||||
}: UseGlobalWebSocketOptions): UseGlobalWebSocketReturn {
|
||||
const { data: session } = useSession();
|
||||
const [isConnected, setIsConnected] = useState<boolean>(false);
|
||||
const [isConnecting, setIsConnecting] = useState<boolean>(false);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [connectionError, setConnectionError] = useState<string | null>(null);
|
||||
const [hasAttemptedConnection, setHasAttemptedConnection] =
|
||||
useState<boolean>(false);
|
||||
const [lastMessage, setLastMessage] = useState<WebSocketMessage | null>(null);
|
||||
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const heartbeatTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const attemptCountRef = useRef<number>(0);
|
||||
const mountedRef = useRef<boolean>(true);
|
||||
const connectionStableTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const onMessageRef = useRef(onMessage);
|
||||
const onConnectRef = useRef(onConnect);
|
||||
const onDisconnectRef = useRef(onDisconnect);
|
||||
const onErrorRef = useRef(onError);
|
||||
|
||||
// Generate auth token (simplified - in production use proper JWT)
|
||||
const getAuthToken = useCallback((): string | null => {
|
||||
if (!session?.user) return null;
|
||||
// In production, this would be a proper JWT token
|
||||
return btoa(
|
||||
JSON.stringify({ userId: session.user.id, timestamp: Date.now() }),
|
||||
);
|
||||
}, [session]);
|
||||
onMessageRef.current = onMessage;
|
||||
onConnectRef.current = onConnect;
|
||||
onDisconnectRef.current = onDisconnect;
|
||||
onErrorRef.current = onError;
|
||||
|
||||
const sendMessage = useCallback((message: OutgoingMessage): void => {
|
||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
wsRef.current.send(JSON.stringify(message));
|
||||
} else {
|
||||
console.warn("WebSocket not connected, message not sent:", message);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const sendHeartbeat = useCallback((): void => {
|
||||
sendMessage({ type: "heartbeat", data: {} });
|
||||
}, [sendMessage]);
|
||||
|
||||
const scheduleHeartbeat = useCallback((): void => {
|
||||
if (heartbeatTimeoutRef.current) {
|
||||
clearTimeout(heartbeatTimeoutRef.current);
|
||||
}
|
||||
heartbeatTimeoutRef.current = setTimeout(() => {
|
||||
if (isConnected && mountedRef.current) {
|
||||
sendHeartbeat();
|
||||
scheduleHeartbeat();
|
||||
}
|
||||
}, heartbeatInterval);
|
||||
}, [isConnected, sendHeartbeat, heartbeatInterval]);
|
||||
|
||||
const handleMessage = useCallback(
|
||||
(event: MessageEvent<string>): void => {
|
||||
try {
|
||||
const message = JSON.parse(event.data) as WebSocketMessage;
|
||||
setLastMessage(message);
|
||||
|
||||
// Handle system messages
|
||||
switch (message.type) {
|
||||
case "connection_established": {
|
||||
console.log(
|
||||
"WebSocket connection established:",
|
||||
(message as ConnectionEstablishedMessage).data,
|
||||
);
|
||||
useEffect(() => {
|
||||
const unsubscribe = globalWS.subscribe(session, {
|
||||
trialId,
|
||||
onMessage: (msg) => {
|
||||
setLastMessage(msg);
|
||||
onMessageRef.current?.(msg);
|
||||
},
|
||||
onConnect: () => {
|
||||
setIsConnected(true);
|
||||
setIsConnecting(false);
|
||||
setConnectionError(null);
|
||||
attemptCountRef.current = 0;
|
||||
scheduleHeartbeat();
|
||||
onConnect?.();
|
||||
break;
|
||||
}
|
||||
|
||||
case "heartbeat_response":
|
||||
// Heartbeat acknowledged, connection is alive
|
||||
break;
|
||||
|
||||
case "error": {
|
||||
console.error("WebSocket server error:", message);
|
||||
const msg =
|
||||
(message as ErrorMessage).data?.message ?? "Server error";
|
||||
setConnectionError(msg);
|
||||
onError?.(new Event("server_error"));
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Pass to user-defined message handler
|
||||
onMessage?.(message);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error parsing WebSocket message:", error);
|
||||
setConnectionError("Failed to parse message");
|
||||
}
|
||||
onConnectRef.current?.();
|
||||
},
|
||||
[onMessage, onConnect, onError, scheduleHeartbeat],
|
||||
);
|
||||
|
||||
const handleClose = useCallback(
|
||||
(event: CloseEvent): void => {
|
||||
console.log("WebSocket connection closed:", event.code, event.reason);
|
||||
onDisconnect: () => {
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
|
||||
if (heartbeatTimeoutRef.current) {
|
||||
clearTimeout(heartbeatTimeoutRef.current);
|
||||
}
|
||||
|
||||
onDisconnect?.();
|
||||
|
||||
// Attempt reconnection if not manually closed and component is still mounted
|
||||
// In development, don't aggressively reconnect to prevent UI flashing
|
||||
if (
|
||||
event.code !== 1000 &&
|
||||
mountedRef.current &&
|
||||
attemptCountRef.current < reconnectAttempts &&
|
||||
process.env.NODE_ENV !== "development"
|
||||
) {
|
||||
attemptCountRef.current++;
|
||||
const delay =
|
||||
reconnectInterval * Math.pow(1.5, attemptCountRef.current - 1); // Exponential backoff
|
||||
|
||||
console.log(
|
||||
`Attempting reconnection ${attemptCountRef.current}/${reconnectAttempts} in ${delay}ms`,
|
||||
);
|
||||
setConnectionError(
|
||||
`Connection lost. Reconnecting... (${attemptCountRef.current}/${reconnectAttempts})`,
|
||||
);
|
||||
|
||||
reconnectTimeoutRef.current = setTimeout(() => {
|
||||
if (mountedRef.current) {
|
||||
attemptCountRef.current = 0;
|
||||
setIsConnecting(true);
|
||||
setConnectionError(null);
|
||||
}
|
||||
}, delay);
|
||||
} else if (attemptCountRef.current >= reconnectAttempts) {
|
||||
setConnectionError("Failed to reconnect after maximum attempts");
|
||||
} else if (
|
||||
process.env.NODE_ENV === "development" &&
|
||||
event.code !== 1000
|
||||
) {
|
||||
// In development, set a stable error message without reconnection attempts
|
||||
setConnectionError("WebSocket unavailable - using polling mode");
|
||||
}
|
||||
onDisconnectRef.current?.();
|
||||
},
|
||||
[onDisconnect, reconnectAttempts, reconnectInterval],
|
||||
);
|
||||
|
||||
const handleError = useCallback(
|
||||
(event: Event): void => {
|
||||
// In development, WebSocket failures are expected with Edge Runtime
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
// Only set error state after the first failed attempt to prevent flashing
|
||||
if (!hasAttemptedConnection) {
|
||||
setHasAttemptedConnection(true);
|
||||
// Debounce the error state to prevent UI flashing
|
||||
if (connectionStableTimeoutRef.current) {
|
||||
clearTimeout(connectionStableTimeoutRef.current);
|
||||
}
|
||||
connectionStableTimeoutRef.current = setTimeout(() => {
|
||||
setConnectionError("WebSocket unavailable - using polling mode");
|
||||
setIsConnecting(false);
|
||||
}, 1000);
|
||||
}
|
||||
} else {
|
||||
console.error("WebSocket error:", event);
|
||||
onError: (err) => {
|
||||
setConnectionError("Connection error");
|
||||
setIsConnecting(false);
|
||||
}
|
||||
onError?.(event);
|
||||
onErrorRef.current?.(err);
|
||||
},
|
||||
[onError, hasAttemptedConnection],
|
||||
);
|
||||
});
|
||||
|
||||
const connectInternal = useCallback((): void => {
|
||||
if (!session?.user || !trialId) {
|
||||
if (!hasAttemptedConnection) {
|
||||
setConnectionError("Missing authentication or trial ID");
|
||||
setHasAttemptedConnection(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
return unsubscribe;
|
||||
}, [trialId, session]);
|
||||
|
||||
if (
|
||||
wsRef.current &&
|
||||
(wsRef.current.readyState === WebSocket.CONNECTING ||
|
||||
wsRef.current.readyState === WebSocket.OPEN)
|
||||
) {
|
||||
return; // Already connecting or connected
|
||||
}
|
||||
|
||||
const token = getAuthToken();
|
||||
if (!token) {
|
||||
if (!hasAttemptedConnection) {
|
||||
setConnectionError("Failed to generate auth token");
|
||||
setHasAttemptedConnection(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Only show connecting state for the first attempt or if we've been stable
|
||||
if (!hasAttemptedConnection || isConnected) {
|
||||
setIsConnecting(true);
|
||||
}
|
||||
|
||||
// Clear any pending error updates
|
||||
if (connectionStableTimeoutRef.current) {
|
||||
clearTimeout(connectionStableTimeoutRef.current);
|
||||
}
|
||||
|
||||
setConnectionError(null);
|
||||
|
||||
try {
|
||||
// Use appropriate WebSocket URL based on environment
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${protocol}//${window.location.host}/api/websocket?trialId=${trialId}&token=${token}`;
|
||||
|
||||
wsRef.current = new WebSocket(wsUrl);
|
||||
wsRef.current.onmessage = handleMessage;
|
||||
wsRef.current.onclose = handleClose;
|
||||
wsRef.current.onerror = handleError;
|
||||
|
||||
wsRef.current.onopen = () => {
|
||||
console.log("WebSocket connection opened");
|
||||
// Connection establishment is handled in handleMessage
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to create WebSocket connection:", error);
|
||||
if (!hasAttemptedConnection) {
|
||||
setConnectionError("Failed to create connection");
|
||||
setHasAttemptedConnection(true);
|
||||
}
|
||||
setIsConnecting(false);
|
||||
}
|
||||
}, [
|
||||
session,
|
||||
trialId,
|
||||
getAuthToken,
|
||||
handleMessage,
|
||||
handleClose,
|
||||
handleError,
|
||||
hasAttemptedConnection,
|
||||
isConnected,
|
||||
]);
|
||||
|
||||
const disconnect = useCallback((): void => {
|
||||
mountedRef.current = false;
|
||||
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current);
|
||||
}
|
||||
|
||||
if (heartbeatTimeoutRef.current) {
|
||||
clearTimeout(heartbeatTimeoutRef.current);
|
||||
}
|
||||
|
||||
if (connectionStableTimeoutRef.current) {
|
||||
clearTimeout(connectionStableTimeoutRef.current);
|
||||
}
|
||||
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close(1000, "Manual disconnect");
|
||||
wsRef.current = null;
|
||||
}
|
||||
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
setConnectionError(null);
|
||||
setHasAttemptedConnection(false);
|
||||
attemptCountRef.current = 0;
|
||||
const sendMessage = useCallback((message: OutgoingMessage) => {
|
||||
globalWS.sendMessage(message);
|
||||
}, []);
|
||||
|
||||
const reconnect = useCallback((): void => {
|
||||
disconnect();
|
||||
mountedRef.current = true;
|
||||
attemptCountRef.current = 0;
|
||||
setHasAttemptedConnection(false);
|
||||
setTimeout(() => {
|
||||
if (mountedRef.current) {
|
||||
void connectInternal();
|
||||
}
|
||||
}, 100); // Small delay to ensure cleanup
|
||||
}, [disconnect, connectInternal]);
|
||||
const disconnect = useCallback(() => {
|
||||
globalWS.disconnect();
|
||||
}, []);
|
||||
|
||||
// Effect to establish initial connection
|
||||
useEffect(() => {
|
||||
if (session?.user?.id && trialId) {
|
||||
// In development, only attempt connection once to prevent flashing
|
||||
if (process.env.NODE_ENV === "development" && hasAttemptedConnection) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger reconnection if timeout was set
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current);
|
||||
reconnectTimeoutRef.current = null;
|
||||
void connectInternal();
|
||||
} else {
|
||||
void connectInternal();
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
disconnect();
|
||||
};
|
||||
}, [session?.user?.id, trialId, hasAttemptedConnection]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
if (connectionStableTimeoutRef.current) {
|
||||
clearTimeout(connectionStableTimeoutRef.current);
|
||||
}
|
||||
disconnect();
|
||||
};
|
||||
}, [disconnect]);
|
||||
const reconnect = useCallback(() => {
|
||||
globalWS.connect();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
isConnected,
|
||||
@@ -458,115 +454,180 @@ export function useWebSocket({
|
||||
};
|
||||
}
|
||||
|
||||
// Hook for trial-specific WebSocket events
|
||||
export function useTrialWebSocket(trialId: string) {
|
||||
const [trialEvents, setTrialEvents] = useState<WebSocketMessage[]>([]);
|
||||
const [currentTrialStatus, setCurrentTrialStatus] =
|
||||
useState<TrialSnapshot | null>(null);
|
||||
const [wizardActions, setWizardActions] = useState<WebSocketMessage[]>([]);
|
||||
// Legacy alias
|
||||
export const useWebSocket = useGlobalWebSocket;
|
||||
|
||||
const handleMessage = useCallback((message: WebSocketMessage): void => {
|
||||
// Add to events log
|
||||
setTrialEvents((prev) => [...prev, message].slice(-100)); // Keep last 100 events
|
||||
// Trial-specific hook
|
||||
export interface TrialEvent {
|
||||
id: string;
|
||||
trialId: string;
|
||||
eventType: string;
|
||||
data: Record<string, unknown> | null;
|
||||
timestamp: Date;
|
||||
createdBy?: string | null;
|
||||
}
|
||||
|
||||
export interface TrialWebSocketState {
|
||||
trialEvents: TrialEvent[];
|
||||
currentTrialStatus: TrialSnapshot | null;
|
||||
wizardActions: WebSocketMessage[];
|
||||
}
|
||||
|
||||
export function useTrialWebSocket(
|
||||
trialId: string,
|
||||
options?: {
|
||||
onTrialEvent?: (event: TrialEvent) => void;
|
||||
onStatusChange?: (status: TrialSnapshot) => void;
|
||||
initialEvents?: TrialEvent[];
|
||||
initialStatus?: TrialSnapshot | null;
|
||||
},
|
||||
) {
|
||||
const [state, setState] = useState<TrialWebSocketState>({
|
||||
trialEvents: options?.initialEvents ?? [],
|
||||
currentTrialStatus: options?.initialStatus ?? null,
|
||||
wizardActions: [],
|
||||
});
|
||||
|
||||
const handleMessage = useCallback(
|
||||
(message: WebSocketMessage): void => {
|
||||
switch (message.type) {
|
||||
case "trial_status": {
|
||||
const data = (message as TrialStatusMessage).data;
|
||||
setCurrentTrialStatus(data.trial);
|
||||
const status = data.trial as TrialSnapshot;
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentTrialStatus: status,
|
||||
}));
|
||||
options?.onStatusChange?.(status);
|
||||
break;
|
||||
}
|
||||
|
||||
case "trial_events_snapshot": {
|
||||
const data = (message as TrialEventsSnapshotMessage).data;
|
||||
const events = (
|
||||
data.events as Array<{
|
||||
id: string;
|
||||
trialId: string;
|
||||
eventType: string;
|
||||
data: Record<string, unknown> | null;
|
||||
timestamp: Date | string;
|
||||
createdBy?: string | null;
|
||||
}>
|
||||
).map((e) => ({
|
||||
...e,
|
||||
timestamp:
|
||||
typeof e.timestamp === "string"
|
||||
? new Date(e.timestamp)
|
||||
: e.timestamp,
|
||||
}));
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
trialEvents: events,
|
||||
}));
|
||||
break;
|
||||
}
|
||||
|
||||
case "trial_event": {
|
||||
const data = (message as TrialEventMessage).data;
|
||||
const event = data.event as {
|
||||
id: string;
|
||||
trialId: string;
|
||||
eventType: string;
|
||||
data: Record<string, unknown> | null;
|
||||
timestamp: Date | string;
|
||||
createdBy?: string | null;
|
||||
};
|
||||
const newEvent: TrialEvent = {
|
||||
...event,
|
||||
timestamp:
|
||||
typeof event.timestamp === "string"
|
||||
? new Date(event.timestamp)
|
||||
: event.timestamp,
|
||||
};
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
trialEvents: [...prev.trialEvents, newEvent].slice(-500),
|
||||
}));
|
||||
options?.onTrialEvent?.(newEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case "trial_action_executed":
|
||||
case "intervention_logged":
|
||||
case "step_changed":
|
||||
setWizardActions((prev) => [...prev, message].slice(-50)); // Keep last 50 actions
|
||||
case "annotation_added":
|
||||
case "step_changed": {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
wizardActions: [...prev.wizardActions, message].slice(-100),
|
||||
}));
|
||||
break;
|
||||
}
|
||||
|
||||
case "step_changed":
|
||||
// Handle step transitions (optional logging)
|
||||
console.log("Step changed:", (message as StepChangedMessage).data);
|
||||
case "pong":
|
||||
break;
|
||||
|
||||
default:
|
||||
// Handle other trial-specific messages
|
||||
break;
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.log(`[WS] Unknown message type: ${message.type}`);
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
},
|
||||
[options],
|
||||
);
|
||||
|
||||
const webSocket = useWebSocket({
|
||||
const webSocket = useGlobalWebSocket({
|
||||
trialId,
|
||||
onMessage: handleMessage,
|
||||
onConnect: () => {
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.log(`Connected to trial ${trialId} WebSocket`);
|
||||
console.log(`[WS] Connected to trial ${trialId}`);
|
||||
}
|
||||
},
|
||||
onDisconnect: () => {
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.log(`Disconnected from trial ${trialId} WebSocket`);
|
||||
console.log(`[WS] Disconnected from trial ${trialId}`);
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
// Suppress noisy WebSocket errors in development
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
console.error(`Trial ${trialId} WebSocket connection failed`);
|
||||
console.error(`[WS] Trial ${trialId} WebSocket connection failed`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Request trial status after connection is established
|
||||
// Request initial data after connection is established
|
||||
useEffect(() => {
|
||||
if (webSocket.isConnected) {
|
||||
webSocket.sendMessage({ type: "request_trial_status", data: {} });
|
||||
webSocket.sendMessage({
|
||||
type: "request_trial_events",
|
||||
data: { limit: 500 },
|
||||
});
|
||||
}
|
||||
}, [webSocket.isConnected, webSocket]);
|
||||
}, [webSocket.isConnected]);
|
||||
|
||||
// Trial-specific actions
|
||||
const executeTrialAction = useCallback(
|
||||
(actionType: string, actionData: Record<string, unknown>): void => {
|
||||
webSocket.sendMessage({
|
||||
type: "trial_action",
|
||||
data: {
|
||||
actionType,
|
||||
...actionData,
|
||||
},
|
||||
});
|
||||
},
|
||||
[webSocket],
|
||||
);
|
||||
// Helper to add an event locally (for optimistic updates)
|
||||
const addLocalEvent = useCallback((event: TrialEvent) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
trialEvents: [...prev.trialEvents, event].slice(-500),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const logWizardIntervention = useCallback(
|
||||
(interventionData: Record<string, unknown>): void => {
|
||||
webSocket.sendMessage({
|
||||
type: "wizard_intervention",
|
||||
data: interventionData,
|
||||
});
|
||||
},
|
||||
[webSocket],
|
||||
);
|
||||
|
||||
const transitionStep = useCallback(
|
||||
(stepData: {
|
||||
from_step?: number;
|
||||
to_step: number;
|
||||
step_name?: string;
|
||||
[k: string]: unknown;
|
||||
}): void => {
|
||||
webSocket.sendMessage({
|
||||
type: "step_transition",
|
||||
data: stepData,
|
||||
});
|
||||
},
|
||||
[webSocket],
|
||||
);
|
||||
// Helper to update trial status locally
|
||||
const updateLocalStatus = useCallback((status: TrialSnapshot) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentTrialStatus: status,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
...webSocket,
|
||||
trialEvents,
|
||||
currentTrialStatus,
|
||||
wizardActions,
|
||||
executeTrialAction,
|
||||
logWizardIntervention,
|
||||
transitionStep,
|
||||
trialEvents: state.trialEvents,
|
||||
currentTrialStatus: state.currentTrialStatus,
|
||||
wizardActions: state.wizardActions,
|
||||
addLocalEvent,
|
||||
updateLocalStatus,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ const s3Client = new S3Client({
|
||||
forcePathStyle: true, // Required for MinIO
|
||||
});
|
||||
|
||||
const BUCKET_NAME = env.MINIO_BUCKET_NAME ?? "hristudio";
|
||||
const BUCKET_NAME = env.MINIO_BUCKET_NAME ?? "hristudio-data";
|
||||
const PRESIGNED_URL_EXPIRY = 3600; // 1 hour in seconds
|
||||
|
||||
export interface UploadParams {
|
||||
|
||||
@@ -5,9 +5,10 @@ import { collaborationRouter } from "~/server/api/routers/collaboration";
|
||||
import { dashboardRouter } from "~/server/api/routers/dashboard";
|
||||
import { experimentsRouter } from "~/server/api/routers/experiments";
|
||||
import { filesRouter } from "~/server/api/routers/files";
|
||||
import { formsRouter } from "~/server/api/routers/forms";
|
||||
import { mediaRouter } from "~/server/api/routers/media";
|
||||
import { participantsRouter } from "~/server/api/routers/participants";
|
||||
import { robotsRouter } from "~/server/api/routers/robots";
|
||||
import { pluginsRouter } from "~/server/api/routers/plugins";
|
||||
import { studiesRouter } from "~/server/api/routers/studies";
|
||||
import { trialsRouter } from "~/server/api/routers/trials";
|
||||
import { usersRouter } from "~/server/api/routers/users";
|
||||
@@ -26,14 +27,15 @@ export const appRouter = createTRPCRouter({
|
||||
experiments: experimentsRouter,
|
||||
participants: participantsRouter,
|
||||
trials: trialsRouter,
|
||||
robots: robotsRouter,
|
||||
files: filesRouter,
|
||||
media: mediaRouter,
|
||||
plugins: pluginsRouter,
|
||||
analytics: analyticsRouter,
|
||||
collaboration: collaborationRouter,
|
||||
admin: adminRouter,
|
||||
dashboard: dashboardRouter,
|
||||
storage: storageRouter,
|
||||
forms: formsRouter,
|
||||
});
|
||||
|
||||
// export type definition of API
|
||||
|
||||
@@ -143,6 +143,7 @@ export const dashboardRouter = createTRPCRouter({
|
||||
const live = await ctx.db
|
||||
.select({
|
||||
id: trials.id,
|
||||
studyId: studies.id,
|
||||
startedAt: trials.startedAt,
|
||||
experimentName: experiments.name,
|
||||
participantCode: participants.participantCode,
|
||||
|
||||
@@ -18,7 +18,7 @@ const minioClient = new Minio.Client({
|
||||
secretKey: env.MINIO_SECRET_KEY ?? "minioadmin",
|
||||
});
|
||||
|
||||
const BUCKET_NAME = env.MINIO_BUCKET_NAME ?? "hristudio-assets";
|
||||
const BUCKET_NAME = env.MINIO_BUCKET_NAME ?? "hristudio";
|
||||
|
||||
// Ensure bucket exists on startup (best effort)
|
||||
const ensureBucket = async () => {
|
||||
|
||||
676
src/server/api/routers/forms.ts
Normal file
676
src/server/api/routers/forms.ts
Normal file
@@ -0,0 +1,676 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, count, desc, eq, ilike, or } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import {
|
||||
activityLogs,
|
||||
formResponses,
|
||||
formTypeEnum,
|
||||
forms,
|
||||
formFieldTypeEnum,
|
||||
participants,
|
||||
studyMembers,
|
||||
userSystemRoles,
|
||||
} from "~/server/db/schema";
|
||||
|
||||
const formTypes = formTypeEnum.enumValues;
|
||||
const fieldTypes = formFieldTypeEnum.enumValues;
|
||||
|
||||
async function checkStudyAccess(
|
||||
db: typeof import("~/server/db").db,
|
||||
userId: string,
|
||||
studyId: string,
|
||||
requiredRole?: string[],
|
||||
) {
|
||||
const adminRole = await db.query.userSystemRoles.findFirst({
|
||||
where: and(
|
||||
eq(userSystemRoles.userId, userId),
|
||||
eq(userSystemRoles.role, "administrator"),
|
||||
),
|
||||
});
|
||||
|
||||
if (adminRole) {
|
||||
return { role: "administrator", studyId, userId, joinedAt: new Date() };
|
||||
}
|
||||
|
||||
const membership = await db.query.studyMembers.findFirst({
|
||||
where: and(
|
||||
eq(studyMembers.studyId, studyId),
|
||||
eq(studyMembers.userId, userId),
|
||||
),
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have access to this study",
|
||||
});
|
||||
}
|
||||
|
||||
if (requiredRole && !requiredRole.includes(membership.role)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have permission to perform this action",
|
||||
});
|
||||
}
|
||||
|
||||
return membership;
|
||||
}
|
||||
|
||||
export const formsRouter = createTRPCRouter({
|
||||
list: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string().uuid(),
|
||||
type: z.enum(formTypes).optional(),
|
||||
search: z.string().optional(),
|
||||
page: z.number().min(1).default(1),
|
||||
limit: z.number().min(1).max(100).default(20),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { studyId, type, search, page, limit } = input;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, studyId);
|
||||
|
||||
const conditions = [eq(forms.studyId, studyId)];
|
||||
if (type) {
|
||||
conditions.push(eq(forms.type, type));
|
||||
}
|
||||
if (search) {
|
||||
conditions.push(
|
||||
or(
|
||||
ilike(forms.title, `%${search}%`),
|
||||
ilike(forms.description, `%${search}%`),
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
const [formsList, totalCount] = await Promise.all([
|
||||
ctx.db.query.forms.findMany({
|
||||
where: and(...conditions),
|
||||
with: {
|
||||
createdBy: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [desc(forms.updatedAt)],
|
||||
limit,
|
||||
offset,
|
||||
}),
|
||||
ctx.db
|
||||
.select({ count: count() })
|
||||
.from(forms)
|
||||
.where(and(...conditions)),
|
||||
]);
|
||||
|
||||
const formsWithCounts = await Promise.all(
|
||||
formsList.map(async (form) => {
|
||||
const responseCount = await ctx.db
|
||||
.select({ count: count() })
|
||||
.from(formResponses)
|
||||
.where(eq(formResponses.formId, form.id));
|
||||
return { ...form, _count: { responses: responseCount[0]?.count ?? 0 } };
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
forms: formsWithCounts,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: totalCount[0]?.count ?? 0,
|
||||
pages: Math.ceil((totalCount[0]?.count ?? 0) / limit),
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
get: protectedProcedure
|
||||
.input(z.object({ id: z.string().uuid() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const form = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, input.id),
|
||||
with: {
|
||||
createdBy: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
with: {
|
||||
participant: {
|
||||
columns: {
|
||||
id: true,
|
||||
participantCode: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [desc(formResponses.submittedAt)],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, form.studyId);
|
||||
|
||||
return form;
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string().uuid(),
|
||||
type: z.enum(formTypes),
|
||||
title: z.string().min(1).max(255),
|
||||
description: z.string().optional(),
|
||||
fields: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
label: z.string(),
|
||||
required: z.boolean().default(false),
|
||||
options: z.array(z.string()).optional(),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
}),
|
||||
).default([]),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
isTemplate: z.boolean().optional(),
|
||||
templateName: z.string().max(100).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { isTemplate, templateName, ...formData } = input;
|
||||
|
||||
if (isTemplate && !templateName) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Template name is required when creating a template",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, input.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
const [newForm] = await ctx.db
|
||||
.insert(forms)
|
||||
.values({
|
||||
studyId: formData.studyId,
|
||||
type: formData.type,
|
||||
title: formData.title,
|
||||
description: formData.description,
|
||||
fields: formData.fields,
|
||||
settings: formData.settings ?? {},
|
||||
isTemplate: isTemplate ?? false,
|
||||
templateName: templateName,
|
||||
createdBy: ctx.session.user.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!newForm) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to create form",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.insert(activityLogs).values({
|
||||
studyId: input.studyId,
|
||||
userId: ctx.session.user.id,
|
||||
action: "form_created",
|
||||
description: `Created form "${newForm.title}"`,
|
||||
resourceType: "form",
|
||||
resourceId: newForm.id,
|
||||
});
|
||||
|
||||
return newForm;
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string().uuid(),
|
||||
title: z.string().min(1).max(255).optional(),
|
||||
description: z.string().optional(),
|
||||
fields: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
label: z.string(),
|
||||
required: z.boolean().default(false),
|
||||
options: z.array(z.string()).optional(),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
}),
|
||||
).optional(),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...updateData } = input;
|
||||
|
||||
const existingForm = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, id),
|
||||
});
|
||||
|
||||
if (!existingForm) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, existingForm.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
const [updatedForm] = await ctx.db
|
||||
.update(forms)
|
||||
.set({
|
||||
...updateData,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(forms.id, id))
|
||||
.returning();
|
||||
|
||||
if (!updatedForm) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to update form",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.insert(activityLogs).values({
|
||||
studyId: existingForm.studyId,
|
||||
userId: ctx.session.user.id,
|
||||
action: "form_updated",
|
||||
description: `Updated form "${updatedForm.title}"`,
|
||||
resourceType: "form",
|
||||
resourceId: id,
|
||||
});
|
||||
|
||||
return updatedForm;
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.string().uuid() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const form = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, input.id),
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, form.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
await ctx.db.delete(forms).where(eq(forms.id, input.id));
|
||||
|
||||
await ctx.db.insert(activityLogs).values({
|
||||
studyId: form.studyId,
|
||||
userId: ctx.session.user.id,
|
||||
action: "form_deleted",
|
||||
description: `Deleted form "${form.title}"`,
|
||||
resourceType: "form",
|
||||
resourceId: input.id,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
setActive: protectedProcedure
|
||||
.input(z.object({ id: z.string().uuid() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const form = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, input.id),
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, form.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
await ctx.db
|
||||
.update(forms)
|
||||
.set({ active: false })
|
||||
.where(eq(forms.studyId, form.studyId));
|
||||
|
||||
const [updatedForm] = await ctx.db
|
||||
.update(forms)
|
||||
.set({ active: true })
|
||||
.where(eq(forms.id, input.id))
|
||||
.returning();
|
||||
|
||||
return updatedForm;
|
||||
}),
|
||||
|
||||
createVersion: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string().uuid(),
|
||||
title: z.string().min(1).max(255).optional(),
|
||||
description: z.string().optional(),
|
||||
fields: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
label: z.string(),
|
||||
required: z.boolean().default(false),
|
||||
options: z.array(z.string()).optional(),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
}),
|
||||
),
|
||||
settings: z.record(z.string(), z.any()).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...updateData } = input;
|
||||
|
||||
const existingForm = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, id),
|
||||
});
|
||||
|
||||
if (!existingForm) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, existingForm.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
const latestForm = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.studyId, existingForm.studyId),
|
||||
orderBy: [desc(forms.version)],
|
||||
});
|
||||
const newVersion = (latestForm?.version ?? 0) + 1;
|
||||
|
||||
const [newForm] = await ctx.db
|
||||
.insert(forms)
|
||||
.values({
|
||||
studyId: existingForm.studyId,
|
||||
type: existingForm.type,
|
||||
title: updateData.title ?? existingForm.title,
|
||||
description: updateData.description ?? existingForm.description,
|
||||
fields: updateData.fields ?? existingForm.fields,
|
||||
settings: updateData.settings ?? existingForm.settings,
|
||||
version: newVersion,
|
||||
active: false,
|
||||
createdBy: ctx.session.user.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!newForm) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to create form version",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.insert(activityLogs).values({
|
||||
studyId: existingForm.studyId,
|
||||
userId: ctx.session.user.id,
|
||||
action: "form_version_created",
|
||||
description: `Created version ${newVersion} of form "${newForm.title}"`,
|
||||
resourceType: "form",
|
||||
resourceId: newForm.id,
|
||||
});
|
||||
|
||||
return newForm;
|
||||
}),
|
||||
|
||||
getResponses: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
formId: z.string().uuid(),
|
||||
page: z.number().min(1).default(1),
|
||||
limit: z.number().min(1).max(100).default(20),
|
||||
status: z.enum(["pending", "completed", "rejected"]).optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { formId, page, limit, status } = input;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const form = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, formId),
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, form.studyId);
|
||||
|
||||
const conditions = [eq(formResponses.formId, formId)];
|
||||
if (status) {
|
||||
conditions.push(eq(formResponses.status, status));
|
||||
}
|
||||
|
||||
const [responses, totalCount] = await Promise.all([
|
||||
ctx.db.query.formResponses.findMany({
|
||||
where: and(...conditions),
|
||||
with: {
|
||||
participant: {
|
||||
columns: {
|
||||
id: true,
|
||||
participantCode: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [desc(formResponses.submittedAt)],
|
||||
limit,
|
||||
offset,
|
||||
}),
|
||||
ctx.db
|
||||
.select({ count: count() })
|
||||
.from(formResponses)
|
||||
.where(and(...conditions)),
|
||||
]);
|
||||
|
||||
return {
|
||||
responses,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: totalCount[0]?.count ?? 0,
|
||||
pages: Math.ceil((totalCount[0]?.count ?? 0) / limit),
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
submitResponse: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
formId: z.string().uuid(),
|
||||
participantId: z.string().uuid(),
|
||||
responses: z.record(z.string(), z.any()),
|
||||
signatureData: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { formId, participantId, responses, signatureData } = input;
|
||||
|
||||
const form = await ctx.db.query.forms.findFirst({
|
||||
where: eq(forms.id, formId),
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, form.studyId);
|
||||
|
||||
const existingResponse = await ctx.db.query.formResponses.findFirst({
|
||||
where: and(
|
||||
eq(formResponses.formId, formId),
|
||||
eq(formResponses.participantId, participantId),
|
||||
),
|
||||
});
|
||||
|
||||
if (existingResponse) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Participant has already submitted this form",
|
||||
});
|
||||
}
|
||||
|
||||
const [newResponse] = await ctx.db
|
||||
.insert(formResponses)
|
||||
.values({
|
||||
formId,
|
||||
participantId,
|
||||
responses,
|
||||
signatureData,
|
||||
status: signatureData ? "completed" : "pending",
|
||||
signedAt: signatureData ? new Date() : null,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return newResponse;
|
||||
}),
|
||||
|
||||
listVersions: protectedProcedure
|
||||
.input(z.object({ studyId: z.string().uuid() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, input.studyId);
|
||||
|
||||
const formsList = await ctx.db.query.forms.findMany({
|
||||
where: eq(forms.studyId, input.studyId),
|
||||
with: {
|
||||
createdBy: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [desc(forms.version)],
|
||||
});
|
||||
|
||||
const formsWithCounts = await Promise.all(
|
||||
formsList.map(async (form) => {
|
||||
const responseCount = await ctx.db
|
||||
.select({ count: count() })
|
||||
.from(formResponses)
|
||||
.where(eq(formResponses.formId, form.id));
|
||||
return { ...form, _count: { responses: responseCount[0]?.count ?? 0 } };
|
||||
})
|
||||
);
|
||||
|
||||
return formsWithCounts;
|
||||
}),
|
||||
|
||||
listTemplates: protectedProcedure
|
||||
.query(async ({ ctx }) => {
|
||||
const templates = await ctx.db.query.forms.findMany({
|
||||
where: eq(forms.isTemplate, true),
|
||||
orderBy: [desc(forms.updatedAt)],
|
||||
});
|
||||
|
||||
return templates;
|
||||
}),
|
||||
|
||||
createFromTemplate: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string().uuid(),
|
||||
templateId: z.string().uuid(),
|
||||
title: z.string().min(1).max(255).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await checkStudyAccess(ctx.db, ctx.session.user.id, input.studyId, [
|
||||
"owner",
|
||||
"researcher",
|
||||
]);
|
||||
|
||||
const template = await ctx.db.query.forms.findFirst({
|
||||
where: and(
|
||||
eq(forms.id, input.templateId),
|
||||
eq(forms.isTemplate, true),
|
||||
),
|
||||
});
|
||||
|
||||
if (!template) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Template not found",
|
||||
});
|
||||
}
|
||||
|
||||
const [newForm] = await ctx.db
|
||||
.insert(forms)
|
||||
.values({
|
||||
studyId: input.studyId,
|
||||
type: template.type,
|
||||
title: input.title ?? `${template.title} (Copy)`,
|
||||
description: template.description,
|
||||
fields: template.fields,
|
||||
settings: template.settings,
|
||||
isTemplate: false,
|
||||
createdBy: ctx.session.user.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!newForm) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to create form from template",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.insert(activityLogs).values({
|
||||
studyId: input.studyId,
|
||||
userId: ctx.session.user.id,
|
||||
action: "form_created_from_template",
|
||||
description: `Created form "${newForm.title}" from template "${template.title}"`,
|
||||
resourceType: "form",
|
||||
resourceId: newForm.id,
|
||||
});
|
||||
|
||||
return newForm;
|
||||
}),
|
||||
});
|
||||
235
src/server/api/routers/plugins.ts
Normal file
235
src/server/api/routers/plugins.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, desc, eq, type SQL } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import {
|
||||
pluginStatusEnum,
|
||||
plugins,
|
||||
studyMembers,
|
||||
studyPlugins,
|
||||
} from "~/server/db/schema";
|
||||
|
||||
export const pluginsRouter = createTRPCRouter({
|
||||
list: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
robotId: z.string().optional(),
|
||||
status: z.enum(pluginStatusEnum.enumValues).optional(),
|
||||
limit: z.number().min(1).max(100).default(50),
|
||||
offset: z.number().min(0).default(0),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const conditions: SQL[] = [];
|
||||
|
||||
if (input.robotId) {
|
||||
conditions.push(eq(plugins.robotId, input.robotId));
|
||||
}
|
||||
|
||||
if (input.status) {
|
||||
conditions.push(eq(plugins.status, input.status));
|
||||
}
|
||||
|
||||
const query = ctx.db
|
||||
.select({
|
||||
id: plugins.id,
|
||||
robotId: plugins.robotId,
|
||||
name: plugins.name,
|
||||
version: plugins.version,
|
||||
description: plugins.description,
|
||||
author: plugins.author,
|
||||
repositoryUrl: plugins.repositoryUrl,
|
||||
trustLevel: plugins.trustLevel,
|
||||
status: plugins.status,
|
||||
createdAt: plugins.createdAt,
|
||||
updatedAt: plugins.updatedAt,
|
||||
metadata: plugins.metadata,
|
||||
})
|
||||
.from(plugins);
|
||||
|
||||
const results = await (
|
||||
conditions.length > 0 ? query.where(and(...conditions)) : query
|
||||
)
|
||||
.orderBy(desc(plugins.updatedAt))
|
||||
.limit(input.limit)
|
||||
.offset(input.offset);
|
||||
|
||||
return results;
|
||||
}),
|
||||
|
||||
get: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const pluginResults = await ctx.db
|
||||
.select()
|
||||
.from(plugins)
|
||||
.where(eq(plugins.id, input.id))
|
||||
.limit(1);
|
||||
|
||||
const plugin = pluginResults[0];
|
||||
|
||||
if (!plugin) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Plugin not found",
|
||||
});
|
||||
}
|
||||
|
||||
return plugin;
|
||||
}),
|
||||
|
||||
install: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string(),
|
||||
pluginId: z.string(),
|
||||
configuration: z.any().optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Check if user has appropriate access
|
||||
const membership = await ctx.db.query.studyMembers.findFirst({
|
||||
where: and(
|
||||
eq(studyMembers.studyId, input.studyId),
|
||||
eq(studyMembers.userId, userId),
|
||||
),
|
||||
});
|
||||
|
||||
if (!membership || !["owner", "researcher"].includes(membership.role)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Insufficient permissions to install plugins",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if plugin exists
|
||||
const plugin = await ctx.db
|
||||
.select()
|
||||
.from(plugins)
|
||||
.where(eq(plugins.id, input.pluginId))
|
||||
.limit(1);
|
||||
|
||||
if (!plugin[0]) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Plugin not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if plugin is already installed
|
||||
const existing = await ctx.db
|
||||
.select()
|
||||
.from(studyPlugins)
|
||||
.where(
|
||||
and(
|
||||
eq(studyPlugins.studyId, input.studyId),
|
||||
eq(studyPlugins.pluginId, input.pluginId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (existing[0]) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Plugin already installed for this study",
|
||||
});
|
||||
}
|
||||
|
||||
const installations = await ctx.db
|
||||
.insert(studyPlugins)
|
||||
.values({
|
||||
studyId: input.studyId,
|
||||
pluginId: input.pluginId,
|
||||
configuration: input.configuration ?? {},
|
||||
installedBy: userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const installation = installations[0];
|
||||
if (!installation) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to install plugin",
|
||||
});
|
||||
}
|
||||
|
||||
return installation;
|
||||
}),
|
||||
|
||||
uninstall: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string(),
|
||||
pluginId: z.string(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Check if user has appropriate access
|
||||
const membership = await ctx.db.query.studyMembers.findFirst({
|
||||
where: and(
|
||||
eq(studyMembers.studyId, input.studyId),
|
||||
eq(studyMembers.userId, userId),
|
||||
),
|
||||
});
|
||||
|
||||
if (!membership || !["owner", "researcher"].includes(membership.role)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Insufficient permissions to uninstall plugins",
|
||||
});
|
||||
}
|
||||
|
||||
const result = await ctx.db
|
||||
.delete(studyPlugins)
|
||||
.where(
|
||||
and(
|
||||
eq(studyPlugins.studyId, input.studyId),
|
||||
eq(studyPlugins.pluginId, input.pluginId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
|
||||
if (!result[0]) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Plugin installation not found",
|
||||
});
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
getActions: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
pluginId: z.string(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const plugin = await ctx.db
|
||||
.select({
|
||||
id: plugins.id,
|
||||
actionDefinitions: plugins.actionDefinitions,
|
||||
})
|
||||
.from(plugins)
|
||||
.where(eq(plugins.id, input.pluginId))
|
||||
.limit(1);
|
||||
|
||||
if (!plugin[0]) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Plugin not found",
|
||||
});
|
||||
}
|
||||
|
||||
return plugin[0].actionDefinitions ?? [];
|
||||
}),
|
||||
});
|
||||
@@ -841,6 +841,63 @@ export const studiesRouter = createTRPCRouter({
|
||||
};
|
||||
}),
|
||||
|
||||
getStudyPlugins: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
studyId: z.string().uuid(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { studyId } = input;
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Check if user has access to this study (any role)
|
||||
const membership = await ctx.db.query.studyMembers.findFirst({
|
||||
where: and(
|
||||
eq(studyMembers.studyId, studyId),
|
||||
eq(studyMembers.userId, userId),
|
||||
),
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have access to this study",
|
||||
});
|
||||
}
|
||||
|
||||
const installedPlugins = await ctx.db
|
||||
.select({
|
||||
plugin: {
|
||||
id: plugins.id,
|
||||
robotId: plugins.robotId,
|
||||
name: plugins.name,
|
||||
version: plugins.version,
|
||||
description: plugins.description,
|
||||
author: plugins.author,
|
||||
repositoryUrl: plugins.repositoryUrl,
|
||||
trustLevel: plugins.trustLevel,
|
||||
status: plugins.status,
|
||||
actionDefinitions: plugins.actionDefinitions,
|
||||
createdAt: plugins.createdAt,
|
||||
updatedAt: plugins.updatedAt,
|
||||
metadata: plugins.metadata,
|
||||
},
|
||||
installation: {
|
||||
id: studyPlugins.id,
|
||||
configuration: studyPlugins.configuration,
|
||||
installedAt: studyPlugins.installedAt,
|
||||
installedBy: studyPlugins.installedBy,
|
||||
},
|
||||
})
|
||||
.from(studyPlugins)
|
||||
.innerJoin(plugins, eq(studyPlugins.pluginId, plugins.id))
|
||||
.where(eq(studyPlugins.studyId, studyId))
|
||||
.orderBy(desc(studyPlugins.installedAt));
|
||||
|
||||
return installedPlugins;
|
||||
}),
|
||||
|
||||
// Plugin configuration management
|
||||
getPluginConfiguration: protectedProcedure
|
||||
.input(
|
||||
@@ -944,4 +1001,20 @@ export const studiesRouter = createTRPCRouter({
|
||||
|
||||
return updatedPlugin;
|
||||
}),
|
||||
|
||||
getMyMemberships: protectedProcedure.query(async ({ ctx }) => {
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
const memberships = await ctx.db.query.studyMembers.findMany({
|
||||
where: eq(studyMembers.userId, userId),
|
||||
columns: {
|
||||
studyId: true,
|
||||
role: true,
|
||||
joinedAt: true,
|
||||
},
|
||||
orderBy: [desc(studyMembers.joinedAt)],
|
||||
});
|
||||
|
||||
return memberships;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -35,6 +35,7 @@ import { GetObjectCommand } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { env } from "~/env";
|
||||
import { uploadFile } from "~/lib/storage/minio";
|
||||
import { wsManager } from "~/server/services/websocket-manager";
|
||||
|
||||
// Helper function to check if user has access to trial
|
||||
async function checkTrialAccess(
|
||||
@@ -591,6 +592,16 @@ export const trialsRouter = createTRPCRouter({
|
||||
data: { userId },
|
||||
});
|
||||
|
||||
// Broadcast trial status update
|
||||
await wsManager.broadcast(input.id, {
|
||||
type: "trial_status",
|
||||
data: {
|
||||
trial: trial[0],
|
||||
current_step_index: 0,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return trial[0];
|
||||
}),
|
||||
|
||||
@@ -643,6 +654,16 @@ export const trialsRouter = createTRPCRouter({
|
||||
data: { userId, notes: input.notes },
|
||||
});
|
||||
|
||||
// Broadcast trial status update
|
||||
await wsManager.broadcast(input.id, {
|
||||
type: "trial_status",
|
||||
data: {
|
||||
trial,
|
||||
current_step_index: 0,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return trial;
|
||||
}),
|
||||
|
||||
@@ -696,6 +717,16 @@ export const trialsRouter = createTRPCRouter({
|
||||
data: { userId, reason: input.reason },
|
||||
});
|
||||
|
||||
// Broadcast trial status update
|
||||
await wsManager.broadcast(input.id, {
|
||||
type: "trial_status",
|
||||
data: {
|
||||
trial: trial[0],
|
||||
current_step_index: 0,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return trial[0];
|
||||
}),
|
||||
|
||||
@@ -846,6 +877,15 @@ export const trialsRouter = createTRPCRouter({
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Broadcast new event to all subscribers
|
||||
await wsManager.broadcast(input.trialId, {
|
||||
type: "trial_event",
|
||||
data: {
|
||||
event,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return event;
|
||||
}),
|
||||
|
||||
@@ -881,6 +921,15 @@ export const trialsRouter = createTRPCRouter({
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Broadcast intervention to all subscribers
|
||||
await wsManager.broadcast(input.trialId, {
|
||||
type: "intervention_logged",
|
||||
data: {
|
||||
intervention,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return intervention;
|
||||
}),
|
||||
|
||||
@@ -936,6 +985,15 @@ export const trialsRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
// Broadcast annotation to all subscribers
|
||||
await wsManager.broadcast(input.trialId, {
|
||||
type: "annotation_added",
|
||||
data: {
|
||||
annotation,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return annotation;
|
||||
}),
|
||||
|
||||
@@ -1302,10 +1360,12 @@ export const trialsRouter = createTRPCRouter({
|
||||
}
|
||||
|
||||
// Log the manual robot action execution
|
||||
await db.insert(trialEvents).values({
|
||||
const [event] = await db
|
||||
.insert(trialEvents)
|
||||
.values({
|
||||
trialId: input.trialId,
|
||||
eventType: "manual_robot_action",
|
||||
actionId: null, // Ad-hoc action, not linked to a protocol action definition
|
||||
actionId: null,
|
||||
data: {
|
||||
userId,
|
||||
pluginName: input.pluginName,
|
||||
@@ -1316,6 +1376,17 @@ export const trialsRouter = createTRPCRouter({
|
||||
},
|
||||
timestamp: new Date(),
|
||||
createdBy: userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Broadcast robot action to all subscribers
|
||||
await wsManager.broadcast(input.trialId, {
|
||||
type: "trial_action_executed",
|
||||
data: {
|
||||
action_type: `${input.pluginName}.${input.actionId}`,
|
||||
event,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -1347,7 +1418,9 @@ export const trialsRouter = createTRPCRouter({
|
||||
"wizard",
|
||||
]);
|
||||
|
||||
await db.insert(trialEvents).values({
|
||||
const [event] = await db
|
||||
.insert(trialEvents)
|
||||
.values({
|
||||
trialId: input.trialId,
|
||||
eventType: "manual_robot_action",
|
||||
data: {
|
||||
@@ -1362,6 +1435,17 @@ export const trialsRouter = createTRPCRouter({
|
||||
},
|
||||
timestamp: new Date(),
|
||||
createdBy: userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Broadcast robot action to all subscribers
|
||||
await wsManager.broadcast(input.trialId, {
|
||||
type: "trial_action_executed",
|
||||
data: {
|
||||
action_type: `${input.pluginName}.${input.actionId}`,
|
||||
event,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
|
||||
@@ -68,6 +68,29 @@ export const stepTypeEnum = pgEnum("step_type", [
|
||||
"conditional",
|
||||
]);
|
||||
|
||||
export const formTypeEnum = pgEnum("form_type", [
|
||||
"consent",
|
||||
"survey",
|
||||
"questionnaire",
|
||||
]);
|
||||
|
||||
export const formFieldTypeEnum = pgEnum("form_field_type", [
|
||||
"text",
|
||||
"textarea",
|
||||
"multiple_choice",
|
||||
"checkbox",
|
||||
"rating",
|
||||
"yes_no",
|
||||
"date",
|
||||
"signature",
|
||||
]);
|
||||
|
||||
export const formResponseStatusEnum = pgEnum("form_response_status", [
|
||||
"pending",
|
||||
"completed",
|
||||
"rejected",
|
||||
]);
|
||||
|
||||
export const communicationProtocolEnum = pgEnum("communication_protocol", [
|
||||
"rest",
|
||||
"ros2",
|
||||
@@ -485,6 +508,25 @@ export const trials = createTable("trial", {
|
||||
metadata: jsonb("metadata").default({}),
|
||||
});
|
||||
|
||||
export const wsConnections = createTable("ws_connection", {
|
||||
id: uuid("id").notNull().primaryKey().defaultRandom(),
|
||||
trialId: uuid("trial_id")
|
||||
.notNull()
|
||||
.references(() => trials.id, { onDelete: "cascade" }),
|
||||
clientId: text("client_id").notNull().unique(),
|
||||
userId: text("user_id"),
|
||||
connectedAt: timestamp("connected_at", { withTimezone: true })
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
});
|
||||
|
||||
export const wsConnectionsRelations = relations(wsConnections, ({ one }) => ({
|
||||
trial: one(trials, {
|
||||
fields: [wsConnections.trialId],
|
||||
references: [trials.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const steps = createTable(
|
||||
"step",
|
||||
{
|
||||
@@ -575,6 +617,66 @@ export const consentForms = createTable(
|
||||
}),
|
||||
);
|
||||
|
||||
// New unified forms table
|
||||
export const forms = createTable(
|
||||
"form",
|
||||
{
|
||||
id: uuid("id").notNull().primaryKey().defaultRandom(),
|
||||
studyId: uuid("study_id")
|
||||
.notNull()
|
||||
.references(() => studies.id, { onDelete: "cascade" }),
|
||||
type: formTypeEnum("type").notNull(),
|
||||
title: varchar("title", { length: 255 }).notNull(),
|
||||
description: text("description"),
|
||||
version: integer("version").default(1).notNull(),
|
||||
active: boolean("active").default(true).notNull(),
|
||||
isTemplate: boolean("is_template").default(false).notNull(),
|
||||
templateName: varchar("template_name", { length: 100 }),
|
||||
fields: jsonb("fields").notNull().default([]),
|
||||
settings: jsonb("settings").default({}),
|
||||
createdBy: text("created_by")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
},
|
||||
(table) => ({
|
||||
studyVersionUnique: unique().on(table.studyId, table.version),
|
||||
}),
|
||||
);
|
||||
|
||||
// Form responses/submissions
|
||||
export const formResponses = createTable(
|
||||
"form_response",
|
||||
{
|
||||
id: uuid("id").notNull().primaryKey().defaultRandom(),
|
||||
formId: uuid("form_id")
|
||||
.notNull()
|
||||
.references(() => forms.id, { onDelete: "cascade" }),
|
||||
participantId: uuid("participant_id")
|
||||
.notNull()
|
||||
.references(() => participants.id, { onDelete: "cascade" }),
|
||||
responses: jsonb("responses").notNull().default({}),
|
||||
status: formResponseStatusEnum("status").default("pending"),
|
||||
signatureData: text("signature_data"),
|
||||
signedAt: timestamp("signed_at", { withTimezone: true }),
|
||||
ipAddress: inet("ip_address"),
|
||||
submittedAt: timestamp("submitted_at", { withTimezone: true })
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
},
|
||||
(table) => ({
|
||||
formParticipantUnique: unique().on(table.formId, table.participantId),
|
||||
}),
|
||||
);
|
||||
|
||||
export const participantConsents = createTable(
|
||||
"participant_consent",
|
||||
{
|
||||
@@ -1099,6 +1201,29 @@ export const participantConsentsRelations = relations(
|
||||
}),
|
||||
);
|
||||
|
||||
export const formsRelations = relations(forms, ({ one, many }) => ({
|
||||
study: one(studies, {
|
||||
fields: [forms.studyId],
|
||||
references: [studies.id],
|
||||
}),
|
||||
createdBy: one(users, {
|
||||
fields: [forms.createdBy],
|
||||
references: [users.id],
|
||||
}),
|
||||
responses: many(formResponses),
|
||||
}));
|
||||
|
||||
export const formResponsesRelations = relations(formResponses, ({ one }) => ({
|
||||
form: one(forms, {
|
||||
fields: [formResponses.formId],
|
||||
references: [forms.id],
|
||||
}),
|
||||
participant: one(participants, {
|
||||
fields: [formResponses.participantId],
|
||||
references: [participants.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const robotsRelations = relations(robots, ({ many }) => ({
|
||||
experiments: many(experiments),
|
||||
plugins: many(plugins),
|
||||
|
||||
272
src/server/services/websocket-manager.ts
Normal file
272
src/server/services/websocket-manager.ts
Normal file
@@ -0,0 +1,272 @@
|
||||
import { db } from "~/server/db";
|
||||
import {
|
||||
trials,
|
||||
trialEvents,
|
||||
wsConnections,
|
||||
experiments,
|
||||
} from "~/server/db/schema";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
|
||||
interface ClientConnection {
|
||||
socket: WebSocket;
|
||||
trialId: string;
|
||||
userId: string | null;
|
||||
connectedAt: number;
|
||||
}
|
||||
|
||||
type OutgoingMessage = {
|
||||
type: string;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
|
||||
class WebSocketManager {
|
||||
private clients: Map<string, ClientConnection> = new Map();
|
||||
private heartbeatIntervals: Map<string, ReturnType<typeof setInterval>> =
|
||||
new Map();
|
||||
|
||||
private getTrialRoomClients(trialId: string): ClientConnection[] {
|
||||
const clients: ClientConnection[] = [];
|
||||
for (const [, client] of this.clients) {
|
||||
if (client.trialId === trialId) {
|
||||
clients.push(client);
|
||||
}
|
||||
}
|
||||
return clients;
|
||||
}
|
||||
|
||||
addClient(clientId: string, connection: ClientConnection): void {
|
||||
this.clients.set(clientId, connection);
|
||||
console.log(
|
||||
`[WS] Client ${clientId} added for trial ${connection.trialId}. Total: ${this.clients.size}`,
|
||||
);
|
||||
}
|
||||
|
||||
removeClient(clientId: string): void {
|
||||
const client = this.clients.get(clientId);
|
||||
if (client) {
|
||||
console.log(
|
||||
`[WS] Client ${clientId} removed from trial ${client.trialId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const heartbeatInterval = this.heartbeatIntervals.get(clientId);
|
||||
if (heartbeatInterval) {
|
||||
clearInterval(heartbeatInterval);
|
||||
this.heartbeatIntervals.delete(clientId);
|
||||
}
|
||||
|
||||
this.clients.delete(clientId);
|
||||
}
|
||||
|
||||
async subscribe(
|
||||
clientId: string,
|
||||
socket: WebSocket,
|
||||
trialId: string,
|
||||
userId: string | null,
|
||||
): Promise<void> {
|
||||
const client: ClientConnection = {
|
||||
socket,
|
||||
trialId,
|
||||
userId,
|
||||
connectedAt: Date.now(),
|
||||
};
|
||||
|
||||
this.clients.set(clientId, client);
|
||||
|
||||
const heartbeatInterval = setInterval(() => {
|
||||
this.sendToClient(clientId, { type: "heartbeat", data: {} });
|
||||
}, 30000);
|
||||
|
||||
this.heartbeatIntervals.set(clientId, heartbeatInterval);
|
||||
|
||||
console.log(
|
||||
`[WS] Client ${clientId} subscribed to trial ${trialId}. Total clients: ${this.clients.size}`,
|
||||
);
|
||||
}
|
||||
|
||||
unsubscribe(clientId: string): void {
|
||||
const client = this.clients.get(clientId);
|
||||
if (client) {
|
||||
console.log(
|
||||
`[WS] Client ${clientId} unsubscribed from trial ${client.trialId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const heartbeatInterval = this.heartbeatIntervals.get(clientId);
|
||||
if (heartbeatInterval) {
|
||||
clearInterval(heartbeatInterval);
|
||||
this.heartbeatIntervals.delete(clientId);
|
||||
}
|
||||
|
||||
this.clients.delete(clientId);
|
||||
}
|
||||
|
||||
sendToClient(clientId: string, message: OutgoingMessage): void {
|
||||
const client = this.clients.get(clientId);
|
||||
if (client?.socket.readyState === 1) {
|
||||
try {
|
||||
client.socket.send(JSON.stringify(message));
|
||||
} catch (error) {
|
||||
console.error(`[WS] Error sending to client ${clientId}:`, error);
|
||||
this.unsubscribe(clientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async broadcast(trialId: string, message: OutgoingMessage): Promise<void> {
|
||||
const clients = this.getTrialRoomClients(trialId);
|
||||
|
||||
if (clients.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const messageStr = JSON.stringify(message);
|
||||
const disconnectedClients: string[] = [];
|
||||
|
||||
for (const [clientId, client] of this.clients) {
|
||||
if (client.trialId === trialId && client.socket.readyState === 1) {
|
||||
try {
|
||||
client.socket.send(messageStr);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[WS] Error broadcasting to client ${clientId}:`,
|
||||
error,
|
||||
);
|
||||
disconnectedClients.push(clientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const clientId of disconnectedClients) {
|
||||
this.unsubscribe(clientId);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[WS] Broadcast to ${clients.length} clients for trial ${trialId}: ${message.type}`,
|
||||
);
|
||||
}
|
||||
|
||||
async broadcastToAll(message: OutgoingMessage): Promise<void> {
|
||||
const messageStr = JSON.stringify(message);
|
||||
const disconnectedClients: string[] = [];
|
||||
|
||||
for (const [clientId, client] of this.clients) {
|
||||
if (client.socket.readyState === 1) {
|
||||
try {
|
||||
client.socket.send(messageStr);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[WS] Error broadcasting to client ${clientId}:`,
|
||||
error,
|
||||
);
|
||||
disconnectedClients.push(clientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const clientId of disconnectedClients) {
|
||||
this.unsubscribe(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
async getTrialStatus(trialId: string): Promise<{
|
||||
trial: {
|
||||
id: string;
|
||||
status: string;
|
||||
startedAt: Date | null;
|
||||
completedAt: Date | null;
|
||||
};
|
||||
currentStepIndex: number;
|
||||
} | null> {
|
||||
const [trial] = await db
|
||||
.select({
|
||||
id: trials.id,
|
||||
status: trials.status,
|
||||
startedAt: trials.startedAt,
|
||||
completedAt: trials.completedAt,
|
||||
})
|
||||
.from(trials)
|
||||
.where(eq(trials.id, trialId))
|
||||
.limit(1);
|
||||
|
||||
if (!trial) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
trial: {
|
||||
id: trial.id,
|
||||
status: trial.status,
|
||||
startedAt: trial.startedAt,
|
||||
completedAt: trial.completedAt,
|
||||
},
|
||||
currentStepIndex: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async getTrialEvents(
|
||||
trialId: string,
|
||||
limit: number = 100,
|
||||
): Promise<unknown[]> {
|
||||
const events = await db
|
||||
.select()
|
||||
.from(trialEvents)
|
||||
.where(eq(trialEvents.trialId, trialId))
|
||||
.orderBy(trialEvents.timestamp)
|
||||
.limit(limit);
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
getTrialStatusSync(trialId: string): {
|
||||
trial: {
|
||||
id: string;
|
||||
status: string;
|
||||
startedAt: Date | null;
|
||||
completedAt: Date | null;
|
||||
};
|
||||
currentStepIndex: number;
|
||||
} | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
getTrialEventsSync(trialId: string, limit: number = 100): unknown[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
getConnectionCount(trialId?: string): number {
|
||||
if (trialId) {
|
||||
return this.getTrialRoomClients(trialId).length;
|
||||
}
|
||||
return this.clients.size;
|
||||
}
|
||||
|
||||
getConnectedTrialIds(): string[] {
|
||||
const trialIds = new Set<string>();
|
||||
for (const [, client] of this.clients) {
|
||||
trialIds.add(client.trialId);
|
||||
}
|
||||
return Array.from(trialIds);
|
||||
}
|
||||
|
||||
async getTrialsWithActiveConnections(studyIds?: string[]): Promise<string[]> {
|
||||
const conditions =
|
||||
studyIds && studyIds.length > 0
|
||||
? sql`${wsConnections.trialId} IN (
|
||||
SELECT ${trials.id} FROM ${trials}
|
||||
WHERE ${trials.experimentId} IN (
|
||||
SELECT ${experiments.id} FROM ${experiments}
|
||||
WHERE ${experiments.studyId} IN (${sql.raw(studyIds.map((id) => `'${id}'`).join(","))})
|
||||
)
|
||||
)`
|
||||
: undefined;
|
||||
|
||||
const connections = await db
|
||||
.selectDistinct({ trialId: wsConnections.trialId })
|
||||
.from(wsConnections);
|
||||
|
||||
return connections.map((c) => c.trialId);
|
||||
}
|
||||
}
|
||||
|
||||
export const wsManager = new WebSocketManager();
|
||||
@@ -7,6 +7,7 @@
|
||||
@theme {
|
||||
--font-sans: var(--font-sans), ui-sans-serif, system-ui, sans-serif,
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -14,6 +15,7 @@
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
@@ -84,48 +86,49 @@
|
||||
}
|
||||
|
||||
:root {
|
||||
/* Light Mode (Inverted: White BG, gray Cards) */
|
||||
--radius: 0.5rem;
|
||||
--background: hsl(0 0% 100%);
|
||||
/* Pure White Background */
|
||||
/* Light Mode - Teal/Cyan Sci-Fi Theme */
|
||||
--radius: 0.75rem;
|
||||
/* More rounded */
|
||||
--background: hsl(190 40% 98%);
|
||||
/* Very Light Cyan Background */
|
||||
--foreground: hsl(240 10% 3.9%);
|
||||
--card: hsl(240 4.8% 95.9%);
|
||||
/* Light Gray Card */
|
||||
--card: hsl(180 20% 97%);
|
||||
/* Light Teal Card */
|
||||
--card-foreground: hsl(240 10% 3.9%);
|
||||
--popover: hsl(0 0% 100%);
|
||||
--popover-foreground: hsl(240 10% 3.9%);
|
||||
--primary: hsl(221.2 83.2% 53.3%);
|
||||
/* Indigo-600 */
|
||||
--primary-foreground: hsl(210 40% 98%);
|
||||
--secondary: hsl(210 40% 96.1%);
|
||||
--secondary-foreground: hsl(222.2 47.4% 11.2%);
|
||||
--muted: hsl(210 40% 96.1%);
|
||||
--muted-foreground: hsl(215.4 16.3% 46.9%);
|
||||
--accent: hsl(210 40% 96.1%);
|
||||
--accent-foreground: hsl(222.2 47.4% 11.2%);
|
||||
/* Teal Primary - Robot/Sci-fi feel */
|
||||
--primary: hsl(173 80% 40%);
|
||||
/* Teal-500: #14b8a6 */
|
||||
--primary-foreground: hsl(180 50% 10%);
|
||||
/* Dark teal text on teal */
|
||||
--secondary: hsl(180 30% 92%);
|
||||
--secondary-foreground: hsl(173 60% 20%);
|
||||
--muted: hsl(180 20% 94%);
|
||||
--muted-foreground: hsl(180 10% 40%);
|
||||
--accent: hsl(180 40% 90%);
|
||||
--accent-foreground: hsl(173 60% 20%);
|
||||
/* Red for destructive, Cyan for highlights */
|
||||
--destructive: hsl(0 84.2% 60.2%);
|
||||
--destructive-foreground: hsl(210 40% 98%);
|
||||
--border: hsl(214.3 31.8% 91.4%);
|
||||
--input: hsl(214.3 31.8% 91.4%);
|
||||
--ring: hsl(221.2 83.2% 53.3%);
|
||||
--chart-1: hsl(221.2 83.2% 53.3%);
|
||||
--chart-2: hsl(173 58% 39%);
|
||||
--chart-3: hsl(197 37% 24%);
|
||||
--chart-4: hsl(43 74% 66%);
|
||||
--chart-5: hsl(27 87% 67%);
|
||||
--sidebar: hsl(240 4.8% 95.9%);
|
||||
/* Zinc-100: Distinct contrast against white BG */
|
||||
--destructive-foreground: hsl(0 0% 98%);
|
||||
--border: hsl(180 20% 80%);
|
||||
/* Slightly more visible border */
|
||||
--input: hsl(180 20% 80%);
|
||||
--ring: hsl(173 80% 40%);
|
||||
/* Chart colors - teal/cyan themed */
|
||||
--chart-1: hsl(173 80% 40%);
|
||||
--chart-2: hsl(190 80% 55%);
|
||||
--chart-3: hsl(200 70% 50%);
|
||||
--chart-4: hsl(160 70% 45%);
|
||||
--chart-5: hsl(210 70% 55%);
|
||||
--sidebar: hsl(180 15% 94%);
|
||||
--sidebar-foreground: hsl(240 10% 3.9%);
|
||||
/* Dark Text */
|
||||
--sidebar-primary: hsl(221.2 83.2% 53.3%);
|
||||
/* Indigo Accent */
|
||||
--sidebar-primary-foreground: hsl(0 0% 98%);
|
||||
--sidebar-accent: hsl(240 5.9% 90%);
|
||||
/* Zinc-200: Slightly darker for hover */
|
||||
--sidebar-accent-foreground: hsl(240 5.9% 10%);
|
||||
--sidebar-border: hsl(240 5.9% 90%);
|
||||
/* Zinc-200 Border */
|
||||
--sidebar-ring: hsl(217.2 91.2% 59.8%);
|
||||
--sidebar-primary: hsl(173 80% 40%);
|
||||
--sidebar-primary-foreground: hsl(180 50% 10%);
|
||||
--sidebar-accent: hsl(180 25% 88%);
|
||||
--sidebar-accent-foreground: hsl(173 60% 20%);
|
||||
--sidebar-border: hsl(180 20% 85%);
|
||||
--sidebar-ring: hsl(173 80% 50%);
|
||||
|
||||
--shadow-color: hsl(0 0% 0%);
|
||||
--shadow-opacity: 0;
|
||||
@@ -152,16 +155,43 @@
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: hsl(240 10% 3.9%);
|
||||
--foreground: hsl(0 0% 98%);
|
||||
/* Distinct Card Background for better contrast */
|
||||
--card: hsl(240 5% 9%);
|
||||
--card-foreground: hsl(0 0% 98%);
|
||||
--popover: hsl(240 5% 9%);
|
||||
--popover-foreground: hsl(0 0% 98%);
|
||||
--primary: hsl(0 0% 98%);
|
||||
--primary-foreground: hsl(240 5.9% 10%);
|
||||
--secondary: hsl(240 3.7% 15.9%);
|
||||
/* Dark Mode - Teal/Cyan Sci-Fi Theme */
|
||||
--background: hsl(200 20% 8%);
|
||||
/* Dark cyan/black */
|
||||
--foreground: hsl(180 20% 95%);
|
||||
/* Light cyan text */
|
||||
--card: hsl(200 15% 12%);
|
||||
/* Slightly lighter card */
|
||||
--card-foreground: hsl(180 20% 95%);
|
||||
--popover: hsl(200 15% 10%);
|
||||
--popover-foreground: hsl(180 20% 95%);
|
||||
--primary: hsl(173 80% 45%);
|
||||
/* Teal-500: brighter in dark */
|
||||
--primary-foreground: hsl(180 50% 10%);
|
||||
--secondary: hsl(200 15% 15%);
|
||||
--secondary-foreground: hsl(180 20% 90%);
|
||||
--muted: hsl(200 15% 15%);
|
||||
--muted-foreground: hsl(180 10% 60%);
|
||||
--accent: hsl(173 60% 25%);
|
||||
--accent-foreground: hsl(180 20% 95%);
|
||||
--destructive: hsl(0 70% 55%);
|
||||
--destructive-foreground: hsl(0 0% 100%);
|
||||
--border: hsl(200 15% 20%);
|
||||
--input: hsl(200 15% 20%);
|
||||
--ring: hsl(173 80% 45%);
|
||||
--chart-1: hsl(173 75% 50%);
|
||||
--chart-2: hsl(180 70% 60%);
|
||||
--chart-3: hsl(190 65% 55%);
|
||||
--chart-4: hsl(160 60% 50%);
|
||||
--chart-5: hsl(200 60% 55%);
|
||||
--sidebar: hsl(200 15% 10%);
|
||||
--sidebar-foreground: hsl(180 20% 90%);
|
||||
--sidebar-primary: hsl(173 80% 45%);
|
||||
--sidebar-primary-foreground: hsl(180 50% 10%);
|
||||
--sidebar-accent: hsl(200 15% 18%);
|
||||
--sidebar-accent-foreground: hsl(180 20% 90%);
|
||||
--sidebar-border: hsl(200 15% 18%);
|
||||
--sidebar-ring: hsl(173 80% 50%);
|
||||
--secondary-foreground: hsl(0 0% 98%);
|
||||
--muted: hsl(240 3.7% 15.9%);
|
||||
--muted-foreground: hsl(240 5% 64.9%);
|
||||
@@ -188,64 +218,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
.dark {
|
||||
--background: hsl(240 10% 3.9%);
|
||||
--foreground: hsl(0 0% 98%);
|
||||
--card: hsl(240 5% 9%);
|
||||
--card-foreground: hsl(0 0% 98%);
|
||||
--popover: hsl(240 5% 9%);
|
||||
--popover-foreground: hsl(0 0% 98%);
|
||||
--primary: hsl(0 0% 98%);
|
||||
--primary-foreground: hsl(240 5.9% 10%);
|
||||
--secondary: hsl(240 3.7% 15.9%);
|
||||
--secondary-foreground: hsl(0 0% 98%);
|
||||
--muted: hsl(240 3.7% 15.9%);
|
||||
--muted-foreground: hsl(240 5% 64.9%);
|
||||
--accent: hsl(240 3.7% 15.9%);
|
||||
--accent-foreground: hsl(0 0% 98%);
|
||||
--destructive: hsl(0 62.8% 30.6%);
|
||||
--destructive-foreground: hsl(0 0% 98%);
|
||||
--border: hsl(240 3.7% 15.9%);
|
||||
--input: hsl(240 3.7% 15.9%);
|
||||
--ring: hsl(240 4.9% 83.9%);
|
||||
--chart-1: hsl(220 70% 50%);
|
||||
--chart-2: hsl(160 60% 45%);
|
||||
--chart-3: hsl(30 80% 55%);
|
||||
--chart-4: hsl(280 65% 60%);
|
||||
--chart-5: hsl(340 75% 55%);
|
||||
--sidebar: hsl(240 5.9% 10%);
|
||||
--sidebar-foreground: hsl(240 4.8% 95.9%);
|
||||
--sidebar-primary: hsl(224.3 76.3% 48%);
|
||||
--sidebar-primary-foreground: hsl(0 0% 100%);
|
||||
--sidebar-accent: hsl(240 3.7% 15.9%);
|
||||
--sidebar-accent-foreground: hsl(240 4.8% 95.9%);
|
||||
--sidebar-border: hsl(240 3.7% 15.9%);
|
||||
--sidebar-border: hsl(240 3.7% 15.9%);
|
||||
--sidebar-ring: hsl(217.2 91.2% 59.8%);
|
||||
|
||||
/* Validation Dark Mode */
|
||||
--validation-error-bg: hsl(0 75% 15%);
|
||||
/* Red 950-ish */
|
||||
--validation-error-text: hsl(0 100% 90%);
|
||||
/* Red 100 */
|
||||
--validation-error-border: hsl(0 50% 30%);
|
||||
/* Red 900 */
|
||||
--validation-warning-bg: hsl(30 90% 10%);
|
||||
/* Amber 950-ish */
|
||||
--validation-warning-text: hsl(30 100% 90%);
|
||||
/* Amber 100 */
|
||||
--validation-warning-border: hsl(30 60% 30%);
|
||||
/* Amber 900 */
|
||||
--validation-info-bg: hsl(210 50% 15%);
|
||||
/* Blue 950-ish */
|
||||
--validation-info-text: hsl(210 100% 90%);
|
||||
/* Blue 100 */
|
||||
--validation-info-border: hsl(210 40% 30%);
|
||||
/* Blue 900 */
|
||||
}
|
||||
}
|
||||
|
||||
:root {
|
||||
/* Validation Light Mode Defaults */
|
||||
--validation-error-bg: hsl(0 85% 97%);
|
||||
@@ -292,6 +264,76 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom Component Theming */
|
||||
@layer utilities {
|
||||
/* Chamfered corners - subtle sci-fi tech feel */
|
||||
.chamfer {
|
||||
clip-path: polygon(
|
||||
0.75rem, 0,
|
||||
100% 0,
|
||||
100% calc(100% - 0.75rem),
|
||||
calc(100% - 0.75rem) 100%,
|
||||
0 100%
|
||||
);
|
||||
}
|
||||
|
||||
/* Soft corners - very rounded */
|
||||
.rounded-chonk {
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
/* Card with subtle gradient */
|
||||
.card-teal {
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
hsl(var(--card) / 1) 0%,
|
||||
hsl(var(--card-hue, 180) var(--card-sat, 20%) var(--card-light, 95%) / 0.5) 100%
|
||||
);
|
||||
}
|
||||
|
||||
/* Glow effects for primary actions */
|
||||
.glow-teal {
|
||||
box-shadow: 0 0 20px hsl(var(--primary) / 0.3);
|
||||
}
|
||||
|
||||
.glow-teal:hover {
|
||||
box-shadow: 0 0 30px hsl(var(--primary) / 0.5);
|
||||
}
|
||||
|
||||
/* Subtle pulse animation for active states */
|
||||
@keyframes pulse-glow {
|
||||
0%, 100% {
|
||||
box-shadow: 0 0 10px hsl(var(--primary) / 0.2);
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 20px hsl(var(--primary) / 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-pulse-glow {
|
||||
animation: pulse-glow 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Italic/oblique text for labels */
|
||||
.font-slant {
|
||||
font-style: oblique 10deg;
|
||||
}
|
||||
|
||||
/* Micro-interaction: subtle scale */
|
||||
.hover-scale {
|
||||
transition: transform 150ms ease-out;
|
||||
}
|
||||
|
||||
.hover-scale:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
/* Border glow on focus */
|
||||
.ring-glow:focus-visible {
|
||||
box-shadow: 0 0 0 2px var(--background), 0 0 0 4px var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
/* Viewport height constraint for proper flex layout */
|
||||
html,
|
||||
body,
|
||||
|
||||
@@ -7,7 +7,7 @@ import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
|
||||
import { useState } from "react";
|
||||
import SuperJSON from "superjson";
|
||||
|
||||
import { type AppRouter } from "~/server/api/root";
|
||||
import type { AppRouter } from "~/server/api/root";
|
||||
import { createQueryClient } from "./query-client";
|
||||
|
||||
let clientQueryClientSingleton: QueryClient | undefined = undefined;
|
||||
|
||||
192
ws-server.ts
Normal file
192
ws-server.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { serve, type ServerWebSocket } from "bun";
|
||||
import { wsManager } from "./src/server/services/websocket-manager";
|
||||
import { db } from "./src/server/db";
|
||||
import { wsConnections } from "./src/server/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const port = parseInt(process.env.WS_PORT || "3001", 10);
|
||||
|
||||
interface WSData {
|
||||
clientId: string;
|
||||
trialId: string;
|
||||
userId: string | null;
|
||||
}
|
||||
|
||||
function generateClientId(): string {
|
||||
return `ws_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
}
|
||||
|
||||
async function recordConnection(
|
||||
clientId: string,
|
||||
trialId: string,
|
||||
userId: string | null,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await db.insert(wsConnections).values({
|
||||
clientId,
|
||||
trialId,
|
||||
userId,
|
||||
});
|
||||
console.log(`[DB] Recorded connection for trial ${trialId}`);
|
||||
} catch (error) {
|
||||
console.error(`[DB] Failed to record connection:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeConnection(clientId: string): Promise<void> {
|
||||
try {
|
||||
await db.delete(wsConnections).where(eq(wsConnections.clientId, clientId));
|
||||
console.log(`[DB] Removed connection ${clientId}`);
|
||||
} catch (error) {
|
||||
console.error(`[DB] Failed to remove connection:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Starting WebSocket server on port ${port}...`);
|
||||
|
||||
serve<WSData>({
|
||||
port,
|
||||
fetch(req, server) {
|
||||
const url = new URL(req.url);
|
||||
|
||||
if (url.pathname === "/api/websocket") {
|
||||
if (req.headers.get("upgrade") !== "websocket") {
|
||||
return new Response("WebSocket upgrade required", { status: 426 });
|
||||
}
|
||||
|
||||
const trialId = url.searchParams.get("trialId");
|
||||
const token = url.searchParams.get("token");
|
||||
|
||||
if (!trialId) {
|
||||
return new Response("Missing trialId parameter", { status: 400 });
|
||||
}
|
||||
|
||||
let userId: string | null = null;
|
||||
if (token) {
|
||||
try {
|
||||
const tokenData = JSON.parse(atob(token));
|
||||
userId = tokenData.userId;
|
||||
} catch {
|
||||
return new Response("Invalid token", { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
const clientId = generateClientId();
|
||||
const wsData: WSData = { clientId, trialId, userId };
|
||||
|
||||
const upgraded = server.upgrade(req, { data: wsData });
|
||||
|
||||
if (!upgraded) {
|
||||
return new Response("WebSocket upgrade failed", { status: 500 });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return new Response("Not found", { status: 404 });
|
||||
},
|
||||
websocket: {
|
||||
async open(ws: ServerWebSocket<WSData>) {
|
||||
const { clientId, trialId, userId } = ws.data;
|
||||
|
||||
wsManager.addClient(clientId, {
|
||||
socket: ws as unknown as WebSocket,
|
||||
trialId,
|
||||
userId,
|
||||
connectedAt: Date.now(),
|
||||
});
|
||||
|
||||
await recordConnection(clientId, trialId, userId);
|
||||
|
||||
console.log(
|
||||
`[WS] Client ${clientId} connected to trial ${trialId}. Total: ${wsManager.getConnectionCount()}`,
|
||||
);
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "connection_established",
|
||||
data: {
|
||||
trialId,
|
||||
userId,
|
||||
role: "connected",
|
||||
connectedAt: Date.now(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
message(ws: ServerWebSocket<WSData>, message) {
|
||||
const { clientId, trialId } = ws.data;
|
||||
|
||||
try {
|
||||
const msg = JSON.parse(message.toString());
|
||||
|
||||
switch (msg.type) {
|
||||
case "heartbeat":
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "heartbeat_response",
|
||||
data: { timestamp: Date.now() },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
|
||||
case "request_trial_status": {
|
||||
const status = wsManager.getTrialStatusSync(trialId);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "trial_status",
|
||||
data: {
|
||||
trial: status?.trial ?? null,
|
||||
current_step_index: status?.currentStepIndex ?? 0,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case "request_trial_events": {
|
||||
const events = wsManager.getTrialEventsSync(
|
||||
trialId,
|
||||
msg.data?.limit ?? 100,
|
||||
);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "trial_events_snapshot",
|
||||
data: { events, timestamp: Date.now() },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case "ping":
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "pong",
|
||||
data: { timestamp: Date.now() },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log(
|
||||
`[WS] Unknown message type from ${clientId}:`,
|
||||
msg.type,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[WS] Error processing message from ${clientId}:`, error);
|
||||
}
|
||||
},
|
||||
async close(ws: ServerWebSocket<WSData>) {
|
||||
const { clientId } = ws.data;
|
||||
console.log(`[WS] Client ${clientId} disconnected`);
|
||||
wsManager.removeClient(clientId);
|
||||
await removeConnection(clientId);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(
|
||||
`> WebSocket server running on ws://localhost:${port}/api/websocket`,
|
||||
);
|
||||
Reference in New Issue
Block a user