jrrribeiro commited on
Commit
661a924
·
verified ·
1 Parent(s): 22198e9

Sync app from GitHub Actions

Browse files
docs/TEMP_PROJECT_STATE_SECURITY_REVIEW_PLAN.md ADDED
@@ -0,0 +1,655 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Temporary Plan: Project State, Security, and Privacy Review
2
+
3
+ Status: planning document
4
+ Created: 2026-05-21
5
+ Scope: BirdNET Validator App project persistence, authentication, authorization, secret handling, and validation-state ownership
6
+
7
+ ## Purpose
8
+
9
+ This document records the next structural review for the BirdNET Validator App after the Gradio UI and current Supabase-backed workflows reached a usable test state.
10
+
11
+ The next target is not a visual redesign. It is a security and persistence redesign:
12
+
13
+ 1. Keep the shared Space lightweight and as close to stateless as practical.
14
+ 2. Avoid making the maintainer's Supabase account the permanent storage and cost center for third-party projects.
15
+ 3. Store each project's durable state under the project admin's Hugging Face account or organization when feasible.
16
+ 4. Preserve privacy, auditability, collaboration, and recovery across Space redeploys and app updates.
17
+
18
+ This is a temporary engineering plan. It should be revisited before implementation and converted into issue-sized tasks once the target state backend is validated.
19
+
20
+ ## Executive Decision
21
+
22
+ The recommended product direction is:
23
+
24
+ > Project audio data and validator state should be owned by the project admin or the admin's organization. The BirdNET Validator Space should authenticate users, load project state, and operate on state stores it does not centrally own.
25
+
26
+ The current Supabase backend should remain available during development and can remain an advanced backend option, but it should not be the only production architecture for a public multi-project app.
27
+
28
+ ## Current Architecture Summary
29
+
30
+ ### Runtime modes
31
+
32
+ The app currently supports:
33
+
34
+ 1. Filesystem state
35
+ - Project bootstrap files.
36
+ - User access files.
37
+ - Invite files.
38
+ - Append-only validation files.
39
+ - Suitable for local tests or Spaces with persistent storage.
40
+
41
+ 2. Supabase state
42
+ - Project records.
43
+ - Project ACL assignments.
44
+ - Pending invites.
45
+ - Validation event log.
46
+ - Current validation snapshot.
47
+ - Suitable for current Spaces testing without persistent local storage.
48
+
49
+ ### Current state surfaces
50
+
51
+ The following durable state exists or is planned to exist per project:
52
+
53
+ | State | Current storage | Sensitivity | Expected growth |
54
+ |---|---|---|---|
55
+ | Project metadata | filesystem or Supabase | low to medium | tiny |
56
+ | Dataset reference | filesystem or Supabase | low unless private metadata is sensitive | tiny |
57
+ | Project ACL | filesystem or Supabase | medium | small |
58
+ | Pending invites | filesystem or Supabase | medium, may include email | small |
59
+ | Project dataset token | filesystem or Supabase | high | tiny but risky |
60
+ | Validation events | filesystem or Supabase | medium | high |
61
+ | Current validation snapshot | filesystem or Supabase | medium | high |
62
+ | Derived progress reports | computed | low to medium | cacheable |
63
+
64
+ ### Current useful properties
65
+
66
+ The app already has several good structural properties:
67
+
68
+ 1. Roles are scoped per project.
69
+ 2. Admin operations are checked in backend callbacks.
70
+ 3. Private projects block collaborator invites.
71
+ 4. Validation writes use append-only history plus current snapshots.
72
+ 5. Optimistic conflict handling exists for concurrent validation writes.
73
+ 6. Dataset index loading now prefers the known `HF_Dataset_Uploader` index path before expensive repository tree discovery.
74
+
75
+ ## Risk Review
76
+
77
+ ## 1. Authentication risk
78
+
79
+ ### Current concern
80
+
81
+ Username-only login is convenient for demo and local testing, but it does not prove identity in production.
82
+
83
+ ### Required direction
84
+
85
+ Production login must require a verified Hugging Face identity:
86
+
87
+ 1. Hugging Face OAuth for Spaces as the preferred flow.
88
+ 2. Token-backed `whoami` validation only as an explicit fallback or developer mode.
89
+ 3. Username-only login restricted to demo/test mode.
90
+
91
+ ### Acceptance criteria
92
+
93
+ 1. A production user cannot claim another Hugging Face username by typing it.
94
+ 2. Session identity is derived from an authenticated Hugging Face identity.
95
+ 3. The app does not persist personal HF tokens in project state.
96
+
97
+ ## 2. Secret storage risk
98
+
99
+ ### Current concern
100
+
101
+ Projects can persist `dataset_token`. This can centralize admin tokens in the app's persistence layer.
102
+
103
+ ### Required direction
104
+
105
+ Prefer tokenless project records:
106
+
107
+ 1. Users access datasets and project state with their own authenticated HF permissions.
108
+ 2. Project tokens are not stored by default.
109
+ 3. Any unavoidable secret support is isolated behind explicit opt-in backend configuration, encrypted storage, least privilege, audit logs, and clear warnings.
110
+
111
+ ### Acceptance criteria
112
+
113
+ 1. The standard collaborative project flow does not require a stored project token.
114
+ 2. Validators cannot read token values through the UI, logs, reports, state exports, or error messages.
115
+ 3. Project-state backends have an explicit policy for whether they may persist secrets.
116
+
117
+ ## 3. Central storage and quota risk
118
+
119
+ ### Current concern
120
+
121
+ One maintainer-owned Supabase project currently stores all project metadata and validation state when Supabase mode is enabled.
122
+
123
+ ### Consequences
124
+
125
+ 1. Quota and possible future cost accumulate on the maintainer.
126
+ 2. A single backend outage can affect all projects.
127
+ 3. The maintainer becomes custodian of third-party ACL and validation data.
128
+ 4. Growth is dominated by validation events, not by the project catalog.
129
+
130
+ ### Required direction
131
+
132
+ Use admin-owned project stores for the community/default architecture.
133
+
134
+ ## 4. Privacy and ownership risk
135
+
136
+ ### Current concern
137
+
138
+ ACL, invite emails, project metadata, and validation decisions can reveal project membership and work activity.
139
+
140
+ ### Required direction
141
+
142
+ 1. Project admins own their durable project state.
143
+ 2. State visibility follows project visibility and admin decisions.
144
+ 3. Email invites are optional and must avoid overexposing private project details.
145
+ 4. Logs should avoid tokens, email contents, and raw secrets.
146
+
147
+ ## Target Architecture
148
+
149
+ ## Core principle
150
+
151
+ The Space should not be the long-term owner of user projects.
152
+
153
+ Each project should reference:
154
+
155
+ 1. An audio dataset.
156
+ 2. A validator state store.
157
+ 3. A schema version.
158
+ 4. A security policy.
159
+
160
+ ## Recommended project layout
161
+
162
+ ### Audio dataset
163
+
164
+ Existing source of segments and uploader index:
165
+
166
+ ```text
167
+ owner-or-org/audio-dataset
168
+ ```
169
+
170
+ ### Validator state store
171
+
172
+ New durable state owned by the admin or organization:
173
+
174
+ ```text
175
+ owner-or-org/audio-dataset-validator-state
176
+ ```
177
+
178
+ The first implementation spike should compare:
179
+
180
+ 1. Hugging Face Storage Bucket state.
181
+ 2. Companion Hugging Face dataset repository state.
182
+
183
+ The preferred option after the spike should become the default `HfProjectStateBackend`.
184
+
185
+ ## Proposed project manifest
186
+
187
+ The project record should contain a non-secret manifest-like reference:
188
+
189
+ ```json
190
+ {
191
+ "schema_version": 1,
192
+ "project_slug": "amazonia-2026",
193
+ "project_name": "Amazonia 2026",
194
+ "dataset_repo_id": "owner-or-org/amazonia-audio",
195
+ "state_backend": "hf_project_store",
196
+ "state_ref": "owner-or-org/amazonia-audio-validator-state",
197
+ "owner_username": "owner-or-org-admin",
198
+ "visibility": "collaborative"
199
+ }
200
+ ```
201
+
202
+ This manifest must not contain a private token.
203
+
204
+ ## Proposed durable state objects
205
+
206
+ The exact storage format may change after the backend spike, but state must be separable into:
207
+
208
+ ```text
209
+ project.json
210
+ acl.json or acl table
211
+ invites.json or invites table
212
+ events/
213
+ snapshots/
214
+ reports/ optional derived cache
215
+ locks/ or reservations/ optional workflow coordination
216
+ ```
217
+
218
+ ### Minimum event record
219
+
220
+ Validation history must preserve:
221
+
222
+ 1. Project identifier.
223
+ 2. Detection key.
224
+ 3. Status.
225
+ 4. Validator identity.
226
+ 5. Timestamp.
227
+ 6. Corrected species if any.
228
+ 7. Notes if any.
229
+ 8. Expected and resulting version or equivalent conflict metadata.
230
+
231
+ ## Backend Abstraction Plan
232
+
233
+ Create an explicit project-state interface before adding more persistence logic to `app_factory.py`.
234
+
235
+ ## Required interfaces
236
+
237
+ At minimum separate:
238
+
239
+ 1. `ProjectCatalogRepository`
240
+ 2. `ProjectAccessRepository`
241
+ 3. `ProjectInviteRepository`
242
+ 4. `ValidationEventRepository`
243
+ 5. `CurrentValidationRepository`
244
+
245
+ If a smaller initial abstraction is needed, begin with:
246
+
247
+ ```python
248
+ class ProjectStateBackend:
249
+ def load_project(...)
250
+ def create_project(...)
251
+ def load_acl(...)
252
+ def save_acl(...)
253
+ def load_invites(...)
254
+ def save_invites(...)
255
+ def append_validation_event(...)
256
+ def load_current_snapshot(...)
257
+ def save_current_snapshot(...)
258
+ ```
259
+
260
+ ## Planned implementations
261
+
262
+ | Backend | Role |
263
+ |---|---|
264
+ | Filesystem | local/demo/dev and offline tests |
265
+ | Supabase | current backend, advanced hosted DB mode |
266
+ | Hugging Face project store | recommended community/default mode |
267
+
268
+ ## Authentication and Authorization Plan
269
+
270
+ ## Production login policy
271
+
272
+ 1. Enable Hugging Face OAuth flow in the Space.
273
+ 2. Restrict requested scopes to the smallest set proven necessary.
274
+ 3. Keep explicit token login only when OAuth does not cover a required flow.
275
+ 4. Keep username-only login behind a demo/development flag.
276
+
277
+ ## Project authorization policy
278
+
279
+ Authorization needs two layers:
280
+
281
+ 1. App/project ACL
282
+ - Admin.
283
+ - Validator.
284
+ - Optional future reviewer/auditor roles.
285
+
286
+ 2. Hugging Face resource permissions
287
+ - Dataset read permissions.
288
+ - State store read/write permissions.
289
+
290
+ Both must pass for a protected operation.
291
+
292
+ ## Role expectations
293
+
294
+ | Action | Admin | Validator |
295
+ |---|---|---|
296
+ | Read authorized project metadata | yes | yes |
297
+ | Read audio dataset if HF permissions allow | yes | yes |
298
+ | Validate assigned project | yes | yes |
299
+ | Read project progress | yes | yes or policy-controlled |
300
+ | Invite/remove users | yes | no |
301
+ | Change state store reference | yes | no |
302
+ | Delete/archive project state | yes with safeguards | no |
303
+
304
+ ## Project Creation Flow
305
+
306
+ ## Target flow
307
+
308
+ 1. User authenticates with verified HF identity.
309
+ 2. User selects an existing dataset or provides a dataset repo id.
310
+ 3. App verifies dataset access.
311
+ 4. User chooses the state backend.
312
+ 5. Default flow creates or connects a state store owned by that user or organization.
313
+ 6. App writes project manifest and initial ACL.
314
+ 7. Creator becomes project admin.
315
+ 8. Project becomes visible to the creator after successful state-store initialization.
316
+
317
+ ## Failure policy
318
+
319
+ Project creation must be transactional enough to avoid half-created UI records:
320
+
321
+ 1. If state store creation fails, project is not shown as ready.
322
+ 2. If manifest write fails, state store is marked incomplete or cleaned up if safe.
323
+ 3. The UI must show a recoverable status instead of silently creating broken projects.
324
+
325
+ ## Validation Write Strategy Review
326
+
327
+ ## Problem to solve
328
+
329
+ HF-backed object or repo storage is not automatically equivalent to a relational transactional database.
330
+
331
+ The spike must decide how to preserve:
332
+
333
+ 1. Append-only audit history.
334
+ 2. Current snapshot lookup speed.
335
+ 3. Concurrency safety.
336
+ 4. Progress dashboard speed.
337
+ 5. Recovery after app restart.
338
+
339
+ ## Candidate strategies
340
+
341
+ ### Strategy A: event batches plus periodic snapshots
342
+
343
+ 1. Append validation events in small batch objects.
344
+ 2. Maintain compact snapshots by project.
345
+ 3. Rebuild snapshot if needed from events.
346
+
347
+ Pros:
348
+ - Audit-friendly.
349
+ - Portable.
350
+ - Works with storage systems that like batch writes.
351
+
352
+ Risks:
353
+ - Needs conflict strategy.
354
+ - Snapshot updates need merge discipline.
355
+
356
+ ### Strategy B: dataset commits with batched JSONL/Parquet files
357
+
358
+ Pros:
359
+ - Native HF repository history.
360
+ - Easy download/export.
361
+
362
+ Risks:
363
+ - Commit pressure.
364
+ - More latency.
365
+ - Git/LFS history is not ideal for frequent small writes.
366
+
367
+ ### Strategy C: admin-owned database
368
+
369
+ Pros:
370
+ - Strongest concurrency and query ergonomics.
371
+
372
+ Risks:
373
+ - Setup burden.
374
+ - Not the default no-cost/no-maintainer-cost flow.
375
+
376
+ ## Initial recommendation
377
+
378
+ Prototype Strategy A for the HF project store. Keep Supabase Strategy C as an advanced backend.
379
+
380
+ ## Storage Growth and Cost Model
381
+
382
+ ## Important observation
383
+
384
+ Project catalog size is negligible compared with validation history.
385
+
386
+ ### Estimate categories
387
+
388
+ | Category | Expected size |
389
+ |---|---|
390
+ | Project manifest | KB |
391
+ | ACL and pending invites | KB to small MB |
392
+ | Current snapshot | grows with validated detection count |
393
+ | Validation events | grows with validation actions and revisions |
394
+ | Cached reports | optional, bounded |
395
+
396
+ ## Required product behavior
397
+
398
+ 1. State store belongs to admin or organization.
399
+ 2. Project exports are supported.
400
+ 3. Archiving is supported.
401
+ 4. Retention policy is explicit for any derived cache.
402
+ 5. Event history is not silently destroyed.
403
+
404
+ ## Security Review Checklist
405
+
406
+ Implementation must address:
407
+
408
+ 1. Verified identity only in production.
409
+ 2. Least-privilege HF OAuth scopes.
410
+ 3. No token values in logs.
411
+ 4. No token values in Gradio component values after submit.
412
+ 5. No token values in state exports by default.
413
+ 6. Admin-only ACL mutation.
414
+ 7. Admin-only state backend mutation.
415
+ 8. Validator cannot inspect unauthorized project metadata.
416
+ 9. State store reference cannot be used to escape project authorization.
417
+ 10. Invite links and invite messages do not become bearer access tokens unless deliberately designed and protected.
418
+ 11. Invite email addresses are minimized and covered by privacy documentation.
419
+ 12. Project deletion/archive flow has confirmation and recovery policy.
420
+ 13. Public datasets and private project state are handled as separate visibility decisions.
421
+
422
+ ## Migration Plan
423
+
424
+ ## Phase 0: freeze assumptions
425
+
426
+ Deliverables:
427
+
428
+ 1. Confirm current production deployment mode.
429
+ 2. Confirm whether the desired default is HF Bucket or companion dataset after a technical spike.
430
+ 3. Confirm whether validation state may be public when audio datasets are public.
431
+
432
+ Exit criteria:
433
+
434
+ 1. Written architecture decision.
435
+ 2. One real project selected for migration testing.
436
+
437
+ ## Phase 1: production auth hardening
438
+
439
+ Deliverables:
440
+
441
+ 1. OAuth-first login path.
442
+ 2. Development-only flag for username login.
443
+ 3. Session identity tests.
444
+ 4. Updated settings/status panel showing active auth mode without exposing secrets.
445
+
446
+ Tests:
447
+
448
+ 1. User A cannot impersonate User B.
449
+ 2. Invalid token cannot create a session.
450
+ 3. OAuth identity maps to ACL identity.
451
+
452
+ ## Phase 2: state abstraction refactor
453
+
454
+ Deliverables:
455
+
456
+ 1. Move state persistence contracts out of UI callbacks.
457
+ 2. Keep Supabase implementation passing existing tests.
458
+ 3. Keep filesystem implementation for local/demo mode.
459
+ 4. Add contract tests shared by each backend.
460
+
461
+ Tests:
462
+
463
+ 1. Project create/load/archive.
464
+ 2. ACL grant/revoke/load.
465
+ 3. Invite create/accept/revoke/expire.
466
+ 4. Validation append/snapshot/conflict.
467
+
468
+ ## Phase 3: HF project-state backend spike
469
+
470
+ Deliverables:
471
+
472
+ 1. Minimal backend for one project store.
473
+ 2. State-store initialization flow.
474
+ 3. Read/write validation proof.
475
+ 4. Multi-user project permission proof.
476
+ 5. Restart/redeploy persistence proof.
477
+
478
+ Questions to answer:
479
+
480
+ 1. Bucket or companion dataset?
481
+ 2. How are write permissions granted to validators?
482
+ 3. Does the app write on behalf of each validator or via an admin-owned delegated path?
483
+ 4. How are atomic version updates represented?
484
+ 5. What write batching is necessary for good latency?
485
+
486
+ Exit criteria:
487
+
488
+ 1. One real project can validate, reload, report progress, and survive app redeploy without Supabase.
489
+
490
+ ## Phase 4: project onboarding flow
491
+
492
+ Deliverables:
493
+
494
+ 1. Create project wizard.
495
+ 2. Connect existing project store wizard.
496
+ 3. Ownership and permission validation.
497
+ 4. Recovery UI for incomplete state stores.
498
+ 5. Optional export manifest.
499
+
500
+ ## Phase 5: migration tools
501
+
502
+ Deliverables:
503
+
504
+ 1. Export Supabase project state.
505
+ 2. Import into HF project store.
506
+ 3. Verification report comparing:
507
+ - project metadata;
508
+ - ACL;
509
+ - invites if retained;
510
+ - current snapshot;
511
+ - event count.
512
+ 4. Rollback plan.
513
+
514
+ ## Phase 6: documentation and production defaults
515
+
516
+ Deliverables:
517
+
518
+ 1. Privacy and storage ownership explanation.
519
+ 2. Admin onboarding guide.
520
+ 3. Validator access guide.
521
+ 4. Backend selection guide.
522
+ 5. Security caveats for public/private datasets and state stores.
523
+ 6. Updated deployment docs that do not present maintainer-owned Supabase as the only durable option.
524
+
525
+ ## Testing Strategy
526
+
527
+ ## Unit tests
528
+
529
+ 1. Auth mode gates.
530
+ 2. ACL checks.
531
+ 3. Invite lifecycle.
532
+ 4. Backend contracts.
533
+ 5. Secret redaction.
534
+ 6. Manifest validation.
535
+ 7. Migration transforms.
536
+
537
+ ## Integration tests
538
+
539
+ 1. Filesystem backend.
540
+ 2. Supabase backend with mocked REST boundary.
541
+ 3. HF project-state backend with mocked Hub/storage boundary.
542
+ 4. Dataset index load versus state load.
543
+
544
+ ## Manual end-to-end tests
545
+
546
+ 1. Admin creates project from HF dataset.
547
+ 2. App initializes project-owned state.
548
+ 3. Admin invites validator.
549
+ 4. Validator accepts access.
550
+ 5. Validator validates audio.
551
+ 6. Admin sees progress.
552
+ 7. Project survives app restart and deploy.
553
+ 8. Unauthorized user cannot see or mutate project.
554
+ 9. Private project cannot be joined without policy approval.
555
+
556
+ ## Load and scale tests
557
+
558
+ Test at least:
559
+
560
+ 1. Thousands of validations.
561
+ 2. Hundreds of thousands of snapshot rows.
562
+ 3. Revalidation history.
563
+ 4. Many project manifests.
564
+ 5. Many validators writing during the same interval.
565
+
566
+ Measure:
567
+
568
+ 1. Validation save latency.
569
+ 2. Snapshot refresh latency.
570
+ 3. Report refresh latency.
571
+ 4. State-store write amplification.
572
+ 5. API rate-limit behavior.
573
+
574
+ ## Open Decisions
575
+
576
+ The next review must decide:
577
+
578
+ 1. Is the first HF state backend a Storage Bucket or companion dataset?
579
+ 2. Should project state default to private even if audio is public?
580
+ 3. Are validators allowed to write directly to state stores with their HF identity?
581
+ 4. Do we support organization-owned projects in the first implementation?
582
+ 5. Do we support email-only invites before OAuth/store ownership is redesigned?
583
+ 6. Is `dataset_token` removed entirely from the default app flow or kept as admin-only legacy compatibility?
584
+ 7. What export format is the long-term portable archive of project state?
585
+
586
+ ## Recommended Implementation Order
587
+
588
+ 1. Auth hardening.
589
+ 2. Backend interfaces and contract tests.
590
+ 3. HF project-state backend spike.
591
+ 4. Project creation/connect wizard.
592
+ 5. Migration/export tooling.
593
+ 6. Documentation and production defaults.
594
+
595
+ ## Not Recommended
596
+
597
+ Avoid these as default production decisions:
598
+
599
+ 1. Treating the free Space filesystem as durable state.
600
+ 2. Storing all third-party projects indefinitely in a maintainer-owned free Supabase project.
601
+ 3. Requiring every non-technical admin to configure a separate database before creating a project.
602
+ 4. Persisting reusable broad HF tokens in project records unless an explicit secure legacy mode is designed.
603
+ 5. Writing one HF repository commit for every single validation action.
604
+
605
+ ## Initial Backlog Seed
606
+
607
+ ### Epic A: Production identity
608
+
609
+ 1. Add auth-mode config.
610
+ 2. Add OAuth session adapter.
611
+ 3. Disable username-only production login.
612
+ 4. Add auth regression tests.
613
+
614
+ ### Epic B: Project state contracts
615
+
616
+ 1. Define storage contracts.
617
+ 2. Move current Supabase persistence behind contracts.
618
+ 3. Move filesystem persistence behind contracts.
619
+ 4. Add backend contract tests.
620
+
621
+ ### Epic C: HF-owned project state spike
622
+
623
+ 1. Prototype state store creation/connect.
624
+ 2. Prototype event append and snapshot update.
625
+ 3. Prototype ACL read/write.
626
+ 4. Prototype report load.
627
+ 5. Document limits and permission behavior.
628
+
629
+ ### Epic D: Product flows
630
+
631
+ 1. Project creation wizard.
632
+ 2. Project connect wizard.
633
+ 3. Project export/archive UI.
634
+ 4. Admin storage visibility/status panel.
635
+
636
+ ### Epic E: Migration and operations
637
+
638
+ 1. Supabase export.
639
+ 2. HF state import.
640
+ 3. State verification report.
641
+ 4. Deployment docs.
642
+ 5. Privacy and security docs.
643
+
644
+ ## Definition of Done for the Redesign
645
+
646
+ The redesign is complete when:
647
+
648
+ 1. The production app does not rely on username-only identity.
649
+ 2. The default public/community architecture does not charge project storage growth to the maintainer.
650
+ 3. Project durable state survives Space redeploys and app updates under admin-owned storage.
651
+ 4. The standard project flow does not require stored project HF tokens.
652
+ 5. ACL, invites, validation writes, and reports are covered by backend contract tests.
653
+ 6. One migrated real project completes validation workflow without Supabase.
654
+ 7. Admins can understand where their project state lives and how to export it.
655
+
src/auth/auth_service.py CHANGED
@@ -260,16 +260,16 @@ class AuthService:
260
  """Authenticate using Hugging Face personal token and resolve username via whoami."""
261
  token_value = (token or "").strip()
262
  if not token_value:
263
- return None, "❌ Please provide a Hugging Face token"
264
 
265
  try:
266
  whoami = HfApi().whoami(token=token_value)
267
  except Exception:
268
- return None, "❌ Invalid Hugging Face token or network error"
269
 
270
  username = str(whoami.get("name") or "").strip()
271
  if not username:
272
- return None, "❌ Unable to resolve Hugging Face username from token"
273
 
274
  email_value = str(whoami.get("email") or "").strip() or None
275
  self._hf_tokens_by_username[username] = token_value
@@ -281,13 +281,13 @@ class AuthService:
281
  auto_promote_to_admin=is_first_user,
282
  )
283
  if session is None:
284
- return None, f"❌ User '{username}' is not invited to any project yet"
285
 
286
  if is_first_user:
287
- return session, f"✅ Welcome, {username}! (Admin)"
288
  if session.role == Role.admin:
289
- return session, f"✅ Welcome, {username}! (Admin)"
290
- return session, f"✅ Welcome, {username}! (Validator)"
291
 
292
  def get_session(self, session_id: str) -> Optional[Session]:
293
  """Retrieve an active session by ID.
@@ -493,7 +493,7 @@ class AuthService:
493
  self._pending_invites.setdefault(email_key, {})[project_slug] = invite
494
 
495
  mode = invite.invite_mode
496
- summary = f"✅ {mode.replace('_', ' ').title()} invite"
497
  return True, summary
498
 
499
  def list_pending_invites(self, username: str) -> List[ProjectInvite]:
@@ -527,7 +527,7 @@ class AuthService:
527
  del pending[project_slug]
528
  if not pending:
529
  self._pending_invites.pop(invite_key, None)
530
- return True, f"✅ Invite accepted for {project_slug} as {invite.role.value}"
531
 
532
  def reject_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
533
  self._prune_expired_invites()
@@ -538,7 +538,7 @@ class AuthService:
538
  del pending[project_slug]
539
  if not pending:
540
  self._pending_invites.pop(invite_key, None)
541
- return True, f"✅ Invite rejected for {project_slug}"
542
 
543
  def accept_all_project_invites(self, username: str) -> tuple[int, int, str]:
544
  self._prune_expired_invites()
@@ -568,7 +568,7 @@ class AuthService:
568
  del pending[project_slug]
569
  if not pending:
570
  self._pending_invites.pop(invite_key, None)
571
- return True, f"✅ Invite revoked for {username} in {project_slug}"
572
 
573
  def export_user_access_map(self, include_inactive: bool = False) -> Dict[str, Dict[str, str]]:
574
  """Export user/project role mapping for persistence."""
 
260
  """Authenticate using Hugging Face personal token and resolve username via whoami."""
261
  token_value = (token or "").strip()
262
  if not token_value:
263
+ return None, "Please provide a Hugging Face token"
264
 
265
  try:
266
  whoami = HfApi().whoami(token=token_value)
267
  except Exception:
268
+ return None, "Invalid Hugging Face token or network error"
269
 
270
  username = str(whoami.get("name") or "").strip()
271
  if not username:
272
+ return None, "Unable to resolve Hugging Face username from token"
273
 
274
  email_value = str(whoami.get("email") or "").strip() or None
275
  self._hf_tokens_by_username[username] = token_value
 
281
  auto_promote_to_admin=is_first_user,
282
  )
283
  if session is None:
284
+ return None, f"User '{username}' is not invited to any project yet"
285
 
286
  if is_first_user:
287
+ return session, f"Welcome, {username}. Admin access enabled."
288
  if session.role == Role.admin:
289
+ return session, f"Welcome, {username}. Admin access enabled."
290
+ return session, f"Welcome, {username}. Validator access enabled."
291
 
292
  def get_session(self, session_id: str) -> Optional[Session]:
293
  """Retrieve an active session by ID.
 
493
  self._pending_invites.setdefault(email_key, {})[project_slug] = invite
494
 
495
  mode = invite.invite_mode
496
+ summary = f"{mode.replace('_', ' ').title()} invite"
497
  return True, summary
498
 
499
  def list_pending_invites(self, username: str) -> List[ProjectInvite]:
 
527
  del pending[project_slug]
528
  if not pending:
529
  self._pending_invites.pop(invite_key, None)
530
+ return True, f"Invite accepted for {project_slug} as {invite.role.value}"
531
 
532
  def reject_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
533
  self._prune_expired_invites()
 
538
  del pending[project_slug]
539
  if not pending:
540
  self._pending_invites.pop(invite_key, None)
541
+ return True, f"Invite rejected for {project_slug}"
542
 
543
  def accept_all_project_invites(self, username: str) -> tuple[int, int, str]:
544
  self._prune_expired_invites()
 
568
  del pending[project_slug]
569
  if not pending:
570
  self._pending_invites.pop(invite_key, None)
571
+ return True, f"Invite revoked for {username} in {project_slug}"
572
 
573
  def export_user_access_map(self, include_inactive: bool = False) -> Dict[str, Dict[str, str]]:
574
  """Export user/project role mapping for persistence."""
src/domain/models.py CHANGED
@@ -44,8 +44,3 @@ class Validation(BaseModel):
44
  validator: str = Field(min_length=1)
45
 
46
 
47
- class IndexManifest(BaseModel):
48
- schema_version: str = "1.0.0"
49
- project_slug: str
50
- total_detections: int = Field(ge=0)
51
- total_audio_files: int = Field(ge=0)
 
44
  validator: str = Field(min_length=1)
45
 
46
 
 
 
 
 
 
src/repositories/contracts.py CHANGED
@@ -1,10 +1,6 @@
1
  from typing import Protocol
2
 
3
- from src.domain.models import Detection, Project, User, Validation
4
-
5
-
6
- class ProjectRepository(Protocol):
7
- def get_project(self, project_slug: str) -> Project: ...
8
 
9
 
10
  class DetectionRepository(Protocol):
@@ -31,5 +27,3 @@ class ValidationRepository(Protocol):
31
  def save_validation(self, project_slug: str, item: Validation, expected_version: int | None = None) -> int: ...
32
 
33
 
34
- class AuthRepository(Protocol):
35
- def authenticate(self, username: str) -> User: ...
 
1
  from typing import Protocol
2
 
3
+ from src.domain.models import Detection, Validation
 
 
 
 
4
 
5
 
6
  class DetectionRepository(Protocol):
 
27
  def save_validation(self, project_slug: str, item: Validation, expected_version: int | None = None) -> int: ...
28
 
29
 
 
 
src/repositories/supabase_state.py CHANGED
@@ -91,6 +91,8 @@ class SupabaseBootstrapStore:
91
  def load_projects(self) -> list[Project]:
92
  projects: list[Project] = []
93
  for row in self._client.select("projects", query={"order": "project_slug.asc"}):
 
 
94
  try:
95
  projects.append(
96
  Project(
@@ -159,6 +161,20 @@ class SupabaseBootstrapStore:
159
  ]
160
  self._client.upsert("projects", project_rows, on_conflict="project_slug")
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  access_rows = []
163
  seen_access: set[tuple[str, str]] = set()
164
  for username, roles in user_access.items():
 
91
  def load_projects(self) -> list[Project]:
92
  projects: list[Project] = []
93
  for row in self._client.select("projects", query={"order": "project_slug.asc"}):
94
+ if not bool(row.get("active", True)):
95
+ continue
96
  try:
97
  projects.append(
98
  Project(
 
161
  ]
162
  self._client.upsert("projects", project_rows, on_conflict="project_slug")
163
 
164
+ active_project_slugs = {
165
+ str(project.get("project_slug") or "").strip()
166
+ for project in projects
167
+ if str(project.get("project_slug") or "").strip()
168
+ }
169
+ for row in self._client.select("projects"):
170
+ project_slug = str(row.get("project_slug") or "").strip()
171
+ if project_slug and project_slug not in active_project_slugs:
172
+ self._client.patch(
173
+ "projects",
174
+ {"active": False, "updated_at": datetime.now(UTC).isoformat()},
175
+ query={"project_slug": SupabaseRestClient.eq(project_slug)},
176
+ )
177
+
178
  access_rows = []
179
  seen_access: set[tuple[str, str]] = set()
180
  for username, roles in user_access.items():
src/services/invite_email_notifier.py CHANGED
@@ -80,7 +80,7 @@ class EmailJSInviteEmailNotifier(InviteEmailNotifier):
80
  """
81
  invite_mode = self._resolve_invite_mode(payload)
82
  if not payload.invitee_email:
83
- return True, f"✅ Internal invite created for {payload.invitee_username or 'pending'}"
84
 
85
  template_id = self._resolve_template_id(invite_mode)
86
  if not template_id:
@@ -116,7 +116,7 @@ class EmailJSInviteEmailNotifier(InviteEmailNotifier):
116
  with request.urlopen(req, timeout=self._timeout_seconds) as response:
117
  status_code = int(getattr(response, "status", 0) or response.getcode())
118
  if 200 <= status_code < 300:
119
- return True, f"✅ Invite sent to {payload.invitee_email}"
120
  return False, f"Internal invite created, but email send failed (status {status_code})"
121
  except Exception as exc:
122
  return False, f"Internal invite created, but email send failed: {exc}"
 
80
  """
81
  invite_mode = self._resolve_invite_mode(payload)
82
  if not payload.invitee_email:
83
+ return True, f"Internal invite created for {payload.invitee_username or 'pending'}"
84
 
85
  template_id = self._resolve_template_id(invite_mode)
86
  if not template_id:
 
116
  with request.urlopen(req, timeout=self._timeout_seconds) as response:
117
  status_code = int(getattr(response, "status", 0) or response.getcode())
118
  if 200 <= status_code < 300:
119
+ return True, f"Invite sent to {payload.invitee_email}"
120
  return False, f"Internal invite created, but email send failed (status {status_code})"
121
  except Exception as exc:
122
  return False, f"Internal invite created, but email send failed: {exc}"
src/ui/admin_panel.py CHANGED
@@ -1,10 +1,8 @@
1
- """Gradio admin panel for managing projects and user assignments."""
2
 
3
  from typing import List, Tuple
4
 
5
- import gradio as gr
6
-
7
- from src.auth.auth_service import AuthService, Session
8
  from src.domain.models import Project, Role
9
  from src.services.invite_email_notifier import InviteEmailNotifier, InviteEmailPayload
10
 
@@ -129,7 +127,7 @@ class AdminPanelManager:
129
 
130
  self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
131
 
132
- return True, f"✅ Assigned {username} to {project_slug} as {role}"
133
 
134
  def invite_user_to_project(
135
  self,
@@ -208,7 +206,7 @@ class AdminPanelManager:
208
  )
209
  if email_ok:
210
  return True, f"{message} | {email_status}"
211
- return True, f"{message} | ⚠️ {email_status}"
212
 
213
  return True, message
214
 
@@ -256,7 +254,7 @@ class AdminPanelManager:
256
  revoked_invites = self.auth_service.revoke_all_invites_for_project(slug)
257
  return (
258
  True,
259
- f"✅ Project '{slug}' deleted (removed assignments: {removed_assignments}, revoked invites: {revoked_invites})",
260
  )
261
 
262
  def remove_user_from_project(self, actor_username: str, username: str, project_slug: str) -> Tuple[bool, str]:
@@ -290,7 +288,7 @@ class AdminPanelManager:
290
  return False, f"User '{username}' is not assigned to project '{project_slug}'"
291
 
292
  _ = self.auth_service.remove_user_project_role(username, project_slug)
293
- return True, f"✅ Removed {username} from {project_slug}"
294
 
295
  def toggleproject_active(self, project_slug: str, active: bool) -> Tuple[bool, str]:
296
  """Enable or disable a project.
@@ -307,145 +305,4 @@ class AdminPanelManager:
307
 
308
  self._projects[project_slug].active = active
309
  status = "activated" if active else "deactivated"
310
- return True, f"✅ Project {project_slug} {status}"
311
-
312
-
313
- def create_admin_panel(admin_manager: AdminPanelManager, current_session: Session) -> gr.Blocks:
314
- """Create Gradio admin panel UI.
315
-
316
- Args:
317
- admin_manager: AdminPanelManager instance
318
- current_session: Current user's session
319
-
320
- Returns:
321
- Gradio Blocks with admin panel tabs
322
- """
323
- if current_session.role != Role.admin:
324
- with gr.Blocks() as restricted:
325
- gr.Markdown("❌ **Access Denied**\n\nOnly administrators can access this panel.")
326
- return restricted
327
-
328
- with gr.Blocks(title="BirdNET Admin Panel") as admin_block:
329
- gr.Markdown("# Admin Panel")
330
- gr.Markdown(f"Logged in as: **{current_session.username}** (Admin)")
331
-
332
- with gr.Tabs():
333
- # Projects Tab
334
- with gr.Tab("Projects"):
335
- gr.Markdown("## Manage Projects")
336
-
337
- with gr.Row():
338
- with gr.Column(scale=2):
339
- project_slug_input = gr.Textbox(
340
- label="Project Slug",
341
- placeholder="e.g., kenya-2024",
342
- lines=1,
343
- )
344
- project_name_input = gr.Textbox(
345
- label="Project Name",
346
- placeholder="e.g., Kenya Survey 2024",
347
- lines=1,
348
- )
349
-
350
- with gr.Column(scale=1):
351
- repo_id_input = gr.Textbox(
352
- label="HF Dataset Repo ID",
353
- placeholder="e.g., org/dataset-name",
354
- lines=1,
355
- )
356
-
357
- project_message = gr.Markdown()
358
-
359
- # Projects list
360
- with gr.Row():
361
- refresh_projects_button = gr.Button("Refresh Projects List")
362
- projects_table = gr.Dataframe(
363
- value=admin_manager.list_projects(),
364
- headers=["project_slug", "name", "dataset_repo_id", "active"],
365
- interactive=False,
366
- )
367
-
368
- refresh_projects_button.click(
369
- fn=lambda: admin_manager.list_projects(),
370
- outputs=[projects_table],
371
- )
372
-
373
- # Users Tab
374
- with gr.Tab("Users"):
375
- gr.Markdown("## Manage User Access")
376
-
377
- with gr.Row():
378
- username_input = gr.Textbox(
379
- label="Username",
380
- placeholder="e.g., validator_001",
381
- lines=1,
382
- )
383
-
384
- project_select = gr.Dropdown(
385
- choices=[p["project_slug"] for p in admin_manager.list_projects()],
386
- label="Project",
387
- )
388
-
389
- role_select = gr.Dropdown(
390
- choices=["admin", "validator"],
391
- value="validator",
392
- label="Role",
393
- )
394
-
395
- user_message = gr.Markdown()
396
-
397
- assign_button = gr.Button("Assign User", variant="primary")
398
- remove_button = gr.Button("Remove User", variant="stop")
399
-
400
- def assign_user(username: str, project_slug: str, role: str) -> str:
401
- success, msg = admin_manager.assign_user_to_project(
402
- current_session.username,
403
- username,
404
- project_slug,
405
- role,
406
- )
407
- return msg
408
-
409
- def remove_user(username: str, project_slug: str) -> str:
410
- success, msg = admin_manager.remove_user_from_project(
411
- current_session.username,
412
- username,
413
- project_slug,
414
- )
415
- return msg
416
-
417
- assign_button.click(
418
- fn=assign_user,
419
- inputs=[username_input, project_select, role_select],
420
- outputs=[user_message],
421
- )
422
-
423
- remove_button.click(
424
- fn=remove_user,
425
- inputs=[username_input, project_select],
426
- outputs=[user_message],
427
- )
428
-
429
- # Users per project view
430
- with gr.Row():
431
- project_filter = gr.Dropdown(
432
- choices=[p["project_slug"] for p in admin_manager.list_projects()],
433
- label="View Users for Project",
434
- )
435
-
436
- users_table = gr.Dataframe(
437
- value=[],
438
- headers=["username", "role"],
439
- interactive=False,
440
- )
441
-
442
- def update_users_table(project_slug: str):
443
- return admin_manager.list_users_for_project(project_slug)
444
-
445
- project_filter.change(
446
- fn=update_users_table,
447
- inputs=[project_filter],
448
- outputs=[users_table],
449
- )
450
-
451
- return admin_block
 
1
+ """Management backend for projects, teams, and invitations."""
2
 
3
  from typing import List, Tuple
4
 
5
+ from src.auth.auth_service import AuthService
 
 
6
  from src.domain.models import Project, Role
7
  from src.services.invite_email_notifier import InviteEmailNotifier, InviteEmailPayload
8
 
 
127
 
128
  self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
129
 
130
+ return True, f"Assigned {username} to {project_slug} as {role}"
131
 
132
  def invite_user_to_project(
133
  self,
 
206
  )
207
  if email_ok:
208
  return True, f"{message} | {email_status}"
209
+ return True, f"{message} | {email_status}"
210
 
211
  return True, message
212
 
 
254
  revoked_invites = self.auth_service.revoke_all_invites_for_project(slug)
255
  return (
256
  True,
257
+ f"Project '{slug}' deleted (removed assignments: {removed_assignments}, revoked invites: {revoked_invites})",
258
  )
259
 
260
  def remove_user_from_project(self, actor_username: str, username: str, project_slug: str) -> Tuple[bool, str]:
 
288
  return False, f"User '{username}' is not assigned to project '{project_slug}'"
289
 
290
  _ = self.auth_service.remove_user_project_role(username, project_slug)
291
+ return True, f"Removed {username} from {project_slug}"
292
 
293
  def toggleproject_active(self, project_slug: str, active: bool) -> Tuple[bool, str]:
294
  """Enable or disable a project.
 
305
 
306
  self._projects[project_slug].active = active
307
  status = "activated" if active else "deactivated"
308
+ return True, f"Project {project_slug} {status}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/ui/app_factory.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/ui/components.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from html import escape
2
+
3
+
4
+ def section_header_html(kicker: str, title: str, subtitle: str, *, class_name: str = "bn-panel") -> str:
5
+ return (
6
+ f"<div class='{class_name}' style='margin-bottom:12px;'>"
7
+ f"<div class='bn-brand-kicker'>{escape(kicker)}</div>"
8
+ f"<div class='bn-section-title'>{escape(title)}</div>"
9
+ f"<div class='bn-compact-note'>{escape(subtitle)}</div>"
10
+ "</div>"
11
+ )
12
+
13
+
14
+ def status_pill_html(label: str, value: str, tone: str = "") -> str:
15
+ tone_class = f" bn-pill-{tone}" if tone else ""
16
+ return f"<span class='bn-pill{tone_class}'><strong>{escape(label)}:</strong>&nbsp;{escape(value)}</span>"
17
+
18
+
19
+ def project_overview_html(project_rows: list[dict], authorized_projects: list[str], selected_project: str | None = None) -> str:
20
+ if not authorized_projects:
21
+ return (
22
+ "<div class='bn-empty-state'>"
23
+ "<div class='bn-empty-title'>No projects assigned</div>"
24
+ "<div class='bn-compact-note'>Create a project in Admin or accept a pending invite to start validating.</div>"
25
+ "</div>"
26
+ )
27
+
28
+ def normalize_project_row(row: object) -> dict:
29
+ if isinstance(row, dict):
30
+ return row
31
+ if isinstance(row, (list, tuple)):
32
+ return {
33
+ "project_slug": row[0] if len(row) > 0 else "",
34
+ "name": row[1] if len(row) > 1 else "",
35
+ "dataset_repo_id": row[2] if len(row) > 2 else "",
36
+ "visibility": row[3] if len(row) > 3 else "collaborative",
37
+ "owner_username": row[4] if len(row) > 4 else "",
38
+ "dataset_token_set": str(row[5]).strip().lower() == "yes" if len(row) > 5 else False,
39
+ "active": str(row[6]).strip().lower() == "yes" if len(row) > 6 else True,
40
+ }
41
+ return {}
42
+
43
+ normalized_project_rows = [normalize_project_row(row) for row in project_rows]
44
+ rows_by_slug = {str(row.get("project_slug", "")): row for row in normalized_project_rows}
45
+ cards: list[str] = []
46
+ for slug in authorized_projects:
47
+ row = rows_by_slug.get(slug, {})
48
+ name = str(row.get("name") or slug)
49
+ dataset_repo = str(row.get("dataset_repo_id") or "dataset not set")
50
+ visibility = str(row.get("visibility") or "collaborative")
51
+ active = "active" if bool(row.get("active", True)) else "inactive"
52
+ token = "token set" if bool(row.get("dataset_token_set", False)) else "public/default token"
53
+ selected_class = " bn-project-card-selected" if selected_project == slug else ""
54
+ cards.append(
55
+ f"<div class='bn-project-card{selected_class}'>"
56
+ f"<div class='bn-project-name'>{escape(name)}</div>"
57
+ f"<div class='bn-project-slug'>{escape(slug)}</div>"
58
+ f"<div class='bn-compact-note'>{escape(dataset_repo)}</div>"
59
+ "<div class='bn-card-pills'>"
60
+ f"{status_pill_html('visibility', visibility)}"
61
+ f"{status_pill_html('status', active, 'ok' if active == 'active' else 'warn')}"
62
+ f"{status_pill_html('access', token)}"
63
+ "</div>"
64
+ "</div>"
65
+ )
66
+
67
+ return "<div class='bn-project-grid'>" + "".join(cards) + "</div>"
68
+
69
+
70
+ def compact_metric_grid(items: list[tuple[str, str, str, str]]) -> str:
71
+ cards = []
72
+ for label, value, hint, tone in items:
73
+ tone_class = f" bn-kpi-{tone}" if tone else ""
74
+ cards.append(
75
+ f"<div class='bn-kpi-card{tone_class}'>"
76
+ f"<div class='bn-kpi-label'>{escape(label)}</div>"
77
+ f"<div class='bn-kpi-value'>{escape(value)}</div>"
78
+ f"<div class='bn-kpi-hint'>{escape(hint)}</div>"
79
+ "</div>"
80
+ )
81
+ return "<div class='bn-kpi-grid'>" + "".join(cards) + "</div>"
82
+
83
+
84
+ def admin_overview_html(
85
+ *,
86
+ username: str | None,
87
+ total_projects: int,
88
+ admin_projects: int,
89
+ validator_projects: int,
90
+ pending_invites: int,
91
+ ) -> str:
92
+ if not username:
93
+ return (
94
+ "<div class='bn-empty-state'>"
95
+ "<div class='bn-empty-title'>Admin workspace locked</div>"
96
+ "<div class='bn-compact-note'>Login to manage projects, teams, invites, and dataset tokens.</div>"
97
+ "</div>"
98
+ )
99
+
100
+ return compact_metric_grid(
101
+ [
102
+ ("User", username, "active session", "info"),
103
+ ("Projects", str(total_projects), "registered in app", ""),
104
+ ("Admin scope", str(admin_projects), "projects you manage", "positive" if admin_projects else "warning"),
105
+ ("Validator scope", str(validator_projects), f"{pending_invites} pending invites", "info"),
106
+ ]
107
+ )
108
+
109
+
110
+ def project_context_html(project_row: list[object] | None, role: str | None = None) -> str:
111
+ if not project_row:
112
+ return (
113
+ "<div class='bn-empty-state'>"
114
+ "<div class='bn-empty-title'>No project selected</div>"
115
+ "<div class='bn-compact-note'>Choose an authorized project before opening the validation workbench.</div>"
116
+ "</div>"
117
+ )
118
+
119
+ def cell(index: int, default: str = "") -> str:
120
+ if len(project_row) <= index:
121
+ return default
122
+ return str(project_row[index] or "").strip() or default
123
+
124
+ slug = cell(0, "unknown-project")
125
+ name = cell(1, slug)
126
+ dataset_repo = cell(2, "dataset not set")
127
+ visibility = cell(3, "collaborative")
128
+ owner = cell(4, "unknown")
129
+ token = "token set" if cell(5, "no").lower() == "yes" else "public/default token"
130
+ active = cell(6, "yes")
131
+ role_label = (role or "unknown").upper()
132
+ role_tone = "ok" if role_label == "ADMIN" else "info"
133
+ active_tone = "ok" if active.lower() == "yes" else "warn"
134
+
135
+ return (
136
+ "<div class='bn-project-context'>"
137
+ "<div>"
138
+ "<div class='bn-brand-kicker'>Selected project</div>"
139
+ f"<div class='bn-project-context-title'>{escape(name)}</div>"
140
+ f"<div class='bn-project-context-subtitle'>{escape(slug)} · {escape(dataset_repo)}</div>"
141
+ "</div>"
142
+ "<div class='bn-card-pills'>"
143
+ f"{status_pill_html('role', role_label, role_tone)}"
144
+ f"{status_pill_html('visibility', visibility)}"
145
+ f"{status_pill_html('owner', owner)}"
146
+ f"{status_pill_html('token', token)}"
147
+ f"{status_pill_html('active', active, active_tone)}"
148
+ "</div>"
149
+ "</div>"
150
+ )
151
+
152
+
153
+ def invite_panel_html(invite_count: int) -> str:
154
+ if invite_count <= 0:
155
+ return inline_hint_html("No pending invites for this user.", "info")
156
+ return (
157
+ "<div class='bn-invite-callout'>"
158
+ f"<div class='bn-empty-title'>{invite_count} pending invite{'s' if invite_count != 1 else ''}</div>"
159
+ "<div class='bn-compact-note'>Review and accept only the project access you expect to use.</div>"
160
+ "</div>"
161
+ )
162
+
163
+
164
+ def coverage_bars_html(rows: list[list[object]], *, limit: int = 12) -> str:
165
+ if not rows:
166
+ return (
167
+ "<div class='bn-coverage-panel'>"
168
+ "<div class='bn-queue-preview-head'><span>Coverage by species</span><span>0 species</span></div>"
169
+ "<div class='bn-empty-mini'>Refresh the dashboard after selecting a project.</div>"
170
+ "</div>"
171
+ )
172
+
173
+ cards: list[str] = []
174
+ for row in rows[:limit]:
175
+ species = str(row[0] if len(row) > 0 else "Unknown species")
176
+ total = int(row[1] or 0) if len(row) > 1 else 0
177
+ validated = int(row[2] or 0) if len(row) > 2 else 0
178
+ remaining = int(row[3] or 0) if len(row) > 3 else max(0, total - validated)
179
+ try:
180
+ pct = float(row[4] if len(row) > 4 else 0.0)
181
+ except Exception:
182
+ pct = 0.0
183
+ pct = max(0.0, min(100.0, pct))
184
+ cards.append(
185
+ "<div class='bn-coverage-row'>"
186
+ "<div class='bn-coverage-row-head'>"
187
+ f"<span>{escape(species)}</span>"
188
+ f"<strong>{pct:.1f}%</strong>"
189
+ "</div>"
190
+ "<div class='bn-coverage-track'>"
191
+ f"<div class='bn-coverage-fill' style='width:{pct:.1f}%;'></div>"
192
+ "</div>"
193
+ f"<div class='bn-coverage-meta'>{validated} validated · {remaining} remaining · {total} total</div>"
194
+ "</div>"
195
+ )
196
+
197
+ remaining_species = max(0, len(rows) - limit)
198
+ footer = f"<div class='bn-queue-footnote'>+{remaining_species} species in the table below</div>" if remaining_species else ""
199
+ return (
200
+ "<div class='bn-coverage-panel'>"
201
+ "<div class='bn-queue-preview-head'>"
202
+ f"<span>Coverage by species</span><span>{len(rows)} species</span>"
203
+ "</div>"
204
+ + "".join(cards)
205
+ + footer
206
+ + "</div>"
207
+ )
208
+
209
+
210
+ def settings_health_html(items: list[tuple[str, str, str]]) -> str:
211
+ cards = []
212
+ for label, value, tone in items:
213
+ tone_class = f" bn-pill-{tone}" if tone else ""
214
+ cards.append(
215
+ "<div class='bn-health-row'>"
216
+ f"<div><div class='bn-health-label'>{escape(label)}</div><div class='bn-health-value'>{escape(value)}</div></div>"
217
+ f"<span class='bn-pill{tone_class}'>{escape(tone or 'info')}</span>"
218
+ "</div>"
219
+ )
220
+ return "<div class='bn-health-panel'>" + "".join(cards) + "</div>"
221
+
222
+
223
+ def inline_hint_html(text: str, tone: str = "info") -> str:
224
+ tone_class = f" bn-hint-{tone}" if tone else ""
225
+ return f"<div class='bn-inline-hint{tone_class}'>{escape(text)}</div>"
226
+
227
+
228
+ def selected_segment_html(row: list[object] | None, selected_index: int | None = None, total_rows: int | None = None) -> str:
229
+ if not row:
230
+ return (
231
+ "<div class='bn-selected-card'>"
232
+ "<div class='bn-brand-kicker'>Selected segment</div>"
233
+ "<div class='bn-empty-title'>No segment loaded</div>"
234
+ "<div class='bn-compact-note'>Choose a species and apply filters to load the validation queue.</div>"
235
+ "</div>"
236
+ )
237
+
238
+ def cell(index: int, default: str = "") -> str:
239
+ if len(row) <= index:
240
+ return default
241
+ value = str(row[index] or "").strip()
242
+ if index == 2 and value.startswith("▶ "):
243
+ value = value[2:].strip()
244
+ return value or default
245
+
246
+ detection_key = cell(0, "unknown")
247
+ audio_id = cell(1, "unknown audio")
248
+ species = cell(2, "Unknown species")
249
+ confidence = cell(3, "0")
250
+ start_time = cell(4, "0")
251
+ end_time = cell(5, "0")
252
+ status = cell(6, "pending")
253
+ version = cell(7, "0")
254
+ conflict = cell(8, "")
255
+ position = ""
256
+ if selected_index is not None and total_rows:
257
+ position = f"{int(selected_index) + 1}/{int(total_rows)}"
258
+
259
+ conflict_badge = "<span class='bn-pill bn-pill-warn'>conflict</span>" if conflict else ""
260
+ return (
261
+ "<div class='bn-selected-card'>"
262
+ "<div class='bn-selected-topline'>"
263
+ "<div>"
264
+ "<div class='bn-brand-kicker'>Selected segment</div>"
265
+ f"<div class='bn-selected-species'>{escape(species)}</div>"
266
+ "</div>"
267
+ f"<span class='bn-pill bn-pill-info'>{escape(position or 'queue')}</span>"
268
+ "</div>"
269
+ "<div class='bn-selected-meta'>"
270
+ f"<span><strong>Confidence</strong>{escape(confidence)}</span>"
271
+ f"<span><strong>Time</strong>{escape(start_time)}-{escape(end_time)}s</span>"
272
+ f"<span><strong>Status</strong>{escape(status)}</span>"
273
+ f"<span><strong>Version</strong>{escape(version)}</span>"
274
+ "</div>"
275
+ f"<div class='bn-selected-audio'>{escape(audio_id)}</div>"
276
+ "<div class='bn-card-pills'>"
277
+ f"<span class='bn-pill'>key: {escape(detection_key)}</span>"
278
+ f"{conflict_badge}"
279
+ "</div>"
280
+ "</div>"
281
+ )
282
+
283
+
284
+ def validation_queue_html(rows: object, selected_index: int | None = None, *, limit: int = 8) -> str:
285
+ if hasattr(rows, "values"):
286
+ normalized_rows = [list(item) for item in rows.values.tolist()]
287
+ else:
288
+ normalized_rows = [list(item) for item in rows] if rows else []
289
+
290
+ if not normalized_rows:
291
+ return (
292
+ "<div class='bn-queue-preview'>"
293
+ "<div class='bn-queue-preview-head'>"
294
+ "<span>Queue preview</span><span>0 loaded</span>"
295
+ "</div>"
296
+ "<div class='bn-empty-mini'>Select a species and apply filters to load segments.</div>"
297
+ "</div>"
298
+ )
299
+
300
+ safe_selected = max(0, min(int(selected_index or 0), len(normalized_rows) - 1))
301
+ cards: list[str] = []
302
+ for idx, row in enumerate(normalized_rows[:limit]):
303
+ def cell(index: int, default: str = "") -> str:
304
+ if len(row) <= index:
305
+ return default
306
+ value = str(row[index] or "").strip()
307
+ if index == 2 and value.startswith("▶ "):
308
+ value = value[2:].strip()
309
+ return value or default
310
+
311
+ species = cell(2, "Unknown species")
312
+ confidence = cell(3, "0")
313
+ status = cell(6, "pending")
314
+ audio_id = cell(1, "unknown audio")
315
+ selected_class = " bn-queue-card-selected" if idx == safe_selected else ""
316
+ cards.append(
317
+ f"<div class='bn-queue-card{selected_class}'>"
318
+ f"<div class='bn-queue-card-index'>{idx + 1}</div>"
319
+ "<div class='bn-queue-card-main'>"
320
+ f"<div class='bn-queue-card-species'>{escape(species)}</div>"
321
+ f"<div class='bn-queue-card-audio'>{escape(audio_id)}</div>"
322
+ "</div>"
323
+ "<div class='bn-queue-card-meta'>"
324
+ f"<span>{escape(confidence)}</span>"
325
+ f"<span>{escape(status)}</span>"
326
+ "</div>"
327
+ "</div>"
328
+ )
329
+
330
+ remaining = max(0, len(normalized_rows) - limit)
331
+ remaining_text = f"+{remaining} more on this page" if remaining else "all loaded rows shown"
332
+ return (
333
+ "<div class='bn-queue-preview'>"
334
+ "<div class='bn-queue-preview-head'>"
335
+ f"<span>Queue preview</span><span>{safe_selected + 1}/{len(normalized_rows)}</span>"
336
+ "</div>"
337
+ + "".join(cards)
338
+ + f"<div class='bn-queue-footnote'>{escape(remaining_text)}</div>"
339
+ "</div>"
340
+ )
src/ui/login_page.py CHANGED
@@ -63,13 +63,13 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Textbox, gr.Textbox
63
  return session.session_id, message
64
 
65
  if not username or not username.strip():
66
- return "", "❌ Please enter a username or provide a Hugging Face token"
67
 
68
  username = username.strip()
69
  session = auth_service.login(username)
70
 
71
  if session is None:
72
- return "", f"❌ User '{username}' not found or inactive"
73
 
74
  admin_projects = 0
75
  validator_projects = 0
@@ -85,7 +85,7 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Textbox, gr.Textbox
85
  return (
86
  session.session_id,
87
  (
88
- f"✅ Welcome, {username}! "
89
  f"Admin in {admin_projects} project(s), validator in {validator_projects} project(s)."
90
  ),
91
  )
 
63
  return session.session_id, message
64
 
65
  if not username or not username.strip():
66
+ return "", "Please enter a username or provide a Hugging Face token"
67
 
68
  username = username.strip()
69
  session = auth_service.login(username)
70
 
71
  if session is None:
72
+ return "", f"User '{username}' not found or inactive"
73
 
74
  admin_projects = 0
75
  validator_projects = 0
 
85
  return (
86
  session.session_id,
87
  (
88
+ f"Welcome, {username}. "
89
  f"Admin in {admin_projects} project(s), validator in {validator_projects} project(s)."
90
  ),
91
  )
src/ui/theme.py ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APP_CSS = """
2
+ :root {
3
+ --bn-bg: #f5f7fb;
4
+ --bn-panel: #ffffff;
5
+ --bn-panel-soft: #f9fafb;
6
+ --bn-border: #d9e0ea;
7
+ --bn-border-strong: #c4cfdd;
8
+ --bn-text: #142033;
9
+ --bn-muted: #667085;
10
+ --bn-primary: #1f6f8b;
11
+ --bn-primary-dark: #14526a;
12
+ --bn-positive: #0f7a4f;
13
+ --bn-negative: #b42318;
14
+ --bn-warning: #b54708;
15
+ --bn-info: #255db3;
16
+ --bn-shadow: 0 8px 24px rgba(20, 32, 51, 0.07);
17
+ }
18
+
19
+ body,
20
+ .gradio-container {
21
+ background: var(--bn-bg) !important;
22
+ color: var(--bn-text) !important;
23
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif !important;
24
+ }
25
+
26
+ .gradio-container {
27
+ max-width: 1540px !important;
28
+ }
29
+
30
+ .bn-shell {
31
+ padding-top: 8px;
32
+ }
33
+
34
+ .bn-app-header {
35
+ display: flex;
36
+ justify-content: space-between;
37
+ gap: 20px;
38
+ align-items: center;
39
+ padding: 18px 22px;
40
+ margin: 0 0 16px 0;
41
+ background: linear-gradient(135deg, #ffffff 0%, #eef6f8 100%);
42
+ border: 1px solid var(--bn-border);
43
+ border-radius: 8px;
44
+ box-shadow: var(--bn-shadow);
45
+ }
46
+
47
+ .bn-brand-kicker {
48
+ color: var(--bn-primary-dark);
49
+ font-size: 12px;
50
+ font-weight: 700;
51
+ letter-spacing: 0;
52
+ text-transform: uppercase;
53
+ }
54
+
55
+ .bn-brand-title {
56
+ margin-top: 2px;
57
+ font-size: 26px;
58
+ line-height: 1.15;
59
+ font-weight: 780;
60
+ color: var(--bn-text);
61
+ }
62
+
63
+ .bn-section-title {
64
+ margin-top: 2px;
65
+ font-size: 22px;
66
+ line-height: 1.18;
67
+ font-weight: 780;
68
+ color: var(--bn-text);
69
+ }
70
+
71
+ .bn-brand-subtitle {
72
+ margin-top: 4px;
73
+ color: var(--bn-muted);
74
+ font-size: 14px;
75
+ }
76
+
77
+ .bn-header-status {
78
+ display: flex;
79
+ flex-wrap: wrap;
80
+ justify-content: flex-end;
81
+ gap: 8px;
82
+ }
83
+
84
+ .bn-pill {
85
+ display: inline-flex;
86
+ align-items: center;
87
+ min-height: 30px;
88
+ padding: 6px 10px;
89
+ border-radius: 999px;
90
+ border: 1px solid var(--bn-border);
91
+ background: rgba(255, 255, 255, 0.82);
92
+ color: var(--bn-text);
93
+ font-size: 12px;
94
+ font-weight: 650;
95
+ white-space: nowrap;
96
+ }
97
+
98
+ .bn-pill-ok {
99
+ border-color: #b7dfc9;
100
+ background: #ecfdf3;
101
+ color: var(--bn-positive);
102
+ }
103
+
104
+ .bn-pill-info {
105
+ border-color: #bfdbfe;
106
+ background: #eff6ff;
107
+ color: var(--bn-info);
108
+ }
109
+
110
+ .bn-pill-warn {
111
+ border-color: #fed7aa;
112
+ background: #fff7ed;
113
+ color: var(--bn-warning);
114
+ }
115
+
116
+ .bn-tabs .tab-nav,
117
+ .tabs .tab-nav {
118
+ gap: 4px !important;
119
+ border-bottom: 1px solid var(--bn-border) !important;
120
+ }
121
+
122
+ .bn-tabs button,
123
+ .tabs button {
124
+ border-radius: 6px 6px 0 0 !important;
125
+ font-weight: 650 !important;
126
+ }
127
+
128
+ .bn-panel {
129
+ background: var(--bn-panel);
130
+ border: 1px solid var(--bn-border);
131
+ border-radius: 8px;
132
+ box-shadow: var(--bn-shadow);
133
+ padding: 14px;
134
+ }
135
+
136
+ .bn-panel-soft {
137
+ background: var(--bn-panel-soft);
138
+ border: 1px solid var(--bn-border);
139
+ border-radius: 8px;
140
+ padding: 12px;
141
+ }
142
+
143
+ .bn-empty-state {
144
+ padding: 18px;
145
+ border: 1px dashed var(--bn-border-strong);
146
+ background: #ffffff;
147
+ border-radius: 8px;
148
+ }
149
+
150
+ .bn-empty-title {
151
+ color: var(--bn-text);
152
+ font-size: 16px;
153
+ font-weight: 760;
154
+ margin-bottom: 4px;
155
+ }
156
+
157
+ .bn-project-grid {
158
+ display: grid;
159
+ grid-template-columns: repeat(3, minmax(180px, 1fr));
160
+ gap: 10px;
161
+ margin: 8px 0 14px 0;
162
+ }
163
+
164
+ .bn-project-card {
165
+ min-height: 132px;
166
+ padding: 14px;
167
+ border: 1px solid var(--bn-border);
168
+ background: #ffffff;
169
+ border-radius: 8px;
170
+ box-shadow: 0 4px 14px rgba(20, 32, 51, 0.05);
171
+ }
172
+
173
+ .bn-project-card-selected {
174
+ border-color: var(--bn-primary);
175
+ box-shadow: 0 0 0 2px rgba(31, 111, 139, 0.12);
176
+ }
177
+
178
+ .bn-project-name {
179
+ color: var(--bn-text);
180
+ font-size: 16px;
181
+ font-weight: 780;
182
+ }
183
+
184
+ .bn-project-slug {
185
+ margin: 2px 0 8px 0;
186
+ color: var(--bn-primary-dark);
187
+ font-size: 12px;
188
+ font-weight: 720;
189
+ }
190
+
191
+ .bn-card-pills {
192
+ display: flex;
193
+ flex-wrap: wrap;
194
+ gap: 6px;
195
+ margin-top: 10px;
196
+ }
197
+
198
+ .bn-project-context {
199
+ display: flex;
200
+ justify-content: space-between;
201
+ gap: 16px;
202
+ align-items: flex-start;
203
+ padding: 14px;
204
+ margin: 8px 0 12px 0;
205
+ border: 1px solid var(--bn-border);
206
+ background: #ffffff;
207
+ border-radius: 8px;
208
+ box-shadow: 0 4px 14px rgba(20, 32, 51, 0.05);
209
+ }
210
+
211
+ .bn-project-context-title {
212
+ margin-top: 2px;
213
+ color: var(--bn-text);
214
+ font-size: 20px;
215
+ line-height: 1.18;
216
+ font-weight: 800;
217
+ }
218
+
219
+ .bn-project-context-subtitle {
220
+ margin-top: 4px;
221
+ color: var(--bn-muted);
222
+ font-size: 13px;
223
+ word-break: break-word;
224
+ }
225
+
226
+ .bn-invite-callout {
227
+ padding: 12px 14px;
228
+ margin: 8px 0 12px 0;
229
+ border: 1px solid #bfdbfe;
230
+ background: #eff6ff;
231
+ border-radius: 8px;
232
+ }
233
+
234
+ .bn-control-band {
235
+ padding: 12px;
236
+ border: 1px solid var(--bn-border);
237
+ background: #fbfcfe;
238
+ border-radius: 8px;
239
+ }
240
+
241
+ .bn-spacer {
242
+ height: 10px;
243
+ }
244
+
245
+ .bn-inline-hint {
246
+ padding: 9px 11px;
247
+ border: 1px solid var(--bn-border);
248
+ background: #f8fafc;
249
+ border-radius: 8px;
250
+ color: var(--bn-muted);
251
+ font-size: 12px;
252
+ line-height: 1.4;
253
+ }
254
+
255
+ .bn-hint-info {
256
+ border-color: #bfdbfe;
257
+ background: #eff6ff;
258
+ color: #1e3a8a;
259
+ }
260
+
261
+ .bn-hint-warn {
262
+ border-color: #fed7aa;
263
+ background: #fff7ed;
264
+ color: #9a3412;
265
+ }
266
+
267
+ .bn-hint-danger {
268
+ border-color: #f3b6b2;
269
+ background: #fff6f5;
270
+ color: var(--bn-negative);
271
+ }
272
+
273
+ .bn-filter-panel {
274
+ padding: 12px;
275
+ border: 1px solid var(--bn-border);
276
+ background: #fbfcfe;
277
+ border-radius: 8px;
278
+ margin: 8px 0 12px 0;
279
+ }
280
+
281
+ .bn-filter-panel .form {
282
+ gap: 8px !important;
283
+ }
284
+
285
+ .bn-danger-zone {
286
+ border-color: #f3b6b2 !important;
287
+ background: #fffafa !important;
288
+ }
289
+
290
+ .bn-selected-card {
291
+ padding: 14px;
292
+ border: 1px solid var(--bn-border);
293
+ background: linear-gradient(180deg, #ffffff 0%, #f8fbfc 100%);
294
+ border-radius: 8px;
295
+ margin: 0 0 12px 0;
296
+ }
297
+
298
+ .bn-selected-topline {
299
+ display: flex;
300
+ justify-content: space-between;
301
+ gap: 12px;
302
+ align-items: flex-start;
303
+ }
304
+
305
+ .bn-selected-species {
306
+ margin-top: 2px;
307
+ color: var(--bn-text);
308
+ font-size: 21px;
309
+ line-height: 1.15;
310
+ font-weight: 820;
311
+ }
312
+
313
+ .bn-selected-meta {
314
+ display: grid;
315
+ grid-template-columns: repeat(4, minmax(90px, 1fr));
316
+ gap: 8px;
317
+ margin-top: 12px;
318
+ }
319
+
320
+ .bn-selected-meta span {
321
+ padding: 8px 10px;
322
+ border: 1px solid var(--bn-border);
323
+ background: #ffffff;
324
+ border-radius: 7px;
325
+ color: var(--bn-text);
326
+ font-size: 13px;
327
+ font-weight: 720;
328
+ }
329
+
330
+ .bn-selected-meta strong {
331
+ display: block;
332
+ color: var(--bn-muted);
333
+ font-size: 11px;
334
+ font-weight: 720;
335
+ margin-bottom: 2px;
336
+ }
337
+
338
+ .bn-selected-audio {
339
+ margin-top: 10px;
340
+ color: var(--bn-muted);
341
+ font-size: 12px;
342
+ word-break: break-word;
343
+ }
344
+
345
+ .bn-queue-preview {
346
+ margin-top: 12px;
347
+ padding: 12px;
348
+ border: 1px solid var(--bn-border);
349
+ background: #fbfcfe;
350
+ border-radius: 8px;
351
+ }
352
+
353
+ .bn-queue-preview-head {
354
+ display: flex;
355
+ justify-content: space-between;
356
+ gap: 12px;
357
+ margin-bottom: 8px;
358
+ color: var(--bn-muted);
359
+ font-size: 12px;
360
+ font-weight: 760;
361
+ text-transform: uppercase;
362
+ }
363
+
364
+ .bn-queue-card {
365
+ display: grid;
366
+ grid-template-columns: 30px minmax(0, 1fr) auto;
367
+ gap: 10px;
368
+ align-items: center;
369
+ padding: 9px 10px;
370
+ border: 1px solid transparent;
371
+ border-radius: 7px;
372
+ }
373
+
374
+ .bn-queue-card + .bn-queue-card {
375
+ margin-top: 4px;
376
+ }
377
+
378
+ .bn-queue-card-selected {
379
+ border-color: var(--bn-primary);
380
+ background: #eef8fb;
381
+ }
382
+
383
+ .bn-queue-card-index {
384
+ width: 28px;
385
+ height: 28px;
386
+ display: inline-flex;
387
+ align-items: center;
388
+ justify-content: center;
389
+ border-radius: 999px;
390
+ background: #ffffff;
391
+ border: 1px solid var(--bn-border);
392
+ color: var(--bn-primary-dark);
393
+ font-size: 12px;
394
+ font-weight: 800;
395
+ }
396
+
397
+ .bn-queue-card-main {
398
+ min-width: 0;
399
+ }
400
+
401
+ .bn-queue-card-species {
402
+ overflow: hidden;
403
+ text-overflow: ellipsis;
404
+ white-space: nowrap;
405
+ color: var(--bn-text);
406
+ font-size: 13px;
407
+ font-weight: 760;
408
+ }
409
+
410
+ .bn-queue-card-audio {
411
+ overflow: hidden;
412
+ text-overflow: ellipsis;
413
+ white-space: nowrap;
414
+ color: var(--bn-muted);
415
+ font-size: 11px;
416
+ }
417
+
418
+ .bn-queue-card-meta {
419
+ display: flex;
420
+ gap: 6px;
421
+ flex-wrap: wrap;
422
+ justify-content: flex-end;
423
+ }
424
+
425
+ .bn-queue-card-meta span {
426
+ padding: 4px 7px;
427
+ border: 1px solid var(--bn-border);
428
+ background: #ffffff;
429
+ border-radius: 999px;
430
+ color: var(--bn-muted);
431
+ font-size: 11px;
432
+ font-weight: 720;
433
+ }
434
+
435
+ .bn-queue-footnote,
436
+ .bn-empty-mini {
437
+ margin-top: 8px;
438
+ color: var(--bn-muted);
439
+ font-size: 12px;
440
+ }
441
+
442
+ .bn-coverage-panel {
443
+ padding: 12px;
444
+ margin: 8px 0 14px 0;
445
+ border: 1px solid var(--bn-border);
446
+ background: #ffffff;
447
+ border-radius: 8px;
448
+ box-shadow: 0 4px 14px rgba(20, 32, 51, 0.04);
449
+ }
450
+
451
+ .bn-coverage-row {
452
+ padding: 9px 0;
453
+ }
454
+
455
+ .bn-coverage-row + .bn-coverage-row {
456
+ border-top: 1px solid #eef2f6;
457
+ }
458
+
459
+ .bn-coverage-row-head {
460
+ display: flex;
461
+ justify-content: space-between;
462
+ gap: 12px;
463
+ color: var(--bn-text);
464
+ font-size: 13px;
465
+ font-weight: 760;
466
+ }
467
+
468
+ .bn-coverage-row-head span {
469
+ overflow: hidden;
470
+ text-overflow: ellipsis;
471
+ white-space: nowrap;
472
+ }
473
+
474
+ .bn-coverage-row-head strong {
475
+ color: var(--bn-primary-dark);
476
+ font-size: 12px;
477
+ }
478
+
479
+ .bn-coverage-track {
480
+ height: 8px;
481
+ margin-top: 7px;
482
+ overflow: hidden;
483
+ background: #edf2f7;
484
+ border-radius: 999px;
485
+ }
486
+
487
+ .bn-coverage-fill {
488
+ height: 100%;
489
+ background: linear-gradient(90deg, var(--bn-primary) 0%, var(--bn-positive) 100%);
490
+ border-radius: 999px;
491
+ }
492
+
493
+ .bn-coverage-meta {
494
+ margin-top: 5px;
495
+ color: var(--bn-muted);
496
+ font-size: 11px;
497
+ }
498
+
499
+ .bn-health-panel {
500
+ display: grid;
501
+ grid-template-columns: repeat(2, minmax(220px, 1fr));
502
+ gap: 10px;
503
+ margin: 8px 0 14px 0;
504
+ }
505
+
506
+ .bn-health-row {
507
+ display: flex;
508
+ justify-content: space-between;
509
+ gap: 12px;
510
+ align-items: center;
511
+ padding: 12px 14px;
512
+ border: 1px solid var(--bn-border);
513
+ background: #ffffff;
514
+ border-radius: 8px;
515
+ }
516
+
517
+ .bn-health-label {
518
+ color: var(--bn-muted);
519
+ font-size: 12px;
520
+ font-weight: 720;
521
+ }
522
+
523
+ .bn-health-value {
524
+ margin-top: 2px;
525
+ color: var(--bn-text);
526
+ font-size: 14px;
527
+ font-weight: 720;
528
+ }
529
+
530
+ .bn-validation-grid {
531
+ align-items: stretch;
532
+ }
533
+
534
+ .bn-media-panel,
535
+ .bn-sidebar-panel,
536
+ .bn-report-panel,
537
+ .bn-admin-panel {
538
+ background: var(--bn-panel);
539
+ border: 1px solid var(--bn-border);
540
+ border-radius: 8px;
541
+ box-shadow: var(--bn-shadow);
542
+ padding: 14px;
543
+ }
544
+
545
+ .bn-media-panel .gradio-image,
546
+ .bn-media-panel .gradio-audio {
547
+ border-radius: 8px !important;
548
+ }
549
+
550
+ .bn-media-panel [data-testid="image"],
551
+ .bn-media-panel [data-testid="audio"] {
552
+ max-width: 100%;
553
+ }
554
+
555
+ .bn-action-row button {
556
+ min-height: 46px !important;
557
+ border-radius: 7px !important;
558
+ font-weight: 760 !important;
559
+ }
560
+
561
+ .bn-action-row button:nth-child(1) {
562
+ background: var(--bn-positive) !important;
563
+ border-color: var(--bn-positive) !important;
564
+ }
565
+
566
+ .bn-action-row button:nth-child(2) {
567
+ background: #fff1f0 !important;
568
+ border-color: #f3b6b2 !important;
569
+ color: var(--bn-negative) !important;
570
+ }
571
+
572
+ .bn-action-row button:nth-child(3) {
573
+ background: #fff7ed !important;
574
+ border-color: #fed7aa !important;
575
+ color: var(--bn-warning) !important;
576
+ }
577
+
578
+ .bn-action-row button:nth-child(4) {
579
+ background: #eff6ff !important;
580
+ border-color: #bfdbfe !important;
581
+ color: var(--bn-info) !important;
582
+ }
583
+
584
+ .bn-status-strip {
585
+ padding: 10px 12px;
586
+ border-radius: 8px;
587
+ border: 1px solid var(--bn-border);
588
+ background: #f8fafc;
589
+ color: var(--bn-text);
590
+ }
591
+
592
+ .bn-kpi-grid {
593
+ display: grid;
594
+ grid-template-columns: repeat(4, minmax(130px, 1fr));
595
+ gap: 10px;
596
+ margin: 6px 0 14px 0;
597
+ }
598
+
599
+ .bn-kpi-card {
600
+ min-height: 82px;
601
+ padding: 12px 14px;
602
+ border-radius: 8px;
603
+ border: 1px solid var(--bn-border);
604
+ background: #ffffff;
605
+ }
606
+
607
+ .bn-kpi-label {
608
+ color: var(--bn-muted);
609
+ font-size: 12px;
610
+ font-weight: 700;
611
+ }
612
+
613
+ .bn-kpi-value {
614
+ margin-top: 4px;
615
+ color: var(--bn-text);
616
+ font-size: 26px;
617
+ line-height: 1.05;
618
+ font-weight: 800;
619
+ }
620
+
621
+ .bn-kpi-hint {
622
+ margin-top: 4px;
623
+ color: var(--bn-muted);
624
+ font-size: 12px;
625
+ }
626
+
627
+ .bn-kpi-positive {
628
+ border-color: #b7dfc9;
629
+ background: #f2fbf6;
630
+ }
631
+
632
+ .bn-kpi-negative {
633
+ border-color: #f3b6b2;
634
+ background: #fff6f5;
635
+ }
636
+
637
+ .bn-kpi-warning {
638
+ border-color: #fed7aa;
639
+ background: #fffaf4;
640
+ }
641
+
642
+ .bn-kpi-info {
643
+ border-color: #bfdbfe;
644
+ background: #f5f9ff;
645
+ }
646
+
647
+ .bn-compact-note {
648
+ color: var(--bn-muted);
649
+ font-size: 12px;
650
+ line-height: 1.4;
651
+ }
652
+
653
+ .bn-dataframe .wrap,
654
+ .bn-dataframe table {
655
+ font-size: 13px !important;
656
+ }
657
+
658
+ .bn-dataframe {
659
+ overflow-x: auto !important;
660
+ }
661
+
662
+ .bn-dataframe table {
663
+ min-width: 920px !important;
664
+ }
665
+
666
+ .bn-dataframe th {
667
+ background: #f1f5f9 !important;
668
+ color: #344054 !important;
669
+ font-weight: 750 !important;
670
+ }
671
+
672
+ textarea,
673
+ input,
674
+ select {
675
+ border-radius: 7px !important;
676
+ }
677
+
678
+ @media (max-width: 900px) {
679
+ .bn-app-header {
680
+ flex-direction: column;
681
+ align-items: flex-start;
682
+ }
683
+
684
+ .bn-header-status {
685
+ justify-content: flex-start;
686
+ }
687
+
688
+ .bn-kpi-grid {
689
+ grid-template-columns: repeat(2, minmax(0, 1fr));
690
+ }
691
+
692
+ .bn-project-grid {
693
+ grid-template-columns: repeat(2, minmax(0, 1fr));
694
+ }
695
+
696
+ .bn-project-context {
697
+ flex-direction: column;
698
+ }
699
+
700
+ .bn-health-panel {
701
+ grid-template-columns: 1fr;
702
+ }
703
+
704
+ .bn-selected-meta {
705
+ grid-template-columns: repeat(2, minmax(0, 1fr));
706
+ }
707
+
708
+ .bn-action-row {
709
+ display: grid !important;
710
+ grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
711
+ }
712
+
713
+ .bn-validation-grid {
714
+ gap: 12px !important;
715
+ }
716
+
717
+ .bn-media-panel,
718
+ .bn-sidebar-panel,
719
+ .bn-report-panel,
720
+ .bn-admin-panel,
721
+ .bn-panel {
722
+ padding: 12px;
723
+ }
724
+ }
725
+
726
+ @media (max-width: 560px) {
727
+ .bn-kpi-grid {
728
+ grid-template-columns: 1fr;
729
+ }
730
+
731
+ .bn-project-grid {
732
+ grid-template-columns: 1fr;
733
+ }
734
+
735
+ .bn-brand-title {
736
+ font-size: 22px;
737
+ }
738
+
739
+ .bn-app-header {
740
+ padding: 14px;
741
+ }
742
+
743
+ .bn-selected-card {
744
+ padding: 12px;
745
+ }
746
+
747
+ .bn-selected-topline {
748
+ flex-direction: column;
749
+ gap: 8px;
750
+ }
751
+
752
+ .bn-selected-species {
753
+ font-size: 18px;
754
+ }
755
+
756
+ .bn-selected-meta {
757
+ grid-template-columns: 1fr;
758
+ }
759
+
760
+ .bn-action-row {
761
+ grid-template-columns: 1fr !important;
762
+ }
763
+
764
+ .bn-action-row button {
765
+ width: 100% !important;
766
+ min-height: 48px !important;
767
+ }
768
+
769
+ .bn-queue-card {
770
+ grid-template-columns: 28px minmax(0, 1fr);
771
+ }
772
+
773
+ .bn-queue-card-meta {
774
+ grid-column: 2;
775
+ justify-content: flex-start;
776
+ }
777
+
778
+ .bn-dataframe table {
779
+ min-width: 780px !important;
780
+ }
781
+ }
782
+ """
783
+
784
+
785
+ def app_header_html(state_backend_message: str = "") -> str:
786
+ backend_text = "Supabase ready" if "Supabase state backend enabled" in state_backend_message else "Filesystem state"
787
+ backend_class = "bn-pill-ok" if "Supabase state backend enabled" in state_backend_message else "bn-pill-warn"
788
+ return f"""
789
+ <div class="bn-app-header">
790
+ <div>
791
+ <div class="bn-brand-kicker">BirdNET validation workspace</div>
792
+ <div class="bn-brand-title">BirdNET Validator</div>
793
+ <div class="bn-brand-subtitle">Collaborative review for audio segments, project teams, and validation progress.</div>
794
+ </div>
795
+ <div class="bn-header-status">
796
+ <span class="bn-pill {backend_class}">{backend_text}</span>
797
+ <span class="bn-pill">Hugging Face datasets</span>
798
+ <span class="bn-pill">Multi-validator workflow</span>
799
+ </div>
800
+ </div>
801
+ """
tests/unit/test_app_factory_audio_helpers.py CHANGED
@@ -27,6 +27,7 @@ from src.ui.app_factory import (
27
  _load_projects_from_file,
28
  _load_user_access_from_file,
29
  _bootstrap_auth_and_projects,
 
30
  )
31
  from src.auth.auth_service import AuthService
32
  from src.config.runtime_config import RuntimeConfig
@@ -847,6 +848,34 @@ def test_bootstrap_auth_and_projects_warns_when_not_configured(tmp_path: Path) -
847
  assert warning == ""
848
 
849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850
  def test_bootstrap_auth_and_projects_recovers_emergency_admin_when_missing(tmp_path: Path) -> None:
851
  projects_file = tmp_path / "projects.json"
852
  projects_file.write_text(
@@ -962,6 +991,104 @@ def test_load_dataset_detections_for_project_reads_jsonl(monkeypatch: pytest.Mon
962
  assert {item.scientific_name for item in detections} == {"Species A", "Species B"}
963
 
964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965
  def test_build_detection_repository_prefers_dataset_rows(monkeypatch: pytest.MonkeyPatch) -> None:
966
  from src.ui import app_factory as module
967
 
@@ -975,7 +1102,7 @@ def test_build_detection_repository_prefers_dataset_rows(monkeypatch: pytest.Mon
975
  monkeypatch.setattr(
976
  module,
977
  "_load_dataset_detections_for_project",
978
- lambda project_obj: (
979
  [
980
  Detection(
981
  detection_key="0000000000002222",
@@ -1175,3 +1302,86 @@ def test_load_dataset_detections_for_project_uses_files_parquet_index(
1175
  assert detections[0].confidence == 0.85
1176
  assert detections[0].start_time == 0.0
1177
  assert detections[0].end_time == 3.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  _load_projects_from_file,
28
  _load_user_access_from_file,
29
  _bootstrap_auth_and_projects,
30
+ _resolve_project_fetch_token,
31
  )
32
  from src.auth.auth_service import AuthService
33
  from src.config.runtime_config import RuntimeConfig
 
848
  assert warning == ""
849
 
850
 
851
+ def test_bootstrap_auth_and_projects_uses_demo_bootstrap_when_enabled(tmp_path: Path) -> None:
852
+ runtime_config = RuntimeConfig(
853
+ detection_seed_path=None,
854
+ validation_base_dir=str(tmp_path / "validations"),
855
+ bootstrap_base_dir=str(tmp_path / "bootstrap"),
856
+ page_size=25,
857
+ projects_file_path=None,
858
+ user_access_file_path=None,
859
+ invites_file_path=None,
860
+ invite_ttl_hours=72,
861
+ enable_demo_bootstrap=True,
862
+ invite_email_enabled=False,
863
+ invite_email_sender="",
864
+ invite_email_login_url="",
865
+ )
866
+ auth_service = AuthService()
867
+ from src.services.invite_email_notifier import EmailJSInviteEmailNotifier
868
+ notifier = EmailJSInviteEmailNotifier("", "", "", "", timeout_seconds=20)
869
+ admin_manager = AdminPanelManager(auth_service, invite_notifier=notifier)
870
+
871
+ warning = _bootstrap_auth_and_projects(auth_service, admin_manager, runtime_config)
872
+
873
+ assert warning == ""
874
+ assert auth_service.login("demo_user") is not None
875
+ assert auth_service.login("admin_user") is not None
876
+ assert any(p["project_slug"] == "demo-project" for p in admin_manager.list_projects())
877
+
878
+
879
  def test_bootstrap_auth_and_projects_recovers_emergency_admin_when_missing(tmp_path: Path) -> None:
880
  projects_file = tmp_path / "projects.json"
881
  projects_file.write_text(
 
991
  assert {item.scientific_name for item in detections} == {"Species A", "Species B"}
992
 
993
 
994
+ def test_load_dataset_detections_for_project_uses_fallback_hf_token(
995
+ monkeypatch: pytest.MonkeyPatch,
996
+ tmp_path: Path,
997
+ ) -> None:
998
+ from src.ui import app_factory as module
999
+
1000
+ observed_tokens: list[str | None] = []
1001
+
1002
+ class FakeHfApi:
1003
+ def __init__(self, token: str | None = None) -> None:
1004
+ observed_tokens.append(token)
1005
+
1006
+ def list_repo_files(self, repo_id: str, repo_type: str = "dataset") -> list[str]:
1007
+ _ = repo_id
1008
+ _ = repo_type
1009
+ return ["detections.jsonl"]
1010
+
1011
+ metadata_file = tmp_path / "detections.jsonl"
1012
+ metadata_file.write_text(
1013
+ json.dumps(
1014
+ {
1015
+ "audio_id": "audio_0001",
1016
+ "scientific_name": "Species A",
1017
+ "confidence": 0.92,
1018
+ "start_time": 1.0,
1019
+ "end_time": 2.0,
1020
+ }
1021
+ ),
1022
+ encoding="utf-8",
1023
+ )
1024
+
1025
+ def fake_download(**kwargs):
1026
+ observed_tokens.append(kwargs.get("token"))
1027
+ if kwargs.get("filename") != "detections.jsonl":
1028
+ raise FileNotFoundError(str(kwargs.get("filename")))
1029
+ return str(metadata_file)
1030
+
1031
+ monkeypatch.setattr(module, "HfApi", FakeHfApi)
1032
+ monkeypatch.setattr(module, "hf_hub_download", fake_download)
1033
+
1034
+ project = Project(
1035
+ project_slug="project-a",
1036
+ name="Project A",
1037
+ dataset_repo_id="org/project-a",
1038
+ active=True,
1039
+ )
1040
+ detections, warning = module._load_dataset_detections_for_project(project, hf_token="hf_session")
1041
+
1042
+ assert warning == ""
1043
+ assert len(detections) == 1
1044
+ assert observed_tokens[-2:] == ["hf_session", "hf_session"]
1045
+
1046
+
1047
+ def test_load_dataset_detections_for_project_reports_missing_token(monkeypatch: pytest.MonkeyPatch) -> None:
1048
+ from src.ui import app_factory as module
1049
+
1050
+ class FakeHfApi:
1051
+ def __init__(self, token: str | None = None) -> None:
1052
+ _ = token
1053
+
1054
+ def list_repo_files(self, repo_id: str, repo_type: str = "dataset") -> list[str]:
1055
+ _ = repo_id
1056
+ _ = repo_type
1057
+ raise RuntimeError("401 Client Error")
1058
+
1059
+ monkeypatch.setattr(module, "HfApi", FakeHfApi)
1060
+
1061
+ project = Project(
1062
+ project_slug="project-a",
1063
+ name="Project A",
1064
+ dataset_repo_id="org/private-project",
1065
+ active=True,
1066
+ )
1067
+ detections, warning = module._load_dataset_detections_for_project(project)
1068
+
1069
+ assert detections == []
1070
+ assert "No Hugging Face token is configured" in warning
1071
+ assert "Admin > Project token management" in warning
1072
+
1073
+
1074
+ def test_resolve_project_fetch_token_uses_session_then_project_then_env(monkeypatch: pytest.MonkeyPatch) -> None:
1075
+ project = Project(
1076
+ project_slug="project-a",
1077
+ name="Project A",
1078
+ dataset_repo_id="org/project-a",
1079
+ dataset_token="hf_project",
1080
+ active=True,
1081
+ )
1082
+
1083
+ assert _resolve_project_fetch_token(project, "hf_session") == "hf_session"
1084
+ assert _resolve_project_fetch_token(project, None) == "hf_project"
1085
+
1086
+ project.dataset_token = None
1087
+ monkeypatch.setenv("HF_TOKEN", "hf_env")
1088
+
1089
+ assert _resolve_project_fetch_token(project, None) == "hf_env"
1090
+
1091
+
1092
  def test_build_detection_repository_prefers_dataset_rows(monkeypatch: pytest.MonkeyPatch) -> None:
1093
  from src.ui import app_factory as module
1094
 
 
1102
  monkeypatch.setattr(
1103
  module,
1104
  "_load_dataset_detections_for_project",
1105
+ lambda project_obj, hf_token=None: (
1106
  [
1107
  Detection(
1108
  detection_key="0000000000002222",
 
1302
  assert detections[0].confidence == 0.85
1303
  assert detections[0].start_time == 0.0
1304
  assert detections[0].end_time == 3.0
1305
+
1306
+
1307
+ def test_load_dataset_detections_for_project_reads_known_files_index_before_repo_tree(
1308
+ monkeypatch: pytest.MonkeyPatch,
1309
+ tmp_path: Path,
1310
+ ) -> None:
1311
+ from src.ui import app_factory as module
1312
+
1313
+ files_index = tmp_path / "files.parquet"
1314
+ pd.DataFrame.from_records(
1315
+ [
1316
+ {
1317
+ "stored_path": "audio/Accipiter_striatus/shard-000000/example.wav",
1318
+ "original_relative_path": "Accipiter striatus/example.wav",
1319
+ "logical_group": "Accipiter striatus",
1320
+ "filename": "example.wav",
1321
+ "size": 123,
1322
+ }
1323
+ ]
1324
+ ).to_parquet(files_index, index=False)
1325
+
1326
+ class TreeApiShouldNotRun:
1327
+ def __init__(self, token: str | None = None) -> None:
1328
+ _ = token
1329
+
1330
+ def list_repo_files(self, repo_id: str, repo_type: str = "dataset") -> list[str]:
1331
+ _ = repo_id
1332
+ _ = repo_type
1333
+ raise AssertionError("tree discovery should not run when index/files.parquet is available")
1334
+
1335
+ def fake_download(repo_id: str, repo_type: str, filename: str, token: str | None = None) -> str:
1336
+ _ = repo_id
1337
+ _ = repo_type
1338
+ _ = token
1339
+ if filename == "index/files.parquet":
1340
+ return str(files_index)
1341
+ raise FileNotFoundError(filename)
1342
+
1343
+ monkeypatch.setattr(module, "HfApi", TreeApiShouldNotRun)
1344
+ monkeypatch.setattr(module, "hf_hub_download", fake_download)
1345
+
1346
+ project = Project(
1347
+ project_slug="ppbio-rabeca",
1348
+ name="PPBIO RABECA",
1349
+ dataset_repo_id="jrrribeiro/PPBIO-RABECA",
1350
+ active=True,
1351
+ )
1352
+
1353
+ detections, warning = module._load_dataset_detections_for_project(project)
1354
+
1355
+ assert warning == ""
1356
+ assert len(detections) == 1
1357
+ assert detections[0].audio_id == "Accipiter_striatus/shard-000000/example.wav"
1358
+
1359
+
1360
+ def test_load_dataset_detections_for_project_explains_tree_rate_limit(monkeypatch: pytest.MonkeyPatch) -> None:
1361
+ from src.ui import app_factory as module
1362
+
1363
+ monkeypatch.setattr(module, "_load_detections_from_known_files_index", lambda **kwargs: ([], ""))
1364
+
1365
+ class RateLimitedHfApi:
1366
+ def __init__(self, token: str | None = None) -> None:
1367
+ _ = token
1368
+
1369
+ def list_repo_files(self, repo_id: str, repo_type: str = "dataset") -> list[str]:
1370
+ _ = repo_id
1371
+ _ = repo_type
1372
+ raise RuntimeError("429 Client Error: Too Many Requests")
1373
+
1374
+ monkeypatch.setattr(module, "HfApi", RateLimitedHfApi)
1375
+
1376
+ project = Project(
1377
+ project_slug="ppbio-rabeca",
1378
+ name="PPBIO RABECA",
1379
+ dataset_repo_id="jrrribeiro/PPBIO-RABECA",
1380
+ active=True,
1381
+ )
1382
+
1383
+ detections, warning = module._load_dataset_detections_for_project(project)
1384
+
1385
+ assert detections == []
1386
+ assert "rate-limited dataset discovery" in warning
1387
+ assert "fast HF_Dataset_Uploader index path" in warning
tests/unit/test_supabase_state.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.repositories.supabase_state import SupabaseBootstrapStore
2
+
3
+
4
+ class FakeSupabaseClient:
5
+ def __init__(self) -> None:
6
+ self.tables: dict[str, list[dict[str, object]]] = {
7
+ "projects": [
8
+ {
9
+ "project_id": "old-id",
10
+ "project_slug": "old-project",
11
+ "name": "Old Project",
12
+ "dataset_repo_id": "org/old-project",
13
+ "visibility": "collaborative",
14
+ "owner_username": "owner",
15
+ "dataset_token": None,
16
+ "active": True,
17
+ }
18
+ ],
19
+ "user_project_access": [],
20
+ "pending_invites": [],
21
+ }
22
+ self.patches: list[tuple[str, dict[str, object], dict[str, str]]] = []
23
+
24
+ def select(self, table: str, *, query: dict[str, str] | None = None) -> list[dict[str, object]]:
25
+ _ = query
26
+ return [dict(row) for row in self.tables.get(table, [])]
27
+
28
+ def upsert(self, table: str, rows: list[dict[str, object]], *, on_conflict: str) -> None:
29
+ _ = on_conflict
30
+ if table != "projects":
31
+ self.tables[table] = [dict(row) for row in rows]
32
+ return
33
+
34
+ by_slug = {
35
+ str(row.get("project_slug") or ""): row
36
+ for row in self.tables.get("projects", [])
37
+ }
38
+ for row in rows:
39
+ by_slug[str(row.get("project_slug") or "")] = dict(row)
40
+ self.tables["projects"] = list(by_slug.values())
41
+
42
+ def insert(self, table: str, row: dict[str, object]) -> None:
43
+ self.tables.setdefault(table, []).append(dict(row))
44
+
45
+ def patch(self, table: str, row: dict[str, object], *, query: dict[str, str]) -> None:
46
+ self.patches.append((table, dict(row), dict(query)))
47
+ if table != "projects":
48
+ return
49
+ project_slug_filter = str(query.get("project_slug") or "")
50
+ if not project_slug_filter.startswith("eq."):
51
+ return
52
+ project_slug = project_slug_filter[3:]
53
+ for existing in self.tables.get("projects", []):
54
+ if existing.get("project_slug") == project_slug:
55
+ existing.update(row)
56
+
57
+ def delete(self, table: str, *, query: dict[str, str]) -> None:
58
+ _ = query
59
+ self.tables[table] = []
60
+
61
+
62
+ def test_supabase_persist_deactivates_projects_missing_from_current_state() -> None:
63
+ client = FakeSupabaseClient()
64
+ store = SupabaseBootstrapStore(client) # type: ignore[arg-type]
65
+
66
+ store.persist(
67
+ projects=[
68
+ {
69
+ "project_id": "new-id",
70
+ "project_slug": "new-project",
71
+ "name": "New Project",
72
+ "dataset_repo_id": "org/new-project",
73
+ "visibility": "collaborative",
74
+ "owner_username": "owner",
75
+ "dataset_token": None,
76
+ "active": True,
77
+ }
78
+ ],
79
+ user_access={"owner": {"new-project": "admin"}},
80
+ invites={},
81
+ )
82
+
83
+ old_project = next(row for row in client.tables["projects"] if row["project_slug"] == "old-project")
84
+
85
+ assert old_project["active"] is False
86
+ assert any(table == "projects" and row["active"] is False for table, row, _ in client.patches)
87
+
88
+
89
+ def test_supabase_load_projects_skips_inactive_rows() -> None:
90
+ client = FakeSupabaseClient()
91
+ client.tables["projects"].append(
92
+ {
93
+ "project_id": "active-id",
94
+ "project_slug": "active-project",
95
+ "name": "Active Project",
96
+ "dataset_repo_id": "org/active-project",
97
+ "visibility": "collaborative",
98
+ "owner_username": "owner",
99
+ "dataset_token": None,
100
+ "active": True,
101
+ }
102
+ )
103
+ client.tables["projects"][0]["active"] = False
104
+ store = SupabaseBootstrapStore(client) # type: ignore[arg-type]
105
+
106
+ projects = store.load_projects()
107
+
108
+ assert [project.project_slug for project in projects] == ["active-project"]
tests/unit/test_ui_components.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.ui.components import (
2
+ admin_overview_html,
3
+ coverage_bars_html,
4
+ project_overview_html,
5
+ project_context_html,
6
+ validation_queue_html,
7
+ )
8
+
9
+
10
+ def test_validation_queue_html_highlights_selected_row_and_escapes_values():
11
+ html = validation_queue_html(
12
+ [
13
+ ["key-1", "audio-one.wav", "Species <one>", "0.91", "0", "3", "pending"],
14
+ ["key-2", "audio-two.wav", "Species two", "0.82", "4", "7", "positive"],
15
+ ],
16
+ selected_index=1,
17
+ )
18
+
19
+ assert "1/2" not in html
20
+ assert "2/2" in html
21
+ assert "bn-queue-card-selected" in html
22
+ assert "Species &lt;one&gt;" in html
23
+ assert "audio-two.wav" in html
24
+
25
+
26
+ def test_coverage_bars_html_renders_species_progress():
27
+ html = coverage_bars_html(
28
+ [
29
+ ["Tinamus major", 100, 25, 75, 25.0],
30
+ ["Attila spadiceus", 10, 10, 0, 100.0],
31
+ ]
32
+ )
33
+
34
+ assert "Coverage by species" in html
35
+ assert "Tinamus major" in html
36
+ assert "25.0%" in html
37
+ assert "width:100.0%;" in html
38
+
39
+
40
+ def test_project_context_html_renders_project_metadata():
41
+ html = project_context_html(
42
+ ["ppbio", "PPBIO", "jrrribeiro/ppbio", "private", "jonathan", "yes", "yes"],
43
+ role="admin",
44
+ )
45
+
46
+ assert "PPBIO" in html
47
+ assert "jrrribeiro/ppbio" in html
48
+ assert "ADMIN" in html
49
+ assert "token set" in html
50
+
51
+
52
+ def test_project_overview_html_accepts_table_rows():
53
+ html = project_overview_html(
54
+ [["ppbio", "PPBIO", "jrrribeiro/ppbio", "collaborative", "jonathan", "yes", "yes"]],
55
+ ["ppbio"],
56
+ "ppbio",
57
+ )
58
+
59
+ assert "PPBIO" in html
60
+ assert "jrrribeiro/ppbio" in html
61
+ assert "token set" in html
62
+ assert "bn-project-card-selected" in html
63
+
64
+
65
+ def test_admin_overview_html_handles_locked_and_authenticated_states():
66
+ locked = admin_overview_html(
67
+ username=None,
68
+ total_projects=3,
69
+ admin_projects=0,
70
+ validator_projects=0,
71
+ pending_invites=0,
72
+ )
73
+ active = admin_overview_html(
74
+ username="validator",
75
+ total_projects=3,
76
+ admin_projects=1,
77
+ validator_projects=2,
78
+ pending_invites=4,
79
+ )
80
+
81
+ assert "Admin workspace locked" in locked
82
+ assert "validator" in active
83
+ assert "4 pending invites" in active