The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(backend): mint and remember each account's private grid name
bitcoinbuilder219ee4f7e54a
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 2c3a023b0..2acbbdb00 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -26,6 +26,11 @@ model User {// Which Autonomous account plane this user signs in against. Existing rows are backfilled to// staging because they were created while the app used staging globally; new users default prod.autonomousEnv String @default("prod") // prod | stag+ // The user's private harness grid, minted on first ask and never rewritten (see routes/grid.ts).+ // Deliberately NOT @unique: on MongoDB a unique index counts nulls as values, so every user+ // without a grid would collide with every other. Global uniqueness is the grid control plane's+ // rule to enforce; ours is only one name per user, which the conditional write in the route gives.+ gridName String?createdAt DateTime @default(now())updatedAt DateTime @updatedAtdiff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex 44d23eab2..c25f085f9 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -214,7 +214,13 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c}// Tell the adapter its machine's display name (it mirrors it locally for `harness status`); null when// unnamed so a stale mirror clears. Renames while connected arrive the same way (machine_meta).- send({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName } } })+ // The account's private harness grid, carried on the frame the adapter already gets on connect.+ // Minted and remembered by `routes/grid.ts`; read-only here. A user who has never signed in since+ // the route shipped simply has none yet, and the daemon treats that as "no grid" rather than an+ // error — the next `harness login` mints it.+ const gridName = (await prisma.user.findUnique({ where: { id: userId }, select: { gridName: true } })+ .catch(() => null))?.gridName ?? null+ send({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: currentName?.trim() || seededName, gridName } } })// The node role — down subscription, presence, `__clients` resync, node_status — is shared with// every other backer of a machine and lives in nodeRole.ts. Only the delivery and teardown arediff --git a/backend/src/lib/gridName.test.ts b/backend/src/lib/gridName.test.tsnew file mode 100644index 000000000..6b30cb6e9--- /dev/null+++ b/backend/src/lib/gridName.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { harnessGridName } from './gridName.js'++/**+ * The NAME only. The route's referee (a conditional `updateMany`) is a database property and is+ * covered where the other Prisma paths are; what is worth pinning here is the string itself, because+ * it is what a grid gets called forever — the stored value is authoritative and this formula runs+ * once.+ */+describe('harnessGridName', () => {+ const ID = '68c1f4a2b3d4e5f601234567'++ it('is the email local-part, a dash, and eight hex of the account id', () => {+ expect(harnessGridName('[email protected]', ID)).toMatch(/^anhthuychaucfc-[0-9a-f]{8}$/)+ })++ it('is stable for one account and different for another', () => {+ const mine = harnessGridName('[email protected]', ID)+ expect(harnessGridName('[email protected]', ID)).toBe(mine)+ // The case the email prefix alone cannot cover: same local-part, different person. Grid names+ // are globally unique, so these two must not collide.+ expect(harnessGridName('[email protected]', '68c1f4a2b3d4e5f60fedcba9')).not.toBe(mine)+ })++ it('reduces a local-part to what the grid CLI would slugify it to anyway', () => {+ // `gridProviderId` in the harness CLI maps [^a-z0-9]+ → '-', so doing it here means the stored+ // name and the sent name are the same string.+ expect(harnessGridName('[email protected]', ID)).toMatch(/^first-last-tag-[0-9a-f]{8}$/)+ })++ it('never produces a name that is only a suffix', () => {+ // A local-part of pure punctuation reduces to nothing; `user` is better than `-7f3a91c4`.+ expect(harnessGridName('[email protected]', ID)).toMatch(/^user-[0-9a-f]{8}$/)+ expect(harnessGridName('@example.com', ID)).toMatch(/^user-[0-9a-f]{8}$/)+ })++ it('bounds the local-part and never ends it on a dash', () => {+ const long = 'a'.repeat(80)+ const name = harnessGridName(`${long}@example.com`, ID)+ expect(name.length).toBeLessThanOrEqual(32 + 1 + 8)+ // A 32-char cut can land mid-dash-run; a trailing dash before the suffix would read as a typo.+ expect(name).not.toContain('--')+ expect(harnessGridName(`${'b'.repeat(31)}[email protected]`, ID)).not.toContain('--')+ })+})diff --git a/backend/src/lib/gridName.ts b/backend/src/lib/gridName.tsnew file mode 100644index 000000000..f3c4660ed--- /dev/null+++ b/backend/src/lib/gridName.ts@@ -0,0 +1,44 @@+import { createHash } from 'node:crypto'++/**+ * The user's private harness grid NAME — minted here, remembered here.+ *+ * The CLI cannot do this itself and should not try. `~/.harness/auth/session.json` holds tokens, a+ * machineId and a computerId — not the account's email and not its id — so a name derived on a+ * machine would differ from the one derived on the next machine, and the second machine would create+ * a SECOND grid rather than find the first. The backend holds both inputs and is the only party that+ * can referee two machines signing in at once, so the whole answer is minted here and handed out.+ */++/** Longest the email half may be, so the whole name stays readable at a glance. */+const LOCAL_PART_MAX = 32+/**+ * Hex characters of account-id hash appended to the email half.+ *+ * Collisions only matter between users who share an email local-part — `admin@`, `info@`, `dev@` are+ * the realistic cases, and they are exactly the ones most likely to be shared. At 8 hex (4.3 × 10⁹) a+ * thousand users on one local-part collide with probability ≈ 0.01%; at 6 it is ≈ 3%.+ */+const SUFFIX_HEX = 8++/**+ * `<email local-part>-<8 hex of sha256(user id)>`, e.g. `anhthuychaucfc-7f3a91c4`.+ *+ * Derived rather than random so the value is reproducible when someone has to support it. The stored+ * string is authoritative either way: this runs once, at mint, and changing it later never renames a+ * grid that already exists.+ *+ * The local part is reduced to `[a-z0-9-]` — the same reduction the CLI's `gridProviderId` applies+ * downstream — so what is stored is exactly what is sent to the control plane. `first.last@`,+ * `foo+tag@` and a local part of pure punctuation are all ordinary inputs; the last falls back to+ * `user` rather than producing a name that is only a suffix.+ */+export function harnessGridName(email: string, userId: string): string {+ const localPart = (email.split('@')[0] ?? '').toLowerCase()+ const slug = localPart+ .replace(/[^a-z0-9]+/g, '-')+ .slice(0, LOCAL_PART_MAX)+ .replace(/^-+|-+$/g, '')+ const suffix = createHash('sha256').update(userId).digest('hex').slice(0, SUFFIX_HEX)+ return `${slug || 'user'}-${suffix}`+}diff --git a/backend/src/routes/grid.ts b/backend/src/routes/grid.tsnew file mode 100644index 000000000..610e279c1--- /dev/null+++ b/backend/src/routes/grid.ts@@ -0,0 +1,40 @@+import type { FastifyInstance } from 'fastify'+import { prisma } from '../lib/prisma.js'+import { sendSuccess } from '../utils/response.js'+import { harnessGridName } from '../lib/gridName.js'++/**+ * `POST /api/grid/name` — read the account's grid name, minting it on the first ask.+ *+ * No body: the user comes from the SSO token the control API already gates on, never from the path,+ * so there is nothing here for one account to point at another's.+ *+ * Idempotent by construction, which is why there is no `GET` twin — a client that loses the response+ * asks again and gets the same string.+ */+export async function gridRoutes(app: FastifyInstance): Promise<void> {+ app.post('/api/grid/name', async (req, reply) => {+ const userId = req.user!.sub+ const minted = harnessGridName(req.user!.email, userId)++ // Compare-and-set, not a transaction: only a row that has NOT claimed a name matches, so two+ // machines signing in at once converge on one name instead of creating two grids.+ //+ // ⚠️ `gridName: null` alone is NOT enough on MongoDB — every user row written before this field+ // existed LACKS it entirely, and absent does not match null. This is the same trap `Machine.+ // deletedAt` documents in schema.prisma; `isSet: false` is what covers the legacy rows, and+ // without it the claim would never match anyone who signed up before today.+ const { count } = await prisma.user.updateMany({+ where: { id: userId, OR: [{ gridName: null }, { gridName: { isSet: false } }] },+ data: { gridName: minted },+ })+ if (count === 1) return sendSuccess(reply, { gridName: minted })++ // Someone else claimed it first (another machine of this user, moments ago) — or this account+ // has had a name for a while. Either way the stored value wins; the loser adopts rather than+ // creating a second grid. Falling back to `minted` covers only the impossible read-after-write+ // miss, and returns the same string the winner would have stored anyway.+ const existing = await prisma.user.findUnique({ where: { id: userId }, select: { gridName: true } })+ return sendSuccess(reply, { gridName: existing?.gridName ?? minted })+ })+}diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.tsindex 41538a50f..21a2b1481 100644--- a/backend/src/routes/index.ts+++ b/backend/src/routes/index.ts@@ -3,6 +3,7 @@ export * from './auth.js'export * from './users.js'export * from './machines.js'export * from './plans.js'+export * from './grid.js'export * from './devices.js'export * from './mobile.js'export * from './apps.js'diff --git a/backend/src/server.ts b/backend/src/server.tsindex 50c611d25..6c07eedf3 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -10,7 +10,7 @@ import { registerAuthMiddleware } from './middlewares/authMiddleware.js'import { cursorRoutes } from './routes/cursor.js'import { voiceRoutes } from './routes/voice.js'import { deviceAuthRoutes } from './routes/deviceAuth.js'-import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, agentRouteRoutes } from './routes/index.js'+import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, gridRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, agentRouteRoutes } from './routes/index.js'import { startSubdomainProxy, startMeshProxy } from './lib/subdomainProxy.js'import { handleDeviceUpgrade } from './lib/deviceWs.js'import { handleWebUpgrade } from './lib/webWs.js'@@ -139,6 +139,7 @@ async function start(): Promise<void> {await app.register(userRoutes)await app.register(machineRoutes)await app.register(planRoutes)+ await app.register(gridRoutes) // the account's private harness grid nameawait app.register(deviceRoutes)await app.register(mobileRoutes)await app.register(appRoutes)