mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-20 18:37:13 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc9dd8a5f7 | ||
|
|
c7fef79860 | ||
|
|
efa0e75a06 | ||
|
|
b5ff76960f | ||
|
|
ca0c2ece75 | ||
|
|
c8b1d521d8 | ||
|
|
4bd5083ac1 | ||
|
|
c6527650d0 | ||
|
|
d4a1eff715 | ||
|
|
463cd61cfd | ||
|
|
93b4656939 | ||
|
|
3e122a86f0 | ||
|
|
292307e28e | ||
|
|
982bca9383 | ||
|
|
d1061a1023 | ||
|
|
994f1d3b44 | ||
|
|
e057f17f8e | ||
|
|
66d07d1fb0 | ||
|
|
5542538a64 | ||
|
|
7753721731 | ||
|
|
ef86cc2713 | ||
|
|
cc79be7e34 | ||
|
|
a9c5a3d9fd | ||
|
|
0d9545f0b5 | ||
|
|
2925fb6bf6 | ||
|
|
7ae34a4bc0 | ||
|
|
f645c8fefa | ||
|
|
1835016a9b | ||
|
|
5e92660d1c | ||
|
|
6cb3ca6874 | ||
|
|
5d14f4fff1 | ||
|
|
009566d42f | ||
|
|
50777d332b | ||
|
|
852a9873dc | ||
|
|
aa265c5322 | ||
|
|
01ab254c21 | ||
|
|
ca5ca5e080 | ||
|
|
3f27439733 | ||
|
|
2a611f9b5a | ||
|
|
7137e00911 | ||
|
|
59db97aedf | ||
|
|
a76dbdfc22 | ||
|
|
61e2a3c53a | ||
|
|
7707498916 | ||
|
|
91c8af86db | ||
|
|
286d71133f | ||
|
|
53c132e41d | ||
|
|
5c285b172b | ||
|
|
f1d52ac44e | ||
|
|
ec6736b452 | ||
|
|
46c975836a | ||
|
|
5d7ea7d118 | ||
|
|
5065346e8a | ||
|
|
60d469c91b | ||
|
|
f68c1c56e1 | ||
|
|
08cf90477a | ||
|
|
e01c348fde | ||
|
|
b0eb5b1eef | ||
|
|
3b7fc410b2 | ||
|
|
4c7ff6f58f | ||
|
|
a197c83580 | ||
|
|
718d9d5b51 | ||
|
|
212ac3bc0e | ||
|
|
eaf2c867b3 | ||
|
|
570d95fa6f | ||
|
|
32892a21c1 | ||
|
|
7819a2034e | ||
|
|
e0f2698a66 | ||
|
|
72c50ffd73 | ||
|
|
d84950d372 | ||
|
|
46815736e2 | ||
|
|
9d1e8378f7 | ||
|
|
f399d2c469 | ||
|
|
4af081f128 | ||
|
|
ce457e1161 | ||
|
|
a69dd6a660 | ||
|
|
62d7061cb3 | ||
|
|
1ad5720f42 | ||
|
|
0be74dd4ab | ||
|
|
f4276a19aa | ||
|
|
d81fc275f4 | ||
|
|
ead91455d8 |
@@ -46,3 +46,12 @@ jobs:
|
||||
- name: Test Local Release
|
||||
run: |
|
||||
bun run release:local --skip-check --out /tmp/shumai-local-release --force
|
||||
|
||||
echo "Smoke testing shumai..."
|
||||
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai/bin/shumai-app.js --check
|
||||
|
||||
echo "Smoke testing shumai-agent..."
|
||||
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-agent/bin/shumai-agent-app.js --check
|
||||
|
||||
echo "Smoke testing shumai-transcode..."
|
||||
bun run /tmp/shumai-local-release/node/node_modules/@shumai-one/shumai-transcode/bin/shumai-transcode-app.js --check
|
||||
|
||||
@@ -396,6 +396,7 @@ To prevent Temporal from indefinitely retrying fatal, expected business validati
|
||||
## Radix UI / Shadcn UI Patterns
|
||||
|
||||
- **Modal Overlays**: When triggering a dialog (e.g., `Dialog`, `AlertDialog`) from inside a `DropdownMenu`, you must set `modal={false}` on the `<DropdownMenu>` component. Failing to do so will cause the UI to freeze due to conflicting focus management between the two modal components.
|
||||
- **Scrollable Content**: Always use the Shadcn `ScrollArea` component (`@/ui/components/ui/scroll-area`) for scrollable content containers to ensure consistent custom scrollbar UI across the application.
|
||||
|
||||
## Logging
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ The easiest way to run Shumai is using Docker Compose. You do not need to clone
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
|
||||
```
|
||||
2. Configure environment variables (if deploying remotely):
|
||||
If you are deploying Shumai to a remote server (e.g., AWS ECS, EC2, VPS), you must edit `docker-compose.yaml`, set `AWS_ENDPOINT_URL_S3` to your server's public IP or domain name (e.g., `http://12.345.567.789:3000`).
|
||||
If you are deploying Shumai to a remote server (e.g., AWS ECS, EC2, VPS), you must edit `docker-compose.yaml`, set `AWS_ENDPOINT_URL_S3` to your server's public IP or domain name (e.g., `http://12.345.567.789`).
|
||||
3. Start the services:
|
||||
```bash
|
||||
docker compose up -d
|
||||
@@ -102,11 +102,12 @@ Create a `.env` file in this folder and add the following configuration (which a
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> If you are deploying on a remote server, make sure to change `AWS_ENDPOINT_URL_S3` from `http://localhost:3000` to your server's public IP address or domain name.
|
||||
> If you are deploying on a remote server, make sure to change `AWS_ENDPOINT_URL_S3` from `http://localhost` to your server's public IP address or domain name. `SHUMAI_SERVER_PORT` defaults to `3000` if not set.
|
||||
|
||||
#### Step 4: Run Shumai
|
||||
|
||||
@@ -189,7 +190,7 @@ DATABASE_URL=postgresql://shumai:shumai_password@<host-ip>:5432/shumai_db?schema
|
||||
WORKFLOW_EXECUTOR=temporal
|
||||
TEMPORAL_ADDRESS=<host-ip>:7233
|
||||
STORAGE_BACKEND=s3
|
||||
AWS_ENDPOINT_URL_S3=http://<host-ip>:3000 # Or your public S3/R2 endpoint URL
|
||||
AWS_ENDPOINT_URL_S3=http://<host-ip> # Or your public S3/R2 endpoint URL
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=shumai
|
||||
S3_ACCESS_KEY_ID=your-access-key-id
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -4,6 +4,12 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Agent worker evaluated successfully!')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize workflows and activities
|
||||
@@ -23,7 +29,7 @@ async function run() {
|
||||
await workflowService.startWorkers(TaskQueueAgent, options)
|
||||
}
|
||||
|
||||
run().catch((err) => {
|
||||
handleDaemonCommands('shumai-agent', run).catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -3,6 +3,12 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { TaskQueueTranscode, workflowService } from '@shumai/workflow-core'
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Transcode worker evaluated successfully!')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize workflows and activities
|
||||
@@ -22,7 +28,7 @@ async function run() {
|
||||
await workflowService.startWorkers(TaskQueueTranscode, options)
|
||||
}
|
||||
|
||||
run().catch((err) => {
|
||||
handleDaemonCommands('shumai-transcode', run).catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
+120
-104
@@ -11,111 +11,127 @@ import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { app } from '@shumai/api'
|
||||
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--workers') {
|
||||
workersOption = args[i + 1] || ''
|
||||
} else if (args[i].startsWith('--workers=')) {
|
||||
workersOption = args[i].split('=')[1]
|
||||
}
|
||||
}
|
||||
|
||||
const queuesToStart: string[] = []
|
||||
if (workersOption === 'agent' || workersOption === 'ai') {
|
||||
queuesToStart.push('agent_queue')
|
||||
} else if (workersOption === 'transcode') {
|
||||
queuesToStart.push('transcode_queue')
|
||||
} else if (workersOption === 'all') {
|
||||
queuesToStart.push('agent_queue', 'transcode_queue')
|
||||
}
|
||||
|
||||
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
|
||||
}
|
||||
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
|
||||
const server = Bun.serve(
|
||||
isProd
|
||||
? {
|
||||
port: 3000,
|
||||
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
|
||||
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
|
||||
: 1024 * 1024 * 1024 * 10, // Default 10GB
|
||||
development: false,
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
|
||||
if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) {
|
||||
const filepath = join(import.meta.dir, url.pathname)
|
||||
const file = Bun.file(filepath)
|
||||
if (await file.exists()) {
|
||||
try {
|
||||
const stat = await file.stat()
|
||||
if (stat.isFile()) {
|
||||
return new Response(file)
|
||||
}
|
||||
} catch {
|
||||
// ignore stat errors
|
||||
}
|
||||
}
|
||||
|
||||
const htmlFile = Bun.file(join(import.meta.dir, 'index.html'))
|
||||
if (await htmlFile.exists()) {
|
||||
return new Response(htmlFile, {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
})
|
||||
}
|
||||
|
||||
const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html'))
|
||||
if (await htmlFileNpm.exists()) {
|
||||
return new Response(htmlFileNpm, {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return app.fetch(req)
|
||||
},
|
||||
}
|
||||
: {
|
||||
port: 3000,
|
||||
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
|
||||
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
|
||||
: 1024 * 1024 * 1024 * 10, // Default 10GB
|
||||
development: true,
|
||||
fetch: app.fetch,
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
// Proxy API requests to Hono
|
||||
'/api/*': app.fetch,
|
||||
'/files/*': app.fetch,
|
||||
|
||||
// Catch-all for SPA routing (fallback to index.html)
|
||||
'/*': index,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
|
||||
const shutdown = () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
assetService.stopCleanupJob()
|
||||
server.stop(true)
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--workers') {
|
||||
workersOption = args[i + 1] || ''
|
||||
} else if (args[i].startsWith('--workers=')) {
|
||||
workersOption = args[i].split('=')[1]
|
||||
}
|
||||
}
|
||||
|
||||
const queuesToStart: string[] = []
|
||||
if (workersOption === 'agent' || workersOption === 'ai') {
|
||||
queuesToStart.push('agent_queue')
|
||||
} else if (workersOption === 'transcode') {
|
||||
queuesToStart.push('transcode_queue')
|
||||
} else if (workersOption === 'all') {
|
||||
queuesToStart.push('agent_queue', 'transcode_queue')
|
||||
}
|
||||
|
||||
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
|
||||
}
|
||||
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
|
||||
const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000
|
||||
|
||||
const server = Bun.serve(
|
||||
isProd
|
||||
? {
|
||||
port,
|
||||
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
|
||||
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
|
||||
: 1024 * 1024 * 1024 * 10, // Default 10GB
|
||||
development: false,
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
|
||||
if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) {
|
||||
const filepath = join(import.meta.dir, url.pathname)
|
||||
const file = Bun.file(filepath)
|
||||
if (await file.exists()) {
|
||||
try {
|
||||
const stat = await file.stat()
|
||||
if (stat.isFile()) {
|
||||
return new Response(file)
|
||||
}
|
||||
} catch {
|
||||
// ignore stat errors
|
||||
}
|
||||
}
|
||||
|
||||
const htmlFile = Bun.file(join(import.meta.dir, 'index.html'))
|
||||
if (await htmlFile.exists()) {
|
||||
return new Response(htmlFile, {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
})
|
||||
}
|
||||
|
||||
const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html'))
|
||||
if (await htmlFileNpm.exists()) {
|
||||
return new Response(htmlFileNpm, {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return app.fetch(req)
|
||||
},
|
||||
}
|
||||
: {
|
||||
port,
|
||||
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
|
||||
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
|
||||
: 1024 * 1024 * 1024 * 10, // Default 10GB
|
||||
development: true,
|
||||
fetch: app.fetch,
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
// Proxy API requests to Hono
|
||||
'/api/*': app.fetch,
|
||||
'/files/*': app.fetch,
|
||||
|
||||
// Catch-all for SPA routing (fallback to index.html)
|
||||
'/*': index,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
|
||||
const shutdown = () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
assetService.stopCleanupJob()
|
||||
server.stop(true)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
}
|
||||
|
||||
handleDaemonCommands('shumai', run).catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
@@ -15,12 +15,21 @@ Shumai is configured via environment variables. You can define these variables i
|
||||
|
||||
---
|
||||
|
||||
## Server Config
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :---------------------- | :------------------------------------------------------------------------------------------------ | :---------------- |
|
||||
| `SHUMAI_SERVER_PORT` | The port on which the Shumai web server will listen. | `3000` (default) |
|
||||
| `MAX_REQUEST_BODY_SIZE` | Maximum allowed size for request bodies (e.g., for large file uploads). Default is 10GB in bytes. | `10737418240` |
|
||||
|
||||
---
|
||||
|
||||
## Authentication Config
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------- | :--------------------------------------------------------------------- | :-------------------------------------- |
|
||||
| `BETTER_AUTH_SECRET` | A secure, random 32-byte secret used to sign session cookies and JWTs. | Generate with `openssl rand -base64 32` |
|
||||
| `BETTER_AUTH_URL` | The public URL of your Hono backend API. Used for redirect flows. | `http://localhost:3000` |
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------- | :--------------------------------------------------------------------- | :--------------------------------------------------------------- |
|
||||
| `BETTER_AUTH_SECRET` | A secure, random 32-byte secret used to sign session cookies and JWTs. | Generate with `openssl rand -base64 32` |
|
||||
| `BETTER_AUTH_URL` | The public URL of your Hono backend API. Used for redirect flows. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback) |
|
||||
|
||||
---
|
||||
|
||||
@@ -28,16 +37,16 @@ Shumai is configured via environment variables. You can define these variables i
|
||||
|
||||
Shumai supports storing files locally or on S3-compatible endpoints.
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------------- | :------------------------------------------------------------------------------------------------ | :-------------------------------- |
|
||||
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
|
||||
| `AWS_ENDPOINT_URL_S3` | Custom endpoint for S3 storage. Must change to public domain/IP if deploying remotely. | `http://localhost:3000` (default) |
|
||||
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
|
||||
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
|
||||
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
|
||||
| `S3_REGION` | S3 storage region. | `auto` (default) |
|
||||
| `S3_USE_SSL` | Set to `true` to use HTTPS for S3 endpoints. | `false` (default) |
|
||||
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download/upload links are valid. | `5` (default) |
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------------- | :------------------------------------------------------------------------------------------------ | :--------------------------- |
|
||||
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
|
||||
| `AWS_ENDPOINT_URL_S3` | Custom endpoint for S3 storage. Must change to public domain/IP if deploying remotely. | `http://localhost` (default) |
|
||||
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
|
||||
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
|
||||
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
|
||||
| `S3_REGION` | S3 storage region. | `auto` (default) |
|
||||
| `S3_USE_SSL` | Set to `true` to use HTTPS for S3 endpoints. | `false` (default) |
|
||||
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download/upload links are valid. | `5` (default) |
|
||||
|
||||
---
|
||||
|
||||
@@ -45,10 +54,12 @@ Shumai supports storing files locally or on S3-compatible endpoints.
|
||||
|
||||
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------ | :------------------------------------------------------------------------------------------------- | :------------------------------ |
|
||||
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
|
||||
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
|
||||
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
|
||||
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
|
||||
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
|
||||
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ To handle media processing and security isolation, the host machine must have th
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=your-random-32-character-secret-key
|
||||
STORAGE_BACKEND=local
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost
|
||||
```
|
||||
4. **Start Shumai**:
|
||||
```bash
|
||||
|
||||
@@ -34,6 +34,7 @@ A specialized utility agent that processes assets to generate search indexes. Yo
|
||||
- Once created and enabled, Shumai automatically runs embedding generation for new file uploads if the file type is supported (image or video).
|
||||
- These search indexes are saved to power Shumai's natural language semantic search capabilities.
|
||||
- **Note:** The Embedding Agent is hardcoded to use `google-embedding-2` as the LLM model. Because of this, you cannot choose a provider or model. Make sure you set the `GEMINI_API_KEY` environment variable to make it work.
|
||||
- **Chunk Duration:** You can configure the duration of chunks used for long video indexing via the `EMBEDDING_CHUNK_DURATION` environment variable (defaults to 60 seconds).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -12,9 +12,22 @@ Traditional search relies on matching exact characters (e.g., searching "dog" wi
|
||||
Semantic search translates text queries and file contents into conceptual profiles. Similar ideas and visuals are mapped near each other.
|
||||
|
||||
1. **Index Generation**: When you upload an asset, Shumai's background agent scans the file's visual elements, text contents, or descriptions, translating them into a concept profile.
|
||||
- **Video Processing**: Shumai uses **gemini-embedding-2** for video indexing.
|
||||
- **Chunking**: For long videos, Shumai breaks them into chunks to ensure high-quality indexing. By default, chunks are **60 seconds** long with a **5-second overlap** to ensure no context is lost at the boundaries.
|
||||
- **Sampling**: The model processes a maximum of 32 frames per chunk: short chunks (≤32s) are sampled at 1 fps, while longer chunks are uniformly sampled to 32 frames.
|
||||
- **Optimization**: To optimize processing, Shumai automatically transcodes each chunk to **1 FPS** and **removes the audio track** before sending it to the embedding agent.
|
||||
- **Configuration**: Administrators can customize these settings using the `EMBEDDING_CHUNK_DURATION` and `EMBEDDING_CHUNK_OVERLAP` environment variables.
|
||||
2. **Concept Matching**: When you search with the "Semantic" toggle enabled, Shumai matches the conceptual meaning of your query against your assets.
|
||||
3. **Result**: Searching "sunset at the beach" will successfully find a video file of ocean waves at dusk, even if the filename is `IMG_4029.mp4`.
|
||||
|
||||
### Understanding Search Results
|
||||
|
||||
Semantic search works differently than traditional keyword filtering:
|
||||
|
||||
- **Sort vs. Filter**: Semantic search acts more like a **sort** than a strict filter. While the most relevant results will appear at the top, less related content may still be present further down the list, ranked lower. If you need to exclude specific types of files, use the **Filter** panel in conjunction with semantic search.
|
||||
- **Video Chunks**: Because Shumai indexes videos in chunks, a single long video may appear multiple times in your search results. Each result corresponds to a specific segment of the video where the match was found.
|
||||
- **Match Timestamps**: When a search result comes from a video chunk, Shumai displays the matching start and end time. Clicking on these results will open the video and automatically jump to the relevant timestamp.
|
||||
|
||||
---
|
||||
|
||||
## Activating Semantic Search
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
generateEmbeddingActivity,
|
||||
generateTextEmbeddingActivity,
|
||||
extractAiMetadataActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
} from './ai'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
|
||||
@@ -93,19 +93,13 @@ describe('AI Activities Unit Tests', () => {
|
||||
contentType: 'image/png',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
const res = await generateImageEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
context,
|
||||
assetKey: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
})
|
||||
|
||||
expect(res.embeddings.length).toBe(1)
|
||||
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
||||
})
|
||||
|
||||
@@ -115,25 +109,16 @@ describe('AI Activities Unit Tests', () => {
|
||||
contentType: 'video/mp4',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
const res = await generateVideoChunkEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a2',
|
||||
context,
|
||||
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
|
||||
// Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120)
|
||||
expect(res.embeddings.length).toBe(2)
|
||||
expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 })
|
||||
expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 })
|
||||
|
||||
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled()
|
||||
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
)
|
||||
})
|
||||
|
||||
it('should generate text embedding successfully', async () => {
|
||||
@@ -291,6 +276,63 @@ describe('AI Database Activities Integration', () => {
|
||||
expect(ctx.asset.id).toBe(asset.id)
|
||||
expect(ctx.asset.mediaType).toBe('video/mp4')
|
||||
})
|
||||
|
||||
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
|
||||
// Create embedding agent if not already present
|
||||
const existingAgent = await prisma.agent.findUnique({ where: { id: user.id } })
|
||||
if (!existingAgent) {
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Test default/fallback
|
||||
delete process.env.EMBEDDING_CHUNK_DURATION
|
||||
let ctx = await getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
expect(ctx.chunkDuration).toBe(60.0)
|
||||
expect(ctx.chunkOverlap).toBe(5.0)
|
||||
|
||||
// Test valid positive
|
||||
process.env.EMBEDDING_CHUNK_DURATION = '45.5'
|
||||
process.env.EMBEDDING_CHUNK_OVERLAP = '10.0'
|
||||
ctx = await getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
expect(ctx.chunkDuration).toBe(45.5)
|
||||
expect(ctx.chunkOverlap).toBe(10.0)
|
||||
|
||||
// Test negative/invalid for overlap
|
||||
process.env.EMBEDDING_CHUNK_OVERLAP = '-5.0'
|
||||
ctx = await getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
expect(ctx.chunkOverlap).toBe(5.0)
|
||||
|
||||
process.env.EMBEDDING_CHUNK_OVERLAP = 'invalid'
|
||||
ctx = await getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
expect(ctx.chunkOverlap).toBe(5.0)
|
||||
|
||||
// Cleanup env
|
||||
delete process.env.EMBEDDING_CHUNK_DURATION
|
||||
delete process.env.EMBEDDING_CHUNK_OVERLAP
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveAssetEmbeddingsActivity', () => {
|
||||
|
||||
@@ -140,6 +140,8 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
'-i',
|
||||
tmpFile,
|
||||
'-ss',
|
||||
@@ -309,9 +311,18 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
|
||||
const chunkDuration =
|
||||
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
|
||||
|
||||
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
|
||||
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
|
||||
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
chunkDuration,
|
||||
chunkOverlap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,3 +349,91 @@ export async function saveAssetEmbeddingsActivity(params: {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface GenerateImageEmbeddingParams {
|
||||
teamId: string
|
||||
assetKey: string
|
||||
mediaType: string
|
||||
}
|
||||
|
||||
export async function generateImageEmbeddingActivity(
|
||||
params: GenerateImageEmbeddingParams,
|
||||
): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.assetKey,
|
||||
)
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
|
||||
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
}
|
||||
}
|
||||
|
||||
export interface GenerateVideoChunkEmbeddingParams {
|
||||
teamId: string
|
||||
chunkKey: string
|
||||
}
|
||||
|
||||
export async function generateVideoChunkEmbeddingActivity(
|
||||
params: GenerateVideoChunkEmbeddingParams,
|
||||
): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
try {
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.chunkKey,
|
||||
)
|
||||
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
}
|
||||
} catch (err) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,6 +380,8 @@ export {
|
||||
generateTextEmbeddingActivity,
|
||||
type ExtractAiMetadataParams,
|
||||
extractAiMetadataActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
} from './activities/ai'
|
||||
export * from './workflows/agent-autofill'
|
||||
export * from './workflows/agent-chat'
|
||||
|
||||
@@ -29,8 +29,11 @@ describe('Agent Embedding Workflow', () => {
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
generateImageEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateImageEmbeddingActivity',
|
||||
}),
|
||||
generateVideoChunkEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateVideoChunkEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
@@ -41,20 +44,58 @@ describe('Agent Embedding Workflow', () => {
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'cleanupTmpDirActivity',
|
||||
}),
|
||||
transcodeVideoChunkActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'transcodeVideoChunkActivity',
|
||||
}),
|
||||
deleteS3ObjectActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'deleteS3ObjectActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: { id: 'a1' },
|
||||
dbProvider: { name: 'google' },
|
||||
asset: {
|
||||
id: 'a1',
|
||||
mediaType: 'image/png',
|
||||
storageKey: { key: 'test.png' },
|
||||
},
|
||||
chunkDuration: 60.0,
|
||||
chunkOverlap: 5.0,
|
||||
})
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [{ embedding: [0.1, 0.2] }],
|
||||
mockActivities.generateImageEmbeddingActivity.mockResolvedValue({
|
||||
embedding: [0.1, 0.2],
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
mockActivities.generateVideoChunkEmbeddingActivity.mockResolvedValue({
|
||||
embedding: [0.3, 0.4],
|
||||
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
|
||||
})
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.mp4',
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
mockActivities.transcodeVideoChunkActivity.mockImplementation(
|
||||
async (params: { assetId: string; startTime: number; endTime: number }) => {
|
||||
return {
|
||||
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
|
||||
}
|
||||
},
|
||||
)
|
||||
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
|
||||
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
@@ -64,7 +105,7 @@ describe('Agent Embedding Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
it('should run agent embedding workflow successfully for image', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
@@ -103,15 +144,11 @@ describe('Agent Embedding Workflow', () => {
|
||||
assetId: 'a1',
|
||||
})
|
||||
|
||||
// Verify embedding generation
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalledWith({
|
||||
// Verify image embedding generation
|
||||
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
context: {
|
||||
agent: { id: 'b1' },
|
||||
asset: { id: 'a1' },
|
||||
dbProvider: { name: 'google' },
|
||||
},
|
||||
assetKey: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
})
|
||||
|
||||
// Verify embeddings saved
|
||||
@@ -125,7 +162,7 @@ describe('Agent Embedding Workflow', () => {
|
||||
taskId: task.id,
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'gpt',
|
||||
model: 'gemini-embedding-2',
|
||||
})
|
||||
|
||||
// Verify placeholder comment updated
|
||||
@@ -141,6 +178,142 @@ describe('Agent Embedding Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully for image with transcoded format', async () => {
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: {
|
||||
id: 'a1',
|
||||
mediaType: 'image/png',
|
||||
storageKey: { key: 'test.png' },
|
||||
media: {
|
||||
imageTranscodes: [{ key: 'test-transcoded.webp', isRaw: false, format: 'webp' }],
|
||||
},
|
||||
},
|
||||
chunkDuration: 60.0,
|
||||
chunkOverlap: 5.0,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetKey: 'test-transcoded.webp',
|
||||
mediaType: 'image/webp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully for video in chunks', async () => {
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: {
|
||||
id: 'a1',
|
||||
mediaType: 'video/mp4',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
media: {
|
||||
duration: 150.0,
|
||||
videoTranscodes: [{ key: 'test-transcoded.mp4', isRaw: false }],
|
||||
},
|
||||
},
|
||||
chunkDuration: 60.0,
|
||||
chunkOverlap: 5.0,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
// Verify video transcode queue discovery & download
|
||||
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'test-transcoded.mp4',
|
||||
})
|
||||
|
||||
// Verify video chunk slicing activity called 3 times on transcode queue
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
|
||||
assetId: 'a1',
|
||||
filePath: '/tmp/test.mp4',
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
})
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
|
||||
assetId: 'a1',
|
||||
filePath: '/tmp/test.mp4',
|
||||
startTime: 55,
|
||||
endTime: 115,
|
||||
})
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
|
||||
assetId: 'a1',
|
||||
filePath: '/tmp/test.mp4',
|
||||
startTime: 110,
|
||||
endTime: 150,
|
||||
})
|
||||
|
||||
// Verify video chunk embedding generation (3 chunks) on agent queue
|
||||
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenCalledTimes(3)
|
||||
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(1, {
|
||||
teamId: 't1',
|
||||
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(2, {
|
||||
teamId: 't1',
|
||||
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
|
||||
})
|
||||
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(3, {
|
||||
teamId: 't1',
|
||||
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
|
||||
})
|
||||
|
||||
// Verify deletion of temporary chunks from S3
|
||||
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
|
||||
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
|
||||
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
})
|
||||
|
||||
// Verify temp directory cleanup on transcode queue
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
|
||||
// Verify usage update (3 chunks * 3 tokens = 9)
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
inputTokens: 9,
|
||||
outputTokens: 9,
|
||||
model: 'gemini-embedding-2',
|
||||
})
|
||||
|
||||
// Verify embeddings saved
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
embeddings: [
|
||||
{ embedding: [0.3, 0.4], startTime: 0, endTime: 60 },
|
||||
{ embedding: [0.3, 0.4], startTime: 55, endTime: 115 },
|
||||
{ embedding: [0.3, 0.4], startTime: 110, endTime: 150 },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw if task has no teamId', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
@@ -160,10 +333,19 @@ describe('Agent Embedding Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should skip saving embeddings if none are returned', async () => {
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [],
|
||||
usage: null,
|
||||
it('should skip saving embeddings if none are returned (video duration 0)', async () => {
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: {
|
||||
id: 'a1',
|
||||
mediaType: 'video/mp4',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
media: {
|
||||
duration: 0.0,
|
||||
},
|
||||
},
|
||||
chunkDuration: 60.0,
|
||||
chunkOverlap: 5.0,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
@@ -178,7 +360,6 @@ describe('Agent Embedding Workflow', () => {
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateTaskUsageActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
@@ -186,7 +367,9 @@ describe('Agent Embedding Workflow', () => {
|
||||
})
|
||||
|
||||
it('should handle failures, update placeholder with error, and set status to failed', async () => {
|
||||
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('AI Service Unavailable'))
|
||||
mockActivities.generateImageEmbeddingActivity.mockRejectedValue(
|
||||
new Error('AI Service Unavailable'),
|
||||
)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
@@ -212,4 +395,40 @@ describe('Agent Embedding Workflow', () => {
|
||||
output: { error: 'AI Service Unavailable' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: {
|
||||
id: 'a1',
|
||||
mediaType: 'video/mp4',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
media: {
|
||||
duration: 60.0,
|
||||
},
|
||||
},
|
||||
chunkDuration: 60.0,
|
||||
chunkOverlap: 5.0,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,25 +1,48 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
} from '@shumai/workflow-core'
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}
|
||||
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateEmbeddingActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
deleteS3ObjectActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let agentWorkerQueue = ''
|
||||
let transcodeWorkerQueue = ''
|
||||
let tmpDir: string | undefined
|
||||
|
||||
try {
|
||||
// 0. Discover queue
|
||||
// 0. Discover queues
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
transcodeWorkerQueue = await executeActivity(
|
||||
TaskQueueTranscode,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
@@ -47,30 +70,153 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
assetId: task.assetId,
|
||||
})
|
||||
|
||||
// Call the activity to generate embeddings
|
||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
context,
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { asset, chunkDuration, chunkOverlap } = context as any
|
||||
|
||||
const isImage = asset.mediaType?.startsWith('image/')
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
|
||||
if (!isImage && !isVideo) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `unsupported media type for embeddings: ${asset.mediaType}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Resolve the S3 key to use for embedding (preferring transcoded version)
|
||||
let embeddingKey = asset.storageKey?.key
|
||||
let embeddingMediaType = asset.mediaType
|
||||
if (asset.media) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const media = asset.media as any
|
||||
if (isVideo) {
|
||||
if (media.videoTranscodes && media.videoTranscodes.length > 0) {
|
||||
// Find first non-raw transcode or fallback to first transcode
|
||||
const transcode =
|
||||
media.videoTranscodes.find((t: PrismaJson.VideoTranscode) => !t.isRaw) ||
|
||||
media.videoTranscodes[0]
|
||||
if (transcode?.key) {
|
||||
embeddingKey = transcode.key
|
||||
}
|
||||
}
|
||||
} else if (isImage) {
|
||||
if (media.imageTranscodes && media.imageTranscodes.length > 0) {
|
||||
// Find first non-raw transcode or fallback to first transcode
|
||||
const transcode =
|
||||
media.imageTranscodes.find((t: PrismaJson.ImageTranscode) => !t.isRaw) ||
|
||||
media.imageTranscodes[0]
|
||||
if (transcode?.key) {
|
||||
embeddingKey = transcode.key
|
||||
if (transcode.format) {
|
||||
embeddingMediaType = `image/${transcode.format}`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!embeddingKey) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true })
|
||||
}
|
||||
|
||||
const results: GeneratedEmbedding[] = []
|
||||
const usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
if (isImage) {
|
||||
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetKey: embeddingKey,
|
||||
mediaType: embeddingMediaType,
|
||||
})
|
||||
results.push({ embedding: result.embedding })
|
||||
if (result.usage) {
|
||||
usage.inputTokens += result.usage.inputTokens || 0
|
||||
usage.outputTokens += result.usage.outputTokens || 0
|
||||
}
|
||||
} else if (isVideo) {
|
||||
// 1. Download full video to transcode worker temp space
|
||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: embeddingKey,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
// Get video duration
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const duration = (asset.media as any)?.duration || 0
|
||||
const limit = chunkDuration || 60.0
|
||||
const overlap = chunkOverlap ?? 5.0
|
||||
const step = Math.max(1, limit - overlap)
|
||||
|
||||
for (let start = 0.0; start < duration; start += step) {
|
||||
let end = start + limit
|
||||
if (end >= duration) {
|
||||
end = duration
|
||||
}
|
||||
|
||||
// Step A: Slice chunk on transcode worker and upload to S3
|
||||
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
|
||||
assetId: asset.id,
|
||||
filePath,
|
||||
startTime: start,
|
||||
endTime: end,
|
||||
})
|
||||
const { chunkKey } = chunkRes
|
||||
|
||||
try {
|
||||
// Step B: Generate embedding on agent worker
|
||||
const chunkResult = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
{
|
||||
teamId: task.teamId,
|
||||
chunkKey,
|
||||
},
|
||||
)
|
||||
|
||||
results.push({
|
||||
embedding: chunkResult.embedding,
|
||||
startTime: start,
|
||||
endTime: end,
|
||||
})
|
||||
|
||||
if (chunkResult.usage) {
|
||||
usage.inputTokens += chunkResult.usage.inputTokens || 0
|
||||
usage.outputTokens += chunkResult.usage.outputTokens || 0
|
||||
}
|
||||
} finally {
|
||||
// Step C: Delete temporary chunk from S3
|
||||
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
|
||||
key: chunkKey,
|
||||
})
|
||||
}
|
||||
|
||||
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
|
||||
if (end >= duration) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save computed embeddings
|
||||
if (result.embeddings.length > 0) {
|
||||
if (results.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||
assetId: task.assetId,
|
||||
embeddings: result.embeddings,
|
||||
embeddings: results,
|
||||
})
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
if (result.usage) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.usage.inputTokens,
|
||||
outputTokens: result.usage.outputTokens,
|
||||
model: result.usage.model,
|
||||
})
|
||||
}
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: usage.inputTokens,
|
||||
outputTokens: usage.outputTokens,
|
||||
model: usage.model,
|
||||
})
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
@@ -109,6 +255,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
}
|
||||
throw err
|
||||
} finally {
|
||||
if (tmpDir && transcodeWorkerQueue) {
|
||||
try {
|
||||
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup transcode worker tmp dir:', cleanupErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -17,7 +17,8 @@ describe('authn api', () => {
|
||||
|
||||
it('GET /signup-info', async () => {
|
||||
mockGetSignupInfo.mockResolvedValue({
|
||||
userCount: 5,
|
||||
initialized: true,
|
||||
demoMode: false,
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', authnRoute)
|
||||
@@ -25,7 +26,8 @@ describe('authn api', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
userCount: 5,
|
||||
initialized: true,
|
||||
demoMode: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,7 +17,8 @@ const route = app
|
||||
.get('/signup-info', async (c) => {
|
||||
const info = await teamService.getSignupInfo()
|
||||
return c.json({
|
||||
userCount: info.userCount,
|
||||
initialized: info.initialized,
|
||||
demoMode: info.demoMode,
|
||||
})
|
||||
})
|
||||
.get('/me', async (c) => {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { authMiddleware } from './auth'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
|
||||
vi.mock('@shumai/core/src/auth/auth', () => ({
|
||||
auth: {
|
||||
api: {
|
||||
getSession: vi.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/db', () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
teamMember: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('authMiddleware', () => {
|
||||
const app = new Hono()
|
||||
.use('*', authMiddleware)
|
||||
.get('/test', (c) => c.text('ok'))
|
||||
.post('/test', (c) => c.text('ok'))
|
||||
.post('/test/search', (c) => c.text('ok'))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
delete process.env.SHUMAI_DEMO_MODE
|
||||
})
|
||||
|
||||
it('allows access when authenticated', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test')
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('rejects when not authenticated', async () => {
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue(null)
|
||||
|
||||
const res = await app.request('/test')
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
describe('read-only mode', () => {
|
||||
beforeEach(() => {
|
||||
process.env.SHUMAI_DEMO_MODE = '1'
|
||||
})
|
||||
|
||||
it('allows GET for reviewer', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test')
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('rejects POST for reviewer', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue(null) // No owner/editor role
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toEqual({ error: 'System is in read-only mode' })
|
||||
})
|
||||
|
||||
it('allows POST /search for reviewer', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test/search', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('allows POST for owner', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
|
||||
id: 'member1',
|
||||
role: 'owner',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('allows POST for editor', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
|
||||
id: 'member1',
|
||||
role: 'editor',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -28,6 +28,24 @@ export const authMiddleware = createMiddleware<{
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
|
||||
if (process.env.SHUMAI_DEMO_MODE === '1') {
|
||||
const method = c.req.method.toUpperCase()
|
||||
const path = c.req.path
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) {
|
||||
const member = await prisma.teamMember.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
role: { in: ['owner', 'editor'] },
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) {
|
||||
return c.json({ error: 'System is in read-only mode' }, 403)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
|
||||
@@ -48,6 +48,8 @@ const route = app
|
||||
hasPassword: shareLink.hasPassword,
|
||||
rootFolderId: shareLink.rootFolderId,
|
||||
projectId: shareLink.projectId,
|
||||
viewMode: shareLink.viewMode,
|
||||
defaultSortOrder: shareLink.defaultSortOrder,
|
||||
})
|
||||
} catch (err) {
|
||||
return c.json({ error: (err as Error).message }, 404)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -15,9 +15,13 @@ export const auth = betterAuth({
|
||||
},
|
||||
secret: process.env.BETTER_AUTH_SECRET,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
baseURL: process.env.BETTER_AUTH_URL || 'http://localhost:3000',
|
||||
baseURL:
|
||||
process.env.BETTER_AUTH_URL || `http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
|
||||
basePath: '/api/auth',
|
||||
trustedOrigins: ['http://localhost:3000', 'http://127.0.0.1:3000'],
|
||||
trustedOrigins: [
|
||||
`http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
|
||||
`http://127.0.0.1:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
|
||||
],
|
||||
advanced: {
|
||||
disableCSRFCheck: true,
|
||||
},
|
||||
@@ -30,7 +34,7 @@ export const auth = betterAuth({
|
||||
|
||||
const info = await teamService.getSignupInfo()
|
||||
|
||||
if (info.userCount > 0) {
|
||||
if (info.initialized) {
|
||||
if (!inviteCode) {
|
||||
console.log('[Better Auth Hook] Public signup is disabled')
|
||||
return ctx.json(
|
||||
|
||||
@@ -362,4 +362,70 @@ describe('NotificationService', () => {
|
||||
count = await notificationService.getUnreadCount(tm.id, u1.id)
|
||||
expect(count).toBe(0)
|
||||
})
|
||||
|
||||
it('toNotificationInfo maps video sprite and poster urls', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-video.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video/mp4',
|
||||
status: 'processed',
|
||||
media: {
|
||||
duration: 10,
|
||||
filesize: 1024,
|
||||
fps: 24,
|
||||
frames: 240,
|
||||
videoPreview: { width: 640, height: 360 },
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
sprite: { key: 'sprites/test-video.jpg', tileX: 10, tileY: 10, frames: 100 },
|
||||
poster: { key: 'posters/test-video.jpg' },
|
||||
thumbnail: {
|
||||
key: 'thumbnails/test-video.jpg',
|
||||
width: 120,
|
||||
height: 90,
|
||||
format: 'jpg',
|
||||
quality: 80,
|
||||
},
|
||||
metadata: {
|
||||
originalWidth: 1280,
|
||||
originalHeight: 720,
|
||||
duration: 10,
|
||||
bitRate: 1000,
|
||||
frameRate: 24,
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
finishedAt: new Date().toISOString(),
|
||||
mimeType: 'video/mp4',
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const n = await prisma.notification.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
type: NotificationType.comment_created,
|
||||
assetId: asset.id,
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
const info = await svc['toNotificationInfo'](
|
||||
await prisma.notification.findUniqueOrThrow({
|
||||
where: { id: n.id },
|
||||
include: { creator: true, team: true, project: true, asset: true, user: true },
|
||||
}),
|
||||
null,
|
||||
)
|
||||
|
||||
expect(info.asset?.preview).toBeDefined()
|
||||
expect(info.asset?.thumbnailUrl).toBeDefined()
|
||||
expect(info.asset?.thumbnailUrl).toContain('posters/test-video.jpg')
|
||||
expect(info.asset?.originalWidth).toBe(1280)
|
||||
expect(info.asset?.originalHeight).toBe(720)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -371,6 +371,9 @@ export class NotificationService {
|
||||
if (n.asset) {
|
||||
const a = n.asset
|
||||
let previewUrl = ''
|
||||
let thumbnailUrl = ''
|
||||
let originalWidth = 0
|
||||
let originalHeight = 0
|
||||
|
||||
const media = a.media as PrismaJson.MediaInfo | null
|
||||
|
||||
@@ -379,8 +382,16 @@ export class NotificationService {
|
||||
try {
|
||||
if (media.sprite) {
|
||||
previewUrl = await s3Service.presign(bucket, media.sprite.key, 'GET')
|
||||
if (media.poster) {
|
||||
thumbnailUrl = await s3Service.presign(bucket, media.poster.key || '', 'GET')
|
||||
}
|
||||
if (media.metadata) {
|
||||
originalWidth = media.metadata.originalWidth
|
||||
originalHeight = media.metadata.originalHeight
|
||||
}
|
||||
} else if (media.thumbnail) {
|
||||
previewUrl = await s3Service.presign(bucket, media.thumbnail.key || '', 'GET')
|
||||
thumbnailUrl = previewUrl
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to generate presigned url for notification asset preview:', e)
|
||||
@@ -392,6 +403,9 @@ export class NotificationService {
|
||||
name: a.name,
|
||||
mediaType: a.mediaType || undefined,
|
||||
preview: previewUrl || undefined,
|
||||
thumbnailUrl: thumbnailUrl || undefined,
|
||||
originalWidth: originalWidth || undefined,
|
||||
originalHeight: originalHeight || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -451,7 +451,8 @@ export class LocalStorageService implements S3Service {
|
||||
}
|
||||
|
||||
const storageBackend = process.env.STORAGE_BACKEND || 'local'
|
||||
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || 'http://localhost:3000'
|
||||
const port = process.env.SHUMAI_SERVER_PORT || '3000'
|
||||
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || 'http://localhost'
|
||||
|
||||
export const s3Service: S3Service =
|
||||
storageBackend === 's3'
|
||||
@@ -463,4 +464,4 @@ export const s3Service: S3Service =
|
||||
process.env.S3_USE_SSL === 'true',
|
||||
process.env.S3_REGION || 'auto',
|
||||
)
|
||||
: new LocalStorageService(s3Endpoint)
|
||||
: new LocalStorageService(`${s3Endpoint}:${port}`)
|
||||
|
||||
@@ -303,6 +303,7 @@ describe('SearchService', () => {
|
||||
// SelectMulti Metadata
|
||||
{ field: 'multi', op: 'hasAny', val: ['a'], expected: ['multi-a-b'] },
|
||||
{ field: 'multi', op: 'hasAny', val: ['b'], expected: ['multi-a-b', 'multi-b-c'] },
|
||||
{ field: 'multi', op: 'hasAny', val: ['a', 'c'], expected: ['multi-a-b', 'multi-b-c'] },
|
||||
{ field: 'multi', op: 'hasAll', val: ['a', 'b'], expected: ['multi-a-b'] },
|
||||
{ field: 'multi', op: 'hasAll', val: ['a', 'c'], expected: [] },
|
||||
{
|
||||
@@ -323,6 +324,23 @@ describe('SearchService', () => {
|
||||
'nothing',
|
||||
],
|
||||
},
|
||||
{
|
||||
field: 'multi',
|
||||
op: 'hasNone',
|
||||
val: ['a', 'c'],
|
||||
expected: [
|
||||
'str-apple',
|
||||
'str-banana',
|
||||
'num-10',
|
||||
'num-20',
|
||||
'bool-true',
|
||||
'bool-false',
|
||||
'date-today',
|
||||
'date-yesterday',
|
||||
'name-contains-test',
|
||||
'nothing',
|
||||
],
|
||||
},
|
||||
{ field: 'multi', op: 'eq', val: ['a', 'b'], expected: ['multi-a-b'] },
|
||||
|
||||
// Date Metadata
|
||||
|
||||
@@ -355,11 +355,16 @@ export class SqlQueryBuilder {
|
||||
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
|
||||
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
|
||||
}
|
||||
case 'hasAny':
|
||||
case 'hasAll':
|
||||
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
|
||||
case 'hasNone':
|
||||
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
|
||||
case 'hasAny': {
|
||||
const valArr = (Array.isArray(value) ? value : [value]).map(String)
|
||||
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND jsonb_exists_any(json_value, ${valArr}::text[]))`
|
||||
}
|
||||
case 'hasNone': {
|
||||
const valArr = (Array.isArray(value) ? value : [value]).map(String)
|
||||
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND jsonb_exists_any(json_value, ${valArr}::text[]))`
|
||||
}
|
||||
case 'isWithin': {
|
||||
const range = this.parseDateRange(value)
|
||||
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${range.start} AND date_value <= ${range.end})`
|
||||
|
||||
@@ -224,17 +224,21 @@ describe('ShareService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('updates a share link including fieldVisibility', async () => {
|
||||
it('updates a share link including fieldVisibility, viewMode, and defaultSortOrder', async () => {
|
||||
const shareLink = await shareService.createShareLink(projectId, { name: 'Old Name' })
|
||||
const updated = await shareService.updateShareLink(shareLink.id, {
|
||||
name: 'New Name',
|
||||
password: 'new-password',
|
||||
fieldVisibility: { field1: true, field2: false },
|
||||
viewMode: 'list',
|
||||
defaultSortOrder: 'name:desc',
|
||||
})
|
||||
|
||||
expect(updated.name).toBe('New Name')
|
||||
expect(updated.hasPassword).toBe(true)
|
||||
expect(updated.fieldVisibility).toEqual({ field1: true, field2: false })
|
||||
expect(updated.viewMode).toBe('list')
|
||||
expect(updated.defaultSortOrder).toBe('name:desc')
|
||||
|
||||
const rootAsset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
|
||||
expect(rootAsset?.name).toBe('New Name')
|
||||
|
||||
@@ -58,6 +58,7 @@ export class ShareService {
|
||||
password: req.password,
|
||||
isDisabled: req.isDisabled ?? false,
|
||||
defaultSortOrder: req.defaultSortOrder,
|
||||
viewMode: req.viewMode,
|
||||
projectId: projectId,
|
||||
rootFolderId: shareFolder.id,
|
||||
creatorId,
|
||||
@@ -84,6 +85,7 @@ export class ShareService {
|
||||
password: req.password,
|
||||
isDisabled: req.isDisabled,
|
||||
defaultSortOrder: req.defaultSortOrder,
|
||||
viewMode: req.viewMode,
|
||||
fieldVisibility: (req.fieldVisibility as PrismaJson.ShareLinkFieldVisibility) ?? undefined,
|
||||
},
|
||||
include: { creator: true },
|
||||
@@ -300,6 +302,7 @@ export class ShareService {
|
||||
isDisabled: l.isDisabled,
|
||||
hasPassword: !!l.password,
|
||||
defaultSortOrder: l.defaultSortOrder,
|
||||
viewMode: l.viewMode,
|
||||
fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined,
|
||||
rootFolderId: l.rootFolderId,
|
||||
projectId: l.projectId,
|
||||
|
||||
@@ -349,7 +349,9 @@ export class TeamService {
|
||||
const count = await prisma.user.count()
|
||||
|
||||
return {
|
||||
initialized: count > 0,
|
||||
userCount: count,
|
||||
demoMode: process.env.SHUMAI_DEMO_MODE === '1',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -145,6 +145,29 @@ describe('TranscodeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle rational fraction frame rate for video transcoding', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
})
|
||||
|
||||
const outputFile = path.join(tempDir, 'output_rational.mp4')
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: 'input.mp4',
|
||||
outputFile,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
frameRate: '160000/142512',
|
||||
disableAudio: true,
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-filter_complex', expect.stringContaining('fps=160000/142512')]),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('should use sharp for image transcoding', async () => {
|
||||
const outputFile = path.join(tempDir, 'output.webp')
|
||||
await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface TranscodeVideoParams {
|
||||
outputFile: string
|
||||
width: number
|
||||
height: number
|
||||
frameRate?: number
|
||||
frameRate?: number | string
|
||||
disableAudio?: boolean
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ export class TranscodeService {
|
||||
|
||||
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
|
||||
|
||||
await execFileAsync('ffmpeg', ['-y', ...args])
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
}
|
||||
|
||||
async transcodeImage(
|
||||
@@ -222,12 +222,12 @@ export class TranscodeService {
|
||||
'1024',
|
||||
outputPoster,
|
||||
]
|
||||
await execFileAsync('ffmpeg', ['-y', ...args])
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
}
|
||||
|
||||
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
|
||||
const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile]
|
||||
await execFileAsync('ffmpeg', ['-y', ...args])
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
}
|
||||
|
||||
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
|
||||
@@ -252,7 +252,7 @@ export class TranscodeService {
|
||||
'80',
|
||||
outputPattern,
|
||||
]
|
||||
await execFileAsync('ffmpeg', ['-y', ...args])
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
|
||||
const files = fs.readdirSync(params.outputDir)
|
||||
return files
|
||||
@@ -370,7 +370,7 @@ export class TranscodeService {
|
||||
'80',
|
||||
localShotPath,
|
||||
]
|
||||
await execFileAsync('ffmpeg', ['-y', ...args])
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
|
||||
// 5. Overlay annotations if timestamp matches commentTimestamp exactly
|
||||
if (
|
||||
|
||||
@@ -294,33 +294,6 @@ export class UploadService {
|
||||
})
|
||||
}
|
||||
|
||||
// Ai Embedding if enabled via agent
|
||||
const embeddingAgent = await tx.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: team.id } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (embeddingAgent) {
|
||||
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: team.id,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId,
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage = asset.mediaType?.startsWith('image/')
|
||||
if (!isVideo && !isImage) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach, type MockInstance } from 'vitest'
|
||||
import { existsSync, writeFileSync, readFileSync, rmSync, mkdirSync, openSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { handleDaemonCommands } from './daemon'
|
||||
import { spawn } from 'node:child_process'
|
||||
|
||||
// Mock os.homedir to return a temporary directory for test isolation
|
||||
vi.mock('node:os', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:os')>()
|
||||
const mockTempDir = `${actual.tmpdir()}/shumai-test-daemon-${Math.random().toString(36).substring(2)}`
|
||||
return {
|
||||
...actual,
|
||||
homedir: () => mockTempDir,
|
||||
}
|
||||
})
|
||||
|
||||
// Mock node:child_process for spawn tests
|
||||
vi.mock('node:child_process', () => {
|
||||
return {
|
||||
spawn: vi.fn(() => {
|
||||
return {
|
||||
pid: 99999,
|
||||
unref: vi.fn(),
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
// Mock node:fs to mock openSync for ESM safety
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>()
|
||||
return {
|
||||
...actual,
|
||||
openSync: vi.fn(() => 42),
|
||||
}
|
||||
})
|
||||
|
||||
import { homedir } from 'node:os'
|
||||
|
||||
describe('handleDaemonCommands', () => {
|
||||
const appName = 'test-app'
|
||||
const mockTempDir = homedir()
|
||||
const pidFile = join(mockTempDir, '.shumai', 'pids', `${appName}.pid`)
|
||||
|
||||
let mockExit: MockInstance<typeof process.exit>
|
||||
let mockKill: MockInstance<typeof process.kill>
|
||||
const originalArgv = process.argv
|
||||
|
||||
beforeEach(() => {
|
||||
mkdirSync(mockTempDir, { recursive: true })
|
||||
mockExit = vi.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw new Error('process.exit')
|
||||
})
|
||||
mockKill = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
|
||||
vi.mocked(spawn).mockClear()
|
||||
vi.mocked(openSync).mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.argv = originalArgv
|
||||
vi.restoreAllMocks()
|
||||
try {
|
||||
rmSync(mockTempDir, { recursive: true, force: true })
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
})
|
||||
|
||||
it('runs the runFn on normal startup', async () => {
|
||||
process.argv = ['node', 'script.js']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
await handleDaemonCommands(appName, runFn)
|
||||
|
||||
expect(runFn).toHaveBeenCalled()
|
||||
expect(existsSync(pidFile)).toBe(true)
|
||||
expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString())
|
||||
})
|
||||
|
||||
it('stops the process if stop command is passed', async () => {
|
||||
process.argv = ['node', 'script.js', 'stop']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
// Write a dummy PID file
|
||||
mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true })
|
||||
writeFileSync(pidFile, '12345')
|
||||
|
||||
await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit')
|
||||
|
||||
expect(runFn).not.toHaveBeenCalled()
|
||||
expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM')
|
||||
expect(mockExit).toHaveBeenCalledWith(0)
|
||||
expect(openSync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('daemonizes the process if -d is passed', async () => {
|
||||
process.argv = ['node', 'script.js', '-d']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit')
|
||||
|
||||
expect(runFn).not.toHaveBeenCalled()
|
||||
expect(spawn).toHaveBeenCalled()
|
||||
expect(existsSync(pidFile)).toBe(true)
|
||||
expect(readFileSync(pidFile, 'utf8').trim()).toBe('99999')
|
||||
expect(mockExit).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('restarts the process if restart command is passed', async () => {
|
||||
process.argv = ['node', 'script.js', 'restart']
|
||||
const runFn = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
// Write a dummy PID file
|
||||
mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true })
|
||||
writeFileSync(pidFile, '12345')
|
||||
|
||||
await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit')
|
||||
|
||||
expect(runFn).not.toHaveBeenCalled()
|
||||
expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM')
|
||||
expect(spawn).toHaveBeenCalled()
|
||||
expect(mockExit).toHaveBeenCalledWith(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,269 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import {
|
||||
existsSync,
|
||||
writeFileSync,
|
||||
readFileSync,
|
||||
unlinkSync,
|
||||
mkdirSync,
|
||||
statSync,
|
||||
createReadStream,
|
||||
openSync,
|
||||
} from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
|
||||
const SHUMAI_DIR = join(homedir(), '.shumai')
|
||||
const PID_DIR = join(SHUMAI_DIR, 'pids')
|
||||
const LOG_DIR = join(SHUMAI_DIR, 'logs')
|
||||
|
||||
function isProcessRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (err) {
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code === 'EPERM') {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function stopProcess(appName: string, pidFile: string): Promise<boolean> {
|
||||
if (!existsSync(pidFile)) {
|
||||
console.log(`No running instance of ${appName} found.`)
|
||||
return false
|
||||
}
|
||||
|
||||
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
|
||||
if (isNaN(pid)) {
|
||||
console.log(`Invalid PID found in ${pidFile}. Cleaning up file.`)
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
let isRunning = isProcessRunning(pid)
|
||||
if (!isRunning) {
|
||||
console.log(`Process ${pid} is not running. Cleaning up PID file.`)
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
console.log(`Stopping ${appName} (PID: ${pid})...`)
|
||||
try {
|
||||
process.kill(pid, 'SIGTERM')
|
||||
} catch (err) {
|
||||
console.error(`Failed to send SIGTERM to process ${pid}:`, err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Wait for it to stop
|
||||
for (let i = 0; i < 30; i++) {
|
||||
if (!isProcessRunning(pid)) {
|
||||
isRunning = false
|
||||
break
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
console.log(`Process ${pid} did not stop gracefully. Sending SIGKILL...`)
|
||||
try {
|
||||
process.kill(pid, 'SIGKILL')
|
||||
} catch (err) {
|
||||
console.error(`Failed to send SIGKILL to process ${pid}:`, err)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
console.log(`Successfully stopped ${appName}.`)
|
||||
return true
|
||||
}
|
||||
|
||||
function startDaemon(appName: string, pidFile: string, logFile: string): void {
|
||||
// Check if already running
|
||||
if (existsSync(pidFile)) {
|
||||
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
|
||||
if (!isNaN(pid) && pid !== process.pid) {
|
||||
if (isProcessRunning(pid)) {
|
||||
console.error(
|
||||
`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`,
|
||||
)
|
||||
process.exit(1)
|
||||
} else {
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Starting ${appName} in background...`)
|
||||
const logFd = openSync(logFile, 'w')
|
||||
|
||||
const childArgs = process.argv.slice(1).filter((arg) => arg !== '-d' && arg !== 'restart')
|
||||
|
||||
const child = spawn(process.argv[0], childArgs, {
|
||||
detached: true,
|
||||
stdio: ['ignore', logFd, logFd],
|
||||
env: {
|
||||
...process.env,
|
||||
SHUMAI_DAEMONIZED: 'true',
|
||||
},
|
||||
})
|
||||
|
||||
if (child.pid === undefined) {
|
||||
console.error(`Failed to spawn background process for ${appName}.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
child.unref()
|
||||
writeFileSync(pidFile, child.pid.toString(), 'utf8')
|
||||
console.log(`🚀 Started ${appName} in background (PID: ${child.pid}).`)
|
||||
console.log(`📄 Logs are being written to ${logFile}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
function viewLogs(appName: string, logFile: string): void {
|
||||
if (!existsSync(logFile)) {
|
||||
console.log(`No log file found for ${appName}.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Print existing content (last 100 lines)
|
||||
const content = readFileSync(logFile, 'utf8')
|
||||
const lines = content.split('\n')
|
||||
const lastLines = lines.slice(-100).join('\n')
|
||||
process.stdout.write(lastLines + '\n')
|
||||
|
||||
let cursor = statSync(logFile).size
|
||||
const interval = setInterval(() => {
|
||||
try {
|
||||
if (existsSync(logFile)) {
|
||||
const stats = statSync(logFile)
|
||||
if (stats.size > cursor) {
|
||||
const stream = createReadStream(logFile, { start: cursor, end: stats.size - 1 })
|
||||
stream.pipe(process.stdout, { end: false })
|
||||
cursor = stats.size
|
||||
} else if (stats.size < cursor) {
|
||||
cursor = stats.size
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore read errors
|
||||
}
|
||||
}, 250)
|
||||
|
||||
const cleanup = () => {
|
||||
clearInterval(interval)
|
||||
process.exit(0)
|
||||
}
|
||||
process.on('SIGINT', cleanup)
|
||||
process.on('SIGTERM', cleanup)
|
||||
}
|
||||
|
||||
export async function handleDaemonCommands(
|
||||
appName: string,
|
||||
runFn: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const pidFile = join(PID_DIR, `${appName}.pid`)
|
||||
const logFile = join(LOG_DIR, `${appName}.log`)
|
||||
|
||||
// Ensure directories exist
|
||||
mkdirSync(PID_DIR, { recursive: true })
|
||||
mkdirSync(LOG_DIR, { recursive: true })
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const isStop = args.includes('stop')
|
||||
const isRestart = args.includes('restart')
|
||||
const isLogs = args.includes('logs')
|
||||
const isDaemon = args.includes('-d') && process.env.SHUMAI_DAEMONIZED !== 'true'
|
||||
|
||||
if (isStop) {
|
||||
await stopProcess(appName, pidFile)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (isRestart) {
|
||||
await stopProcess(appName, pidFile)
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
startDaemon(appName, pidFile, logFile)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (isLogs) {
|
||||
viewLogs(appName, logFile)
|
||||
// Keep process open for logs tailing
|
||||
return new Promise(() => {})
|
||||
}
|
||||
|
||||
if (isDaemon) {
|
||||
startDaemon(appName, pidFile, logFile)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Normal Startup logic: check if already running
|
||||
if (existsSync(pidFile)) {
|
||||
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
|
||||
if (!isNaN(pid) && pid !== process.pid) {
|
||||
if (isProcessRunning(pid)) {
|
||||
console.error(
|
||||
`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`,
|
||||
)
|
||||
process.exit(1)
|
||||
} else {
|
||||
// Process is dead, clean up PID file
|
||||
try {
|
||||
unlinkSync(pidFile)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write the PID file
|
||||
writeFileSync(pidFile, process.pid.toString(), 'utf8')
|
||||
|
||||
const cleanPidFile = () => {
|
||||
try {
|
||||
if (existsSync(pidFile)) {
|
||||
const pidStr = readFileSync(pidFile, 'utf8').trim()
|
||||
if (parseInt(pidStr, 10) === process.pid) {
|
||||
unlinkSync(pidFile)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Register cleanups
|
||||
process.on('exit', cleanPidFile)
|
||||
|
||||
const handleSignal = (signal: string) => {
|
||||
if (process.listenerCount(signal) === 1) {
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => handleSignal('SIGINT'))
|
||||
process.on('SIGTERM', () => handleSignal('SIGTERM'))
|
||||
|
||||
// Run the main app
|
||||
await runFn()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "share_links" ADD COLUMN "view_mode" TEXT;
|
||||
@@ -338,6 +338,7 @@ model ShareLink {
|
||||
password String?
|
||||
isDisabled Boolean @default(false) @map("is_disabled")
|
||||
defaultSortOrder String? @map("default_sort_order")
|
||||
viewMode String? @map("view_mode")
|
||||
/// [ShareLinkFieldVisibility]
|
||||
fieldVisibility Json? @map("field_visibility")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3038,6 +3038,7 @@ export const ShareLinkScalarFieldEnum = {
|
||||
password: 'password',
|
||||
isDisabled: 'isDisabled',
|
||||
defaultSortOrder: 'defaultSortOrder',
|
||||
viewMode: 'viewMode',
|
||||
fieldVisibility: 'fieldVisibility',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
|
||||
@@ -253,6 +253,7 @@ export const ShareLinkScalarFieldEnum = {
|
||||
password: 'password',
|
||||
isDisabled: 'isDisabled',
|
||||
defaultSortOrder: 'defaultSortOrder',
|
||||
viewMode: 'viewMode',
|
||||
fieldVisibility: 'fieldVisibility',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
|
||||
@@ -32,6 +32,7 @@ export type ShareLinkMinAggregateOutputType = {
|
||||
password: string | null
|
||||
isDisabled: boolean | null
|
||||
defaultSortOrder: string | null
|
||||
viewMode: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
projectId: string | null
|
||||
@@ -46,6 +47,7 @@ export type ShareLinkMaxAggregateOutputType = {
|
||||
password: string | null
|
||||
isDisabled: boolean | null
|
||||
defaultSortOrder: string | null
|
||||
viewMode: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
projectId: string | null
|
||||
@@ -60,6 +62,7 @@ export type ShareLinkCountAggregateOutputType = {
|
||||
password: number
|
||||
isDisabled: number
|
||||
defaultSortOrder: number
|
||||
viewMode: number
|
||||
fieldVisibility: PrismaJson.ShareLinkFieldVisibility
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
@@ -76,6 +79,7 @@ export type ShareLinkMinAggregateInputType = {
|
||||
password?: true
|
||||
isDisabled?: true
|
||||
defaultSortOrder?: true
|
||||
viewMode?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
projectId?: true
|
||||
@@ -90,6 +94,7 @@ export type ShareLinkMaxAggregateInputType = {
|
||||
password?: true
|
||||
isDisabled?: true
|
||||
defaultSortOrder?: true
|
||||
viewMode?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
projectId?: true
|
||||
@@ -104,6 +109,7 @@ export type ShareLinkCountAggregateInputType = {
|
||||
password?: true
|
||||
isDisabled?: true
|
||||
defaultSortOrder?: true
|
||||
viewMode?: true
|
||||
fieldVisibility?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -195,6 +201,7 @@ export type ShareLinkGroupByOutputType = {
|
||||
password: string | null
|
||||
isDisabled: boolean
|
||||
defaultSortOrder: string | null
|
||||
viewMode: string | null
|
||||
fieldVisibility: PrismaJson.ShareLinkFieldVisibility | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
@@ -228,6 +235,7 @@ export type ShareLinkWhereInput = {
|
||||
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
|
||||
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
|
||||
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
@@ -246,6 +254,7 @@ export type ShareLinkOrderByWithRelationInput = {
|
||||
password?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
isDisabled?: Prisma.SortOrder
|
||||
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -269,6 +278,7 @@ export type ShareLinkWhereUniqueInput = Prisma.AtLeast<
|
||||
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
|
||||
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
|
||||
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
@@ -288,6 +298,7 @@ export type ShareLinkOrderByWithAggregationInput = {
|
||||
password?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
isDisabled?: Prisma.SortOrder
|
||||
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -313,6 +324,7 @@ export type ShareLinkScalarWhereWithAggregatesInput = {
|
||||
password?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
|
||||
isDisabled?: Prisma.BoolWithAggregatesFilter<'ShareLink'> | boolean
|
||||
defaultSortOrder?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
|
||||
viewMode?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
|
||||
fieldVisibility?: Prisma.JsonNullableWithAggregatesFilter<'ShareLink'>
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string
|
||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string
|
||||
@@ -328,6 +340,7 @@ export type ShareLinkCreateInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -343,6 +356,7 @@ export type ShareLinkUncheckedCreateInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -358,6 +372,7 @@ export type ShareLinkUpdateInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -373,6 +388,7 @@ export type ShareLinkUncheckedUpdateInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -388,6 +404,7 @@ export type ShareLinkCreateManyInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -403,6 +420,7 @@ export type ShareLinkUpdateManyMutationInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -415,6 +433,7 @@ export type ShareLinkUncheckedUpdateManyInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -440,6 +459,7 @@ export type ShareLinkCountOrderByAggregateInput = {
|
||||
password?: Prisma.SortOrder
|
||||
isDisabled?: Prisma.SortOrder
|
||||
defaultSortOrder?: Prisma.SortOrder
|
||||
viewMode?: Prisma.SortOrder
|
||||
fieldVisibility?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -455,6 +475,7 @@ export type ShareLinkMaxOrderByAggregateInput = {
|
||||
password?: Prisma.SortOrder
|
||||
isDisabled?: Prisma.SortOrder
|
||||
defaultSortOrder?: Prisma.SortOrder
|
||||
viewMode?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
projectId?: Prisma.SortOrder
|
||||
@@ -469,6 +490,7 @@ export type ShareLinkMinOrderByAggregateInput = {
|
||||
password?: Prisma.SortOrder
|
||||
isDisabled?: Prisma.SortOrder
|
||||
defaultSortOrder?: Prisma.SortOrder
|
||||
viewMode?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
projectId?: Prisma.SortOrder
|
||||
@@ -716,6 +738,7 @@ export type ShareLinkCreateWithoutCreatorInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -730,6 +753,7 @@ export type ShareLinkUncheckedCreateWithoutCreatorInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -788,6 +812,7 @@ export type ShareLinkScalarWhereInput = {
|
||||
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
|
||||
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
|
||||
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
|
||||
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
|
||||
@@ -803,6 +828,7 @@ export type ShareLinkCreateWithoutProjectInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -817,6 +843,7 @@ export type ShareLinkUncheckedCreateWithoutProjectInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -872,6 +899,7 @@ export type ShareLinkCreateWithoutRootFolderInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -886,6 +914,7 @@ export type ShareLinkUncheckedCreateWithoutRootFolderInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -928,6 +957,7 @@ export type ShareLinkUpdateWithoutRootFolderInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -942,6 +972,7 @@ export type ShareLinkUncheckedUpdateWithoutRootFolderInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -956,6 +987,7 @@ export type ShareLinkCreateManyCreatorInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -970,6 +1002,7 @@ export type ShareLinkUpdateWithoutCreatorInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -984,6 +1017,7 @@ export type ShareLinkUncheckedUpdateWithoutCreatorInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -998,6 +1032,7 @@ export type ShareLinkUncheckedUpdateManyWithoutCreatorInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1012,6 +1047,7 @@ export type ShareLinkCreateManyProjectInput = {
|
||||
password?: string | null
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: string | null
|
||||
viewMode?: string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -1026,6 +1062,7 @@ export type ShareLinkUpdateWithoutProjectInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1040,6 +1077,7 @@ export type ShareLinkUncheckedUpdateWithoutProjectInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1054,6 +1092,7 @@ export type ShareLinkUncheckedUpdateManyWithoutProjectInput = {
|
||||
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1071,6 +1110,7 @@ export type ShareLinkSelect<
|
||||
password?: boolean
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: boolean
|
||||
viewMode?: boolean
|
||||
fieldVisibility?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -1094,6 +1134,7 @@ export type ShareLinkSelectCreateManyAndReturn<
|
||||
password?: boolean
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: boolean
|
||||
viewMode?: boolean
|
||||
fieldVisibility?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -1117,6 +1158,7 @@ export type ShareLinkSelectUpdateManyAndReturn<
|
||||
password?: boolean
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: boolean
|
||||
viewMode?: boolean
|
||||
fieldVisibility?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -1137,6 +1179,7 @@ export type ShareLinkSelectScalar = {
|
||||
password?: boolean
|
||||
isDisabled?: boolean
|
||||
defaultSortOrder?: boolean
|
||||
viewMode?: boolean
|
||||
fieldVisibility?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
@@ -1154,6 +1197,7 @@ export type ShareLinkOmit<
|
||||
| 'password'
|
||||
| 'isDisabled'
|
||||
| 'defaultSortOrder'
|
||||
| 'viewMode'
|
||||
| 'fieldVisibility'
|
||||
| 'createdAt'
|
||||
| 'updatedAt'
|
||||
@@ -1201,6 +1245,7 @@ export type $ShareLinkPayload<
|
||||
password: string | null
|
||||
isDisabled: boolean
|
||||
defaultSortOrder: string | null
|
||||
viewMode: string | null
|
||||
/**
|
||||
* [ShareLinkFieldVisibility]
|
||||
*/
|
||||
@@ -1823,6 +1868,7 @@ export interface ShareLinkFieldRefs {
|
||||
readonly password: Prisma.FieldRef<'ShareLink', 'String'>
|
||||
readonly isDisabled: Prisma.FieldRef<'ShareLink', 'Boolean'>
|
||||
readonly defaultSortOrder: Prisma.FieldRef<'ShareLink', 'String'>
|
||||
readonly viewMode: Prisma.FieldRef<'ShareLink', 'String'>
|
||||
readonly fieldVisibility: Prisma.FieldRef<'ShareLink', 'Json'>
|
||||
readonly createdAt: Prisma.FieldRef<'ShareLink', 'DateTime'>
|
||||
readonly updatedAt: Prisma.FieldRef<'ShareLink', 'DateTime'>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { PrismaClient, WorkflowTask } from './generated/prisma/client'
|
||||
import { PrismaTestingHelper } from './prisma-testing-helper'
|
||||
import { PrismaPg } from '@prisma/adapter-pg'
|
||||
import { Pool } from 'pg'
|
||||
import { PrismaClient, WorkflowTask } from './generated/prisma/client'
|
||||
import { PrismaTestingHelper } from './prisma-testing-helper'
|
||||
import { generateNgrams } from './utils/ngram'
|
||||
|
||||
// Global callback for workflow task creation (decouples db package from workflow engine)
|
||||
@@ -26,6 +26,7 @@ function createPrismaClient() {
|
||||
const pool = new Pool({ connectionString })
|
||||
const adapter = new PrismaPg(pool)
|
||||
const client = new PrismaClient({ adapter, log: ['error'] })
|
||||
|
||||
return client.$extends({
|
||||
query: {
|
||||
workflowTask: {
|
||||
@@ -48,7 +49,14 @@ function createPrismaClient() {
|
||||
if (typeof args.data.name === 'string') {
|
||||
args.data.nameNgram = generateNgrams(args.data.name)
|
||||
}
|
||||
return query(args)
|
||||
const result = await query(args)
|
||||
if (args.where) {
|
||||
await client.project.updateMany({
|
||||
where: { assets: { some: args.where } },
|
||||
data: { updatedAt: new Date() },
|
||||
})
|
||||
}
|
||||
return result
|
||||
},
|
||||
async upsert({ args, query }) {
|
||||
if (typeof args.create.name === 'string') {
|
||||
@@ -95,5 +103,5 @@ export function getPrismaTestingHelper() {
|
||||
return prismaTestingHelper
|
||||
}
|
||||
|
||||
export * from './utils/ngram'
|
||||
export * from './generated/prisma/client'
|
||||
export * from './utils/ngram'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -21,6 +21,9 @@ export const assetPreviewSchema = z.object({
|
||||
mediaType: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
preview: z.string().optional(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
})
|
||||
|
||||
export type AssetPreview = z.infer<typeof assetPreviewSchema>
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface ShareLinkInfo {
|
||||
isDisabled: boolean
|
||||
hasPassword: boolean
|
||||
defaultSortOrder?: string
|
||||
viewMode?: string
|
||||
fieldVisibility?: Record<string, boolean>
|
||||
rootFolderId: string
|
||||
projectId: string
|
||||
@@ -23,6 +24,7 @@ export const createShareLinkRequestSchema = z.object({
|
||||
password: z.string().optional(),
|
||||
isDisabled: z.boolean().optional(),
|
||||
defaultSortOrder: z.string().optional(),
|
||||
viewMode: z.string().optional(),
|
||||
})
|
||||
|
||||
export type CreateShareLinkRequest = z.infer<typeof createShareLinkRequestSchema>
|
||||
@@ -33,6 +35,7 @@ export const updateShareLinkRequestSchema = z.object({
|
||||
password: z.string().optional().nullable(),
|
||||
isDisabled: z.boolean().optional(),
|
||||
defaultSortOrder: z.string().optional().nullable(),
|
||||
viewMode: z.string().optional().nullable(),
|
||||
fieldVisibility: z.record(z.string(), z.boolean()).optional().nullable(),
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -4,6 +4,11 @@ import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import * as child_process from 'child_process'
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execFile: vi.fn(),
|
||||
}))
|
||||
import {
|
||||
getMediaInfoActivity,
|
||||
overlayAnnotationsActivity,
|
||||
@@ -13,6 +18,8 @@ import {
|
||||
downloadMediaToTmpActivity,
|
||||
transcodeImageActivity,
|
||||
generateSpriteActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
deleteS3ObjectActivity,
|
||||
} from './transcode'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
@@ -22,6 +29,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
headObject: vi.fn(),
|
||||
presign: vi.fn(),
|
||||
downloadToFile: vi.fn(),
|
||||
deleteObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -365,4 +373,67 @@ describe('Transcode Activities', () => {
|
||||
).rejects.toThrowError(/Overlay annotations failed/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Video Chunk Activities', () => {
|
||||
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
|
||||
// Mock child_process.execFile to simulate ffmpeg succeeding
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
const res = await transcodeVideoChunkActivity({
|
||||
assetId: 'asset-abc',
|
||||
filePath: '/tmp/full-video.mp4',
|
||||
startTime: 10,
|
||||
endTime: 25,
|
||||
})
|
||||
|
||||
// Verify ffmpeg command args
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining([
|
||||
'-y',
|
||||
'-i',
|
||||
'/tmp/full-video.mp4',
|
||||
'-ss',
|
||||
'10',
|
||||
'-t',
|
||||
'15',
|
||||
'-vf',
|
||||
'fps=1',
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'ultrafast',
|
||||
'-crf',
|
||||
'28',
|
||||
'-an',
|
||||
]),
|
||||
expect.any(Function),
|
||||
)
|
||||
|
||||
// Verify S3 upload
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
expect.stringMatching(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/),
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/)
|
||||
})
|
||||
|
||||
it('should delete S3 object successfully', async () => {
|
||||
await deleteS3ObjectActivity({ key: 'files/test-key.mp4' })
|
||||
expect(s3Service.deleteObject).toHaveBeenCalledWith('shumai', 'files/test-key.mp4')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export interface GetMediaInfoActivityParams {
|
||||
assetId: string
|
||||
@@ -166,7 +172,7 @@ export async function transcodeVideoActivity(
|
||||
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
|
||||
|
||||
try {
|
||||
let targetFps = 0
|
||||
let targetFps: number | string = 0
|
||||
let disableAudio = false
|
||||
|
||||
if (params.videoSpec.resolution === '180p') {
|
||||
@@ -175,8 +181,8 @@ export async function transcodeVideoActivity(
|
||||
if (params.originalFps > 0 && params.originalFps < 24.0) {
|
||||
targetFps = params.originalFps
|
||||
}
|
||||
if (params.duration * targetFps > 1600) {
|
||||
targetFps = 1600 / params.duration
|
||||
if (params.duration * (targetFps as number) > 1600) {
|
||||
targetFps = `160000/${Math.floor(params.duration * 100)}`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,3 +474,139 @@ export async function overlayAnnotationsActivity(params: {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateEmbeddingTaskIfEnabledParams {
|
||||
assetId: string
|
||||
teamId: string | null
|
||||
projectId: string | null
|
||||
}
|
||||
|
||||
export async function createEmbeddingTaskIfEnabledActivity(
|
||||
params: CreateEmbeddingTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
let teamId = params.teamId
|
||||
let projectId = params.projectId
|
||||
|
||||
// Resolve teamId and projectId from asset if missing
|
||||
if (!teamId || !projectId) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (asset) {
|
||||
projectId = projectId || asset.projectId
|
||||
teamId = teamId || asset.project?.teamId || null
|
||||
}
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active embedding agent for the team
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create embedding task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface TranscodeVideoChunkParams {
|
||||
assetId: string
|
||||
filePath: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunkActivity(
|
||||
params: TranscodeVideoChunkParams,
|
||||
): Promise<{ chunkKey: string }> {
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
|
||||
try {
|
||||
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
'-i',
|
||||
params.filePath,
|
||||
'-ss',
|
||||
params.startTime.toString(),
|
||||
'-t',
|
||||
(params.endTime - params.startTime).toString(),
|
||||
'-vf',
|
||||
'fps=1',
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'ultrafast',
|
||||
'-crf',
|
||||
'28',
|
||||
'-an',
|
||||
chunkTmp,
|
||||
])
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
|
||||
// Upload to S3
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
|
||||
|
||||
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
|
||||
|
||||
return { chunkKey: key }
|
||||
} catch (err) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
} finally {
|
||||
if (fs.existsSync(chunkTmp)) {
|
||||
try {
|
||||
fs.unlinkSync(chunkTmp)
|
||||
} catch (e) {
|
||||
console.error('Failed to cleanup local chunk file:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ describe('Transcode Workflow', () => {
|
||||
overlayAnnotationsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'overlayAnnotationsActivity',
|
||||
}),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -134,6 +137,12 @@ describe('Transcode Workflow', () => {
|
||||
status: AssetStatus.processed,
|
||||
})
|
||||
|
||||
expect(mockActivities.createEmbeddingTaskIfEnabledActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
@@ -205,6 +214,12 @@ describe('Transcode Workflow', () => {
|
||||
assetId: 'asset-image',
|
||||
status: AssetStatus.processed,
|
||||
})
|
||||
|
||||
expect(mockActivities.createEmbeddingTaskIfEnabledActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-image',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
|
||||
@@ -18,6 +18,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
cleanupTmpDirActivity,
|
||||
takeScreenshotsActivity,
|
||||
overlayAnnotationsActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
let tmpDir: string | undefined
|
||||
@@ -245,6 +246,13 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'processed',
|
||||
})
|
||||
|
||||
// 11.5 Create AI embedding task if enabled
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
// 12. Update Task Status
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import type { AncestorFolder } from '@shumai/dtos'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
DockToLeft,
|
||||
@@ -18,9 +16,11 @@ import {
|
||||
DockToRight,
|
||||
DockToRightFilled,
|
||||
} from '@/ui/components/ui/icons'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ChevronDown, LayoutGrid, List, History, Check, FileIcon } from 'lucide-react'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import type { AncestorFolder } from '@shumai/dtos'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { Check, ChevronDown, FileIcon, History, LayoutGrid, List } from 'lucide-react'
|
||||
|
||||
interface BreadcrumbNavProps {
|
||||
teamId: string
|
||||
|
||||
@@ -119,31 +119,35 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
|
||||
if (isEditing) {
|
||||
return (
|
||||
<div className="relative w-full" ref={containerRef}>
|
||||
<div className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm shadow-sm min-h-[28px] flex items-center">
|
||||
{value ? getDisplayValue(value) : <span className="text-gray-400">Select date...</span>}
|
||||
<div className="w-full px-2 py-1 border border-ring rounded bg-background text-sm shadow-sm min-h-[28px] flex items-center">
|
||||
{value ? (
|
||||
getDisplayValue(value)
|
||||
) : (
|
||||
<span className="text-muted-foreground">Select date...</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="absolute z-50 top-full left-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
|
||||
<div className="absolute z-50 top-full left-0 mt-1 bg-popover border border-border rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
|
||||
{/* Date Picker */}
|
||||
<div className="p-4 w-64">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
{/* Replaced subMonths with addMonths(-1) */}
|
||||
<button
|
||||
onClick={() => setViewDate(addMonths(viewDate, -1))}
|
||||
className="p-1 hover:bg-gray-100 rounded"
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</button>
|
||||
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
|
||||
<button
|
||||
onClick={() => setViewDate(addMonths(viewDate, 1))}
|
||||
className="p-1 hover:bg-gray-100 rounded"
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-gray-500">
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-muted-foreground">
|
||||
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
|
||||
<div key={d}>{d}</div>
|
||||
))}
|
||||
@@ -166,8 +170,10 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
|
||||
<button
|
||||
key={date.toString()}
|
||||
onClick={() => handleDateClick(date)}
|
||||
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-50 transition-colors ${
|
||||
isSelected ? 'bg-blue-50 text-white hover:bg-blue-600' : 'text-gray-700'
|
||||
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-accent transition-colors ${
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground hover:bg-primary/90'
|
||||
: 'text-foreground'
|
||||
}`}
|
||||
>
|
||||
{getDate(date)}
|
||||
@@ -179,17 +185,17 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
|
||||
|
||||
{/* Time Picker */}
|
||||
{dateConfig?.includeTime && (
|
||||
<div className="border-l border-gray-200 bg-gray-50 w-32 flex flex-col">
|
||||
<div className="p-2 border-b border-gray-200 text-xs font-semibold text-gray-500 flex items-center justify-center gap-1">
|
||||
<div className="border-l border-border bg-muted w-32 flex flex-col">
|
||||
<div className="p-2 border-b border-border text-xs font-semibold text-muted-foreground flex items-center justify-center gap-1">
|
||||
<Clock className="w-3 h-3" /> Time
|
||||
</div>
|
||||
<div className="flex flex-1 h-64">
|
||||
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-gray-200">
|
||||
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-border">
|
||||
{hours.map((h) => (
|
||||
<div
|
||||
key={h}
|
||||
onClick={() => handleTimeChange('hour', h)}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getHours(safeDate) === h ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getHours(safeDate) === h ? 'bg-primary/10 font-medium text-primary' : ''}`}
|
||||
>
|
||||
{h.toString().padStart(2, '0')}
|
||||
</div>
|
||||
@@ -200,7 +206,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
|
||||
<div
|
||||
key={m}
|
||||
onClick={() => handleTimeChange('minute', m)}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getMinutes(safeDate) === m ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getMinutes(safeDate) === m ? 'bg-primary/10 font-medium text-primary' : ''}`}
|
||||
>
|
||||
{m.toString().padStart(2, '0')}
|
||||
</div>
|
||||
@@ -217,11 +223,11 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
|
||||
return (
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
|
||||
}`}
|
||||
>
|
||||
{value ? getDisplayValue(value) : <span className="text-gray-400 italic">Empty</span>}
|
||||
{value ? getDisplayValue(value) : <span className="text-muted-foreground italic">Empty</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
className="w-full min-h-[80px] p-2 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm resize-none"
|
||||
className="w-full min-h-[80px] p-2 border border-ring rounded bg-background text-sm outline-none shadow-sm resize-none"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -73,23 +73,23 @@ const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }
|
||||
{/* Placeholder */}
|
||||
<div
|
||||
onClick={handlePlaceholderClick}
|
||||
className={`w-full text-gray-800 rounded border border-transparent transition-all px-2 py-1 line-clamp-2 max-h-[3rem] overflow-hidden ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : 'cursor-pointer'
|
||||
className={`w-full text-foreground rounded border border-transparent transition-all px-2 py-1 line-clamp-2 max-h-[3rem] overflow-hidden ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : 'cursor-pointer'
|
||||
}`}
|
||||
title="Click to expand"
|
||||
>
|
||||
{value ? value : <span className="text-gray-400 italic">Empty</span>}
|
||||
{value ? value : <span className="text-muted-foreground italic">Empty</span>}
|
||||
</div>
|
||||
|
||||
{/* Expanded Overlay */}
|
||||
{expanded && (
|
||||
<div
|
||||
onClick={handleOverlayClick}
|
||||
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-white border border-blue-500 rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
|
||||
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-background border border-ring rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
|
||||
!readOnly ? 'cursor-text' : ''
|
||||
}`}
|
||||
>
|
||||
{value ? value : <span className="text-gray-400 italic">Empty</span>}
|
||||
{value ? value : <span className="text-muted-foreground italic">Empty</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -62,7 +62,7 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm text-left font-mono"
|
||||
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm text-left font-mono"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -71,14 +71,14 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors text-left font-mono ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors text-left font-mono ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
|
||||
}`}
|
||||
>
|
||||
{value !== undefined && value !== null ? (
|
||||
formatNumber(value)
|
||||
) : (
|
||||
<span className="text-gray-400 italic font-sans text-left block">Empty</span>
|
||||
<span className="text-muted-foreground italic font-sans text-left block">Empty</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -43,7 +43,7 @@ const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, read
|
||||
>
|
||||
<Star
|
||||
className={`w-5 h-5 transition-colors ${
|
||||
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-100 text-gray-300'
|
||||
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-muted text-muted-foreground/30'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
@@ -28,7 +28,7 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
|
||||
}
|
||||
|
||||
const renderOptionBadge = (option: SelectOption | undefined) => {
|
||||
if (!option) return <span className="text-gray-400 italic">Select an option</span>
|
||||
if (!option) return <span className="text-muted-foreground italic">Select an option</span>
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
@@ -46,23 +46,23 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`flex items-center justify-between w-full min-h-[28px] px-2 py-1 rounded border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200 group' : ''
|
||||
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border group' : ''
|
||||
}`}
|
||||
>
|
||||
{renderOptionBadge(selectedOption)}
|
||||
{!readOnly && (
|
||||
<ChevronDown className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" />
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100" />
|
||||
)}
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent
|
||||
className="p-1 w-[--radix-popover-trigger-width] min-w-[150px] max-h-60 overflow-auto bg-white border border-gray-200 rounded-lg shadow-lg"
|
||||
className="p-1 w-[--radix-popover-trigger-width] min-w-[150px] max-h-60 overflow-auto bg-popover border border-border rounded-lg shadow-lg"
|
||||
align="start"
|
||||
>
|
||||
<div
|
||||
onClick={() => handleSelect('')}
|
||||
className="px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer flex items-center gap-2"
|
||||
className="px-3 py-2 text-sm text-muted-foreground hover:bg-accent cursor-pointer flex items-center gap-2"
|
||||
>
|
||||
<X className="w-3 h-3" /> Clear
|
||||
</div>
|
||||
@@ -70,7 +70,7 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
|
||||
<div
|
||||
key={option.id}
|
||||
onClick={() => handleSelect(option.id)}
|
||||
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center"
|
||||
className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center"
|
||||
>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
|
||||
@@ -120,12 +120,12 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
onClick={handlePlaceholderClick}
|
||||
className={`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${
|
||||
!readOnly || hiddenCount > 0
|
||||
? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200'
|
||||
? 'cursor-pointer hover:bg-accent hover:border-border'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
{selectedOptions.length === 0 && (
|
||||
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
|
||||
<span className="text-muted-foreground text-sm italic px-1 pt-0.5">Empty</span>
|
||||
)}
|
||||
|
||||
{/* Render visible items */}
|
||||
@@ -140,7 +140,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
))}
|
||||
|
||||
{hiddenCount > 0 && (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-600 h-[22px]">
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground h-[22px]">
|
||||
+{hiddenCount}
|
||||
</span>
|
||||
)}
|
||||
@@ -148,10 +148,10 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent
|
||||
className={`p-1 bg-white border rounded-lg shadow-xl max-h-60 overflow-auto ${
|
||||
className={`p-1 bg-popover border rounded-lg shadow-xl max-h-60 overflow-auto ${
|
||||
expanded && !isEditing
|
||||
? 'w-[--radix-popover-trigger-width] min-w-[200px] flex flex-wrap gap-1 border-blue-500 min-h-[32px] h-auto cursor-pointer'
|
||||
: 'w-64 border-gray-200'
|
||||
? 'w-[--radix-popover-trigger-width] min-w-[200px] flex flex-wrap gap-1 border-ring min-h-[32px] h-auto cursor-pointer'
|
||||
: 'w-64 border-border'
|
||||
}`}
|
||||
align="start"
|
||||
onClick={expanded && !isEditing ? handleOverlayClick : undefined}
|
||||
@@ -159,7 +159,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
{expanded && !isEditing ? (
|
||||
<>
|
||||
{selectedOptions.length === 0 && (
|
||||
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
|
||||
<span className="text-muted-foreground text-sm italic px-1 pt-0.5">Empty</span>
|
||||
)}
|
||||
{selectedOptions.map((option: SelectOption) => (
|
||||
<span
|
||||
@@ -178,7 +178,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
<div
|
||||
key={option.id}
|
||||
onClick={() => toggleOption(option.id)}
|
||||
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between"
|
||||
className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center justify-between"
|
||||
>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
@@ -186,7 +186,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
{isSelected && <Check className="w-4 h-4 text-blue-500" />}
|
||||
{isSelected && <Check className="w-4 h-4 text-primary" />}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
@@ -43,7 +43,7 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm"
|
||||
className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -51,11 +51,11 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
|
||||
return (
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded truncate border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
|
||||
}`}
|
||||
>
|
||||
{value || <span className="text-gray-400 italic">Empty</span>}
|
||||
{value || <span className="text-muted-foreground italic">Empty</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import React from 'react'
|
||||
|
||||
@@ -9,32 +10,20 @@ interface FieldProps {
|
||||
}
|
||||
|
||||
const ToggleField: React.FC<FieldProps> = ({ value, onSave, readOnly }) => {
|
||||
// Toggle is instant edit, doesn't really have a separate "Edit mode" UI structure other than interaction.
|
||||
const handleToggle = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
const handleToggle = (checked: boolean) => {
|
||||
if (!readOnly) {
|
||||
const newValue = !value
|
||||
onSave(newValue)
|
||||
onSave(checked)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleToggle}
|
||||
className={`flex items-center h-[28px] w-full ${!readOnly ? 'cursor-pointer' : ''}`}
|
||||
>
|
||||
<div
|
||||
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
|
||||
value ? 'bg-green-500' : 'bg-gray-300'
|
||||
} ${readOnly ? 'opacity-70' : ''}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition duration-200 ease-in-out ${
|
||||
value ? 'translate-x-4.5' : 'translate-x-1'
|
||||
}`}
|
||||
style={{ transform: value ? 'translateX(18px)' : 'translateX(4px)' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center h-[28px] w-full" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={value}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={readOnly}
|
||||
className="cursor-pointer"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,21 +2,25 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import type { CreateUploadTaskRequest } from '@shumai/dtos'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { ulid } from 'ulid'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import type {
|
||||
AssetInfo,
|
||||
CollectionInfo,
|
||||
CreateUploadTaskRequest,
|
||||
SearchCondition,
|
||||
SearchSort,
|
||||
ShareLinkInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Download, AlertTriangle, Loader2 } from 'lucide-react'
|
||||
import { AlertTriangle, Download, Loader2 } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { ulid } from 'ulid'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
@@ -31,6 +35,8 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '../ui/alert-dialog'
|
||||
import { Button } from '../ui/button'
|
||||
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -39,8 +45,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '../ui/dialog'
|
||||
import { Button } from '../ui/button'
|
||||
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
||||
import { FileCard } from './file-card'
|
||||
import { FileListItem } from './file-list-item'
|
||||
import { FolderCard } from './folder-card'
|
||||
@@ -138,6 +142,70 @@ export function FileBrowser({
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [isExternalDragging, setIsExternalDragging] = useState(false)
|
||||
const [externalOverFolderId, setExternalOverFolderId] = useState<string | null>(null)
|
||||
const dragCounter = useRef(0)
|
||||
|
||||
const resetExternalDragState = useCallback(() => {
|
||||
setIsExternalDragging(false)
|
||||
setExternalOverFolderId(null)
|
||||
dragCounter.current = 0
|
||||
}, [])
|
||||
|
||||
// Prevent default window behavior to avoid browser replacing page on accidental drops
|
||||
useEffect(() => {
|
||||
const preventDefault = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
window.addEventListener('dragover', preventDefault)
|
||||
window.addEventListener('drop', preventDefault)
|
||||
return () => {
|
||||
window.removeEventListener('dragover', preventDefault)
|
||||
window.removeEventListener('drop', preventDefault)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleGlobalDragEnter = (e: React.DragEvent) => {
|
||||
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||
e.preventDefault()
|
||||
if (e.dataTransfer.types.includes('Files')) {
|
||||
dragCounter.current++
|
||||
setIsExternalDragging(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGlobalDragLeave = (e: React.DragEvent) => {
|
||||
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||
e.preventDefault()
|
||||
if (e.dataTransfer.types.includes('Files')) {
|
||||
dragCounter.current--
|
||||
if (dragCounter.current <= 0) {
|
||||
dragCounter.current = 0
|
||||
setIsExternalDragging(false)
|
||||
setExternalOverFolderId(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleGlobalDragOver = (e: React.DragEvent) => {
|
||||
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
const handleGlobalDrop = async (e: React.DragEvent) => {
|
||||
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||
|
||||
resetExternalDragState()
|
||||
|
||||
if (files.length > 0) {
|
||||
processAndUploadFiles(files)
|
||||
}
|
||||
}
|
||||
|
||||
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
|
||||
|
||||
const displayedFiles = useMemo(() => {
|
||||
@@ -147,7 +215,7 @@ export function FileBrowser({
|
||||
}, [files, localUploadingFiles])
|
||||
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', projectId],
|
||||
queryKey: ['shares', projectId, 'list'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
@@ -207,7 +275,7 @@ export function FileBrowser({
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
@@ -237,7 +305,7 @@ export function FileBrowser({
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
@@ -389,18 +457,45 @@ export function FileBrowser({
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
Error,
|
||||
InferRequestType<typeof $createUploadTask>
|
||||
InferRequestType<typeof $createUploadTask>,
|
||||
{ files: FileWithId[] }
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $createUploadTask(request)
|
||||
if (!res.ok) throw new Error('Failed to create upload task')
|
||||
return (await res.json()) as InferResponseType<typeof $createUploadTask>
|
||||
},
|
||||
onSuccess: async (data, variables) => {
|
||||
onMutate: () => {
|
||||
return { files: [...filesToUpload] }
|
||||
},
|
||||
onSuccess: async (data, variables, context) => {
|
||||
const currentFiles = context?.files || []
|
||||
const isCurrentFolderUpload = variables.json.parentId === assetId
|
||||
|
||||
// Register task and files in the store for real-time progress tracking
|
||||
const filesProgressInfo = currentFiles
|
||||
.map((f) => {
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
return {
|
||||
fileId: urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
size: f.file.size,
|
||||
}
|
||||
})
|
||||
.filter((info) => !!info.fileId)
|
||||
|
||||
const visibleFiles = currentFiles.filter((f) => !f.file.name.startsWith('.'))
|
||||
const taskName =
|
||||
visibleFiles.length === 1 ? visibleFiles[0].file.name : `${visibleFiles.length} Items`
|
||||
|
||||
if (data.taskId) {
|
||||
startTask(data.taskId, taskName, filesProgressInfo)
|
||||
}
|
||||
|
||||
if (isCurrentFolderUpload) {
|
||||
const newLocalFiles: AssetInfo[] = filesToUpload
|
||||
const newLocalFiles: AssetInfo[] = currentFiles
|
||||
.filter((f) => {
|
||||
const path = (f.file.webkitRelativePath || f.file.name).split('/')
|
||||
return path.length === 1
|
||||
@@ -432,7 +527,7 @@ export function FileBrowser({
|
||||
|
||||
// The RPC client returns an object that we cast to the expected type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!)
|
||||
await uploadFiles(currentFiles, data.presignedUrls as any, data.taskId!)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
@@ -441,6 +536,10 @@ export function FileBrowser({
|
||||
|
||||
const incrementUploading = useUploadStore((state) => state.increment)
|
||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||
const startTask = useUploadStore((state) => state.startTask)
|
||||
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
|
||||
const completeFile = useUploadStore((state) => state.completeFile)
|
||||
const failFile = useUploadStore((state) => state.failFile)
|
||||
const { fields } = useFieldStore()
|
||||
const displayedFields = useMemo(() => {
|
||||
if (!isShareView) return fields.filter((f) => f.visible)
|
||||
@@ -550,6 +649,13 @@ export function FileBrowser({
|
||||
isShareView,
|
||||
fields: displayedFields,
|
||||
canEdit,
|
||||
isExternalDragging,
|
||||
externalOverFolderId,
|
||||
setExternalOverFolderId,
|
||||
resetExternalDragState,
|
||||
onExternalDrop: (files: File[], folderId: string) => {
|
||||
processAndUploadFiles(files, folderId)
|
||||
},
|
||||
}
|
||||
if (displayStyle === 'card') {
|
||||
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
|
||||
@@ -613,25 +719,53 @@ export function FileBrowser({
|
||||
incrementUploading()
|
||||
try {
|
||||
try {
|
||||
const resp = await fetch(uploadInfo.url, {
|
||||
method: 'PUT',
|
||||
body: file.file,
|
||||
headers: {
|
||||
'Content-Type': file.file.type,
|
||||
const xhr = new XMLHttpRequest()
|
||||
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
|
||||
(resolve, reject) => {
|
||||
xhr.open('PUT', uploadInfo.url)
|
||||
xhr.setRequestHeader('Content-Type', file.file.type)
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve({ ok: true, status: xhr.status })
|
||||
} else {
|
||||
resolve({ ok: false, status: xhr.status })
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onerror = () => {
|
||||
reject(new Error('Network error'))
|
||||
}
|
||||
|
||||
xhr.onabort = () => {
|
||||
reject(new Error('Upload aborted'))
|
||||
}
|
||||
|
||||
xhr.send(file.file)
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const resp = await uploadPromise
|
||||
|
||||
if (resp.ok) {
|
||||
completeFile(taskId, uploadInfo.fileId)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with status: ${resp.status}`,
|
||||
@@ -640,9 +774,10 @@ export function FileBrowser({
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
failFile(taskId, uploadInfo.fileId)
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
param: { teamId: teamId!, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
@@ -812,6 +947,10 @@ export function FileBrowser({
|
||||
<div
|
||||
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
|
||||
onContextMenu={(e) => onContextMenu(e)}
|
||||
onDragEnter={handleGlobalDragEnter}
|
||||
onDragLeave={handleGlobalDragLeave}
|
||||
onDragOver={handleGlobalDragOver}
|
||||
onDrop={handleGlobalDrop}
|
||||
>
|
||||
{!isShareView && !isPublic && onFilterChange && onSortChange && (
|
||||
<FileBrowserToolbar
|
||||
@@ -886,6 +1025,11 @@ export function FileBrowser({
|
||||
handleEmptyAreaClick={handleEmptyAreaClick}
|
||||
dragState={dragState}
|
||||
sort={sort}
|
||||
isExternalDragging={isExternalDragging}
|
||||
externalOverFolderId={externalOverFolderId}
|
||||
setExternalOverFolderId={setExternalOverFolderId}
|
||||
resetExternalDragState={resetExternalDragState}
|
||||
onExternalDrop={(files, folderId) => processAndUploadFiles(files, folderId)}
|
||||
/>
|
||||
) : (
|
||||
<FileBrowserGridView
|
||||
@@ -970,6 +1114,13 @@ export function FileBrowser({
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isExternalDragging && !externalOverFolderId && (
|
||||
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-50 pointer-events-none animate-in fade-in slide-in-from-bottom-4 duration-300">
|
||||
<div className="flex items-center gap-3 px-6 py-3 rounded-full bg-primary/80 text-primary-foreground shadow-lg shadow-primary/20 border border-primary/20 backdrop-blur-md">
|
||||
<span className="font-medium text-sm">Drop files here to upload</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<FileBrowserContextMenu
|
||||
|
||||
@@ -22,6 +22,8 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import FieldRenderer from '../field-renderer'
|
||||
import { FilePreview } from './file-preview'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||
|
||||
import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import { FIELD_TYPE_ICONS } from '../fields-manager'
|
||||
@@ -82,6 +84,13 @@ export function FileCard({
|
||||
const [name, setName] = useState(item.name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
|
||||
const uploadPercent = fileUploadState
|
||||
? fileUploadState.total > 0
|
||||
? (fileUploadState.loaded / fileUploadState.total) * 100
|
||||
: 0
|
||||
: 0
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
@@ -247,20 +256,24 @@ export function FileCard({
|
||||
{displayItem.status !== 'error' && (
|
||||
<Skeleton className="absolute inset-0 h-full w-full" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'z-10 font-medium px-2 text-center text-sm',
|
||||
displayItem.status === 'error'
|
||||
? 'text-destructive font-semibold'
|
||||
: 'text-muted-foreground capitalize',
|
||||
)}
|
||||
>
|
||||
{displayItem.status === 'uploaded'
|
||||
? 'Processing'
|
||||
: displayItem.status === 'error'
|
||||
? 'Failed to upload'
|
||||
: displayItem.status}
|
||||
</span>
|
||||
{displayItem.status === 'uploading' ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
) : (
|
||||
<span
|
||||
className={cn(
|
||||
'z-10 font-medium px-2 text-center text-sm',
|
||||
displayItem.status === 'error'
|
||||
? 'text-destructive font-semibold'
|
||||
: 'text-muted-foreground capitalize',
|
||||
)}
|
||||
>
|
||||
{displayItem.status === 'uploaded'
|
||||
? 'Processing'
|
||||
: displayItem.status === 'error'
|
||||
? 'Failed to upload'
|
||||
: displayItem.status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<FilePreview item={displayItem} />
|
||||
@@ -372,13 +385,13 @@ export function FileCard({
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{fields && fields.length > 0 && (
|
||||
<div className="space-y-2 border-t p-3 mx-2">
|
||||
<div className="space-y-2 border-t p-1 pt-3 mx-2">
|
||||
{fields.map((field) => {
|
||||
const Icon = field.config?.type
|
||||
? FIELD_TYPE_ICONS[field.config.type as FieldType]
|
||||
: null
|
||||
return (
|
||||
<div key={field.id} className="space-y-1">
|
||||
<div key={field.id} className="space-y-1 bg-muted/50 p-1 rounded border">
|
||||
<label className="text-xs text-muted-foreground tracking-wide flex items-center gap-1">
|
||||
{Icon && <Icon className="h-3.5 w-3.5 text-muted-foreground shrink-0" />}
|
||||
<span>{field.config?.name}</span>
|
||||
|
||||
@@ -11,6 +11,8 @@ import FieldRenderer from '../field-renderer'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
|
||||
@@ -60,6 +62,13 @@ export function FileListItem({
|
||||
const [name, setName] = useState(item.name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
|
||||
const uploadPercent = fileUploadState
|
||||
? fileUploadState.total > 0
|
||||
? (fileUploadState.loaded / fileUploadState.total) * 100
|
||||
: 0
|
||||
: 0
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
@@ -197,7 +206,9 @@ export function FileListItem({
|
||||
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
||||
{displayItem.preview?.thumbnailUrl ? (
|
||||
{displayItem.status === 'uploading' ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
|
||||
) : displayItem.preview?.thumbnailUrl ? (
|
||||
<img
|
||||
src={displayItem.preview.thumbnailUrl}
|
||||
alt=""
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { FilePreview } from './file-preview'
|
||||
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||
|
||||
interface FolderCardProps {
|
||||
item: AssetInfo
|
||||
@@ -38,6 +39,11 @@ interface FolderCardProps {
|
||||
selectedCount?: number
|
||||
canEdit?: boolean
|
||||
isShareView?: boolean
|
||||
isExternalDragging?: boolean
|
||||
externalOverFolderId?: string | null
|
||||
setExternalOverFolderId?: (id: string | null) => void
|
||||
resetExternalDragState?: () => void
|
||||
onExternalDrop?: (files: File[], folderId: string) => void
|
||||
}
|
||||
|
||||
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
|
||||
@@ -114,6 +120,11 @@ export function FolderCard({
|
||||
selectedCount,
|
||||
canEdit = true,
|
||||
isShareView,
|
||||
isExternalDragging,
|
||||
externalOverFolderId,
|
||||
setExternalOverFolderId,
|
||||
resetExternalDragState,
|
||||
onExternalDrop,
|
||||
}: FolderCardProps) {
|
||||
const [name, setName] = useState(item.name || '')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
@@ -153,7 +164,8 @@ export function FolderCard({
|
||||
return true
|
||||
}, [dragState, item.id])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
const isExternalOver = isExternalDragging && externalOverFolderId === item.id
|
||||
const showDropFeedback = (isOver && isValidDropTarget) || isExternalOver
|
||||
const opacity = isBeingDragged ? 0.5 : 1
|
||||
|
||||
useEffect(() => {
|
||||
@@ -224,6 +236,40 @@ export function FolderCard({
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
onDragEnter={
|
||||
isExternalDragging
|
||||
? () => {
|
||||
setExternalOverFolderId?.(item.id!)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDragLeave={
|
||||
isExternalDragging
|
||||
? (e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||
setExternalOverFolderId?.(null)
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDragOver={
|
||||
isExternalDragging
|
||||
? (e) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDrop={
|
||||
isExternalDragging
|
||||
? async (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
resetExternalDragState?.()
|
||||
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||
onExternalDrop?.(files, item.id!)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
className={cn(
|
||||
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
|
||||
)}
|
||||
|
||||
@@ -13,6 +13,7 @@ import React, { useMemo, useState, useEffect } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { Checkbox } from '../ui/checkbox'
|
||||
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||
|
||||
interface ListRowProps {
|
||||
item: AssetInfo
|
||||
@@ -23,6 +24,11 @@ interface ListRowProps {
|
||||
columnSizing?: Record<string, number>
|
||||
virtualRow: { start: number; index: number }
|
||||
measureElement: (el: HTMLElement | null) => void
|
||||
isExternalDragging?: boolean
|
||||
externalOverFolderId?: string | null
|
||||
setExternalOverFolderId?: (id: string | null) => void
|
||||
resetExternalDragState?: () => void
|
||||
onExternalDrop?: (files: File[], folderId: string) => void
|
||||
}
|
||||
|
||||
function ListRow({
|
||||
@@ -34,6 +40,11 @@ function ListRow({
|
||||
columnSizing,
|
||||
virtualRow,
|
||||
measureElement,
|
||||
isExternalDragging,
|
||||
externalOverFolderId,
|
||||
setExternalOverFolderId,
|
||||
resetExternalDragState,
|
||||
onExternalDrop,
|
||||
}: ListRowProps) {
|
||||
const isDraggingItem = dragState?.draggedIds.has(item.id!)
|
||||
const isDraggingAny = dragState?.isActive
|
||||
@@ -83,7 +94,8 @@ function ListRow({
|
||||
return false
|
||||
}, [dragState, item.id, item.type])
|
||||
|
||||
const showDropFeedback = isRowOver && isValidDropTarget
|
||||
const isExternalOver = isExternalDragging && externalOverFolderId === item.id
|
||||
const showDropFeedback = (isRowOver && isValidDropTarget) || isExternalOver
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -92,6 +104,40 @@ function ListRow({
|
||||
measureElement(node)
|
||||
}}
|
||||
data-index={virtualRow.index}
|
||||
onDragEnter={
|
||||
isExternalDragging && item.type === 'folder'
|
||||
? () => {
|
||||
setExternalOverFolderId?.(item.id!)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDragLeave={
|
||||
isExternalDragging && item.type === 'folder'
|
||||
? (e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||
setExternalOverFolderId?.(null)
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDragOver={
|
||||
isExternalDragging && item.type === 'folder'
|
||||
? (e) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onDrop={
|
||||
isExternalDragging && item.type === 'folder'
|
||||
? async (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
resetExternalDragState?.()
|
||||
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||
onExternalDrop?.(files, item.id!)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
className={cn(
|
||||
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col',
|
||||
isSelected && 'bg-primary/10',
|
||||
@@ -146,6 +192,11 @@ interface FileBrowserListViewProps {
|
||||
handleEmptyAreaClick: (e: React.MouseEvent) => void
|
||||
dragState?: DragState
|
||||
sort?: SearchSort
|
||||
isExternalDragging?: boolean
|
||||
externalOverFolderId?: string | null
|
||||
setExternalOverFolderId?: (id: string | null) => void
|
||||
resetExternalDragState?: () => void
|
||||
onExternalDrop?: (files: File[], folderId: string) => void
|
||||
}
|
||||
|
||||
export function FileBrowserListView({
|
||||
@@ -174,6 +225,11 @@ export function FileBrowserListView({
|
||||
handleEmptyAreaClick,
|
||||
dragState,
|
||||
sort,
|
||||
isExternalDragging,
|
||||
externalOverFolderId,
|
||||
setExternalOverFolderId,
|
||||
resetExternalDragState,
|
||||
onExternalDrop,
|
||||
}: FileBrowserListViewProps) {
|
||||
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
|
||||
|
||||
@@ -459,6 +515,11 @@ export function FileBrowserListView({
|
||||
columnSizing={columnSizing}
|
||||
virtualRow={virtualRow}
|
||||
measureElement={rowVirtualizer.measureElement}
|
||||
isExternalDragging={isExternalDragging}
|
||||
externalOverFolderId={externalOverFolderId}
|
||||
setExternalOverFolderId={setExternalOverFolderId}
|
||||
resetExternalDragState={resetExternalDragState}
|
||||
onExternalDrop={onExternalDrop}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -159,6 +159,9 @@ export function useFileActions({
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders'],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -273,7 +276,7 @@ export function useFileActions({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
queryKey: ['folders'],
|
||||
})
|
||||
if (data?.id) {
|
||||
setEditingItemId(data.id)
|
||||
@@ -293,7 +296,7 @@ export function useFileActions({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
queryKey: ['folders'],
|
||||
})
|
||||
},
|
||||
},
|
||||
@@ -310,7 +313,7 @@ export function useFileActions({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
queryKey: ['folders'],
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
@@ -18,6 +18,7 @@ type FileViewerProps = {
|
||||
onPause?: () => void
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
@@ -28,6 +29,7 @@ export function FileViewer({
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
children,
|
||||
}: FileViewerProps) {
|
||||
const { width: screenWidth } = useScreenSize()
|
||||
@@ -308,6 +310,7 @@ export function FileViewer({
|
||||
onPause={onPause}
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
annotations={displayAnnotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{children}
|
||||
</VideoPlayer>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSeparator,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
@@ -31,12 +33,15 @@ import type { AssetInfo, AssetInfoPaginatedList, CollectionInfo, ShareLinkInfo }
|
||||
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useMatch, useNavigate, useParams } from '@tanstack/react-router'
|
||||
import {
|
||||
AlertTriangle,
|
||||
Bookmark,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ChevronsDownUp,
|
||||
ChevronsUpDown,
|
||||
Clapperboard,
|
||||
Download,
|
||||
Edit,
|
||||
Folder,
|
||||
LayoutGrid,
|
||||
Loader2,
|
||||
@@ -222,16 +227,129 @@ export function FolderTree({
|
||||
from: '/projects/$projectId/shares/$shareId',
|
||||
shouldThrow: false,
|
||||
})
|
||||
const folderParams = useParams({
|
||||
from: '/projects/$projectId/folders/$folderId',
|
||||
shouldThrow: false,
|
||||
})
|
||||
|
||||
const [renameId, setRenameId] = useState<string | null>(null)
|
||||
const [renameType, setRenameType] = useState<'collection' | 'share'>('collection')
|
||||
const [renameType, setRenameType] = useState<'collection' | 'share' | 'folder'>('collection')
|
||||
const [renameName, setRenameName] = useState('')
|
||||
const [isRenameOpen, setIsRenameOpen] = useState(false)
|
||||
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [deleteType, setDeleteType] = useState<'collection' | 'share'>('collection')
|
||||
const [deleteType, setDeleteType] = useState<'collection' | 'share' | 'folder'>('collection')
|
||||
const [isDeleteOpen, setIsDeleteOpen] = useState(false)
|
||||
|
||||
const { mutate: renameFolder } = useMutation({
|
||||
mutationFn: async ({ id, name }: { id: string; name: string }) => {
|
||||
const res = await client.api.folders[':folderId'].$put({
|
||||
param: { folderId: id },
|
||||
json: { name },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to rename folder')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
toast.success('Folder renamed')
|
||||
setIsRenameOpen(false)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: deleteFolder } = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.folders.$delete({
|
||||
json: { ids: [id] },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete folder')
|
||||
return id
|
||||
},
|
||||
onSuccess: (deletedId) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
toast.success('Folder deleted')
|
||||
setIsDeleteOpen(false)
|
||||
if (folderParams?.folderId === deletedId) {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
params: { projectId },
|
||||
})
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const [isDownloadOpen, setIsDownloadOpen] = useState(false)
|
||||
const [isLoadingLinks, setIsLoadingLinks] = useState(false)
|
||||
const [resolvedFiles, setResolvedFiles] = useState<
|
||||
Array<{ id: string; name: string; url: string }>
|
||||
>([])
|
||||
|
||||
const handleDownloadFolder = async (folderId: string) => {
|
||||
setIsDownloadOpen(true)
|
||||
setIsLoadingLinks(true)
|
||||
setResolvedFiles([])
|
||||
try {
|
||||
const res = await client.api.files['download-links'].$post({
|
||||
json: { ids: [folderId] },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to prepare download links')
|
||||
const data = await res.json()
|
||||
setResolvedFiles(data.files)
|
||||
} catch (error) {
|
||||
toast.error('Failed to prepare download links')
|
||||
setIsDownloadOpen(false)
|
||||
console.error(error)
|
||||
} finally {
|
||||
setIsLoadingLinks(false)
|
||||
}
|
||||
}
|
||||
|
||||
const startDownload = () => {
|
||||
const files = [...resolvedFiles]
|
||||
setIsDownloadOpen(false)
|
||||
|
||||
if (files.length === 0) return
|
||||
|
||||
toast.info(
|
||||
`Starting download of ${files.length} files. Please allow multiple downloads if prompted by your browser.`,
|
||||
{
|
||||
duration: 5000,
|
||||
},
|
||||
)
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
const runQueue = async () => {
|
||||
const batchSize = 5
|
||||
for (let i = 0; i < files.length; i += batchSize) {
|
||||
const chunk = files.slice(i, i + batchSize)
|
||||
for (const file of chunk) {
|
||||
const a = document.createElement('a')
|
||||
a.href = file.url
|
||||
a.download = file.name
|
||||
a.target = '_blank'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
}
|
||||
await delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
runQueue().catch((err) => {
|
||||
console.error('Background downloads failed:', err)
|
||||
toast.error('Some downloads could not be started')
|
||||
})
|
||||
}
|
||||
|
||||
const { mutate: renameCollection } = useMutation({
|
||||
mutationFn: async ({ id, name }: { id: string; name: string }) => {
|
||||
const res = await client.api.collections[':collectionId'].$patch({
|
||||
@@ -338,9 +456,6 @@ export function FolderTree({
|
||||
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
)}
|
||||
</div>
|
||||
<button className="text-muted-foreground hover:text-foreground flex-none">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
@@ -372,6 +487,20 @@ export function FolderTree({
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
canEdit={canEdit}
|
||||
onRenameTrigger={(id, currentName) => {
|
||||
setRenameId(id)
|
||||
setRenameType('folder')
|
||||
setRenameName(currentName)
|
||||
setIsRenameOpen(true)
|
||||
}}
|
||||
onDeleteTrigger={(id) => {
|
||||
setDeleteId(id)
|
||||
setDeleteType('folder')
|
||||
setIsDeleteOpen(true)
|
||||
}}
|
||||
onDownloadTrigger={(id) => {
|
||||
handleDownloadFolder(id)
|
||||
}}
|
||||
/>
|
||||
|
||||
{canEdit && (
|
||||
@@ -619,7 +748,12 @@ export function FolderTree({
|
||||
<DialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Rename {renameType === 'collection' ? 'Collection' : 'Share Link'}
|
||||
Rename{' '}
|
||||
{renameType === 'collection'
|
||||
? 'Collection'
|
||||
: renameType === 'share'
|
||||
? 'Share Link'
|
||||
: 'Folder'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
@@ -631,8 +765,10 @@ export function FolderTree({
|
||||
if (e.key === 'Enter' && renameName.trim()) {
|
||||
if (renameType === 'collection') {
|
||||
renameCollection({ id: renameId!, name: renameName })
|
||||
} else {
|
||||
} else if (renameType === 'share') {
|
||||
renameShareLink({ id: renameId!, name: renameName })
|
||||
} else if (renameType === 'folder') {
|
||||
renameFolder({ id: renameId!, name: renameName })
|
||||
}
|
||||
}
|
||||
}}
|
||||
@@ -647,8 +783,10 @@ export function FolderTree({
|
||||
onClick={() => {
|
||||
if (renameType === 'collection') {
|
||||
renameCollection({ id: renameId!, name: renameName })
|
||||
} else {
|
||||
} else if (renameType === 'share') {
|
||||
renameShareLink({ id: renameId!, name: renameName })
|
||||
} else if (renameType === 'folder') {
|
||||
renameFolder({ id: renameId!, name: renameName })
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -663,12 +801,22 @@ export function FolderTree({
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
Delete {deleteType === 'collection' ? 'Collection' : 'Share Link'}?
|
||||
Delete{' '}
|
||||
{deleteType === 'collection'
|
||||
? 'Collection'
|
||||
: deleteType === 'share'
|
||||
? 'Share Link'
|
||||
: 'Folder'}
|
||||
?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this{' '}
|
||||
{deleteType === 'collection' ? 'collection' : 'share link'}? This action cannot be
|
||||
undone.
|
||||
{deleteType === 'collection'
|
||||
? 'collection'
|
||||
: deleteType === 'share'
|
||||
? 'share link'
|
||||
: 'folder'}
|
||||
? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -678,8 +826,10 @@ export function FolderTree({
|
||||
onClick={() => {
|
||||
if (deleteType === 'collection') {
|
||||
deleteCollection(deleteId!)
|
||||
} else {
|
||||
} else if (deleteType === 'share') {
|
||||
deleteShareLink(deleteId!)
|
||||
} else if (deleteType === 'folder') {
|
||||
deleteFolder(deleteId!)
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -688,6 +838,69 @@ export function FolderTree({
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Folder Download Dialog */}
|
||||
<Dialog open={isDownloadOpen} onOpenChange={setIsDownloadOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isLoadingLinks ? 'Preparing Download' : 'Confirm Download'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isLoadingLinks
|
||||
? 'Resolving all files and folders. Please wait...'
|
||||
: 'Selected folder files will be prepared for download.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoadingLinks ? (
|
||||
<div className="space-y-4 py-6 flex flex-col items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<span className="text-sm font-medium text-muted-foreground mt-2">
|
||||
Preparing download links...
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
This download will include{' '}
|
||||
<span className="font-semibold text-foreground">{resolvedFiles.length}</span>{' '}
|
||||
file(s).
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
|
||||
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-semibold">No Folder Structure</p>
|
||||
<p className="mt-0.5 text-xs text-amber-700/90 dark:text-amber-400/90">
|
||||
Folder hierarchy will be flattened. All nested files will be downloaded directly
|
||||
into your default download folder.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{!isLoadingLinks ? (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsDownloadOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={startDownload}
|
||||
className="gap-2"
|
||||
disabled={resolvedFiles.length === 0}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
Start Download
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button disabled variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -795,6 +1008,9 @@ interface FolderTreeItemProps {
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
canEdit?: boolean
|
||||
onRenameTrigger: (id: string, name: string) => void
|
||||
onDeleteTrigger: (id: string) => void
|
||||
onDownloadTrigger: (id: string) => void
|
||||
}
|
||||
|
||||
function FolderTreeItem({
|
||||
@@ -807,6 +1023,9 @@ function FolderTreeItem({
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
canEdit,
|
||||
onRenameTrigger,
|
||||
onDeleteTrigger,
|
||||
onDownloadTrigger,
|
||||
}: FolderTreeItemProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(isRoot || false)
|
||||
const navigate = useNavigate()
|
||||
@@ -954,6 +1173,53 @@ function FolderTreeItem({
|
||||
<Folder className="h-4 w-4 text-sidebar-primary" />
|
||||
)}
|
||||
<span className="flex-1 truncate text-sidebar-foreground">{folder.name}</span>
|
||||
|
||||
{canEdit && !isRoot && (
|
||||
<div
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="h-6 w-6 shrink-0 hover:bg-muted hover:text-muted-foreground p-0"
|
||||
>
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
onRenameTrigger(folder.id!, folder.name)
|
||||
}}
|
||||
>
|
||||
<Edit className="mr-2 h-4 w-4" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
onDownloadTrigger(folder.id!)
|
||||
}}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive focus:bg-destructive/10"
|
||||
onClick={() => {
|
||||
onDeleteTrigger(folder.id!)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
@@ -977,6 +1243,9 @@ function FolderTreeItem({
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
canEdit={canEdit}
|
||||
onRenameTrigger={onRenameTrigger}
|
||||
onDeleteTrigger={onDeleteTrigger}
|
||||
onDownloadTrigger={onDownloadTrigger}
|
||||
/>
|
||||
))}
|
||||
{hasNextPage && (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { NotificationInfo } from '@shumai/dtos'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { SpriteScrubber } from './sprite-scrubber'
|
||||
|
||||
interface NotificationCardProps {
|
||||
notification: NotificationInfo
|
||||
@@ -76,6 +77,13 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
}
|
||||
})()
|
||||
|
||||
const isVideoWithSprite =
|
||||
asset?.mediaType?.startsWith('video/') &&
|
||||
asset.preview &&
|
||||
asset.thumbnailUrl &&
|
||||
asset.originalWidth &&
|
||||
asset.originalHeight
|
||||
|
||||
const hasPreview =
|
||||
asset?.preview && (asset.mediaType?.startsWith('image') || asset.mediaType?.startsWith('video'))
|
||||
|
||||
@@ -98,7 +106,16 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
|
||||
{hasPreview && (
|
||||
<div className="w-18 h-18 ml-2 rounded-md overflow-hidden flex-shrink-0 bg-muted border border-border flex items-center justify-center mt-0.5">
|
||||
<img src={asset!.preview} alt={asset!.name} className="w-full h-full object-cover" />
|
||||
{isVideoWithSprite ? (
|
||||
<SpriteScrubber
|
||||
spriteUrl={asset.preview!}
|
||||
thumbnailUrl={asset.thumbnailUrl!}
|
||||
videoWidth={asset.originalWidth!}
|
||||
videoHeight={asset.originalHeight!}
|
||||
/>
|
||||
) : (
|
||||
<img src={asset!.preview} alt={asset!.name} className="w-full h-full object-cover" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -30,15 +30,19 @@ interface PublicShareManagerProps {
|
||||
hasPassword: boolean
|
||||
rootFolderId: string
|
||||
projectId: string
|
||||
viewMode?: string | null
|
||||
defaultSortOrder?: string | null
|
||||
}
|
||||
initialFolderId?: string
|
||||
initialFileId?: string
|
||||
startTime?: number
|
||||
}
|
||||
|
||||
export function PublicShareManager({
|
||||
shareInfo,
|
||||
initialFolderId,
|
||||
initialFileId,
|
||||
startTime,
|
||||
}: PublicShareManagerProps) {
|
||||
const navigate = useNavigate()
|
||||
const [password, setPassword] = useState(() => {
|
||||
@@ -86,7 +90,7 @@ export function PublicShareManager({
|
||||
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
const [isRightSidebarCollapsed] = useState(false)
|
||||
const [isRightSidebarCollapsed, setIsRightSidebarCollapsed] = useState(() => !initialFileId)
|
||||
const videoRef = useRef<Player | null>(null)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
@@ -203,8 +207,14 @@ export function PublicShareManager({
|
||||
}
|
||||
}, [foldersError, shareInfo.id])
|
||||
|
||||
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
const folders = useMemo(
|
||||
() => foldersData?.pages.flatMap((page) => page.data ?? []) ?? [],
|
||||
[foldersData],
|
||||
)
|
||||
const files = useMemo(
|
||||
() => filesData?.pages.flatMap((page) => page.data ?? []) ?? [],
|
||||
[filesData],
|
||||
)
|
||||
|
||||
const currentSelectedItem = useMemo(() => {
|
||||
if (viewingFileData) return viewingFileData
|
||||
@@ -306,7 +316,10 @@ export function PublicShareManager({
|
||||
isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId,
|
||||
isPublic: true,
|
||||
shareId: shareInfo.id,
|
||||
fileId: viewingFileId || undefined,
|
||||
onFolderClick: handleBreadcrumbClick,
|
||||
isRightSidebarCollapsed,
|
||||
onRightSidebarToggle: () => setIsRightSidebarCollapsed((prev) => !prev),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -321,6 +334,7 @@ export function PublicShareManager({
|
||||
ancestorFolders,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
isRightSidebarCollapsed,
|
||||
])
|
||||
|
||||
let content
|
||||
@@ -387,6 +401,7 @@ export function PublicShareManager({
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -411,7 +426,7 @@ export function PublicShareManager({
|
||||
}}
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onSaveField={() => {}}
|
||||
displayStyle="card"
|
||||
displayStyle={(shareInfo.viewMode as 'card' | 'list') ?? 'card'}
|
||||
onClearSelection={() => setSelectedIds(new Set())}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { SearchCondition, SearchConditionOperator } from '@shumai/dtos'
|
||||
import { type FieldInfo } from '@shumai/dtos'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { DebouncedInput } from '@/ui/components/ui/debounced-input'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -11,7 +10,11 @@ import {
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import type { SearchCondition, SearchConditionOperator } from '@shumai/dtos'
|
||||
import { type FieldInfo } from '@shumai/dtos'
|
||||
import { Check, ChevronDown, Trash2 } from 'lucide-react'
|
||||
import { getOptionStyle } from '../fields-manager'
|
||||
import RatingField from '../fields/rating-field'
|
||||
|
||||
interface FilterPanelProps {
|
||||
fields: FieldInfo[]
|
||||
@@ -43,7 +46,8 @@ export function FilterPanel({
|
||||
id: f.id!,
|
||||
label: f.config?.name || f.description || 'Unknown',
|
||||
type: getFieldType(f),
|
||||
options: f.config?.select?.options,
|
||||
options: f.config?.select?.options || f.config?.selectMulti?.options,
|
||||
config: f.config,
|
||||
})),
|
||||
].filter((f) => !excludeFields?.includes(f.id))
|
||||
|
||||
@@ -77,6 +81,29 @@ export function FilterPanel({
|
||||
}
|
||||
}
|
||||
|
||||
// Convert value format when switching between single/multi-select operators
|
||||
if (key === 'operator') {
|
||||
const field = allFields.find((f) => f.id === newConditions[index].field)
|
||||
if (field && (field.type === 'select' || field.type === 'selectMulti')) {
|
||||
const oldOperator = conditions[index].operator
|
||||
const newOperator = value as SearchConditionOperator
|
||||
const wasMulti = isMultiSelectOperator(field.type, oldOperator)
|
||||
const isMulti = isMultiSelectOperator(field.type, newOperator)
|
||||
|
||||
if (wasMulti && !isMulti) {
|
||||
// Multi -> Single: take first item or empty string
|
||||
const arr = Array.isArray(newConditions[index].value)
|
||||
? (newConditions[index].value as string[])
|
||||
: []
|
||||
newConditions[index].value = arr[0] || ''
|
||||
} else if (!wasMulti && isMulti) {
|
||||
// Single -> Multi: wrap in array if non-empty
|
||||
const str = newConditions[index].value as string
|
||||
newConditions[index].value = str ? [str] : []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onChange(newConditions)
|
||||
}
|
||||
|
||||
@@ -132,6 +159,7 @@ export function FilterPanel({
|
||||
{condition.operator !== 'isEmpty' && condition.operator !== 'isNotEmpty' && (
|
||||
<ConditionValueInput
|
||||
field={allFields.find((f) => f.id === condition.field)}
|
||||
operator={condition.operator}
|
||||
value={condition.value}
|
||||
onChange={(val) => handleConditionChange(index, 'value', val)}
|
||||
/>
|
||||
@@ -163,7 +191,7 @@ function getFieldType(field: FieldInfo): string {
|
||||
if (field.config?.type === 'selectMulti') return 'selectMulti'
|
||||
if (field.config?.type === 'number') return 'number'
|
||||
if (field.config?.type === 'date') return 'date'
|
||||
if (field.config?.type === 'rating') return 'number'
|
||||
if (field.config?.type === 'rating') return 'rating'
|
||||
if (field.config?.type === 'toggle') return 'toggle'
|
||||
return 'text'
|
||||
}
|
||||
@@ -173,6 +201,7 @@ function getDefaultOperator(type: string): SearchConditionOperator {
|
||||
case 'selectMulti':
|
||||
return 'hasAny' as SearchConditionOperator
|
||||
case 'number':
|
||||
case 'rating':
|
||||
case 'date':
|
||||
return 'eq'
|
||||
default:
|
||||
@@ -207,6 +236,7 @@ function getOperators(field: { id: string; label: string; type: string }): {
|
||||
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
|
||||
]
|
||||
case 'number':
|
||||
case 'rating':
|
||||
return [
|
||||
{ value: 'eq' as SearchConditionOperator, label: '=' },
|
||||
{ value: 'neq' as SearchConditionOperator, label: '≠' },
|
||||
@@ -254,67 +284,142 @@ function getOperators(field: { id: string; label: string; type: string }): {
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type FieldType = any
|
||||
interface SelectOptionItem {
|
||||
id: string
|
||||
displayName: string
|
||||
color?: string
|
||||
}
|
||||
|
||||
interface FilterField {
|
||||
id: string
|
||||
label: string
|
||||
type: string
|
||||
options?: SelectOptionItem[]
|
||||
config?: FieldInfo['config']
|
||||
}
|
||||
|
||||
function isMultiSelectOperator(fieldType: string, operator: SearchConditionOperator): boolean {
|
||||
if (fieldType === 'select') {
|
||||
return operator === 'in' || operator === 'notIn'
|
||||
}
|
||||
if (fieldType === 'selectMulti') {
|
||||
return operator !== 'eq'
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function MultiSelectValueInput({
|
||||
options,
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
options: SelectOptionItem[]
|
||||
selected: string[]
|
||||
onChange: (val: string[]) => void
|
||||
}) {
|
||||
const selectedOptions = options.filter((opt) => selected.includes(opt.id))
|
||||
|
||||
const toggleOption = (optionId: string) => {
|
||||
let newVal
|
||||
if (selected.includes(optionId)) {
|
||||
newVal = selected.filter((id) => id !== optionId)
|
||||
} else {
|
||||
newVal = [...selected, optionId]
|
||||
}
|
||||
onChange(newVal)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-1.5 text-sm shadow-xs hover:bg-accent/50 focus:outline-hidden focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 text-left"
|
||||
>
|
||||
<div className="flex flex-wrap gap-1 items-center max-w-[90%]">
|
||||
{selectedOptions.length === 0 ? (
|
||||
<span className="text-muted-foreground">Select options...</span>
|
||||
) : (
|
||||
selectedOptions.map((option) => (
|
||||
<span
|
||||
key={option.id}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[20px]"
|
||||
style={getOptionStyle(option.color)}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 opacity-50 ml-2" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-64 p-1 bg-popover border border-border rounded-lg shadow-xl max-h-60 overflow-auto"
|
||||
align="start"
|
||||
>
|
||||
{options.map((option) => {
|
||||
const isSelected = selected.includes(option.id)
|
||||
return (
|
||||
<div
|
||||
key={option.id}
|
||||
onClick={() => toggleOption(option.id)}
|
||||
className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center justify-between rounded-sm"
|
||||
>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
style={getOptionStyle(option.color)}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
{isSelected && <Check className="w-4 h-4 text-primary" />}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
function ConditionValueInput({
|
||||
field,
|
||||
operator,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
field: FieldType
|
||||
field: FilterField | undefined
|
||||
operator: SearchConditionOperator
|
||||
value: unknown
|
||||
onChange: (val: unknown) => void
|
||||
}) {
|
||||
if (!field) return <Input disabled />
|
||||
|
||||
if (field.type === 'select' && field.options) {
|
||||
if ((field.type === 'select' || field.type === 'selectMulti') && field.options) {
|
||||
if (isMultiSelectOperator(field.type, operator)) {
|
||||
const selected = Array.isArray(value) ? (value as string[]) : []
|
||||
return (
|
||||
<MultiSelectValueInput
|
||||
options={field.options}
|
||||
selected={selected}
|
||||
onChange={(val) => onChange(val)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
// Single-select
|
||||
return (
|
||||
<Select value={value as string} onValueChange={onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select option" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{field.options.map((opt: FieldType) => (
|
||||
{field.options.map((opt) => (
|
||||
<SelectItem key={opt.id} value={opt.id}>
|
||||
{opt.displayName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'selectMulti' && field.options) {
|
||||
const selected = Array.isArray(value) ? value : []
|
||||
return (
|
||||
<Select
|
||||
value={selected[0] || ''}
|
||||
onValueChange={(val) => {
|
||||
if (selected.includes(val)) {
|
||||
onChange(selected.filter((v) => v !== val))
|
||||
} else {
|
||||
onChange([...selected, val])
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue
|
||||
placeholder={selected.length > 0 ? `${selected.length} selected` : 'Select options'}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{field.options.map((opt: FieldType) => (
|
||||
<SelectItem key={opt.id} value={opt.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(opt.id)}
|
||||
readOnly
|
||||
className="pointer-events-none"
|
||||
/>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
style={getOptionStyle(opt.color)}
|
||||
>
|
||||
{opt.displayName}
|
||||
</div>
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
@@ -378,6 +483,16 @@ function ConditionValueInput({
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'rating') {
|
||||
return (
|
||||
<RatingField
|
||||
value={Number(value) || 0}
|
||||
config={field.config || { name: field.label, type: 'rating' }}
|
||||
onSave={onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'toggle') {
|
||||
return (
|
||||
<Select
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { SearchCondition } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
@@ -221,9 +222,6 @@ export function SearchFilterDialog({
|
||||
|
||||
const handleClearFilters = () => {
|
||||
setConditions([])
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
setIsSemantic(false)
|
||||
}
|
||||
|
||||
const formatTimestamp = (seconds: number) => {
|
||||
@@ -242,7 +240,10 @@ export function SearchFilterDialog({
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id! },
|
||||
search: { version: undefined },
|
||||
search: {
|
||||
version: undefined,
|
||||
start: item.startTime && item.startTime > 0 ? item.startTime : undefined,
|
||||
},
|
||||
})
|
||||
}
|
||||
onOpenChange(false)
|
||||
@@ -252,7 +253,7 @@ export function SearchFilterDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[900px] p-0 gap-0 overflow-hidden bg-background border-border rounded-2xl shadow-2xl flex flex-col max-h-[90vh]">
|
||||
<DialogContent className="sm:max-w-[900px] p-0 gap-0 overflow-hidden bg-background border-border rounded-2xl shadow-2xl flex flex-col h-[85vh]">
|
||||
<DialogHeader className="px-6 pt-3 pb-0 text-left">
|
||||
<DialogTitle className="text-lg font-bold">Search</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -325,17 +326,20 @@ export function SearchFilterDialog({
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div
|
||||
onClick={() => setIsFiltersExpanded(!isFiltersExpanded)}
|
||||
className="flex items-center justify-between py-1.5 px-1 mt-1 rounded-lg hover:bg-accent/50 cursor-pointer select-none transition-colors group"
|
||||
>
|
||||
<div className="flex items-center justify-between py-1.5 px-1 mt-1 select-none">
|
||||
<div className="flex items-center gap-2">
|
||||
{isFiltersExpanded ? (
|
||||
<ChevronUp className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
|
||||
)}
|
||||
<span className="text-xs font-semibold text-foreground/80">Filters</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsFiltersExpanded(!isFiltersExpanded)}
|
||||
className="flex items-center gap-2 py-1 px-1.5 rounded-lg hover:bg-accent/50 cursor-pointer transition-colors group text-left"
|
||||
>
|
||||
{isFiltersExpanded ? (
|
||||
<ChevronUp className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
|
||||
)}
|
||||
<span className="text-xs font-semibold text-foreground/80">Filters</span>
|
||||
</button>
|
||||
|
||||
{activeFiltersCount > 0 && (
|
||||
<span className="px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/10 text-primary border border-primary/20">
|
||||
@@ -344,7 +348,7 @@ export function SearchFilterDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(activeFiltersCount > 0 || searchInput) && (
|
||||
{activeFiltersCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
@@ -359,148 +363,155 @@ export function SearchFilterDialog({
|
||||
</div>
|
||||
|
||||
{isFiltersExpanded && (
|
||||
<div className="mt-1 p-4 bg-muted/40 border border-border rounded-xl flex flex-col gap-3 animate-in slide-in-from-top-1 duration-200">
|
||||
<FilterPanel
|
||||
fields={fields}
|
||||
conditions={conditions}
|
||||
onChange={setConditions}
|
||||
excludeFields={['name']}
|
||||
hidePrefix={true}
|
||||
className="p-0 bg-transparent space-y-2"
|
||||
/>
|
||||
</div>
|
||||
<ScrollArea className="mt-1 max-h-[28vh] rounded-xl border border-border bg-muted/40">
|
||||
<div className="p-4 flex flex-col gap-3 animate-in slide-in-from-top-1 duration-200">
|
||||
<FilterPanel
|
||||
fields={fields}
|
||||
conditions={conditions}
|
||||
onChange={setConditions}
|
||||
excludeFields={['name']}
|
||||
hidePrefix={true}
|
||||
className="p-0 bg-transparent space-y-2"
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results Body ported from Demo */}
|
||||
<div className="flex-1 overflow-y-auto p-4 md:p-5 bg-background">
|
||||
<div className="flex items-center justify-between mb-3 px-1">
|
||||
<span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono">
|
||||
Search Results
|
||||
</span>
|
||||
{isLoading && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-primary">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
{isSemantic
|
||||
? 'Semantic search using media intelligence might be slow...'
|
||||
: 'Querying database...'}
|
||||
<ScrollArea className="flex-1 min-h-0 bg-background">
|
||||
<div className="p-4 md:p-5">
|
||||
<div className="flex items-center justify-between mb-3 px-1">
|
||||
<span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono">
|
||||
Search Results
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{isLoading && (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs text-primary">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
{isSemantic
|
||||
? 'Semantic search using media intelligence might be slow...'
|
||||
: 'Querying database...'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden">
|
||||
{!hasActiveCriteria ? (
|
||||
<div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4">
|
||||
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">Ready to Search</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
Type your query above and click the Search button to display results.
|
||||
</p>
|
||||
{isSemantic && (
|
||||
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
|
||||
Semantic search results will be ordered by their relevance to the search query
|
||||
text, but won't be strictly filtered. If you need accurate filtering, please add
|
||||
filter conditions to control that.
|
||||
<div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden">
|
||||
{!hasActiveCriteria ? (
|
||||
<div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4">
|
||||
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">Ready to Search</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
Type your query above and click the Search button to display results.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : searchError ? (
|
||||
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
|
||||
<AlertCircle className="w-10 h-10 text-destructive/50 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">Search failed</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{searchError.message.includes('Embedding agent not configured')
|
||||
? 'Please create and enable an embedding agent in the team settings to use semantic search.'
|
||||
: searchError.message}
|
||||
</p>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
Array.from({ length: 3 }).map((_, idx) => (
|
||||
<div key={idx} className="p-3.5 flex items-center gap-3 animate-pulse bg-muted/10">
|
||||
<div className="w-11 h-11 rounded-xl bg-muted shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="h-4 bg-muted rounded w-1/3" />
|
||||
<div className="h-3 bg-muted/50 rounded w-1/4" />
|
||||
</div>
|
||||
{isSemantic && (
|
||||
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
|
||||
Semantic search results will be ordered by their relevance to the search query
|
||||
text, but won't be strictly filtered. If you need accurate filtering, please
|
||||
add filter conditions to control that.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
) : flattenedResults.length === 0 ? (
|
||||
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
|
||||
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">
|
||||
No records matched your criteria
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
Try adjusting spelling or removing filter rows.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{flattenedResults.map((record) => (
|
||||
) : searchError ? (
|
||||
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
|
||||
<AlertCircle className="w-10 h-10 text-destructive/50 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">Search failed</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{searchError.message.includes('Embedding agent not configured')
|
||||
? 'Please create and enable an embedding agent in the team settings to use semantic search.'
|
||||
: searchError.message}
|
||||
</p>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
Array.from({ length: 3 }).map((_, idx) => (
|
||||
<div
|
||||
key={record.id}
|
||||
onClick={() => handleResultClick(record)}
|
||||
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
|
||||
key={idx}
|
||||
className="p-3.5 flex items-center gap-3 animate-pulse bg-muted/10"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
|
||||
record.type === 'folder' ? 'bg-primary/5' : '',
|
||||
)}
|
||||
>
|
||||
{record.preview?.thumbnailUrl ? (
|
||||
<img
|
||||
src={record.preview.thumbnailUrl}
|
||||
alt=""
|
||||
className="w-full h-full object-cover rounded-xl"
|
||||
/>
|
||||
) : record.type === 'folder' ? (
|
||||
<FolderIcon className="h-6 w-6 text-primary/70" />
|
||||
) : (
|
||||
<FileIcon className="h-6 w-6 text-muted-foreground" />
|
||||
)}
|
||||
<div className="w-11 h-11 rounded-xl bg-muted shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="h-4 bg-muted rounded w-1/3" />
|
||||
<div className="h-3 bg-muted/50 rounded w-1/4" />
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : flattenedResults.length === 0 ? (
|
||||
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
|
||||
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">
|
||||
No records matched your criteria
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
Try adjusting spelling or removing filter rows.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{flattenedResults.map((record) => (
|
||||
<div
|
||||
key={record.id}
|
||||
onClick={() => handleResultClick(record)}
|
||||
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
|
||||
record.type === 'folder' ? 'bg-primary/5' : '',
|
||||
)}
|
||||
>
|
||||
{record.preview?.thumbnailUrl ? (
|
||||
<img
|
||||
src={record.preview.thumbnailUrl}
|
||||
alt=""
|
||||
className="w-full h-full object-cover rounded-xl"
|
||||
/>
|
||||
) : record.type === 'folder' ? (
|
||||
<FolderIcon className="h-6 w-6 text-primary/70" />
|
||||
) : (
|
||||
<FileIcon className="h-6 w-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="truncate">
|
||||
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
|
||||
{record.name}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="truncate">
|
||||
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
|
||||
{record.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
|
||||
{record.type === 'folder'
|
||||
? 'Folder'
|
||||
: `Size: ${formatSize(record.sizeByte || 0)}`}
|
||||
</span>
|
||||
{record.startTime !== undefined &&
|
||||
record.startTime !== null &&
|
||||
record.endTime !== undefined &&
|
||||
record.endTime !== null && (
|
||||
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
|
||||
Match found at {formatTimestamp(record.startTime)} -{' '}
|
||||
{formatTimestamp(record.endTime)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground font-mono shrink-0">
|
||||
{new Date(record.createdAt).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
|
||||
{record.type === 'folder'
|
||||
? 'Folder'
|
||||
: `Size: ${formatSize(record.sizeByte || 0)}`}
|
||||
</span>
|
||||
{record.startTime !== undefined &&
|
||||
record.startTime !== null &&
|
||||
record.endTime !== undefined &&
|
||||
record.endTime !== null && (
|
||||
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
|
||||
Match found at {formatTimestamp(record.startTime)} -{' '}
|
||||
{formatTimestamp(record.endTime)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground font-mono shrink-0">
|
||||
{new Date(record.createdAt).toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(hasNextPage || isFetchingNextPage) && (
|
||||
<div ref={ref} className="p-4 flex justify-center items-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
))}
|
||||
{(hasNextPage || isFetchingNextPage) && (
|
||||
<div ref={ref} className="p-4 flex justify-center items-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Footer ported from Demo */}
|
||||
<div className="p-4 border-t border-border bg-muted/30 flex items-center justify-between shrink-0">
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
|
||||
import type {
|
||||
AncestorFolder,
|
||||
AssetInfo,
|
||||
AssetInfoPaginatedList,
|
||||
UpdateShareLinkRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useState, useMemo } from 'react'
|
||||
@@ -86,12 +91,20 @@ export default function ShareManager({
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
|
||||
viewModes,
|
||||
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
shareConfigRightSidebarCollapsed: isRightSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const displayStyle = viewModes[projectId] ?? 'card'
|
||||
const defaultSortOrder = shareLink?.defaultSortOrder || null
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
if (defaultSortOrder) {
|
||||
const parts = defaultSortOrder.split(':')
|
||||
sort = parts[0]
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const displayStyle = (shareLink?.viewMode as 'card' | 'list') ?? 'card'
|
||||
|
||||
const {
|
||||
data: foldersData,
|
||||
@@ -99,13 +112,15 @@ export default function ShareManager({
|
||||
hasNextPage: hasNextPageFolders,
|
||||
isFetchingNextPage: isFetchingNextFoldersPage,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'folder'],
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'folder', sort, order],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: currentFolderId! },
|
||||
query: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
sort,
|
||||
order,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folders')
|
||||
@@ -122,13 +137,15 @@ export default function ShareManager({
|
||||
hasNextPage: hasNextPageFiles,
|
||||
isFetchingNextPage: isFetchingNextFilesPage,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'file'],
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'file', sort, order],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: currentFolderId! },
|
||||
query: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
sort,
|
||||
order,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch files')
|
||||
@@ -212,6 +229,22 @@ export default function ShareManager({
|
||||
},
|
||||
})
|
||||
|
||||
const $updateShare = client.api.shares[':shareId'].$put
|
||||
const { mutate: updateShare } = useMutation({
|
||||
mutationFn: async (json: UpdateShareLinkRequest) => {
|
||||
const res = await $updateShare({
|
||||
param: { shareId },
|
||||
json,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['share', shareId] })
|
||||
toast.success('Settings updated')
|
||||
},
|
||||
})
|
||||
|
||||
const handleItemDoubleClick = (item: AssetInfo) => {
|
||||
if (item.type === 'folder' || item.targetType === 'folder') {
|
||||
const currentFolderName =
|
||||
@@ -239,7 +272,7 @@ export default function ShareManager({
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<div className="flex h-screen flex-col bg-background">
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
@@ -305,8 +338,14 @@ export default function ShareManager({
|
||||
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
|
||||
}
|
||||
/>
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
|
||||
<ShareSettingsSidebar shareLink={shareLink} />
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 h-full">
|
||||
<ShareSettingsSidebar
|
||||
shareLink={shareLink}
|
||||
viewMode={displayStyle}
|
||||
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
|
||||
defaultSortOrder={defaultSortOrder}
|
||||
onSortOrderChange={(sortOrder) => updateShare({ defaultSortOrder: sortOrder })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -11,19 +11,39 @@ import {
|
||||
Copy,
|
||||
ExternalLink,
|
||||
Shield,
|
||||
Settings2,
|
||||
Palette,
|
||||
ListFilter,
|
||||
SortAsc,
|
||||
LayoutGrid,
|
||||
List,
|
||||
ArrowDownUp,
|
||||
} from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
|
||||
interface ShareSettingsSidebarProps {
|
||||
shareLink: ShareLinkInfo
|
||||
viewMode: 'card' | 'list'
|
||||
onViewModeChange: (mode: 'card' | 'list') => void
|
||||
defaultSortOrder: string | null
|
||||
onSortOrderChange: (sortOrder: string | null) => void
|
||||
}
|
||||
|
||||
export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
export function ShareSettingsSidebar({
|
||||
shareLink,
|
||||
viewMode,
|
||||
onViewModeChange,
|
||||
defaultSortOrder,
|
||||
onSortOrderChange,
|
||||
}: ShareSettingsSidebarProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [password, setPassword] = useState('')
|
||||
const [expireAt, setExpireAt] = useState<Date | undefined>(
|
||||
@@ -74,6 +94,15 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
updateShare({ fieldVisibility: next })
|
||||
}
|
||||
|
||||
// Parse current sort field and order
|
||||
let currentSortField = 'index'
|
||||
let currentSortOrder = 'asc'
|
||||
if (defaultSortOrder) {
|
||||
const parts = defaultSortOrder.split(':')
|
||||
currentSortField = parts[0]
|
||||
currentSortOrder = parts[1] || 'asc'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background border-l border-border">
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
@@ -87,29 +116,20 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full"
|
||||
onClick={() => copyToClipboard(shareUrl)}
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="outline" className="px-3">
|
||||
<Settings2 className="h-4 w-4 mr-2" />
|
||||
Public
|
||||
<div className="relative w-full">
|
||||
<Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full"
|
||||
onClick={() => copyToClipboard(shareUrl)}
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Input placeholder="Send to name or email" className="text-sm" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<SidebarAccordionItem title="Permissions" icon={<Settings2 className="h-4 w-4" />} />
|
||||
<SidebarAccordionItem title="Security" icon={<Shield className="h-4 w-4" />}>
|
||||
<div className="p-3 space-y-4 pt-0">
|
||||
<div className="space-y-2">
|
||||
@@ -167,7 +187,28 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
</div>
|
||||
</div>
|
||||
</SidebarAccordionItem>
|
||||
<SidebarAccordionItem title="Appearance" icon={<Palette className="h-4 w-4" />} />
|
||||
<SidebarAccordionItem title="Appearance" icon={<Palette className="h-4 w-4" />}>
|
||||
<div className="p-3 space-y-3 pt-0 flex gap-2">
|
||||
<Button
|
||||
variant={viewMode === 'card' ? 'secondary' : 'outline'}
|
||||
size="sm"
|
||||
className="flex-1 gap-2 text-xs"
|
||||
onClick={() => onViewModeChange('card')}
|
||||
>
|
||||
<LayoutGrid className="h-4 w-4" />
|
||||
Grid
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === 'list' ? 'secondary' : 'outline'}
|
||||
size="sm"
|
||||
className="flex-1 gap-2 text-xs"
|
||||
onClick={() => onViewModeChange('list')}
|
||||
>
|
||||
<List className="h-4 w-4" />
|
||||
List
|
||||
</Button>
|
||||
</div>
|
||||
</SidebarAccordionItem>
|
||||
<SidebarAccordionItem title="Fields" icon={<ListFilter className="h-4 w-4" />}>
|
||||
<div className="p-3 space-y-3 pt-0">
|
||||
{(fields as MetadataFieldInfo[])?.map((field) => (
|
||||
@@ -181,7 +222,65 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
))}
|
||||
</div>
|
||||
</SidebarAccordionItem>
|
||||
<SidebarAccordionItem title="Sort by" icon={<SortAsc className="h-4 w-4" />} />
|
||||
<SidebarAccordionItem title="Sort by" icon={<SortAsc className="h-4 w-4" />}>
|
||||
<div className="p-3 space-y-4 pt-0">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">Field</Label>
|
||||
<Select
|
||||
value={currentSortField}
|
||||
onValueChange={(val) => {
|
||||
if (val === 'index') {
|
||||
onSortOrderChange(null)
|
||||
} else {
|
||||
onSortOrderChange(`${val}:${currentSortOrder}`)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full text-xs h-9">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="index">Custom</SelectItem>
|
||||
<SelectItem value="name">Name</SelectItem>
|
||||
<SelectItem value="createdAt">Date Created</SelectItem>
|
||||
<SelectItem value="size">Size</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">Order</Label>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-between font-normal text-xs h-9"
|
||||
disabled={currentSortField === 'index'}
|
||||
onClick={() => {
|
||||
const nextOrder = currentSortOrder === 'asc' ? 'desc' : 'asc'
|
||||
onSortOrderChange(`${currentSortField}:${nextOrder}`)
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
{currentSortField === 'name'
|
||||
? currentSortOrder === 'asc'
|
||||
? 'A → Z'
|
||||
: 'Z → A'
|
||||
: currentSortField === 'createdAt'
|
||||
? currentSortOrder === 'asc'
|
||||
? 'Oldest → Newest'
|
||||
: 'Newest → Oldest'
|
||||
: currentSortField === 'size'
|
||||
? currentSortOrder === 'asc'
|
||||
? 'Smallest → Largest'
|
||||
: 'Largest → Smallest'
|
||||
: currentSortOrder === 'asc'
|
||||
? 'Ascending'
|
||||
: 'Descending'}
|
||||
</span>
|
||||
<ArrowDownUp className="h-4 w-4 opacity-50" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarAccordionItem>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -27,23 +27,41 @@ export function TopNav() {
|
||||
|
||||
const isFileView = !!fileId
|
||||
|
||||
const isShareConfig = !!shareId && !isFileView
|
||||
|
||||
const isLeftSidebarCollapsed = isFileView
|
||||
? uiStore.fileViewLeftSidebarCollapsed
|
||||
: uiStore.fileListLeftSidebarCollapsed
|
||||
: isShareConfig
|
||||
? uiStore.shareConfigLeftSidebarCollapsed
|
||||
: uiStore.fileListLeftSidebarCollapsed
|
||||
const onLeftSidebarToggle = isPublic
|
||||
? undefined
|
||||
: () =>
|
||||
isFileView
|
||||
? uiStore.setFileViewLeftSidebarCollapsed(!uiStore.fileViewLeftSidebarCollapsed)
|
||||
: uiStore.setFileListLeftSidebarCollapsed(!uiStore.fileListLeftSidebarCollapsed)
|
||||
: isShareConfig
|
||||
? uiStore.setShareConfigLeftSidebarCollapsed(!uiStore.shareConfigLeftSidebarCollapsed)
|
||||
: uiStore.setFileListLeftSidebarCollapsed(!uiStore.fileListLeftSidebarCollapsed)
|
||||
|
||||
const isRightSidebarCollapsed = isFileView
|
||||
? uiStore.fileViewRightSidebarCollapsed
|
||||
: uiStore.fileListRightSidebarCollapsed
|
||||
const onRightSidebarToggle = () =>
|
||||
isFileView
|
||||
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
|
||||
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
|
||||
const isRightSidebarCollapsed =
|
||||
isPublic && projectState.isRightSidebarCollapsed !== undefined
|
||||
? projectState.isRightSidebarCollapsed
|
||||
: isFileView
|
||||
? uiStore.fileViewRightSidebarCollapsed
|
||||
: isShareConfig
|
||||
? uiStore.shareConfigRightSidebarCollapsed
|
||||
: uiStore.fileListRightSidebarCollapsed
|
||||
const onRightSidebarToggle =
|
||||
isPublic && projectState.onRightSidebarToggle
|
||||
? projectState.onRightSidebarToggle
|
||||
: () =>
|
||||
isFileView
|
||||
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
|
||||
: isShareConfig
|
||||
? uiStore.setShareConfigRightSidebarCollapsed(
|
||||
!uiStore.shareConfigRightSidebarCollapsed,
|
||||
)
|
||||
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
|
||||
|
||||
const displayStyle = projectId ? (uiStore.viewModes[projectId] ?? 'card') : 'card'
|
||||
const onDisplayStyleChange = isPublic
|
||||
@@ -60,8 +78,8 @@ export function TopNav() {
|
||||
ancestorFolders={ancestorFolders}
|
||||
currentAsset={currentAsset}
|
||||
isRootFolder={isRootFolder}
|
||||
displayStyle={isFileView ? undefined : displayStyle}
|
||||
onDisplayStyleChange={isFileView ? undefined : onDisplayStyleChange}
|
||||
displayStyle={isFileView || isShareConfig ? undefined : displayStyle}
|
||||
onDisplayStyleChange={isFileView || isShareConfig ? undefined : onDisplayStyleChange}
|
||||
isLeftSidebarCollapsed={isLeftSidebarCollapsed}
|
||||
onLeftSidebarToggle={onLeftSidebarToggle}
|
||||
isRightSidebarCollapsed={isRightSidebarCollapsed}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface ProgressCircleProps {
|
||||
progress: number
|
||||
@@ -8,15 +9,15 @@ interface ProgressCircleProps {
|
||||
export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, className }) => {
|
||||
const radius = 20
|
||||
const circumference = 2 * Math.PI * radius
|
||||
const offset = circumference - (progress / 100) * circumference
|
||||
const offset = circumference - (Math.min(100, Math.max(0, progress)) / 100) * circumference
|
||||
|
||||
return (
|
||||
<svg width="50" height="50" viewBox="0 0 50 50" className={className}>
|
||||
<svg viewBox="0 0 50 50" className={cn('w-12 h-12', className)}>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r={radius}
|
||||
className="stroke-current text-gray-200"
|
||||
className="stroke-muted"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
/>
|
||||
@@ -24,12 +25,11 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
|
||||
cx="25"
|
||||
cy="25"
|
||||
r={radius}
|
||||
className="stroke-current text-blue-600"
|
||||
className="stroke-primary transition-all duration-300 ease-out"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={offset}
|
||||
style={{ transition: 'stroke-dashoffset 0.3s' }}
|
||||
transform="rotate(-90 25 25)"
|
||||
/>
|
||||
<text
|
||||
@@ -37,7 +37,7 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
|
||||
y="50%"
|
||||
textAnchor="middle"
|
||||
dy=".3em"
|
||||
className="text-xs font-semibold text-gray-700"
|
||||
className="fill-foreground text-[10px] font-bold"
|
||||
>
|
||||
{`${Math.round(progress)}%`}
|
||||
</text>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useTeamId } from '@/ui/hooks/use-team-id'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { format, parseISO, isToday, isYesterday } from 'date-fns'
|
||||
import { Progress } from '@/ui/components/ui/progress'
|
||||
@@ -24,9 +24,28 @@ function formatDayHeader(dateString: string): string {
|
||||
return format(date, 'MMMM d, yyyy')
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B'
|
||||
const k = 1024
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
function UploadTaskItem({ task }: { task: TaskInfo }) {
|
||||
const isCompleted = task.uploaded === task.total
|
||||
const percent = task.total > 0 ? (task.uploaded / task.total) * 100 : 0
|
||||
const clientProgress = useUploadStore((state) => state.tasks[task.id])
|
||||
|
||||
const isCompleted = clientProgress
|
||||
? clientProgress.loaded === clientProgress.total && task.uploaded === task.total
|
||||
: task.uploaded === task.total
|
||||
|
||||
const percent = clientProgress
|
||||
? clientProgress.total > 0
|
||||
? (clientProgress.loaded / clientProgress.total) * 100
|
||||
: 0
|
||||
: task.total > 0
|
||||
? (task.uploaded / task.total) * 100
|
||||
: 0
|
||||
|
||||
let formattedTime: string
|
||||
try {
|
||||
@@ -72,7 +91,9 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
|
||||
<div className="space-y-1.5 mt-auto">
|
||||
<div className="flex items-center justify-between text-xs font-semibold">
|
||||
<span className="text-muted-foreground/80">
|
||||
{task.uploaded} / {task.total} {task.total === 1 ? 'file' : 'files'}
|
||||
{clientProgress
|
||||
? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'})`
|
||||
: `${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'}`}
|
||||
</span>
|
||||
{!isCompleted && (
|
||||
<span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span>
|
||||
@@ -92,6 +113,7 @@ interface TaskGroup {
|
||||
export function UploadTasks() {
|
||||
const teamId = useTeamId()
|
||||
const uploading = useUploadStore((state) => state.uploading)
|
||||
const clientActiveTasks = useUploadStore((state) => state.tasks)
|
||||
const {
|
||||
data: tasksData,
|
||||
fetchNextPage,
|
||||
@@ -126,6 +148,27 @@ export function UploadTasks() {
|
||||
|
||||
const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
|
||||
const combinedTasks = useMemo(() => {
|
||||
const serverTaskIds = new Set(tasks.map((t) => t.id))
|
||||
const clientOnlyTasks: TaskInfo[] = Object.values(clientActiveTasks)
|
||||
.filter((ct) => !serverTaskIds.has(ct.taskId))
|
||||
.map((ct) => {
|
||||
const completedCount = Object.values(ct.files).filter(
|
||||
(f) => f.status === 'completed' || f.status === 'failed',
|
||||
).length
|
||||
|
||||
return {
|
||||
id: ct.taskId,
|
||||
name: ct.name,
|
||||
total: Object.keys(ct.files).length,
|
||||
uploaded: completedCount,
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
})
|
||||
|
||||
return [...clientOnlyTasks, ...tasks].sort((a, b) => b.id.localeCompare(a.id))
|
||||
}, [tasks, clientActiveTasks])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
@@ -134,7 +177,7 @@ export function UploadTasks() {
|
||||
)
|
||||
}
|
||||
|
||||
if (tasks.length === 0) {
|
||||
if (combinedTasks.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-center border border-dashed border-border rounded-xl bg-muted/10 my-4">
|
||||
<UploadCloud className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||
@@ -148,7 +191,7 @@ export function UploadTasks() {
|
||||
|
||||
// Group tasks by day (maintaining desc ordering)
|
||||
const taskGroups: TaskGroup[] = []
|
||||
tasks.forEach((task) => {
|
||||
combinedTasks.forEach((task) => {
|
||||
const day = formatDayHeader(task.createdAt)
|
||||
let group = taskGroups.find((g) => g.day === day)
|
||||
if (!group) {
|
||||
|
||||
@@ -299,7 +299,7 @@ export function useFileSystemDnd({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
queryKey: ['folders'],
|
||||
})
|
||||
// Clear selection after move
|
||||
onClearSelection()
|
||||
|
||||
@@ -5,20 +5,39 @@ import {
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { useTeamId } from '@/ui/hooks/use-team-id'
|
||||
import { signOut } from '@/ui/lib/auth-client'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useTheme } from './theme-provider'
|
||||
import { Check } from 'lucide-react'
|
||||
import { APP_VERSION } from '../version'
|
||||
import { useTheme } from './theme-provider'
|
||||
|
||||
const Github = (props: React.SVGProps<SVGSVGElement>) => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
{...props}
|
||||
>
|
||||
<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
|
||||
<path d="M9 18c-4.51 2-5-2-7-2" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
export function UserMenu() {
|
||||
const { clearAuth } = useAuthStore()
|
||||
@@ -125,6 +144,16 @@ export function UserMenu() {
|
||||
<DropdownMenuItem className="text-red-500 focus:text-red-500" onClick={handleLogout}>
|
||||
Log out
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-xs text-muted-foreground flex items-center gap-2 cursor-pointer focus:bg-accent focus:text-accent-foreground justify-center bg-accent border"
|
||||
onClick={() =>
|
||||
window.open('https://github.com/shumaiOne/shumai', '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
>
|
||||
<Github className="size-3.5" />
|
||||
<span>Version {APP_VERSION}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
|
||||
@@ -53,6 +53,7 @@ interface VideoPlayerProps {
|
||||
onPause?: () => void
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
@@ -311,6 +312,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
children,
|
||||
}) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
@@ -550,6 +552,13 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
// Set initial state
|
||||
player.volume(state.volume)
|
||||
|
||||
// Seek to startTime if provided
|
||||
if (startTime && startTime > 0) {
|
||||
player.ready(() => {
|
||||
player.currentTime(startTime)
|
||||
})
|
||||
}
|
||||
|
||||
// 4. Cleanup
|
||||
return () => {
|
||||
if (player && !player.isDisposed()) {
|
||||
@@ -559,6 +568,18 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
}
|
||||
}, [data])
|
||||
|
||||
// Handle changes to startTime (e.g., clicking different chunks in search results)
|
||||
useEffect(() => {
|
||||
const player = playerRef.current
|
||||
if (player && startTime !== undefined && startTime !== null && startTime > 0) {
|
||||
// Only seek if the difference is significant (e.g., > 1s) to avoid jumping due to small precision differences
|
||||
const current = player.currentTime() || 0
|
||||
if (Math.abs(current - startTime) > 1) {
|
||||
player.currentTime(startTime)
|
||||
}
|
||||
}
|
||||
}, [startTime, playerRef])
|
||||
|
||||
// Smooth progress updates using requestAnimationFrame when playing
|
||||
useEffect(() => {
|
||||
let animationFrameId: number
|
||||
|
||||
@@ -3,3 +3,114 @@ export function arrayMove<T>(array: T[], from: number, to: number): T[] {
|
||||
newArray.splice(to, 0, newArray.splice(from, 1)[0])
|
||||
return newArray
|
||||
}
|
||||
|
||||
interface SafeFileSystemEntry {
|
||||
name: string
|
||||
isFile: boolean
|
||||
isDirectory: boolean
|
||||
}
|
||||
|
||||
interface SafeFileSystemFileEntry extends SafeFileSystemEntry {
|
||||
file(successCallback: (file: File) => void, errorCallback?: (err: unknown) => void): void
|
||||
}
|
||||
|
||||
interface SafeFileSystemDirectoryEntry extends SafeFileSystemEntry {
|
||||
createReader(): SafeFileSystemDirectoryReader
|
||||
}
|
||||
|
||||
interface SafeFileSystemDirectoryReader {
|
||||
readEntries(
|
||||
successCallback: (entries: SafeFileSystemEntry[]) => void,
|
||||
errorCallback?: (err: unknown) => void,
|
||||
): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively retrieves all files from a DataTransfer object, traversing directories.
|
||||
* Preserves the directory structure using the non-standard `webkitRelativePath` property on File objects.
|
||||
*/
|
||||
export async function getAllFilesFromEntries(dataTransfer: DataTransfer): Promise<File[]> {
|
||||
const files: File[] = []
|
||||
|
||||
interface QueueItem {
|
||||
entry: SafeFileSystemEntry
|
||||
path: string
|
||||
}
|
||||
|
||||
const queue: QueueItem[] = []
|
||||
const items = dataTransfer.items
|
||||
|
||||
if (items) {
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.kind === 'file') {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const entry = (item as any).webkitGetAsEntry?.() as SafeFileSystemEntry | null
|
||||
if (entry) {
|
||||
queue.push({ entry, path: '' })
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fallback if dataTransfer.items is not supported (only dataTransfer.files is available)
|
||||
return Array.from(dataTransfer.files)
|
||||
}
|
||||
|
||||
const readEntries = (
|
||||
dirReader: SafeFileSystemDirectoryReader,
|
||||
): Promise<SafeFileSystemEntry[]> => {
|
||||
return new Promise((resolve) => {
|
||||
dirReader.readEntries(
|
||||
(entries) => resolve(entries),
|
||||
() => resolve([]),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const getFile = (fileEntry: SafeFileSystemFileEntry): Promise<File> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fileEntry.file(
|
||||
(file) => resolve(file),
|
||||
(err) => reject(err),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
while (queue.length > 0) {
|
||||
const next = queue.shift()
|
||||
if (!next) continue
|
||||
const { entry, path } = next
|
||||
|
||||
if (entry.isFile) {
|
||||
try {
|
||||
const file = await getFile(entry as SafeFileSystemFileEntry)
|
||||
const relativePath = path ? `${path}/${file.name}` : file.name
|
||||
|
||||
// Define webkitRelativePath dynamically so processAndUploadFiles can read the structure
|
||||
Object.defineProperty(file, 'webkitRelativePath', {
|
||||
value: relativePath,
|
||||
writable: false,
|
||||
configurable: true,
|
||||
})
|
||||
files.push(file)
|
||||
} catch (e) {
|
||||
console.error('Error reading file entry:', e)
|
||||
}
|
||||
} else if (entry.isDirectory) {
|
||||
const dirReader = (entry as SafeFileSystemDirectoryEntry).createReader()
|
||||
let entries: SafeFileSystemEntry[] = []
|
||||
let readBatch = await readEntries(dirReader)
|
||||
while (readBatch.length > 0) {
|
||||
entries = entries.concat(readBatch)
|
||||
readBatch = await readEntries(dirReader)
|
||||
}
|
||||
|
||||
const newPath = path ? `${path}/${entry.name}` : entry.name
|
||||
for (const childEntry of entries) {
|
||||
queue.push({ entry: childEntry, path: newPath })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { signIn } from '@/ui/lib/auth-client'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowRight, Loader2, Lock, LogIn, Mail } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
import { signIn } from '@/ui/lib/auth-client'
|
||||
import { Loader2, Mail, Lock, ArrowRight, LogIn } from 'lucide-react'
|
||||
import { ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { AuthLayout } from '@/ui/components/auth-layout'
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email('Invalid email address'),
|
||||
@@ -37,11 +37,13 @@ function LoginPage() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (signupInfo?.userCount === 0) {
|
||||
if (signupInfo && !signupInfo.initialized) {
|
||||
navigate({ to: '/signup', search: { inviteCode: '' } })
|
||||
}
|
||||
}, [signupInfo, navigate])
|
||||
|
||||
const isDemoEnv = signupInfo?.demoMode === true
|
||||
|
||||
const form = useForm<LoginSchema>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
})
|
||||
@@ -88,6 +90,15 @@ function LoginPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{isDemoEnv && (
|
||||
<div className="mb-6 p-4 bg-blue-500/10 border border-blue-500/20 text-blue-700 dark:text-blue-400 rounded-xl text-sm leading-relaxed">
|
||||
<p>
|
||||
<strong>Demo Access:</strong> Use <strong>"foo@bar.com"</strong> as the email and{' '}
|
||||
<strong>"foo"</strong> as the password to login.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-3 bg-red-500/10 border border-red-500/20 text-red-600 dark:text-red-400 rounded-xl text-sm text-center font-medium">
|
||||
{error}
|
||||
|
||||
@@ -21,7 +21,8 @@ import type Player from 'video.js/dist/types/player'
|
||||
function FileViewPage() {
|
||||
const { projectId, fileId } = Route.useParams()
|
||||
const search = Route.useSearch()
|
||||
const versionAssetId = (search as { version?: string }).version
|
||||
const versionAssetId = search.version
|
||||
const startTime = search.start
|
||||
const activeFileId = versionAssetId || fileId
|
||||
|
||||
const videoRef = useRef<Player | null>(null)
|
||||
@@ -328,6 +329,7 @@ function FileViewPage() {
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={setCurrentTime}
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
@@ -373,6 +375,7 @@ export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
version: (search.version as string) || undefined,
|
||||
}
|
||||
start: search.start ? Number(search.start) : undefined,
|
||||
} as { version?: string; start?: number }
|
||||
},
|
||||
})
|
||||
|
||||
@@ -65,8 +65,8 @@ function SharesPage() {
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
} = useUiStore()
|
||||
|
||||
const {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
function PublicShareFilePage() {
|
||||
const { shareId, fileId } = Route.useParams()
|
||||
const { start } = Route.useSearch()
|
||||
|
||||
const { data: shareInfo } = useQuery({
|
||||
queryKey: ['share-info', shareId],
|
||||
@@ -27,10 +28,16 @@ function PublicShareFilePage() {
|
||||
isDisabled: shareInfo.isDisabled ?? false,
|
||||
}}
|
||||
initialFileId={fileId}
|
||||
startTime={start}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/share/$shareId/files/$fileId')({
|
||||
component: PublicShareFilePage,
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
start: search.start ? Number(search.start) : undefined,
|
||||
} as { start?: number }
|
||||
},
|
||||
})
|
||||
|
||||
@@ -96,7 +96,7 @@ function SignupPage() {
|
||||
)
|
||||
}
|
||||
|
||||
const isFirstUser = signupInfo?.userCount === 0
|
||||
const isFirstUser = signupInfo?.initialized === false
|
||||
const isPublicSignupDisabled = !isFirstUser && !inviteCode
|
||||
|
||||
if (isPublicSignupDisabled) {
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface TopNavProjectState {
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
onFolderClick?: (folderId: string) => void
|
||||
isRightSidebarCollapsed?: boolean
|
||||
onRightSidebarToggle?: () => void
|
||||
}
|
||||
|
||||
interface TopNavStore {
|
||||
|
||||
@@ -14,6 +14,12 @@ interface UiState {
|
||||
fileListRightSidebarCollapsed: boolean
|
||||
setFileListRightSidebarCollapsed: (collapsed: boolean) => void
|
||||
|
||||
shareConfigLeftSidebarCollapsed: boolean
|
||||
setShareConfigLeftSidebarCollapsed: (collapsed: boolean) => void
|
||||
|
||||
shareConfigRightSidebarCollapsed: boolean
|
||||
setShareConfigRightSidebarCollapsed: (collapsed: boolean) => void
|
||||
|
||||
viewModes: { [projectId: string]: 'card' | 'list' }
|
||||
setViewMode: (projectId: string, mode: 'card' | 'list') => void
|
||||
}
|
||||
@@ -33,10 +39,18 @@ export const useUiStore = create<UiState>()(
|
||||
setFileListLeftSidebarCollapsed: (collapsed) =>
|
||||
set({ fileListLeftSidebarCollapsed: collapsed }),
|
||||
|
||||
fileListRightSidebarCollapsed: false,
|
||||
fileListRightSidebarCollapsed: true,
|
||||
setFileListRightSidebarCollapsed: (collapsed) =>
|
||||
set({ fileListRightSidebarCollapsed: collapsed }),
|
||||
|
||||
shareConfigLeftSidebarCollapsed: false,
|
||||
setShareConfigLeftSidebarCollapsed: (collapsed) =>
|
||||
set({ shareConfigLeftSidebarCollapsed: collapsed }),
|
||||
|
||||
shareConfigRightSidebarCollapsed: false,
|
||||
setShareConfigRightSidebarCollapsed: (collapsed) =>
|
||||
set({ shareConfigRightSidebarCollapsed: collapsed }),
|
||||
|
||||
viewModes: {},
|
||||
setViewMode: (projectId, mode) =>
|
||||
set((state) => ({
|
||||
|
||||
@@ -1,13 +1,166 @@
|
||||
import { create } from 'zustand'
|
||||
|
||||
export interface FileUploadState {
|
||||
fileId: string
|
||||
name: string
|
||||
loaded: number
|
||||
total: number
|
||||
status: 'uploading' | 'completed' | 'failed'
|
||||
}
|
||||
|
||||
export interface TaskUploadState {
|
||||
taskId: string
|
||||
name: string
|
||||
loaded: number
|
||||
total: number
|
||||
files: Record<string, FileUploadState>
|
||||
}
|
||||
|
||||
type UploadStore = {
|
||||
uploading: number
|
||||
tasks: Record<string, TaskUploadState>
|
||||
fileProgress: Record<string, FileUploadState>
|
||||
increment: () => void
|
||||
decrement: () => void
|
||||
startTask: (
|
||||
taskId: string,
|
||||
taskName: string,
|
||||
files: Array<{ fileId: string; name: string; size: number }>,
|
||||
) => void
|
||||
updateFileProgress: (taskId: string, fileId: string, loaded: number) => void
|
||||
completeFile: (taskId: string, fileId: string) => void
|
||||
failFile: (taskId: string, fileId: string) => void
|
||||
}
|
||||
|
||||
export const useUploadStore = create<UploadStore>((set) => ({
|
||||
uploading: 0,
|
||||
tasks: {},
|
||||
fileProgress: {},
|
||||
increment: () => set((state) => ({ uploading: state.uploading + 1 })),
|
||||
decrement: () => set((state) => ({ uploading: state.uploading - 1 })),
|
||||
|
||||
startTask: (taskId, taskName, files) =>
|
||||
set((state) => {
|
||||
const taskFiles: Record<string, FileUploadState> = {}
|
||||
let totalBytes = 0
|
||||
|
||||
files.forEach((f) => {
|
||||
taskFiles[f.fileId] = {
|
||||
fileId: f.fileId,
|
||||
name: f.name,
|
||||
loaded: 0,
|
||||
total: f.size,
|
||||
status: 'uploading',
|
||||
}
|
||||
totalBytes += f.size
|
||||
})
|
||||
|
||||
const newTasks = {
|
||||
...state.tasks,
|
||||
[taskId]: {
|
||||
taskId,
|
||||
name: taskName,
|
||||
loaded: 0,
|
||||
total: totalBytes,
|
||||
files: taskFiles,
|
||||
},
|
||||
}
|
||||
|
||||
const newFileProgress = { ...state.fileProgress }
|
||||
files.forEach((f) => {
|
||||
newFileProgress[f.fileId] = taskFiles[f.fileId]
|
||||
})
|
||||
|
||||
return {
|
||||
tasks: newTasks,
|
||||
fileProgress: newFileProgress,
|
||||
}
|
||||
}),
|
||||
|
||||
updateFileProgress: (taskId, fileId, loaded) =>
|
||||
set((state) => {
|
||||
const task = state.tasks[taskId]
|
||||
if (!task) return {}
|
||||
|
||||
const file = task.files[fileId]
|
||||
if (!file) return {}
|
||||
|
||||
const updatedFile = { ...file, loaded }
|
||||
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||
|
||||
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||
|
||||
return {
|
||||
tasks: {
|
||||
...state.tasks,
|
||||
[taskId]: {
|
||||
...task,
|
||||
loaded: loadedBytes,
|
||||
files: updatedFiles,
|
||||
},
|
||||
},
|
||||
fileProgress: {
|
||||
...state.fileProgress,
|
||||
[fileId]: updatedFile,
|
||||
},
|
||||
}
|
||||
}),
|
||||
|
||||
completeFile: (taskId, fileId) =>
|
||||
set((state) => {
|
||||
const task = state.tasks[taskId]
|
||||
if (!task) return {}
|
||||
|
||||
const file = task.files[fileId]
|
||||
if (!file) return {}
|
||||
|
||||
const updatedFile: FileUploadState = { ...file, status: 'completed', loaded: file.total }
|
||||
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||
|
||||
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||
|
||||
return {
|
||||
tasks: {
|
||||
...state.tasks,
|
||||
[taskId]: {
|
||||
...task,
|
||||
loaded: loadedBytes,
|
||||
files: updatedFiles,
|
||||
},
|
||||
},
|
||||
fileProgress: {
|
||||
...state.fileProgress,
|
||||
[fileId]: updatedFile,
|
||||
},
|
||||
}
|
||||
}),
|
||||
|
||||
failFile: (taskId, fileId) =>
|
||||
set((state) => {
|
||||
const task = state.tasks[taskId]
|
||||
if (!task) return {}
|
||||
|
||||
const file = task.files[fileId]
|
||||
if (!file) return {}
|
||||
|
||||
const updatedFile: FileUploadState = { ...file, status: 'failed' }
|
||||
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||
|
||||
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||
|
||||
return {
|
||||
tasks: {
|
||||
...state.tasks,
|
||||
[taskId]: {
|
||||
...task,
|
||||
loaded: loadedBytes,
|
||||
files: updatedFiles,
|
||||
},
|
||||
},
|
||||
fileProgress: {
|
||||
...state.fileProgress,
|
||||
[fileId]: updatedFile,
|
||||
},
|
||||
}
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const APP_VERSION = '0.0.9'
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
+47
-12
@@ -1,5 +1,5 @@
|
||||
import tailwindPlugin from 'bun-plugin-tailwind'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
||||
import { cp, mkdir, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { temporalWorkflow } from '../packages/workflow-core/src/bun-temporal-plugin'
|
||||
@@ -34,20 +34,48 @@ const commonExternal = [
|
||||
'@temporalio/worker',
|
||||
'@temporalio/workflow',
|
||||
'prisma',
|
||||
'zod',
|
||||
]
|
||||
|
||||
// Extract exact dependency versions from workspace
|
||||
// Extract exact dependency versions from workspace package.json files
|
||||
console.log('🔍 Extracting exact dependency versions for runtime packages...')
|
||||
const lsOutput = Bun.spawnSync(['bun', 'pm', 'ls', '--all']).stdout.toString()
|
||||
const dependencyVersions: Record<string, string> = {}
|
||||
|
||||
// Find all workspace package.json files
|
||||
const packageJsonPaths = ['package.json']
|
||||
const workspaceDirs = ['packages', 'apps']
|
||||
for (const dir of workspaceDirs) {
|
||||
if (existsSync(dir)) {
|
||||
const subdirs = readdirSync(dir)
|
||||
for (const subdir of subdirs) {
|
||||
const p = path.join(dir, subdir, 'package.json')
|
||||
if (existsSync(p)) {
|
||||
packageJsonPaths.push(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const dep of commonExternal) {
|
||||
const escapedDep = dep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const regex = new RegExp(`(?:^|\\s)${escapedDep}@(\\d+\\.\\d+\\.\\d+[^\\s]*)`, 'g')
|
||||
const match = regex.exec(lsOutput)
|
||||
if (match && match[1]) {
|
||||
dependencyVersions[dep] = match[1]
|
||||
console.log(` ✅ Found ${dep}@${match[1]}`)
|
||||
let foundVersion: string | null = null
|
||||
for (const p of packageJsonPaths) {
|
||||
try {
|
||||
const content = readFileSync(p, 'utf8')
|
||||
const pkgJson = JSON.parse(content)
|
||||
const version = pkgJson.dependencies?.[dep] || pkgJson.devDependencies?.[dep]
|
||||
if (version) {
|
||||
// Strip any leading range specifiers like ^ or ~ to get the base version
|
||||
foundVersion = version.replace(/^[\^~]/, '')
|
||||
break
|
||||
}
|
||||
} catch {
|
||||
// ignore read/parse errors
|
||||
}
|
||||
}
|
||||
|
||||
if (foundVersion) {
|
||||
dependencyVersions[dep] = foundVersion
|
||||
console.log(` ✅ Found ${dep}@${foundVersion}`)
|
||||
} else {
|
||||
console.warn(` ⚠️ Warning: Could not find exact version for ${dep}`)
|
||||
}
|
||||
@@ -137,6 +165,7 @@ async function buildPlatformPackages(
|
||||
entrypoint: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
plugins: any[] = [],
|
||||
external?: string[],
|
||||
) {
|
||||
for (const target of targets) {
|
||||
const dirName = `${appName}-${target.platform}-${target.arch}`
|
||||
@@ -152,6 +181,7 @@ async function buildPlatformPackages(
|
||||
binaryName,
|
||||
bunTarget: target.bunTarget,
|
||||
plugins,
|
||||
external,
|
||||
})
|
||||
|
||||
// Generate package.json for platform-specific package
|
||||
@@ -181,6 +211,7 @@ async function buildMainPackage({
|
||||
entrypoint,
|
||||
plugins = [],
|
||||
extraDependencies = {},
|
||||
external = commonExternal,
|
||||
}: {
|
||||
appName: string
|
||||
description: string
|
||||
@@ -189,6 +220,7 @@ async function buildMainPackage({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
plugins?: any[]
|
||||
extraDependencies?: Record<string, string>
|
||||
external?: string[]
|
||||
}) {
|
||||
console.log(`\n📄 Packaging wrapper app ${appName}...`)
|
||||
const mainOutDir = path.join(distDir, appName)
|
||||
@@ -207,7 +239,7 @@ async function buildMainPackage({
|
||||
minify: true,
|
||||
naming: `${appName}-app.[ext]`,
|
||||
plugins,
|
||||
external: commonExternal,
|
||||
external,
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
@@ -345,7 +377,8 @@ console.log(\`ℹ️ [${appName}] Running from CWD: \${process.cwd()}\`)
|
||||
console.log(\`ℹ️ [${appName}] DATABASE_URL is: \${process.env.DATABASE_URL ? '(defined)' : '(undefined)'}\`)
|
||||
|
||||
const prismaSchemaPath = join(__dirname, '..', 'prisma', 'schema.prisma')
|
||||
if (existsSync(prismaSchemaPath)) {
|
||||
const isUtilityCommand = process.argv.includes('stop') || process.argv.includes('logs')
|
||||
if (existsSync(prismaSchemaPath) && !isUtilityCommand) {
|
||||
console.log('🔄 Running database migrations...')
|
||||
activeProcess = spawn(
|
||||
binaryPath,
|
||||
@@ -460,13 +493,15 @@ const shumaiPlugins = [
|
||||
}),
|
||||
tailwindPlugin,
|
||||
]
|
||||
await buildPlatformPackages('shumai', dummyRunnerPath)
|
||||
const shumaiExternal = commonExternal.filter((dep) => dep !== 'zod')
|
||||
await buildPlatformPackages('shumai', dummyRunnerPath, shumaiPlugins, shumaiExternal)
|
||||
await buildMainPackage({
|
||||
appName: 'shumai',
|
||||
description: 'A fullstack AI-powered media workspace and workflow engine',
|
||||
hasPrisma: true,
|
||||
entrypoint: './apps/web/src/index.ts',
|
||||
plugins: shumaiPlugins,
|
||||
external: shumaiExternal,
|
||||
})
|
||||
|
||||
// 3. Build shumai-agent (Agent app & platform binaries)
|
||||
|
||||
@@ -91,6 +91,12 @@ function updateVersions(newVersion: string) {
|
||||
writeFileSync(file, JSON.stringify(content, null, 2) + '\n', 'utf-8')
|
||||
console.log(` Updated version in ${file}`)
|
||||
}
|
||||
|
||||
const versionFile = 'packages/webui/version.ts'
|
||||
if (existsSync(versionFile)) {
|
||||
writeFileSync(versionFile, `export const APP_VERSION = '${newVersion}'\n`, 'utf-8')
|
||||
console.log(` Updated version in ${versionFile}`)
|
||||
}
|
||||
}
|
||||
|
||||
function shellQuote(value: string) {
|
||||
|
||||
Reference in New Issue
Block a user