Annotation workbench
Open Annotation workbench from the sidebar (#/labeling). The original Workbench overview remains available. Choose a production project and task package. Personal projects have My data; group and team projects expose My tasks, Review queue, and Project cockpit according to the effective server scopes. Create projects, published label sets, and packages with the existing production CLI; datakeel production demo creates a personal box project with generated predictions.
The module bar shows the project, task package, and authoritative production progress. The operation bar names the open file by its path under the imported directory (the file name when none was recorded; a path too long for the bar shows in full on hover) and contains save, undo, redo, submission, and task navigation. While a task is open the page drops the marketing heading and footer, and the work area fills the window height below the two bars; it follows window resizes. Image tools and zoom controls sit in a narrow left rail. The right drawer (properties, immutable revisions, review comments, guide) collapses with Hide details, which widens the canvas. Task lists, the review queue and the cockpit show tasks by file name; hovering a task shows its path under the imported directory, and the search box matches file names and folder names alike, so same-named files in different folders stay apart. Importing a directory records each file's path relative to that directory (hidden entries and symbolic links inside it are skipped); the machine's own path is never returned by the API or shown. Files imported on their own, and datasets imported before this, show the file name.
Boxes and polygons use their label's configured colour; labels without a colour take a fixed eight-colour palette in label order (--label-1…--label-8, light and dark values checked by check:contrast). Each shape carries its label name in a chip that keeps a constant screen size at any zoom. A chip is no wider than its shape on screen (56–160 px); a longer name ends in an ellipsis and shows in full on hover. Chips are drawn after every shape, so a later shape never hides an earlier shape's name; where chips overlap, the later shape's chip is on top and hovering names that chip. Chips never take the pointer: pressing on one draws a box, adds a polygon point or selects a shape exactly as pressing the canvas or shape beneath it would. While part of a shape is on screen, its chip is pulled inside the visible canvas, so zooming in on one corner of a large box still shows its name.
Editing and templates
Templates use the existing versioned ProductionTemplate catalog object. A project's published label-set version supplies stable category identities. Without a template, a project uses the box component. Configure the primary annotation_type and optional component_config:
{
"components": ["box", "classification"],
"label_mode": "multi",
"shortcuts": {"cat": "1", "dog": "2"},
"guidelines": "Label only visible objects."
}
Templates may also define typed attribute fields (attributes): boolean, enum, multi_enum, number (optional range) and text, each with Chinese and English names, required, a default and a target of object (every box, polygon, skeleton, span and media segment) or record (the whole item). The workbench renders them as native form controls; required fields block both autosave (status "Not saved · fill in the required attributes") and submission, naming the shape and field. The server applies the same rules and returns 422 naming the field, so a bypassing client is rejected too. Tasks on older templates without fields still open and save as before. Annotators and reviewers no longer see raw JSON attributes; project managers can edit them under Advanced: raw attributes. See PRODUCTION.md for the field schema and its comparison with CVAT, Label Studio and Labelbox.
Supported components are box, polygon, keypoints, segment, classification, and text_span. A segment template is valid alone or with classification; spatial/text component combinations are rejected. Creating or upgrading to one requires a positive media_probe.duration_ms and a browser-supported codec on every locked audio/video source, including tasks with no revisions. The authoritative interval is integer-millisecond half-open [start_ms,end_ms) within 0..duration_ms; 1ms, exact endpoints, overlap, nesting, adjacency and duplicates are preserved in record order, while zero/reversed/out-of-bounds values are refused. A derived clip uses its local readable duration without a source offset. Every save, submission, review, package acceptance, finalization and native batch import rechecks the locked source probe. segments=null means unreviewed; segments=[] means reviewed empty. Automatic segment agreement/accuracy is unsupported and explicitly null. For segment templates, min_annotations and max_annotations count only AnnotationSegment entries, never classification labels; other component templates keep their previous counting rule. A keypoint template carries one typed keypoint_schema: an ordered point list (stable ID, Chinese/English names and required) plus undirected edges. The template editor changes points and edges structurally, never through unchecked schema JSON. Reordering, renaming and edge changes preserve annotations by point ID; new optional points read as missing in old revisions. Deleting or renaming a point used by any historical revision is refused. New required points list affected tasks in the signed upgrade preview and block submission, approval, package acceptance and finalization until filled. Legacy schema-less keypoint placeholders remain readable but cannot be used for new projects, annotation saves or COCO exports. Label names remain user content; stored categories are label IDs. Template configuration is available to project managers; saving builds the template's next version from its newest revision through create_label_set. Each project stays on the template version it locked when it was created (and on its label-set version), so a saved edit changes no project, including the one whose page it was saved from. The cockpit's Template version card (personal projects have no cockpit, so it sits below the data list, above the template configuration) shows "Current template vN, latest vM" and the label-set versions; when a newer version exists, a manager prepares an upgrade_project_template plan there, reads which labels and attributes change, how many tasks and existing annotations it affects and which annotations would no longer pass, and signs it. Only that project moves. Template name, revision, and label-set version are visible in the drawer.
Every field and operation is keyboard reachable. Press ? within an editor to show the shortcut table. Ctrl/⌘+S saves, Ctrl/⌘+Enter submits, Ctrl/⌘+Z undoes, Ctrl/⌘+Shift+Z or Ctrl/⌘+Y redoes. Alt+N/Alt+P navigates tasks after flushing pending changes; presses made while a page or task is still loading are queued and replayed in order, so rapid presses across page edges land on the right task. Text fields retain native text undo.
- Boxes:
Badds; arrows move one source pixel, Shift+arrows ten;Rswitches the arrows to the right/bottom edges, then the left/top edges, then back to moving (the rail states the current mode);Ctrl/⌘+Dcopies; Delete removes. Dragging and transform handles use source-image pixel coordinates. Coordinate fields provide an accessible alternative. - Polygons:
Pstarts; arrows move the cursor one source pixel (Shift: ten); Space or a click adds a point, also on top of an existing shape; Enter closes; Escape cancels. Outside drawing, clicking a shape selects it. Arrows move the whole polygon;Rswitches them to the selected point. Backspace deletes a point when a valid polygon remains. - Keypoints:
Kadds a labelled skeleton with every template point initiallymissing; the first missing point is selected. Click or Space places it asvisibleand advances in template order.[/]switch points,Vswitches visible/occluded,Xmarks missing, arrows move one upright source pixel (Shift: ten). Native instance, point-state, coordinate, label and attribute controls provide the same operations. Drafts may be partial or entirely missing; submission requires every required point and at least one positioned point per instance. Point radius and hit area stay constant on screen, occluded points are hollow/dashed, missing points are not drawn, and edges require two positioned endpoints. Instances outside the viewport are culled by point/edge bounds. - Segments use the native audio/video player with
preload=metadata, never autoplay. Drag blank timeline space to create (reverse drags normalize, zero-length releases do nothing), drag bodies to move and edges to resize; one pointer-up is one undo step. Overlap uses display-only swim lanes and never reorders the record. Space plays,,/.seek 10ms (Shift: 100ms),Tadds a 1000ms segment,Rswitches move/start/end, arrows adjust 1ms (Shift: 10ms),I/Oseek to the selected edges,[/]select, Delete removes, and+/-/0zoom/fit. A native segment list, label and integer-millisecond inputs and attribute controls provide every operation without pointer hit-testing. Reviewers get the same player and read-only timeline. Playback, playhead, selection, zoom and pan are UI state, not annotation edits. - Classification: radio/checkbox controls support Tab, Space, and arrow keys; label shortcuts also work.
label_modechooses single or multiple labels. - Text spans: select characters with Shift+arrows or the pointer, then Enter. Numeric start/end fields also work. Nested spans are retained. Offsets count original Unicode codepoints, including astral characters and CRLF source offsets, matching Python.
Saving and review
Edits are retained in a local draft immediately and saved through save_revision after a 500 ms debounce. Saves are serialized; an edit made while a request is pending remains dirty until its own save completes. Draft keys include actor, project, and task. A same-tab workspace snapshot restores the selected task across reloads. Current server identity is verified before restored drafts can sync. Browser document availability during a complete offline reload depends on the hosting/browser cache; a service worker is not installed.
The next two tasks, revision payloads, and decoded images are prefetched. Segment tasks prefetch task data only, not the whole recording; native playback reuses the authorized /content response and its HTTP Range support. Task navigation waits for a pending save; offline errors and conflicts keep the current draft visible. The undo timeline has no fixed step cap, but available device memory/storage still bounds practical history. Unsaved local state survives reload; completed undo timelines are session-local.
A 409 never silently replaces a revision. Reload server revision discards the local changes only after the explicit choice; Overwrite with my edits reads the current head and attempts a compare-and-swap save. Another concurrent write can cause another visible conflict. Storage failures show a warning. Returning online automatically retries pending edits.
Open tasks refresh themselves
An open task polls GET /api/production/tasks/{id}/status every 5 seconds; a hidden tab slows to every 30 seconds and reads again as soon as it is shown. Lease renewal continues while hidden. Within that interval the page says when the task was returned for rework, changed state elsewhere, or got a newer revision from someone else, and offers Reload server revision or Back to list; local unsaved drafts are kept either way. A return also counts when the page's own submission read already shows the task pending in the next round, and the notice quotes the reviewer's notes. Team-tier leases renew automatically on open and then every 2 minutes, or every third of the lease when the lease is shorter (the length the server granted on the last renewal), through the heartbeat action, and the time left sits under the save state, beside the toolbar, so it costs no canvas height. A failed renewal is shown with Renew now and retried. When the lease expires, the holder's assignment is reclaimed, or a save is refused because the lease expired or the task now belongs to someone else, editing locks and the notice "This task was taken back" takes the toolbar's place; the save state reads "Not saved · draft kept on this device" instead of a save error, Ctrl/⌘+S and Ctrl/⌘+Enter send nothing more, and the draft can be exported as JSON. Back to list then leaves at once without waiting for a save that can no longer succeed, and reloads the list so it shows the new holder and state. A 409 caused by a concurrent change ("Action target state changed after preparation") is shown as "Someone else just changed this task" with Try again; raw server text is not shown.
| Option | What it needs here | Delay | Cost and failure modes | Decision |
|---|---|---|---|---|
| Polling a small status read | One indexed read per open task; works through every proxy and with SQLite | ≤ poll interval (5 s, inside the 10 s budget) | One request per tab every 5 s; nothing to reconnect | Chosen |
| Server-sent events (HTML Standard, MDN EventSource) | A long-lived response per tab plus a change feed every API process can see (database notifications or a broker) | Near-immediate | Over HTTP/1.1 browsers allow about six connections per host, shared by all tabs (EventSource pitfalls); buffering proxies delay events; reconnect and missed-event replay must be built | Not now |
| WebSocket | Same change feed plus a bidirectional protocol and authentication on upgrade | Near-immediate | Most moving parts; no benefit for one-way notices | Not now |
Polling reuses the existing read path and access checks and adds no dependency. If push is needed later, SSE on top of a database change feed is the smallest step; the page logic only needs a different source for the same status object.
Personal submission approves the task directly. Group reviewers approve or return the exact current revision with an issue; rework remains with the original annotator unless a manager takes the round back and assigns it to someone else by name. The queue orders by AI pre-review risk, then rework rounds, model confidence, prelabel difference and stable task ID; with a low-risk review sampling rate below 100%, exempted submissions never reach it (see AI pre-review). Prelabel difference is the share of draft and human objects left unmatched by the same rule as prelabel accuracy (one-to-one within a label at IoU ≥ 0.5), so a box moved by a few pixels is not a difference; it orders the queue and is not a measured model-accuracy score. The cockpit displays P29 counters, workload, confidence distribution, annotation agreement, prelabel accuracy and repeated-rework IDs without maintaining a second fact store. Prelabel accuracy leads with F1 at IoU 0.5; hovering or opening How it is measured explains one-to-one matching and shows precision, recall and F1 at 0.5 and 0.75, the all-hit task share and attribute agreement, with the exact-match rate on a second line. Below it the cockpit shows the confidence thresholds and their source (configured, measured on approved data, or defaults with Not enough reviewed samples; using defaults and the object count), the measured hits per tier, the calibration curve's segments (confidence range, objects, hits, hit rate), Not enough samples to pass through yet while defaults hold high drafts back, spend per model (runs, images, input and output tokens, cost), and each recent cloud run's progress (status, images done and failed, spend against budget, and "Held by someone, drafts only: N" when the run only drafted tasks someone held), refreshed every 5 seconds while one runs. Group and team managers get a Review sampling card; lowering the rate opens a signed plan, raising it executes directly. In a task, the drawer shows the model draft's confidence tier. A group or team task whose latest revision is a low-tier model draft opens empty, with Use model draft to load it. Whenever the latest revision is a model draft and the person submits without editing, the workbench first saves what they see as their own revision (the empty start for low, the draft as confirmed for medium or personal), so a draft is never submitted in their name; the server refuses such a submission anyway. An empty start carries an empty list for each enabled component, and a template's minimum annotation count is checked before submitting with a message in the interface language. Reviewers see the AI pre-review above the review buttons: risk, the decision and each reason as a rule name and one sentence in the interface language, and a Locate button that selects the box, polygon or span a reason points to. In personal projects a risky submission shows the same reasons as a notice and is never blocked. Finalization first displays a frozen action plan in plain words: how many approved tasks will be finalized, into which dataset as a new version, and how many unapproved tasks block it; the digest and raw parameters stay under Details. A separate Approve and finalize project click signs and executes it.
Team-tier projects add to the cockpit: each package's acceptance state and sampling (read from package_acceptance: the rule while the package is open, what the last inspection checked once it is decided); Accept package, where the manager marks each sampled task, prepares an accept_package plan that states the outcome, then signs it; Dispatch by skill, which previews per-person counts and the reason each unassigned task was skipped (dispatch-preview), then prepares and signs an assign_tasks plan with strategy: "skill" (after any refresh the ticks reset to the tasks still waiting; a project without a skill requirement says so instead of offering a preview that would fail); Assign to a named person, which lists the registered people holding annotation authority with their open load (GET /api/production/projects/{id}/assignees, managers only) and prepares and signs a named assign_tasks plan for the ticked tasks nobody holds (open load counts only work that is pending or in progress, not work waiting for review; when a ticked task is a rework round taken back from its annotator, the plan says which round goes from whom to whom); and Who holds what (lease_status), where a manager takes a task back from its holder through a signed revoke_assignment plan. In the team tier the review queue never lists tasks the reviewer annotated, and an opened task that this person annotated in any round shows no approve or return controls; the server refuses such a review either way. Work assigned to local before anyone registered shows up there after a team upgrade; the manager takes it back and assigns it by name without registering local. MCP and agents can still only prepare these plans; signing and execution happen in the UI. MCP always acts as local, so once people are registered it is refused exactly like an HTTP call without a registered actor.
The UI hides actions outside effective scopes. All writes still use the existing controlled action routes and server ownership/role checks. Source reads use existing project/source grants. A zero-user instance retains local personal behavior.
Image orientation
Every image is shown, annotated, imported and exported upright: the frame after applying EXIF Orientation (tag 274, values 1–8, mirrors included), which is what a browser shows when it opens the original. The original file is never rewritten; its bytes and hash stay as imported. Import records the upright width/height (the public image_width/image_height), the stored stored_width/stored_height and orientation (an unreadable tag counts as 1); older datasets resolve the same three values from the stored file header on first use, and the dataset file list, version manifests and evidence samples report them the same way; the stored manifest itself is never rewritten. The canvas (/content) and thumbnails are served as upright pixels without an orientation tag, so box, polygon and point coordinates are upright pixel coordinates. A rotated JPEG is re-encoded as JPEG at quality 95 with full-resolution chroma (a 12 MP phone photo: 6.8 MB in 0.09 s, against 24.6 MB in 0.48 s as PNG); other formats become lossless PNG. These responses carry an ETag with Cache-Control: private, no-cache, so a repeat view still checks the grant but receives a 304 instead of re-encoding.
Annotations made up to v0.18.0 were drawn on stored pixels, so they are stored-frame data. This covers workbench revisions and every annotation batch imported into a dataset before the upgrade (the platform showed those on stored pixels too) as well as training splits frozen from them. Their rows have no coordinate_frame (NULL); rows written since say display. Reading a NULL row of an EXIF-oriented image converts boxes, polygon points and image size into the upright frame, so the same object stays framed, and the revision carries coordinate_conversion (orientation, Pillow transform, stored size). Nothing is written back: history and audit stay byte-identical, and repeated upgrades or reads never convert twice.
Evidence extracted up to v0.18.0 is also in the stored frame: evidence.image_phash recorded the stored size and evidence.annotation_labels placed boxes on stored pixels. Both extractors are now version 1.1 (the other three stay 1.0). uv run datakeel rebuild-evidence does not correct those boxes: it replays the stored extraction results and never reads an image again. After upgrading, re-run the extraction once for every paired dataset that contains EXIF-oriented images. Set DATASET_ID (from GET /api/datasets) and SOURCE_VERSION_ID (the earliest version in GET /api/datasets/$DATASET_ID/versions, the one extraction reads); on an instance with registered users also set ACTOR to a person allowed to run pipelines. The script prepares the existing run_pipeline action with the current preset and executes it (a reversible local action, so no approval step):
uv run python - "$DATASET_ID" "$SOURCE_VERSION_ID" "${ACTOR:-local}" <<'PY'
import json, sys, urllib.request
from datakeel.pipeline.evidence import evidence_pipeline
dataset_id, version_id, actor = sys.argv[1:]
def post(path, body):
request = urllib.request.Request(
"http://127.0.0.1:8765/api/actions" + path,
json.dumps(body).encode(),
{"Content-Type": "application/json", "X-Datakeel-Actor": actor},
)
with urllib.request.urlopen(request) as response:
return json.load(response)
pipeline = evidence_pipeline().model_dump(mode="json")
plan = post("/run_pipeline/prepare", {"dataset_id": dataset_id, "version_id": version_id, "shards": 1, "pipeline": pipeline})
run = post(f"/{plan['id']}/execute", {"plan_digest": plan["plan_digest"], "actor": actor})
print(json.dumps({"plan_id": plan["id"], "status": run["status"]}))
PY
A worker must be running (uv run datakeel worker) to process the queued task. The cache key includes each extractor's version, so only those two extractors read the images again while the other three come from the cache; every replaced assertion is invalidated with reason extractor_version_changed, so the audit keeps the old boxes and their review decisions. For the demo's paired dataset, running uv run datakeel demo again does the same.
Lossless training round trips
AnnotationRecord adds optional polygons, native skeleton keypoints, media segments and record/shape/span/skeleton/segment attributes. Existing fields and endpoints remain compatible. Finalized records can be exported with controlled export_dataset, format: "annotations_jsonl". The archive contains annotations.jsonl with full core records; import through the existing version training import-annotations endpoint using format: "annotations_jsonl", annotations_jsonl, and a fresh idempotency_key. Native export/import preserves point IDs, order, tri-state values, coordinates and skeleton attributes exactly. Segment records additionally preserve millisecond boundaries, source duration, null versus reviewed-empty and segment array order. COCO without that schema, and YOLO/ImageFolder/HF/text JSONL with nonempty keypoints, are refused rather than dropping data. COCO writes the finalized project's single locked schema once through the annotation batch and frozen split: category unions include boxes and skeletons, point triples follow template order (v=2/1/0), num_keypoints counts positioned points, and bbox/area come only from non-missing points (a one-point zero-area bbox is allowed). COCO without that schema, and YOLO/ImageFolder/HF/text JSONL with nonempty keypoints, are refused rather than dropping data. COCO keypoint import is also explicitly refused; use native JSONL. Detection-only COCO keeps its previous fields and byte-stable archives.
webvtt is an export-only projection for reviewed segment media. Original bytes stay under media/<split>/; each same-named annotations/<split>/*.vtt contains a NOTE with sample ID and source duration, plus one cue per segment sorted by (start,end,original index). Overlap and duplicate cues are legal, and reviewed-empty media emits a valid header. Unreviewed media is refused. COCO, YOLO, ImageFolder, HF and text JSONL reject nonempty segments before modality filtering, both while preparing and while writing; use webvtt or lossless annotations_jsonl. WebVTT does not preserve attributes or record order and has no importer.
Canvas choice
Konva and react-konva are the only added direct runtime dependencies, pinned to 10.9.0 and 19.3.2. Their runtime dependency closure and shipped modules pass the existing license audit. The decision was fixed before implementation; the suitability assessments below are engineering judgments based on the linked upstream documentation.
License sources: Konva, react-konva, Fabric.js, PixiJS.
| Option | Relevant upstream capabilities | Assessment for this workbench |
|---|---|---|
| Konva, react-konva | Canvas scene graph, hit detection, layers, shapes, transforms, React bindings; MIT | Chosen. Declarative shape editing fits the existing React state/history boundary. Native DOM controls supply keyboard accessibility. |
| Fabric.js | Interactive object canvas, controls, custom properties, serialization; MIT | Suitable object editing, but its independent canvas object state would need an additional React synchronization boundary. |
| PixiJS | GPU scene rendering and continuous render-loop control; MIT | Attractive for dense animated scenes; annotation handles and form/accessibility behavior would require more custom work. |
| Canvas2D / SVG | Browser-native raster drawing / vector DOM | No library dependency, but hit testing, selection transforms and interaction synchronization would need to be maintained locally. SVG is useful for smaller DOM-based drawings. |
The Konva backing canvas stays at viewport size. Large images expose a 1024-pixel preview and then replace it with the decoded original. Zoom/pan transforms a group rather than allocating an 8000×6000 backing canvas. This is progressive image loading, not a tile server. Performance limits must be measured on the target browser/hardware.
Reproducible checks
Generate local-only fixtures (including 2000×1500, 3840×2160, and 8000×6000 images):
DATAKEEL_HOME=/tmp/workbench-home uv run python scripts/workbench_fixture.py \
--output /tmp/workbench-manifest.json --source-dir /tmp/workbench-source
DATAKEEL_HOME=/tmp/workbench-home uv run python scripts/workbench_fixture.py --serve
cd web
npm run smoke:workbench -- http://127.0.0.1:8840 /tmp/workbench-evidence /tmp/workbench-manifest.json
The runner measures W1–W6 against real APIs, checks keyboard-only annotation/submission for all five spatial/text/classification components, segment mouse and keyboard editing, offline recovery and explicit conflict decisions, 200 undo/redo steps per component, and five seconds of large-image panning. Segment W6 additionally uses 24 probed WAV tasks, a browser-decodable MP4 and a two-hour low-bitrate video with 500 segments; it checks HTTP 206/416/400 ranges, playback and seek, only-visible-window rendering, and save integrity. Keypoint coverage adds mixed box/classification templates, 24 prefetch tasks, a 4K image with 50×17-point skeletons, continuous zoom/pan, and fit/20x/pan placement and drag accuracy within one source pixel; pan/zoom must not create revisions. It records metrics and light/dark screenshots. Use a fresh fixture for each full run. PostgreSQL fixtures use --test-database --schema p30_workbench with an explicitly authorized isolated test database supplied by the host; never use an unknown/shared database. API and Web use port 8840.
Rendering/state tests use Vitest. The standard type, lint, API, token, contrast, source-hash, build and license checks remain in place. A browser launch blocked by the host sandbox is an unmeasured result, not a performance pass. Full SQLite/PostgreSQL gates and full mutation runs remain integration CI responsibilities for this task.