` header injection in `src/api/client.js` (single change point — all API calls go through this module already)
-- Add login/register views and auth Pinia store
-- Redirect to `/login` on 401 responses
-- No other frontend changes required until Phase 4 (user-scoped UI)
-
----
-
-## Horizontal Scaling Concerns
-
-| Concern | What to Share | What Can Be Instance-Local |
-|---------|--------------|---------------------------|
-| DB connections | PostgreSQL (shared) — use connection pooling (asyncpg pool size 10-20 per instance) | None |
-| Object storage | MinIO (shared) — all instances use same endpoint | None |
-| Refresh token state | PostgreSQL `refresh_tokens` table (shared) | JWT validation (CPU-only, no shared state needed) |
-| Quota state | PostgreSQL `quotas` table with atomic UPDATE (shared) | Pre-flight Content-Length check (instance-local read, final write shared) |
-| Background tasks | Cannot use `BackgroundTasks` across instances — use Celery + Redis OR Postgres-backed queue (pg_boss / pgqueuer) | Single-instance: `BackgroundTasks` is fine for Phase 1 |
-| File upload temp buffers | If streaming proxy pattern used: RAM per instance | Use presigned URLs to avoid this entirely |
-| AI provider instances | Re-instantiated per request already — no shared state | Per-instance re-instantiation is fine |
-| CORS / session | Stateless JWT — no sticky sessions needed | — |
-
-**First bottleneck:** Background task queue. `FastAPI BackgroundTasks` runs in the same process. When classification is slow or multiple uploads arrive simultaneously, workers block. Introduce a task queue (Celery + Redis, or pgqueuer) before scaling to N instances — otherwise each instance has its own queue and tasks are not distributed.
-
-**Second bottleneck:** DB connection count. With N instances × 20 connections = N×20 PostgreSQL connections. Add PgBouncer in transaction mode in front of PostgreSQL before N gets large.
-
----
-
-## Anti-Patterns
-
-### Anti-Pattern 1: Per-Instance File Locks for Quota
-
-**What people do:** Carry forward the `filelock` pattern into the multi-instance world, using a lock file on a shared volume.
-
-**Why it's wrong:** Shared NFS/volume file locking has undefined behavior under Docker Compose networking, requires a shared filesystem mount (kills stateless instances), and is slower than a DB atomic update.
-
-**Do this instead:** Atomic `UPDATE quotas SET used_bytes = used_bytes + $delta WHERE user_id = $uid AND (used_bytes + $delta) <= limit_bytes` in PostgreSQL. Single round-trip, correct under concurrency, no shared filesystem required.
-
----
-
-### Anti-Pattern 2: Streaming All File Traffic Through FastAPI
-
-**What people do:** `POST /upload` receives the multipart body into memory, then POSTs it to MinIO from FastAPI.
-
-**Why it's wrong:** Doubles memory usage (once in FastAPI, once in MinIO client buffer). Saturates FastAPI worker threads during large uploads. Introduces FastAPI as a bottleneck for byte transfer.
-
-**Do this instead:** Two-step presigned URL flow (Pattern 3 above). FastAPI only handles metadata; bytes flow browser → MinIO directly.
-
----
-
-### Anti-Pattern 3: Auth in Middleware Instead of Dependencies
-
-**What people do:** Write a custom ASGI middleware that reads the `Authorization` header and either passes or rejects requests.
-
-**Why it's wrong:** Middleware runs before FastAPI routing. To allow public routes (login, register, health), you must maintain an exclusion list in the middleware. This list inevitably goes stale when new public routes are added. Middleware cannot easily populate `request.state.user` in a way that's type-safe for path operations.
-
-**Do this instead:** `Depends(get_current_user)` on each protected router. Optional auth uses `Depends(get_optional_user)` returning `User | None`. Explicit, type-safe, co-located with the route it protects. Confirmed as FastAPI's recommended pattern.
-
----
-
-### Anti-Pattern 4: Storing Cloud Credentials Unencrypted (or Relying on DB-Level Encryption Alone)
-
-**What people do:** Store OAuth tokens in plaintext DB columns, assuming DB-level TLS or disk encryption is sufficient.
-
-**Why it's wrong:** Any user with DB read access (admin, compromised migration, backup leak) can extract all users' cloud tokens. Violates the privacy-first admin model requirement.
-
-**Do this instead:** Fernet-encrypt the credential JSON blob in `cloud_service.py` before writing to `cloud_backends.credentials_enc`. The Fernet key lives in `CLOUD_CREDS_KEY` env var only — never in the DB. Admin queries on `cloud_backends` return only `id`, `backend_type`, `display_name`, `is_default` — the `credentials_enc` column is excluded from all admin-facing serializers.
-
----
-
-### Anti-Pattern 5: One MinIO Bucket Per User
-
-**What people do:** Create a new MinIO bucket for each registered user to enforce isolation.
-
-**Why it's wrong:** MinIO is not designed for millions of buckets. Bucket creation is a management operation. IAM policies per bucket become complex to manage at scale.
-
-**Do this instead:** Single bucket, key prefix isolation: `{user_id}/{document_id}/{filename}`. Enforce prefix scoping in `storage_service.py` — never let a user-supplied key escape their `{user_id}/` prefix. Verify in every `get_object` and `delete_object` call that the resolved key starts with the authenticated user's ID.
-
----
-
-## Integration Points
-
-### External Services
-
-| Service | Integration Pattern | Notes |
-|---------|---------------------|-------|
-| PostgreSQL | SQLAlchemy 2.0 async (`asyncpg` driver), sessions via `Depends(get_db)` | Use `asyncpg` pool, not per-request connections |
-| MinIO | `minio` Python SDK (sync) wrapped in `asyncio.to_thread()`, or `aiobotocore` for async S3 | Presigned URL generation is CPU-bound, not I/O-bound — `to_thread` is fine |
-| OneDrive | Microsoft Graph API via `httpx` async client + OAuth2 PKCE flow | Refresh tokens stored encrypted in `cloud_backends` |
-| Google Drive | Google Drive API v3 via `httpx` or `google-auth` library | Same credential model as OneDrive |
-| Nextcloud | WebDAV via `httpx` (PUT/GET/DELETE) or `webdavclient3` library | Basic auth or app password — simpler than OAuth |
-| PyOTP | TOTP generation/verification (`pyotp.TOTP(secret).verify(code)`) | Time-window tolerance: default ±1 period (±30 sec) is sufficient |
-| `python-jose` or `PyJWT` | JWT encode/decode | Use `HS256` with a 256-bit secret. `python-jose` has broader algorithm support; `PyJWT` is simpler and more actively maintained |
-| `cryptography` (Fernet) | Cloud credential encryption/decryption | `Fernet.generate_key()` at setup; store in `CLOUD_CREDS_KEY` env var |
-| `passlib[bcrypt]` | Password hashing | bcrypt work factor 12 minimum |
-
-### Internal Boundaries
-
-| Boundary | Communication | Notes |
-|----------|---------------|-------|
-| `api/` ↔ `services/` | Direct async function calls | Services never import from `api/`; dependency is one-directional |
-| `services/` ↔ `storage/` | `StorageBackend` ABC interface | Services import from `storage/__init__.py` factory only |
-| `services/` ↔ `ai/` | Existing `get_provider()` factory — unchanged | AI provider is still re-instantiated per call |
-| `deps/` ↔ `services/` | Services can be called from deps (e.g., quota_service from quota dep) | Keep deps thin — prefer passing a DB session to the dep and calling service functions |
-| `db/models.py` ↔ everywhere | Import models directly | No repository pattern needed at this scale; SQLAlchemy session + models is sufficient |
-
----
-
-## Scaling Considerations
-
-| Scale | Architecture | Notes |
-|-------|-------------|-------|
-| 1–100 users | Single FastAPI instance, `BackgroundTasks`, no queue | This milestone's target; simplest path |
-| 100–10k users | Add Celery + Redis for background tasks; add PgBouncer; scale FastAPI to 2–4 instances | Background task queue is the first change needed |
-| 10k–100k users | Read replica for PostgreSQL (document listing queries), MinIO multi-node cluster | Document metadata reads dominate; separate read/write paths |
-| 100k+ users | Consider separate microservice for classification (GPU workers); CDN in front of MinIO presigned URLs | Classification latency becomes user-facing bottleneck |
+| Change | Is the minimal solution also the proper one? |
+|---|---|
+| Backend decomposition | Yes. Sub-router via `__init__.py` aggregator is both minimal and the standard FastAPI pattern. |
+| client.js decomposition | Yes. Re-export barrel means zero consumer churn while achieving internal separation. |
+| Admin layout | Yes. Three-way `v-if` in App.vue + new layout file is 20 lines of change in existing files. |
+| Icon refactor | The minimal solution (AppIcon.vue) is simpler than lucide but adds maintenance burden for the path map. lucide is more proper but adds a dependency. Call must be made by project owner. |
---
## Sources
-- FastAPI official docs — Security / OAuth2 with JWT: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ (HIGH confidence — directly confirmed pattern)
-- FastAPI official docs — Advanced Middleware: https://fastapi.tiangolo.com/advanced/middleware/ (HIGH confidence — confirms DI > middleware for auth)
-- FastAPI official docs — SQL Databases: https://fastapi.tiangolo.com/tutorial/sql-databases/ (HIGH confidence — session-per-request via Depends confirmed)
-- MinIO S3 presigned URL pattern: S3-compatible standard, documented in AWS S3 and MinIO docs (HIGH confidence — industry-standard pattern)
-- PostgreSQL atomic UPDATE for quota enforcement: standard optimistic concurrency pattern (HIGH confidence)
-- Fernet symmetric encryption (`cryptography` library): well-documented Python standard for symmetric key encryption (HIGH confidence)
-- Refresh token rotation pattern: IETF OAuth 2.0 Security BCP (RFC 9700 / draft-ietf-oauth-security-topics) (HIGH confidence)
-
----
-*Architecture research for: DocuVault multi-user SaaS document management (FastAPI + Vue 3 brownfield)*
-*Researched: 2026-05-21*
+- Inspected source: `backend/main.py`, `backend/api/admin.py`, `frontend/src/App.vue`, `frontend/src/router/index.js`, `frontend/src/layouts/AuthLayout.vue`, `frontend/src/api/client.js`, `frontend/src/views/AdminView.vue`, `frontend/src/components/layout/AppSidebar.vue`
+- FastAPI sub-router `include_router` nesting: standard FastAPI router composition (HIGH confidence)
+- Vue Router 4 `route.matched` for meta inheritance: Vue Router 4 documented behavior (HIGH confidence)
+- lucide-vue-next: tree-shakeable Vue 3 icon library (MEDIUM confidence — verified as active, Tailwind-compatible)
diff --git a/.planning/research/FEATURES.md b/.planning/research/FEATURES.md
index 07792c6..ca3fd57 100644
--- a/.planning/research/FEATURES.md
+++ b/.planning/research/FEATURES.md
@@ -1,449 +1,257 @@
-# Feature Research
+# Feature Landscape — v0.2 UI Overhaul
-**Domain:** SaaS Document Management Platform (multi-user, quota-enforced, privacy-first)
-**Researched:** 2026-05-21
-**Confidence:** MEDIUM (web fetch/search unavailable; based on training knowledge of Google Drive, OneDrive, Dropbox, Box, Notion, Paperless-ngx, DocuWare through Aug 2025 — all mature platforms with stable, well-documented feature sets)
+**Domain:** Self-hosted SaaS document management (DocuVault)
+**Researched:** 2026-06-07
+**Scope:** UX patterns and UI feature decisions for v0.2. Existing functional features (upload, extraction, sharing, cloud backends, auth) are not re-researched — only their UX surface.
---
-## Research Scope
+## Table Stakes
-Platforms surveyed: Google Drive, Microsoft OneDrive, Dropbox, Notion, Box, Paperless-ngx (self-hosted), DocuWare (enterprise DMS).
+Features users expect. Missing = product feels incomplete or broken.
-Eight areas analyzed per the brief:
-1. Auth & access control
-2. Storage & quota UX
-3. Folder/organization UX
-4. Sharing model
-5. Cloud storage integration UX
-6. Admin panel
-7. Audit / compliance
-8. Document viewer features
+| Feature | Why Expected | Complexity | Depends On |
+|---------|--------------|------------|------------|
+| Standalone admin layout (`/admin/*` routes with own sidebar) | AdminView.vue is currently a tab sheet bolted to the user layout. Admin and user contexts share no chrome. Nextcloud, Mayan EDMS, and every self-hosted SaaS treat admin as a distinct area. | Medium | Router nested routes, new `AdminLayout.vue` |
+| Admin sidebar with discrete nav items (Users, Quotas, AI Config, Audit Log) | Each admin tab is already a full standalone component. Route-based nav replaces in-view tabs — enables deep linking, browser back button, and future per-section permissions. | Low | Vue Router `/admin/users`, `/admin/quotas`, `/admin/ai`, `/admin/audit` child routes |
+| Empty states for every zero-content context | File list empty, folder empty, search no-results, shared-with-me empty, topics empty — each needs a distinct, actionable state. Current implementation is plain gray text. Zero-content states are the first thing new users see. | Medium | `StorageBrowser.vue`, `SharedView.vue`, `TopicsView.vue` |
+| Loading skeletons for document list and sidebar tree | The document list (`StorageBrowser`) and sidebar folder tree currently render a plain "Loading…" text string. Skeletons reduce perceived load time by 30–50% on equivalent wait times per usability studies. The `QuotaBar` already uses `animate-pulse` — extend that pattern. | Medium | `StorageBrowser.vue`, `AppSidebar.vue`, new `SkeletonRow.vue` |
+| Global search focus shortcut (`/` key) | Table stakes for document management tools. Paperless-ngx, Notion, GitHub, Linear all use `/` to focus search. Users who type `/` and nothing happens feel the app is unpolished. | Low | `SearchBar.vue`, `FileManagerView.vue` global `keydown` listener |
+| Escape key closes modals and clears search | Universal browser convention. Escape should: close `ShareModal`, close `FolderDeleteModal`, close `DocumentPreviewModal`, clear the inline folder rename input, and clear search field. Several of these already handle `keydown.escape` in inputs but not at the modal overlay level. | Low | `ShareModal.vue`, `FolderDeleteModal.vue`, `DocumentPreviewModal.vue` |
+| Sidebar collapses on mobile (hamburger toggle, overlay drawer) | On viewports below 1024px the fixed 256px sidebar eats 25–40% of the viewport. The current layout has no mobile handling — sidebar overlaps content on small screens. Minimum viable mobile: hamburger button + slide-in overlay drawer. | Medium | `AppSidebar.vue`, `App.vue`, new mobile toggle state |
+| Responsive document list column hiding | `StorageBrowser` grid already uses `hidden md:block` for Size and `hidden sm:block` for Modified. This is correct — verify it works and document the pattern as intentional. Ensure the icon + name + actions columns always render. | Low | `StorageBrowser.vue` (verify existing classes) |
+| Upload trigger keyboard shortcut (`U` key when no input is focused) | Secondary table stakes. Windows Explorer, Nextcloud, and Dropbox support pressing a key to trigger upload when focus is on the file list. Makes keyboard-first workflows viable. | Low | `DropZone.vue` or `FileManagerView.vue` global `keydown` listener |
+| Visible drag-and-drop affordance on the drop zone at all times | `DropZone.vue` already exists and handles dragover/drop. The gap: the drop zone is a full-width dashed box inside the content area, which is correct, but there is no whole-page drag overlay when a user drags a file from the OS file manager. Users miss the target and the drop is ignored. | Medium | `FileManagerView.vue` document-level dragenter/dragleave listener |
+| Contextual breadcrumb with admin section label | Admin subroutes need breadcrumbs: `Admin > Users`, `Admin > Audit Log`. Without them, admin pages feel unmoored. The user-facing `FolderBreadcrumb` is already built — admin can use the same component with static segments. | Low | `FolderBreadcrumb.vue`, `AdminLayout.vue` |
---
-## Feature Landscape
+## Differentiators
-### Table Stakes (Users Expect These)
+Features that add genuine value beyond the baseline. Not expected by most users, but valued when present.
-Features users assume exist. Missing these = product feels incomplete or broken.
-
-#### 1. Auth & Access Control
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Email + password registration with validation | Every SaaS has this | LOW | Strength rules (length, complexity) expected; breach-check (HaveIBeenPwned API) is a notable addition |
-| Persistent sessions with "remember me" | Users hate logging in every visit | LOW | JWT with refresh token; sliding expiry. Pure stateless JWT without refresh feels cheap. |
-| Password reset via email | Users forget passwords constantly | LOW | Time-limited signed token; mandatory |
-| TOTP 2FA (authenticator app) | Expected at any security-conscious SaaS | MEDIUM | PyOTP / HOTP RFC 6238. Users expect QR code setup + backup codes. Missing backup codes = major UX gap. |
-| Forced logout / session revocation | Power users and security-conscious users expect this | MEDIUM | "Sign out all devices" is table stakes at Box and Google. Requires server-side session tracking (defeats pure JWT — use a token revocation list or short-lived JWTs + refresh token table). |
-| Per-user isolated data space | Every cloud storage product does this | LOW | Violated = catastrophic trust failure. MinIO prefix isolation per user ID. |
-| Account deletion with data wipe | GDPR + user trust | MEDIUM | Must cascade: documents, quotas, shares, cloud credentials, audit entries scoped to user. |
-
-#### 2. Storage & Quota UX
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Visible quota indicator (used / total) | Google Drive, Dropbox, OneDrive all show this prominently | LOW | Progress bar + "X MB of Y MB used" in sidebar or settings. Missing = users feel blind. |
-| Quota check at upload time with clear error | Every platform rejects over-quota uploads | LOW | Error must say "You've used X of Y MB — free up space or upgrade." Not a generic 500. |
-| Per-file size shown in file list | Dropbox, Drive show sizes in list view | LOW | Users make quota decisions based on file size visibility. |
-| Sort/filter by size | Users cleaning up quota expect to find large files | LOW | "Largest files first" sort is a common quota-management action. |
-| Quota warning at 80% and 95% | Drive warns at 80%; Dropbox emails at 90% | LOW | In-app banner + optionally email. Users are surprised when they hit the wall without warning. |
-| Storage usage breakdown by folder/category | Drive shows breakdown by file type | MEDIUM | "X MB in Documents, Y MB in Images" helps users understand what to delete. Folder-level usage is lower priority but expected by power users. |
-| Delete confirmation that shows freed space | Minor but Dropbox/Drive do this | LOW | "Deleting this file will free 24 MB." Reinforces value of the action. |
-
-#### 3. Folder / Organization UX
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Create folder | Universal | LOW | Standard. |
-| Rename folder | Universal | LOW | Inline rename (click-to-edit) is expected; modal is acceptable. |
-| Delete folder (with contents confirmation) | Universal | LOW | Must warn if non-empty: "This will delete N documents." Soft-delete preferred; hard-delete on confirm. |
-| Move document to folder (drag-and-drop or context menu) | Drive, Dropbox have both | MEDIUM | Drag-and-drop is a strong UX expectation in desktop-class web apps. Context menu "Move to..." is the fallback minimum. |
-| Move folder into another folder (nesting) | Drive, OneDrive support arbitrary depth | MEDIUM | Users expect arbitrary depth. Cap at 5–8 levels deep to avoid pathological nesting; unlimited is fine for v1. |
-| Breadcrumb navigation | Universal in file managers | LOW | Clickable breadcrumb showing full path: Root > Invoices > 2025. Without this users get lost in nested folders. |
-| Sort documents within folder (name, date, size, type) | All platforms have this | LOW | Default: date descending (newest first). |
-| "Recent" / "Last accessed" virtual folder | Drive, OneDrive surface this prominently | LOW | Not a real folder — a filtered view. Users navigating back to recent work expect it. |
-| Search across all documents | Every platform has global search | MEDIUM | Full-text or metadata search. For DocuVault, text is already extracted — expose it in search. Missing = product feels like a filing cabinet with no index. |
-| Multi-select for batch operations | Drive, Dropbox support shift-click + checkbox | MEDIUM | Batch delete, batch move. Without this, managing many files is tedious. |
-| "Shared with me" virtual folder | Drive has this; Box has it; Dropbox has it | LOW | Auto-populated when another user shares a document. Already in PROJECT.md. |
-
-#### 4. Sharing Model
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Share with named user (by handle or email) | Drive, Box, Dropbox all do this | MEDIUM | Core sharing primitive. Must show: who has access, their permission level, revoke button. |
-| View-only vs. edit permission distinction | Box, Drive, Dropbox all distinguish view/edit | LOW | For DocuVault, edit means "re-upload / annotate" — since no in-app editing, view-only is the primary mode. Still must distinguish the concept for future extensibility. |
-| Revoke share immediately | All platforms do this | LOW | No delay. If the user is currently viewing the document, their next request should 403. |
-| Share notification to recipient | Drive/Dropbox send email; Box shows in-app | LOW | At minimum: in-app notification. Email is table stakes for platforms where users may not be logged in. |
-| See list of "what I've shared" | Drive, Box surface this | LOW | Users need to audit their own shares. A "Shared by me" list per document + a global shares list in settings. |
-| Accept / decline incoming share | Box requires acceptance; Drive shows silently | MEDIUM | DocuVault's "Shared with me" folder appearing is implicit acceptance. An explicit accept/decline adds trust. Drive skips it; Box requires it for external shares. Given privacy-first positioning, explicit accept is the better default. |
-| Share expiry date | Box supports this; Drive (with Workspace) does; Dropbox Business does | MEDIUM | Not universal at consumer tier but expected in security-conscious / business contexts. |
-
-#### 5. Cloud Storage Integration UX
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| OAuth2 connect flow for Google Drive / OneDrive | Standard for these integrations | HIGH | Redirect-based OAuth2 PKCE. Users expect "Connect" → browser popup → granted → back to app. No credential entry. |
-| Connection status indicator (connected / disconnected / error) | Any integration page shows this | LOW | Green dot = connected, red = error with message. Dropbox Business sync indicators are the model. |
-| Disconnect / re-authenticate option | Users rotate tokens; credentials expire | LOW | "Disconnect" button. Re-auth if token expires (silent token refresh where possible). |
-| Default storage selector | Users need to know where new uploads go | LOW | Clear radio/dropdown: "Local storage" vs "Google Drive" vs "OneDrive." Show current default prominently. |
-| Upload routing confirmation | When cloud is default, users want to see it confirmed | LOW | "Stored in Google Drive" in upload success message. |
-| Error state when cloud storage unreachable | Cloud services go down; credentials expire | MEDIUM | Graceful: queue locally, show warning, retry. Hard fail (lose document) = catastrophic. Minimum: "Storage unavailable — document saved locally." |
-| Basic usage from cloud backend | Show how much cloud storage is used vs available | MEDIUM | Google Drive has 15 GB free; OneDrive 5 GB. Surfacing "You've used 3 GB of your 15 GB Google Drive" alongside local quota gives users a full picture. |
-
-#### 6. Admin Panel
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| User list with search and pagination | Every admin panel has this | LOW | Show: username, email, registration date, last login, quota used/total, active/inactive status. |
-| Create user account | Admin needs to onboard users manually (invite flow) | LOW | Form: email, temp password (force reset on first login), quota assignment. |
-| Deactivate / reactivate user | Admin must be able to remove access without deleting data | LOW | Soft disable: user cannot log in; data preserved. Separate from delete. |
-| Force password reset | Standard admin action | LOW | Invalidates current sessions; user gets reset email. |
-| Quota adjustment per user | Already in PROJECT.md | LOW | Input: new quota in MB. Show current usage. Prevent setting quota below current usage (warn, not block). |
-| System-wide default quota setting | Admins want to change the free tier baseline | LOW | Global default that new users inherit. Existing users keep their individually-set quota. |
-| AI provider/model assignment per user | Already in PROJECT.md | MEDIUM | Dropdown of configured providers + models. Show "using system default" until overridden. |
-| System-wide AI provider default | Already in PROJECT.md | LOW | Global fallback when no user override exists. |
-| Audit log viewer | All enterprise DMS products have this | MEDIUM | See Audit section below. |
-| Platform health indicators | Admins need to know if things are broken | MEDIUM | Storage backend connectivity, database connection, queue depth. A simple status page at /admin/health. |
-
-#### 7. Audit / Compliance
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Audit log of security events | GDPR, SOC2 baseline, enterprise buyers expect this | MEDIUM | Mandatory events: login, failed login, password reset, 2FA enable/disable, session revoke. |
-| Audit log of data events | Same compliance baseline | MEDIUM | Mandatory events: document upload, document delete, document move/rename, share create, share revoke, quota change. |
-| Metadata-only audit (no content) | Privacy requirement — DocuVault's stated constraint | LOW | Log: actor_user_id, action, target_resource_id, timestamp, IP address. Never log document content or filenames in the log (filename is sensitive metadata). |
-| Admin-viewable audit log with filters | Already in PROJECT.md | MEDIUM | Filter by: user, action type, date range. Export to CSV is expected by compliance-oriented admins. |
-| Immutable audit log | Audit logs lose their value if they can be edited | MEDIUM | Append-only table. No UPDATE/DELETE on audit rows. Admin UI shows only read operations. |
-| IP address logging | Standard for login events; expected by security teams | LOW | Log IP on all auth events. GDPR note: IP is PII — include in retention policy. |
-| Log retention policy | GDPR requires defined retention | LOW | Configurable in admin settings. Default: 1 year. Automated purge of older entries. |
-| GDPR data export (user's own data) | GDPR Article 20 right to portability | HIGH | User can request export of all their data: document list + metadata (not necessarily content), account info, audit log of their own actions. Full content export is optional but the metadata export is required. |
-
-#### 8. Document Viewer Features
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| In-browser PDF preview | Drive, Dropbox, Box all have this | MEDIUM | Use browser's native PDF viewer or PDF.js. Without preview, users must download to read — major friction. |
-| Document metadata panel | All DMS platforms show this | LOW | Show: upload date, file size, MIME type, AI-assigned topics, uploader, storage backend. |
-| AI topics display | Core DocuVault feature | LOW | Show assigned topics with confidence if available. Allow manual topic override from document detail. |
-| Download original file | Universal | LOW | Always available. Even if preview fails, download must work. |
-| Document rename | Drive, Dropbox allow rename from detail view | LOW | Inline rename in detail view or list view. |
-| Delete from detail view | Universal | LOW | With confirmation. Returns to parent folder. |
-| "Shared with" indicator on document | Drive shows a "people" icon on shared items | LOW | Visual indicator in list view that document is shared. Click to see who. |
-| Basic image preview (JPG, PNG) | All platforms preview images natively | LOW | Browser
tag is sufficient. |
-| Text file preview | Drive, Dropbox show .txt inline | LOW | Simple render of extracted text is adequate. |
+| Feature | Value Proposition | Complexity | Depends On |
+|---------|-------------------|------------|------------|
+| Whole-page drop zone (drag files anywhere on the screen to upload) | Removes the requirement to aim at the DropZone rectangle. Paperless-ngx supports this. Implementation: listen for `dragenter` at the document level, show a full-screen overlay with the drop target, then pipe the `drop` event into the existing upload emit chain. | Medium | `FileManagerView.vue`, new `PageDropOverlay.vue`, existing `DropZone` emit chain |
+| Skeleton placeholders shaped like the real content (5-column grid rows) | The QuotaBar has a simple pulse bar. The document list skeleton should be 5-column grid rows matching the actual layout — icon placeholder, name placeholder, size placeholder, date placeholder. This makes the transition from loading to content feel instantaneous rather than a layout jump. | Medium | New `SkeletonRow.vue`, `StorageBrowser.vue` |
+| Admin dashboard overview page (`/admin` root — stats at a glance) | User count, storage total across all users, recent audit log entries. Gives admins a reason to visit the admin panel rather than jumping straight to sub-sections. Self-hosted tools consistently provide this at the admin root. | Medium | New `AdminOverviewView.vue`, read-only aggregate API endpoints (may require backend work) |
+| Inline toast/notification system for upload completion and errors | Currently errors appear in the UploadProgress inline list and are never dismissed. A toast system enables transient success/error messages for any action (rename, delete, share) — not just upload. Constraint: keep it simple, not a full notification center. | Medium | New `ToastManager.vue` in `App.vue`, composable `useToast()` |
+| Document count badge polish on topic sidebar links | Already has `{{ topic.doc_count }}` in the sidebar. What's missing: show 0 counts as dimmed rather than hidden (users want to know the topic exists even if empty), and truncate to "9+" at double digits. | Low | `AppSidebar.vue` (minor change) |
+| Upload from keyboard shortcut `U` with accessible file picker trigger | The keyboard shortcut fires `triggerInput()` on DropZone. Accessibility requirement: this is equivalent to clicking the hidden file input — screen readers announce the file dialog opening. Already partially supported by `DropZone.vue`'s `triggerInput()` — wire up the global shortcut. | Low | `DropZone.vue`, `FileManagerView.vue` |
+| Tablet landscape layout: sidebar + content, no collapse needed | At 1024px (lg breakpoint), the sidebar is fully visible alongside content. This is the natural Tailwind `lg:flex` pattern. Verify it and make the breakpoint logic explicit in the layout wrapper. | Low | `App.vue` layout wrapper |
---
-### Differentiators (Competitive Advantage)
+## Anti-Features
-Features that align with DocuVault's core value (privacy-first, self-hosted, AI-classified).
+Features to explicitly NOT build in v0.2.
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Privacy-first admin model (admin cannot read documents) | Unique trust proposition vs Google Drive/OneDrive where the operator can read everything | HIGH | Encryption-at-rest with user-scoped keys; admin queries explicitly exclude content. No other mainstream cloud platform offers this by default. Strong differentiator for privacy-conscious users. |
-| Bring-your-own cloud storage backend | Users keep their existing cloud storage; DocuVault is the intelligent layer on top | HIGH | Google Drive/OneDrive are the storage, DocuVault is the classifier/organizer. Removes the "I have to trust another cloud with my docs" objection. |
-| AI topic classification on upload (automatic) | No other mainstream DMS auto-classifies by topic on upload | MEDIUM | Paperless-ngx has auto-tagging; DocuWare has rules-based classification. AI-driven flexible topics is differentiated for non-enterprise users. |
-| Multiple AI provider support (local/private inference) | Users who want fully on-premises AI (Ollama) get privacy guarantee no cloud DMS offers | MEDIUM | Ollama / LMStudio means documents never leave the user's infrastructure. Strong appeal to privacy-first and regulated-industry users. |
-| Per-user topic customization on top of system defaults | Users get personalized classification without admin overhead | MEDIUM | System topics + per-user overrides. No mainstream cloud DMS supports per-user AI taxonomy customization. |
-| Share expiry with automatic revocation | Goes beyond basic sharing; prevents forgotten shares | MEDIUM | Dropbox Business and Box have this at paid tiers. Including it at v1 is differentiating for a free-tier self-hosted platform. |
-| Explicit share accept/decline | Recipient has control; aligns with privacy-first positioning | LOW | Box has this; Drive doesn't require it. Gives recipients agency. |
-| Storage backend per-document routing | Some documents go to Drive, others to local — user decides per-upload | HIGH | No mainstream platform does this. Users with mixed sensitivity needs can route sensitive docs to local and bulk docs to Drive. Complex to implement but uniquely valuable. |
-| In-app audit log visible to the user (not just admin) | Users can see their own activity history | LOW | GDPR-aligned; builds trust. Google Activity Dashboard is the model. Most self-hosted DMS don't surface this to users. |
+| Anti-Feature | Why Avoid | What to Do Instead |
+|--------------|-----------|-------------------|
+| Folder reorder by drag-and-drop (drag folder A above folder B to change sidebar order) | Requires a persistent `position` column in the DB, a backend migration, and drag state tracking across the sidebar tree. The sidebar is already collapsible. Payoff is marginal. | Keep alphabetical or creation-time ordering. Users can rename folders to impose their own order (e.g., "1. Contracts"). |
+| Reorderable sidebar sections (drag "Folders" above "Cloud Storage") | Same DB persistence problem. Section order is fixed and meaningful — user folders first, then external cloud. No self-hosted document manager reorders sections. | Fixed section order in `AppSidebar.vue`. |
+| Virtual scrolling for the document list | DocuVault is quota-capped at 100 MB per user. At typical document sizes (10–500 KB each), a user has at most a few hundred documents before hitting quota. Virtual scrolling adds significant complexity (dynamic row height, scroll restoration) for an edge case that the quota cap prevents. | Standard `v-for`. Add server-side pagination in a later milestone if needed. |
+| Rich text document annotations or in-app editing | Already scoped out in `PROJECT.md`. Mentioned here because UX redesigns often attract "what if we added..." scope creep. The preview modal shows PDF; that is the limit. | Stay read-only. Document content is immutable after upload. |
+| Dark mode toggle | Requires a systematic color token system across all components plus full testing of the inverted palette. The current light-mode palette is inconsistent — fix that first. Tailwind makes dark mode mechanically possible but the v0.2 payoff is low relative to scope. | Design tokens and CSS variables in v0.2 that would support dark mode in a future milestone. |
+| Drag-and-drop to reorder documents within a folder | Requires a persistent sort order column per user per folder. Documents are naturally sorted by creation date or name — both useful orderings. Custom ordering has high complexity and low frequency of use in a document vault. | Keep the existing sort controls (created_at, name, size). Server-side sort is already implemented. |
+| Full-screen modal for file upload | The DropZone is embedded in the file browser content area, which is the correct placement. A modal upload workflow adds navigation overhead with no benefit for a simple file picker. | The whole-page drag overlay (differentiator above) is the right scope. |
+| Notification center / inbox for async events | Building a polling-based notification center (classification done, quota warning) is a full feature, not UX polish. Celery classification runs in the background and its result is visible when the user next opens the document. | Toast on upload completion. Badge count on the document list is sufficient for v0.2. |
+| Multi-select with batch operations (select 10 files, delete all) | Requires a selection state layer across the file list, a selection-aware toolbar, and confirmed batch-delete UX. Medium-to-high complexity for a feature that is rarely needed in a personal document vault. | Address in a future milestone if user feedback identifies it as a gap. |
+| Drag documents from file list to sidebar folder entries | Cross-component drag state requires either a Pinia drag store or provide/inject. The sidebar `FolderTreeItem` and `StorageBrowser` have no shared parent that can coordinate state without significant refactoring. The "Move to folder" picker button already covers this use case. | The existing folder picker button in the file row actions menu. |
---
-### Anti-Features (Deliberately Excluded)
+## Admin Panel: Specific Pattern Decisions
-Features that seem good but would create problems for this project.
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Public link sharing (unauthenticated) | Users want to share with people not on the platform | Creates a public attack surface; quota abuse; legal exposure if abused; hard to revoke at scale | Out of scope for v1 per PROJECT.md. Named-user sharing with accept/decline serves legitimate use cases. |
-| In-app document editing | Users want a full office suite | Massive scope expansion (collaborative editing = CRDT, OT, conflict resolution); not core to document management; every vendor locks you into their editor | "View and organize" is the value; editing stays in the originating app. |
-| Real-time collaborative editing (Google Docs model) | Feels modern | Requires WebSocket infrastructure, OT/CRDT algorithms, presence indicators — easily 3x the codebase complexity of everything else combined | Explicit non-goal; DocuVault stores files, not live documents. |
-| Mobile app (iOS/Android) | Users want mobile access | React Native or Flutter doubles the implementation surface; mobile OAuth2 and background sync are non-trivial | Responsive web app is the minimum. PWA capabilities (offline-capable via service worker) are a future v2 differentiator. |
-| SSO / SAML / OAuth enterprise federation | Enterprise buyers ask for it | Premature: adds Keycloak or similar dependency, requires session model changes, needs testing against multiple IdPs | TOTP 2FA first; SSO when subscription billing lands. Schema already designed for extension. |
-| Subscription billing in-platform | Users want self-service upgrades | Payment processing is a separate product (Stripe integration, dunning, invoicing, tax). Doing it half-way creates billing bugs that destroy trust | Quota model is billing-ready (limit_bytes column); add Stripe when subscription tier is validated. |
-| Soft-delete / Trash with restore | Users accidentally delete things | Reasonable feature, but complicates quota accounting (does trash count against quota?), storage lifecycle, and purge timing. Drive's 30-day trash has caused user confusion about "why is my quota still full?" | Clear confirmation dialog before hard delete is the v1 approach. Trash can be added in v1.x. |
-| Document version history | Users want to see old versions | Correct for collaborative tools; for a personal document store where users own their files, versioning explodes storage use. Paperless-ngx doesn't have it. DocuWare does but it's enterprise | Hash-based deduplication (don't store the same file twice) is a better v1 primitive. Version history in v2 for users who need it. |
-| AI-generated document summaries | Seems valuable given AI integration | Every summary requires an AI call → cost scales with uploads; summaries become stale when topics change; storing summaries consumes quota | AI is used for classification only. Summary generation can be a user-triggered on-demand action later. |
-| Admin impersonation / "log in as user" | Admins want to debug user issues | Directly contradicts the privacy-first core value. If admin can impersonate, admin can access user documents. Trust collapses. | Structured audit logs give admins enough to diagnose issues without impersonation. Document this as an explicit architectural decision. |
-
----
-
-## Feature Dependencies
+### Route structure
```
-[User Registration + Auth]
- └──requires──> [Email verification] (optional at v1, needed for password reset)
- └──requires──> [JWT session management]
- └──requires──> [Token revocation list] (for forced logout)
-
-[TOTP 2FA]
- └──requires──> [Backup codes] (users get locked out without these)
- └──requires──> [User Auth base]
-
-[Document Upload]
- └──requires──> [User Auth]
- └──requires──> [Quota enforcement]
- └──requires──> [Quota tracking (DB)]
-
-[Folder Structure]
- └──requires──> [Document Upload]
- └──enhances──> [Search] (search within folder scope)
-
-[Document Sharing]
- └──requires──> [User accounts] (both sender and recipient)
- └──requires──> [Folder Structure] ("Shared with me" virtual folder)
- └──requires──> [Permission model in DB]
-
-[Share expiry]
- └──requires──> [Document Sharing base]
- └──requires──> [Background job / cron] (to revoke expired shares)
-
-[Cloud Storage Integration]
- └──requires──> [User Auth] (OAuth2 tokens stored per user)
- └──requires──> [Credential encryption] (Fernet / pgcrypto)
- └──requires──> [StorageBackend adapter interface] (already planned)
- └──enhances──> [Quota tracking] (cloud quota shown separately)
-
-[Per-document storage routing]
- └──requires──> [Cloud Storage Integration]
- └──requires──> [Multiple backends connected]
-
-[Admin Panel]
- └──requires──> [User accounts]
- └──requires──> [Quota DB model]
- └──requires──> [Audit log]
-
-[Audit Log]
- └──requires──> [User Auth] (actor_user_id)
- └──requires──> [All logged operations exist]
- └──conflicts──> [Admin impersonation] (impersonation breaks log integrity)
-
-[GDPR data export]
- └──requires──> [Audit log]
- └──requires──> [Document metadata model]
- └──requires──> [Background export job] (large exports are async)
-
-[AI classification]
- └──requires──> [Document upload + text extraction] (already exists)
- └──requires──> [Topic model] (already exists)
- └──enhances──> [Search] (topic-filtered search)
-
-[In-browser PDF preview]
- └──requires──> [Document stored accessibly] (MinIO presigned URL or proxy endpoint)
- └──independent of──> [Cloud storage] (preview proxied through app, not direct cloud URL)
+/admin → AdminLayout.vue wrapper (persistent sidebar + router-view)
+ /admin/ → AdminOverviewView.vue (stats at a glance)
+ /admin/users → AdminUsersView.vue (wraps AdminUsersTab.vue)
+ /admin/quotas → AdminQuotasView.vue (wraps AdminQuotasTab.vue)
+ /admin/ai → AdminAiConfigView.vue (wraps AdminAiConfigTab.vue)
+ /admin/audit → AdminAuditView.vue (wraps AuditLogTab.vue)
```
-### Dependency Notes
+The existing tab components (`AdminUsersTab.vue`, `AdminQuotasTab.vue`, `AdminAiConfigTab.vue`, `AuditLogTab.vue`) are promoted to route-level views. The `AdminLayout.vue` replaces `AdminView.vue`. The tab strip becomes a sidebar with router-link active styling. No logic changes inside the tab components — only the container changes. `AdminView.vue` is deleted after the migration.
-- **TOTP requires backup codes:** Without backup codes, users who lose their phone lose their account permanently. This is a support nightmare and a documented UX failure in many 2FA implementations.
-- **Forced logout requires server-side token tracking:** Pure stateless JWT cannot support "sign out all devices." A revocation list (Redis or DB table) or short-lived JWTs (15 min) + refresh token table is required. This is a non-trivial architecture decision that must be resolved before auth is implemented.
-- **Share expiry requires a background job:** Expiry cannot be purely DB-enforced. A cron job or Celery task must scan and revoke expired shares, or each share-check must evaluate expiry at access time (lazy revocation — simpler, acceptable for v1).
-- **Per-document storage routing is independent of the default storage selector:** Default storage is "which backend do new uploads go to by default?" Routing is "for this specific upload, override the default." Routing is a differentiator; default selector is table stakes.
-- **Admin impersonation conflicts with privacy-first model:** These two features are architecturally incompatible. Document this as an explicit decision in PROJECT.md.
-- **GDPR export is async:** Exporting all user data (documents + metadata) can take minutes for large accounts. Must be a background job with "email me when ready" — not a synchronous HTTP download.
+Vue Router 4 nested routes pattern (HIGH confidence — verified against official docs):
+
+```js
+{
+ path: '/admin',
+ component: AdminLayout, // contains
+ meta: { requiresAdmin: true },
+ children: [
+ { path: '', component: AdminOverviewView },
+ { path: 'users', component: AdminUsersView },
+ { path: 'quotas', component: AdminQuotasView },
+ { path: 'ai', component: AdminAiConfigView },
+ { path: 'audit', component: AdminAuditView },
+ ],
+}
+```
+
+The `requiresAdmin` guard moves from the child route to the parent. All children inherit it automatically.
+
+### Admin sidebar nav items (in order)
+1. Overview
+2. Users
+3. Quotas
+4. AI Config
+5. Audit Log
+
+A "Back to app" link at the bottom of the admin sidebar returns to `/` — admin should not feel like a dead end.
+
+### Admin sidebar does NOT share code with `AppSidebar.vue`
+
+`AdminSidebar.vue` is a separate component. It has no folder tree, no cloud tree, no topics list, no quota bar. Those belong to the user interface. Sharing the sidebar component would create coupling between two logically separate contexts and conflict with the "thin view + smart component" architecture described in CLAUDE.md.
+
+### Breadcrumb
+
+Use the existing `FolderBreadcrumb.vue` or a simpler static variant: `Admin > [Section Name]`. No dynamic nesting required. The admin sidebar's active link already signals location; the breadcrumb adds skimmability for users who navigate via URL.
---
-## MVP Definition (This Milestone)
+## Empty State Patterns: Specific Decisions
-This is a subsequent milestone — the core document + AI system exists. MVP for this milestone is everything in PROJECT.md Active section, implemented in a way that doesn't create rework.
+Each zero-content context gets a distinct implementation. Generic "No items" text is the anti-pattern.
-### Must Ship (v1 — this milestone)
+| Context | Headline | Subtext | CTA |
+|---------|----------|---------|-----|
+| Root folder (no folders yet) | "Start organizing your documents" | "Create a folder to group related files together." | "New folder" button |
+| Folder is empty (exists but has no contents) | "This folder is empty" | "Upload files here or move documents into this folder." | "Upload files" link (triggers DropZone click) |
+| Search returns no results | "No matches for '{query}'" | "Try a different search term or clear your search." | "Clear search" button |
+| Shared with me (no shares yet) | "Nothing shared with you yet" | "When someone shares a document with your handle, it appears here." | None (passive state) |
+| Topics list empty | "No topics yet" | "Topics are created automatically when you upload and classify a document." | None |
+| Audit log (admin, no entries yet) | "No audit events recorded" | "Events are recorded when users log in, upload documents, or make changes." | None |
+| Cloud storage — no connections | "No cloud storage connected" | "Connect OneDrive, Google Drive, Nextcloud, or WebDAV in Settings." | "Open Settings" link |
-- [ ] Email + password registration with strength validation — table stakes, nothing works without it
-- [ ] JWT sessions with refresh tokens + forced logout capability — security baseline
-- [ ] TOTP 2FA with backup codes — PROJECT.md requires it; backup codes prevent lockouts
-- [ ] Password reset via email — users will forget passwords
-- [ ] Per-user isolated storage (MinIO prefix per user ID) — without this, multi-user is unsafe
-- [ ] Quota tracking (DB) + enforcement at upload + visible indicator — table stakes for any quota system
-- [ ] Quota warnings at 80% and 95% — prevents users hitting the wall blindly
-- [ ] Create / rename / delete folders with breadcrumb navigation — table stakes file management
-- [ ] Move document to folder (context menu minimum; drag-drop in v1.x) — without this folder structure is useless
-- [ ] Sort by name/date/size — basic list management
-- [ ] Global search (metadata + extracted text) — without this the product is a dumb file cabinet
-- [ ] Share document with named user by handle (view-only default) — core sharing primitive
-- [ ] Revoke share with immediate effect — security; users must be able to undo shares
-- [ ] "Shared with me" virtual folder — PROJECT.md requires it
-- [ ] Cloud storage connect flow (Google Drive + OneDrive OAuth2) — PROJECT.md requires it
-- [ ] Connection status indicator + error state with local fallback — users need to know if cloud is broken
-- [ ] Default storage backend selector — users need to control where uploads go
-- [ ] Credential encryption (Fernet + env key) — PROJECT.md hard requirement
-- [ ] Admin: user list, create, deactivate, quota adjustment — PROJECT.md requires it
-- [ ] Admin: AI provider/model assignment per user + system default — PROJECT.md requires it
-- [ ] Audit log (append-only): auth events + data events — PROJECT.md requires it
-- [ ] Admin audit log viewer with date/user/action filters — PROJECT.md requires it
-- [ ] In-browser PDF preview (PDF.js or native) — without preview, users must download to read
-- [ ] Document metadata panel (size, date, topics, storage backend) — contextual information users expect
+Rule: every empty state that the user can resolve with an action gets exactly one CTA. Empty states that are passive (shared-with-me before anyone shares, topics before first upload, audit before any events) get explanatory subtext only — no CTA that leads nowhere useful.
-### Add After Core Validated (v1.x)
-
-- [ ] Share expiry date — valuable for security-conscious users; requires background job
-- [ ] Explicit share accept/decline — adds trust; low complexity
-- [ ] "What I've shared" global list in settings — users need to audit their shares
-- [ ] In-app share notification — without email infrastructure, in-app is the fallback
-- [ ] Storage usage breakdown by folder — power user feature; quota bar is sufficient at v1
-- [ ] CSV export of audit log — compliance teams want this; not day-one critical
-- [ ] Log retention policy configuration — needed for GDPR compliance; default 1yr is fine for v1
-- [ ] Drag-and-drop document move — UX polish; context menu is the functional minimum
-- [ ] "Recent documents" virtual view — convenience; not blocking
-
-### Future (v2+)
-
-- [ ] GDPR data export (Article 20) — required eventually; complex (async job); defer until user base exists
-- [ ] Per-document storage routing (override default per upload) — strong differentiator but complex; v2
-- [ ] User-facing activity log (own audit trail) — GDPR-aligned trust feature; v2
-- [ ] Soft-delete / Trash with restore — adds quota accounting complexity; solve properly in v2
-- [ ] Document version history — storage-intensive; needs a clear retention policy first
-- [ ] SSO / SAML — per PROJECT.md, after subscription billing
-- [ ] Public link sharing — per PROJECT.md, explicitly out of scope for v1
-- [ ] Platform health dashboard at /admin/health — operational convenience; Docker healthchecks handle v1
+Implementation: extract a shared `EmptyState.vue` presentational component that accepts `headline`, `subtext`, and an optional `action` slot. Use it in all seven contexts above instead of duplicating the layout.
---
-## Feature Prioritization Matrix
+## Loading State Patterns: Specific Decisions
-| Feature | User Value | Implementation Cost | Priority |
-|---------|------------|---------------------|----------|
-| Per-user auth (registration, login, JWT) | HIGH | LOW | P1 |
-| TOTP 2FA + backup codes | HIGH | MEDIUM | P1 |
-| Password reset | HIGH | LOW | P1 |
-| Quota tracking + enforcement + indicator | HIGH | LOW | P1 |
-| Quota warnings (80%, 95%) | HIGH | LOW | P1 |
-| Folder CRUD + breadcrumb | HIGH | LOW | P1 |
-| Move document to folder | HIGH | LOW | P1 |
-| Global search | HIGH | MEDIUM | P1 |
-| Share with named user (view-only) | HIGH | MEDIUM | P1 |
-| Revoke share | HIGH | LOW | P1 |
-| "Shared with me" folder | HIGH | LOW | P1 |
-| Cloud connect flow (OAuth2) | HIGH | HIGH | P1 |
-| Connection status + error state + local fallback | HIGH | MEDIUM | P1 |
-| Default storage selector | HIGH | LOW | P1 |
-| Credential encryption | HIGH | MEDIUM | P1 |
-| Admin user management (list/create/deactivate/quota) | HIGH | LOW | P1 |
-| Admin AI config | MEDIUM | LOW | P1 |
-| Audit log (append-only) | HIGH | MEDIUM | P1 |
-| Admin audit log viewer | MEDIUM | MEDIUM | P1 |
-| In-browser PDF preview | HIGH | MEDIUM | P1 |
-| Document metadata panel | MEDIUM | LOW | P1 |
-| Forced logout / session revocation | MEDIUM | MEDIUM | P2 |
-| Share expiry date | MEDIUM | MEDIUM | P2 |
-| Explicit share accept/decline | MEDIUM | LOW | P2 |
-| "What I've shared" list | MEDIUM | LOW | P2 |
-| Storage usage breakdown by folder | MEDIUM | MEDIUM | P2 |
-| CSV export of audit log | MEDIUM | LOW | P2 |
-| Log retention policy | MEDIUM | LOW | P2 |
-| Drag-and-drop move | MEDIUM | MEDIUM | P2 |
-| Recent documents view | LOW | LOW | P2 |
-| Per-document storage routing | HIGH | HIGH | P3 |
-| GDPR data export | MEDIUM | HIGH | P3 |
-| Soft-delete / Trash | MEDIUM | HIGH | P3 |
-| User-facing activity log | MEDIUM | LOW | P3 |
-| Document version history | LOW | HIGH | P3 |
-| Platform health dashboard | LOW | MEDIUM | P3 |
+| Component | Current | Target | Rationale |
+|-----------|---------|--------|-----------|
+| Document list (`StorageBrowser`) | `Loading…
` text | 6–8 skeleton rows (5-col grid, `animate-pulse`) | List loads on every folder navigation. Skeletons match the grid layout exactly, preventing layout jump. |
+| Sidebar folder tree | `Loading…
` text | 3 skeleton nav items (indent + placeholder bar) | Sidebar loads once on mount. Short skeleton is sufficient. |
+| Sidebar topics list | `Loading…
` text | 4 skeleton topic pills (color dot + bar) | Same rationale as folder tree. |
+| Admin user table | No loading state | Skeleton table rows (3–5 rows, matching column count) | Admin tables are data-heavy; skeleton preserves table chrome during load. |
+| Audit log table | No loading state | Skeleton rows matching timestamp/user/action columns | Same. |
+| Upload progress item | Spinner + progress bar (correct) | Keep as-is | Upload is a blocking action, not a content load. Spinners are correct for actions. |
+| QuotaBar | `animate-pulse` bar (correct) | No change | Already implemented correctly. Document as the canonical skeleton pattern. |
+| Document preview modal | None | Spinner centered in modal body | PDF proxy fetch is a single-request action. Spinner is correct. |
+
+Rule: if the loading UI represents content the user will read (list, table, tree), use a skeleton. If the loading UI represents a system action (save, upload, submit, process), use a spinner. Never show a loading state that will be visible for less than 300ms — add a minimum display delay.
---
-## Competitor Feature Analysis
+## Drag-and-Drop: Scope Boundaries
-| Feature | Google Drive | Dropbox | Box | Paperless-ngx | DocuVault Plan |
-|---------|--------------|---------|-----|----------------|----------------|
-| Share by named user | Yes (email) | Yes (email) | Yes (email + internal) | No (single-user) | Yes (by handle) |
-| Share permission levels | View / Comment / Edit | View / Edit | View / Edit / Co-owner | N/A | View-only v1; edit later |
-| Share expiry | Google Workspace only | Business+ only | Business+ free tier | N/A | Include in v1.x — differentiator at free tier |
-| Public link sharing | Yes | Yes | Yes | No | Explicitly excluded v1 |
-| Quota indicator | Yes (prominent) | Yes | Yes | N/A (local disk) | Yes — progress bar + text |
-| Quota warnings | Yes (email at 80%) | Yes (email at 90%) | Yes | N/A | In-app banner at 80%, 95% |
-| Folder organization | Yes (arbitrary depth) | Yes | Yes | Yes | Yes (arbitrary depth) |
-| Drag-and-drop move | Yes | Yes | Yes | Yes | v1.x (context menu at v1) |
-| Global search | Yes (full-text) | Yes (full-text) | Yes (full-text) | Yes (extracted text) | Yes (extracted text — already extracted) |
-| AI classification | No (manual labels) | No | No | Basic rules-based | Yes — core differentiator |
-| Audit log (admin) | Google Workspace | Business+ | All tiers | No | Yes — all tiers |
-| TOTP 2FA | Yes | Yes | Yes | Yes | Yes |
-| Backup codes | Yes | Yes | Yes | Yes | Yes — required with TOTP |
-| Bring-your-own storage | No | No | No | Partially (local FS) | Yes — core differentiator |
-| Privacy-first admin model | No (Google can read) | No | No | N/A (self-hosted) | Yes — core differentiator |
-| In-browser PDF preview | Yes | Yes | Yes | Yes | Yes (PDF.js) |
-| Document version history | Yes | Yes (30 days free) | Yes (30 days free) | No | v2 |
-| GDPR data export | Yes (Google Takeout) | Yes | Yes | N/A | v2 |
+### Build in v0.2
+
+1. **Whole-page drop overlay for file upload** — listen for `dragenter` at the document level, show a full-screen overlay, delegate the `drop` event to the existing DropZone emit chain. The drop must only activate when files are being dragged (check `e.dataTransfer.types.includes('Files')`).
+
+2. **Move a document to a folder by dragging the file row onto a folder row** — already implemented in `StorageBrowser.vue`. Verify it functions correctly and polish the drop highlight: `ring-2 ring-inset ring-amber-300` on the folder row is correct. Ensure the file row shows reduced opacity during drag (`opacity-50` already applied).
+
+### Do Not Build in v0.2
+
+- Dragging files from the file list onto sidebar folder entries (requires cross-component drag state via Pinia or provide/inject — the "Move to folder" picker already covers this)
+- Touch drag-and-drop on mobile (HTML5 drag events do not fire on iOS Safari without a polyfill library; defer to the move picker button)
+- Drag folders to reorder them
+
+### Required for every drag interaction
+
+- Visual affordance on dragover (already done on DropZone; add to whole-page overlay)
+- Non-drag alternative for every drag action: the "Move to folder" picker button covers the drag-to-move case
+- Drop must be clearly confirmed: file row disappears from source location and appears in target on success
---
-## Critical UX Patterns to Follow
+## Keyboard Shortcuts: Final List
-### Quota UX (from Drive / Dropbox study)
+| Shortcut | Action | Condition |
+|----------|--------|-----------|
+| `/` | Focus search bar | Not in an input, textarea, or contenteditable |
+| `Escape` | Close modal or clear active inline input | Modal open, or search focused with content |
+| `U` | Trigger file picker (upload) | Not in any input, on a folder/file manager view |
+| `N` | Start new folder inline input | Not in any input, on a folder/file manager view |
-**Sidebar quota bar pattern** (Drive): Always-visible storage indicator at the bottom of the left sidebar. Shows "X.X MB of Y MB used" with a color-coded bar (green → yellow → red as quota fills). This is the pattern users are conditioned to expect.
+### Do Not Build
-**Upload rejection UX**: Never show a generic error. Show: current usage, quota limit, how much the rejected file would have added, and a direct link to storage settings. Dropbox does this well; many self-hosted tools fail here.
-
-**Quota warning banner**: Non-modal, dismissable, but persistent. Appears at 80% — amber. At 95% — red. At 100% — blocks upload with inline error (not just a banner).
-
-### Folder UX (from Drive / Explorer pattern)
-
-**Breadcrumb is mandatory**: Any folder deeper than one level without a breadcrumb creates navigation confusion. Users instinctively hit "back" in their browser and are surprised to leave the app.
-
-**Empty folder state**: Show a clear empty state ("This folder has no documents yet. Upload one to get started.") — not a blank white space.
-
-**Delete folder confirmation must list contents**: "Are you sure? This will permanently delete 47 documents." — not just a generic "are you sure?"
-
-### Sharing UX (from Box / Drive)
-
-**Share dialog anti-pattern to avoid**: Auto-sending share notifications without preview. Drive's "A notification will be sent" with an optional message is the correct pattern — user controls whether to notify.
-
-**Shared document visual indicator**: An icon overlay (people icon) in list view on shared items. Without this, users lose track of what they've shared. Drive and Box both do this.
-
-**Revoke is immediate and feedback is given**: "Access revoked for user@handle" toast. Not silent.
-
-### Cloud Integration UX (from Dropbox Business / Google Drive)
-
-**Connection health must be persistent**: Don't only show errors at connect time. Show ongoing status in storage settings. A disconnected cloud backend that silently fails uploads is a data-loss scenario.
-
-**Token expiry is silent without handling**: OAuth2 tokens expire. If the app doesn't handle refresh silently (or at least alert the user clearly), users will think their uploads succeeded when they didn't. **This is a critical pitfall.**
+- `J`/`K` for row-by-row navigation — requires focus management, ARIA selected state, and keyboard event bubbling control. Over-engineered for a vault where opening a document is secondary to browsing and uploading.
+- `Ctrl+A` / `Cmd+A` for select all — requires multi-select, which is an anti-feature.
+- Arrow key tree navigation in the sidebar — screen readers handle this natively; custom arrow-key navigation would conflict with browser defaults.
+- `?` shortcut for a shortcut reference modal — too few shortcuts to warrant a help overlay.
---
-## What We Might Miss (Gap Analysis)
+## Responsive Layout: Breakpoint Decisions
-Items that competitors have which aren't in PROJECT.md Active requirements and are easy to overlook:
+| Viewport | Tailwind breakpoint | Sidebar | Document list | Admin |
+|----------|---------------------|---------|--------------|-------|
+| Mobile portrait | `< 640px` (below `sm`) | Hidden; hamburger button + overlay drawer | Icon + name only; Size (`hidden md:block`) and Modified (`hidden sm:block`) hidden | Same drawer |
+| Mobile landscape / small tablet | `640–767px` (`sm`) | Hidden; hamburger still active | Icon + name + Modified visible; Size hidden | Same |
+| Tablet portrait | `768–1023px` (`md`) | Hidden; hamburger still active | Full 5-col grid | Full columns |
+| Tablet landscape / small desktop | `1024px+` (`lg`) | Always visible (256px fixed) | Full 5-col grid | Full admin sidebar + content |
+| Desktop | `1280px+` (`xl`) | Always visible | Full grid + comfortable padding | Full layout |
-1. **Backup codes for TOTP** — PROJECT.md mentions TOTP but not backup codes. Without backup codes, a lost phone = permanently locked-out account. Every 2FA implementation must include these. HIGH severity omission.
+Key decision: sidebar collapses at the `lg` breakpoint (1024px), using `hidden lg:flex` on the sidebar and `lg:hidden` on the hamburger button. At 1024px the sidebar (256px) leaves 768px for content — sufficient for the 5-column grid with room for padding.
-2. **Quota warning thresholds** — PROJECT.md says "quota enforced; uploads rejected." It doesn't mention pre-emptive warnings at 80%/95%. Users who hit the wall without warning give negative reviews. Easy to implement; easy to forget.
+Touch targets: all inline action icon buttons are currently `p-1.5` (approximately 30px). Increase to `p-2` on `sm:` and below using responsive padding classes. 44px is the WCAG target — not achievable for inline buttons without breaking the grid layout, but 36px is a reasonable minimum.
-3. **Session revocation / forced logout** — Not in PROJECT.md. JWT-based auth has no built-in revocation. If a user believes their account is compromised, they need "sign out everywhere." Requires either short-lived JWTs + refresh token table, or a server-side revocation list.
+---
-4. **Breadcrumb navigation** — Easy to forget in folder implementation. The folder CRUD is in PROJECT.md but the navigation UX isn't. Without breadcrumbs, nested folders become unusable.
+## Feature Dependencies (summary)
-5. **"What I've shared" list** — PROJECT.md covers sharing mechanics but doesn't cover share auditability from the sharer's perspective. Users who've shared many documents need a way to manage them all.
+```
+Admin route subtree
+ → AdminLayout.vue (new) contains AdminSidebar.vue (new) +
+ → Child views wrap existing AdminUsersTab, AdminQuotasTab, AdminAiConfigTab, AuditLogTab
+ → AdminView.vue deleted after migration
-6. **Upload error when cloud backend is unreachable** — PROJECT.md says "documents stored in cloud backend accessed via app." What happens if the cloud backend is down at upload time? Needs explicit handling: local fallback with a flag, or queue with retry, or reject with explanation. Silence = data loss.
+Empty states
+ → New EmptyState.vue (presentational, accepts headline/subtext/action slot)
+ → Used in StorageBrowser.vue, SharedView.vue, TopicsView.vue, CloudStorageView.vue, AuditLogTab.vue
-7. **MinIO presigned URL vs proxy for document access** — Not a feature gap but an architecture gap that affects features: if documents in cloud backends are accessed via presigned URLs, the URL leaks the storage path. If proxied through the app, privacy is preserved but adds load to the backend. For a privacy-first platform, proxy is the correct choice — but it must be a conscious decision before the cloud integration is built.
+Skeleton rows
+ → New SkeletonRow.vue (5-col grid, animate-pulse)
+ → Used in StorageBrowser.vue (document list), AppSidebar.vue (folder tree, topics list)
-8. **Empty folder state and confirmation dialogs** — Micro-UX that competitors all get right. Easy to skip in implementation. Users notice.
+Keyboard shortcuts
+ → Global keydown listener in FileManagerView.vue
+ → SearchBar.vue exposes focus() method
+ → DropZone.vue exposes triggerInput() (already exists as triggerInput())
+ → StorageBrowser.vue exposes startNewFolder() (already defineExposed)
-9. **Shared document icon in list view** — Small visual indicator but prevents users from losing track of what they've shared. Three lines of CSS; easy to miss in sprint planning.
+Mobile sidebar
+ → App.vue holds sidebarOpen boolean state
+ → AppSidebar.vue accepts isOpen prop + emits close
+ → Hamburger button in App.vue header (mobile only, hidden lg:hidden)
-10. **Admin cannot set quota below current usage without warning** — Obvious in hindsight but easy to leave as a silent truncation. Must warn and require explicit confirmation.
+Whole-page drop overlay
+ → New PageDropOverlay.vue (full-screen overlay, accepts active prop)
+ → FileManagerView.vue listens for document dragenter/dragleave
+ → On drop, delegates to existing upload flow via onFilesSelected
+```
---
## Sources
-- Google Drive feature set: training knowledge through Aug 2025 (stable, well-documented product)
-- Microsoft OneDrive feature set: training knowledge through Aug 2025
-- Dropbox feature set: training knowledge through Aug 2025
-- Box feature set: training knowledge through Aug 2025 (enterprise DMS reference)
-- Notion: training knowledge through Aug 2025 (organization patterns)
-- Paperless-ngx: training knowledge through Aug 2025 (self-hosted DMS reference — open source, well-documented)
-- DocuWare: training knowledge through Aug 2025 (enterprise DMS reference)
-- Web fetch and web search unavailable during this research session; confidence reduced to MEDIUM for specific UI detail claims; HIGH for feature existence claims (these are all mature, stable platforms)
-
----
-*Feature research for: DocuVault — SaaS Document Management Platform*
-*Researched: 2026-05-21*
+- Vue Router 4 nested routes: https://router.vuejs.org/guide/essentials/nested-routes
+- Skeleton screens vs. spinners UX: https://www.onething.design/post/skeleton-screens-vs-loading-spinners
+- Skeleton loading screen design: https://blog.logrocket.com/ux-design/skeleton-loading-screen-design/
+- SaaS empty state patterns: https://pixxen.com/saas-empty-state-design/
+- IBM Carbon Design System empty states: https://carbondesignsystem.com/patterns/empty-states-pattern/
+- Drag-and-drop SaaS UX: https://www.eleken.co/blog-posts/drag-and-drop-ui
+- Drag-and-drop NN/g guidelines: https://www.nngroup.com/articles/drag-drop/
+- Responsive SaaS breakpoints: https://tryhoverify.com/blog/responsive-design-breakpoints-2024-guide/
+- Keyboard shortcut design for web apps: https://sashika.medium.com/j-k-or-how-to-choose-keyboard-shortcuts-for-web-applications-a7c3b7b408ee
+- Nextcloud layout patterns: https://docs.nextcloud.com/server/latest/developer_manual/design/layout.html
+- Paperless-ngx frontend architecture: https://deepwiki.com/paperless-ngx/paperless-ngx/2-frontend-architecture
diff --git a/.planning/research/PITFALLS.md b/.planning/research/PITFALLS.md
index 3ad6e18..85f10e7 100644
--- a/.planning/research/PITFALLS.md
+++ b/.planning/research/PITFALLS.md
@@ -1,550 +1,290 @@
-# Pitfalls Research
+# Domain Pitfalls — v0.2 UI Overhaul and Optimization
-**Domain:** Multi-user SaaS document management platform (FastAPI + Vue 3, PostgreSQL + MinIO, cloud storage integrations)
-**Researched:** 2026-05-21
-**Confidence:** HIGH (auth/storage/multi-tenancy patterns are well-established; specific FastAPI + MinIO combination is MEDIUM — no web search available)
+**Project:** DocuVault
+**Milestone:** v0.2 — UI Overhaul and Optimization on existing FastAPI + Vue 3 app
+**Researched:** 2026-06-07
+**Confidence:** HIGH (all pitfalls grounded in actual source files: router/index.js, App.vue, main.py, client.js, StorageBrowser.vue, DocumentCard.vue, DropZone.vue, AppSidebar.vue, and all api/*.py router files)
---
## Critical Pitfalls
-### Pitfall 1: JWT in localStorage — XSS Gives Full Account Takeover
+Mistakes that cause regressions, security gaps, or rewrites.
+
+---
+
+### Pitfall 1: FastAPI Router Splitting — Prefix Already Embedded in APIRouter, Not in include_router
+
+**Phase:** Backend refactoring (split large router files)
+
+**What goes wrong:** Every existing router in this codebase declares its prefix on the `APIRouter` instance itself — `router = APIRouter(prefix="/api/documents", tags=["documents"])` — NOT on the `include_router(router, prefix=...)` call in `main.py`. When splitting a large file (e.g. `documents.py` at 852 lines, `admin.py` at 934 lines) into sub-modules, the new sub-routers pick up their endpoints via an `include_router` call inside the original module, or they are wired directly in `main.py`. Either way, if you add a prefix on `include_router` in addition to the prefix on the inner `APIRouter`, all URLs double-prefix to `/api/documents/api/documents/...`. Likewise, if you strip the prefix from the inner router and forget to add it to `include_router`, all URLs return 404.
+
+**Why it happens:** The original pattern (`router = APIRouter(prefix=...)` in the module + `app.include_router(router)` without a prefix in `main.py`) is unusual but consistent in this project. Developers splitting a file expect the standard pattern where prefixes go on `include_router`, not on the router definition.
+
+**Consequences:** 404 on all endpoints in the split module; existing tests and the frontend `client.js` (which hard-codes `/api/documents`, `/api/admin`, etc.) silently break.
+
+**Prevention:** When splitting, create sub-routers with NO prefix: `sub = APIRouter(tags=["documents-upload"])`. Register them inside the parent module with `router.include_router(sub)` so the parent's prefix propagates. The parent module keeps its existing prefix and its existing `app.include_router(parent)` call in `main.py` is unchanged.
+
+**Detection warning signs:** Any test that calls `/api/documents/*` returns 404 immediately after the split; Swagger UI shows doubled path segments.
+
+---
+
+### Pitfall 2: FastAPI Router Splitting — Circular Import via Shared Dependencies
+
+**Phase:** Backend refactoring
+
+**What goes wrong:** `folders.py` already exports a `document_move_router = APIRouter(prefix="/api/documents")` — a cross-cutting concern documented in the file (line 439-442). When splitting `documents.py`, if the new sub-module imports anything from `api/folders.py` (e.g. a shared validator or Pydantic schema), Python raises `ImportError: cannot import name X` at startup because both modules are in partial initialization state.
+
+**Why it happens:** FastAPI modules that share models and validators tend to grow cross-references. The `document_move_router` in `folders.py` under the `/api/documents` prefix is the existing example — any new import in the opposite direction closes the import cycle.
+
+**Consequences:** Application fails to start. Docker container exits immediately.
+
+**Prevention:** Shared Pydantic models and validators must live in `db/models.py` or a dedicated `schemas/` module — not in router files. Before splitting, grep for any `from api.X import` inside the router files being split and move the shared symbols to a neutral module first.
+
+**Detection warning signs:** `ImportError` or `cannot import name` in the uvicorn startup log.
+
+---
+
+### Pitfall 3: AdminLayout Vue Router Integration — beforeEach Guard Misses /admin/* Children
+
+**Phase:** Admin panel rearchitecture
+
+**What goes wrong:** The current guard in `router/index.js` (lines 81-93) checks `to.meta.requiresAdmin` on the matched route object. The current `/admin` route is a flat route with that meta set directly. When `/admin` becomes a parent route with nested children (`/admin/users`, `/admin/audit`, etc.), the children do NOT automatically inherit `meta: { requiresAdmin: true }` from the parent in Vue Router 4 unless the guard iterates `to.matched`. If the children are added without repeating the meta, the guard's `to.meta.requiresAdmin` check evaluates to `undefined` (falsy) for every child route — non-admin users can navigate to `/admin/users` directly.
+
+**Why it happens:** Vue Router 4 does NOT merge parent `meta` into child `meta` by default. `to.meta` reflects only the deepest matched route's own meta, not the parent's.
+
+**Consequences:** Security regression — the admin guard that currently works correctly stops protecting all admin child routes. Non-admin users can access `/admin/users`, `/admin/audit`, etc.
+
+**Prevention:** Update the guard to check `to.matched.some(r => r.meta.requiresAdmin)` instead of `to.meta.requiresAdmin`. This is the correct Vue Router 4 idiom for inherited meta and requires one change to the guard. Apply the same fix to the `!to.meta.public` check if any auth routes gain children.
+
+```javascript
+// router/index.js — change:
+if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
+// to:
+if (to.matched.some(r => r.meta.requiresAdmin) && authStore.user?.role !== 'admin') {
+```
+
+---
+
+### Pitfall 4: AdminLayout Integration — App.vue Layout Switch Breaks for /admin/* Routes
+
+**Phase:** Admin panel rearchitecture
+
+**What goes wrong:** `App.vue` currently switches between `AuthLayout` (when `route.meta.layout === 'auth'`) and the main app shell (sidebar + ``) for everything else. The admin panel needs a third layout (`AdminLayout`) with its own nav. The naive approach — `v-else-if="route.meta.layout === 'admin'"` in `App.vue` rendering `AdminLayout` which then renders `` — creates double rendering: `App.vue`'s `` already resolved the full route. The inner `` inside `AdminLayout` gets nothing because the route is already consumed.
+
+**Consequences:** Admin layout renders with an empty content area, or the admin page renders without the admin chrome.
+
+**Prevention:** The correct structure for a standalone admin layout in Vue Router 4:
+
+```javascript
+// router/index.js
+{
+ path: '/admin',
+ component: AdminLayout, // resolves to the layout shell, which contains
+ meta: { requiresAdmin: true },
+ children: [
+ { path: '', redirect: '/admin/users' },
+ { path: 'users', component: AdminUsersView },
+ { path: 'quotas', component: AdminQuotasView },
+ { path: 'ai', component: AdminAiView },
+ { path: 'audit', component: AdminAuditView },
+ ]
+}
+```
+
+`AdminLayout.vue` contains `` where page content renders. `App.vue` remains unchanged — it renders the component that the route resolves to, which is now `AdminLayout`. No third branch in `App.vue` is needed.
+
+---
+
+### Pitfall 5: client.js Splitting — noRefreshPaths Breaks When Paths Move to Sub-modules
+
+**Phase:** Frontend refactoring (client.js split)
+
+**What goes wrong:** `client.js` has a hardcoded `noRefreshPaths` list inside `request()` (line 26) that guards against infinite refresh loops. If `request()` is moved to a shared `api/core.js` module and the path list stays there, it works. But the three blob-download functions (`adminExportAuditLogCsv`, `adminDownloadDailyExport`, `fetchDocumentContent`) each contain a duplicated copy of the 401-refresh-retry logic. When splitting `client.js` into domain files, those duplicates will be copied into new sub-files. This is the correct moment to eliminate them — but if missed, the bug surface multiplies.
+
+**Additionally:** If components are changed to import from sub-files directly (e.g. `import { listDocuments } from '../api/documents.js'`) instead of the barrel, every other component that imports from `client.js` still works — but a future refactor that renames a function in the sub-file will miss the barrel re-export and break components that still use the barrel. Both import paths exist simultaneously and diverge.
+
+**Prevention:** Split in this order:
+1. Extract `request()` + `noRefreshPaths` into `api/core.js`. Export `request` from there.
+2. Extract the 401-retry pattern from the three blob-download functions into a single `fetchWithRetry(url, headers)` helper also in `api/core.js`.
+3. Create domain files (`api/documents.js`, `api/admin.js`, `api/auth.js`, etc.) that import from `api/core.js`.
+4. Keep `api/client.js` as a re-export barrel: `export * from './documents.js'; export * from './admin.js'` etc. This preserves all existing `import { listDocuments } from '../api/client.js'` calls without touching any component. Never change component imports to point at sub-files directly.
+
+---
+
+### Pitfall 6: Drag-and-Drop on DocumentCard — dragstart vs @click Conflict
+
+**Phase:** UX improvements (drag-and-drop)
+
+**What goes wrong:** `DocumentCard.vue` navigates on `@click="$router.push('/document/' + doc.id)"` (line 4). Browsers fire `click` after `dragend` when the drag distance is below the browser's drag-initiation threshold — typically ~4px. A user who clicks and releases without moving far enough triggers both `dragstart` and then `click`: the card navigates to the document even though the user intended to start a drag.
+
+**Also:** The action buttons inside `DocumentCard` use `@click.stop`. If a drag handle overlaps an action button area, `@click.stop` prevents the click from propagating but does not prevent `dragstart` from bubbling — behavior becomes inconsistent depending on which pixel the user starts from.
+
+**Note:** `StorageBrowser.vue` already implements drag-and-drop on list rows correctly (lines 141-145: `draggable`, `@dragstart`, `@dragend`) and does not have this problem because the row's `@click` emits `file-open` rather than navigating imperatively. The risk is specific to adding drag to `DocumentCard.vue` (card grid used in `TopicsView`).
+
+**Prevention:**
+1. Track drag state with a component-level `dragging` ref. Set `dragging = true` in `@dragstart`, reset to `false` in `@dragend`. Guard `@click`: `if (this.dragging) return`.
+2. Preferred: use a dedicated drag handle element (grip icon, `cursor-grab`) and set `draggable="true"` only on that element. Add `@click.stop` on the handle. The rest of the card retains click-to-navigate.
+
+---
+
+### Pitfall 7: Virtual Scrolling — StorageBrowser DOM Assumptions Break
+
+**Phase:** Frontend performance (virtual scrolling)
**What goes wrong:**
-The Vue 3 SPA stores the JWT access token in `localStorage`. Any JavaScript injected via XSS (in file names, document content previewed in the UI, a compromised dependency) can call `localStorage.getItem('token')` and exfiltrate a long-lived credential. The attacker then impersonates the user from any origin, bypasses TOTP entirely (the token is post-authentication), and can access all documents, including cloud storage credentials.
-**Why it happens:**
-`localStorage` is the path of least resistance in SPAs. It survives page reloads, works with Axios interceptors trivially, and requires no server-side session state. FastAPI tutorials almost universally use `Authorization: Bearer` headers set from localStorage.
+`StorageBrowser.vue` renders its item list with `divide-y divide-gray-100` (line 76). The Tailwind `divide-y` utility inserts borders using adjacent-sibling CSS (`& > * + * { border-top-width: 1px }`). This only works when all children are present in the DOM simultaneously. Virtual scroll libraries keep only visible rows in the DOM — `divide-y` produces borders only between the visible subset, leaving gaps at virtual boundaries.
-**How to avoid:**
-- Issue the JWT as an **httpOnly, SameSite=Strict, Secure cookie** — JavaScript cannot read it.
-- Use a short-lived access token (15 minutes) in the httpOnly cookie.
-- Issue a separate refresh token (httpOnly cookie, longer TTL, `/auth/refresh` path-scoped) to rotate access tokens silently.
-- The Vue frontend never holds the raw token string. Axios is configured with `withCredentials: true`; the browser attaches cookies automatically.
-- CSRF protection: because `SameSite=Strict` blocks cross-site cookie submission, CSRF tokens are not strictly required for same-origin SPAs, but add a CSRF header check (`X-Requested-With: XMLHttpRequest`) as defence-in-depth.
+The folder picker dropdown inside file rows (lines 185-213) is `absolute right-0 top-full` — positioned relative to its parent row. Virtual scroll repositions rows via `transform: translateY()`. Absolutely positioned children escape their transformed parent and appear at wrong viewport positions.
-**Warning signs:**
-- `localStorage.getItem` anywhere in auth-related frontend code
-- JWT decode functions in frontend code (the frontend should not need to decode a token it can't read)
-- `Authorization: Bearer ${token}` header set manually in Axios interceptor
+CSS transitions on rows (`transition-all`, `transition-colors`) work with `v-for` because Vue animates DOM insertion/removal. Virtual scroll does not insert/remove — it repositions. Vue's `` cannot wrap a virtually scrolled list and will throw warnings.
-**Phase to address:** Auth phase (Phase 1 — Users & Auth)
+**Prevention:**
+1. Replace `divide-y` with `border-b border-gray-100` on each individual row element. Rows become self-contained and do not depend on DOM adjacency.
+2. The folder picker dropdown must use `` with `position: fixed` coordinates computed from `getBoundingClientRect()`. This is a prerequisite for virtual scroll adoption, not optional.
+3. Remove any `` wrapping a virtually scrolled list. Use per-row fade-in via a CSS class added on first mount instead.
---
-### Pitfall 2: TOTP Bypass via Password Reset Flow
-
-**What goes wrong:**
-The password reset flow issues a one-time token by email. After the user resets their password, the system logs them in and redirects to the dashboard — skipping the TOTP prompt because the session was created through the reset path, not the login path. An attacker who compromises a user's email account can therefore completely bypass TOTP.
-
-**Why it happens:**
-Password reset and login are treated as separate code paths. The TOTP check lives in the login handler; the reset handler creates a session directly after credential update without going through the TOTP gate.
-
-**How to avoid:**
-- After a successful password reset, issue a partial session or a `password_reset_pending` state, not a full authenticated session.
-- Force the user to complete the full login flow (including TOTP if enabled) from the new credentials.
-- Alternatively, on password reset completion, invalidate all existing sessions and send the user to the login page (no auto-login).
-- Log password resets in the audit trail with IP and user-agent.
-
-**Warning signs:**
-- Password reset handler calls the same session-creation function as login but omits 2FA state checks
-- No `mfa_verified` flag on sessions (only `authenticated`)
-- Users can reach protected endpoints via a token created from the reset path
-
-**Phase to address:** Auth phase (Phase 1 — Users & Auth)
+## Moderate Pitfalls
---
-### Pitfall 3: Refresh Token Rotation — Stolen Refresh Token Not Detected
+### Pitfall 8: Responsive Layout — w-64 Sidebar vs Flex-1 Content on Mobile
-**What goes wrong:**
-Refresh tokens are issued as single-use rotating credentials. If an attacker steals a refresh token and uses it before the legitimate user does, the server rotates the token and the attacker has a valid new one. The legitimate user's next refresh request fails — but without a detection mechanism the failure just looks like a session expiry, no alert is raised, and the attacker continues with the stolen session indefinitely.
+**Phase:** Responsive / mobile layout
-**Why it happens:**
-Teams implement the "rotate on use" mechanic without implementing the "revoke family on reuse" detection. The `refresh_tokens` table lacks a `family_id` column linking reissued tokens.
+**What goes wrong:** `App.vue` uses `flex h-screen overflow-hidden` with `AppSidebar` fixed at `w-64 shrink-0`. On screens narrower than ~320px the content area collapses below usable width. `StorageBrowser`'s 5-column grid `grid-cols-[2rem_1fr_6rem_8rem_6rem]` has `hidden sm:block` and `hidden md:block` to hide size and date columns — but the fixed `2rem` icon and `6rem` action columns still consume 128px on either side of the filename, leaving minimal space on a 375px screen.
-**How to avoid:**
-- Store refresh tokens in the database with a `family_id` (UUID for the original issuance chain) and a `revoked` flag.
-- When a refresh token is presented: if it is already marked `revoked` (i.e., a previously rotated token), revoke the **entire family** — force logout of all sessions for that user.
-- Emit a security alert (audit log + optionally email) when a reuse attempt is detected.
-- Refresh tokens should be hashed before storage (bcrypt or SHA-256 with a per-row salt), same as passwords.
-
-**Warning signs:**
-- Refresh tokens stored as plain values in DB with no `revoked` column
-- No `family_id` linking related rotation chains
-- Stolen refresh token detection treated as "v2 feature"
-
-**Phase to address:** Auth phase (Phase 1 — Users & Auth)
+**Prevention:**
+1. On mobile (`< lg`), hide the sidebar. Use a hamburger button in a mobile-only header bar. Toggle with `translate-x-0 / -translate-x-full` transition on the sidebar element.
+2. The sidebar open/closed state needs to be in a Pinia store ref (or provided from `App.vue`) so the hamburger button in the header, the sidebar overlay, and the main content area all react to it. Do not put it in a component's `data()`.
+3. On mobile, simplify the grid to `grid-cols-[2rem_1fr_4rem]` — filename and a single action column. Test at 375px explicitly.
---
-### Pitfall 4: TOTP — Timing Attack on Code Verification
+### Pitfall 9: Admin Panel + Responsive — Double Padding After Extracting Tab Content
-**What goes wrong:**
-TOTP verification uses Python `==` string comparison. Python's `==` on strings is not constant-time — it short-circuits on the first differing character. A sufficiently sophisticated timing oracle (millions of requests from a local network) can distinguish valid from invalid codes, reducing the 6-digit brute-force space. More practically: without rate limiting, an attacker can brute-force all 1,000,000 possible 6-digit codes during a 30-second window.
+**Phase:** Admin panel rearchitecture + responsive layout (interaction pitfall)
-**Why it happens:**
-TOTP libraries (PyOTP) return a string; developers do `if provided == expected`. Rate limiting is added "later" and often never lands.
+**What goes wrong:** `AdminView.vue` wraps all content in `p-8 max-w-5xl mx-auto`. Each tab component (`AdminUsersTab.vue`, `AdminQuotasTab.vue`, etc.) has its own internal padding. When tab components are extracted into standalone page views (`AdminUsersView.vue`, etc.), the `p-8 max-w-5xl mx-auto` wrapper moves to `AdminLayout.vue`. If the extracted page views retain their own inner padding, content is double-padded. If `AdminLayout` does not include the constraint, the new admin pages render full-bleed against the viewport.
-**How to avoid:**
-- Use `hmac.compare_digest(provided, expected)` instead of `==` for TOTP comparison.
-- Rate-limit TOTP attempts: 5 attempts per 30-second window, 15-minute lockout on excess.
-- The lockout must be stored server-side (Redis or DB), not client-side.
-- Accept only the current window and optionally ±1 window for clock drift — do not accept wider ranges.
-- Log every failed TOTP attempt with IP.
-
-**Warning signs:**
-- `if totp.verify(code):` without inspecting PyOTP's internal comparison method
-- No rate limit on `POST /auth/totp/verify`
-- TOTP window set to 2+ (default is ±1 window = 90 seconds valid — wider than needed)
-
-**Phase to address:** Auth phase (Phase 1 — Users & Auth)
+**Prevention:** When extracting tab components into page views, strip all top-level padding and `max-w` from the extracted component — those belong to `AdminLayout`'s content area. The page components should fill 100% of the space provided by the layout slot.
---
-### Pitfall 5: Path Traversal in User File Access (MinIO Object Keys)
+### Pitfall 10: Options API Refactoring — Prop Mutation via v-model
-**What goes wrong:**
-MinIO object keys are constructed from user input: `f"users/{user_id}/{filename}"`. If `filename` contains `../`, `../../`, or URL-encoded equivalents (`%2e%2e%2f`), the resulting key may escape the user's prefix and land in another user's namespace. A request for `../../other_user_id/secret.pdf` resolves to `users/other_user_id/secret.pdf`.
+**Phase:** Frontend refactoring (Vue component decomposition)
-**Why it happens:**
-Developers trust that MinIO will sanitize paths. It does not — S3-compatible APIs treat object keys as arbitrary strings. The prefix-based isolation is only as safe as the key construction code.
+**What goes wrong:** If a component receives a prop and binds it directly to ``, Vue emits a prop mutation warning in development. In production (no warnings), the mutation silently fails to propagate: the component's displayed value updates (local vdom), but the parent never receives the change because no `update:propName` event was emitted.
-**How to avoid:**
-- Never use raw filenames as object key components. Generate a UUID (or UUID + original extension) as the stored key: `f"users/{user_id}/{uuid4()}{ext}"`.
-- Store the human-readable filename in the database metadata row, completely decoupled from the storage key.
-- If filenames must appear in keys for any reason, strip or reject any `/`, `\`, `..`, `%` characters before key construction.
-- On retrieval, look up the object key from the database row (which is owned by `user_id`) rather than constructing it from user input.
+**Specific risk in this codebase:** `AdminUsersTab`, `AdminQuotasTab`, and `AuditLogTab` currently own their filter/search state internally. When extracted into standalone views, these may receive initial state from route query params and accidentally bind those props directly to inputs.
-**Warning signs:**
-- `object_key = f"users/{user_id}/{request.filename}"`
-- File download endpoint accepts a `path` or `filename` query parameter and constructs the key from it
-- No database lookup intermediating between "user requests file" and "MinIO key used"
-
-**Phase to address:** Storage migration phase (Phase 2 — DB + MinIO migration)
+**Prevention:** Any input the component controls must bind to a local `data()` copy initialized from the prop: `data() { return { localFilter: this.initialFilter } }`. Emit `update:initialFilter` on change. Never write `v-model="$props.X"`.
---
-### Pitfall 6: Quota Race Condition — Concurrent Uploads Bypass the Limit
+### Pitfall 11: Options API Refactoring — data() vs computed() in Decomposed Components
-**What goes wrong:**
-Two upload requests arrive simultaneously for a user at 99 MB of a 100 MB quota. Both read quota usage as 99 MB, both pass the `99 + 1 < 100` check, both proceed to upload — the user ends at 101 MB. At larger scale (many simultaneous large uploads) the overage can be significant.
+**Phase:** Frontend refactoring
-**Why it happens:**
-Quota enforcement is implemented as: read current usage → check → write file → update usage. This is a classic check-then-act race when the check and the write are not atomic.
+**What goes wrong:** When extracting a large component, logic that was a `computed()` in the parent often gets copy-pasted into a child's `data()`. A `data()` value initializes once at mount — it does not react to prop changes. If the parent later passes a different prop value (e.g. the document list changes after a search), the child's stale `data()` copy never updates.
-**How to avoid:**
-- Enforce quota atomically using a `SELECT ... FOR UPDATE` on the quota row before uploading, or use a PostgreSQL advisory lock keyed on `user_id`.
-- Better: use an optimistic update: `UPDATE quotas SET used_bytes = used_bytes + $new WHERE user_id = $uid AND used_bytes + $new <= limit_bytes RETURNING used_bytes`. If 0 rows are updated, the quota was exceeded — reject before touching MinIO.
-- Only update `used_bytes` after the MinIO upload succeeds, but hold the lock/reservation through the upload, or use a two-phase: reserve bytes → upload → confirm, with a cleanup job for stuck reservations.
-- Never read quota, do arithmetic in Python, then write back as two separate statements.
-
-**Warning signs:**
-- `current = get_quota(user_id); if current + size <= limit: upload()`
-- No database transaction wrapping quota check and update
-- Quota table updated with `SET used_bytes = $computed_value` (full overwrite) rather than `used_bytes + delta`
-
-**Phase to address:** Storage migration phase (Phase 2 — DB + MinIO migration) and Quotas phase
+**Prevention:** For every value in a newly created component, ask: "If the parent passes a different value for this prop, should the child update?" Yes → `computed()`. No → `data()`. Initialized from prop but locally modified afterward → `data()` with a `watch` on the prop to reset when it changes externally.
---
-### Pitfall 7: Admin Privilege Escalation via Missing Ownership Checks
+### Pitfall 12: Keyboard Shortcuts — Conflict with Text Inputs and Browser Defaults
-**What goes wrong:**
-An admin API endpoint is gated on `is_admin=True` but document-access endpoints only check `is_authenticated`. An admin user calling `GET /api/documents/{id}` with any document ID can read any user's document because the handler checks authentication but not `document.owner_id == current_user.id`. The privacy-first model is violated without any special exploit — just a correctly authenticated request.
+**Phase:** UX improvements (keyboard shortcuts)
-**Why it happens:**
-Authorization is implemented as authentication + role checks ("is this user an admin?") without resource-level ownership verification ("does this user own this resource?"). FastAPI dependency injection makes it easy to write `current_user = Depends(get_current_user)` and forget to check `resource.user_id == current_user.id`.
+**What goes wrong:** A global `keydown` listener on `window` fires regardless of focused element. Shortcuts like `/` (focus search), `n` (new folder), `Delete` (delete selected) are also typed characters. They must not fire when any ``, `