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

50.8 KB
Raw Blame
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Link } from 'react-router';
import {
  DndContext, DragOverlay, KeyboardSensor, PointerSensor,
  useDraggable, useSensor, useSensors,
} from '@dnd-kit/core';
import * as api from '../../../services/api';
import {
  Link2,
  Send,
  RefreshCw,
  ExternalLink,
  Trash2,
  Edit2,
  Save,
  X,
  GitBranch,
  Download,
  Check,
  AlertCircle,
  FolderOpen,
  Tag,
  ShieldCheck,
  Skull,
  Lightbulb,
  Search,
  ChevronDown,
  ChevronUp,
  FolderClosed,
  GripVertical,
  FileText
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { timeAgo } from '../../../utils/formatters';
import { sameJsonShape } from '../../../lib/sameJsonShape';
import { useSocketResource } from '../../../hooks/useSocketResource';
import BucketBoard from '../links/BucketBoard';
import RepoRestudyPanel from '../RepoRestudyPanel';
import LinkChip from '../links/LinkChip';
import { reorderLinksInBucket } from '../links/bucketReorder';
import {
  linksCollisionDetection, linksKeyboardCoordinates,
  BUCKET_KIND, LINK_KIND, LINK_SLOT_KIND,
} from '../links/bucketDnd';
import { normalizeUrl as normalizeUrlShared } from '../../../utils/urlNormalize';

/**
 * True once a link has a malware-scan report that can actually be opened. A
 * capture-time scan is stamped `queued` before the agent runs, and a scan whose
 * agent never wrote a report file finalizes as `failed` — both carry a reportId
 * with no file behind it, so the "Scan Reports" filter must not offer either
 * (the report route would 404). Legacy records carry no `status` at all and are
 * treated as readable.
 */
const hasScanReport = (link) => {
  if (!link.malwareScan?.reportId) return false;
  const { status } = link.malwareScan;
  return status === undefined || status === 'completed';
};

/** Normalize a user-entered URL the way the quick-add form does. */
function normalizeUrl(raw) {
  return normalizeUrlShared(raw, { allowGit: true, requireDot: true });
}

const REPO_TYPE_COLOR = 'bg-purple-500/20 text-purple-400 border-purple-500/30';

const LINK_TYPE_COLORS = {
  repo: REPO_TYPE_COLOR,
  // Pre-multi-host records still carry `github`; migration 330 renames the
  // stored value but a peer on older code can still federate one in.
  github: REPO_TYPE_COLOR,
  article: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
  documentation: 'bg-green-500/20 text-green-400 border-green-500/30',
  tool: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
  reference: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30',
  other: 'bg-gray-500/20 text-gray-400 border-gray-500/30'
};

const CLONE_STATUS_STYLES = {
  none: '',
  pending: 'text-port-warning',
  cloning: 'text-port-accent animate-pulse',
  cloned: 'text-port-success',
  failed: 'text-port-error'
};

const LINK_EVENTS = ['brain:links:changed'];

// The fields the background clone and its post-clone intake write. The event read
// merges ONLY these onto the record it already has, so a response that was
// already in flight when the user renamed a link or dragged its chip cannot
// revert that edit with a pre-edit snapshot of the whole record. All five are
// server-owned; nothing in this tab edits them locally.
const CLONE_PROGRESS_FIELDS = ['cloneStatus', 'cloneError', 'localPath', 'malwareScan', 'repoStudy'];

// `malwareScan` / `repoStudy` arrive as fresh objects on every event read, so they
// need a value comparison — otherwise every event would look like a change and
// re-render the whole list. A false "changed" costs one render; there is no
// false "same" for equal content the server serializes consistently.
const sameFieldValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);

/** The clone-progress fields that actually moved, or null when none did. */
function cloneProgressPatch(fresh, current) {
  const patch = {};
  for (const field of CLONE_PROGRESS_FIELDS) {
    if (!sameFieldValue(fresh[field], current[field])) patch[field] = fresh[field];
  }
  return Object.keys(patch).length > 0 ? patch : null;
}

export default function LinksTab({ onRefresh }) {
  const [inputUrl, setInputUrl] = useState('');
  const [inputTitle, setInputTitle] = useState('');
  const [inputNote, setInputNote] = useState('');
  const [inputTags, setInputTags] = useState('');
  const [showDetails, setShowDetails] = useState(false);
  const [sending, setSending] = useState(false);
  const [links, setLinks] = useState([]);
  const [buckets, setBuckets] = useState([]);
  const [loading, setLoading] = useState(true);
  // A local action-refresh read (revert after a failed optimistic update) failed.
  const [actionReadFailed, setActionReadFailed] = useState(false);
  const [filter, setFilter] = useState('all'); // all, repo, scanned, other, ungrouped
  const [search, setSearch] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [editForm, setEditForm] = useState({});
  const [confirmingDeleteId, setConfirmingDeleteId] = useState(null);
  const [scanningId, setScanningId] = useState(null);
  // The one repo whose "Update & study" form is open, if any.
  const [studyingId, setStudyingId] = useState(null);
  const inputRef = useRef(null);

  // Fetch the full link set; filtering, search, and bucket membership are all
  // computed client-side, so we need every link in one round-trip — the prior
  // `limit: 100` silently truncated power-user collections (>100 links lost
  // from list views, search, and bucket boards). The server schema caps at
  // 5000, which is ample headroom for a single-user bookmark collection.
  const fetchLinks = useCallback(async () => {
    // On failure keep the last good snapshot and flag the collection as
    // unavailable rather than substituting an empty (and authoritative-looking) list.
    const data = await api.getBrainLinks({ limit: 5000, silent: true }).catch(() => null);
    if (data) {
      setLinks(data.links || []);
      setActionReadFailed(false);
    } else {
      setActionReadFailed(true);
    }
    setLoading(false);
  }, []);

  const readChanges = useCallback(async ({ reconcile, events }) => {
    if (reconcile) {
      const [data, bucketData] = await Promise.all([
        api.getBrainLinks({ limit: 5000, silent: true }),
        api.getBrainBuckets({ silent: true })
      ]);
      return { links: data.links || [], buckets: bucketData.buckets || [] };
    }
    const ids = [...new Set(events.map(({ payload }) => payload.id))];
    const updates = await Promise.all(ids.map(id => api.getBrainLink(id, { silent: true })
      .then(fresh => ({ id, fresh }))
      .catch(error => {
        if (error?.status === 404) return { id, gone: true };
        return { id }; // Keep this record on transient failure; other updates still land.
      })));
    return { updates };
  }, []);
  const { data: changes, loading: reading, error: readError, refetch } = useSocketResource(readChanges, {
    events: LINK_EVENTS,
    matchesEvent: payload => typeof payload?.id === 'string',
    compare: sameJsonShape
  });
  useEffect(() => {
    if (!reading) setLoading(false);
    if (!changes) return;
    if (changes.links) {
      setLinks(changes.links);
      setBuckets(changes.buckets);
      return;
    }
    // Merge only server-owned progress fields so a late read cannot undo a
    // local rename or bucket drag. Completed clones still receive scan updates.
    setLinks(prev => {
      const byId = new Map(changes.updates.map(update => [update.id, update]));
      let changed = false;
      const next = [];
      for (const link of prev) {
        const result = byId.get(link.id);
        byId.delete(link.id);
        if (result?.gone) { changed = true; continue; }
        const patch = result?.fresh ? cloneProgressPatch(result.fresh, link) : null;
        if (!patch) { next.push(link); continue; }
        changed = true;
        next.push({ ...link, ...patch });
      }
      for (const result of byId.values()) {
        if (result.fresh) { next.push(result.fresh); changed = true; }
      }
      return changed ? next : prev;
    });
  }, [changes, reading]);

  const unavailable = Boolean(readError) || actionReadFailed;
  const retryRead = () => {
    if (actionReadFailed) fetchLinks();
    refetch();
  };

  // Client-side filter (type / bucket membership) then keyword search.
  const matchesFilter = (link) => {
    if (filter === 'repo') return link.isRepo;
    if (filter === 'scanned') return hasScanReport(link);
    if (filter === 'other') return !link.isRepo;
    if (filter === 'ungrouped') return !link.bucketId;
    return true;
  };
  const filteredLinks = links.filter(matchesFilter);

  const query = search.trim().toLowerCase();
  const visibleLinks = query
    ? filteredLinks.filter(link => {
        const haystack = [
          link.title,
          link.url,
          link.note,
          link.description,
          ...(link.tags || [])
        ].filter(Boolean).join(' ').toLowerCase();
        return haystack.includes(query);
      })
    : filteredLinks;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!inputUrl.trim() || sending) return;

    const url = normalizeUrl(inputUrl);
    if (!url) {
      toast.error('Please enter a valid URL');
      return;
    }

    const payload = { url };
    const title = inputTitle.trim();
    if (title) payload.title = title;
    const note = inputNote.trim();
    if (note) payload.note = note;
    const tags = inputTags.split(',').map(t => t.trim()).filter(Boolean);
    if (tags.length) payload.tags = tags;

    setSending(true);
    const result = await api.createBrainLink(payload, { silent: true }).catch(err => {
      if (err.message?.includes('already exists')) {
        toast.error('This URL is already saved');
      } else {
        toast.error(err.message || 'Failed to save link');
      }
      return null;
    });
    setSending(false);

    if (result) {
      toast.success(result.isRepo ? 'Repo added - cloning in background' : 'Link saved');
      setInputUrl('');
      setInputTitle('');
      setInputNote('');
      setInputTags('');
      setShowDetails(false);
      setLinks(prev => prev.some(link => link.id === result.id) ? prev : [result, ...prev]);
      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, { silent: true }).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
    }
  };

  // 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 persists the whole batch in
  // one atomic call: N concurrent single-link PUTs would race the shared links
  // store and silently lose-update some chips' bucketOrder.
  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 ok = await api.reorderBrainLinks(changed, { silent: true }).catch(() => null);
    if (!ok) {
      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);
    if (!url) {
      toast.error('Please enter a valid URL');
      return false;
    }
    const result = await api.createBrainLink({ url, bucketId, bucketOrder: nextBucketOrder(bucketId) }, { silent: true }).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({
      url: link.url,
      title: link.title,
      description: link.description || '',
      note: link.note || '',
      linkType: link.linkType,
      tags: link.tags?.join(', ') || ''
    });
  };

  const handleSaveEdit = async (linkId) => {
    const url = editForm.url?.trim();
    if (!url) {
      toast.error('URL cannot be empty');
      return;
    }

    const updates = {
      url,
      title: editForm.title,
      description: editForm.description,
      note: editForm.note,
      linkType: editForm.linkType,
      tags: editForm.tags ? editForm.tags.split(',').map(t => t.trim()).filter(Boolean) : []
    };

    const result = await api.updateBrainLink(linkId, updates, { silent: true }).catch(err => {
      if (err.message?.includes('already exists')) {
        toast.error('Another link already uses this URL');
      } else {
        toast.error(err.message || 'Failed to update');
      }
      return null;
    });

    if (result) {
      toast.success('Link updated');
      setEditingId(null);
      setEditForm({});
      setLinks(prev => prev.map(link => link.id === result.id ? result : link));
    }
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditForm({});
  };

  const handleDelete = async (linkId) => {
    const result = await api.deleteBrainLink(linkId, { silent: true }).catch(err => {
      toast.error(err.message || 'Failed to delete');
      return null;
    });
    if (!result) return;

    toast.success('Link deleted');
    setConfirmingDeleteId(null);
    setLinks(prev => prev.filter(link => link.id !== linkId));
    onRefresh?.();
  };

  const handleClone = async (linkId) => {
    const result = await api.cloneBrainLink(linkId, { silent: true }).catch(err => {
      toast.error(err.message || 'Failed to start clone');
      return null;
    });

    if (result) {
      toast.success('Clone started');
      // The persisted clone transition arrives through brain:links:changed.
    }
  };

  const handlePull = async (linkId) => {
    const result = await api.pullBrainLink(linkId, { silent: true }).catch(err => {
      toast.error(err.message || 'Failed to pull');
      return null;
    });

    if (result) {
      toast.success('Pulled latest changes');
    }
  };

  const handleOpenFolder = async (linkId) => {
    await api.openBrainLinkFolder(linkId, { silent: true }).catch(err => {
      toast.error(err.message || 'Failed to open folder');
    });
  };

  const handleScan = async (linkId) => {
    setScanningId(linkId);
    const result = await api.scanBrainLink(linkId, { silent: true }).catch(err => {
      toast.error(err.message || 'Failed to start scan');
      return null;
    });
    setScanningId(null);

    if (result) {
      toast.success('Malware scan queued — track progress in CoS Tasks');
    }
  };

  // --- Drag-and-drop: buckets (reorder) and links (file/reorder into a
  // bucket, from the flat list or from another chip) share ONE DndContext so
  // a link picked up in the list can be dropped straight into a bucket at a
  // specific position. See bucketDnd.js for the coordinate/collision logic.
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
    useSensor(KeyboardSensor, { coordinateGetter: linksKeyboardCoordinates }),
  );
  const [activeDrag, setActiveDrag] = useState(null);

  const handleReorderBuckets = useCallback((draggedId, targetId) => {
    if (!draggedId || draggedId === targetId) return;
    setBuckets(prev => {
      const ids = prev.map(b => b.id);
      const from = ids.indexOf(draggedId);
      const to = ids.indexOf(targetId);
      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), { silent: true }).catch(err => {
        toast.error(err.message || 'Failed to reorder buckets');
      });
      return next;
    });
  }, []);

  const handleDragStart = useCallback((event) => {
    setActiveDrag(event.active.data.current || null);
  }, []);

  const handleDragEnd = useCallback((event) => {
    const { active, over } = event;
    setActiveDrag(null);
    if (!over || !active) return;
    const activeData = active.data.current || {};
    const overData = over.data.current || {};
    if (activeData.kind === BUCKET_KIND && overData.kind === BUCKET_KIND) {
      handleReorderBuckets(activeData.bucket?.id, overData.bucketId);
      return;
    }
    if (activeData.kind === LINK_KIND && overData.kind === LINK_SLOT_KIND && activeData.link) {
      handleMoveLinkToIndex(activeData.link, overData.bucketId, overData.index);
    }
  }, [handleReorderBuckets, handleMoveLinkToIndex]);

  const handleDragCancel = useCallback(() => setActiveDrag(null), []);

  // dnd-kit's stock announcements only say "draggable item N" (an id). Name
  // the bucket/link and its destination instead, using the live counts so
  // "position 2 of 5" stays accurate as buckets fill up.
  const dndAccessibility = useMemo(() => {
    const bucketName = (id) => buckets.find(b => b.id === id)?.name || 'Unfiled';
    const describeBucketTarget = (over) => {
      const bucketId = over?.data?.current?.bucketId;
      if (!bucketId) return null;
      const idx = buckets.findIndex(b => b.id === bucketId);
      return idx === -1 ? null : `position ${idx + 1} of ${buckets.length}`;
    };
    const describeLinkTarget = (active, over) => {
      const data = over?.data?.current;
      if (!data || data.kind !== LINK_SLOT_KIND) return null;
      const link = active?.data?.current?.link;
      if (!link) return null;
      // Reuse the same helper the actual move persists with, rather than
      // hand-rolling the position math again: dropping an already-in-bucket
      // link on its own bucket's trailing "append" slot lands ONE EARLIER
      // than the raw slot index once the link's own current slot is removed
      // from under it, and only reorderLinksInBucket's insertAt adjustment
      // gets that right (see its own tests for the exact case).
      const { renumbered } = reorderLinksInBucket(links, link, data.bucketId, data.index);
      const finalIndex = renumbered.findIndex(r => r.id === link.id);
      if (finalIndex === -1) return null;
      return `position ${finalIndex + 1} of ${renumbered.length} in ${bucketName(data.bucketId)}`;
    };
    const itemLabel = (active) => {
      const data = active?.data?.current;
      if (!data) return 'item';
      return data.kind === BUCKET_KIND ? `bucket ${data.bucket?.name || ''}`.trim() : (data.link?.title || 'link');
    };
    const destinationFor = (active, over) => (active?.data?.current?.kind === BUCKET_KIND
      ? describeBucketTarget(over)
      : describeLinkTarget(active, over));
    return {
      announcements: {
        onDragStart: ({ active }) => (active?.data?.current?.kind === BUCKET_KIND
          ? `Picked up ${itemLabel(active)}. Use the arrow keys to choose a new position, Space to drop it there, or Escape to cancel.`
          : `Picked up ${itemLabel(active)}. Use the arrow keys to choose a bucket and position, Space to file it there, or Escape to cancel.`),
        onDragOver: ({ active, over }) => {
          const dest = destinationFor(active, over);
          return dest ? `${itemLabel(active)} is over ${dest}.` : `${itemLabel(active)} is not over a valid destination.`;
        },
        onDragEnd: ({ active, over }) => {
          const dest = destinationFor(active, over);
          return dest ? `Moved ${itemLabel(active)} to ${dest}.` : `${itemLabel(active)} was dropped outside a valid destination and did not move.`;
        },
        onDragCancel: ({ active }) => `Cancelled moving ${itemLabel(active)}. It stayed where it was.`,
      },
      screenReaderInstructions: {
        draggable: 'To move this item, press Space or Enter. While dragging, use the arrow keys to choose a destination, then press Space to drop it there, or Escape to cancel.',
      },
    };
  }, [links, buckets]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <BrailleSpinner text="Loading" />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      <DndContext
        sensors={sensors}
        collisionDetection={linksCollisionDetection}
        accessibility={dndAccessibility}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        onDragCancel={handleDragCancel}
      >
      {unavailable && (
        <Banner
          tone="error"
          icon={AlertCircle}
          title="Links unavailable"
          className="mb-4"
          actions={(
            <button
              type="button"
              onClick={retryRead}
              className="flex items-center gap-1 px-3 py-1.5 min-h-[40px] rounded border border-port-error/40 text-port-error hover:bg-port-error/10 text-xs"
            >
              <RefreshCw size={12} /> Retry
            </button>
          )}
        >
          {links.length > 0 || buckets.length > 0
            ? 'Could not refresh your saved links. The list below may be out of date.'
            : 'Could not load your saved links. This does not mean the collection is empty.'}
        </Banner>
      )}
      <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">
          <input
            ref={inputRef}
            type="text"
            value={inputUrl}
            onChange={(e) => setInputUrl(e.target.value)}
            placeholder="Paste a URL (GitHub / GitLab repos auto-clone)..."
            aria-label="Link URL to save"
            className="flex-1 px-4 py-3 bg-port-card border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-hidden focus:border-port-accent"
            disabled={sending}
          />
          <button
            type="submit"
            disabled={sending || !inputUrl.trim()}
            className="px-4 py-3 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 min-h-[48px]"
            title={sending ? 'Saving...' : 'Save link'}
          >
            {sending ? (
              <BrailleSpinner />
            ) : (
              <Send className="w-5 h-5" />
            )}
          </button>
        </div>
        <button
          type="button"
          onClick={() => setShowDetails(v => !v)}
          className="mt-2 flex items-center gap-1 text-xs text-gray-400 hover:text-white transition-colors"
        >
          {showDetails ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
          {showDetails ? 'Hide link details' : 'Add title, note & tags (optional)'}
        </button>

        {showDetails && (
          <div className="mt-2 space-y-2">
            <div>
              <label htmlFor="link-title" className="sr-only">Title</label>
              <input
                id="link-title"
                type="text"
                value={inputTitle}
                onChange={(e) => setInputTitle(e.target.value)}
                placeholder="Title (defaults to repo name or URL)"
                className="w-full px-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm placeholder-gray-500 focus:outline-hidden focus:border-port-accent"
                disabled={sending}
              />
            </div>
            <div>
              <label htmlFor="link-note" className="block text-xs text-gray-400 mb-1">
                Why are you saving this? <span className="text-gray-600">(optional)</span>
              </label>
              <textarea
                id="link-note"
                rows={2}
                maxLength={2000}
                value={inputNote}
                onChange={(e) => setInputNote(e.target.value)}
                placeholder="e.g. Read later, share with the team, or turn into a future task"
                className="w-full px-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm placeholder-gray-500 focus:outline-hidden focus:border-port-accent resize-y"
                disabled={sending}
              />
            </div>
            <div>
              <label htmlFor="link-tags" className="sr-only">Tags</label>
              <input
                id="link-tags"
                type="text"
                value={inputTags}
                onChange={(e) => setInputTags(e.target.value)}
                placeholder="Tags (comma-separated)"
                className="w-full px-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm placeholder-gray-500 focus:outline-hidden focus:border-port-accent"
                disabled={sending}
              />
            </div>
          </div>
        )}

        <p className="mt-2 text-xs text-gray-500">
          Paste any URL. GitHub and GitLab repos will be automatically cloned for local reference.
        </p>
      </form>

      {/* Filter tabs */}
      <div className="flex gap-2 mb-4 flex-wrap">
        {[
          { id: 'all', label: 'All', count: links.length },
          { id: 'repo', label: 'Repos', icon: GitBranch, count: links.filter(l => l.isRepo).length },
          { id: 'scanned', label: 'Scan Reports', icon: FileText, count: links.filter(hasScanReport).length },
          { id: 'other', label: 'Other Links', icon: Link2, count: links.filter(l => !l.isRepo).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;
          return (
            <button
              key={tab.id}
              onClick={() => setFilter(tab.id)}
              className={`flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-colors min-h-[40px] ${
                isActive
                  ? 'bg-port-accent/20 text-port-accent border border-port-accent/30'
                  : 'bg-port-card text-gray-400 hover:text-white border border-port-border'
              }`}
            >
              {Icon && <Icon size={14} />}
              {tab.label}
              {tab.count !== undefined && (
                <span className="text-xs opacity-60">({tab.count})</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Search */}
      <div className="relative mb-4">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search links by title, URL, note, description, or tag..."
          aria-label="Search links"
          className="w-full pl-9 pr-9 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm placeholder-gray-500 focus:outline-hidden focus:border-port-accent"
        />
        {search && (
          <button
            onClick={() => setSearch('')}
            className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-white transition-colors"
            title="Clear search" aria-label="Clear search"
          >
            <X size={14} />
          </button>
        )}
      </div>

      {/* Links list */}
      <div className="space-y-3">
        {visibleLinks.map(link => {
          const isEditing = editingId === link.id;
          return (
          <div
            key={link.id}
            className="p-4 bg-port-card border border-port-border rounded-lg"
          >
            {/* Header row */}
            <div className="flex items-start justify-between gap-3 mb-2">
              {!isEditing && (
                <LinkDragHandle link={link} />
              )}
              {editingId === link.id ? (
                <div className="flex-1 space-y-2">
                  <div>
                    <label htmlFor={`link-url-${link.id}`} className="block text-xs text-gray-400 mb-1">URL</label>
                    <input
                      id={`link-url-${link.id}`}
                      type="url"
                      value={editForm.url}
                      onChange={(e) => setEditForm({ ...editForm, url: e.target.value })}
                      className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
                      placeholder="https://example.com"
                    />
                  </div>
                  <div>
                    <label htmlFor={`link-title-${link.id}`} className="block text-xs text-gray-400 mb-1">Title</label>
                    <input
                      id={`link-title-${link.id}`}
                      type="text"
                      value={editForm.title}
                      onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                      className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
                      placeholder="Title"
                      autoFocus
                    />
                  </div>
                  <textarea
                    aria-label="Description"
                    value={editForm.description}
                    onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                    className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm resize-none"
                    placeholder="Description (optional)"
                    rows={2}
                  />
                  <div>
                    <label htmlFor={`link-note-${link.id}`} className="block text-xs text-gray-400 mb-1">
                      Why are you saving this? <span className="text-gray-600">(optional)</span>
                    </label>
                    <textarea
                      id={`link-note-${link.id}`}
                      value={editForm.note}
                      onChange={(e) => setEditForm({ ...editForm, note: e.target.value })}
                      className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm resize-y"
                      placeholder="Why are you saving this link?"
                      rows={2}
                    />
                  </div>
                  <div className="flex gap-2">
                    <select
                      aria-label="Link type"
                      value={editForm.linkType}
                      onChange={(e) => setEditForm({ ...editForm, linkType: e.target.value })}
                      className="px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
                    >
                      <option value="repo">Repository</option>
                      {/* Pre-multi-host records (and any federated in from a peer on
                          older code) still carry `github`. Without an option to match,
                          the select renders BLANK on those rows — the value is intact
                          but it reads as data loss. */}
                      {editForm.linkType === 'github' && <option value="github">GitHub (legacy)</option>}
                      <option value="article">Article</option>
                      <option value="documentation">Documentation</option>
                      <option value="tool">Tool</option>
                      <option value="reference">Reference</option>
                      <option value="other">Other</option>
                    </select>
                    <input
                      type="text"
                      value={editForm.tags}
                      onChange={(e) => setEditForm({ ...editForm, tags: e.target.value })}
                      className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
                      placeholder="Tags (comma-separated)"
                      aria-label="Link tags, comma-separated"
                    />
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleSaveEdit(link.id)}
                      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={handleCancelEdit}
                      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-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      {link.isRepo ? (
                        link.malwareScan?.verdict === 'DANGEROUS'
                          ? <Skull size={16} className="text-port-error shrink-0" aria-label="Dangerous repository" />
                          : <GitBranch size={16} className="text-purple-400 shrink-0" />
                      ) : (
                        <Link2 size={16} className="text-gray-400 shrink-0" />
                      )}
                      <h3 className="font-medium text-white truncate">{link.title}</h3>
                    </div>
                    <a
                      href={link.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      draggable={false}
                      className="text-sm text-gray-400 hover:text-port-accent truncate block"
                    >
                      {link.url}
                    </a>
                    {link.description && (
                      <p className="text-sm text-gray-500 mt-1">{link.description}</p>
                    )}
                    {link.note && (
                      <p className="text-sm text-gray-400 mt-1">
                        <span className="text-gray-500">Note:</span> {link.note}
                      </p>
                    )}
                  </div>

                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={() => handleEdit(link)}
                      className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-400 hover:text-white transition-colors"
                      title="Edit" aria-label="Edit"
                    >
                      <Edit2 size={14} />
                    </button>
                    <button
                      onClick={() => setConfirmingDeleteId(link.id)}
                      className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-400 hover:text-port-error transition-colors"
                      title="Delete" aria-label="Delete"
                    >
                      <Trash2 size={14} />
                    </button>
                    <a
                      href={link.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      draggable={false}
                      className="p-1.5 text-gray-400 hover:text-port-accent transition-colors"
                      title="Open in new tab"
                      aria-label={`Open ${link.title || link.url} in a new tab`}
                    >
                      <ExternalLink size={14} />
                    </a>
                  </div>
                </>
              )}

              <span className="text-xs text-gray-500 whitespace-nowrap">
                {timeAgo(link.createdAt)}
              </span>
            </div>

            {/* Delete confirmation */}
            {confirmingDeleteId === link.id && (
              <InlineConfirmRow
                question="Delete this link? This cannot be undone."
                className="mb-2"
                onConfirm={() => handleDelete(link.id)}
                onCancel={() => setConfirmingDeleteId(null)}
              />
            )}

            {/* Footer row */}
            {editingId !== link.id && (
              <div className="flex items-center gap-2 flex-wrap mt-2">
                {/* Link type badge */}
                <span className={`px-2 py-1 text-xs rounded border ${LINK_TYPE_COLORS[link.linkType] || LINK_TYPE_COLORS.other}`}>
                  {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 min-w-0 flex-wrap items-center gap-1">
                    <Tag size={12} className="text-gray-500" />
                    {link.tags.map((tag, i) => (
                      <span key={i} className="max-w-full break-all px-1.5 py-0.5 text-xs bg-port-border/50 text-gray-400 rounded">
                        {tag}
                      </span>
                    ))}
                  </div>
                )}

                {/* Repository-specific controls */}
                {link.isRepo && (
                  <>
                    {/* Clone status */}
                    <span className={`flex items-center gap-1 text-xs ${CLONE_STATUS_STYLES[link.cloneStatus]}`}>
                      {link.cloneStatus === 'cloned' && <Check size={12} />}
                      {link.cloneStatus === 'cloning' && <BrailleSpinner />}
                      {link.cloneStatus === 'pending' && <Download size={12} />}
                      {link.cloneStatus === 'failed' && <AlertCircle size={12} />}
                      {link.cloneStatus === 'cloned' && 'Cloned'}
                      {link.cloneStatus === 'cloning' && 'Cloning...'}
                      {link.cloneStatus === 'pending' && 'Pending clone'}
                      {link.cloneStatus === 'failed' && 'Clone failed'}
                    </span>

                    {/* Clone error */}
                    {link.cloneError && (
                      <span role="status" className="text-xs text-port-error truncate max-w-[200px]" title={link.cloneError}>
                        {link.cloneError}
                      </span>
                    )}

                    {/* A capture-time scan is stamped `queued` before the agent runs,
                        and `failed` when the run landed without writing a report —
                        neither has a file to open, so say so instead of linking at a
                        404. finalizeMalwareScan flips it once the run lands. */}
                    {link.malwareScan?.status === 'queued' ? (
                      <span className="flex items-center gap-1 text-xs text-gray-400" title="Malware scan queued — track it in Chief of Staff">
                        <ShieldCheck size={12} />
                        Scan queued
                      </span>
                    ) : link.malwareScan?.status === 'failed' ? (
                      <span className="flex items-center gap-1 text-xs text-port-error" title="Malware scan finished without producing a report — re-run it from Chief of Staff">
                        <ShieldCheck size={12} />
                        Scan failed
                      </span>
                    ) : hasScanReport(link) && (
                      <Link
                        to={api.brainScanReportPath(link.id)}
                        className={`flex items-center gap-1 text-xs ${link.malwareScan.verdict === 'DANGEROUS' ? 'text-port-error' : 'text-port-accent'} hover:underline`}
                        title="View malware scan report"
                      >
                        {link.malwareScan.verdict === 'DANGEROUS' ? <Skull size={12} /> : <ShieldCheck size={12} />}
                        {link.malwareScan.verdict || 'Scan report'}
                      </Link>
                    )}

                    {link.repoStudy?.taskId && (
                      <Link
                        to="/cos/tasks"
                        className="flex items-center gap-1 text-xs text-gray-400 hover:text-port-accent transition-colors"
                        title={`Repo study queued as ${link.repoStudy.taskId} — track it in Chief of Staff`}
                      >
                        <Lightbulb size={12} />
                        Repo study
                      </Link>
                    )}

                    {/* Local path */}
                    {link.localPath && (
                      <span className="flex items-center gap-1 text-xs text-gray-500 truncate max-w-[200px]" title={link.localPath}>
                        <FolderOpen size={12} />
                        {link.localPath.split('/').slice(-2).join('/')}
                      </span>
                    )}

                    {/* Action buttons */}
                    {link.cloneStatus === 'none' && (
                      <button
                        onClick={() => handleClone(link.id)}
                        className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
                        title="Clone repository"
                      >
                        <Download size={12} />
                        Clone
                      </button>
                    )}

                    {link.cloneStatus === 'failed' && (
                      <button
                        onClick={() => handleClone(link.id)}
                        className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
                        title="Retry clone"
                      >
                        <RefreshCw size={12} />
                        Retry
                      </button>
                    )}

                    {link.cloneStatus === 'cloned' && (
                      <>
                        <button
                          onClick={() => handleOpenFolder(link.id)}
                          className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
                          title="Open folder in file manager"
                        >
                          <FolderOpen size={12} />
                          Open
                        </button>
                        <button
                          onClick={() => handlePull(link.id)}
                          className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
                          title="Pull latest changes"
                        >
                          <RefreshCw size={12} />
                          Pull
                        </button>
                        <button
                          onClick={() => setStudyingId(current => (current === link.id ? null : link.id))}
                          className={`flex items-center gap-1 px-2 py-1 text-xs rounded border transition-colors ${
                            studyingId === link.id
                              ? 'border-port-accent/30 bg-port-accent/20 text-port-accent'
                              : 'border-port-border text-gray-400 hover:text-white'
                          }`}
                          title="Pull the latest commits and queue a fresh repo study with your own brief"
                        >
                          <Lightbulb size={12} />
                          Update &amp; study
                        </button>
                        <button
                          onClick={() => handleScan(link.id)}
                          disabled={scanningId === link.id}
                          className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          title="Read-only malware/risk scan via /do:scan (writes report to ~/.claude/scans/)"
                        >
                          {scanningId === link.id ? (
                            <BrailleSpinner />
                          ) : (
                            <ShieldCheck size={12} />
                          )}
                          Scan
                        </button>
                      </>
                    )}

                    {studyingId === link.id && (
                      <RepoRestudyPanel
                        link={link}
                        onClose={() => setStudyingId(null)}
                        onQueued={(updated) => updated && setLinks(prev => prev.map(l => (l.id === updated.id ? updated : l)))}
                      />
                    )}
                  </>
                )}
              </div>
            )}
          </div>
          );
        })}

        {visibleLinks.length === 0 && query && (
          <div className="text-center py-12 text-gray-500">
            <Search className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p>No links match "{search.trim()}".</p>
            <button
              onClick={() => setSearch('')}
              className="text-sm mt-1 text-port-accent hover:underline"
            >
              Clear search
            </button>
          </div>
        )}

        {links.length === 0 && !unavailable && (
          <div className="text-center py-12 text-gray-500">
            <Link2 className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p>No links saved yet.</p>
            <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 (or use a chip/bucket's grip handle with the keyboard) to reorder or move 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>
      <DragOverlay>
        {activeDrag?.kind === LINK_KIND && activeDrag.link && (
          <div className="rotate-1 shadow-lg">
            <LinkChip link={activeDrag.link} />
          </div>
        )}
        {activeDrag?.kind === BUCKET_KIND && activeDrag.bucket && (
          <div className="flex items-center gap-2 px-3 py-1.5 rounded bg-port-card border border-port-accent text-sm text-port-accent shadow-lg">
            {activeDrag.bucket.icon && <span className="text-base leading-none">{activeDrag.bucket.icon}</span>}
            {activeDrag.bucket.name}
          </div>
        )}
      </DragOverlay>
      </DndContext>
    </div>
  );
}

/**
 * Drag source for a link-list row: dnd-kit's `attributes`/`listeners` must be
 * spread on a real focusable element (not the whole row, which also hosts
 * click targets like Edit/Delete/Open), so the grip icon becomes a dedicated
 * handle — the same shape as `LibraryPane.jsx`'s `WorkRow` and
 * `KanbanBoard.jsx`'s `DraggableTicket`. Its `data.bucketId`/`index` are
 * always null: a list row isn't rendered inside any one bucket's order, so a
 * keyboard pickup here always enters bucket order fresh (see
 * `bucketDnd.js`'s fallback for "no current position").
 */
function LinkDragHandle({ link, disabled }) {
  const { attributes, listeners, setNodeRef, setActivatorNodeRef, isDragging } = useDraggable({
    id: `link-list:${link.id}`,
    data: { kind: LINK_KIND, link, bucketId: null, index: null },
    disabled,
  });
  return (
    <button
      type="button"
      ref={(node) => { setNodeRef(node); setActivatorNodeRef(node); }}
      {...attributes}
      {...listeners}
      disabled={disabled}
      className={`shrink-0 mt-0.5 flex items-center justify-center text-gray-600 hover:text-gray-400 ${
        disabled ? 'cursor-not-allowed opacity-50' : 'cursor-grab active:cursor-grabbing'
      } ${isDragging ? 'opacity-30' : ''}`}
      aria-label={`Drag ${link.title} to a bucket`}
      title="Drag to a bucket"
    >
      <GripVertical size={16} />
    </button>
  );
}