Skip to content

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

feat: link buckets (bookmark groups) on Brain Links tab

Adam Eivy4c15b8baad34
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 37cf37b1d4..096236e9a8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@ TBD
## Added
+- **Brain → Links buckets (bookmark groups)**: the Links tab now has a bucket board above the searchable list, so links can be organized into arbitrary groups (e.g. a "Reading list" or "Work tools" bucket of quick-launch buttons). Each bucket is a colored card whose links render as compact favicon + title chips that open in a new tab; buckets have an inline "add a URL" field (auto-titled from the hostname), inline rename/recolor/icon edit, and can be reordered by dragging. Links can be filed into a bucket by dragging a chip between buckets or via a per-row "+ Bucket…" dropdown in the list; an "Ungrouped" filter tab surfaces links not yet in any bucket. Buckets reuse the existing link records (a new `bucketId`/`bucketOrder` on each link) — single source of truth — and are a new federated brain collection (`buckets`) that syncs across peers. Deleting a bucket keeps its links (they fall back to ungrouped).
- **Brain → Links search**: a keyword search box on the Links tab filters the saved links list in real time across title, URL, description, and tags (case-insensitive). It composes with the existing GitHub/Other category tabs, includes a clear (×) affordance, and shows a distinct "no links match" empty state separate from the "no links saved yet" state. Filtering is client-side over the already-loaded list, so there are no extra round-trips and no server changes.
- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage. An **AI provider/model picker** at the top of the builder (and the import tab) drives every operation — idea expand, aesthetic, arc, reader map, character refine, and the import analysis — persisted on the session so one selection applies throughout. The **characters step generates a styled preview image per character** (world style fused with the character descriptor, via the same render path as the Universe Builder) and shows it alongside each character so you can eyeball that the world and character styles read correctly together.
- **Brain → Links: optional title & tags on quick-add**: the Links tab quick-add form now has a collapsible "Add title & tags (optional)" section so a link can be saved with a custom title and tags up front, instead of only being editable after the fact. Collapsed by default to keep the paste-and-go flow clean.
diff --git a/PLAN.md b/PLAN.md
index 526c07f292..570964e1e3 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -217,6 +217,11 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [migration-043-line-ending-precedent] **Migration 043 (story-builder prompts) is first-shipment-only — no OLD_SHIPPED_MD5 hashing.** That's correct today: the prompts haven't shipped to anyone, so a hash-compare-and-update would be no-op. But the precedent matters: when a future migration AMENDS these prompts, follow migration 003's pattern — normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing, and ship both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` so existing installs whose copy still matches the prior shipped hash auto-upgrade. Add a one-line reminder comment to the migration. Surfaced by local-review SS-3 (2026-05-27).
- [ ] [style-probe-image-uses-draft-not-saved] **`<StyleProbeImage>` in Universe Builder renders against the in-memory draft but persists the resulting filename to the SERVER's saved record.** A probe image semantically built from in-progress styleNotes/influences gets pinned to a saved universe whose actual style fields are still on the prior values; once the user discards the draft, the styleImageRefs persists on a record that never had those style notes. Either gate `canRender` on `!draftDirty` (require save first — but users want to evaluate unsaved edits) or warn when the draft has uncommitted style changes. Story Builder's aesthetic step is fine because it persists before render. Surfaced by local-review C-5 (2026-05-27).
+## Deferred
+
+- [ ] [consolidate-client-url-normalize] **Consolidate client-side URL normalization.** Three components prepend `https://` to a bare URL with near-identical logic: `normalizeUrl` in `client/src/components/brain/tabs/LinksTab.jsx`, the inline block in `client/src/components/QuickBrainCapture.jsx` (~line 34, with `URL_PATTERN`/`DOMAIN_PATTERN` regexes), and `client/src/components/brain/tabs/FeedsTab.jsx` (~line 50, no `git@` handling). Extract one `normalizeUrl`/`isUrl` pair to a shared `client/src/utils/` helper and migrate all three. Skipped during the buckets PR /simplify (2026-05-28) because a correct consolidation touches two unrelated components and must preserve each one's subtly different behavior (FeedsTab ignores `git@`; QuickBrainCapture splits detection from normalization).
+- [ ] [brain-bucket-chip-reorder] **Drag-to-reorder chips *within* a bucket.** The Brain → Links bucket board (`client/src/components/brain/links/BucketBoard.jsx` + `BucketCard.jsx`) supports dragging a chip *between* buckets and reordering buckets, but not repositioning a chip within its own bucket — `bucketOrder` is only ever appended (max+1) on assign. Add intra-bucket position-aware drop (compute target index from the drop location, renumber `bucketOrder`, persist via `updateBrainLink`). Skipped in the initial buckets PR (2026-05-28) to avoid fragile drop-index math; chips currently sort by `bucketOrder` then insertion order, which is fine for the common case.
+
## Future Ideas
- **Identity Context Injection** — per-task-type digital twin preamble toggle.
diff --git a/client/src/components/brain/links/BucketBoard.jsx b/client/src/components/brain/links/BucketBoard.jsx
new file mode 100644
index 0000000000..286ef099e5
--- /dev/null
+++ b/client/src/components/brain/links/BucketBoard.jsx
@@ -0,0 +1,153 @@
+import { useState, useRef, useCallback } from 'react';
+import { Plus, FolderPlus, X } from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import BucketCard from './BucketCard';
+
+/**
+ * The bucket board: a responsive grid of bucket cards plus a "new bucket"
+ * affordance. The bucket collection + links (the single source of truth) live
+ * in the parent LinksTab and flow in via props; the board owns drag-and-drop.
+ */
+export default function BucketBoard({ links, buckets, setBuckets, onAssignLink, onAddLinkToBucket, onBucketDeleted }) {
+ const [creating, setCreating] = useState(false);
+ const [newName, setNewName] = useState('');
+ const draggedLink = useRef(null);
+ const draggedBucket = useRef(null);
+
+ const handleCreate = async (e) => {
+ e.preventDefault();
+ const name = newName.trim();
+ if (!name) return;
+ const bucket = await api.createBrainBucket({ name }).catch(err => {
+ toast.error(err.message || 'Failed to create bucket');
+ return null;
+ });
+ if (bucket) {
+ setBuckets(prev => [...prev, bucket]);
+ setNewName('');
+ setCreating(false);
+ }
+ };
+
+ const handleUpdate = useCallback(async (id, patch) => {
+ const updated = await api.updateBrainBucket(id, patch).catch(err => {
+ toast.error(err.message || 'Failed to update bucket');
+ return null;
+ });
+ if (updated) setBuckets(prev => prev.map(b => (b.id === id ? updated : b)));
+ }, [setBuckets]);
+
+ const handleDelete = useCallback(async (id) => {
+ const ok = await api.deleteBrainBucket(id).catch(err => {
+ toast.error(err.message || 'Failed to delete bucket');
+ return null;
+ });
+ if (ok) {
+ setBuckets(prev => prev.filter(b => b.id !== id));
+ // Server unassigned this bucket's links — mirror that locally (no refetch).
+ onBucketDeleted?.(id);
+ }
+ }, [onBucketDeleted, setBuckets]);
+
+ // --- Drag: move a chip into a bucket ---
+ const handleDropChip = useCallback((bucketId) => {
+ const link = draggedLink.current;
+ draggedLink.current = null;
+ if (link && link.bucketId !== bucketId) {
+ onAssignLink?.(link, bucketId);
+ }
+ }, [onAssignLink]);
+
+ // --- Drag: reorder buckets ---
+ const handleReorder = useCallback((targetBucket) => {
+ const dragged = draggedBucket.current;
+ draggedBucket.current = null;
+ if (!dragged || dragged.id === targetBucket.id) return;
+
+ setBuckets(prev => {
+ const ids = prev.map(b => b.id);
+ const from = ids.indexOf(dragged.id);
+ const to = ids.indexOf(targetBucket.id);
+ if (from === -1 || to === -1) return prev;
+ const next = [...prev];
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ api.reorderBrainBuckets(next.map(b => b.id)).catch(err => {
+ toast.error(err.message || 'Failed to reorder buckets');
+ });
+ return next;
+ });
+ }, [setBuckets]);
+
+ const linksFor = (bucketId) => links
+ .filter(l => l.bucketId === bucketId)
+ .sort((a, b) => (a.bucketOrder ?? 0) - (b.bucketOrder ?? 0));
+
+ return (
+ <div className="@container">
+ <div className="grid grid-cols-1 @md:grid-cols-2 @4xl:grid-cols-3 gap-4">
+ {buckets.map(bucket => (
+ <BucketCard
+ key={bucket.id}
+ bucket={bucket}
+ links={linksFor(bucket.id)}
+ onUpdate={handleUpdate}
+ onDelete={handleDelete}
+ onAddLink={onAddLinkToBucket}
+ onRemoveLink={(link) => onAssignLink?.(link, null)}
+ onChipDragStart={(link) => { draggedLink.current = link; }}
+ onChipDragEnd={() => { draggedLink.current = null; }}
+ onDropChip={handleDropChip}
+ onHeaderDragStart={(b) => { draggedBucket.current = b; }}
+ onHeaderDragEnd={() => { draggedBucket.current = null; }}
+ onHeaderDropReorder={handleReorder}
+ />
+ ))}
+
+ {/* New bucket */}
+ {creating ? (
+ <form
+ onSubmit={handleCreate}
+ className="flex flex-col items-stretch justify-center gap-2 p-4 bg-port-card border border-dashed border-port-accent/50 rounded-lg"
+ >
+ <label htmlFor="new-bucket-name" className="sr-only">New bucket name</label>
+ <input
+ id="new-bucket-name"
+ type="text"
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ placeholder="Bucket name (e.g. Reading list)"
+ className="px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-hidden focus:border-port-accent"
+ autoFocus
+ />
+ <div className="flex gap-2">
+ <button
+ type="submit"
+ disabled={!newName.trim()}
+ className="flex items-center gap-1 px-3 py-1.5 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded transition-colors disabled:opacity-40"
+ >
+ <Plus size={14} /> Create
+ </button>
+ <button
+ type="button"
+ onClick={() => { setCreating(false); setNewName(''); }}
+ className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"
+ >
+ <X size={14} /> Cancel
+ </button>
+ </div>
+ </form>
+ ) : (
+ <button
+ onClick={() => setCreating(true)}
+ className="flex flex-col items-center justify-center gap-2 p-4 min-h-[7rem] bg-port-card/50 border border-dashed border-port-border rounded-lg text-gray-500 hover:text-port-accent hover:border-port-accent/50 transition-colors"
+ >
+ <FolderPlus size={22} />
+ <span className="text-sm">New bucket</span>
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/brain/links/BucketBoard.test.jsx b/client/src/components/brain/links/BucketBoard.test.jsx
new file mode 100644
index 0000000000..31a2b0b6cb
--- /dev/null
+++ b/client/src/components/brain/links/BucketBoard.test.jsx
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ createBrainBucket: vi.fn(),
+ updateBrainBucket: vi.fn(),
+ deleteBrainBucket: vi.fn(),
+ reorderBrainBuckets: vi.fn()
+}));
+vi.mock('../../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+import * as api from '../../../services/api';
+import BucketBoard from './BucketBoard';
+
+const buckets = [
+ { id: 'b1', name: 'Bookmarks', color: 'purple', icon: '', order: 0 },
+ { id: 'b2', name: 'Tools', color: 'accent', icon: '', order: 1 }
+];
+const links = [
+ { id: 'l1', url: 'https://news.example.com', title: 'News', bucketId: 'b1', bucketOrder: 0 },
+ { id: 'l2', url: 'https://example.org', title: 'Ungrouped Link', bucketId: null }
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('BucketBoard', () => {
+ it('renders each bucket and its chips, but not links from other buckets', () => {
+ render(
+ <BucketBoard
+ links={links}
+ buckets={buckets}
+ setBuckets={vi.fn()}
+ onAssignLink={vi.fn()}
+ onAddLinkToBucket={vi.fn()}
+ onBucketDeleted={vi.fn()}
+ />
+ );
+ expect(screen.getByText('Bookmarks')).toBeTruthy();
+ expect(screen.getByText('Tools')).toBeTruthy();
+ expect(screen.getByText('News')).toBeTruthy();
+ // The ungrouped link is never shown on the board.
+ expect(screen.queryByText('Ungrouped Link')).toBeNull();
+ });
+
+ 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();
+ render(
+ <BucketBoard
+ links={links}
+ buckets={buckets}
+ setBuckets={setBuckets}
+ onAssignLink={vi.fn()}
+ onAddLinkToBucket={vi.fn()}
+ onBucketDeleted={vi.fn()}
+ />
+ );
+ fireEvent.click(screen.getByText('New bucket'));
+ fireEvent.change(screen.getByLabelText('New bucket name'), { target: { value: 'Reading' } });
+ fireEvent.click(screen.getByText('Create'));
+
+ await waitFor(() => expect(api.createBrainBucket).toHaveBeenCalledWith({ name: 'Reading' }));
+ expect(setBuckets).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/brain/links/BucketCard.jsx b/client/src/components/brain/links/BucketCard.jsx
new file mode 100644
index 0000000000..99ede795d0
--- /dev/null
+++ b/client/src/components/brain/links/BucketCard.jsx
@@ -0,0 +1,214 @@
+import { useState } from 'react';
+import { Plus, Edit2, Trash2, Save, X, Check, GripVertical } from 'lucide-react';
+import BrailleSpinner from '../../BrailleSpinner';
+import LinkChip from './LinkChip';
+import { bucketColor, BUCKET_COLORS, BUCKET_COLOR_KEYS } from './bucketColors';
+
+/**
+ * A single bucket (bookmark group): colored header with inline edit/delete,
+ * a grid of link chips, and an inline "add URL" affordance. Acts as a drop
+ * target so links can be dragged in from other buckets.
+ */
+export default function BucketCard({
+ bucket,
+ links,
+ onUpdate,
+ onDelete,
+ onAddLink,
+ onRemoveLink,
+ onChipDragStart,
+ onChipDragEnd,
+ onDropChip,
+ onHeaderDragStart,
+ onHeaderDragEnd,
+ onHeaderDropReorder
+}) {
+ const formFromBucket = () => ({ name: bucket.name, color: bucket.color, icon: bucket.icon || '' });
+ const [editing, setEditing] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [form, setForm] = useState(formFromBucket);
+ const [addUrl, setAddUrl] = useState('');
+ const [adding, setAdding] = useState(false);
+ const [dropActive, setDropActive] = useState(false);
+
+ const colors = bucketColor(bucket.color);
+
+ const startEdit = () => {
+ setForm(formFromBucket());
+ setEditing(true);
+ };
+
+ const saveEdit = async () => {
+ const name = form.name.trim();
+ if (!name) return;
+ await onUpdate(bucket.id, { name, color: form.color, icon: form.icon.trim() });
+ setEditing(false);
+ };
+
+ const handleAdd = async (e) => {
+ e.preventDefault();
+ const url = addUrl.trim();
+ if (!url || adding) return;
+ setAdding(true);
+ const ok = await onAddLink(url, bucket.id);
+ setAdding(false);
+ if (ok) setAddUrl('');
+ };
+
+ return (
+ <div
+ className={`flex flex-col bg-port-card border rounded-lg overflow-hidden transition-colors ${
+ dropActive ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'
+ }`}
+ onDragOver={(e) => { e.preventDefault(); setDropActive(true); }}
+ onDragLeave={() => setDropActive(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setDropActive(false);
+ onDropChip?.(bucket.id);
+ onHeaderDropReorder?.(bucket);
+ }}
+ >
+ {/* Header */}
+ {editing ? (
+ <div className="p-3 space-y-2 border-b border-port-border">
+ <div>
+ <label htmlFor={`bucket-name-${bucket.id}`} className="sr-only">Bucket name</label>
+ <input
+ id={`bucket-name-${bucket.id}`}
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
+ placeholder="Bucket name"
+ autoFocus
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ value={form.icon}
+ onChange={(e) => setForm({ ...form, icon: e.target.value })}
+ className="w-12 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm text-center"
+ placeholder="🔖"
+ maxLength={4}
+ aria-label="Bucket icon (emoji)"
+ />
+ <div className="flex items-center gap-1 flex-wrap">
+ {BUCKET_COLOR_KEYS.map(key => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setForm({ ...form, color: key })}
+ className={`w-5 h-5 rounded-full ${BUCKET_COLORS[key].dot} flex items-center justify-center`}
+ title={key}
+ aria-label={`Color ${key}`}
+ >
+ {form.color === key && <Check size={12} className="text-white" />}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={saveEdit}
+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-success/20 text-port-success rounded hover:bg-port-success/30 transition-colors"
+ >
+ <Save size={12} /> Save
+ </button>
+ <button
+ onClick={() => setEditing(false)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ <X size={12} /> Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div
+ className={`flex items-center gap-2 px-3 py-2 border-b ${colors.header}`}
+ draggable
+ onDragStart={() => onHeaderDragStart?.(bucket)}
+ onDragEnd={onHeaderDragEnd}
+ >
+ <GripVertical size={14} className="shrink-0 text-gray-500 cursor-grab" />
+ {bucket.icon && <span className="shrink-0 text-base leading-none">{bucket.icon}</span>}
+ <h3 className={`font-medium truncate flex-1 ${colors.text}`}>{bucket.name}</h3>
+ <span className="text-xs text-gray-500">{links.length}</span>
+ <button
+ onClick={startEdit}
+ className="p-1 text-gray-400 hover:text-white transition-colors"
+ title="Edit bucket"
+ >
+ <Edit2 size={13} />
+ </button>
+ <button
+ onClick={() => setConfirmDelete(true)}
+ className="p-1 text-gray-400 hover:text-port-error transition-colors"
+ title="Delete bucket"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ )}
+
+ {/* Delete confirm */}
+ {confirmDelete && (
+ <div className="flex items-center gap-2 px-3 py-2 bg-port-error/10 border-b border-port-error/30">
+ <span className="text-xs text-white flex-1">Delete bucket? Its links stay (ungrouped).</span>
+ <button
+ onClick={() => { onDelete(bucket.id); setConfirmDelete(false); }}
+ className="px-2 py-1 text-xs bg-port-error text-white rounded hover:bg-port-error/80 transition-colors"
+ >
+ Delete
+ </button>
+ <button
+ onClick={() => setConfirmDelete(false)}
+ className="px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ )}
+
+ {/* Chips */}
+ <div className="flex flex-wrap gap-2 p-3 min-h-[2.5rem]">
+ {links.length === 0 && (
+ <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
+ onDragStart={() => onChipDragStart?.(link)}
+ onDragEnd={onChipDragEnd}
+ />
+ ))}
+ </div>
+
+ {/* Add URL */}
+ <form onSubmit={handleAdd} className="flex gap-1 p-2 border-t border-port-border">
+ <label htmlFor={`bucket-add-${bucket.id}`} className="sr-only">Add a URL to {bucket.name}</label>
+ <input
+ id={`bucket-add-${bucket.id}`}
+ type="text"
+ value={addUrl}
+ onChange={(e) => setAddUrl(e.target.value)}
+ placeholder="Add a URL…"
+ className="flex-1 min-w-0 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm placeholder-gray-600 focus:outline-hidden focus:border-port-accent"
+ disabled={adding}
+ />
+ <button
+ type="submit"
+ disabled={adding || !addUrl.trim()}
+ className="shrink-0 px-2 py-1 bg-port-accent/80 hover:bg-port-accent text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ title="Add link to bucket"
+ >
+ {adding ? <BrailleSpinner /> : <Plus size={14} />}
+ </button>
+ </form>
+ </div>
+ );
+}
diff --git a/client/src/components/brain/links/LinkChip.jsx b/client/src/components/brain/links/LinkChip.jsx
new file mode 100644
index 0000000000..07d93a69ce
--- /dev/null
+++ b/client/src/components/brain/links/LinkChip.jsx
@@ -0,0 +1,56 @@
+import { useState } from 'react';
+import { Link2, X, GripVertical } from 'lucide-react';
+import { faviconUrl } from './bucketColors';
+
+/**
+ * A compact favicon + title button for a link inside a bucket.
+ * Clicking opens the link in a new tab; the hover-revealed X removes it
+ * from the bucket (does not delete the underlying link).
+ */
+export default function LinkChip({ link, onRemove, draggable, onDragStart, onDragEnd }) {
+ const [iconFailed, setIconFailed] = useState(false);
+ const favicon = faviconUrl(link.url);
+
+ return (
+ <div
+ className="group flex items-center gap-2 pl-1.5 pr-1 py-1 bg-port-bg border border-port-border rounded-md hover:border-port-accent/50 transition-colors max-w-full"
+ draggable={draggable}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ >
+ {draggable && (
+ <GripVertical size={12} className="shrink-0 text-gray-600 cursor-grab group-hover:text-gray-400" />
+ )}
+ <a
+ href={link.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1.5 min-w-0 flex-1 text-sm text-gray-200 hover:text-white"
+ title={link.url}
+ >
+ {favicon && !iconFailed ? (
+ <img
+ src={favicon}
+ alt=""
+ width={16}
+ height={16}
+ className="shrink-0 rounded-sm"
+ onError={() => setIconFailed(true)}
+ />
+ ) : (
+ <Link2 size={14} className="shrink-0 text-gray-500" />
+ )}
+ <span className="truncate">{link.title}</span>
+ </a>
+ {onRemove && (
+ <button
+ onClick={() => onRemove(link)}
+ className="shrink-0 p-0.5 text-gray-600 hover:text-port-error opacity-0 group-hover:opacity-100 transition-opacity"
+ title="Remove from bucket"
+ >
+ <X size={13} />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/brain/links/LinkChip.test.jsx b/client/src/components/brain/links/LinkChip.test.jsx
new file mode 100644
index 0000000000..b0f1461470
--- /dev/null
+++ b/client/src/components/brain/links/LinkChip.test.jsx
@@ -0,0 +1,34 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import LinkChip from './LinkChip';
+
+const link = { id: 'l1', url: 'https://www.example.com/docs', title: 'Example Docs' };
+
+describe('LinkChip', () => {
+ it('renders the title and a favicon img derived from the hostname', () => {
+ const { container } = render(<LinkChip link={link} />);
+ expect(screen.getByText('Example Docs')).toBeTruthy();
+ const img = container.querySelector('img');
+ expect(img.getAttribute('src')).toContain('example.com');
+ });
+
+ it('opens the link in a new tab', () => {
+ render(<LinkChip link={link} />);
+ const anchor = screen.getByText('Example Docs').closest('a');
+ expect(anchor.getAttribute('href')).toBe(link.url);
+ expect(anchor.getAttribute('target')).toBe('_blank');
+ });
+
+ it('falls back to the link icon when the favicon fails to load', () => {
+ const { container } = render(<LinkChip link={link} />);
+ fireEvent.error(container.querySelector('img'));
+ expect(container.querySelector('img')).toBeNull();
+ });
+
+ it('calls onRemove when the remove button is clicked', () => {
+ const onRemove = vi.fn();
+ render(<LinkChip link={link} onRemove={onRemove} />);
+ fireEvent.click(screen.getByTitle('Remove from bucket'));
+ expect(onRemove).toHaveBeenCalledWith(link);
+ });
+});
diff --git a/client/src/components/brain/links/bucketColors.js b/client/src/components/brain/links/bucketColors.js
new file mode 100644
index 0000000000..79dd7e6dfe
--- /dev/null
+++ b/client/src/components/brain/links/bucketColors.js
@@ -0,0 +1,36 @@
+/**
+ * Bucket color presets — keyed to the PortOS design tokens plus a few extras.
+ * Each preset carries full literal Tailwind class strings so the JIT compiler
+ * picks them up (dynamic concatenation would be purged).
+ */
+export const BUCKET_COLORS = {
+ accent: { dot: 'bg-port-accent', header: 'bg-port-accent/10 border-port-accent/40', text: 'text-port-accent' },
+ success: { dot: 'bg-port-success', header: 'bg-port-success/10 border-port-success/40', text: 'text-port-success' },
+ warning: { dot: 'bg-port-warning', header: 'bg-port-warning/10 border-port-warning/40', text: 'text-port-warning' },
+ error: { dot: 'bg-port-error', header: 'bg-port-error/10 border-port-error/40', text: 'text-port-error' },
+ purple: { dot: 'bg-purple-500', header: 'bg-purple-500/10 border-purple-500/40', text: 'text-purple-400' },
+ pink: { dot: 'bg-pink-500', header: 'bg-pink-500/10 border-pink-500/40', text: 'text-pink-400' },
+ cyan: { dot: 'bg-cyan-500', header: 'bg-cyan-500/10 border-cyan-500/40', text: 'text-cyan-400' },
+ slate: { dot: 'bg-slate-500', header: 'bg-slate-500/10 border-slate-500/40', text: 'text-slate-300' }
+};
+
+export const BUCKET_COLOR_KEYS = Object.keys(BUCKET_COLORS);
+
+export function bucketColor(key) {
+ return BUCKET_COLORS[key] || BUCKET_COLORS.accent;
+}
+
+/** Extract a clean hostname for favicon lookup; null if unparseable. */
+export function hostnameOf(url) {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return null;
+ }
+}
+
+/** Google favicon service URL for a link (64px), or null if no hostname. */
+export function faviconUrl(url) {
+ const host = hostnameOf(url);
+ return host ? `https://www.google.com/s2/favicons?domain=${host}&sz=64` : null;
+}
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index 07b76f37f4..1f812a9cba 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -18,12 +18,28 @@ import {
ShieldCheck,
Search,
ChevronDown,
- ChevronUp
+ ChevronUp,
+ FolderClosed
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import { timeAgo } from '../../../utils/formatters';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import BucketBoard from '../links/BucketBoard';
+
+/** Normalize a user-entered URL the way the quick-add form does. */
+function normalizeUrl(raw) {
+ let url = raw.trim();
+ if (!url) return null;
+ if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('git@')) {
+ if (url.includes('github.com') || url.includes('.')) {
+ url = 'https://' + url;
+ } else {
+ return null;
+ }
+ }
+ return url;
+}
const LINK_TYPE_COLORS = {
github: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
@@ -49,9 +65,9 @@ export default function LinksTab({ onRefresh }) {
const [showDetails, setShowDetails] = useState(false);
const [sending, setSending] = useState(false);
const [links, setLinks] = useState([]);
- const [total, setTotal] = useState(0);
+ const [buckets, setBuckets] = useState([]);
const [loading, setLoading] = useState(true);
- const [filter, setFilter] = useState('all'); // all, github, other
+ const [filter, setFilter] = useState('all'); // all, github, other, ungrouped
const [search, setSearch] = useState('');
const [editingId, setEditingId] = useState(null);
const [editForm, setEditForm] = useState({});
@@ -59,32 +75,37 @@ export default function LinksTab({ onRefresh }) {
const [scanningId, setScanningId] = useState(null);
const inputRef = useRef(null);
+ // Fetch the full link set; filtering happens client-side so the bucket board
+ // always sees every link regardless of the list filter.
const fetchLinks = useCallback(async () => {
- const options = {};
- if (filter === 'github') {
- options.isGitHubRepo = true;
- } else if (filter === 'other') {
- options.isGitHubRepo = false;
- }
-
- const data = await api.getBrainLinks(options).catch(() => ({ links: [], total: 0 }));
+ const data = await api.getBrainLinks({ limit: 100, silent: true }).catch(() => ({ links: [] }));
setLinks(data.links || []);
- setTotal(data.total || 0);
setLoading(false);
- }, [filter]);
+ }, []);
useEffect(() => {
fetchLinks();
+ api.getBrainBuckets({ silent: true })
+ .then(data => setBuckets(data.buckets || []))
+ .catch(() => setBuckets([]));
}, [fetchLinks]);
// Poll for clone status updates while at least one link is in flight.
const hasInFlightClone = links.some(l => l.cloneStatus === 'cloning' || l.cloneStatus === 'pending');
useAutoRefetch(fetchLinks, 3000, { enabled: hasInFlightClone, pollOnly: true });
- // Client-side keyword search across title, url, description, and tags.
+ // Client-side filter (type / bucket membership) then keyword search.
+ const matchesFilter = (link) => {
+ if (filter === 'github') return link.isGitHubRepo;
+ if (filter === 'other') return !link.isGitHubRepo;
+ if (filter === 'ungrouped') return !link.bucketId;
+ return true;
+ };
+ const filteredLinks = links.filter(matchesFilter);
+
const query = search.trim().toLowerCase();
const visibleLinks = query
- ? links.filter(link => {
+ ? filteredLinks.filter(link => {
const haystack = [
link.title,
link.url,
@@ -93,22 +114,16 @@ export default function LinksTab({ onRefresh }) {
].filter(Boolean).join(' ').toLowerCase();
return haystack.includes(query);
})
- : links;
+ : filteredLinks;
const handleSubmit = async (e) => {
e.preventDefault();
if (!inputUrl.trim() || sending) return;
- // Basic URL validation
- let url = inputUrl.trim();
- if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('git@')) {
- // Try adding https://
- if (url.includes('github.com') || url.includes('.')) {
- url = 'https://' + url;
- } else {
- toast.error('Please enter a valid URL');
- return;
- }
+ const url = normalizeUrl(inputUrl);
+ if (!url) {
+ toast.error('Please enter a valid URL');
+ return;
}
const payload = { url };
@@ -140,6 +155,52 @@ export default function LinksTab({ onRefresh }) {
}
};
+ // Next bucketOrder for a target bucket (append to the end).
+ const nextBucketOrder = (bucketId) => links
+ .filter(l => l.bucketId === bucketId)
+ .reduce((max, l) => Math.max(max, l.bucketOrder ?? 0), -1) + 1;
+
+ // Assign (or, with bucketId === null, unassign) a link to a bucket.
+ const handleAssignLink = async (link, bucketId) => {
+ const patch = bucketId
+ ? { bucketId, bucketOrder: nextBucketOrder(bucketId) }
+ : { 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 => {
+ toast.error(err.message || 'Failed to update link');
+ return null;
+ });
+ if (updated) {
+ setLinks(prev => prev.map(l => (l.id === updated.id ? updated : l)));
+ } else {
+ 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);
+ if (!url) {
+ toast.error('Please enter a valid URL');
+ return false;
+ }
+ const result = await api.createBrainLink({ url, bucketId, bucketOrder: nextBucketOrder(bucketId) }).catch(err => {
+ if (err.message?.includes('already exists')) {
+ toast.error('This URL is already saved');
+ } else {
+ toast.error(err.message || 'Failed to add link');
+ }
+ return null;
+ });
+ if (result) {
+ setLinks(prev => [result, ...prev]);
+ onRefresh?.();
+ return true;
+ }
+ return false;
+ };
+
const handleEdit = (link) => {
setEditingId(link.id);
setEditForm({
@@ -252,7 +313,15 @@ export default function LinksTab({ onRefresh }) {
}
return (
- <div className="flex flex-col h-full max-w-4xl mx-auto">
+ <div className="flex flex-col h-full">
+ <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-6 items-start">
+ {/* Left column: entry form, filters, and the full link list */}
+ <div className="min-w-0 flex flex-col">
+ <div className="flex items-center gap-2 mb-3">
+ <Link2 size={16} className="text-gray-400 shrink-0" />
+ <h2 className="text-sm font-semibold text-gray-300">All Links</h2>
+ </div>
+
{/* Quick-add input */}
<form onSubmit={handleSubmit} className="mb-6">
<div className="flex gap-2">
@@ -322,11 +391,12 @@ export default function LinksTab({ onRefresh }) {
</form>
{/* Filter tabs */}
- <div className="flex gap-2 mb-4">
+ <div className="flex gap-2 mb-4 flex-wrap">
{[
- { id: 'all', label: 'All', count: total },
- { id: 'github', label: 'GitHub Repos', icon: GitBranch },
- { id: 'other', label: 'Other Links', icon: Link2 }
+ { id: 'all', label: 'All', count: links.length },
+ { id: 'github', label: 'GitHub Repos', icon: GitBranch, count: links.filter(l => l.isGitHubRepo).length },
+ { id: 'other', label: 'Other Links', icon: Link2, count: links.filter(l => !l.isGitHubRepo).length },
+ { id: 'ungrouped', label: 'Ungrouped', icon: FolderClosed, count: links.filter(l => !l.bucketId).length }
].map(tab => {
const Icon = tab.icon;
const isActive = filter === tab.id;
@@ -534,6 +604,21 @@ export default function LinksTab({ onRefresh }) {
{link.linkType}
</span>
+ {/* Bucket assignment */}
+ <label htmlFor={`link-bucket-${link.id}`} className="sr-only">Assign to bucket</label>
+ <select
+ id={`link-bucket-${link.id}`}
+ value={link.bucketId || ''}
+ onChange={(e) => handleAssignLink(link, e.target.value || null)}
+ className="px-1.5 py-1 text-xs rounded border border-port-border bg-port-bg text-gray-300 focus:outline-hidden focus:border-port-accent"
+ title="Assign to a bucket"
+ >
+ <option value="">+ Bucket…</option>
+ {buckets.map(b => (
+ <option key={b.id} value={b.id}>{b.icon ? `${b.icon} ` : ''}{b.name}</option>
+ ))}
+ </select>
+
{/* Tags */}
{link.tags?.length > 0 && (
<div className="flex items-center gap-1">
@@ -659,6 +744,38 @@ export default function LinksTab({ onRefresh }) {
<p className="text-sm mt-1">Paste a URL above to get started.</p>
</div>
)}
+
+ {links.length > 0 && visibleLinks.length === 0 && !query && (
+ <div className="text-center py-12 text-gray-500">
+ <FolderClosed className="w-12 h-12 mx-auto mb-3 opacity-30" />
+ <p>No links in this view.</p>
+ <button
+ onClick={() => setFilter('all')}
+ className="text-sm mt-1 text-port-accent hover:underline"
+ >
+ Show all links
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Right column: bucket boards as a vertical grid */}
+ <aside className="min-w-0">
+ <div className="flex items-center gap-2 mb-3 flex-wrap">
+ <FolderClosed size={16} className="text-port-accent shrink-0" />
+ <h2 className="text-sm font-semibold text-gray-300">Buckets</h2>
+ <span className="text-xs text-gray-500">Group links — drag chips between buckets.</span>
+ </div>
+ <BucketBoard
+ links={links}
+ buckets={buckets}
+ setBuckets={setBuckets}
+ onAssignLink={handleAssignLink}
+ onAddLinkToBucket={handleAddLinkToBucket}
+ onBucketDeleted={(bucketId) => setLinks(prev => prev.map(l => (l.bucketId === bucketId ? { ...l, bucketId: null } : l)))}
+ />
+ </aside>
</div>
</div>
);
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 90ba6cdbd3..9c1bfdba47 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -166,6 +166,22 @@ export const pullBrainLink = (id) => request(`/brain/links/${id}/pull`, { method
export const openBrainLinkFolder = (id) => request(`/brain/links/${id}/open-folder`, { method: 'POST' });
export const scanBrainLink = (id) => request(`/brain/links/${id}/scan`, { method: 'POST' });
+// Brain - Buckets (bookmark groups for links)
+export const getBrainBuckets = (options = {}) => request('/brain/buckets', options);
+export const createBrainBucket = (data) => request('/brain/buckets', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateBrainBucket = (id, data) => request(`/brain/buckets/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteBrainBucket = (id) => request(`/brain/buckets/${id}`, { method: 'DELETE' });
+export const reorderBrainBuckets = (ids) => request('/brain/buckets/reorder', {
+ method: 'POST',
+ body: JSON.stringify({ ids })
+});
+
// Brain - Graph
export const getBrainGraph = () => request('/brain/graph');
diff --git a/docs/plans/2026-05-28-brain-link-buckets.md b/docs/plans/2026-05-28-brain-link-buckets.md
new file mode 100644
index 0000000000..15726a8740
--- /dev/null
+++ b/docs/plans/2026-05-28-brain-link-buckets.md
@@ -0,0 +1,112 @@
+# Brain Links Redesign — Link Buckets (Bookmark Groups)
+
+## Context
+
+Today the Brain → Links tab (`client/src/components/brain/tabs/LinksTab.jsx`) is a single flat,
+searchable/filterable list of link records. The user wants to use the desktop-mode space to organize
+links into **arbitrary buckets** (bookmark groups) rendered as boards of clickable button-chips — e.g. a
+"Reading list" bucket with quick-launch buttons for all your reading resources.
+
+**Decided approach (from clarifying questions):**
+1. **Data model** — reuse the existing brain `links` store; add optional `bucketId` + `bucketOrder` to link
+ records. Buckets are a new lightweight collection (`{ id, name, color, icon, order }`). Single source of
+ truth; any link (including GitHub repos) can be filed into a bucket.
+2. **Layout** — bucket boards on top, the classic searchable/filterable list below.
+3. **Button style** — each bucketed link renders as a compact **favicon + title chip** that opens in a new tab.
+
+No new page/route (stays at `/brain/links`), so no `NAV_COMMANDS` change is needed.
+
+## Data model changes
+
+Add to the link record (additive, optional — no migration required, old records are simply "ungrouped"):
+- `bucketId: string|null` (uuid of owning bucket; absent/null = ungrouped)
+- `bucketOrder: number` (position within the bucket)
+
+New `buckets` JSON entity store record:
+```
+bucket { id, name, color, icon, order, originInstanceId, createdAt, updatedAt }
+```
+- `color` — one of the port design tokens / a small preset palette
+- `icon` — optional emoji or lucide icon name (default a generic folder)
+- `order` — board position
+
+## Server changes
+
+### `server/services/brainStorage.js`
+- Add `buckets: join(DATA_DIR, 'buckets.json')` to `FILES` and `buckets: { data: null, timestamp: 0 }` to `caches`.
+- Add convenience exports mirroring links: `getBuckets / getBucketById / createBucket / updateBucket / deleteBucket`
+ (delegating to the generic `create/update/remove/getAll/getById` helpers — these already emit events + append to the sync log).
+- Add `'buckets'` to the `entityTypes` array in `backfillOriginInstanceId`.
+- Add `buckets` count to `getSummary()` (optional, low priority).
+
+### `server/services/brainSync.js`
+- Add `'buckets'` to `ENTITY_TYPES` (line 16) so buckets federate across sync peers (per the distribution model in CLAUDE.md).
+
+### `server/services/brain.js`
+- Add delegation exports for the five bucket CRUD functions (mirrors existing `getLinks`/`createLink`/… block).
+
+### `server/lib/brainValidation.js`
+- Extend `linkRecordSchema`, `linkInputSchema`, and `linkUpdateInputSchema` with:
+ `bucketId: z.string().uuid().nullable().optional()` and `bucketOrder: z.number().int().optional()`.
+ (POST accepting `bucketId` lets "quick-add inside a bucket" be a single call.)
+- Add new schemas: `bucketRecordSchema`, `bucketInputSchema` (`{ name, color?, icon? }`),
+ `bucketUpdateInputSchema` (partial), and `bucketReorderSchema` (`{ ids: z.array(z.string().uuid()) }`).
+- (File is already in the `server/lib` barrel/README — no barrel maintenance needed since no new file.)
+
+### `server/routes/brain.js`
+- New bucket routes (mirror the links CRUD block, all inputs validated):
+ - `GET /api/brain/buckets` → buckets sorted by `order`.
+ - `POST /api/brain/buckets` (`bucketInputSchema`) → assigns next `order`.
+ - `PUT /api/brain/buckets/:id` (`bucketUpdateInputSchema`).
+ - `DELETE /api/brain/buckets/:id` → also **unassign** its links (set `bucketId: null` on links where `bucketId === :id`) so links survive bucket deletion as ungrouped.
+ - `POST /api/brain/buckets/reorder` (`bucketReorderSchema`) → persist new `order` per id in one call (avoids N races).
+- Link assignment reuses existing `PUT /api/brain/links/:id` with `{ bucketId, bucketOrder }` (now schema-allowed).
+- Minor enhancement to `POST /api/brain/links`: when not a GitHub repo and no title supplied, derive title from the URL hostname (strip `www.`) so quick-added chips read nicely instead of showing the full URL.
+
+## Client changes
+
+### API wrapper — `client/src/services/apiBrain.js`
+Add (functions only; file already wired into the `api.js` barrel):
+`getBrainBuckets`, `createBrainBucket`, `updateBrainBucket`, `deleteBrainBucket`, `reorderBrainBuckets`.
+Add a `bucketId`/`bucketOrder` pass-through where links are created/updated.
+
+### New components (one concern per file) under `client/src/components/brain/links/`
+- `LinkChip.jsx` — favicon + title button. Favicon via `https://www.google.com/s2/favicons?domain=<hostname>&sz=64`
+ with `onError` fallback to the lucide `Link2` icon. Click opens `url` in a new tab (`target="_blank" rel="noopener"`).
+- `BucketCard.jsx` — one bucket: colored header (name + edit/delete menu), chip grid body, inline "+ add link"
+ (paste URL → `createBrainLink({ url, bucketId })`), and inline edit (name/color/icon). Supports removing a chip
+ from the bucket (set `bucketId: null`).
+- `BucketBoard.jsx` — responsive grid of `BucketCard`s (multi-column desktop, single-column stack on mobile per
+ the mobile-responsive convention) + a "+ New Bucket" affordance. Owns bucket list state with reactive updates
+ (`setState(prev => …)` after mutations, no full refetch). Drag-to-reorder chips within/between buckets and
+ buckets themselves via HTML5 DnD, persisting through `updateBrainLink`/`reorderBrainBuckets`.
+
+### `client/src/components/brain/tabs/LinksTab.jsx`
+- Render `<BucketBoard>` at the top, a divider, then the **existing** searchable/filterable list below (kept intact).
+- Each list row gains a small "bucket" control: a badge if assigned + an "Add to bucket ▾" menu that calls
+ `updateBrainLink(id, { bucketId })`. Add an optional **"Ungrouped"** entry alongside the existing
+ All / GitHub / Other filter tabs.
+- Keep the existing GitHub clone/scan/pull controls untouched on list rows.
+
+## Persistence / compatibility
+
+- `buckets.json` auto-creates lazily (`readJSONFile(..., { records: {} })`); the new link fields are additive and
+ optional → **no migration script required**. Federation is covered by adding `buckets` to `ENTITY_TYPES`.
+- Cross-machine sync payloads remain version-gated by the existing generic per-type sync path; buckets flow through
+ the same `appendChange`/`applyRemoteRecord` machinery as other entities.
+
+## Tests
+
+- `server/lib/brainValidation.test.js` — bucket schema valid/invalid cases; link schema accepts `bucketId`/`bucketOrder`.
+- `server/routes/brain.test.js` — bucket CRUD + reorder; deleting a bucket unassigns its links; hostname title derivation on plain-URL POST.
+- `client` (vitest/jsdom) — `LinkChip` renders title + favicon with fallback; `BucketBoard` renders buckets and adds a link.
+- Run `cd server && npm test` and `cd client && npm test`.
+
+## Verification (end-to-end)
+
+1. `npm run dev`, open `/brain/links`.
+2. Create a "Reading list" bucket; quick-add several URLs → confirm favicon+title chips render and open in new tabs.
+3. From the list below, file an existing link into a bucket via "Add to bucket"; confirm it appears as a chip and the list badge updates (no full reload fl/flicker).
+4. Drag to reorder chips and buckets; reload to confirm persistence.
+5. Delete a bucket; confirm its links survive as ungrouped in the list.
+6. Use Playwright MCP (persistent `~/.browser` profile) to screenshot the board in desktop and mobile widths to confirm responsive stacking.
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 1821e0f83a..36a2520601 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -343,6 +343,9 @@ export const linkRecordSchema = z.object({
localPath: z.string().max(500).optional(),
cloneStatus: z.enum(['pending', 'cloning', 'cloned', 'failed', 'none']).default('none'),
cloneError: z.string().max(500).optional(),
+ // Bucket grouping (nullable = ungrouped)
+ bucketId: z.string().uuid().nullable().optional(),
+ bucketOrder: z.number().int().optional(),
// Metadata
createdAt: z.string().datetime(),
updatedAt: z.string().datetime()
@@ -355,6 +358,8 @@ export const linkInputSchema = z.object({
description: z.string().max(2000).optional(),
linkType: linkTypeEnum.optional(),
tags: z.array(z.string().max(50)).optional(),
+ bucketId: z.string().uuid().nullable().optional(),
+ bucketOrder: z.number().int().optional(),
autoClone: z.boolean().optional().default(true)
});
@@ -364,7 +369,9 @@ export const linkUpdateInputSchema = z.object({
title: z.string().min(1).max(500).optional(),
description: z.string().max(2000).optional(),
linkType: linkTypeEnum.optional(),
- tags: z.array(z.string().max(50)).optional()
+ tags: z.array(z.string().max(50)).optional(),
+ bucketId: z.string().uuid().nullable().optional(),
+ bucketOrder: z.number().int().optional()
});
// Links query schema
@@ -380,6 +387,46 @@ export const linksQuerySchema = z.object({
offset: z.coerce.number().int().min(0).optional().default(0)
});
+// =============================================================================
+// BUCKET SCHEMAS (bookmark groups for links)
+// =============================================================================
+
+// A small preset palette keyed to the port design tokens (plus a neutral default)
+export const bucketColorEnum = z.enum([
+ 'accent', 'success', 'warning', 'error', 'purple', 'pink', 'cyan', 'slate'
+]);
+
+// Bucket Record schema
+export const bucketRecordSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ color: bucketColorEnum.default('accent'),
+ icon: z.string().max(50).optional().default(''),
+ order: z.number().int().default(0),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+// Create Bucket input schema
+export const bucketInputSchema = z.object({
+ name: z.string().min(1).max(100),
+ color: bucketColorEnum.optional(),
+ icon: z.string().max(50).optional()
+});
+
+// Update Bucket input schema (partial)
+export const bucketUpdateInputSchema = z.object({
+ name: z.string().min(1).max(100).optional(),
+ color: bucketColorEnum.optional(),
+ icon: z.string().max(50).optional(),
+ order: z.number().int().optional()
+});
+
+// Reorder buckets input schema (ordered list of bucket ids)
+export const bucketReorderSchema = z.object({
+ ids: z.array(z.string().uuid()).min(1)
+});
+
// =============================================================================
// SYNC SCHEMAS
// =============================================================================
diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.js
index c49dc5fd46..4251e07067 100644
--- a/server/lib/brainValidation.test.js
+++ b/server/lib/brainValidation.test.js
@@ -28,6 +28,9 @@ import {
linkInputSchema,
linkUpdateInputSchema,
linksQuerySchema,
+ bucketInputSchema,
+ bucketUpdateInputSchema,
+ bucketReorderSchema,
brainSyncQuerySchema,
brainSyncPushSchema
} from './brainValidation.js';
@@ -500,9 +503,29 @@ describe('brainValidation.js', () => {
it('should reject invalid URL', () => {
expect(linkInputSchema.safeParse({ url: 'not-valid' }).success).toBe(false);
});
+
+ it('should accept a bucketId + bucketOrder', () => {
+ const result = linkInputSchema.safeParse({
+ url: 'https://example.com',
+ bucketId: '11111111-1111-4111-8111-111111111111',
+ bucketOrder: 3
+ });
+ expect(result.success).toBe(true);
+ expect(result.data.bucketOrder).toBe(3);
+ });
+
+ it('should reject a non-uuid bucketId', () => {
+ expect(linkInputSchema.safeParse({ url: 'https://example.com', bucketId: 'nope' }).success).toBe(false);
+ });
});
describe('linkUpdateInputSchema', () => {
+ it('should accept a null bucketId (unassign)', () => {
+ const result = linkUpdateInputSchema.safeParse({ bucketId: null });
+ expect(result.success).toBe(true);
+ expect(result.data.bucketId).toBeNull();
+ });
+
it('should accept a url-only update', () => {
const result = linkUpdateInputSchema.safeParse({ url: 'https://example.com/new' });
expect(result.success).toBe(true);
@@ -547,6 +570,50 @@ describe('brainValidation.js', () => {
});
});
+ describe('bucketInputSchema', () => {
+ it('should accept a minimal name-only bucket', () => {
+ expect(bucketInputSchema.safeParse({ name: 'Disney' }).success).toBe(true);
+ });
+
+ it('should accept a valid color + icon', () => {
+ const result = bucketInputSchema.safeParse({ name: 'Disney', color: 'purple', icon: '🎢' });
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject an empty name', () => {
+ expect(bucketInputSchema.safeParse({ name: '' }).success).toBe(false);
+ });
+
+ it('should reject an unknown color', () => {
+ expect(bucketInputSchema.safeParse({ name: 'X', color: 'neon' }).success).toBe(false);
+ });
+ });
+
+ describe('bucketUpdateInputSchema', () => {
+ it('should accept a partial update', () => {
+ const result = bucketUpdateInputSchema.safeParse({ order: 2 });
+ expect(result.success).toBe(true);
+ expect(result.data.order).toBe(2);
+ });
+ });
+
+ describe('bucketReorderSchema', () => {
+ it('should accept a list of uuids', () => {
+ const result = bucketReorderSchema.safeParse({
+ ids: ['11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222']
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject an empty list', () => {
+ expect(bucketReorderSchema.safeParse({ ids: [] }).success).toBe(false);
+ });
+
+ it('should reject non-uuid entries', () => {
+ expect(bucketReorderSchema.safeParse({ ids: ['nope'] }).success).toBe(false);
+ });
+ });
+
describe('brainSyncQuerySchema', () => {
it('should accept valid query with defaults', () => {
const result = brainSyncQuerySchema.safeParse({});
diff --git a/server/routes/brain.js b/server/routes/brain.js
index b28e35f354..54a8896052 100644
--- a/server/routes/brain.js
+++ b/server/routes/brain.js
@@ -30,6 +30,9 @@ import {
linkInputSchema,
linkUpdateInputSchema,
linksQuerySchema,
+ bucketInputSchema,
+ bucketUpdateInputSchema,
+ bucketReorderSchema,
brainSyncQuerySchema,
brainSyncPushSchema,
dailyLogSettingsSchema
@@ -486,6 +489,17 @@ router.get('/summary', asyncHandler(async (req, res) => {
res.json(summary);
}));
+/**
+ * Extract a clean hostname from a URL (strip a leading www.), or null if unparseable.
+ */
+function hostnameFromUrl(url) {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return null;
+ }
+}
+
// =============================================================================
// LINKS CRUD
// =============================================================================
@@ -533,7 +547,7 @@ router.get('/links/:id', asyncHandler(async (req, res) => {
* Create a new link (quick-add with URL)
*/
router.post('/links', asyncHandler(async (req, res) => {
- const { url, title, description, linkType, tags, autoClone } = validateRequest(linkInputSchema, req.body);
+ const { url, title, description, linkType, tags, bucketId, bucketOrder, autoClone } = validateRequest(linkInputSchema, req.body);
// Check if URL already exists
const existing = await brainService.getLinkByUrl(url);
@@ -549,10 +563,16 @@ router.post('/links', asyncHandler(async (req, res) => {
const parsed = githubCloner.parseGitHubUrl(url);
const isGitHubRepo = !!parsed;
+ // Derive a readable default title: repo slug for GitHub, hostname for plain
+ // URLs (so quick-added bucket chips read "example.com" instead of the full URL).
+ const defaultTitle = parsed
+ ? `${parsed.owner}/${parsed.repo}`
+ : (hostnameFromUrl(url) || url);
+
// Create initial link record
const linkData = {
url,
- title: title || (parsed ? `${parsed.owner}/${parsed.repo}` : url),
+ title: title || defaultTitle,
description: description || '',
linkType: linkType || (isGitHubRepo ? 'github' : 'other'),
tags: tags || [],
@@ -561,7 +581,9 @@ router.post('/links', asyncHandler(async (req, res) => {
gitHubRepo: parsed?.repo,
localPath: null,
cloneStatus: isGitHubRepo && autoClone !== false ? 'pending' : 'none',
- cloneError: null
+ cloneError: null,
+ ...(bucketId !== undefined ? { bucketId } : {}),
+ ...(bucketOrder !== undefined ? { bucketOrder } : {})
};
const link = await brainService.createLink(linkData);
@@ -808,6 +830,92 @@ ${scanCommand}`;
res.json({ message: 'Scan queued', taskId: result.id, linkId: link.id, scanPath: link.localPath });
}));
+// =============================================================================
+// BUCKETS (bookmark groups for links)
+// =============================================================================
+
+/**
+ * GET /api/brain/buckets
+ * List buckets sorted by their display order.
+ */
+router.get('/buckets', asyncHandler(async (req, res) => {
+ const buckets = await brainService.getBuckets();
+ buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ res.json({ buckets });
+}));
+
+/**
+ * POST /api/brain/buckets
+ * Create a bucket. New buckets are appended after the existing ones.
+ */
+router.post('/buckets', asyncHandler(async (req, res) => {
+ const { name, color, icon } = validateRequest(bucketInputSchema, req.body);
+ const existing = await brainService.getBuckets();
+ const nextOrder = existing.reduce((max, b) => Math.max(max, b.order ?? 0), -1) + 1;
+ const bucket = await brainService.createBucket({
+ name,
+ color: color || 'accent',
+ icon: icon || '',
+ order: nextOrder
+ });
+ console.log(`🗂️ Created bucket: ${bucket.id} (${bucket.name})`);
+ res.status(201).json(bucket);
+}));
+
+/**
+ * POST /api/brain/buckets/reorder
+ * Persist a new display order for buckets in a single call.
+ * (Registered before /buckets/:id so "reorder" isn't captured as an :id.)
+ */
+router.post('/buckets/reorder', asyncHandler(async (req, res) => {
+ const { ids } = validateRequest(bucketReorderSchema, req.body);
+ for (let i = 0; i < ids.length; i++) {
+ await brainService.updateBucket(ids[i], { order: i });
+ }
+ const buckets = await brainService.getBuckets();
+ buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ res.json({ buckets });
+}));
+
+/**
+ * PUT /api/brain/buckets/:id
+ * Update a bucket's name / color / icon / order.
+ */
+router.put('/buckets/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(bucketUpdateInputSchema, req.body);
+ const existing = await brainService.getBucketById(req.params.id);
+ if (!existing) {
+ throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const bucket = await brainService.updateBucket(req.params.id, data);
+ res.json(bucket);
+}));
+
+/**
+ * DELETE /api/brain/buckets/:id
+ * Delete a bucket. Its links survive — they're unassigned (bucketId -> null)
+ * so they fall back to the ungrouped list rather than being orphaned.
+ */
+router.delete('/buckets/:id', asyncHandler(async (req, res) => {
+ const existing = await brainService.getBucketById(req.params.id);
+ if (!existing) {
+ throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });
+ }
+
+ const links = await brainService.getLinks();
+ let unassigned = 0;
+ for (const link of links) {
+ if (link.bucketId === req.params.id) {
+ await brainService.updateLink(link.id, { bucketId: null });
+ unassigned++;
+ }
+ }
+
+ await brainService.deleteBucket(req.params.id);
+ console.log(`🗂️ Deleted bucket: ${req.params.id} (unassigned ${unassigned} links)`);
+ res.json({ deleted: true, unassigned });
+}));
+
// =============================================================================
// GRAPH
// =============================================================================
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index 6c7c93301f..74283735f3 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -53,7 +53,20 @@ vi.mock('../services/brain.js', () => ({
// Settings & Summary
loadMeta: vi.fn(),
updateMeta: vi.fn(),
- getSummary: vi.fn()
+ getSummary: vi.fn(),
+ // Links
+ getLinks: vi.fn(),
+ getLinkById: vi.fn(),
+ getLinkByUrl: vi.fn(),
+ createLink: vi.fn(),
+ updateLink: vi.fn(),
+ deleteLink: vi.fn(),
+ // Buckets
+ getBuckets: vi.fn(),
+ getBucketById: vi.fn(),
+ createBucket: vi.fn(),
+ updateBucket: vi.fn(),
+ deleteBucket: vi.fn()
}));
// Mock the brain graph service
@@ -1177,4 +1190,117 @@ describe('Brain Routes', () => {
expect(res.status).toBe(400);
});
});
+
+ // ===========================================================================
+ // BUCKETS
+ // ===========================================================================
+
+ describe('GET /api/brain/buckets', () => {
+ it('returns buckets sorted by order', async () => {
+ brainService.getBuckets.mockResolvedValue([
+ { id: 'b2', name: 'Second', order: 1 },
+ { id: 'b1', name: 'First', order: 0 }
+ ]);
+ const res = await request(app).get('/api/brain/buckets');
+ expect(res.status).toBe(200);
+ expect(res.body.buckets.map(b => b.id)).toEqual(['b1', 'b2']);
+ });
+ });
+
+ describe('POST /api/brain/buckets', () => {
+ it('creates a bucket appended after existing ones', async () => {
+ brainService.getBuckets.mockResolvedValue([{ id: 'b1', order: 0 }, { id: 'b2', order: 1 }]);
+ brainService.createBucket.mockImplementation(async (data) => ({ id: 'b3', ...data }));
+ const res = await request(app).post('/api/brain/buckets').send({ name: 'Disney' });
+ expect(res.status).toBe(201);
+ expect(brainService.createBucket).toHaveBeenCalledWith(expect.objectContaining({ name: 'Disney', order: 2 }));
+ });
+
+ it('rejects an empty name with 400', async () => {
+ const res = await request(app).post('/api/brain/buckets').send({ name: '' });
+ expect(res.status).toBe(400);
+ expect(brainService.createBucket).not.toHaveBeenCalled();
+ });
+
+ it('rejects an invalid color with 400', async () => {
+ const res = await request(app).post('/api/brain/buckets').send({ name: 'X', color: 'neon' });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe('POST /api/brain/buckets/reorder', () => {
+ it('persists order for each id in the given sequence', async () => {
+ const id3 = '33333333-3333-4333-8333-333333333333';
+ const id1 = '11111111-1111-4111-8111-111111111111';
+ const id2 = '22222222-2222-4222-8222-222222222222';
+ brainService.updateBucket.mockResolvedValue({});
+ brainService.getBuckets.mockResolvedValue([]);
+ const res = await request(app)
+ .post('/api/brain/buckets/reorder')
+ .send({ ids: [id3, id1, id2] });
+ expect(res.status).toBe(200);
+ expect(brainService.updateBucket).toHaveBeenNthCalledWith(1, id3, { order: 0 });
+ expect(brainService.updateBucket).toHaveBeenNthCalledWith(2, id1, { order: 1 });
+ expect(brainService.updateBucket).toHaveBeenNthCalledWith(3, id2, { order: 2 });
+ });
+ });
+
+ describe('PUT /api/brain/buckets/:id', () => {
+ it('updates an existing bucket', async () => {
+ brainService.getBucketById.mockResolvedValue({ id: 'b1', name: 'Old' });
+ brainService.updateBucket.mockResolvedValue({ id: 'b1', name: 'New' });
+ const res = await request(app).put('/api/brain/buckets/b1').send({ name: 'New' });
+ expect(res.status).toBe(200);
+ expect(res.body.name).toBe('New');
+ });
+
+ it('returns 404 for an unknown bucket', async () => {
+ brainService.getBucketById.mockResolvedValue(null);
+ const res = await request(app).put('/api/brain/buckets/missing').send({ name: 'X' });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('DELETE /api/brain/buckets/:id', () => {
+ it('deletes the bucket and unassigns its links', async () => {
+ brainService.getBucketById.mockResolvedValue({ id: 'b1', name: 'Disney' });
+ brainService.getLinks.mockResolvedValue([
+ { id: 'l1', bucketId: 'b1' },
+ { id: 'l2', bucketId: 'b2' },
+ { id: 'l3', bucketId: 'b1' }
+ ]);
+ brainService.updateLink.mockResolvedValue({});
+ brainService.deleteBucket.mockResolvedValue(true);
+
+ const res = await request(app).delete('/api/brain/buckets/b1');
+ expect(res.status).toBe(200);
+ expect(res.body.unassigned).toBe(2);
+ expect(brainService.updateLink).toHaveBeenCalledWith('l1', { bucketId: null });
+ expect(brainService.updateLink).toHaveBeenCalledWith('l3', { bucketId: null });
+ expect(brainService.updateLink).not.toHaveBeenCalledWith('l2', { bucketId: null });
+ expect(brainService.deleteBucket).toHaveBeenCalledWith('b1');
+ });
+
+ it('returns 404 for an unknown bucket', async () => {
+ brainService.getBucketById.mockResolvedValue(null);
+ const res = await request(app).delete('/api/brain/buckets/missing');
+ expect(res.status).toBe(404);
+ expect(brainService.deleteBucket).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('POST /api/brain/links (bucket + title derivation)', () => {
+ it('derives a hostname title for a plain URL and stores bucketId', async () => {
+ brainService.getLinkByUrl.mockResolvedValue(null);
+ brainService.createLink.mockImplementation(async (data) => ({ id: 'l9', ...data }));
+ const res = await request(app)
+ .post('/api/brain/links')
+ .send({ url: 'https://www.example.com/parks', bucketId: '11111111-1111-4111-8111-111111111111' });
+ expect(res.status).toBe(201);
+ expect(brainService.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'example.com',
+ bucketId: '11111111-1111-4111-8111-111111111111'
+ }));
+ });
+ });
});
diff --git a/server/services/brain.js b/server/services/brain.js
index c3fd22c1c9..16959559aa 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -699,3 +699,8 @@ export const getLinkByUrl = storage.getLinkByUrl;
export const createLink = storage.createLink;
export const updateLink = storage.updateLink;
export const deleteLink = storage.deleteLink;
+export const getBuckets = storage.getBuckets;
+export const getBucketById = storage.getBucketById;
+export const createBucket = storage.createBucket;
+export const updateBucket = storage.updateBucket;
+export const deleteBucket = storage.deleteBucket;
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index b4268ecc36..8b999f9c79 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -50,7 +50,12 @@ vi.mock('./brainStorage.js', () => {
getLinkByUrl: vi.fn(),
createLink: vi.fn(),
updateLink: vi.fn(),
- deleteLink: vi.fn()
+ deleteLink: vi.fn(),
+ getBuckets: vi.fn(),
+ getBucketById: vi.fn(),
+ createBucket: vi.fn(),
+ updateBucket: vi.fn(),
+ deleteBucket: vi.fn()
};
});
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index f265f948b6..723da50b18 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -31,6 +31,7 @@ const FILES = {
admin: join(DATA_DIR, 'admin.json'),
memories: join(DATA_DIR, 'memories.json'),
links: join(DATA_DIR, 'links.json'),
+ buckets: join(DATA_DIR, 'buckets.json'),
digests: join(DATA_DIR, 'digests.jsonl'),
reviews: join(DATA_DIR, 'reviews.jsonl')
};
@@ -47,6 +48,7 @@ const caches = {
admin: { data: null, timestamp: 0 },
memories: { data: null, timestamp: 0 },
links: { data: null, timestamp: 0 },
+ buckets: { data: null, timestamp: 0 },
inboxLog: { data: null, timestamp: 0 },
digests: { data: null, timestamp: 0 },
reviews: { data: null, timestamp: 0 }
@@ -570,6 +572,13 @@ export async function getLinkByUrl(url) {
return links.find(link => link.url === url) || null;
}
+// Buckets (bookmark groups for links)
+export const getBuckets = (filters) => filters ? query('buckets', filters) : getAll('buckets');
+export const getBucketById = (id) => getById('buckets', id);
+export const createBucket = (data) => create('buckets', data);
+export const updateBucket = (id, data) => update('buckets', id, data);
+export const deleteBucket = (id) => remove('buckets', id);
+
// =============================================================================
// REMOTE SYNC OPERATIONS (no events, no sync log — echo prevention)
// =============================================================================
@@ -614,7 +623,7 @@ export async function applyRemoteRecord(type, id, record, op) {
*/
export async function backfillOriginInstanceId() {
const instanceId = await getInstanceId();
- const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories', 'links'];
+ const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];
let totalBackfilled = 0;
for (const type of entityTypes) {
@@ -660,13 +669,14 @@ export function invalidateAllCaches() {
* Get brain data summary (for dashboard)
*/
export async function getSummary() {
- const [people, projects, ideas, adminItems, memoryEntries, links, inboxCounts, meta] = await Promise.all([
+ const [people, projects, ideas, adminItems, memoryEntries, links, buckets, inboxCounts, meta] = await Promise.all([
getAll('people'),
getAll('projects'),
getAll('ideas'),
getAll('admin'),
getAll('memories'),
getAll('links'),
+ getAll('buckets'),
getInboxLogCounts(),
loadMeta()
]);
@@ -679,6 +689,7 @@ export async function getSummary() {
admin: adminItems.length,
memories: memoryEntries.length,
links: links.length,
+ buckets: buckets.length,
inbox: inboxCounts
},
activeProjects: projects.filter(p => p.status === 'active').length,
diff --git a/server/services/brainSync.js b/server/services/brainSync.js
index 5d595d03d2..778fd5e821 100644
--- a/server/services/brainSync.js
+++ b/server/services/brainSync.js
@@ -13,7 +13,7 @@ import * as brainStorage from './brainStorage.js';
import * as brainSyncLog from './brainSyncLog.js';
// Entity types stored as JSON (have records with IDs)
-const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links'];
+const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];
/**
* Apply remote changes from a peer instance.