+ The last try failed {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries
+ again in an hour.
+
+ )}
+
+ The database is copied each night at {status.time} ({status.timeZone}) into backups{" "}
+ in the data folder, and the latest {status.kept} are kept. The README says how to restore one.
+
+
+ )}
+
+ );
+}
diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx
new file mode 100644
index 0000000..eabba0d
--- /dev/null
+++ b/web/src/components/notification-settings.tsx
@@ -0,0 +1,526 @@
+import type { NotificationsView, NotifyEvent, SentNotice } from "@selects/server";
+import { type FormEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
+import { api } from "@/api";
+import { Button } from "@/components/ui/button";
+import { problemsIn, useAutosave } from "@/lib/autosave";
+import {
+ type EventSettings,
+ type EventsDraft,
+ outcomeText,
+ parseEvents,
+ testResultText,
+} from "@/lib/notifications";
+import { SaveStatus } from "./schedule-editor";
+
+type Notifications = NotificationsView & EventSettings & { recent: SentNotice[] };
+
+const SETTLE_MS = 600;
+
+const EVENT_LABELS: Record = {
+ posted: { label: "Posted", detail: "A post reached Instagram, and how many selects are left in the pool." },
+ failed: {
+ label: "Failed",
+ detail: "A post failed for good, or Instagram has not said whether it published one.",
+ },
+ token: {
+ label: "Token about to expire",
+ detail: "Once a day while the Instagram token expires within 7 days or no longer works.",
+ },
+ pool: { label: "Pool running low", detail: "Once when the pool drops below the number you set." },
+};
+
+const formatTime = (at: number) =>
+ new Date(at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
+
+/**
+ * Notifications in Settings: which events notify, the ntfy topic and the webhook, each with a
+ * Send test, and the latest notices. Never shows a topic, token or URL in full once saved.
+ */
+export function NotificationSettings() {
+ const [view, setView] = useState();
+ const [loadError, setLoadError] = useState(false);
+
+ const load = useCallback(async () => {
+ try {
+ const { data, error } = await api.notifications.get();
+ if (data) setView(data);
+ setLoadError(error !== null);
+ } catch {
+ setLoadError(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ return (
+
+
+ Fake mode: nothing leaves Selects. Notices are listed below as what would have been sent, and
+ Send test sends nothing. Set INSTAGRAM_API=live to send them.
+
+ The Selects server, not your browser, sends each notice to this URL as a JSON POST with its{" "}
+ event, title and message. Redirects are not followed.
+
+ );
+}
diff --git a/web/src/lib/notifications.test.ts b/web/src/lib/notifications.test.ts
new file mode 100644
index 0000000..95d64cc
--- /dev/null
+++ b/web/src/lib/notifications.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { outcomeText, parseEvents, testResultText } from "./notifications";
+
+const saved = { events: { posted: true, failed: true, token: true, pool: true }, poolThreshold: 10 };
+
+describe("parseEvents", () => {
+ test("takes the switches and a whole-number threshold", () => {
+ const draft = { events: { ...saved.events, posted: false }, poolThreshold: " 25 " };
+
+ expect(parseEvents(draft, saved)).toEqual({
+ settings: { events: { ...saved.events, posted: false }, poolThreshold: 25 },
+ error: undefined,
+ });
+ });
+
+ test("keeps the saved threshold while the one typed is not a whole number from 1 to 10,000", () => {
+ for (const poolThreshold of ["0", "", "2.5", "10001"]) {
+ expect(parseEvents({ events: saved.events, poolThreshold }, saved)).toEqual({
+ settings: saved,
+ error: "A whole number from 1 to 10,000.",
+ });
+ }
+ });
+});
+
+describe("what Settings says", () => {
+ test("about a notice", () => {
+ expect(outcomeText("sent")).toBe("Sent");
+ expect(outcomeText("failed")).toBe("Not sent to every channel");
+ expect(outcomeText("would-send")).toBe("Would have been sent (fake mode)");
+ expect(outcomeText("no-channel")).toBe("No channel set");
+ });
+
+ test("about a test", () => {
+ expect(testResultText({ status: "sent" })).toBe("Sent. Check that it arrived.");
+ expect(testResultText({ status: "failed", reason: "The server answered 403." })).toBe(
+ "Couldn't send: The server answered 403.",
+ );
+ expect(testResultText({ status: "would-send", message: "Fake mode: nothing was sent." })).toBe(
+ "Fake mode: nothing was sent.",
+ );
+ });
+});
diff --git a/web/src/lib/notifications.ts b/web/src/lib/notifications.ts
new file mode 100644
index 0000000..94ba800
--- /dev/null
+++ b/web/src/lib/notifications.ts
@@ -0,0 +1,44 @@
+import type { SentNotice, TestResult } from "@selects/server";
+import { wholeNumber } from "./schedule";
+
+export type EventSwitches = { posted: boolean; failed: boolean; token: boolean; pool: boolean };
+export type EventSettings = { events: EventSwitches; poolThreshold: number };
+export type EventsDraft = { events: EventSwitches; poolThreshold: string };
+
+export const POOL_THRESHOLD = { min: 1, max: 10_000 } as const;
+
+/** The events to save: the threshold as typed while it is valid, and otherwise the one saved. */
+export function parseEvents(
+ draft: EventsDraft,
+ saved: EventSettings,
+): { settings: EventSettings; error: string | undefined } {
+ const parsed = wholeNumber(draft.poolThreshold, POOL_THRESHOLD);
+ return {
+ settings: { events: draft.events, poolThreshold: parsed.ok ? parsed.value : saved.poolThreshold },
+ error: parsed.ok ? undefined : parsed.problem,
+ };
+}
+
+export function outcomeText(outcome: SentNotice["outcome"]): string {
+ switch (outcome) {
+ case "sent":
+ return "Sent";
+ case "failed":
+ return "Not sent to every channel";
+ case "would-send":
+ return "Would have been sent (fake mode)";
+ case "no-channel":
+ return "No channel set";
+ }
+}
+
+export function testResultText(result: Exclude): string {
+ switch (result.status) {
+ case "sent":
+ return "Sent. Check that it arrived.";
+ case "failed":
+ return `Couldn't send: ${result.reason}`;
+ case "would-send":
+ return result.message;
+ }
+}
diff --git a/web/src/screens/settings.tsx b/web/src/screens/settings.tsx
index 4553760..d186cc6 100644
--- a/web/src/screens/settings.tsx
+++ b/web/src/screens/settings.tsx
@@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import { api } from "@/api";
+import { BackupStatus } from "@/components/backup-status";
import { GallerySettings } from "@/components/gallery-settings";
+import { NotificationSettings } from "@/components/notification-settings";
import { PrivacyZones } from "@/components/privacy-zones";
import { PublishingSettings } from "@/components/publishing-settings";
import { Screen } from "./screen";
@@ -44,12 +46,14 @@ export function SettingsScreen() {
+
Privacy zones
+
About
From 98252e7e33bd3659c83bca6ec14a37323074cb04 Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 11:43:03 +0000
Subject: [PATCH 06/13] docs(repo): say how backups are made and how to restore
one
---
README.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/README.md b/README.md
index 417d612..c2bda31 100644
--- a/README.md
+++ b/README.md
@@ -114,6 +114,32 @@ or you say whether it was posted.
Try a post with the Dry run switch on first: the Posted screen shows the frame, caption and
everything a real post would send.
+### Backups and restoring
+
+Each night at 03:30, in the timezone set on the Queue screen, Selects copies its database to
+`backups/selects-YYYY-MM-DD.db` in `DATA_DIR`, keeping the latest seven. It also makes one at
+start when the last copy is from before last night. Settings shows when the last copy was made
+and why the last try failed, if it did. Each copy holds the Instagram token and the notification
+channels, so it is readable by its owner only; keep it that way wherever you copy it.
+
+To restore a copy:
+
+1. Stop Selects.
+2. Copy the database aside, in case you want it back: `selects.db`, `selects.db-wal` and
+ `selects.db-shm` in `DATA_DIR`.
+3. Replace `selects.db` with the copy, named `selects.db`, and keep it owner-only
+ (`chmod 600 selects.db`).
+4. Remove `selects.db-wal` and `selects.db-shm`. They belong to the database you replaced, and
+ SQLite would apply them to the copy.
+5. Start Selects.
+
+The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and are
+not part of a copy. Restoring takes the library, posts, schedule and settings back to the night
+of the copy. A select posted since then is back in the pool and could be posted again, so as
+soon as Selects starts, turn on the pause switch on the Queue screen, compare the Posted screen
+with Instagram, and delete from the Library any select already on Instagram (its hash is kept,
+so it is never picked again). Then turn the pause switch off.
+
## Checks
These run in CI on every pull request:
From 5818d9a34d913475b1a443d2afcc9499bf8e8a56 Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 11:43:03 +0000
Subject: [PATCH 07/13] docs(adr): record notification and backup decisions
---
docs/adr/0009-notifications-and-backups.md | 65 ++++++++++++++++++++++
1 file changed, 65 insertions(+)
create mode 100644 docs/adr/0009-notifications-and-backups.md
diff --git a/docs/adr/0009-notifications-and-backups.md b/docs/adr/0009-notifications-and-backups.md
new file mode 100644
index 0000000..fe33380
--- /dev/null
+++ b/docs/adr/0009-notifications-and-backups.md
@@ -0,0 +1,65 @@
+# ADR 0009: Notices say only what happened, fake mode sends none, and backups are snapshots
+
+## Status
+
+Accepted, November 13, 2026.
+
+## Context
+
+[docs/PRODUCT.md](../PRODUCT.md) settles the two channels (an ntfy topic and a webhook), the four
+switchable events and the nightly backup with seven copies. It leaves open what a notice
+carries, whether fake mode sends one, how often the token and pool events repeat, what a failed
+delivery does, and how a copy of a live database is made safely. A notice leaves the install and
+a copy holds the Instagram token, so each choice leans towards sending and keeping less.
+
+## Decision
+
+- **A notice says what happened, and nothing about the photo.** It never carries coordinates, a
+ file name, a caption or a link. Posted: that a select was posted, and how many are left in the
+ pool. Failed: that a post failed and its select is back in the pool, or that Instagram has not
+ said whether it published one. Token: that the token expires in so many days (and could not be
+ refreshed), or that Instagram no longer accepts it. Pool: how many selects are left, below the
+ threshold. ntfy gets `topic`, `title`, `message` and the event as a tag, as JSON to the server's
+ URL; the webhook gets `event`, `title` and `message` as a JSON POST.
+- **Fake mode sends nothing.** As with Instagram and the bucket ([ADR 0006](0006-publishing-safety.md)),
+ fake mode makes no outside request: each notice is recorded and shown in Settings as one that
+ would have been sent, and Send test says so. Only `INSTAGRAM_API=live` sends.
+- **The publisher tells how each post settles** (published, failed for good, or left needing a
+ check), whether a slot or Post now made it, and whenever Instagram decides it later. Dry runs
+ and what the owner says by hand on the Posted screen are not told. The scheduler's notify hook
+ ([ADR 0007](0007-scheduling.md)) runs the token and pool checks after each slot; a timer runs
+ them every minute too.
+- **The token event repeats once a day until fixed.** It fires while the known expiry is within
+ 7 days, or once Instagram refuses the token. A token whose expiry is unknown (never refreshed)
+ is told only once refused: its expiry is never guessed.
+- **The pool event fires once per crossing.** It fires when the pool drops below the threshold
+ (10 by default, 1 to 10,000), and again only after the pool has been back at or above it. A
+ crossing while the event is off is not sent later.
+- **Delivery is best effort and never holds up a post.** Each channel gets up to three tries
+ (waits of 2 and 10 seconds) for no answer, a timeout of 10 seconds, a 5xx or a 429; any other
+ answer fails at once. Sending runs in the background and never throws into the publisher or
+ the scheduler. Redirects are not followed and the answer's body is never read. Each channel's
+ last error is shown in Settings in words without its URL; the latest 20 notices are kept.
+- **Channel secrets are written, never read back.** URLs must be http or https with no user name
+ or password. Settings shows the ntfy server, the first three characters of the topic, whether
+ an access token is set, and only the scheme and host of the webhook URL. They are kept in the
+ settings table with everything else the UI sets, so no migration was needed.
+- **A backup is a snapshot made by `VACUUM INTO`** from the app's own connection: a read
+ transaction, so the copy is consistent while Selects runs and holds everything committed,
+ WAL included. It is written into an empty owner-only temporary file in `backups` in the data
+ volume and renamed to `selects-YYYY-MM-DD.db`, by its date in the install's timezone (the
+ schedule's); a second copy that day replaces the first. Seven are kept.
+- **A backup runs whenever the latest 03:30 in the install's timezone has none**: nightly, and at
+ start after a stop. A failure is shown in Settings with its kind only and tried again an hour
+ later. One runs at a time. The last copy's time is read from the files, not the database, so a
+ restored database never misreports it.
+
+## Consequences
+
+- Nobody learns of a fake-mode post through a notification, and a channel can only be proven
+ against its real server with `INSTAGRAM_API=live`.
+- A notice tells the owner to open Selects; it never shows which photo.
+- A channel that fails all three tries (about 12 seconds of waits between them) misses that notice.
+- A restored copy brings back the state of that night: a select posted since is back in the pool.
+ The README says to pause posting and check before the next slot.
+- Notification settings and backups add no environment variable.
From 62c13570316e92dbf2bb4c2229e034443b9db82f Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 11:43:10 +0000
Subject: [PATCH 08/13] fix(server): word the test notice for either channel
---
server/src/notify.test.ts | 2 +-
server/src/notify.ts | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/server/src/notify.test.ts b/server/src/notify.test.ts
index e15b9ca..a2d76ff 100644
--- a/server/src/notify.test.ts
+++ b/server/src/notify.test.ts
@@ -93,7 +93,7 @@ describe("ntfy", () => {
expect(JSON.parse(request?.body ?? "")).toMatchObject({
topic: TOPIC,
title: "Selects test",
- message: "Notifications from Selects reach this topic.",
+ message: "A test notice from Selects: notifications arrive here.",
});
});
});
diff --git a/server/src/notify.ts b/server/src/notify.ts
index f74cdc2..a2a4a70 100644
--- a/server/src/notify.ts
+++ b/server/src/notify.ts
@@ -206,7 +206,7 @@ async function post(url: string, body: unknown, headers: Record,
const TEST_NOTICE: Notice = {
event: "test",
title: "Selects test",
- message: "Notifications from Selects reach this topic.",
+ message: "A test notice from Selects: notifications arrive here.",
};
// An unexpected error is told without its message, which may hold the URL, and tried again.
From b6cf77e78727c698303354a43c121f3c98a4ca13 Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 11:46:02 +0000
Subject: [PATCH 09/13] refactor(web): drop fragments left around single
children
---
web/src/components/notification-settings.tsx | 56 +++++++++-----------
1 file changed, 24 insertions(+), 32 deletions(-)
diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx
index eabba0d..e7041e5 100644
--- a/web/src/components/notification-settings.tsx
+++ b/web/src/components/notification-settings.tsx
@@ -378,23 +378,19 @@ function NtfyChannel({
+ ) : channel === null ? (
+
- ) : (
-
-
-
-
- )}
- >
+
+
+
+
)}
);
From 343c44489f7482c57a7afc354ae73c8b4de4c841 Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 12:08:16 +0000
Subject: [PATCH 10/13] fix(server): start paused on a restored copy, refuse a
notice aimed at Selects itself and show less of the ntfy channel
---
.env.example | 4 +++
README.md | 27 ++++++++++++++------
docs/adr/0009-notifications-and-backups.md | 8 +++++-
server/src/app.ts | 4 ++-
server/src/backup.ts | 11 ++++++--
server/src/config.test.ts | 11 ++++++++
server/src/config.ts | 12 +++++++++
server/src/main.ts | 7 ++++-
server/src/notify.test.ts | 16 +++++++++++-
server/src/notify.ts | 18 +++++++++----
server/src/publisher.test.ts | 22 ++++++++++++++++
server/src/publisher.ts | 14 +++++++++-
web/src/components/backup-status.tsx | 4 +--
web/src/components/notification-settings.tsx | 25 ++++++++++++------
14 files changed, 153 insertions(+), 30 deletions(-)
diff --git a/.env.example b/.env.example
index 59345be..df8351a 100644
--- a/.env.example
+++ b/.env.example
@@ -12,6 +12,10 @@ PORT=3000
# The password page belongs to `bun run start`; leave this empty under `bun run dev`.
SELECTS_PASSWORD=
+# Optional. `true` starts Selects with posting paused, and holds any post that was under way for
+# you to check. Set it for the first start on a restored backup, then remove it.
+SELECTS_START_PAUSED=
+
# Which Instagram to publish to: `fake` (the default) or `live`.
# `fake` runs the fake Instagram server and a fake bucket inside Selects and ignores the bucket
# below: nothing leaves the install and nothing is posted for real. Set `live` only on the
diff --git a/README.md b/README.md
index c2bda31..71fb955 100644
--- a/README.md
+++ b/README.md
@@ -131,14 +131,25 @@ To restore a copy:
(`chmod 600 selects.db`).
4. Remove `selects.db-wal` and `selects.db-shm`. They belong to the database you replaced, and
SQLite would apply them to the copy.
-5. Start Selects.
-
-The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and are
-not part of a copy. Restoring takes the library, posts, schedule and settings back to the night
-of the copy. A select posted since then is back in the pool and could be posted again, so as
-soon as Selects starts, turn on the pause switch on the Queue screen, compare the Posted screen
-with Instagram, and delete from the Library any select already on Instagram (its hash is kept,
-so it is never picked again). Then turn the pause switch off.
+5. Start Selects with `SELECTS_START_PAUSED=true`. It starts with posting paused, and a post
+ that was under way when the copy was made is held on the Posted screen for you to check
+ instead of being sent again. Without this, a slot that is due could post before you get to
+ the pause switch.
+
+Restoring takes the library, posts, schedule, settings, Instagram token and notification
+channels back to the night of the copy. Before you resume:
+
+- A select posted since the copy is back in the pool and could be posted again. The Posted
+ screen shows only what the copy knew of, so compare your Instagram feed with the Library and
+ delete from the Library any select already on Instagram (its hash is kept, so it is never
+ picked again).
+- The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and
+ are not part of a copy. A select added since the copy is no longer in the library though its
+ file is still on disk; upload it again.
+- If the token was replaced since the copy, paste the current one in Settings.
+
+Then remove `SELECTS_START_PAUSED`, so a later restart does not pause again, and turn the pause
+switch off on the Queue screen.
## Checks
diff --git a/docs/adr/0009-notifications-and-backups.md b/docs/adr/0009-notifications-and-backups.md
index fe33380..1cf0f90 100644
--- a/docs/adr/0009-notifications-and-backups.md
+++ b/docs/adr/0009-notifications-and-backups.md
@@ -16,7 +16,7 @@ a copy holds the Instagram token, so each choice leans towards sending and keepi
- **A notice says what happened, and nothing about the photo.** It never carries coordinates, a
file name, a caption or a link. Posted: that a select was posted, and how many are left in the
- pool. Failed: that a post failed and its select is back in the pool, or that Instagram has not
+ pool. Failed: that a post failed for good, or that Instagram has not
said whether it published one. Token: that the token expires in so many days (and could not be
refreshed), or that Instagram no longer accepts it. Pool: how many selects are left, below the
threshold. ntfy gets `topic`, `title`, `message` and the event as a tag, as JSON to the server's
@@ -54,6 +54,12 @@ a copy holds the Instagram token, so each choice leans towards sending and keepi
later. One runs at a time. The last copy's time is read from the files, not the database, so a
restored database never misreports it.
+- **A restored copy starts paused.** `SELECTS_START_PAUSED=true` starts Selects with posting
+ paused and holds every post that was under way as needing a check, so nothing in a restored
+ copy is posted or sent again before its owner has compared it with Instagram.
+- **A notice is never taken by Selects itself.** Each carries a header that Selects refuses, so
+ a webhook set to the app's own address cannot call it in a loop.
+
## Consequences
- Nobody learns of a fake-mode post through a notification, and a channel can only be proven
diff --git a/server/src/app.ts b/server/src/app.ts
index 2ba1b60..f2aa409 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -25,7 +25,7 @@ import { galleryRoutes } from "./gallery-routes";
import { createInstagramApi, type InstagramApi, InstagramError, LIVE_INSTAGRAM_URL } from "./instagram";
import { createInstagramAccount } from "./instagram-account";
import { createLibrary, duplicateMessage, errorKind, type Library } from "./library";
-import { createNotifier } from "./notify";
+import { createNotifier, NOTICE_HEADER } from "./notify";
import { notifyRoutes } from "./notify-routes";
import { passwordGate } from "./password";
import { publishRoutes } from "./publish-routes";
@@ -497,6 +497,8 @@ export function createApp(options: AppOptions) {
backups: services.backups,
fetch: async (request: Request): Promise => {
if (isCrossOrigin(request)) return Response.json({ error: "Forbidden" }, { status: 403 });
+ // A notice of Selects' own, aimed back at it by a webhook set to its own address.
+ if (request.headers.has(NOTICE_HEADER)) return Response.json({ error: "Forbidden" }, { status: 403 });
return (await gate?.(request)) ?? routes.handle(request);
},
};
diff --git a/server/src/backup.ts b/server/src/backup.ts
index 86ec760..ee62fc8 100644
--- a/server/src/backup.ts
+++ b/server/src/backup.ts
@@ -24,7 +24,7 @@ export const BACKUP_TIME = "03:30";
const RETRY_AFTER_MS = HOUR;
const COPY_NAME = /^selects-\d{4}-\d{2}-\d{2}\.db$/;
-const TEMPORARY = /^\.selects-.*\.tmp$/;
+const TEMPORARY = /^\.selects-.*\.tmp(-journal)?$/;
export type BackupCopy = { name: string; at: number; bytes: number };
@@ -95,6 +95,8 @@ export function createBackups(options: BackupsOptions) {
const now = clock.now();
const name = `selects-${localDate(now, timeZone())}.db`;
mkdirSync(dir, { recursive: true, mode: 0o700 });
+ // A folder that was already there keeps its mode otherwise.
+ chmodSync(dir, 0o700);
// Leftovers of a copy a stop interrupted.
for (const found of readdirSync(dir)) {
if (TEMPORARY.test(found)) rmSync(join(dir, found), { force: true });
@@ -111,7 +113,12 @@ export function createBackups(options: BackupsOptions) {
rmSync(temporary, { force: true });
throw error;
}
- for (const old of listCopies().slice(BACKUPS_KEPT)) rmSync(join(dir, old.name), { force: true });
+ // The copy is made: a copy too many that cannot be removed now goes on the next night.
+ try {
+ for (const old of listCopies().slice(BACKUPS_KEPT)) rmSync(join(dir, old.name), { force: true });
+ } catch (error) {
+ console.error(`An old backup could not be removed (${errorKind(error)}).`);
+ }
}
function run(): Promise {
diff --git a/server/src/config.test.ts b/server/src/config.test.ts
index b8d0fc3..b790366 100644
--- a/server/src/config.test.ts
+++ b/server/src/config.test.ts
@@ -171,3 +171,14 @@ describe("loadConfig: the fake bucket", () => {
expect(loadConfig({ ...minimal, BUCKET_PUBLIC_URL: "https://cdn.test" }).fakePublicUrl).toBe(true);
});
});
+
+describe("starting paused", () => {
+ test("is off unless SELECTS_START_PAUSED says true, and anything else is refused by name", () => {
+ expect(loadConfig({ DATA_DIR: "/data" }).startPaused).toBe(false);
+ expect(loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "true" }).startPaused).toBe(true);
+ expect(loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "false" }).startPaused).toBe(false);
+ expect(() => loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "maybe" })).toThrow(
+ /SELECTS_START_PAUSED/,
+ );
+ });
+});
diff --git a/server/src/config.ts b/server/src/config.ts
index 2ed94a2..e7adda2 100644
--- a/server/src/config.ts
+++ b/server/src/config.ts
@@ -55,6 +55,11 @@ export class Config {
* of its own, so gallery output can be tried; the variable's value is not used.
*/
readonly fakePublicUrl = false,
+ /**
+ * Start with posting paused and posts that were under way held for checking. For the first
+ * start on a restored copy, whose selects may have been posted since it was made.
+ */
+ readonly startPaused = false,
) {
this.#password = password;
}
@@ -110,6 +115,12 @@ export function loadConfig(env: Env): Config {
problems.push("INSTAGRAM_API must be fake or live");
}
+ const rawPaused = read("SELECTS_START_PAUSED");
+ const startPaused = rawPaused === "true" || rawPaused === "1";
+ if (rawPaused !== undefined && !startPaused && rawPaused !== "false" && rawPaused !== "0") {
+ problems.push("SELECTS_START_PAUSED must be true or false");
+ }
+
if (problems.length > 0 || dataDir === undefined) {
throw new ConfigError(`Invalid configuration:\n - ${problems.join("\n - ")}`);
}
@@ -121,6 +132,7 @@ export function loadConfig(env: Env): Config {
bucket,
instagram,
read("BUCKET_PUBLIC_URL") !== undefined,
+ startPaused,
);
}
diff --git a/server/src/main.ts b/server/src/main.ts
index 12edfd7..8ce2ec1 100644
--- a/server/src/main.ts
+++ b/server/src/main.ts
@@ -51,11 +51,16 @@ const app = createApp({
fakeBucket: fakes?.bucket,
});
// Posts a stop left mid-attempt are taken up again, before any request can start a new one.
-app.publisher.recover();
+app.publisher.recover({ hold: config.startPaused });
// Posts a stop left recorded for the gallery and not yet taken in, before any frame is cleaned up.
// In fake mode the fake bucket starts empty: the gallery writes again what it lost.
app.gallery.recover({ bucketEmptied: config.instagram === "fake" });
// Slots a stop left part way are settled before the schedule runs: never posted twice.
+// Asked to start paused, as on a restored copy: no slot posts until its owner resumes.
+if (config.startPaused) {
+ app.scheduler.setPaused(true);
+ console.log("Started with posting paused (SELECTS_START_PAUSED). Resume on the Queue screen.");
+}
app.scheduler.recover();
const server = Bun.serve({
diff --git a/server/src/notify.test.ts b/server/src/notify.test.ts
index a2d76ff..03d2c53 100644
--- a/server/src/notify.test.ts
+++ b/server/src/notify.test.ts
@@ -255,7 +255,7 @@ describe("events", () => {
{
event: "failed",
title: "A post failed",
- message: "A post failed and its select is back in the pool. The Posted screen says why.",
+ message: "A post failed for good. The Posted screen says why.",
},
{
event: "failed",
@@ -416,6 +416,20 @@ describe("token about to expire", () => {
});
describe("pool running low", () => {
+ test("a pool already low before any channel is set is told once a channel is", async () => {
+ const recorded = recordingChannels();
+ const notifier = notifierWith({ channels: recorded.channels, poolSize: () => 0 });
+ notifier.check();
+ await notifier.idle();
+ expect(recorded.sent).toHaveLength(0);
+
+ notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null });
+ notifier.check();
+ await notifier.idle();
+
+ expect(recorded.sent.map(({ notice }) => notice.event)).toEqual(["pool"]);
+ });
+
test("notifies once when the pool drops below the threshold, and again only after it has gone back up", async () => {
const recorded = recordingChannels();
let pool = 11;
diff --git a/server/src/notify.ts b/server/src/notify.ts
index a2a4a70..c323148 100644
--- a/server/src/notify.ts
+++ b/server/src/notify.ts
@@ -175,12 +175,15 @@ export function httpChannels(stored: Stored, http: HttpOptions): Channel[] {
* POSTs JSON. Redirects are not followed, the answer's body is never read, and every failure
* is told in words without the URL.
*/
+/** Marks a request as a notice from Selects, so Selects refuses one aimed at itself. */
+export const NOTICE_HEADER = "x-selects-notice";
+
async function post(url: string, body: unknown, headers: Record, http: HttpOptions) {
let response: Response;
try {
response = await fetch(url, {
method: "POST",
- headers: { "content-type": "application/json", ...headers },
+ headers: { "content-type": "application/json", [NOTICE_HEADER]: "1", ...headers },
body: JSON.stringify(body),
redirect: "manual",
signal: AbortSignal.timeout(http.timeoutMs),
@@ -233,6 +236,10 @@ export function createNotifier(options: NotifierOptions) {
"INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
).run(key, JSON.stringify(value));
};
+ const hasChannel = () => {
+ const { ntfy, webhook } = read();
+ return ntfy !== null || webhook !== null;
+ };
const read = (): Stored => {
const saved = readKey(KEY);
return { ntfy: saved.ntfy ?? null, webhook: saved.webhook ?? null };
@@ -350,7 +357,7 @@ export function createNotifier(options: NotifierOptions) {
send({
event: "failed",
title: "A post failed",
- message: "A post failed and its select is back in the pool. The Posted screen says why.",
+ message: "A post failed for good. The Posted screen says why.",
});
} else {
send({
@@ -382,7 +389,8 @@ export function createNotifier(options: NotifierOptions) {
const pool = options.poolSize();
const { poolThreshold } = events();
if (pool >= poolThreshold) state.poolLow = false;
- else if (!state.poolLow) {
+ else if (!state.poolLow && hasChannel()) {
+ // Marked only once there is a channel to tell: a crossing before one is set is told then.
state.poolLow = true;
send({
event: "pool",
@@ -419,8 +427,8 @@ export function createNotifier(options: NotifierOptions) {
ntfy === null
? null
: {
- server: ntfy.server,
- topic: `${ntfy.topic.slice(0, 3)}…`,
+ server: shownUrl(ntfy.server),
+ topic: ntfy.topic.length > 6 ? `${ntfy.topic.slice(0, 3)}…` : "…",
token: ntfy.token !== null,
...statusOf("ntfy"),
},
diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts
index 5fb3fe5..82bfde4 100644
--- a/server/src/publisher.test.ts
+++ b/server/src/publisher.test.ts
@@ -853,6 +853,28 @@ describe("a publish interrupted part way", () => {
expect(post?.permalink).toBe(instagram.media[0]?.permalink ?? "missing");
});
+ test("on a start that holds, as on a restored copy, is not sent again and waits to be checked", async () => {
+ const before = setup();
+ await connect(before.account);
+ const id = await addSelect("portrait");
+ instagram.fail("container", "transient");
+ const first = await postNow(before.publisher, id);
+ expect(first.state).toBe("retrying");
+ const requests = instagram.requests.length;
+
+ const { publisher } = setup();
+ publisher.recover({ hold: true });
+ clock.advance(5 * MINUTE);
+ await publisher.runDue();
+
+ expect(publisher.post(first.id)?.state).toBe("unconfirmed");
+ expect(instagram.media).toHaveLength(0);
+ expect(instagram.requests.filter((r) => r.operation === "container")).toHaveLength(
+ instagram.requests.slice(0, requests).filter((r) => r.operation === "container").length,
+ );
+ expect(library.pool()).toEqual([]);
+ });
+
test("by a restart is finished after it, and published once", async () => {
const before = setup();
await connect(before.account);
diff --git a/server/src/publisher.ts b/server/src/publisher.ts
index b066a3b..392fb41 100644
--- a/server/src/publisher.ts
+++ b/server/src/publisher.ts
@@ -1017,7 +1017,19 @@ export function createPublisher(options: PublisherOptions) {
* Takes up posts a stop left mid-attempt: the next `runDue` resumes them. Called once at
* start, before anything is published.
*/
- recover(): void {
+ recover({ hold = false }: { hold?: boolean } = {}): void {
+ if (hold) {
+ // A restored copy: what was under way when it was made has long since ended one way or
+ // the other. Nothing is sent again; each waits for its owner to say what became of it.
+ db.query(
+ `UPDATE posts SET state = 'unconfirmed', next_attempt_at = ?, error = ?
+ WHERE state IN ('publishing', 'retrying')`,
+ ).run(
+ clock.now() + UNCONFIRMED_CHECK_MS,
+ "Selects started on a restored copy while this post was under way. Check Instagram, then say whether it was posted.",
+ );
+ return;
+ }
db.query("UPDATE posts SET state = 'retrying', next_attempt_at = ? WHERE state = 'publishing'").run(
clock.now(),
);
diff --git a/web/src/components/backup-status.tsx b/web/src/components/backup-status.tsx
index 4936ff2..192880b 100644
--- a/web/src/components/backup-status.tsx
+++ b/web/src/components/backup-status.tsx
@@ -40,8 +40,8 @@ export function BackupStatus() {
{status.lastError !== null && (
- The last try failed {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries
- again in an hour.
+ Last try {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries again in an
+ hour.
)}
diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx
index e7041e5..cabe0de 100644
--- a/web/src/components/notification-settings.tsx
+++ b/web/src/components/notification-settings.tsx
@@ -202,7 +202,12 @@ function ChannelFooter({
Last sent {formatTime(status.lastSentAt)}.
)}
-
>
) : (
- setConfirm(true)}>
+ setConfirm(true)}
+ >
Remove…
)}
@@ -365,7 +374,7 @@ function NtfyChannel({
kept on this server and never shown again in full. Saving replaces both.
{problems !== undefined && (
-
) : (
- setEditing(true)}>
+ setEditing(true)}>
Change…
@@ -464,7 +473,7 @@ function WebhookChannel({
An http or https URL. Only its scheme and host are shown again: the rest may be a secret.
{problems !== undefined && (
-
) : (
- setEditing(true)}>
+ setEditing(true)}>
Change…
From baee3d7954feaed6bd49bc4371fbbcaf76338a9e Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 12:12:42 +0000
Subject: [PATCH 11/13] fix(server): start the token notice's day only once a
channel is set
---
server/src/notify.ts | 2 ++
1 file changed, 2 insertions(+)
diff --git a/server/src/notify.ts b/server/src/notify.ts
index c323148..a048aa6 100644
--- a/server/src/notify.ts
+++ b/server/src/notify.ts
@@ -381,6 +381,8 @@ export function createNotifier(options: NotifierOptions) {
if (token === undefined) state.tokenWarnedAt = null;
else if (
events().events.token &&
+ // Counted only once there is a channel to tell, like the pool below.
+ hasChannel() &&
(state.tokenWarnedAt === null || now - state.tokenWarnedAt >= TOKEN_REPEAT_MS)
) {
send(token);
From 77be853c43262c40fccb59d7b6d4515587a1e251 Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 12:24:29 +0000
Subject: [PATCH 12/13] fix(server): leave a restored post held until its owner
says what became of it
---
server/src/backup.ts | 9 +++++++--
server/src/publisher.test.ts | 7 +++++--
server/src/publisher.ts | 5 +++--
3 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/server/src/backup.ts b/server/src/backup.ts
index ee62fc8..b191109 100644
--- a/server/src/backup.ts
+++ b/server/src/backup.ts
@@ -78,8 +78,13 @@ export function createBackups(options: BackupsOptions) {
.sort()
.reverse()
.flatMap((name) => {
- const stats = statSync(join(dir, name), { throwIfNoEntry: false });
- return stats?.isFile() ? [{ name, at: stats.mtimeMs, bytes: stats.size }] : [];
+ // A folder that can be listed but not looked into leaves its copies unknown, not a crash.
+ try {
+ const stats = statSync(join(dir, name), { throwIfNoEntry: false });
+ return stats?.isFile() ? [{ name, at: stats.mtimeMs, bytes: stats.size }] : [];
+ } catch {
+ return [];
+ }
});
}
diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts
index 82bfde4..64cecb4 100644
--- a/server/src/publisher.test.ts
+++ b/server/src/publisher.test.ts
@@ -864,8 +864,11 @@ describe("a publish interrupted part way", () => {
const { publisher } = setup();
publisher.recover({ hold: true });
- clock.advance(5 * MINUTE);
- await publisher.runDue();
+ // Well past the time an unconfirmed post is checked on its own: this one never is.
+ for (let i = 0; i < 6; i++) {
+ clock.advance(5 * MINUTE);
+ await publisher.runDue();
+ }
expect(publisher.post(first.id)?.state).toBe("unconfirmed");
expect(instagram.media).toHaveLength(0);
diff --git a/server/src/publisher.ts b/server/src/publisher.ts
index 392fb41..a63a73c 100644
--- a/server/src/publisher.ts
+++ b/server/src/publisher.ts
@@ -1022,10 +1022,11 @@ export function createPublisher(options: PublisherOptions) {
// A restored copy: what was under way when it was made has long since ended one way or
// the other. Nothing is sent again; each waits for its owner to say what became of it.
db.query(
- `UPDATE posts SET state = 'unconfirmed', next_attempt_at = ?, error = ?
+ `UPDATE posts SET state = 'unconfirmed', next_attempt_at = NULL, error = ?
WHERE state IN ('publishing', 'retrying')`,
).run(
- clock.now() + UNCONFIRMED_CHECK_MS,
+ // No time for a check of its own: the container the copy knew may have been replaced
+ // since, so only its owner can say what became of it.
"Selects started on a restored copy while this post was under way. Check Instagram, then say whether it was posted.",
);
return;
From 79e67a19bea58262be25add804f443cc5d47ffab Mon Sep 17 00:00:00 2001
From: Brandon Ly
Date: Fri, 13 Nov 2026 12:27:17 +0000
Subject: [PATCH 13/13] test(server): a restored post with a container is never
checked on its own
---
server/src/publisher.test.ts | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts
index 64cecb4..0e3a57e 100644
--- a/server/src/publisher.test.ts
+++ b/server/src/publisher.test.ts
@@ -878,6 +878,30 @@ describe("a publish interrupted part way", () => {
expect(library.pool()).toEqual([]);
});
+ test("on a start that holds, a post with a container is never checked on its own", async () => {
+ const before = setup();
+ await connect(before.account);
+ const id = await addSelect("portrait");
+ // The container is made, then checking on it fails: the copy knows a container.
+ instagram.fail("status", "transient");
+ const first = await postNow(before.publisher, id);
+ expect(first.state).toBe("retrying");
+
+ const { publisher } = setup();
+ publisher.recover({ hold: true });
+ const statusChecks = () => instagram.requests.filter((r) => r.operation === "status").length;
+ const checked = statusChecks();
+ for (let i = 0; i < 6; i++) {
+ clock.advance(5 * MINUTE);
+ await publisher.runDue();
+ }
+
+ expect(statusChecks()).toBe(checked);
+ expect(publisher.post(first.id)?.state).toBe("unconfirmed");
+ expect(instagram.media).toHaveLength(0);
+ expect(library.pool()).toEqual([]);
+ });
+
test("by a restart is finished after it, and published once", async () => {
const before = setup();
await connect(before.account);