Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): filter the Library by each page's last send to the CMS (#1567)

Cihan5d89bd19dda1
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdx
index 034a4bd66..cdca09cdc 100644
--- a/docs/guides/content-editor.mdx
+++ b/docs/guides/content-editor.mdx
@@ -20,12 +20,12 @@ The **Content plan** lists the work for the last 7, 30 or 90 days. Pick the peri
### Cards
-| Card | What it counts |
-|---|---|
-| **Create** | New pages AI needs: open opportunities with no page on your site yet. |
-| **Optimize** | Pages losing ground, and opportunities to improve a page you already have. |
-| **Protect** | Your top pages (cited at least 5 times in the period and not losing ground, up to 5), and opportunities to defend a page. |
-| **Priority** | Rows your team marked as a priority. |
+| Card | What it counts |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------- |
+| **Create** | New pages AI needs: open opportunities with no page on your site yet. |
+| **Optimize** | Pages losing ground, and opportunities to improve a page you already have. |
+| **Protect** | Your top pages (cited at least 5 times in the period and not losing ground, up to 5), and opportunities to defend a page. |
+| **Priority** | Rows your team marked as a priority. |
Click a card to filter the list to it; click it again to clear the filter.
@@ -56,7 +56,8 @@ The score runs from 0 to 100 and is built from four factors:
Hover over the score, or focus it, to see **How this score is worked out**: each factor with the points it gave, and the total. The badge's level (critical, high, medium or low) uses the Plan's own cut-offs, and only a page losing citations can reach critical.
<Note>
-This score ranks the Plan only. The Action Center scores its tasks on its own: see [Action Center](/guides/action-center).
+ This score ranks the Plan only. The Action Center scores its tasks on its own:
+ see [Action Center](/guides/action-center).
</Note>
### Row menu
@@ -74,7 +75,9 @@ The **What AI cites in your topics** section opens with **Show**. For each page
The shares cover only the cited addresses whose type can be read. Forums, encyclopedias, news and the long tail of less cited pages are left out, and a line under the section says what share of the period's citations is covered.
<Tip>
-The page types follow your brand's **Site type** (B2B SaaS, E-commerce or B2C) in the brand settings: feature and comparison pages for B2B SaaS, product and category pages for e-commerce, destination and help pages for B2C.
+ The page types follow your brand's **Site type** (B2B SaaS, E-commerce or B2C)
+ in the brand settings: feature and comparison pages for B2B SaaS, product and
+ category pages for e-commerce, destination and help pages for B2C.
</Tip>
## New content
@@ -92,11 +95,13 @@ The page types follow your brand's **Site type** (B2B SaaS, E-commerce or B2C) i
- **Page URL**: a page on your brand's site (its domains are in the brand settings). **Import** brings in its main text, headings, links and schema; menus and footers stay out.
- **Paste text** from Word, Google Docs or a web page. Headings, lists, links and tables are kept.
- **Upload file**: Word, Markdown, HTML or text, up to 10 MB.
+
</Step>
<Step title="Pick the page type">
Click **Continue**. Ansvisor picks a **Page type** from the title, the content, the page or the opportunity, and says which. Pick another if it's wrong; you can also change it later in the editor.
For a new page, **Overview** lists your pages AI already cites for the same prompts, with how many of those prompts each one answers, its AI citations and its Google position. You can choose **Optimize *page* instead**, or **Create a new page**.
+
</Step>
<Step title="Choose who does it">
| Who does it | What happens |
@@ -159,16 +164,16 @@ The Content Agent never changes these passages. If you edit one, the editor asks
The **Library** lists the drafts by status, each tab with its count:
-| Tab | What's in it |
-|---|---|
-| **All** | Every draft that isn't archived. |
-| **In progress** | Drafts being written. |
-| **In review** | Drafts the Content Agent wrote, waiting for a person. |
-| **Ready** | Drafts marked ready. |
-| **Published** | Drafts marked published, by you or your CMS. |
-| **Archived** | Drafts sent to the archive. They keep their status for when they're restored. |
+| Tab | What's in it |
+| --------------- | ----------------------------------------------------------------------------- |
+| **All** | Every draft that isn't archived. |
+| **In progress** | Drafts being written. |
+| **In review** | Drafts the Content Agent wrote, waiting for a person. |
+| **Ready** | Drafts marked ready. |
+| **Published** | Drafts marked published, by you or your CMS. |
+| **Archived** | Drafts sent to the archive. They keep their status for when they're restored. |
-The columns are Content, Type, Method (Create or Optimize), By (you, the Content Agent or a teammate), Status, Created and Updated. Click a row to open the draft in the editor. The **Created** filter narrows the list to the last 7, 30 or 90 days.
+The columns are Content, Type, Method (Create or Optimize), By (you, the Content Agent or a teammate), Status, Created and Updated. Click a row to open the draft in the editor. The **Created** filter narrows the list to the last 7, 30 or 90 days. Once a page has been sent to your CMS, a **Last send** filter lists the pages by how their last send went: never sent, sending, sent, failed or published (see [Send to CMS](/guides/send-to-cms)).
### Row menu
@@ -180,7 +185,7 @@ The columns are Content, Type, Method (Create or Optimize), By (you, the Content
### Export
-**Export** in the header downloads the drafts listed, that is the current tab within the **Created** range, with their pages:
+**Export** in the header downloads the drafts listed, that is the current tab within the **Created** range and the **Last send** filter, with their pages:
- **Export CSV** and **Export Excel**: one row per draft, with its title, status, method, page type, author, dates, page URL, length and text.
- **Export Word**: one document, each draft starting on a page of its own.
diff --git a/docs/guides/send-to-cms.mdx b/docs/guides/send-to-cms.mdx
index 4332a97b4..1d92deb27 100644
--- a/docs/guides/send-to-cms.mdx
+++ b/docs/guides/send-to-cms.mdx
@@ -57,6 +57,8 @@ Beside each row's status, the Library shows its last send:
| Red warning | It failed. Hover it to see what your workflow answered or reported, or why it couldn't be reached. |
| Blue link | Published. Click it to open the live page. |
+To list only some of them, use the **Last send** filter beside **Created**: **Never sent**, **Sending**, **Sent**, **Failed** or **Published**. It shows once a page of the brand has been sent. The filter is kept in the page's address (for example `?sent=failed`), and **Export** exports the rows it lists.
+
## Build the workflow
Every workflow has the same three steps:
diff --git a/web/messages/en.json b/web/messages/en.json
index 709c31c62..7a710de34 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3467,6 +3467,16 @@
"90d": "Last 90 days",
"empty": "Nothing in this tab was created in this period."
},
+ "lastSend": {
+ "label": "Last send",
+ "all": "Any",
+ "never": "Never sent",
+ "queued": "Sending",
+ "sent": "Sent",
+ "failed": "Failed",
+ "published": "Published",
+ "empty": "No page in this tab matches the Last send filter."
+ },
"title": "Library",
"description": "Everything you and the agents wrote or changed.",
"selectBrand": "Select a brand to see its content.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
index 79775c8ec..15e09af60 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx
@@ -117,6 +117,17 @@ async function renderPage() {
});
}
+/** A draft's last send, as readCmsStatuses returns it. */
+const sendOf = (status: string) => ({
+ status,
+ target: 'webhook',
+ at: '2026-10-24T10:00:00Z',
+ httpStatus: status === 'failed' ? 500 : 200,
+ error: null,
+ publishedUrl: null,
+});
+const lastSendBox = () => container.querySelector('[aria-label="Last send"]');
+
const tab = (name: string) =>
[...container.querySelectorAll<HTMLElement>('[role="tab"]')].find((el) =>
el.textContent?.startsWith(name),
@@ -750,6 +761,27 @@ describe('a Library row’s menu (00233)', () => {
await act(async () => found.click());
};
+ it('keeps a list filtered by Last send on show when it is read again in another order', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=failed');
+ const first = row({});
+ const second = row({ id: 'd2', title: 'Churn guide' });
+ getContentDrafts.mockResolvedValueOnce([first, second]).mockResolvedValue([second, first]);
+ readCmsStatuses.mockResolvedValue(
+ new Map([
+ ['d1', sendOf('failed')],
+ ['d2', sendOf('failed')],
+ ]),
+ );
+ await renderPage();
+ // The second read of the sends never answers: the drafts are the same.
+ readCmsStatuses.mockReturnValue(new Promise(() => {}));
+ await pick('Pipeline forecasting', 'In progress');
+ expect(getContentDrafts).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(container.textContent).toContain('Churn guide');
+ expect(container.textContent).toContain('Pipeline forecasting');
+ });
+
it('sets a status, Ready as the editor’s Mark ready, and reads the list again', async () => {
getContentDrafts.mockResolvedValue([row({})]);
await renderPage();
@@ -1005,6 +1037,126 @@ describe('the Library’s Export and Created filter (CE-002)', () => {
expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['new']);
});
+ it('lists only the drafts whose last send is as the URL names, and exports those (#1331)', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=failed');
+ getContentDrafts.mockResolvedValue([
+ row({ id: 'd1', title: 'Failed page' }),
+ row({ id: 'd2', title: 'Sent page' }),
+ row({ id: 'd3', title: 'Unsent page' }),
+ ]);
+ readCmsStatuses.mockResolvedValue(
+ new Map([
+ ['d1', sendOf('failed')],
+ ['d2', sendOf('sent')],
+ ]),
+ );
+ await renderPage();
+ expect(container.textContent).toContain('Failed page');
+ expect(container.textContent).not.toContain('Sent page');
+ expect(container.textContent).not.toContain('Unsent page');
+ expect(container.querySelector('[aria-label="Last send"]')!.textContent).toContain(
+ 'Last send: Failed',
+ );
+
+ const items = await openExport();
+ await act(async () => csvItem(items).click());
+ await act(async () => {});
+ expect(getContentDraftPages).toHaveBeenCalledWith('brand-1', ['d1']);
+ });
+
+ it('lists the drafts never sent', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=never');
+ getContentDrafts.mockResolvedValue([
+ row({ id: 'd1', title: 'Sent page' }),
+ row({ id: 'd2', title: 'Unsent page' }),
+ ]);
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('published')]]));
+ await renderPage();
+ expect(container.textContent).toContain('Unsent page');
+ expect(container.textContent).not.toContain('Sent page');
+ });
+
+ it('leaves Last send out for a brand that sent no page', async () => {
+ getContentDrafts.mockResolvedValue([row({})]);
+ await renderPage();
+ expect(lastSendBox()).toBeNull();
+ expect(container.querySelector('[aria-label="Created"]')).not.toBeNull();
+ });
+
+ it('shows Last send once a page was sent', async () => {
+ getContentDrafts.mockResolvedValue([row({})]);
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('sent')]]));
+ await renderPage();
+ expect(container.querySelector('[aria-label="Last send"]')!.textContent).toContain(
+ 'Last send: Any',
+ );
+ });
+
+ it('waits for the sends before it filters by them, rather than list every draft', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=failed');
+ getContentDrafts.mockResolvedValue([
+ row({ id: 'd1', title: 'Failed page' }),
+ row({ id: 'd2', title: 'Unsent page' }),
+ ]);
+ let answer: (sends: Map<string, unknown>) => void = () => {};
+ readCmsStatuses.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ await renderPage();
+ expect(container.textContent).not.toContain('Unsent page');
+ expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
+
+ await act(async () => answer(new Map([['d1', sendOf('failed')]])));
+ expect(container.textContent).toContain('Failed page');
+ expect(container.textContent).not.toContain('Unsent page');
+ });
+
+ it('lists nothing to export while the sends it filters by are read', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=never');
+ getContentDrafts.mockResolvedValue([row({})]);
+ readCmsStatuses.mockReturnValue(new Promise(() => {}));
+ await renderPage();
+ const exportButton = [...container.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent === 'Export',
+ )!;
+ expect(exportButton.disabled).toBe(true);
+ });
+
+ it('leaves Last send out on a brand that sent none, after one that did', async () => {
+ getContentDrafts.mockImplementation(async (brandId: string) =>
+ brandId === 'brand-1' ? [row({})] : [],
+ );
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('sent')]]));
+ await renderPage();
+ expect(lastSendBox()).not.toBeNull();
+ brandState.activeBrandId = 'brand-2';
+ await renderPage();
+ expect(lastSendBox()).toBeNull();
+ });
+
+ it('blames the Created filter when it is the one that leaves nothing', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?created=7d&sent=failed');
+ getContentDrafts.mockResolvedValue([row({ createdAt: '2026-01-05T09:00:00Z' })]);
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('failed')]]));
+ await renderPage();
+ expect(container.textContent).toContain('Nothing in this tab was created in this period.');
+ });
+
+ it('says nothing of the cap while Last send narrows the list', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=failed');
+ getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', title: 'Churn guide' })]);
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('failed')]]));
+ await renderPage();
+ expect(container.textContent).not.toContain('Churn guide');
+ expect(container.textContent).not.toContain('changed most recently');
+ });
+
+ it('says when nothing in the tab matches the Last send filter', async () => {
+ window.history.replaceState(null, '', '/dashboard/content/library?sent=queued');
+ getContentDrafts.mockResolvedValue([row({})]);
+ readCmsStatuses.mockResolvedValue(new Map([['d1', sendOf('sent')]]));
+ await renderPage();
+ expect(container.textContent).toContain('No page in this tab matches the Last send filter.');
+ });
+
it('says when nothing in the tab was created in the range', async () => {
window.history.replaceState(null, '', '/dashboard/content/library?created=30d');
getContentDrafts.mockResolvedValue([row({ createdAt: '2026-01-05T09:00:00Z' })]);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
index d08c240af..e07ee177f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx
@@ -45,13 +45,16 @@ import {
AGENT_POLL_MS,
CREATED_RANGES,
LIBRARY_TABS,
+ SEND_FILTERS,
contentEditorPath,
draftsCreatedIn,
draftsInTab,
+ draftsLastSent,
type ContentDraftListItem,
type CreatedRange,
type DraftStatus,
type LibraryTab,
+ type SendFilter,
} from '@/lib/content/drafts';
import { siteTypeOf } from '@/lib/content/page-types';
import { formatNumber } from '@/lib/format';
@@ -88,6 +91,8 @@ export default function ContentLibraryPage() {
const [tab, setTab] = useState<LibraryTab>('all');
// When the drafts listed (and exported) were created: ?created=30d.
const [created, setCreated] = useState<CreatedRange>('all');
+ // How the listed drafts' last send to the CMS stands (#1331): ?sent=failed.
+ const [sent, setSent] = useState<SendFilter>('all');
const [read, setRead] = useState<LibraryRead | null>(null);
const [attempt, setAttempt] = useState(0);
const [starting, setStarting] = useState(false);
@@ -102,6 +107,8 @@ export default function ContentLibraryPage() {
const [publishing, setPublishing] = useState<string | null>(null);
// Each draft's last send, beside its status; read with the list.
const [cms, setCms] = useState<ReadonlyMap<string, CmsStatus>>(new Map());
+ // The drafts the sends above were read for, in any order.
+ const [cmsReadFor, setCmsReadFor] = useState<ReadonlySet<string>>(new Set());
// The rows picked to send together, for the brand they were picked in.
const [picked, setPicked] = useState<{ brandId: string | null; ids: ReadonlySet<string> }>({
brandId: null,
@@ -119,6 +126,7 @@ export default function ContentLibraryPage() {
// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
setTab(readUrlChoice('tab', LIBRARY_TABS, 'all'));
setCreated(readUrlChoice('created', CREATED_RANGES, 'all'));
+ setSent(readUrlChoice('sent', SEND_FILTERS, 'all'));
// Once: closed, it doesn't open again on a reload.
if (readUrlParam('new') === '1') {
setStarting(true);
@@ -161,8 +169,16 @@ export default function ContentLibraryPage() {
if (!readIds) return;
let cancelled = false;
readCmsStatuses(readIds.split(','))
- .then((statuses) => !cancelled && setCms(statuses))
- .catch((err) => console.error('Failed to read the pages’ sends:', err));
+ .then((statuses) => {
+ if (cancelled) return;
+ setCms(statuses);
+ setCmsReadFor(new Set(readIds.split(',')));
+ })
+ .catch((err) => {
+ console.error('Failed to read the pages’ sends:', err);
+ // The filter lists what it has rather than wait for good.
+ if (!cancelled) setCmsReadFor(new Set(readIds.split(',')));
+ });
return () => {
cancelled = true;
};
@@ -290,6 +306,11 @@ export default function ContentLibraryPage() {
clearPicked();
writeUrlParams({ created: next }, { created: 'all' });
};
+ const changeSent = (next: SendFilter) => {
+ setSent(next);
+ clearPicked();
+ writeUrlParams({ sent: next }, { sent: 'all' });
+ };
if (!activeBrandId) {
return (
@@ -304,7 +325,14 @@ export default function ContentLibraryPage() {
const drafts = current?.drafts ?? null;
const counts = current?.counts ?? null;
const inTab = drafts ? draftsInTab(drafts, tab) : [];
- const listed = draftsCreatedIn(inTab, created);
+ const createdIn = draftsCreatedIn(inTab, created);
+ // Filtered by their last send only once these drafts' sends are read (a
+ // list read again in another order needn't wait); till then, none listed
+ // to export or pick.
+ const sendsRead = sent === 'all' || !drafts || drafts.every((draft) => cmsReadFor.has(draft.id));
+ const listed = sendsRead ? draftsLastSent(createdIn, cms, sent) : [];
+ // Any of this brand's drafts sent: the sends of the last brand don't count.
+ const anySent = !!drafts?.some((draft) => cms.has(draft.id));
// Picked rows still listed (a read may have moved some), never archived ones.
const pickedIds = picked.brandId === activeBrandId ? picked.ids : new Set<string>();
const pickedDrafts = listed.filter((draft) => pickedIds.has(draft.id) && !draft.archivedAt);
@@ -364,26 +392,50 @@ export default function ContentLibraryPage() {
))}
</TabsList>
</Tabs>
- <Select
- value={created}
- onValueChange={(value) => changeCreated(value as CreatedRange)}
- items={CREATED_RANGES.map((range) => ({
- value: range,
- label: `${t('created.label')}: ${t(`created.${range}`)}`,
- }))}
- >
- {/* On the tabs' line when it fits, else on its own, on the right. */}
- <SelectTrigger size="sm" className="ml-auto" aria-label={t('created.label')}>
- <SelectValue />
- </SelectTrigger>
- <SelectContent align="end">
- {CREATED_RANGES.map((range) => (
- <SelectItem key={range} value={range}>
- {t(`created.${range}`)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ {/* On the tabs' line when they fit, else on their own, on the right. */}
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ {/* Once a page of the brand's was sent, or while the URL names one. */}
+ {(anySent || sent !== 'all') && (
+ <Select
+ value={sent}
+ onValueChange={(value) => changeSent(value as SendFilter)}
+ items={SEND_FILTERS.map((filter) => ({
+ value: filter,
+ label: `${t('lastSend.label')}: ${t(`lastSend.${filter}`)}`,
+ }))}
+ >
+ <SelectTrigger size="sm" aria-label={t('lastSend.label')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {SEND_FILTERS.map((filter) => (
+ <SelectItem key={filter} value={filter}>
+ {t(`lastSend.${filter}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ <Select
+ value={created}
+ onValueChange={(value) => changeCreated(value as CreatedRange)}
+ items={CREATED_RANGES.map((range) => ({
+ value: range,
+ label: `${t('created.label')}: ${t(`created.${range}`)}`,
+ }))}
+ >
+ <SelectTrigger size="sm" aria-label={t('created.label')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {CREATED_RANGES.map((range) => (
+ <SelectItem key={range} value={range}>
+ {t(`created.${range}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
</div>
<Card className="py-0">
@@ -436,13 +488,13 @@ export default function ContentLibraryPage() {
{t('retry')}
</Button>
</div>
- ) : drafts === null ? (
+ ) : drafts === null || !sendsRead ? (
<div className="flex items-center justify-center py-12" aria-busy="true">
<LoadingDots size="md" className="text-muted-foreground" />
</div>
) : listed.length === 0 && inTab.length > 0 ? (
<p className="px-6 py-12 text-center text-sm text-muted-foreground">
- {t('created.empty')}
+ {t(createdIn.length === 0 ? 'created.empty' : 'lastSend.empty')}
</p>
) : (
<LibraryTable
@@ -520,7 +572,8 @@ export default function ContentLibraryPage() {
</DialogFooter>
</DialogContent>
</Dialog>
- {counts && created === 'all' && listed.length < counts[tab] && (
+ {/* The cap's note: a filter that narrows the list isn't the cap. */}
+ {counts && created === 'all' && sent === 'all' && listed.length < counts[tab] && (
<p className="text-xs text-muted-foreground">
{t('latestOnly', {
shown: formatNumber(listed.length),
diff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.ts
index 6981302ae..e7d8e9fdc 100644
--- a/web/src/lib/content/drafts.test.ts
+++ b/web/src/lib/content/drafts.test.ts
@@ -8,6 +8,7 @@ import {
agentStateOf,
contentEditorPath,
draftsCreatedIn,
+ draftsLastSent,
draftsInTab,
isPageType,
libraryTabCounts,
@@ -57,6 +58,27 @@ describe('the Library’s Created filter', () => {
});
});
+describe('the Library’s Last send filter (#1331)', () => {
+ const list = ['going', 'sent', 'failed', 'live', 'never'].map((id) => draft(id, 'draft'));
+ const sends = new Map([
+ ['going', { status: 'queued' }],
+ ['sent', { status: 'sent' }],
+ ['failed', { status: 'failed' }],
+ ['live', { status: 'published' }],
+ ]);
+ const ids = (filter: Parameters<typeof draftsLastSent>[2]) =>
+ draftsLastSent(list, sends, filter).map((d) => d.id);
+
+ it('keeps the drafts whose last send is as picked, or never sent', () => {
+ expect(ids('all')).toEqual(['going', 'sent', 'failed', 'live', 'never']);
+ expect(ids('never')).toEqual(['never']);
+ expect(ids('queued')).toEqual(['going']);
+ expect(ids('sent')).toEqual(['sent']);
+ expect(ids('failed')).toEqual(['failed']);
+ expect(ids('published')).toEqual(['live']);
+ });
+});
+
describe('the Library tabs', () => {
it('counts every draft under All and each under its status', () => {
expect(libraryTabCounts(drafts)).toEqual({
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index 1d1d2e569..3af6eb0c0 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -301,6 +301,27 @@ export function draftsCreatedIn(
return drafts.filter((d) => new Date(d.createdAt).getTime() >= since);
}
+/**
+ * The Library's Last send filter (#1331): any, never sent, or how the last
+ * send to the CMS stands, as the row's mark shows it.
+ */
+export const SEND_FILTERS = ['all', 'never', 'queued', 'sent', 'failed', 'published'] as const;
+export type SendFilter = (typeof SEND_FILTERS)[number];
+
+/**
+ * The drafts whose last send is as picked, read from each draft's last send
+ * (readCmsStatuses: one left queued past its half hour reads as failed).
+ */
+export function draftsLastSent(
+ drafts: ContentDraftListItem[],
+ sends: ReadonlyMap<string, { status: string }>,
+ filter: SendFilter,
+): ContentDraftListItem[] {
+ if (filter === 'all') return drafts;
+ if (filter === 'never') return drafts.filter((d) => !sends.has(d.id));
+ return drafts.filter((d) => sends.get(d.id)?.status === filter);
+}
+
export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {
if (tab === 'archived') return drafts.filter((d) => d.archivedAt !== null);
const live = drafts.filter((d) => d.archivedAt === null);