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
feat([brain-bucket-chip-reorder]): drag-to-reorder link chips within a bucket
[._.]/ Adam Eivy1276e5c4b2b1
diff --git a/client/src/components/brain/links/BucketBoard.jsx b/client/src/components/brain/links/BucketBoard.jsxindex 1202325ab3..2448926cac 100644--- a/client/src/components/brain/links/BucketBoard.jsx+++ b/client/src/components/brain/links/BucketBoard.jsx@@ -12,7 +12,7 @@ import BucketCard from './BucketCard';* dragged from another bucket, and a bucket header dragged to reorder all* resolve the same way regardless of which component started the drag.*/-export default function BucketBoard({ links, buckets, setBuckets, onAssignLink, onAddLinkToBucket, onBucketDeleted }) {+export default function BucketBoard({ links, buckets, setBuckets, onAssignLink, onAddLinkToBucket, onBucketDeleted, onMoveLinkToIndex }) {const [creating, setCreating] = useState(false);const [newName, setNewName] = useState('');@@ -59,6 +59,12 @@ export default function BucketBoard({ links, buckets, setBuckets, onAssignLink,}}, [links, onAssignLink]);+ // --- Drag: drop a chip at a specific position within (or into) a bucket ---+ const handleMoveLink = useCallback((linkId, bucketId, targetIndex) => {+ const link = links.find(l => l.id === linkId);+ if (link) onMoveLinkToIndex?.(link, bucketId, targetIndex);+ }, [links, onMoveLinkToIndex]);+// --- Drag: reorder buckets ---const handleReorder = useCallback((draggedId, targetBucket) => {if (!draggedId || draggedId === targetBucket.id) return;@@ -96,6 +102,7 @@ export default function BucketBoard({ links, buckets, setBuckets, onAssignLink,onRemoveLink={(link) => onAssignLink?.(link, null)}onDropLink={(linkId) => handleDropLink(linkId, bucket.id)}onReorderBucket={(draggedId) => handleReorder(draggedId, bucket)}+ onMoveLink={(linkId, index) => handleMoveLink(linkId, bucket.id, index)}/>))}diff --git a/client/src/components/brain/links/BucketBoard.test.jsx b/client/src/components/brain/links/BucketBoard.test.jsxindex 31a2b0b6cb..0a75fe907f 100644--- a/client/src/components/brain/links/BucketBoard.test.jsx+++ b/client/src/components/brain/links/BucketBoard.test.jsx@@ -44,6 +44,50 @@ describe('BucketBoard', () => {expect(screen.queryByText('Ungrouped Link')).toBeNull();});+ const twoChip = [+ { id: 'l1', url: 'https://a.com', title: 'Alpha', bucketId: 'b1', bucketOrder: 0 },+ { id: 'l2', url: 'https://b.com', title: 'Beta', bucketId: 'b1', bucketOrder: 1 }+ ];++ it('routes a positioned chip drop to onMoveLinkToIndex with the dragged link + chip index', () => {+ const onMoveLinkToIndex = vi.fn();+ render(+ <BucketBoard+ links={twoChip}+ buckets={buckets}+ setBuckets={vi.fn()}+ onAssignLink={vi.fn()}+ onAddLinkToBucket={vi.fn()}+ onBucketDeleted={vi.fn()}+ onMoveLinkToIndex={onMoveLinkToIndex}+ />+ );+ // Drag Alpha (l1) onto Beta (index 1). jsdom reports a zero-size rect, so+ // the before/after midpoint resolves to "before" → index 1. (The exact+ // before/after split is geometry the helper test covers.)+ const dataTransfer = { getData: () => 'l1', types: ['text/x-brain-link'] };+ fireEvent.drop(screen.getByText('Beta'), { dataTransfer });+ expect(onMoveLinkToIndex).toHaveBeenCalledWith(twoChip[0], 'b1', 1);+ });++ it('ignores a chip-level drop that carries no link payload (e.g. a bucket reorder)', () => {+ const onMoveLinkToIndex = vi.fn();+ render(+ <BucketBoard+ links={twoChip}+ buckets={buckets}+ setBuckets={vi.fn()}+ onAssignLink={vi.fn()}+ onAddLinkToBucket={vi.fn()}+ onBucketDeleted={vi.fn()}+ onMoveLinkToIndex={onMoveLinkToIndex}+ />+ );+ const dataTransfer = { getData: () => '', types: ['text/x-brain-bucket'] };+ fireEvent.drop(screen.getByText('Alpha'), { dataTransfer });+ expect(onMoveLinkToIndex).not.toHaveBeenCalled();+ });+it('creates a new bucket through the inline form', async () => {api.createBrainBucket.mockResolvedValue({ id: 'b3', name: 'Reading', color: 'accent', order: 2 });const setBuckets = vi.fn();diff --git a/client/src/components/brain/links/BucketCard.jsx b/client/src/components/brain/links/BucketCard.jsxindex 986b4116e6..c228a81eb4 100644--- a/client/src/components/brain/links/BucketCard.jsx+++ b/client/src/components/brain/links/BucketCard.jsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useState, Fragment } from 'react';import { Plus, Edit2, Trash2, Save, X, Check, GripVertical } from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';@@ -19,7 +19,8 @@ export default function BucketCard({onAddLink,onRemoveLink,onDropLink,- onReorderBucket+ onReorderBucket,+ onMoveLink}) {const formFromBucket = () => ({ name: bucket.name, color: bucket.color, icon: bucket.icon || '' });const [editing, setEditing] = useState(false);@@ -28,9 +29,41 @@ export default function BucketCard({const [addUrl, setAddUrl] = useState('');const [adding, setAdding] = useState(false);const [dropActive, setDropActive] = useState(false);+ // The chip index where a dragged link would be inserted (null = no chip-level+ // drop in progress); renders a vertical insertion bar at that position.+ const [dropIndex, setDropIndex] = useState(null);const colors = bucketColor(bucket.color);+ // Insert a chip before or after the chip at index `i` based on which half of+ // it the pointer is over (chips flow left-to-right within a wrapping row).+ const dropIndexFor = (e, i) => {+ const rect = e.currentTarget.getBoundingClientRect();+ return e.clientX > rect.left + rect.width / 2 ? i + 1 : i;+ };++ // While dragging a link over a chip: show a precise insertion bar instead of+ // the whole-card drop ring. Bucket-reorder drags (no link payload) fall+ // through so they bubble to the card's drop handler.+ const handleChipDragOver = (e, i) => {+ if (!e.dataTransfer.types.includes(LINK_DND_TYPE)) return;+ e.preventDefault();+ e.stopPropagation();+ setDropActive(false);+ setDropIndex(dropIndexFor(e, i));+ };++ const handleChipDrop = (e, i) => {+ const linkId = e.dataTransfer.getData(LINK_DND_TYPE);+ if (!linkId) return; // not a chip drag — let the card handle bucket reorder+ e.preventDefault();+ e.stopPropagation();+ const targetIndex = dropIndexFor(e, i);+ setDropIndex(null);+ setDropActive(false);+ onMoveLink?.(linkId, targetIndex);+ };+const startEdit = () => {setForm(formFromBucket());setEditing(true);@@ -59,10 +92,11 @@ export default function BucketCard({dropActive ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'}`}onDragOver={(e) => { e.preventDefault(); setDropActive(true); }}- onDragLeave={() => setDropActive(false)}+ onDragLeave={() => { setDropActive(false); setDropIndex(null); }}onDrop={(e) => {e.preventDefault();setDropActive(false);+ setDropIndex(null);const linkId = e.dataTransfer.getData(LINK_DND_TYPE);if (linkId) { onDropLink?.(linkId); return; }const draggedBucketId = e.dataTransfer.getData(BUCKET_DND_TYPE);@@ -165,18 +199,26 @@ export default function BucketCard({)}{/* Chips */}- <div className="flex flex-wrap gap-2 p-3 min-h-[2.5rem]">- {links.length === 0 && (+ <div+ className="flex flex-wrap gap-2 p-3 min-h-[2.5rem]"+ onDragLeave={(e) => {+ // Only clear when the pointer truly left the chips area — crossing+ // between chips fires its own dragleave we don't want to react to.+ if (!e.currentTarget.contains(e.relatedTarget)) setDropIndex(null);+ }}+ >+ {links.length === 0 && dropIndex === null && (<span className="text-xs text-gray-600 italic">Drop links here or add a URL below.</span>)}- {links.map(link => (- <LinkChip- key={link.id}- link={link}- onRemove={onRemoveLink}- draggable- />+ {links.map((link, i) => (+ <Fragment key={link.id}>+ {dropIndex === i && <ChipInsertionBar />}+ <div onDragOver={(e) => handleChipDragOver(e, i)} onDrop={(e) => handleChipDrop(e, i)}>+ <LinkChip link={link} onRemove={onRemoveLink} draggable />+ </div>+ </Fragment>))}+ {dropIndex === links.length && links.length > 0 && <ChipInsertionBar />}</div>{/* Add URL */}@@ -203,3 +245,8 @@ export default function BucketCard({</div>);}++/** A thin vertical accent bar marking where a dragged chip will land. */+function ChipInsertionBar() {+ return <div className="w-0.5 self-stretch min-h-[1.75rem] rounded-full bg-port-accent" aria-hidden="true" />;+}diff --git a/client/src/components/brain/links/bucketReorder.js b/client/src/components/brain/links/bucketReorder.jsnew file mode 100644index 0000000000..e232ec2f79--- /dev/null+++ b/client/src/components/brain/links/bucketReorder.js@@ -0,0 +1,31 @@+/**+ * Pure helper for intra-bucket (and cross-bucket) positioned chip drops.+ *+ * Given the full link list, the dragged link, the destination bucket, and the+ * insertion index (computed from the drop location — relative to the bucket's+ * CURRENT chip order, counting the dragged chip if it already lives there),+ * returns a dense renumbering of the destination bucket plus the subset of+ * links whose `{ bucketId, bucketOrder }` actually changed (so the caller only+ * PATCHes what moved).+ */+export function reorderLinksInBucket(links, link, bucketId, targetIndex) {+ const ordered = links+ .filter(l => l.bucketId === bucketId)+ .sort((a, b) => (a.bucketOrder ?? 0) - (b.bucketOrder ?? 0));+ const fromIndex = ordered.findIndex(l => l.id === link.id);+ const without = ordered.filter(l => l.id !== link.id);++ // The drop index includes the dragged chip when it already lives in this+ // bucket; removing it shifts every later position down one, so the insertion+ // point must decrement when the chip moved rightward within its own bucket.+ let insertAt = fromIndex !== -1 && fromIndex < targetIndex ? targetIndex - 1 : targetIndex;+ insertAt = Math.max(0, Math.min(insertAt, without.length));+ without.splice(insertAt, 0, link);++ const renumbered = without.map((l, i) => ({ id: l.id, bucketId, bucketOrder: i }));+ const changed = renumbered.filter(r => {+ const cur = links.find(l => l.id === r.id);+ return !cur || cur.bucketId !== bucketId || (cur.bucketOrder ?? 0) !== r.bucketOrder;+ });+ return { renumbered, changed };+}diff --git a/client/src/components/brain/links/bucketReorder.test.js b/client/src/components/brain/links/bucketReorder.test.jsnew file mode 100644index 0000000000..4adeeadd8f--- /dev/null+++ b/client/src/components/brain/links/bucketReorder.test.js@@ -0,0 +1,54 @@+import { describe, it, expect } from 'vitest';+import { reorderLinksInBucket } from './bucketReorder';++const mk = (id, bucketId, bucketOrder) => ({ id, bucketId, bucketOrder });++describe('reorderLinksInBucket', () => {+ it('moves a chip later within its bucket, accounting for its own removal', () => {+ const links = [mk('a', 'b1', 0), mk('b', 'b1', 1), mk('c', 'b1', 2), mk('d', 'b1', 3)];+ // Drag A to "after C" — drop index 3 in the current array [A,B,C,D].+ const { renumbered, changed } = reorderLinksInBucket(links, links[0], 'b1', 3);+ expect(renumbered.map(r => r.id)).toEqual(['b', 'c', 'a', 'd']);+ // a, b, c all shifted; d kept order 3.+ expect(changed.map(c => c.id).sort()).toEqual(['a', 'b', 'c']);+ });++ it('moves a chip earlier within its bucket', () => {+ const links = [mk('a', 'b1', 0), mk('b', 'b1', 1), mk('c', 'b1', 2), mk('d', 'b1', 3)];+ // Drag D to before B — drop index 1.+ const { renumbered } = reorderLinksInBucket(links, links[3], 'b1', 1);+ expect(renumbered.map(r => r.id)).toEqual(['a', 'd', 'b', 'c']);+ });++ it('is a no-op when the chip lands back in its current slot', () => {+ const links = [mk('a', 'b1', 0), mk('b', 'b1', 1), mk('c', 'b1', 2)];+ // Drag B to "after A" (index 1) — its existing position.+ const { changed } = reorderLinksInBucket(links, links[1], 'b1', 1);+ expect(changed).toEqual([]);+ });++ it('inserts a chip dragged in from another bucket at the target index', () => {+ const links = [mk('a', 'b1', 0), mk('b', 'b1', 1), mk('x', 'b2', 0)];+ // Drag X (from b2) into b1 at index 1 — between A and B.+ const { renumbered, changed } = reorderLinksInBucket(links, links[2], 'b1', 1);+ expect(renumbered).toEqual([+ { id: 'a', bucketId: 'b1', bucketOrder: 0 },+ { id: 'x', bucketId: 'b1', bucketOrder: 1 },+ { id: 'b', bucketId: 'b1', bucketOrder: 2 }+ ]);+ // X changes bucket + order; B shifts to 2. A is unchanged.+ expect(changed.map(c => c.id).sort()).toEqual(['b', 'x']);+ });++ it('clamps an out-of-range target index to the end', () => {+ const links = [mk('a', 'b1', 0), mk('b', 'b1', 1)];+ const { renumbered } = reorderLinksInBucket(links, links[0], 'b1', 99);+ expect(renumbered.map(r => r.id)).toEqual(['b', 'a']);+ });++ it('treats a missing bucketOrder as 0 when sorting', () => {+ const links = [{ id: 'a', bucketId: 'b1' }, mk('b', 'b1', 1)];+ const { renumbered } = reorderLinksInBucket(links, links[1], 'b1', 0);+ expect(renumbered.map(r => r.id)).toEqual(['b', 'a']);+ });+});diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 12244dfa22..4c70476ce0 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -29,6 +29,7 @@ import { timeAgo } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';import BucketBoard from '../links/BucketBoard';import { LINK_DND_TYPE } from '../links/bucketColors';+import { reorderLinksInBucket } from '../links/bucketReorder';/** Normalize a user-entered URL the way the quick-add form does. */function normalizeUrl(raw) {@@ -173,7 +174,7 @@ export default function LinksTab({ onRefresh }) {: { bucketId: null };// Optimistic update so chips move instantly.setLinks(prev => prev.map(l => (l.id === link.id ? { ...l, ...patch } : l)));- const updated = await api.updateBrainLink(link.id, patch).catch(err => {+ const updated = await api.updateBrainLink(link.id, patch, { silent: true }).catch(err => {toast.error(err.message || 'Failed to update link');return null;});@@ -184,6 +185,29 @@ export default function LinksTab({ onRefresh }) {}};+ // Reposition a chip within (or into) a bucket at a specific index — the+ // intra-bucket reorder the bucket board's "append on assign" path can't do.+ // Renumbers the destination bucket densely and PATCHes only the chips that+ // actually moved.+ const handleMoveLinkToIndex = async (link, bucketId, targetIndex) => {+ const { renumbered, changed } = reorderLinksInBucket(links, link, bucketId, targetIndex);+ if (changed.length === 0) return;+ // Optimistic reorder so the chips settle instantly.+ const byId = new Map(renumbered.map(r => [r.id, r]));+ setLinks(prev => prev.map(l => {+ const r = byId.get(l.id);+ return r ? { ...l, bucketId: r.bucketId, bucketOrder: r.bucketOrder } : l;+ }));+ const results = await Promise.all(changed.map(r =>+ api.updateBrainLink(r.id, { bucketId: r.bucketId, bucketOrder: r.bucketOrder }, { silent: true })+ .catch(() => null)+ ));+ if (results.some(r => r === null)) {+ toast.error('Failed to reorder links');+ fetchLinks(); // revert optimistic change on failure+ }+ };+// Quick-add a URL directly into a bucket. Returns true on success.const handleAddLinkToBucket = async (rawUrl, bucketId) => {const url = normalizeUrl(rawUrl);@@ -783,6 +807,7 @@ export default function LinksTab({ onRefresh }) {setBuckets={setBuckets}onAssignLink={handleAssignLink}onAddLinkToBucket={handleAddLinkToBucket}+ onMoveLinkToIndex={handleMoveLinkToIndex}onBucketDeleted={(bucketId) => setLinks(prev => prev.map(l => (l.bucketId === bucketId ? { ...l, bucketId: null } : l)))}/></aside>diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 9c1bfdba47..861d2c3f65 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -156,9 +156,10 @@ export const createBrainLink = (data) => request('/brain/links', {method: 'POST',body: JSON.stringify(data)});-export const updateBrainLink = (id, data) => request(`/brain/links/${id}`, {+export const updateBrainLink = (id, data, options = {}) => request(`/brain/links/${id}`, {method: 'PUT',- body: JSON.stringify(data)+ body: JSON.stringify(data),+ ...options});export const deleteBrainLink = (id) => request(`/brain/links/${id}`, { method: 'DELETE' });export const cloneBrainLink = (id) => request(`/brain/links/${id}/clone`, { method: 'POST' });