diff --git a/app/main.py b/app/main.py
index 2c60c7c..1e4b00d 100644
--- a/app/main.py
+++ b/app/main.py
@@ -2410,28 +2410,39 @@ async def provision_member(email: str, name: str, slug: str = "") -> str:
# email, and the newsletter subscription. NO Loomio/Matrix invites. See the
# constants block for the lapse rules (credit exhaustion + GIFT_DAYS time box).
-def gift_welcome_email(name: str, setup_url: str) -> tuple[str, str, str]:
- """Build the GIFT welcome email — same branded shell as the member welcome.
+def gift_invitation_email(name: str, setup_url: str, inviter_name: str = "") -> tuple[str, str, str]:
+ """Build the gift INVITATION email — the one email a gift sends.
- Says what the recipient can use, that it lasts until the $5 of credits are
- spent (or 60 days pass), carries the Become-a-member button, notes the
- newsletter subscription, and points replies at the co-op inbox. No
- Loomio/Matrix — guests receive no member invitations.
+ This is the gift-time email AND the guest welcome in one: the recipient is
+ invited in (the inviter named), told what the gift gives ($5 of credits,
+ how long access runs), and given the account-setup link. The guest welcome
+ content lives here rather than in a second email — one coherent invitation,
+ not two mails at once. Same branded shell as welcome_email(): cream
+ background, white card, forest-green button, pine mark, no external
+ assets. No Loomio/Matrix — guests receive no member invitations.
"""
- subject = "You've been gifted access to the Inference Cooperative"
+ subject = "You've been invited to the Inference Cooperative"
+ if inviter_name:
+ invited_line = f"{inviter_name} has invited you to the Inference Cooperative"
+ html_invited = f"{inviter_name} has invited you to the Inference Cooperative"
+ else:
+ invited_line = "A member has invited you to the Inference Cooperative"
+ html_invited = "A member has invited you to the Inference Cooperative"
text = (
f"Hi {name},\n\n"
- "A member of the Inference Cooperative has gifted you access!\n\n"
- "Your gift gives you $5 of AI usage across the co-op's chat and API —\n"
- "the same private, renewable-energy models members use. It lasts until\n"
- "the $5 of credits are used up (they don't expire early; your access\n"
- "runs for 60 days from today).\n\n"
- f"To start, create your account — it takes about a minute:\n\n{setup_url}\n\n"
- "When the credits run out (or anytime), you can become a member for\n"
- "$10-20/month, sliding scale — same login, plus a monthly allowance:\n"
+ f"{invited_line}.\n\n"
+ "It's a member-governed AI cooperative that runs open models on\n"
+ "renewable energy.\n\n"
+ "Your invitation comes with $5 of credits for the co-op's chat and\n"
+ f"API. Access runs for {int(GIFT_DAYS)} days from today; the credits\n"
+ "themselves don't expire early.\n\n"
+ "To accept, create your account — it takes about a minute:\n\n"
+ f"{setup_url}\n\n"
+ "If you like it, membership is $15/month: a full monthly allowance,\n"
+ "the co-op's forum and chat community, and a say in how it's run.\n\n"
f"{BECOME_MEMBER_URL}\n\n"
- "You're also on our (low-volume, member) newsletter — a way to hear\n"
- "what the co-op is building. Unsubscribe anytime from any issue.\n\n"
+ "You're also on our low-volume newsletter — unsubscribe anytime\n"
+ "from any issue.\n\n"
"Questions? Just reply to this email — it reaches the co-op directly.\n\n"
"— The Inference Cooperative\n"
)
@@ -2445,27 +2456,20 @@ def gift_welcome_email(name: str, setup_url: str) -> tuple[str, str, str]:
-
+ {PINE_LOGO_SVG}
-
You've been gifted access, {name}
-
A member of the Inference Cooperative has given you $5 of AI usage — the co-op's private, renewable-energy models across chat and the API.
-
Your gift lasts until the $5 of credits are used up (they don't expire early — access runs 60 days from today).
+
You're invited, {name}
+
{html_invited} — a member-governed AI cooperative running open models on renewable energy.
+
Your invitation comes with $5 of credits for the co-op's chat and API. Access runs for {int(GIFT_DAYS)} days from today; the credits themselves don't expire early.
You're also on our (low-volume) newsletter — hear what the co-op is building; unsubscribe anytime.
+
You're also on our low-volume newsletter — unsubscribe anytime from any issue.
@@ -2535,6 +2539,59 @@ def gift_member_congrats_email(name: str, setup_url: str | None) -> tuple[str, s
return subject, text, html
+def gift_limits_email(name: str, reason: str) -> tuple[str, str, str]:
+ """Build the reaching-limits email for a gift account hitting its limit.
+
+ Sent ONCE per guest when the sweep deactivates the gift — either the $5
+ of credits are spent or the GIFT_DAYS time box has run out. Says plainly:
+ the gift access has ended, the account and data are kept, and becoming a
+ member ($15/month via Open Collective) restores access with a full
+ monthly allowance and the community spaces. Same shell as the other gift
+ emails; matter-of-fact and welcoming — no guilt, no upsell.
+ """
+ subject = "Your guest access has ended — become a member to continue"
+ if reason == "depleted":
+ ended = f"Your ${GIFT_BUDGET:g} of gift credits are spent."
+ else:
+ ended = f"The gift's {int(GIFT_DAYS)} days are up."
+ text = (
+ f"Hi {name},\n\n"
+ f"{ended} Your gift access to the Inference Cooperative has ended.\n\n"
+ "Your account and data are kept. If you'd like to continue, become a\n"
+ "member: $15/month through Open Collective restores full access, with\n"
+ "a full monthly allowance and the co-op's community spaces.\n\n"
+ f"{BECOME_MEMBER_URL}\n\n"
+ "Questions? Just reply to this email — it reaches the co-op directly.\n\n"
+ "— The Inference Cooperative\n"
+ )
+ html = f"""
+
+
+
+
+
+
+
+ {PINE_LOGO_SVG}
+
+
+
Your gift access has ended
+
{ended} Your gift access to the Inference Cooperative has ended.
+
Your account and data are kept. If you'd like to continue, become a member — $15/month through Open Collective restores full access, with a full monthly allowance and the co-op's community spaces.
Questions? Reply to this email — it reaches the co-op directly.
+
+
+ The Inference Cooperative · inference.coop
+
+
+
+
+
+"""
+ return subject, text, html
+
+
async def provision_gift_member(email: str, name: str, inviter_email: str) -> str:
"""Provision a GIFT account end-to-end (operator gifting feature).
@@ -2545,7 +2602,8 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st
(budget_duration None — the cap is the gift's whole life);
* the portal row marked account_type='gift' with the $5 held as
non-expiring credit (the credits model) and gift_expires_at set;
- * the gift welcome email (setup link, expiry, Become-a-member) and the
+ * the gift INVITATION email (inviter named, the $5 credits, the setup
+ link — the invitation and the guest welcome in one) and the
newsletter subscription;
* a gifts-ledger row recording inviter → recipient;
* NO Loomio/Matrix invites, no docs-RAG members group.
@@ -2596,7 +2654,19 @@ async def provision_gift_member(email: str, name: str, inviter_email: str) -> st
await sync_team_budget_from_balance(email) # cap = allowance(0) + credits(5)
setup_url = await cloudron_get_invite_link(user_id)
- subject, text, html = gift_welcome_email(name, setup_url)
+ # Name the inviter in the invitation: their member slug (the username the
+ # co-op knows them by — the members table has no display-name column).
+ inviter_name = ""
+ conn = get_db()
+ row = conn.execute(
+ "SELECT slug FROM members WHERE email = ?", (inviter_email.strip().lower(),)
+ ).fetchone()
+ conn.close()
+ if row and row[0]:
+ inviter_name = row[0]
+ # ONE email at gift time: the invitation is also the guest welcome (merged,
+ # not two mails to the same person at once).
+ subject, text, html = gift_invitation_email(name, setup_url, inviter_name)
send_email(email, subject, text, html)
touch_welcome_sent(email)
@@ -2715,6 +2785,86 @@ async def convert_gift_to_member(email: str, name: str, slug: str = "") -> str:
return user_id
+def gift_lapse_notice_sent(email: str) -> bool:
+ """True when the reaching-limits email has already gone out for this guest.
+
+ The once-only gate (same shape as shortfall_notice_sent): one row per
+ guest, ever. The gifts ledger records what became of a gift; this table
+ records what actually left the building.
+ """
+ conn = get_db()
+ _ensure_gift_notice_table(conn)
+ row = conn.execute(
+ "SELECT 1 FROM gift_lapse_notices WHERE email = ? LIMIT 1", (email,)
+ ).fetchone()
+ conn.close()
+ return bool(row)
+
+
+def mark_gift_lapse_notice_sent(email: str, reason: str) -> None:
+ conn = get_db()
+ _ensure_gift_notice_table(conn)
+ conn.execute(
+ "INSERT OR REPLACE INTO gift_lapse_notices (email, reason, sent_at)"
+ " VALUES (?, ?, datetime('now'))",
+ (email, reason),
+ )
+ conn.commit()
+ conn.close()
+
+
+def _ensure_gift_notice_table(conn) -> None:
+ """Records which guests have been told their gift access ended.
+
+ Kept apart from the gifts ledger on purpose: the ledger answers "what was
+ gifted and what became of it", this answers "what left the building". A
+ guest is notified at most once, ever.
+ """
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS gift_lapse_notices ("
+ " email TEXT PRIMARY KEY, reason TEXT NOT NULL,"
+ " sent_at TEXT NOT NULL DEFAULT (datetime('now')))"
+ )
+ conn.commit()
+
+
+async def send_gift_lapse_notice(email: str, user_id: str | None, reason: str) -> bool:
+ """Send the reaching-limits email ONCE per guest.
+
+ Checks the sent-state row before sending and marks it only after the send
+ succeeded — an unmarked guest (send failed, or lapsed before this email
+ shipped) is retried by the sweep's catch-up pass, never double-sent.
+ Returns True when a send actually left the building.
+ """
+ if gift_lapse_notice_sent(email):
+ return False
+ # Greet by name where we can find one: the Cloudron display name, else the
+ # portal slug, else "there" (never the email local part).
+ name = ""
+ if user_id:
+ try:
+ async with httpx.AsyncClient() as client:
+ users = await cloudron_fetch_all_users(client)
+ if users:
+ name = next((u.get("displayName") or "" for u in users
+ if u.get("id") == user_id), "")
+ except Exception as e:
+ logger.warning("Gift lapse notice: name lookup failed for %s: %s", email, e)
+ if not name:
+ conn = get_db()
+ row = conn.execute(
+ "SELECT slug FROM members WHERE email = ?", (email,)
+ ).fetchone()
+ conn.close()
+ if row and row[0]:
+ name = row[0]
+ subject, text_body, html_body = gift_limits_email(name or "there", reason)
+ if send_email(email, subject, text_body, html_body):
+ mark_gift_lapse_notice_sent(email, reason)
+ return True
+ return False
+
+
async def reconcile_gift_lifecycles() -> dict:
"""Lapse gift accounts by their own rules: time box or spent credits.
@@ -2728,10 +2878,12 @@ async def reconcile_gift_lifecycles() -> dict:
KEPT so a returning payer resumes cleanly; the gifts-ledger status records
which rule ended it ('expired' | 'depleted').
- Returns {expired, depleted} counts; never raises past a logged warning.
+ Returns {expired, depleted, lapse_notices} counts; never raises past a
+ logged warning.
"""
expired = 0
depleted = 0
+ notified = 0
conn = get_db()
rows = conn.execute(
"SELECT email, cloudron_user_id, credit_balance, balance, gift_expires_at "
@@ -2780,9 +2932,53 @@ async def reconcile_gift_lifecycles() -> dict:
else:
depleted += 1
logger.info("Gift lifecycle: %s deactivated (%s)", email, reason)
+ # Reaching-limits email: once per guest, ever, sent AFTER the
+ # deactivation committed (never tell someone their access ended
+ # while it hasn't). A failed send stays unmarked and is retried
+ # by the catch-up pass below on a later sweep.
+ try:
+ if await send_gift_lapse_notice(email, user_id, reason):
+ notified += 1
+ except Exception as e:
+ logger.warning("Gift lapse notice failed for %s: %s", email, e)
except Exception as e:
logger.warning("Gift lifecycle: failed for %s: %s", email, e)
- return {"expired": expired, "depleted": depleted}
+ # Catch-up: guests already deactivated (lapsed before this email shipped,
+ # or whose send failed) who were never told. Converted guests are excluded
+ # by the WHERE — their account_type is 'member' now, and a member is never
+ # told their gift ended.
+ conn = get_db()
+ pending = conn.execute(
+ "SELECT email, cloudron_user_id, gift_expires_at FROM members "
+ "WHERE active = 0 AND account_type = 'gift'"
+ ).fetchall()
+ conn.close()
+ for email, user_id, expires_at in pending:
+ if gift_lapse_notice_sent(email):
+ continue
+ try:
+ conn = get_db()
+ grow = conn.execute(
+ "SELECT status FROM gifts WHERE recipient_email = ? "
+ "ORDER BY id DESC LIMIT 1", (email,)
+ ).fetchone()
+ conn.close()
+ reason = grow[0] if grow and grow[0] in ("expired", "depleted") else None
+ if reason is None:
+ # No ledger verdict: read the time box off the row; a row with
+ # no expiry was ended by its credits.
+ try:
+ exp = datetime.fromisoformat(str(expires_at)) if expires_at else None
+ if exp and exp.tzinfo is None:
+ exp = exp.replace(tzinfo=timezone.utc)
+ reason = "expired" if (exp and datetime.now(timezone.utc) >= exp) else "depleted"
+ except ValueError:
+ reason = "depleted"
+ if await send_gift_lapse_notice(email, user_id, reason):
+ notified += 1
+ except Exception as e:
+ logger.warning("Gift lapse catch-up failed for %s: %s", email, e)
+ return {"expired": expired, "depleted": depleted, "lapse_notices": notified}
async def litellm_get_or_create_team(email: str, budget: float,
@@ -5663,6 +5859,7 @@ async def reconcile_memberships() -> dict:
"converted": converted_count,
"gifts_expired": gift_counts.get("expired", 0),
"gifts_depleted": gift_counts.get("depleted", 0),
+ "gift_lapse_notices": gift_counts.get("lapse_notices", 0),
"newsletter_removed": newsletter.get("removed", 0),
}
diff --git a/tests/test_gift_lifecycle.py b/tests/test_gift_lifecycle.py
index 881fd3b..26ebbde 100644
--- a/tests/test_gift_lifecycle.py
+++ b/tests/test_gift_lifecycle.py
@@ -87,8 +87,9 @@ async def rec_pin(team_id, reset_at):
calls["pin"].append((team_id, str(reset_at)))
-def rec_email(to, subject, text_body, html_body=None):
+def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject))
+ return True # send_email's contract: truthy = the send left the building
async def rec_listmonk(email, subscribe):
@@ -242,8 +243,8 @@ def main():
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
check("provision: cap set to 5.00 (one-time)",
(calls["budget"] and calls["budget"][0][1] == 5.0), str(calls["budget"]))
- check("provision: welcome email sent",
- any("gifted access" in s for _, s in calls["email"]), str(calls["email"]))
+ check("provision: invitation email sent (merged invite + welcome)",
+ any("invited to the Inference Cooperative" in s for _, s in calls["email"]), str(calls["email"]))
check("provision: newsletter subscribed",
("gifted@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
@@ -288,9 +289,14 @@ def main():
credits=5.0, anchor=8, expires=future)
seed_member(conn, "depleted@x.org", account_type="gift", active=1, balance=0.0,
credits=5.0, anchor=8, expires=future)
- for e in ("expired@x.org", "healthy@x.org", "depleted@x.org"):
+ # A guest whose gift ended BEFORE the reaching-limits email shipped: the
+ # sweep's catch-up pass must tell them exactly once.
+ seed_member(conn, "already-gone@x.org", account_type="gift", active=0, balance=0.0,
+ credits=5.0, anchor=8, expires=past)
+ for e in ("expired@x.org", "healthy@x.org", "depleted@x.org", "already-gone@x.org"):
conn.execute("INSERT INTO gifts (inviter_email, recipient_email, gift_expires_at, status) "
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
+ conn.execute("UPDATE gifts SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
conn.commit()
conn.close()
@@ -315,6 +321,16 @@ def main():
not any(e == "uid-healthy@x.org" for e, _ in calls["group"]))
check("lifecycle: counts report expired=1 depleted=0",
out.get("expired") == 1 and out.get("depleted") == 0, str(out))
+ check("lifecycle: reaching-limits email sent once to the expired guest",
+ sum(1 for to, s in calls["email"]
+ if to == "expired@x.org" and "guest access has ended" in s) == 1,
+ str(calls["email"]))
+ check("lifecycle: catch-up told the pre-shutdown guest exactly once",
+ sum(1 for to, s in calls["email"]
+ if to == "already-gone@x.org" and "guest access has ended" in s) == 1,
+ str(calls["email"]))
+ check("lifecycle: notice counts in the sweep result",
+ out.get("lapse_notices") == 2, str(out))
conn.close()
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
@@ -329,6 +345,17 @@ def main():
check("lifecycle: healthy gift STILL untouched on second pass",
row_of(conn, "healthy@x.org", "active") == 1)
check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out))
+ check("lifecycle: depleted guest also told once",
+ sum(1 for to, s in calls["email"]
+ if to == "depleted@x.org" and "guest access has ended" in s) == 1,
+ str(calls["email"]))
+ check("lifecycle: ONCE per guest — second sweep sent no repeat notices",
+ sum(1 for to, s in calls["email"] if "guest access has ended" in s) == 1
+ and m.gift_lapse_notice_sent("expired@x.org")
+ and m.gift_lapse_notice_sent("already-gone@x.org"),
+ str(calls["email"]))
+ check("lifecycle: healthy guest never emailed",
+ not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))
conn.close()
failed = [r for r in results if not r[1]]