Skip to content

Latest commit

 

History

History
1146 lines (757 loc) · 44.4 KB

API.md

File metadata and controls

1146 lines (757 loc) · 44.4 KB

TuneForge API

Overview

The desktop backend exposes a local FastAPI API under /api/v1. It is intended for the bundled TuneForge frontend on the same machine and binds to 127.0.0.1 by default.

This document summarizes the current route surface. The generated OpenAPI schema in packages/shared-types/openapi.json remains the implementation source of truth for exact schemas and generated TypeScript types.

Conventions

  • Base path: /api/v1
  • Request and response format: JSON unless an endpoint streams a file.
  • IDs: string identifiers generated by the backend.
  • Timestamps: ISO 8601 strings in API responses.
  • Errors use a structured error object with code, message, and details.

Pagination Contract

Endpoints that expose growable collections use offset pagination. Endpoint-specific follow-ups should add this contract without renaming the existing list field, so generated OpenAPI clients keep a predictable response shape.

Request query parameters:

  • limit - page size, default 50, minimum 1, maximum 200.
  • offset - zero-based row offset, default 0, minimum 0.

Existing search and filter parameters apply to the full matching collection before total, limit, and offset are applied.

Response fields:

  • the existing list field, such as projects or jobs.
  • total - count after search and filters, before pagination.
  • limit - the effective limit used for this response.
  • offset - the effective offset used for this response.
  • has_more - true when offset + <returned count> < total.

Example:

{
  "projects": [],
  "total": 125,
  "limit": 50,
  "offset": 0,
  "has_more": true
}

Paginated endpoints must document their default sort and any supported client-selected sort keys. Sorting must be deterministic across repeated requests: timestamp, status, search-rank, or other non-unique sort keys need a stable tie-breaker, normally the entity's immutable ID. For example, newest-first pages should sort by updated_at DESC, id DESC instead of timestamp alone. If a sort key can be null, the endpoint must also document where null values appear.

Pagination Endpoint Audit

This audit captures the current list-like API surface. Individual endpoint sections later in this document describe current pagination behavior or explicit unpaginated exceptions.

Endpoint or payload List field Pagination decision
GET /api/v1/jobs jobs Paginated growable list with status, project_id, and project-name search filters plus sort_by/sort_order. Default ordering is active-first and deterministic.
POST /api/v1/jobs/bulk created_jobs, skipped Explicit unpaginated bounded bulk-action result. The response is bounded by the current project library and the requested job type.
GET /api/v1/projects projects Paginated growable list. search filters the full matching collection before pagination. Default ordering is updated_at DESC, id DESC. Desktop Library consumers should lazy-load this list.
GET /api/v1/projects/{project_id}/artifacts artifacts Explicit unpaginated bounded project inventory exception: source audio, generated stems, practice mixes, exports, and cache artifacts. Ordered by created_at DESC; no pagination.
GET /api/v1/projects/{project_id}/sections sections Explicit unpaginated project document/song-structure exception. Sections are bounded by the song arrangement and must stay complete for editing and playback.
GET /api/v1/sync/trusted-peers trusted_peers Explicit unpaginated active manual trust-list exception. Active peers only; bounded by user-paired devices and returned complete for sync UI. Deterministic ordering is display_name case-insensitive, then device_id.
GET /api/v1/beat-backends backends Explicit unpaginated exception: small static capability list, bounded by bundled/local backend implementations.
GET /api/v1/chord-backends backends Explicit unpaginated exception: small static capability list, bounded by bundled/local backend implementations.
GET /api/v1/stem-models models Explicit unpaginated exception: small static capability list, bounded by supported local stem models.
GET /api/v1/sync/metadata projects, artifacts, delete_tombstones Explicit unpaginated sync snapshot exception. The payload is a complete sync inventory used by native sync and reconciliation, not an interactive scroll list. If scale requires chunking, it should be a sync protocol change rather than this generic pagination contract.
GET /api/v1/sync/preflight projects, duplicate_groups, manual_cleanup_guidance Explicit unpaginated diagnostic exception. The response is a complete local-library health report.
GET /api/v1/sync/projects/{project_id}/manifest entity_revisions, artifacts, delete_tombstones Explicit unpaginated manifest exception. The response is an atomic project export unit.
POST /api/v1/sync/projects/manifests project_manifests, manifest_errors Explicit unpaginated batch manifest export result, bounded by the requested project_ids.
POST /api/v1/sync/artifacts/files/resolve records, errors Explicit unpaginated artifact-file resolution result, bounded by the requested artifact_ids.
POST /api/v1/sync/reconciliation/plan items, actions Explicit unpaginated planning exception. The response is a complete computed plan for the supplied sync inventory.
POST /api/v1/sync/reconciliation/apply plan.items, plan.actions, results, timing_evidence Explicit unpaginated apply exception. Partial pages would make apply summaries and results incomplete.
Project document payloads, including analysis timing, chords, lyrics, tab imports, and tab apply results nested content arrays and result arrays Explicit unpaginated document exceptions unless a future endpoint exposes them as standalone growable collections. These arrays are part of a single project document or edit result, not top-level list browsing.

Example error response:

{
  "error": {
    "code": "PROJECT_NOT_FOUND",
    "message": "Project not found.",
    "details": {}
  }
}

Shared Shapes

Job

Jobs represent asynchronous work such as analysis, chords, lyrics, transforms, stems, previews, and exports.

Important fields:

  • id
  • project_id
  • type
  • status
  • progress
  • stage
  • stage_label
  • source_artifact_id
  • chord_backend
  • chord_source
  • error_message
  • runtime_device
  • runtime_detail
  • created_at
  • updated_at

Artifact

Artifacts represent generated or imported files associated with a project.

Important fields:

  • id
  • project_id
  • type
  • format
  • path
  • size_bytes
  • generated_by
  • can_delete
  • can_regenerate
  • metadata
  • created_at
  • updated_at

Health

Get health

GET /api/v1/health

Returns backend name, legacy backend git ref in version, backend/frontend package versions and git refs, status, API base URL, data root, default export format, and preview format. Build git refs use the packaged build metadata when available, otherwise local development resolves them with git describe --tags --long --dirty --always --abbrev=8.

Beat Backends

List beat backends

GET /api/v1/beat-backends

Returns available Advanced Beat Analysis and Built-in Beat Analysis backends. Built-in Beat Analysis is always expected to be available. Advanced Beat Analysis is the default desktop/dev/package request, but may be unavailable when desktop-only dependencies are explicitly excluded, unsupported, or missing.

Chord Backends

List chord backends

GET /api/v1/chord-backends

Returns available chord backends and capability metadata. Built-in chords are always expected to be available. Advanced Chords is the default desktop/dev/package engine, but may be unavailable when desktop-only dependencies are explicitly excluded, unsupported, missing, or the runtime platform is mobile.

Stem Models

List stem models

GET /api/v1/stem-models

Returns supported stem models and availability metadata. Labels are Default (6 stems model) for htdemucs_6s and 2 stems model for htdemucs_ft.

Vocal refinement

  • GET /api/v1/vocal-substems/capabilities reports desktop availability, verified cache state, and download size. This request only checks the local cache.
  • POST /api/v1/projects/{project_id}/vocal-substems queues a job for vocals_artifact_id. Accepts output_format (WAV, FLAC, MP3, or M4A) and explicit allow_download. On success, result_artifact_ids contains the Lead and Backing tracks.
  • DELETE /api/v1/projects/{project_id}/vocal-substems/{vocals_artifact_id} removes the current split and leaves Original Vocals. The normal artifact delete route removes an individual part and records its exclusion.

A six-stem vocal_stem records its current vocal_substems membership in artifact metadata. Child types are lead_vocal_substem and backing_vocal_substem. They transfer as durable audio under the existing sync manifest and transport versions.

Sync

The sync API exposes local sync metadata, identity, and trust management for the bundled desktop app. FastAPI remains bound to loopback; LAN transport, peer discovery, QR scanning, and file transfer belong to the separate native sync layer.

device_id is the stable identity for one TuneForge install. sync_group_id identifies the sync group that trusted devices may share. Display names are editable convenience labels and must not be treated as identity.

Get local sync identity

GET /api/v1/sync/identity

Returns the local sync identity, creating it if it does not exist yet.

Response wrapper:

  • identity

Identity fields:

  • device_id
  • sync_group_id
  • display_name - nullable convenience label.
  • public_key
  • created_at - nullable when the service returns an identity DTO without persistence metadata.
  • updated_at - nullable when the service returns an identity DTO without persistence metadata.

Update local sync identity

PATCH /api/v1/sync/identity

Updates the local identity display name.

Request fields:

  • display_name

Response wrapper:

  • identity

Changing display_name does not change device_id, sync_group_id, or public identity material.

Create sync pairing offer

POST /api/v1/sync/pairing/offers

Creates a short-lived manual pairing offer for copy/paste style pairing. The endpoint does not start LAN discovery, expose FastAPI beyond loopback, or create QR UI.

Request fields:

  • endpoint_hints - optional advisory peer endpoints, default [].
  • ttl_seconds - pairing offer lifetime in seconds, default 600, maximum 3600.

Response wrapper:

  • pairing_offer

Pairing offer fields:

  • payload
  • expires_at
  • ttl_seconds

The payload is the portable value another device submits inside the payload field of POST /api/v1/sync/trusted-peers. For this backend-first slice, a peer trust request must carry the pairing_offer_id and pairing_secret from a pending local offer so this install can verify the manual exchange before storing trust. It includes:

  • protocol_version
  • pairing_offer_id
  • sync_group_id
  • device_id
  • display_name
  • public_key
  • endpoint_hints
  • pairing_secret
  • expires_at
  • signature

Pairing payloads are signed by the source device's private identity key so copied payloads are tamper-evident. Endpoint hints are advisory and do not authenticate a peer. The receiving install must still explicitly trust the payload before accepting manifests, revisions, tombstones, or artifact bytes from that device. The payload submitted to this endpoint must reference a locally issued pairing_offer_id; that local offer must still be unused, unexpired, and match the payload's pairing_secret.

Answer sync pairing offer

POST /api/v1/sync/pairing/responses

Answers a copied pairing offer, stores trust for the peer, and returns a signed response payload the offer creator can verify through the manual exchange.

Request fields:

  • offer - copied pairing offer payload.
  • endpoint_hints - optional advisory endpoints, default [].
  • adopt_sync_group - whether this install should adopt the offer's sync_group_id, default false.

Response fields:

  • pairing_response
  • trusted_peer

List trusted peers

GET /api/v1/sync/trusted-peers

Returns active peers this install explicitly trusts. Revoked peers are not returned by this list.

Response wrapper:

  • trusted_peers

Trusted peer fields:

  • device_id
  • sync_group_id
  • display_name
  • public_key
  • endpoint_hints
  • trusted_at
  • revoked_at
  • updated_at

Trust is explicit and non-transitive. Joining the same sync_group_id, discovering a device, or hearing about a peer from another trusted device does not automatically trust that peer.

Trust peer from pairing payload

POST /api/v1/sync/trusted-peers

Stores trust for one peer from a manual pairing payload.

Request fields:

  • payload - pairing payload copied from another device.
  • adopt_sync_group - whether this install should adopt the payload's sync_group_id, default false.

Response wrapper:

  • trusted_peer

Trusting a peer records its device_id, public identity, display name, endpoint hints, and sync group. The peer can later be revoked without deleting local projects or changing this install's own device_id. Standalone payloads that do not reference a local pending offer are rejected.

Update trusted peer endpoint hints

PATCH /api/v1/sync/trusted-peers/{device_id}/endpoint-hints

Replaces advisory endpoint hints for an active trusted peer.

Request fields:

  • endpoint_hints - advisory peer endpoints. Values are trimmed and empty values are rejected.

Response wrapper:

  • trusted_peer

Unknown or revoked peers return 404.

Revoke trusted peer

DELETE /api/v1/sync/trusted-peers/{device_id}

Revokes trust for the peer with the matching device_id.

Response wrapper:

  • trusted_peer

Revocation stops this install from accepting future sync material from that peer unless it is explicitly paired again. Revocation is local to this install and does not revoke trust transitively on any other device.

Run sync preflight

GET /api/v1/sync/preflight

Checks the local library before multi-device sync is enabled. The endpoint returns HTTP 200 for both passing and failing preflight results because failures are actionable diagnostics rather than request errors.

The response includes:

  • ok - overall sync readiness. This is true when library checks pass. Pending or running jobs are diagnostic state, not a hard sync blocker.
  • library_ok - library-only readiness, matching the previous ok behavior.
  • project status counts
  • per-project sync identity status
  • duplicate source-hash groups
  • job_state - active job diagnostics for sync startup and backend responsiveness failures.
  • manual cleanup guidance

job_state includes state (ready or busy), running_job_count, pending_job_count, blocking_job_count, blocking_job_counts, blocking_jobs, blocking_jobs_truncated, and guidance. Pending and running jobs do not block sync by themselves; they are included so the UI can explain backend-busy or endpoint-timeout failures. blocking_jobs is capped at 20 entries and exposes only sync-safe fields: id, project_id, project_name, type, status, progress, started_at, and updated_at. It does not expose job payloads, file paths, audio data, or endpoint details.

Project status values are ready, missing_source_hash, invalid_source_hash, duplicate_source_hash, and noncanonical_project_id. Canonical project IDs use proj_sha256_<full_source_sha256>, while project storage directories use a shorter derived key such as proj_<first_24_sha256_hex>. Preflight uses a stored projects.source_sha256 when present. If that field is missing, preflight only recovers it from an explicit app-managed original-byte copy and otherwise reports missing_source_hash; source_path is provenance only and is not hashed during recovery. This endpoint is sync-specific; general project responses do not expose source hashes.

Get sync metadata

GET /api/v1/sync/metadata

Returns sync-safe project and artifact metadata so sync clients do not need to read the local SQLite database directly. The endpoint does not expose absolute local file paths.

Project fields:

  • project_id
  • display_name
  • source_key_override
  • source_sha256
  • duration_seconds
  • sample_rate
  • channels
  • created_at
  • updated_at

Artifact fields:

  • artifact_id
  • project_id
  • type
  • format
  • relative_path
  • content_sha256
  • size_bytes
  • generated_by
  • can_delete
  • can_regenerate
  • cache_key
  • metadata
  • created_at

Delete tombstone fields:

  • tombstone_id
  • sync_group_id
  • project_id
  • target_type
  • target_id
  • author_device_id
  • deleted_at
  • prior_metadata
  • created_at
  • updated_at

relative_path is project-root relative when the artifact is stored under the backend-managed project root; otherwise it is null. Operational source_audio artifacts are app-managed WAV files under the project root. Artifact metadata is sanitized recursively before returning and removes local path-bearing keys such as source_path, original_copy_path, playback_path, imported_path, and any metadata key ending in _path. Non-path metadata such as retune/transpose settings, stem_model, and source_artifact_id is preserved. Job internals such as result_artifact_ids_json are not exposed.

Plan sync reconciliation

POST /api/v1/sync/reconciliation/plan

Returns a stateless sync plan comparing the local library with metadata supplied by the native sync layer. The endpoint reads local state but does not write projects, artifacts, revisions, tombstones, staged files, jobs, or conflict records. Clients execute returned actions through the existing import, staging, and future sync flows.

Request fields:

  • remote_library - sync metadata in the same shape returned by GET /api/v1/sync/metadata, plus optional entity_revisions: projects, artifacts, entity_revisions, and optional delete_tombstones.
  • project_manifests - optional list of exported project manifests, default [].
  • peer_inventory - peer entries with device_id, available_content_sha256, and optional small metadata.

Response fields:

  • summary - total_items, total_actions, total_conflicts, and status_counts.
  • items - per-project, artifact, revision, or tombstone decisions with item_type, item_id, optional project_id, status, optional action_type, optional content_sha256, optional chosen_provider_device_id, optional reason, and details.
  • actions - ordered operations with action_type, item_type, item_id, optional project_id, optional content_sha256, optional provider_device_id, optional reason, priority, and details.

Planner statuses are noop, identical_content, missing_local_bytes, remote_available, missing_provider, deleted, and conflicted.

Action types are apply_delete_tombstone, import_project_manifest, import_entity_revision, fetch_artifact_content, import_artifact_manifest, upsert_project_status, record_conflict, and noop.

Apply sync reconciliation

POST /api/v1/sync/reconciliation/apply

Computes a reconciliation plan and applies selected local state changes. This endpoint writes local project status, imports manifests/revisions, applies tombstones, records conflicts, and can consume staged artifact files prepared by the native sync layer.

Request fields:

  • remote_library
  • project_manifests
  • peer_inventory
  • staging_root - optional; only null is accepted.
  • use_content_addressed_staging - optional; defaults to true and only true is accepted.
  • project_ids
  • include_timing_evidence

HTTP reconciliation consumes verified content from backend-managed content-addressed staging. Caller-selected staging directories and relative-folder mode are rejected with HTTP 422 before applying any state changes.

Response fields:

  • summary
  • plan
  • results
  • timing_evidence

Sign sync transport handshake

POST /api/v1/sync/transport/handshake/sign

Signs a native sync transport handshake challenge with this install's local sync identity. This is metadata for the native sync transport; it does not expose FastAPI beyond loopback.

Request fields:

  • peer_device_id
  • challenge

Response fields include protocol_version, challenge_type, local_device_id, peer_device_id, public_key, challenge, canonical_challenge_json, signature, and signed_at.

Export project sync manifest

GET /api/v1/sync/projects/{project_id}/manifest

Returns a single project manifest for manifest-only sync export. The response is wrapped as project_manifest and includes:

  • schema_version
  • exported_at
  • project
  • entity_revisions
  • artifacts
  • delete_tombstones

Manifest paths are project-root relative and use portable path separators. The response does not expose absolute local source, project, artifact, or app data paths. The project entry's source_sha256 is the identity hash of the original imported source bytes. Artifact entries' content_sha256 values hash the bytes for those specific staged artifact files, including the source_audio artifact. These hashes are separate on purpose: an app-managed normalized WAV source artifact may have different bytes from the original import identity hash. sync_entity_revisions.content_sha256 is also per-entity revision payload content, not project source identity. Projects whose source_audio artifact is not an app-managed readable PCM WAV must be reimported or repaired before manifest export. Receiving peers must verify staged files against the artifact SHA-256 values and must preserve the project source_sha256 as identity metadata before accepting the import. The endpoint exports metadata only. File transfer and LAN peer discovery belong to the native sync layer, not the loopback FastAPI API.

entity_revisions carries durable sync records for project metadata, chords, lyrics, sections, regeneration events, and other editable or generated project entities. Each revision records revision_id, project_id, entity_type, entity_id, revision_type, optional base_revision_id, author_device_id, optional source_artifact_id, content_sha256, state, metadata, payload, created_at, and updated_at.

delete_tombstones carries durable group-delete records for project, artifact, and entity revision targets so offline peers do not resurrect deleted records when they reconnect. Each tombstone records the author device, delete timestamp, target type, target ID, sync group/project context, and prior metadata needed for diagnostics.

Export project sync manifests

POST /api/v1/sync/projects/manifests

Exports manifests for multiple requested projects. Failures for individual projects are returned in manifest_errors instead of discarding successful exports.

Request fields:

  • project_ids

Response fields:

  • project_manifests
  • manifest_errors

Update project sync status

PATCH /api/v1/sync/projects/{project_id}/status

Updates local sync status metadata for a project placeholder or imported project.

Request fields:

  • sync_status
  • sync_status_reason
  • sync_required_artifact_ids
  • sync_provider_device_ids
  • sync_conflict_count
  • manifest
  • project

Provide either manifest or project, not both.

Response wrapper:

  • project

Stage sync artifact file

POST /api/v1/sync/artifacts/staging

Stages a local artifact file for sync import/export handoff, verifies its SHA-256 and size, and returns the content-addressed staging record. This endpoint reads a local path supplied by the native sync layer and does not expose arbitrary file content over the API.

Request fields:

  • source_path
  • content_sha256
  • size_bytes
  • provider_device_id
  • metadata

Response fields include content_sha256, size_bytes, relative_path, provider_device_id, metadata, verified_at, created_at, and updated_at.

Resolve sync artifact files

POST /api/v1/sync/artifacts/files/resolve

Resolves project artifact IDs into local file records for the native sync layer.

Request fields:

  • artifact_ids

Response fields:

  • records
  • errors

Get staged sync artifact

GET /api/v1/sync/artifacts/staging/{content_sha256}

Returns the staging record for a previously staged artifact content hash.

Response: SyncStagedArtifactSchema.

Import staged project sync manifest

POST /api/v1/sync/projects/import

Imports a project from a previously exported project manifest plus files that have already been staged on disk by the sync transport.

Request fields:

  • manifest
  • staging_root - optional; only null is accepted.
  • use_content_addressed_staging - optional; defaults to true and only true is accepted.

Files must already be verified in backend-managed content-addressed staging, indexed by their manifest SHA-256 hashes. Caller-selected staging directories and relative-folder mode are rejected with HTTP 422 before import. During import, the backend requires exactly one source_audio artifact. Durable sources, stems, and practice mixes accept exact wav/.wav, flac/.flac, mp3/.mp3, or AAC-LC m4a/.m4a pairs. The backend verifies size, SHA-256, readability, container, and codec before commit, rewrites accepted paths into this install's backend-managed project root, and persists the project through backend services instead of copying database rows from another device. Original absolute import paths are local provenance only and are not sync-operational inputs.

If the local library already contains the same canonical project or source SHA-256, staged import rejects the duplicate with HTTP 409 instead of creating a second project. The response uses the normal project wrapper shape:

  • project

Staged import does not enqueue analysis, chord, lyrics, stem, or other generation jobs. Synced projects should import the durable state that was actually exported; future rebuilds are explicit user actions. Imports must reject older manifests that would recreate a project, artifact, or entity revision covered by an accepted delete tombstone. This endpoint also does not expose FastAPI on the LAN. Peer communication should keep using the separate native sync layer while FastAPI remains bound to loopback.

Projects

Import project

POST /api/v1/projects/import

Creates a project from a source path and queues initial analysis, chord, lyrics, and source stem jobs. Desktop imports selecting htdemucs_6s append named section detection after lyrics. Two-source imports skip section detection. Generated candidates are stored separately from accepted song sections.

Request fields:

  • source_path
  • copy_into_project
  • display_name
  • output_format - wav, flac, mp3, or m4a; defaults to wav.
  • chord_backend
  • chord_backend_fallback_from
  • stem_model
  • beat_backend

Response: ProjectResponse.

stem_model is optional. Desktop imports send the user's default stem model so automatic source stems match manual stem generation preferences; if omitted, the backend stem model default is used. beat_backend defaults to beat-this. An Advanced Beat Analysis dependency, checkpoint download/load, runtime, or unusable-timing failure fails the analysis job; the backend does not switch to Built-in Beat Analysis. Chord backend fields follow the same validation as explicit chord generation.

source_path records where the user imported the file from on this install. Sync treats it as local provenance, not a durable source of original bytes or an operational sync input. copy_into_project=false is accepted for compatibility, but new imports still create an app-managed durable source artifact under the project root. Project identity remains derived from the original selected bytes; the artifact hash describes the encoded durable bytes.

If the same source track has already been imported, the endpoint returns HTTP 409 with code DUPLICATE_PROJECT_SOURCE, message This project is already imported with name "{name}"., and details containing:

  • project_id
  • project_name

List projects

GET /api/v1/projects

Optional query:

  • search - filters projects by display name or path before pagination.
  • limit - page size, default 50, minimum 1, maximum 200.
  • offset - zero-based row offset, default 0, minimum 0.

Default ordering is deterministic newest-first: updated_at DESC, id DESC.

Response: ProjectsResponse with projects, total, limit, offset, and has_more.

Get project

GET /api/v1/projects/{project_id}

Response: ProjectResponse.

Update project

PATCH /api/v1/projects/{project_id}

Supported fields:

  • display_name
  • source_key_override

Response: ProjectResponse.

Delete project

DELETE /api/v1/projects/{project_id}

Deletes the project and project-owned data.

Response: DeleteResponse.

Analysis

Start analysis

POST /api/v1/projects/{project_id}/analyze

Queues an analysis job.

Request fields:

  • include_tempo
  • force
  • beat_backend

Response: JobResponse.

beat_backend defaults to beat-this. Analysis jobs expose the selected backend in beat_backend. Pending jobs reconstructed without a selection adopt Advanced Beat Analysis; legacy completed jobs without a backend remain readable as Built-in Beat Analysis.

Get analysis

GET /api/v1/projects/{project_id}/analysis

Returns the stored analysis result, or null if no result exists.

Analysis includes key, key confidence, reference tuning, tuning offset, tempo, analysis version, source artifact, and creation time.

Analysis is an unpaginated project document payload. Its timing data is returned with the analysis document so playback and practice consumers do not need lazy-loaded fragments.

Chords

Generate chords

POST /api/v1/projects/{project_id}/chords

Queues chord generation.

Request fields:

  • backend
  • backend_fallback_from
  • force
  • overwrite_user_edits

Response: JobResponse.

Get chords

GET /api/v1/projects/{project_id}/chords

Returns source segments, current timeline segments, backend, source artifact, source kind, user-edit state, metadata, and timestamps. If no chord timeline exists, the response contains an empty timeline.

Chord timelines are unpaginated project document payloads. The source and current timelines stay complete so playback and editing consumers share one coherent chord document.

Lyrics

Generate lyrics

POST /api/v1/projects/{project_id}/lyrics

Queues local lyrics generation.

Request fields:

  • force
  • language_override (optional): null or omitted uses Whisper auto-detection. Supported overrides are none, en, pt, es, fr, de, it, ja, ko, zh, and hi. none marks the project as having no lyrics and does not run Whisper.

Response: JobResponse.

Get lyrics

GET /api/v1/projects/{project_id}/lyrics

Returns source transcript segments, current edited segments, backend, source artifact, model/device metadata, effective language, language override, user-edit state, and timestamps. If no lyrics exist, the response contains empty segment lists.

Lyrics segments are unpaginated project document payloads. Source and edited segments stay complete so lyric editing and playback highlighting do not depend on lazy-loaded fragments.

Update lyrics

PUT /api/v1/projects/{project_id}/lyrics

Persists edited lyric segment text.

Request fields:

  • segments

Each segment currently accepts:

  • text

Response: LyricsResponse.

Tab Imports

Create tab import proposals

POST /api/v1/projects/{project_id}/tabs/proposals

Parses pasted local tab/chord text and returns proposed lyrics, chord, or section edits for review. The endpoint stores proposals but does not apply them.

Request fields:

  • raw_text

Response: TabImportResponse.

Get tab import

GET /api/v1/projects/{project_id}/tabs/{tab_import_id}

Returns a stored tab import and its suggestion groups.

Response: TabImportResponse.

Accept tab import suggestions

POST /api/v1/projects/{project_id}/tabs/{tab_import_id}/accept

Applies selected suggestions from a tab import to editable project documents.

Request fields:

  • accepted_suggestion_ids

Response: TabImportApplyResponse, including the updated tab import, accepted/ignored IDs, and any updated lyrics, chords, sections, or project metadata.

Sections

Detect named section candidates

POST /api/v1/projects/{project_id}/sections/detect

Queues a local sections job. No request body. Requires the project's six-source stem set. The CPU/accelerator profile accepts at most 926 seconds, with aligned 44.1 kHz mono/stereo stems. Input bounds and temporary-disk preflight remain; failed final attempts are reported through the job.

Response: the existing JobResponse shape. Poll the normal job endpoint for completion or failure. The processing stage is labeled Detecting named section candidates.

The job stores one local row with project_id, model_revision, nullable source_artifact_id, raw_sections_json, refined_sections_json, and a working sections_json list. On success it seeds the working list from refined results, sets source_kind to generated, clears has_user_edits, preserves created_at, and advances the non-null UTC updated_at, including identical reruns. These fields prepare future editing, tab-import reconciliation, and LWW sync; those flows remain deferred. Each ordered array contains only {start_seconds, end_seconds, label} objects. Frame scores are used transiently with the current saved timing, chord, lyric, and vocal cues for refinement, then discarded. Each request runs inference again; previous maps remain intact if inference fails, is cancelled, or its inputs/cues change before commit. Repeated adjacent role names remain separate occurrences; uncertain labels may abstain. Detection does not generate, replace, or synchronize accepted SongSection records. The section list endpoint below continues to return accepted project sections.

List project sections

GET /api/v1/projects/{project_id}/sections

Returns the project's complete accepted song-structure section list and a has_detected_sections flag indicating whether it has a saved detection result.

Sections are an unpaginated project document payload. They are bounded by the arrangement and stay complete so editing, playback navigation, and tab-import apply results use one shared song-structure view.

Response: SongSectionsResponse.

Transforms and Previews

Retune

POST /api/v1/projects/{project_id}/retune

Queues a retune job.

Request fields:

  • exactly one of target_reference_hz or target_cents_offset
  • preview_only
  • output_format

Response: JobResponse.

Transpose

POST /api/v1/projects/{project_id}/transpose

Queues a transpose job.

Request fields:

  • semitones
  • preview_only
  • output_format

Response: JobResponse.

Generate preview

POST /api/v1/projects/{project_id}/preview

Queues a preview job for a retune and/or transpose transform.

Request fields:

  • retune
  • transpose
  • output_format

At least one transform must be provided. Durable practice mixes support wav, flac, mp3, and m4a.

Response: JobResponse.

Stems

Generate stems

POST /api/v1/projects/{project_id}/stems

Queues stem generation for the selected source audio or practice mix.

Request fields:

  • mode
  • stem_model
  • output_format
  • force
  • source_artifact_id
  • chord_backend
  • chord_backend_fallback_from
  • overwrite_chord_edits

Current validation allows mode: "stems" or mode: "two_stem" and output_format: "wav", "flac", "mp3", or "m4a". If stem_model is omitted, mode: "stems" uses the backend default htdemucs_6s; mode: "two_stem" maps to htdemucs_ft for compatibility.

htdemucs_6s creates visible Vocals, Drums, Bass, Guitar, Piano, and Other artifacts. htdemucs_ft creates visible Vocals and Instrumental artifacts.

Response: JobResponse.

Project Artifacts

List project artifacts

GET /api/v1/projects/{project_id}/artifacts

Returns the bounded project inventory for source audio, generated stems, practice mixes, exports, and cache artifacts. Results are ordered by created_at DESC.

Project artifacts are not paginated. They are project-scoped inventory, not a library-level growable browsing list.

Response: ArtifactsResponse.

Delete project artifact

DELETE /api/v1/projects/{project_id}/artifacts/{artifact_id}

Deletes a project artifact when it belongs to the project and can be removed.

Response: DeleteResponse.

Export

Export project artifacts

POST /api/v1/projects/{project_id}/export

Queues an export job for selected project audio artifacts and generated project documents.

Request fields:

  • artifact_ids - unique ordered IDs from one source track or practice mix and its stems; defaults to an empty list.
  • generated_document_ids - unique ordered GeneratedExportDocumentId values, lyrics or lyrics_with_chords; defaults to an empty list.
  • document_audio_set_artifact_id - same-project primary source_audio or preview_mix used as the document's musical context. Required for lyrics_with_chords; when audio is also selected, both selections must resolve to this audio set.
  • document_chord_display_mode - auto, sharps, flats, neutral, or dual. Required for lyrics_with_chords; plain lyrics ignore document chord context.
  • output_format - wav, flac, mp3, or m4a, subject to runtime capabilities. It is ignored by document-only exports, which always write UTF-8 TXT.
  • filename_base - sanitized base used for stable friendly output names.
  • destination - tagged single_file, folder, or zip object with opaque target and explicit overwrite approval.

Legacy mixdown_mode, destination_path, destination_file_path, and overwrite_existing remain accepted for one audio artifact during migration. Generated documents require the canonical destination. Canonical and legacy destinations cannot be combined. The combined audio-and-document count selects File for one item or Folder/ZIP for multiple items. Audio artifacts from different sets are rejected before queuing.

Generated documents read current saved lyrics and chords from the database when the job starts. Job payloads contain only document IDs, output names, and resolved key/transpose/display context, never lyric or chord content. Lyrics TXT preserves saved segment text and order with normalized LF newlines. Lyrics with chords corrects labels from the detected key to source_key_override, then adds only the selected practice mix's metadata transpose. The override-or-detected key, transposed for that mix, controls enharmonic spelling; retune-only/source audio contributes no mix transpose, and capo or other playback-only shifts are excluded. Known chords and slash bass notes follow the desktop playback spelling modes, while N.C. and unparseable labels remain unchanged. Chords stay anchored above lyric blocks, and every leading, internal, or trailing instrumental gap becomes one chronological, single-space-separated chord row with blank block separation.

Direct files remain user-owned external outputs. Successful direct documents register local export_mix receipts, while ZIP uses the existing archive receipt. No document copy is stored under the project and export receipts remain excluded from sync.

Response: JobResponse.

Completed export jobs expose ordered result_artifact_ids and export_result. The result contains aggregate outcome/counts plus per-item progress, status, output name, registered result ID, and safe error. ExportResultItemSchema is an exact union: each item has either a non-null artifact_id or a non-null generated_document_id, never both. A mixed batch keeps global job status completed with export outcome partial. Document availability failures use EXPORT_LYRICS_UNAVAILABLE, EXPORT_CHORDS_UNAVAILABLE, or EXPORT_DOCUMENTS_UNAVAILABLE; export 422 responses use the typed ErrorResponse envelope rather than FastAPI's validation-error shape.

Get export capabilities

GET /api/v1/export-capabilities

Returns runtime-probed format availability, destination availability, and maximum artifact count. Desktop probes configured host FFmpeg encoders and muxers once per backend process.

Jobs

List jobs

GET /api/v1/jobs

Returns a paginated list of jobs.

Query parameters:

  • limit - page size, default 50, minimum 1, maximum 200.
  • offset - zero-based row offset, default 0, minimum 0.
  • status - optional repeatable status filter, for example ?status=pending&status=running.
  • project_id - optional project ID filter.
  • search - optional project display name filter. Search is applied before pagination and composes with status and project_id filters.
  • sort_by - optional sort key. Supported values are activity (default), created_at, started_at, updated_at, and status.
  • sort_order - optional asc or desc direction for non-activity sorts. Omit this when sort_by is activity or omitted; sort_order with activity sorting returns 422 INVALID_REQUEST.

Filters and search are applied before sorting, total, and pagination. Pagination is applied after sorting.

Default activity ordering:

  • running jobs first, ordered by started_at when present, otherwise created_at, ascending, then id ascending.
  • pending jobs next, ordered by created_at ascending, then id ascending.
  • terminal jobs (completed, cancelled, failed) next, ordered by completed_at when present, otherwise updated_at, descending, then id descending.
  • unknown statuses last, ordered by updated_at descending, then id descending.

Timestamp ordering:

  • created_at, started_at, and updated_at default to desc; use sort_order=asc for oldest-first.
  • null timestamp values are always last for both asc and desc.
  • Timestamp ties use id ascending as the deterministic tie-breaker.

Status ordering:

  • sort_by=status defaults to asc.
  • asc groups jobs as running, pending, completed, cancelled, failed, then unknown statuses.
  • desc reverses those groups.
  • Jobs inside each status group use the same deterministic tie-breakers as activity ordering for that group.

Response: JobsResponse.

Create bulk jobs

POST /api/v1/jobs/bulk

Queues the same project activity job for eligible projects in the local library.

Request fields:

  • job_type - analyze, chords, lyrics, stems, or desktop-only sections / convert_audio.
  • output_format - captured durable stem/conversion format; defaults to wav and must remain wav for other jobs.
  • chord_backend
  • chord_backend_fallback_from
  • stem_model
  • beat_backend

Response: BulkJobsResponse, with created_jobs, total_projects, and skipped.

Bulk sections queues a fresh detection for each eligible project using its source audio and complete matching htdemucs_6s stem generation. Active section jobs and sync-locked projects are skipped. Missing or mismatched stems report section_stems_required; ongoing stem generation reports section_stems_busy; missing or non-owned input files report section_inputs_unavailable. Deleted projects are excluded. Mobile runtimes reject the action with SECTIONS_UNAVAILABLE. Detection uses available saved analysis/chords from any backend and replaces local candidates only after success, preserving accepted song sections and model start/end labels. Section inference uses TUNEFORGE_SECTION_DEVICE (auto, cpu, mps, cuda); auto prefers compatible CUDA, then MPS, then CPU. Existing job runtime fields report the actual inference device after placement. Explicit unavailable accelerators fail clearly. Failed resolved CUDA/MPS execution retries once in a fresh CPU worker, with fallback stage/detail and the actual CPU device after placement. CPU-first failures, failed CPU retries, cancellation, and input/configuration failures do not enqueue more attempts. Section inference uses standard framework allocator behavior without section-specific memory caps or an RSS watchdog.

Get job

GET /api/v1/jobs/{job_id}

Response: JobResponse.

For analysis jobs, beat_backend is the backend selected for the run. Analysis artifact metadata records the completed engine as analysis_backend. Advanced Beat Analysis failures do not produce a Built-in Beat Analysis artifact.

Cancel job

POST /api/v1/jobs/{job_id}/cancel

Requests cancellation for a job.

Response: JobResponse.

Artifact Streaming

Stream artifact

GET /api/v1/artifacts/{artifact_id}/stream

Streams the artifact file as an audio response. Returns ARTIFACT_NOT_FOUND if the artifact row or file is missing.