feat(bridge): promote backfill cron + settings Connect OrangeCat

Closes the two operational gaps in bridge Parts A/C (FC master plan
Phase 0.4/0.5):

- /api/crons/orangecat-promote-backfill re-emits project_published +
  recent devlog promotes for every OC-linked project daily (09:00 UTC
  timer added to install-hetzner-crons.sh). Deterministic external ids
  make re-posting idempotent — 'best-effort must not mean silently
  lossy' is now true.
- promoteMomentToOrangeCat/promoteDevLogEntry return a PromoteOutcome
  so the janitor can count posted/skipped/failed (user-action call
  sites still fire-and-forget via void).
- Settings → Account gains a Connect OrangeCat row for existing users
  (env-gated like the sign-in button); links via the same OIDC flow,
  which also unlocks Publish to OrangeCat.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mao NakamotoandClaude Fable 5 committed 2026-07-02 19:40:15 +02:00
1 parent 5253c156a7
commit d9b784d33f
7 files changed
+158 -23

No files matched your search

+2 -2
View File
@@ -41,7 +41,7 @@ Type=oneshot
ExecStart=/opt/fleetcrown/fc-cron.sh %i
SVC
declare -A SCHED=( [prune-debug-logs]="03:00" [nudge-idle]="04:00" [prune-agent-tokens]="05:00" [email-canary]="06:00" [send-digest-emails]="07:00" [frontier-digest]="08:00" )
declare -A SCHED=( [prune-debug-logs]="03:00" [nudge-idle]="04:00" [prune-agent-tokens]="05:00" [email-canary]="06:00" [send-digest-emails]="07:00" [frontier-digest]="08:00" [orangecat-promote-backfill]="09:00" )
for name in "${!SCHED[@]}"; do
cat > "/etc/systemd/system/fc-cron@${name}.timer" <<TIMER
[Unit]
@@ -58,7 +58,7 @@ TIMER
done
systemctl daemon-reload
for name in prune-debug-logs nudge-idle prune-agent-tokens email-canary send-digest-emails frontier-digest; do
for name in prune-debug-logs nudge-idle prune-agent-tokens email-canary send-digest-emails frontier-digest orangecat-promote-backfill; do
systemctl enable --now "fc-cron@${name}.timer" >/dev/null 2>&1
done
+2
View File
@@ -7,6 +7,7 @@ import { getUserPreferences } from "@/db/queries/user-preferences";
import { SettingsTabs } from "@/components/settings/SettingsTabs";
import { PageLayout } from "@/components/ui/page-layout";
import { isStripeReady } from "@/lib/stripe";
import { getEnabledAuthProviders } from "@/lib/auth-providers";
import { getProjectLimit, isUnlimitedProjects } from "@/lib/plan";
import { ROUTES } from "@/config/auth";
@@ -54,6 +55,7 @@ export default async function SettingsPage() {
teamProjects={teamProjects}
projectLimit={user.isDefault || isUnlimitedProjects(user.plan) ? null : getProjectLimit(user.plan)}
invitations={invitations}
orangecatEnabled={getEnabledAuthProviders().orangecat}
/>
</PageLayout>
);
@@ -0,0 +1,92 @@
// Cron target — OrangeCat promote backfill (bridge Part C reconcile step).
//
// promoteDevLogEntry / promoteMomentToOrangeCat are fire-and-forget at the
// user-action call sites: a process restart, OC downtime, or an expired token
// drops the promote silently. The bridge spec's rule is "best-effort must not
// mean silently lossy" — this janitor makes that true by re-emitting recent
// publish-worthy moments for every OC-linked project. External ids are
// deterministic (sha256 of the entry / stable project id), so re-posting is
// idempotent: OrangeCat reconciles on (source, external_id) and returns 200
// instead of double-posting.
//
// Schedule: daily at 09:00 UTC (systemd timer, scripts/install-hetzner-crons.sh).
import { type NextRequest, NextResponse } from "next/server";
import { and, eq, isNotNull } from "drizzle-orm";
import { db } from "@/db";
import { userProjects } from "@/db/schema";
import type { DevLogEntry } from "@/db/schema/user-projects";
import { requireCronAuth } from "@/lib/cron-auth";
import { logDebug } from "@/db/queries/debug-logs";
import {
promoteDevLogEntry,
promoteMomentToOrangeCat,
type PromoteOutcome,
} from "@/lib/integrations/orangecat-publish";
/** Only re-emit devlog entries this recent — older wall history is settled. */
const BACKFILL_WINDOW_DAYS = 14;
/** Cap re-emits per tick so a misconfig can't hammer the OC publish bus. */
const MAX_PROMOTES_PER_TICK = 50;
export async function GET(req: NextRequest) {
const denied = requireCronAuth(req);
if (denied) return denied;
const cutoff = new Date(Date.now() - BACKFILL_WINDOW_DAYS * 24 * 60 * 60 * 1000)
.toISOString()
.slice(0, 10);
const linked = await db
.select({
id: userProjects.id,
userId: userProjects.userId,
name: userProjects.name,
description: userProjects.description,
devLog: userProjects.devLog,
orangecatProjectId: userProjects.orangecatProjectId,
})
.from(userProjects)
.where(and(isNotNull(userProjects.orangecatProjectId), eq(userProjects.isActive, true)));
const counts: Record<PromoteOutcome, number> = { posted: 0, skipped: 0, failed: 0 };
let attempted = 0;
let capped = false;
outer: for (const project of linked) {
// The "went public" moment first — it anchors the wall if the original
// fire-and-forget emit was dropped during the publish call.
const moments: Array<() => Promise<PromoteOutcome>> = [
() =>
promoteMomentToOrangeCat(project.userId, project.id, "project_published", {
externalId: `fleetcrown_project_published_${project.id}`,
title: `${project.name} is now building in public`,
description: project.description ?? undefined,
subjectId: project.orangecatProjectId ?? undefined,
}),
...((project.devLog ?? []) as DevLogEntry[])
.filter((entry) => entry.date >= cutoff)
.map((entry) => () => promoteDevLogEntry(project.userId, project.id, project.name, entry)),
];
// Sequential on purpose: this is a janitor, not a hot path — one in-flight
// request to the OC bus at a time.
for (const emit of moments) {
if (attempted >= MAX_PROMOTES_PER_TICK) {
capped = true;
break outer;
}
attempted++;
counts[await emit()]++;
}
}
const summary = { projects: linked.length, attempted, ...counts, capped };
await logDebug({
source: "crons/orangecat-promote-backfill",
level: counts.failed > 0 ? "warn" : "info",
message: "backfill tick",
meta: summary,
});
return NextResponse.json({ ok: true, ...summary });
}
+40 -7
View File
@@ -2,7 +2,8 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, GitBranch, X as XIcon, Globe, Trash2 } from "lucide-react";
import { signIn } from "next-auth/react";
import { Loader2, GitBranch, X as XIcon, Globe, Trash2, Cat } from "lucide-react";
import { patchJson, postJson, deleteJson } from "@/lib/api/fetch";
import { useFetch } from "@/hooks/use-fetch";
import { TOAST_MEDIUM_MS } from "@/lib/constants/timings";
@@ -10,17 +11,34 @@ import { TOAST_MEDIUM_MS } from "@/lib/constants/timings";
type ConnectedAccount = { provider: string; providerAccountId: string };
const PROVIDER_META: Record<string, { label: string; icon: React.ElementType }> = {
github: { label: "GitHub", icon: GitBranch },
google: { label: "Google", icon: Globe },
twitter: { label: "Twitter/X", icon: XIcon },
github: { label: "GitHub", icon: GitBranch },
google: { label: "Google", icon: Globe },
twitter: { label: "Twitter/X", icon: XIcon },
orangecat: { label: "OrangeCat", icon: Cat },
};
function ConnectedAccountsSection({ hasPassword }: { hasPassword: boolean }) {
function ConnectedAccountsSection({ hasPassword, orangecatEnabled }: { hasPassword: boolean; orangecatEnabled: boolean }) {
const { data, refetch } = useFetch<{ accounts: ConnectedAccount[] }>("/api/me/connected-accounts");
const [disconnecting, setDisconnecting] = useState<string | null>(null);
const [connecting, setConnecting] = useState(false);
const [error, setError] = useState<string | null>(null);
const connectedAccounts = data?.accounts ?? [];
// Bridge Part A settings-connect: existing FC users link their OrangeCat
// identity here (the sign-in button only covers the login page). The OIDC
// round-trip carries the capability scopes, so a successful link also
// unlocks Publish to OrangeCat — no separate API-key step.
const showOrangeCatConnect =
orangecatEnabled && !connectedAccounts.some((a) => a.provider === "orangecat");
const connectOrangeCat = async () => {
setConnecting(true);
setError(null);
// Auth.js links by verified-email match (allowDangerousEmailAccountLinking);
// an OC account with a DIFFERENT email signs into that other FC user
// instead of linking — same behavior as the sign-in page button.
await signIn("orangecat", { callbackUrl: "/settings#account" });
};
const disconnect = async (provider: string) => {
setDisconnecting(provider);
@@ -68,6 +86,19 @@ function ConnectedAccountsSection({ hasPassword }: { hasPassword: boolean }) {
</div>
);
})}
{showOrangeCatConnect && (
<div className="flex items-center gap-3 rounded-lg border border-border-subtle bg-surface-base px-3 py-2.5">
<Cat className="h-4 w-4 shrink-0 text-text-secondary" />
<span className="flex-1 text-sm text-text-primary">OrangeCat</span>
<button
onClick={connectOrangeCat}
disabled={connecting}
className="ui-btn-xs"
>
{connecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Connect"}
</button>
</div>
)}
{error && <p className="ui-error-xs">{error}</p>}
</div>
);
@@ -157,9 +188,11 @@ function SetInitialPasswordSection() {
type Props = {
user: { email: string | null; hasPassword: boolean };
/** Whether the OrangeCat OIDC provider is mounted (env-gated, server-derived). */
orangecatEnabled: boolean;
};
export function AccountSettings({ user }: Props) {
export function AccountSettings({ user, orangecatEnabled }: Props) {
const [currentPwd, setCurrentPwd] = useState("");
const [newPwd, setNewPwd] = useState("");
const [confirmPwd, setConfirmPwd] = useState("");
@@ -207,7 +240,7 @@ export function AccountSettings({ user }: Props) {
{/* Connected OAuth accounts */}
<div className="space-y-2">
<label className="ui-kicker">Connected accounts</label>
<ConnectedAccountsSection hasPassword={user.hasPassword} />
<ConnectedAccountsSection hasPassword={user.hasPassword} orangecatEnabled={orangecatEnabled} />
</div>
{/* Set initial password (OAuth-only accounts with no password yet) */}
+4 -2
View File
@@ -37,6 +37,8 @@ type Props = {
teamProjects: UserProject[];
projectLimit: number | null;
invitations: Invitation[];
/** Whether the OrangeCat OIDC provider is mounted (env-gated, server-derived). */
orangecatEnabled: boolean;
};
const TABS = [
@@ -75,7 +77,7 @@ function resolveInitialTab(): TabId {
return HASH_TO_TAB[raw] ?? "profile";
}
export function SettingsTabs({ user, userPrefs, projects, teamProjects, projectLimit, invitations }: Props) {
export function SettingsTabs({ user, userPrefs, projects, teamProjects, projectLimit, invitations, orangecatEnabled }: Props) {
// Lazy initializer reads the URL hash once at first render so deep links
// like /settings#agent or /settings#tokens (from RunnerStatusBanner's
// onboarding link) open the right tab. Without this, the banner landed
@@ -111,7 +113,7 @@ export function SettingsTabs({ user, userPrefs, projects, teamProjects, projectL
<ProfileSettings user={{ id: user.id, name: user.name, username: user.username, image: user.image }} />
)}
{activeTab === "account" && (
<AccountSettings user={{ email: user.email, hasPassword: user.hasPassword }} />
<AccountSettings user={{ email: user.email, hasPassword: user.hasPassword }} orangecatEnabled={orangecatEnabled} />
)}
{activeTab === "notifications" && (
<NotificationSettings />
+2 -2
View File
@@ -201,7 +201,7 @@ export async function appendProjectDevLog(
await writeDevLog(project.id, (project.devLog ?? []) as DevLogEntry[], entry);
// Changelog→wall promote step (async, idempotent, non-blocking) — no-ops
// unless the project is published to OrangeCat and the user is linked.
promoteDevLogEntry(userId, project.id, project.name, entry);
void promoteDevLogEntry(userId, project.id, project.name, entry);
}
export async function appendProjectDevLogByEntityProjectId(
@@ -215,7 +215,7 @@ export async function appendProjectDevLogByEntityProjectId(
});
if (!project) return;
await writeDevLog(project.id, (project.devLog ?? []) as DevLogEntry[], entry);
promoteDevLogEntry(userId, project.id, project.name, entry);
void promoteDevLogEntry(userId, project.id, project.name, entry);
}
/**
+16 -10
View File
@@ -117,19 +117,22 @@ interface PromoteContent {
content?: Record<string, unknown>;
}
/** Outcome of a promote attempt — lets the backfill janitor count and report. */
export type PromoteOutcome = "posted" | "skipped" | "failed";
/**
* Promote one publish-worthy moment onto the OrangeCat wall. Fire-and-forget:
* never throws, never blocks the user action; a dropped promote is recoverable
* later by backfill because external ids are deterministic.
* Promote one publish-worthy moment onto the OrangeCat wall. Never throws,
* never blocks the user action (call sites may `void` it); a dropped promote
* is recoverable by the backfill cron because external ids are deterministic.
*/
export async function promoteMomentToOrangeCat(
userId: string,
userProjectId: string,
moment: PromotableMoment,
input: PromoteContent,
): Promise<void> {
): Promise<PromoteOutcome> {
const policy = PROMOTE_POLICY[moment];
if (!policy?.enabled) return;
if (!policy?.enabled) return "skipped";
try {
let subjectId = input.subjectId;
@@ -140,10 +143,10 @@ export async function promoteMomentToOrangeCat(
});
subjectId = project?.orangecatProjectId ?? undefined;
}
if (!subjectId) return; // not published to OC — nothing to promote onto
if (!subjectId) return "skipped"; // not published to OC — nothing to promote onto
const link = await getOrangeCatLink(userId);
if (!link) return;
if (!link) return "skipped";
const res = await fetch(`${OC_BASE}/api/v1/timeline/publish`, {
method: "POST",
@@ -171,29 +174,32 @@ export async function promoteMomentToOrangeCat(
externalId: input.externalId,
status: res.status,
});
return "failed";
}
return "posted";
} catch (err) {
console.warn("[orangecat-publish] promote errored (non-fatal)", {
userProjectId,
moment,
err,
});
return "failed";
}
}
/**
* Promote a freshly appended dev-log entry (the changelog→wall loop).
* Deterministic external id = hash of the entry, so the same entry retried
* never double-posts.
* never double-posts (OC reconciles on source + external_id).
*/
export function promoteDevLogEntry(
userId: string,
userProjectId: string,
projectName: string,
entry: DevLogEntry,
): void {
): Promise<PromoteOutcome> {
const digest = createHash("sha256").update(JSON.stringify(entry)).digest("hex").slice(0, 24);
void promoteMomentToOrangeCat(userId, userProjectId, "devlog_entry", {
return promoteMomentToOrangeCat(userId, userProjectId, "devlog_entry", {
externalId: `fleetcrown_devlog_${userProjectId}_${digest}`,
title: `${projectName}: ${firstLine(entry.done) || "progress update"}`,
description: [entry.done, entry.next ? `Next: ${entry.next}` : null]