Skip to content
中文

Build a teacher's AI twin

A teacher says “make me an AI twin my students can talk to”. This page delivers three things:

  • a twin page that works on a phone;
  • entry for students by scanning a QR code and typing a passcode and their name, with no sign-up;
  • an admin page for the teacher: the link, the QR code, the passcode, who has joined, and a way to disable someone.

The chat is the Praxis Kit, never a chat UI of your own. Everything around it is an ordinary Praxis application.

Support bubbles, docs Q&A, lead generation and communities use the same code with four things changed: the scenario, the shape, the access and the AI style (see the end of the page).

Result

PathWhat students or the teacher see
/A full-page chat: the teacher’s name and a one-line intro, a greeting, four suggested questions and the input
/joinPasscode and name, then “进入”. The device is remembered for 30 days
/j/<link>List access: one personal link per person, which signs them in directly
/admin/entranceThe teacher’s share page: the link, the QR code, the passcode (changeable), a ready-to-forward sentence, and the people who joined (each can be disabled; in list mode, a person’s link can be regenerated)

Before you start

  • The praxis CLI 0.5.0 or later, which supports "platform": true in praxis.jsonc, and Bun.
  • A service agent: praxis.agent.agents.create with kind: "service", model: "deepseek-flash", and a system prompt written from the skeleton below.
  • The teacher’s material in a vector store of the knowledge base (praxis.knowledge.vectorStores), bound to the agent as vector_store with access set to read_only. See Configure an agent.

The instruction skeleton:

You are Yoko's AI twin and serve the students of her English writing class. You help them revise essays and explain writing methods.
Tone: patient and encouraging, like a kind teacher. Never hand over a full answer: ask what the student thinks first, then hint step by step.
Search the knowledge base before answering writing questions; if the material does not cover it, say so.
You do not write whole essays or answer questions unrelated to English writing.
When you cannot answer, or it needs Yoko herself: tell the student to ask Yoko directly.
Keep answers short enough to read on a phone.

Steps

  1. Run praxis app create <name> and add the files from Full code. In wrangler.jsonc vars, set AGENT_ID, and set ENTRANCE_MODE to passcode.

  2. Run bun add qrcode@1.5.4 && bun add -d @types/qrcode@1.5.5. Then, in app/layout.tsx:

    • set <html lang="zh-CN"> for a Chinese audience;
    • set the site name to the twin’s name and translate the navigation;
    • add a link to /admin/entrance next to the admin link.
  3. Run bun run typecheck && bun run build, then praxis app publish. Note the url it prints.

  4. Add that URL’s origin to the agent’s embed policy:

    • read the current allowed_origins with praxis.agent.agents.retrieveEmbedPolicy({ path: { agent_id } });
    • write the extended list back with praxis.agent.agents.updateEmbedPolicy({ path: { agent_id }, body: { allowed_origins } }).

    See Embed settings.

  5. Register the teacher’s admin account at /register right away, because the first account becomes admin. Then open /admin/entrance and read the passcode.

Full code

The files below sit on top of the template that praxis app create generates, which already includes sign-in, the database and lib/auth.ts.

praxis.jsonc (keep the name praxis app create wrote; add platform):

{
"$schema": "https://deepraxis.com/schemas/praxis.json",
"kind": "application",
"name": "<app-name>",
"secrets": { "SESSION_SECRET": "generate" },
"healthcheck": "/api/health",
"platform": true
}

In wrangler.jsonc, add after the bindings:

"vars": {
"PRAXIS_API_URL": "https://api.deepraxis.com",
"AGENT_ID": "agent_REPLACE_ME",
"ENTRANCE_MODE": "passcode",
"PUBLISHABLE_KEY": ""
}

env.d.ts

// Types of the bindings declared in wrangler.jsonc and the secrets declared in praxis.jsonc.
// Read them with `import { env } from "cloudflare:workers"`; add a line here for every new one.
declare namespace Cloudflare {
interface Env {
DB: D1Database;
IMAGES: R2Bucket;
ASSETS: Fetcher;
/** Signs session cookies; created by `praxis app publish` ("generate" in praxis.jsonc). */
SESSION_SECRET?: string;
/** Publish Agent: the Praxis API this app was deployed to (https://api.deepraxis.com). */
PRAXIS_API_URL: string;
/** The service agent people chat with (agent_…). */
AGENT_ID: string;
/** open | passcode | list */
ENTRANCE_MODE: string;
/** Open mode only: the publishable key (public by design). */
PUBLISHABLE_KEY?: string;
}
}

migrations/0002_entrance.sql

-- Publish Agent entrance: who may chat, without accounts of their own.
CREATE TABLE IF NOT EXISTS entrance_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- A member is a users row (role 'user', unusable password) plus the name people typed or the owner gave.
CREATE TABLE IF NOT EXISTS members (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
link_hash TEXT UNIQUE,
disabled INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);

In lib/migrations.ts, import it as m0002 from "../migrations/0002_entrance.sql?raw" and append { name: "0002_entrance", sql: m0002 }. Append to lib/schema.ts:

export const entranceSettings = sqliteTable("entrance_settings", {
key: text("key").primaryKey(),
value: text("value").notNull(),
});
export const members = sqliteTable("members", {
userId: text("user_id").primaryKey(),
name: text("name").notNull(),
linkHash: text("link_hash").unique(),
disabled: integer("disabled").notNull().default(0),
createdAt: integer("created_at").notNull(),
});

lib/entrance.ts

// Publish Agent entrance: who may chat, and the Kit grant code for them. Members never register; they are a users
// row with an unusable password, signed in with the template's own session cookie.
import { env } from "cloudflare:workers";
import { and, eq } from "drizzle-orm";
import { hashPassword, newSessionToken, sha256Hex } from "./auth";
import type { Db } from "./db";
import { entranceSettings, members } from "./schema";
import { createUser, type User } from "./users";
export type EntranceMode = "open" | "passcode" | "list";
export const entranceMode = (): EntranceMode =>
env.ENTRANCE_MODE === "open" || env.ENTRANCE_MODE === "list" ? env.ENTRANCE_MODE : "passcode";
/** A six-digit passcode; easy to say aloud in a class or a group chat. */
export const newPasscode = () => String(100000 + (crypto.getRandomValues(new Uint32Array(1))[0]! % 900000));
export async function getPasscode(db: Db): Promise<string> {
const [row] = await db.select().from(entranceSettings).where(eq(entranceSettings.key, "passcode")).limit(1);
if (row) return row.value;
const passcode = newPasscode();
await db.insert(entranceSettings).values({ key: "passcode", value: passcode }).onConflictDoNothing();
return (await db.select().from(entranceSettings).where(eq(entranceSettings.key, "passcode")).limit(1))[0]!.value;
}
export async function setPasscode(db: Db, passcode: string) {
await db.insert(entranceSettings).values({ key: "passcode", value: passcode })
.onConflictDoUpdate({ target: entranceSettings.key, set: { value: passcode } });
}
/** A member account: a random username and a password nobody knows, so it can only be entered through the entrance. */
async function createMember(db: Db, name: string, linkHash: string | null): Promise<User> {
const created = await createUser(db, { username: `m_${newSessionToken().slice(0, 12).toLowerCase().replace(/[^a-z0-9]/g, "0")}`, passwordHash: await hashPassword(newSessionToken()) });
if (!created.ok) throw new Error("member username collision; try again");
await db.insert(members).values({ userId: created.user.id, name, linkHash, createdAt: Date.now() });
return created.user;
}
export const nameSchemaMax = 20;
export const cleanName = (value: unknown) => typeof value === "string" ? value.trim().slice(0, nameSchemaMax) : "";
/** Passcode mode: anyone who knows the passcode joins once with a name. */
export async function joinWithPasscode(db: Db, name: string, passcode: string): Promise<User | "wrong-passcode"> {
if (passcode.trim() !== await getPasscode(db)) return "wrong-passcode";
return createMember(db, name, null);
}
/** List mode: the owner adds a person and gets their personal link token (shown once; only its hash is stored). */
export async function addListMember(db: Db, name: string): Promise<{ user: User; token: string }> {
const token = newSessionToken();
return { user: await createMember(db, name, await sha256Hex(token)), token };
}
/** The member a personal link names, unless disabled. */
export async function memberByLink(db: Db, token: string) {
const [row] = await db.select().from(members).where(and(eq(members.linkHash, await sha256Hex(token)), eq(members.disabled, 0))).limit(1);
return row ?? null;
}
/** Who may chat: an enabled member, or the admin (the owner trying it out). */
export async function chatterOf(db: Db, user: User | null): Promise<{ id: string; name: string } | null> {
if (!user) return null;
if (user.role === "admin") return { id: user.id, name: user.username };
const [row] = await db.select().from(members).where(eq(members.userId, user.id)).limit(1);
return row && row.disabled === 0 ? { id: user.id, name: row.name } : null;
}
/** One single-use Kit grant code for this person, bound to this page's origin. Needs "platform": true in praxis.jsonc. */
export async function issueGrantCode(chatter: { id: string; name: string }, origin: string): Promise<string> {
const response = await fetch(`${env.PRAXIS_API_URL}/customer/v1/grant_codes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: `member_${chatter.id}`,
metadata: { name: chatter.name },
resources: [`agent:${env.AGENT_ID}:chat`],
origin,
}),
});
if (!response.ok) throw new Error(`grant code failed: HTTP ${response.status} ${(await response.text()).slice(0, 300)}`);
const body = await response.json() as { code?: string };
if (!body.code) throw new Error("grant code response has no code");
return body.code;
}
/** Ends every Kit sign-in of this person at once (used when the owner disables someone). */
export async function revokeChatSignIns(userId: string): Promise<void> {
const response = await fetch(`${env.PRAXIS_API_URL}/customer/v1/customers/${encodeURIComponent(`member_${userId}`)}/revoke_tokens`, { method: "POST" });
// 404: the person never opened the chat, so there is nothing to end.
if (!response.ok && response.status !== 404) throw new Error(`revoke failed: HTTP ${response.status}`);
}
/** List mode: a new personal link for one person; the old link stops working at once. Returns the new token. */
export async function regenerateLink(db: Db, userId: string): Promise<string> {
const token = newSessionToken();
await db.update(members).set({ linkHash: await sha256Hex(token) }).where(eq(members.userId, userId));
return token;
}

lib/chat-options.ts

// Kit options of this entrance (see the Kit component reference): who the agent is, its look and its start screen.
// Change the agent's look only here; never restyle the Kit's internals.
export const CHAT_OPTIONS = {
agent: { name: "Yoko 老师的 AI 分身" /* , avatar: "https://…" only when the owner gives a picture */ },
layout: "inline",
header: { title: "Yoko 老师的 AI 分身", subtitle: "基于 Yoko 老师的讲义与答疑" },
startScreen: {
greeting: "嗨,我是 Yoko 的 AI 分身。我不会直接给你答案,会陪你一步步把作文改好。",
prompts: [
{ label: "这篇作文的结构哪里有问题?", prompt: "这篇作文的结构哪里有问题?" },
{ label: "帮我检查语法错误", prompt: "帮我检查语法错误" },
{ label: "怎么写一个好的开头?", prompt: "怎么写一个好的开头?" },
{ label: "考前怎么复习写作?", prompt: "考前怎么复习写作?" },
],
},
composer: { placeholder: "问 Yoko 的分身…" },
footer: "AI 生成内容仅供参考 · 拿不准的问题请找 Yoko 老师本人",
theme: { accent: "#1F6F66", grayscale: "warm", radius: "lg" },
locale: "zh",
};

components/kit-chat.tsx

// The chat is the Praxis Kit (<praxis-agent>), loaded from the Praxis CDN. Nothing here restyles the Kit: change its
// look through `options` (theme, header, startScreen, composer, footer). Server component: it renders the element and
// one module script; the page signs in once with configure(), the element takes its identity from that sign-in.
import { env } from "cloudflare:workers";
/** Kit options (see the Kit component reference). `agent` is filled in from AGENT_ID. */
export type KitOptions = Record<string, unknown>;
const cdnOf = (_apiUrl: string) => "https://cdn.deepraxis.com";
/** JSON inside an inline script: escape "<" so a value can never close the script tag. */
const inline = (value: unknown) => JSON.stringify(value).replace(/</g, "\\u003c");
export function KitChat({ options, credential, className = "", height = "100%" }: {
options: KitOptions;
/** "grant": the page asks /api/praxis-grant-code (members, list, the owner's login); "open": the publishable key. */
credential: "grant" | "open";
className?: string;
height?: string;
}) {
const api = env.PRAXIS_API_URL;
const cdn = cdnOf(api);
const script = `
import { configure } from "${cdn}/v1/praxis-session.js";
const api = ${inline(api)};
const credential = ${inline(credential)};
const options = ${inline({ ...options, agent: { ...(options.agent as object ?? {}), id: env.AGENT_ID } })};
async function signIn() {
if (credential === "open") { configure({ api: { url: api, publishableKey: ${inline(env.PUBLISHABLE_KEY ?? "")} } }); return; }
const response = await fetch("/api/praxis-grant-code", { method: "POST", credentials: "same-origin", cache: "no-store" });
if (response.status === 401) { location.href = "/join"; return; }
if (!response.ok) throw new Error("grant code " + response.status);
configure({ api: { url: api, grantCode: (await response.json()).code } });
}
await signIn();
await import("${cdn}/v1/praxis-kit.js");
await customElements.whenDefined("praxis-agent");
const element = document.querySelector("praxis-agent");
element.setOptions(options);
// A sign-in that ended (expired, revoked) is renewed with a fresh grant code; the conversation history stays.
element.addEventListener("praxis.session.end", () => { signIn().catch(() => {}); });
element.addEventListener("praxis.error", () => { document.querySelector("#chat-status").textContent = "对话暂时不可用,请稍后刷新重试。"; });
`;
return (
<div className={className} style={{ height }}>
<div style={{ height: "100%" }} dangerouslySetInnerHTML={{ __html: `<praxis-agent style="display:block;height:100%;width:100%"></praxis-agent>` }} />
<p id="chat-status" role="status" className="sr-only" />
<script type="module" dangerouslySetInnerHTML={{ __html: script }} />
</div>
);
}

app/page.tsx

// The entrance: a full-page chat. Members (or the owner) only, unless ENTRANCE_MODE is open.
import { redirect } from "next/navigation";
import { KitChat } from "@/components/kit-chat";
import { getDb } from "@/lib/db";
import { chatterOf, entranceMode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
import { CHAT_OPTIONS } from "@/lib/chat-options";
export const dynamic = "force-dynamic";
export default async function Home() {
const open = entranceMode() === "open";
if (!open && !(await chatterOf(await getDb(), await getCurrentUser()))) redirect("/join");
// fixed + inset-0 covers the template's header and container: the chat owns the whole screen. On a wide screen the
// conversation stays a readable column (max-w-3xl) instead of stretching edge to edge; the Kit itself is untouched.
return (
<div className="fixed inset-0 z-50 flex justify-center bg-background">
<KitChat className="h-full w-full max-w-3xl" options={CHAT_OPTIONS} credential={open ? "open" : "grant"} />
</div>
);
}

app/join/page.tsx

// How people get in without an account: the passcode and a name (passcode mode). List mode uses personal links (/j/…).
import { redirect } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getDb } from "@/lib/db";
import { chatterOf, entranceMode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
import { CHAT_OPTIONS } from "@/lib/chat-options";
export const dynamic = "force-dynamic";
const ERRORS: Record<string, string> = { passcode: "口令不对,请向发给你链接的人确认。", name: "请填写你的名字(最多 20 个字)。" };
export default async function Join({ searchParams }: { searchParams: Promise<{ error?: string; name?: string }> }) {
const mode = entranceMode();
if (mode === "open" || await chatterOf(await getDb(), await getCurrentUser())) redirect("/");
const { error, name } = await searchParams;
const title = CHAT_OPTIONS.header.title;
return (
<div className="fixed inset-0 z-50 overflow-y-auto bg-background">
<div className="mx-auto flex min-h-full max-w-sm flex-col justify-center gap-8 px-6 py-12">
<div className="flex flex-col items-center gap-3 text-center">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-accent text-3xl font-semibold text-primary">{title.slice(0, 1)}</div>
<h1 className="text-xl font-semibold">{title}</h1>
<p className="text-sm text-muted-foreground">{CHAT_OPTIONS.header.subtitle}</p>
</div>
{mode === "list" ? (
<p className="text-center text-sm text-muted-foreground">请使用发给你的专属链接或二维码进入。</p>
) : (
<form action="/api/entrance/join" method="post" className="flex flex-col gap-5">
<div className="flex flex-col gap-2">
<Label htmlFor="passcode">口令</Label>
<Input id="passcode" name="passcode" inputMode="numeric" autoComplete="off" placeholder="请输入 6 位口令" required />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="name">你的名字</Label>
<Input id="name" name="name" maxLength={20} defaultValue={name ?? ""} placeholder="怎么称呼你" required />
</div>
{error && ERRORS[error] && <p role="alert" className="text-sm text-destructive">{ERRORS[error]}</p>}
<Button type="submit" className="w-full">进入</Button>
<p className="text-center text-xs text-muted-foreground">不用注册。下次打开会记住你。</p>
</form>
)}
</div>
</div>
);
}

app/api/entrance/join/route.ts

import { env } from "cloudflare:workers";
import { MissingSecretError, requireSecret } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { cleanName, entranceMode, joinWithPasscode } from "@/lib/entrance";
import { redirectResponse } from "@/lib/guard";
import { createSession, sessionCookie } from "@/lib/session";
// Passcode mode only. A wrong passcode costs nothing but a retry; rate limiting per IP would go here.
export async function POST(req: Request) {
try {
requireSecret(env.SESSION_SECRET);
if (entranceMode() !== "passcode") return redirectResponse("/join");
const form = await req.formData();
const name = cleanName(form.get("name"));
if (!name) return redirectResponse("/join?error=name");
const db = await getDb();
const member = await joinWithPasscode(db, name, String(form.get("passcode") ?? ""));
if (member === "wrong-passcode") return redirectResponse(`/join?error=passcode&name=${encodeURIComponent(name)}`);
const session = await createSession(db, member.id, env.SESSION_SECRET);
return redirectResponse("/", sessionCookie(session.value, session.expiresAt));
} catch (e) {
if (e instanceof MissingSecretError) return new Response(e.message, { status: 500 });
throw e;
}
}

app/j/[token]/route.ts

// List mode: a personal link signs its person in and opens the chat.
import { env } from "cloudflare:workers";
import { getDb } from "@/lib/db";
import { memberByLink } from "@/lib/entrance";
import { redirectResponse } from "@/lib/guard";
import { createSession, sessionCookie } from "@/lib/session";
export async function GET(_req: Request, { params }: { params: Promise<{ token: string }> }) {
const db = await getDb();
const member = await memberByLink(db, (await params).token);
if (!member) return new Response("这个链接已失效,请联系发给你链接的人。", { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8" } });
const session = await createSession(db, member.userId, env.SESSION_SECRET);
return redirectResponse("/", sessionCookie(session.value, session.expiresAt));
}

app/api/praxis-grant-code/route.ts

// The Kit asks here for a single-use grant code for the signed-in member (or the owner). Never cache a code.
import { getDb } from "@/lib/db";
import { chatterOf, issueGrantCode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
export async function POST(req: Request) {
const chatter = await chatterOf(await getDb(), await getCurrentUser(req.headers.get("cookie")));
if (!chatter) return Response.json({ error: "not signed in" }, { status: 401 });
const code = await issueGrantCode(chatter, new URL(req.url).origin);
return Response.json({ code }, { headers: { "Cache-Control": "no-store" } });
}

app/admin/entrance/page.tsx

// The owner's entrance page: the link and QR code to share, the passcode, and who has joined.
import { desc, eq } from "drizzle-orm";
import { headers } from "next/headers";
import QRCode from "qrcode";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { getDb } from "@/lib/db";
import { entranceMode, getPasscode } from "@/lib/entrance";
import { formatDateTime } from "@/lib/format";
import { requireAdmin } from "@/lib/guard";
import { members } from "@/lib/schema";
export const dynamic = "force-dynamic";
export default async function EntranceAdmin({ searchParams }: { searchParams: Promise<{ link?: string; name?: string }> }) {
await requireAdmin("/admin/entrance");
const db = await getDb();
const mode = entranceMode();
const h = await headers();
const origin = `https://${h.get("host")}`;
const [passcode, people] = await Promise.all([
mode === "passcode" ? getPasscode(db) : Promise.resolve(null),
db.select().from(members).orderBy(desc(members.createdAt)),
]);
const qr = await QRCode.toString(origin, { type: "svg", margin: 1, width: 160 });
const { link, name } = await searchParams;
const share = mode === "passcode" ? `扫码或打开 ${origin} ,输入口令 ${passcode} 就能开始问。` : mode === "open" ? `打开 ${origin} 就能开始问。` : "";
return (
<div className="space-y-6">
<Card>
<CardHeader><CardTitle>分享给使用的人</CardTitle></CardHeader>
<CardContent className="flex flex-col gap-6 sm:flex-row sm:items-start">
<div className="flex h-44 w-44 shrink-0 items-center justify-center rounded-lg border border-border bg-white [&>svg]:h-40 [&>svg]:w-40" role="img" aria-label="入口二维码" dangerouslySetInnerHTML={{ __html: qr }} />
<div className="flex min-w-0 flex-col gap-3 text-sm">
<p className="break-all"><span className="text-muted-foreground">链接:</span>{origin}</p>
{passcode && (
<div className="flex flex-wrap items-center gap-3">
<span className="text-muted-foreground">口令:</span>
<span className="font-mono text-2xl tracking-widest">{passcode}</span>
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value="rotate" /><Button variant="outline" size="sm">换口令</Button></form>
</div>
)}
{share && <p className="rounded-md bg-accent px-3 py-2 text-accent-foreground">可以直接转发:{share}</p>}
{passcode && <p className="text-muted-foreground">换口令后,新来的人要用新口令;已经进来的人不受影响。</p>}
</div>
</CardContent>
</Card>
{mode === "list" && (
<Card>
<CardHeader><CardTitle>添加成员</CardTitle></CardHeader>
<CardContent className="space-y-3">
<form action="/api/entrance/admin" method="post" className="flex gap-3">
<input type="hidden" name="action" value="add" />
<Input name="name" maxLength={20} placeholder="成员名字" required />
<Button type="submit">生成专属链接</Button>
</form>
{link && <p className="break-all rounded-md bg-accent px-3 py-2 text-sm text-accent-foreground">{name} 的专属链接(只显示这一次,请现在发给 TA;旧链接已失效):{origin}/j/{link}</p>}
</CardContent>
</Card>
)}
<Card>
<CardHeader><CardTitle>已进入的人({people.length})</CardTitle></CardHeader>
<CardContent>
{people.length === 0 ? <p className="text-sm text-muted-foreground">还没有人进入。把上面的链接或二维码发出去吧。</p> : (
// A list, not a table: it reads on a 390 px phone and on a laptop alike.
<ul className="divide-y divide-border">
{people.map(p => (
<li key={p.userId} className="flex flex-wrap items-center gap-x-4 gap-y-2 py-3">
<div className="min-w-0 flex-1">
<p className="font-medium">{p.name}</p>
<p className="text-xs text-muted-foreground">{formatDateTime(p.createdAt)} 进入</p>
</div>
<Badge variant={p.disabled ? "secondary" : "default"}>{p.disabled ? "已停用" : "可使用"}</Badge>
<div className="flex gap-1">
{mode === "list" && !p.disabled && (
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value="relink" /><input type="hidden" name="user" value={p.userId} /><Button variant="ghost" size="sm">重新生成链接</Button></form>
)}
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value={p.disabled ? "enable" : "disable"} /><input type="hidden" name="user" value={p.userId} /><Button variant="ghost" size="sm">{p.disabled ? "恢复" : "停用"}</Button></form>
</div>
</li>
))}
</ul>
)}
<p className="mt-4 text-xs text-muted-foreground">每个人问了什么:在 Praxis 控制台 → 服务智能体 → 这个智能体 → 会话里查看。</p>
</CardContent>
</Card>
</div>
);
}

app/api/entrance/admin/route.ts

import { eq } from "drizzle-orm";
import { getDb } from "@/lib/db";
import { addListMember, cleanName, newPasscode, regenerateLink, revokeChatSignIns, setPasscode } from "@/lib/entrance";
import { getCurrentUser, redirectResponse } from "@/lib/guard";
import { members, sessions } from "@/lib/schema";
export async function POST(req: Request) {
const user = await getCurrentUser(req.headers.get("cookie"));
if (user?.role !== "admin") return redirectResponse("/login?next=/admin/entrance");
const form = await req.formData();
const db = await getDb();
const action = form.get("action");
if (action === "rotate") await setPasscode(db, newPasscode());
if (action === "add") {
const name = cleanName(form.get("name"));
if (!name) return redirectResponse("/admin/entrance");
const { token } = await addListMember(db, name);
return redirectResponse(`/admin/entrance?link=${encodeURIComponent(token)}&name=${encodeURIComponent(name)}`);
}
if (action === "relink") {
const id = String(form.get("user") ?? "");
const [person] = await db.select().from(members).where(eq(members.userId, id)).limit(1);
if (!person) return redirectResponse("/admin/entrance");
const token = await regenerateLink(db, id);
return redirectResponse(`/admin/entrance?link=${encodeURIComponent(token)}&name=${encodeURIComponent(person.name)}`);
}
if (action === "disable" || action === "enable") {
const id = String(form.get("user") ?? "");
await db.update(members).set({ disabled: action === "disable" ? 1 : 0 }).where(eq(members.userId, id));
// Disabling signs the person out of this app and ends their chat sign-ins right away.
if (action === "disable") {
await db.delete(sessions).where(eq(sessions.userId, id));
await revokeChatSignIns(id);
}
}
return redirectResponse("/admin/entrance");
}

Verify

终端窗口
U=<url>; A=$(mktemp); M=$(mktemp)
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -c $A -d 'username=yoko&password=<强密码>' $U/api/auth/register # 303 /account
P=$(curl -s -b $A $U/admin/entrance | grep -oE 'tracking-widest">[0-9]{6}' | grep -oE '[0-9]{6}')
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -d "passcode=000000&name=test" $U/api/entrance/join # 303 /join?error=passcode
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -c $M -d "passcode=$P&name=test" $U/api/entrance/join # 303 /
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' $U/ # 307 /join
curl -s -b $M -X POST -H "Origin: $U" $U/api/praxis-grant-code # {"code":"cgc_…"}

Then, in a browser:

  1. At 390 px wide, join with the passcode and ask three typical questions; check the answers against the material.
  2. At 1280 px wide, check the admin page.
  3. Disable the test member.

When it fails

SymptomCauseFix
The chat says unavailable, ORIGIN_NOT_ALLOWEDThe app’s origin is not in the embed policyStep 4
/api/praxis-grant-code answers 500 and the platform answered 401Deployed without "platform": trueAdd it to praxis.jsonc and deploy again
GRANT_CODE_INVALIDA grant code was reused or expiredFetch a fresh code on every page load
Answers ignore the materialThe vector store is not bound, files are still processing, or system does not say to searchSee “Before you start”
The first student became adminThe teacher did not register firstDo step 5 right after deploying

Another scenario

Change four things and keep the rest of the code:

  • Scenario and AI style: system, plus the greeting and suggested questions in lib/chat-options.ts.
  • Shape: its own page uses this code. Inside an existing website, give one Kit snippet: layout: "popup" for a floating bubble, "sidebar" for a sidebar, "inline" for inline. See the component reference.
  • Access: when anyone with the link may chat and no page of your own is needed, build nothing: turn on the agent’s share links and create one (praxis.share.permissions.create with resource type agent). It opens the agent’s own full-page chat; the same browser comes back as the same visitor, and the link can be revoked at any time. For your own page, ENTRANCE_MODE is open (with a publishable key), passcode or list. A site with its own accounts issues grant codes from its own login; see the web embed guide.