The cloud side of Code Hands AI. In the current design it stores state and runs nothing: it holds accounts, devices and a synced copy of your sessions, memory and preferences, so signing in on another machine brings your work with you. Tasks always run on your own machine.
Owner: Memoona Contract: C3 (cloud API) in codehands-contracts Part of: Code Hands AI. Read the design in that README first.
Read this first. What is in this repo today is the week 1 relay, built for the first design, where a phone sent commands through the cloud to the laptop. The design has since moved to local-first (docs README). The daemon in
src/daemon.tsmoves out tocodehands-daemon(Midhat), and this repo becomes the state API plus the@codehands/syncclient. Both halves are described below: what runs today and where it is going.
flowchart LR
subgraph A["Desktop A: where the work runs"]
app["Desktop app"]
daemon["Daemon"]
sync["@codehands/sync (this repo)"]
daemon --- sync
end
subgraph C["Cloud: state only"]
api["State API (this repo)"]
pg[("Postgres")]
api --> pg
end
subgraph B["Desktop B: same account"]
daemonB["Daemon"]
end
app -- "C3: sign up, log in" --> api
sync -- "C3: push(changes)" --> api
api -- "C3: pull(cursor) on sign-in" --> daemonB
This repo will ship two things:
| Part | What | Runs |
|---|---|---|
| State API | Auth and device tokens, the synced schema in Postgres, push and pull endpoints, hosting |
On our Linux server |
@codehands/sync |
A small library the daemon loads. It pushes local changes up and pulls remote ones down, and the daemon writes them into state.db |
Inside the daemon on each machine |
The sync client is a library, not a process. One rule of the design is that only the daemon does work; another is that only the daemon writes the local tables other than tasks and commands. So the sync client hands rows to the daemon, and the daemon writes them.
| Data | Synced | How |
|---|---|---|
| Account, devices | Yes | Logging out on one machine revokes only that machine's token |
| Projects | Yes | By repo identity (a hash of the origin URL), not folder path. Each machine maps it to its own clone |
| Sessions | Yes | Prompt, agent, models, status, branch name, cost, times |
| Events | Yes | Append only, keyed by session and seq, so a resend is harmless. Raw agent output stripped |
| Diff | Small ones | Up to a size cap |
| Memory | Yes | Repo notes, task summaries, user memory, as versioned records |
| Preferences | Yes | Default agent, model per phase, app settings. Last write wins |
| Repo files, worktrees | Never | Each machine uses its own clone. A branch reaches another machine through GitHub |
| Credentials | Never | Agent logins, API keys, the app token. Each machine signs in itself |
| Raw output, big logs | Never | Stay in ~/.codehands/ on the machine that made them |
| Area | Endpoints |
|---|---|
| Auth | Sign up, log in, log out. Each login creates a device token; the desktop app keeps it in the OS keychain |
| Devices | List devices, revoke one |
| Sync | push(changes) with record versions, pull(cursor) returning everything after the cursor |
The shapes go into codehands-contracts first, with a mock server holding accounts in memory so the desktop app and the daemon can build against it before this API is live.
A Fastify server with Postgres and a WebSocket, plus a demo daemon that pretends to run tasks. It proves the week 1 loop: a command sent over HTTP reaches a laptop over its open connection, and the laptop's events come back and are stored within a second.
sequenceDiagram
participant P as Caller (curl, phone)
participant S as Server (src/server.ts)
participant DB as Postgres
participant D as Daemon (src/daemon.ts)
D->>S: WS /ws?token=…&deviceId=…
S-->>D: { type: "hello" }
P->>S: POST /commands { deviceId, type: "start" }
S->>DB: insert command, insert session (running)
S-->>D: { type: "command", commandType: "start", sessionId }
S-->>P: { commandId, sessionId, delivered: true }
D->>S: { type: "ack", commandId }
S->>DB: command acked
loop each step
D->>S: { type: "event", sessionId, eventType, clientEventId }
S->>DB: insert event
S-->>D: { type: "event_ack", clientEventId }
Note over D: logs the round trip in ms
end
| Path | What |
|---|---|
| src/server.ts | HTTP and WebSocket on one port. Keeps a map of connected daemons by device id |
| src/daemon.ts | Demo daemon. Connects, reconnects every 2 s after a drop, acks commands and plays a scripted task. Moving to codehands-daemon |
| src/migrate.ts | pnpm migrate. Applies the numbered files in db/migrations/ to DATABASE_URL |
| src/migrations.ts | The migration runner, so the command and the tests share it. Skips files already in schema_migrations |
| src/testclient.ts | An earlier hand-test client with a hard-coded device id and token |
| db/migrations/ | 001_start.sql … 004_synced_records.sql. One file per schema change; never edit one that has shipped, add the next number |
| docker-compose.yml | Local Postgres 16 on port 5434 |
| test/real-db.test.ts | pnpm test:db. Migrations and the main routes on a real Postgres |
| bin/codehands.js | codehands start runs the daemon |
| Method and path | Body | Returns |
|---|---|---|
GET /health |
{ ok: true, db_time }. Proves the database is reachable |
|
POST /commands |
{ deviceId, type, payload? }, type one of start, stop, approve, reject |
{ commandId, sessionId, delivered: true }, or 202 { commandId, delivered: false } when that device is not connected |
A start creates a session row and passes its id to the daemon. Other commands take the session id in payload.sessionId.
Connect to /ws?token=<DEV_TOKEN>&deviceId=<uuid>. A wrong token closes the socket with code 4001.
| Direction | type |
Fields |
|---|---|---|
| Server → daemon | hello |
deviceId |
| Server → daemon | command |
commandId, commandType, sessionId, payload |
| Daemon → server | ack |
commandId. Marks the command acked |
| Daemon → server | event |
sessionId, eventType, clientEventId, payload, deviceTs |
| Server → daemon | event_ack |
clientEventId, once the event is stored |
The demo daemon answers start with task.started, step.plan, step.implement, approval.requested; approve with step.test, task.finished; stop and reject with task.stopped and task.rejected.
You need Node 22, pnpm 10 and Docker (for the local database). This repo uses pnpm only, so do not run npm install.
pnpm install
cp .env.example .env # PowerShell: Copy-Item .env.example .env
docker compose up -d --wait # Postgres 16 on localhost:5434
pnpm migrate # builds the tables
pnpm dev # API on http://localhost:3001Then http://localhost:3001/health returns {"ok":true,...}. To start over with an empty database: docker compose down -v, then the same steps.
.env is git-ignored; .env.example explains every setting. To use a hosted database (Neon) instead of Docker, put its connection string in DATABASE_URL; never commit or share the file. A database made by the old db/schema.sql works too: pnpm migrate records the four files without changing existing data.
Migrations are the numbered files in db/migrations/. schema_migrations lists the ones a database has run, so pnpm migrate is safe to repeat. Change the tables by adding the next numbered file, never by editing an old one.
To prove it all works on a real database (needs docker compose up -d), run pnpm test:db. It makes a throwaway database, migrates it, starts the real server and calls /health, sign-up, devices, sync push and pull, sessions and commands. pnpm test stays free of Docker.
The port is 3001 because Langfuse uses 3000 on many laptops. For the desktop app, set VITE_CLOUD_URL=http://localhost:3001 in the desktop repo's ignored .env, then restart Vite/Tauri. Check /health before signing in. The desktop app never connects directly to the database. Confirm the Neon project and branch with the team before running migrations against a shared database.
The legacy daemon relay instructions below still use DEV_TOKEN and DEVICE_ID; those values are not needed for email/password desktop authentication. Fill DEVICE_ID in .env for them.
Send a command and watch both terminals:
curl -s localhost:3001/health
curl -s -X POST localhost:3001/commands \
-H 'content-type: application/json' \
-d '{"deviceId":"<DEVICE_ID>","type":"start"}'
# → { "commandId": "…", "sessionId": "…", "delivered": true }
curl -s -X POST localhost:3001/commands \
-H 'content-type: application/json' \
-d '{"deviceId":"<DEVICE_ID>","type":"approve","payload":{"sessionId":"<sessionId>"}}'Look at what was stored:
select type, device_ts, server_ts - device_ts as lag from events order by id desc limit 10;
select type, status, acked_at from commands order by created_at desc limit 5;These are fine for a week 1 demo and are what the next version fixes.
| Gap | Why it matters |
|---|---|
One shared DEV_TOKEN, sent in the query string |
No real accounts or per-device tokens. Query strings end up in logs |
A command for an offline device is stored as queued and never re-sent |
The daemon misses it after reconnecting |
| The schema does not match the contracts | Statuses here are pending, running, finished; the contracts have seven others. No projects table, no seq on events |
Event names are the demo's (step.plan, approval.requested) |
The contracts' RunnerEvent types replace them |
| No build script, tests or CI | Scripts run through tsx. bin/codehands.js must be run from the repo root |
- One branch per Linear issue, the issue id in the PR title.
- Any change to what the API accepts or returns is a C3 change: codehands-contracts first, then here, and the mock server updated the same week.
- Credentials, repo files and raw agent output must never reach this server. If a change would send them, it is the wrong change.
- No secrets in code or logs. Configuration comes from
.envlocally and from the host's secret store in production.