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

link Importer from Series Pipeline and add universe/series autocomplete

[._.]/ Adam Eivyafd2a0a5a5ab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a8d1e31ef8..be2b9603d9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Jump to the Importer from the Series Pipeline — with the universe & series carried over** — Starting a series and realizing you already have a manuscript no longer means hunting for the Importer. The Series Pipeline index gains an **Import** button beside **New Series**, the create form carries an inline "Already have a manuscript? **Import it instead**" link (deep-linking your in-progress universe + typed series name), and a series detail page gains an **Import** action that opens the Importer pre-targeted at *that* universe and series. The Importer's **Universe Name** and **Series Name** fields are now **autocomplete comboboxes** — the same match-or-create UX as the Universe creator — so you land an exact match instead of guessing the spelling; the series picker is scoped to the matched universe (its existing series, or type a new name). Deep links resolve via `?universeId=…&seriesId=…` (with raw `universe`/`series` name params as a fallback), where a `seriesId` also pins its parent universe so the pair can't drift. The autocomplete itself is extracted into a shared `EntityCombobox` (the Universe creator's selector now wraps it). (`client/src/components/EntityCombobox.jsx`, `client/src/pages/Importer.jsx`, `client/src/pages/Pipeline.jsx`, `client/src/pages/PipelineSeries.jsx`, `client/src/pages/UniverseBuilder.jsx`)
+
- **Generate an author headshot from the persona's description + style** — The Authors editor's headshot field gains a **Generate** button alongside Upload and Choose from gallery: it folds the author's **physical description** (the subject) and **headshot style** (the art direction) into one portrait prompt and renders through the existing image-gen system, dropping the result straight into the headshot slot. The button stays disabled until at least one of those fields is filled. While a render is in flight the thumbnail shows the live diffusion preview and step percentage (async local/codex backends), and the Upload / gallery / URL controls lock so a manual choice can't be clobbered when the render lands; the synchronous external SD-API backend lands the image directly. Switching authors mid-render cancels the in-flight tracking so a completed (or still-pending) render can't write the wrong persona's headshot. (`client/src/pages/Authors.jsx`)
- **Author personas — manage reusable authors and pick one for a series** — Create gains an **Authors** page (`/authors`, reachable from the sidebar and ⌘K) for managing reusable author personas: each carries a **name**, **writing style**, **bio**, a **physical description** and a **headshot style** (the prompt inputs for generating a book-cover author headshot), plus an optional **headshot image** you can **upload** (a photo from your device), **choose from your image gallery** (the same searchable picker the image-gen page uses), or paste a URL into — with a live thumbnail preview and one-click clear. The Series Pipeline's author field — previously a free-text byline on both the create form and the series bible — is now an **author picker** that lists your personas: selecting one stores the persona link (`authorId`) **and** the denormalized byline string on the series, so covers and title screens still render the right name. Picking "— No author —" clears it; a legacy free-text byline with no linked persona is shown as a hint until you link one. Authors are stored in PostgreSQL (`authors` table, `db-primary`); they're local-only for now (a federated peer renders a synced series' byline from the string it carries) — cross-machine sync of the personas themselves is tracked as a follow-up. (`server/services/authors/`, `server/routes/authors.js`, `server/scripts/init-db.sql`, `server/lib/db.js`, `server/services/pipeline/series.js`, `client/src/pages/Authors.jsx`, `client/src/components/pipeline/AuthorPicker.jsx`, `client/src/services/apiAuthors.js`, `client/src/components/Layout.jsx`, `server/lib/navManifest.js`)
diff --git a/client/src/components/EntityCombobox.jsx b/client/src/components/EntityCombobox.jsx
new file mode 100644
index 0000000000..22313d9515
--- /dev/null
+++ b/client/src/components/EntityCombobox.jsx
@@ -0,0 +1,211 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Search, ChevronDown, Check, Plus, Loader2 } from 'lucide-react';
+import useClickOutside from '../hooks/useClickOutside';
+
+/**
+ * Generic autocomplete combobox: search a list of `{ id, name, subtitle? }`
+ * items or create a new one when the trimmed query doesn't exactly match an
+ * existing item. Extracted from UniverseBuilder's `UniverseSelector` so the
+ * Importer can reuse the same match-or-create UX for both universe and series
+ * selection.
+ *
+ * Behaviour preserved from the original:
+ * - When the input still mirrors the selected item's name (user opened the
+ * list on a selection), every item is shown instead of filtering down to the
+ * one we then exclude (`isBrowsing`).
+ * - The currently-selected item is excluded from the list — clicking it would
+ * be a no-op.
+ * - Keyboard nav: ArrowUp/Down move the active option, Enter picks/creates,
+ * Escape closes.
+ *
+ * The parent owns `value` (controlled input). `onPick` receives the full item;
+ * `onCreate` (optional) fires when the user commits a non-matching name.
+ */
+export default function EntityCombobox({
+ items,
+ selectedId,
+ value,
+ onChange,
+ onPick,
+ onCreate,
+ busy,
+ inputId,
+ noun = 'item',
+ placeholder,
+ createPrefix = 'Create',
+ emptyNoItems,
+ maxLength = 200,
+ className = 'flex-1 min-w-[200px]',
+}) {
+ const wrapRef = useRef(null);
+ const [open, setOpen] = useState(false);
+ const [activeIdx, setActiveIdx] = useState(0);
+ // Memoize the close callback so useClickOutside doesn't rebind its window
+ // listener on every render of the parent (which re-renders per keystroke).
+ const close = useCallback(() => setOpen(false), []);
+ useClickOutside(wrapRef, open, close);
+
+ const list = useMemo(() => (Array.isArray(items) ? items : []), [items]);
+ const trimmed = (value || '').trim();
+ const lower = trimmed.toLowerCase();
+
+ const listId = `${inputId}-listbox`;
+ const optionId = (id) => `${inputId}-option-${id}`;
+ const createOptionId = `${inputId}-option-create`;
+
+ // When the input still mirrors the selected item's name, the user is browsing
+ // the list (just clicked the chevron) rather than searching — show every item
+ // instead of filtering down to the one we then exclude.
+ const selectedName = list.find((u) => u.id === selectedId)?.name || '';
+ const isBrowsing = !!selectedId && lower === selectedName.trim().toLowerCase();
+
+ // Exclude current — clicking it would be a navigation no-op.
+ const filtered = useMemo(() => {
+ if (list.length === 0) return [];
+ return list
+ .filter((u) => u.id !== selectedId)
+ .filter((u) => isBrowsing || !lower || (u.name || '').toLowerCase().includes(lower))
+ .slice(0, 20);
+ }, [list, selectedId, lower, isBrowsing]);
+
+ // exactMatch still considers the current one so renaming-to-same doesn't
+ // surface a misleading Create option.
+ const exactMatch = useMemo(() => {
+ if (!trimmed) return false;
+ return list.some((u) => (u.name || '').trim().toLowerCase() === lower);
+ }, [list, trimmed, lower]);
+
+ const showCreateOption = !!onCreate && !!trimmed && !exactMatch;
+ const totalItems = filtered.length + (showCreateOption ? 1 : 0);
+
+ // Reset on result change to avoid stale Enter target.
+ useEffect(() => { setActiveIdx(0); }, [filtered.length, showCreateOption]);
+
+ const activeOptionId = open
+ ? (activeIdx < filtered.length
+ ? optionId(filtered[activeIdx]?.id)
+ : (showCreateOption ? createOptionId : undefined))
+ : undefined;
+
+ const handleKeyDown = (e) => {
+ if (!open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
+ setOpen(true);
+ e.preventDefault();
+ return;
+ }
+ if (!open) return;
+ if (e.key === 'Escape') { setOpen(false); e.preventDefault(); return; }
+ if (e.key === 'ArrowDown') {
+ setActiveIdx((i) => (totalItems ? Math.min(totalItems - 1, i + 1) : 0));
+ e.preventDefault();
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ setActiveIdx((i) => Math.max(0, i - 1));
+ e.preventDefault();
+ return;
+ }
+ if (e.key === 'Enter') {
+ if (activeIdx < filtered.length) {
+ const u = filtered[activeIdx];
+ if (u) { onPick(u); setOpen(false); }
+ e.preventDefault();
+ } else if (showCreateOption) {
+ onCreate();
+ setOpen(false);
+ e.preventDefault();
+ }
+ }
+ };
+
+ return (
+ <div ref={wrapRef} className={`relative ${className}`}>
+ <div className="relative">
+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
+ <input
+ id={inputId}
+ type="text"
+ value={value}
+ onChange={(e) => { onChange(e.target.value); setOpen(true); }}
+ onFocus={() => setOpen(true)}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder || `Search ${noun}s or type a new name…`}
+ className="w-full bg-port-bg border border-port-border rounded pl-8 pr-9 py-2 text-white focus:outline-none focus:border-port-accent"
+ maxLength={maxLength}
+ autoComplete="off"
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={open}
+ aria-controls={listId}
+ aria-activedescendant={activeOptionId}
+ />
+ <button
+ type="button"
+ onClick={() => setOpen((p) => !p)}
+ className="absolute right-1 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-white"
+ aria-label={open ? `Close ${noun} list` : `Open ${noun} list`}
+ tabIndex={-1}
+ >
+ <ChevronDown size={14} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+ </div>
+ {open && (
+ <ul
+ id={listId}
+ role="listbox"
+ className="absolute left-0 right-0 top-full mt-1 z-30 max-h-80 overflow-y-auto bg-port-card border border-port-border rounded shadow-lg"
+ >
+ {filtered.length === 0 && !showCreateOption && (
+ <li className="px-3 py-2 text-xs text-gray-500">
+ {list.length === 0
+ ? (emptyNoItems || `No ${noun}s yet — type a name.`)
+ : 'No matches'}
+ </li>
+ )}
+ {filtered.map((u, i) => (
+ <li key={u.id}>
+ <button
+ type="button"
+ id={optionId(u.id)}
+ role="option"
+ aria-selected={u.id === selectedId}
+ onClick={() => { onPick(u); setOpen(false); }}
+ onMouseEnter={() => setActiveIdx(i)}
+ className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 ${
+ i === activeIdx ? 'bg-port-bg text-white' : 'text-gray-300 hover:bg-port-bg'
+ }`}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="font-medium truncate">{u.name}</div>
+ {u.subtitle ? <div className="text-[11px] text-gray-500 truncate">{u.subtitle}</div> : null}
+ </div>
+ {u.id === selectedId && <Check size={14} className="text-port-accent" />}
+ </button>
+ </li>
+ ))}
+ {showCreateOption && (
+ <li>
+ <button
+ type="button"
+ id={createOptionId}
+ role="option"
+ aria-selected={false}
+ disabled={busy}
+ onClick={() => { onCreate(); setOpen(false); }}
+ onMouseEnter={() => setActiveIdx(filtered.length)}
+ className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 border-t border-port-border disabled:opacity-50 ${
+ activeIdx === filtered.length
+ ? 'bg-port-accent/20 text-port-accent'
+ : 'text-port-accent hover:bg-port-accent/15'
+ }`}
+ >
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}
+ {createPrefix} &ldquo;{trimmed}&rdquo;
+ </button>
+ </li>
+ )}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/EntityCombobox.test.jsx b/client/src/components/EntityCombobox.test.jsx
new file mode 100644
index 0000000000..eedf61c922
--- /dev/null
+++ b/client/src/components/EntityCombobox.test.jsx
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import EntityCombobox from './EntityCombobox';
+
+const items = [
+ { id: 'a', name: 'Cyberpunk 2099', subtitle: 'Neon rain' },
+ { id: 'b', name: 'Salt Run', subtitle: 'Foundry city' },
+ { id: 'c', name: 'Choir Awakens', subtitle: 'Empty cathedral' },
+];
+
+describe('EntityCombobox', () => {
+ it('lists every item (except the selected one) when opened on a selection', async () => {
+ const user = userEvent.setup();
+ render(
+ <EntityCombobox
+ items={items}
+ selectedId="a"
+ value="Cyberpunk 2099"
+ onChange={() => {}}
+ onPick={() => {}}
+ onCreate={() => {}}
+ inputId="test-universe"
+ noun="universe"
+ />
+ );
+ await user.click(screen.getByRole('button', { name: /Open universe list/i }));
+ const list = screen.getByRole('listbox');
+ expect(within(list).getByText('Salt Run')).toBeInTheDocument();
+ expect(within(list).getByText('Choir Awakens')).toBeInTheDocument();
+ // The selected item is excluded (clicking it would no-op).
+ expect(within(list).queryByText('Cyberpunk 2099')).toBeNull();
+ // Exact match on an existing name → no create row.
+ expect(within(list).queryByText(/New universe/i)).toBeNull();
+ });
+
+ it('calls onPick with the full item when an option is clicked', async () => {
+ const user = userEvent.setup();
+ const onPick = vi.fn();
+ render(
+ <EntityCombobox
+ items={items}
+ selectedId={null}
+ value=""
+ onChange={() => {}}
+ onPick={onPick}
+ onCreate={() => {}}
+ inputId="test-universe"
+ noun="universe"
+ />
+ );
+ await user.click(screen.getByRole('combobox'));
+ await user.click(screen.getByText('Salt Run'));
+ expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ id: 'b', name: 'Salt Run' }));
+ });
+
+ it('shows a create row with the custom prefix when the query has no exact match', async () => {
+ const user = userEvent.setup();
+ const onCreate = vi.fn();
+ render(
+ <EntityCombobox
+ items={items}
+ selectedId={null}
+ value="Brand New World"
+ onChange={() => {}}
+ onPick={() => {}}
+ onCreate={onCreate}
+ inputId="test-universe"
+ noun="universe"
+ createPrefix="New universe"
+ />
+ );
+ await user.click(screen.getByRole('combobox'));
+ const createBtn = screen.getByRole('option', { name: /New universe/i });
+ expect(createBtn).toHaveTextContent('Brand New World');
+ await user.click(createBtn);
+ expect(onCreate).toHaveBeenCalled();
+ });
+
+ it('omits the create row entirely when onCreate is not provided', async () => {
+ const user = userEvent.setup();
+ render(
+ <EntityCombobox
+ items={items}
+ selectedId={null}
+ value="Brand New World"
+ onChange={() => {}}
+ onPick={() => {}}
+ inputId="test-series"
+ noun="series"
+ />
+ );
+ await user.click(screen.getByRole('combobox'));
+ const list = screen.getByRole('listbox');
+ expect(within(list).getByText(/No matches/i)).toBeInTheDocument();
+ });
+
+ it('renders the custom empty hint when there are no items', async () => {
+ const user = userEvent.setup();
+ render(
+ <EntityCombobox
+ items={[]}
+ selectedId={null}
+ value=""
+ onChange={() => {}}
+ onPick={() => {}}
+ inputId="test-series"
+ noun="series"
+ emptyNoItems="Pick a universe above to list its series, or type a new name."
+ />
+ );
+ await user.click(screen.getByRole('combobox'));
+ expect(screen.getByText(/Pick a universe above to list its series/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d0330eb646..f267b9f43d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -48,6 +48,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageGenBackends.js` | `IMAGE_GEN_MODE` enum (local / codex / external) + metadata; `deriveAvailableBackends`; `I2I_CAPABLE_MODES` / `isI2iCapableMode(mode)` / `pickI2iMode(backends)` — image-to-image capability gating + best-backend selection. |
| `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. |
| `imageGenResolutions.js` | Shared resolution presets for image generation. |
+| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. |
| `videoGenResolutions.js` | Shared resolution presets for video generation (companion to image side; LTX-2 latent-friendly sizes). |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
diff --git a/client/src/lib/importerDeepLink.js b/client/src/lib/importerDeepLink.js
new file mode 100644
index 0000000000..d1314324dd
--- /dev/null
+++ b/client/src/lib/importerDeepLink.js
@@ -0,0 +1,48 @@
+// The Importer deep-link contract, both directions:
+// - `buildImporterLink` produces the `/importer?…` URL a Series Pipeline page
+// navigates to so the importer opens pre-targeted at a universe/series.
+// - `resolveImporterDeepLink` reads those params back into the universe +
+// series NAMES the importer matches on (it matches by name, not id).
+// Keeping both in one module means a param-name change touches a single file.
+
+// Build an `/importer` deep-link. An existing universe/series is referenced by
+// id; a not-yet-created series (e.g. a typed-but-unsaved name on the create
+// form) is passed by name. All parts are optional — with none, this is just
+// `/importer`.
+export function buildImporterLink({ universeId, seriesId, seriesName } = {}) {
+ const params = new URLSearchParams();
+ if (universeId) params.set('universeId', universeId);
+ if (seriesId) params.set('seriesId', seriesId);
+ if (seriesName && seriesName.trim()) params.set('series', seriesName.trim());
+ const qs = params.toString();
+ return qs ? `/importer?${qs}` : '/importer';
+}
+
+// Resolve a deep-link into the universe + series names the Importer matches on.
+// A Series Pipeline page links here with `?universeId=…&seriesId=…`; raw
+// `universe`/`series` name params are accepted as a fallback (e.g. an
+// in-progress create form that has a typed name but no id yet). Ids win over
+// names: a `seriesId` also pins its parent universe so the pair can't drift.
+// Returns the resolved names (each '' when nothing matched) — the caller only
+// overwrites intake fields that resolved to a non-empty value.
+export function resolveImporterDeepLink({
+ universeId, seriesId, universeName, seriesName, universes = [], series = [],
+}) {
+ let uName = '';
+ let sName = '';
+ if (seriesId) {
+ const s = series.find((x) => x.id === seriesId);
+ if (s) {
+ sName = s.name || '';
+ const u = universes.find((x) => x.id === s.universeId);
+ if (u) uName = u.name || '';
+ }
+ }
+ if (!uName && universeId) {
+ const u = universes.find((x) => x.id === universeId);
+ if (u) uName = u.name || '';
+ }
+ if (!uName && universeName) uName = universeName;
+ if (!sName && seriesName) sName = seriesName;
+ return { universeName: uName, seriesName: sName };
+}
diff --git a/client/src/lib/importerDeepLink.test.js b/client/src/lib/importerDeepLink.test.js
new file mode 100644
index 0000000000..ba96a2a9ac
--- /dev/null
+++ b/client/src/lib/importerDeepLink.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+import { buildImporterLink, resolveImporterDeepLink } from './importerDeepLink.js';
+
+describe('buildImporterLink', () => {
+ it('returns a bare /importer with no args', () => {
+ expect(buildImporterLink()).toBe('/importer');
+ expect(buildImporterLink({})).toBe('/importer');
+ });
+
+ it('encodes a universeId + seriesId pair (existing records)', () => {
+ expect(buildImporterLink({ universeId: 'u1', seriesId: 's1' }))
+ .toBe('/importer?universeId=u1&seriesId=s1');
+ });
+
+ it('passes a not-yet-created series by name and trims it', () => {
+ expect(buildImporterLink({ universeId: 'u1', seriesName: ' Salt Run ' }))
+ .toBe('/importer?universeId=u1&series=Salt+Run');
+ });
+
+ it('drops a whitespace-only series name', () => {
+ expect(buildImporterLink({ universeId: 'u1', seriesName: ' ' }))
+ .toBe('/importer?universeId=u1');
+ });
+});
+
+describe('resolveImporterDeepLink', () => {
+ const universes = [
+ { id: 'u1', name: 'Cyberpunk 2099' },
+ { id: 'u2', name: 'Salt Run' },
+ ];
+ const series = [
+ { id: 's1', name: 'The Choir Awakens', universeId: 'u1' },
+ { id: 's2', name: 'Foundry', universeId: 'u2' },
+ ];
+
+ it('resolves a seriesId to its name AND pins its parent universe', () => {
+ expect(resolveImporterDeepLink({ seriesId: 's1', universes, series })).toEqual({
+ universeName: 'Cyberpunk 2099',
+ seriesName: 'The Choir Awakens',
+ });
+ });
+
+ it('resolves a universeId on its own', () => {
+ expect(resolveImporterDeepLink({ universeId: 'u2', universes, series })).toEqual({
+ universeName: 'Salt Run',
+ seriesName: '',
+ });
+ });
+
+ it('lets a seriesId override a mismatched universeId so the pair cannot drift', () => {
+ // universeId points at u2 (Salt Run) but the series belongs to u1 — the
+ // series wins and pins Cyberpunk 2099.
+ expect(resolveImporterDeepLink({ universeId: 'u2', seriesId: 's1', universes, series })).toEqual({
+ universeName: 'Cyberpunk 2099',
+ seriesName: 'The Choir Awakens',
+ });
+ });
+
+ it('falls back to raw name params when ids do not match a record', () => {
+ expect(resolveImporterDeepLink({
+ universeId: 'missing', universeName: 'Brand New World', seriesName: 'Brand New Series',
+ universes, series,
+ })).toEqual({ universeName: 'Brand New World', seriesName: 'Brand New Series' });
+ });
+
+ it('returns empty names when nothing resolves', () => {
+ expect(resolveImporterDeepLink({ universes, series })).toEqual({ universeName: '', seriesName: '' });
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c22b0635d1..3e6500cbc2 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -21,6 +21,7 @@ export * from './imageCleaners.js';
export * from './imageGenBackends.js';
export * from './imageGenDefaults.js';
export * from './imageGenResolutions.js';
+export * from './importerDeepLink.js';
export * from './issueLength.js';
export * from './pipelineImageDefaults.js';
export * from './runnerFamilies.js';
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
index d343bb9b16..861ebf0043 100644
--- a/client/src/pages/Importer.jsx
+++ b/client/src/pages/Importer.jsx
@@ -1,14 +1,17 @@
import { memo, useEffect, useMemo, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useNavigate, useSearchParams } from 'react-router-dom';
import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle, ChevronDown, ChevronRight, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useImporterProgress, stageStatusIcon } from '../hooks/useImporterProgress';
import { STORY_SHAPES } from '../components/pipeline/StoryShapes';
import EntryCard from '../components/universe/EntryCard';
+import EntityCombobox from '../components/EntityCombobox';
import ProviderModelSelector from '../components/ProviderModelSelector';
import useProviderModels from '../hooks/useProviderModels';
import { previewCanonFragments } from '../lib/canonPrompt';
+import { resolveImporterDeepLink } from '../lib/importerDeepLink';
+import { listUniverses, listPipelineSeries } from '../services/api';
import {
analyzeImport,
classifyImport,
@@ -104,10 +107,90 @@ const emptyIntake = () => ({
export default function Importer() {
const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
const [phase, setPhase] = useState('intake'); // 'intake' | 'review'
const [intake, setIntake] = useState(emptyIntake);
const [preview, setPreview] = useState(null);
+ // Existing universes + series power the intake autocomplete: the importer
+ // matches the typed universe/series by name (case-insensitive), so surfacing
+ // the real records lets the user land an exact match instead of guessing the
+ // spelling. `listsLoaded` distinguishes "still fetching" from "fetched and
+ // legitimately empty" so the deep-link resolver doesn't wait forever on an
+ // install with no universes yet.
+ const [universes, setUniverses] = useState([]);
+ const [allSeries, setAllSeries] = useState([]);
+ const [listsLoaded, setListsLoaded] = useState(false);
+ useEffect(() => {
+ let canceled = false;
+ Promise.all([
+ listUniverses({ silent: true }).catch(() => []),
+ listPipelineSeries({ silent: true }).catch(() => []),
+ ]).then(([u, s]) => {
+ if (canceled) return;
+ setUniverses(Array.isArray(u) ? u : []);
+ setAllSeries(Array.isArray(s) ? s : []);
+ setListsLoaded(true);
+ });
+ return () => { canceled = true; };
+ }, []);
+
+ // Apply a `?universeId=…&seriesId=…` (or name-param) deep-link exactly once,
+ // after the lists load so ids can resolve to names. Guarded by a ref so a
+ // later list refresh or param change can't clobber what the user has since
+ // typed.
+ const deepLinkAppliedRef = useRef(false);
+ useEffect(() => {
+ if (deepLinkAppliedRef.current || !listsLoaded) return;
+ deepLinkAppliedRef.current = true;
+ const { universeName, seriesName } = resolveImporterDeepLink({
+ universeId: searchParams.get('universeId'),
+ seriesId: searchParams.get('seriesId'),
+ universeName: searchParams.get('universe'),
+ seriesName: searchParams.get('series'),
+ universes,
+ series: allSeries,
+ });
+ if (!universeName && !seriesName) return;
+ setIntake((prev) => ({
+ ...prev,
+ ...(universeName ? { universeName } : {}),
+ ...(seriesName ? { seriesName } : {}),
+ }));
+ }, [listsLoaded, searchParams, universes, allSeries]);
+
+ // The importer matches by name, so derive the matched universe straight from
+ // the typed name rather than tracking a separate "selected id" that could
+ // drift out of sync with the input. The matched id scopes the series
+ // autocomplete to that universe (series names are matched within a universe).
+ const universeMatch = useMemo(() => {
+ const lower = intake.universeName.trim().toLowerCase();
+ if (!lower) return null;
+ return universes.find((u) => (u.name || '').trim().toLowerCase() === lower) || null;
+ }, [universes, intake.universeName]);
+ const universeSeries = useMemo(
+ () => (universeMatch ? allSeries.filter((s) => s.universeId === universeMatch.id) : []),
+ [allSeries, universeMatch],
+ );
+ const seriesMatch = useMemo(() => {
+ const lower = intake.seriesName.trim().toLowerCase();
+ if (!lower) return null;
+ return universeSeries.find((s) => (s.name || '').trim().toLowerCase() === lower) || null;
+ }, [universeSeries, intake.seriesName]);
+
+ // Combobox option shapes. Memoized so a stable array identity reaches the
+ // child instead of a fresh `.map()` allocation on every keystroke-driven
+ // render. Universes prefer a logline subtitle, falling back to the starter
+ // prompt; series only carry a logline.
+ const universeItems = useMemo(
+ () => universes.map((u) => ({ id: u.id, name: u.name, subtitle: u.logline || u.starterPrompt || '' })),
+ [universes],
+ );
+ const seriesItems = useMemo(
+ () => universeSeries.map((s) => ({ id: s.id, name: s.name, subtitle: s.logline || '' })),
+ [universeSeries],
+ );
+
// Live analyze-phase stage progress, driven by `importer:progress` socket
// frames. `null` = no run started yet. See `useImporterProgress`.
const { stages: analyzeStages, reset: resetAnalyzeStages } = useImporterProgress();
@@ -395,6 +478,10 @@ export default function Importer() {
<IntakeForm
intake={intake}
setIntake={setIntake}
+ universeItems={universeItems}
+ universeSelectedId={universeMatch?.id || null}
+ seriesItems={seriesItems}
+ seriesSelectedId={seriesMatch?.id || null}
sourceCharLimit={config.sourceCharLimit}
analyzing={analyzing}
analyzeStages={analyzeStages}
@@ -444,13 +531,21 @@ export default function Importer() {
}
function IntakeForm({
- intake, setIntake, sourceCharLimit, analyzing, analyzeStages, onAnalyze, classifying, onClassify, classifyHint,
+ intake, setIntake,
+ universeItems, universeSelectedId, seriesItems, seriesSelectedId,
+ sourceCharLimit, analyzing, analyzeStages, onAnalyze, classifying, onClassify, classifyHint,
providers, llmProvider, llmModel, llmModels, onProviderChange, onModelChange,
}) {
const sourceLen = intake.source.length;
const sourceOver = sourceLen > sourceCharLimit;
const intakeValid = intake.universeName.trim() && intake.seriesName.trim() && intake.source.trim() && !sourceOver;
const canClassify = intake.source.trim().length > 0 && !sourceOver && !classifying && !analyzing;
+ // Unlike the Universe creator (which creates a record via its onCreate), the
+ // importer never eagerly creates — typing a non-matching name IS the create,
+ // and the server mints the universe/series on commit. Passing onCreate just
+ // surfaces the confirming "New … 'X'" row; committing it only needs to close
+ // the dropdown (EntityCombobox already does), so the handler is a no-op.
+ const confirmNewName = () => {};
return (
<form
className="space-y-4 bg-port-card border border-port-border rounded-lg p-4 sm:p-6"
@@ -466,31 +561,50 @@ function IntakeForm({
<label htmlFor="importer-universe-name" className="block text-sm font-medium mb-1">
Universe Name
</label>
- <input
- id="importer-universe-name"
- type="text"
+ <EntityCombobox
+ items={universeItems}
+ selectedId={universeSelectedId}
value={intake.universeName}
- onChange={(e) => setIntake({ ...intake, universeName: e.target.value })}
- placeholder="e.g. Cyberpunk 2099"
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
- maxLength={200}
+ onChange={(name) => setIntake({ ...intake, universeName: name })}
+ onPick={(item) => setIntake({ ...intake, universeName: item.name })}
+ onCreate={confirmNewName}
+ inputId="importer-universe-name"
+ noun="universe"
+ placeholder="Search universes or type a new name… e.g. Cyberpunk 2099"
+ createPrefix="New universe"
+ className="w-full"
/>
- <p className="text-xs text-port-text-muted mt-1">Existing universe is matched by name (case-insensitive); otherwise created fresh.</p>
+ <p className="text-xs text-port-text-muted mt-1">
+ {universeSelectedId
+ ? 'Matched an existing universe — the import is added to it.'
+ : 'Existing universe is matched by name (case-insensitive); otherwise created fresh on import.'}
+ </p>
</div>
<div>
<label htmlFor="importer-series-name" className="block text-sm font-medium mb-1">
Series Name
</label>
- <input
- id="importer-series-name"
- type="text"
+ <EntityCombobox
+ items={seriesItems}
+ selectedId={seriesSelectedId}
value={intake.seriesName}
- onChange={(e) => setIntake({ ...intake, seriesName: e.target.value })}
- placeholder="e.g. The Choir Awakens"
- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
- maxLength={200}
+ onChange={(name) => setIntake({ ...intake, seriesName: name })}
+ onPick={(item) => setIntake({ ...intake, seriesName: item.name })}
+ onCreate={confirmNewName}
+ inputId="importer-series-name"
+ noun="series"
+ placeholder="Search this universe's series or type a new name… e.g. The Choir Awakens"
+ createPrefix="New series"
+ emptyNoItems={intake.universeName.trim()
+ ? 'No series in this universe yet — type a name.'
+ : 'Pick a universe above to list its series, or type a new name.'}
+ className="w-full"
/>
- <p className="text-xs text-port-text-muted mt-1">Series match is scoped to the universe — same name in a different universe creates a fresh series.</p>
+ <p className="text-xs text-port-text-muted mt-1">
+ {seriesSelectedId
+ ? 'Matched an existing series — the import extends it.'
+ : 'Series match is scoped to the universe — same name in a different universe creates a fresh series.'}
+ </p>
</div>
</div>
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
index a5e7e8fd08..501931fc22 100644
--- a/client/src/pages/Pipeline.jsx
+++ b/client/src/pages/Pipeline.jsx
@@ -7,9 +7,9 @@
* drills into its detail page where issues are created and managed.
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
-import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2 } from 'lucide-react';
+import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput } from 'lucide-react';
import toast from '../components/ui/Toast';
import ShareToButton from '../components/sharing/ShareToButton';
import SyncToPeerButton from '../components/sharing/SyncToPeerButton';
@@ -28,6 +28,7 @@ import {
} from '../services/api';
import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from '../components/pipeline/StoryShapes';
import AuthorPicker from '../components/pipeline/AuthorPicker';
+import { buildImporterLink } from '../lib/importerDeepLink';
const emptyForm = () => ({
name: '',
@@ -137,6 +138,15 @@ export default function Pipeline() {
}
};
+ // Carry the in-progress create-form selection into the Importer deep-link:
+ // the universe by id (an existing record) and the typed series name (no id
+ // yet — it's being created). The importer resolves these into its match-or-
+ // create autocomplete so the user doesn't have to retype them.
+ const importerHref = useMemo(
+ () => buildImporterLink({ universeId: form.universeId, seriesName: form.name }),
+ [form.universeId, form.name],
+ );
+
// Two-click delete: first click "arms" the row, second click fires. Avoids
// window.confirm (banned per CLAUDE.md) without pulling in a modal for the
// skeleton. armedId resets on any other click.
@@ -162,14 +172,24 @@ export default function Pipeline() {
<WorkflowIcon className="w-6 h-6 text-port-accent" />
<h1 className="text-2xl font-bold text-white">Series Pipeline</h1>
</div>
- <button
- type="button"
- onClick={() => setShowForm((v) => !v)}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
- >
- <Plus size={16} aria-hidden="true" />
- New Series
- </button>
+ <div className="flex items-center gap-2">
+ <Link
+ to="/importer"
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-port-border text-gray-300 hover:text-white hover:border-port-accent/50 text-sm font-medium"
+ title="Reverse-engineer an existing manuscript, novel, screenplay, or comic script into a series"
+ >
+ <FileInput size={16} aria-hidden="true" />
+ Import
+ </Link>
+ <button
+ type="button"
+ onClick={() => setShowForm((v) => !v)}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
+ >
+ <Plus size={16} aria-hidden="true" />
+ New Series
+ </button>
+ </div>
</div>
<p className="text-sm text-gray-400 mb-6">
@@ -180,6 +200,19 @@ export default function Pipeline() {
{showForm && (
<form onSubmit={handleCreate} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg space-y-3">
+ <div className="flex items-start gap-2 text-xs text-gray-400 bg-port-bg border border-port-border rounded p-2.5">
+ <FileInput size={14} className="mt-0.5 flex-shrink-0 text-port-accent" aria-hidden="true" />
+ <span>
+ Already have a manuscript, novel, screenplay, or comic script?{' '}
+ <Link to={importerHref} className="text-port-accent hover:underline">
+ Import it instead
+ </Link>{' '}
+ — the importer extracts canon, the arc, and an issue split for you.
+ {(form.universeId || form.name.trim())
+ ? ' Your current universe / series selection carries over.'
+ : ''}
+ </span>
+ </div>
<div className="grid grid-cols-1 sm:grid-cols-[1fr_240px] gap-3">
<div>
<label htmlFor="series-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index d536440d5d..97e671f42c 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -14,7 +14,7 @@ import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,
- PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen,
+ PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import ArcCanvas from '../components/pipeline/ArcCanvas';
@@ -28,6 +28,7 @@ import {
SERIES_TITLE_LOGO_MAX,
} from '../services/api';
import AuthorPicker from '../components/pipeline/AuthorPicker';
+import { buildImporterLink } from '../lib/importerDeepLink';
import { recommendStructure, describeStructure } from '../lib/seasonStructure';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
@@ -186,6 +187,13 @@ export default function PipelineSeries() {
>
<BookOpen size={12} /> Manuscript
</Link>
+ <Link
+ to={buildImporterLink({ universeId: series.universeId, seriesId: series.id })}
+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Import an existing manuscript, novel, screenplay, or comic script into this series"
+ >
+ <FileInput size={12} /> Import
+ </Link>
<button
type="button"
onClick={handleSave}
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index eb328c79fb..864321e8ff 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -12,7 +12,7 @@ import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom'
import {
Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
- ArrowUpCircle, ArrowLeft, Search, ChevronDown, Check,
+ ArrowUpCircle, ArrowLeft,
BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree,
} from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -26,6 +26,7 @@ import {
listImageModels, listLorasFull, getSettings,
} from '../services/api';
import useClickOutside from '../hooks/useClickOutside';
+import EntityCombobox from '../components/EntityCombobox';
import { useLocalStoragePersisted } from '../hooks/useLocalStorageBool';
import useUniverseAction from '../hooks/useUniverseAction';
import { useUniverseNav } from '../hooks/useUniverseNav';
@@ -296,175 +297,34 @@ function StyleNegativePromptEditor({ influences, onChange, locked, onToggleLock
// Universe autocomplete combobox: search existing universes or create one when
// the trimmed query doesn't exactly match any. `onCreate` is wired to a
// dedicated create path (not handleSave) so typing a new name while an existing
-// universe is selected never accidentally renames it.
-const LIST_ID = 'universe-selector-list';
-const OPTION_ID_PREFIX = 'universe-option-';
-const CREATE_OPTION_ID = 'universe-option-create';
-
+// universe is selected never accidentally renames it. The match-or-create UX
+// lives in the shared `EntityCombobox`; this thin wrapper maps universes into
+// its `{ id, name, subtitle }` item shape and preserves the universe-specific
+// labels/ids.
export function UniverseSelector({ universes, selectedId, value, onChange, onPick, onCreate, busy }) {
- const wrapRef = useRef(null);
- const [open, setOpen] = useState(false);
- const [activeIdx, setActiveIdx] = useState(0);
- // Memoize the close callback so useClickOutside doesn't rebind its window
- // listener on every render of the parent (which re-renders per keystroke).
- const close = useCallback(() => setOpen(false), []);
- useClickOutside(wrapRef, open, close);
-
- const trimmed = (value || '').trim();
- const lower = trimmed.toLowerCase();
-
- // When the input still mirrors the selected universe's name, the user is
- // browsing the list (just clicked the chevron) rather than searching — show
- // every universe instead of filtering down to the one we then exclude.
- const selectedName = (universes || []).find((u) => u.id === selectedId)?.name || '';
- const isBrowsing = !!selectedId && lower === selectedName.trim().toLowerCase();
-
- // Exclude current — clicking it would be a navigation no-op.
- const filtered = useMemo(() => {
- if (!Array.isArray(universes) || universes.length === 0) return [];
- return universes
- .filter((u) => u.id !== selectedId)
- .filter((u) => isBrowsing || !lower || (u.name || '').toLowerCase().includes(lower))
- .slice(0, 20);
- }, [universes, selectedId, lower, isBrowsing]);
-
- // exactMatch still considers the current one so renaming-to-same doesn't
- // surface a misleading Create option.
- const exactMatch = useMemo(() => {
- if (!trimmed) return false;
- return (universes || []).some((u) => (u.name || '').trim().toLowerCase() === lower);
- }, [universes, trimmed, lower]);
-
- const showCreateOption = !!trimmed && !exactMatch;
- const totalItems = filtered.length + (showCreateOption ? 1 : 0);
-
- // Reset on result change to avoid stale Enter target.
- useEffect(() => { setActiveIdx(0); }, [filtered.length, showCreateOption]);
-
- const activeOptionId = open
- ? (activeIdx < filtered.length
- ? `${OPTION_ID_PREFIX}${filtered[activeIdx]?.id}`
- : (showCreateOption ? CREATE_OPTION_ID : undefined))
- : undefined;
-
- const handleKeyDown = (e) => {
- if (!open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
- setOpen(true);
- e.preventDefault();
- return;
- }
- if (!open) return;
- if (e.key === 'Escape') { setOpen(false); e.preventDefault(); return; }
- if (e.key === 'ArrowDown') {
- setActiveIdx((i) => (totalItems ? Math.min(totalItems - 1, i + 1) : 0));
- e.preventDefault();
- return;
- }
- if (e.key === 'ArrowUp') {
- setActiveIdx((i) => Math.max(0, i - 1));
- e.preventDefault();
- return;
- }
- if (e.key === 'Enter') {
- if (activeIdx < filtered.length) {
- const u = filtered[activeIdx];
- if (u) { onPick(u.id); setOpen(false); }
- e.preventDefault();
- } else if (showCreateOption) {
- onCreate();
- setOpen(false);
- e.preventDefault();
- }
- }
- };
-
+ const items = useMemo(
+ () => (Array.isArray(universes) ? universes : []).map((u) => ({
+ id: u.id,
+ name: u.name,
+ subtitle: u.starterPrompt || 'No starter prompt',
+ })),
+ [universes],
+ );
return (
- <div ref={wrapRef} className="relative flex-1 min-w-[200px]">
- <div className="relative">
- <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
- <input
- id="universe-name"
- type="text"
- value={value}
- onChange={(e) => { onChange(e.target.value); setOpen(true); }}
- onFocus={() => setOpen(true)}
- onKeyDown={handleKeyDown}
- placeholder="Search universes or type a new name…"
- className="w-full bg-port-bg border border-port-border rounded pl-8 pr-9 py-2 text-white focus:outline-none focus:border-port-accent"
- maxLength={100}
- autoComplete="off"
- role="combobox"
- aria-autocomplete="list"
- aria-expanded={open}
- aria-controls={LIST_ID}
- aria-activedescendant={activeOptionId}
- />
- <button
- type="button"
- onClick={() => setOpen((p) => !p)}
- className="absolute right-1 top-1/2 -translate-y-1/2 p-1 text-gray-500 hover:text-white"
- aria-label={open ? 'Close universe list' : 'Open universe list'}
- tabIndex={-1}
- >
- <ChevronDown size={14} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
- </button>
- </div>
- {open && (
- <ul
- id={LIST_ID}
- role="listbox"
- className="absolute left-0 right-0 top-full mt-1 z-30 max-h-80 overflow-y-auto bg-port-card border border-port-border rounded shadow-lg"
- >
- {filtered.length === 0 && !showCreateOption && (
- <li className="px-3 py-2 text-xs text-gray-500">
- {(universes?.length || 0) === 0 ? 'No universes yet — type a name and Create.' : 'No matches'}
- </li>
- )}
- {filtered.map((u, i) => (
- <li key={u.id}>
- <button
- type="button"
- id={`${OPTION_ID_PREFIX}${u.id}`}
- role="option"
- aria-selected={u.id === selectedId}
- onClick={() => { onPick(u.id); setOpen(false); }}
- onMouseEnter={() => setActiveIdx(i)}
- className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 ${
- i === activeIdx ? 'bg-port-bg text-white' : 'text-gray-300 hover:bg-port-bg'
- }`}
- >
- <div className="min-w-0 flex-1">
- <div className="font-medium truncate">{u.name}</div>
- <div className="text-[11px] text-gray-500 truncate">{u.starterPrompt || 'No starter prompt'}</div>
- </div>
- {u.id === selectedId && <Check size={14} className="text-port-accent" />}
- </button>
- </li>
- ))}
- {showCreateOption && (
- <li>
- <button
- type="button"
- id={CREATE_OPTION_ID}
- role="option"
- aria-selected={false}
- disabled={busy}
- onClick={() => { onCreate(); setOpen(false); }}
- onMouseEnter={() => setActiveIdx(filtered.length)}
- className={`w-full text-left px-3 py-2 text-sm flex items-center gap-2 border-t border-port-border disabled:opacity-50 ${
- activeIdx === filtered.length
- ? 'bg-port-accent/20 text-port-accent'
- : 'text-port-accent hover:bg-port-accent/15'
- }`}
- >
- {busy ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}
- Create &ldquo;{trimmed}&rdquo;
- </button>
- </li>
- )}
- </ul>
- )}
- </div>
+ <EntityCombobox
+ items={items}
+ selectedId={selectedId}
+ value={value}
+ onChange={onChange}
+ onPick={(item) => onPick(item.id)}
+ onCreate={onCreate}
+ busy={busy}
+ inputId="universe-name"
+ noun="universe"
+ placeholder="Search universes or type a new name…"
+ emptyNoItems="No universes yet — type a name and Create."
+ maxLength={100}
+ />
);
}