Skip to content

Commit 3f453d4

Browse files
author
manno23
committed
fork: add web and function Cloudflare Workers infrastructure
- Rewrite packages/web/ from Astro SSR to SolidJS + Hono worker arch - Add Cloudflare Workers deployment via wrangler.jsonc - Add vite.config.ts, worker.ts, tsconfig variants for worker builds - Add SessionsList, Share components for fork's session viewer - Add web middleware, SPA routing, and CloudSession service bindings - Move docs content to docs/ subdirectory - Update packages/function/ for Cloudflare Workers deployment - Add function wrangler.jsonc, docs, and API route modifications
1 parent 6da4425 commit 3f453d4

93 files changed

Lines changed: 13344 additions & 1835 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

packages/function/.gitignore

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Local
2+
.env*
3+
.env.*
4+
5+
# Cloudflare
6+
.wrangler/
7+
.dev.vars
8+
.dev.vars.*
9+
worker-configuration.d.ts

packages/function/AGENTS.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
## Build/Test/Lint
2+
3+
- `bun dev` - Run local development with Wrangler
4+
- `wrangler dev` - Test against local Cloudflare environment
5+
- `wrangler deploy` - Deploy to Cloudflare Workers
6+
- No test framework - use manual testing or curl for endpoints
7+
8+
## Tech Stack
9+
10+
- **Hono** - Lightweight TypeScript web framework for Cloudflare Workers
11+
- **Durable Objects** - For session state management and WebSocket handling
12+
- **R2 Storage** - For persistent session data storage
13+
- **Cloudflare Workers** - Serverless compute platform
14+
- **TypeScript** - strict mode enabled
15+
16+
## Code Style
17+
18+
- Use async/await for async operations
19+
- Keep functions focused on single responsibilities
20+
- Use Hono middleware for cross-cutting concerns
21+
- Store critical data in both Durable Objects (for speed) and R2 (for durability)
22+
- Use JSON serialization for all R2 storage
23+
- Validate sessionID and secrets before any storage operations
24+
- Avoid try/catch where possible; use explicit error handling
25+
- Prefer single-word variable names where applicable
26+
27+
## Key Patterns
28+
29+
### Session ID Handling
30+
31+
- Full sessionID passed in request bodies
32+
- Short names (8-char suffix) derived using `SyncServer.shortName()`
33+
- Short names used for URL-friendly share links and Durable Object IDs
34+
35+
### Data Persistence
36+
37+
- Durable Object storage for real-time state
38+
- R2 for long-term persistence and backup
39+
- Metadata synced to both stores for resilience
40+
41+
### WebSocket Pattern
42+
43+
- Durable Objects handle WebSocket connections via `/share_poll`
44+
- On connection, send all stored session data to client
45+
- New updates broadcast to all connected clients
46+
47+
## Context
48+
49+
- Part of OpenCode session sharing infrastructure
50+
- Designed to scale horizontally via Durable Object partitioning
51+
- Session data lifetime matches Durable Object lifetime (auto-cleanup possible)
52+
- No authentication required (relies on secret tokens)
53+
- Admin endpoints require separate admin secret for operational tasks
54+
55+
## Cloudflare Integration
56+
57+
- **Durable Objects:** Binding name `SYNC_SERVER` with namespace `SyncServer`
58+
- **R2 Bucket:** Binding name `Bucket` for persistent storage
59+
- **Environment:** Development uses `localhost`, production uses configured domain
60+
- **Security:** Secrets stored via `wrangler secret put` (never in code)
61+
62+
## Common Tasks
63+
64+
### Adding a new endpoint
65+
66+
1. Add route to Hono app (`.post()`, `.get()`, etc.)
67+
2. Validate required query/body parameters
68+
3. Get or create Durable Object stub via `SyncServer.idFromName()`
69+
4. Call appropriate stub methods
70+
5. Return JSON response with proper error codes
71+
72+
### Modifying metadata tracking
73+
74+
1. Update `SyncServer.updateMetadata()` method
75+
2. Ensure R2 metadata files are updated in parallel
76+
3. Test with `POST /migrate_metadata` if adding new fields
77+
78+
### Debugging WebSocket issues
79+
80+
1. Check browser console for connection errors
81+
2. Use `wrangler tail` to view worker logs
82+
3. Verify `WEB_DOMAIN` environment variable matches actual domain
83+
4. Check Durable Object state in wrangler dashboard

packages/function/README.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# OpenCode Function - Session Sync Worker
2+
3+
## Project Structure
4+
5+
- **Framework:** Hono (lightweight web framework for Cloudflare Workers)
6+
- **Deployment:** Cloudflare Workers + Durable Objects + R2
7+
- **Type Safety:** TypeScript strict mode
8+
- **Storage:** R2 buckets for session data persistence
9+
- **Real-time:** WebSocket support via Durable Objects
10+
11+
## Key Components
12+
13+
### SyncServer (Durable Object)
14+
15+
- Manages real-time WebSocket connections for session synchronization
16+
- Stores session data in Durable Object storage
17+
- Persists messages and metadata to R2 buckets
18+
- Handles session sharing with secret-based access
19+
- Supports session metadata tracking (message count, token usage, timestamps)
20+
21+
### API Endpoints
22+
23+
- `POST /share_create` - Create a shareable session with secret token
24+
- `POST /share_delete` - Delete session (requires valid secret)
25+
- `POST /share_delete_admin` - Admin deletion endpoint (requires admin secret)
26+
- `POST /share_sync` - Sync session data (messages, parts, info)
27+
- `GET /share_poll` - WebSocket endpoint for real-time updates
28+
- `GET /share_data` - Fetch complete session data
29+
- `GET /sessions_list` - List all shared sessions with metadata
30+
- `POST /migrate_metadata` - Admin endpoint for metadata migration
31+
32+
## Development Commands
33+
34+
```bash
35+
bun dev # Local dev with hot reload
36+
bun build # Build for Cloudflare Workers
37+
wrangler dev # Test against local Cloudflare environment
38+
```
39+
40+
## Environment Variables
41+
42+
- **SYNC_SERVER** - Durable Object namespace reference
43+
- **Bucket** - R2 bucket for session storage
44+
- **WEB_DOMAIN** - Domain for share URLs (CORS origin)
45+
- **ADMIN_SECRET** - Secret key for admin operations
46+
47+
## Data Structure
48+
49+
### Session Metadata
50+
51+
```typescript
52+
{
53+
id: string // Short name (last 8 chars of sessionID)
54+
sessionID: string // Full session identifier
55+
title: string // Session title
56+
directory: string // Working directory
57+
messageCount: number // Total messages in session
58+
inputTokens: number // Total input tokens used
59+
outputTokens: number // Total output tokens used
60+
createdAt: string // ISO timestamp
61+
updatedAt: string // ISO timestamp
62+
}
63+
```
64+
65+
### Message Structure (in Durable Storage)
66+
67+
```
68+
session/info/{sessionID} // Session metadata
69+
session/message/{sessionID}/{id} // Individual messages
70+
session/part/{sessionID}/{partId} // Message parts (streaming)
71+
```
72+
73+
## Cloudflare Configuration (wrangler.jsonc)
74+
75+
- **Durable Objects:** SyncServer binding for session management
76+
- **R2 Bindings:** Bucket configuration for persistent storage
77+
- **Routes:** Specific routes for session sharing endpoints
78+
- **Secrets:** Admin credentials and domain configuration
79+
80+
## Agent Reminders
81+
82+
- Always check `wrangler.jsonc` for current bindings and environment setup
83+
- Session data is stored in R2 with prefix `share/` for accessibility
84+
- Metadata is synced to R2 for quick listing without Durable Object access
85+
- WebSocket connections are managed per session ID via SyncServer instances
86+
- Short names (8-char suffix) are used for URL-friendly share links
87+
- Ensure `WEB_DOMAIN` is properly configured for CORS on share endpoints
88+
89+
## Architecture Overview
90+
91+
```
92+
Client (web) → /share_poll (WebSocket) → SyncServer (Durable Object)
93+
94+
R2 Storage
95+
96+
Durable Storage
97+
```
98+
99+
Real-time updates flow through WebSocket, while historical data is served from R2 and Durable storage.

0 commit comments

Comments
 (0)