"""Offline, clean-room Airtable-inspired workspace application.""" from __future__ import annotations import html import json import os import sqlite3 import tempfile import threading from contextlib import contextmanager from pathlib import Path from typing import Any from urllib.parse import urlencode from fastapi import FastAPI, File, HTTPException, Request, UploadFile from fastapi.responses import ( FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, ) from fastapi.staticfiles import StaticFiles import site_business as biz from backend.site_backend_integration import open_site_services from websitebench.local_clone_auth import AuthError ROOT = Path(__file__).resolve().parent RUNTIME_ROOT = Path( os.environ.get( "WEBSITEBENCH_AIRTABLE_RUNTIME_ROOT", str(Path(tempfile.gettempdir()) / "websitebench-airtable-runtime"), ) ).resolve() if ( "WEBSITEBENCH_SITE_BACKEND_DATABASE" not in os.environ and RUNTIME_ROOT.parent.exists() ): os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str( RUNTIME_ROOT / "data" / "airtable.sqlite3" ) VOLUME_ROOT = Path( os.environ.get("WEBSITEBENCH_AIRTABLE_VOLUME_ROOT", str(RUNTIME_ROOT / "volume")) ).resolve() VOLUME_ROOT.mkdir(parents=True, exist_ok=True) app = FastAPI(title="Airtable Offline Workspace", version="1.0.0") app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static") _lock = threading.Lock() _services: tuple[Any, Any] | None = None def services(): global _services if _services is None: with _lock: if _services is None: _services = open_site_services() backend, auth = _services auth.seed_account( subject_id="seed:owner", email="owner@airtable.local", display_name="Avery Owner", password="Conference!2026", ) auth.seed_account( subject_id="seed:member", email="member@airtable.local", display_name="Morgan Member", password="Conference!2026", ) return _services @contextmanager def connection(): _, auth = services() with auth.connect() as conn: conn.row_factory = sqlite3.Row yield conn def loopback(request: Request) -> bool: return request.url.hostname in {"127.0.0.1", "localhost", "::1", "testserver"} def cookie_name(request: Request) -> str: """Keep the runtime's __Host cookie on HTTPS; use an explicit loopback name on HTTP.""" backend, _ = services() return ( "wb-airtable-local-session" if loopback(request) else backend.session_cookie["name"] ) def set_session(response, token: str, request: Request) -> None: response.set_cookie( cookie_name(request), token, secure=not loopback(request), httponly=True, samesite="lax", path="/", ) def session( request: Request, *, create: bool = True ) -> tuple[str | None, dict[str, Any] | None]: _, auth = services() token = request.cookies.get(cookie_name(request)) resolved = auth.resolve_session(token) if token and resolved is not None: account = resolved.get("account") if resolved.get("authenticated") else None return token, account if not create: return None, None token = auth.create_anonymous_session() return token, None def require_account(request: Request) -> tuple[str, dict[str, Any]]: token, account = session(request, create=False) if token is None or account is None or not account.get("account_id"): raise HTTPException(status_code=401, detail="Sign in to continue") return token, account def owner_of(account: dict[str, Any]) -> str: return str(account.get("subject_id") or account["account_id"]) ROLE_CAPABILITIES = { "owner": frozenset({"read", "data", "comment", "schema", "manage"}), "creator": frozenset({"read", "data", "comment", "schema", "manage"}), "editor": frozenset({"read", "data", "comment"}), "commenter": frozenset({"read", "comment"}), "read_only": frozenset({"read"}), } def account_email(account: dict[str, Any]) -> str: return str(account.get("email_normalized") or account.get("email") or "").strip().casefold() def workspace_role( conn: sqlite3.Connection, account: dict[str, Any], workspace_id: str ) -> str | None: workspace = conn.execute( "SELECT owner FROM at_workspaces WHERE id=?", (workspace_id,) ).fetchone() if workspace is None: return None if workspace["owner"] == owner_of(account): return "owner" email_value = account_email(account) if not email_value: return None collaborator = conn.execute( "SELECT role FROM at_collaborators " "WHERE workspace_id=? AND email=? AND status='accepted'", (workspace_id, email_value), ).fetchone() return str(collaborator["role"]) if collaborator else None def require_workspace_capability( conn: sqlite3.Connection, account: dict[str, Any], workspace_id: str, capability: str, ) -> str: role = workspace_role(conn, account, workspace_id) if role is None: raise HTTPException(404, "Workspace not found") if capability not in ROLE_CAPABILITIES.get(role, frozenset()): raise HTTPException(403, "Your workspace role does not allow this action") return role def workspace_id_for( conn: sqlite3.Connection, resource: str, resource_id: str | int ) -> str | None: queries = { "base": "SELECT workspace_id FROM at_bases WHERE id=?", "table": "SELECT b.workspace_id FROM at_tables t JOIN at_bases b ON b.id=t.base_id WHERE t.id=?", "record": "SELECT b.workspace_id FROM at_records r JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE r.id=?", "view": "SELECT b.workspace_id FROM at_views v JOIN at_tables t ON t.id=v.table_id JOIN at_bases b ON b.id=t.base_id WHERE v.id=?", "field": "SELECT b.workspace_id FROM at_fields f JOIN at_tables t ON t.id=f.table_id JOIN at_bases b ON b.id=t.base_id WHERE f.id=?", "comment": "SELECT b.workspace_id FROM at_comments c JOIN at_records r ON r.id=c.record_id JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE c.id=?", "attachment": "SELECT b.workspace_id FROM at_attachments a JOIN at_records r ON r.id=a.record_id JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id WHERE a.id=?", "history": "SELECT b.workspace_id FROM at_history h JOIN at_bases b ON b.id=h.base_id WHERE h.id=?", "automation": "SELECT b.workspace_id FROM at_automations a JOIN at_bases b ON b.id=a.base_id WHERE a.id=?", } row = conn.execute(queries[resource], (resource_id,)).fetchone() return str(row[0]) if row else None def require_resource_capability( conn: sqlite3.Connection, account: dict[str, Any], resource: str, resource_id: str | int, capability: str, ) -> str: workspace_id = workspace_id_for(conn, resource, resource_id) if workspace_id is None: raise HTTPException(404, f"{resource.title()} not found") return require_workspace_capability(conn, account, workspace_id, capability) def form_capability(conn: sqlite3.Connection, base_id: str) -> sqlite3.Row | None: return conn.execute( "SELECT b.* FROM at_bases b WHERE b.id=? AND b.trashed=0 " "AND EXISTS (SELECT 1 FROM at_tables t JOIN at_views v ON v.table_id=t.id " "WHERE t.base_id=b.id AND v.view_type='form')", (base_id,), ).fetchone() def payload_error(exc: Exception) -> HTTPException: if isinstance(exc, HTTPException): return exc if isinstance(exc, AuthError): return HTTPException(422, str(exc)) if isinstance(exc, PermissionError): return HTTPException(403, str(exc)) if isinstance(exc, LookupError): return HTTPException(404, str(exc)) if isinstance(exc, RuntimeError): return HTTPException(409, str(exc)) if isinstance(exc, ValueError): return HTTPException(422, str(exc)) return HTTPException(500, "Unexpected local workspace error") async def json_object(request: Request) -> dict[str, Any]: """Normalize empty or malformed JSON into route-level validation input.""" try: body = await request.json() except (json.JSONDecodeError, UnicodeDecodeError): return {} return body if isinstance(body, dict) else {} def shell( title: str, body: str, *, app_mode: bool = False, account: dict[str, Any] | None = None, ) -> HTMLResponse: account_name = html.escape(str((account or {}).get("display_name", ""))) if app_mode: nav = f"""
Invite your friends and coworkers to earn account credit.
Airtable
""" else: nav = """
Airtable
Sign inSign up for free
""" return HTMLResponse(f""" {html.escape(title)} · Airtable {nav}
{body}
""") def public_shell(title: str, body: str, *, support: bool = False) -> HTMLResponse: if support: nav = """
Airtable
""" body_class = "public-calibration support-public" else: nav = """
Airtable
Book Demo
""" body_class = "public-calibration" return HTMLResponse(f"""{html.escape(title)} · Airtable{nav}
{body}
""") @app.on_event("startup") def initialize() -> None: services() @app.get("/healthz") def health() -> dict[str, Any]: backend, auth = services() check = backend.lifecycle.health() return { "ok": True, "site_id": "airtable", "database": Path(backend.lifecycle.database_path).name, "binding": check.get("site_id", "airtable"), "auth_tables": len(auth.counts()), } @app.get("/", response_class=HTMLResponse) def homepage(request: Request) -> HTMLResponse: _, account = session(request, create=False) if account and account.get("account_id"): return shell("Home", workspace_body(account, "home"), app_mode=True, account=account) return public_shell( "Build apps that connect your work", """

All your teams, all their workflows—connected in
one workspace

Build AI-powered workflows that unify data, maximize collaboration, and set your teams up for long-term success. No
code required.

Get started for freeBook demo
Airtable AI workflow preview

AI transformed
individual work.
Airtable transforms
teamwork.

Where humans and agents work from the same
data, toward the same goals.

Start building for freeGet in touch
90% of Fortune 100 companies trust Airtable
CCPAGDPRISO
27001
AICPA
SOC 1

BUILD WITH AI

AI app building

Turn a sentence, a spreadsheet, or an existing process into a custom business app your whole team can use.

Explore AI app building →

AGENTS IN EVERY WORKFLOW

Agents at Scale

Deploy AI agents across thousands of records while your teams stay in control of the data, logic, and outcomes.

Meet Airtable agents →

YOUR AI COLLABORATOR

Meet Omni

Describe the workflow you need in plain language. Omni builds the app, connects the data, and helps your team improve it.

Learn about Omni →
How can I help?

Build a launch tracker for the product team.

BUILT FOR THE ENTERPRISE

Enterprise capabilities

Scale connected work without compromising control.

Scalable infrastructure

Run high-volume workflows on shared, trustworthy data.

Flexible administration

Give teams room to build with granular permissions and governance.

Security and compliance

Protect every human and agent action with enterprise-grade controls.

Get in touch →

LEARN AND EXPLORE

Resources to inspire

GUIDE

Build your first connected workflow

Practical patterns for moving from scattered work to one system.

AI PLAYBOOK

Put AI to work across every record

See repeatable plays that teams can start using today.

CUSTOMER STORY

How leading teams move faster

Learn how organizations scale their most important work.

Explore all resources →
""", ) @app.get("/platform", response_class=HTMLResponse) def platform_page() -> HTMLResponse: return public_shell( "Platform", """

The Airtable Platform

Humans and agents,
on the same
page

One relational source of truth for every app, agent, and workflow.
Try it nowBook demo
Airtable workflow preview

ONE CONNECTED PLATFORM

An AI foundation shaped around your work

01

Omni

Describe what you need in plain language and build it.

02

Field Agents

Run AI across all of your records.

03

HyperDB

Work from one trusted source at 100M-record scale.

04

App library

Package and share high-impact apps across the organization.

""", ) @app.get("/solutions", response_class=HTMLResponse) def solutions_page() -> HTMLResponse: teams = [ ("product", "Product teams", "Set your roadmap, act on feedback, and launch products customers love."), ("marketing", "Marketing teams", "Manage campaigns through every stage and report on outcomes."), ("operations", "Operations teams", "Connect initiatives and streamline critical workflows."), ("hr", "Human Resources teams", "Orchestrate hiring, onboarding, and employee programs."), ("sales", "Sales teams", "Keep account teams in sync and manage every opportunity."), ("finance", "Finance teams", "Connect planning, reporting, budgets, and approvals."), ("projects", "Project Management", "Manage strategic work around outcomes, not just tasks."), ] cards = "".join( f'
↗

{name}

{copy}

Explore solutions →
' for slug, name, copy in teams ) return public_shell( "Solutions", f"""

AIRTABLE SOLUTIONS

Solutions to empower every team

Customize the right workflows to fit your needs and help your team find success with Airtable.

Start building for free

No matter your workflow, you can build it in Airtable

Explore solutions for every type of team.

{cards}

Start building on Airtable today

Start building for freeContact sales
""", ) @app.get("/resources", response_class=HTMLResponse) def resources_page() -> HTMLResponse: resources = [ ("Webinar", "Getting started in Airtable", "Learn the foundations for connected, AI-powered workflows."), ("Demo", "Automate your workflow with Airtable", "See how teams remove busywork and keep projects moving."), ("Demo", "Modern marketing teams run on Airtable", "Bring campaign planning, production, and reporting together."), ("Quick Read", "The next era of work", "Move from isolated automation to human-agent orchestration."), ("Guide", "Getting the most out of Omni", "Write better prompts and build complete workflows faster."), ("Customer Story", "Scale operations on shared data", "See how leading teams replace silos with one source of truth."), ] cards = "".join( f'
{kind}

{name}

{copy}

Read more →
' for kind, name, copy in resources ) return public_shell( "Resource Center", f"""

RESOURCES AND INSIGHTS

Resource Center

Stay one step ahead of the trends.

Demos, best practices, industry trends, and the latest ways teams are putting AI to work.

{cards}
""", ) @app.get("/contact-sales", response_class=HTMLResponse) def contact_sales_page() -> HTMLResponse: return public_shell( "Contact sales", """

BOOK A DEMO

Get in touch with us!

Build better processes, faster, with Airtable. Backed by advanced data security, no-code capabilities, and embedded AI, Airtable helps teams drive better results.

Trusted by 50% of the Fortune 1000

For technical or product support, please visit our Help Center.

Contact our sales team

This offline form is a local demonstration and sends no external message.
""", ) @app.get("/templates", response_class=HTMLResponse) def templates_page(request: Request) -> HTMLResponse: _, account = session(request, create=False) if account and account.get("account_id"): return shell("Templates", workspace_body(account, "templates"), app_mode=True, account=account) use_cases = [("🗒️","Project Management"),("📣","Marketing"),("🚀","Product Management"),("🧵","Sales & CRM"),("👥","HR & Recruiting")] case_cards = "".join(f'{icon}{label}' for icon,label in use_cases) featured = "".join( f'

{name}

' for index, (name, slug, color) in enumerate( [ ("Project management template", "project", "lavender"), ("AI content calendar template", "content", "rose"), ("Product roadmap template", "roadmap", "aqua"), ("Campaign tracker", "campaign", "sky"), ], start=1, ) ) return public_shell( "Templates", f"""

Templates

Ready-to-use apps that are fully customizable.

{case_cards}

Featured templates

""", ) @app.get("/pricing", response_class=HTMLResponse) def pricing_page() -> HTMLResponse: def feature_line(item: str) -> str: learn_more = " Learn more" if "AI credits" in item else "" return ( "
  • ✓" f"{item}{learn_more}
  • " ) plans = [("Free","For individuals or very small teams just getting started with Airtable","Free","Try for free",["500 AI credits per editor each month.","Unlimited bases","1,000 records per base"]),("Team","For teams building apps to collaborate on shared workflows","$20","Try for free",["15,000 AI credits per paid user each month.","50,000 records per base","25,000 automation runs"]),("Business","For teams and departments who need advanced features and basic administration","$45","Purchase now",["20,000 AI credits per paid user each month.","125,000 records per base","100,000 automation runs"]),("Enterprise Scale","For organizations looking to build scalable, flexible apps with powerful governance and administration","Custom","Contact Sales",["25,000 AI credits per paid user each month at list price.","500,000 records per base","500,000 automation runs"])] cards = "".join(f'

    {name}

    {desc}

    {price}{" USDper seat/month
    billed annually
    " if price.startswith("$") else ""}
    {action}

    {"Free includes:" if name == "Free" else "Everything in " + ("Free" if name == "Team" else "Team") + ", plus:"}

    ' for name,desc,price,action,features in plans) comparison = [ ("Fundamentals", "Bases", "Unlimited", "Unlimited", "Unlimited", "Unlimited"), ("Fundamentals", "Records per base", "1,000", "50,000", "125,000", "500,000"), ("Fundamentals", "Attachment space per base", "1 GB", "20 GB", "100 GB", "1,000 GB"), ("AI", "AI credits", "500", "15,000", "20,000", "25,000"), ("Automations", "Runs per month", "100", "25,000", "100,000", "500,000"), ("Collaboration", "Revision history", "2 weeks", "1 year", "2 years", "3+ years"), ("Administration", "SAML single sign-on", "—", "—", "Included", "Included"), ("Security", "Audit logs and DLP", "—", "—", "—", "Included"), ] rows = "".join( f'
    {group}{feature}{free}{team}{business}{enterprise}
    ' for group, feature, free, team, business, enterprise in comparison ) return public_shell( "Pricing", f"""

    A plan for every organization's needs

    {cards}
    See all features and compare plans ↓

    Compare our plans

    FeaturesFreeTeamBusinessEnterprise Scale
    {rows}
    """, ) def auth_page(mode: str, message: str = "") -> HTMLResponse: signup = mode == "signup" email_label = "Work email" if signup else "Email" email_placeholder = "name@company.com" if signup else "Email address" second_fields = ( "" if signup else "" ) + "" legal = ( "By using Airtable, you agree to the Terms of Service and Privacy Policy." if signup else "By signing up, you agree to the Terms of Service and Privacy Policy." ) promo = "" if signup else """""" google_icon = """""" apple_icon = """""" chatgpt_icon = """""" title = "Sign up" if signup else "Log in" notice = f'
    {html.escape(message)}
    ' if message else "" return HTMLResponse( f"""{title} · Airtable

    Welcome to Airtable

    {notice}
    or
    {promo}
    """ ) @app.get("/login", response_class=HTMLResponse) def login_page(request: Request) -> HTMLResponse: _, account = session(request, create=False) if account and account.get("account_id"): return RedirectResponse("/", status_code=303) return auth_page("login") @app.get("/signup", response_class=HTMLResponse) def signup_page(request: Request) -> HTMLResponse: _, account = session(request, create=False) if account and account.get("account_id"): return RedirectResponse("/", status_code=303) return auth_page("signup") @app.get("/forgot", response_class=HTMLResponse) def forgot_page() -> HTMLResponse: return shell( "Reset password", """
    Airtable

    Reset your password

    Enter your email and we'll create a message in the local inbox.

    Back to sign in
    """, ) @app.get("/support", response_class=HTMLResponse) def support_page() -> HTMLResponse: categories = [("Getting started with Airtable",14),("Airtable AI",5),("Airtable Automations",47),("Airtable Bases",14),("Airtable Betas",3),("Collaborating in Airtable",15),("Airtable Enterprise Support",49),("Airtable Extensions",37),("Airtable Fields",73),("Integrating with Airtable",23),("Airtable Interface Designer",12),("Learning and Resources",3),("Managing data",28),("Account settings",19),("Troubleshooting",31)] cards = "".join(f'{name}{count} articles' for name,count in categories) return public_shell( "Help Center", f"""

    How can we help?

    {cards}
    👋 Hi, how can I help?
    """, support=True, ) def workspace_body(account: dict[str, Any], page: str = "home", account_tab: str = "profile") -> str: owner = owner_of(account) email_value = account_email(account) with connection() as conn: bases = conn.execute( "SELECT DISTINCT b.* FROM at_bases b JOIN at_workspaces w ON w.id=b.workspace_id " "LEFT JOIN at_collaborators c ON c.workspace_id=w.id AND c.email=? AND c.status='accepted' " "WHERE b.archived=0 AND b.trashed=0 AND (w.owner=? OR c.id IS NOT NULL) " "ORDER BY b.updated_at DESC", (email_value, owner), ).fetchall() preference_row = conn.execute( "SELECT values_json FROM at_preferences WHERE owner=?", (owner,) ).fetchone() preferences = json.loads(preference_row["values_json"]) if preference_row else {} recent_base = bases[0] if bases else None base_cards = ( f"Un
    Untitled BaseOpened 22 minutes ago
    " if recent_base else "" ) labels = {"home":"Home", "starred":"Starred", "shared":"Shared", "workspaces":"Workspaces", "templates":"Templates and apps", "marketplace":"Marketplace", "import":"Import", "account":"Account"} label = labels.get(page, "Home") nav_items = [("home","/","⌂","Home"),("starred","/starred","☆","Starred"),("shared","/shared","♧","Shared"),("workspaces","/workspaces","▦","Workspaces")] nav = "".join(f'{icon}{text}' for key,href,icon,text in nav_items) side = f'''''' if page == "home": content = f'''

    Home

    Upgrade to the Team plan before your trial expires in 14 days

    Keep the power you need to manage complex workflows, design interfaces, and more.

    ✦  UpgradeCompare
    plans
    ▦Start with templatesSelect a template to get started and customize as you go.
    ▦ ☷
    {base_cards}
    ''' elif page == "account": security = account_tab == "security" density = preferences.get("density", "comfortable") density_options = "".join(f'' for value, text in (("comfortable", "Comfortable"), ("compact", "Compact"))) checked = " checked" if preferences.get("email_updates") is True else "" content = f'''

    Account

    Profile & preferencesSecurity and sessions
    {('

    Security and sessions

    Revoke every other local session while keeping this browser signed in.

    ' if security else f'

    Profile & preferences

    ')}
    ''' else: descriptions = {"starred":"Bases you mark as important appear here.","shared":"Workspaces and bases shared with this local account.","workspaces":"Manage your deterministic local workspaces.","templates":"Create a base from a synthetic starter workflow.","marketplace":"Add local-only extensions to your workflow.","import":"Bring synthetic CSV data into a local base."} controls = {"starred":base_cards or '

    No starred bases yet.

    ',"shared":base_cards,"workspaces":f'
    {base_cards}
    ',"templates":'
    ',"marketplace":'

    Local extensions

    ',"import":'

    Import data

    Choose a local file from the import dialog. Nothing is uploaded remotely.

    '} content = f'

    {label}

    {descriptions.get(page, "")}

    {controls.get(page, "")}
    ' return f'
    {side}{content}
    ' @app.get("/app", response_class=HTMLResponse) def workspace_home(request: Request): token, account = session(request, create=False) if not account or not account.get("account_id"): return RedirectResponse("/login", 303) return shell("Home", workspace_body(account, "home"), app_mode=True, account=account) @app.get("/starred", response_class=HTMLResponse) @app.get("/marketplace", response_class=HTMLResponse) @app.get("/account", response_class=HTMLResponse) @app.get("/import", response_class=HTMLResponse) @app.get("/shared", response_class=HTMLResponse) @app.get("/workspaces", response_class=HTMLResponse) def app_section(request: Request, tab: str = "profile"): page_name = request.url.path.removeprefix("/") _, account = session(request, create=False) if not account or not account.get("account_id"): return RedirectResponse(f"/login?next=/{page_name}", 303) return shell(page_name.title(), workspace_body(account, page_name, tab), app_mode=True, account=account) def base_body( base_id: str, account: dict[str, Any], query: str = "", status: str = "", sort: str = "", mode: str = "data", page: int = 1, ) -> str: with connection() as conn: require_resource_capability(conn, account, "base", base_id, "read") base = conn.execute( "SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,) ).fetchone() if base is None: raise HTTPException(404, "Base not found") table = conn.execute( "SELECT * FROM at_tables WHERE base_id=? ORDER BY position LIMIT 1", (base_id,), ).fetchone() fields = conn.execute( "SELECT * FROM at_fields WHERE table_id=? ORDER BY position", (table["id"],) ).fetchall() views = conn.execute( "SELECT * FROM at_views WHERE table_id=? ORDER BY rowid", (table["id"],) ).fetchall() records = biz.list_records( conn, table["id"], query=query, status=status, sort=sort ) page_size = 25 total_records = len(records) total_pages = max(1, (total_records + page_size - 1) // page_size) page_index = min(max(1, page), total_pages) page_start = (page_index - 1) * page_size page_records = records[page_start : page_start + page_size] field_names = [r["name"] for r in fields if not r["hidden"]][:7] source_labels = {"Speaker": "Name", "Company": "Notes", "Track": "Assignee", "Status": "Status"} headers = "".join( f"{html.escape(source_labels.get(n, n))}" for n in field_names ) rows = "" for idx, record in enumerate(page_records, page_start + 1): cells = "".join( f"{html.escape(str(record['values'].get(n, '')))}" for n in field_names ) rows += f"{idx}{cells}↗" if not rows: rows = f"No records match this viewClear filters or add a record." view_items = "".join( f"" for v in views ) preserved = {k: v for k, v in {"q": query, "status": status, "sort": sort}.items() if v} previous_query = urlencode({**preserved, "page": max(1, page_index - 1)}) next_query = urlencode({**preserved, "page": min(total_pages, page_index + 1)}) pagination = f'' data_stage = f"""
    {headers}{rows}
    """ automations_stage = """
    ☰ Automations
    TRIGGER

    Suggested triggers for you:

    """ interfaces_stage = f"""

    Visualize and act on your data with AI

    Build easy-to-use interfaces that make even complex workflows simple—for everyone on your team.

    Build it yourself
    Management › InsightsFilter     Sort    ⌕   ···

    Insights

    On this page, you can view insights across all of your projects. To view insights for a specific project, choose the project from the dropdown below.

    Percent Complete19%
    Payment Overdue81%
    Store BreakdownStatus
    ●  To do
    ●  In progress
    ●  Done
    ●  Blocked
    ●  Not committed
    Sales by Country – Retail vs. Online
    Initiatives timelineStatus             2024
    """ forms_stage = f"""

    Gather and organize
    your data with AI

    Quickly collect data from a broad audience, even outside of Airtable.

    Build it yourselfView templates
    ◇

    New Feedback

    """ stage = { "data": data_stage, "automations": automations_stage, "interfaces": interfaces_stage, "forms": forms_stage, }.get(mode, data_stage) labels = {"data": "Data", "automations": "Automations", "interfaces": "Interfaces", "forms": "Forms"} nav = "".join( f'' for key, label in labels.items() ) omni_footer_title = ( "Automations catalog" if mode == "automations" else "Connect your favorite AI tool" ) omni_footer_copy = ( "Easily set up automated workflows with Omni" if mode == "automations" else "Bring Airtable to where you work" ) omni = f"""""" onboarding = ( """""" if base_id == "base-untitled" and mode == "data" else "" ) # Preserve the source-observed fixture label used by the private visual # contracts, while making every user-created base visibly addressable by # its persisted name. displayed_base_name = ( "Untitled Base" if base_id in {"base-conference", "base-untitled"} else str(base["name"]) ) base_name = html.escape(displayed_base_name) return f"""
    {omni}
    ◆
    Trial: 14 days left
    {stage}
    {onboarding}
    """ @app.get("/base/{base_id}", response_class=HTMLResponse) def base_page( base_id: str, request: Request, q: str = "", status: str = "", sort: str = "", page: int = 1 ): token, account = session(request, create=False) if not account or not account.get("account_id"): return RedirectResponse(f"/login?next=/base/{base_id}", 303) return shell( "Conference Tracker", base_body(base_id, account, q, status, sort, page=page), app_mode=True, account=account, ) @app.get("/base/{base_id}/{mode}", response_class=HTMLResponse) def base_mode_page( base_id: str, mode: str, request: Request, q: str = "", status: str = "", sort: str = "", page: int = 1, ): if mode not in {"automations", "interfaces", "forms"}: raise HTTPException(404, "Base mode unavailable") _, account = session(request, create=False) if not account or not account.get("account_id"): return RedirectResponse(f"/login?next=/base/{base_id}/{mode}", 303) return shell( f"{mode.title()} · Conference Tracker", base_body(base_id, account, q, status, sort, mode, page), app_mode=True, account=account, ) @app.get("/base/{base_id}/record/{record_id}", response_class=HTMLResponse) def record_detail_page(base_id: str, record_id: str, request: Request): _, account = session(request, create=False) if not account or not account.get("account_id"): return RedirectResponse(f"/login?next=/base/{base_id}/record/{record_id}", 303) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "read") row = conn.execute( "SELECT r.*,b.name AS base_name FROM at_records r " "JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id " "WHERE r.id=? AND b.id=? AND r.trashed=0", (record_id, base_id), ).fetchone() if row is None: raise HTTPException(404, "Record not found") values = json.loads(row["values_json"] or "{}") fields = "".join( f"
    {html.escape(str(key))}{html.escape(str(value or ''))}
    " for key, value in values.items() ) title = str(values.get("Speaker") or values.get("Name") or "Untitled") return shell( f"{title} · {row['base_name']}", f"
    ← Back to base

    RECORD DETAIL

    {html.escape(title)}

    {fields}
    Status{html.escape(row['status'])}
    Priority{html.escape(row['priority'])}
    ", app_mode=True, account=account, ) @app.get("/share/{share_token}", response_class=HTMLResponse) def public_share(share_token: str): with connection() as conn: base = conn.execute( "SELECT * FROM at_bases WHERE share_token=? AND trashed=0", (share_token,) ).fetchone() if base is None: raise HTTPException(404, "This shared view is unavailable") table = conn.execute( "SELECT * FROM at_tables WHERE base_id=? LIMIT 1", (base["id"],) ).fetchone() records = biz.list_records(conn, table["id"]) cards = "".join( f"

    {html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}

    {html.escape(str(r['values'].get('Company', '')))}

    {html.escape(r['status'])}
    " for r in records ) return shell( f"Shared · {base['name']}", f"

    SHARED VIEW · READ ONLY

    {html.escape(base['name'])}

    This public link is served entirely by the local clone.

    {cards}
    ", ) @app.get("/forms/{base_id}", response_class=HTMLResponse) def form_view(base_id: str): with connection() as conn: base = form_capability(conn, base_id) if base is None: raise HTTPException(404, "Form unavailable") return shell( "Speaker nomination", f"""

    Speaker nomination

    Suggest a speaker for {html.escape(base["name"])}. Required fields are marked.

    """, ) @app.get("/interface/{base_id}", response_class=HTMLResponse) def interface_view(base_id: str, request: Request): _, account = session(request, create=False) if not account: return RedirectResponse("/login", 303) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "read") base = conn.execute( "SELECT name FROM at_bases WHERE id=?", (base_id,) ).fetchone() table = conn.execute( "SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,) ).fetchone() records = biz.list_records(conn, table["id"]) if table else [] confirmed = sum(1 for r in records if r["status"] == "Confirmed") bars = "".join( f"
    {html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}
    " for r in records[:8] ) return shell( "Conference dashboard", f"""

    Conference overview

    Total speakers{len(records)}current records
    Confirmed{confirmed}ready to schedule
    Confirmation rate{round(100 * confirmed / max(1, len(records)))}%local calculation

    Speaker score

    {bars}
    """, app_mode=True, account=account, ) @app.post("/api/auth/login") async def api_login(request: Request): data = await json_object(request) token, _ = session(request) try: result = services()[1].sign_in( token, email=str(data.get("email", "")), password=str(data.get("password", "")), ) except Exception as exc: raise payload_error(exc) response = JSONResponse( {"ok": True, "account": result["account"], "redirect": "/"} ) set_session(response, result["session_token"], request) return response @app.post("/api/auth/signup") async def api_signup(request: Request): data = await json_object(request) token, _ = session(request) auth = services()[1] try: auth.start_registration( token, email=str(data.get("email", "")), display_name=str(data.get("name", "")), password=str(data.get("password", "")), ) mail = auth.local_mail_for_session(token, purpose="registration") except Exception as exc: raise payload_error(exc) response = JSONResponse( { "ok": True, "verification_required": True, "local_code": mail.get("verification_code") if mail else None, "message": "Verification message created in the local inbox.", } ) set_session(response, token, request) return response @app.post("/api/auth/signup/verify") async def api_signup_verify(request: Request): data = await json_object(request) token, _ = session(request) auth = services()[1] try: auth.verify_registration_code(token, str(data.get("code", ""))) result = auth.complete_registration(token) except Exception as exc: raise payload_error(exc) response = JSONResponse( {"ok": True, "account": result["account"], "redirect": "/"} ) set_session(response, result["session_token"], request) return response @app.post("/api/auth/logout") def api_logout(request: Request): token, _ = session(request, create=False) services()[1].sign_out(token) response = JSONResponse({"ok": True, "redirect": "/login"}) if token: response.delete_cookie(cookie_name(request), path="/") return response @app.post("/api/auth/reset") async def api_reset(request: Request): data = await json_object(request) token, _ = session(request) auth = services()[1] try: result = auth.start_password_reset(token, email=str(data.get("email", ""))) mail = auth.local_mail_for_session(token, purpose="password-reset") except Exception as exc: raise payload_error(exc) response = JSONResponse( { **result, "ok": True, "local_code": mail.get("verification_code") if mail else None, } ) set_session(response, token, request) return response @app.post("/api/auth/reset/complete") async def api_reset_complete(request: Request): data = await json_object(request) token, _ = session(request) auth = services()[1] try: auth.verify_password_reset_code(token, str(data.get("code", ""))) new_token = auth.complete_password_reset( token, new_password=str(data.get("password", "")) ) except Exception as exc: raise payload_error(exc) response = JSONResponse({"ok": True, "message": "Password updated"}) set_session(response, new_token, request) return response @app.post("/api/workspaces") async def api_create_workspace(request: Request): _, account = require_account(request) data = await request.json() try: with connection() as conn: result = biz.create_workspace( conn, owner_of(account), str(data.get("name", "")) ) except Exception as exc: raise payload_error(exc) return {"ok": True, "workspace": result} @app.post("/api/bases") async def api_create_base(request: Request): _, account = require_account(request) data = await request.json() try: with connection() as conn: workspace_id = str(data.get("workspace_id") or "") require_workspace_capability(conn, account, workspace_id, "schema") result = biz.create_base( conn, owner_of(account), workspace_id, str(data.get("name", "")), str(data.get("template")) if data.get("template") else None, ) except Exception as exc: raise payload_error(exc) return {"ok": True, "base": result, "redirect": f"/base/{result['id']}"} @app.get("/api/bases/{base_id}") def api_base(base_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "read") base = conn.execute( "SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,) ).fetchone() if base is None: raise HTTPException(404, "Base not found") tables = [ dict(r) for r in conn.execute( "SELECT * FROM at_tables WHERE base_id=? ORDER BY position", (base_id,) ) ] for table in tables: table["fields"] = [ dict(r) for r in conn.execute( "SELECT * FROM at_fields WHERE table_id=? ORDER BY position", (table["id"],), ) ] table["views"] = [ dict(r) for r in conn.execute( "SELECT * FROM at_views WHERE table_id=?", (table["id"],) ) ] table["records"] = biz.list_records(conn, table["id"]) return {"ok": True, "base": dict(base), "tables": tables} @app.post("/api/tables/{table_id}/records") async def api_create_record(table_id: str, request: Request): _, account = require_account(request) data = await request.json() try: with connection() as conn: require_resource_capability(conn, account, "table", table_id, "data") result = biz.create_record( conn, owner_of(account), table_id, dict(data.get("values") or {}), status=str(data.get("status") or "Planned"), priority=str(data.get("priority") or "Medium"), assignee=data.get("assignee"), due_date=data.get("due_date"), ) except Exception as exc: raise payload_error(exc) return {"ok": True, "record": result} @app.patch("/api/records/{record_id}") async def api_update_record(record_id: str, request: Request): _, account = require_account(request) data = await request.json() try: with connection() as conn: require_resource_capability(conn, account, "record", record_id, "data") result = biz.update_record( conn, owner_of(account), record_id, data, data.get("expected_updated_at"), ) except Exception as exc: raise payload_error(exc) return {"ok": True, "record": result} @app.delete("/api/records/{record_id}") def api_delete_record(record_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "record", record_id, "data") row = conn.execute( "SELECT table_id,values_json FROM at_records WHERE id=? AND trashed=0", (record_id,), ).fetchone() if row is None: raise HTTPException(404, "Record not found") changed = conn.execute( "UPDATE at_records SET trashed=1,updated_at=? WHERE id=? AND trashed=0", (biz.now(), record_id), ) if changed.rowcount == 0: raise HTTPException(404, "Record not found") base_id = conn.execute( "SELECT base_id FROM at_tables WHERE id=?", (row["table_id"],) ).fetchone()[0] biz.log( conn, owner_of(account), "moved record to trash", base_id=base_id, entity_type="record", entity_id=record_id, snapshot=json.loads(row["values_json"]), ) return {"ok": True, "state": "trashed"} @app.post("/api/records/bulk") async def api_bulk_records(request: Request): _, account = require_account(request) data = await request.json() ids = [str(x) for x in data.get("record_ids", [])] if not ids or len(ids) > 100: raise HTTPException(422, "Select 1 to 100 records") action = str(data.get("action", "")) placeholders = ",".join("?" for _ in ids) with connection() as conn: rows = conn.execute( f"SELECT id FROM at_records WHERE id IN ({placeholders})", ids ).fetchall() if len(rows) != len(set(ids)): raise HTTPException(404, "Record not found") workspace_ids = { workspace_id_for(conn, "record", record_id) for record_id in ids } if None in workspace_ids or len(workspace_ids) != 1: raise HTTPException(404, "Records not found") require_workspace_capability( conn, account, next(iter(workspace_ids)), "data" ) if action == "confirm": conn.execute( f"UPDATE at_records SET status='Confirmed',updated_at=? WHERE id IN ({placeholders})", (biz.now(), *ids), ) elif action == "archive": conn.execute( f"UPDATE at_records SET archived=1,updated_at=? WHERE id IN ({placeholders})", (biz.now(), *ids), ) elif action == "trash": conn.execute( f"UPDATE at_records SET trashed=1,updated_at=? WHERE id IN ({placeholders})", (biz.now(), *ids), ) else: raise HTTPException(422, "Unsupported bulk action") changed = conn.execute( f"SELECT COUNT(*) FROM at_records WHERE id IN ({placeholders})", ids ).fetchone()[0] biz.log( conn, owner_of(account), f"bulk {action}", entity_type="records", snapshot={"count": changed}, ) return {"ok": True, "changed": changed, "action": action} @app.post("/api/tables/{table_id}/fields") async def api_create_field(table_id: str, request: Request): _, account = require_account(request) data = await request.json() name = " ".join(str(data.get("name", "")).split()) typ = str(data.get("type", "singleLineText")) allowed = { "singleLineText", "longText", "number", "singleSelect", "multipleSelect", "date", "checkbox", "email", "url", "attachment", "collaborator", "linkedRecord", "lookup", "rollup", "formula", } if not name or typ not in allowed: raise HTTPException(422, "Choose a valid field name and type") with connection() as conn: require_resource_capability(conn, account, "table", table_id, "schema") pos = conn.execute( "SELECT COALESCE(MAX(position),-1)+1 FROM at_fields WHERE table_id=?", (table_id,), ).fetchone()[0] fid = biz.token("fld") conn.execute( "INSERT INTO at_fields VALUES (?,?,?,?,?,?,0)", (fid, table_id, name, typ, json.dumps(data.get("options") or {}), pos), ) base = conn.execute( "SELECT base_id FROM at_tables WHERE id=?", (table_id,) ).fetchone() if not base: raise HTTPException(404, "Table not found") biz.log( conn, owner_of(account), "created field", base_id=base[0], entity_type="field", entity_id=fid, snapshot={"name": name, "type": typ}, ) return {"ok": True, "field": {"id": fid, "name": name, "type": typ}} @app.post("/api/tables/{table_id}/views") async def api_create_view(table_id: str, request: Request): _, account = require_account(request) data = await request.json() typ = str(data.get("type", "grid")) name = str(data.get("name", f"{typ.title()} view")) if typ not in {"grid", "gallery", "kanban", "calendar", "form"}: raise HTTPException(422, "Unsupported view type") with connection() as conn: require_resource_capability(conn, account, "table", table_id, "schema") vid = biz.token("view") conn.execute( "INSERT INTO at_views VALUES (?,?,?,?,?,?)", ( vid, table_id, name, typ, json.dumps(data.get("config") or {}), int(bool(data.get("favorite"))), ), ) return {"ok": True, "view": {"id": vid, "name": name, "type": typ}} @app.post("/api/records/{record_id}/comments") async def api_comment(record_id: str, request: Request): _, account = require_account(request) data = await request.json() body = " ".join(str(data.get("body", "")).split()) if not 1 <= len(body) <= 2000: raise HTTPException(422, "Comment must contain 1 to 2000 characters") with connection() as conn: require_resource_capability(conn, account, "record", record_id, "comment") if ( conn.execute("SELECT 1 FROM at_records WHERE id=?", (record_id,)).fetchone() is None ): raise HTTPException(404, "Record not found") cid = biz.token("comment") conn.execute( "INSERT INTO at_comments VALUES (?,?,?,?,?)", (cid, record_id, owner_of(account), body, biz.now()), ) if "@" in body: conn.execute( "INSERT INTO at_notifications VALUES (?,?,?,?,?)", ( biz.token("note"), "seed:member", f"Mention in a comment: {body[:120]}", None, biz.now(), ), ) return { "ok": True, "comment": {"id": cid, "body": body}, "mention_notified": "@" in body, } @app.post("/api/workspaces/{workspace_id}/invite") async def api_invite(workspace_id: str, request: Request): _, account = require_account(request) data = await request.json() email_value = str(data.get("email", "")).strip().casefold() role = str(data.get("role", "editor")) if "@" not in email_value or role not in { "owner", "creator", "editor", "commenter", "read_only", }: raise HTTPException(422, "Enter a valid email and role") with connection() as conn: actor_role = require_workspace_capability( conn, account, workspace_id, "manage" ) if role == "owner" and actor_role != "owner": raise HTTPException(403, "Only the workspace owner can grant owner access") iid = biz.token("invite") try: conn.execute( "INSERT INTO at_collaborators VALUES (?,?,?,?,?,?)", (iid, workspace_id, email_value, role, "invited-local", biz.now()), ) except sqlite3.IntegrityError: conn.execute( "UPDATE at_collaborators SET role=?,status='invited-local' WHERE workspace_id=? AND email=?", (role, workspace_id, email_value), ) biz.log( conn, owner_of(account), "invited collaborator (local delivery)", entity_type="collaborator", entity_id=iid, snapshot={"role": role}, ) return { "ok": True, "status": "invited-local", "delivery": "local-outbox", "role": role, } @app.post("/api/bases/{base_id}/share") def api_share(base_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "manage") base = conn.execute( "SELECT * FROM at_bases WHERE id=?", (base_id,) ).fetchone() if base is None: raise HTTPException(403, "Base unavailable") share_token = base["share_token"] or biz.token("share") conn.execute( "UPDATE at_bases SET share_token=?,updated_at=? WHERE id=?", (share_token, biz.now(), base_id), ) return {"ok": True, "share_url": f"/share/{share_token}", "read_only": True} @app.post("/api/bases/{base_id}/automations") async def api_automation(base_id: str, request: Request): _, account = require_account(request) data = await request.json() action = str(data.get("action", "create")) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "manage") if action == "run": aid = str(data.get("automation_id") or "auto-confirm") row = conn.execute( "SELECT * FROM at_automations WHERE id=? AND base_id=?", (aid, base_id) ).fetchone() if row is None: raise HTTPException(404, "Automation not found") conn.execute( "UPDATE at_automations SET run_count=run_count+1,last_status='Succeeded locally' WHERE id=?", (aid,), ) conn.execute( "INSERT INTO at_notifications VALUES (?,?,?,?,?)", ( biz.token("note"), owner_of(account), f"Automation '{row['name']}' completed locally", None, biz.now(), ), ) result = {"id": aid, "status": "Succeeded locally"} else: name = str(data.get("name", "Untitled automation")) aid = biz.token("auto") conn.execute( "INSERT INTO at_automations VALUES (?,?,?,?,?,?,?,?)", ( aid, base_id, name, str(data.get("trigger", "record_created")), str(data.get("then", "create_notification")), int(bool(data.get("enabled", True))), 0, "Never run", ), ) result = { "id": aid, "status": "enabled" if data.get("enabled", True) else "disabled", } return {"ok": True, "automation": result, "sandbox": True} @app.post("/api/bases/{base_id}/integrations") async def api_integration(base_id: str, request: Request): _, account = require_account(request) data = await request.json() provider = str(data.get("provider", "Local webhook")) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "manage") iid = biz.token("int") conn.execute( "INSERT INTO at_integrations VALUES (?,?,?,?,?)", (iid, base_id, provider, 1, json.dumps({"mode": "offline-simulation"})), ) return { "ok": True, "integration": {"id": iid, "provider": provider, "mode": "offline-simulation"}, } @app.post("/api/tables/{table_id}/import") async def api_import(table_id: str, request: Request): _, account = require_account(request) text = (await request.body()).decode("utf-8", "replace") try: with connection() as conn: require_resource_capability(conn, account, "table", table_id, "data") result = biz.csv_import(conn, owner_of(account), table_id, text) except Exception as exc: raise payload_error(exc) return {"ok": True, **result} @app.get("/api/tables/{table_id}/export") def api_export(table_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "table", table_id, "read") text = biz.csv_export(conn, table_id) return PlainTextResponse( text, media_type="text/csv", headers={"Content-Disposition": "attachment; filename=airtable-export.csv"}, ) @app.post("/api/records/{record_id}/attachments") async def api_attachment( record_id: str, request: Request, file: UploadFile = File(...) ): _, account = require_account(request) data = await file.read(5_000_001) if len(data) > 5_000_000: raise HTTPException(413, "Attachment exceeds the 5 MB offline limit") safe = ( "".join( c for c in (file.filename or "attachment.bin") if c.isalnum() or c in ".-_ " )[:100] or "attachment.bin" ) aid = biz.token("attachment") target = VOLUME_ROOT / "attachments" / f"{aid}-{safe}" target.parent.mkdir(parents=True, exist_ok=True) with connection() as conn: require_resource_capability(conn, account, "record", record_id, "data") target.write_bytes(data) conn.execute( "INSERT INTO at_attachments VALUES (?,?,?,?,?,?,?)", ( aid, record_id, safe, file.content_type or "application/octet-stream", len(data), str(target), biz.now(), ), ) biz.log( conn, owner_of(account), "attached file", entity_type="attachment", entity_id=aid, snapshot={"filename": safe, "size": len(data)}, ) return { "ok": True, "attachment": { "id": aid, "filename": safe, "size": len(data), "download": f"/api/attachments/{aid}", }, } @app.get("/api/attachments/{attachment_id}") def api_attachment_download(attachment_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability( conn, account, "attachment", attachment_id, "read" ) row = conn.execute( "SELECT * FROM at_attachments WHERE id=?", (attachment_id,) ).fetchone() if row is None or not Path(row["local_path"]).is_file(): raise HTTPException(404, "Attachment unavailable") return FileResponse( row["local_path"], media_type=row["content_type"], filename=row["filename"] ) @app.post("/api/forms/{base_id}/submit") async def api_form_submit(base_id: str, request: Request): data = await json_object(request) name = str(data.get("Speaker", "")).strip() email_value = str(data.get("Email", "")).strip() if not name or "@" not in email_value: raise HTTPException(422, "Speaker name and a valid email are required") with connection() as conn: if form_capability(conn, base_id) is None: raise HTTPException(404, "Form unavailable") table = conn.execute( "SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,) ).fetchone() if table is None: raise HTTPException(404, "Form unavailable") sid = biz.token("submission") conn.execute( "INSERT INTO at_form_submissions VALUES (?,?,?,?)", (sid, base_id, json.dumps(data), biz.now()), ) record = biz.create_record( conn, "public-form", table[0], data, status="Invited" ) return { "ok": True, "submission_id": sid, "record_id": record["id"], "message": "Thanks — your response was submitted.", } @app.get("/api/history/{base_id}") def api_history(base_id: str, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "base", base_id, "read") rows = [ dict(r) for r in conn.execute( "SELECT * FROM at_history WHERE base_id=? ORDER BY id DESC LIMIT 50", (base_id,), ) ] return {"ok": True, "history": rows} @app.post("/api/history/{history_id}/undo") def api_undo(history_id: int, request: Request): _, account = require_account(request) with connection() as conn: require_resource_capability(conn, account, "history", history_id, "data") event = conn.execute( "SELECT * FROM at_history WHERE id=?", (history_id,) ).fetchone() if event is None: raise HTTPException(404, "History entry not found") snapshot = json.loads(event["snapshot_json"]) if event["entity_type"] == "record" and event["action"] in { "updated record", "moved record to trash", }: if event["action"] == "moved record to trash": conn.execute( "UPDATE at_records SET trashed=0,updated_at=? WHERE id=?", (biz.now(), event["entity_id"]), ) else: conn.execute( "UPDATE at_records SET values_json=?,status=?,priority=?,assignee=?,due_date=?,updated_at=? WHERE id=?", ( snapshot["values_json"], snapshot["status"], snapshot["priority"], snapshot["assignee"], snapshot["due_date"], biz.now(), event["entity_id"], ), ) else: raise HTTPException(422, "This history entry cannot be undone") biz.log( conn, owner_of(account), "undo", base_id=event["base_id"], entity_type=event["entity_type"], entity_id=event["entity_id"], snapshot={"source_history_id": history_id}, ) return {"ok": True, "message": "Change undone"} @app.post("/api/bases/{base_id}/lifecycle") async def api_base_lifecycle(base_id: str, request: Request): _, account = require_account(request) data = await request.json() action = str(data.get("action", "")) states = { "archive": (1, 0), "restore": (0, 0), "trash": (0, 1), "restore-trash": (0, 0), } if action == "permanent-delete": with connection() as conn: require_resource_capability(conn, account, "base", base_id, "manage") base = conn.execute( "SELECT * FROM at_bases WHERE id=? AND trashed=1", (base_id,) ).fetchone() if base is None: raise HTTPException( 409, "Move the base to trash before permanent deletion" ) conn.execute("DELETE FROM at_bases WHERE id=?", (base_id,)) return {"ok": True, "state": "permanently-deleted"} if action not in states: raise HTTPException(422, "Unsupported lifecycle action") archived, trashed = states[action] with connection() as conn: require_resource_capability(conn, account, "base", base_id, "manage") changed = conn.execute( "UPDATE at_bases SET archived=?,trashed=?,updated_at=? WHERE id=?", (archived, trashed, biz.now(), base_id), ).rowcount if not changed: raise HTTPException(404, "Base not found") biz.log( conn, owner_of(account), action, base_id=base_id, entity_type="base", entity_id=base_id, ) return {"ok": True, "state": action} @app.get("/api/notifications") def api_notifications(request: Request): _, account = require_account(request) with connection() as conn: rows = [ dict(r) for r in conn.execute( "SELECT * FROM at_notifications WHERE owner=? ORDER BY created_at DESC", (owner_of(account),), ) ] return {"ok": True, "notifications": rows} @app.post("/api/preferences") async def api_preferences(request: Request): _, account = require_account(request) data = await request.json() owner = owner_of(account) with connection() as conn: conn.execute( "INSERT INTO at_preferences VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET values_json=excluded.values_json,updated_at=excluded.updated_at", (owner, json.dumps(data), biz.now()), ) return {"ok": True, "preferences": data} @app.post("/api/security/revoke-sessions") def api_revoke_sessions(request: Request): token, account = require_account(request) auth = services()[1] with auth.connect() as conn: digest = auth._session_row(conn, token)["session_digest"] conn.execute( "UPDATE local_auth_sessions SET revoked_at=? WHERE account_id=? AND session_digest<>? AND revoked_at IS NULL", (biz.now(), account["account_id"], digest), ) changed = conn.total_changes return {"ok": True, "revoked": changed, "current_session_preserved": True} @app.delete("/api/account") def api_delete_account(request: Request): token, account = require_account(request) owner = owner_of(account) auth = services()[1] with auth.connect() as conn: owned = conn.execute( "SELECT COUNT(*) FROM at_workspaces WHERE owner=? AND archived=0", (owner,) ).fetchone()[0] if owned: raise HTTPException( 409, "Archive or transfer owned workspaces before deleting the account" ) conn.execute( "DELETE FROM local_auth_accounts WHERE account_id=?", (account["account_id"],), ) return {"ok": True, "state": "deleted"} @app.get("/api/formula") def api_formula( request: Request, expression: str, speaker: str = "Ada", company: str = "Northstar" ): require_account(request) try: value = biz.evaluate_formula( expression, {"Speaker": speaker, "Company": company, "Score": 9} ) except Exception as exc: raise payload_error(exc) return {"ok": True, "value": value, "sandbox": True} @app.exception_handler(HTTPException) def http_error(request: Request, exc: HTTPException): if request.url.path.startswith("/api/"): return JSONResponse( { "ok": False, "error": exc.detail, "retryable": exc.status_code in {409, 429, 500, 503}, }, status_code=exc.status_code, ) response = shell( "Something went wrong", f"

    {exc.status_code}

    {html.escape(str(exc.detail))}

    Your prior local state has not been changed.

    Return home
    ", app_mode=True, ) response.status_code = exc.status_code return response