Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3164e57e1f | ||
|
|
743f4ed5f9 | ||
|
|
1c04ace573 | ||
|
|
6cbff73687 | ||
|
|
dec8b10939 | ||
|
|
133a5278af | ||
|
|
da856274cc |
@@ -77,6 +77,17 @@ steps:
|
||||
limit: 2
|
||||
agents:
|
||||
queue: "default"
|
||||
- label: ":microscope: Preprocessing Tests"
|
||||
if: build.env("TEST_SCOPE") == "direct" && build.env("TEST_TYPE") == "preprocessing"
|
||||
command: "timeout 90m .buildkite/scripts/pr_test.sh"
|
||||
retry:
|
||||
automatic:
|
||||
- exit_status: 128
|
||||
limit: 3
|
||||
- exit_status: -1
|
||||
limit: 2
|
||||
agents:
|
||||
queue: "default"
|
||||
- label: ":microscope: DreamVerse App Tests"
|
||||
if: build.env("TEST_SCOPE") == "direct" && build.env("TEST_TYPE") == "dreamverse_app"
|
||||
command: "timeout 90m .buildkite/scripts/pr_test.sh"
|
||||
@@ -322,6 +333,29 @@ steps:
|
||||
- TEST_TYPE=unit_test
|
||||
agents:
|
||||
queue: "default"
|
||||
- path:
|
||||
- "fastvideo/pipelines/preprocess/**"
|
||||
- "fastvideo/workflow/preprocess/**"
|
||||
- "fastvideo/dataset/dataloader/parquet_io.py"
|
||||
- "fastvideo/dataset/dataloader/record_schema.py"
|
||||
- "fastvideo/dataset/dataloader/schema.py"
|
||||
- "fastvideo/configs/configs.py"
|
||||
- "fastvideo/fastvideo_args.py"
|
||||
- "fastvideo/tests/workflow/test_t2v_preprocessing_e2e.py"
|
||||
- "fastvideo/tests/nightly/reference_video_1_sample_v0.mp4"
|
||||
- "fastvideo/tests/modal/pr_test.py"
|
||||
- ".buildkite/pipeline.yml"
|
||||
- ".buildkite/scripts/pr_test.sh"
|
||||
- ".github/workflows/ci-slash-commands.yml"
|
||||
- "pyproject.toml"
|
||||
- "docker/Dockerfile"
|
||||
config:
|
||||
command: "timeout 20m .buildkite/scripts/pr_test.sh"
|
||||
label: ":microscope: Preprocessing Tests"
|
||||
env:
|
||||
- TEST_TYPE=preprocessing
|
||||
agents:
|
||||
queue: "default"
|
||||
- path:
|
||||
- "apps/dreamverse/**"
|
||||
- "pyproject.toml"
|
||||
|
||||
@@ -233,6 +233,10 @@ case "$TEST_TYPE" in
|
||||
log "Running unit tests..."
|
||||
MODAL_COMMAND="$MODAL_ENV python3 -m modal run $MODAL_TEST_FILE::run_unit_test"
|
||||
;;
|
||||
"preprocessing")
|
||||
log "Running preprocessing integration test..."
|
||||
MODAL_COMMAND="$MODAL_ENV HF_API_KEY=$HF_API_KEY python3 -m modal run $MODAL_TEST_FILE::run_preprocessing_tests"
|
||||
;;
|
||||
"dreamverse_app")
|
||||
log "Running DreamVerse app tests..."
|
||||
MODAL_COMMAND="$MODAL_ENV python3 -m modal run $MODAL_TEST_FILE::run_dreamverse_app_tests"
|
||||
|
||||
@@ -129,7 +129,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
TEST_NAME=$(echo "$COMMENT" | grep -oP '(?<=/test\s)\S+' | head -1 || true)
|
||||
|
||||
VALID="encoder vae transformer kernel unit dreamverse ssim training lora-inference lora-training lora-extraction distillation self-forcing vsa vmoba performance api train-framework eval full fastcheck pre-commit"
|
||||
VALID="encoder vae transformer kernel unit preprocessing dreamverse ssim training lora-inference lora-training lora-extraction distillation self-forcing vsa vmoba performance api train-framework eval full fastcheck pre-commit"
|
||||
if [ -z "$TEST_NAME" ] || ! echo "$VALID" | grep -qw "$TEST_NAME"; then
|
||||
echo "Unknown test: '$TEST_NAME'. Valid: $VALID"
|
||||
exit 1
|
||||
@@ -137,7 +137,8 @@ jobs:
|
||||
|
||||
declare -A MAP=(
|
||||
[encoder]=encoder [vae]=vae [transformer]=transformer
|
||||
[kernel]=kernel_tests [unit]=unit_test [dreamverse]=dreamverse_app
|
||||
[kernel]=kernel_tests [unit]=unit_test [preprocessing]=preprocessing
|
||||
[dreamverse]=dreamverse_app
|
||||
[ssim]=ssim [training]=training
|
||||
[lora-inference]=inference_lora [lora-training]=training_lora
|
||||
[lora-extraction]=lora_extraction
|
||||
|
||||
@@ -11,7 +11,9 @@ on:
|
||||
- 'requirements-mkdocs.txt'
|
||||
- 'scripts/check_docs_links.py'
|
||||
- '.github/workflows/infra-docs.yml'
|
||||
pull_request:
|
||||
# Run the trusted base-branch workflow so fork PRs can be skipped without
|
||||
# waiting for maintainer approval.
|
||||
pull_request_target:
|
||||
branches: [ main ]
|
||||
paths:
|
||||
- 'docs/**'
|
||||
@@ -24,21 +26,19 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# MkDocs executes repository code; only trusted same-repository PRs run it.
|
||||
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
@@ -52,6 +52,7 @@ jobs:
|
||||
run: uv pip install --system -r requirements-mkdocs.txt
|
||||
|
||||
- name: Setup Pages
|
||||
if: github.event_name == 'push'
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
- name: Build documentation
|
||||
@@ -61,17 +62,22 @@ jobs:
|
||||
run: python scripts/check_docs_links.py
|
||||
|
||||
- name: Upload artifact
|
||||
if: github.event_name == 'push'
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: ./site
|
||||
|
||||
deploy:
|
||||
permissions:
|
||||
pages: write
|
||||
id-token: write
|
||||
concurrency: pages
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: github.ref == 'refs/heads/main'
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
|
||||
@@ -1 +1 @@
|
||||
PUBLIC_API_BASE_URL=http://localhost:8189/api
|
||||
NEXT_PUBLIC_API_BASE_URL=http://localhost:8189/api
|
||||
@@ -13,6 +13,12 @@
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# playwright
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
/.playwright/
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
@@ -39,4 +45,3 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
.svelte-kit
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"tabWidth": 4
|
||||
}
|
||||
@@ -11,19 +11,63 @@ The UI currently supports:
|
||||
- Datasets
|
||||
- Gallery View
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
apps/fastvideo_studio/
|
||||
├── server.py / job_runner.py / database.py # FastAPI backend + job lifecycle
|
||||
├── mock_server.py # In-memory API mock for e2e tests
|
||||
├── models/ # Pydantic request models (shared with the mock)
|
||||
├── training_config.py # Studio workloads → fastvideo/train YAML configs
|
||||
├── tests/ # Backend unit tests (pytest)
|
||||
├── e2e/ # Playwright specs (run against the mock)
|
||||
└── src/
|
||||
├── app/ # Next.js App Router pages (thin routes)
|
||||
├── components/
|
||||
│ ├── shell/ # App chrome: header, sidebars, layout
|
||||
│ ├── jobs/ # Job queue, cards, create-job modal, log sidebar
|
||||
│ ├── datasets/ # Dataset cards, upload, captions
|
||||
│ └── ui/ # shadcn-style primitives (shared theme)
|
||||
├── stores/ # Framework-agnostic state + React bridge (hooks/)
|
||||
├── lib/ # API client, types, option persistence
|
||||
└── test/ # Vitest setup + factories
|
||||
```
|
||||
|
||||
The visual theme (slate light/dark palettes, IBM Plex type, `#356cff` accent)
|
||||
is shared with `apps/dreamverse`; the toggle in the header persists the choice
|
||||
per browser.
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
npm run typecheck # tsc
|
||||
npm test # vitest unit tests
|
||||
npm run e2e # Playwright against the in-memory mock backend
|
||||
python -m pytest tests/ # backend unit tests (from apps/fastvideo_studio)
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
The easiest way to run the application is:
|
||||
For local development, install dependencies and start the Next.js dev server:
|
||||
|
||||
```bash
|
||||
cd apps/fastvideo_studio
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
You can then access the app at [http://localhost:3000](http://localhost:3000).
|
||||
Start the Python API server (default port 8189) in a separate terminal — see below.
|
||||
|
||||
For a production build of the web app together with the API server:
|
||||
|
||||
```bash
|
||||
cd apps/fastvideo_studio
|
||||
npm install
|
||||
npm run build
|
||||
npm run start
|
||||
npm run start:all
|
||||
```
|
||||
|
||||
You can then access the app at [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
### Running API and Web Separately
|
||||
|
||||
The UI is composed of two separate components:
|
||||
@@ -31,7 +75,7 @@ The UI is composed of two separate components:
|
||||
- API Server
|
||||
- Web Server
|
||||
|
||||
To run each component separately, you can use the commands `npm run start:web` and `npm run start:api`.
|
||||
To run each component separately, you can use the commands `npm run start:web` (after `npm run build`) and `npm run start:api`.
|
||||
|
||||
You can also run the API server with this command from the `apps/` directory:
|
||||
|
||||
|
||||
@@ -251,11 +251,10 @@ class Database:
|
||||
sp_size, negative_prompt,
|
||||
data_path, max_train_steps, train_batch_size, learning_rate,
|
||||
num_latent_t, validation_dataset_file, lora_rank,
|
||||
ltx2_first_frame_conditioning_p,
|
||||
dmd_use_vsa, dmd_vsa_sparsity, dmd_denoising_steps,
|
||||
min_timestep_ratio, max_timestep_ratio, real_score_guidance_scale,
|
||||
real_score_guidance_scale,
|
||||
generator_update_interval, real_score_model_path, fake_score_model_path
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
job["id"],
|
||||
@@ -297,12 +296,9 @@ class Database:
|
||||
job.get("num_latent_t", 20),
|
||||
job.get("validation_dataset_file", ""),
|
||||
job.get("lora_rank", 32),
|
||||
job.get("ltx2_first_frame_conditioning_p"),
|
||||
1 if job.get("dmd_use_vsa") else 0,
|
||||
job.get("dmd_vsa_sparsity", 0.8),
|
||||
job.get("dmd_denoising_steps", "1000,757,522"),
|
||||
job.get("min_timestep_ratio", 0.02),
|
||||
job.get("max_timestep_ratio", 0.98),
|
||||
job.get("real_score_guidance_scale", 3.5),
|
||||
job.get("generator_update_interval", 5),
|
||||
job.get("real_score_model_path", ""),
|
||||
@@ -401,24 +397,6 @@ class Database:
|
||||
for file_name, caption in captions.items():
|
||||
self.upsert_dataset_caption(dataset_id, file_name, caption)
|
||||
|
||||
def update_dataset(self, dataset_id: str, updates: dict[str, Any]) -> None:
|
||||
"""Update dataset fields. Only provided keys are updated."""
|
||||
if not updates:
|
||||
return
|
||||
allowed: set[str] = set()
|
||||
cols = []
|
||||
vals = []
|
||||
for k, v in updates.items():
|
||||
if k in allowed:
|
||||
cols.append(f"{k} = ?")
|
||||
vals.append(v)
|
||||
if not cols:
|
||||
return
|
||||
vals.append(dataset_id)
|
||||
sql = f"UPDATE datasets SET {', '.join(cols)} WHERE id = ?"
|
||||
self._execute(sql, tuple(vals))
|
||||
self._commit()
|
||||
|
||||
def delete_dataset(self, dataset_id: str) -> bool:
|
||||
"""Delete a dataset. Returns True if a row was deleted."""
|
||||
cur = self._execute("DELETE FROM datasets WHERE id = ?", (dataset_id, ))
|
||||
@@ -443,7 +421,7 @@ class Database:
|
||||
cur = self._execute("SELECT * FROM settings WHERE id = 1")
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return _default_settings_dict()
|
||||
return default_settings_dict()
|
||||
t2v = ((row["default_model_id_t2v"] or row["default_model_id"] or "") if "default_model_id_t2v" in row else
|
||||
(row["default_model_id"] or ""))
|
||||
i2v = ((row["default_model_id_i2v"] or "") if "default_model_id_i2v" in row else "")
|
||||
@@ -557,8 +535,6 @@ def _row_to_job(row: sqlite3.Row) -> dict[str, Any]:
|
||||
}
|
||||
float_defaults = {
|
||||
"dmd_vsa_sparsity": 0.8,
|
||||
"min_timestep_ratio": 0.02,
|
||||
"max_timestep_ratio": 0.98,
|
||||
"real_score_guidance_scale": 3.5,
|
||||
}
|
||||
result = {
|
||||
@@ -625,7 +601,7 @@ def _row_to_job(row: sqlite3.Row) -> dict[str, Any]:
|
||||
return result
|
||||
|
||||
|
||||
def _default_settings_dict() -> dict[str, Any]:
|
||||
def default_settings_dict() -> dict[str, Any]:
|
||||
"""Return default settings as API-style dict."""
|
||||
return {
|
||||
"defaultModelId": DEFAULT_SETTINGS["default_model_id"],
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { skipWithoutMock } from './helpers';
|
||||
|
||||
/**
|
||||
* Create-job flow: open the Create Job modal on /inference, fill the prompt
|
||||
* (the model auto-selects once the mock's /api/models loads), submit, and
|
||||
* confirm the new job lands in the queue.
|
||||
*/
|
||||
test.describe('create inference job', () => {
|
||||
skipWithoutMock();
|
||||
|
||||
test('creates a T2V job and shows it in the queue', async ({ page }) => {
|
||||
await page.goto('/inference');
|
||||
|
||||
// The "Create Job" button reveals a workload menu on hover; wait for the
|
||||
// T2V item to become visible before clicking so the CSS hover transition
|
||||
// can't race the click.
|
||||
await page.getByRole('button', { name: /create job/i }).hover();
|
||||
const t2vItem = page.getByRole('menuitem', { name: /T2V/i });
|
||||
await expect(t2vItem).toBeVisible();
|
||||
await t2vItem.click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
// Wait for the mock's model catalogue to populate the dropdown (more than
|
||||
// just the disabled placeholder), then pick one explicitly — the app's
|
||||
// auto-selection is racy.
|
||||
const modelSelect = dialog.getByLabel('Model', { exact: true });
|
||||
await expect(modelSelect.locator('option')).not.toHaveCount(1);
|
||||
await modelSelect.selectOption({ index: 1 });
|
||||
|
||||
const prompt = `e2e raccoon in sunflowers ${Date.now()}`;
|
||||
await dialog.getByLabel('Prompt', { exact: true }).fill(prompt);
|
||||
|
||||
await dialog.getByRole('button', { name: 'Create Job' }).click();
|
||||
|
||||
// Modal closes and the queue refreshes with the newly created job.
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(page.getByText(prompt)).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { API_BASE, skipWithoutMock } from './helpers';
|
||||
|
||||
/**
|
||||
* Datasets page: the seeded datasets render as cards, and the Create Dataset
|
||||
* modal opens from the header action.
|
||||
*/
|
||||
test.describe('datasets', () => {
|
||||
skipWithoutMock();
|
||||
|
||||
test('lists the seeded datasets', async ({ page, request }) => {
|
||||
// Read the seeded names from the mock so the assertion tracks the fixture.
|
||||
const res = await request.get(`${API_BASE}/datasets`);
|
||||
const datasets = (await res.json()) as Array<{ name: string }>;
|
||||
expect(datasets.length).toBeGreaterThan(0);
|
||||
|
||||
await page.goto('/datasets');
|
||||
|
||||
for (const ds of datasets) {
|
||||
await expect(page.getByText(ds.name, { exact: true })).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test('opens the Create Dataset modal', async ({ page }) => {
|
||||
await page.goto('/datasets');
|
||||
|
||||
await page.getByRole('button', { name: 'Add Dataset' }).click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(
|
||||
dialog.getByRole('heading', { name: /Add Dataset/i }),
|
||||
).toBeVisible();
|
||||
await expect(dialog.getByLabel('Name', { exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { API_BASE, skipWithoutMock } from './helpers';
|
||||
|
||||
/**
|
||||
* Gallery page: the seeded completed inference job surfaces as a media tile
|
||||
* (an <article> wrapping a <video>) captioned with its prompt.
|
||||
*/
|
||||
test.describe('gallery', () => {
|
||||
skipWithoutMock();
|
||||
|
||||
test('shows a media tile for the seeded completed job', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
const res = await request.get(`${API_BASE}/jobs?job_type=inference`);
|
||||
const jobs = (await res.json()) as Array<{
|
||||
status: string;
|
||||
output_path: string | null;
|
||||
prompt: string;
|
||||
}>;
|
||||
const completed = jobs.find(
|
||||
(j) => j.status === 'completed' && j.output_path,
|
||||
);
|
||||
expect(completed, 'mock should seed a completed inference job').toBeTruthy();
|
||||
|
||||
await page.goto('/gallery');
|
||||
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: 'Gallery' }),
|
||||
).toBeVisible();
|
||||
|
||||
// The completed job renders as an <article> containing a <video> tile.
|
||||
const tile = page
|
||||
.locator('article')
|
||||
.filter({ has: page.locator('video') });
|
||||
await expect(tile.first()).toBeVisible();
|
||||
|
||||
await expect(page.getByText(completed!.prompt)).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { skipWithoutMock } from './helpers';
|
||||
|
||||
/**
|
||||
* GPU status page: the mock's fake GPUs render as cards with meters, and the
|
||||
* page is reachable from the primary sidebar.
|
||||
*/
|
||||
test.describe('gpus', () => {
|
||||
skipWithoutMock();
|
||||
|
||||
test('lists the mock GPUs with utilization meters', async ({ page }) => {
|
||||
await page.goto('/gpus');
|
||||
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: 'GPUs' }),
|
||||
).toBeVisible();
|
||||
|
||||
await expect(page.getByText('GPU 0')).toBeVisible();
|
||||
await expect(page.getByText('GPU 1')).toBeVisible();
|
||||
expect(await page.getByRole('meter').count()).toBe(4);
|
||||
});
|
||||
|
||||
test('is reachable from the sidebar', async ({ page }) => {
|
||||
await page.goto('/inference');
|
||||
await page.getByRole('link', { name: 'GPUs' }).click();
|
||||
await expect(page).toHaveURL(/\/gpus$/);
|
||||
await expect(page.getByText('GPU 0')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { test, type APIRequestContext } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Port and base URL of the mock API — the single source of truth shared by
|
||||
* playwright.config.ts (which boots the mock and points `npm run dev` at it
|
||||
* via NEXT_PUBLIC_API_BASE_URL) and the specs (which probe/read mock state
|
||||
* directly through the Playwright `request` fixture).
|
||||
*
|
||||
* The default port is deliberately NOT the real server's default (8189): the
|
||||
* e2e specs create and (if autostart is on) launch jobs, so running them
|
||||
* against a real backend would mutate the developer's database and fire real
|
||||
* GPU runs. API_BASE is derived solely from MOCK_API_PORT (it does not inherit
|
||||
* NEXT_PUBLIC_API_BASE_URL) so the specs always talk to the mock.
|
||||
*/
|
||||
export const MOCK_API_PORT = process.env.MOCK_API_PORT || '8190';
|
||||
|
||||
export const API_BASE = `http://127.0.0.1:${MOCK_API_PORT}/api`;
|
||||
|
||||
export const MOCK_SKIP_MESSAGE =
|
||||
`Mock backend not reachable at ${API_BASE}/__mock__ ` +
|
||||
`(start fastvideo_studio.mock_server on port ${MOCK_API_PORT}).`;
|
||||
|
||||
/**
|
||||
* True only when the mock server answers on the configured port. Probes the
|
||||
* mock-only /api/__mock__ sentinel (which the real server does not serve) so
|
||||
* the suite refuses to run its mutating specs against a real backend.
|
||||
*/
|
||||
export async function mockIsUp(request: APIRequestContext): Promise<boolean> {
|
||||
try {
|
||||
const res = await request.get(`${API_BASE}/__mock__`);
|
||||
if (!res.ok()) return false;
|
||||
const body = await res.json();
|
||||
return body?.mock === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Self-skip every test in the enclosing describe when the mock is down. */
|
||||
export function skipWithoutMock(): void {
|
||||
test.beforeEach(async ({ request }) => {
|
||||
test.skip(!(await mockIsUp(request)), MOCK_SKIP_MESSAGE);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
import { skipWithoutMock } from './helpers';
|
||||
|
||||
/**
|
||||
* App-shell smoke: the Next.js frontend hydrates, renders the FastVideo logo
|
||||
* and the primary-sidebar navigation, and routing between the top-level
|
||||
* sections works. Each spec self-skips when the mock backend isn't reachable.
|
||||
*/
|
||||
test.describe('app shell', () => {
|
||||
skipWithoutMock();
|
||||
|
||||
test('loads with the logo and primary-sidebar nav', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
// The root route redirects to /inference.
|
||||
await expect(page).toHaveURL(/\/inference$/);
|
||||
|
||||
await expect(page.getByRole('img', { name: /fastvideo/i })).toBeVisible();
|
||||
|
||||
for (const label of ['Inference', 'Datasets', 'Gallery', 'Settings']) {
|
||||
await expect(page.getByRole('link', { name: label })).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test('navigates between the primary sections', async ({ page }) => {
|
||||
await page.goto('/inference');
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: 'Jobs' }),
|
||||
).toBeVisible();
|
||||
|
||||
const sections: Array<{ link: string; url: RegExp; title: string }> = [
|
||||
{ link: 'Datasets', url: /\/datasets$/, title: 'Datasets' },
|
||||
{ link: 'Gallery', url: /\/gallery$/, title: 'Gallery' },
|
||||
{ link: 'Settings', url: /\/settings$/, title: 'Settings' },
|
||||
{ link: 'Inference', url: /\/inference$/, title: 'Jobs' },
|
||||
];
|
||||
|
||||
for (const section of sections) {
|
||||
await page.getByRole('link', { name: section.link }).click();
|
||||
await expect(page).toHaveURL(section.url);
|
||||
// The header <h1> is the only level-1 heading and reflects the route.
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: section.title }),
|
||||
).toBeVisible();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
// Minimal ESLint config for SvelteKit (add typescript-eslint / eslint-plugin-svelte as needed)
|
||||
export default [];
|
||||
@@ -0,0 +1,74 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""GPU telemetry for the studio status page, via NVML (nvidia-ml-py)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("fastvideo.studio.gpu")
|
||||
|
||||
_nvml_initialized = False
|
||||
|
||||
|
||||
def _ensure_nvml() -> Any:
|
||||
"""Import and initialize NVML once; raises on machines without it."""
|
||||
global _nvml_initialized # noqa: PLW0603
|
||||
import pynvml
|
||||
if not _nvml_initialized:
|
||||
pynvml.nvmlInit()
|
||||
_nvml_initialized = True
|
||||
return pynvml
|
||||
|
||||
|
||||
def _device_snapshot(pynvml: Any, index: int) -> dict[str, Any]:
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(index)
|
||||
name = pynvml.nvmlDeviceGetName(handle)
|
||||
if isinstance(name, bytes):
|
||||
name = name.decode()
|
||||
mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
|
||||
util = pynvml.nvmlDeviceGetUtilizationRates(handle)
|
||||
|
||||
# Optional sensors: not every GPU/driver exposes them.
|
||||
temperature: int | None = None
|
||||
power_watts: float | None = None
|
||||
power_limit_watts: float | None = None
|
||||
with contextlib.suppress(pynvml.NVMLError):
|
||||
temperature = int(pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU))
|
||||
with contextlib.suppress(pynvml.NVMLError):
|
||||
power_watts = pynvml.nvmlDeviceGetPowerUsage(handle) / 1000.0
|
||||
power_limit_watts = (pynvml.nvmlDeviceGetEnforcedPowerLimit(handle) / 1000.0)
|
||||
|
||||
return {
|
||||
"index": index,
|
||||
"name": name,
|
||||
"utilization": int(util.gpu),
|
||||
"memory_used_mib": int(mem.used / (1024 * 1024)),
|
||||
"memory_total_mib": int(mem.total / (1024 * 1024)),
|
||||
"temperature_c": temperature,
|
||||
"power_watts": power_watts,
|
||||
"power_limit_watts": power_limit_watts,
|
||||
}
|
||||
|
||||
|
||||
def get_gpu_snapshot() -> dict[str, Any]:
|
||||
"""Return {"available", "gpus", "error"} — never raises.
|
||||
|
||||
``available: False`` covers both "no NVIDIA driver/library on this host"
|
||||
and transient NVML failures; the frontend shows ``error`` as-is.
|
||||
"""
|
||||
try:
|
||||
pynvml = _ensure_nvml()
|
||||
count = pynvml.nvmlDeviceGetCount()
|
||||
gpus = [_device_snapshot(pynvml, i) for i in range(count)]
|
||||
return {"available": True, "gpus": gpus, "error": None}
|
||||
except ImportError:
|
||||
return {
|
||||
"available": False,
|
||||
"gpus": [],
|
||||
"error": "nvidia-ml-py is not installed on the API server host.",
|
||||
}
|
||||
except Exception as exc: # NVMLError, driver issues, …
|
||||
logger.warning("GPU snapshot failed: %s", exc)
|
||||
return {"available": False, "gpus": [], "error": str(exc)}
|
||||
@@ -23,12 +23,13 @@ import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import yaml
|
||||
|
||||
from fastvideo.utils import get_mp_context
|
||||
from fastvideo_studio.database import Database
|
||||
from fastvideo_studio.training_config import (
|
||||
build_training_args,
|
||||
build_training_config,
|
||||
get_training_env,
|
||||
get_training_module_info,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("fastvideo.studio.job_runner")
|
||||
@@ -160,13 +161,10 @@ class Job:
|
||||
num_latent_t: int = 20
|
||||
validation_dataset_file: str = ""
|
||||
lora_rank: int = 32
|
||||
ltx2_first_frame_conditioning_p: float | None = None
|
||||
# DMD options
|
||||
dmd_use_vsa: bool = False
|
||||
dmd_vsa_sparsity: float = 0.8
|
||||
dmd_denoising_steps: str = "1000,757,522"
|
||||
min_timestep_ratio: float = 0.02
|
||||
max_timestep_ratio: float = 0.98
|
||||
real_score_guidance_scale: float = 3.5
|
||||
generator_update_interval: int = 5
|
||||
real_score_model_path: str = ""
|
||||
@@ -221,12 +219,9 @@ class Job:
|
||||
"num_width": self.width,
|
||||
"validation_dataset_file": self.validation_dataset_file,
|
||||
"lora_rank": self.lora_rank,
|
||||
"ltx2_first_frame_conditioning_p": self.ltx2_first_frame_conditioning_p,
|
||||
"dmd_use_vsa": self.dmd_use_vsa,
|
||||
"dmd_vsa_sparsity": self.dmd_vsa_sparsity,
|
||||
"dmd_denoising_steps": self.dmd_denoising_steps,
|
||||
"min_timestep_ratio": self.min_timestep_ratio,
|
||||
"max_timestep_ratio": self.max_timestep_ratio,
|
||||
"real_score_guidance_scale": self.real_score_guidance_scale,
|
||||
"generator_update_interval": self.generator_update_interval,
|
||||
"real_score_model_path": self.real_score_model_path or "",
|
||||
@@ -330,12 +325,9 @@ class JobRunner:
|
||||
num_latent_t=row.get("num_latent_t", 20),
|
||||
validation_dataset_file=row.get("validation_dataset_file", "") or "",
|
||||
lora_rank=row.get("lora_rank", 32),
|
||||
ltx2_first_frame_conditioning_p=row.get("ltx2_first_frame_conditioning_p"),
|
||||
dmd_use_vsa=row.get("dmd_use_vsa", False),
|
||||
dmd_vsa_sparsity=float(row.get("dmd_vsa_sparsity", 0.8)),
|
||||
dmd_denoising_steps=row.get("dmd_denoising_steps", "1000,757,522") or "1000,757,522",
|
||||
min_timestep_ratio=float(row.get("min_timestep_ratio", 0.02)),
|
||||
max_timestep_ratio=float(row.get("max_timestep_ratio", 0.98)),
|
||||
real_score_guidance_scale=float(row.get("real_score_guidance_scale", 3.5)),
|
||||
generator_update_interval=int(row.get("generator_update_interval", 5)),
|
||||
real_score_model_path=row.get("real_score_model_path", "") or "",
|
||||
@@ -412,12 +404,9 @@ class JobRunner:
|
||||
num_latent_t: int = 20,
|
||||
validation_dataset_file: str = "",
|
||||
lora_rank: int = 32,
|
||||
ltx2_first_frame_conditioning_p: float | None = None,
|
||||
dmd_use_vsa: bool = False,
|
||||
dmd_vsa_sparsity: float = 0.8,
|
||||
dmd_denoising_steps: str = "1000,757,522",
|
||||
min_timestep_ratio: float = 0.02,
|
||||
max_timestep_ratio: float = 0.98,
|
||||
real_score_guidance_scale: float = 3.5,
|
||||
generator_update_interval: int = 5,
|
||||
real_score_model_path: str = "",
|
||||
@@ -457,12 +446,9 @@ class JobRunner:
|
||||
num_latent_t=num_latent_t,
|
||||
validation_dataset_file=validation_dataset_file or "",
|
||||
lora_rank=lora_rank,
|
||||
ltx2_first_frame_conditioning_p=ltx2_first_frame_conditioning_p,
|
||||
dmd_use_vsa=dmd_use_vsa,
|
||||
dmd_vsa_sparsity=dmd_vsa_sparsity,
|
||||
dmd_denoising_steps=dmd_denoising_steps,
|
||||
min_timestep_ratio=min_timestep_ratio,
|
||||
max_timestep_ratio=max_timestep_ratio,
|
||||
real_score_guidance_scale=real_score_guidance_scale,
|
||||
generator_update_interval=generator_update_interval,
|
||||
real_score_model_path=real_score_model_path or "",
|
||||
@@ -733,46 +719,23 @@ class JobRunner:
|
||||
self._save_job(job)
|
||||
return
|
||||
|
||||
module_info = get_training_module_info(job.workload_type, job.model_id)
|
||||
if not module_info:
|
||||
env = os.environ.copy()
|
||||
env.update(get_training_env())
|
||||
|
||||
try:
|
||||
# Job.to_dict() carries every key the config builder reads
|
||||
# (extra keys are ignored by its .get() lookups).
|
||||
train_config = build_training_config(job.to_dict(), job_output_dir)
|
||||
except ValueError as exc:
|
||||
job.status = JobStatus.FAILED
|
||||
job.error = f"Unknown workload type: {job.workload_type}"
|
||||
job.error = str(exc)
|
||||
job.finished_at = time.time()
|
||||
self._save_job(job)
|
||||
return
|
||||
|
||||
module_path, _pipeline_workload, use_vsa, _is_lora = module_info
|
||||
dmd_use_vsa = (job.workload_type.startswith("dmd_") and getattr(job, "dmd_use_vsa", False))
|
||||
env = os.environ.copy()
|
||||
env.update(get_training_env(use_vsa or dmd_use_vsa))
|
||||
|
||||
job_dict = {
|
||||
"model_id": job.model_id,
|
||||
"data_path": job.data_path,
|
||||
"workload_type": job.workload_type,
|
||||
"num_gpus": job.num_gpus,
|
||||
"max_train_steps": job.max_train_steps,
|
||||
"train_batch_size": job.train_batch_size,
|
||||
"learning_rate": job.learning_rate,
|
||||
"num_latent_t": job.num_latent_t,
|
||||
"num_height": job.height,
|
||||
"num_width": job.width,
|
||||
"num_frames": job.num_frames,
|
||||
"validation_dataset_file": job.validation_dataset_file,
|
||||
"lora_rank": job.lora_rank,
|
||||
"ltx2_first_frame_conditioning_p": job.ltx2_first_frame_conditioning_p,
|
||||
}
|
||||
if job.workload_type.startswith("dmd_") or job.workload_type.startswith("self_forcing_"):
|
||||
job_dict["dmd_use_vsa"] = getattr(job, "dmd_use_vsa", False)
|
||||
job_dict["dmd_vsa_sparsity"] = getattr(job, "dmd_vsa_sparsity", 0.8)
|
||||
job_dict["dmd_denoising_steps"] = getattr(job, "dmd_denoising_steps", "1000,757,522")
|
||||
job_dict["min_timestep_ratio"] = getattr(job, "min_timestep_ratio", 0.02)
|
||||
job_dict["max_timestep_ratio"] = getattr(job, "max_timestep_ratio", 0.98)
|
||||
job_dict["real_score_guidance_scale"] = getattr(job, "real_score_guidance_scale", 3.5)
|
||||
job_dict["generator_update_interval"] = getattr(job, "generator_update_interval", 5)
|
||||
job_dict["real_score_model_path"] = (getattr(job, "real_score_model_path", "") or job.model_id)
|
||||
job_dict["fake_score_model_path"] = (getattr(job, "fake_score_model_path", "") or job.model_id)
|
||||
train_args = build_training_args(job_dict, job_output_dir)
|
||||
config_path = os.path.join(job_output_dir, "train_config.yaml")
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(train_config, f, sort_keys=False)
|
||||
|
||||
repo_root = Path(__file__).resolve().parent.parent
|
||||
torchrun_cmd = [
|
||||
@@ -783,9 +746,12 @@ class JobRunner:
|
||||
str(job.num_gpus),
|
||||
"--nnodes",
|
||||
"1",
|
||||
str(repo_root / module_path),
|
||||
] + train_args
|
||||
buf.write(f"Starting training: {' '.join(torchrun_cmd[:12])}...")
|
||||
"-m",
|
||||
"fastvideo.train.entrypoint.train",
|
||||
"--config",
|
||||
config_path,
|
||||
]
|
||||
buf.write(f"Starting training: {' '.join(torchrun_cmd)}")
|
||||
buf.phase = "starting"
|
||||
|
||||
try:
|
||||
@@ -825,12 +791,21 @@ class JobRunner:
|
||||
job._process.wait()
|
||||
exit_code = job._process.returncode or 0
|
||||
|
||||
if exit_code == 0:
|
||||
if job._stop_event.is_set():
|
||||
# Terminated by stop_job() without the reader loop observing the
|
||||
# flag (e.g. the process died between log lines).
|
||||
job.status = JobStatus.STOPPED
|
||||
buf.phase = "stopped"
|
||||
elif exit_code == 0:
|
||||
job.status = JobStatus.COMPLETED
|
||||
buf.progress = 100.0
|
||||
buf.phase = "done"
|
||||
# Training outputs checkpoints, not video
|
||||
ckpt_dirs = sorted(Path(job_output_dir).glob("checkpoint-*"))
|
||||
# Training outputs checkpoints, not video. Sort by step number,
|
||||
# not lexically ("checkpoint-1000" < "checkpoint-500" as strings).
|
||||
ckpt_dirs = sorted(
|
||||
Path(job_output_dir).glob("checkpoint-*"),
|
||||
key=lambda p: int(m.group(1)) if (m := re.fullmatch(r"checkpoint-(\d+)", p.name)) else -1,
|
||||
)
|
||||
if ckpt_dirs:
|
||||
job.output_path = str(ckpt_dirs[-1])
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""
|
||||
In-memory mock of the FastVideo Studio API (``server.py``).
|
||||
|
||||
This mock implements the same ``/api`` routes and response shapes as the real
|
||||
FastAPI server but keeps everything in memory and never touches the FastVideo
|
||||
library, a GPU, or a database. It is meant to back the Playwright e2e suite so
|
||||
the Next.js frontend can be exercised end-to-end without a real backend.
|
||||
|
||||
Job lifecycle is simulated by recording a start timestamp and *computing* the
|
||||
status on read: a started job reports ``running`` for a few seconds and then
|
||||
flips to ``completed`` with an ``output_path``, so polling the job list / logs
|
||||
shows progression. Generated media is a tiny 1s ``testsrc`` MP4 built lazily
|
||||
with ffmpeg and cached.
|
||||
|
||||
Usage (from the ``apps/`` directory)::
|
||||
|
||||
PYTHONPATH=.. python -m fastvideo_studio.mock_server --port 8190
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import FastAPI, File, HTTPException, UploadFile
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, PlainTextResponse
|
||||
|
||||
from fastvideo_studio.database import default_settings_dict
|
||||
from fastvideo_studio.models import (CreateDatasetRequest, CreateJobRequest, SettingsUpdate, UpdateCaptionRequest,
|
||||
model_label)
|
||||
|
||||
# --- Config -----------------------------------------------------------------
|
||||
|
||||
# How long a started job stays "running" before it flips to "completed".
|
||||
COMPLETE_AFTER_SECONDS = 3.0
|
||||
FFMPEG_BIN = shutil.which(os.getenv("FASTVIDEO_FFMPEG_BIN", "ffmpeg"))
|
||||
|
||||
# A small catalogue of fake models keyed by workload type. Mirrors the real
|
||||
# server's {id, label} shape (label derived from the HF-style path).
|
||||
_MODELS_BY_WORKLOAD: dict[str, list[str]] = {
|
||||
"t2v": [
|
||||
"Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
"FastVideo/FastHunyuan-diffusers",
|
||||
],
|
||||
"i2v": [
|
||||
"Wan-AI/Wan2.1-I2V-14B-480P-Diffusers",
|
||||
],
|
||||
"t2i": [
|
||||
"black-forest-labs/FLUX.1-schnell",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _models_for(workload_type: str | None) -> list[dict[str, str]]:
|
||||
if workload_type:
|
||||
paths = _MODELS_BY_WORKLOAD.get(workload_type, [])
|
||||
else:
|
||||
seen: dict[str, None] = {}
|
||||
for paths_for_workload in _MODELS_BY_WORKLOAD.values():
|
||||
for path in paths_for_workload:
|
||||
seen.setdefault(path, None)
|
||||
paths = list(seen)
|
||||
return [{"id": path, "label": model_label(path)} for path in paths]
|
||||
|
||||
|
||||
# The real settings catalogue lives in database.py; the mock only pre-fills
|
||||
# the default model ids so the Create Job modal auto-selects one.
|
||||
_DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
**default_settings_dict(),
|
||||
"defaultModelId": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
"defaultModelIdT2v": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
"defaultModelIdI2v": "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers",
|
||||
"defaultModelIdT2i": "black-forest-labs/FLUX.1-schnell",
|
||||
}
|
||||
|
||||
# --- In-memory state --------------------------------------------------------
|
||||
|
||||
_state_lock = threading.Lock()
|
||||
_settings: dict[str, Any] = dict(_DEFAULT_SETTINGS)
|
||||
_jobs: dict[str, dict[str, Any]] = {}
|
||||
_datasets: dict[str, dict[str, Any]] = {}
|
||||
# dataset_id -> {"file_names": [...], "captions": {file_name: caption}}
|
||||
_dataset_files: dict[str, dict[str, Any]] = {}
|
||||
|
||||
# Lazily-built, cached media clips (shared by every job/dataset media response),
|
||||
# keyed by extension: "mp4" (1s testsrc video) or "png" (single testsrc frame).
|
||||
_mock_media_cache: dict[str, str] = {}
|
||||
_mock_media_lock = threading.Lock()
|
||||
|
||||
|
||||
def _build_mock_media(kind: str) -> str:
|
||||
"""Build (once) a tiny testsrc clip of the given ``kind`` with ffmpeg; cache the path."""
|
||||
with _mock_media_lock:
|
||||
cached = _mock_media_cache.get(kind)
|
||||
if cached and os.path.isfile(cached):
|
||||
return cached
|
||||
if not FFMPEG_BIN:
|
||||
raise HTTPException(status_code=500, detail="ffmpeg is required to build mock media")
|
||||
fd, path = tempfile.mkstemp(prefix="fvstudio_mock_", suffix=f".{kind}")
|
||||
os.close(fd)
|
||||
if kind == "png":
|
||||
command = [
|
||||
FFMPEG_BIN,
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"testsrc=size=320x240:rate=1",
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-f",
|
||||
"image2",
|
||||
path,
|
||||
]
|
||||
else:
|
||||
command = [
|
||||
FFMPEG_BIN,
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"testsrc=size=320x240:rate=24",
|
||||
"-t",
|
||||
"1",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"ultrafast",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-f",
|
||||
"mp4",
|
||||
path,
|
||||
]
|
||||
try:
|
||||
subprocess.run(command, check=True, capture_output=True)
|
||||
except (subprocess.CalledProcessError, OSError) as exc:
|
||||
with contextlib.suppress(OSError):
|
||||
os.remove(path)
|
||||
raise HTTPException(status_code=500, detail=f"ffmpeg failed to build mock {kind}: {exc}") from exc
|
||||
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
||||
raise HTTPException(status_code=500, detail=f"ffmpeg produced no mock {kind} bytes")
|
||||
_mock_media_cache[kind] = path
|
||||
return path
|
||||
|
||||
|
||||
# --- Job helpers ------------------------------------------------------------
|
||||
|
||||
|
||||
def _new_job_dict(req: CreateJobRequest) -> dict[str, Any]:
|
||||
"""Build a job dict (mirrors job_runner.Job.to_dict()) in the pending state."""
|
||||
job_id = str(uuid.uuid4())
|
||||
return {
|
||||
"id": job_id,
|
||||
"model_id": req.model_id,
|
||||
"prompt": req.prompt,
|
||||
"workload_type": req.workload_type or "t2v",
|
||||
"job_type": req.job_type or "inference",
|
||||
"image_path": req.image_path or "",
|
||||
"status": "pending",
|
||||
"created_at": time.time(),
|
||||
"started_at": None,
|
||||
"finished_at": None,
|
||||
"error": None,
|
||||
"output_path": None,
|
||||
"log_file_path": None,
|
||||
"num_inference_steps": req.num_inference_steps,
|
||||
"num_frames": req.num_frames,
|
||||
"height": req.height,
|
||||
"width": req.width,
|
||||
"guidance_scale": req.guidance_scale,
|
||||
"guidance_rescale": req.guidance_rescale,
|
||||
"fps": req.fps,
|
||||
"seed": req.seed,
|
||||
"negative_prompt": req.negative_prompt or "",
|
||||
"num_gpus": req.num_gpus,
|
||||
"data_path": req.data_path or "",
|
||||
"progress": 0.0,
|
||||
"progress_msg": "",
|
||||
"phase": "pending",
|
||||
}
|
||||
|
||||
|
||||
def _advance_job(job: dict[str, Any]) -> None:
|
||||
"""Flip a running job to completed once enough wall-clock time has passed.
|
||||
|
||||
Status is *computed on read* from the recorded start timestamp, so polling
|
||||
the job list / logs naturally shows pending -> running -> completed.
|
||||
"""
|
||||
if job["status"] != "running" or not job.get("started_at"):
|
||||
return
|
||||
elapsed = time.time() - job["started_at"]
|
||||
if elapsed >= COMPLETE_AFTER_SECONDS:
|
||||
job["status"] = "completed"
|
||||
job["finished_at"] = job["started_at"] + COMPLETE_AFTER_SECONDS
|
||||
job["progress"] = 100.0
|
||||
job["progress_msg"] = "50/50 steps"
|
||||
job["phase"] = "done"
|
||||
ext = "png" if job.get("workload_type") == "t2i" else "mp4"
|
||||
job["output_path"] = f"/mock/outputs/{job['id']}/output.{ext}"
|
||||
|
||||
|
||||
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Advance + return a copy safe to serialize."""
|
||||
_advance_job(job)
|
||||
return dict(job)
|
||||
|
||||
|
||||
_LOG_TAIL = [
|
||||
"Loading model...",
|
||||
"Model loaded.",
|
||||
"Starting generation...",
|
||||
"Denoising step 10/50",
|
||||
"Denoising step 20/50",
|
||||
"Denoising step 30/50",
|
||||
"Denoising step 40/50",
|
||||
"Denoising step 50/50",
|
||||
"Generation complete. Saving output...",
|
||||
"Saved output file.",
|
||||
"Job completed successfully.",
|
||||
]
|
||||
|
||||
|
||||
def _log_sequence(job: dict[str, Any]) -> list[str]:
|
||||
return [
|
||||
f"Job {job['id']} started",
|
||||
f"Model: {job['model_id']}",
|
||||
f"Prompt: {job['prompt']}",
|
||||
*_LOG_TAIL,
|
||||
]
|
||||
|
||||
|
||||
def _compute_logs(job: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return JobLogs-shaped data, growing the visible lines as time passes."""
|
||||
seq = _log_sequence(job)
|
||||
status = job["status"]
|
||||
if status == "pending":
|
||||
return {"lines": [], "progress": 0.0, "progress_msg": "", "phase": "pending"}
|
||||
if status == "completed":
|
||||
return {"lines": seq, "progress": 100.0, "progress_msg": "50/50 steps", "phase": "done"}
|
||||
if status in ("failed", "stopped"):
|
||||
# Keep the total line count monotonic across running -> terminal (the
|
||||
# `after` cursor relies on it): show every non-final line plus a terminal
|
||||
# notice, which is always >= any prefix a running job revealed.
|
||||
lines = seq[:-1] + [f"Job {status}."]
|
||||
return {"lines": lines, "progress": job.get("progress", 0.0), "progress_msg": "", "phase": status}
|
||||
# running: reveal a prefix proportional to elapsed time, but never the final
|
||||
# "completed" line — that appears only once the job is actually completed.
|
||||
elapsed = time.time() - (job.get("started_at") or time.time())
|
||||
frac = max(0.0, min(elapsed / COMPLETE_AFTER_SECONDS, 0.99))
|
||||
reveal = min(max(4, round(frac * len(seq))), len(seq) - 1)
|
||||
lines = seq[:reveal]
|
||||
if frac < 0.2:
|
||||
phase = "loading model"
|
||||
elif frac < 0.85:
|
||||
phase = "denoising"
|
||||
else:
|
||||
phase = "saving"
|
||||
return {
|
||||
"lines": lines,
|
||||
"progress": round(frac * 100.0, 1),
|
||||
"progress_msg": f"{int(frac * 50)}/50 steps",
|
||||
"phase": phase,
|
||||
}
|
||||
|
||||
|
||||
# --- Dataset helpers --------------------------------------------------------
|
||||
|
||||
|
||||
def _dataset_stats(dataset_id: str) -> tuple[int, int]:
|
||||
files = _dataset_files.get(dataset_id, {}).get("file_names", [])
|
||||
count = len(files)
|
||||
# Fake but stable per-file size so the UI shows a non-zero footprint.
|
||||
return count, count * 1_048_576
|
||||
|
||||
|
||||
def _public_dataset(dataset: dict[str, Any]) -> dict[str, Any]:
|
||||
count, size = _dataset_stats(dataset["id"])
|
||||
return {**dataset, "file_count": count, "size_bytes": size}
|
||||
|
||||
|
||||
def _seed() -> None:
|
||||
"""Seed a couple of datasets and one completed inference job."""
|
||||
now = time.time()
|
||||
seeds = [
|
||||
("Sunset Clips", ["sunset_01.mp4", "sunset_02.mp4"], {
|
||||
"sunset_01.mp4": "A sunset over the ocean",
|
||||
"sunset_02.mp4": "A sunset over the mountains"
|
||||
}),
|
||||
("City Timelapse", ["city_01.mp4"], {
|
||||
"city_01.mp4": "A busy city intersection at night"
|
||||
}),
|
||||
]
|
||||
for idx, (name, file_names, captions) in enumerate(seeds):
|
||||
dataset_id = str(uuid.uuid4())
|
||||
_datasets[dataset_id] = {"id": dataset_id, "name": name, "created_at": now - 600 + idx}
|
||||
_dataset_files[dataset_id] = {"file_names": list(file_names), "captions": dict(captions)}
|
||||
|
||||
job_id = str(uuid.uuid4())
|
||||
_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"model_id": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
|
||||
"prompt": "A curious raccoon peers through a field of yellow sunflowers",
|
||||
"workload_type": "t2v",
|
||||
"job_type": "inference",
|
||||
"image_path": "",
|
||||
"status": "completed",
|
||||
"created_at": now - 300,
|
||||
"started_at": now - 280,
|
||||
"finished_at": now - 250,
|
||||
"error": None,
|
||||
"output_path": f"/mock/outputs/{job_id}/output.mp4",
|
||||
"log_file_path": f"/mock/logs/{job_id}.log",
|
||||
"num_inference_steps": 50,
|
||||
"num_frames": 81,
|
||||
"height": 480,
|
||||
"width": 832,
|
||||
"guidance_scale": 5.0,
|
||||
"guidance_rescale": 0.0,
|
||||
"fps": 24,
|
||||
"seed": 1024,
|
||||
"negative_prompt": "",
|
||||
"num_gpus": 1,
|
||||
"data_path": "",
|
||||
"progress": 100.0,
|
||||
"progress_msg": "50/50 steps",
|
||||
"phase": "done",
|
||||
}
|
||||
|
||||
|
||||
# --- App --------------------------------------------------------------------
|
||||
|
||||
app = FastAPI(title="FastVideo Studio Mock API", version="0.1.0")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
_seed()
|
||||
|
||||
|
||||
@app.get("/api/__mock__")
|
||||
def mock_sentinel() -> dict[str, bool]:
|
||||
"""Mock-only marker so the e2e suite can prove it isn't hitting a real
|
||||
backend before running its mutating specs (the real server has no such
|
||||
route)."""
|
||||
return {"mock": True}
|
||||
|
||||
|
||||
# --- Settings ---------------------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/settings")
|
||||
def get_settings() -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
return dict(_settings)
|
||||
|
||||
|
||||
@app.put("/api/settings")
|
||||
def update_settings(settings: SettingsUpdate) -> dict[str, Any]:
|
||||
updates = settings.model_dump(exclude_unset=True)
|
||||
with _state_lock:
|
||||
_settings.update({k: v for k, v in updates.items() if v is not None})
|
||||
return dict(_settings)
|
||||
|
||||
|
||||
# --- Models -----------------------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/models")
|
||||
def list_models(workload_type: str | None = None) -> list[dict[str, Any]]:
|
||||
return _models_for(workload_type)
|
||||
|
||||
|
||||
# --- GPUs -------------------------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/gpus")
|
||||
def list_gpus() -> dict[str, Any]:
|
||||
"""Two fake GPUs with slight per-request jitter so the page looks live."""
|
||||
gpus = []
|
||||
for index, (base_util, used_mib) in enumerate([(62, 61_440), (7, 4_096)]):
|
||||
gpus.append({
|
||||
"index": index,
|
||||
"name": "NVIDIA Mock GPU 80GB",
|
||||
"utilization": max(0, min(100, base_util + random.randint(-5, 5))),
|
||||
"memory_used_mib": used_mib + random.randint(-256, 256),
|
||||
"memory_total_mib": 81_920,
|
||||
"temperature_c": 55 + random.randint(-3, 3),
|
||||
"power_watts": 310.0 + random.randint(-20, 20),
|
||||
"power_limit_watts": 700.0,
|
||||
})
|
||||
return {"available": True, "gpus": gpus, "error": None}
|
||||
|
||||
|
||||
# --- Uploads ----------------------------------------------------------------
|
||||
|
||||
|
||||
@app.post("/api/upload-image")
|
||||
async def upload_image(file: Annotated[UploadFile, File()]) -> dict[str, str]:
|
||||
name = file.filename or "image.png"
|
||||
return {"path": f"/mock/uploads/{uuid.uuid4().hex}_{os.path.basename(name)}"}
|
||||
|
||||
|
||||
@app.post("/api/upload-raw-dataset")
|
||||
async def upload_raw_dataset(files: Annotated[list[UploadFile], File()]) -> dict[str, Any]:
|
||||
video_exts = {".mp4", ".webm", ".avi", ".mov", ".mkv"}
|
||||
file_names: list[str] = []
|
||||
for uf in files:
|
||||
name = os.path.basename(uf.filename or f"{uuid.uuid4().hex}.mp4")
|
||||
if os.path.splitext(name)[1].lower() in video_exts:
|
||||
file_names.append(name)
|
||||
if not file_names:
|
||||
raise HTTPException(status_code=400, detail="No video files found.")
|
||||
upload_id = uuid.uuid4().hex
|
||||
path = f"/mock/uploads/{upload_id}"
|
||||
return {"path": path, "upload_id": upload_id, "file_names": file_names}
|
||||
|
||||
|
||||
# --- Jobs -------------------------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/jobs")
|
||||
def list_jobs(job_type: str | None = None) -> list[dict[str, Any]]:
|
||||
# _public_job mutates the shared job dict via _advance_job, so it must run
|
||||
# under the lock (matching every other job route) to avoid racing start/stop.
|
||||
with _state_lock:
|
||||
jobs = list(_jobs.values())
|
||||
if job_type:
|
||||
jobs = [j for j in jobs if j.get("job_type") == job_type]
|
||||
jobs.sort(key=lambda j: j["created_at"], reverse=True)
|
||||
return [_public_job(j) for j in jobs]
|
||||
|
||||
|
||||
@app.get("/api/jobs/{job_id}")
|
||||
def get_job(job_id: str) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return _public_job(job)
|
||||
|
||||
|
||||
@app.post("/api/jobs", status_code=201)
|
||||
def create_job(req: CreateJobRequest) -> dict[str, Any]:
|
||||
job = _new_job_dict(req)
|
||||
with _state_lock:
|
||||
_jobs[job["id"]] = job
|
||||
if _settings.get("autoStartJob"):
|
||||
_start(job)
|
||||
return _public_job(job)
|
||||
|
||||
|
||||
def _start(job: dict[str, Any]) -> None:
|
||||
job["status"] = "running"
|
||||
job["started_at"] = time.time()
|
||||
job["finished_at"] = None
|
||||
job["error"] = None
|
||||
job["output_path"] = None
|
||||
# The real server assigns the log path once the job starts running; mirror
|
||||
# that so the Job Details "Download Log" button (gated on log_file_path) works.
|
||||
job["log_file_path"] = f"/mock/logs/{job['id']}.log"
|
||||
job["progress"] = 0.0
|
||||
job["progress_msg"] = ""
|
||||
job["phase"] = "starting"
|
||||
|
||||
|
||||
@app.post("/api/jobs/{job_id}/start")
|
||||
def start_job(job_id: str) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
_advance_job(job)
|
||||
if job["status"] == "running":
|
||||
raise HTTPException(status_code=409, detail="Job is already running")
|
||||
if job["status"] == "completed":
|
||||
raise HTTPException(status_code=409, detail="Job already completed. Delete and re-create to run again.")
|
||||
_start(job)
|
||||
return _public_job(job)
|
||||
|
||||
|
||||
@app.post("/api/jobs/{job_id}/stop")
|
||||
def stop_job(job_id: str) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
_advance_job(job)
|
||||
if job["status"] != "running":
|
||||
raise HTTPException(status_code=409, detail=f"Job is not running (status={job['status']})")
|
||||
job["status"] = "stopped"
|
||||
job["finished_at"] = time.time()
|
||||
job["phase"] = "stopped"
|
||||
return dict(job)
|
||||
|
||||
|
||||
@app.delete("/api/jobs/{job_id}")
|
||||
def delete_job(job_id: str) -> dict[str, str]:
|
||||
with _state_lock:
|
||||
if _jobs.pop(job_id, None) is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return {"detail": f"Job {job_id} deleted"}
|
||||
|
||||
|
||||
@app.get("/api/jobs/{job_id}/logs")
|
||||
def get_job_logs(job_id: str, after: int = 0) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
_advance_job(job)
|
||||
result = _compute_logs(job)
|
||||
all_lines = result["lines"]
|
||||
return {
|
||||
"lines": all_lines[after:],
|
||||
"total": len(all_lines),
|
||||
"progress": result["progress"],
|
||||
"progress_msg": result["progress_msg"],
|
||||
"phase": result["phase"],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/jobs/{job_id}/video")
|
||||
def get_video(job_id: str) -> FileResponse:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
_advance_job(job)
|
||||
output_path = job.get("output_path")
|
||||
if job["status"] != "completed" or not output_path:
|
||||
raise HTTPException(status_code=404, detail="No output available for this job")
|
||||
# Mirror the real server: image workloads (t2i) output a .png served as an
|
||||
# image; everything else is a video.
|
||||
if output_path.endswith(".png"):
|
||||
return FileResponse(_build_mock_media("png"), media_type="image/png", filename=f"job_{job_id}.png")
|
||||
return FileResponse(_build_mock_media("mp4"), media_type="video/mp4", filename=f"job_{job_id}.mp4")
|
||||
|
||||
|
||||
@app.get("/api/jobs/{job_id}/download_log")
|
||||
def download_log(job_id: str) -> PlainTextResponse:
|
||||
with _state_lock:
|
||||
job = _jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
_advance_job(job)
|
||||
lines = _compute_logs(job)["lines"]
|
||||
return PlainTextResponse("\n".join(lines) + "\n", media_type="text/plain")
|
||||
|
||||
|
||||
# --- Datasets ---------------------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/datasets")
|
||||
def list_datasets() -> list[dict[str, Any]]:
|
||||
with _state_lock:
|
||||
datasets = sorted(_datasets.values(), key=lambda d: d["created_at"], reverse=True)
|
||||
return [_public_dataset(d) for d in datasets]
|
||||
|
||||
|
||||
@app.get("/api/datasets/{dataset_id}")
|
||||
def get_dataset(dataset_id: str) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
dataset = _datasets.get(dataset_id)
|
||||
if dataset is None:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
return _public_dataset(dataset)
|
||||
|
||||
|
||||
@app.post("/api/datasets", status_code=201)
|
||||
def create_dataset(req: CreateDatasetRequest) -> dict[str, Any]:
|
||||
if not req.upload_path:
|
||||
raise HTTPException(status_code=400, detail="upload_path is required. Upload media files first.")
|
||||
if not req.file_names:
|
||||
raise HTTPException(status_code=400, detail="No media files found.")
|
||||
dataset_id = str(uuid.uuid4())
|
||||
dataset = {"id": dataset_id, "name": req.name, "created_at": time.time()}
|
||||
captions = {fn: (req.captions.get(fn, "") if req.captions else "") for fn in req.file_names}
|
||||
with _state_lock:
|
||||
_datasets[dataset_id] = dataset
|
||||
_dataset_files[dataset_id] = {"file_names": list(req.file_names), "captions": captions}
|
||||
return _public_dataset(dataset)
|
||||
|
||||
|
||||
@app.get("/api/datasets/{dataset_id}/files")
|
||||
def get_dataset_files(dataset_id: str) -> dict[str, Any]:
|
||||
with _state_lock:
|
||||
if dataset_id not in _datasets:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
files = _dataset_files.get(dataset_id, {"file_names": [], "captions": {}})
|
||||
return {"file_names": list(files["file_names"]), "captions": dict(files["captions"])}
|
||||
|
||||
|
||||
@app.put("/api/datasets/{dataset_id}/captions")
|
||||
def update_dataset_caption(dataset_id: str, req: UpdateCaptionRequest) -> dict[str, str]:
|
||||
with _state_lock:
|
||||
if dataset_id not in _datasets:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
files = _dataset_files.setdefault(dataset_id, {"file_names": [], "captions": {}})
|
||||
files["captions"][req.file_name] = req.caption
|
||||
return {"detail": "Caption updated"}
|
||||
|
||||
|
||||
@app.get("/api/datasets/{dataset_id}/media/{file_name:path}")
|
||||
def serve_dataset_media(dataset_id: str, file_name: str) -> FileResponse:
|
||||
with _state_lock:
|
||||
if dataset_id not in _datasets:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
if file_name not in _dataset_files.get(dataset_id, {}).get("file_names", []):
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return FileResponse(_build_mock_media("mp4"), media_type="video/mp4")
|
||||
|
||||
|
||||
@app.delete("/api/datasets/{dataset_id}")
|
||||
def delete_dataset(dataset_id: str) -> dict[str, str]:
|
||||
with _state_lock:
|
||||
if _datasets.pop(dataset_id, None) is None:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
_dataset_files.pop(dataset_id, None)
|
||||
return {"detail": f"Dataset {dataset_id} deleted"}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import argparse
|
||||
|
||||
import uvicorn
|
||||
|
||||
parser = argparse.ArgumentParser(description="FastVideo Studio mock API server")
|
||||
parser.add_argument("--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1)")
|
||||
# Default off the real server's 8189 so the mock never shadows a real API.
|
||||
parser.add_argument("--port", type=int, default=8190, help="Port number (default: 8190)")
|
||||
args = parser.parse_args()
|
||||
|
||||
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,14 +1,22 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Pydantic request/response models for the API."""
|
||||
"""Pydantic request/response models for the API, plus tiny shared helpers
|
||||
usable by both the real server and the dependency-light mock server."""
|
||||
|
||||
from fastvideo_studio.models.create_job_request import CreateJobRequest
|
||||
from fastvideo_studio.models.settings_update import SettingsUpdate
|
||||
from fastvideo_studio.models.create_dataset_request import CreateDatasetRequest
|
||||
from fastvideo_studio.models.update_caption_request import UpdateCaptionRequest
|
||||
|
||||
|
||||
def model_label(model_path: str) -> str:
|
||||
"""Derive a readable label from an HF-style model path."""
|
||||
return model_path.split("/")[-1].replace("-", " ").replace("_", " ")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CreateJobRequest",
|
||||
"SettingsUpdate",
|
||||
"CreateDatasetRequest",
|
||||
"UpdateCaptionRequest",
|
||||
"model_label",
|
||||
]
|
||||
|
||||
@@ -17,7 +17,6 @@ class CreateJobRequest(BaseModel):
|
||||
num_latent_t: int = 20
|
||||
validation_dataset_file: str = ""
|
||||
lora_rank: int = 32
|
||||
ltx2_first_frame_conditioning_p: float | None = None
|
||||
negative_prompt: str = ""
|
||||
num_inference_steps: int = 50
|
||||
num_frames: int = 81
|
||||
@@ -41,8 +40,6 @@ class CreateJobRequest(BaseModel):
|
||||
dmd_use_vsa: bool = False
|
||||
dmd_vsa_sparsity: float = 0.8
|
||||
dmd_denoising_steps: str = "1000,757,522"
|
||||
min_timestep_ratio: float = 0.02
|
||||
max_timestep_ratio: float = 0.98
|
||||
real_score_guidance_scale: float = 3.5
|
||||
generator_update_interval: int = 5
|
||||
real_score_model_path: str = ""
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const configDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// Point tracing at the monorepo root (apps/fastvideo_studio -> apps -> repo
|
||||
// root) so Next stops warning about multiple lockfiles in the workspace.
|
||||
outputFileTracingRoot: path.join(configDir, '..', '..'),
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+4618
-1038
File diff suppressed because it is too large
Load Diff
@@ -4,33 +4,54 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"start": "concurrently --kill-others-on-fail \"npm:start:api\" \"npm:start:web\"",
|
||||
"dev": "next dev --port 3000",
|
||||
"build": "next build",
|
||||
"start": "next start --port 3000",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"e2e": "playwright test",
|
||||
"start:api": "cd .. && python -m fastvideo_studio.server",
|
||||
"start:web": "node build",
|
||||
"lint": "eslint ."
|
||||
"start:web": "next start --port 3000",
|
||||
"start:all": "concurrently --kill-others-on-fail \"npm:start:api\" \"npm:start:web\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@sveltejs/kit": "2.57.1",
|
||||
"svelte": "5.55.7"
|
||||
"@radix-ui/react-dialog": "^1.1.0",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slider": "^1.2.0",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.1.0",
|
||||
"@radix-ui/react-tabs": "^1.1.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.577.0",
|
||||
"next": "15.5.18",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-node": "^5.5.4",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.0",
|
||||
"@types/node": "^20",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"@tailwindcss/postcss": "^4.2.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^22",
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"concurrently": "^9",
|
||||
"eslint": "^9",
|
||||
"typescript": "^5",
|
||||
"vite": "6.4.2"
|
||||
},
|
||||
"overrides": {
|
||||
"cookie": "0.7.0",
|
||||
"devalue": "5.8.1",
|
||||
"flatted": "3.4.2",
|
||||
"minimatch": "3.1.4",
|
||||
"picomatch": "4.0.4",
|
||||
"postcss": "8.5.10"
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "8.5.10",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
import { API_BASE, MOCK_API_PORT } from './e2e/helpers';
|
||||
|
||||
/**
|
||||
* Playwright config for FastVideo Studio end-to-end tests.
|
||||
*
|
||||
* The Next.js frontend runs on port 3000 and talks to the in-memory mock API
|
||||
* (fastvideo_studio.mock_server) on port 8189. The webServer block boots both
|
||||
* the mock backend and `npm run dev` (pointed at the mock via
|
||||
* NEXT_PUBLIC_API_BASE_URL) if nothing is already listening, so the suite works
|
||||
* both locally and in CI. Set PLAYWRIGHT_SKIP_WEBSERVER to reuse externally
|
||||
* managed servers.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
reporter: process.env.CI ? 'github' : 'list',
|
||||
timeout: 120_000,
|
||||
expect: { timeout: 30_000 },
|
||||
use: {
|
||||
baseURL: process.env.PLAYWRIGHT_BASE_URL ?? 'http://127.0.0.1:3000',
|
||||
headless: true,
|
||||
viewport: { width: 1280, height: 720 },
|
||||
screenshot: 'only-on-failure',
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
|
||||
webServer: process.env.PLAYWRIGHT_SKIP_WEBSERVER
|
||||
? undefined
|
||||
: [
|
||||
{
|
||||
command: `PYTHONPATH=.. python -m fastvideo_studio.mock_server --port ${MOCK_API_PORT}`,
|
||||
// Probe the mock-only sentinel, not /api/models (which a real server
|
||||
// also serves), so a real backend on this port is never mistaken for
|
||||
// the mock. Always boot a fresh mock in CI.
|
||||
url: `http://127.0.0.1:${MOCK_API_PORT}/api/__mock__`,
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
},
|
||||
{
|
||||
command: 'npm run dev',
|
||||
url: 'http://127.0.0.1:3000',
|
||||
reuseExistingServer: true,
|
||||
timeout: 120_000,
|
||||
env: {
|
||||
NEXT_PUBLIC_API_BASE_URL: API_BASE,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
@@ -1,142 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""
|
||||
Runs preprocessing subprocess for datasets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from collections.abc import Callable
|
||||
|
||||
logger = logging.getLogger("fastvideo.studio.preprocess_runner")
|
||||
|
||||
|
||||
def build_preprocess_args(
|
||||
dataset_id: str,
|
||||
raw_path: str,
|
||||
output_dir: str,
|
||||
workload_type: str,
|
||||
model_path: str,
|
||||
dataset_type: str = "merged",
|
||||
num_gpus: int = 1,
|
||||
) -> list[str]:
|
||||
"""Build CLI args for v1_preprocessing_new."""
|
||||
return [
|
||||
"--model-path",
|
||||
model_path,
|
||||
"--mode",
|
||||
"preprocess",
|
||||
"--workload-type",
|
||||
workload_type,
|
||||
"--preprocess.video_loader_type",
|
||||
"torchvision",
|
||||
"--preprocess.dataset_type",
|
||||
dataset_type,
|
||||
"--preprocess.dataset_path",
|
||||
raw_path,
|
||||
"--preprocess.dataset_output_dir",
|
||||
output_dir,
|
||||
"--preprocess.preprocess_video_batch_size",
|
||||
"2",
|
||||
"--preprocess.dataloader_num_workers",
|
||||
"0",
|
||||
"--preprocess.max_height",
|
||||
"480",
|
||||
"--preprocess.max_width",
|
||||
"832",
|
||||
"--preprocess.num_frames",
|
||||
"77",
|
||||
"--preprocess.train_fps",
|
||||
"16",
|
||||
"--preprocess.samples_per_file",
|
||||
"8",
|
||||
"--preprocess.flush_frequency",
|
||||
"8",
|
||||
"--preprocess.video_length_tolerance_range",
|
||||
"5",
|
||||
]
|
||||
|
||||
|
||||
def run_preprocess(
|
||||
dataset_id: str,
|
||||
raw_path: str,
|
||||
output_dir: str,
|
||||
workload_type: str,
|
||||
model_path: str,
|
||||
dataset_type: str,
|
||||
num_gpus: int,
|
||||
log_file_path: str,
|
||||
on_status_change: Callable[[str, str | None], None],
|
||||
stop_event: threading.Event,
|
||||
) -> None:
|
||||
"""Run preprocessing subprocess. Calls on_status_change(status, error)."""
|
||||
repo_root = Path(__file__).resolve().parent.parent
|
||||
preprocess_module = "fastvideo.pipelines.preprocess.v1_preprocessing_new"
|
||||
|
||||
args = build_preprocess_args(
|
||||
dataset_id=dataset_id,
|
||||
raw_path=raw_path,
|
||||
output_dir=output_dir,
|
||||
workload_type=workload_type,
|
||||
model_path=model_path,
|
||||
dataset_type=dataset_type,
|
||||
num_gpus=num_gpus,
|
||||
)
|
||||
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"torch.distributed.run",
|
||||
"--nproc_per_node",
|
||||
str(num_gpus),
|
||||
"--nnodes",
|
||||
"1",
|
||||
"-m",
|
||||
preprocess_module,
|
||||
] + args
|
||||
|
||||
env = os.environ.copy()
|
||||
env["TOKENIZERS_PARALLELISM"] = "false"
|
||||
|
||||
try:
|
||||
on_status_change("preprocessing", None)
|
||||
with open(log_file_path, "w", encoding="utf-8") as log_file:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(repo_root),
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
assert proc.stdout is not None
|
||||
for line in iter(proc.stdout.readline, ""):
|
||||
if stop_event.is_set():
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
on_status_change("stopped", "Preprocessing stopped by user")
|
||||
return
|
||||
line = line.rstrip()
|
||||
if line:
|
||||
log_file.write(line + "\n")
|
||||
log_file.flush()
|
||||
|
||||
proc.wait()
|
||||
exit_code = proc.returncode or 0
|
||||
|
||||
if exit_code == 0:
|
||||
on_status_change("ready", None)
|
||||
else:
|
||||
on_status_change("failed", f"Preprocessing exited with code {exit_code}")
|
||||
except Exception as exc:
|
||||
on_status_change("failed", f"{type(exc).__name__}: {exc}")
|
||||
logger.exception("Preprocessing failed for dataset %s", dataset_id)
|
||||
@@ -32,8 +32,10 @@ from fastapi.responses import FileResponse
|
||||
|
||||
from fastvideo.registry import (get_registered_model_paths, get_registered_models_with_workloads)
|
||||
from fastvideo_studio.database import Database, _get_db_path
|
||||
from fastvideo_studio.gpu import get_gpu_snapshot
|
||||
from fastvideo_studio.job_runner import JobRunner, JobStatus
|
||||
from fastvideo_studio.models import (CreateDatasetRequest, CreateJobRequest, SettingsUpdate, UpdateCaptionRequest)
|
||||
from fastvideo_studio.models import (CreateDatasetRequest, CreateJobRequest, SettingsUpdate, UpdateCaptionRequest,
|
||||
model_label)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -43,15 +45,9 @@ logger = logging.getLogger("fastvideo.studio.api")
|
||||
|
||||
DEFAULT_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "..", "outputs", "ui_jobs")
|
||||
|
||||
|
||||
def _get_model_label(model_path: str) -> str:
|
||||
"""Derive a readable label from a HF model path."""
|
||||
return model_path.split("/")[-1].replace("-", " ").replace("_", " ")
|
||||
|
||||
|
||||
_available_models: list[dict[str, str]] = [{
|
||||
"id": path,
|
||||
"label": _get_model_label(path)
|
||||
"label": model_label(path)
|
||||
} for path in get_registered_model_paths()]
|
||||
|
||||
job_runner: JobRunner
|
||||
@@ -100,6 +96,12 @@ def update_settings(settings: SettingsUpdate) -> dict[str, Any]:
|
||||
return database.get_settings()
|
||||
|
||||
|
||||
@app.get("/api/gpus")
|
||||
def list_gpus() -> dict[str, Any]:
|
||||
"""Return an NVML snapshot of every GPU on the API server host."""
|
||||
return get_gpu_snapshot()
|
||||
|
||||
|
||||
@app.get("/api/models")
|
||||
def list_models(workload_type: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Return the catalogue of available video-generation models.
|
||||
@@ -148,7 +150,7 @@ async def upload_image(file: Annotated[UploadFile, File()], ) -> dict[str, str]:
|
||||
return {"path": os.path.abspath(dest_path)}
|
||||
|
||||
|
||||
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".avi", ".mov"}
|
||||
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".avi", ".mov", ".mkv"}
|
||||
|
||||
|
||||
def _filter_video_files(files: list[UploadFile]) -> list[UploadFile]:
|
||||
@@ -156,6 +158,23 @@ def _filter_video_files(files: list[UploadFile]) -> list[UploadFile]:
|
||||
return [f for f in files if Path(f.filename or "").suffix.lower() in ALLOWED_VIDEO_EXTENSIONS]
|
||||
|
||||
|
||||
def _path_is_within(child: str, parent: str) -> bool:
|
||||
"""True if ``child`` resolves to a location inside ``parent``."""
|
||||
try:
|
||||
parent_real = os.path.realpath(parent)
|
||||
return os.path.commonpath([os.path.realpath(child), parent_real]) == parent_real
|
||||
except (ValueError, OSError):
|
||||
return False
|
||||
|
||||
|
||||
def _staging_base_path() -> str:
|
||||
"""Root under which raw uploads are staged (settings override or default)."""
|
||||
settings = database.get_settings() if database is not None else {}
|
||||
raw_path = (settings.get("datasetUploadPath") or settings.get("dataset_upload_path") or "")
|
||||
base_path = (raw_path.strip() if raw_path and isinstance(raw_path, str) else "")
|
||||
return datasets_upload_dir if not base_path else os.path.abspath(base_path)
|
||||
|
||||
|
||||
@app.post("/api/upload-raw-dataset")
|
||||
async def upload_raw_dataset(files: Annotated[list[UploadFile], File()], ) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -167,10 +186,7 @@ async def upload_raw_dataset(files: Annotated[list[UploadFile], File()], ) -> di
|
||||
status_code=503,
|
||||
detail="Database not initialized",
|
||||
)
|
||||
settings = database.get_settings()
|
||||
raw_path = (settings.get("datasetUploadPath") or settings.get("dataset_upload_path") or "")
|
||||
base_path = (raw_path.strip() if raw_path and isinstance(raw_path, str) else "")
|
||||
base_path = (datasets_upload_dir if not base_path else os.path.abspath(base_path))
|
||||
base_path = _staging_base_path()
|
||||
if not base_path:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
@@ -250,6 +266,19 @@ def create_job(req: CreateJobRequest) -> dict[str, Any]:
|
||||
f"Valid options: {sorted(valid_ids)}"),
|
||||
)
|
||||
|
||||
# Training jobs reference a dataset by id; resolve it to the on-disk media
|
||||
# directory the trainer reads (the UI has no free-text path field). Falls
|
||||
# through unchanged for inference and for anything already a real path.
|
||||
def _resolve_dataset_path(value: str) -> str:
|
||||
media_dir = _dataset_media_dir(value) if value else ""
|
||||
return media_dir if media_dir and os.path.isdir(media_dir) else value
|
||||
|
||||
data_path = req.data_path or ""
|
||||
validation_dataset_file = req.validation_dataset_file or ""
|
||||
if job_type != "inference":
|
||||
data_path = _resolve_dataset_path(data_path)
|
||||
validation_dataset_file = _resolve_dataset_path(validation_dataset_file)
|
||||
|
||||
job = job_runner.create_job(
|
||||
job_id=str(uuid.uuid4()),
|
||||
model_id=req.model_id,
|
||||
@@ -257,14 +286,13 @@ def create_job(req: CreateJobRequest) -> dict[str, Any]:
|
||||
workload_type=req.workload_type or "t2v",
|
||||
job_type=job_type,
|
||||
image_path=req.image_path or "",
|
||||
data_path=req.data_path or "",
|
||||
data_path=data_path,
|
||||
max_train_steps=req.max_train_steps,
|
||||
train_batch_size=req.train_batch_size,
|
||||
learning_rate=req.learning_rate,
|
||||
num_latent_t=req.num_latent_t,
|
||||
validation_dataset_file=req.validation_dataset_file or "",
|
||||
validation_dataset_file=validation_dataset_file,
|
||||
lora_rank=req.lora_rank,
|
||||
ltx2_first_frame_conditioning_p=req.ltx2_first_frame_conditioning_p,
|
||||
negative_prompt=req.negative_prompt,
|
||||
num_inference_steps=req.num_inference_steps,
|
||||
num_frames=req.num_frames,
|
||||
@@ -287,8 +315,6 @@ def create_job(req: CreateJobRequest) -> dict[str, Any]:
|
||||
dmd_use_vsa=req.dmd_use_vsa,
|
||||
dmd_vsa_sparsity=req.dmd_vsa_sparsity,
|
||||
dmd_denoising_steps=req.dmd_denoising_steps or "1000,757,522",
|
||||
min_timestep_ratio=req.min_timestep_ratio,
|
||||
max_timestep_ratio=req.max_timestep_ratio,
|
||||
real_score_guidance_scale=req.real_score_guidance_scale,
|
||||
generator_update_interval=req.generator_update_interval,
|
||||
real_score_model_path=req.real_score_model_path or "",
|
||||
@@ -418,6 +444,13 @@ def create_dataset(req: CreateDatasetRequest) -> dict[str, Any]:
|
||||
status_code=400,
|
||||
detail="No media files found. Ensure at least one image or video.",
|
||||
)
|
||||
# upload_path must be a staging dir produced by /api/upload-raw-dataset,
|
||||
# not an arbitrary client path — the code below copies then rmtrees it.
|
||||
if not _path_is_within(req.upload_path, _staging_base_path()):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="upload_path must be a staged upload directory.",
|
||||
)
|
||||
dataset_id = str(uuid.uuid4())
|
||||
created_at = time.time()
|
||||
dest_dir = os.path.join(datasets_upload_dir, dataset_id)
|
||||
@@ -491,8 +524,9 @@ def serve_dataset_media(dataset_id: str, file_name: str) -> FileResponse:
|
||||
ds = database.get_dataset(dataset_id)
|
||||
if ds is None:
|
||||
raise HTTPException(status_code=404, detail="Dataset not found")
|
||||
media_path = os.path.join(_dataset_media_dir(dataset_id), file_name)
|
||||
if not os.path.isfile(media_path):
|
||||
media_dir = _dataset_media_dir(dataset_id)
|
||||
media_path = os.path.realpath(os.path.join(media_dir, file_name))
|
||||
if not (_path_is_within(media_path, media_dir) and os.path.isfile(media_path)):
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
import mimetypes
|
||||
mime, _ = mimetypes.guess_type(media_path)
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
/* CSS Variables */
|
||||
:root {
|
||||
--header-height: 74px;
|
||||
--bg: #0f1117;
|
||||
--surface: #1a1d27;
|
||||
--border: #2a2d3a;
|
||||
--text: #e4e4e7;
|
||||
--text-dim: #9ca3af;
|
||||
--accent: #356cff;
|
||||
--accent-h: #818cf8;
|
||||
--green: #22c55e;
|
||||
--red: #ef4444;
|
||||
--yellow: #eab308;
|
||||
--blue: #3b82f6;
|
||||
--radius: 8px;
|
||||
--shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
/* Reset */
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Base body styles */
|
||||
body {
|
||||
font-family:
|
||||
"Inter",
|
||||
system-ui,
|
||||
-apple-system,
|
||||
sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.6;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Base form input styles (used globally) */
|
||||
select,
|
||||
input,
|
||||
textarea {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.55rem 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
select:focus,
|
||||
input:focus,
|
||||
textarea:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/fastvideo.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FastVideo</title>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body class="antialiased" data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import AddDatasetButton from '@/components/datasets/AddDatasetButton';
|
||||
import CreateDatasetModal from '@/components/datasets/CreateDatasetModal';
|
||||
import DatasetCard from '@/components/datasets/DatasetCard';
|
||||
import { HeaderActions } from '@/components/shell/HeaderActionsContext';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import { getDatasets } from '@/lib/api';
|
||||
import type { Dataset } from '@/lib/api';
|
||||
import {
|
||||
setActiveDataset,
|
||||
setActiveDatasetId,
|
||||
} from '@/stores/activeDataset';
|
||||
import {
|
||||
createDatasetModalStore,
|
||||
setCreateDatasetModalOpen,
|
||||
} from '@/stores/createDatasetModalOpen';
|
||||
|
||||
export default function DatasetsPage() {
|
||||
const [datasets, setDatasets] = React.useState<Dataset[]>([]);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
const { open } = useStore(createDatasetModalStore);
|
||||
|
||||
const fetchDatasets = React.useCallback(async () => {
|
||||
try {
|
||||
setDatasets(await getDatasets());
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch datasets:', err);
|
||||
// Distinguish an API outage from a genuinely empty list, so the user
|
||||
// isn't told they have no datasets when the server is unreachable.
|
||||
setError(err instanceof Error ? err.message : 'Failed to load datasets');
|
||||
}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchDatasets();
|
||||
}, [fetchDatasets]);
|
||||
|
||||
function handleSelectDataset(ds: Dataset) {
|
||||
setActiveDataset(ds);
|
||||
setActiveDatasetId(ds.id);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<HeaderActions>
|
||||
<AddDatasetButton />
|
||||
</HeaderActions>
|
||||
<main className="mx-auto flex w-full max-w-[850px] flex-col gap-6 px-4 pb-12">
|
||||
<Card className="p-6">
|
||||
<div>
|
||||
{error ? (
|
||||
<p className="py-8 text-center text-destructive">{error}</p>
|
||||
) : datasets.length === 0 ? (
|
||||
<p className="py-8 text-center text-muted-foreground">
|
||||
No datasets yet.
|
||||
</p>
|
||||
) : (
|
||||
datasets.map((ds) => (
|
||||
<DatasetCard
|
||||
key={ds.id}
|
||||
dataset={ds}
|
||||
onUpdated={fetchDatasets}
|
||||
onSelect={() => handleSelectDataset(ds)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</main>
|
||||
<CreateDatasetModal
|
||||
isOpen={open}
|
||||
onClose={() => setCreateDatasetModalOpen(false)}
|
||||
onSuccess={() => {
|
||||
fetchDatasets();
|
||||
setCreateDatasetModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import CreateJobButton from '@/components/jobs/CreateJobButton';
|
||||
import { HeaderActions } from '@/components/shell/HeaderActionsContext';
|
||||
import JobQueue from '@/components/jobs/JobQueue';
|
||||
|
||||
export default function DistillationPage() {
|
||||
return (
|
||||
<>
|
||||
<HeaderActions>
|
||||
<CreateJobButton jobType="distillation" />
|
||||
</HeaderActions>
|
||||
<JobQueue jobType="distillation" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
'use client';
|
||||
|
||||
import CreateJobButton from '@/components/jobs/CreateJobButton';
|
||||
import { HeaderActions } from '@/components/shell/HeaderActionsContext';
|
||||
import JobQueue from '@/components/jobs/JobQueue';
|
||||
import type { JobType } from '@/lib/types';
|
||||
|
||||
// 'lora' is a backend job_type (LoRA finetunes) that isn't part of the
|
||||
// JobType union; the finetuning queue lists both alongside full finetunes.
|
||||
const FINETUNING_LIST = ['finetuning', 'lora'] as JobType[];
|
||||
|
||||
export default function FinetuningPage() {
|
||||
return (
|
||||
<>
|
||||
<HeaderActions>
|
||||
<CreateJobButton jobType="finetuning" />
|
||||
</HeaderActions>
|
||||
<JobQueue jobType="finetuning" jobTypesForList={FINETUNING_LIST} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import GalleryPage from './page';
|
||||
import { HeaderActionsProvider } from '@/components/shell/HeaderActionsContext';
|
||||
import { getJobsList } from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
import { makeJob as makeBaseJob } from '@/test/factories';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
getJobsList: vi.fn(),
|
||||
getJobVideoUrl: (id: string) => `http://test.local/api/jobs/${id}/video`,
|
||||
}));
|
||||
|
||||
const makeJob = (overrides: Partial<Job> = {}): Job =>
|
||||
makeBaseJob({
|
||||
model_id: 'wan',
|
||||
prompt: 'a cat surfing a wave',
|
||||
status: 'completed',
|
||||
created_at: 1,
|
||||
finished_at: 2,
|
||||
output_path: '/out/clip.mp4',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function renderGallery() {
|
||||
return render(
|
||||
<HeaderActionsProvider>
|
||||
<GalleryPage />
|
||||
</HeaderActionsProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('GalleryPage', () => {
|
||||
it('renders a grid item for a completed inference job', async () => {
|
||||
vi.mocked(getJobsList).mockResolvedValue([
|
||||
makeJob({ prompt: 'a cat surfing a wave' }),
|
||||
]);
|
||||
|
||||
renderGallery();
|
||||
|
||||
expect(await screen.findByText('a cat surfing a wave')).toBeInTheDocument();
|
||||
expect(getJobsList).toHaveBeenCalledWith('inference');
|
||||
});
|
||||
|
||||
it('shows the empty state when no completed videos exist', async () => {
|
||||
vi.mocked(getJobsList).mockResolvedValue([
|
||||
makeJob({ status: 'running', output_path: null }),
|
||||
]);
|
||||
|
||||
renderGallery();
|
||||
|
||||
expect(
|
||||
await screen.findByText('No completed videos yet'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText('a cat surfing a wave'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
'use client';
|
||||
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { getJobVideoUrl, getJobsList } from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
|
||||
function isImage(job: Job): boolean {
|
||||
return job.output_path?.toLowerCase().endsWith('.png') ?? false;
|
||||
}
|
||||
|
||||
export default function GalleryPage() {
|
||||
const [jobs, setJobs] = useState<Job[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
async function load() {
|
||||
try {
|
||||
const list = await getJobsList('inference');
|
||||
if (cancelled) return;
|
||||
const sorted = [...list].sort(
|
||||
(a, b) =>
|
||||
(b.finished_at ?? b.created_at ?? 0) -
|
||||
(a.finished_at ?? a.created_at ?? 0),
|
||||
);
|
||||
setJobs(sorted);
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load jobs');
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
}
|
||||
}
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const galleryJobs = jobs.filter(
|
||||
(j) =>
|
||||
j.status === 'completed' &&
|
||||
j.output_path &&
|
||||
(j.job_type === 'inference' || !j.job_type),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-[1200px] px-4 pb-12 pt-4">
|
||||
<Card className="p-6">
|
||||
<h2 className="mb-1 text-2xl font-semibold text-foreground">Gallery</h2>
|
||||
<p className="mb-6 text-sm text-muted-foreground">
|
||||
Generated videos from completed inference jobs. Captions show the
|
||||
prompt used for each generation.
|
||||
</p>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-3 p-8 text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-primary" />
|
||||
<span>Loading gallery…</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="py-8 text-destructive">{error}</p>
|
||||
) : galleryJobs.length === 0 ? (
|
||||
<p className="py-8 text-center text-muted-foreground">
|
||||
No completed videos yet
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-5">
|
||||
{galleryJobs.map((job) => (
|
||||
<article
|
||||
key={job.id}
|
||||
className="flex flex-col overflow-hidden rounded-lg border border-border bg-background"
|
||||
>
|
||||
<div className="relative aspect-video overflow-hidden bg-muted">
|
||||
{isImage(job) ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={getJobVideoUrl(job.id)}
|
||||
alt={job.prompt}
|
||||
className="block h-full w-full object-contain"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<video
|
||||
src={getJobVideoUrl(job.id)}
|
||||
className="block h-full w-full object-contain"
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
preload="metadata"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p
|
||||
className="line-clamp-3 border-t border-border px-4 py-3 text-sm text-muted-foreground"
|
||||
title={job.prompt}
|
||||
>
|
||||
{job.prompt || '—'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/*
|
||||
* FastVideo Studio theme — shared with the Dreamverse design system:
|
||||
* slate light/dark palettes, #356cff accent blue, IBM Plex type. The studio
|
||||
* defaults to dark (see the theme init script in layout.tsx); the toggle in
|
||||
* the header persists the choice to localStorage.
|
||||
*/
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
--header-height: 74px;
|
||||
|
||||
--accent-blue: #356cff;
|
||||
|
||||
--background: #f5f4f4;
|
||||
--foreground: #0f172a;
|
||||
|
||||
--card: #ffffff;
|
||||
--card-foreground: #0f172a;
|
||||
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #0f172a;
|
||||
|
||||
--primary: #0f172a;
|
||||
--primary-foreground: #f8fafc;
|
||||
|
||||
--secondary: #f1f5f9;
|
||||
--secondary-foreground: #1e293b;
|
||||
|
||||
--muted: #f1f5f9;
|
||||
--muted-foreground: #64748b;
|
||||
|
||||
--accent: #e2e8f0;
|
||||
--accent-foreground: #0f172a;
|
||||
|
||||
--destructive: #ef4444;
|
||||
--destructive-foreground: #ffffff;
|
||||
|
||||
--border: #e2e8f0;
|
||||
--input: #cbd5e1;
|
||||
--ring: #94a3b8;
|
||||
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
color-scheme: dark;
|
||||
|
||||
--accent-blue: #356cff;
|
||||
|
||||
--background: #0f172a;
|
||||
--foreground: #e2e8f0;
|
||||
|
||||
--card: #0f172a;
|
||||
--card-foreground: #f1f5f9;
|
||||
|
||||
--popover: #0f172a;
|
||||
--popover-foreground: #f1f5f9;
|
||||
|
||||
--primary: #f1f5f9;
|
||||
--primary-foreground: #0f172a;
|
||||
|
||||
--secondary: #1e293b;
|
||||
--secondary-foreground: #f1f5f9;
|
||||
|
||||
--muted: #1e293b;
|
||||
--muted-foreground: #94a3b8;
|
||||
|
||||
--accent: #1e293b;
|
||||
--accent-foreground: #f1f5f9;
|
||||
|
||||
--destructive: #991b1b;
|
||||
--destructive-foreground: #fecaca;
|
||||
|
||||
--border: #334155;
|
||||
--input: #334155;
|
||||
--ring: #cbd5e1;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--font-plex-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-mono: var(--font-plex-mono), ui-monospace, monospace;
|
||||
|
||||
--color-accent-blue: var(--accent-blue);
|
||||
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
/* ——— Resets ——— */
|
||||
|
||||
html,
|
||||
body {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
html {
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
line-height: 1.6;
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-plex-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
/* Dreamverse's dark-mode backdrop: subtle radial glows over a deep fade. */
|
||||
body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 300ms ease;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(56, 189, 248, 0.14), transparent 36%),
|
||||
radial-gradient(circle at right top, rgba(129, 140, 248, 0.12), transparent 28%),
|
||||
linear-gradient(180deg, #020617 0%, #000000 100%);
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
.dark body::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
summary {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: rgba(56, 189, 248, 0.25);
|
||||
}
|
||||
|
||||
.dark ::selection {
|
||||
background: rgba(56, 189, 248, 0.35);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
/* Smooth the light/dark switch (class applied briefly by the theme toggle). */
|
||||
html.theme-transition,
|
||||
html.theme-transition *,
|
||||
html.theme-transition *::before,
|
||||
html.theme-transition *::after {
|
||||
transition:
|
||||
background-color 300ms ease,
|
||||
color 300ms ease,
|
||||
border-color 300ms ease,
|
||||
box-shadow 300ms ease,
|
||||
fill 300ms ease,
|
||||
stroke 300ms ease !important;
|
||||
}
|
||||
|
||||
/* ——— Base layer ——— */
|
||||
|
||||
@layer base {
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
img,
|
||||
svg,
|
||||
video,
|
||||
canvas {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import GpuGrid from '@/components/system/GpuGrid';
|
||||
|
||||
export default function GpusPage() {
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-[1100px] flex-col gap-6 px-4 pb-12 pt-6">
|
||||
<GpuGrid />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import CreateJobButton from '@/components/jobs/CreateJobButton';
|
||||
import { HeaderActions } from '@/components/shell/HeaderActionsContext';
|
||||
import JobQueue from '@/components/jobs/JobQueue';
|
||||
|
||||
export default function InferencePage() {
|
||||
return (
|
||||
<>
|
||||
<HeaderActions>
|
||||
<CreateJobButton jobType="inference" />
|
||||
</HeaderActions>
|
||||
<JobQueue jobType="inference" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { IBM_Plex_Mono, IBM_Plex_Sans } from 'next/font/google';
|
||||
|
||||
import { AppShell } from '@/components/shell/AppShell';
|
||||
import './globals.css';
|
||||
|
||||
const plexSans = IBM_Plex_Sans({
|
||||
subsets: ['latin'],
|
||||
weight: ['400', '500', '600', '700'],
|
||||
variable: '--font-plex-sans',
|
||||
display: 'swap',
|
||||
});
|
||||
|
||||
const plexMono = IBM_Plex_Mono({
|
||||
subsets: ['latin'],
|
||||
weight: ['400', '500', '600'],
|
||||
variable: '--font-plex-mono',
|
||||
display: 'swap',
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'FastVideo Studio',
|
||||
icons: { icon: '/fastvideo.ico' },
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
suppressHydrationWarning
|
||||
className={`${plexSans.variable} ${plexMono.variable}`}
|
||||
>
|
||||
<head>
|
||||
{/* The studio defaults to dark; apply the stored choice before paint. */}
|
||||
<script
|
||||
id="theme-init-script"
|
||||
suppressHydrationWarning
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `(function(){var dark=true;try{dark=localStorage.getItem('theme')!=='light'}catch(e){}if(dark)document.documentElement.classList.add('dark')})()`,
|
||||
}}
|
||||
/>
|
||||
</head>
|
||||
<body className="antialiased">
|
||||
<AppShell>{children}</AppShell>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function Page() {
|
||||
redirect('/finetuning');
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function Page() {
|
||||
redirect('/inference');
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HeaderActionsProvider } from '@/components/shell/HeaderActionsContext';
|
||||
import { resetToDefaults, updateOption } from '@/stores/defaultOptions';
|
||||
|
||||
import SettingsPage from './page';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
getModels: vi.fn().mockResolvedValue([]),
|
||||
getSettings: vi.fn().mockResolvedValue({}),
|
||||
updateSettings: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
|
||||
// Keep the real store (so `useStore` resolves) but spy on the mutators.
|
||||
vi.mock('@/stores/defaultOptions', async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import('@/stores/defaultOptions')>();
|
||||
return {
|
||||
...actual,
|
||||
updateOption: vi.fn(),
|
||||
resetToDefaults: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function renderPage() {
|
||||
return render(
|
||||
<HeaderActionsProvider>
|
||||
<SettingsPage />
|
||||
</HeaderActionsProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('Settings page', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('calls updateOption when a toggle changes', () => {
|
||||
renderPage();
|
||||
fireEvent.click(
|
||||
screen.getByRole('switch', { name: 'Auto Start Job on Create' }),
|
||||
);
|
||||
expect(updateOption).toHaveBeenCalledWith('autoStartJob', true);
|
||||
});
|
||||
|
||||
it('calls updateOption when a slider changes', () => {
|
||||
renderPage();
|
||||
// First slider in DOM order is "Frames".
|
||||
const slider = screen.getAllByRole('slider')[0];
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' });
|
||||
expect(updateOption).toHaveBeenCalledWith('numFrames', expect.any(Number));
|
||||
});
|
||||
|
||||
it('calls resetToDefaults when Reset to Defaults is clicked', () => {
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reset to Defaults' }));
|
||||
expect(resetToDefaults).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,358 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import {
|
||||
FieldRow,
|
||||
NumberRow,
|
||||
SliderRow,
|
||||
ToggleRow,
|
||||
} from '@/components/form-rows';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { NativeSelect } from '@/components/ui/native-select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import { getModels, type Model } from '@/lib/api';
|
||||
import {
|
||||
defaultOptionsStore,
|
||||
resetToDefaults,
|
||||
updateOption,
|
||||
} from '@/stores/defaultOptions';
|
||||
|
||||
function TextSettingRow({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
placeholder,
|
||||
onCommit,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
placeholder?: string;
|
||||
onCommit: (v: string) => void;
|
||||
}) {
|
||||
// Buffer keystrokes locally and persist on blur/Enter so each character
|
||||
// doesn't fire a settings PUT (or a localStorage write).
|
||||
const [draft, setDraft] = React.useState<string | null>(null);
|
||||
return (
|
||||
<FieldRow htmlFor={id} label={label}>
|
||||
<Input
|
||||
id={id}
|
||||
type="text"
|
||||
className="font-mono text-sm"
|
||||
value={draft ?? value}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={() => {
|
||||
if (draft !== null && draft !== value) onCommit(draft);
|
||||
setDraft(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectRow({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
children,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<FieldRow htmlFor={id} label={label}>
|
||||
<NativeSelect
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
>
|
||||
{children}
|
||||
</NativeSelect>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { options } = useStore(defaultOptionsStore);
|
||||
|
||||
const [models, setModels] = React.useState<
|
||||
Record<'t2v' | 'i2v' | 't2i', Model[]>
|
||||
>({ t2v: [], i2v: [], t2i: [] });
|
||||
|
||||
React.useEffect(() => {
|
||||
Promise.all([getModels('t2v'), getModels('i2v'), getModels('t2i')])
|
||||
.then(([t2v, i2v, t2i]) => setModels({ t2v, i2v, t2i }))
|
||||
.catch((e) => console.error('Failed to load models:', e));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[850px] flex-col gap-6 px-4 pb-12 pt-6">
|
||||
<Card>
|
||||
<CardContent className="space-y-4 p-6">
|
||||
<h2 className="text-lg font-semibold">Behavior</h2>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label
|
||||
htmlFor="settings-auto-start-job"
|
||||
className="pl-0.5 text-xs font-normal tracking-wide text-muted-foreground"
|
||||
>
|
||||
Auto Start Job on Create
|
||||
</Label>
|
||||
<Switch
|
||||
id="settings-auto-start-job"
|
||||
checked={options.autoStartJob}
|
||||
onCheckedChange={(v) => updateOption('autoStartJob', v)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<h2 className="text-lg font-semibold">Paths</h2>
|
||||
<div className="space-y-4">
|
||||
<TextSettingRow
|
||||
id="settings-api-server-base-url"
|
||||
label="API Server Base URL"
|
||||
value={options.apiServerBaseUrl ?? ''}
|
||||
onCommit={(v) => updateOption('apiServerBaseUrl', v)}
|
||||
placeholder="http://localhost:8189/api"
|
||||
/>
|
||||
<TextSettingRow
|
||||
id="settings-dataset-upload-path"
|
||||
label="Dataset Upload Path"
|
||||
value={options.datasetUploadPath ?? ''}
|
||||
onCommit={(v) => updateOption('datasetUploadPath', v)}
|
||||
placeholder="outputs/ui_data/uploads/datasets"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Default Options</h2>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={resetToDefaults}
|
||||
>
|
||||
Reset to Defaults
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
These values are used as defaults when creating new jobs.
|
||||
</p>
|
||||
|
||||
<div className="grid gap-x-3 gap-y-2 [grid-template-columns:repeat(auto-fill,minmax(160px,1fr))]">
|
||||
<SelectRow
|
||||
id="settings-default-model-t2v"
|
||||
label="Default Model (T2V)"
|
||||
value={options.defaultModelIdT2v}
|
||||
onChange={(v) => updateOption('defaultModelIdT2v', v)}
|
||||
>
|
||||
<option value="">None (select when creating job)</option>
|
||||
{models.t2v.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label} ({model.id})
|
||||
</option>
|
||||
))}
|
||||
</SelectRow>
|
||||
<SelectRow
|
||||
id="settings-default-model-i2v"
|
||||
label="Default Model (I2V)"
|
||||
value={options.defaultModelIdI2v}
|
||||
onChange={(v) => updateOption('defaultModelIdI2v', v)}
|
||||
>
|
||||
<option value="">None</option>
|
||||
{models.i2v.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label} ({model.id})
|
||||
</option>
|
||||
))}
|
||||
</SelectRow>
|
||||
<SelectRow
|
||||
id="settings-default-model-t2i"
|
||||
label="Default Model (T2I)"
|
||||
value={options.defaultModelIdT2i}
|
||||
onChange={(v) => updateOption('defaultModelIdT2i', v)}
|
||||
>
|
||||
<option value="">None</option>
|
||||
{models.t2i.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label} ({model.id})
|
||||
</option>
|
||||
))}
|
||||
</SelectRow>
|
||||
|
||||
<SliderRow
|
||||
id="settings-num-frames"
|
||||
label="Frames"
|
||||
min={1}
|
||||
max={500}
|
||||
step={1}
|
||||
value={options.numFrames}
|
||||
onChange={(v) => updateOption('numFrames', v)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-height"
|
||||
label="Height"
|
||||
min={64}
|
||||
max={1080}
|
||||
step={16}
|
||||
value={options.height}
|
||||
onChange={(v) => updateOption('height', v)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-width"
|
||||
label="Width"
|
||||
min={64}
|
||||
max={1920}
|
||||
step={16}
|
||||
value={options.width}
|
||||
onChange={(v) => updateOption('width', v)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-num-steps"
|
||||
label="Inference Steps"
|
||||
min={1}
|
||||
max={200}
|
||||
step={1}
|
||||
value={options.numInferenceSteps}
|
||||
onChange={(v) => updateOption('numInferenceSteps', v)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-vsa-sparsity"
|
||||
label="VSA Sparsity"
|
||||
title="VSA sparsity (0–1)"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={options.vsaSparsity}
|
||||
onChange={(v) => updateOption('vsaSparsity', v)}
|
||||
format={(v) => v.toFixed(2)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-guidance"
|
||||
label="Guidance Scale"
|
||||
min={0}
|
||||
max={20}
|
||||
step={0.1}
|
||||
value={options.guidanceScale}
|
||||
onChange={(v) => updateOption('guidanceScale', v)}
|
||||
format={(v) => v.toFixed(1)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-guidance-rescale"
|
||||
label="Guidance Rescale"
|
||||
title="0 = disabled"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={options.guidanceRescale ?? 0}
|
||||
onChange={(v) => updateOption('guidanceRescale', v)}
|
||||
format={(v) => v.toFixed(2)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-tp-size"
|
||||
label="TP Size"
|
||||
title="-1 = auto"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={options.tpSize}
|
||||
onChange={(v) => updateOption('tpSize', v)}
|
||||
format={(v) => (v === -1 ? 'Auto' : String(v))}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-sp-size"
|
||||
label="SP Size"
|
||||
title="-1 = auto"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={options.spSize}
|
||||
onChange={(v) => updateOption('spSize', v)}
|
||||
format={(v) => (v === -1 ? 'Auto' : String(v))}
|
||||
/>
|
||||
<SliderRow
|
||||
id="settings-fps"
|
||||
label="FPS"
|
||||
min={1}
|
||||
max={60}
|
||||
step={1}
|
||||
value={options.fps ?? 24}
|
||||
onChange={(v) => updateOption('fps', v)}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
id="settings-dit-cpu-offload"
|
||||
label="DiT CPU Offload"
|
||||
checked={options.ditCpuOffload}
|
||||
onChange={(v) => updateOption('ditCpuOffload', v)}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="settings-text-encoder-cpu-offload"
|
||||
label="Text Encoder CPU Offload"
|
||||
checked={options.textEncoderCpuOffload}
|
||||
onChange={(v) => updateOption('textEncoderCpuOffload', v)}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="settings-use-fsdp-inference"
|
||||
label="Use FSDP Inference"
|
||||
checked={options.useFsdpInference}
|
||||
onChange={(v) => updateOption('useFsdpInference', v)}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="settings-vae-cpu-offload"
|
||||
label="VAE CPU Offload"
|
||||
checked={options.vaeCpuOffload}
|
||||
onChange={(v) => updateOption('vaeCpuOffload', v)}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="settings-image-encoder-cpu-offload"
|
||||
label="Image Encoder CPU Offload"
|
||||
checked={options.imageEncoderCpuOffload}
|
||||
onChange={(v) => updateOption('imageEncoderCpuOffload', v)}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="settings-enable-torch-compile"
|
||||
label="Torch Compile"
|
||||
checked={options.enableTorchCompile}
|
||||
onChange={(v) => updateOption('enableTorchCompile', v)}
|
||||
/>
|
||||
|
||||
<SliderRow
|
||||
id="settings-num-gpus"
|
||||
label="GPUs"
|
||||
min={1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={options.numGpus}
|
||||
onChange={(v) => updateOption('numGpus', v)}
|
||||
/>
|
||||
|
||||
<NumberRow
|
||||
id="settings-seed"
|
||||
label="Seed"
|
||||
min={0}
|
||||
value={options.seed}
|
||||
onChange={(v) => updateOption('seed', v)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { setCreateDatasetModalOpen } from '@/stores/createDatasetModalOpen';
|
||||
|
||||
export default function AddDatasetButton() {
|
||||
return (
|
||||
<Button type="button" onClick={() => setCreateDatasetModalOpen(true)}>
|
||||
Add Dataset
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
|
||||
import CreateDatasetModal from '@/components/datasets/CreateDatasetModal';
|
||||
import { createDataset } from '@/lib/api';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
createDataset: vi.fn(),
|
||||
uploadRawDataset: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedCreateDataset = vi.mocked(createDataset);
|
||||
|
||||
describe('CreateDatasetModal', () => {
|
||||
it('renders nothing when closed', () => {
|
||||
render(
|
||||
<CreateDatasetModal isOpen={false} onClose={() => {}} onSuccess={() => {}} />,
|
||||
);
|
||||
expect(screen.queryByText('Add Dataset — Raw')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the form and the default JSON caption upload when open', () => {
|
||||
render(
|
||||
<CreateDatasetModal isOpen onClose={() => {}} onSuccess={() => {}} />,
|
||||
);
|
||||
expect(screen.getByText('Add Dataset — Raw')).toBeInTheDocument();
|
||||
expect(screen.getByText('Upload video files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Upload videos2caption.json')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Create Dataset' }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not create a dataset when the name is empty', () => {
|
||||
const onSuccess = vi.fn();
|
||||
render(
|
||||
<CreateDatasetModal isOpen onClose={() => {}} onSuccess={onSuccess} />,
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create Dataset' }));
|
||||
expect(mockedCreateDataset).not.toHaveBeenCalled();
|
||||
expect(onSuccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,465 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import UploadZone from '@/components/datasets/UploadZone';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { createDataset, uploadRawDataset } from '@/lib/api';
|
||||
import {
|
||||
parseCaptionCsv,
|
||||
parseVideos2Caption,
|
||||
parseVideosCaptionsTxt,
|
||||
} from '@/lib/captionParsing';
|
||||
|
||||
const ALLOWED_VIDEO_EXT = '.mp4,.webm,.avi,.mov,.mkv';
|
||||
|
||||
type CaptionFormat = 'json' | 'txt' | 'csv';
|
||||
|
||||
export interface CreateDatasetModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function CreateDatasetModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: CreateDatasetModalProps) {
|
||||
const [name, setName] = React.useState('');
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const [rawPath, setRawPath] = React.useState('');
|
||||
const [fileNames, setFileNames] = React.useState<string[]>([]);
|
||||
const [isUploading, setIsUploading] = React.useState(false);
|
||||
const [validationError, setValidationError] = React.useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [captionFormat, setCaptionFormat] = React.useState<CaptionFormat>('json');
|
||||
const [captionMap, setCaptionMap] = React.useState<Record<
|
||||
string,
|
||||
string
|
||||
> | null>(null);
|
||||
const [captionFileName, setCaptionFileName] = React.useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [videosTxtLines, setVideosTxtLines] = React.useState<string[] | null>(
|
||||
null,
|
||||
);
|
||||
const [videosTxtFileName, setVideosTxtFileName] = React.useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [captionsTxtLines, setCaptionsTxtLines] = React.useState<
|
||||
string[] | null
|
||||
>(null);
|
||||
const [captionsTxtFileName, setCaptionsTxtFileName] = React.useState<
|
||||
string | null
|
||||
>(null);
|
||||
// Bumped on every new media selection and on reset/clear; an in-flight
|
||||
// upload whose generation no longer matches is discarded, so a superseded or
|
||||
// abandoned upload can't repopulate/overwrite state.
|
||||
const uploadGeneration = React.useRef(0);
|
||||
|
||||
const txtCaptionMap = React.useMemo(() => {
|
||||
if (!captionsTxtLines || fileNames.length === 0) return null;
|
||||
const { captions, error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines ?? null,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
if (error) return null;
|
||||
return Object.keys(captions).length > 0 ? captions : null;
|
||||
}, [captionsTxtLines, fileNames, videosTxtLines]);
|
||||
|
||||
const effectiveCaptionMap =
|
||||
captionFormat === 'txt' ? txtCaptionMap : captionMap;
|
||||
|
||||
// Keep the validation message in sync with the TXT inputs.
|
||||
React.useEffect(() => {
|
||||
if (captionFormat === 'txt' && captionsTxtLines && fileNames.length > 0) {
|
||||
const hasVideosTxt =
|
||||
!!videosTxtLines &&
|
||||
videosTxtLines.length > 0 &&
|
||||
videosTxtLines.some((s) => s.trim());
|
||||
if (hasVideosTxt && videosTxtLines) {
|
||||
const { error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
setValidationError(error);
|
||||
} else {
|
||||
setValidationError(null);
|
||||
}
|
||||
}
|
||||
}, [captionFormat, captionsTxtLines, fileNames, videosTxtLines]);
|
||||
|
||||
function resetState() {
|
||||
uploadGeneration.current += 1;
|
||||
setName('');
|
||||
setRawPath('');
|
||||
setFileNames([]);
|
||||
setValidationError(null);
|
||||
setCaptionFormat('json');
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
setVideosTxtLines(null);
|
||||
setVideosTxtFileName(null);
|
||||
setCaptionsTxtLines(null);
|
||||
setCaptionsTxtFileName(null);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (isSubmitting) return;
|
||||
resetState();
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleMediaChange(files: File[]) {
|
||||
const gen = (uploadGeneration.current += 1);
|
||||
setValidationError(null);
|
||||
if (files.length === 0) {
|
||||
setRawPath('');
|
||||
setFileNames([]);
|
||||
return;
|
||||
}
|
||||
setIsUploading(true);
|
||||
try {
|
||||
const res = await uploadRawDataset(files);
|
||||
if (gen !== uploadGeneration.current) return; // superseded or abandoned
|
||||
setRawPath(res.path);
|
||||
setFileNames(res.file_names);
|
||||
if (res.file_names.length === 0) {
|
||||
setValidationError(`No video files found. Allowed: ${ALLOWED_VIDEO_EXT}`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (gen !== uploadGeneration.current) return;
|
||||
setRawPath('');
|
||||
setFileNames([]);
|
||||
setValidationError(err instanceof Error ? err.message : 'Upload failed');
|
||||
} finally {
|
||||
if (gen === uploadGeneration.current) setIsUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCaptionJsonChange(files: File[]) {
|
||||
setValidationError(null);
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
if (files.length === 0) return;
|
||||
const file = files[0];
|
||||
try {
|
||||
const text = await file.text();
|
||||
const { captions, error } = parseVideos2Caption(text, fileNames);
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
return;
|
||||
}
|
||||
setCaptionMap(captions);
|
||||
setCaptionFileName(file.name);
|
||||
} catch {
|
||||
setValidationError('Could not read the file.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCaptionCsvChange(files: File[]) {
|
||||
setValidationError(null);
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
if (files.length === 0) return;
|
||||
const file = files[0];
|
||||
try {
|
||||
const text = await file.text();
|
||||
const { captions, error } = parseCaptionCsv(text, fileNames);
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
return;
|
||||
}
|
||||
setCaptionMap(captions);
|
||||
setCaptionFileName(file.name);
|
||||
} catch {
|
||||
setValidationError('Could not read the file.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVideosTxtChange(files: File[]) {
|
||||
setValidationError(null);
|
||||
setVideosTxtLines(null);
|
||||
setVideosTxtFileName(null);
|
||||
if (files.length === 0) return;
|
||||
try {
|
||||
const text = await files[0].text();
|
||||
setVideosTxtLines(text.split(/\r?\n/).map((s) => s.trim()));
|
||||
setVideosTxtFileName(files[0].name);
|
||||
} catch {
|
||||
setValidationError('Could not read videos.txt.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCaptionsTxtChange(files: File[]) {
|
||||
setValidationError(null);
|
||||
setCaptionsTxtLines(null);
|
||||
setCaptionsTxtFileName(null);
|
||||
if (files.length === 0) return;
|
||||
try {
|
||||
const text = await files[0].text();
|
||||
setCaptionsTxtLines(text.split(/\r?\n/).map((s) => s.trim()));
|
||||
setCaptionsTxtFileName(files[0].name);
|
||||
} catch {
|
||||
setValidationError('Could not read captions.txt.');
|
||||
}
|
||||
}
|
||||
|
||||
function handleCaptionFormatChange(format: CaptionFormat) {
|
||||
setCaptionFormat(format);
|
||||
setValidationError(null);
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
setVideosTxtLines(null);
|
||||
setVideosTxtFileName(null);
|
||||
setCaptionsTxtLines(null);
|
||||
setCaptionsTxtFileName(null);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setValidationError(null);
|
||||
if (!name.trim()) return;
|
||||
if (!rawPath || fileNames.length === 0) {
|
||||
setValidationError('No data was found. Upload at least one video.');
|
||||
return;
|
||||
}
|
||||
if (captionFormat === 'json' || captionFormat === 'csv') {
|
||||
if (captionFileName && !captionMap) {
|
||||
setValidationError(
|
||||
'Caption file has errors. Fix or remove it before creating the dataset.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else if (captionFormat === 'txt') {
|
||||
if (videosTxtFileName || captionsTxtFileName) {
|
||||
if (!captionsTxtFileName) {
|
||||
setValidationError('Upload captions.txt to use TXT captions.');
|
||||
return;
|
||||
}
|
||||
// Re-validate against current state rather than the stale render-time
|
||||
// `validationError`, so a videos.txt mismatch both blocks submission
|
||||
// and keeps its message visible.
|
||||
const hasVideosTxt =
|
||||
!!videosTxtLines &&
|
||||
videosTxtLines.length > 0 &&
|
||||
videosTxtLines.some((s) => s.trim());
|
||||
if (hasVideosTxt && videosTxtLines) {
|
||||
const { error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines,
|
||||
captionsTxtLines ?? [],
|
||||
fileNames,
|
||||
);
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const finalCaptionMap =
|
||||
effectiveCaptionMap && Object.keys(effectiveCaptionMap).length > 0
|
||||
? effectiveCaptionMap
|
||||
: null;
|
||||
if (finalCaptionMap) {
|
||||
const missing = fileNames.filter((fn) => !(fn in finalCaptionMap));
|
||||
if (missing.length > 0) {
|
||||
const list =
|
||||
missing.length <= 5
|
||||
? missing.join(', ')
|
||||
: `${missing.slice(0, 5).join(', ')} and ${missing.length - 5} more`;
|
||||
const ok = window.confirm(
|
||||
`The caption file does not include captions for ${missing.length} video(s): ${list}. They will get empty captions. Continue?`,
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await createDataset({
|
||||
name: name.trim(),
|
||||
upload_path: rawPath,
|
||||
file_names: fileNames,
|
||||
...(finalCaptionMap ? { captions: finalCaptionMap } : {}),
|
||||
});
|
||||
onSuccess();
|
||||
resetState();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setValidationError(
|
||||
err instanceof Error ? err.message : 'Failed to create dataset',
|
||||
);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) handleClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
aria-describedby={undefined}
|
||||
className="max-h-[90vh] w-[90vw] max-w-[850px] overflow-y-auto"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Dataset — Raw</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} autoComplete="off">
|
||||
<div className="mb-3.5 flex flex-col gap-1.5">
|
||||
<Label htmlFor="add-dataset-name">Name</Label>
|
||||
<Input
|
||||
id="add-dataset-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="My dataset"
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-3.5 flex flex-col gap-1.5">
|
||||
<Label>Videos</Label>
|
||||
<UploadZone
|
||||
label="Upload video files"
|
||||
hint="Select files or a folder (.mp4, .webm, .avi, .mov, .mkv)"
|
||||
accept={ALLOWED_VIDEO_EXT}
|
||||
multiple
|
||||
directory
|
||||
allowBothFileAndDirectory
|
||||
value={rawPath}
|
||||
fileName={
|
||||
fileNames.length > 0 ? `${fileNames.length} file(s)` : undefined
|
||||
}
|
||||
onFiles={handleMediaChange}
|
||||
onClear={() => {
|
||||
uploadGeneration.current += 1;
|
||||
setRawPath('');
|
||||
setFileNames([]);
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
setValidationError(null);
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
uploading={isUploading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-3.5 flex flex-col gap-1.5">
|
||||
<Tabs
|
||||
value={captionFormat}
|
||||
onValueChange={(value) =>
|
||||
handleCaptionFormatChange(value as CaptionFormat)
|
||||
}
|
||||
>
|
||||
<div className="mb-1.5 flex flex-wrap items-center gap-4">
|
||||
<Label>Captions (optional)</Label>
|
||||
<TabsList>
|
||||
<TabsTrigger value="json" disabled={isSubmitting}>
|
||||
JSON
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="txt" disabled={isSubmitting}>
|
||||
TXT
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="csv" disabled={isSubmitting}>
|
||||
CSV
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
<TabsContent value="json">
|
||||
<UploadZone
|
||||
label="Upload videos2caption.json"
|
||||
hint="Array of { path, cap } or object mapping file names to captions"
|
||||
accept=".json,application/json"
|
||||
value={captionFileName ? '1' : ''}
|
||||
fileName={captionFileName ?? undefined}
|
||||
onFiles={handleCaptionJsonChange}
|
||||
onClear={() => {
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
setValidationError(null);
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="txt">
|
||||
<div className="flex flex-wrap gap-[15px] [&>*]:min-w-[200px] [&>*]:flex-1">
|
||||
<UploadZone
|
||||
label="Upload videos.txt (optional)"
|
||||
hint="One video path per line, or leave empty to match captions to videos in alphabetical order"
|
||||
accept=".txt,text/plain"
|
||||
value={videosTxtFileName ? '1' : ''}
|
||||
fileName={videosTxtFileName ?? undefined}
|
||||
onFiles={handleVideosTxtChange}
|
||||
onClear={() => {
|
||||
setVideosTxtLines(null);
|
||||
setVideosTxtFileName(null);
|
||||
setValidationError(null);
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<UploadZone
|
||||
label="Upload captions.txt"
|
||||
hint="One caption per line (same order as videos.txt or alphabetical)"
|
||||
accept=".txt,text/plain"
|
||||
value={captionsTxtFileName ? '1' : ''}
|
||||
fileName={captionsTxtFileName ?? undefined}
|
||||
onFiles={handleCaptionsTxtChange}
|
||||
onClear={() => {
|
||||
setCaptionsTxtLines(null);
|
||||
setCaptionsTxtFileName(null);
|
||||
setValidationError(null);
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="csv">
|
||||
<UploadZone
|
||||
label="Upload captions CSV"
|
||||
hint="Header: video_name, caption"
|
||||
accept=".csv,text/csv"
|
||||
value={captionFileName ? '1' : ''}
|
||||
fileName={captionFileName ?? undefined}
|
||||
onFiles={handleCaptionCsvChange}
|
||||
onClear={() => {
|
||||
setCaptionMap(null);
|
||||
setCaptionFileName(null);
|
||||
setValidationError(null);
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{validationError && (
|
||||
<p className="mb-2 text-sm text-destructive">{validationError}</p>
|
||||
)}
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Creating…' : 'Create Dataset'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
|
||||
import DatasetCard from '@/components/datasets/DatasetCard';
|
||||
import { deleteDataset } from '@/lib/api';
|
||||
import type { Dataset } from '@/lib/api';
|
||||
import { setActiveDatasetId } from '@/stores/activeDataset';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
deleteDataset: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedDeleteDataset = vi.mocked(deleteDataset);
|
||||
|
||||
const dataset: Dataset = {
|
||||
id: 'ds-1',
|
||||
name: 'My Dataset',
|
||||
created_at: 0,
|
||||
file_count: 3,
|
||||
size_bytes: 2048,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
setActiveDatasetId(null);
|
||||
});
|
||||
|
||||
describe('DatasetCard', () => {
|
||||
it('renders the name, file count and human-readable size', () => {
|
||||
render(<DatasetCard dataset={dataset} onUpdated={() => {}} />);
|
||||
expect(screen.getByText('My Dataset')).toBeInTheDocument();
|
||||
expect(screen.getByText('3 files · 2.0 KB')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses the singular "file" label and byte units for a small dataset', () => {
|
||||
render(
|
||||
<DatasetCard
|
||||
dataset={{ ...dataset, file_count: 1, size_bytes: 512 }}
|
||||
onUpdated={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('1 file · 512 B')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onSelect when the card body is clicked', () => {
|
||||
const onSelect = vi.fn();
|
||||
render(
|
||||
<DatasetCard dataset={dataset} onUpdated={() => {}} onSelect={onSelect} />,
|
||||
);
|
||||
fireEvent.click(screen.getByText('My Dataset'));
|
||||
expect(onSelect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('deletes after confirmation and notifies the parent without selecting', async () => {
|
||||
const onUpdated = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
mockedDeleteDataset.mockResolvedValue(undefined);
|
||||
|
||||
render(
|
||||
<DatasetCard
|
||||
dataset={dataset}
|
||||
onUpdated={onUpdated}
|
||||
onSelect={onSelect}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(confirmSpy).toHaveBeenCalledWith('Delete dataset "My Dataset"?');
|
||||
expect(mockedDeleteDataset).toHaveBeenCalledWith('ds-1');
|
||||
await waitFor(() => expect(onUpdated).toHaveBeenCalledTimes(1));
|
||||
expect(onSelect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('selects on keyboard activation of the card body but not of the Delete button', () => {
|
||||
const onSelect = vi.fn();
|
||||
render(
|
||||
<DatasetCard dataset={dataset} onUpdated={() => {}} onSelect={onSelect} />,
|
||||
);
|
||||
|
||||
// Activating the Delete button must not bubble into a card selection.
|
||||
fireEvent.keyDown(screen.getByRole('button', { name: 'Delete' }), {
|
||||
key: 'Enter',
|
||||
});
|
||||
expect(onSelect).not.toHaveBeenCalled();
|
||||
|
||||
// Activating the card body itself does select.
|
||||
fireEvent.keyDown(screen.getByText('My Dataset'), { key: 'Enter' });
|
||||
expect(onSelect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not delete when the user cancels the confirm dialog', () => {
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(false);
|
||||
render(<DatasetCard dataset={dataset} onUpdated={() => {}} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(mockedDeleteDataset).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies selected styling when it is the active dataset', () => {
|
||||
setActiveDatasetId('ds-1');
|
||||
const { container } = render(
|
||||
<DatasetCard dataset={dataset} onUpdated={() => {}} />,
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('border-accent-blue', 'bg-accent-blue/5');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { deleteDataset } from '@/lib/api';
|
||||
import type { Dataset } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { activeDatasetStore, setActiveDatasetId } from '@/stores/activeDataset';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
|
||||
function formatSize(sizeBytes: number): string {
|
||||
if (sizeBytes < 1024) return `${sizeBytes} B`;
|
||||
if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(1)} KB`;
|
||||
if (sizeBytes < 1024 * 1024 * 1024) {
|
||||
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
return `${(sizeBytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
export default function DatasetCard({
|
||||
dataset,
|
||||
onUpdated,
|
||||
onSelect = () => {},
|
||||
}: {
|
||||
dataset: Dataset;
|
||||
onUpdated: () => void;
|
||||
onSelect?: () => void;
|
||||
}) {
|
||||
const { activeDatasetId } = useStore(activeDatasetStore);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
|
||||
const isSelected = activeDatasetId === dataset.id;
|
||||
const fileCount = dataset.file_count ?? 0;
|
||||
const sizeLabel = formatSize(dataset.size_bytes ?? 0);
|
||||
|
||||
async function handleDelete(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading) return;
|
||||
if (!window.confirm(`Delete dataset "${dataset.name}"?`)) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await deleteDataset(dataset.id);
|
||||
if (activeDatasetStore.get().activeDatasetId === dataset.id) {
|
||||
setActiveDatasetId(null);
|
||||
}
|
||||
onUpdated();
|
||||
} catch (err) {
|
||||
window.alert(
|
||||
err instanceof Error ? err.message : 'Failed to delete dataset',
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if ((e.target as HTMLElement).closest('button')) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onSelect();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'mb-3 flex cursor-pointer flex-col gap-[0.6rem] rounded-lg border border-border bg-background px-[1.15rem] py-4',
|
||||
isSelected && 'border-accent-blue bg-accent-blue/5',
|
||||
)}
|
||||
onClick={(e) => {
|
||||
if ((e.target as HTMLElement).closest('button')) return;
|
||||
onSelect();
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-[0.95rem] font-semibold">{dataset.name}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{fileCount} {fileCount === 1 ? 'file' : 'files'} · {sizeLabel}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
|
||||
import DatasetSidebar from '@/components/datasets/DatasetSidebar';
|
||||
import * as api from '@/lib/api';
|
||||
import type { Dataset } from '@/lib/api';
|
||||
|
||||
vi.mock('@/lib/api');
|
||||
|
||||
const mockedApi = vi.mocked(api);
|
||||
|
||||
const dataset: Dataset = {
|
||||
id: 'ds-1',
|
||||
name: 'My Dataset',
|
||||
created_at: 0,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockedApi.getDatasetFiles.mockResolvedValue({
|
||||
file_names: ['a.mp4', 'b.mp4'],
|
||||
captions: { 'a.mp4': 'cap a', 'b.mp4': '' },
|
||||
});
|
||||
mockedApi.getDatasetMediaUrl.mockImplementation(
|
||||
(id, fileName) => `http://test/${id}/${fileName}`,
|
||||
);
|
||||
mockedApi.updateDatasetCaption.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe('DatasetSidebar', () => {
|
||||
it('lists dataset files after loading', async () => {
|
||||
render(<DatasetSidebar dataset={dataset} onClose={() => {}} />);
|
||||
|
||||
// The first file's caption is rendered once loading resolves.
|
||||
expect(await screen.findByDisplayValue('cap a')).toBeInTheDocument();
|
||||
expect(mockedApi.getDatasetFiles).toHaveBeenCalledWith('ds-1');
|
||||
|
||||
// One caption editor per returned file.
|
||||
const captionFields = screen.getAllByPlaceholderText('Caption');
|
||||
expect(captionFields).toHaveLength(2);
|
||||
|
||||
// Media URLs are requested per visible file.
|
||||
expect(mockedApi.getDatasetMediaUrl).toHaveBeenCalledWith('ds-1', 'a.mp4');
|
||||
expect(mockedApi.getDatasetMediaUrl).toHaveBeenCalledWith('ds-1', 'b.mp4');
|
||||
});
|
||||
|
||||
it('debounces caption save by 500ms', async () => {
|
||||
render(<DatasetSidebar dataset={dataset} onClose={() => {}} />);
|
||||
const textarea = await screen.findByDisplayValue('cap a');
|
||||
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
fireEvent.change(textarea, { target: { value: 'updated caption' } });
|
||||
|
||||
// Nothing saved immediately or just before the debounce window closes.
|
||||
expect(mockedApi.updateDatasetCaption).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(499);
|
||||
});
|
||||
expect(mockedApi.updateDatasetCaption).not.toHaveBeenCalled();
|
||||
|
||||
// Saved exactly once after the full 500ms.
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1);
|
||||
});
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledWith(
|
||||
'ds-1',
|
||||
'a.mp4',
|
||||
'updated caption',
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('coalesces rapid edits into a single debounced save', async () => {
|
||||
render(<DatasetSidebar dataset={dataset} onClose={() => {}} />);
|
||||
const textarea = await screen.findByDisplayValue('cap a');
|
||||
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
fireEvent.change(textarea, { target: { value: 'one' } });
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
fireEvent.change(textarea, { target: { value: 'two' } });
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledWith(
|
||||
'ds-1',
|
||||
'a.mp4',
|
||||
'two',
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('debounces per file: editing another caption does not cancel a pending save', async () => {
|
||||
render(<DatasetSidebar dataset={dataset} onClose={() => {}} />);
|
||||
await screen.findByDisplayValue('cap a');
|
||||
const [textareaA, textareaB] = screen.getAllByPlaceholderText('Caption');
|
||||
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
fireEvent.change(textareaA, { target: { value: 'new cap a' } });
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
// Editing b.mp4 inside a.mp4's debounce window must not drop a's save.
|
||||
fireEvent.change(textareaB, { target: { value: 'new cap b' } });
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledTimes(2);
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledWith(
|
||||
'ds-1',
|
||||
'a.mp4',
|
||||
'new cap a',
|
||||
);
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledWith(
|
||||
'ds-1',
|
||||
'b.mp4',
|
||||
'new cap b',
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('flushes a pending save on unmount instead of dropping it', async () => {
|
||||
const { unmount } = render(
|
||||
<DatasetSidebar dataset={dataset} onClose={() => {}} />,
|
||||
);
|
||||
const textarea = await screen.findByDisplayValue('cap a');
|
||||
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
fireEvent.change(textarea, { target: { value: 'edited just before close' } });
|
||||
unmount();
|
||||
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.updateDatasetCaption).toHaveBeenCalledWith(
|
||||
'ds-1',
|
||||
'a.mp4',
|
||||
'edited just before close',
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
import DownloadCaptions from '@/components/datasets/DownloadCaptions';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useResizable } from '@/hooks/useResizable';
|
||||
import {
|
||||
getDatasetFiles,
|
||||
getDatasetMediaUrl,
|
||||
updateDatasetCaption,
|
||||
type Dataset,
|
||||
} from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 320;
|
||||
const SIDEBAR_MAX_WIDTH = 900;
|
||||
const INITIAL_PAGE_SIZE = 24;
|
||||
const PAGE_SIZE = 24;
|
||||
const SCROLL_THRESHOLD = 200;
|
||||
|
||||
// Memoized so a caption keystroke re-renders only the edited card, not every
|
||||
// visible <video> in the grid (visibleCount grows unbounded with scrolling).
|
||||
const DatasetFileCard = React.memo(function DatasetFileCard({
|
||||
fileName,
|
||||
mediaUrl,
|
||||
caption,
|
||||
thumbLoaded,
|
||||
onCaptionChange,
|
||||
onThumbLoaded,
|
||||
}: {
|
||||
fileName: string;
|
||||
mediaUrl: string;
|
||||
caption: string;
|
||||
thumbLoaded: boolean;
|
||||
onCaptionChange: (fileName: string, value: string) => void;
|
||||
onThumbLoaded: (fileName: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="relative flex flex-col overflow-hidden rounded-lg border border-border bg-background">
|
||||
{!thumbLoaded && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-background/70">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground/40 border-t-accent-blue" />
|
||||
</div>
|
||||
)}
|
||||
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
|
||||
<video
|
||||
src={mediaUrl}
|
||||
className="aspect-video w-full bg-border object-cover"
|
||||
muted
|
||||
autoPlay
|
||||
loop
|
||||
playsInline
|
||||
onLoadedData={() => onThumbLoaded(fileName)}
|
||||
onError={() => onThumbLoaded(fileName)}
|
||||
/>
|
||||
<Textarea
|
||||
value={caption}
|
||||
onChange={(e) => onCaptionChange(fileName, e.target.value)}
|
||||
placeholder="Caption"
|
||||
rows={2}
|
||||
className="min-h-[2.5rem] resize-y rounded-none border-0 bg-transparent p-1.5 text-xs shadow-none focus-visible:border-transparent focus-visible:ring-0"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default function DatasetSidebar({
|
||||
dataset,
|
||||
onClose,
|
||||
onWidthChange,
|
||||
}: {
|
||||
dataset: Dataset;
|
||||
onClose: () => void;
|
||||
onWidthChange?: (w: number) => void;
|
||||
}) {
|
||||
const [width, setWidth] = React.useState(400);
|
||||
const [isDragging, setIsDragging] = React.useState(false);
|
||||
const [fileNames, setFileNames] = React.useState<string[]>([]);
|
||||
const [captions, setCaptions] = React.useState<Record<string, string>>({});
|
||||
const [visibleCount, setVisibleCount] = React.useState(INITIAL_PAGE_SIZE);
|
||||
const [isLoading, setIsLoading] = React.useState(true);
|
||||
const [thumbLoaded, setThumbLoaded] = React.useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
|
||||
// Pending debounced caption saves, keyed per file so editing one caption
|
||||
// can't cancel another file's pending save.
|
||||
const pendingSaves = React.useRef(
|
||||
new Map<string, { timer: ReturnType<typeof setTimeout>; save: () => void }>(),
|
||||
);
|
||||
const scrollRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
onWidthChange?.(width);
|
||||
}, [width, onWidthChange]);
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
getDatasetFiles(dataset.id)
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
setFileNames(data.file_names);
|
||||
setCaptions(data.captions);
|
||||
setVisibleCount(INITIAL_PAGE_SIZE);
|
||||
setThumbLoaded({});
|
||||
})
|
||||
.catch((err) => console.error('Failed to load dataset files:', err))
|
||||
.finally(() => {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [dataset.id]);
|
||||
|
||||
const flushPendingSaves = React.useCallback(() => {
|
||||
for (const { timer, save } of pendingSaves.current.values()) {
|
||||
clearTimeout(timer);
|
||||
save();
|
||||
}
|
||||
pendingSaves.current.clear();
|
||||
}, []);
|
||||
|
||||
// Flush (not drop) pending saves when the dataset changes or on unmount, so
|
||||
// an edit made within the debounce window of closing isn't lost.
|
||||
React.useEffect(() => flushPendingSaves, [dataset.id, flushPendingSaves]);
|
||||
|
||||
const { onMouseDown } = useResizable({
|
||||
edge: 'right',
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: setWidth,
|
||||
onDragChange: setIsDragging,
|
||||
});
|
||||
|
||||
const datasetId = dataset.id;
|
||||
const handleCaptionChange = React.useCallback(
|
||||
(fileName: string, value: string) => {
|
||||
setCaptions((prev) => ({ ...prev, [fileName]: value }));
|
||||
const pending = pendingSaves.current.get(fileName);
|
||||
if (pending) clearTimeout(pending.timer);
|
||||
const save = () => {
|
||||
updateDatasetCaption(datasetId, fileName, value).catch((err) =>
|
||||
console.error('Failed to save caption:', err),
|
||||
);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
pendingSaves.current.delete(fileName);
|
||||
save();
|
||||
}, 500);
|
||||
pendingSaves.current.set(fileName, { timer, save });
|
||||
},
|
||||
[datasetId],
|
||||
);
|
||||
|
||||
function handleScroll() {
|
||||
const el = scrollRef.current;
|
||||
if (!el || isLoading || visibleCount >= fileNames.length) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = el;
|
||||
const distanceFromBottom = scrollHeight - (scrollTop + clientHeight);
|
||||
if (distanceFromBottom < SCROLL_THRESHOLD) {
|
||||
setVisibleCount((c) => Math.min(c + PAGE_SIZE, fileNames.length));
|
||||
}
|
||||
}
|
||||
|
||||
// When the visible grid doesn't overflow (a wide/tall sidebar can fit the
|
||||
// first page without a scrollbar), no scroll event ever fires — so top up
|
||||
// visibleCount until it overflows or every file is shown. Re-runs on resize
|
||||
// (width) and after each page grows, otherwise files 25..N are unreachable.
|
||||
React.useEffect(() => {
|
||||
if (isLoading || visibleCount >= fileNames.length) return;
|
||||
const el = scrollRef.current;
|
||||
if (el && el.scrollHeight <= el.clientHeight) {
|
||||
setVisibleCount((c) => Math.min(c + PAGE_SIZE, fileNames.length));
|
||||
}
|
||||
}, [visibleCount, fileNames.length, isLoading, width]);
|
||||
|
||||
const markThumbLoaded = React.useCallback((fileName: string) => {
|
||||
setThumbLoaded((prev) =>
|
||||
prev[fileName] ? prev : { ...prev, [fileName]: true },
|
||||
);
|
||||
}, []);
|
||||
|
||||
const visibleFiles = fileNames.slice(0, visibleCount);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="fixed bottom-0 right-0 top-[var(--header-height)] z-50 flex max-h-[calc(100vh-var(--header-height))] min-w-[320px] shrink-0 flex-col border-l border-border bg-card"
|
||||
style={{ width, maxWidth: SIDEBAR_MAX_WIDTH }}
|
||||
>
|
||||
<div className="flex shrink-0 items-center justify-between border-b border-border px-5 py-4">
|
||||
<h2 className="m-0 min-w-0 truncate text-base font-semibold text-foreground">
|
||||
{dataset.name}
|
||||
</h2>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<DownloadCaptions fileNames={fileNames} captions={captions} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
title="Close"
|
||||
aria-label="Close"
|
||||
className="flex items-center justify-center rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<X className="h-[18px] w-[18px]" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={handleScroll}
|
||||
className="flex-1 overflow-y-auto p-4"
|
||||
>
|
||||
{isLoading ? (
|
||||
<p className="p-8 text-center text-muted-foreground">Loading…</p>
|
||||
) : fileNames.length === 0 ? (
|
||||
<p className="p-8 text-center text-muted-foreground">
|
||||
No media files
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(140px,1fr))]">
|
||||
{visibleFiles.map((fileName) => (
|
||||
<DatasetFileCard
|
||||
key={fileName}
|
||||
fileName={fileName}
|
||||
mediaUrl={getDatasetMediaUrl(dataset.id, fileName)}
|
||||
caption={captions[fileName] ?? ''}
|
||||
thumbLoaded={!!thumbLoaded[fileName]}
|
||||
onCaptionChange={handleCaptionChange}
|
||||
onThumbLoaded={markThumbLoaded}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="presentation"
|
||||
onMouseDown={onMouseDown}
|
||||
className={cn(
|
||||
'absolute bottom-0 left-0 top-0 z-[1] w-1.5 cursor-col-resize hover:bg-accent-blue/25',
|
||||
isDragging && 'bg-accent-blue/25',
|
||||
)}
|
||||
/>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
'use client';
|
||||
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { downloadBlob } from '@/lib/utils';
|
||||
|
||||
const MENU_ITEM =
|
||||
'block w-full cursor-pointer px-4 py-2 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50';
|
||||
|
||||
export default function DownloadCaptions({
|
||||
fileNames,
|
||||
captions,
|
||||
}: {
|
||||
fileNames: string[];
|
||||
captions: Record<string, string>;
|
||||
}) {
|
||||
const disabled = fileNames.length === 0;
|
||||
|
||||
// Sorted lazily in the click handlers: this component re-renders with the
|
||||
// sidebar on every caption keystroke, and the sort is only needed on click.
|
||||
const sortedFileNames = () => [...fileNames].sort();
|
||||
|
||||
function handleDownloadJson() {
|
||||
const data = sortedFileNames().map((path) => ({
|
||||
path,
|
||||
cap: captions[path] ?? '',
|
||||
}));
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], {
|
||||
type: 'application/json',
|
||||
});
|
||||
downloadBlob(blob, 'videos2caption.json');
|
||||
}
|
||||
|
||||
function handleDownloadTxt() {
|
||||
const sortedNames = sortedFileNames();
|
||||
const videosContent = sortedNames.join('\n');
|
||||
const promptContent = sortedNames
|
||||
.map((fn) => captions[fn] ?? '')
|
||||
.join('\n');
|
||||
downloadBlob(
|
||||
new Blob([videosContent], { type: 'text/plain' }),
|
||||
'videos.txt',
|
||||
);
|
||||
setTimeout(() => {
|
||||
downloadBlob(
|
||||
new Blob([promptContent], { type: 'text/plain' }),
|
||||
'captions.txt',
|
||||
);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function handleDownloadCsv() {
|
||||
const escape = (s: string) =>
|
||||
s.includes('"') || s.includes(',') || s.includes('\n')
|
||||
? `"${s.replace(/"/g, '""')}"`
|
||||
: s;
|
||||
const rows = sortedFileNames().map(
|
||||
(fn) => `${escape(fn)},${escape(captions[fn] ?? '')}`,
|
||||
);
|
||||
const csv = ['video_name,caption', ...rows].join('\n');
|
||||
downloadBlob(new Blob([csv], { type: 'text/csv' }), 'captions.csv');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group relative inline-block">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
aria-haspopup="menu"
|
||||
className="gap-1.5"
|
||||
>
|
||||
Download Captions
|
||||
<ChevronDown className="h-3.5 w-3.5 opacity-85" />
|
||||
</Button>
|
||||
{!disabled && (
|
||||
<div
|
||||
role="menu"
|
||||
className="invisible absolute right-0 top-full z-[200] min-w-full -translate-y-1 pt-1 opacity-0 transition-all group-focus-within:visible group-focus-within:translate-y-0 group-focus-within:opacity-100 group-hover:visible group-hover:translate-y-0 group-hover:opacity-100"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-popover py-1 shadow-lg">
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={MENU_ITEM}
|
||||
onClick={handleDownloadJson}
|
||||
>
|
||||
JSON
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={MENU_ITEM}
|
||||
onClick={handleDownloadTxt}
|
||||
>
|
||||
TXT
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={MENU_ITEM}
|
||||
onClick={handleDownloadCsv}
|
||||
>
|
||||
CSV
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface UploadZoneProps {
|
||||
label: string;
|
||||
hint?: string;
|
||||
accept?: string;
|
||||
multiple?: boolean;
|
||||
directory?: boolean;
|
||||
allowBothFileAndDirectory?: boolean;
|
||||
value?: string;
|
||||
fileName?: string;
|
||||
onFiles?: (files: File[]) => void;
|
||||
onClear?: () => void;
|
||||
disabled?: boolean;
|
||||
uploading?: boolean;
|
||||
}
|
||||
|
||||
const linkButtonClass =
|
||||
'cursor-pointer bg-transparent p-0 text-accent-blue hover:underline disabled:cursor-not-allowed disabled:no-underline disabled:opacity-50';
|
||||
|
||||
export default function UploadZone({
|
||||
label,
|
||||
hint,
|
||||
accept,
|
||||
multiple = false,
|
||||
directory = false,
|
||||
allowBothFileAndDirectory = false,
|
||||
value = '',
|
||||
fileName,
|
||||
onFiles,
|
||||
onClear,
|
||||
disabled = false,
|
||||
uploading = false,
|
||||
}: UploadZoneProps) {
|
||||
const fileInputRef = React.useRef<HTMLInputElement>(null);
|
||||
const directoryInputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const useBoth = directory && allowBothFileAndDirectory;
|
||||
const clickable = !useBoth;
|
||||
const hasContent = !!(value || fileName);
|
||||
|
||||
// `webkitdirectory` is a DOM property without a typed JSX prop, so set it
|
||||
// imperatively. The primary input only selects folders when it is the sole
|
||||
// input; the dedicated directory input always does.
|
||||
React.useEffect(() => {
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.webkitdirectory = directory && !allowBothFileAndDirectory;
|
||||
}
|
||||
if (directoryInputRef.current) {
|
||||
directoryInputRef.current.webkitdirectory = true;
|
||||
}
|
||||
}, [directory, allowBothFileAndDirectory]);
|
||||
|
||||
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
onFiles?.(Array.from(files));
|
||||
}
|
||||
e.target.value = '';
|
||||
}
|
||||
|
||||
function handleClick() {
|
||||
if (!disabled) {
|
||||
fileInputRef.current?.click();
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyActivate(e: React.KeyboardEvent) {
|
||||
if ((e.target as HTMLElement).closest('button')) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleClick();
|
||||
}
|
||||
}
|
||||
|
||||
function handleDrop(e: React.DragEvent) {
|
||||
if (disabled) return;
|
||||
e.preventDefault();
|
||||
const files = e.dataTransfer.files;
|
||||
if (files && files.length > 0) {
|
||||
onFiles?.(Array.from(files));
|
||||
}
|
||||
}
|
||||
|
||||
function handleDragOver(e: React.DragEvent) {
|
||||
if (disabled) return;
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
function clearInputs() {
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
if (directoryInputRef.current) directoryInputRef.current.value = '';
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-h-[150px] grow flex-col items-center justify-center rounded-lg border-2 border-dashed border-border bg-muted/40 px-5 py-6 text-center transition-colors hover:border-accent-blue hover:bg-muted/60',
|
||||
clickable ? 'cursor-pointer' : 'cursor-default',
|
||||
hasContent && 'border-solid border-accent-blue',
|
||||
)}
|
||||
onClick={clickable ? handleClick : undefined}
|
||||
onKeyDown={clickable ? handleKeyActivate : undefined}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
role={clickable ? 'button' : undefined}
|
||||
tabIndex={clickable ? 0 : undefined}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept={accept}
|
||||
multiple={multiple}
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{useBoth && (
|
||||
<input
|
||||
ref={directoryInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
multiple
|
||||
onChange={handleChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="mb-2 text-sm text-muted-foreground">{label}</div>
|
||||
|
||||
{!hasContent && (
|
||||
<span className="mt-1.5 text-xs text-muted-foreground">
|
||||
{uploading ? (
|
||||
'Uploading…'
|
||||
) : useBoth ? (
|
||||
<>
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="cursor-pointer text-accent-blue hover:underline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleClick();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleClick();
|
||||
}
|
||||
}}
|
||||
>
|
||||
Select files
|
||||
</span>
|
||||
{' · '}
|
||||
<button
|
||||
type="button"
|
||||
className={linkButtonClass}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!disabled) directoryInputRef.current?.click();
|
||||
}}
|
||||
disabled={disabled}
|
||||
>
|
||||
Select folder
|
||||
</button>
|
||||
</>
|
||||
) : directory ? (
|
||||
'Click or drop folder'
|
||||
) : (
|
||||
'Click or drop file(s)'
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{fileName && (
|
||||
<div className="mt-2 text-sm text-foreground">
|
||||
{fileName}
|
||||
{onClear && (
|
||||
<>
|
||||
{' · '}
|
||||
<button
|
||||
type="button"
|
||||
className={linkButtonClass}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClear();
|
||||
clearInputs();
|
||||
}}
|
||||
disabled={disabled || uploading}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hint && <div className="mt-1.5 text-xs text-muted-foreground">{hint}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* Labeled form-field rows shared by the Settings page and the Create Job
|
||||
* modal. They mirror the Svelte `Toggle`/`Slider` UX on top of the shadcn
|
||||
* `Switch`/`Slider`/`Input` primitives.
|
||||
*/
|
||||
|
||||
export function FieldRow({
|
||||
htmlFor,
|
||||
label,
|
||||
title,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
htmlFor: string;
|
||||
label: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||
<Label
|
||||
htmlFor={htmlFor}
|
||||
title={title}
|
||||
className="pl-0.5 text-xs font-normal tracking-wide text-muted-foreground"
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SliderRow({
|
||||
id,
|
||||
label,
|
||||
title,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
format = (v) => String(v),
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
title?: string;
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
value: number;
|
||||
/** Called once per gesture (pointer release / key press), not per drag tick. */
|
||||
onChange: (v: number) => void;
|
||||
disabled?: boolean;
|
||||
format?: (v: number) => string;
|
||||
}) {
|
||||
// Track the in-progress drag locally so `onChange` only fires on commit;
|
||||
// any external `value` change (commit landing, reset button) takes over.
|
||||
const [dragValue, setDragValue] = React.useState<number | null>(null);
|
||||
React.useEffect(() => {
|
||||
setDragValue(null);
|
||||
}, [value]);
|
||||
const shown = dragValue ?? value;
|
||||
return (
|
||||
<FieldRow htmlFor={id} label={label} title={title}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Slider
|
||||
id={id}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={[shown]}
|
||||
onValueChange={(v) => setDragValue(v[0])}
|
||||
onValueCommit={(v) => onChange(v[0])}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
className="min-w-0 flex-1"
|
||||
/>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="min-w-10 shrink-0 text-right text-sm tabular-nums text-muted-foreground"
|
||||
>
|
||||
{format(shown)}
|
||||
</span>
|
||||
</div>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
|
||||
export function ToggleRow({
|
||||
id,
|
||||
label,
|
||||
title,
|
||||
checked,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
title?: string;
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<FieldRow htmlFor={id} label={label} title={title}>
|
||||
<Switch
|
||||
id={id}
|
||||
checked={checked}
|
||||
onCheckedChange={onChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
|
||||
export function NumberRow({
|
||||
id,
|
||||
label,
|
||||
title,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
title?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number | string;
|
||||
value: number;
|
||||
onChange: (v: number) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
// Buffer the raw text so the field can be emptied while retyping; only
|
||||
// valid numbers are committed, and blur restores the last committed value.
|
||||
const [draft, setDraft] = React.useState<string | null>(null);
|
||||
React.useEffect(() => {
|
||||
setDraft(null);
|
||||
}, [value]);
|
||||
return (
|
||||
<FieldRow htmlFor={id} label={label} title={title}>
|
||||
<Input
|
||||
id={id}
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={draft ?? value}
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
const v = e.target.valueAsNumber;
|
||||
if (!Number.isNaN(v)) onChange(v);
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</FieldRow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
import CreateJobModal from '@/components/jobs/CreateJobModal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { WORKLOAD_OPTIONS } from '@/lib/jobConfig';
|
||||
import type { JobType } from '@/lib/types';
|
||||
import { triggerRefresh } from '@/stores/jobsRefresh';
|
||||
|
||||
interface CreateJobButtonProps {
|
||||
jobType: JobType;
|
||||
}
|
||||
|
||||
export default function CreateJobButton({ jobType }: CreateJobButtonProps) {
|
||||
const options = WORKLOAD_OPTIONS[jobType] ?? [];
|
||||
|
||||
const [modalOpen, setModalOpen] = React.useState(false);
|
||||
const [workloadType, setWorkloadType] = React.useState(
|
||||
options[0]?.type ?? 't2v',
|
||||
);
|
||||
|
||||
function openModal(type: string) {
|
||||
setWorkloadType(type);
|
||||
setModalOpen(true);
|
||||
}
|
||||
|
||||
function handleSuccess() {
|
||||
triggerRefresh();
|
||||
setModalOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="group relative inline-block">
|
||||
<Button type="button" className="gap-1.5">
|
||||
Create Job
|
||||
<ChevronDown className="size-3.5 opacity-85" aria-hidden />
|
||||
</Button>
|
||||
<div
|
||||
role="menu"
|
||||
className="invisible absolute right-0 top-full z-[200] mt-1 min-w-full -translate-y-1 rounded-lg border border-border bg-popover py-1 opacity-0 shadow-lg transition-all duration-150 group-hover:visible group-hover:translate-y-0 group-hover:opacity-100"
|
||||
>
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
key={opt.type}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => openModal(opt.type)}
|
||||
className="block w-full whitespace-nowrap px-4 py-2 text-left text-sm font-medium text-popover-foreground transition-colors hover:bg-secondary"
|
||||
>
|
||||
{opt.label}
|
||||
<span className="mt-0.5 block text-xs font-normal text-muted-foreground">
|
||||
{opt.desc}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<CreateJobModal
|
||||
isOpen={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
onSuccess={handleSuccess}
|
||||
jobType={jobType}
|
||||
workloadType={workloadType}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import * as React from 'react';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import CreateJobModal from './CreateJobModal';
|
||||
import { createJob, getDatasets, getModels, uploadImage } from '@/lib/api';
|
||||
import { defaultOptionsStore } from '@/stores/defaultOptions';
|
||||
import { DEFAULT_OPTIONS } from '@/lib/defaultOptions';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
createJob: vi.fn(),
|
||||
getModels: vi.fn(),
|
||||
getDatasets: vi.fn(),
|
||||
uploadImage: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
const MODELS = [
|
||||
{ id: 'wan/t2v-1.3b', label: 'Wan T2V', type: 't2v' },
|
||||
{ id: 'wan/t2v-14b', label: 'Wan T2V Large', type: 't2v' },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset the shared options store to a known baseline for test isolation.
|
||||
defaultOptionsStore.set({ options: DEFAULT_OPTIONS });
|
||||
vi.mocked(getModels).mockResolvedValue(MODELS);
|
||||
vi.mocked(getDatasets).mockResolvedValue([]);
|
||||
vi.mocked(uploadImage).mockResolvedValue({ path: '/uploads/x.png' });
|
||||
vi.mocked(createJob).mockResolvedValue({ id: 'job-1' } as never);
|
||||
});
|
||||
|
||||
function renderModal(
|
||||
overrides: Partial<React.ComponentProps<typeof CreateJobModal>> = {},
|
||||
) {
|
||||
const onClose = vi.fn();
|
||||
const onSuccess = vi.fn();
|
||||
render(
|
||||
<CreateJobModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onSuccess={onSuccess}
|
||||
jobType="inference"
|
||||
workloadType="t2v"
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
return { onClose, onSuccess };
|
||||
}
|
||||
|
||||
describe('CreateJobModal', () => {
|
||||
it('renders the form fields for an inference job', async () => {
|
||||
renderModal();
|
||||
|
||||
expect(
|
||||
await screen.findByText('New Inference Job (T2V)'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Model')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Prompt')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Negative Prompt')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Create Job' }),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// The model dropdown is populated once getModels resolves.
|
||||
expect(
|
||||
await screen.findByRole('option', {
|
||||
name: 'Wan T2V (wan/t2v-1.3b)',
|
||||
}),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('seeds fields from the options store and submits an inference payload', async () => {
|
||||
// Non-default store values prove the open-time seeding effect ran (the
|
||||
// useState defaults are 50 / 480).
|
||||
defaultOptionsStore.set({
|
||||
options: { ...DEFAULT_OPTIONS, numInferenceSteps: 25, height: 720 },
|
||||
});
|
||||
|
||||
const user = userEvent.setup();
|
||||
const { onClose, onSuccess } = renderModal();
|
||||
|
||||
// Wait for models to load so the default model is selected.
|
||||
await screen.findByRole('option', { name: 'Wan T2V (wan/t2v-1.3b)' });
|
||||
|
||||
await user.type(
|
||||
screen.getByLabelText('Prompt'),
|
||||
'a raccoon in sunflowers',
|
||||
);
|
||||
await user.click(screen.getByRole('button', { name: 'Create Job' }));
|
||||
|
||||
await waitFor(() => expect(createJob).toHaveBeenCalledTimes(1));
|
||||
const payload = vi.mocked(createJob).mock.calls[0][0];
|
||||
expect(payload).toMatchObject({
|
||||
model_id: 'wan/t2v-1.3b',
|
||||
prompt: 'a raccoon in sunflowers',
|
||||
workload_type: 't2v',
|
||||
job_type: 'inference',
|
||||
num_inference_steps: 25,
|
||||
height: 720,
|
||||
num_frames: 81,
|
||||
width: 832,
|
||||
guidance_scale: 5,
|
||||
seed: 1024,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('submits a dmd_t2v distillation payload including the DMD fields', async () => {
|
||||
vi.mocked(getDatasets).mockResolvedValue([
|
||||
{ id: 'ds1', name: 'My Dataset', created_at: 0 },
|
||||
]);
|
||||
|
||||
const user = userEvent.setup();
|
||||
const { onSuccess } = renderModal({
|
||||
jobType: 'distillation',
|
||||
workloadType: 'dmd_t2v',
|
||||
});
|
||||
|
||||
// Models + datasets load asynchronously on open. The model/dataset option
|
||||
// labels also appear in the Real/Fake Score Model and Validation Dataset
|
||||
// selects, so scope each wait to the relevant select.
|
||||
await within(screen.getByLabelText('Model')).findByRole('option', {
|
||||
name: 'Wan T2V (wan/t2v-1.3b)',
|
||||
});
|
||||
const datasetSelect = screen.getByLabelText('Dataset *');
|
||||
await within(datasetSelect).findByRole('option', { name: 'My Dataset' });
|
||||
|
||||
await user.type(screen.getByLabelText('Description'), 'distill run');
|
||||
await user.selectOptions(datasetSelect, 'ds1');
|
||||
await user.click(screen.getByRole('button', { name: 'Create Job' }));
|
||||
|
||||
await waitFor(() => expect(createJob).toHaveBeenCalledTimes(1));
|
||||
const payload = vi.mocked(createJob).mock.calls[0][0];
|
||||
expect(payload).toMatchObject({
|
||||
workload_type: 'dmd_t2v',
|
||||
job_type: 'distillation',
|
||||
// The dataset id is sent; the backend resolves it to the on-disk dir.
|
||||
data_path: 'ds1',
|
||||
lora_rank: 32,
|
||||
// DMD-specific fields added to CreateJobRequest for this modal.
|
||||
dmd_use_vsa: false,
|
||||
dmd_vsa_sparsity: 0.8,
|
||||
dmd_denoising_steps: '1000,757,522',
|
||||
real_score_guidance_scale: 3.5,
|
||||
generator_update_interval: 5,
|
||||
real_score_model_path: 'wan/t2v-1.3b',
|
||||
fake_score_model_path: 'wan/t2v-1.3b',
|
||||
});
|
||||
// Inference-only keys must be absent for a training job.
|
||||
expect(payload).not.toHaveProperty('num_inference_steps');
|
||||
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,823 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import {
|
||||
FieldRow,
|
||||
NumberRow,
|
||||
SliderRow,
|
||||
ToggleRow,
|
||||
} from '@/components/form-rows';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { NativeSelect } from '@/components/ui/native-select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import { defaultOptionsStore } from '@/stores/defaultOptions';
|
||||
import {
|
||||
createJob,
|
||||
getDatasets,
|
||||
getModels,
|
||||
uploadImage,
|
||||
type CreateJobRequest,
|
||||
type Model,
|
||||
} from '@/lib/api';
|
||||
import { getDefaultModelForWorkload } from '@/lib/defaultOptions';
|
||||
import { WORKLOAD_OPTIONS } from '@/lib/jobConfig';
|
||||
import type { JobType } from '@/lib/types';
|
||||
|
||||
export interface CreateJobModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
jobType: JobType;
|
||||
workloadType: string;
|
||||
}
|
||||
|
||||
export default function CreateJobModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
jobType,
|
||||
workloadType,
|
||||
}: CreateJobModalProps) {
|
||||
const { options } = useStore(defaultOptionsStore);
|
||||
|
||||
const isInference = jobType === 'inference';
|
||||
// Training jobs always pick from the t2v model catalogue.
|
||||
const inferenceWorkload = isInference ? workloadType : 't2v';
|
||||
|
||||
const [models, setModels] = React.useState<Model[]>([]);
|
||||
const [modelId, setModelId] = React.useState('');
|
||||
const [prompt, setPrompt] = React.useState('');
|
||||
const [imagePath, setImagePath] = React.useState('');
|
||||
const [imageFileName, setImageFileName] = React.useState('');
|
||||
const [isUploadingImage, setIsUploadingImage] = React.useState(false);
|
||||
const [negativePrompt, setNegativePrompt] = React.useState('');
|
||||
const [numInferenceSteps, setNumInferenceSteps] = React.useState(50);
|
||||
const [numFrames, setNumFrames] = React.useState(81);
|
||||
const [height, setHeight] = React.useState(480);
|
||||
const [width, setWidth] = React.useState(832);
|
||||
const [guidanceScale, setGuidanceScale] = React.useState(5);
|
||||
const [guidanceRescale, setGuidanceRescale] = React.useState(0);
|
||||
const [fps, setFps] = React.useState(24);
|
||||
const [seed, setSeed] = React.useState(1024);
|
||||
const [numGpus, setNumGpus] = React.useState(1);
|
||||
const [ditCpuOffload, setDitCpuOffload] = React.useState(false);
|
||||
const [textEncoderCpuOffload, setTextEncoderCpuOffload] =
|
||||
React.useState(false);
|
||||
const [vaeCpuOffload, setVaeCpuOffload] = React.useState(false);
|
||||
const [imageEncoderCpuOffload, setImageEncoderCpuOffload] =
|
||||
React.useState(false);
|
||||
const [useFsdpInference, setUseFsdpInference] = React.useState(false);
|
||||
const [enableTorchCompile, setEnableTorchCompile] = React.useState(false);
|
||||
const [vsaSparsity, setVsaSparsity] = React.useState(0);
|
||||
const [tpSize, setTpSize] = React.useState(-1);
|
||||
const [spSize, setSpSize] = React.useState(-1);
|
||||
const [selectedDatasetId, setSelectedDatasetId] = React.useState('');
|
||||
const [readyDatasets, setReadyDatasets] = React.useState<
|
||||
Awaited<ReturnType<typeof getDatasets>>
|
||||
>([]);
|
||||
const [maxTrainSteps, setMaxTrainSteps] = React.useState(1000);
|
||||
const [trainBatchSize, setTrainBatchSize] = React.useState(1);
|
||||
const [learningRate, setLearningRate] = React.useState(5e-5);
|
||||
const [numLatentT, setNumLatentT] = React.useState(20);
|
||||
const [selectedValidationDatasetId, setSelectedValidationDatasetId] =
|
||||
React.useState('');
|
||||
const [loraRank, setLoraRank] = React.useState(32);
|
||||
const [dmdUseVsa, setDmdUseVsa] = React.useState(false);
|
||||
const [dmdVsaSparsity, setDmdVsaSparsity] = React.useState(0.8);
|
||||
const [dmdDenoisingSteps, setDmdDenoisingSteps] =
|
||||
React.useState('1000,757,522');
|
||||
const [realScoreGuidanceScale, setRealScoreGuidanceScale] =
|
||||
React.useState(3.5);
|
||||
const [generatorUpdateInterval, setGeneratorUpdateInterval] =
|
||||
React.useState(5);
|
||||
const [realScoreModelPath, setRealScoreModelPath] = React.useState('');
|
||||
const [fakeScoreModelPath, setFakeScoreModelPath] = React.useState('');
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const [isLoadingModels, setIsLoadingModels] = React.useState(false);
|
||||
const imageInputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
// Seed field values from the persisted default options each time the modal
|
||||
// OPENS. A naive port of the Svelte `$effect` would re-seed on every
|
||||
// `$defaultOptions` change; we deliberately seed only on the open transition
|
||||
// so a late `initDefaultOptions()` settings refresh can't clobber the user's
|
||||
// in-progress edits or desync the (already validated) model selection.
|
||||
const justOpenedRef = React.useRef(false);
|
||||
React.useEffect(() => {
|
||||
const justOpened = isOpen && !justOpenedRef.current;
|
||||
justOpenedRef.current = isOpen;
|
||||
if (!justOpened) return;
|
||||
const opts = options;
|
||||
setNumInferenceSteps(opts.numInferenceSteps);
|
||||
setNumFrames(workloadType === 't2i' ? 1 : opts.numFrames);
|
||||
setHeight(opts.height);
|
||||
setWidth(opts.width);
|
||||
setGuidanceScale(opts.guidanceScale);
|
||||
setGuidanceRescale(opts.guidanceRescale);
|
||||
setFps(opts.fps);
|
||||
setSeed(opts.seed);
|
||||
setNumGpus(opts.numGpus);
|
||||
setDitCpuOffload(opts.ditCpuOffload);
|
||||
setTextEncoderCpuOffload(opts.textEncoderCpuOffload);
|
||||
setVaeCpuOffload(opts.vaeCpuOffload);
|
||||
setImageEncoderCpuOffload(opts.imageEncoderCpuOffload);
|
||||
setUseFsdpInference(opts.useFsdpInference);
|
||||
setEnableTorchCompile(opts.enableTorchCompile);
|
||||
setVsaSparsity(opts.vsaSparsity);
|
||||
setTpSize(opts.tpSize);
|
||||
setSpSize(opts.spSize);
|
||||
setModelId(
|
||||
getDefaultModelForWorkload(
|
||||
opts,
|
||||
inferenceWorkload as 't2v' | 'i2v' | 't2i',
|
||||
),
|
||||
);
|
||||
setImagePath('');
|
||||
setImageFileName('');
|
||||
setSelectedDatasetId('');
|
||||
setSelectedValidationDatasetId('');
|
||||
if (workloadType === 'dmd_t2v') {
|
||||
setDmdUseVsa(false);
|
||||
setDmdVsaSparsity(0.8);
|
||||
setDmdDenoisingSteps('1000,757,522');
|
||||
setRealScoreGuidanceScale(3.5);
|
||||
setGeneratorUpdateInterval(5);
|
||||
setRealScoreModelPath('');
|
||||
setFakeScoreModelPath('');
|
||||
}
|
||||
}, [isOpen, workloadType, inferenceWorkload, options]);
|
||||
|
||||
// Load the models available for this workload.
|
||||
React.useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
// Ignore a superseded response so a slow fetch for a previous workload
|
||||
// can't overwrite the current workload's model list/selection.
|
||||
let stale = false;
|
||||
setIsLoadingModels(true);
|
||||
getModels(inferenceWorkload)
|
||||
.then((list) => {
|
||||
if (stale) return;
|
||||
setModels(list);
|
||||
const ids = list.map((m) => m.id);
|
||||
const opts = defaultOptionsStore.get().options;
|
||||
const defaultId = getDefaultModelForWorkload(
|
||||
opts,
|
||||
inferenceWorkload as 't2v' | 'i2v' | 't2i',
|
||||
);
|
||||
const chosen = ids.includes(defaultId) ? defaultId : (list[0]?.id ?? '');
|
||||
setModelId(chosen);
|
||||
if (workloadType === 'dmd_t2v') {
|
||||
setRealScoreModelPath(chosen);
|
||||
setFakeScoreModelPath(chosen);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!stale) console.error('Failed to load models:', e);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!stale) setIsLoadingModels(false);
|
||||
});
|
||||
return () => {
|
||||
stale = true;
|
||||
};
|
||||
}, [isOpen, inferenceWorkload, workloadType]);
|
||||
|
||||
// Training jobs need a dataset; load the ready datasets when relevant.
|
||||
React.useEffect(() => {
|
||||
if (isOpen && !isInference) {
|
||||
getDatasets()
|
||||
.then(setReadyDatasets)
|
||||
.catch(() => setReadyDatasets([]));
|
||||
} else {
|
||||
setReadyDatasets([]);
|
||||
}
|
||||
}, [isOpen, isInference]);
|
||||
|
||||
async function handleImageChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) {
|
||||
setImagePath('');
|
||||
setImageFileName('');
|
||||
return;
|
||||
}
|
||||
setIsUploadingImage(true);
|
||||
setImageFileName(file.name);
|
||||
try {
|
||||
const { path } = await uploadImage(file);
|
||||
setImagePath(path);
|
||||
} catch {
|
||||
setImagePath('');
|
||||
setImageFileName('');
|
||||
} finally {
|
||||
setIsUploadingImage(false);
|
||||
}
|
||||
}
|
||||
|
||||
function clearImage() {
|
||||
setImagePath('');
|
||||
setImageFileName('');
|
||||
if (imageInputRef.current) imageInputRef.current.value = '';
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
if (isInference && workloadType === 'i2v' && !imagePath) return;
|
||||
// Send the dataset id; the backend resolves it to the on-disk media dir.
|
||||
const effectiveDataPath = selectedDatasetId ?? '';
|
||||
if (!isInference && !selectedDatasetId) return;
|
||||
// `lora_t2v` jobs are persisted with a dedicated backend job_type that the
|
||||
// front-end JobType enum does not model; cast to keep payload parity.
|
||||
const effectiveJobType = (
|
||||
workloadType === 'lora_t2v' ? 'lora' : jobType
|
||||
) as JobType;
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const payload: CreateJobRequest = {
|
||||
model_id: modelId,
|
||||
prompt,
|
||||
workload_type: workloadType,
|
||||
job_type: effectiveJobType,
|
||||
...(isInference
|
||||
? {
|
||||
...(workloadType === 'i2v' && imagePath
|
||||
? { image_path: imagePath }
|
||||
: {}),
|
||||
negative_prompt: negativePrompt,
|
||||
num_inference_steps: numInferenceSteps,
|
||||
num_frames: numFrames,
|
||||
height,
|
||||
width,
|
||||
guidance_scale: guidanceScale,
|
||||
guidance_rescale: guidanceRescale,
|
||||
fps,
|
||||
seed,
|
||||
num_gpus: numGpus,
|
||||
dit_cpu_offload: ditCpuOffload,
|
||||
text_encoder_cpu_offload: textEncoderCpuOffload,
|
||||
vae_cpu_offload: vaeCpuOffload,
|
||||
image_encoder_cpu_offload: imageEncoderCpuOffload,
|
||||
use_fsdp_inference: useFsdpInference,
|
||||
enable_torch_compile: enableTorchCompile,
|
||||
vsa_sparsity: vsaSparsity,
|
||||
tp_size: tpSize,
|
||||
sp_size: spSize,
|
||||
}
|
||||
: {
|
||||
data_path: effectiveDataPath.trim(),
|
||||
max_train_steps: maxTrainSteps,
|
||||
train_batch_size: trainBatchSize,
|
||||
learning_rate: learningRate,
|
||||
num_latent_t: numLatentT,
|
||||
validation_dataset_file: selectedValidationDatasetId || undefined,
|
||||
lora_rank: loraRank,
|
||||
...(workloadType === 'dmd_t2v'
|
||||
? {
|
||||
dmd_use_vsa: dmdUseVsa,
|
||||
dmd_vsa_sparsity: dmdVsaSparsity,
|
||||
dmd_denoising_steps: dmdDenoisingSteps,
|
||||
real_score_guidance_scale: realScoreGuidanceScale,
|
||||
generator_update_interval: generatorUpdateInterval,
|
||||
real_score_model_path: realScoreModelPath || modelId,
|
||||
fake_score_model_path: fakeScoreModelPath || modelId,
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
};
|
||||
await createJob(payload);
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
console.error('Failed to create job:', err);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (isSubmitting) return;
|
||||
onClose();
|
||||
}
|
||||
|
||||
const workloadLabel =
|
||||
WORKLOAD_OPTIONS[jobType]?.find((o) => o.type === workloadType)?.label ?? '';
|
||||
const title = `New ${jobType.charAt(0).toUpperCase() + jobType.slice(1)} Job${
|
||||
workloadLabel ? ` (${workloadLabel})` : ''
|
||||
}`;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) handleClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-h-[90vh] w-[90vw] max-w-[850px] overflow-y-auto"
|
||||
onEscapeKeyDown={(e) => {
|
||||
if (isSubmitting) e.preventDefault();
|
||||
}}
|
||||
onInteractOutside={(e) => {
|
||||
if (isSubmitting) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
autoComplete="off"
|
||||
className="flex flex-col gap-3.5"
|
||||
>
|
||||
<FieldRow htmlFor="modal-modelId" label="Model">
|
||||
<NativeSelect
|
||||
id="modal-modelId"
|
||||
value={modelId}
|
||||
onChange={(e) => setModelId(e.target.value)}
|
||||
required
|
||||
disabled={isSubmitting || isLoadingModels}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{isLoadingModels
|
||||
? 'Loading models…'
|
||||
: models.length === 0
|
||||
? 'No models available for this workload'
|
||||
: 'Select a model…'}
|
||||
</option>
|
||||
{models.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label} ({model.id})
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</FieldRow>
|
||||
|
||||
{isInference && workloadType === 'i2v' && (
|
||||
<FieldRow htmlFor="modal-image" label="Image">
|
||||
<Input
|
||||
ref={imageInputRef}
|
||||
id="modal-image"
|
||||
type="file"
|
||||
accept=".png,.jpg,.jpeg,.webp,.bmp"
|
||||
onChange={handleImageChange}
|
||||
disabled={isSubmitting || isUploadingImage}
|
||||
required
|
||||
className="h-auto py-2 file:mr-3 file:cursor-pointer file:rounded-md file:border-0 file:bg-secondary file:px-2 file:py-1 file:text-sm file:text-secondary-foreground"
|
||||
/>
|
||||
{imageFileName && (
|
||||
<span className="mt-0.5 text-xs text-muted-foreground">
|
||||
{isUploadingImage ? 'Uploading…' : imageFileName} ·{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearImage}
|
||||
disabled={isSubmitting || isUploadingImage}
|
||||
className="text-accent-blue underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</FieldRow>
|
||||
)}
|
||||
|
||||
<FieldRow
|
||||
htmlFor="modal-prompt"
|
||||
label={isInference ? 'Prompt' : 'Description'}
|
||||
>
|
||||
<Textarea
|
||||
id="modal-prompt"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
rows={isInference ? 3 : 2}
|
||||
placeholder={
|
||||
isInference
|
||||
? 'A curious raccoon peers through a vibrant field of yellow sunflowers…'
|
||||
: 'Brief description of this training job…'
|
||||
}
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</FieldRow>
|
||||
|
||||
{isInference && (
|
||||
<FieldRow htmlFor="modal-negative-prompt" label="Negative Prompt">
|
||||
<Textarea
|
||||
id="modal-negative-prompt"
|
||||
value={negativePrompt}
|
||||
onChange={(e) => setNegativePrompt(e.target.value)}
|
||||
rows={2}
|
||||
placeholder="Optional: things to avoid in the output…"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</FieldRow>
|
||||
)}
|
||||
|
||||
{!isInference && (
|
||||
<>
|
||||
<div className="flex gap-4">
|
||||
<FieldRow
|
||||
htmlFor="modal-dataset"
|
||||
label="Dataset *"
|
||||
className="min-w-0 flex-1"
|
||||
>
|
||||
<NativeSelect
|
||||
id="modal-dataset"
|
||||
value={selectedDatasetId}
|
||||
onChange={(e) => setSelectedDatasetId(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{readyDatasets.length === 0
|
||||
? 'No datasets (add in Datasets tab)'
|
||||
: 'Select a dataset…'}
|
||||
</option>
|
||||
{readyDatasets.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</FieldRow>
|
||||
<FieldRow
|
||||
htmlFor="modal-validation-dataset"
|
||||
label="Validation Dataset (optional)"
|
||||
className="min-w-0 flex-1"
|
||||
>
|
||||
<NativeSelect
|
||||
id="modal-validation-dataset"
|
||||
value={selectedValidationDatasetId}
|
||||
onChange={(e) =>
|
||||
setSelectedValidationDatasetId(e.target.value)
|
||||
}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">None</option>
|
||||
{readyDatasets.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</FieldRow>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary className="mb-2 cursor-pointer select-none text-sm font-medium text-accent-blue">
|
||||
Options
|
||||
</summary>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-x-3 gap-y-2">
|
||||
<SliderRow
|
||||
id="modal-max-train-steps"
|
||||
label="Max Train Steps"
|
||||
min={100}
|
||||
max={50000}
|
||||
step={100}
|
||||
value={maxTrainSteps}
|
||||
onChange={setMaxTrainSteps}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-train-batch-size"
|
||||
label="Train Batch Size"
|
||||
min={1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={trainBatchSize}
|
||||
onChange={setTrainBatchSize}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<NumberRow
|
||||
id="modal-learning-rate"
|
||||
label="Learning Rate"
|
||||
step="1e-6"
|
||||
min={1e-6}
|
||||
max={1}
|
||||
value={learningRate}
|
||||
onChange={setLearningRate}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-num-latent-t"
|
||||
label="Num Latent T"
|
||||
min={8}
|
||||
max={40}
|
||||
step={1}
|
||||
value={numLatentT}
|
||||
onChange={setNumLatentT}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{workloadType === 'lora_t2v' && (
|
||||
<SliderRow
|
||||
id="modal-lora-rank"
|
||||
label="LoRA Rank"
|
||||
min={8}
|
||||
max={128}
|
||||
step={8}
|
||||
value={loraRank}
|
||||
onChange={setLoraRank}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
{workloadType === 'dmd_t2v' && (
|
||||
<>
|
||||
<ToggleRow
|
||||
id="modal-dmd-use-vsa"
|
||||
label="Video Sparse Attention (VSA)"
|
||||
title="Use Video Sparse Attention for DMD"
|
||||
checked={dmdUseVsa}
|
||||
onChange={setDmdUseVsa}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{dmdUseVsa && (
|
||||
<SliderRow
|
||||
id="modal-dmd-vsa-sparsity"
|
||||
label="VSA Sparsity"
|
||||
title="VSA sparsity (0–1)"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={dmdVsaSparsity}
|
||||
onChange={setDmdVsaSparsity}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => v.toFixed(2)}
|
||||
/>
|
||||
)}
|
||||
<FieldRow
|
||||
htmlFor="modal-dmd-denoising-steps"
|
||||
label="DMD Denoising Steps"
|
||||
title="Comma-separated denoising steps, e.g. 1000,757,522"
|
||||
>
|
||||
<Input
|
||||
id="modal-dmd-denoising-steps"
|
||||
type="text"
|
||||
value={dmdDenoisingSteps}
|
||||
onChange={(e) => setDmdDenoisingSteps(e.target.value)}
|
||||
placeholder="1000,757,522"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</FieldRow>
|
||||
<SliderRow
|
||||
id="modal-real-score-guidance-scale"
|
||||
label="Real Score Guidance Scale"
|
||||
min={1}
|
||||
max={10}
|
||||
step={0.1}
|
||||
value={realScoreGuidanceScale}
|
||||
onChange={setRealScoreGuidanceScale}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => v.toFixed(1)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-generator-update-interval"
|
||||
label="Generator Update Interval"
|
||||
min={1}
|
||||
max={20}
|
||||
step={1}
|
||||
value={generatorUpdateInterval}
|
||||
onChange={setGeneratorUpdateInterval}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{(
|
||||
[
|
||||
{
|
||||
id: 'modal-real-score-model',
|
||||
label: 'Real Score Model',
|
||||
value: realScoreModelPath,
|
||||
onChange: setRealScoreModelPath,
|
||||
},
|
||||
{
|
||||
id: 'modal-fake-score-model',
|
||||
label: 'Fake Score Model',
|
||||
value: fakeScoreModelPath,
|
||||
onChange: setFakeScoreModelPath,
|
||||
},
|
||||
] as const
|
||||
).map((select) => (
|
||||
<FieldRow
|
||||
key={select.id}
|
||||
htmlFor={select.id}
|
||||
label={select.label}
|
||||
>
|
||||
<NativeSelect
|
||||
id={select.id}
|
||||
value={select.value}
|
||||
onChange={(e) => select.onChange(e.target.value)}
|
||||
disabled={isSubmitting || isLoadingModels}
|
||||
>
|
||||
<option value="">Same as main model</option>
|
||||
{models.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label} ({model.id})
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</FieldRow>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isInference && (
|
||||
<details>
|
||||
<summary className="mb-2 cursor-pointer select-none text-sm font-medium text-accent-blue">
|
||||
Options
|
||||
</summary>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-x-3 gap-y-2">
|
||||
{workloadType !== 't2i' && (
|
||||
<SliderRow
|
||||
id="modal-num-frames"
|
||||
label="Frames"
|
||||
min={1}
|
||||
max={500}
|
||||
step={1}
|
||||
value={numFrames}
|
||||
onChange={setNumFrames}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
<SliderRow
|
||||
id="modal-height"
|
||||
label="Height"
|
||||
min={64}
|
||||
max={1080}
|
||||
step={16}
|
||||
value={height}
|
||||
onChange={setHeight}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-width"
|
||||
label="Width"
|
||||
min={64}
|
||||
max={1920}
|
||||
step={16}
|
||||
value={width}
|
||||
onChange={setWidth}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-num-steps"
|
||||
label="Inference Steps"
|
||||
min={1}
|
||||
max={200}
|
||||
step={1}
|
||||
value={numInferenceSteps}
|
||||
onChange={setNumInferenceSteps}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-vsa-sparsity"
|
||||
label="VSA Sparsity"
|
||||
title="VSA sparsity (0–1)"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={vsaSparsity}
|
||||
onChange={setVsaSparsity}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => v.toFixed(2)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-guidance"
|
||||
label="Guidance Scale"
|
||||
min={0}
|
||||
max={20}
|
||||
step={0.1}
|
||||
value={guidanceScale}
|
||||
onChange={setGuidanceScale}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => v.toFixed(1)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-guidance-rescale"
|
||||
label="Guidance Rescale"
|
||||
title="0 = disabled"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={guidanceRescale}
|
||||
onChange={setGuidanceRescale}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => v.toFixed(2)}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-tp-size"
|
||||
label="TP Size"
|
||||
title="-1 = auto"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={tpSize}
|
||||
onChange={setTpSize}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => (v === -1 ? 'Auto' : String(v))}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-sp-size"
|
||||
label="SP Size"
|
||||
title="-1 = auto"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={spSize}
|
||||
onChange={setSpSize}
|
||||
disabled={isSubmitting}
|
||||
format={(v) => (v === -1 ? 'Auto' : String(v))}
|
||||
/>
|
||||
{workloadType !== 't2i' && (
|
||||
<SliderRow
|
||||
id="modal-fps"
|
||||
label="FPS"
|
||||
min={1}
|
||||
max={60}
|
||||
step={1}
|
||||
value={fps}
|
||||
onChange={setFps}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
<ToggleRow
|
||||
id="modal-dit-cpu-offload"
|
||||
label="DiT CPU Offload"
|
||||
checked={ditCpuOffload}
|
||||
onChange={setDitCpuOffload}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="modal-text-encoder-cpu-offload"
|
||||
label="Text Encoder CPU Offload"
|
||||
checked={textEncoderCpuOffload}
|
||||
onChange={setTextEncoderCpuOffload}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="modal-use-fsdp-inference"
|
||||
label="Use FSDP Inference"
|
||||
checked={useFsdpInference}
|
||||
onChange={setUseFsdpInference}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="modal-vae-cpu-offload"
|
||||
label="VAE CPU Offload"
|
||||
checked={vaeCpuOffload}
|
||||
onChange={setVaeCpuOffload}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="modal-image-encoder-cpu-offload"
|
||||
label="Image Encoder CPU Offload"
|
||||
checked={imageEncoderCpuOffload}
|
||||
onChange={setImageEncoderCpuOffload}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<ToggleRow
|
||||
id="modal-enable-torch-compile"
|
||||
label="Torch Compile"
|
||||
checked={enableTorchCompile}
|
||||
onChange={setEnableTorchCompile}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<SliderRow
|
||||
id="modal-num-gpus"
|
||||
label="GPUs"
|
||||
min={1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={numGpus}
|
||||
onChange={setNumGpus}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<NumberRow
|
||||
id="modal-seed"
|
||||
label="Seed"
|
||||
min={0}
|
||||
value={seed}
|
||||
onChange={setSeed}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Creating...' : 'Create Job'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import JobCard from '@/components/jobs/JobCard';
|
||||
import {
|
||||
deleteJob,
|
||||
downloadJobVideo,
|
||||
startJob,
|
||||
stopJob,
|
||||
} from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
import { activeJobStore, setActiveJobId } from '@/stores/activeJob';
|
||||
import { makeJob as makeBaseJob } from '@/test/factories';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
startJob: vi.fn(),
|
||||
stopJob: vi.fn(),
|
||||
deleteJob: vi.fn(),
|
||||
downloadJobVideo: vi.fn(),
|
||||
}));
|
||||
|
||||
const makeJob = (overrides: Partial<Job> = {}): Job =>
|
||||
makeBaseJob({
|
||||
model_id: 'Wan2.1-T2V',
|
||||
prompt: 'a cat surfing a wave',
|
||||
created_at: 1_700_000_000,
|
||||
num_inference_steps: 50,
|
||||
num_frames: 81,
|
||||
height: 480,
|
||||
width: 832,
|
||||
guidance_scale: 5,
|
||||
seed: 42,
|
||||
num_gpus: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
setActiveJobId(null);
|
||||
vi.mocked(startJob).mockResolvedValue({} as Job);
|
||||
vi.mocked(stopJob).mockResolvedValue({} as Job);
|
||||
vi.mocked(deleteJob).mockResolvedValue(undefined);
|
||||
vi.mocked(downloadJobVideo).mockResolvedValue(new Blob());
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
vi.spyOn(window, 'alert').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('JobCard', () => {
|
||||
it('renders the model, prompt, status and inference meta', () => {
|
||||
render(<JobCard job={makeJob()} />);
|
||||
expect(screen.getByText('Wan2.1-T2V')).toBeInTheDocument();
|
||||
expect(screen.getByText('a cat surfing a wave')).toBeInTheDocument();
|
||||
expect(screen.getByText('pending')).toBeInTheDocument();
|
||||
expect(screen.getByText('81 frames')).toBeInTheDocument();
|
||||
expect(screen.getByText('480×832')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the workload type (not frames) for non-inference jobs', () => {
|
||||
render(
|
||||
<JobCard
|
||||
job={makeJob({ job_type: 'finetuning', workload_type: 'lora_t2v' })}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('lora t2v')).toBeInTheDocument();
|
||||
expect(screen.queryByText('81 frames')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('starts a pending job and notifies the parent', async () => {
|
||||
const onJobUpdated = vi.fn();
|
||||
render(<JobCard job={makeJob({ status: 'pending' })} onJobUpdated={onJobUpdated} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Start' }));
|
||||
await waitFor(() => expect(startJob).toHaveBeenCalledWith('job-1'));
|
||||
expect(onJobUpdated).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops a running job', async () => {
|
||||
render(<JobCard job={makeJob({ status: 'running', started_at: Date.now() })} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Stop' }));
|
||||
await waitFor(() => expect(stopJob).toHaveBeenCalledWith('job-1'));
|
||||
});
|
||||
|
||||
it('restarts a failed job via startJob', async () => {
|
||||
render(<JobCard job={makeJob({ status: 'failed' })} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Restart' }));
|
||||
await waitFor(() => expect(startJob).toHaveBeenCalledWith('job-1'));
|
||||
});
|
||||
|
||||
it('deletes when confirmed and skips when cancelled', async () => {
|
||||
const { rerender } = render(<JobCard job={makeJob()} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await waitFor(() => expect(deleteJob).toHaveBeenCalledWith('job-1'));
|
||||
|
||||
vi.mocked(deleteJob).mockClear();
|
||||
vi.mocked(window.confirm).mockReturnValue(false);
|
||||
rerender(<JobCard job={makeJob()} />);
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(deleteJob).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('downloads the video for a completed inference job', async () => {
|
||||
render(
|
||||
<JobCard
|
||||
job={makeJob({ status: 'completed', output_path: '/out/video.mp4' })}
|
||||
/>,
|
||||
);
|
||||
await userEvent.click(
|
||||
screen.getByRole('button', { name: 'Download Video' }),
|
||||
);
|
||||
await waitFor(() => expect(downloadJobVideo).toHaveBeenCalledWith('job-1'));
|
||||
});
|
||||
|
||||
it('selects the job when the card body is clicked', async () => {
|
||||
render(<JobCard job={makeJob()} />);
|
||||
await userEvent.click(screen.getByText('Wan2.1-T2V'));
|
||||
expect(activeJobStore.get().activeJobId).toBe('job-1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { Timer } from 'lucide-react';
|
||||
|
||||
import { Badge, type BadgeProps } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import {
|
||||
deleteJob,
|
||||
downloadJobVideo,
|
||||
startJob,
|
||||
stopJob,
|
||||
} from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
import { cn, downloadBlob } from '@/lib/utils';
|
||||
import { activeJobStore, setActiveJobId } from '@/stores/activeJob';
|
||||
|
||||
interface JobCardProps {
|
||||
job: Job;
|
||||
onJobUpdated?: () => void;
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const roundedSeconds = Math.round(seconds);
|
||||
if (roundedSeconds < 60) return `${roundedSeconds}s`;
|
||||
if (roundedSeconds < 3600) {
|
||||
const mins = Math.floor(roundedSeconds / 60);
|
||||
const secs = roundedSeconds % 60;
|
||||
return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
|
||||
}
|
||||
const hours = Math.floor(roundedSeconds / 3600);
|
||||
const mins = Math.floor((roundedSeconds % 3600) / 60);
|
||||
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
function computeElapsed(job: Job, currentTime: number): string | null {
|
||||
if (!job.started_at) return null;
|
||||
const endTime =
|
||||
job.status === 'running' ? currentTime : (job.finished_at ?? 0);
|
||||
if (!endTime && job.status !== 'running') return null;
|
||||
const startedAtMs =
|
||||
job.started_at < 1e12 ? job.started_at * 1000 : job.started_at;
|
||||
const endTimeMs = endTime < 1e12 ? endTime * 1000 : endTime;
|
||||
const elapsedSeconds = (endTimeMs - startedAtMs) / 1000;
|
||||
if (elapsedSeconds <= 0) return null;
|
||||
return formatDuration(elapsedSeconds);
|
||||
}
|
||||
|
||||
const BADGE_VARIANTS: Record<string, BadgeProps['variant']> = {
|
||||
pending: 'secondary',
|
||||
running: 'warning',
|
||||
completed: 'success',
|
||||
ready: 'success',
|
||||
failed: 'destructive',
|
||||
stopped: 'secondary',
|
||||
preprocessing: 'default',
|
||||
};
|
||||
|
||||
export default function JobCard({ job, onJobUpdated }: JobCardProps) {
|
||||
const { activeJobId } = useStore(activeJobStore);
|
||||
const isSelected = activeJobId === job.id;
|
||||
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [currentTime, setCurrentTime] = React.useState(() => Date.now());
|
||||
|
||||
const elapsedTime = computeElapsed(job, currentTime);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (job.status !== 'running' || !job.started_at) return;
|
||||
const interval = setInterval(() => setCurrentTime(Date.now()), 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [job.status, job.started_at]);
|
||||
|
||||
async function handleStart(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || job.status === 'running' || job.status === 'completed')
|
||||
return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await startJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to start job');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStop(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || job.status !== 'running') return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await stopJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to stop job');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading) return;
|
||||
if (!confirm('Delete this job?')) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await deleteJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete job');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSelectJob(e: React.MouseEvent | React.KeyboardEvent) {
|
||||
if ((e.target as HTMLElement).closest('button')) return;
|
||||
setActiveJobId(isSelected ? null : job.id);
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleSelectJob(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDownloadVideo(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || !job.output_path) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const blob = await downloadJobVideo(job.id);
|
||||
const ext = job.output_path.endsWith('.png') ? 'png' : 'mp4';
|
||||
downloadBlob(blob, `job_${job.id}.${ext}`);
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to download video');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={handleSelectJob}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
'mb-3 flex cursor-pointer flex-col gap-2.5 rounded-lg border bg-background p-4 transition-colors last:mb-0',
|
||||
isSelected
|
||||
? 'border-accent-blue bg-accent-blue/5'
|
||||
: 'border-border hover:border-muted-foreground/40',
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-[0.95rem] font-semibold text-foreground">
|
||||
{job.model_id}
|
||||
</span>
|
||||
<Badge variant={BADGE_VARIANTS[job.status] ?? 'secondary'}>
|
||||
{job.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm text-muted-foreground">
|
||||
{job.prompt}
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-4 text-xs text-muted-foreground">
|
||||
{job.job_type === 'inference' ? (
|
||||
<>
|
||||
<span>{job.num_frames} frames</span>
|
||||
<span>
|
||||
{job.height}×{job.width}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span>{job.workload_type?.replace(/_/g, ' ') ?? job.job_type}</span>
|
||||
)}
|
||||
{elapsedTime && (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Timer className="size-3.5" aria-hidden />
|
||||
{elapsedTime}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{job.status === 'running' ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStop}
|
||||
disabled={isLoading}
|
||||
className="border-transparent bg-amber-500 text-black shadow-md hover:bg-amber-400"
|
||||
>
|
||||
Stop
|
||||
</Button>
|
||||
) : job.status === 'failed' ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStart}
|
||||
disabled={isLoading}
|
||||
className="border-transparent bg-emerald-600 text-white shadow-md hover:bg-emerald-500"
|
||||
>
|
||||
Restart
|
||||
</Button>
|
||||
) : job.status === 'pending' || job.status === 'stopped' ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStart}
|
||||
disabled={isLoading}
|
||||
className="border-transparent bg-emerald-600 text-white shadow-md hover:bg-emerald-500"
|
||||
>
|
||||
Start
|
||||
</Button>
|
||||
) : null}
|
||||
{job.status === 'completed' &&
|
||||
job.output_path &&
|
||||
job.job_type === 'inference' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleDownloadVideo}
|
||||
disabled={isLoading}
|
||||
title="Download video"
|
||||
>
|
||||
Download Video
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import JobDetailsSidebar from './JobDetailsSidebar';
|
||||
import { getJobLogs } from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
import { makeJob as makeBaseJob } from '@/test/factories';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
getJobLogs: vi.fn(),
|
||||
downloadJobLog: vi.fn(),
|
||||
}));
|
||||
|
||||
const makeJob = (overrides: Partial<Job> = {}): Job =>
|
||||
makeBaseJob({
|
||||
status: 'running',
|
||||
log_file_path: '/logs/job-1.log',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('JobDetailsSidebar', () => {
|
||||
it('renders log lines streamed from the job log poll', async () => {
|
||||
vi.mocked(getJobLogs).mockResolvedValue({
|
||||
lines: ['boot sequence started', 'loading model weights'],
|
||||
total: 2,
|
||||
progress: 0,
|
||||
progress_msg: '',
|
||||
phase: '',
|
||||
});
|
||||
|
||||
render(
|
||||
<JobDetailsSidebar job={makeJob({ status: 'running' })} onClose={vi.fn()} />,
|
||||
);
|
||||
|
||||
expect(await screen.findByText(/boot sequence started/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/loading model weights/)).toBeInTheDocument();
|
||||
expect(getJobLogs).toHaveBeenCalledWith('job-1', 0);
|
||||
});
|
||||
|
||||
it('keeps polling while the job is running', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
vi.mocked(getJobLogs).mockResolvedValue({
|
||||
lines: [],
|
||||
total: 0,
|
||||
progress: 0,
|
||||
progress_msg: '',
|
||||
phase: '',
|
||||
});
|
||||
|
||||
render(
|
||||
<JobDetailsSidebar
|
||||
job={makeJob({ status: 'running' })}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Flush the immediate poll fired on mount.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
const initialCalls = vi.mocked(getJobLogs).mock.calls.length;
|
||||
|
||||
// Two 2s interval ticks should fire while the job is running.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(4000);
|
||||
});
|
||||
|
||||
expect(vi.mocked(getJobLogs).mock.calls.length).toBeGreaterThan(
|
||||
initialCalls,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops polling once the job is completed', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
vi.mocked(getJobLogs).mockResolvedValue({
|
||||
lines: ['final line'],
|
||||
total: 1,
|
||||
progress: 0,
|
||||
progress_msg: '',
|
||||
phase: '',
|
||||
});
|
||||
|
||||
render(
|
||||
<JobDetailsSidebar
|
||||
job={makeJob({ status: 'completed' })}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// The component fetches once on mount even for terminal jobs.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(getJobLogs).toHaveBeenCalledTimes(1);
|
||||
|
||||
// No interval is registered, so advancing the clock must not re-poll.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10000);
|
||||
});
|
||||
expect(getJobLogs).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useResizable } from '@/hooks/useResizable';
|
||||
import { downloadJobLog, getJobLogs } from '@/lib/api';
|
||||
import type { Job } from '@/lib/types';
|
||||
import { cn, downloadBlob } from '@/lib/utils';
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 280;
|
||||
const SIDEBAR_MAX_WIDTH = 750;
|
||||
const POLL_INTERVAL_MS = 2000;
|
||||
|
||||
export default function JobDetailsSidebar({
|
||||
job,
|
||||
onClose,
|
||||
onWidthChange,
|
||||
}: {
|
||||
job: Job;
|
||||
onClose: () => void;
|
||||
onWidthChange?: (w: number) => void;
|
||||
}) {
|
||||
const [width, setWidth] = React.useState(360);
|
||||
const [isDragging, setIsDragging] = React.useState(false);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [logs, setLogs] = React.useState('');
|
||||
|
||||
// Race-guard ref (mirrors the Svelte original): the cursor + accumulated
|
||||
// text live here so in-flight polls don't read stale React state. Do NOT
|
||||
// swap these for effect deps — they must update synchronously, outside
|
||||
// React's render cycle. The log is one growing string (amortized O(new)
|
||||
// appends), not an array re-copied and re-joined on every poll tick.
|
||||
const stateRef = React.useRef<{ text: string; logAfter: number }>({
|
||||
text: '',
|
||||
logAfter: 0,
|
||||
});
|
||||
const previousJobId = React.useRef<string | null>(null);
|
||||
const previousStatus = React.useRef<string | null>(null);
|
||||
const consoleRef = React.useRef<HTMLPreElement | null>(null);
|
||||
|
||||
const { onMouseDown } = useResizable({
|
||||
// Right-docked panel with the drag handle on its left edge: dragging the
|
||||
// handle left must grow the panel, which is `edge: 'right'` (matches the
|
||||
// Svelte original). `edge: 'left'` would invert the drag.
|
||||
edge: 'right',
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: setWidth,
|
||||
onDragChange: setIsDragging,
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
onWidthChange?.(width);
|
||||
}, [width, onWidthChange]);
|
||||
|
||||
// Auto-scroll the console to the bottom whenever new lines land. Runs after
|
||||
// commit so scrollHeight reflects the freshly-rendered output.
|
||||
React.useEffect(() => {
|
||||
const el = consoleRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [logs]);
|
||||
|
||||
// Reset on job switch or restart. Declared before the polling effect so the
|
||||
// cursor is cleared before the next poll reads it.
|
||||
React.useEffect(() => {
|
||||
const wasTerminal =
|
||||
previousStatus.current === 'failed' ||
|
||||
previousStatus.current === 'stopped' ||
|
||||
previousStatus.current === 'completed';
|
||||
const isRestarting =
|
||||
previousJobId.current === job.id &&
|
||||
wasTerminal &&
|
||||
(job.status === 'pending' || job.status === 'running');
|
||||
|
||||
if (previousJobId.current !== job.id || isRestarting) {
|
||||
stateRef.current.text = '';
|
||||
stateRef.current.logAfter = 0;
|
||||
setLogs('');
|
||||
}
|
||||
previousJobId.current = job.id;
|
||||
previousStatus.current = job.status;
|
||||
}, [job.id, job.status]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const shouldPoll = job.status === 'running' || job.status === 'pending';
|
||||
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let mounted = true;
|
||||
// Effect-local lock so this job's first fetch is never blocked by a
|
||||
// previous job's in-flight poll (stale writes are dropped via `mounted`).
|
||||
let locked = false;
|
||||
|
||||
async function pollLogs() {
|
||||
if (!mounted || locked) return;
|
||||
locked = true;
|
||||
try {
|
||||
const logData = await getJobLogs(job.id, stateRef.current.logAfter);
|
||||
if (mounted && logData.lines.length > 0) {
|
||||
const chunk = logData.lines.join('\n');
|
||||
stateRef.current.text = stateRef.current.text
|
||||
? `${stateRef.current.text}\n${chunk}`
|
||||
: chunk;
|
||||
stateRef.current.logAfter = logData.total;
|
||||
setLogs(stateRef.current.text);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch logs:', e);
|
||||
} finally {
|
||||
locked = false;
|
||||
}
|
||||
}
|
||||
|
||||
pollLogs();
|
||||
if (shouldPoll) pollInterval = setInterval(pollLogs, POLL_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
if (pollInterval) clearInterval(pollInterval);
|
||||
};
|
||||
}, [job.id, job.status]);
|
||||
|
||||
async function handleDownloadLog() {
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const blob = await downloadJobLog(job.id);
|
||||
downloadBlob(blob, `job_${job.id}.log`);
|
||||
} catch (err) {
|
||||
console.error('Failed to download log:', err);
|
||||
alert(err instanceof Error ? err.message : 'Failed to download log');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="fixed bottom-0 right-0 top-[var(--header-height)] z-50 flex max-h-[calc(100vh-var(--header-height))] min-w-[280px] shrink-0 flex-col border-l border-border bg-card"
|
||||
style={{ width, maxWidth: SIDEBAR_MAX_WIDTH }}
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-border px-5 py-4">
|
||||
<h2 className="m-0 text-base font-semibold text-foreground">
|
||||
Job Details
|
||||
</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownloadLog}
|
||||
disabled={isLoading || !job.log_file_path}
|
||||
title="Download log file"
|
||||
>
|
||||
Download Log
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onClose}
|
||||
title="Close"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X className="h-[18px] w-[18px]" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col px-5 py-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Console Output
|
||||
</span>
|
||||
{job.status === 'running' && (
|
||||
<span className="text-[0.7rem] font-medium text-emerald-600 dark:text-emerald-400">
|
||||
● Live
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<pre
|
||||
ref={consoleRef}
|
||||
className="m-0 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border bg-background p-3 font-mono text-xs leading-normal text-foreground"
|
||||
>
|
||||
{logs === '' ? (
|
||||
<span className="italic text-muted-foreground">
|
||||
{job.status === 'running'
|
||||
? 'Waiting for logs...'
|
||||
: 'No logs available'}
|
||||
</span>
|
||||
) : (
|
||||
logs
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="presentation"
|
||||
onMouseDown={onMouseDown}
|
||||
className={cn(
|
||||
'absolute bottom-0 left-0 top-0 z-[1] w-1.5 cursor-col-resize hover:bg-accent-blue/25',
|
||||
isDragging && 'bg-accent-blue/25',
|
||||
)}
|
||||
/>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import JobQueue from '@/components/jobs/JobQueue';
|
||||
import { getJobsList } from '@/lib/api';
|
||||
import type { Job, JobType } from '@/lib/types';
|
||||
import { setActiveJobId } from '@/stores/activeJob';
|
||||
import { triggerRefresh } from '@/stores/jobsRefresh';
|
||||
import { makeJob as makeBaseJob } from '@/test/factories';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
getJobsList: vi.fn(),
|
||||
startJob: vi.fn(),
|
||||
stopJob: vi.fn(),
|
||||
deleteJob: vi.fn(),
|
||||
downloadJobVideo: vi.fn(),
|
||||
}));
|
||||
|
||||
const makeJob = (overrides: Partial<Job> = {}): Job =>
|
||||
makeBaseJob({
|
||||
model_id: 'Wan2.1-T2V',
|
||||
status: 'completed',
|
||||
created_at: 1_700_000_000,
|
||||
num_inference_steps: 50,
|
||||
num_frames: 81,
|
||||
height: 480,
|
||||
width: 832,
|
||||
guidance_scale: 5,
|
||||
seed: 42,
|
||||
num_gpus: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
setActiveJobId(null);
|
||||
vi.mocked(getJobsList).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('JobQueue', () => {
|
||||
it('shows an empty placeholder and fetches for the single job type', async () => {
|
||||
render(<JobQueue jobType="inference" />);
|
||||
expect(
|
||||
await screen.findByText('No inference jobs yet. Create one above.'),
|
||||
).toBeInTheDocument();
|
||||
expect(getJobsList).toHaveBeenCalledWith('inference');
|
||||
});
|
||||
|
||||
it('renders a JobCard for each fetched job', async () => {
|
||||
vi.mocked(getJobsList).mockResolvedValue([
|
||||
makeJob({ id: 'a', model_id: 'Model-A' }),
|
||||
]);
|
||||
render(<JobQueue jobType="distillation" />);
|
||||
expect(await screen.findByText('Model-A')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('merges all job types when jobTypesForList is provided', async () => {
|
||||
vi.mocked(getJobsList).mockImplementation((t?: JobType) =>
|
||||
Promise.resolve(
|
||||
t === ('lora' as JobType)
|
||||
? [makeJob({ id: 'l', model_id: 'Lora-Model', created_at: 2 })]
|
||||
: [makeJob({ id: 'f', model_id: 'Full-Model', created_at: 1 })],
|
||||
),
|
||||
);
|
||||
render(
|
||||
<JobQueue
|
||||
jobType="finetuning"
|
||||
jobTypesForList={['finetuning', 'lora'] as JobType[]}
|
||||
/>,
|
||||
);
|
||||
expect(await screen.findByText('Lora-Model')).toBeInTheDocument();
|
||||
expect(screen.getByText('Full-Model')).toBeInTheDocument();
|
||||
expect(getJobsList).toHaveBeenCalledWith('finetuning');
|
||||
expect(getJobsList).toHaveBeenCalledWith('lora');
|
||||
});
|
||||
|
||||
it('refetches when a refresh is triggered', async () => {
|
||||
render(<JobQueue jobType="inference" />);
|
||||
await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));
|
||||
act(() => triggerRefresh());
|
||||
await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import JobCard from '@/components/jobs/JobCard';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import { getJobsList } from '@/lib/api';
|
||||
import type { Job, JobType } from '@/lib/types';
|
||||
import {
|
||||
activeJobStore,
|
||||
setActiveJob,
|
||||
setActiveJobId,
|
||||
} from '@/stores/activeJob';
|
||||
import { jobsRefreshStore } from '@/stores/jobsRefresh';
|
||||
|
||||
interface JobQueueProps {
|
||||
jobType: JobType;
|
||||
jobTypesForList?: JobType[];
|
||||
}
|
||||
|
||||
// Jobs are flat objects of primitives, so a shallow compare detects "nothing
|
||||
// changed" across poll responses (which are referentially fresh every fetch).
|
||||
function jobsShallowEqual(a: Job | null, b: Job | null): boolean {
|
||||
if (a === b) return true;
|
||||
if (!a || !b) return false;
|
||||
const aKeys = Object.keys(a) as (keyof Job)[];
|
||||
return (
|
||||
aKeys.length === Object.keys(b).length &&
|
||||
aKeys.every((k) => a[k] === b[k])
|
||||
);
|
||||
}
|
||||
|
||||
export default function JobQueue({ jobType, jobTypesForList }: JobQueueProps) {
|
||||
const [jobs, setJobs] = React.useState<Job[]>([]);
|
||||
const { nonce } = useStore(jobsRefreshStore);
|
||||
const { activeJobId } = useStore(activeJobStore);
|
||||
|
||||
// Stable primitive key so the memoized list below keeps its identity when an
|
||||
// inline array prop (e.g. ['finetuning', 'lora']) gets a fresh reference each
|
||||
// render, which would otherwise re-run the fetch effects needlessly.
|
||||
const typesKey = (jobTypesForList ?? [jobType]).join(',');
|
||||
const typesToFetch = React.useMemo<JobType[]>(
|
||||
() => jobTypesForList ?? [jobType],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[typesKey],
|
||||
);
|
||||
|
||||
// Guard the poll against slow responses: `inFlight` lets the interval skip
|
||||
// a tick instead of stacking requests, and the sequence counter drops
|
||||
// out-of-order responses so a delayed older payload can't overwrite a newer
|
||||
// job list (direct refetches always run and supersede in-flight polls).
|
||||
const fetchSeq = React.useRef(0);
|
||||
const inFlight = React.useRef(false);
|
||||
|
||||
const fetchJobs = React.useCallback(async () => {
|
||||
const seq = ++fetchSeq.current;
|
||||
inFlight.current = true;
|
||||
try {
|
||||
let next: Job[];
|
||||
if (typesToFetch.length === 1) {
|
||||
next = await getJobsList(typesToFetch[0]);
|
||||
} else {
|
||||
const results = await Promise.all(
|
||||
typesToFetch.map((t) => getJobsList(t)),
|
||||
);
|
||||
next = results
|
||||
.flat()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
new Date(b.created_at ?? 0).getTime() -
|
||||
new Date(a.created_at ?? 0).getTime(),
|
||||
);
|
||||
}
|
||||
if (seq === fetchSeq.current) setJobs(next);
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch jobs:', e);
|
||||
} finally {
|
||||
if (seq === fetchSeq.current) inFlight.current = false;
|
||||
}
|
||||
}, [typesKey]);
|
||||
|
||||
// Keep the latest fetchJobs reachable from the polling interval without
|
||||
// tearing it down/recreating it on every fetchJobs identity change.
|
||||
const fetchJobsRef = React.useRef(fetchJobs);
|
||||
React.useEffect(() => {
|
||||
fetchJobsRef.current = fetchJobs;
|
||||
}, [fetchJobs]);
|
||||
|
||||
// Initial fetch + refetch whenever an external refresh is triggered.
|
||||
React.useEffect(() => {
|
||||
fetchJobs();
|
||||
}, [fetchJobs, nonce]);
|
||||
|
||||
// Poll every second while any job is running/pending; stop otherwise.
|
||||
const hasActive = jobs.some(
|
||||
(j) => j.status === 'running' || j.status === 'pending',
|
||||
);
|
||||
React.useEffect(() => {
|
||||
if (!hasActive) return;
|
||||
const interval = setInterval(() => {
|
||||
if (!inFlight.current) fetchJobsRef.current();
|
||||
}, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [hasActive]);
|
||||
|
||||
// Keep the active job in sync with the selected id, and void the selection
|
||||
// if its job disappeared (e.g. deleted). Skip the store write when nothing
|
||||
// changed — each poll returns fresh objects, and an unconditional write
|
||||
// would re-render every subscriber (shell, sidebars, cards) once a second.
|
||||
React.useEffect(() => {
|
||||
if (!activeJobId) {
|
||||
if (activeJobStore.get().activeJob) setActiveJob(null);
|
||||
return;
|
||||
}
|
||||
const activeJob = jobs.find((j) => j.id === activeJobId) ?? null;
|
||||
if (!jobsShallowEqual(activeJob, activeJobStore.get().activeJob)) {
|
||||
setActiveJob(activeJob);
|
||||
}
|
||||
if (!activeJob) setActiveJobId(null);
|
||||
}, [activeJobId, jobs]);
|
||||
|
||||
const multiType = typesToFetch.length > 1;
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-[850px] flex-col gap-6 px-4 pb-12">
|
||||
<section className="p-6">
|
||||
<div>
|
||||
{jobs.length === 0 ? (
|
||||
<p className="py-8 text-center text-muted-foreground">
|
||||
No {multiType ? 'jobs' : `${jobType} jobs`} yet. Create one above.
|
||||
</p>
|
||||
) : (
|
||||
jobs.map((job) => (
|
||||
<JobCard key={job.id} job={job} onJobUpdated={fetchJobs} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
import DatasetSidebar from '@/components/datasets/DatasetSidebar';
|
||||
import Header from '@/components/shell/Header';
|
||||
import { HeaderActionsProvider } from '@/components/shell/HeaderActionsContext';
|
||||
import PrimarySidebar from '@/components/shell/PrimarySidebar';
|
||||
import JobDetailsSidebar from '@/components/jobs/JobDetailsSidebar';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { useStore } from '@/hooks/useStore';
|
||||
import {
|
||||
activeDatasetStore,
|
||||
setActiveDatasetId,
|
||||
} from '@/stores/activeDataset';
|
||||
import { activeJobStore, setActiveJobId } from '@/stores/activeJob';
|
||||
import { initDefaultOptions } from '@/stores/defaultOptions';
|
||||
|
||||
const JOB_ROUTES = ['/inference', '/finetuning', '/distillation'];
|
||||
|
||||
export function AppShell({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const { activeJob } = useStore(activeJobStore);
|
||||
const { activeDataset } = useStore(activeDatasetStore);
|
||||
|
||||
const [primaryWidth, setPrimaryWidth] = React.useState(220);
|
||||
const [secondaryWidth, setSecondaryWidth] = React.useState(0);
|
||||
|
||||
const jobSidebarOpen = JOB_ROUTES.includes(pathname) && activeJob != null;
|
||||
const datasetSidebarOpen =
|
||||
pathname === '/datasets' && activeDataset != null;
|
||||
const secondaryOpen = jobSidebarOpen || datasetSidebarOpen;
|
||||
|
||||
React.useEffect(() => {
|
||||
initDefaultOptions();
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape' && !document.querySelector('[data-modal]')) {
|
||||
if (activeJobStore.get().activeJob) setActiveJobId(null);
|
||||
if (activeDatasetStore.get().activeDataset) setActiveDatasetId(null);
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<HeaderActionsProvider>
|
||||
<Header />
|
||||
<div
|
||||
className="flex overflow-hidden"
|
||||
style={{
|
||||
marginTop: 'var(--header-height)',
|
||||
height: 'calc(100vh - var(--header-height))',
|
||||
}}
|
||||
>
|
||||
<PrimarySidebar onWidthChange={setPrimaryWidth} />
|
||||
<main
|
||||
className="flex min-w-0 flex-1 flex-col overflow-auto"
|
||||
style={{
|
||||
marginLeft: primaryWidth,
|
||||
marginRight: secondaryOpen ? secondaryWidth : 0,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
{jobSidebarOpen && activeJob && (
|
||||
<JobDetailsSidebar
|
||||
job={activeJob}
|
||||
onClose={() => setActiveJobId(null)}
|
||||
onWidthChange={setSecondaryWidth}
|
||||
/>
|
||||
)}
|
||||
{datasetSidebarOpen && activeDataset && (
|
||||
<DatasetSidebar
|
||||
dataset={activeDataset}
|
||||
onClose={() => setActiveDatasetId(null)}
|
||||
onWidthChange={setSecondaryWidth}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Toaster />
|
||||
</HeaderActionsProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
import { useHeaderActions } from '@/components/shell/HeaderActionsContext';
|
||||
import { ThemeToggle } from '@/components/ui/theme-toggle';
|
||||
|
||||
const TAB_TITLES: Record<string, string> = {
|
||||
'/inference': 'Jobs',
|
||||
'/finetuning': 'Jobs',
|
||||
'/distillation': 'Jobs',
|
||||
'/datasets': 'Datasets',
|
||||
'/gallery': 'Gallery',
|
||||
'/gpus': 'GPUs',
|
||||
'/settings': 'Settings',
|
||||
};
|
||||
|
||||
export default function Header() {
|
||||
const pathname = usePathname();
|
||||
const { actions } = useHeaderActions();
|
||||
const title = TAB_TITLES[pathname] ?? 'FastVideo';
|
||||
|
||||
return (
|
||||
<header className="fixed inset-x-0 top-0 z-[100] flex h-[var(--header-height)] items-center gap-6 border-b border-border bg-background/80 px-6 backdrop-blur">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src="/logo.svg"
|
||||
alt="FastVideo Logo"
|
||||
width={100}
|
||||
height={42}
|
||||
className="block h-[42px] w-[100px]"
|
||||
/>
|
||||
<h1 className="m-0 flex-1 text-xl font-semibold tracking-tight">
|
||||
{title}
|
||||
</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
{actions}
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
interface HeaderActionsContextValue {
|
||||
actions: React.ReactNode;
|
||||
setActions: (node: React.ReactNode) => void;
|
||||
}
|
||||
|
||||
const HeaderActionsContext =
|
||||
React.createContext<HeaderActionsContextValue | null>(null);
|
||||
|
||||
export function HeaderActionsProvider({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const [actions, setActions] = React.useState<React.ReactNode>(null);
|
||||
const value = React.useMemo(() => ({ actions, setActions }), [actions]);
|
||||
return (
|
||||
<HeaderActionsContext.Provider value={value}>
|
||||
{children}
|
||||
</HeaderActionsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useHeaderActions(): HeaderActionsContextValue {
|
||||
const ctx = React.useContext(HeaderActionsContext);
|
||||
if (!ctx) {
|
||||
throw new Error(
|
||||
'useHeaderActions must be used within a HeaderActionsProvider',
|
||||
);
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declaratively publish the current page's header actions: renders nothing,
|
||||
* registers `children` in the header on mount and clears them on unmount.
|
||||
* Pages without actions simply don't render it.
|
||||
*/
|
||||
export function HeaderActions({ children }: { children: React.ReactNode }) {
|
||||
const { setActions } = useHeaderActions();
|
||||
// Mount-only on purpose: pages pass inline JSX, which is referentially new
|
||||
// every render and would re-register per render if it were a dependency.
|
||||
React.useEffect(() => {
|
||||
setActions(children);
|
||||
return () => setActions(null);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [setActions]);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
import { useResizable } from '@/hooks/useResizable';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 100;
|
||||
const SIDEBAR_MAX_WIDTH = 300;
|
||||
const SIDEBAR_COLLAPSED_WIDTH = 0;
|
||||
const SIDEBAR_COLLAPSED_VISIBLE_WIDTH = 60;
|
||||
|
||||
const JOB_ROUTES = [
|
||||
{ href: '/inference', label: 'Inference' },
|
||||
{ href: '/finetuning', label: 'Finetuning' },
|
||||
{ href: '/distillation', label: 'Distillation' },
|
||||
] as const;
|
||||
|
||||
const TAB_BASE =
|
||||
'block px-5 py-[0.65rem] text-left text-sm text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground';
|
||||
const TAB_ACTIVE = 'bg-accent-blue/10 font-medium text-accent-blue';
|
||||
|
||||
export default function PrimarySidebar({
|
||||
onWidthChange,
|
||||
}: {
|
||||
onWidthChange?: (w: number) => void;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const [width, setWidth] = React.useState(220);
|
||||
const [isCollapsed, setIsCollapsed] = React.useState(false);
|
||||
const [isDragging, setIsDragging] = React.useState(false);
|
||||
const [jobsOpen, setJobsOpen] = React.useState(true);
|
||||
|
||||
const effectiveWidth = isCollapsed ? SIDEBAR_COLLAPSED_WIDTH : width;
|
||||
const layoutWidth = isCollapsed ? SIDEBAR_COLLAPSED_VISIBLE_WIDTH : width;
|
||||
const isJobsActive = JOB_ROUTES.some((r) => pathname === r.href);
|
||||
|
||||
React.useEffect(() => {
|
||||
onWidthChange?.(layoutWidth);
|
||||
}, [layoutWidth, onWidthChange]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (JOB_ROUTES.some((r) => pathname === r.href)) {
|
||||
setJobsOpen(true);
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
const { onMouseDown } = useResizable({
|
||||
edge: 'left',
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: setWidth,
|
||||
onDragChange: setIsDragging,
|
||||
});
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="fixed bottom-0 left-0 top-[var(--header-height)] z-50 flex max-h-[calc(100vh-var(--header-height))] shrink-0 flex-col border-r border-border bg-card"
|
||||
style={{ width: effectiveWidth }}
|
||||
>
|
||||
{!isCollapsed && (
|
||||
<nav className="flex flex-col py-2">
|
||||
<div className="flex flex-col">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setJobsOpen((v) => !v)}
|
||||
aria-expanded={jobsOpen}
|
||||
aria-haspopup="true"
|
||||
className={cn(
|
||||
TAB_BASE,
|
||||
'flex w-full cursor-pointer items-center justify-between',
|
||||
isJobsActive && TAB_ACTIVE,
|
||||
)}
|
||||
>
|
||||
<span>Jobs</span>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
className={cn(
|
||||
'h-4 w-4 shrink-0 opacity-85 transition-transform',
|
||||
jobsOpen && 'rotate-180',
|
||||
)}
|
||||
>
|
||||
<path d="M6 9l6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
{jobsOpen && (
|
||||
<div className="mb-1 ml-4 flex flex-col border-l-2 border-border pl-2">
|
||||
{JOB_ROUTES.map((route) => (
|
||||
<Link
|
||||
key={route.href}
|
||||
href={route.href}
|
||||
className={cn(
|
||||
TAB_BASE,
|
||||
'px-4 py-2 text-[0.85rem]',
|
||||
pathname === route.href && TAB_ACTIVE,
|
||||
)}
|
||||
>
|
||||
{route.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
href="/datasets"
|
||||
className={cn(TAB_BASE, pathname === '/datasets' && TAB_ACTIVE)}
|
||||
>
|
||||
Datasets
|
||||
</Link>
|
||||
<Link
|
||||
href="/gallery"
|
||||
className={cn(TAB_BASE, pathname === '/gallery' && TAB_ACTIVE)}
|
||||
>
|
||||
Gallery
|
||||
</Link>
|
||||
<Link
|
||||
href="/gpus"
|
||||
className={cn(TAB_BASE, pathname === '/gpus' && TAB_ACTIVE)}
|
||||
>
|
||||
GPUs
|
||||
</Link>
|
||||
<Link
|
||||
href="/settings"
|
||||
className={cn(TAB_BASE, pathname === '/settings' && TAB_ACTIVE)}
|
||||
>
|
||||
Settings
|
||||
</Link>
|
||||
</nav>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'absolute bottom-0 p-2',
|
||||
isCollapsed ? '-right-[60px] top-0' : 'right-0',
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsCollapsed((v) => !v)}
|
||||
title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
|
||||
className={cn(
|
||||
'flex items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
|
||||
isCollapsed ? 'p-3' : 'p-2',
|
||||
)}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
className="h-[18px] w-[18px]"
|
||||
>
|
||||
<path d={isCollapsed ? 'M9 18l6-6-6-6' : 'M15 18l-6-6 6-6'} />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!isCollapsed && (
|
||||
<div
|
||||
role="presentation"
|
||||
onMouseDown={onMouseDown}
|
||||
className={cn(
|
||||
'absolute bottom-0 right-0 top-0 z-[1] w-1.5 cursor-col-resize hover:bg-accent-blue/25',
|
||||
isDragging && 'bg-accent-blue/25',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import GpuGrid from './GpuGrid';
|
||||
import { getGpus } from '@/lib/api';
|
||||
import type { GpuSnapshot } from '@/lib/api';
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
getGpus: vi.fn(),
|
||||
}));
|
||||
|
||||
const SNAPSHOT: GpuSnapshot = {
|
||||
available: true,
|
||||
error: null,
|
||||
gpus: [
|
||||
{
|
||||
index: 0,
|
||||
name: 'NVIDIA B200',
|
||||
utilization: 62,
|
||||
memory_used_mib: 61_440,
|
||||
memory_total_mib: 183_359,
|
||||
temperature_c: 41,
|
||||
power_watts: 312.4,
|
||||
power_limit_watts: 1000,
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
name: 'NVIDIA B200',
|
||||
utilization: 0,
|
||||
memory_used_mib: 1_024,
|
||||
memory_total_mib: 183_359,
|
||||
temperature_c: null,
|
||||
power_watts: null,
|
||||
power_limit_watts: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getGpus).mockResolvedValue(SNAPSHOT);
|
||||
});
|
||||
|
||||
describe('GpuGrid', () => {
|
||||
it('renders a card per GPU with utilization and memory', async () => {
|
||||
render(<GpuGrid />);
|
||||
|
||||
expect(await screen.findAllByText('NVIDIA B200')).toHaveLength(2);
|
||||
expect(screen.getByText('GPU 0')).toBeInTheDocument();
|
||||
expect(screen.getByText('GPU 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('62%')).toBeInTheDocument();
|
||||
expect(screen.getByText('60.0 GiB / 179.1 GiB')).toBeInTheDocument();
|
||||
// Optional sensors render only when present.
|
||||
expect(screen.getByText('41°C')).toBeInTheDocument();
|
||||
expect(screen.getByText('312 W / 1000 W')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the backend-reported reason when telemetry is unavailable', async () => {
|
||||
vi.mocked(getGpus).mockResolvedValue({
|
||||
available: false,
|
||||
gpus: [],
|
||||
error: 'NVML Shared Library Not Found',
|
||||
});
|
||||
render(<GpuGrid />);
|
||||
expect(
|
||||
await screen.findByText(/GPU telemetry unavailable: NVML/),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('explains when the API server is unreachable', async () => {
|
||||
vi.mocked(getGpus).mockRejectedValue(new Error('network down'));
|
||||
render(<GpuGrid />);
|
||||
expect(
|
||||
await screen.findByText(/Could not reach the API server/),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { getGpus, type GpuInfo, type GpuSnapshot } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
|
||||
function formatGib(mib: number): string {
|
||||
return `${(mib / 1024).toFixed(1)} GiB`;
|
||||
}
|
||||
|
||||
function Meter({
|
||||
label,
|
||||
percent,
|
||||
detail,
|
||||
warnAt,
|
||||
}: {
|
||||
label: string;
|
||||
percent: number;
|
||||
detail: string;
|
||||
/** Turn the fill rose at this percentage (e.g. VRAM pressure). */
|
||||
warnAt?: number;
|
||||
}) {
|
||||
const clamped = Math.max(0, Math.min(100, percent));
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-baseline justify-between gap-2 text-xs">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="font-medium tabular-nums text-foreground">
|
||||
{detail}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
role="meter"
|
||||
aria-label={label}
|
||||
aria-valuenow={Math.round(clamped)}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
className="h-1.5 overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'h-full rounded-full bg-accent-blue transition-[width] duration-500',
|
||||
warnAt !== undefined && clamped >= warnAt && 'bg-rose-500',
|
||||
)}
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GpuCard({ gpu }: { gpu: GpuInfo }) {
|
||||
const memPercent =
|
||||
gpu.memory_total_mib > 0
|
||||
? (gpu.memory_used_mib / gpu.memory_total_mib) * 100
|
||||
: 0;
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-4 p-5">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="min-w-0 truncate text-sm font-semibold">
|
||||
{gpu.name}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
||||
GPU {gpu.index}
|
||||
</span>
|
||||
</div>
|
||||
<Meter
|
||||
label="Utilization"
|
||||
percent={gpu.utilization}
|
||||
detail={`${gpu.utilization}%`}
|
||||
/>
|
||||
<Meter
|
||||
label="Memory"
|
||||
percent={memPercent}
|
||||
warnAt={90}
|
||||
detail={`${formatGib(gpu.memory_used_mib)} / ${formatGib(gpu.memory_total_mib)}`}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1 text-xs tabular-nums text-muted-foreground">
|
||||
{gpu.temperature_c != null && <span>{gpu.temperature_c}°C</span>}
|
||||
{gpu.power_watts != null && (
|
||||
<span>
|
||||
{Math.round(gpu.power_watts)} W
|
||||
{gpu.power_limit_watts != null &&
|
||||
` / ${Math.round(gpu.power_limit_watts)} W`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function GpuGrid() {
|
||||
const [snapshot, setSnapshot] = React.useState<GpuSnapshot | null>(null);
|
||||
const [fetchError, setFetchError] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
let mounted = true;
|
||||
let inFlight = false;
|
||||
|
||||
async function poll() {
|
||||
if (inFlight) return;
|
||||
inFlight = true;
|
||||
try {
|
||||
const next = await getGpus();
|
||||
if (mounted) {
|
||||
setSnapshot(next);
|
||||
setFetchError(false);
|
||||
}
|
||||
} catch {
|
||||
if (mounted) setFetchError(true);
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
poll();
|
||||
const interval = setInterval(poll, POLL_INTERVAL_MS);
|
||||
return () => {
|
||||
mounted = false;
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (fetchError && !snapshot) {
|
||||
return (
|
||||
<p className="py-8 text-center text-muted-foreground">
|
||||
Could not reach the API server. GPU status needs the studio API server
|
||||
running.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (!snapshot) {
|
||||
return <p className="py-8 text-center text-muted-foreground">Loading…</p>;
|
||||
}
|
||||
if (!snapshot.available) {
|
||||
return (
|
||||
<p className="py-8 text-center text-muted-foreground">
|
||||
GPU telemetry unavailable
|
||||
{snapshot.error ? `: ${snapshot.error}` : '.'}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{fetchError && (
|
||||
<p className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-600 dark:text-amber-400">
|
||||
Lost contact with the API server — showing the last known values.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(280px,1fr))]">
|
||||
{snapshot.gpus.map((gpu) => (
|
||||
<GpuCard key={gpu.index} gpu={gpu} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] transition-colors',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
'border-blue-400/35 bg-blue-500/15 text-blue-900 dark:text-blue-100',
|
||||
secondary: 'border-border bg-secondary text-secondary-foreground',
|
||||
outline: 'border-border bg-transparent text-muted-foreground',
|
||||
success:
|
||||
'border-emerald-400/30 bg-emerald-500/15 text-emerald-800 dark:text-emerald-100',
|
||||
warning:
|
||||
'border-amber-400/30 bg-amber-500/15 text-amber-800 dark:text-amber-100',
|
||||
destructive:
|
||||
'border-rose-400/30 bg-rose-500/15 text-rose-800 dark:text-rose-100',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl border !text-sm !font-semibold transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/40 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-slate-700 bg-slate-800 text-white shadow-md hover:bg-slate-700 dark:border-slate-300 dark:bg-slate-300 dark:text-slate-900 dark:hover:bg-slate-200",
|
||||
secondary: "border-input bg-card text-card-foreground hover:bg-accent",
|
||||
outline: "border-input bg-secondary text-secondary-foreground hover:bg-accent",
|
||||
ghost: "border-transparent bg-transparent text-foreground hover:bg-accent",
|
||||
destructive: "border-rose-500/60 bg-rose-600/90 text-white hover:bg-rose-500",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-lg px-3 !text-xs",
|
||||
lg: "h-11 px-5 !text-sm",
|
||||
icon: "size-10",
|
||||
"icon-sm": "size-8",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
|
||||
});
|
||||
Button.displayName = "Button";
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'rounded-2xl border border-border bg-card text-card-foreground shadow-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('flex flex-col gap-1.5 p-6', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
));
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('flex items-center p-6 pt-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
data-modal=""
|
||||
className={cn(
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-2xl border border-border bg-card p-6 text-card-foreground shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-lg p-1 text-muted-foreground opacity-70 transition-opacity hover:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-sky-400/40 disabled:pointer-events-none">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn('flex flex-col gap-1.5 text-left', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'text-lg font-semibold leading-none tracking-tight',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-xl border border-input bg-card/60 px-3 py-2 text-sm text-foreground shadow-sm backdrop-blur-md transition-colors placeholder:text-muted-foreground focus-visible:border-sky-400/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/25 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
});
|
||||
Input.displayName = "Input";
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const labelVariants = cva(
|
||||
'text-sm font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,24 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const NativeSelect = React.forwardRef<
|
||||
HTMLSelectElement,
|
||||
React.ComponentProps<'select'>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<select
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-10 w-full appearance-none rounded-xl border border-input bg-card px-3 py-2 text-sm text-foreground shadow-sm transition-colors focus-visible:border-sky-400/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/25 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
));
|
||||
NativeSelect.displayName = 'NativeSelect';
|
||||
|
||||
export { NativeSelect };
|
||||
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('relative overflow-hidden', className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
));
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = 'vertical', ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'flex touch-none select-none p-0.5 transition-colors',
|
||||
orientation === 'vertical' ? 'h-full w-2.5' : 'h-2.5 flex-col',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
));
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1,158 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between gap-2 rounded-xl border border-input bg-card px-3 py-2 text-sm text-foreground shadow-sm outline-none transition-colors placeholder:text-muted-foreground focus:border-sky-400/70 focus:ring-2 focus:ring-sky-400/25 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default items-center justify-center py-1 text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName =
|
||||
SelectPrimitive.ScrollUpButton.displayName;
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default items-center justify-center py-1 text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative z-50 max-h-80 min-w-[8rem] overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-lg backdrop-blur-sm',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('px-2 py-1.5 text-xs font-semibold text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-xl py-2 pl-8 pr-3 text-sm text-foreground outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4 text-accent-blue" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn('-mx-1 my-1 h-px bg-border', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(
|
||||
(
|
||||
{ className, orientation = 'horizontal', decorative = true, ...props },
|
||||
ref,
|
||||
) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'shrink-0 bg-border',
|
||||
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName;
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as SliderPrimitive from '@radix-ui/react-slider';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Slider = React.forwardRef<
|
||||
React.ElementRef<typeof SliderPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SliderPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full touch-none select-none items-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-border">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-accent-blue" />
|
||||
</SliderPrimitive.Track>
|
||||
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border-2 border-accent-blue bg-accent-blue shadow transition-colors hover:border-accent-blue/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/40 disabled:pointer-events-none disabled:opacity-50" />
|
||||
</SliderPrimitive.Root>
|
||||
));
|
||||
Slider.displayName = SliderPrimitive.Root.displayName;
|
||||
|
||||
export { Slider };
|
||||
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import { Toaster as Sonner, type ToasterProps } from 'sonner';
|
||||
|
||||
export function Toaster(props: ToasterProps) {
|
||||
return (
|
||||
<Sonner
|
||||
theme="dark"
|
||||
position="bottom-center"
|
||||
richColors={true}
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
'border border-border bg-card text-card-foreground shadow-lg',
|
||||
description: 'text-muted-foreground',
|
||||
actionButton:
|
||||
'bg-primary text-primary-foreground hover:bg-primary/90',
|
||||
cancelButton:
|
||||
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as SwitchPrimitives from '@radix-ui/react-switch';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/40 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-accent-blue data-[state=checked]:bg-accent-blue data-[state=unchecked]:bg-background',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
'pointer-events-none block h-3.5 w-3.5 rounded-full bg-muted-foreground shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=checked]:bg-white data-[state=unchecked]:translate-x-0.5',
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
));
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||
|
||||
export { Switch };
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center rounded-lg border border-border bg-background p-0.5 text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/40 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn('mt-2 focus-visible:outline-none', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentProps<"textarea">>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-24 w-full resize-y rounded-xl border border-input bg-card px-3 py-2 text-sm text-foreground shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:border-sky-400/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/25 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
});
|
||||
Textarea.displayName = "Textarea";
|
||||
|
||||
export { Textarea };
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { Moon, Sun } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
/**
|
||||
* Light/dark switch (ported from Dreamverse). The studio defaults to dark —
|
||||
* layout.tsx applies the stored choice before paint; this button just
|
||||
* mirrors and persists it.
|
||||
*/
|
||||
function ThemeToggle({ className }: { className?: string }) {
|
||||
const [dark, setDark] = React.useState(true);
|
||||
|
||||
React.useEffect(() => {
|
||||
setDark(document.documentElement.classList.contains('dark'));
|
||||
}, []);
|
||||
|
||||
const transitionTimer =
|
||||
React.useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
|
||||
function toggle() {
|
||||
const next = !dark;
|
||||
setDark(next);
|
||||
|
||||
clearTimeout(transitionTimer.current);
|
||||
document.documentElement.classList.add('theme-transition');
|
||||
document.documentElement.classList.toggle('dark', next);
|
||||
|
||||
transitionTimer.current = setTimeout(() => {
|
||||
document.documentElement.classList.remove('theme-transition');
|
||||
}, 350);
|
||||
|
||||
try {
|
||||
localStorage.setItem('theme', next ? 'dark' : 'light');
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => clearTimeout(transitionTimer.current);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={toggle}
|
||||
aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
|
||||
className={className}
|
||||
>
|
||||
{dark ? <Sun className="size-4" /> : <Moon className="size-4" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export { ThemeToggle };
|
||||
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
export type ResizableEdge = 'left' | 'right';
|
||||
|
||||
export interface UseResizableOptions {
|
||||
/** Which edge is fixed: "left" = drag right grows; "right" = drag left grows. */
|
||||
edge: ResizableEdge;
|
||||
minWidth: number;
|
||||
maxWidth: number;
|
||||
/** Return current width (e.g. from parent state). */
|
||||
getWidth: () => number;
|
||||
/** Called with the new width while the user drags. */
|
||||
onWidth: (width: number) => void;
|
||||
/** Optional: notified when a drag starts/stops. */
|
||||
onDragChange?: (dragging: boolean) => void;
|
||||
}
|
||||
|
||||
export interface UseResizableResult {
|
||||
onMouseDown: (event: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* React port of the Svelte `resizable` action. Spread the returned
|
||||
* `onMouseDown` onto a drag handle; the parent owns the width state.
|
||||
*/
|
||||
export function useResizable(
|
||||
options: UseResizableOptions,
|
||||
): UseResizableResult {
|
||||
const optionsRef = React.useRef(options);
|
||||
optionsRef.current = options;
|
||||
|
||||
const dragStart = React.useRef({ x: 0, width: 0 });
|
||||
const dragging = React.useRef(false);
|
||||
|
||||
const onMouseMove = React.useCallback((e: MouseEvent) => {
|
||||
const opts = optionsRef.current;
|
||||
const delta = e.clientX - dragStart.current.x;
|
||||
const sign = opts.edge === 'left' ? 1 : -1;
|
||||
const newWidth = Math.min(
|
||||
opts.maxWidth,
|
||||
Math.max(opts.minWidth, dragStart.current.width + sign * delta),
|
||||
);
|
||||
opts.onWidth(newWidth);
|
||||
}, []);
|
||||
|
||||
const onMouseUp = React.useCallback(() => {
|
||||
dragging.current = false;
|
||||
optionsRef.current.onDragChange?.(false);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
}, [onMouseMove]);
|
||||
|
||||
const onMouseDown = React.useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const opts = optionsRef.current;
|
||||
dragStart.current = { x: e.clientX, width: opts.getWidth() };
|
||||
dragging.current = true;
|
||||
opts.onDragChange?.(true);
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
},
|
||||
[onMouseMove, onMouseUp],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
if (dragging.current) {
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
};
|
||||
}, [onMouseMove, onMouseUp]);
|
||||
|
||||
return { onMouseDown };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
import type { ManagedStore } from '@/stores/createManagedStore';
|
||||
|
||||
export function useStore<T>(
|
||||
store: ManagedStore<T>,
|
||||
): T {
|
||||
return useSyncExternalStore(
|
||||
store.subscribe,
|
||||
store.get,
|
||||
store.getServerSnapshot,
|
||||
);
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* Svelte action: attach horizontal resize behavior to a handle element.
|
||||
* Use on the resize-handle div inside a sidebar; the parent holds width state.
|
||||
*/
|
||||
|
||||
export type ResizableEdge = "left" | "right";
|
||||
|
||||
export interface ResizableOptions {
|
||||
/** Which edge is fixed: "left" = drag right increases width, "right" = drag left increases width */
|
||||
edge: ResizableEdge;
|
||||
minWidth: number;
|
||||
maxWidth: number;
|
||||
/** Return current width (e.g. from parent state) */
|
||||
getWidth: () => number;
|
||||
/** Called with new width when user drags */
|
||||
onWidth: (width: number) => void;
|
||||
/** Optional: called when drag starts/stops so parent can show active state */
|
||||
onDragChange?: (dragging: boolean) => void;
|
||||
}
|
||||
|
||||
export function resizable(
|
||||
node: HTMLElement,
|
||||
options: ResizableOptions,
|
||||
): { update?: (opts: ResizableOptions) => void; destroy?: () => void } {
|
||||
let dragStart = { x: 0, width: 0 };
|
||||
let listenersAttached = false;
|
||||
|
||||
function onMouseMove(e: MouseEvent) {
|
||||
const delta = e.clientX - dragStart.x;
|
||||
const sign = options.edge === "left" ? 1 : -1;
|
||||
const newWidth = Math.min(
|
||||
options.maxWidth,
|
||||
Math.max(options.minWidth, dragStart.width + sign * delta),
|
||||
);
|
||||
options.onWidth(newWidth);
|
||||
}
|
||||
|
||||
function onMouseUp() {
|
||||
listenersAttached = false;
|
||||
options.onDragChange?.(false);
|
||||
document.body.style.cursor = "";
|
||||
document.body.style.userSelect = "";
|
||||
document.removeEventListener("mousemove", onMouseMove);
|
||||
document.removeEventListener("mouseup", onMouseUp);
|
||||
}
|
||||
|
||||
function onMouseDown(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
dragStart = { x: e.clientX, width: options.getWidth() };
|
||||
listenersAttached = true;
|
||||
options.onDragChange?.(true);
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
document.addEventListener("mousemove", onMouseMove);
|
||||
document.addEventListener("mouseup", onMouseUp);
|
||||
}
|
||||
|
||||
node.addEventListener("mousedown", onMouseDown);
|
||||
|
||||
return {
|
||||
update(newOptions: ResizableOptions) {
|
||||
options = newOptions;
|
||||
},
|
||||
destroy() {
|
||||
node.removeEventListener("mousedown", onMouseDown);
|
||||
if (listenersAttached) {
|
||||
options.onDragChange?.(false);
|
||||
document.body.style.cursor = "";
|
||||
document.body.style.userSelect = "";
|
||||
document.removeEventListener("mousemove", onMouseMove);
|
||||
document.removeEventListener("mouseup", onMouseUp);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,30 +1,52 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { env } from "$env/dynamic/public";
|
||||
import type { Job, JobType } from "$lib/types";
|
||||
import {
|
||||
STORAGE_KEY,
|
||||
loadDefaultOptions,
|
||||
type DefaultOptions,
|
||||
} from "./defaultOptions";
|
||||
import type { Job, JobType } from "./types";
|
||||
|
||||
const DEFAULT_API_BASE_URL = "http://localhost:8189/api";
|
||||
|
||||
// getApiBaseUrl runs on every request and in render paths (media URL
|
||||
// builders), so cache the configured URL keyed on the raw stored options
|
||||
// string instead of re-parsing the options JSON each call.
|
||||
let cachedRaw: string | null = null;
|
||||
let cachedConfigured = "";
|
||||
|
||||
export function getApiBaseUrl(): string {
|
||||
// 1) Check user-configured value from local storage (Settings page)
|
||||
// 1) Check user-configured value from the persisted options (Settings
|
||||
// page). The settings sync persists the full options object, so the key
|
||||
// holds an empty string until the user sets a URL — treat that as unset
|
||||
// and fall through to the env/default below.
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
const stored = window.localStorage.getItem("fastvideo-default-options");
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored) as { apiServerBaseUrl?: string };
|
||||
return parsed.apiServerBaseUrl!.trim();
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (raw !== cachedRaw) {
|
||||
cachedRaw = raw;
|
||||
cachedConfigured = stripTrailingSlash(
|
||||
loadDefaultOptions().apiServerBaseUrl.trim(),
|
||||
);
|
||||
}
|
||||
if (cachedConfigured) return cachedConfigured;
|
||||
} catch {
|
||||
// Ignore storage / JSON errors and fall back to env/default
|
||||
// Ignore storage errors and fall back to env/default
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Fall back to env var if set, then hardcoded default
|
||||
const fromEnv = process.env.NEXT_PUBLIC_API_BASE_URL;
|
||||
const apiUrl =
|
||||
typeof env.PUBLIC_API_BASE_URL === "string" && env.PUBLIC_API_BASE_URL
|
||||
? env.PUBLIC_API_BASE_URL
|
||||
: DEFAULT_API_BASE_URL;
|
||||
return apiUrl;
|
||||
typeof fromEnv === "string" && fromEnv ? fromEnv : DEFAULT_API_BASE_URL;
|
||||
return stripTrailingSlash(apiUrl);
|
||||
}
|
||||
|
||||
// The base URL is used as a prefix in `${base}/jobs` template strings, so a
|
||||
// trailing slash (a natural thing to paste into Settings) would produce `//`
|
||||
// and 404 every request.
|
||||
function stripTrailingSlash(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/** Full URL for streaming a job's video/image output (for <video> or <img> src). */
|
||||
@@ -64,41 +86,44 @@ export interface CreateJobRequest {
|
||||
vsa_sparsity?: number;
|
||||
tp_size?: number;
|
||||
sp_size?: number;
|
||||
// DMD distillation extras (sent by CreateJobModal)
|
||||
dmd_use_vsa?: boolean;
|
||||
dmd_vsa_sparsity?: number;
|
||||
dmd_denoising_steps?: string;
|
||||
real_score_guidance_scale?: number;
|
||||
generator_update_interval?: number;
|
||||
real_score_model_path?: string;
|
||||
fake_score_model_path?: string;
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
label: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
defaultModelId: string;
|
||||
defaultModelIdT2v: string;
|
||||
defaultModelIdI2v: string;
|
||||
defaultModelIdT2i: string;
|
||||
numInferenceSteps: number;
|
||||
numFrames: number;
|
||||
height: number;
|
||||
width: number;
|
||||
guidanceScale: number;
|
||||
guidanceRescale: number;
|
||||
fps: number;
|
||||
seed: number;
|
||||
numGpus: number;
|
||||
ditCpuOffload: boolean;
|
||||
textEncoderCpuOffload: boolean;
|
||||
vaeCpuOffload: boolean;
|
||||
imageEncoderCpuOffload: boolean;
|
||||
useFsdpInference: boolean;
|
||||
enableTorchCompile: boolean;
|
||||
vsaSparsity: number;
|
||||
tpSize: number;
|
||||
spSize: number;
|
||||
autoStartJob: boolean;
|
||||
datasetUploadPath: string;
|
||||
export interface GpuInfo {
|
||||
index: number;
|
||||
name: string;
|
||||
utilization: number;
|
||||
memory_used_mib: number;
|
||||
memory_total_mib: number;
|
||||
temperature_c: number | null;
|
||||
power_watts: number | null;
|
||||
power_limit_watts: number | null;
|
||||
}
|
||||
|
||||
export interface GpuSnapshot {
|
||||
available: boolean;
|
||||
gpus: GpuInfo[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-persisted settings: everything in DefaultOptions except
|
||||
* apiServerBaseUrl, which is purely local (per-browser).
|
||||
*/
|
||||
export type Settings = Omit<DefaultOptions, "apiServerBaseUrl">;
|
||||
|
||||
// MARK: - API Functions
|
||||
|
||||
export async function getSettings(): Promise<Settings> {
|
||||
@@ -177,6 +202,15 @@ export async function getModels(workloadType?: string): Promise<Model[]> {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getGpus(): Promise<GpuSnapshot> {
|
||||
const baseApiUrl = getApiBaseUrl();
|
||||
const response = await fetch(`${baseApiUrl}/gpus`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch GPU status");
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getJobsList(jobType?: JobType): Promise<Job[]> {
|
||||
const baseApiUrl = getApiBaseUrl();
|
||||
const url = jobType
|
||||
@@ -204,15 +238,6 @@ export async function createJob(job: CreateJobRequest): Promise<Job> {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getJobDetails(id: string): Promise<Job> {
|
||||
const baseApiUrl = getApiBaseUrl();
|
||||
const response = await fetch(`${baseApiUrl}/jobs/${id}`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch job");
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function startJob(id: string): Promise<Job> {
|
||||
const baseApiUrl = getApiBaseUrl();
|
||||
const response = await fetch(`${baseApiUrl}/jobs/${id}/start`, {
|
||||
@@ -326,15 +351,6 @@ export async function getDatasets(): Promise<Dataset[]> {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getDataset(id: string): Promise<Dataset> {
|
||||
const baseApiUrl = getApiBaseUrl();
|
||||
const response = await fetch(`${baseApiUrl}/datasets/${id}`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch dataset");
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function createDataset(
|
||||
data: CreateDatasetRequest,
|
||||
): Promise<Dataset> {
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { createDatasetModalOpen } from "$lib/stores/createDatasetModalOpen";
|
||||
|
||||
function openModal() {
|
||||
createDatasetModalOpen.set(true);
|
||||
}
|
||||
</script>
|
||||
|
||||
<button type="button" class="btn btnPrimary" onclick={openModal}>
|
||||
Add Dataset
|
||||
</button>
|
||||
|
||||
<style>
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btnPrimary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
@@ -1,514 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { createDataset, uploadRawDataset } from "$lib/api";
|
||||
import UploadZone from "./UploadZone.svelte";
|
||||
import TabSwitch from "./TabSwitch.svelte";
|
||||
import {
|
||||
parseVideos2Caption,
|
||||
parseVideosCaptionsTxt,
|
||||
parseCaptionCsv,
|
||||
} from "$lib/captionParsing";
|
||||
|
||||
const ALLOWED_VIDEO_EXT = ".mp4,.webm,.avi,.mov,.mkv";
|
||||
|
||||
let {
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
} = $props();
|
||||
|
||||
let name = $state("");
|
||||
let isSubmitting = $state(false);
|
||||
let rawPath = $state("");
|
||||
let fileNames = $state<string[]>([]);
|
||||
let isUploading = $state(false);
|
||||
let validationError = $state<string | null>(null);
|
||||
let captionFormat = $state<"json" | "txt" | "csv">("json");
|
||||
let captionMap = $state<Record<string, string> | null>(null);
|
||||
let captionFileName = $state<string | null>(null);
|
||||
let videosTxtLines = $state<string[] | null>(null);
|
||||
let videosTxtFileName = $state<string | null>(null);
|
||||
let captionsTxtLines = $state<string[] | null>(null);
|
||||
let captionsTxtFileName = $state<string | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (captionFormat === "txt" && captionsTxtLines && fileNames.length > 0) {
|
||||
const hasVideosTxt =
|
||||
videosTxtLines &&
|
||||
videosTxtLines.length > 0 &&
|
||||
videosTxtLines.some((s) => s.trim());
|
||||
if (hasVideosTxt && videosTxtLines) {
|
||||
const { error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
validationError = error;
|
||||
} else {
|
||||
validationError = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const txtCaptionMap = $derived.by(() => {
|
||||
if (!captionsTxtLines || fileNames.length === 0) return null;
|
||||
const { captions, error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines ?? null,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
if (error) return null;
|
||||
return Object.keys(captions).length > 0 ? captions : null;
|
||||
});
|
||||
|
||||
const effectiveCaptionMap = $derived(
|
||||
captionFormat === "txt" ? txtCaptionMap : captionMap,
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === "Escape" && !isSubmitting) handleClose();
|
||||
}
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => document.removeEventListener("keydown", onKey);
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
if (isSubmitting) return;
|
||||
name = "";
|
||||
rawPath = "";
|
||||
fileNames = [];
|
||||
validationError = null;
|
||||
captionFormat = "json";
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
videosTxtLines = null;
|
||||
videosTxtFileName = null;
|
||||
captionsTxtLines = null;
|
||||
captionsTxtFileName = null;
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleCaptionJsonChange(files: File[]) {
|
||||
validationError = null;
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
if (files.length === 0) return;
|
||||
const file = files[0];
|
||||
try {
|
||||
const text = await file.text();
|
||||
const uploaded = fileNames.length > 0 ? fileNames : [];
|
||||
const { captions, error } = parseVideos2Caption(text, uploaded);
|
||||
if (error) {
|
||||
validationError = error;
|
||||
return;
|
||||
}
|
||||
captionMap = captions;
|
||||
captionFileName = file.name;
|
||||
} catch {
|
||||
validationError = "Could not read the file.";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVideosTxtChange(files: File[]) {
|
||||
validationError = null;
|
||||
videosTxtLines = null;
|
||||
videosTxtFileName = null;
|
||||
if (files.length === 0) return;
|
||||
try {
|
||||
const text = await files[0].text();
|
||||
videosTxtLines = text.split(/\r?\n/).map((s) => s.trim());
|
||||
videosTxtFileName = files[0].name;
|
||||
if (captionsTxtLines && fileNames.length > 0) {
|
||||
const { error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
if (error) validationError = error;
|
||||
}
|
||||
} catch {
|
||||
validationError = "Could not read videos.txt.";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCaptionsTxtChange(files: File[]) {
|
||||
validationError = null;
|
||||
captionsTxtLines = null;
|
||||
captionsTxtFileName = null;
|
||||
if (files.length === 0) return;
|
||||
try {
|
||||
const text = await files[0].text();
|
||||
captionsTxtLines = text.split(/\r?\n/).map((s) => s.trim());
|
||||
captionsTxtFileName = files[0].name;
|
||||
if (videosTxtLines && fileNames.length > 0) {
|
||||
const { error } = parseVideosCaptionsTxt(
|
||||
videosTxtLines,
|
||||
captionsTxtLines,
|
||||
fileNames,
|
||||
);
|
||||
if (error) validationError = error;
|
||||
}
|
||||
} catch {
|
||||
validationError = "Could not read captions.txt.";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCaptionCsvChange(files: File[]) {
|
||||
validationError = null;
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
if (files.length === 0) return;
|
||||
const file = files[0];
|
||||
try {
|
||||
const text = await file.text();
|
||||
const uploaded = fileNames.length > 0 ? fileNames : [];
|
||||
const { captions, error } = parseCaptionCsv(text, uploaded);
|
||||
if (error) {
|
||||
validationError = error;
|
||||
return;
|
||||
}
|
||||
captionMap = captions;
|
||||
captionFileName = file.name;
|
||||
} catch {
|
||||
validationError = "Could not read the file.";
|
||||
}
|
||||
}
|
||||
|
||||
function handleCaptionFormatChange(format: string) {
|
||||
captionFormat = format as "json" | "txt" | "csv";
|
||||
validationError = null;
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
videosTxtLines = null;
|
||||
videosTxtFileName = null;
|
||||
captionsTxtLines = null;
|
||||
captionsTxtFileName = null;
|
||||
}
|
||||
|
||||
async function handleMediaChange(files: File[]) {
|
||||
validationError = null;
|
||||
if (files.length === 0) {
|
||||
rawPath = "";
|
||||
fileNames = [];
|
||||
return;
|
||||
}
|
||||
isUploading = true;
|
||||
try {
|
||||
const res = await uploadRawDataset(files);
|
||||
rawPath = res.path;
|
||||
fileNames = res.file_names;
|
||||
if (res.file_names.length === 0) {
|
||||
validationError = `No video files found. Allowed: ${ALLOWED_VIDEO_EXT}`;
|
||||
}
|
||||
} catch (err) {
|
||||
rawPath = "";
|
||||
fileNames = [];
|
||||
validationError =
|
||||
err instanceof Error ? err.message : "Upload failed";
|
||||
} finally {
|
||||
isUploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
validationError = null;
|
||||
if (!name.trim()) return;
|
||||
if (!rawPath || fileNames.length === 0) {
|
||||
validationError = "No data was found. Upload at least one video.";
|
||||
return;
|
||||
}
|
||||
if (captionFormat === "json" || captionFormat === "csv") {
|
||||
if (captionFileName && !captionMap) {
|
||||
validationError =
|
||||
"Caption file has errors. Fix or remove it before creating the dataset.";
|
||||
return;
|
||||
}
|
||||
} else if (captionFormat === "txt") {
|
||||
if (videosTxtFileName || captionsTxtFileName) {
|
||||
if (!captionsTxtFileName) {
|
||||
validationError = "Upload captions.txt to use TXT captions.";
|
||||
return;
|
||||
}
|
||||
if (validationError) return;
|
||||
}
|
||||
}
|
||||
|
||||
const finalCaptionMap =
|
||||
effectiveCaptionMap && Object.keys(effectiveCaptionMap).length > 0
|
||||
? effectiveCaptionMap
|
||||
: null;
|
||||
if (finalCaptionMap) {
|
||||
const missing = fileNames.filter((fn) => !(fn in finalCaptionMap));
|
||||
if (missing.length > 0) {
|
||||
const list =
|
||||
missing.length <= 5
|
||||
? missing.join(", ")
|
||||
: `${missing.slice(0, 5).join(", ")} and ${missing.length - 5} more`;
|
||||
const ok = confirm(
|
||||
`The caption file does not include captions for ${missing.length} video(s): ${list}. They will get empty captions. Continue?`,
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
}
|
||||
|
||||
isSubmitting = true;
|
||||
try {
|
||||
await createDataset({
|
||||
name: name.trim(),
|
||||
upload_path: rawPath,
|
||||
file_names: fileNames,
|
||||
...(finalCaptionMap ? { captions: finalCaptionMap } : {}),
|
||||
});
|
||||
onSuccess();
|
||||
handleClose();
|
||||
} catch (err) {
|
||||
validationError =
|
||||
err instanceof Error ? err.message : "Failed to create dataset";
|
||||
} finally {
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isOpen}
|
||||
<div class="modal" data-modal>
|
||||
<div class="modalBackdrop" onclick={handleClose} role="presentation"></div>
|
||||
<div class="modalContent modalForm">
|
||||
<button
|
||||
class="modalClose"
|
||||
onclick={handleClose}
|
||||
disabled={isSubmitting}
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<div class="card">
|
||||
<h2>Add Dataset — Raw</h2>
|
||||
<form onsubmit={handleSubmit} autocomplete="off">
|
||||
<div class="formRow">
|
||||
<label for="add-dataset-name">Name</label>
|
||||
<input
|
||||
id="add-dataset-name"
|
||||
type="text"
|
||||
bind:value={name}
|
||||
placeholder="My dataset"
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label>Videos</label>
|
||||
<UploadZone
|
||||
label="Upload video files"
|
||||
hint="Select files or a folder (.mp4, .webm, .avi, .mov, .mkv)"
|
||||
accept={ALLOWED_VIDEO_EXT}
|
||||
multiple={true}
|
||||
directory={true}
|
||||
allowBothFileAndDirectory={true}
|
||||
value={rawPath}
|
||||
fileName={fileNames.length > 0 ? `${fileNames.length} file(s)` : undefined}
|
||||
onFileChange={handleMediaChange}
|
||||
onClear={() => {
|
||||
rawPath = "";
|
||||
fileNames = [];
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
validationError = null;
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
uploading={isUploading}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<div class="captionRow">
|
||||
<label>Captions (optional)</label>
|
||||
<TabSwitch
|
||||
options={[
|
||||
{ id: "json", label: "JSON" },
|
||||
{ id: "txt", label: "TXT" },
|
||||
{ id: "csv", label: "CSV" },
|
||||
]}
|
||||
value={captionFormat}
|
||||
onChange={handleCaptionFormatChange}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{#if captionFormat === "json"}
|
||||
<UploadZone
|
||||
label="Upload videos2caption.json"
|
||||
hint={'Array of { path, cap } or object mapping file names to captions'}
|
||||
accept=".json,application/json"
|
||||
value={captionFileName ? "1" : ""}
|
||||
fileName={captionFileName ?? undefined}
|
||||
onFileChange={handleCaptionJsonChange}
|
||||
onClear={() => {
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
validationError = null;
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{:else if captionFormat === "txt"}
|
||||
<div class="twoCol">
|
||||
<UploadZone
|
||||
label="Upload videos.txt (optional)"
|
||||
hint="One video path per line, or leave empty to match captions to videos in alphabetical order"
|
||||
accept=".txt,text/plain"
|
||||
value={videosTxtFileName ? "1" : ""}
|
||||
fileName={videosTxtFileName ?? undefined}
|
||||
onFileChange={handleVideosTxtChange}
|
||||
onClear={() => {
|
||||
videosTxtLines = null;
|
||||
videosTxtFileName = null;
|
||||
validationError = null;
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<UploadZone
|
||||
label="Upload captions.txt"
|
||||
hint="One caption per line (same order as videos.txt or alphabetical)"
|
||||
accept=".txt,text/plain"
|
||||
value={captionsTxtFileName ? "1" : ""}
|
||||
fileName={captionsTxtFileName ?? undefined}
|
||||
onFileChange={handleCaptionsTxtChange}
|
||||
onClear={() => {
|
||||
captionsTxtLines = null;
|
||||
captionsTxtFileName = null;
|
||||
validationError = null;
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<UploadZone
|
||||
label="Upload captions CSV"
|
||||
hint="Header: video_name, caption"
|
||||
accept=".csv,text/csv"
|
||||
value={captionFileName ? "1" : ""}
|
||||
fileName={captionFileName ?? undefined}
|
||||
onFileChange={handleCaptionCsvChange}
|
||||
onClear={() => {
|
||||
captionMap = null;
|
||||
captionFileName = null;
|
||||
validationError = null;
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{#if validationError}
|
||||
<p class="validationError">{validationError}</p>
|
||||
{/if}
|
||||
<button type="submit" class="btn btnPrimary" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Creating…" : "Create Dataset"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.modalBackdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
.modalContent {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0;
|
||||
max-width: 850px;
|
||||
width: 90vw;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.modalClose {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.75rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
font-size: 1.6rem;
|
||||
cursor: pointer;
|
||||
z-index: 2;
|
||||
}
|
||||
.card {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.card h2 {
|
||||
font-size: 1.15rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.formRow {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
.formRow label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.captionRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.captionRow label {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.twoCol {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.twoCol :global(> *) {
|
||||
flex: 1 1 0;
|
||||
min-width: 200px;
|
||||
}
|
||||
.validationError {
|
||||
color: var(--red);
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btnPrimary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
@@ -1,126 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { JobType } from "$lib/types";
|
||||
import { WORKLOAD_OPTIONS } from "$lib/jobConfig";
|
||||
import { triggerRefresh } from "$lib/stores/jobsRefresh";
|
||||
import CreateJobModal from "./CreateJobModal.svelte";
|
||||
|
||||
let { jobType }: { jobType: JobType } = $props();
|
||||
|
||||
let modalOpen = $state(false);
|
||||
const options = $derived(WORKLOAD_OPTIONS[jobType] ?? []);
|
||||
let workloadType = $state(options[0]?.type ?? "t2v");
|
||||
|
||||
function openModal(type: string) {
|
||||
workloadType = type;
|
||||
modalOpen = true;
|
||||
}
|
||||
|
||||
function handleSuccess() {
|
||||
triggerRefresh();
|
||||
modalOpen = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="wrapper">
|
||||
<button type="button" class="btn btnPrimary trigger">Create Job</button>
|
||||
<div class="menu" role="menu">
|
||||
{#each options as opt}
|
||||
<button
|
||||
type="button"
|
||||
class="menuItem"
|
||||
role="menuitem"
|
||||
onclick={() => openModal(opt.type)}
|
||||
>
|
||||
{opt.label}
|
||||
<div class="menuItemDesc">{opt.desc}</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
<CreateJobModal
|
||||
isOpen={modalOpen}
|
||||
onClose={() => (modalOpen = false)}
|
||||
onSuccess={handleSuccess}
|
||||
{jobType}
|
||||
{workloadType}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
.trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.trigger::after {
|
||||
content: "";
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid currentColor;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.menu {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
right: 0;
|
||||
margin-top: 0.25rem;
|
||||
min-width: 100%;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
padding: 0.25rem 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(-4px);
|
||||
transition: opacity 0.15s, visibility 0.15s, transform 0.15s;
|
||||
z-index: 200;
|
||||
}
|
||||
.wrapper:hover .menu {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
}
|
||||
.menuItem {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.menuItem:hover {
|
||||
background: var(--border);
|
||||
}
|
||||
.menuItemDesc {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-dim);
|
||||
font-weight: 400;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btnPrimary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
@@ -1,989 +0,0 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
createJob,
|
||||
getModels,
|
||||
getDatasets,
|
||||
uploadImage,
|
||||
type Model,
|
||||
} from "$lib/api";
|
||||
import { getDefaultModelForWorkload } from "$lib/defaultOptions";
|
||||
import { defaultOptions } from "$lib/stores/defaultOptions";
|
||||
import { WORKLOAD_OPTIONS } from "$lib/jobConfig";
|
||||
import type { JobType } from "$lib/types";
|
||||
import Toggle from "./Toggle.svelte";
|
||||
import Slider from "./Slider.svelte";
|
||||
|
||||
let {
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
jobType,
|
||||
workloadType,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
jobType: JobType;
|
||||
workloadType: string;
|
||||
} = $props();
|
||||
|
||||
function getModelWorkloadForTraining(_w: string): string {
|
||||
return "t2v";
|
||||
}
|
||||
|
||||
const isInference = $derived(jobType === "inference");
|
||||
const inferenceWorkload = $derived(
|
||||
isInference ? workloadType : getModelWorkloadForTraining(workloadType),
|
||||
);
|
||||
|
||||
let models = $state<Model[]>([]);
|
||||
let modelId = $state("");
|
||||
let prompt = $state("");
|
||||
let imagePath = $state("");
|
||||
let imageFileName = $state("");
|
||||
let isUploadingImage = $state(false);
|
||||
let negativePrompt = $state("");
|
||||
let numInferenceSteps = $state(50);
|
||||
let numFrames = $state(81);
|
||||
let height = $state(480);
|
||||
let width = $state(832);
|
||||
let guidanceScale = $state(5);
|
||||
let guidanceRescale = $state(0);
|
||||
let fps = $state(24);
|
||||
let seed = $state(1024);
|
||||
let numGpus = $state(1);
|
||||
let ditCpuOffload = $state(false);
|
||||
let textEncoderCpuOffload = $state(false);
|
||||
let vaeCpuOffload = $state(false);
|
||||
let imageEncoderCpuOffload = $state(false);
|
||||
let useFsdpInference = $state(false);
|
||||
let enableTorchCompile = $state(false);
|
||||
let vsaSparsity = $state(0);
|
||||
let tpSize = $state(-1);
|
||||
let spSize = $state(-1);
|
||||
let selectedDatasetId = $state("");
|
||||
let readyDatasets = $state<Awaited<ReturnType<typeof getDatasets>>>([]);
|
||||
let maxTrainSteps = $state(1000);
|
||||
let trainBatchSize = $state(1);
|
||||
let learningRate = $state(5e-5);
|
||||
let numLatentT = $state(20);
|
||||
let selectedValidationDatasetId = $state("");
|
||||
let loraRank = $state(32);
|
||||
let ltx2FirstFrameConditioningP = $state(0.1);
|
||||
let dmdUseVsa = $state(false);
|
||||
let dmdVsaSparsity = $state(0.8);
|
||||
let dmdDenoisingSteps = $state("1000,757,522");
|
||||
let minTimestepRatio = $state(0.02);
|
||||
let maxTimestepRatio = $state(0.98);
|
||||
let realScoreGuidanceScale = $state(3.5);
|
||||
let generatorUpdateInterval = $state(5);
|
||||
let realScoreModelPath = $state("");
|
||||
let fakeScoreModelPath = $state("");
|
||||
let isSubmitting = $state(false);
|
||||
let isLoadingModels = $state(false);
|
||||
let imageInputEl: HTMLInputElement;
|
||||
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
const opts = $defaultOptions;
|
||||
numInferenceSteps = opts.numInferenceSteps;
|
||||
numFrames = workloadType === "t2i" ? 1 : opts.numFrames;
|
||||
height = opts.height;
|
||||
width = opts.width;
|
||||
guidanceScale = opts.guidanceScale;
|
||||
guidanceRescale = opts.guidanceRescale;
|
||||
fps = opts.fps;
|
||||
seed = opts.seed;
|
||||
numGpus = opts.numGpus;
|
||||
ditCpuOffload = opts.ditCpuOffload;
|
||||
textEncoderCpuOffload = opts.textEncoderCpuOffload;
|
||||
vaeCpuOffload = opts.vaeCpuOffload;
|
||||
imageEncoderCpuOffload = opts.imageEncoderCpuOffload;
|
||||
useFsdpInference = opts.useFsdpInference;
|
||||
enableTorchCompile = opts.enableTorchCompile;
|
||||
vsaSparsity = opts.vsaSparsity;
|
||||
tpSize = opts.tpSize;
|
||||
spSize = opts.spSize;
|
||||
modelId = getDefaultModelForWorkload(
|
||||
opts,
|
||||
inferenceWorkload as "t2v" | "i2v" | "t2i",
|
||||
);
|
||||
imagePath = "";
|
||||
imageFileName = "";
|
||||
selectedDatasetId = "";
|
||||
selectedValidationDatasetId = "";
|
||||
if (workloadType === "dmd_t2v") {
|
||||
dmdUseVsa = false;
|
||||
dmdVsaSparsity = 0.8;
|
||||
dmdDenoisingSteps = "1000,757,522";
|
||||
minTimestepRatio = 0.02;
|
||||
maxTimestepRatio = 0.98;
|
||||
realScoreGuidanceScale = 3.5;
|
||||
generatorUpdateInterval = 5;
|
||||
realScoreModelPath = "";
|
||||
fakeScoreModelPath = "";
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
isLoadingModels = true;
|
||||
const filter = isInference ? workloadType : getModelWorkloadForTraining(workloadType);
|
||||
getModels(filter)
|
||||
.then((list) => {
|
||||
models = list;
|
||||
const ids = list.map((m) => m.id);
|
||||
const opts = $defaultOptions;
|
||||
const defaultId = getDefaultModelForWorkload(
|
||||
opts,
|
||||
filter as "t2v" | "i2v" | "t2i",
|
||||
);
|
||||
modelId = ids.includes(defaultId) ? defaultId : list[0]?.id ?? "";
|
||||
if (workloadType === "dmd_t2v") {
|
||||
const mid = ids.includes(defaultId) ? defaultId : list[0]?.id ?? "";
|
||||
realScoreModelPath = mid;
|
||||
fakeScoreModelPath = mid;
|
||||
}
|
||||
})
|
||||
.catch((e) => console.error("Failed to load models:", e))
|
||||
.finally(() => (isLoadingModels = false));
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (isOpen && !isInference) {
|
||||
getDatasets()
|
||||
.then(setReadyDatasets)
|
||||
.catch(() => (readyDatasets = []));
|
||||
} else {
|
||||
readyDatasets = [];
|
||||
}
|
||||
});
|
||||
|
||||
function setReadyDatasets(list: Awaited<ReturnType<typeof getDatasets>>) {
|
||||
readyDatasets = list;
|
||||
}
|
||||
|
||||
async function handleImageChange(e: Event) {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) {
|
||||
imagePath = "";
|
||||
imageFileName = "";
|
||||
return;
|
||||
}
|
||||
isUploadingImage = true;
|
||||
imageFileName = file.name;
|
||||
try {
|
||||
const { path } = await uploadImage(file);
|
||||
imagePath = path;
|
||||
} catch (err) {
|
||||
imagePath = "";
|
||||
imageFileName = "";
|
||||
} finally {
|
||||
isUploadingImage = false;
|
||||
}
|
||||
}
|
||||
|
||||
function clearImage() {
|
||||
imagePath = "";
|
||||
imageFileName = "";
|
||||
if (imageInputEl) imageInputEl.value = "";
|
||||
}
|
||||
|
||||
async function handleSubmit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (isInference && workloadType === "i2v" && !imagePath) return;
|
||||
const effectiveDataPath = selectedDatasetId
|
||||
? readyDatasets.find((d) => d.id === selectedDatasetId)?.name ?? ""
|
||||
: "";
|
||||
if (!isInference && !selectedDatasetId) return;
|
||||
const effectiveJobType: JobType =
|
||||
workloadType === "lora_t2v" ? "lora" : jobType;
|
||||
isSubmitting = true;
|
||||
try {
|
||||
const basePayload = {
|
||||
model_id: modelId,
|
||||
prompt,
|
||||
workload_type: workloadType,
|
||||
job_type: effectiveJobType,
|
||||
...(isInference
|
||||
? {}
|
||||
: {
|
||||
data_path: effectiveDataPath.trim(),
|
||||
max_train_steps: maxTrainSteps,
|
||||
train_batch_size: trainBatchSize,
|
||||
learning_rate: learningRate,
|
||||
num_latent_t: numLatentT,
|
||||
validation_dataset_file: selectedValidationDatasetId
|
||||
? (readyDatasets.find(
|
||||
(d) => d.id === selectedValidationDatasetId,
|
||||
)?.name ?? "") || undefined
|
||||
: undefined,
|
||||
lora_rank: loraRank,
|
||||
...(isLtx2Model
|
||||
? { ltx2_first_frame_conditioning_p: ltx2FirstFrameConditioningP }
|
||||
: {}),
|
||||
...(workloadType === "dmd_t2v"
|
||||
? {
|
||||
dmd_use_vsa: dmdUseVsa,
|
||||
dmd_vsa_sparsity: dmdVsaSparsity,
|
||||
dmd_denoising_steps: dmdDenoisingSteps,
|
||||
min_timestep_ratio: minTimestepRatio,
|
||||
max_timestep_ratio: maxTimestepRatio,
|
||||
real_score_guidance_scale: realScoreGuidanceScale,
|
||||
generator_update_interval: generatorUpdateInterval,
|
||||
real_score_model_path: realScoreModelPath || modelId,
|
||||
fake_score_model_path: fakeScoreModelPath || modelId,
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
};
|
||||
const inferencePayload = isInference
|
||||
? {
|
||||
...(workloadType === "i2v" && imagePath ? { image_path: imagePath } : {}),
|
||||
negative_prompt: negativePrompt,
|
||||
num_inference_steps: numInferenceSteps,
|
||||
num_frames: numFrames,
|
||||
height,
|
||||
width,
|
||||
guidance_scale: guidanceScale,
|
||||
guidance_rescale: guidanceRescale,
|
||||
fps,
|
||||
seed,
|
||||
num_gpus: numGpus,
|
||||
dit_cpu_offload: ditCpuOffload,
|
||||
text_encoder_cpu_offload: textEncoderCpuOffload,
|
||||
vae_cpu_offload: vaeCpuOffload,
|
||||
image_encoder_cpu_offload: imageEncoderCpuOffload,
|
||||
use_fsdp_inference: useFsdpInference,
|
||||
enable_torch_compile: enableTorchCompile,
|
||||
vsa_sparsity: vsaSparsity,
|
||||
tp_size: tpSize,
|
||||
sp_size: spSize,
|
||||
}
|
||||
: {};
|
||||
await createJob({ ...basePayload, ...inferencePayload });
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
console.error("Failed to create job:", err);
|
||||
} finally {
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (isSubmitting) return;
|
||||
onClose();
|
||||
}
|
||||
|
||||
function handleBackdropClick() {
|
||||
handleClose();
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === "Escape" && !isSubmitting) handleClose();
|
||||
}
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => document.removeEventListener("keydown", onKey);
|
||||
});
|
||||
|
||||
const isLtx2Model = $derived(
|
||||
(modelId || "").toLowerCase().includes("ltx2") ||
|
||||
(modelId || "").toLowerCase().includes("ltx-2"),
|
||||
);
|
||||
|
||||
const workloadLabel = $derived(
|
||||
WORKLOAD_OPTIONS[jobType]?.find((o) => o.type === workloadType)?.label ?? "",
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if isOpen}
|
||||
<div class="modal" data-modal>
|
||||
<div class="modalBackdrop" onclick={handleBackdropClick} role="presentation"></div>
|
||||
<div class="modalContent modalForm">
|
||||
<button
|
||||
class="modalClose"
|
||||
onclick={handleClose}
|
||||
disabled={isSubmitting}
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<div class="card">
|
||||
<h2>
|
||||
New {jobType.charAt(0).toUpperCase() + jobType.slice(1)} Job
|
||||
{workloadLabel ? ` (${workloadLabel})` : ""}
|
||||
</h2>
|
||||
<form onsubmit={handleSubmit} autocomplete="off">
|
||||
<div class="formRow">
|
||||
<label for="modal-modelId">Model</label>
|
||||
<select
|
||||
id="modal-modelId"
|
||||
bind:value={modelId}
|
||||
required
|
||||
disabled={isSubmitting || isLoadingModels}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{isLoadingModels
|
||||
? "Loading models…"
|
||||
: models.length === 0
|
||||
? "No models available for this workload"
|
||||
: "Select a model…"}
|
||||
</option>
|
||||
{#each models as model}
|
||||
<option value={model.id}>{model.label} ({model.id})</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
{#if isInference && workloadType === "i2v"}
|
||||
<div class="formRow">
|
||||
<label for="modal-image">Image</label>
|
||||
<input
|
||||
bind:this={imageInputEl}
|
||||
id="modal-image"
|
||||
type="file"
|
||||
accept=".png,.jpg,.jpeg,.webp,.bmp"
|
||||
onchange={handleImageChange}
|
||||
disabled={isSubmitting || isUploadingImage}
|
||||
required
|
||||
/>
|
||||
{#if imageFileName}
|
||||
<span class="helperText">
|
||||
{isUploadingImage ? "Uploading…" : imageFileName} ·
|
||||
<button
|
||||
type="button"
|
||||
class="clearLink"
|
||||
onclick={clearImage}
|
||||
disabled={isSubmitting || isUploadingImage}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="formRow">
|
||||
<label for="modal-prompt">{isInference ? "Prompt" : "Description"}</label>
|
||||
<textarea
|
||||
id="modal-prompt"
|
||||
bind:value={prompt}
|
||||
rows={isInference ? 3 : 2}
|
||||
placeholder={
|
||||
isInference
|
||||
? "A curious raccoon peers through a vibrant field of yellow sunflowers…"
|
||||
: "Brief description of this training job…"
|
||||
}
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
></textarea>
|
||||
</div>
|
||||
{#if isInference}
|
||||
<div class="formRow">
|
||||
<label for="modal-negative-prompt">Negative Prompt</label>
|
||||
<textarea
|
||||
id="modal-negative-prompt"
|
||||
bind:value={negativePrompt}
|
||||
rows={2}
|
||||
placeholder="Optional: things to avoid in the output…"
|
||||
disabled={isSubmitting}
|
||||
></textarea>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !isInference}
|
||||
<div class="datasetRow">
|
||||
<div class="formRow">
|
||||
<label for="modal-dataset">Dataset *</label>
|
||||
<select
|
||||
id="modal-dataset"
|
||||
bind:value={selectedDatasetId}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{readyDatasets.length === 0
|
||||
? "No datasets (add in Datasets tab)"
|
||||
: "Select a dataset…"}
|
||||
</option>
|
||||
{#each readyDatasets as d}
|
||||
<option value={d.id}>{d.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-validation-dataset"
|
||||
>Validation Dataset (optional)</label
|
||||
>
|
||||
<select
|
||||
id="modal-validation-dataset"
|
||||
bind:value={selectedValidationDatasetId}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">None</option>
|
||||
{#each readyDatasets as d}
|
||||
<option value={d.id}>{d.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<details class="optionsSection">
|
||||
<summary>Options</summary>
|
||||
<div class="settingsGrid">
|
||||
<div class="formRow">
|
||||
<label for="modal-max-train-steps">Max Train Steps</label>
|
||||
<Slider
|
||||
id="modal-max-train-steps"
|
||||
min={100}
|
||||
max={50000}
|
||||
step={100}
|
||||
value={maxTrainSteps}
|
||||
onChange={(v) => (maxTrainSteps = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-train-batch-size">Train Batch Size</label>
|
||||
<Slider
|
||||
id="modal-train-batch-size"
|
||||
min={1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={trainBatchSize}
|
||||
onChange={(v) => (trainBatchSize = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-learning-rate">Learning Rate</label>
|
||||
<input
|
||||
id="modal-learning-rate"
|
||||
type="number"
|
||||
step="1e-6"
|
||||
min={1e-6}
|
||||
max={1}
|
||||
bind:value={learningRate}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-num-latent-t">Num Latent T</label>
|
||||
<Slider
|
||||
id="modal-num-latent-t"
|
||||
min={8}
|
||||
max={40}
|
||||
step={1}
|
||||
value={numLatentT}
|
||||
onChange={(v) => (numLatentT = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{#if workloadType === "lora_t2v"}
|
||||
<div class="formRow">
|
||||
<label for="modal-lora-rank">LoRA Rank</label>
|
||||
<Slider
|
||||
id="modal-lora-rank"
|
||||
min={8}
|
||||
max={128}
|
||||
step={8}
|
||||
value={loraRank}
|
||||
onChange={(v) => (loraRank = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if isLtx2Model}
|
||||
<div class="formRow">
|
||||
<label for="modal-ltx2-first-frame" title="Probability of conditioning on the first frame during LTX-2 training">First Frame Conditioning</label>
|
||||
<Slider
|
||||
id="modal-ltx2-first-frame"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={ltx2FirstFrameConditioningP}
|
||||
onChange={(v) => (ltx2FirstFrameConditioningP = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if workloadType === "dmd_t2v"}
|
||||
<div class="formRow">
|
||||
<label for="modal-dmd-use-vsa" title="Use Video Sparse Attention for DMD">Video Sparse Attention (VSA)</label>
|
||||
<Toggle
|
||||
id="modal-dmd-use-vsa"
|
||||
checked={dmdUseVsa}
|
||||
onChange={(v) => (dmdUseVsa = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{#if dmdUseVsa}
|
||||
<div class="formRow">
|
||||
<label for="modal-dmd-vsa-sparsity" title="VSA sparsity (0–1)">VSA Sparsity</label>
|
||||
<Slider
|
||||
id="modal-dmd-vsa-sparsity"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={dmdVsaSparsity}
|
||||
onChange={(v) => (dmdVsaSparsity = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="formRow">
|
||||
<label for="modal-dmd-denoising-steps" title="Comma-separated denoising steps, e.g. 1000,757,522">DMD Denoising Steps</label>
|
||||
<input
|
||||
id="modal-dmd-denoising-steps"
|
||||
type="text"
|
||||
bind:value={dmdDenoisingSteps}
|
||||
placeholder="1000,757,522"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-min-timestep-ratio">Min Timestep Ratio</label>
|
||||
<Slider
|
||||
id="modal-min-timestep-ratio"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.01}
|
||||
value={minTimestepRatio}
|
||||
onChange={(v) => (minTimestepRatio = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-max-timestep-ratio">Max Timestep Ratio</label>
|
||||
<Slider
|
||||
id="modal-max-timestep-ratio"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.01}
|
||||
value={maxTimestepRatio}
|
||||
onChange={(v) => (maxTimestepRatio = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-real-score-guidance-scale">Real Score Guidance Scale</label>
|
||||
<Slider
|
||||
id="modal-real-score-guidance-scale"
|
||||
min={1}
|
||||
max={10}
|
||||
step={0.1}
|
||||
value={realScoreGuidanceScale}
|
||||
onChange={(v) => (realScoreGuidanceScale = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(1)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-generator-update-interval">Generator Update Interval</label>
|
||||
<Slider
|
||||
id="modal-generator-update-interval"
|
||||
min={1}
|
||||
max={20}
|
||||
step={1}
|
||||
value={generatorUpdateInterval}
|
||||
onChange={(v) => (generatorUpdateInterval = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-real-score-model">Real Score Model</label>
|
||||
<select
|
||||
id="modal-real-score-model"
|
||||
bind:value={realScoreModelPath}
|
||||
disabled={isSubmitting || isLoadingModels}
|
||||
>
|
||||
<option value="">Same as main model</option>
|
||||
{#each models as model}
|
||||
<option value={model.id}>{model.label} ({model.id})</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-fake-score-model">Fake Score Model</label>
|
||||
<select
|
||||
id="modal-fake-score-model"
|
||||
bind:value={fakeScoreModelPath}
|
||||
disabled={isSubmitting || isLoadingModels}
|
||||
>
|
||||
<option value="">Same as main model</option>
|
||||
{#each models as model}
|
||||
<option value={model.id}>{model.label} ({model.id})</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</details>
|
||||
{/if}
|
||||
|
||||
{#if isInference}
|
||||
<details class="optionsSection">
|
||||
<summary>Options</summary>
|
||||
<div class="settingsGrid">
|
||||
{#if workloadType !== "t2i"}
|
||||
<div class="formRow">
|
||||
<label for="modal-num-frames">Frames</label>
|
||||
<Slider
|
||||
id="modal-num-frames"
|
||||
min={1}
|
||||
max={500}
|
||||
step={1}
|
||||
value={numFrames}
|
||||
onChange={(v) => (numFrames = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="formRow">
|
||||
<label for="modal-height">Height</label>
|
||||
<Slider
|
||||
id="modal-height"
|
||||
min={64}
|
||||
max={1080}
|
||||
step={16}
|
||||
value={height}
|
||||
onChange={(v) => (height = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-width">Width</label>
|
||||
<Slider
|
||||
id="modal-width"
|
||||
min={64}
|
||||
max={1920}
|
||||
step={16}
|
||||
value={width}
|
||||
onChange={(v) => (width = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-num-steps">Inference Steps</label>
|
||||
<Slider
|
||||
id="modal-num-steps"
|
||||
min={1}
|
||||
max={200}
|
||||
step={1}
|
||||
value={numInferenceSteps}
|
||||
onChange={(v) => (numInferenceSteps = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-vsa-sparsity" title="VSA sparsity (0–1)">VSA Sparsity</label>
|
||||
<Slider
|
||||
id="modal-vsa-sparsity"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={vsaSparsity}
|
||||
onChange={(v) => (vsaSparsity = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-guidance">Guidance Scale</label>
|
||||
<Slider
|
||||
id="modal-guidance"
|
||||
min={0}
|
||||
max={20}
|
||||
step={0.1}
|
||||
value={guidanceScale}
|
||||
onChange={(v) => (guidanceScale = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(1)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-guidance-rescale" title="0 = disabled">Guidance Rescale</label>
|
||||
<Slider
|
||||
id="modal-guidance-rescale"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={guidanceRescale}
|
||||
onChange={(v) => (guidanceRescale = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => v.toFixed(2)}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-tp-size" title="-1 = auto">TP Size</label>
|
||||
<Slider
|
||||
id="modal-tp-size"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={tpSize}
|
||||
onChange={(v) => (tpSize = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => (v === -1 ? "Auto" : String(v))}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-sp-size" title="-1 = auto">SP Size</label>
|
||||
<Slider
|
||||
id="modal-sp-size"
|
||||
min={-1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={spSize}
|
||||
onChange={(v) => (spSize = v)}
|
||||
disabled={isSubmitting}
|
||||
formatValue={(v) => (v === -1 ? "Auto" : String(v))}
|
||||
/>
|
||||
</div>
|
||||
{#if workloadType !== "t2i"}
|
||||
<div class="formRow">
|
||||
<label for="modal-fps">FPS</label>
|
||||
<Slider
|
||||
id="modal-fps"
|
||||
min={1}
|
||||
max={60}
|
||||
step={1}
|
||||
value={fps}
|
||||
onChange={(v) => (fps = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="formRow">
|
||||
<label for="modal-dit-cpu-offload">DiT CPU Offload</label>
|
||||
<Toggle
|
||||
id="modal-dit-cpu-offload"
|
||||
checked={ditCpuOffload}
|
||||
onChange={(v) => (ditCpuOffload = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-text-encoder-cpu-offload">Text Encoder CPU Offload</label>
|
||||
<Toggle
|
||||
id="modal-text-encoder-cpu-offload"
|
||||
checked={textEncoderCpuOffload}
|
||||
onChange={(v) => (textEncoderCpuOffload = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-use-fsdp-inference">Use FSDP Inference</label>
|
||||
<Toggle
|
||||
id="modal-use-fsdp-inference"
|
||||
checked={useFsdpInference}
|
||||
onChange={(v) => (useFsdpInference = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-vae-cpu-offload">VAE CPU Offload</label>
|
||||
<Toggle
|
||||
id="modal-vae-cpu-offload"
|
||||
checked={vaeCpuOffload}
|
||||
onChange={(v) => (vaeCpuOffload = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-image-encoder-cpu-offload">Image Encoder CPU Offload</label>
|
||||
<Toggle
|
||||
id="modal-image-encoder-cpu-offload"
|
||||
checked={imageEncoderCpuOffload}
|
||||
onChange={(v) => (imageEncoderCpuOffload = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-enable-torch-compile">Torch Compile</label>
|
||||
<Toggle
|
||||
id="modal-enable-torch-compile"
|
||||
checked={enableTorchCompile}
|
||||
onChange={(v) => (enableTorchCompile = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-num-gpus">GPUs</label>
|
||||
<Slider
|
||||
id="modal-num-gpus"
|
||||
min={1}
|
||||
max={8}
|
||||
step={1}
|
||||
value={numGpus}
|
||||
onChange={(v) => (numGpus = v)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div class="formRow">
|
||||
<label for="modal-seed">Seed</label>
|
||||
<input
|
||||
id="modal-seed"
|
||||
type="number"
|
||||
bind:value={seed}
|
||||
min={0}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
{/if}
|
||||
|
||||
<button type="submit" class="btn btnPrimary" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Creating..." : "Create Job"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: modal-fade-in 0.2s ease-out;
|
||||
}
|
||||
.modalBackdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
.modalContent {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
}
|
||||
.modalForm {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0;
|
||||
max-width: 850px;
|
||||
width: 90vw;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.modalClose {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.75rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
font-size: 1.6rem;
|
||||
cursor: pointer;
|
||||
z-index: 2;
|
||||
line-height: 1;
|
||||
}
|
||||
.modalClose:hover {
|
||||
opacity: 0.7;
|
||||
}
|
||||
.modalClose:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.card {
|
||||
padding: 1.5rem;
|
||||
margin: 0;
|
||||
border: none;
|
||||
}
|
||||
.card h2 {
|
||||
font-size: 1.15rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.formRow {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
.formRow label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-dim);
|
||||
padding-left: 3px;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.datasetRow {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
.datasetRow .formRow {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.helperText {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-dim);
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
.clearLink {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: var(--accent-h);
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
.clearLink:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
}
|
||||
.optionsSection {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.optionsSection summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
color: var(--accent-h);
|
||||
user-select: none;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.settingsGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 0.5rem 0.75rem;
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btnPrimary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@keyframes modal-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,133 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Dataset } from "$lib/api";
|
||||
import { deleteDataset } from "$lib/api";
|
||||
import { activeDatasetId, setActiveDatasetId } from "$lib/stores/activeDataset";
|
||||
|
||||
let { dataset, onUpdated, onSelect = () => {} }: {
|
||||
dataset: Dataset;
|
||||
onUpdated: () => void;
|
||||
onSelect?: () => void;
|
||||
} = $props();
|
||||
|
||||
let isLoading = $state(false);
|
||||
|
||||
const isSelected = $derived($activeDatasetId === dataset.id);
|
||||
|
||||
const fileCount = $derived(dataset.file_count ?? 0);
|
||||
const sizeBytes = $derived(dataset.size_bytes ?? 0);
|
||||
const sizeLabel = $derived(
|
||||
sizeBytes < 1024
|
||||
? `${sizeBytes} B`
|
||||
: sizeBytes < 1024 * 1024
|
||||
? `${(sizeBytes / 1024).toFixed(1)} KB`
|
||||
: sizeBytes < 1024 * 1024 * 1024
|
||||
? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${(sizeBytes / (1024 * 1024 * 1024)).toFixed(1)} GB`,
|
||||
);
|
||||
|
||||
async function handleDelete(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading) return;
|
||||
if (!confirm(`Delete dataset "${dataset.name}"?`)) return;
|
||||
isLoading = true;
|
||||
try {
|
||||
await deleteDataset(dataset.id);
|
||||
if ($activeDatasetId === dataset.id) setActiveDatasetId(null);
|
||||
onUpdated();
|
||||
} catch (err) {
|
||||
alert(
|
||||
err instanceof Error ? err.message : "Failed to delete dataset",
|
||||
);
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
onSelect();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="jobCard"
|
||||
class:jobCardSelected={isSelected}
|
||||
onclick={(e) => {
|
||||
if ((e.target as HTMLElement).closest("button")) return;
|
||||
onSelect();
|
||||
}}
|
||||
onkeydown={handleKeyDown}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="jobHeader">
|
||||
<span class="jobModel">{dataset.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btnDelete btnSmall"
|
||||
onclick={handleDelete}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
<div class="jobPrompt">
|
||||
{fileCount} {fileCount === 1 ? "file" : "files"} · {sizeLabel}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.jobCard {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.15rem;
|
||||
margin-bottom: 0.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.jobCardSelected {
|
||||
border-color: var(--accent);
|
||||
background: rgba(99, 102, 241, 0.06);
|
||||
}
|
||||
.jobHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.jobModel {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.jobPrompt {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btnSmall {
|
||||
background: transparent;
|
||||
color: var(--accent-h);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.btnDelete {
|
||||
background: var(--red);
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
@@ -1,320 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Dataset } from "$lib/api";
|
||||
import {
|
||||
getDatasetFiles,
|
||||
updateDatasetCaption,
|
||||
getDatasetMediaUrl,
|
||||
} from "$lib/api";
|
||||
import DownloadCaptions from "./DownloadCaptions.svelte";
|
||||
import { resizable } from "$lib/actions/resizable";
|
||||
|
||||
let { dataset, onClose, onWidthChange }: {
|
||||
dataset: Dataset;
|
||||
onClose: () => void;
|
||||
onWidthChange?: (w: number) => void;
|
||||
} = $props();
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 320;
|
||||
const SIDEBAR_MAX_WIDTH = 900;
|
||||
const INITIAL_PAGE_SIZE = 24;
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
let width = $state(400);
|
||||
let isDragging = $state(false);
|
||||
let fileNames = $state<string[]>([]);
|
||||
let captions = $state<Record<string, string>>({});
|
||||
let visibleCount = $state(INITIAL_PAGE_SIZE);
|
||||
let isLoading = $state(true);
|
||||
let thumbLoaded = $state<Record<string, boolean>>({});
|
||||
let saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let scrollEl: HTMLDivElement;
|
||||
|
||||
$effect(() => {
|
||||
onWidthChange?.(width);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
let cancelled = false;
|
||||
isLoading = true;
|
||||
getDatasetFiles(dataset.id)
|
||||
.then((data) => {
|
||||
if (!cancelled) {
|
||||
fileNames = data.file_names;
|
||||
captions = data.captions;
|
||||
visibleCount = INITIAL_PAGE_SIZE;
|
||||
thumbLoaded = {};
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error("Failed to load dataset files:", err))
|
||||
.finally(() => {
|
||||
if (!cancelled) isLoading = false;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
|
||||
function handleCaptionChange(fileName: string, value: string) {
|
||||
captions = { ...captions, [fileName]: value };
|
||||
if (saveTimeout) clearTimeout(saveTimeout);
|
||||
saveTimeout = setTimeout(() => {
|
||||
saveTimeout = null;
|
||||
updateDatasetCaption(dataset.id, fileName, value).catch((err) =>
|
||||
console.error("Failed to save caption:", err),
|
||||
);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function handleLoadMore() {
|
||||
visibleCount = Math.min(visibleCount + PAGE_SIZE, fileNames.length);
|
||||
}
|
||||
|
||||
const resizableOpts = $derived({
|
||||
edge: "right" as const,
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: (w: number) => (width = w),
|
||||
onDragChange: (dragging: boolean) => (isDragging = dragging),
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
return () => {
|
||||
if (saveTimeout) clearTimeout(saveTimeout);
|
||||
};
|
||||
});
|
||||
|
||||
const visibleFiles = $derived(fileNames.slice(0, visibleCount));
|
||||
const hasMore = $derived(visibleCount < fileNames.length);
|
||||
|
||||
function handleScroll() {
|
||||
if (!hasMore || isLoading || !scrollEl) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = scrollEl;
|
||||
const distanceFromBottom = scrollHeight - (scrollTop + clientHeight);
|
||||
if (distanceFromBottom < 200) {
|
||||
visibleCount = Math.min(visibleCount + PAGE_SIZE, fileNames.length);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<aside class="sidebar" style="width: {width}px; max-width: {SIDEBAR_MAX_WIDTH}px">
|
||||
<div class="header">
|
||||
<h2 class="title">{dataset.name}</h2>
|
||||
<div class="headerActions">
|
||||
<DownloadCaptions {fileNames} {captions} />
|
||||
<button
|
||||
type="button"
|
||||
class="closeBtn"
|
||||
onclick={onClose}
|
||||
title="Close"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M18 6L6 18M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="gallerySection">
|
||||
<div
|
||||
class="galleryScroll"
|
||||
bind:this={scrollEl}
|
||||
onscroll={handleScroll}
|
||||
>
|
||||
{#if isLoading}
|
||||
<p class="galleryEmpty">Loading…</p>
|
||||
{:else if fileNames.length === 0}
|
||||
<p class="galleryEmpty">No media files</p>
|
||||
{:else}
|
||||
<div class="galleryGrid">
|
||||
{#each visibleFiles as fileName}
|
||||
<div class="galleryItem">
|
||||
{#if !thumbLoaded[fileName]}
|
||||
<div class="thumbLoading">
|
||||
<div class="thumbSpinner"></div>
|
||||
</div>
|
||||
{/if}
|
||||
<video
|
||||
src={getDatasetMediaUrl(dataset.id, fileName)}
|
||||
class="galleryThumb"
|
||||
muted
|
||||
autoplay
|
||||
loop
|
||||
playsinline
|
||||
onloadeddata={() => {
|
||||
thumbLoaded = { ...thumbLoaded, [fileName]: true };
|
||||
}}
|
||||
onerror={() => {
|
||||
thumbLoaded = { ...thumbLoaded, [fileName]: true };
|
||||
}}
|
||||
></video>
|
||||
<div class="galleryCaption">
|
||||
<textarea
|
||||
value={captions[fileName] ?? ""}
|
||||
oninput={(e) =>
|
||||
handleCaptionChange(
|
||||
fileName,
|
||||
(e.target as HTMLTextAreaElement).value,
|
||||
)}
|
||||
placeholder="Caption"
|
||||
rows={2}
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="resizeHandle"
|
||||
class:resizeHandleActive={isDragging}
|
||||
use:resizable={resizableOpts}
|
||||
role="presentation"
|
||||
></div>
|
||||
</aside>
|
||||
|
||||
<style>
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: var(--header-height);
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: calc(100vh - var(--header-height));
|
||||
min-width: 320px;
|
||||
background: var(--surface);
|
||||
border-left: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
z-index: 50;
|
||||
}
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 6px;
|
||||
bottom: 0;
|
||||
cursor: col-resize;
|
||||
z-index: 1;
|
||||
}
|
||||
.resizeHandle:hover,
|
||||
.resizeHandleActive {
|
||||
background: rgba(99, 102, 241, 0.2);
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 1.25rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.closeBtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.4rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-dim);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius);
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.closeBtn:hover {
|
||||
color: var(--text);
|
||||
background: rgba(99, 102, 241, 0.08);
|
||||
}
|
||||
.closeBtn svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.gallerySection {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.galleryScroll {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 1rem;
|
||||
}
|
||||
.galleryGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.galleryItem {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.galleryThumb {
|
||||
aspect-ratio: 16 / 9;
|
||||
object-fit: cover;
|
||||
width: 100%;
|
||||
background: var(--border);
|
||||
}
|
||||
.galleryCaption {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.galleryCaption textarea {
|
||||
width: 100%;
|
||||
min-height: 2.5rem;
|
||||
padding: 0.4rem;
|
||||
font-size: 0.8rem;
|
||||
font-family: inherit;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
resize: vertical;
|
||||
}
|
||||
.thumbLoading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: radial-gradient(
|
||||
circle at center,
|
||||
rgba(15, 17, 23, 0.6),
|
||||
rgba(15, 17, 23, 0.9)
|
||||
);
|
||||
pointer-events: none;
|
||||
}
|
||||
.thumbSpinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 999px;
|
||||
border: 2px solid rgba(148, 163, 184, 0.4);
|
||||
border-top-color: var(--accent);
|
||||
animation: thumb-spin 0.7s linear infinite;
|
||||
}
|
||||
@keyframes thumb-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.galleryEmpty {
|
||||
color: var(--text-dim);
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,171 +0,0 @@
|
||||
<script lang="ts">
|
||||
let { fileNames = [], captions = {} }: {
|
||||
fileNames?: string[];
|
||||
captions?: Record<string, string>;
|
||||
} = $props();
|
||||
|
||||
function downloadBlob(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
const sortedNames = $derived([...fileNames].sort());
|
||||
const disabled = $derived(fileNames.length === 0);
|
||||
|
||||
function handleDownloadJson() {
|
||||
const data = sortedNames.map((path) => ({
|
||||
path,
|
||||
cap: captions[path] ?? "",
|
||||
}));
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], {
|
||||
type: "application/json",
|
||||
});
|
||||
downloadBlob(blob, "videos2caption.json");
|
||||
}
|
||||
|
||||
function handleDownloadTxt() {
|
||||
const videosContent = sortedNames.join("\n");
|
||||
const promptContent = sortedNames.map((fn) => captions[fn] ?? "").join("\n");
|
||||
downloadBlob(new Blob([videosContent], { type: "text/plain" }), "videos.txt");
|
||||
setTimeout(() => {
|
||||
downloadBlob(
|
||||
new Blob([promptContent], { type: "text/plain" }),
|
||||
"captions.txt",
|
||||
);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function handleDownloadCsv() {
|
||||
const escape = (s: string) =>
|
||||
s.includes('"') || s.includes(",") || s.includes("\n")
|
||||
? `"${s.replace(/"/g, '""')}"`
|
||||
: s;
|
||||
const rows = sortedNames.map(
|
||||
(fn) => `${escape(fn)},${escape(captions[fn] ?? "")}`,
|
||||
);
|
||||
const header = "video_name,caption";
|
||||
const csv = [header, ...rows].join("\n");
|
||||
downloadBlob(new Blob([csv], { type: "text/csv" }), "captions.csv");
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="wrapper">
|
||||
<button type="button" class="btn btnSmall trigger" disabled={disabled}>
|
||||
Download Captions
|
||||
</button>
|
||||
<div class="menu" role="menu">
|
||||
<button
|
||||
class="menuItem"
|
||||
role="menuitem"
|
||||
onclick={handleDownloadJson}
|
||||
disabled={disabled}
|
||||
>
|
||||
JSON
|
||||
</button>
|
||||
<button
|
||||
class="menuItem"
|
||||
role="menuitem"
|
||||
onclick={handleDownloadTxt}
|
||||
disabled={disabled}
|
||||
>
|
||||
TXT
|
||||
</button>
|
||||
<button
|
||||
class="menuItem"
|
||||
role="menuitem"
|
||||
onclick={handleDownloadCsv}
|
||||
disabled={disabled}
|
||||
>
|
||||
CSV
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
.trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.trigger::after {
|
||||
content: "";
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid currentColor;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.menu {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
right: 0;
|
||||
margin-top: 0.25rem;
|
||||
min-width: 100%;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
padding: 0.25rem 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(-4px);
|
||||
transition: opacity 0.15s, visibility 0.15s, transform 0.15s;
|
||||
z-index: 200;
|
||||
}
|
||||
.wrapper:hover .menu {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
}
|
||||
.menuItem {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.menuItem:hover {
|
||||
background: var(--border);
|
||||
}
|
||||
.menuItem:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.btnSmall {
|
||||
background: transparent;
|
||||
color: var(--accent-h);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,72 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from "$app/stores";
|
||||
import { headerActions } from "$lib/stores/headerActions";
|
||||
import type { HeaderAction } from "$lib/stores/headerActions";
|
||||
|
||||
const TAB_TITLES: Record<string, string> = {
|
||||
"/inference": "Jobs",
|
||||
"/finetuning": "Jobs",
|
||||
"/distillation": "Jobs",
|
||||
"/datasets": "Datasets",
|
||||
"/gallery": "Gallery",
|
||||
"/settings": "Settings",
|
||||
};
|
||||
|
||||
const title = $derived(TAB_TITLES[$page.url.pathname] ?? "FastVideo");
|
||||
|
||||
let actions = $state<HeaderAction[]>([]);
|
||||
$effect(() => {
|
||||
const unsub = headerActions.subscribe((v) => (actions = v));
|
||||
return unsub;
|
||||
});
|
||||
</script>
|
||||
|
||||
<header class="header">
|
||||
<img src="/logo.svg" alt="FastVideo Logo" width="100" height="42" class="logo" />
|
||||
<h1 class="title">{title}</h1>
|
||||
{#if actions.length > 0}
|
||||
<div class="actions">
|
||||
{#each actions as action, i (i)}
|
||||
<svelte:component this={action.component} {...(action.props ?? {})} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
<style>
|
||||
.header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
padding: 1rem 1.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
}
|
||||
.title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
}
|
||||
.logo {
|
||||
width: 100px;
|
||||
height: 42px;
|
||||
display: block;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,318 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Job } from "$lib/types";
|
||||
import {
|
||||
startJob,
|
||||
stopJob,
|
||||
deleteJob,
|
||||
downloadJobVideo,
|
||||
} from "$lib/api";
|
||||
import { activeJobId, setActiveJobId } from "$lib/stores/activeJob";
|
||||
|
||||
let { job, onJobUpdated }: {
|
||||
job: Job;
|
||||
onJobUpdated?: () => void;
|
||||
} = $props();
|
||||
|
||||
let isLoading = $state(false);
|
||||
let currentTime = $state(Date.now());
|
||||
|
||||
const isSelected = $derived($activeJobId === job.id);
|
||||
const badgeClass =
|
||||
"badge" +
|
||||
job.status.charAt(0).toUpperCase() +
|
||||
job.status.slice(1);
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const roundedSeconds = Math.round(seconds);
|
||||
if (roundedSeconds < 60) return `${roundedSeconds}s`;
|
||||
if (roundedSeconds < 3600) {
|
||||
const mins = Math.floor(roundedSeconds / 60);
|
||||
const secs = roundedSeconds % 60;
|
||||
return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
|
||||
}
|
||||
const hours = Math.floor(roundedSeconds / 3600);
|
||||
const mins = Math.floor((roundedSeconds % 3600) / 60);
|
||||
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
const elapsedTime = $derived((() => {
|
||||
if (!job.started_at) return null;
|
||||
const endTime =
|
||||
job.status === "running" ? currentTime : (job.finished_at ?? 0);
|
||||
if (!endTime && job.status !== "running") return null;
|
||||
const startedAtMs =
|
||||
job.started_at < 1e12 ? job.started_at * 1000 : job.started_at;
|
||||
const endTimeMs = endTime < 1e12 ? endTime * 1000 : endTime;
|
||||
const elapsedSeconds = (endTimeMs - startedAtMs) / 1000;
|
||||
if (elapsedSeconds <= 0) return null;
|
||||
return formatDuration(elapsedSeconds);
|
||||
})());
|
||||
|
||||
$effect(() => {
|
||||
if (job.status !== "running" || !job.started_at) return;
|
||||
const interval = setInterval(() => (currentTime = Date.now()), 1000);
|
||||
return () => clearInterval(interval);
|
||||
});
|
||||
|
||||
async function handleStart(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || job.status === "running" || job.status === "completed")
|
||||
return;
|
||||
isLoading = true;
|
||||
try {
|
||||
await startJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : "Failed to start job");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStop(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || job.status !== "running") return;
|
||||
isLoading = true;
|
||||
try {
|
||||
await stopJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : "Failed to stop job");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading) return;
|
||||
if (!confirm("Delete this job?")) return;
|
||||
isLoading = true;
|
||||
try {
|
||||
await deleteJob(job.id);
|
||||
onJobUpdated?.();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : "Failed to delete job");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleSelectJob(e: MouseEvent) {
|
||||
if ((e.target as HTMLElement).closest("button")) return;
|
||||
setActiveJobId(isSelected ? null : job.id);
|
||||
}
|
||||
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
handleSelectJob(e as unknown as MouseEvent);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDownloadVideo(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (isLoading || !job.output_path) return;
|
||||
isLoading = true;
|
||||
try {
|
||||
const blob = await downloadJobVideo(job.id);
|
||||
const ext = job.output_path.endsWith(".png") ? "png" : "mp4";
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `job_${job.id}.${ext}`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
} catch (err) {
|
||||
alert(
|
||||
err instanceof Error ? err.message : "Failed to download video",
|
||||
);
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="jobCard"
|
||||
class:jobCardSelected={isSelected}
|
||||
onclick={handleSelectJob}
|
||||
onkeydown={handleKeyDown}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="jobHeader">
|
||||
<span class="jobModel">{job.model_id}</span>
|
||||
<span class="badge {badgeClass}">{job.status}</span>
|
||||
</div>
|
||||
<p class="jobPrompt">{job.prompt}</p>
|
||||
<div class="jobMeta">
|
||||
{#if job.job_type === "inference"}
|
||||
<span>{job.num_frames} frames</span>
|
||||
<span>{job.height}×{job.width}</span>
|
||||
{:else}
|
||||
<span>{job.workload_type?.replace(/_/g, " ") ?? job.job_type}</span>
|
||||
{/if}
|
||||
{#if elapsedTime}
|
||||
<span class="jobDuration">⏱ {elapsedTime}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="jobActions">
|
||||
{#if job.status === "running"}
|
||||
<button class="btn btnStop btnSmall" onclick={handleStop} disabled={isLoading}>
|
||||
Stop
|
||||
</button>
|
||||
{:else if job.status === "failed"}
|
||||
<button class="btn btnStart btnSmall" onclick={handleStart} disabled={isLoading}>
|
||||
Restart
|
||||
</button>
|
||||
{:else if job.status === "pending" || job.status === "stopped"}
|
||||
<button class="btn btnStart btnSmall" onclick={handleStart} disabled={isLoading}>
|
||||
Start
|
||||
</button>
|
||||
{/if}
|
||||
{#if job.status === "completed" && job.output_path && job.job_type === "inference"}
|
||||
<button
|
||||
class="btn btnSmall"
|
||||
onclick={handleDownloadVideo}
|
||||
disabled={isLoading}
|
||||
title="Download video"
|
||||
>
|
||||
Download Video
|
||||
</button>
|
||||
{/if}
|
||||
<button class="btn btnDelete btnSmall" onclick={handleDelete} disabled={isLoading}>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.jobCard {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.15rem;
|
||||
margin-bottom: 0.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.jobCard:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.jobCardSelected {
|
||||
border-color: var(--accent);
|
||||
background: rgba(99, 102, 241, 0.06);
|
||||
}
|
||||
.jobHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.jobModel {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.jobPrompt {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-dim);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
}
|
||||
.jobMeta {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-dim);
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
.jobActions {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
.jobDuration {
|
||||
/* use default */
|
||||
}
|
||||
.badge {
|
||||
display: inline-block;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.badgePending {
|
||||
background: var(--border);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.badgeRunning {
|
||||
background: rgba(234, 179, 8, 0.2);
|
||||
color: var(--yellow);
|
||||
}
|
||||
.badgeCompleted,
|
||||
.badgeReady {
|
||||
background: rgba(34, 197, 94, 0.2);
|
||||
color: var(--green);
|
||||
}
|
||||
.badgeFailed {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
color: var(--red);
|
||||
}
|
||||
.badgeStopped {
|
||||
background: rgba(156, 163, 175, 0.2);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.badgePreprocessing {
|
||||
background: rgba(99, 102, 241, 0.2);
|
||||
color: var(--accent);
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
transition: background 0.15s, opacity 0.15s;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.btnSmall {
|
||||
background: transparent;
|
||||
color: var(--accent-h);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.btnStart {
|
||||
background: var(--green);
|
||||
color: #fff;
|
||||
}
|
||||
.btnStop {
|
||||
background: var(--yellow);
|
||||
color: #000;
|
||||
}
|
||||
.btnDelete {
|
||||
background: var(--red);
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
@@ -1,111 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { getJobsList } from "$lib/api";
|
||||
import type { JobType } from "$lib/types";
|
||||
import type { Job } from "$lib/types";
|
||||
import JobCard from "./JobCard.svelte";
|
||||
import { activeJobId, setActiveJobId, setActiveJob } from "$lib/stores/activeJob";
|
||||
import { registerRefresh, triggerRefresh } from "$lib/stores/jobsRefresh";
|
||||
|
||||
let {
|
||||
jobType,
|
||||
jobTypesForList,
|
||||
}: { jobType: JobType; jobTypesForList?: JobType[] } = $props();
|
||||
|
||||
let jobs = $state<Job[]>([]);
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const typesToFetch = $derived(jobTypesForList ?? [jobType]);
|
||||
|
||||
const activeJob = $derived(
|
||||
$activeJobId ? jobs.find((j) => j.id === $activeJobId) ?? null : null,
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
setActiveJob(activeJob);
|
||||
// Void active job ID if deleeted
|
||||
if ($activeJobId && !activeJob) setActiveJobId(null);
|
||||
});
|
||||
|
||||
async function fetchJobs() {
|
||||
try {
|
||||
if (typesToFetch.length === 1) {
|
||||
jobs = await getJobsList(typesToFetch[0]);
|
||||
} else {
|
||||
const results = await Promise.all(
|
||||
typesToFetch.map((t) => getJobsList(t)),
|
||||
);
|
||||
jobs = results
|
||||
.flat()
|
||||
.sort(
|
||||
(a, b) =>
|
||||
new Date(b.created_at ?? 0).getTime() -
|
||||
new Date(a.created_at ?? 0).getTime(),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch jobs:", e);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const hasActive = jobs.some(
|
||||
(j) => j.status === "running" || j.status === "pending",
|
||||
);
|
||||
if (hasActive) {
|
||||
interval = setInterval(fetchJobs, 1000);
|
||||
} else if (interval) {
|
||||
clearInterval(interval);
|
||||
interval = null;
|
||||
}
|
||||
return () => {
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
fetchJobs();
|
||||
return registerRefresh(fetchJobs);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (interval) clearInterval(interval);
|
||||
});
|
||||
</script>
|
||||
|
||||
<main class="main">
|
||||
<section class="card">
|
||||
<div id="jobs-container">
|
||||
{#if jobs.length === 0}
|
||||
<p class="placeholder">
|
||||
No {typesToFetch.length > 1 ? "jobs" : jobType + " jobs"} yet. Create
|
||||
one above.
|
||||
</p>
|
||||
{:else}
|
||||
{#each jobs as job (job.id)}
|
||||
<JobCard {job} onJobUpdated={fetchJobs} />
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.main {
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1rem 3rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
.card {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.placeholder {
|
||||
text-align: center;
|
||||
color: var(--text-dim);
|
||||
padding: 2rem 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,275 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from "$app/stores";
|
||||
import { resizable } from "$lib/actions/resizable";
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 100;
|
||||
const SIDEBAR_MAX_WIDTH = 300;
|
||||
const SIDEBAR_COLLAPSED_WIDTH = 0;
|
||||
const SIDEBAR_COLLAPSED_VISIBLE_WIDTH = 60;
|
||||
|
||||
const JOB_ROUTES = [
|
||||
{ href: "/inference", label: "Inference" },
|
||||
{ href: "/finetuning", label: "Finetuning" },
|
||||
{ href: "/distillation", label: "Distillation" },
|
||||
] as const;
|
||||
|
||||
let { onWidthChange }: { onWidthChange?: (w: number) => void } = $props();
|
||||
|
||||
let width = $state(220);
|
||||
let isCollapsed = $state(false);
|
||||
let isDragging = $state(false);
|
||||
let jobsOpen = $state(true);
|
||||
|
||||
const effectiveWidth = isCollapsed ? SIDEBAR_COLLAPSED_WIDTH : width;
|
||||
const layoutWidth = isCollapsed ? SIDEBAR_COLLAPSED_VISIBLE_WIDTH : width;
|
||||
const pathname = $derived($page.url.pathname);
|
||||
const isJobsActive = $derived(
|
||||
JOB_ROUTES.some((r) => pathname === r.href),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
onWidthChange?.(layoutWidth);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (JOB_ROUTES.some((r) => pathname === r.href)) {
|
||||
jobsOpen = true;
|
||||
}
|
||||
});
|
||||
|
||||
const resizableOpts = $derived({
|
||||
edge: "left" as const,
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: (w: number) => (width = w),
|
||||
onDragChange: (dragging: boolean) => (isDragging = dragging),
|
||||
});
|
||||
|
||||
function toggleCollapse() {
|
||||
isCollapsed = !isCollapsed;
|
||||
}
|
||||
|
||||
function toggleJobs() {
|
||||
jobsOpen = !jobsOpen;
|
||||
}
|
||||
</script>
|
||||
|
||||
<aside
|
||||
class="sidebar"
|
||||
class:collapsed={isCollapsed}
|
||||
style="width: {effectiveWidth}px"
|
||||
>
|
||||
<nav class="tabs">
|
||||
<div class="jobsGroup">
|
||||
<button
|
||||
type="button"
|
||||
class="tab tabTrigger"
|
||||
class:tabActive={isJobsActive}
|
||||
onclick={toggleJobs}
|
||||
aria-expanded={jobsOpen}
|
||||
aria-haspopup="true"
|
||||
>
|
||||
<span>Jobs</span>
|
||||
<svg
|
||||
class="chevron"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
class:rotated={jobsOpen}
|
||||
>
|
||||
<path d="M6 9l6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
{#if jobsOpen}
|
||||
<div class="jobsSubnav">
|
||||
{#each JOB_ROUTES as route}
|
||||
<a
|
||||
href={route.href}
|
||||
class="tab subTab"
|
||||
class:tabActive={pathname === route.href}
|
||||
>
|
||||
{route.label}
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<a href="/datasets" class="tab" class:tabActive={pathname === "/datasets"}>Datasets</a>
|
||||
<a href="/gallery" class="tab" class:tabActive={pathname === "/gallery"}>Gallery</a>
|
||||
<a href="/settings" class="tab" class:tabActive={pathname === "/settings"}>Settings</a>
|
||||
</nav>
|
||||
<div class="collapseFooter">
|
||||
<button
|
||||
type="button"
|
||||
class="collapseBtn"
|
||||
onclick={toggleCollapse}
|
||||
title={isCollapsed ? "Expand sidebar" : "Collapse sidebar"}
|
||||
>
|
||||
{#if isCollapsed}
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M9 18l6-6-6-6" />
|
||||
</svg>
|
||||
{:else}
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{#if !isCollapsed}
|
||||
<div
|
||||
class="resizeHandle"
|
||||
class:resizeHandleActive={isDragging}
|
||||
use:resizable={resizableOpts}
|
||||
role="presentation"
|
||||
></div>
|
||||
{/if}
|
||||
</aside>
|
||||
|
||||
<style>
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: var(--header-height);
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: calc(100vh - var(--header-height));
|
||||
background: var(--surface);
|
||||
border-right: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
z-index: 50;
|
||||
}
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 6px;
|
||||
bottom: 0;
|
||||
cursor: col-resize;
|
||||
z-index: 1;
|
||||
}
|
||||
.resizeHandle:hover,
|
||||
.resizeHandleActive {
|
||||
background: rgba(99, 102, 241, 0.2);
|
||||
}
|
||||
.resizeHandle::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 2px;
|
||||
height: 24px;
|
||||
background: var(--border);
|
||||
border-radius: 1px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.resizeHandle:hover::after,
|
||||
.resizeHandleActive::after {
|
||||
opacity: 1;
|
||||
}
|
||||
.collapseFooter {
|
||||
padding: 0.5rem;
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
}
|
||||
.collapseBtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-dim);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.collapseBtn:hover {
|
||||
color: var(--text);
|
||||
background: rgba(99, 102, 241, 0.08);
|
||||
}
|
||||
.collapseBtn svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.collapsed .tabs {
|
||||
display: none;
|
||||
}
|
||||
.collapsed .collapseFooter {
|
||||
border-top: none;
|
||||
top: 0;
|
||||
right: -60px;
|
||||
}
|
||||
.collapsed .collapseBtn {
|
||||
width: auto;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
.tabs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
.tab {
|
||||
display: block;
|
||||
padding: 0.65rem 1.25rem;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-dim);
|
||||
text-decoration: none;
|
||||
border: none;
|
||||
background: none;
|
||||
text-align: left;
|
||||
font-family: inherit;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.tab:hover {
|
||||
color: var(--text);
|
||||
background: rgba(99, 102, 241, 0.08);
|
||||
}
|
||||
.tabActive {
|
||||
color: var(--accent);
|
||||
font-weight: 500;
|
||||
background: rgba(99, 102, 241, 0.12);
|
||||
}
|
||||
.jobsGroup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
.tabTrigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tabTrigger .chevron {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex-shrink: 0;
|
||||
opacity: 0.85;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
.tabTrigger .chevron.rotated {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.jobsSubnav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 0.5rem;
|
||||
border-left: 2px solid var(--border);
|
||||
margin-left: 1rem;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.subTab {
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,305 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Job } from "$lib/types";
|
||||
import { getJobLogs, downloadJobLog } from "$lib/api";
|
||||
import { resizable } from "$lib/actions/resizable";
|
||||
|
||||
let { job, onClose, onWidthChange }: {
|
||||
job: Job;
|
||||
onClose: () => void;
|
||||
onWidthChange?: (w: number) => void;
|
||||
} = $props();
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 280;
|
||||
const SIDEBAR_MAX_WIDTH = 750;
|
||||
|
||||
let width = $state(360);
|
||||
let isDragging = $state(false);
|
||||
let isLoading = $state(false);
|
||||
let logs = $state<string[]>([]);
|
||||
let logAfter = $state(0);
|
||||
let consoleEl: HTMLPreElement;
|
||||
let previousJobId = $state<string | null>(null);
|
||||
let previousStatus = $state<string | null>(null);
|
||||
const stateRef = { logs: [] as string[], logAfter: 0 };
|
||||
let pollingLock = false;
|
||||
|
||||
$effect(() => {
|
||||
onWidthChange?.(width);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const wasTerminal =
|
||||
previousStatus === "failed" ||
|
||||
previousStatus === "stopped" ||
|
||||
previousStatus === "completed";
|
||||
const isRestarting =
|
||||
previousJobId === job.id &&
|
||||
wasTerminal &&
|
||||
(job.status === "pending" || job.status === "running");
|
||||
|
||||
if (previousJobId !== job.id || isRestarting) {
|
||||
logs = [];
|
||||
logAfter = 0;
|
||||
stateRef.logs = [];
|
||||
stateRef.logAfter = 0;
|
||||
}
|
||||
previousJobId = job.id;
|
||||
previousStatus = job.status;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const shouldPoll = job.status === "running" || job.status === "pending";
|
||||
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let mounted = true;
|
||||
|
||||
async function pollLogs() {
|
||||
if (!mounted || pollingLock) return;
|
||||
pollingLock = true;
|
||||
try {
|
||||
const logData = await getJobLogs(job.id, stateRef.logAfter);
|
||||
if (mounted && logData.lines.length > 0) {
|
||||
stateRef.logs = [...stateRef.logs, ...logData.lines];
|
||||
stateRef.logAfter = logData.total;
|
||||
logs = stateRef.logs;
|
||||
logAfter = stateRef.logAfter;
|
||||
if (consoleEl) consoleEl.scrollTop = consoleEl.scrollHeight;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch logs:", e);
|
||||
} finally {
|
||||
pollingLock = false;
|
||||
}
|
||||
}
|
||||
|
||||
pollLogs();
|
||||
if (shouldPoll) pollInterval = setInterval(pollLogs, 2000);
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
if (pollInterval) clearInterval(pollInterval);
|
||||
};
|
||||
});
|
||||
|
||||
const resizableOpts = $derived({
|
||||
edge: "right" as const,
|
||||
minWidth: SIDEBAR_MIN_WIDTH,
|
||||
maxWidth: SIDEBAR_MAX_WIDTH,
|
||||
getWidth: () => width,
|
||||
onWidth: (w: number) => (width = w),
|
||||
onDragChange: (dragging: boolean) => (isDragging = dragging),
|
||||
});
|
||||
|
||||
async function handleDownloadLog(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
isLoading = true;
|
||||
try {
|
||||
const blob = await downloadJobLog(job.id);
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `job_${job.id}.log`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
} catch (err) {
|
||||
console.error("Failed to download log:", err);
|
||||
alert(err instanceof Error ? err.message : "Failed to download log");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<aside class="sidebar" style="width: {width}px; max-width: {SIDEBAR_MAX_WIDTH}px">
|
||||
<div class="header">
|
||||
<h2 class="title">Job Details</h2>
|
||||
<div class="headerActions">
|
||||
<button
|
||||
class="btn btnSmall"
|
||||
onclick={handleDownloadLog}
|
||||
disabled={isLoading || !job.log_file_path}
|
||||
title="Download log file"
|
||||
>
|
||||
Download Log
|
||||
</button>
|
||||
<button type="button" class="closeBtn" onclick={onClose} title="Close">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M18 6L6 18M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="consoleSection">
|
||||
<div class="consoleHeader">
|
||||
<span class="consoleTitle">Console Output</span>
|
||||
{#if job.status === "running"}
|
||||
<span class="consoleStatus">● Live</span>
|
||||
{/if}
|
||||
</div>
|
||||
<pre bind:this={consoleEl} class="consoleOutput">{#if logs.length === 0}<span class="consoleEmpty">{job.status === "running" ? "Waiting for logs..." : "No logs available"}</span>{:else}{logs.join("\n")}{/if}</pre>
|
||||
</div>
|
||||
<div
|
||||
class="resizeHandle"
|
||||
class:resizeHandleActive={isDragging}
|
||||
use:resizable={resizableOpts}
|
||||
role="presentation"
|
||||
></div>
|
||||
</aside>
|
||||
|
||||
<style>
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: var(--header-height);
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: calc(100vh - var(--header-height));
|
||||
min-width: 280px;
|
||||
background: var(--surface);
|
||||
border-left: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
z-index: 50;
|
||||
}
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 6px;
|
||||
bottom: 0;
|
||||
cursor: col-resize;
|
||||
z-index: 1;
|
||||
}
|
||||
.resizeHandle:hover,
|
||||
.resizeHandleActive {
|
||||
background: rgba(99, 102, 241, 0.2);
|
||||
}
|
||||
.resizeHandle::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 2px;
|
||||
height: 24px;
|
||||
background: var(--border);
|
||||
border-radius: 1px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.resizeHandle:hover::after,
|
||||
.resizeHandleActive::after {
|
||||
opacity: 1;
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 1.25rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.closeBtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.4rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-dim);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius);
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.closeBtn:hover {
|
||||
color: var(--text);
|
||||
background: rgba(99, 102, 241, 0.08);
|
||||
}
|
||||
.closeBtn svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.consoleSection {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
padding: 1rem 1.25rem;
|
||||
}
|
||||
.consoleHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.consoleTitle {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-dim);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.consoleStatus {
|
||||
font-size: 0.7rem;
|
||||
color: var(--green);
|
||||
font-weight: 500;
|
||||
}
|
||||
.consoleOutput {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.75rem;
|
||||
font-family: Monaco, Menlo, "Ubuntu Mono", Consolas, monospace;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text);
|
||||
overflow-y: auto;
|
||||
overflow-x: auto;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
margin: 0;
|
||||
}
|
||||
.consoleEmpty {
|
||||
color: var(--text-dim);
|
||||
font-style: italic;
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.55rem 1.2rem;
|
||||
transition: background 0.15s, opacity 0.15s;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.btnSmall {
|
||||
background: transparent;
|
||||
color: var(--accent-h);
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.btnSmall:hover {
|
||||
background: var(--border);
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user