diff --git a/scripts/install-hetzner-crons.sh b/scripts/install-hetzner-crons.sh index 1983b2be2..bfd33d5a8 100755 --- a/scripts/install-hetzner-crons.sh +++ b/scripts/install-hetzner-crons.sh @@ -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" </dev/null 2>&1 done diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx index 6ebdca561..7e71db232 100644 --- a/src/app/(app)/settings/page.tsx +++ b/src/app/(app)/settings/page.tsx @@ -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} /> ); diff --git a/src/app/api/crons/orangecat-promote-backfill/route.ts b/src/app/api/crons/orangecat-promote-backfill/route.ts new file mode 100644 index 000000000..39bab00a4 --- /dev/null +++ b/src/app/api/crons/orangecat-promote-backfill/route.ts @@ -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 = { 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> = [ + () => + 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 }); +} diff --git a/src/components/settings/AccountSettings.tsx b/src/components/settings/AccountSettings.tsx index 918507862..6ca13f60c 100644 --- a/src/components/settings/AccountSettings.tsx +++ b/src/components/settings/AccountSettings.tsx @@ -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 = { - 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(null); + const [connecting, setConnecting] = useState(false); const [error, setError] = useState(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 }) { ); })} + {showOrangeCatConnect && ( +
+ + OrangeCat + +
+ )} {error &&

{error}

} ); @@ -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 */}
- +
{/* Set initial password (OAuth-only accounts with no password yet) */} diff --git a/src/components/settings/SettingsTabs.tsx b/src/components/settings/SettingsTabs.tsx index 5165a3118..9f029816b 100644 --- a/src/components/settings/SettingsTabs.tsx +++ b/src/components/settings/SettingsTabs.tsx @@ -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 )} {activeTab === "account" && ( - + )} {activeTab === "notifications" && ( diff --git a/src/db/queries/user-projects.ts b/src/db/queries/user-projects.ts index f56c1d6cb..5af299989 100644 --- a/src/db/queries/user-projects.ts +++ b/src/db/queries/user-projects.ts @@ -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); } /** diff --git a/src/lib/integrations/orangecat-publish.ts b/src/lib/integrations/orangecat-publish.ts index ac4a48c15..c4215cb33 100644 --- a/src/lib/integrations/orangecat-publish.ts +++ b/src/lib/integrations/orangecat-publish.ts @@ -117,19 +117,22 @@ interface PromoteContent { content?: Record; } +/** 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 { +): Promise { 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 { 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]