Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: make folder filing, clip reordering and goal reparenting work from the keyboard (#7243)
[._.]/ Adam Eivyae9ebeffa3d4
diff --git a/client/src/a11yConventions.test.js b/client/src/a11yConventions.test.jsindex 3f345c99d5..b4e3e4eb71 100644--- a/client/src/a11yConventions.test.js+++ b/client/src/a11yConventions.test.js@@ -35,6 +35,11 @@* 7. An icon-only `<button>` sized to its bare icon (`p-1` around a* 12-14px glyph = a 22px target) instead of the 44px floor the rest of* the app enforces.+ * 8. A `DndContext` whose sensor list has no `KeyboardSensor`. dnd-kit's+ * `attributes` make every drag handle a tab stop that announces itself as+ * draggable and points at "press the space bar to pick up" instructions,+ * so a pointer-only sensor list actively instructs the user to use an+ * interaction nothing is listening for.** Scoped to git-tracked `.jsx` under `client/src` so an untracked scratch file* can't fail the suite.@@ -45,6 +50,7 @@ import { readFileSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { trackedJsxFiles as trackedJsx, trackedSourceFiles as trackedSources } from './test/trackedFiles.js';+import { escapeRegExp } from './lib/textUtils.js';const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');@@ -3323,4 +3329,84 @@ describe('a11y conventions', () => {for (const file of scanned) offenders.push(...offendersIn(file, rawSourceOf(file)));expect(offenders, `Icon-only <button> under the 44px touch-target minimum — add min-h-[44px] min-w-[44px] inline-flex items-center justify-center and leave the icon size alone:\n${offenders.join("\n")}`).toEqual([]);});++ it('registers a KeyboardSensor in every DndContext (#7243)', () => {+ // `useDraggable`/`useSortable` return `attributes` that UNCONDITIONALLY+ // carry role="button", tabIndex={0}, aria-roledescription="draggable" and+ // an aria-describedby pointing at dnd-kit's own "press the space bar to+ // pick up" instruction text. So a DndContext registered with PointerSensor+ // alone is worse than a missing feature: every handle is a tab stop that+ // tells the user to press a key nothing is listening for.+ //+ // #6911 fixed KanbanBoard and three siblings kept the defect, because+ // nothing asked the question tree-wide. This is that question. It is+ // file-local on purpose — every DndContext in this tree builds its sensors+ // in the same module — so a future call site that imports its sensors from+ // elsewhere should extend the rule rather than be quietly exempted.+ //+ // Which getter to pass is the surface's call: a SortableContext wants+ // @dnd-kit/sortable's `sortableKeyboardCoordinates`, free `useDroppable`+ // zones want `createFreeDroppableKeyboardCoordinates` from+ // lib/dndKeyboardCoordinates.js, and a board with its own geometry writes+ // one (KanbanBoard.jsx's `kanbanKeyboardCoordinates`).+ const namedImportsFrom = (src, moduleId) => {+ const re = new RegExp(`import\\s*(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*['"]${escapeRegExp(moduleId)}['"]`, 'g');+ const bindings = new Map();+ let m;+ while ((m = re.exec(src))) {+ for (const part of m[1].split(',')) {+ const [imported, local] = part.trim().split(/\s+as\s+/).map((s) => s.trim());+ if (imported) bindings.set(imported, local || imported);+ }+ }+ return bindings;+ };++ // Read off the import clause and the call expression, never off raw text:+ // a quoted `"useSensor(KeyboardSensor)"` in a title or a className must not+ // be able to forge the exemption.+ const offendersIn = (file, src) => {+ const core = namedImportsFrom(src, '@dnd-kit/core');+ const contextLocal = core.get('DndContext');+ if (!contextLocal) return [];+ const sensorLocal = core.get('KeyboardSensor');+ const useSensorLocal = core.get('useSensor');+ if (sensorLocal && useSensorLocal+ && new RegExp(`\\b${useSensorLocal}\\s*\\(\\s*${sensorLocal}\\b`).test(src)) return [];+ const index = src.indexOf(`<${contextLocal}`);+ return [`${file}:${lineOf(src, Math.max(index, 0))}`];+ };++ // Probe first — the tree is green, so nothing in it pins what the matcher+ // rejects, and a silent change of shape would turn the rule vacuous.+ const probe = (src) => offendersIn('probe.jsx', src);+ const IMPORT_BOTH = "import { DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';";+ const IMPORT_POINTER = "import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';";+ expect(probe(`${IMPORT_POINTER}\nconst s = useSensor(PointerSensor);\n<DndContext sensors={s} />`)).toEqual(['probe.jsx:3']);+ expect(probe(`${IMPORT_BOTH}\nconst s = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, { coordinateGetter }));\n<DndContext sensors={s} />`)).toEqual([]);+ // An aliased import is the same registration under another name…+ expect(probe("import { DndContext as Dnd, KeyboardSensor as KS, useSensor as sensor } from '@dnd-kit/core';\nconst s = sensor(KS, {});\n<Dnd sensors={s} />")).toEqual([]);+ // …and importing the symbol without ever registering it is not.+ expect(probe(`${IMPORT_BOTH}\nconst s = useSensor(PointerSensor);\n<DndContext sensors={s} />`)).toEqual(['probe.jsx:3']);+ // Neither is a quoted mention, nor one from some other module.+ expect(probe(`${IMPORT_POINTER}\n<DndContext title="useSensor(KeyboardSensor)" />`)).toEqual(['probe.jsx:2']);+ expect(probe(`${IMPORT_POINTER}\nimport { KeyboardSensor, useSensor } from './fake';\nconst s = useSensor(KeyboardSensor);\n<DndContext sensors={s} />`)).toEqual(['probe.jsx:4']);+ // A file that never mounts a DndContext is out of the rule's remit, even+ // when it uses dnd-kit for something else.+ expect(probe("import { useDraggable } from '@dnd-kit/core';\nconst d = useDraggable({ id });")).toEqual([]);++ // `maskComments` is the most expensive routine in this file, so mask only+ // the handful of files that mention dnd-kit at all — the raw substring is a+ // superset of "imports DndContext", and a commented-out import is still+ // rejected because the masked source is what `offendersIn` then reads.+ const scanned = trackedSourceFiles().filter((file) => rawSourceOf(file).includes('@dnd-kit/core'));+ const withContext = scanned.filter((file) => namedImportsFrom(maskedSourceOf(file), '@dnd-kit/core').has('DndContext'));+ // Assert the scan really found the live call sites, so a change to the file+ // walker can't turn this into a pass over zero DndContexts.+ expect(withContext.length, 'no client source mounts a DndContext — has trackedSourceFiles() changed its path shape?').toBeGreaterThanOrEqual(7);++ const offenders = [];+ for (const file of withContext) offenders.push(...offendersIn(file, maskedSourceOf(file)));+ expect(offenders, `DndContext registered without a KeyboardSensor — every dnd-kit handle already announces itself as draggable and tells the user to press Space, so a pointer-only sensor list is a WCAG 2.1.1 failure. Add useSensor(KeyboardSensor, { coordinateGetter }) (sortableKeyboardCoordinates for a SortableContext, createFreeDroppableKeyboardCoordinates from lib/dndKeyboardCoordinates.js for free droppables):\n${offenders.join('\n')}`).toEqual([]);+ });});diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsxindex 47df641cc0..4427bfde81 100644--- a/client/src/components/goals/GoalsListView.jsx+++ b/client/src/components/goals/GoalsListView.jsx@@ -4,7 +4,8 @@ import {ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag, Link2, Crown, Star, Wand2, AlertTriangle} from 'lucide-react';import toast from '../ui/Toast';-import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors, useDraggable, useDroppable } from '@dnd-kit/core';+import { DndContext, DragOverlay, KeyboardSensor, PointerSensor, useSensor, useSensors, useDraggable, useDroppable } from '@dnd-kit/core';+import { createFreeDroppableKeyboardCoordinates, keyboardAwareCollisionDetection } from '../../lib/dndKeyboardCoordinates';import * as api from '../../services/api';import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';import { GOALS_LIST_PATH, goalDetailPath } from './goalConstants';@@ -15,6 +16,13 @@ import ProviderModelSelector from '../ProviderModelSelector';import { enabledApiProviderFilter } from '../../utils/providers';import { clickableProps } from '../../lib/a11yKeyboard.js';+// Arrow keys step row-to-row through the tree instead of nudging the drag 25px+// at a time. The dragged goal's own row is skipped: it IS a drop target (every+// row is), but dropping a goal onto itself is a no-op `handleDragEnd` discards.+const goalsKeyboardCoordinates = createFreeDroppableKeyboardCoordinates({+ isSkipped: ({ data, active }) => Boolean(data?.goal?.id) && data.goal.id === active?.data?.current?.goal?.id,+});+function urgencyIndicator(urgency) {if (urgency == null) return null;const color = urgency >= 0.7 ? 'bg-red-400' : urgency >= 0.4 ? 'bg-yellow-400' : 'bg-port-success';@@ -76,8 +84,12 @@ function GoalRow({ goal, depth, expandedIds, onToggle, onSelect, selectedId, onAonClick={() => onSelect(goal)}{...clickableProps(() => onSelect(goal))}>+ {/* dnd-kit's `attributes` make this a focusable role="button", so it+ needs a name of its own — otherwise it is announced as an unlabeled+ button sitting in front of every goal in the tree. */}<divclassName="shrink-0 cursor-grab active:cursor-grabbing touch-none hidden sm:block"+ aria-label={`Reparent ${goal.title}`}{...attributes}{...listeners}onClick={e => e.stopPropagation()}@@ -207,7 +219,10 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {const navigate = useNavigate();- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),+ useSensor(KeyboardSensor, { coordinateGetter: goalsKeyboardCoordinates }),+ );// Which goal is open comes from the route, so the panel is shareable/bookmarkable and// survives a reload. `goalsLoaded` keeps "the tree failed to load" distinct from "this@@ -344,6 +359,39 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {const handleDragCancel = useCallback(() => setDraggedGoal(null), []);+ // dnd-kit's stock announcements read out `drag-<uuid>`. Name the goals the+ // user is reparenting instead, and say which target the drag is currently on.+ const accessibility = useMemo(() => {+ const goalTitle = (node) => node?.data?.current?.goal?.title || 'goal';+ const targetName = (over) => {+ if (!over) return null;+ if (over.data?.current?.root) return 'the top level';+ const title = over.data?.current?.goal?.title;+ return title ? `under "${title}"` : null;+ };+ return {+ announcements: {+ onDragStart: ({ active }) => `Picked up ${goalTitle(active)}. Use the arrow keys to choose a new parent, Space to move it there, or Escape to cancel.`,+ onDragOver: ({ active, over }) => {+ const target = targetName(over);+ return target+ ? `${goalTitle(active)} is over ${target}.`+ : `${goalTitle(active)} is not over a drop target.`;+ },+ onDragEnd: ({ active, over }) => {+ const target = targetName(over);+ return target+ ? `Moved ${goalTitle(active)} ${target}.`+ : `${goalTitle(active)} was dropped outside the tree and did not move.`;+ },+ onDragCancel: ({ active }) => `Cancelled moving ${goalTitle(active)}. It stayed where it was.`,+ },+ screenReaderInstructions: {+ draggable: 'To reparent this goal, press Space or Enter. While moving, use the arrow keys to choose a new parent goal or the top-level drop zone, then press Space to move it there, or Escape to cancel.',+ },+ };+ }, []);+return (<div className="h-full flex flex-col sm:flex-row relative"><div className="flex-1 flex flex-col overflow-hidden min-w-0">@@ -482,6 +530,8 @@ export default function GoalsListView({ data, onRefresh, selectedGoalId }) {{/* Tree list with drag-and-drop */}<DndContextsensors={sensors}+ accessibility={accessibility}+ collisionDetection={keyboardAwareCollisionDetection}onDragStart={handleDragStart}onDragEnd={handleDragEnd}onDragCancel={handleDragCancel}diff --git a/client/src/components/goals/GoalsListView.test.jsx b/client/src/components/goals/GoalsListView.test.jsxindex 81c522a187..ad54648831 100644--- a/client/src/components/goals/GoalsListView.test.jsx+++ b/client/src/components/goals/GoalsListView.test.jsx@@ -1,14 +1,16 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, act } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, Routes, Route, useLocation, useParams } from 'react-router';+import { stubSequentialLayout, pressKey, pressKeyTimes, dndAnnouncement } from '../../test/dndKeyboardDrag';-const { toastError, toastSuccess, organizeGoals, createGoal, applyGoalOrganization } = vi.hoisted(() => ({+const { toastError, toastSuccess, organizeGoals, createGoal, applyGoalOrganization, updateGoal } = vi.hoisted(() => ({toastError: vi.fn(),toastSuccess: vi.fn(),organizeGoals: vi.fn(),createGoal: vi.fn(),applyGoalOrganization: vi.fn(),+ updateGoal: vi.fn(),}));vi.mock('../ui/Toast', () => ({@@ -18,6 +20,7 @@ vi.mock('../../services/api', () => ({createGoal,organizeGoals,applyGoalOrganization,+ updateGoal,}));vi.mock('../../hooks/useProviderModels', () => ({default: () => ({@@ -216,3 +219,51 @@ describe('routed goal selection', () => {expect(screen.queryByText('Goal not found')).not.toBeInTheDocument();});});++// Guards #7243: every goal row carries a grip that dnd-kit makes a focusable+// role="button" announcing itself as draggable, but the view registered a+// PointerSensor only — so the handle advertised a keyboard interaction that did+// nothing. Reparenting is also reachable through GoalEditForm's "Parent Goal"+// select, so this is not the hard block LibraryPane was; the dead affordance in+// front of every goal in the tree is the defect.+describe('GoalsListView keyboard reparenting (#7243)', () => {+ let restoreLayout;+ beforeEach(() => {+ updateGoal.mockResolvedValue({ id: 'g2', parentId: 'g1' });+ restoreLayout = stubSequentialLayout();+ });+ afterEach(() => restoreLayout());++ const pickUp = async (goalTitle) => {+ await renderList();+ const handle = screen.getByLabelText(`Reparent ${goalTitle}`);+ handle.focus();+ await pressKey('Space', handle);+ };++ it('reparents a goal with Space, arrows and Space', async () => {+ await pickUp('Restore the boat');+ expect(dndAnnouncement()).toMatch(/Restore the boat/);++ // Drop targets in document order are the root zone, then each goal row.+ // Walk to the top of that list (the getter clamps rather than wrapping),+ // then step down one to the first goal row.+ await pressKeyTimes('ArrowUp', 3);+ expect(dndAnnouncement()).toMatch(/over the top level/);+ await pressKey('ArrowDown');+ expect(dndAnnouncement()).toMatch(/under "Sail across an ocean"/);++ await pressKey('Space');+ expect(updateGoal).toHaveBeenCalledWith('g2', { parentId: 'g1' }, { silent: true });+ });++ it('cancels on Escape without reparenting', async () => {+ await pickUp('Restore the boat');+ await pressKeyTimes('ArrowUp', 3);+ await pressKey('ArrowDown');+ await pressKey('Escape');++ expect(updateGoal).not.toHaveBeenCalled();+ expect(dndAnnouncement()).toMatch(/Cancelled moving Restore the boat/);+ });+});diff --git a/client/src/components/media/VideoTimelineLanes.jsx b/client/src/components/media/VideoTimelineLanes.jsxindex 50d596239e..9e8db483cb 100644--- a/client/src/components/media/VideoTimelineLanes.jsx+++ b/client/src/components/media/VideoTimelineLanes.jsx@@ -59,6 +59,24 @@ export const TimelineBlock = memo(function TimelineBlock({width: `${Math.max(60, dur * pxPerSec)}px`,opacity: isDragging ? 0.4 : 1,};+ // This block is both the drag handle and the click-to-select target, and+ // dnd-kit's keyboard activator lives on `listeners.onKeyDown` — so the+ // `clickableProps` spread that used to sit here REPLACED that activator and+ // left the block announcing itself as draggable with no working pickup+ // (#7243). Split the keys instead: Enter selects, Space and the arrows that+ // follow it belong to dnd-kit. The `currentTarget` guard is the one+ // `clickableProps` carries, so Enter on the inner Remove button still removes.+ // `role`/`tabIndex` below repeat what `attributes` already sets, so the+ // clickable-element guard reads the triple off the tag.+ const handleKeyDown = (event) => {+ if (event.currentTarget != null && event.target !== event.currentTarget) return;+ if (event.key !== 'Enter') {+ listeners?.onKeyDown?.(event);+ return;+ }+ event.preventDefault();+ onSelect(clip._key);+ };return (<divref={setNodeRef}@@ -73,7 +91,9 @@ export const TimelineBlock = memo(function TimelineBlock({onClick={() => onSelect(clip._key)}{...attributes}{...listeners}- {...clickableProps(() => onSelect(clip._key))}+ role="button"+ tabIndex={0}+ onKeyDown={handleKeyDown}>{thumbSrc && (<img src={thumbSrc} alt="" draggable={false} className="w-full h-full object-cover rounded-md opacity-80" />diff --git a/client/src/components/writers-room/LibraryPane.jsx b/client/src/components/writers-room/LibraryPane.jsxindex 7474f240a1..afab794851 100644--- a/client/src/components/writers-room/LibraryPane.jsx+++ b/client/src/components/writers-room/LibraryPane.jsx@@ -1,6 +1,10 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { Folder, FolderPlus, FilePlus, FileText, ChevronDown, ChevronRight, Trash2, GripVertical, PanelLeftClose } from 'lucide-react';-import { DndContext, DragOverlay, PointerSensor, useDraggable, useDroppable, useSensor, useSensors } from '@dnd-kit/core';+import {+ DndContext, DragOverlay, KeyboardSensor, PointerSensor,+ useDraggable, useDroppable, useSensor, useSensors,+} from '@dnd-kit/core';+import { createFreeDroppableKeyboardCoordinates, keyboardAwareCollisionDetection } from '../../lib/dndKeyboardCoordinates';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import {@@ -15,6 +19,11 @@ import { KIND_LABELS } from './labels';const UNFILED_DROP_ID = 'wr-unfiled';+// Arrow keys step between the folder rows and the Unfiled zone rather than+// nudging the drag 25px at a time, which is dnd-kit's default and skips right+// past a collapsed folder row.+const libraryKeyboardCoordinates = createFreeDroppableKeyboardCoordinates();+export default function LibraryPane({folders, works, activeWorkId, onSelectWork, onRefresh, onCollapse,creatingWork, onCreatingWorkChange,@@ -93,13 +102,20 @@ export default function LibraryPane({// PointerSensor with a small activation distance so a quick click still// selects the work — only an actual drag gesture starts a DnD operation.- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));+ // KeyboardSensor is not optional here: filing a work into a folder is the+ // ONLY write of `folderId` in the client, so without it a keyboard-only user+ // can never move a work in or out of a folder (WCAG 2.1.1).+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),+ useSensor(KeyboardSensor, { coordinateGetter: libraryKeyboardCoordinates }),+ );const [draggingWork, setDraggingWork] = useState(null);const handleDragStart = useCallback((event) => {setDraggingWork(event.active.data.current?.work || null);}, []);+const handleDragEnd = useCallback(async (event) => {setDraggingWork(null);const { active, over } = event;@@ -119,6 +135,45 @@ export default function LibraryPane({onRefresh?.();}, [folders, onRefresh]);+ // Escape (and a pointer drag released outside any zone) ends the drag without+ // a drop; without this the overlay and the "Drop here to unfile" affordance+ // stay on screen for good.+ const handleDragCancel = useCallback(() => setDraggingWork(null), []);++ // dnd-kit's stock announcements only ever say "draggable item N", which is an+ // id. Name the work and the folder instead — for the Unfiled zone and for+ // every folder, resolved off the drop target's own `folderId`.+ const accessibility = useMemo(() => {+ const zoneName = (over) => {+ if (!over) return null;+ const folderId = over.data?.current?.folderId ?? null;+ if (!folderId) return 'Unfiled';+ return folders.find((f) => f.id === folderId)?.name || 'a folder';+ };+ const workTitle = (active) => active?.data?.current?.work?.title || 'work';+ return {+ announcements: {+ onDragStart: ({ active }) => `Picked up ${workTitle(active)}. Use the arrow keys to choose a folder, Space to file it there, or Escape to cancel.`,+ onDragOver: ({ active, over }) => {+ const zone = zoneName(over);+ return zone+ ? `${workTitle(active)} is over ${zone}.`+ : `${workTitle(active)} is not over a folder.`;+ },+ onDragEnd: ({ active, over }) => {+ const zone = zoneName(over);+ return zone+ ? `Filed ${workTitle(active)} in ${zone}.`+ : `${workTitle(active)} was dropped outside a folder and did not move.`;+ },+ onDragCancel: ({ active }) => `Cancelled moving ${workTitle(active)}. It stayed where it was.`,+ },+ screenReaderInstructions: {+ draggable: 'To move this work into a folder, press Space or Enter. While moving, use the arrow keys to choose a folder or the Unfiled section, then press Space to file it there, or Escape to cancel.',+ },+ };+ }, [folders]);+const renderWorkRow = (work) => (<WorkRowkey={work.id}@@ -214,7 +269,14 @@ export default function LibraryPane({</form>)}- <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>+ <DndContext+ sensors={sensors}+ accessibility={accessibility}+ collisionDetection={keyboardAwareCollisionDetection}+ onDragStart={handleDragStart}+ onDragEnd={handleDragEnd}+ onDragCancel={handleDragCancel}+ ><ul className="space-y-1">{folders.length === 0 && grouped.get(null).length === 0 && !creatingFolder && !creatingWork && (<li className="px-2 py-3 text-center">diff --git a/client/src/components/writers-room/LibraryPane.test.jsx b/client/src/components/writers-room/LibraryPane.test.jsxindex 7b35fde10b..d7e91432b1 100644--- a/client/src/components/writers-room/LibraryPane.test.jsx+++ b/client/src/components/writers-room/LibraryPane.test.jsx@@ -1,6 +1,7 @@import { useState } from 'react';-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, fireEvent } from '@testing-library/react';+import { stubSequentialLayout, pressKey, pressKeyTimes, dndAnnouncement } from '../../test/dndKeyboardDrag';// Regression guard for #3569: the Writers Room library header actions wrapped// 14px icons in `p-1`, giving them ~22x22px of tappable area — small enough@@ -16,6 +17,11 @@ vi.mock('../../services/apiWritersRoom', () => ({updateWritersRoomWork: vi.fn(),}));+vi.mock('../ui/Toast', () => ({+ default: Object.assign(() => {}, { success: vi.fn(), error: vi.fn() }),+}));++import { updateWritersRoomWork } from '../../services/apiWritersRoom';import LibraryPane from './LibraryPane';function LibraryPaneHarness(props) {@@ -92,3 +98,63 @@ describe('LibraryPane header actions (#3569)', () => {expect(screen.queryByText(/Click .* to start/)).toBeNull();});});++// Guards #7243: filing a work into a folder is the ONLY write of `folderId`+// anywhere in the client, and this pane registered a PointerSensor alone. Every+// work's grip is a `<button>` carrying dnd-kit's `aria-roledescription="draggable"`+// and its "press the space bar to pick up" instructions, so the pane was telling+// keyboard users to do something nothing listened for — and there is no other+// path to the same edit, which makes it a WCAG 2.1.1 failure rather than a+// missing convenience.+describe('LibraryPane keyboard filing (#7243)', () => {+ const FOLDERS = [{ id: 'f-drafts', name: 'Drafts' }, { id: 'f-archive', name: 'Archive' }];+ const WORKS = [{+ id: 'w-1', title: 'Example Story', kind: 'short-story', wordCount: 120,+ folderId: null, updatedAt: '2026-01-01T00:00:00.000Z',+ }];++ let restoreLayout;+ beforeEach(() => {+ vi.clearAllMocks();+ updateWritersRoomWork.mockResolvedValue({ id: 'w-1', folderId: 'f-drafts' });+ restoreLayout = stubSequentialLayout();+ });+ afterEach(() => restoreLayout());++ const pickUpWork = async () => {+ renderPane({ folders: FOLDERS, works: WORKS });+ const handle = screen.getByRole('button', { name: 'Drag Example Story' });+ handle.focus();+ await pressKey('Space', handle);+ };++ it('files a work into a folder with Space, arrows and Space', async () => {+ await pickUpWork();+ expect(dndAnnouncement()).toMatch(/Example Story/);++ // The pane's three drop zones are Unfiled, then each folder row. Walk to+ // the top of that list (the getter clamps rather than wrapping), so one+ // ArrowDown lands on the first folder from a known position.+ await pressKeyTimes('ArrowUp', 3);+ expect(dndAnnouncement()).toMatch(/over Unfiled/);+ await pressKey('ArrowDown');+ expect(dndAnnouncement()).toMatch(/over Drafts/);++ await pressKey('Space');+ expect(updateWritersRoomWork).toHaveBeenCalledWith('w-1', { folderId: 'f-drafts' }, { silent: true });+ expect(dndAnnouncement()).toMatch(/Filed Example Story in Drafts/);+ });++ it('cancels on Escape without moving the work', async () => {+ await pickUpWork();+ await pressKeyTimes('ArrowUp', 3);+ await pressKey('ArrowDown');+ await pressKey('Escape');++ expect(updateWritersRoomWork).not.toHaveBeenCalled();+ expect(dndAnnouncement()).toMatch(/Cancelled moving Example Story/);+ // The overlay and the "drop here to unfile" affordance are driven by the+ // same state; a cancel that never cleared it would strand both on screen.+ expect(screen.queryByText('Drop here to unfile')).toBeNull();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 75228bc301..4a38432794 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -141,6 +141,7 @@ grep -i "what you want to do" client/src/lib/README.md| `cosTaskType.js` | CoS task-learning bucket resolver for ETA surfaces: `extractCosTaskType(task)` mirrors the server's metadata-first `extractTaskType` handling for live tasks and archived-agent projections, so `self-improve:*`, `user-task`, and fallback estimates use the same history bucket that recorded the run. || `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). || `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. |+| `dndKeyboardCoordinates.js` | `createFreeDroppableKeyboardCoordinates({ isSkipped? })` + `keyboardAwareCollisionDetection` — build a `KeyboardSensor` `coordinateGetter` for a `DndContext` whose drop targets are free `useDroppable` zones (no `SortableContext`): arrow keys JUMP to the adjacent zone in visual order instead of nudging 25px. Use it in `LibraryPane` / `GoalsListView`-shaped surfaces; a sortable list uses `@dnd-kit/sortable`'s `sortableKeyboardCoordinates` instead. Pair the getter with `keyboardAwareCollisionDetection` (keeps `rectIntersection` for pointer drags, `closestCenter` for keyboard ones) so adding keyboard support does not change where a mouse drop lands. || `dndTransform.js` | `dndTransformToCss(transform)` — render a dnd-kit `useSortable` transform (`{ x, y, scaleX, scaleY }` or `null`) as a CSS `transform` string. Owned replacement for `@dnd-kit/utilities`' `CSS.Transform.toString()`; use it in every `useSortable` style object instead of re-adding that dependency. || `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. || `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS. Re-exported from `server/lib/extensionErrors.js`, which the ingest route filters on. |diff --git a/client/src/lib/dndKeyboardCoordinates.js b/client/src/lib/dndKeyboardCoordinates.jsnew file mode 100644index 0000000000..543b35a690--- /dev/null+++ b/client/src/lib/dndKeyboardCoordinates.js@@ -0,0 +1,103 @@+/**+ * Keyboard coordinate getters for `@dnd-kit/core`'s `KeyboardSensor`.+ *+ * `@dnd-kit/sortable` ships `sortableKeyboardCoordinates` for a+ * `SortableContext`, and a board with its own geometry writes a bespoke getter+ * (`KanbanBoard.jsx`'s `kanbanKeyboardCoordinates`). What has no shipped answer+ * is the shape in between: a `DndContext` whose drop targets are FREE+ * `useDroppable` zones — a folder list a work is filed into, a goal tree a goal+ * is reparented onto — with no sort order to interpolate against.+ *+ * dnd-kit's default getter only nudges the drag by 25px per arrow press, so a+ * user crossing a tall zone presses the key a dozen times and a zone shorter+ * than the step can be skipped entirely. This getter instead JUMPS to the+ * adjacent drop zone in visual order, which is the interaction a pointer user+ * gets and the one the announcements describe.+ *+ * `keyboardAwareCollisionDetection` is the other half: the jump lands the drag+ * on a zone's centre, which `closestCenter` resolves and dnd-kit's default+ * `rectIntersection` may not.+ */++import { closestCenter, rectIntersection } from '@dnd-kit/core';++/**+ * dnd-kit's default collision detection for pointer drags, `closestCenter` for+ * keyboard ones.+ *+ * A keyboard drag needs `closestCenter`: the coordinate getters above move the+ * drag to a zone's centre, and with `rectIntersection` a destination smaller+ * than the dragged item (a collapsed folder row under a tall work row) still+ * resolves to no target at all, so the drop silently does nothing. Applying+ * `closestCenter` to POINTER drags as well is the tempting one-line version and+ * a behavior change: it always finds a nearest target, so a mouse drop released+ * over empty space would file the item into whichever zone happened to be+ * closest instead of leaving it alone.+ *+ * @param {object} args dnd-kit collision-detection arguments+ */+export function keyboardAwareCollisionDetection(args) {+ return args.pointerCoordinates ? rectIntersection(args) : closestCenter(args);+}++// Both axes traverse the same one-dimensional list of zones: these surfaces are+// vertical lists, and a user who reaches for Left/Right on one should not find+// the key dead.+const DIRECTIONS = {+ ArrowDown: 1,+ ArrowRight: 1,+ ArrowUp: -1,+ ArrowLeft: -1,+};++/**+ * Build a `coordinateGetter` that steps a keyboard drag between the enabled+ * droppables of a `DndContext`, ordered top-to-bottom then left-to-right.+ *+ * @param {object} [options]+ * @param {(entry: { id: string|number, data: object, active: object|null }) => boolean} [options.isSkipped]+ * Return true for a zone the drag must step OVER rather than land on — a+ * target that would be a no-op, such as the dragged item's own row. Skipped+ * zones are still traversed, so a run of them costs one keypress, not one+ * per zone.+ * @returns {(event: KeyboardEvent, args: object) => ({ x: number, y: number } | undefined)}+ */+export function createFreeDroppableKeyboardCoordinates({ isSkipped } = {}) {+ return function freeDroppableKeyboardCoordinates(event, { active, context }) {+ const direction = DIRECTIONS[event.code];+ if (!direction) return undefined;++ const activeDescriptor = context?.active || active || null;+ const zones = (context?.droppableContainers?.getEnabled?.() || [])+ .map((container) => ({+ id: container.id,+ data: container.data?.current || {},+ rect: context.droppableRects?.get(container.id),+ }))+ .filter((zone) => zone.rect)+ .sort((left, right) => (left.rect.top - right.rect.top) || (left.rect.left - right.rect.left));+ if (zones.length === 0) return undefined;++ // No current target means the drag started over nothing (an empty or+ // scrolled-away region). Enter the list from the end the key points at+ // rather than making the first keypress do nothing.+ const currentIndex = zones.findIndex((zone) => zone.id === context?.over?.id);+ let index = currentIndex === -1+ ? (direction > 0 ? 0 : zones.length - 1)+ : currentIndex + direction;+ while (zones[index] && isSkipped?.({ ...zones[index], active: activeDescriptor })) index += direction;++ const target = zones[index];+ if (!target) return undefined;++ // KeyboardSensor reads the result as the dragged node's top-left corner.+ // Centering it on the zone keeps `closestCenter` from preferring a+ // neighbour when the destination is taller than the item being dragged.+ const activeRect = activeDescriptor?.rect?.current?.translated+ || activeDescriptor?.rect?.current?.initial;+ return {+ x: target.rect.left + (target.rect.width - (activeRect?.width || 0)) / 2,+ y: target.rect.top + (target.rect.height - (activeRect?.height || 0)) / 2,+ };+ };+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex ffec224c02..3465a79ecd 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -107,6 +107,7 @@ export * from './consoleFilters.js';export * from './cosTaskType.js';export * from './diffLines.js';export * from './diffWords.js';+export * from './dndKeyboardCoordinates.js';export * from './dndTransform.js';export * from './downloadBlob.js';export * from './extensionErrors.js';diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsxindex 15cc7f925f..a6452dba8b 100644--- a/client/src/pages/VideoTimelineEditor.jsx+++ b/client/src/pages/VideoTimelineEditor.jsx@@ -3,6 +3,7 @@ import { useEffect, useRef, useState, useCallback, useMemo } from 'react';import { useParams, useNavigate } from 'react-router';import {DndContext,+ KeyboardSensor,PointerSensor,useSensor,useSensors,@@ -12,6 +13,7 @@ import {SortableContext,arrayMove,horizontalListSortingStrategy,+ sortableKeyboardCoordinates,} from '@dnd-kit/sortable';import {Play, Pause, Save, Film, Loader2, ArrowLeft, Volume2, VolumeX,@@ -45,6 +47,18 @@ import {const EMPTY_LANES = { segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] } };+// A timeline block is both the drag handle and the click-to-select target, and+// dnd-kit's default keyboard codes claim Enter as well as Space. Narrowing the+// drag to Space leaves Enter free to select the block, so the two activations+// can't fight over one keystroke (see `TimelineBlock` in+// components/media/VideoTimelineLanes.jsx). Tab stays an end key so tabbing+// away can't strand a drag in flight.+const TIMELINE_KEYBOARD_CODES = {+ start: ['Space'],+ cancel: ['Escape'],+ end: ['Space', 'Tab'],+};+// Default lengths for a newly-added still/overlay/bed. The bed length is a// guess — the client can't probe the file — so the server clamps it down to// the real duration at render time.@@ -140,7 +154,15 @@ export default function VideoTimelineEditor() {// across the setProject that every successful save performs.const updatedAtRef = useRef(null);- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));+ // Reordering segments by dragging is the only clip-reorder path on this page,+ // so the KeyboardSensor is what makes the timeline orderable without a mouse.+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ keyboardCodes: TIMELINE_KEYBOARD_CODES,+ }),+ );const { segments, overlays, audio } = lanes;@@ -636,6 +658,29 @@ export default function VideoTimelineEditor() {[segments],);const segmentKeys = useMemo(() => segments.map((s) => s._key), [segments]);++ // A segment's _key is a generated id, so dnd-kit's stock "draggable item N"+ // announcements say nothing a listener can act on. Positions are what the+ // user is actually rearranging, so announce those.+ const timelineAccessibility = useMemo(() => {+ const positionOf = (id) => segmentKeys.indexOf(id) + 1;+ const total = segmentKeys.length;+ return {+ announcements: {+ onDragStart: ({ active }) => `Picked up clip ${positionOf(active.id)} of ${total}. Use the left and right arrow keys to move it, Space to drop it, or Escape to cancel.`,+ onDragOver: ({ active, over }) => (over+ ? `Clip ${positionOf(active.id)} is over position ${positionOf(over.id)} of ${total}.`+ : `Clip ${positionOf(active.id)} is outside the timeline.`),+ onDragEnd: ({ active, over }) => (over+ ? `Dropped clip in position ${positionOf(over.id)} of ${total}.`+ : `Clip ${positionOf(active.id)} was dropped outside the timeline and did not move.`),+ onDragCancel: ({ active }) => `Cancelled moving clip ${positionOf(active.id)}. It returned to its original position.`,+ },+ screenReaderInstructions: {+ draggable: 'To reorder this clip, press Space. While moving, use the left and right arrow keys to change its position, then press Space to drop it, or Escape to cancel. Press Enter to select the clip and edit it in the inspector.',+ },+ };+ }, [segmentKeys]);// Everything about an overlay except its opacity is frame-invariant; only the// opacity is recomputed as the playhead moves.const overlayChrome = useMemo(() => overlays.map((ov) => ({@@ -964,7 +1009,12 @@ export default function VideoTimelineEditor() {{segments.length === 0 ? (<div className="text-[10px] text-gray-600 pl-2 py-2">Add a clip or a still from the library</div>) : (- <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>+ <DndContext+ sensors={sensors}+ accessibility={timelineAccessibility}+ collisionDetection={closestCenter}+ onDragEnd={onDragEnd}+ ><SortableContext items={segmentKeys} strategy={horizontalListSortingStrategy}><div className="flex gap-1 items-stretch min-w-min py-1">{segments.map((segment) => (diff --git a/client/src/pages/VideoTimelineEditor.keyboard.test.jsx b/client/src/pages/VideoTimelineEditor.keyboard.test.jsxnew file mode 100644index 0000000000..00eb8999e2--- /dev/null+++ b/client/src/pages/VideoTimelineEditor.keyboard.test.jsx@@ -0,0 +1,126 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import { stubSequentialLayout, pressKey, dndAnnouncement } from '../test/dndKeyboardDrag';++// Guards #7243. This lives in its own file rather than in VideoTimelineEditor.test.jsx+// because that suite mocks `useSortable` down to empty attributes/listeners —+// exactly the wiring a keyboard drag has to exercise for real.+//+// Two defects are pinned here. The page registered a PointerSensor alone, so+// `arrayMove` inside onDragEnd — the only clip-reorder path there is — was+// unreachable without a mouse. And `TimelineBlock` spread `clickableProps`+// AFTER dnd-kit's `listeners`, which REPLACES the keyboard activator outright,+// so adding the sensor alone would still have left Space doing nothing.++const toastError = vi.hoisted(() => vi.fn());+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: toastError, success: vi.fn() }),+}));++vi.mock('react-router', () => ({+ useParams: () => ({ projectId: 'p1' }),+ useNavigate: () => vi.fn(),+}));++vi.mock('../hooks/useSseProgress', () => ({+ useSseProgress: () => ({ latest: null, closed: false }),+ isTerminalSseFrame: () => false,+}));++const api = vi.hoisted(() => ({ project: null, saved: [] }));++vi.mock('../services/api', () => ({+ getTimelineProject: async () => api.project,+ listVideoHistory: async () => [],+ getGalleryImages: async () => [{ filename: 'first.png' }, { filename: 'second.png' }],+ listMusicLibrary: async () => ({ tracks: [] }),+ updateTimelineProject: async (_id, patch) => { api.saved.push(patch); return { updatedAt: 'u2' }; },+ renderTimelineProject: async () => ({ jobId: 'j1' }),+}));++vi.mock('../services/apiImageVideo', () => ({+ listImageGalleryPage: async () => ({ items: [], total: 0, offset: 0, limit: 24 }),+}));++const VideoTimelineEditor = (await import('./VideoTimelineEditor')).default;++const still = (assetFile) => ({+ type: 'still', assetKind: 'images', assetFile, durationSec: 3, fadeInSec: 0, fadeOutSec: 0,+});++let restoreLayout;+beforeEach(() => {+ api.saved = [];+ api.project = {+ id: 'p1', name: 'Example Project', updatedAt: 'u1', schemaVersion: 2,+ segments: [still('first.png'), still('second.png')],+ overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [],+ };+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1024 });+ window.matchMedia = vi.fn((query) => ({+ matches: query === '(min-width: 64rem)', media: query,+ addEventListener: vi.fn(), removeEventListener: vi.fn(),+ }));+ // The clip lane is a horizontal sortable list.+ restoreLayout = stubSequentialLayout({ axis: 'horizontal' });+});+afterEach(() => restoreLayout());++const renderEditor = async () => {+ render(<VideoTimelineEditor />);+ await waitFor(() => expect(screen.queryByText('Loading project…')).not.toBeInTheDocument());+};++// The block is the drag handle, so it is reached through its own remove+// button's accessible name — the only text that names a specific segment.+const blockFor = (assetFile) => screen+ .getByRole('button', { name: `Remove ${assetFile} from timeline` })+ .closest('[aria-roledescription="sortable"]');++describe('VideoTimelineEditor keyboard clip reordering (#7243)', () => {+ it('reorders segments with Space, arrows and Space', async () => {+ await renderEditor();+ const first = blockFor('first.png');+ first.focus();++ await pressKey('Space', first);+ // Collision resolves immediately after the pickup, so the live region+ // already carries the onDragOver announcement by the time it is read.+ expect(dndAnnouncement()).toMatch(/Clip 1 is over position 1 of 2/);++ await pressKey('ArrowRight');+ await pressKey('Space');++ expect(dndAnnouncement()).toMatch(/Dropped clip in position 2 of 2/);+ await waitFor(() => expect(api.saved.length).toBeGreaterThan(0));+ expect(api.saved.at(-1).segments.map((s) => s.assetFile)).toEqual(['second.png', 'first.png']);+ });++ it('cancels on Escape and leaves the order untouched', async () => {+ await renderEditor();+ const first = blockFor('first.png');+ first.focus();++ await pressKey('Space', first);+ await pressKey('ArrowRight');+ await pressKey('Escape');++ expect(dndAnnouncement()).toMatch(/Cancelled moving clip 1/);+ expect(api.saved).toEqual([]);+ });++ it('still selects the block on Enter, which the drag must not swallow', async () => {+ // Enter is deliberately NOT a dnd-kit start/end code on this surface, so+ // the block's own select handler keeps it — that is what lets one element+ // be both the drag handle and the click-to-select target.+ await renderEditor();+ const second = blockFor('second.png');+ second.focus();++ await pressKey('Enter', second);++ expect(dndAnnouncement()).not.toMatch(/Picked up/);+ // The inspector only renders a Hold field once a still segment is selected.+ expect(screen.getByLabelText('Hold (s)')).toBeInTheDocument();+ });+});diff --git a/client/src/test/dndKeyboardDrag.js b/client/src/test/dndKeyboardDrag.jsnew file mode 100644index 0000000000..c4c6a96503--- /dev/null+++ b/client/src/test/dndKeyboardDrag.js@@ -0,0 +1,94 @@+/**+ * Driving a real `@dnd-kit` keyboard drag under happy-dom.+ *+ * Two things stand between a test and an honest keyboard-drag assertion, and+ * both are environment artifacts rather than product behavior:+ *+ * 1. **No layout.** happy-dom returns an all-zero `getBoundingClientRect`, so+ * every droppable measures to the same zero-area box at the origin and+ * `closestCenter` can only ever tie. `stubSequentialLayout` stacks the+ * elements in DOCUMENT order instead — which is the order a vertical list+ * really paints in, and the order the keyboard coordinate getters sort+ * their zones by. Deriving it from the document rather than from the order+ * elements happen to be measured matters: dnd-kit measures the node being+ * dragged first, so a measurement-order stub puts the dragged row above+ * everything else and collision detection picks the wrong starting zone.+ * 2. **A deferred listener.** `KeyboardSensor.attach()` registers its+ * document-level keydown handler inside a `setTimeout`, so the arrow key+ * that immediately follows the pickup is dropped on the floor. A real user+ * never presses two keys inside the same macrotask; `pressKey` yields one+ * before dispatching, which is what makes a scripted drag behave like a+ * human one.+ *+ * Use with the REAL `@dnd-kit/core` (no module mock) — proving the sensor is+ * registered is exactly what these helpers exist to do.+ */++import { act, fireEvent } from '@testing-library/react';++const ROW_HEIGHT = 40;+const ROW_WIDTH = 200;++/**+ * Stack every element vertically in document order, one row apart.+ * Call from a `beforeEach`; it returns a teardown for `afterEach`.+ *+ * @param {object} [options]+ * @param {'vertical'|'horizontal'} [options.axis='vertical'] which way the+ * elements are laid out. A horizontal surface (the video timeline's clip+ * lane) needs this: `sortableKeyboardCoordinates` looks for the next item in+ * the direction of the arrow key, so Left/Right find nothing at all when+ * every rect shares a `left`.+ * @param {number} [options.height=40] per-element height+ * @param {number} [options.width=200] per-element width+ * @returns {() => void} restores the original `getBoundingClientRect`+ */+export function stubSequentialLayout({ axis = 'vertical', height = ROW_HEIGHT, width = ROW_WIDTH } = {}) {+ const original = Element.prototype.getBoundingClientRect;+ Element.prototype.getBoundingClientRect = function stubbedRect() {+ const order = Math.max(Array.prototype.indexOf.call(this.ownerDocument.querySelectorAll('*'), this), 0);+ const top = axis === 'vertical' ? order * height : 0;+ const left = axis === 'vertical' ? 0 : order * width;+ return {+ x: left, y: top, left, top, right: left + width, bottom: top + height, width, height,+ toJSON: () => ({}),+ };+ };+ return () => { Element.prototype.getBoundingClientRect = original; };+}++/**+ * Dispatch one key on `element` (default: whatever holds focus) and let the+ * sensor's deferred listeners and state updates settle before returning.+ *+ * @param {string} code a `KeyboardEvent.code` — 'Space', 'ArrowDown', 'Escape', …+ * @param {Element} [element]+ */+export async function pressKey(code, element) {+ const key = code === 'Space' ? ' ' : code.replace(/^Key/, '');+ await act(async () => {+ // Flush the macrotask KeyboardSensor.attach() defers its listener into, so+ // the key after a pickup is not swallowed.+ await new Promise((resolve) => setTimeout(resolve, 0));+ fireEvent.keyDown(element || document.activeElement || document.body, { key, code });+ });+}++/**+ * Press one key `times` times. Useful for walking a keyboard drag to a known+ * end of its drop-zone list before asserting: which zone a drag STARTS on comes+ * out of collision detection against the synthetic layout above, which is an+ * artifact of the environment, while stepping from a clamped boundary is the+ * product behavior a test should pin.+ *+ * @param {string} code+ * @param {number} times+ */+export async function pressKeyTimes(code, times) {+ for (let i = 0; i < times; i += 1) await pressKey(code);+}++/** Current text of the DndContext live region, or '' when nothing is announced. */+export function dndAnnouncement() {+ return document.querySelector('[id^="DndLiveRegion"]')?.textContent || '';+}