Skip to content
Source
Sign inSign up
samwillis/neon-glow-demo
Open History to see the last commit

IMPLEMENTATION.md

331 lines19.3 KB

First implementation

This document describes the code delivered on 20 November 2026, with managed Neon Auth added on 23 November. The other design documents retain the broader roadmap; capabilities listed as future work here are not available merely because they appear in those designs.

What is built

  • TanStack Start web UI with Base UI and CSS Modules. Desktop shows chat beside a phone preview; mobile web switches between chat and play.
  • Expo Router / React Native builder with native navigation, secure session storage, chat, a WebView player, sharing, remixing, and revision history.
  • A shared TanStack DB client using the official Neon Realtime adapter for apps, messages, and runs. Foreground/reconnect refresh obtains a fresh authorized snapshot. A polling fallback works when Realtime is not configured.
  • Hono API on Neon Functions with managed Neon Auth. Web and native use the official @neon/auth SDK and email sign-in codes. Neon generates, sends, expires, and verifies codes using its shared development email provider. The API admits verified emails from exact GLOW_SIGNIN_DOMAINS entries (default databricks.com) and explicit GLOW_SIGNUP_ALLOWLIST addresses. Native stores managed session cookies in SecureStore without the Expo auth plugin.
  • Pi 1.5.2 running inside hosted Node 24 Functions. Its file tools edit normal React/TypeScript/CSS source; the platform compiles a browser artifact. The official Neon Postgres, Object Storage, and Realtime skills are pinned with their license and manifest, alongside a Glow guide describing the actual available APIs.
  • Neon AI Gateway inference through a budgeted App API proxy. The worker receives a short-lived run capability rather than the gateway credential.
  • Source and serialized Pi sessions in private Neon Object Storage, referenced from coordination Postgres. Completed turns checkpoint; subsequent edits restore the saved source and session. A failed change preserves the last working version.
  • Durable queue, explicit HTTP dispatch, invocation ownership, attempt fences, leases, heartbeats, bounded retries, and a scheduled recovery Function trigger. Realtime signals prompt reconciliation; they do not deliver durable commands or start an absent Function. Messages during generation are queued changes. Session-level provisioning and credential-policy locks use direct Postgres connections; ordinary API transactions use the pooled connection. Transaction pooling cannot preserve session-lock ownership across statements.
  • One Neon project per original and one child branch per explicit remix. Normal edits and restores keep their existing project/branch. Provisioning records retain uncertain operations for reconciliation rather than blindly recreating.
  • Stable share links, unlisted/public visibility, attribution, private drafts, and a response list for shared remixes. Published creations follow their latest successful edit; private conversations and Pi sessions are excluded from remixes.
  • Shared app pages show comments and direct remixes on web and native. Anyone with the link can read them; posting requires sign-in. Authors and app owners can remove comments. Only ready, shared, enabled remixes appear, with creator names and links. Private remix drafts stay hidden.
  • A small glow.state SDK with player/shared scopes, expected record revisions, typed field patches, and operation receipts. Private player/preview state is in App Postgres; live shared state is in the creation branch. Remix namespaces start fresh. Preview sessions cannot write live player/shared state.

Social discovery and media (23 November 2026)

  • The web app opens on a vertical feed of public apps (For you, Following, New). Each card plays the app's captured clip; Tap to play loads the live app in place, so only one live frame runs at a time. Cards carry likes, remixes, comments, share, follow, plays, the caption, and a link to the app it remixes.
  • Sidebar: Make, Feed, Discover, Notifications, Profile, Drafts, About. The mobile tab bar keeps Feed, Discover, Make, Notifications, Profile.
  • Discover (an optional remix challenge, trending, fresh remixes, new posts), Make (composer, ideas, recent drafts), Notifications (remixes, comments, likes, follows of your work), About, and profiles at /u/:userId. A profile is a timeline of posts with an optional pinned post, a bio and picture the owner edits, a Replies tab (comments on other people's apps), and a private Drafts tab; /drafts opens it. Profile pictures are square JPEGs cropped in the browser and stored as content-addressed media (glow_profiles).
  • Everyone gets a unique handle (from their name or email, de-duplicated) on first visit; scripts/backfill-handles.ts assigned existing ones. Profile URLs are /u/:handle (user IDs still resolve). Display name and handle are editable; handles are 3-24 lowercase letters, numbers, dots, or underscores, with a reserved list. The display name replaces the sign-in name everywhere.
  • Brand: NEON uses the Neon wordmark's own letter paths; GLOW is drawn on the same grid (3.38-unit stroke on a 16.92-unit cap height). The Glow spark uses the same stroke ratio, and tiles use a thick gradient ring. Favicons, touch and manifest icons are in apps/web/public; Expo icons in apps/mobile/assets.
  • Posting replaces the share dialog: choose a cover from captured frames, a title, a caption (the original prompt is offered, never published implicitly), and Feed (public) or Link only (unlisted). Make private hides it again.
  • The agent names each change with describe_app (title, tagline, emoji, colour, optional demo steps); a creator's own title always wins. Existing apps were renamed once by scripts/backfill-media.ts.
  • New tables: likes, follows, daily de-duplicated plays, inbox read markers, challenges, capture jobs, and capture workers. pnpm db:migrate applies them. Start a challenge with scripts/challenge.ts.
  • /a/:appId emits Open Graph tags from the published title, caption, and cover.

Native app (Expo)

The native app mirrors the web: bottom tabs (Feed, Discover, Make, Notifications, Profile) plus the builder, shared app, profiles, About, and Drafts. Brand art and generated avatars come from the shared @glow/design-tokens/art SVG module (rendered with react-native-svg), and agent replies use the shared Markdown parser in @glow/client/markdown. Clips play with expo-video (WebM clips fall back to posters on iOS). Covers and agent checks run in a hidden phone-sized WebView; because iOS WebKit will not read back DOM-to-image renders, iOS takes native view snapshots (react-native-view-shot) while the in-page runtime runs steps and reports text and errors (images: false). Profile pictures use the photo picker and are resized to 320px JPEGs on device. Typecheck and iOS/Android bundling pass; the app has not yet been run on a simulator or device.

Covers, clips, and agent visual checks

Capture currently runs in the creator's browser. Preview HTML is served with a capture runtime (@glow/creation-runtime/capture) that renders the live DOM into an SVG foreignObject image (canvases copied, running CSS animations frozen) and records clips with MediaRecorder from the dominant canvas or DOM snapshots.

  • After a new version loads, the builder captures a poster, two extra frames, and a five-second clip in a hidden frame with throwaway state, running the agent's demo steps, and uploads them to POST /v1/apps/:id/versions/:versionId/media. Media is content-addressed, JPEG/WebM/MP4-checked, and served immutable from /v1/media/:hash.:ext. Retake records the visible preview instead.
  • The agent's look_at_app tool queues a capture job. An open builder tab for that app long-polls /v1/apps/:id/capture/next, renders the job with stubbed state, runs tap/drag/key steps as synthetic events, and returns screenshots, visible text, errors, and console output. Before handing a change back, the agent renders it once and repairs a blank screen or uncaught errors. When the builder is closed, the agent is told visual checks are unavailable.
  • Limits: Safari may refuse to read foreignObject images back from a canvas, so covers may be missing for Safari creators; WebGL canvases without preserveDrawingBuffer capture blank; external fonts and images are not used by creations, so they do not need inlining.

Headless Chromium on Functions (not enabled)

A Playwright capture worker (services/capture) is kept for when Function limits allow Chromium. On 23 November 2026, Functions run Ubuntu 24.04 on arm64; /tmp (256 MiB), /run, and /dev are noexec, and the read-only code mount is the only executable location. The deploy API accepts a 32 MiB ZIP, 128 MB uncompressed, 64 MB per file, and 32k files. A stripped linux-arm64 headless shell is 157 MiB for the binary alone (about 240 MB with SwiftShader, ICU, missing system libraries from the image, and fonts; 106 MiB zipped), so it needs larger limits or an executable writable directory. The same worker ran in a locked-down Ubuntu arm64 container at about 1.4 s per warm capture and 160 MB RSS. The pull-based job protocol (/internal/capture/*, worker grants from scripts/capture-token.ts) and scripts/backfill-media.ts remain for that path.

Function and credential placement

Web / native
     |
     v
App project: authenticated API, scheduler, Postgres, Object Storage, AI Gateway
     |                       ^
     | dispatch              | scoped run APIs, model proxy, checkpoints
     v                       |
Sandbox project: app-bound bootstrap -> signed central Pi/tool/skill package

App API -> original creation project / existing branch -> shared gameplay state
        -> same project / child remix branch           -> independent state

Functions inject their own branch credentials. The hosted runtime overwrote a custom DATABASE_URL, and the available role could not set the default owner to NOLOGIN. The approved solution is a separate sandbox project holding no app data. Its database is disposable carrier infrastructure. Workers never receive the coordination or creation database URLs. The trusted API revokes injected carrier storage/model credentials and verifies denial before admitting execution. See the sandbox policy.

Each app's bootstrap verifies the dispatch app binding and the selected package's signed version and digest. Agent updates publish a central package, which each new run pins. Existing bootstraps load it without an agent deployment per app. Bootstrap or public-key updates still need a fleet rollout. Compilation uses esbuild's WASM browser API in-process with a bounded source/dependency resolver. Hosted checks rejected executing packaged native binaries, including from /tmp, with EACCES; the runtime compiler therefore needs no native compiler subprocess.

Running the existing development environment

From the repository root:

pnpm install
pnpm dev

Open http://localhost:3000. The ignored root .env.local selects the hosted API when GLOW_REMOTE_WORKERS=true. Otherwise the dev script starts local API and worker processes too; the worker receives a restricted environment.

Click Sign in, enter your Databricks email, and enter the six-digit code from Neon Auth. Explicitly invited personal addresses still work. Ask for a silly touch game, try it in Play, ask for a change, and try History. Share its link and open it in another account. Choose Make your version, change it, and share back. Return to the original link after its creator edits it: it should open the latest working version while the remix keeps its own version.

For native development:

pnpm dev:mobile
pnpm --filter @glow/mobile ios
# Or: pnpm --filter @glow/mobile android

Only the API URL and web share URL belong in apps/mobile/.env.local; no server credentials belong there. Build and device checks require the appropriate native toolchain. On a physical phone, the configured web share URL must be reachable from that phone; localhost points to the phone itself.

Provisioning another development environment

Use the existing environment when possible. These commands create billable Neon resources in the explicitly selected organization:

pnpm exec tsx scripts/setup.ts <organization-id>
pnpm db:migrate
pnpm exec tsx scripts/setup-sandboxes.ts
pnpm exec tsx scripts/deploy.ts

Review .env.example; configure sign-in domains, optional invited emails, and the web URL before deploying the API. Setup provisions the App project, private bucket, Gateway, and Realtime; the sandbox setup provisions the empty carrier. Deploy publishes the central agent package, deploys the App API, registers scheduled recovery, and writes native public URL configuration. .local, .neon, and real environment files are ignored. The web frontend still needs an external host for remote sharing. Native signing, bundle identifiers, and app-store distribution are not configured.

Verification

pnpm typecheck
pnpm test
pnpm build
pnpm --filter @glow/mobile export

The focused tests cover state conflicts and field preservation, malformed source, compiler dependency restrictions, worker environment/file boundaries, trusted skill integrity, session leaf restoration, and rejection of pooled connections for session locks. The production web build and iOS / Android JavaScript exports pass. Exports do not establish native device behavior.

Community checks run with pnpm exec tsx --test services/api/test/community.test.ts packages/client/test/community.test.ts. Setting GLOW_TEST_DATABASE_URL to an existing direct development connection also exercises the actual SQL. That test uses temporary tables in a rolled-back transaction. It checks visibility, comment idempotency, author/owner deletion, rate limits, and stable pagination. The client check verifies page reconciliation and clearing cached content after access loss.

pnpm exec tsx scripts/smoke.ts exercises the configured hosted API with two two signed-in test accounts. It creates persistent projects/branches, uses model credits, and retains ignored progress so a retry reuses its creation. Configure GLOW_SMOKE_MAKER_COOKIE and GLOW_SMOKE_FRIEND_COOKIE with the two accounts' managed session cookies in the ignored environment file. These are credentials; keep them out of source control. Password-based test-account provisioning was removed with the auth migration. Never use the smoke against production.

A separate live check confirmed committed Postgres changes reaching a TanStack DB collection through Neon Realtime. No browser automation or native device interaction was performed in this session.

The hosted smoke passed the following checks on 20 November 2026:

CheckResult
Creation through Pi, scoped model proxy, and central agent packageCompiled artifact persisted and available through preview
Editing with restored source/sessionBoth original and remix produced new working versions
Neon fleet modelRemix shares the original project and has a distinct ready branch
Ordinary editingOriginal and remix retain their assigned branches
Stable share linkOriginal link opens its newest successful version
Remix independenceParent edit does not change the existing remix
Social responseShared remix appears in the original creator's response list
AuthorizationAnother account cannot read the private builder
Remix privacyPrivate user messages are absent from the remix conversation
StateDuplicate operation returns the same receipt; preview and remix state are isolated
Carrier policyRevoked storage/model credentials denied; repeated direct-connection policy checks pass

The validation also observed scheduled recovery completing an interrupted hosted attempt. This is evidence for that recovery path, not a complete fault-injection or concurrency test. Deployment and retry work reused the existing creations; they did not allocate editing branches. Two temporary compiler diagnostic Functions were deployed in succession under one slug and removed after use.

Remaining limits

This is a development slice limited to the configured work domains and invited emails. Generated dependencies currently include React and React DOM; no arbitrary npm installs, shell, SQL, migrations, server processes, secrets, uploads, or generated-app Realtime subscriptions are exposed. Object Storage and Realtime already power the platform itself. Assets, richer libraries, broader backend APIs, and multiplayer are later capabilities.

Trusted compilation checks syntax/imports and builds the artifact; it does not prove the creation behaves correctly or is enjoyable. Independent execution and visual validation are not implemented. Content reporting and owner disabling exist, but public moderation operations and abuse/cost controls need more work before an open launch. Native reporting and visibility controls still need parity with web. Native device identity/keyboard/player checks remain open.

Recovery primitives are implemented, but forced-crash, dropped-dispatch, duplicate-delivery, cancellation-race, fork-of-fork, and long-running soak tests have not all been exercised. Receipt/object cleanup, a fleet bootstrap updater, observability dashboards, schema evolution, and production deployment hardening are also unfinished. Do not infer those guarantees from the architecture roadmap.

Neon Auth migration

neon.ts enables managed Auth on the App project only. Auth routes proxy through Neon's official server SDK so web uses same-origin HttpOnly cookies and native persists the same managed session in SecureStore. Only code request, code sign-in, get-session, and sign-out routes are exposed by Glow. The App API independently rechecks verified email and the domain/invitation policy for protected operations; signing up directly at the managed Auth URL cannot bypass this access policy.

glow_auth_identities maps each managed identity to its existing Glow user by verified email. Existing creations, chats, and private player state retain their owner IDs. The first verified sign-in creates the mapping; existing mappings cannot be silently reassigned. Legacy password hashes and sessions are not imported into Neon Auth. Existing users must sign in again using an email code. The old public user table remains the Glow profile/ownership directory; Neon owns authentication in its separate managed schema.

Run pnpm db:migrate before deploying the API. NEON_AUTH_BASE_URL and NEON_AUTH_JWKS_URL are managed service configuration, injected into hosted Functions. scripts/setup.ts obtains them for local development. Add the web URL to Neon's trusted domains when changing hosts. Native code sign-in uses the same trusted web origin and requires no custom-scheme redirect.

Focused non-browser checks cover exact domain matching, rejected requests, unverified managed identities, ownership-ID translation, invalid codes, and native cookie persistence/expiry. The official SDK also passed live empty-session, disallowed-address, and invalid-code checks through the deployed API. Neon accepted a test sign-in email request for the developer. Web build, workspace types, and both native JavaScript exports pass. Real code receipt and a complete sign-in on a device still require testing with the recipient's inbox. Shared SMTP is for development; a public production rollout needs the email-provider setup described by Neon.