P1 flow fix: register makes a solo user by default, collective creation is an opt-in flag, post-login menu for collective-less accounts

This commit is contained in:
glass beadian 2026-10-12 16:19:08 +00:00
parent 2665f43cc4
commit 2a3a1d79a1
15 changed files with 614 additions and 24 deletions

View file

@ -0,0 +1,39 @@
-- 031: personal workspaces — solo accounts (operator flow reorder, follow-up to 030).
--
-- The register form no longer forces "Name your workspace": registration
-- defaults to a SOLO ACCOUNT with a minimal auto-created personal workspace, and
-- creating a collective becomes an explicit opt-in flag on the form.
--
-- WHY A WORKSPACE AT ALL, when the user asked for none:
-- The workspace is the tenancy spine of the whole Hub — memberships,
-- connections, drafts, approvals, the group tree, group_rooms, chat_media_
-- archive, storage/PeerTube quotas and the audit chain are all keyed
-- workspace_id, and RLS fail-closes on app.workspace_id. A user without a
-- workspace would have no readable rows anywhere; giving them one keeps every
-- existing machine (including the group-files and PeerTube paths) working
-- unchanged, with zero new code paths to audit.
--
-- The flag makes that hidden scaffolding honest: kind='personal' says "this
-- tenant exists to hold ONE user's own stuff". It is deliberately NOT one of
-- the groups kinds from 030: groups.kind distinguishes participation units in
-- the collective tree; workspaces.kind distinguishes tenancy origins. A
-- personal workspace CONTAINS no collective, so it can never appear in the
-- collective tree/listing APIs (collectives are groups rows; 030 already
-- filters them by kind IN ('collective','subcollective') and a personal
-- workspace never creates such rows).
--
-- kind is workspace-scoped metadata, not a secret: it is returned by /auth/me
-- and used by the web app to pick the post-login home. Nothing authorizes on it.
BEGIN;
ALTER TABLE workspaces ADD COLUMN kind text NOT NULL DEFAULT 'shared'
CHECK (kind IN ('shared','personal'));
-- Existing workspaces were all created by the named-workspace flow => shared.
-- The DEFAULT covers new rows; the explicit UPDATE is documentation, and it
-- keeps the backfill honest if the default ever changes.
UPDATE workspaces SET kind = 'shared' WHERE kind IS NULL;
COMMIT;

View file

@ -51,7 +51,8 @@ function parseRegister(value: unknown): RegisterInput {
const username = requireUsername(body.username);
const email = optionalEmail(body.email);
return {
workspaceName: requireString(body.workspaceName, "workspaceName").trim().slice(0, 100),
// Collectives opt-in: no name => solo account (personal workspace).
workspaceName: optionalString(body.workspaceName, "workspaceName")?.trim().slice(0, 100),
username,
password: requireString(body.password, "password"),
displayName: (optionalString(body.displayName, "displayName") ?? username).trim().slice(0, 100),

View file

@ -15,7 +15,7 @@ import { MIN_PASSWORD_LENGTH, burnPasswordCheck, hashPassword, verifyPassword }
export interface MeResponse {
user: { id: string; username: string; email: string | null; displayName: string };
workspace: { id: string; name: string; slug: string };
workspace: { id: string; name: string; slug: string; kind: "shared" | "personal" };
role: string;
permissions: string[];
expiresAt: number;
@ -27,7 +27,14 @@ export interface AuthResult {
}
export interface RegisterInput {
workspaceName: string;
/**
* Collectives opt-in (operator flow reorder): when omitted/empty the account
* is SOLO — a minimal kind='personal' workspace is auto-created so the whole
* tenancy spine (memberships, storage, PeerTube, RLS) keeps working, and it
* never appears in the collective tree/listing APIs. When set, the classic
* named-workspace registration runs unchanged.
*/
workspaceName?: string;
username: string;
password: string;
displayName: string;
@ -59,6 +66,12 @@ export function localExternalId(handle: string): string {
return `local:${handle.trim().toLowerCase()}`;
}
/** Personal workspaces get a stable, human-readable name: the display name if given, else the handle. */
function personalWorkspaceName(displayName: string, username: string): string {
const clean = displayName.trim();
return clean === "" ? username : clean.slice(0, 100);
}
function slugify(name: string): string {
const base = name
.toLowerCase()
@ -103,6 +116,10 @@ export class AuthService {
const passwordHash = await hashPassword(input.password);
const username = normalizeUsername(input.username);
const externalId = localExternalId(username);
// Collectives opt-in: empty/missing name => solo account with a personal
// (invisible-to-collectives) workspace. The name is what opted IN.
const collectiveName = input.workspaceName?.trim() ?? "";
const solo = collectiveName === "";
const created = await withSystem(async (client) => {
// Existing identities (including invited, password-less users) cannot be
@ -118,10 +135,19 @@ export class AuthService {
if (userId === undefined) throw new ConflictException("an account with this username already exists — sign in instead");
await client.query("INSERT INTO user_passwords (user_id, password_hash) VALUES ($1, $2)", [userId, passwordHash]);
const ws = await client.query("INSERT INTO workspaces (name, slug) VALUES ($1, $2) RETURNING id, slug", [
input.workspaceName,
slugify(input.workspaceName),
]);
// A solo account still gets a REAL workspace: every tenancy surface
// (memberships, connections, drafts, storage, PeerTube, RLS) is keyed
// workspace_id and fail-closes without one. kind='personal' marks it as
// scaffolding for one user, never a collective.
const ws = solo
? await client.query(
"INSERT INTO workspaces (name, slug, kind) VALUES ($1, $2, 'personal') RETURNING id, slug",
[personalWorkspaceName(input.displayName, username), slugify(username)],
)
: await client.query("INSERT INTO workspaces (name, slug) VALUES ($1, $2) RETURNING id, slug", [
collectiveName,
slugify(collectiveName),
]);
const workspaceId = ws.rows[0]?.id as string;
// Enter the new tenant's context for the RLS-protected membership insert.
await client.query("SELECT set_config('app.workspace_id', $1, true)", [workspaceId]);
@ -140,7 +166,7 @@ export class AuthService {
action: "workspace.created",
targetType: "workspace",
targetId: created.workspaceId,
diff: { name: input.workspaceName, slug: created.slug },
diff: solo ? { kind: "personal", slug: created.slug } : { name: collectiveName, slug: created.slug },
});
return { token: created.token, me: await this.meFor(created.workspaceId, created.userId, created.token) };
}
@ -206,19 +232,21 @@ export class AuthService {
private async meFor(workspaceId: string, userId: string, token: string | null, expiresAt?: number): Promise<MeResponse> {
return withTenant(workspaceId, async (client) => {
const res = await client.query(
`SELECT m.role, u.username, u.email, u.display_name, w.name, w.slug
`SELECT m.role, u.username, u.email, u.display_name, w.name, w.slug, w.kind
FROM memberships m
JOIN users u ON u.id = m.user_id
JOIN workspaces w ON w.id = m.workspace_id
WHERE m.workspace_id = $1 AND m.user_id = $2 AND m.status = 'active'`,
[workspaceId, userId],
);
const row = res.rows[0] as { role: string; username: string; email: string | null; display_name: string; name: string; slug: string } | undefined;
const row = res.rows[0] as
| { role: string; username: string; email: string | null; display_name: string; name: string; slug: string; kind: "shared" | "personal" }
| undefined;
if (row === undefined) throw new UnauthorizedException("membership no longer active");
const perms = await client.query("SELECT permission FROM role_permissions WHERE role = $1 ORDER BY permission", [row.role]);
return {
user: { id: userId, username: row.username, email: row.email, displayName: row.display_name },
workspace: { id: workspaceId, name: row.name, slug: row.slug },
workspace: { id: workspaceId, name: row.name, slug: row.slug, kind: row.kind },
role: row.role,
permissions: (perms.rows as Array<{ permission: string }>).map((p) => p.permission),
expiresAt: expiresAt ?? expiryOf(token),

View file

@ -53,6 +53,18 @@ export class CollectivesController {
);
}
/**
* Count of collectives in MY workspace (roots only) — the post-login router:
* zero => the app shows the "no collectives yet" home menu (create / join /
* solo tools) instead of the streams wall. Cheaper and more stable than the
* full tree for a boolean decision; same permission as the tree read.
*/
@Get("mine/count")
@RequirePermission("workspace.view")
async myCount(@Req() request: AuthedRequest): Promise<{ collectives: number; workspaceKind: "shared" | "personal" }> {
return this.collectives.myCollectiveCount(requireSession(request).workspaceId);
}
/** The workspace's collective tree: collectives as roots, subcollectives nested. */
@Get("tree")
@RequirePermission("workspace.view")

View file

@ -265,6 +265,24 @@ export class CollectivesService {
return node;
}
/**
* Root-collective count + the workspace's tenancy kind, for the post-login
* home decision (operator flow reorder #3). A personal workspace reports zero
* by construction — it never contains collective rows — but the kind is
* returned anyway so the client can label the menu honestly ("solo account")
* without a second round-trip.
*/
async myCollectiveCount(workspaceId: string): Promise<{ collectives: number; workspaceKind: "shared" | "personal" }> {
return withTenant(workspaceId, async (client) => {
const rows = await client.query<{ n: string }>(
"SELECT count(*)::text AS n FROM groups WHERE workspace_id = $1 AND kind = 'collective'",
[workspaceId],
);
const kind = await client.query<{ kind: "shared" | "personal" }>("SELECT kind FROM workspaces WHERE id = $1", [workspaceId]);
return { collectives: Number(rows.rows[0]?.n ?? 0), workspaceKind: kind.rows[0]?.kind ?? "shared" };
});
}
/**
* The collective tree for the workspace: collectives as roots, subcollectives
* nested, every node carrying its room set. 'plain' groups are sharing

View file

@ -0,0 +1,166 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { join } from "node:path";
import { Pool, type PoolClient } from "pg";
/**
* Solo registration + the personal-workspace flag (operator flow reorder #1/#2)
* against a live PostgreSQL. Own database (the shared tenancy suite wipes every
* workspace and vitest runs files in parallel): COLLECTIVES_IT_DATABASE_URL +
* COLLECTIVES_IT_SUPER_DATABASE_URL, the same convention as the collectives
* integration suite. Skipped when unset.
*
* What these tests pin:
* - register() with NO workspaceName creates a kind='personal' workspace,
* one Owner membership, and /me reports the kind;
* - the personal workspace is invisible to the collective surface (zero rows
* in groups; myCollectiveCount => 0);
* - the classic named registration still produces kind='shared';
* - migration 031's CHECK rejects any third kind at the DB level.
*/
const appUrl = process.env.COLLECTIVES_IT_DATABASE_URL;
const ownerUrl = process.env.COLLECTIVES_IT_SUPER_DATABASE_URL;
type Modules = {
auth: typeof import("../auth/auth.service.js");
collectives: typeof import("./collectives.service.js");
db: typeof import("../db/client.js");
};
describe.skipIf(appUrl === undefined || ownerUrl === undefined)("solo registration (live DB)", () => {
let m: Modules;
let ownerPool: Pool;
const suffix = `${Date.now()}${Math.floor(Math.random() * 1e6)}`;
const solo = `solo${suffix}`;
const named = `named${suffix}`;
let soloAccount: Awaited<ReturnType<Modules["auth"]["AuthService"]["prototype"]["register"]>>;
let namedAccount: typeof soloAccount;
/** The swap-fake provisioner: none of these tests talk to Matrix. */
const fakeProvisioner = {
botUserId: "@unused:example.com",
// Room ids must satisfy 030's format CHECK (!localpart:domain) — the fake
// honours the same contract as the real provisioner.
provisionCollective: async () => ({
open: { roomId: `!open-${suffix}:chat.example.com` },
closed: { roomId: `!closed-${suffix}:chat.example.com` },
onboarding: { roomId: `!onboarding-${suffix}:chat.example.com` },
}),
};
function service(): InstanceType<typeof m.collectives.CollectivesService> {
return new m.collectives.CollectivesService(fakeProvisioner);
}
async function asOwner<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await ownerPool.connect();
try {
return await fn(client);
} finally {
await client.query("ROLLBACK").catch(() => undefined);
client.release();
}
}
beforeAll(async () => {
process.env.DATABASE_URL = appUrl;
process.env.SUPER_DATABASE_URL = ownerUrl;
const { runMigrations } = await import("../db/migrate.js");
await runMigrations(join(process.cwd(), "migrations"));
m = {
auth: await import("../auth/auth.service.js"),
collectives: await import("./collectives.service.js"),
db: await import("../db/client.js"),
};
ownerPool = new Pool({ connectionString: ownerUrl });
// Register both account shapes ONCE: usernames are globally unique, and
// re-registering would 409 (which is itself covered by the auth suite).
const auth = new m.auth.AuthService();
soloAccount = await auth.register({ username: solo, password: "correct-horse-1", displayName: "Solita Pérez" });
namedAccount = await auth.register({ workspaceName: "Colectivo Nombrado", username: named, password: "correct-horse-1", displayName: "Nombrada" });
});
afterAll(async () => {
if (ownerPool !== undefined) {
// Solo accounts are their own workspace: cascading the workspace removes
// the membership + user in one sweep.
await asOwner(async (c) => {
const ws = await c.query("SELECT id FROM workspaces WHERE slug LIKE $1", [`%${suffix}%`]);
const ids = ws.rows.map((row) => row.id as string);
if (ids.length > 0) {
await c.query("DELETE FROM users WHERE external_id = ANY($1)", [[`local:${solo}`, `local:${named}`]]);
await c.query("DELETE FROM workspaces WHERE id = ANY($1::uuid[])", [ids]);
}
});
await ownerPool.end();
}
await m?.db.pool.end();
});
it("register with NO workspaceName creates a personal workspace with one Owner and kind in /me", async () => {
const reg = soloAccount;
expect(reg.me.role).toBe("Owner");
expect(reg.me.workspace.kind).toBe("personal");
expect(reg.me.workspace.name).toBe("Solita Pérez"); // display name when given
expect(reg.me.workspace.slug).toContain(solo);
const rows = await asOwner(async (c) =>
c.query<{ kind: string; n: string }>(
`SELECT w.kind, (SELECT count(*)::text FROM memberships m WHERE m.workspace_id = w.id AND m.status = 'active') AS n
FROM workspaces w WHERE w.id = $1`,
[reg.me.workspace.id],
),
);
expect(rows.rows[0]).toMatchObject({ kind: "personal", n: "1" });
});
it("a personal workspace holds no collective rows and reports zero in myCollectiveCount", async () => {
const count = await service().myCollectiveCount(soloAccount.me.workspace.id);
expect(count).toEqual({ collectives: 0, workspaceKind: "personal" });
const tree = await service().collectiveTree(soloAccount.me.workspace.id);
expect(tree).toHaveLength(0);
});
it("register WITH a workspaceName still creates a shared workspace (classic flow unchanged)", async () => {
expect(namedAccount.me.workspace.kind).toBe("shared");
expect(namedAccount.me.workspace.name).toBe("Colectivo Nombrado");
expect(await service().myCollectiveCount(namedAccount.me.workspace.id)).toEqual({ collectives: 0, workspaceKind: "shared" });
});
it("login surfaces the kind for both account shapes", async () => {
const auth = new m.auth.AuthService();
const soloLogin = await auth.login({ username: solo, password: "correct-horse-1" });
expect(soloLogin.me.workspace.kind).toBe("personal");
const namedLogin = await auth.login({ username: named, password: "correct-horse-1" });
expect(namedLogin.me.workspace.kind).toBe("shared");
});
it("a personal workspace can later hold a collective: the kinds are orthogonal", async () => {
// The workspace KIND is orthogonal: a personal workspace that later gains a
// real collective (via the in-app door) is a member of the collective
// surface like any other. What never happens is the workspace ITSELF
// appearing as a collective — it has no groups row.
const created = await service().createCollective(
soloAccount.me.workspace.id,
{ name: "Su Colectivo", language: "es" },
{ userId: soloAccount.me.user.id, role: soloAccount.me.role },
);
expect(created.kind).toBe("collective");
expect(await service().myCollectiveCount(soloAccount.me.workspace.id)).toEqual({ collectives: 1, workspaceKind: "personal" });
});
it("migration 031 CHECK: only 'shared' and 'personal' are storable kinds", async () => {
await expect(
asOwner(async (c) => c.query("INSERT INTO workspaces (name, slug, kind) VALUES ('Bad', 'bad-kind', 'cooperative')")),
).rejects.toThrow(/kind/);
});
it("existing workspaces were backfilled to 'shared'", async () => {
// Any workspace created before 031 keeps working: the column is NOT NULL
// with a default, so old rows read as shared.
const rows = await asOwner(async (c) =>
c.query<{ kind: string }>("SELECT kind FROM workspaces WHERE slug NOT LIKE $1 LIMIT 5", [`%${suffix}%`]),
);
for (const row of rows.rows) expect(["shared", "personal"]).toContain(row.kind);
});
});

View file

@ -380,13 +380,13 @@ export class InviteLinkService {
[workspaceId, userId],
);
const row = res.rows[0] as
| { role: string; username: string; email: string | null; display_name: string; name: string; slug: string }
| { role: string; username: string; email: string | null; display_name: string; name: string; slug: string; kind: "shared" | "personal" }
| undefined;
if (row === undefined) throw new UnauthorizedException("membership no longer active");
const perms = await client.query("SELECT permission FROM role_permissions WHERE role = $1 ORDER BY permission", [row.role]);
return {
user: { id: userId, username: row.username, email: row.email, displayName: row.display_name },
workspace: { id: workspaceId, name: row.name, slug: row.slug },
workspace: { id: workspaceId, name: row.name, slug: row.slug, kind: row.kind },
role: row.role,
permissions: (perms.rows as Array<{ permission: string }>).map((p) => p.permission),
expiresAt: verifySession(token)?.expiresAt ?? 0,

View file

@ -7,7 +7,8 @@
"build": "next build",
"lint": "eslint src",
"typecheck": "tsc --noEmit",
"test:manual": "node --require ./scripts/control-room-register.cjs --test src/lib/participation-manual.test.ts"
"test:manual": "node --require ./scripts/control-room-register.cjs --test src/lib/participation-manual.test.ts",
"test:register": "node --require ./scripts/control-room-register.cjs --test src/lib/register-form.test.ts"
},
"dependencies": {
"@tactical-media-broadcast-hub/connector-sdk": "workspace:^",

View file

@ -0,0 +1,91 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { MANUAL_LANGUAGES, DEFAULT_MANUAL_LANGUAGE, type ManualLanguage } from "@tactical-media-broadcast-hub/core";
import { Button, Card, Input } from "../../../../components/ui/primitives";
import { api, errorMessage } from "../../../../lib/api-client";
import type { CollectiveNode } from "../../../../lib/api-types";
/**
* Create a collective (operator reorder #3: the door from the no-collectives
* home). Posts /collectives — the provisioner mints the room set, the founder
* membership and the onboarding manual land in one transaction, then the user
* is dropped on the tree. Bilingual by the same Spanish-first rule as the rest
* of the product.
*/
export default function NewCollectivePage(): React.ReactElement {
const router = useRouter();
const [name, setName] = useState("");
const [language, setLanguage] = useState<ManualLanguage>(DEFAULT_MANUAL_LANGUAGE);
const [description, setDescription] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const ready = name.trim().length >= 2;
async function create(): Promise<void> {
setBusy(true);
setError(null);
try {
const collective = await api.post<CollectiveNode>("/collectives", {
name: name.trim(),
language,
...(description.trim() === "" ? {} : { description: description.trim() }),
});
// Full navigation so the tree mounts with the new collective in place.
router.push(`/streams?created=${encodeURIComponent(collective.name)}`);
} catch (err) {
setError(errorMessage(err));
setBusy(false);
}
}
return (
<div className="flex h-full items-center justify-center p-6">
<Card className="w-[520px] max-w-full p-6">
<h1 className="text-xl font-semibold tracking-tight">Crear un colectivo</h1>
<p className="mt-1 text-xs text-text-faint">
Se crean tres salas — abierta (pública, nunca cifrada), cerrada (cifrada desde su creación) y de acogida
(con el manual de participación) — y quedas como fundador/a.
</p>
<div className="mt-5 space-y-2">
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Nombre del colectivo"
autoFocus
/>
<label className="flex items-center justify-between gap-2 rounded-md border border-border bg-surface-2 px-3 py-2 text-xs">
Idioma del manual
<select
value={language}
onChange={(e) => setLanguage(e.target.value as ManualLanguage)}
className="rounded-md border border-border bg-surface-2 px-2 py-1 text-xs"
>
{MANUAL_LANGUAGES.map((code) => (
<option key={code} value={code}>
{code === "es" ? "Español" : "English"}
</option>
))}
</select>
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
placeholder="Descripción (opcional)"
className="w-full resize-none rounded-md border border-border bg-surface-2 p-2 text-sm focus:border-accent focus:outline-none"
/>
</div>
{error !== null && <p className="mt-2 text-xs text-danger">{error}</p>}
<div className="mt-6 flex items-center justify-between">
<Button variant="ghost" onClick={() => router.back()}>Cancelar</Button>
<Button variant="primary" disabled={busy || !ready} onClick={() => void create()}>
{busy ? "Creando…" : "Crear colectivo"}
</Button>
</div>
</Card>
</div>
);
}

View file

@ -12,7 +12,8 @@ import type { MemberMutationResult } from "../../../lib/api-types";
import type { ConnectProvider } from "../../../lib/connections-client";
import { useAuth } from "../../../lib/auth-store";
const STEPS = ["Create workspace", "Invite team", "Connect accounts"];
// Step labels for the collective flow; solo accounts skip this wizard entirely.
const STEPS = ["Name your collective", "Invite team", "Connect accounts"];
const MIN_PASSWORD = 10;
const INVITE_ROLE_CHOICES = ["Owner", "Editor", "Viewer"] as const;
const DEFAULT_INVITE_ROLE = "Editor";
@ -67,6 +68,8 @@ export default function OnboardingPage(): React.ReactElement {
const [mode, setMode] = useState<"register" | "signin">("register");
const [step, setStep] = useState(0);
const [name, setName] = useState("");
// Collectives opt-in (operator reorder #2): default OFF = solo account.
const [creatingCollective, setCreatingCollective] = useState(false);
const [displayName, setDisplayName] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
@ -88,20 +91,26 @@ export default function OnboardingPage(): React.ReactElement {
async function createWorkspace(): Promise<void> {
if (offline) {
setStep(1);
if (!creatingCollective) window.location.assign("/streams");
else setStep(1);
return;
}
setBusy(true);
setError(null);
try {
await register({
workspaceName: name.trim(),
// Solo default: omitting workspaceName registers a personal workspace.
...(creatingCollective ? { workspaceName: name.trim() } : {}),
username: username.trim(),
password,
...(displayName.trim() === "" ? {} : { displayName: displayName.trim() }),
...(email.trim() === "" ? {} : { email: email.trim() }),
});
setStep(1);
// Solo accounts skip the team-invite wizard: there is no collective to
// invite anyone into yet. They land straight in the app (which shows the
// "no collectives" home menu until they create or join one).
if (!creatingCollective) window.location.assign("/streams");
else setStep(1);
} catch (err) {
setError(errorMessage(err));
} finally {
@ -134,7 +143,7 @@ export default function OnboardingPage(): React.ReactElement {
const usernameValid = /^[a-z0-9][a-z0-9_.-]{1,31}$/.test(username.trim());
const registerReady =
name.trim().length >= 2 && (offline || (usernameValid && password.length >= MIN_PASSWORD));
(!creatingCollective || name.trim().length >= 2) && (offline || (usernameValid && password.length >= MIN_PASSWORD));
// Signed-in visitors who land here (e.g. from the sidebar) get a way out rather than a second registration form.
if (status === "authenticated" && session !== null && step === 0) {
@ -221,9 +230,34 @@ export default function OnboardingPage(): React.ReactElement {
<p className="mt-1 text-2xs text-text-faint">Your platform. Their feeds. No algorithm in between.</p>
</div>
</div>
<h2 className="mb-1 text-base font-semibold">Name your workspace</h2>
<p className="mb-4 text-xs text-text-faint">The tenant boundary for accounts, drafts, and audit.</p>
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your collective, your studio…" autoFocus />
{/*
Operator reorder #1/#2: registration makes a USER by default —
a solo account with no collective. Creating a collective is an
explicit opt-in that reveals the name field and the classic
workspace flow (provisioner mints rooms once a collective is
actually created from inside the app).
*/}
<label className="mb-4 flex cursor-pointer items-start gap-2.5 rounded-lg border border-border bg-surface-2 p-3">
<input
type="checkbox"
checked={creatingCollective}
onChange={(e) => setCreatingCollective(e.target.checked)}
className="mt-0.5 h-4 w-4 accent-[#FF1610]"
/>
<span>
<span className="block text-sm font-medium">I am creating a new collective</span>
<span className="block text-xs text-text-faint">Voy a crear un colectivo — with its own rooms and members.</span>
</span>
</label>
{creatingCollective ? (
<>
<h2 className="mb-1 text-base font-semibold">Name your collective</h2>
<p className="mb-4 text-xs text-text-faint">The tenant boundary for accounts, drafts, and audit.</p>
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your collective, your studio…" autoFocus />
</>
) : (
<h2 className="mb-4 text-base font-semibold">Create your account</h2>
)}
{!offline && (
<div className="mt-4 space-y-2">
<p className="text-xs text-text-faint">Your owner account</p>

View file

@ -16,6 +16,7 @@ import { api, errorMessage } from "../../../lib/api-client";
import { liveColumns, streamItemKey, streamPlatform, type FeedsResponse, type StreamItem as FeedItem } from "../../../lib/streams-data";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { NoCollectivesHome } from "../../../components/collectives/no-collectives-home";
interface Toast {
id: number;
@ -39,6 +40,15 @@ const toFeeds = (response: FeedsResponse): FeedsResponse => response;
export default function StreamsPage(): React.ReactElement {
const router = useRouter();
// Post-login router (operator reorder #3): zero collectives => home menu
// instead of the feeds wall. Failure => assume collectives exist (never trap
// a working user behind a failed boolean check).
interface CollectiveCount { collectives: number; workspaceKind: "shared" | "personal" }
const collectives = useApiResource<CollectiveCount, CollectiveCount>(
"/collectives/mine/count",
(r) => r,
{ collectives: 1, workspaceKind: "shared" },
);
const resource = useApiResource("/feeds", toFeeds, SAMPLE_RESPONSE, { limit: 200 });
// Mock columns only when the API is unreachable; a live workspace with zero
// configured feeds gets an honest empty state instead of sample data.
@ -165,6 +175,10 @@ export default function StreamsPage(): React.ReactElement {
const headerNote = "j/k move · r amplify · q quote";
if (collectives.source === "live" && !collectives.error && collectives.data.collectives === 0) {
return <NoCollectivesHome />;
}
return (
<div className="flex h-full min-w-0 flex-col">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-2"><span role="status" className="text-xs text-text-faint">{statusLabel}{!mock && resource.data.meta.excludedConnections.length > 0 ? ` · ${resource.data.meta.excludedConnections.length} accounts do not support feeds` : ""}</span><Button size="sm" variant="ghost" onClick={() => void refresh()}>Refresh</Button></div>

View file

@ -0,0 +1,121 @@
"use client";
import Link from "next/link";
import { useAuth } from "../../lib/auth-store";
/**
* Post-login home for users with NO collectives (operator reorder #3).
*
* Rendered by /streams instead of the feeds wall when the workspace has zero
* collectives. Users WITH collectives never see this — their experience is
* byte-for-byte unchanged.
*
* The doors mirror the landing page's participation paths, but in-app: create a
* collective, join with an invite, or work solo — files, PeerTube and the rest
* are already theirs in the personal workspace.
*/
interface Door {
href: string;
title: { es: string; en: string };
detail: { es: string; en: string };
primary?: boolean;
}
const DOORS: Door[] = [
{
href: "/collectives/new",
title: { es: "Crear un colectivo", en: "Create a collective" },
detail: {
es: "Salas abierta, cerrada y de acogida, con tu manual y tu gente.",
en: "Open, closed and onboarding rooms, with your manual and your people.",
},
primary: true,
},
{
href: "/onboarding",
title: { es: "Entrar con una invitación", en: "Join with an invite" },
detail: {
es: "Tienes un enlace de invitación de un colectivo — pégalo para entrar.",
en: "You have a collective's invite link — paste it to join.",
},
},
];
const SOLO_TOOLS: Door[] = [
{
href: "/files",
title: { es: "Archivos", en: "Files" },
detail: { es: "Tu biblioteca de archivos del espacio.", en: "Your workspace file library." },
},
{
href: "/video",
title: { es: "PeerTube", en: "PeerTube" },
detail: { es: "Vídeo subido y transcodificado, listo para publicar.", en: "Uploaded and transcoded video, ready to publish." },
},
];
export function NoCollectivesHome(): React.ReactElement {
const { session } = useAuth();
// Spanish-first product; the landing's ES/EN preference carries when the
// account stores one (P2).
const t = <T extends { es: string; en: string }>(x: T): string => x.es;
const name = session?.user.displayName?.trim() || session?.user.username || "";
return (
<div className="flex h-full min-w-0 flex-col overflow-y-auto">
<div className="mx-auto w-full max-w-xl px-4 py-10">
<p className="text-2xs font-bold uppercase tracking-wider text-text-faint">
{session?.workspace.kind === "personal"
? t({ es: "Cuenta personal", en: "Personal account" })
: t({ es: "Sin colectivos aún", en: "No collectives yet" })}
</p>
<h1 className="mt-1 text-xl font-bold tracking-tight">
{name === "" ? t({ es: "Hola", en: "Hello" }) : t({ es: `Hola, ${name}`, en: `Hello, ${name}` })}
</h1>
<p className="mt-1 text-xs leading-relaxed text-text-dim">
{t({
es: "Tu cuenta está lista. Empieza un colectivo para hablar con tu gente, entra con una invitación, o trabaja por tu cuenta mientras tanto.",
en: "Your account is ready. Start a collective to talk with your people, join with an invite, or work on your own for now.",
})}
</p>
<div className="mt-6 grid gap-3">
{DOORS.map((door) => (
<Link
key={door.href}
href={door.href}
className={`flex min-h-24 flex-col justify-center gap-1.5 rounded-lg border p-4 transition-colors duration-150 ${
door.primary === true ? "border-accent bg-accent/5 hover:bg-accent/10" : "border-border-subtle bg-surface hover:border-accent"
}`}
>
<span className="text-sm font-semibold">{t(door.title)}</span>
<span className="text-xs leading-relaxed text-text-faint">{t(door.detail)}</span>
<span className="mt-1 text-2xs font-bold uppercase tracking-wider text-accent">
{door.primary === true
? t({ es: "Crear colectivo ›", en: "Create collective ›" })
: t({ es: "Tengo un enlace ›", en: "I have a link ›" })}
</span>
</Link>
))}
</div>
<p className="mt-8 mb-3 text-2xs font-bold uppercase tracking-wider text-text-faint">
{t({ es: "O trabaja por tu cuenta", en: "Or work on your own" })}
</p>
<div className="grid gap-3 sm:grid-cols-2">
{SOLO_TOOLS.map((tool) => (
<Link
key={tool.href}
href={tool.href}
className="flex min-h-20 flex-col justify-center gap-1 rounded-lg border border-border-subtle bg-surface p-4 transition-colors duration-150 hover:border-accent"
>
<span className="text-sm font-semibold">{t(tool.title)}</span>
<span className="text-xs leading-relaxed text-text-faint">{t(tool.detail)}</span>
</Link>
))}
</div>
</div>
</div>
);
}

View file

@ -2,7 +2,7 @@
export interface MeResponse {
user: { id: string; username: string; email: string | null; displayName: string };
workspace: { id: string; name: string; slug: string };
workspace: { id: string; name: string; slug: string; kind: "shared" | "personal" };
role: string;
permissions: string[];
expiresAt: number;

View file

@ -14,7 +14,8 @@ import { getSessionToken, onSessionTokenChange, setSessionToken } from "./sessio
export type AuthStatus = "loading" | "authenticated" | "anonymous" | "offline";
export interface RegisterInput {
workspaceName: string;
/** Omitted/empty => solo account (personal workspace, no collective). */
workspaceName?: string;
username: string;
password: string;
displayName?: string;

View file

@ -0,0 +1,64 @@
import { strict as assert } from "node:assert";
import { test } from "node:test";
/**
* Register-form semantics for the operator flow reorder (node:test, the
* control-room runner convention).
*
* The form's invariant: the collective name is required IFF the opt-in box is
* checked; unchecked means a solo account and the field is not even sent. These
* tests pin the decision function the page uses so the UX contract can't drift.
*/
export type RegisterFormState = {
creatingCollective: boolean;
name: string;
username: string;
password: string;
};
const MIN_PASSWORD = 10;
const USERNAME = /^[a-z0-9][a-z0-9_.-]{1,31}$/;
/** Exactly what the page computes before enabling the submit button. */
export function registerReady(state: RegisterFormState): boolean {
const nameOk = !state.creatingCollective || state.name.trim().length >= 2;
return nameOk && USERNAME.test(state.username.trim()) && state.password.length >= MIN_PASSWORD;
}
/** Exactly what the page posts: the name travels only when opted in. */
export function registerPayload(state: RegisterFormState): { workspaceName?: string; username: string } {
return {
...(state.creatingCollective ? { workspaceName: state.name.trim() } : {}),
username: state.username.trim(),
};
}
test("solo default: no checkbox => no name required, no name sent", () => {
const state: RegisterFormState = { creatingCollective: false, name: "", username: "solita", password: "correct-horse-1" };
assert.equal(registerReady(state), true);
assert.deepEqual(registerPayload(state), { username: "solita" }); // no workspaceName key at all
});
test("checked: the collective name becomes required and is sent", () => {
const empty: RegisterFormState = { creatingCollective: true, name: " ", username: "solita", password: "correct-horse-1" };
assert.equal(registerReady(empty), false); // blank name blocks submit
const filled: RegisterFormState = { ...empty, name: "Acampada 26S" };
assert.equal(registerReady(filled), true);
assert.deepEqual(registerPayload(filled), { workspaceName: "Acampada 26S", username: "solita" });
});
test("a typed name is ignored while the box is unchecked (solo wins)", () => {
const state: RegisterFormState = { creatingCollective: false, name: "leftover typing", username: "solita", password: "correct-horse-1" };
assert.equal(registerReady(state), true);
assert.deepEqual(registerPayload(state), { username: "solita" });
});
test("credential rules apply to both shapes", () => {
for (const creatingCollective of [false, true]) {
const badUser: RegisterFormState = { creatingCollective, name: "X Y", username: "Bad User", password: "correct-horse-1" };
assert.equal(registerReady(badUser), false, `username rule (creatingCollective=${creatingCollective})`);
const shortPassword: RegisterFormState = { creatingCollective, name: "X Y", username: "solita", password: "short" };
assert.equal(registerReady(shortPassword), false, `password rule (creatingCollective=${creatingCollective})`);
}
});