PEP-108: web dictation — microphone in story, comment, answer and chat fields via /api/transcribe
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2d4e8e6119
commit
027cd8b81a
@ -75,7 +75,7 @@ import { eq, sql } from "drizzle-orm";
|
||||
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
||||
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
||||
import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts";
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts";
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "@peppa/core";
|
||||
|
||||
/** Longest voice note the bot transcribes (seconds). */
|
||||
const VOICE_MAX_SEC = 5 * 60;
|
||||
|
||||
@ -15,7 +15,6 @@ import {
|
||||
resolveTask,
|
||||
revokeApp,
|
||||
createPairingCode,
|
||||
getSetting,
|
||||
unpairTelegram,
|
||||
getIncident,
|
||||
getProject as getProjectByKey,
|
||||
|
||||
@ -9,6 +9,7 @@ import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { ago, Empty, Flash, PageHeader } from "@/components/common";
|
||||
import { Hidden, QuestionCard } from "@/components/cards";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
@ -252,8 +253,9 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
) : (
|
||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
|
||||
<Textarea id="chat-text" name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
|
||||
<div className="flex items-center gap-2">
|
||||
<Dictate target="chat-text" compact />
|
||||
<span className="text-xs text-muted-foreground">{discussion ? "отвечает аналитик на подписке проекта · переписку видят участники проекта" : thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
|
||||
@ -108,7 +108,7 @@ export default async function Help() {
|
||||
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
|
||||
<li><b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».</li>
|
||||
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Ему же можно наговорить задачу голосовым, если на сервере включено распознавание речи.</li>
|
||||
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
||||
<li><b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
||||
<li><b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <span className="font-mono">GOOGLE_CLIENT_ID/SECRET</span>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
||||
|
||||
@ -9,6 +9,7 @@ import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
|
||||
import { AutonomyPanel } from "@/components/Autonomy";
|
||||
@ -464,7 +465,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
<form action={addTask} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ projectId: p.id, back }} />
|
||||
<Input name="title" required placeholder="Что сделать" aria-label={`Название ${w.task("gen")}`} />
|
||||
<Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label={`Описание ${w.task("gen")}`} />
|
||||
<Textarea id="new-story-description" name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label={`Описание ${w.task("gen")}`} />
|
||||
<Dictate target="new-story-description" className="self-start" />
|
||||
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label="Эпик">
|
||||
<option value="">Без эпика</option>
|
||||
{epics.map((e) => (
|
||||
|
||||
@ -5,6 +5,7 @@ import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass
|
||||
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
|
||||
import { reviewLabel } from "@peppa/core";
|
||||
import { Hidden, QuestionCard } from "@/components/cards";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { ago, Disclosure, Empty } from "@/components/common";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { eventLine } from "@/components/RunnerConsole";
|
||||
@ -171,6 +172,7 @@ export function CommentsTab({ taskKey, taskStatus, questions, comments, back, ha
|
||||
</label>
|
||||
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder="Что учесть или изменить в задаче" aria-describedby="story-comment-hint" />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Dictate target="story-comment" />
|
||||
<p id="story-comment-hint" className="m-0 text-sm text-muted-foreground">
|
||||
{commentHint(taskStatus, hasLive)}
|
||||
</p>
|
||||
|
||||
51
apps/web/app/api/transcribe/route.ts
Normal file
51
apps/web/app/api/transcribe/route.ts
Normal file
@ -0,0 +1,51 @@
|
||||
// PEP-108: dictation in the web — the browser records (MediaRecorder: webm/opus, Safari mp4) and
|
||||
// posts the audio here; Peppa forwards it to the same speech-to-text service as the Telegram bot
|
||||
// (PEPPA_TRANSCRIBE_URL, core/transcribe.ts) and returns the text. The page puts it into the
|
||||
// field, the user edits and sends. Logged-in users only; size cap and a per-user rate limit.
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "@peppa/core";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** ~10 minutes of opus; the service itself takes up to 25 MB. */
|
||||
const MAX_BYTES = 10 * 1024 * 1024;
|
||||
const PER_USER_PER_5MIN = 30;
|
||||
const g = globalThis as { __peppaTranscribeHits?: Map<number, { at: number; n: number }> };
|
||||
const hits = (g.__peppaTranscribeHits ??= new Map());
|
||||
|
||||
function limited(userId: number, now = Date.now()): boolean {
|
||||
const h = hits.get(userId);
|
||||
if (!h || now - h.at >= 5 * 60_000) {
|
||||
hits.set(userId, { at: now, n: 1 });
|
||||
return false;
|
||||
}
|
||||
return ++h.n > PER_USER_PER_5MIN;
|
||||
}
|
||||
|
||||
const json = (status: number, body: { text?: string; error?: string }) => Response.json(body, { status, headers: { "Cache-Control": "private, no-store" } });
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const user = await currentUser();
|
||||
if (!user) return json(401, { error: "Нужно войти" });
|
||||
const cfg = transcribeConfig();
|
||||
if (!cfg) return json(503, { error: "Распознавание речи не настроено — напишите текстом" });
|
||||
if (Number(req.headers.get("content-length") ?? 0) > MAX_BYTES) return json(413, { error: "Слишком длинная запись — запишите короче" });
|
||||
if (limited(user.id)) return json(429, { error: "Слишком много записей подряд — подождите пару минут" });
|
||||
let file: FormDataEntryValue | null;
|
||||
try {
|
||||
file = (await req.formData()).get("file");
|
||||
} catch {
|
||||
return json(400, { error: "Запись не пришла" });
|
||||
}
|
||||
if (!(file instanceof Blob) || !file.size) return json(400, { error: "Запись пустая" });
|
||||
if (file.size > MAX_BYTES) return json(413, { error: "Слишком длинная запись — запишите короче" });
|
||||
const type = file.type || "audio/webm";
|
||||
const ext = type.includes("mp4") ? "m4a" : type.includes("ogg") ? "ogg" : type.includes("wav") ? "wav" : "webm";
|
||||
try {
|
||||
const text = await transcribe(cfg, Buffer.from(await file.arrayBuffer()), `dictation.${ext}`, type);
|
||||
return json(200, { text });
|
||||
} catch (e) {
|
||||
if (e instanceof TranscribeError) return json(502, { error: e.message });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
7
apps/web/components/Dictate.tsx
Normal file
7
apps/web/components/Dictate.tsx
Normal file
@ -0,0 +1,7 @@
|
||||
// PEP-108: the microphone for a text field, only where the server has speech to text.
|
||||
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { DictateButton } from "@/components/DictateButton";
|
||||
|
||||
export function Dictate(props: { target: string; className?: string; compact?: boolean }) {
|
||||
return voiceStoriesEnabled() ? <DictateButton {...props} /> : null;
|
||||
}
|
||||
112
apps/web/components/DictateButton.tsx
Normal file
112
apps/web/components/DictateButton.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
// PEP-108: a microphone next to a text field — records in the browser (MediaRecorder), sends the
|
||||
// audio to Peppa (POST /api/transcribe → the speech-to-text service, the same as the Telegram
|
||||
// bot's) and appends the text to the field; the user edits it and sends as usual. Rendered only
|
||||
// when the server has speech to text (see Dictate) and the browser can record.
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Loader2, Mic, Square } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Longest recording; the bot's voice limit is the same 3 minutes. */
|
||||
const MAX_MS = 3 * 60_000;
|
||||
|
||||
type State = "idle" | "recording" | "sending";
|
||||
|
||||
/** Appends text to an input/textarea so that React-controlled fields notice it too. */
|
||||
function appendTo(target: string, text: string) {
|
||||
const el = document.getElementById(target) as HTMLInputElement | HTMLTextAreaElement | null;
|
||||
if (!el) return;
|
||||
const value = `${el.value}${el.value && !/\s$/.test(el.value) ? " " : ""}${text}`;
|
||||
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, value);
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
el.focus();
|
||||
}
|
||||
|
||||
function pickMime(): string | undefined {
|
||||
for (const t of ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg;codecs=opus"]) {
|
||||
if (MediaRecorder.isTypeSupported?.(t)) return t;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function DictateButton({ target, className, compact = false }: { target: string; className?: string; compact?: boolean }) {
|
||||
const [supported, setSupported] = useState(false);
|
||||
const [state, setState] = useState<State>("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const rec = useRef<MediaRecorder | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setSupported(typeof window !== "undefined" && !!navigator.mediaDevices?.getUserMedia && typeof MediaRecorder !== "undefined");
|
||||
return () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
rec.current?.stream.getTracks().forEach((t) => t.stop());
|
||||
};
|
||||
}, []);
|
||||
if (!supported) return null;
|
||||
|
||||
async function send(blob: Blob) {
|
||||
setState("sending");
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.set("file", blob, "dictation");
|
||||
const res = await fetch("/api/transcribe", { method: "POST", body: form });
|
||||
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: string };
|
||||
if (!res.ok) throw new Error(body.error || `Не получилось распознать (${res.status})`);
|
||||
if (!body.text) throw new Error("Не разобрал ни слова — попробуйте ещё раз");
|
||||
appendTo(target, body.text);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
setError(null);
|
||||
let stream: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
} catch {
|
||||
setError("Нет доступа к микрофону — разрешите его в браузере");
|
||||
return;
|
||||
}
|
||||
const mimeType = pickMime();
|
||||
const r = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
||||
const chunks: Blob[] = [];
|
||||
r.ondataavailable = (e) => e.data.size && chunks.push(e.data);
|
||||
r.onstop = () => {
|
||||
stream.getTracks().forEach((t) => t.stop());
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
void send(new Blob(chunks, { type: r.mimeType || mimeType || "audio/webm" }));
|
||||
};
|
||||
rec.current = r;
|
||||
r.start();
|
||||
setState("recording");
|
||||
timer.current = setTimeout(() => r.state === "recording" && r.stop(), MAX_MS);
|
||||
}
|
||||
|
||||
const label = state === "recording" ? "Стоп" : state === "sending" ? "Распознаю…" : "Голосом";
|
||||
return (
|
||||
<span className={cn("inline-flex flex-col items-start gap-1", className)}>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={state === "recording" ? "destructive" : "outline"}
|
||||
disabled={state === "sending"}
|
||||
onClick={() => (state === "recording" ? rec.current?.stop() : void start())}
|
||||
aria-pressed={state === "recording"}
|
||||
title={state === "recording" ? "Остановить запись и распознать" : "Наговорить текст голосом"}
|
||||
data-dictate={target}
|
||||
>
|
||||
{state === "recording" ? <Square /> : state === "sending" ? <Loader2 className="animate-spin" /> : <Mic />}
|
||||
{!compact && label}
|
||||
{compact && <span className="sr-only">{label}</span>}
|
||||
</Button>
|
||||
{error && <span role="alert" className="text-xs text-destructive">{error}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@ -9,6 +9,7 @@ import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ago, Disclosure, Empty, Key, StatusBadge } from "@/components/common";
|
||||
import { AgentSteps } from "@/components/AgentSteps";
|
||||
import { Dictate } from "@/components/Dictate";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { SessionUsageLine } from "@/components/Accounting";
|
||||
import { cn } from "@/lib/utils";
|
||||
@ -70,7 +71,8 @@ export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }:
|
||||
</div>
|
||||
{q.kind !== "permission" && (
|
||||
<div className="flex gap-2">
|
||||
<Input name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
|
||||
<Input id={`answer-${q.id}`} name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
|
||||
<Dictate target={`answer-${q.id}`} compact />
|
||||
<Button size="sm">Ответить</Button>
|
||||
</div>
|
||||
)}
|
||||
@ -88,7 +90,8 @@ export function SessionActions({ s, back }: { s: SessionView; back: string }) {
|
||||
{alive && (
|
||||
<form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2">
|
||||
<Hidden fields={{ sessionId: s.id, back }} />
|
||||
<Input name="text" placeholder="Написать агенту" aria-label="Написать агенту" className="h-8" />
|
||||
<Input id={`agent-message-${s.id}`} name="text" placeholder="Написать агенту" aria-label="Написать агенту" className="h-8" />
|
||||
<Dictate target={`agent-message-${s.id}`} compact />
|
||||
<Button size="sm" aria-label="Отправить" title="Отправить">
|
||||
<Send />
|
||||
<span className="max-sm:hidden">Отправить</span>
|
||||
|
||||
@ -60,3 +60,4 @@ export * from "./onboarding.ts";
|
||||
export * from "./chats.ts";
|
||||
export * from "./subscription-care.ts";
|
||||
export * from "./subscription-names.ts";
|
||||
export * from "./transcribe.ts";
|
||||
|
||||
38
packages/testkit/test/transcribe.test.ts
Normal file
38
packages/testkit/test/transcribe.test.ts
Normal file
@ -0,0 +1,38 @@
|
||||
// PEP-108: the speech-to-text client shared by the Telegram bot and the web dictation route
|
||||
// (core/transcribe.ts) against mock-transcribe (the OpenAI-compatible contract of
|
||||
// infra/whisper/server.py).
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { transcribe, transcribeConfig, TranscribeError } from "@peppa/core";
|
||||
import { voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { MockTranscribe } from "../src/mock-transcribe.ts";
|
||||
|
||||
const stt = new MockTranscribe();
|
||||
before(() => stt.start());
|
||||
after(() => stt.stop());
|
||||
|
||||
describe("распознавание речи", () => {
|
||||
test("Scenario: не настроено — голоса нет ни в боте, ни в вебе", () => {
|
||||
assert.equal(transcribeConfig({}), null);
|
||||
assert.equal(voiceStoriesEnabled({}), false);
|
||||
assert.equal(voiceStoriesEnabled({ PEPPA_TRANSCRIBE_URL: "http://127.0.0.1:8178/v1" }), true);
|
||||
});
|
||||
|
||||
test("Scenario: адрес сервиса Пеппы — язык ru, таймаут 300 с по умолчанию, свой таймаут из env", () => {
|
||||
const cfg = transcribeConfig({ PEPPA_TRANSCRIBE_URL: "http://127.0.0.1:8178/v1/", PEPPA_TRANSCRIBE_LANG: "ru" })!;
|
||||
assert.deepEqual(cfg, { url: "http://127.0.0.1:8178/v1", key: null, model: "whisper-1", language: "ru", timeoutMs: 300_000 });
|
||||
assert.equal(transcribeConfig({ PEPPA_TRANSCRIBE_URL: "http://x/v1", PEPPA_TRANSCRIBE_TIMEOUT_SEC: "30" })!.timeoutMs, 30_000);
|
||||
});
|
||||
|
||||
test("Scenario: запись из браузера (webm) расшифровывается", async () => {
|
||||
const cfg = transcribeConfig({ PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key })!;
|
||||
const text = await transcribe(cfg, MockTranscribe.speech("починить вход"), "dictation.webm", "audio/webm");
|
||||
assert.equal(text, "починить вход");
|
||||
assert.deepEqual(stt.requests.at(-1), { model: "whisper-1", language: "ru", filename: "dictation.webm", bytes: MockTranscribe.speech("починить вход").length });
|
||||
});
|
||||
|
||||
test("Scenario: сервис недоступен — понятная ошибка", async () => {
|
||||
const cfg = transcribeConfig({ PEPPA_TRANSCRIBE_URL: "http://127.0.0.1:9/v1", PEPPA_TRANSCRIBE_TIMEOUT_SEC: "5" })!;
|
||||
await assert.rejects(transcribe(cfg, Buffer.from("x")), (e: unknown) => e instanceof TranscribeError && /сервис расшифровки недоступен/.test((e as Error).message));
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user