Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: cursor pagination for YouTube ingest history (#8267)

[._.]/ Adam Eivy8c9857088bc9
diff --git a/client/src/components/brain/YoutubeIngestSettings.jsx b/client/src/components/brain/YoutubeIngestSettings.jsx
index 69955ea712..be01fae1ea 100644
--- a/client/src/components/brain/YoutubeIngestSettings.jsx
+++ b/client/src/components/brain/YoutubeIngestSettings.jsx
@@ -1,12 +1,15 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { Film, Save, Trash2 } from 'lucide-react';
import * as api from '../../services/api';
import { INGEST_OPTIONS } from '../../lib/youtubeUrl';
import { formatDurationMs, timeAgo } from '../../utils/formatters';
import BrailleSpinner from '../BrailleSpinner';
+import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
+import { usePagedCollection } from '../../hooks/usePagedCollection';
import toast from '../ui/Toast';
const PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
+const INGESTS_PAGE_SIZE = 50;
/**
* Settings for the YouTube → Brain ingest, plus the list of what has been
@@ -23,7 +26,6 @@ export default function YoutubeIngestSettings() {
const [saving, setSaving] = useState(false);
const [vaults, setVaults] = useState([]);
const [settings, setSettings] = useState(null);
- const [ingests, setIngests] = useState([]);
// Two-click arm rather than a confirm dialog, per the client UI conventions.
const [armedDelete, setArmedDelete] = useState(null);
@@ -31,15 +33,26 @@ export default function YoutubeIngestSettings() {
Promise.all([
api.getYoutubeIngestSettings({ silent: true }).catch(() => null),
api.getNotesVaults().catch(() => ({ vaults: [] })),
- api.getYoutubeIngests({ silent: true }).catch(() => ({ ingests: [] })),
- ]).then(([loaded, vaultData, ingestData]) => {
+ ]).then(([loaded, vaultData]) => {
setSettings(loaded);
setVaults(vaultData?.vaults || []);
- setIngests(ingestData?.ingests || []);
setLoading(false);
});
}, []);
+ // Loads 50 records at a time; `usePagedCollection` dedupes by `id`, so each
+ // record is given one from its `videoId` (the ingest index's own key).
+ const fetchIngestsPage = useCallback(async ({ cursor, signal }) => {
+ const res = await api.getYoutubeIngests({ limit: INGESTS_PAGE_SIZE, cursor, silent: true, signal })
+ .catch(() => ({ ingests: [] }));
+ return {
+ items: (res.ingests || []).map((record) => ({ ...record, id: record.videoId })),
+ nextCursor: res.nextCursor ?? null,
+ };
+ }, []);
+ const ingestsPage = usePagedCollection(fetchIngestsPage);
+ const ingests = ingestsPage.items;
+
const handleForget = async (videoId) => {
if (armedDelete !== videoId) {
setArmedDelete(videoId);
@@ -51,7 +64,7 @@ export default function YoutubeIngestSettings() {
return null;
});
if (!ok) return;
- setIngests((prev) => prev.filter((i) => i.videoId !== videoId));
+ ingestsPage.setItems((prev) => prev.filter((i) => i.videoId !== videoId));
toast.success('Ingest removed — the link, video and timeline entry were kept');
};
@@ -190,47 +203,57 @@ export default function YoutubeIngestSettings() {
{saving ? 'Saving…' : 'Save YouTube Settings'}
</button>
- {ingests.length > 0 && (
+ {(ingests.length > 0 || ingestsPage.loading) && (
<div className="pt-4 border-t border-port-border">
- <h4 className="text-sm font-medium text-gray-400 mb-2">Ingested ({ingests.length})</h4>
- <ul className="space-y-1 max-h-64 overflow-y-auto">
- {ingests.map((ingest) => (
- <li key={ingest.videoId} className="flex items-center gap-2 py-1.5 text-sm">
- <div className="min-w-0 flex-1">
- <a
- href={ingest.url}
- target="_blank"
- rel="noreferrer"
- className="block truncate text-gray-200 hover:text-port-accent transition-colors"
+ <h4 className="text-sm font-medium text-gray-400 mb-2">
+ Ingested ({ingests.length}{ingestsPage.hasMore ? '+' : ''})
+ </h4>
+ <div className="max-h-64 overflow-y-auto">
+ <ul className="space-y-1">
+ {ingests.map((ingest) => (
+ <li key={ingest.videoId} className="flex items-center gap-2 py-1.5 text-sm">
+ <div className="min-w-0 flex-1">
+ <a
+ href={ingest.url}
+ target="_blank"
+ rel="noreferrer"
+ className="block truncate text-gray-200 hover:text-port-accent transition-colors"
+ >
+ {ingest.title || ingest.videoId}
+ </a>
+ <p className="text-xs text-gray-500 truncate">
+ {[
+ ingest.channel,
+ ingest.durationSec ? formatDurationMs(ingest.durationSec * 1000) : null,
+ ingest.transcript ? `${Math.round(ingest.transcript.chars / 1000)}k transcript` : 'no transcript',
+ ingest.audio ? 'audio' : null,
+ ingest.video ? 'video' : null,
+ ingest.ingestedAt ? timeAgo(ingest.ingestedAt) : null,
+ ].filter(Boolean).join(' · ')}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => handleForget(ingest.videoId)}
+ onBlur={() => setArmedDelete((v) => (v === ingest.videoId ? null : v))}
+ aria-label={`Forget ingest: ${ingest.title || ingest.videoId}`}
+ title="Removes the stored transcript, audio and Obsidian note. The link, downloaded video and timeline entry are kept."
+ className={`flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg transition-colors ${armedDelete === ingest.videoId
+ ? 'text-red-300 bg-red-500/20'
+ : 'text-gray-500 hover:text-red-400'}`}
>
- {ingest.title || ingest.videoId}
- </a>
- <p className="text-xs text-gray-500 truncate">
- {[
- ingest.channel,
- ingest.durationSec ? formatDurationMs(ingest.durationSec * 1000) : null,
- ingest.transcript ? `${Math.round(ingest.transcript.chars / 1000)}k transcript` : 'no transcript',
- ingest.audio ? 'audio' : null,
- ingest.video ? 'video' : null,
- ingest.ingestedAt ? timeAgo(ingest.ingestedAt) : null,
- ].filter(Boolean).join(' · ')}
- </p>
- </div>
- <button
- type="button"
- onClick={() => handleForget(ingest.videoId)}
- onBlur={() => setArmedDelete((v) => (v === ingest.videoId ? null : v))}
- aria-label={`Forget ingest: ${ingest.title || ingest.videoId}`}
- title="Removes the stored transcript, audio and Obsidian note. The link, downloaded video and timeline entry are kept."
- className={`flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg transition-colors ${armedDelete === ingest.videoId
- ? 'text-red-300 bg-red-500/20'
- : 'text-gray-500 hover:text-red-400'}`}
- >
- {armedDelete === ingest.videoId ? <span className="text-xs px-1">Sure?</span> : <Trash2 size={14} />}
- </button>
- </li>
- ))}
- </ul>
+ {armedDelete === ingest.videoId ? <span className="text-xs px-1">Sure?</span> : <Trash2 size={14} />}
+ </button>
+ </li>
+ ))}
+ </ul>
+ <InfiniteScrollFooter
+ hasMore={ingestsPage.hasMore}
+ loading={ingestsPage.loading}
+ error={ingestsPage.error}
+ onLoadMore={ingestsPage.loadMore}
+ />
+ </div>
</div>
)}
</section>
diff --git a/client/src/components/brain/YoutubeIngestSettings.test.jsx b/client/src/components/brain/YoutubeIngestSettings.test.jsx
new file mode 100644
index 0000000000..feacc3cb43
--- /dev/null
+++ b/client/src/components/brain/YoutubeIngestSettings.test.jsx
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ getYoutubeIngestSettings: vi.fn(),
+ getNotesVaults: vi.fn(),
+ getYoutubeIngests: vi.fn(),
+ deleteYoutubeIngest: vi.fn(),
+ updateYoutubeIngestSettings: vi.fn(),
+}));
+
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
+}));
+
+import YoutubeIngestSettings from './YoutubeIngestSettings';
+
+const SETTINGS = { obsidianVaultId: null, obsidianFolder: '', autoSync: false, taskPriority: 'MEDIUM' };
+
+const ingest = (videoId, ingestedAt) => ({ videoId, ingestedAt, title: `Video ${videoId}`, url: `https://youtu.be/${videoId}` });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getYoutubeIngestSettings.mockResolvedValue(SETTINGS);
+ api.getNotesVaults.mockResolvedValue({ vaults: [] });
+});
+
+describe('YoutubeIngestSettings ingest history pagination (#8267)', () => {
+ it('requests the first page at 50 and renders it without a Load more affordance when nothing else remains', async () => {
+ api.getYoutubeIngests.mockResolvedValue({ ingests: [ingest('v1', '2026-01-02T00:00:00.000Z')] });
+
+ render(<YoutubeIngestSettings />);
+
+ await waitFor(() => expect(screen.getByText('Video v1')).toBeInTheDocument());
+
+ expect(api.getYoutubeIngests).toHaveBeenCalledWith(expect.objectContaining({ limit: 50, cursor: null }));
+ expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument();
+ });
+
+ it('appends the next page and forwards the prior nextCursor when Load more is clicked', async () => {
+ api.getYoutubeIngests
+ .mockResolvedValueOnce({ ingests: [ingest('v1', '2026-01-02T00:00:00.000Z')], nextCursor: 'opaque-token' })
+ .mockResolvedValueOnce({ ingests: [ingest('v2', '2026-01-01T00:00:00.000Z')], nextCursor: null });
+
+ render(<YoutubeIngestSettings />);
+ await waitFor(() => expect(screen.getByText('Video v1')).toBeInTheDocument());
+
+ const loadMore = await screen.findByRole('button', { name: /load more/i });
+ fireEvent.click(loadMore);
+
+ await waitFor(() => expect(screen.getByText('Video v2')).toBeInTheDocument());
+ expect(api.getYoutubeIngests).toHaveBeenLastCalledWith(expect.objectContaining({ limit: 50, cursor: 'opaque-token' }));
+ // Both pages stay visible — appended, not replaced.
+ expect(screen.getByText('Video v1')).toBeInTheDocument();
+ });
+
+ it('removes a forgotten ingest from the loaded page without refetching', async () => {
+ api.getYoutubeIngests.mockResolvedValue({ ingests: [ingest('v1', '2026-01-02T00:00:00.000Z')] });
+ api.deleteYoutubeIngest.mockResolvedValue({ message: 'Ingest removed' });
+
+ render(<YoutubeIngestSettings />);
+ await waitFor(() => expect(screen.getByText('Video v1')).toBeInTheDocument());
+
+ const forgetButton = screen.getByRole('button', { name: /forget ingest: video v1/i });
+ fireEvent.click(forgetButton); // arm
+ fireEvent.click(forgetButton); // confirm
+
+ await waitFor(() => expect(screen.queryByText('Video v1')).not.toBeInTheDocument());
+ expect(api.deleteYoutubeIngest).toHaveBeenCalledWith('v1', expect.objectContaining({ silent: true }));
+ expect(api.getYoutubeIngests).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index ab1be85a2f..624fe32c67 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -440,7 +440,15 @@ export const cancelYoutubeIngest = (jobId, options = {}) => request(
`/brain/youtube/ingest/${encodeURIComponent(jobId)}/cancel`,
{ method: 'POST', ...options }
);
-export const getYoutubeIngests = (options = {}) => request('/brain/youtube/ingests', options);
+// `limit`/`cursor` opt into a bounded page (echo `nextCursor` from the
+// previous response); a query-less call keeps the legacy full-history array.
+export const getYoutubeIngests = ({ limit, cursor, ...options } = {}) => {
+ const params = new URLSearchParams();
+ if (limit !== undefined && limit !== null) params.set('limit', limit);
+ if (cursor) params.set('cursor', cursor);
+ const qs = params.toString();
+ return request(`/brain/youtube/ingests${qs ? `?${qs}` : ''}`, options);
+};
export const deleteYoutubeIngest = (videoId, options = {}) => request(
`/brain/youtube/ingests/${encodeURIComponent(videoId)}`,
{ method: 'DELETE', ...options }
diff --git a/server/lib/README.md b/server/lib/README.md
index 141293b505..ba2a2ed428 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -414,7 +414,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ptySpawnDiagnostics.js` | `diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe})` + `probePtyRuntime(pty, cwd)` and the `PTY_UNAVAILABLE_PREFIX` / `PTY_WORKSPACE_MISSING_PREFIX` markers — turns node-pty’s one opaque `posix_spawn failed: No such file or directory` into a named fault. The executable is already cleared upstream (PATH resolve + `--version` probe), so a throw is either a `cwd` that vanished (cheap `existsSync`) or a PTY layer that cannot fork AT ALL — proven by re-forking a known-good command in a known-good directory; `diagnosed: false` means neither matched, and the caller re-throws rather than inventing a cause. **Retry policy is the caller’s and the two faults differ:** `agentTuiSpawning.js` matches only the PTY-layer prefix, mapping it to the actionable `runner-pty-unavailable` so the task blocks once with the repair, while a reaped workspace falls through to the retrying `spawn-rejected` because the next attempt provisions a fresh worktree. The motivating outage: an `npm ci` inside a CoS worktree emptied the primary checkout’s `server/node_modules` through a symlink, deleting the `spawn-helper` binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
| `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. |
-| `youtubeIngestFormat.js` | Pure data transformations for the brain's YouTube ingest (#6015): `parseVideoMetadata(json)` (yt-dlp `--dump-single-json` → the stored metadata shape, incl. the `subtitles`-vs-`automatic_captions` manual-caption signal), `buildIngestNote({meta,url,transcript,tags,agentPrompt,capturedAt})` (the Obsidian note, whose YAML frontmatter the user's own vault queries key on — every interpolated scalar goes through `yamlString`), `buildAgentTaskContext(...)` (the CoS follow-up prompt, including the untrusted-transcript boundary notice), `resolveObsidianPointer({written,vaultId,notePath,prior})` (keeps the prior note pointer when an ATTEMPTED mirror failed, so an evicted note can't be orphaned — #3706), plus `sanitizeFilename`, `formatDuration` (seconds → `h:mm:ss`) and `yamlString`. No fs/db/childProcess/SSE imports; orchestration and storage stay in `services/youtubeIngest.js`. Surfaced through the barrel as a NAMESPACE export (`youtubeIngestFormat.*`) because `formatDuration` collides with `fileCore.js` and `sanitizeFilename` with `mimeTypes.js`. |
+| `youtubeIngestFormat.js` | Pure data transformations for the brain's YouTube ingest (#6015): `parseVideoMetadata(json)` (yt-dlp `--dump-single-json` → the stored metadata shape, incl. the `subtitles`-vs-`automatic_captions` manual-caption signal), `buildIngestNote({meta,url,transcript,tags,agentPrompt,capturedAt})` (the Obsidian note, whose YAML frontmatter the user's own vault queries key on — every interpolated scalar goes through `yamlString`), `buildAgentTaskContext(...)` (the CoS follow-up prompt, including the untrusted-transcript boundary notice), `resolveObsidianPointer({written,vaultId,notePath,prior})` (keeps the prior note pointer when an ATTEMPTED mirror failed, so an evicted note can't be orphaned — #3706), plus `sanitizeFilename`, `formatDuration` (seconds → `h:mm:ss`) and `yamlString`; and the ingest-history cursor pagination (#8267): `compareIngestsDesc(a,b)` (newest-first order, `ingestedAt` desc with `videoId` desc as a deterministic tie-breaker), `encodeIngestCursor(record)`/`decodeIngestCursor(cursor)` (opaque base64url sort-key token; decode returns `null` rather than throwing on anything malformed), and `paginateIngests(sorted, {limit, cursor})` (slices a page starting strictly after the decoded cursor, so records added/removed elsewhere in the index between pages can't repeat or skip a row). No fs/db/childProcess/SSE imports; orchestration and storage stay in `services/youtubeIngest.js`. Surfaced through the barrel as a NAMESPACE export (`youtubeIngestFormat.*`) because `formatDuration` collides with `fileCore.js` and `sanitizeFilename` with `mimeTypes.js`. |
| `youtubeUrl.js` | Canonical YouTube single-video URL rule (#6014). `YOUTUBE_VIDEO_URL_RE` (accepts `watch`/`shorts`/`live`/`embed` plus the `www.`/`m.`/`music.` hosts, rejects playlists, channels, and `/@handle` feeds), `youtubeVideoIdFromUrl(url)` (alias `youtubeVideoId`), `isYoutubeVideoUrl(url)`, and the shared `YOUTUBE_URL_INVALID_MESSAGE`. Single source for the brain ingest, the Takeout importer, the history scrape, the Music Video track import, and (by re-export) `client/src/lib/youtubeUrl.js`. A pure leaf — the throwing form lives in `youtubeUrlAssert.js`, so importing this can never drag `errorHandler.js` into the browser bundle. |
| `youtubeUrlAssert.js` | `assertYoutubeVideoUrl(url)` — the throwing form of the `youtubeUrl.js` rule: returns the video id, else throws 400 `YOUTUBE_URL_INVALID`. Separate because it needs `ServerError` (and so Node's `events`), which must stay out of the pure leaf the client re-exports. |
| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. `resetYtDlpCache()` drops that cache after an in-place update or a fresh install, so neither needs a server restart to take effect. |
diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.js
index 381faeba6f..0dc859138d 100644
--- a/server/lib/apiOperationContracts.js
+++ b/server/lib/apiOperationContracts.js
@@ -75,6 +75,20 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
},
},
},
+ '/api/brain/youtube/ingests': {
+ get: {
+ summary: 'List YouTube ingest history',
+ description: 'No query returns the legacy { ingests } array of every stored ingest. Passing limit opts into a page ordered by ingestedAt desc (videoId as a deterministic tie-breaker); echo nextCursor from the previous response to continue.',
+ parameters: [
+ { name: 'limit', in: 'query', required: false, schema: { type: 'integer', minimum: 1, maximum: 100 } },
+ { name: 'cursor', in: 'query', required: false, schema: { type: 'string', maxLength: 4096 } },
+ ],
+ responses: {
+ 200: { description: 'Legacy full ingest array, or a bounded page with an optional nextCursor' },
+ 400: { description: 'Invalid query or cursor', 'x-portos-error-codes': ['VALIDATION_ERROR', 'INVALID_CURSOR'] },
+ },
+ },
+ },
'/api/agent-context/manifest': {
get: { summary: 'Read local Agent Tools MCP manifest', responses: { 200: { description: 'MCP transport, context scopes, semantic grants, schemas, and limits' } } },
},
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 91818f612e..b8857e80e8 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -931,6 +931,15 @@ export const youtubeIngestSchema = repoIntakeSchema.pick({ targetAppId: true, pr
priority: z.enum(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']).optional()
});
+// GET /api/brain/youtube/ingests — query-less callers keep the legacy
+// `{ ingests }` full-history array. Passing `limit` opts into a page ordered
+// by `ingestedAt` desc with `videoId` as a deterministic tie-breaker (#8267);
+// `cursor` is the opaque key of the last record on the prior page.
+export const youtubeIngestsQuerySchema = z.object({
+ limit: z.preprocess((v) => (v === undefined || v === '' ? undefined : Number(v)), z.number().int().min(1).max(100).optional()),
+ cursor: z.preprocess((v) => (v === undefined || v === '' ? undefined : v), z.string().trim().min(1).max(4096).optional()),
+}).strict();
+
// PUT /api/brain/youtube/settings. strict() rejects unknown keys so a typo
// can't quietly accumulate in the settings file.
export const youtubeIngestSettingsSchema = z.object({
diff --git a/server/lib/youtubeIngestFormat.js b/server/lib/youtubeIngestFormat.js
index 535a4c30a7..2f94fcd464 100644
--- a/server/lib/youtubeIngestFormat.js
+++ b/server/lib/youtubeIngestFormat.js
@@ -180,3 +180,62 @@ export function buildAgentTaskContext({ meta, url, agentPrompt, transcriptPath,
'If the content does not actually support the request, say so plainly rather than inventing findings.',
].join('\n');
}
+
+// =============================================================================
+// INGEST HISTORY CURSOR PAGINATION (#8267)
+// =============================================================================
+
+const INGEST_CURSOR_VERSION = 1;
+
+/**
+ * Deterministic newest-first order for ingest records: `ingestedAt` descending
+ * with `videoId` descending as an explicit tie-breaker, so two records ingested
+ * in the same instant still have a stable relative order and cursor
+ * continuation neither repeats nor skips one of them.
+ */
+export function compareIngestsDesc(a, b) {
+ const byDate = String(b?.ingestedAt || '').localeCompare(String(a?.ingestedAt || ''));
+ if (byDate !== 0) return byDate;
+ return String(b?.videoId || '').localeCompare(String(a?.videoId || ''));
+}
+
+/** Opaque continuation token: the sort key of the last record on a page. */
+export function encodeIngestCursor(record) {
+ const payload = JSON.stringify({ v: INGEST_CURSOR_VERSION, ingestedAt: record.ingestedAt, videoId: record.videoId });
+ return Buffer.from(payload, 'utf8').toString('base64url');
+}
+
+/**
+ * Decode a cursor produced by `encodeIngestCursor`. Returns null (never
+ * throws) on anything malformed, so the route can turn it into one
+ * consistent 400 rather than leaking a JSON/base64 parse error.
+ */
+export function decodeIngestCursor(cursor) {
+ let payload;
+ try {
+ payload = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
+ } catch {
+ return null;
+ }
+ if (!payload || payload.v !== INGEST_CURSOR_VERSION
+ || typeof payload.ingestedAt !== 'string' || !payload.ingestedAt
+ || typeof payload.videoId !== 'string' || !payload.videoId) {
+ return null;
+ }
+ return { ingestedAt: payload.ingestedAt, videoId: payload.videoId };
+}
+
+/**
+ * Page an already-`compareIngestsDesc`-sorted ingest list. `cursor` (if given)
+ * is the decoded sort key of the last record already delivered; the page
+ * begins at the first record that sorts strictly after it by the SAME
+ * comparator, so a record ingested or removed elsewhere in the index between
+ * two page fetches can't shift an already-delivered row back into view.
+ */
+export function paginateIngests(sorted, { limit, cursor } = {}) {
+ const startIndex = cursor ? sorted.findIndex((item) => compareIngestsDesc(cursor, item) < 0) : 0;
+ if (startIndex === -1) return { items: [], nextCursor: null };
+ const items = sorted.slice(startIndex, startIndex + limit);
+ const hasMore = startIndex + limit < sorted.length;
+ return { items, nextCursor: hasMore ? encodeIngestCursor(items[items.length - 1]) : null };
+}
diff --git a/server/lib/youtubeIngestFormat.test.js b/server/lib/youtubeIngestFormat.test.js
index 058d4d7cbe..0834fa835f 100644
--- a/server/lib/youtubeIngestFormat.test.js
+++ b/server/lib/youtubeIngestFormat.test.js
@@ -8,6 +8,10 @@ import {
buildIngestNote,
buildAgentTaskContext,
resolveObsidianPointer,
+ compareIngestsDesc,
+ encodeIngestCursor,
+ decodeIngestCursor,
+ paginateIngests,
} from './youtubeIngestFormat.js';
const META = {
@@ -248,3 +252,66 @@ describe('resolveObsidianPointer', () => {
})).toBeNull();
});
});
+
+describe('ingest history cursor pagination (#8267)', () => {
+ // Two records ingested in the same instant — the case that would repeat or
+ // skip a row if the sort/cursor only compared `ingestedAt`.
+ const RECORDS = [
+ { videoId: 'aaaaaaaaaaa', ingestedAt: '2026-01-03T00:00:00.000Z' },
+ { videoId: 'ccccccccccc', ingestedAt: '2026-01-02T00:00:00.000Z' },
+ { videoId: 'bbbbbbbbbbb', ingestedAt: '2026-01-02T00:00:00.000Z' },
+ { videoId: 'ddddddddddd', ingestedAt: '2026-01-01T00:00:00.000Z' },
+ ];
+
+ it('sorts newest ingestedAt first, and breaks same-instant ties by videoId descending', () => {
+ const sorted = [...RECORDS].sort(compareIngestsDesc);
+ expect(sorted.map((r) => r.videoId)).toEqual([
+ 'aaaaaaaaaaa', // 01-03
+ 'ccccccccccc', // 01-02, c > b
+ 'bbbbbbbbbbb', // 01-02
+ 'ddddddddddd', // 01-01
+ ]);
+ });
+
+ it('round-trips a cursor through encode/decode', () => {
+ const record = { ingestedAt: '2026-01-02T00:00:00.000Z', videoId: 'ccccccccccc' };
+ const decoded = decodeIngestCursor(encodeIngestCursor(record));
+ expect(decoded).toEqual({ ingestedAt: record.ingestedAt, videoId: record.videoId });
+ });
+
+ it('decodeIngestCursor returns null (never throws) on garbage input', () => {
+ expect(decodeIngestCursor('not-base64url-json')).toBeNull();
+ expect(decodeIngestCursor(Buffer.from(JSON.stringify({ v: 1 })).toString('base64url'))).toBeNull();
+ expect(decodeIngestCursor(Buffer.from(JSON.stringify({ v: 2, ingestedAt: 'x', videoId: 'y' })).toString('base64url'))).toBeNull();
+ });
+
+ it('pages without a cursor, returning a nextCursor keyed to the last row', () => {
+ const sorted = [...RECORDS].sort(compareIngestsDesc);
+ const page = paginateIngests(sorted, { limit: 2 });
+ expect(page.items.map((r) => r.videoId)).toEqual(['aaaaaaaaaaa', 'ccccccccccc']);
+ expect(decodeIngestCursor(page.nextCursor)).toEqual({ ingestedAt: '2026-01-02T00:00:00.000Z', videoId: 'ccccccccccc' });
+ });
+
+ it('continues from a cursor without repeating or skipping the same-instant tie', () => {
+ const sorted = [...RECORDS].sort(compareIngestsDesc);
+ const first = paginateIngests(sorted, { limit: 2 });
+ const second = paginateIngests(sorted, { limit: 2, cursor: decodeIngestCursor(first.nextCursor) });
+ expect(second.items.map((r) => r.videoId)).toEqual(['bbbbbbbbbbb', 'ddddddddddd']);
+ expect(second.nextCursor).toBeNull();
+ });
+
+ it('returns no items once the cursor is past the last record', () => {
+ const sorted = [...RECORDS].sort(compareIngestsDesc);
+ const lastCursor = { ingestedAt: '2026-01-01T00:00:00.000Z', videoId: 'ddddddddddd' };
+ expect(paginateIngests(sorted, { limit: 10, cursor: lastCursor })).toEqual({ items: [], nextCursor: null });
+ });
+
+ it('tolerates a cursor whose record was deleted between page fetches', () => {
+ // The deleted record sorted between b and d; continuation still resumes
+ // strictly after it rather than erroring or replaying b/c.
+ const sorted = [...RECORDS].sort(compareIngestsDesc);
+ const deletedCursor = { ingestedAt: '2026-01-01T12:00:00.000Z', videoId: 'zzzzzzzzzzz' };
+ const page = paginateIngests(sorted, { limit: 10, cursor: deletedCursor });
+ expect(page.items.map((r) => r.videoId)).toEqual(['ddddddddddd']);
+ });
+});
diff --git a/server/routes/brainYoutube.js b/server/routes/brainYoutube.js
index 4f1fd023ef..0b9e6ed7ed 100644
--- a/server/routes/brainYoutube.js
+++ b/server/routes/brainYoutube.js
@@ -10,7 +10,7 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { youtubeIngestSchema, youtubeIngestSettingsSchema } from '../lib/brainValidation.js';
+import { youtubeIngestSchema, youtubeIngestSettingsSchema, youtubeIngestsQuerySchema } from '../lib/brainValidation.js';
import * as ingest from '../services/youtubeIngest.js';
const router = Router();
@@ -40,9 +40,19 @@ router.post('/ingest/:jobId/cancel', asyncHandler(async (req, res) => {
res.json({ message: 'Cancellation requested' });
}));
-/** GET /api/brain/youtube/ingests — every ingest, newest first. */
+/**
+ * GET /api/brain/youtube/ingests — every ingest, newest first. Query-less
+ * callers keep the legacy `{ ingests }` full-history array; passing `limit`
+ * opts into a bounded, cursor-continuable page (#8267).
+ */
router.get('/ingests', asyncHandler(async (req, res) => {
- res.json({ ingests: await ingest.listIngests() });
+ const { limit, cursor } = validateRequest(youtubeIngestsQuerySchema, req.query);
+ if (limit === undefined && cursor === undefined) {
+ res.json({ ingests: await ingest.listIngests() });
+ return;
+ }
+ const { items, nextCursor } = await ingest.listIngests({ limit: limit ?? 50, cursor });
+ res.json({ ingests: items, ...(nextCursor ? { nextCursor } : {}) });
}));
/** GET /api/brain/youtube/ingests/:videoId */
diff --git a/server/routes/brainYoutube.test.js b/server/routes/brainYoutube.test.js
new file mode 100644
index 0000000000..2553b6e887
--- /dev/null
+++ b/server/routes/brainYoutube.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const listIngests = vi.fn();
+
+vi.mock('../services/youtubeIngest.js', () => ({ listIngests }));
+
+const { default: routes } = await import('./brainYoutube.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/brain/youtube', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /api/brain/youtube/ingests', () => {
+ it('returns the legacy full-history array for a query-less request', async () => {
+ listIngests.mockResolvedValue([{ videoId: 'v1' }, { videoId: 'v2' }]);
+
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ ingests: [{ videoId: 'v1' }, { videoId: 'v2' }] });
+ expect(listIngests).toHaveBeenCalledWith();
+ });
+
+ it('opts into a bounded page when limit is passed, defaulting cursor to undefined', async () => {
+ listIngests.mockResolvedValue({ items: [{ videoId: 'v1' }], nextCursor: 'opaque-token' });
+
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests?limit=1');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ ingests: [{ videoId: 'v1' }], nextCursor: 'opaque-token' });
+ expect(listIngests).toHaveBeenCalledWith({ limit: 1, cursor: undefined });
+ });
+
+ it('omits nextCursor once no more records remain', async () => {
+ listIngests.mockResolvedValue({ items: [{ videoId: 'v1' }], nextCursor: null });
+
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests?limit=50');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ ingests: [{ videoId: 'v1' }] });
+ expect(response.body.nextCursor).toBeUndefined();
+ });
+
+ it('forwards a cursor and defaults the limit to 50 when only cursor is given', async () => {
+ listIngests.mockResolvedValue({ items: [], nextCursor: null });
+
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests?cursor=opaque-token');
+
+ expect(response.status).toBe(200);
+ expect(listIngests).toHaveBeenCalledWith({ limit: 50, cursor: 'opaque-token' });
+ });
+
+ it('rejects a limit above the cap before the service is called', async () => {
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests?limit=101');
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('VALIDATION_ERROR');
+ expect(listIngests).not.toHaveBeenCalled();
+ });
+
+ it('propagates an INVALID_CURSOR error from the service as a 400', async () => {
+ listIngests.mockRejectedValue(Object.assign(new Error('Invalid ingest cursor'), { status: 400, code: 'INVALID_CURSOR' }));
+
+ const response = await request(makeApp()).get('/api/brain/youtube/ingests?limit=10&cursor=garbage');
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INVALID_CURSOR');
+ });
+});
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index cf0dea919b..f817479946 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -61,7 +61,10 @@ import { assertYoutubeVideoUrl } from '../lib/youtubeUrlAssert.js';
import {
buildAgentTaskContext,
buildIngestNote,
+ compareIngestsDesc,
+ decodeIngestCursor,
formatDuration,
+ paginateIngests,
parseVideoMetadata,
resolveObsidianPointer,
sanitizeFilename,
@@ -169,10 +172,22 @@ async function putIngest(videoId, patch) {
});
}
-/** Every ingest, newest first. */
-export async function listIngests() {
+/**
+ * Every ingest, newest first. Query-less callers (the default) get the full
+ * legacy array. Passing `limit` opts into a bounded page ordered by
+ * `ingestedAt` desc with `videoId` as a deterministic tie-breaker; pass back
+ * a prior page's `nextCursor` to continue (#8267).
+ */
+export async function listIngests({ limit, cursor } = {}) {
const index = await loadIndex();
- return Object.values(index).sort((a, b) => String(b.ingestedAt || '').localeCompare(String(a.ingestedAt || '')));
+ const sorted = Object.values(index).sort(compareIngestsDesc);
+ if (limit === undefined) return sorted;
+ let decodedCursor = null;
+ if (cursor) {
+ decodedCursor = decodeIngestCursor(cursor);
+ if (!decodedCursor) throw new ServerError('Invalid ingest cursor', { status: 400, code: 'INVALID_CURSOR' });
+ }
+ return paginateIngests(sorted, { limit, cursor: decodedCursor });
}
export async function getIngest(videoId) {