πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(annotation-queues): keyboard shortcuts + comment-icon disambiguation + icon alignment (LFE-7628) (#14501)
Nikita Kabardin04d2231cf540
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex b5dc65464f..eb100e3f35 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -29,17 +29,18 @@ this.## Need β command-| I need... | Command |-| --- | --- |-| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |-| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |-| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |-| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |-| Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |-| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode, bignum) |-| Big integers beyond 2^53-1 (number-precision testing) | `pnpm run seed -- trace-tree --observations 1 --payload-style bignum` |-| See all scenarios and flags | `pnpm run seed -- list --json` |-| Predict without writing | add `--dry-run` |+| I need... | Command |+| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |+| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |+| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |+| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |+| Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |+| Varied human-annotation queues (annotate UI / keyboard testing) | `pnpm run seed -- annotation-queue --core-items 12` (creates a "core types" queue covering every score-field render path + an "edge cases" queue with archived/stale/partial scores and observation/session/deleted/completed items) |+| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode, bignum) |+| Big integers beyond 2^53-1 (number-precision testing) | `pnpm run seed -- trace-tree --observations 1 --payload-style bignum` |+| See all scenarios and flags | `pnpm run seed -- list --json` |+| Predict without writing | add `--dry-run` |## Contractdiff --git a/packages/shared/scripts/seeder/README.md b/packages/shared/scripts/seeder/README.mdindex 75d413d414..26b33e83ec 100644--- a/packages/shared/scripts/seeder/README.md+++ b/packages/shared/scripts/seeder/README.md@@ -36,11 +36,12 @@ programmatic calls from the dx seed chain.## Scenarios-| Scenario | Covers | Key flags |-| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |-| `trace-tree` | one trace with a large, branching observation tree: all ten observation kinds always present, guaranteed depth backbone, hub node with many children, errors/retries/missing end times | `--observations`, `--depth`, `--breadth`, `--payload-bytes`, `--payload-style json\|text\|malformed\|unicode`, `--v4` |-| `long-session` | one session with many traces for session-detail and virtualization work; creates the Postgres `trace_sessions` row the session page requires | `--traces`, `--observations-per-trace`, `--payload-bytes`, `--minutes`, `--session-id`, `--v4` |-| `many-traces` | trace-list and filter performance via `numbers()` bulk SQL; parent/score/prompt/session links all resolve | `--count`, `--days`, `--observations-per-trace`, `--scores-per-trace`, `--rich-payloads` |+| Scenario | Covers | Key flags |+| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| `trace-tree` | one trace with a large, branching observation tree: all ten observation kinds always present, guaranteed depth backbone, hub node with many children, errors/retries/missing end times | `--observations`, `--depth`, `--breadth`, `--payload-bytes`, `--payload-style json\|text\|malformed\|unicode`, `--v4` |+| `long-session` | one session with many traces for session-detail and virtualization work; creates the Postgres `trace_sessions` row the session page requires | `--traces`, `--observations-per-trace`, `--payload-bytes`, `--minutes`, `--session-id`, `--v4` |+| `many-traces` | trace-list and filter performance via `numbers()` bulk SQL; parent/score/prompt/session links all resolve | `--count`, `--days`, `--observations-per-trace`, `--scores-per-trace`, `--rich-payloads` |+| `annotation-queue` | two human-annotation queues for the annotate UI: a "core types" queue with one of every score-field render path (categorical toggle/combobox, boolean, ranged/decimal/unranged numeric, text) over fresh trace items, and an "edge cases" queue adding archived/stale/partial scores, comments, and observation/session/deleted/completed items | `--core-items`, `--v4` (default true) |Common flags: `--project` (defaults to the seeded example project),`--environment`, `--seed`, `--id-prefix`, `--dry-run` (instant, arithmeticdiff --git a/packages/shared/scripts/seeder/scenarios/annotation-queue.ts b/packages/shared/scripts/seeder/scenarios/annotation-queue.tsnew file mode 100644index 0000000000..c239e256da--- /dev/null+++ b/packages/shared/scripts/seeder/scenarios/annotation-queue.ts@@ -0,0 +1,689 @@+import { prisma } from "../../../src/db";+import {+ createObservation,+ createObservationsCh,+ createScoresCh,+ createTrace,+ createTraceScore,+ createTracesCh,+ createEventsCh,+ EventRecordInsertType,+ ObservationRecordInsertType,+ ScoreRecordInsertType,+ TraceRecordInsertType,+} from "../../../src/server";+import { observationToEvent, traceToEvent } from "./event-mirror";+import { jitter, utcDayStartMs } from "./rng";+import {+ chunk,+ ScenarioContext,+ ScenarioDefinition,+ SeedError,+ SeedSummary,+} from "./types";+import { countRows } from "./verify";++// ---------------------------------------------------------------------------+// Score-config catalog β one of every shape the annotation form can render, so+// the keyboard UX is exercised across all its branches:+// - categorical, short labels (β€3) β ToggleGroup (1-3 badges, β/β roving)+// - categorical, long labels / >3 opts β Combobox (1-9 pick, Enter opens)+// - boolean β ToggleGroup True/False+// - numeric, ranged (int) β out-of-range complete-gate+// - numeric, ranged (decimal) β step="any" decimals+// - numeric, unranged β free number entry+// - text β textarea (Enter newline / Enter edit)+// - archived categorical β disabled / delete-only path+// A stale categorical *score* (value no longer in the config) is seeded on one+// edge item to exercise the disabled stale-chip path.+// ---------------------------------------------------------------------------+type Category = { label: string; value: number };+type ConfigDef = {+ key: string;+ name: string;+ dataType: "CATEGORICAL" | "NUMERIC" | "BOOLEAN" | "TEXT";+ categories?: Category[];+ minValue?: number;+ maxValue?: number;+ isArchived?: boolean;+ description?: string;+};++const CONFIG_DEFS: ConfigDef[] = [+ {+ key: "accuracy",+ name: "Accuracy",+ dataType: "CATEGORICAL",+ categories: [+ { label: "Fully Correct", value: 2 },+ { label: "Partially Correct", value: 1 },+ { label: "Incorrect", value: 0 },+ ],+ description: "Long labels β renders as a searchable dropdown (combobox).",+ },+ {+ key: "sentiment",+ name: "Sentiment",+ dataType: "CATEGORICAL",+ categories: [+ { label: "Pos", value: 1 },+ { label: "Neu", value: 0 },+ { label: "Neg", value: -1 },+ ],+ description: "Short labels (β€3) β renders as a toggle group.",+ },+ {+ key: "quality",+ name: "Quality",+ dataType: "CATEGORICAL",+ categories: [+ { label: "Excellent", value: 5 },+ { label: "Good", value: 4 },+ { label: "Fair", value: 3 },+ { label: "Poor", value: 2 },+ { label: "Unusable", value: 1 },+ ],+ description: "5 options β combobox; exercises 1-9 on a long option list.",+ },+ {+ key: "toxicity",+ name: "Toxicity",+ dataType: "BOOLEAN",+ categories: [+ { label: "True", value: 1 },+ { label: "False", value: 0 },+ ],+ },+ {+ key: "helpfulness",+ name: "Helpfulness (1-5)",+ dataType: "NUMERIC",+ minValue: 1,+ maxValue: 5,+ description: "Ranged integer β out-of-range completion gate.",+ },+ {+ key: "confidence",+ name: "Confidence (0-1)",+ dataType: "NUMERIC",+ minValue: 0,+ maxValue: 1,+ description: "Decimal range β step=any (e.g. 0.7 must stay valid).",+ },+ {+ key: "tokens",+ name: "Token estimate",+ dataType: "NUMERIC",+ description: "Unranged numeric β free entry, no validity gate.",+ },+ {+ key: "feedback",+ name: "Feedback",+ dataType: "TEXT",+ description: "Free-form text β Enter inserts a newline, not submit.",+ },+ {+ key: "legacy",+ name: "Legacy rating",+ dataType: "CATEGORICAL",+ isArchived: true,+ categories: [+ { label: "Yes", value: 1 },+ { label: "No", value: 0 },+ ],+ description: "Archived config β disabled, delete-only.",+ },+];++// Configs surfaced on the "core types" queue β every render path, nothing+// archived, kept small enough to process fast keyboard-first.+const CORE_KEYS = [+ "accuracy",+ "sentiment",+ "toxicity",+ "helpfulness",+ "confidence",+ "feedback",+];++const TRACE_NAMES = [+ "rag-answer",+ "summarize-doc",+ "classify-intent",+ "qa-eval-run",+ "extract-entities",+ "draft-reply",+] as const;++const QUESTIONS = [+ "What is Langfuse used for?",+ "Summarize the attached release notes.",+ "Is this support ticket urgent?",+ "Translate the message to German.",+ "Extract the action items from the call.",+] as const;++const ANSWERS = [+ "Langfuse is an open-source LLM engineering platform.",+ "The release adds keyboard-first annotation and bug fixes.",+ "Yes β the customer reports a production outage.",+ "Der Build schlug fehl; bitte erneut versuchen.",+ "1) Send the report 2) Schedule a follow-up call.",+] as const;++const annotationQueueLink = (ctx: ScenarioContext, queueId: string): string =>+ `${ctx.baseUrl}/project/${ctx.projectId}/annotation-queues/${encodeURIComponent(queueId)}/items`;++const run = async (+ ctx: ScenarioContext,+ params: Record<string, string | number | boolean>,+): Promise<SeedSummary> => {+ const startedAt = Date.now();+ const coreItems = Math.max(1, Number(params["core-items"] ?? 12));+ const withV4 = params.v4 !== false; // default true β local dev renders v4 events+ const pfx = ctx.idPrefix && ctx.idPrefix.length > 0 ? ctx.idPrefix : "annoqa";++ // Deterministic time window (6h before today's UTC midnight); jitter() adds+ // stateless per-row variation so re-runs overwrite in place.+ const windowMs = 6 * 60 * 60 * 1000;+ const endMs = utcDayStartMs();+ const startMs = endMs - windowMs;++ // Desired ids for fresh creation; reassigned to the actual row id after the+ // upserts (the queues are keyed by name, so a row created under a different+ // --id-prefix is reused β items must reference its real id, not ours).+ let coreQueueId = `${pfx}-q-core`;+ let edgeQueueId = `${pfx}-q-edge`;++ if (ctx.dryRun) {+ return {+ scenario: "annotation-queue",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: [`${pfx}-core-t0`],+ sessionIds: [`${pfx}-edge-session`],+ counts: {+ // Mirror the real-run counts: 8 edge items (partial1/2, stale, 2 obs,+ // session, missing, done), of which 8 have traces (missing has none),+ // 2 carry observations, and 9 pre-existing scores (2+3+1+3) are seeded.+ scoreConfigs: CONFIG_DEFS.length,+ queues: 2,+ items: coreItems + 8,+ traces: coreItems + 8,+ observations: 2,+ scores: 9,+ events: withV4 ? coreItems + 10 : 0,+ },+ verified: {},+ links: [+ annotationQueueLink(ctx, coreQueueId),+ annotationQueueLink(ctx, edgeQueueId),+ ],+ dryRun: true,+ durationMs: Date.now() - startedAt,+ };+ }++ // --- 1. Score configs (Postgres) ----------------------------------------+ const configId: Record<string, string> = {};+ for (const def of CONFIG_DEFS) {+ const id = `${pfx}-cfg-${def.key}`;+ configId[def.key] = id;+ const base = {+ name: def.name,+ dataType: def.dataType,+ isArchived: def.isArchived ?? false,+ description: def.description ?? null,+ minValue: def.minValue ?? null,+ maxValue: def.maxValue ?? null,+ ...(def.categories ? { categories: def.categories } : {}),+ };+ await prisma.scoreConfig.upsert({+ where: { id },+ update: base,+ create: { id, projectId: ctx.projectId, ...base },+ });+ }++ // --- 2. Queues (Postgres) -----------------------------------------------+ const coreConfigIds = CORE_KEYS.map((k) => configId[k]);+ const edgeConfigIds = CONFIG_DEFS.map((d) => configId[d.key]);++ const coreQueue = await prisma.annotationQueue.upsert({+ where: {+ projectId_name: {+ projectId: ctx.projectId,+ name: "Keyboard QA Β· core types",+ },+ },+ update: {+ description: "Every score-field type, fresh items β fast keyboard run.",+ scoreConfigIds: coreConfigIds,+ },+ create: {+ id: coreQueueId,+ projectId: ctx.projectId,+ name: "Keyboard QA Β· core types",+ description: "Every score-field type, fresh items β fast keyboard run.",+ scoreConfigIds: coreConfigIds,+ },+ });+ coreQueueId = coreQueue.id;+ const edgeQueue = await prisma.annotationQueue.upsert({+ where: {+ projectId_name: {+ projectId: ctx.projectId,+ name: "Keyboard QA Β· edge cases",+ },+ },+ update: {+ description:+ "Many fields + partial/stale/archived scores, observation/session/deleted/completed items.",+ scoreConfigIds: edgeConfigIds,+ },+ create: {+ id: edgeQueueId,+ projectId: ctx.projectId,+ name: "Keyboard QA Β· edge cases",+ description:+ "Many fields + partial/stale/archived scores, observation/session/deleted/completed items.",+ scoreConfigIds: edgeConfigIds,+ },+ });+ edgeQueueId = edgeQueue.id;++ // --- 3. ClickHouse rows + queue items -----------------------------------+ const traces: TraceRecordInsertType[] = [];+ const observations: ObservationRecordInsertType[] = [];+ const scores: ScoreRecordInsertType[] = [];+ const events: EventRecordInsertType[] = [];++ // Spread all traces (core + the 8 edge traces) across the window; derive the+ // step from the real total so timestamps never spill past the UTC-day anchor+ // (the seeder contract), even with a large --core-items.+ const totalTraces = coreItems + 8;+ const stepMs = windowMs / totalTraces;+ let traceIndex = 0;+ const newTrace = (id: string, opts?: { sessionId?: string }) => {+ const timestamp =+ startMs ++ Math.floor(traceIndex * stepMs) ++ jitter(ctx.seed, traceIndex, 1000);+ traceIndex += 1;+ const i = traceIndex;+ const trace = createTrace({+ id,+ project_id: ctx.projectId,+ environment: ctx.environment,+ session_id: opts?.sessionId ?? null,+ timestamp,+ name: TRACE_NAMES[i % TRACE_NAMES.length],+ user_id: `user-${pfx}-${i % 6}`,+ tags: ["seed", "annotation-queue"],+ metadata: { scenario: "annotation-queue" },+ input: JSON.stringify({ question: QUESTIONS[i % QUESTIONS.length] }),+ output: ANSWERS[i % ANSWERS.length],+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });+ traces.push(trace);+ if (withV4) events.push(traceToEvent(trace));+ return { trace, timestamp };+ };+ const newObservation = (+ traceId: string,+ obsId: string,+ timestamp: number,+ ) => {+ const observation = createObservation({+ id: obsId,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: "GENERATION",+ name: "answer-generation",+ start_time: timestamp,+ end_time: timestamp + 1500,+ input: JSON.stringify({ prompt: "Answer the question." }),+ output: ANSWERS[traceIndex % ANSWERS.length],+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });+ observations.push(observation);+ const parent = traces.find((t) => t.id === traceId);+ if (withV4 && parent) events.push(observationToEvent(observation, parent));+ return observation;+ };++ // Pre-existing ANNOTATION score helper (so an item shows as partly annotated).+ const annScore = (args: {+ traceId: string;+ observationId?: string | null;+ timestamp: number;+ key: string;+ value: number;+ stringValue?: string | null;+ comment?: string | null;+ queueId: string;+ }) => {+ const def = CONFIG_DEFS.find((d) => d.key === args.key);+ if (!def) return;+ scores.push(+ createTraceScore({+ id: `${args.traceId}-ann-${args.key}`,+ project_id: ctx.projectId,+ trace_id: args.traceId,+ observation_id: args.observationId ?? null,+ environment: ctx.environment,+ name: def.name,+ value: args.value,+ string_value: args.stringValue ?? null,+ data_type: def.dataType,+ source: "ANNOTATION",+ config_id: configId[args.key],+ queue_id: args.queueId,+ comment: args.comment ?? null,+ metadata: {},+ timestamp: args.timestamp,+ }),+ );+ };++ const items: Array<{+ id: string;+ queueId: string;+ objectId: string;+ objectType: "TRACE" | "OBSERVATION" | "SESSION";+ status: "PENDING" | "COMPLETED";+ completedAt?: Date | null;+ order: number;+ }> = [];+ let order = 0;+ const pushItem = (+ id: string,+ queueId: string,+ objectId: string,+ objectType: "TRACE" | "OBSERVATION" | "SESSION",+ status: "PENDING" | "COMPLETED" = "PENDING",+ completedAt: Date | null = null,+ ) => {+ items.push({+ id,+ queueId,+ objectId,+ objectType,+ status,+ completedAt,+ order: order++,+ });+ };++ // 3a. Core queue β fresh trace items.+ for (let i = 0; i < coreItems; i++) {+ const traceId = `${pfx}-core-t${i}`;+ newTrace(traceId);+ pushItem(`${pfx}-core-i${i}`, coreQueueId, traceId, "TRACE");+ }++ // 3b. Edge queue β varied, complex items.+ // (i) Two partly-annotated traces (filled comment icon, re-annotation).+ {+ const { timestamp } = newTrace(`${pfx}-edge-partial1`);+ annScore({+ traceId: `${pfx}-edge-partial1`,+ timestamp,+ key: "accuracy",+ value: 1,+ stringValue: "Partially Correct",+ comment: "Missed the second half of the answer.",+ queueId: edgeQueueId,+ });+ annScore({+ traceId: `${pfx}-edge-partial1`,+ timestamp,+ key: "toxicity",+ value: 0,+ stringValue: "False",+ queueId: edgeQueueId,+ });+ pushItem(+ `${pfx}-edge-i-partial1`,+ edgeQueueId,+ `${pfx}-edge-partial1`,+ "TRACE",+ );+ }+ {+ const { timestamp } = newTrace(`${pfx}-edge-partial2`);+ annScore({+ traceId: `${pfx}-edge-partial2`,+ timestamp,+ key: "helpfulness",+ value: 4,+ queueId: edgeQueueId,+ });+ annScore({+ traceId: `${pfx}-edge-partial2`,+ timestamp,+ key: "confidence",+ value: 0.8,+ queueId: edgeQueueId,+ });+ annScore({+ traceId: `${pfx}-edge-partial2`,+ timestamp,+ key: "sentiment",+ value: 1,+ stringValue: "Pos",+ queueId: edgeQueueId,+ });+ pushItem(+ `${pfx}-edge-i-partial2`,+ edgeQueueId,+ `${pfx}-edge-partial2`,+ "TRACE",+ );+ }+ // (ii) Stale categorical value β score string no longer in the config.+ {+ const { timestamp } = newTrace(`${pfx}-edge-stale`);+ annScore({+ traceId: `${pfx}-edge-stale`,+ timestamp,+ key: "accuracy",+ value: 99,+ stringValue: "Needs Review (v1)",+ comment: "Imported from an older rubric.",+ queueId: edgeQueueId,+ });+ pushItem(`${pfx}-edge-i-stale`, edgeQueueId, `${pfx}-edge-stale`, "TRACE");+ }+ // (iii) Observation items (annotate an observation, not the whole trace).+ for (let i = 0; i < 2; i++) {+ const traceId = `${pfx}-edge-obsT${i}`;+ const obsId = `${traceId}-o0`;+ const { timestamp } = newTrace(traceId);+ newObservation(traceId, obsId, timestamp);+ pushItem(`${pfx}-edge-i-obs${i}`, edgeQueueId, obsId, "OBSERVATION");+ }+ // (iv) Session item (trace_sessions row + traces sharing the session).+ const sessionId = `${pfx}-edge-session`;+ {+ newTrace(`${pfx}-edge-sessT0`, { sessionId });+ newTrace(`${pfx}-edge-sessT1`, { sessionId });+ await prisma.traceSession.upsert({+ where: { id_projectId: { id: sessionId, projectId: ctx.projectId } },+ update: {},+ create: {+ id: sessionId,+ projectId: ctx.projectId,+ environment: ctx.environment,+ createdAt: new Date(startMs),+ },+ });+ pushItem(`${pfx}-edge-i-session`, edgeQueueId, sessionId, "SESSION");+ }+ // (v) Deleted/missing object β no trace created β ObjectNotFound card.+ pushItem(+ `${pfx}-edge-i-missing`,+ edgeQueueId,+ `${pfx}-edge-missing-trace`,+ "TRACE",+ );+ // (vi) An already-completed item, fully scored.+ {+ const { timestamp } = newTrace(`${pfx}-edge-done`);+ annScore({+ traceId: `${pfx}-edge-done`,+ timestamp,+ key: "accuracy",+ value: 2,+ stringValue: "Fully Correct",+ queueId: edgeQueueId,+ });+ annScore({+ traceId: `${pfx}-edge-done`,+ timestamp,+ key: "toxicity",+ value: 0,+ stringValue: "False",+ queueId: edgeQueueId,+ });+ annScore({+ traceId: `${pfx}-edge-done`,+ timestamp,+ key: "helpfulness",+ value: 5,+ queueId: edgeQueueId,+ });+ pushItem(+ `${pfx}-edge-i-done`,+ edgeQueueId,+ `${pfx}-edge-done`,+ "TRACE",+ "COMPLETED",+ new Date(startMs),+ );+ }++ // --- 4. Persist queue items (Postgres) ----------------------------------+ for (const it of items) {+ const data = {+ queueId: it.queueId,+ projectId: ctx.projectId,+ objectId: it.objectId,+ objectType: it.objectType,+ status: it.status,+ completedAt: it.completedAt ?? null,+ createdAt: new Date(startMs + it.order * 1000),+ };+ await prisma.annotationQueueItem.upsert({+ where: { id: it.id },+ update: data,+ create: { id: it.id, ...data },+ });+ }++ // --- 5. Persist ClickHouse rows -----------------------------------------+ ctx.log(+ `writing ${CONFIG_DEFS.length} score configs, 2 queues, ${items.length} items, ${traces.length} traces, ${observations.length} observations, ${scores.length} scores${withV4 ? `, ${events.length} events` : ""}`,+ );+ for (const batch of chunk(traces, 1000)) await createTracesCh(batch);+ for (const batch of chunk(observations, 1000))+ await createObservationsCh(batch);+ for (const batch of chunk(scores, 1000)) await createScoresCh(batch);+ for (const batch of chunk(events, 500)) await createEventsCh(batch);++ // --- 6. Readback verification -------------------------------------------+ const traceIds = traces.map((t) => t.id);+ const verified: Record<string, number> = {+ traces: await countRows(+ "traces",+ `project_id = {projectId: String} AND id IN {traceIds: Array(String)}`,+ { projectId: ctx.projectId, traceIds },+ "uniqExact(id)",+ ),+ scores: await countRows(+ "scores",+ `project_id = {projectId: String} AND trace_id IN {traceIds: Array(String)}`,+ { projectId: ctx.projectId, traceIds },+ "uniqExact(id)",+ ),+ };+ const pgItems = await prisma.annotationQueueItem.count({+ where: {+ projectId: ctx.projectId,+ queueId: { in: [coreQueueId, edgeQueueId] },+ },+ });+ verified.queueItems = pgItems;++ if (verified.traces < traces.length) {+ throw new SeedError(+ `Readback mismatch: expected ${traces.length} traces, found ${verified.traces}`,+ );+ }+ if (verified.scores < scores.length) {+ throw new SeedError(+ `Readback mismatch: expected ${scores.length} scores, found ${verified.scores}`,+ );+ }+ if (verified.queueItems < items.length) {+ throw new SeedError(+ `Readback mismatch: expected ${items.length} queue items, found ${verified.queueItems}`,+ );+ }++ return {+ scenario: "annotation-queue",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: traceIds.slice(0, 5),+ sessionIds: [sessionId],+ counts: {+ scoreConfigs: CONFIG_DEFS.length,+ queues: 2,+ items: items.length,+ traces: traces.length,+ observations: observations.length,+ scores: scores.length,+ events: events.length,+ },+ verified,+ links: [+ annotationQueueLink(ctx, coreQueueId),+ annotationQueueLink(ctx, edgeQueueId),+ ],+ dryRun: false,+ durationMs: Date.now() - startedAt,+ };+};++export const annotationQueueScenario: ScenarioDefinition = {+ name: "annotation-queue",+ description:+ "Two human-annotation queues for testing the annotate UI keyboard-first: a 'core types' queue with one of every score-field render path (categorical toggle/combobox, boolean, ranged/decimal/unranged numeric, text) over fresh trace items, and an 'edge cases' queue adding archived/stale/partial scores, comments, and observation/session/deleted/completed items.",+ supportsV4: true,+ flags: [+ {+ flag: "core-items",+ type: "number",+ default: 12,+ description: "number of fresh trace items on the core-types queue",+ },+ {+ flag: "v4",+ type: "boolean",+ default: true,+ description:+ "mirror traces/observations into v4 events_full (on by default so they render on a v4 local dev instance)",+ },+ ],+ run,+};diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.tsindex 554abcd65b..6498a54922 100644--- a/packages/shared/scripts/seeder/scenarios/index.ts+++ b/packages/shared/scripts/seeder/scenarios/index.ts@@ -1,3 +1,4 @@+import { annotationQueueScenario } from "./annotation-queue";import { longSessionScenario } from "./long-session";import { manyTracesScenario } from "./many-traces";import { scoredTracesScenario } from "./scored-traces";@@ -12,6 +13,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {"long-session": longSessionScenario,"many-traces": manyTracesScenario,"scored-traces": scoredTracesScenario,+ "annotation-queue": annotationQueueScenario,};export * from "./types";diff --git a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsxindex 3e8715252a..708ed0bf77 100644--- a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx+++ b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx@@ -7,10 +7,32 @@ import {AnnotationQueueStatus,AnnotationQueueObjectType,} from "@langfuse/shared";-import { ArrowLeft, ArrowRight, SearchXIcon } from "lucide-react";+import { ArrowLeft, ArrowRight, Keyboard, SearchXIcon } from "lucide-react";import { useRouter } from "next/router";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Button } from "@/src/components/ui/button";+import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { cn } from "@/src/utils/tailwind";+import {+ hasModifier,+ isAppleDevice,+ isCompleteShortcut,+ isInteractiveTarget,+ isOpenDialogPresent,+ isTypingTarget,+} from "@/src/features/scores/lib/keyboardShortcuts";import { useAnnotationQueueData } from "./shared/hooks/useAnnotationQueueData";import { useAnnotationObjectData } from "./shared/hooks/useAnnotationObjectData";import { TraceAnnotationProcessor } from "./processors/TraceAnnotationProcessor";@@ -18,6 +40,18 @@ import { SessionAnnotationProcessor } from "./processors/SessionAnnotationProcesimport { ObjectNotFoundCard } from "@/src/components/ui/object-not-found-card";import { useSession } from "next-auth/react";+// A single row in the keyboard-shortcuts cheatsheet: label on the left, one or+// more <KeyboardShortcut> glyphs (passed as children) on the right.+const ShortcutRow: React.FC<{+ label: string;+ children: React.ReactNode;+}> = ({ label, children }) => (+ <div className="flex items-center justify-between gap-6 py-1.5">+ <span className="text-sm">{label}</span>+ <span className="flex items-center gap-1">{children}</span>+ </div>+);+export const AnnotationQueueItemPage: React.FC<{annotationQueueId: string;projectId: string;@@ -144,27 +178,15 @@ export const AnnotationQueueItemPage: React.FC<{// eslint-disable-next-line react-hooks/exhaustive-deps}, [relevantItem]);- if (- (seenItemData.isPending && itemId) ||- (fetchAndLockNextMutation.isPending && !itemId) ||- unseenPendingItemCount.isPending ||- objectData.isLoading ||- (!sessionLoaded && !isSingleItem)- ) {- return <Skeleton className="h-full w-full" />;- }-- if (!relevantItem && !(itemId && seenItemIds.includes(itemId))) {- return <div>No more items left to annotate!</div>;- }-const isNextItemAvailable = totalItems > progressIndex + 1;+ const isPending = relevantItem?.status === AnnotationQueueStatus.PENDING;- const handleNavigateBack = () => {- setProgressIndex(progressIndex - 1);- };+ // LFE-7628 β keyboard-first navigation/completion.+ const handleNavigateBack = useCallback(() => {+ setProgressIndex((prev) => prev - 1);+ }, []);- const handleNavigateNext = async () => {+ const handleNavigateNext = useCallback(async () => {if (progressIndex >= seenItemIds.length - 1) {const nextItem = await fetchAndLockNextMutation.mutateAsync({queueId: annotationQueueId,@@ -174,15 +196,179 @@ export const AnnotationQueueItemPage: React.FC<{setNextItemData(nextItem);}setProgressIndex(Math.max(progressIndex + 1, 0));- };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [progressIndex, seenItemIds, annotationQueueId, projectId]);- const handleComplete = async () => {+ const handleComplete = useCallback(async () => {if (!relevantItem) return;await completeMutation.mutateAsync({itemId: relevantItem.id,projectId,});- };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [relevantItem?.id, projectId]);++ // Brief highlight on the button when its shortcut fires.+ const [shortcutPulse, setShortcutPulse] = useState<+ "back" | "next" | "complete" | null+ >(null);+ const pulseTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const pulse = useCallback((which: "back" | "next" | "complete") => {+ if (pulseTimeoutRef.current) clearTimeout(pulseTimeoutRef.current);+ setShortcutPulse(which);+ pulseTimeoutRef.current = setTimeout(() => setShortcutPulse(null), 160);+ }, []);+ useEffect(+ () => () => {+ if (pulseTimeoutRef.current) clearTimeout(pulseTimeoutRef.current);+ },+ [],+ );++ // Platform-aware modifier glyph for the complete chord (β on macOS, Ctrl else).+ const [isMac, setIsMac] = useState(false);+ useEffect(() => {+ setIsMac(isAppleDevice());+ }, []);+ const modLabel = isMac ? "β" : "Ctrl";++ // "?" opens a keyboard-shortcuts cheatsheet.+ const [showShortcuts, setShowShortcuts] = useState(false);++ useEffect(() => {+ if (isSingleItem) return; // single-item view has no queue navigation+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented) return;+ if (!hasAccess) return;+ // Mirror the Skeleton gate below, and also bail while a complete is in+ // flight: this listener stays attached while the current/next item is+ // loading, so a held or repeated key during the post-complete fetch must+ // not complete or skip an item the annotator hasn't actually seen yet+ // (e.g. a quick β between β/Ctrl+Enter and onSuccess advancing would skip+ // the next item, which only flashed as a Skeleton).+ if (+ objectData.isLoading ||+ fetchAndLockNextMutation.isPending ||+ completeMutation.isPending+ )+ return;++ // Complete + next β the Cmd/Ctrl+Enter submit chord. Handled first and+ // *before* the typing guard so it works even while the annotator is in the+ // multi-line Feedback field (bare Enter there stays a newline). Defer to an+ // open drawer/dialog so it never steals that surface's own submit.+ if (isCompleteShortcut(event)) {+ if (isOpenDialogPresent()) return;+ if (isPending && !completeMutation.isPending && !objectData.isError) {+ event.preventDefault();+ // An out-of-range numeric score is vetoed on blur (no mutation fires),+ // so completing now would silently drop it. Scan *all* numeric score+ // inputs β not just the focused one β because the invalid value stays+ // in the DOM after Tabbing away (`:invalid` = native min/max overflow;+ // step="any" keeps decimals valid, mirroring validateNumericScore).+ const invalidNumber = document.querySelector<HTMLInputElement>(+ '[data-annotation-form] input[type="number"]:invalid',+ );+ if (invalidNumber) {+ invalidNumber.focus();+ invalidNumber.reportValidity();+ return;+ }+ // Text/numeric score fields persist on blur. Flush a focused one first+ // so feedback typed right before β/Ctrl+Enter isn't lost when we+ // navigate away (its onBlur fires the save mutation synchronously).+ const active = document.activeElement;+ if (+ active instanceof HTMLTextAreaElement ||+ active instanceof HTMLInputElement+ ) {+ active.blur();+ }+ pulse("complete");+ handleComplete().catch(() => {});+ }+ return;+ }++ // "?" β open the shortcuts cheatsheet.+ if (event.key === "?") {+ if (+ isTypingTarget(event.target) ||+ hasModifier(event) ||+ isOpenDialogPresent()+ )+ return;+ event.preventDefault();+ setShowShortcuts(true);+ return;+ }++ // The remaining shortcuts are bare keys: bail if another listener already+ // handled the event, while typing, on a held modifier, when a focusable+ // control / roving-focus widget owns the key, or while a dialog is open.+ if (isTypingTarget(event.target) || hasModifier(event)) return;+ if (+ isInteractiveTarget(event.target) ||+ isInteractiveTarget(document.activeElement) ||+ isOpenDialogPresent()+ )+ return;++ // Don't hijack Alt+β/β β that's the browser's back/forward on+ // Windows/Linux/ChromeOS (hasModifier lets altKey through for AltGr-typed+ // printables, but arrow keys are never AltGr-produced).+ if (event.altKey) return;++ // Next item (skip β no completion).+ if (event.key === "ArrowRight") {+ if (isNextItemAvailable) {+ event.preventDefault();+ pulse("next");+ handleNavigateNext().catch(() => {});+ }+ return;+ }+ // Previous item.+ if (event.key === "ArrowLeft") {+ if (progressIndex > 0) {+ event.preventDefault();+ pulse("back");+ handleNavigateBack();+ }+ return;+ }+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [+ isSingleItem,+ hasAccess,+ isPending,+ isNextItemAvailable,+ progressIndex,+ completeMutation.isPending,+ objectData.isError,+ objectData.isLoading,+ fetchAndLockNextMutation.isPending,+ handleComplete,+ handleNavigateNext,+ handleNavigateBack,+ pulse,+ ]);++ if (+ (seenItemData.isPending && itemId) ||+ (fetchAndLockNextMutation.isPending && !itemId) ||+ unseenPendingItemCount.isPending ||+ objectData.isLoading ||+ (!sessionLoaded && !isSingleItem)+ ) {+ return <Skeleton className="h-full w-full" />;+ }++ if (!relevantItem && !(itemId && seenItemIds.includes(itemId))) {+ return <div>No more items left to annotate!</div>;+ }const renderContent = () => {// Handle deleted object (trace/observation/session not found)@@ -240,45 +426,122 @@ export const AnnotationQueueItemPage: React.FC<{</div><div className="grid w-full shrink-0 grid-cols-1 justify-end gap-2 py-2 sm:grid-cols-[auto_min-content]">{!isSingleItem && (- <div className="flex max-h-10 flex-row gap-2">+ <div className="flex max-h-10 flex-row items-center gap-2"><span className="bg-muted grid h-9 min-w-16 items-center rounded-md p-1 text-center text-sm">{progressIndex + 1} / {totalItems}</span>- <Button- onClick={handleNavigateBack}- variant="outline"- disabled={progressIndex === 0 || !hasAccess}- size="lg"- className="px-4"+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleNavigateBack}+ variant="outline"+ disabled={progressIndex === 0 || !hasAccess}+ size="lg"+ className={cn(+ "gap-1.5 px-4 transition-colors duration-150",+ shortcutPulse === "back" &&+ "border-primary/60 bg-accent/60 ring-primary/20 ring-2",+ )}+ aria-label="Previous item"+ >+ <ArrowLeft className="h-4 w-4" />+ <KeyboardShortcut>β</KeyboardShortcut>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>Previous item</span>+ <KeyboardShortcut className="ml-2">β</KeyboardShortcut>+ </TooltipContent>+ </Tooltip>+ {/* Shortcut legend so annotators can discover keyboard-first flow */}+ <span className="text-muted-foreground hidden items-center gap-1.5 pl-1 text-[11px] lg:flex">+ <KeyboardShortcut+ className="h-4 px-1 text-[9px]"+ keys={[modLabel, "β΅"]}+ />+ complete + next Β·+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ β+ </KeyboardShortcut>+ skip+ </span>+ <button+ type="button"+ onClick={() => setShowShortcuts(true)}+ className="text-muted-foreground hover:text-foreground hidden items-center gap-1 text-[11px] transition-colors lg:flex"+ aria-label="Show keyboard shortcuts">- <ArrowLeft className="h-4 w-4" />- </Button>+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ ?+ </KeyboardShortcut>+ shortcuts+ </button></div>)}- <div className="flex w-full min-w-[265px] justify-end gap-2">+ <div className="flex w-full min-w-[265px] items-center justify-end gap-2">{!isSingleItem && (- <Button- onClick={handleNavigateNext}- disabled={!isNextItemAvailable || !hasAccess}- size="lg"- className={`px-4 ${!relevantItem ? "w-full" : ""}`}- variant="outline"- >- <ArrowRight className="h-4 w-4" />- </Button>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleNavigateNext}+ disabled={!isNextItemAvailable || !hasAccess}+ size="lg"+ className={cn(+ "gap-1.5 px-4 transition-colors duration-150",+ !relevantItem ? "w-full" : "",+ shortcutPulse === "next" &&+ "border-primary/60 bg-accent/60 ring-primary/20 ring-2",+ )}+ variant="outline"+ aria-label="Skip to next item"+ >+ <ArrowRight className="h-4 w-4" />+ <KeyboardShortcut>β</KeyboardShortcut>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>Skip to next item</span>+ <KeyboardShortcut className="ml-2">β</KeyboardShortcut>+ </TooltipContent>+ </Tooltip>)}{!!relevantItem &&(relevantItem.status === AnnotationQueueStatus.PENDING ? (- <Button- onClick={handleComplete}- size="lg"- className="mr-2 w-full"- disabled={- completeMutation.isPending || !hasAccess || objectData.isError- }- >- Mark Completed- </Button>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleComplete}+ size="lg"+ className={cn(+ "mr-2 w-full gap-1.5 transition-colors duration-150",+ shortcutPulse === "complete" && "ring-primary/40 ring-2",+ )}+ disabled={+ completeMutation.isPending ||+ !hasAccess ||+ objectData.isError+ }+ >+ <span>Mark Completed</span>+ {!isSingleItem && (+ <KeyboardShortcut+ className="bg-primary-foreground/20 text-primary-foreground border-primary-foreground/30"+ keys={[modLabel, "β΅"]}+ />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>+ {isSingleItem+ ? "Mark completed"+ : "Mark completed + go to next item"}+ </span>+ {!isSingleItem && (+ <KeyboardShortcut className="ml-2" keys={[modLabel, "β΅"]} />+ )}+ </TooltipContent>+ </Tooltip>) : (<div className="border-dark-green bg-light-green inline-flex h-9 w-full items-center justify-center rounded-md border px-8 text-sm font-medium">Completed@@ -286,6 +549,66 @@ export const AnnotationQueueItemPage: React.FC<{))}</div></div>+ <Dialog open={showShortcuts} onOpenChange={setShowShortcuts}>+ <DialogContent className="max-w-sm">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-base">+ <Keyboard className="h-4 w-4" />+ Keyboard shortcuts+ </DialogTitle>+ </DialogHeader>+ <DialogBody className="gap-4 py-3">+ <div>+ <p className="text-muted-foreground mb-1 text-xs font-medium tracking-wide uppercase">+ Navigate+ </p>+ <ShortcutRow label="Complete & go to next item">+ <KeyboardShortcut keys={[modLabel, "β΅"]} />+ </ShortcutRow>+ <ShortcutRow label="Skip to next item">+ <KeyboardShortcut>β</KeyboardShortcut>+ </ShortcutRow>+ <ShortcutRow label="Previous item">+ <KeyboardShortcut>β</KeyboardShortcut>+ </ShortcutRow>+ </div>+ <div>+ <p className="text-muted-foreground mb-1 text-xs font-medium tracking-wide uppercase">+ Score the item+ </p>+ <ShortcutRow label="Move between score fields">+ <KeyboardShortcut>β</KeyboardShortcut>+ <KeyboardShortcut>β</KeyboardShortcut>+ </ShortcutRow>+ <ShortcutRow label="Select an option on the focused field">+ <KeyboardShortcut>1</KeyboardShortcut>+ <span className="text-muted-foreground text-xs">β</span>+ <KeyboardShortcut>9</KeyboardShortcut>+ </ShortcutRow>+ <ShortcutRow label="Edit a field / open a dropdown">+ <KeyboardShortcut>β΅</KeyboardShortcut>+ </ShortcutRow>+ <ShortcutRow label="Commit a number / leave a text field">+ <KeyboardShortcut>Esc</KeyboardShortcut>+ <span className="text-muted-foreground text-xs">/</span>+ <KeyboardShortcut>Tab</KeyboardShortcut>+ </ShortcutRow>+ </div>+ <p className="text-muted-foreground border-t pt-3 text-xs">+ Bare{" "}+ <KeyboardShortcut className="h-4 px-1 text-[9px]">+ β΅+ </KeyboardShortcut>{" "}+ inside a text field (e.g. Feedback) inserts a new line β use{" "}+ <KeyboardShortcut+ className="h-4 px-1 text-[9px]"+ keys={[modLabel, "β΅"]}+ />{" "}+ to complete.+ </p>+ </DialogBody>+ </DialogContent>+ </Dialog></div>);};diff --git a/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsx b/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsxindex 2dbe08b0f4..f073106fa9 100644--- a/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsx+++ b/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsx@@ -51,7 +51,10 @@ export const AnnotationProcessingLayout: React.FC<<ResizableHandle /><ResizablePanelclassName="col-span-1 flex h-full flex-col overflow-hidden"- minSize="30%"+ // Pixel floor (not a %) so the annotate form never cramps at the default+ // split on smaller screens β the score rows need a usable width to keep+ // labels/options from wrapping to single characters. Still resizable.+ minSize="400px">{rightPanel}</ResizablePanel>diff --git a/web/src/features/comments/CommentCountIcon.tsx b/web/src/features/comments/CommentCountIcon.tsxindex 7c638031a5..6323c1f532 100644--- a/web/src/features/comments/CommentCountIcon.tsx+++ b/web/src/features/comments/CommentCountIcon.tsx@@ -1,11 +1,13 @@-import { MessageCircleMore } from "lucide-react";+// LFE-7628: general comment counts use the square speech bubble, matching the+// CommentDrawerButton, to stay distinct from per-score comment indicators.+import { MessageSquareMore } from "lucide-react";export function CommentCountIcon({ count }: { count?: number }) {if (!count) return null;return (<span className="relative mr-1 text-xs">- <MessageCircleMore className="h-4 w-4" />+ <MessageSquareMore className="h-4 w-4" /><span className="border-muted-foreground bg-muted-foreground text-muted dark:bg-muted dark:text-muted-foreground absolute -top-0.5 left-2.5 flex max-h-[0.8rem] min-w-[0.8rem] items-center justify-center rounded-sm border px-[0.2rem] text-[8px] shadow-xs">{count > 99 ? "99+" : count}</span>diff --git a/web/src/features/comments/CommentDrawerButton.tsx b/web/src/features/comments/CommentDrawerButton.tsxindex ba0842742f..4240a4226f 100644--- a/web/src/features/comments/CommentDrawerButton.tsx+++ b/web/src/features/comments/CommentDrawerButton.tsx@@ -10,7 +10,10 @@ import {import { CommentList } from "@/src/features/comments/CommentList";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { type CommentObjectType } from "@langfuse/shared";-import { MessageCircleIcon, MessageCircleOff } from "lucide-react";+// LFE-7628: general (trace/observation/session) comments use a square speech+// bubble to stay visually distinct from per-score comments, which use the round+// MessageCircle bubble in the annotation form.+import { MessageSquare, MessageSquareOff } from "lucide-react";import React, { useState, useEffect, useRef } from "react";import { useRouter } from "next/router";import { type SelectionData } from "./contexts/InlineCommentSelectionContext";@@ -113,7 +116,7 @@ export function CommentDrawerButton({className={className}disabled>- <MessageCircleOff+ <MessageSquareOffclassName={size === "sm"? "text-muted-foreground h-3.5 w-3.5"@@ -164,7 +167,7 @@ export function CommentDrawerButton({>{!!count ? (<div className="flex items-center gap-1">- <MessageCircleIcon+ <MessageSquareclassName={size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4"}/><span>Add comment</span>@@ -174,7 +177,7 @@ export function CommentDrawerButton({</div>) : (<div className="flex items-center gap-1">- <MessageCircleIcon+ <MessageSquareclassName={size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4"}/><span>Add comment</span>diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsxindex 0f31080fdc..ed96e1c077 100644--- a/web/src/features/scores/components/AnnotationForm.tsx+++ b/web/src/features/scores/components/AnnotationForm.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useMemo, useState } from "react";+import React, { useEffect, useMemo, useRef, useState } from "react";import { Button } from "@/src/components/ui/button";import {MessageCircleMore,@@ -67,6 +67,11 @@ import { useScoreMutations } from "@/src/features/scores/hooks/useScoreMutationsimport { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";import { useScoreConfigSelection } from "@/src/features/scores/hooks/useScoreConfigSelection";+import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";+import {+ hasBlockingOverlay,+ hasModifier,+} from "@/src/features/scores/lib/keyboardShortcuts";import { useRouter } from "next/router";import { useAnnotationScoreConfigs } from "@/src/features/scores/hooks/useScoreConfigs";import { Skeleton } from "@/src/components/ui/skeleton";@@ -273,6 +278,42 @@ function InnerAnnotationForm<Target extends ScoreTarget>({const [showSaving, setShowSaving] = useState(false);+ // LFE-7628 β root of this form, used to scope the global keydown listener so+ // it doesn't double-fire across multiple mounted forms (DualAnnotationContent+ // mounts an observation form and a trace form side-by-side).+ const formRootRef = useRef<HTMLDivElement | null>(null);++ // LFE-7628 β keyboard-first scoring. Real DOM focus is the single source of+ // truth: `β`/`β` (and `Tab`) move focus between fields, `1`-`9` pick an option+ // on the *focused* row, and the focused row is highlighted via `:focus-within`.+ // There is deliberately no parallel "active row" state β it previously fought+ // the browser's own focus (a focused True/False toggle showed two outlines and+ // arrows moved both the field and the toggle at once).+ const isKeyboardSelectable = (+ field: (typeof controlledFields)[number] | undefined,+ ) => {+ if (!field) return false;+ if (isTextDataType(field.dataType) || isNumericDataType(field.dataType))+ return false;+ const config = configs.find((c) => c.id === field.configId);+ return (+ !!config && !config.isArchived && (config.categories?.length ?? 0) > 0+ );+ };++ // Counts for the keyboard legend.+ const optionRowCount = controlledFields.filter((field) =>+ isKeyboardSelectable(field),+ ).length;+ const rowCount = controlledFields.filter((field) =>+ configs.some((c) => c.id === field.configId),+ ).length;+ const hasEditableRow = controlledFields.some(+ (field) =>+ configs.some((c) => c.id === field.configId) &&+ (isTextDataType(field.dataType) || isNumericDataType(field.dataType)),+ );+useEffect(() => {const isPending =createMutation.isPending ||@@ -489,7 +530,10 @@ function InnerAnnotationForm<Target extends ScoreTarget>({if (!config || !field) return;if (field.value === null || field.value === undefined) {- return; // Don't create/update score with empty value+ // Cleared to empty: remove an existing score (mirrors the text field),+ // otherwise nothing to do.+ if (field.id) handleDeleteScore(index);+ return;}// Client-side validation - don't fire mutation if invalid@@ -582,8 +626,208 @@ function InnerAnnotationForm<Target extends ScoreTarget>({);};+ // LFE-7628 β keyboard-first scoring, driven by real DOM focus with a+ // spreadsheet-style navigate-vs-edit split (single source of truth, one+ // outline, never trapped):+ // - `β` / `β` move focus between *rows* (the row container, never into a text+ // field) so navigation keeps working even when the active row is text.+ // - `Enter` drills into the focused row's control (a text/number field to+ // type, the combobox to open, a toggle to use β/β).+ // - `Esc` pops back out of an editing text field to its row.+ // - `1`-`9` pick the Nth option of the focused row (option rows only).+ // A focused text field owns its keys; an open popover/drawer suspends these.+ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (hasModifier(event)) return;++ const root = formRootRef.current;+ if (!root) return;+ // Suspend for an overlapping popover/drawer (e.g. the comment editor), but+ // NOT for a drawer this form is mounted inside (the Annotate drawer) β that+ // is an ancestor of the form, so the scheme stays alive there.+ if (hasBlockingOverlay(root)) return;+ const target = event.target;+ const editing =+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ (target instanceof HTMLElement && target.isContentEditable);++ // (`Esc` to leave a field is handled by a separate capture-phase listener+ // below, so it can stop a wrapping drawer from also dismissing.)++ // `Enter` in a single-line field (e.g. a numeric score) commits the value+ // and returns to row navigation β there is no newline to insert, so this is+ // the spreadsheet "confirm cell" gesture. Multi-line text (textarea) keeps+ // Enter for newlines and is excluded here.+ if (+ event.key === "Enter" &&+ target instanceof HTMLInputElement &&+ root.contains(target)+ ) {+ // Out-of-range numeric: surface the constraint and stay so the value+ // isn't committed-and-dropped (mirrors the β/Ctrl+Enter complete gate).+ if (+ target.type === "number" &&+ (target.validity.rangeOverflow || target.validity.rangeUnderflow)+ ) {+ event.preventDefault();+ target.reportValidity();+ return;+ }+ event.preventDefault();+ const row = target.closest<HTMLElement>("[data-score-row]");+ // Focusing the row blurs the input (its onBlur saves) and resumes β/β.+ if (row) row.focus();+ else target.blur();+ return;+ }++ // While editing a text field, leave its keys (typing, caret, number step)+ // alone β `Esc` / `Tab` move out.+ if (editing) return;+ if (rowCount === 0) return;++ // Scope to a single form (DualAnnotationContent mounts two): the form that+ // contains focus acts; if focus is on the body (nothing focused) the first+ // form acts. A control focused *outside* any form (e.g. the Mark Completed+ // / Skip / Back / "?" page buttons) must NOT drive the form β otherwise+ // β/β would hijack focus off that button into the score rows.+ const active = document.activeElement;+ const focusedForm =+ active instanceof HTMLElement+ ? active.closest("[data-annotation-form]")+ : null;+ if (focusedForm) {+ if (focusedForm !== root) return;+ } else {+ if (active && active !== document.body) return;+ if (document.querySelector("[data-annotation-form]") !== root) return;+ }++ const rowEls = Array.from(+ root.querySelectorAll<HTMLElement>("[data-score-row]"),+ );+ if (rowEls.length === 0) return;+ const currentRow =+ active instanceof HTMLElement+ ? (active.closest("[data-score-row]") as HTMLElement | null)+ : null;+ const currentPos = currentRow ? rowEls.indexOf(currentRow) : -1;++ // `β` / `β` move focus between rows (to the row container itself, never+ // into a text field β so navigation is never trapped).+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ if (rowEls.length < 2) return;+ // Navigate from a focused row, or enter from the body β but NOT from an+ // in-form non-row control (e.g. the config-picker trigger), which would+ // otherwise teleport focus to a row.+ if (currentPos < 0 && active !== document.body) return;+ event.preventDefault();+ const delta = event.key === "ArrowDown" ? 1 : -1;+ const nextPos =+ currentPos < 0+ ? delta > 0+ ? 0+ : rowEls.length - 1+ : (currentPos + delta + rowEls.length) % rowEls.length;+ rowEls[nextPos].focus();+ return;+ }++ // `Enter` drills into the focused row's control (only from the row+ // container itself β once a control is focused, Enter is left to it).+ if (event.key === "Enter") {+ if (currentRow && active === currentRow) {+ // First *enabled* control β skip the disabled stale-category chip that+ // enrichCategoryOptionsWithStaleScoreValue prepends (focusing a disabled+ // control is a no-op, so Enter would otherwise appear to do nothing).+ const control = Array.from(+ currentRow.querySelectorAll<HTMLElement>(+ "[data-score-control] :is(textarea, input, button)",+ ),+ ).find((el) => !el.matches(":disabled"));+ if (control) {+ event.preventDefault();+ // A dropdown trigger (combobox, `aria-haspopup`) opens directly so a+ // single Enter is enough (not focus-then-Enter). Radix's Popover+ // trigger opens on click. Other controls (number/text input, toggle)+ // just take focus.+ if (+ control.tagName === "BUTTON" &&+ control.getAttribute("aria-haspopup")+ ) {+ control.click();+ } else {+ control.focus();+ }+ }+ }+ return;+ }++ // `1`-`9` pick an option on the focused row (option rows only).+ if (/^[1-9]$/.test(event.key)) {+ if (currentPos < 0 || !currentRow) return;+ // Only from the row container itself or its value control β never the+ // in-row Comment / Delete buttons (else a stray digit writes a phantom+ // score). Mirrors the Enter branch's `active === currentRow` gate.+ if (+ active !== currentRow &&+ !(+ active instanceof HTMLElement &&+ active.closest("[data-score-control]")+ )+ )+ return;+ const rowIndex = Number(currentRow.getAttribute("data-score-row"));+ const field = controlledFields[rowIndex];+ if (!isKeyboardSelectable(field)) return;+ const config = configs.find((c) => c.id === field?.configId);+ const category = (config?.categories ?? [])[Number(event.key) - 1];+ if (!category) return;+ event.preventDefault();+ handleCategoricalUpsert(rowIndex, category.label);+ }+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [controlledFields, configs, rowCount]);++ // LFE-7628 β `Esc` leaves a focused score field (back to its row) WITHOUT+ // dismissing a wrapping drawer. Vaul/Radix DismissableLayer listens for Esc on+ // `document` with `{capture:true}`; a window capture-phase listener runs first+ // (window is the ancestor), so stopping propagation here prevents the drawer+ // from closing. Scoped to fields inside this form (a portaled comment popover+ // is not inside the form root, so its own Esc-to-close still works).+ useEffect(() => {+ const onEscapeCapture = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ const root = formRootRef.current;+ if (!root) return;+ const target = event.target;+ const inField =+ (target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement) &&+ root.contains(target);+ if (!inField) return;+ event.stopPropagation();+ const row = (target as HTMLElement).closest<HTMLElement>(+ "[data-score-row]",+ );+ if (row) row.focus();+ else (target as HTMLElement).blur();+ };+ window.addEventListener("keydown", onEscapeCapture, true);+ return () => window.removeEventListener("keydown", onEscapeCapture, true);+ }, []);+return (- <div className="mx-auto w-full space-y-2 overflow-y-auto md:max-h-full">+ <div+ ref={formRootRef}+ data-annotation-form+ className="mx-auto w-full space-y-2 overflow-y-auto md:max-h-full"+ ><div className="bg-background sticky top-0 z-10 rounded-sm"><AnnotateHeadershowSaving={showSaving}@@ -628,8 +872,14 @@ function InnerAnnotationForm<Target extends ScoreTarget>({) : null}</div><Form {...form}>- <form className="flex flex-col gap-4">- <div className="grid grid-flow-row gap-2">+ {/* No real submit: scores save per-field. Prevent the browser's implicit+ form submission (Enter in a single-line input would otherwise reload+ the page). */}+ <form+ className="flex flex-col gap-4"+ onSubmit={(e) => e.preventDefault()}+ >+ <div className="grid grid-flow-row gap-2.5"><FormFieldcontrol={form.control}name="scoreData"@@ -648,9 +898,22 @@ function InnerAnnotationForm<Target extends ScoreTarget>({return (<divkey={fields[index]?.id}- className="grid w-full grid-cols-[1fr_2fr] items-center gap-8 text-left"+ data-score-row={index}+ // `tabIndex={-1}` makes the row programmatically focusable+ // so β/β can land on the row itself (navigate) without+ // entering its text field. The focused row highlights via+ // `:focus-within` (single source of truth = real focus;+ // `ring-inset` so the scroll container's overflow can't+ // clip it), and `group` shows the option badges only on it.+ tabIndex={-1}+ role="group"+ aria-label={score.name}+ className={cn(+ "group grid w-full grid-cols-[1fr_2fr] items-center gap-3 rounded-md px-3 py-1 text-left transition-colors outline-none",+ "focus-within:ring-primary/30 focus-within:bg-accent/40 focus-within:ring-1 focus-within:ring-inset",+ )}>- <div className="grid h-full grid-cols-[1fr_auto] items-center">+ <div className="flex h-full min-w-0 items-center">{config.description ||isPresent(config.maxValue) ||isPresent(config.minValue) ? (@@ -658,7 +921,7 @@ function InnerAnnotationForm<Target extends ScoreTarget>({<HoverCardTrigger asChild><spanclassName={cn(- "decoration-muted-gray line-clamp-2 text-xs font-medium wrap-break-word underline decoration-dashed underline-offset-2",+ "decoration-muted-gray line-clamp-2 min-w-0 text-xs font-medium wrap-break-word underline decoration-dashed underline-offset-2",config.isArchived? "text-foreground/40": "",@@ -674,7 +937,7 @@ function InnerAnnotationForm<Target extends ScoreTarget>({) : (<spanclassName={cn(- "line-clamp-2 text-xs font-medium wrap-break-word",+ "line-clamp-2 min-w-0 text-xs font-medium wrap-break-word",config.isArchived ? "text-foreground/40" : "",)}title={score.name}@@ -689,7 +952,12 @@ function InnerAnnotationForm<Target extends ScoreTarget>({type="button"size="xs"title="Add or view score comment"- className="disabled:text-primary/50 h-full px-0 pl-1 disabled:opacity-100"+ // LFE-7628: center the comment icon vertically+ // against the score label instead of stretching+ // to the full (possibly multi-line) row height,+ // and keep it hugging the label (shrink-0) rather+ // than floating in the middle of the row.+ className="disabled:text-primary/50 flex h-auto shrink-0 items-center self-center px-0 pl-1 disabled:opacity-100"disabled={isScoreUnsaved(score.id) ||(config.isArchived && !score.comment)@@ -730,139 +998,183 @@ function InnerAnnotationForm<Target extends ScoreTarget>({</Popover></div><div className="grid grid-cols-[11fr_1fr] items-center py-1">- {isTextDataType(score.dataType) ? (- <FormField- control={form.control}- name={`scoreData.${index}.stringValue`}- render={({ field }) => (- <FormItem>- <FormControl>- <Textarea- {...field}- value={field.value ?? ""}- maxLength={TEXT_SCORE_MAX_LENGTH}- className="text-xs"- disabled={isInputDisabled(config)}- placeholder="Enter free form text..."- onBlur={() => handleTextUpsert(index)}- />- </FormControl>- <FormMessage className="text-xs" />- </FormItem>- )}- />- ) : isNumericDataType(score.dataType) ? (- <FormField- control={form.control}- name={`scoreData.${index}.value`}- render={({ field }) => (- <FormItem>- <FormControl>- <Input- {...field}- value={field.value ?? ""}- onChange={(e) => {- const value = e.target.value;- if (value === "") {- return;+ {/* data-score-control wraps only the value control so+ keyboard 1-9 scoring targets it, not the in-row+ Comment / Delete buttons. */}+ <div data-score-control>+ {isTextDataType(score.dataType) ? (+ <FormField+ control={form.control}+ name={`scoreData.${index}.stringValue`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Textarea+ {...field}+ value={field.value ?? ""}+ maxLength={TEXT_SCORE_MAX_LENGTH}+ className="text-xs"+ disabled={isInputDisabled(config)}+ placeholder="Enter free form text..."+ onBlur={() => handleTextUpsert(index)}+ />+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ ) : isNumericDataType(score.dataType) ? (+ <FormField+ control={form.control}+ name={`scoreData.${index}.value`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ {...field}+ value={field.value ?? ""}+ onChange={(e) => {+ const value = e.target.value;+ // Empty β null so the field can be+ // cleared back to blank (returning here+ // instead trapped the last digit β the+ // form kept the old value and re-rendered+ // it). onBlur deletes the score when null.+ field.onChange(+ value === "" ? null : Number(value),+ );+ }}+ type="number"+ // Mirror the config range as native+ // constraints so out-of-range values are+ // catchable via the β/Ctrl+Enter complete+ // gate's rangeOverflow/Underflow check, on+ // top of the existing onBlur JS validation.+ // `step="any"` keeps decimals valid (config+ // validation is range-only, not integer).+ min={config.minValue ?? undefined}+ max={config.maxValue ?? undefined}+ step="any"+ className="text-xs"+ disabled={isInputDisabled(config)}+ onBlur={() =>+ handleNumericUpsert(index)}- field.onChange(Number(value));- }}- type="number"- className="text-xs"- disabled={isInputDisabled(config)}- onBlur={() => handleNumericUpsert(index)}- />- </FormControl>- <FormMessage className="text-xs" />- </FormItem>- )}- />- ) : config.categories && renderSelect(categories) ? (- <FormField- control={form.control}- name={`scoreData.${index}.stringValue`}- render={({ field }) => (- <FormItem>- <FormControl>- <Combobox- name={field.name}- value={field.value ?? ""}- disabled={isInputDisabled(config)}- onValueChange={(value) => {- field.onChange(value);- handleCategoricalUpsert(index, value);- }}- options={categories.map((category) => ({- value: category.label,- disabled: category.isOutdated,- }))}- placeholder="Select category"- searchPlaceholder="Search categories..."- emptyText="No category found."- />- </FormControl>- <FormMessage className="text-xs" />- </FormItem>- )}- />- ) : (- <FormField- control={form.control}- name={`scoreData.${index}.stringValue`}- render={({ field }) => (- <FormItem>- <FormControl>- <ToggleGroup- type="single"- value={field.value ?? ""}- disabled={isInputDisabled(config)}- className={`grid grid-cols-${categories.length}`}- onValueChange={(value) => {- field.onChange(value);- handleCategoricalUpsert(index, value);- }}- >- {categories.map((category) =>- category.isOutdated ? (- <ToggleGroupItem- key={category.value}- value={category.label}- disabled- variant="outline"- className="grid grid-flow-col gap-1 px-1 text-xs font-normal text-nowrap opacity-50"- >- <span- className="truncate"- title={category.label}+ />+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ ) : config.categories &&+ renderSelect(categories) ? (+ <FormField+ control={form.control}+ name={`scoreData.${index}.stringValue`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Combobox+ name={field.name}+ value={field.value ?? ""}+ disabled={isInputDisabled(config)}+ onValueChange={(value) => {+ field.onChange(value);+ handleCategoricalUpsert(index, value);+ }}+ options={categories.map((category) => ({+ value: category.label,+ disabled: category.isOutdated,+ }))}+ placeholder="Select category"+ searchPlaceholder="Search categories..."+ emptyText="No category found."+ />+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ ) : (+ <FormField+ control={form.control}+ name={`scoreData.${index}.stringValue`}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <ToggleGroup+ type="single"+ // Horizontal roving so Radix only uses+ // β/β between True/False, leaving β/β for+ // our field navigation (no double-handling).+ orientation="horizontal"+ value={field.value ?? ""}+ disabled={isInputDisabled(config)}+ className={`grid grid-cols-${categories.length}`}+ onValueChange={(value) => {+ field.onChange(value);+ handleCategoricalUpsert(index, value);+ }}+ >+ {categories.map((category) =>+ category.isOutdated ? (+ <ToggleGroupItem+ key={category.value}+ value={category.label}+ disabled+ variant="outline"+ className="grid grid-flow-col gap-1 px-1 text-xs font-normal text-nowrap opacity-50">- {category.label}- </span>- <span>{`(${category.value})`}</span>- </ToggleGroupItem>- ) : (- <ToggleGroupItem- key={category.value}- value={category.label}- variant="outline"- className="grid grid-flow-col gap-1 px-1 text-xs font-normal text-nowrap"- >- <span- className="truncate"- title={category.label}+ <span+ className="truncate"+ title={category.label}+ >+ {category.label}+ </span>+ <span>{`(${category.value})`}</span>+ </ToggleGroupItem>+ ) : (+ <ToggleGroupItem+ key={category.value}+ value={category.label}+ variant="outline"+ className="grid grid-flow-col gap-1 px-1 text-xs font-normal text-nowrap">- {category.label}- </span>- </ToggleGroupItem>- ),- )}- </ToggleGroup>- </FormControl>- <FormMessage className="text-xs" />- </FormItem>- )}- />- )}+ <span+ className="truncate"+ title={category.label}+ >+ {category.label}+ </span>+ {(() => {+ // LFE-7628: number-key hint for this+ // option, shown only while the row is+ // focused (CSS `group-focus-within`,+ // so it tracks real focus directly).+ const digit =+ (config.categories?.findIndex(+ (c) =>+ c.label ===+ category.label,+ ) ?? -1) + 1;+ return digit >= 1 &&+ digit <= 9 ? (+ <KeyboardShortcut className="ml-0.5 hidden h-3.5 min-w-3.5 px-1 text-[9px] group-focus-within:inline-flex">+ {digit}+ </KeyboardShortcut>+ ) : null;+ })()}+ </ToggleGroupItem>+ ),+ )}+ </ToggleGroup>+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ )}+ </div>{config.isArchived ? (<Popover><PopoverTrigger asChild>@@ -923,6 +1235,41 @@ function InnerAnnotationForm<Target extends ScoreTarget>({)}/></div>+ {rowCount > 0 && (+ <div className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 px-0.5 text-[11px]">+ {rowCount > 1 && (+ <span className="flex items-center gap-1">+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ β+ </KeyboardShortcut>+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ β+ </KeyboardShortcut>+ move between fields+ </span>+ )}+ {optionRowCount > 0 && (+ <span className="flex items-center gap-1">+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ 1+ </KeyboardShortcut>+ <span className="text-muted-foreground">β¦</span>+ <KeyboardShortcut className="h-4 min-w-4 px-1 text-[9px]">+ 9+ </KeyboardShortcut>+ select option+ </span>+ )}+ {hasEditableRow && (+ <span className="flex items-center gap-1">+ <KeyboardShortcut className="h-4 px-1 text-[9px]">+ β΅+ </KeyboardShortcut>+ edit field+ </span>+ )}+ </div>+ )}</form></Form></div>diff --git a/web/src/features/scores/lib/keyboardShortcuts.ts b/web/src/features/scores/lib/keyboardShortcuts.tsnew file mode 100644index 0000000000..4945c7292f--- /dev/null+++ b/web/src/features/scores/lib/keyboardShortcuts.ts@@ -0,0 +1,146 @@+// Shared keyboard-shortcut helpers for the annotation workflow (LFE-7628).+//+// Annotators process queue items keyboard-first: select scores, then complete /+// skip / navigate without reaching for the mouse on every item. These helpers+// keep the "don't hijack typing" guard consistent across the score form and the+// queue navigation controls.++/**+ * True when a keyboard event originated from an element where the user is+ * actively typing (text input, textarea, contenteditable / role=textbox, or a+ * select). Global annotation shortcuts must bail out in that case so they never+ * swallow normal text entry (e.g. the free-form score field or comment box).+ */+export function isTypingTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;++ if (+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ target instanceof HTMLSelectElement+ ) {+ return true;+ }++ if (target.isContentEditable) return true;++ // Radix Select/Combobox dropdowns move focus onto the listbox/option elements+ // while navigating with the keyboard; bail there too so `1`-`9` don't pick a+ // score at the same time as moving through dropdown options.+ const role = target.getAttribute("role");+ if (+ role === "textbox" ||+ role === "combobox" ||+ role === "listbox" ||+ role === "option"+ )+ return true;++ return false;+}++/**+ * True when focus sits on a focusable *activation* control (button, radio,+ * `role=button`, or a Radix roving-focus item) rather than the page body.+ *+ * Queue-navigation shortcuts (Enter / arrows) must bail in that case: pressing+ * Enter on a focused button dispatches the browser-synthesized click as the+ * keydown's default action, and Radix `ToggleGroup` uses β/β for roving focus.+ * Without this guard a window-level handler would `preventDefault()` (cancelling+ * the button's click) and run the navigation/complete action instead.+ *+ * Pass `except` to allow a specific control (e.g. the Mark-Completed button)+ * through β though even there the button's own click handler does the work, so+ * bailing is harmless.+ */+export function isInteractiveTarget(+ target: EventTarget | null,+ except?: HTMLElement | null,+): boolean {+ if (!(target instanceof HTMLElement)) return false;+ if (except && (target === except || except.contains(target))) return false;++ if (target instanceof HTMLButtonElement) return true;++ const role = target.getAttribute("role");+ if (role === "button" || role === "radio") return true;++ // Radix roving-focus widgets (ToggleGroup, RadioGroup, β¦) tag their items.+ if (target.closest("[data-radix-collection-item]")) return true;++ return false;+}++/**+ * True when an open modal/drawer is present. Annotation-queue shortcuts bail so+ * they never steal Enter from a drawer's Submit button or hijack keys while a+ * dialog is the user's focus context.+ */+export function isOpenDialogPresent(): boolean {+ if (typeof document === "undefined") return false;+ return !!document.querySelector('[role="dialog"]:not([aria-hidden="true"])');+}++/**+ * True when an open overlay (dialog/drawer or dropdown menu) that does NOT+ * contain `root` is present.+ *+ * The score form suspends its shortcuts for an *overlapping* surface β the+ * comment editor popover, or the score-config picker dropdown (`role="menu"`,+ * portaled to body) whose own β/β navigation we must not steal β but must keep+ * working when it is merely mounted *inside* a drawer (the Annotate drawer on a+ * trace/observation/session detail page); that wrapping drawer is an ancestor+ * of `root`, so it doesn't count.+ */+export function hasBlockingOverlay(root: HTMLElement | null): boolean {+ if (typeof document === "undefined") return false;+ const overlays = document.querySelectorAll(+ '[role="dialog"]:not([aria-hidden="true"]), [role="menu"][data-state="open"]',+ );+ for (const overlay of overlays) {+ if (!root || !overlay.contains(root)) return true;+ }+ return false;+}++/**+ * True when the event is the "complete + next" submit chord: `Cmd+Enter`+ * (macOS) or `Ctrl+Enter` (Windows/Linux).+ *+ * This is the universal web "submit / send" gesture (Slack, GitHub, Linear, and+ * Langfuse's own NewProject / Comment forms). Unlike the bare-key shortcuts it+ * is deliberately allowed to fire *while a text field is focused* β so an+ * annotator can finish typing in the multi-line Feedback field and complete the+ * item without first blurring it. Bare `Enter` inside a textarea stays a newline.+ */+export function isCompleteShortcut(event: KeyboardEvent): boolean {+ return event.key === "Enter" && (event.metaKey || event.ctrlKey);+}++/**+ * Best-effort "is this an Apple device" check, used only to render `β` vs `Ctrl`+ * in shortcut hints. Call from an effect (not during render) to avoid an SSR+ * hydration mismatch.+ */+export function isAppleDevice(): boolean {+ if (typeof navigator === "undefined") return false;+ return navigator.userAgent.includes("Mac");+}++/**+ * True when a "hot" platform modifier key is held β reserve those for browser /+ * app shortcuts (Cmd+K, Ctrl+S, β¦) and bail out of our printable-key shortcuts.+ *+ * AltGr (Right Alt) is deliberately NOT treated as hot: on many international+ * layouts (German QWERTZ, French AZERTY, Spanish, Italian, Nordic, β¦) printable+ * characters (digits, punctuation) are produced via AltGr, which the browser+ * surfaces as `altKey=true` (and `ctrlKey=true` on Windows/Linux). Treating that+ * as a modifier would silently kill the printable-key shortcuts for those users,+ * so we detect AltGr explicitly and only treat `metaKey` / `ctrl-without-alt` as+ * hot.+ */+export function hasModifier(event: KeyboardEvent): boolean {+ if (event.getModifierState && event.getModifierState("AltGraph"))+ return false;+ return event.metaKey || (event.ctrlKey && !event.altKey);+}