PEP-159: вложения в чате с аналитиком, комментариях и новой задаче

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 12:46:43 +05:00
parent a28faf3a07
commit cdbab4466d
34 changed files with 1120 additions and 32 deletions

View File

@ -50,3 +50,4 @@
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`.
- Сообщения ИИ-ролей в обсуждении (PEP-138): свободный текст модели через общий localizeText не пропускать — он его переписывает; постоянная строка = отдельная строка через `m()` + ключ в `ROLE_MESSAGE_KEYS`, веб — `t.role`, Telegram/push из `sayInDiscussion` — на языке получателя с `Delivery.localized`.
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
- Вложения (PEP-159): файл грузится отдельно (`POST /api/attachments`, не server action — предел 1 МБ) и привязывается действием через `linkAttachments`; новое место с файлами — `<AttachField projectId target>` в форме и `<Attachments files>` для показа; типы только по содержимому (`sniffAttachment`). Агент читает файлы из `.peppa/attachments/` (папка сама в gitignore).

View File

@ -49,6 +49,7 @@
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:<userId>`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
- **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts`
- **Обращения пользователей (PEP-143)**: «Сообщить о проблеме» в самой Peppa FACTORY. Таблица `feedback` (миграция 0019; статусы `received` → `analyzed` → `planned` → `fixed` | `rejected`, автору — четыре слова `FEEDBACK_USER_STATUS`; JSON `context`, `screenshots`, `analysis`), всё в `core/feedback.ts`: `submitFeedback` (текст и/или ≤5 картинок PNG/JPEG/WebP по сигнатуре `sniffImage`, ≤5 МБ, файлы `$PEPPA_HOME/feedback/<id>/<n>.<ext>` под своими именами, предел `PEPPA_FEEDBACK_MAX_PER_HOUR` = 10 на пользователя), `feedbackForUser`/`feedbackScreenshot` (автор или суперадмин, иначе null → 404), решения только суперадмина — `fixFeedback` (вариант разбора → задача в `PEPPA_PLATFORM_KEY`; ошибка — в эпик «Стабильность», то есть приоритет PEP-103; intake `done`), `linkFeedback`, `rejectFeedback` (ответ автору с причиной), `closeFixedFeedback` (задача `done` → «Исправили: …»). Агент — `feedbackTick` в тике вачдога (`runner/feedback.ts`): `claudePrint` на подписке платформенного проекта (`PEPPA_FEEDBACK_BIN` ← `PEPPA_INTAKE_BIN`, `PEPPA_FEEDBACK_MODEL`), скриншоты файлами, контекст — 10 последних `incidents` и открытые задачи платформы (`feedbackPromptContext`); одна попытка: сбой, ответ не по форме, `PEPPA_FEEDBACK=off`, умерший процесс (`analysis_started_at` старше таймаута) → `finishFeedbackAnalysis({error})` — суперадмину без разбора, один раз; обращения из Telegram ждут `PEPPA_FEEDBACK_SETTLE_SEC` (20), пока дойдёт альбом. Суперадминам — `announceFeedback`: событие уведомлений `feedback` (строка настроек только суперадмину; автору ответы идут тем же событием), скриншоты — метод outbox `sendPhoto` (`params.photo_path`, бот читает файл и шлёт multipart `TelegramApi.sendPhoto`), карточка `feedbackCardText` с кнопками `f:<id>:o<N>|dup|no`. Бот (`apps/bot/src/feedback.ts`): `/problem` → режим `bot.feedback:<userId>` (15 мин), следующее сообщение (текст / фото с подписью / голос) — обращение, фото следом (2 мин) прикладываются; «Не исправлять» ждёт причину следующим сообщением (`bot.feedback.reject:<userId>`, «-» — без причины). Веб: `POST /api/feedback` (multipart; вид и язык берёт сервер), `GET /api/feedback/<id>/shots/<n>`, плавающая кнопка `FeedbackButton` в раскладке (файл, перетаскивание, вставка из буфера; ошибки браузера — `window.__peppaErrors` из `ErrorReporter`), страница `/feedback` (свои; суперадмину — все с фильтром `?status=` и решениями, `components/Feedback.tsx`), секция на Главной, пункт меню суперадмина со счётчиком. Мок — роль `feedback` в `mock-intake`, фото/`sendPhoto`/`editMessageReplyMarkup` в `mock-telegram`; тест `feedback.test.ts`
- **Вложения (PEP-159)**: таблица `attachments` (миграция 0020: проект, загрузивший, `task_id`/`chat_message_id`/`event_id`, имя для показа, имя на диске, mime, размер), всё в `core/attachments.ts`: `sniffAttachment` (тип по содержимому — PNG/JPEG/WebP/GIF, PDF, DOCX/XLSX/PPTX по ZIP, текст TXT/MD/CSV/JSON; SVG/HTML/скрипт/архив/исполняемый — отказ), файлы `$PEPPA_HOME/files/<projectId>/<id>/<id>.<ext>`, ≤5 файлов по ≤20 МБ. Загрузка двухшаговая: `POST /api/attachments` (multipart, `projectId`) сразу после выбора → id, форма несёт скрытые `attachment=<id>`, действия (`postChatAction`/`postToChat`, `commentStoryAction`, `addTask`) зовут `linkAttachments` (только свои неотправленные файлы того же проекта); висящие старше суток убирает `pruneAttachments` (вачдог, раз в час). Отдача `GET /api/attachments/<id>` (владелец/участник/суперадмин, иначе 404; nosniff, картинки и PDF inline, прочее скачиванием). UI: `components/AttachField.tsx` (скрепка, перетаскивание и Ctrl+V на поле), `components/Attachments.tsx` (миниатюры и строки). Аналитик: `attachmentsForModel` → `claudePrint({files})` для картинок и PDF, текст файлов (≤20 КБ) в промпт, Office — по имени; чат берёт файлы сообщений после курсора, `storyRefineTick` — новых комментариев и самой стори. Агент: `launch` и `syncSessionAttachments` копируют файлы стори в `<рабочая копия>/.peppa/attachments/` (внутри свой `.gitignore` с `*`), `get_task` — раздел «Приложенные файлы»; на отдельном хосте не копируется. Не сделано (второй PR): Telegram-бот, извлечение текста из Office. Тест `attachments.test.ts`
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
- **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:<taskId>` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts`
- **Мерж только со свежим main внутри (PEP-127)**: `prGate` закрыт с `behind: true`, если ветка открытого PR не содержит голову основной (`pullBehind`: `merge_base` ≠ `base.sha` из ответа Gitea); `reviewGate` агента `behind` пропускает. Обновляет Пеппа — `GiteaClient.updatePullBranch` (`POST /pulls/{n}/update`, merge), раз на head SHA (`updateSha` в `review.hold` / `accept.pending` / `autonomy.merge`), потом ждёт проверок нового коммита: `reviewCardTick`, `pendingAcceptTick`, `autoMergeReviews`. `deferAccept` запоминает «Принять» при конфликте, отставшей ветке и идущих проверках; красные — отказ с причиной

View File

@ -62,10 +62,10 @@ import {
checkGiteaBotToken,
setUiMode,
} from "@peppa/core";
import { fixFeedback, linkFeedback, rejectFeedback } from "@peppa/core";
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback } from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { acceptStory, autoPublish, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser, words } from "@/lib/auth";
@ -128,7 +128,9 @@ export async function addTask(f: FormData) {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (!str(f, "title")) throw new PeppaError(m("Нужно название задачи"));
const epic = Number(str(f, "epicId")) || undefined;
const ids = parseAttachmentIds(f.getAll("attachment"));
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
await linkAttachments(db, user, p.id, ids, { taskId: ref.task.id });
return `/t/${ref.key}`;
});
}
@ -176,12 +178,15 @@ export async function commentStoryAction(f: FormData) {
await attempt(f, async () => {
const ref = await resolveTask(db, str(f, "taskKey"));
await projectForUser(db, user.id, ref.project.id);
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
const ids = parseAttachmentIds(f.getAll("attachment"));
const body = String(f.get("text") ?? "").trim() || (await attachmentLabel(db, ids));
const c = await addStoryComment(db, ref, user, body);
await linkAttachments(db, user, ref.project.id, ids, { taskId: ref.task.id, eventId: c.id });
if (str(f, "toAgent")) {
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
if (!live) throw new PeppaError(m("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче"));
// i18n-ignore — text for the agent
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`, { person: true });
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
}
});
}

View File

@ -1,7 +1,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
import { analystPending, attachmentsByMessage, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core";
import { projects, questions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { PRODUCT_NAME } from "@peppa/shared/i18n";
@ -11,6 +11,8 @@ 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 { Attachments } from "@/components/Attachments";
import { AttachField } from "@/components/AttachField";
import { Workspace } from "@/components/Workspace";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
@ -53,6 +55,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
: discussion
? await discussionMessages(db, chat.id)
: await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
const files = await attachmentsByMessage(db, messages.map((m) => m.id));
const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
// Live state of the questions in view (answer buttons, «отвечено» marks).
@ -241,7 +244,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{messages.map((m) => (
<li key={m.id}>
<MessageItem m={m} q={m.question ? qById.get(m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && m.authorUserId === user.id} />
<MessageItem files={files.get(m.id)} m={m} q={m.question ? qById.get(m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && m.authorUserId === user.id} />
</li>
))}
</ol>
@ -259,7 +262,8 @@ 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 id="chat-text" name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label={t("Сообщение")} />
<Textarea id="chat-text" name="text" rows={2} maxLength={8000} placeholder={placeholder} aria-label={t("Сообщение")} />
{chat.projectId && <AttachField projectId={chat.projectId} target="chat-text" />}
<div className="flex items-center gap-2">
<Dictate target="chat-text" compact />
<span className="text-xs text-muted-foreground">{discussion ? t("отвечает аналитик на подписке проекта · переписку видят участники проекта") : thread ? t("в тред") : master ? t("в мастер-чат") : t("в канал")}{chat.tgTitle ? " · " + t("и в Telegram «{title}»", { title: chat.tgTitle }) : ""}</span>
@ -315,7 +319,7 @@ function threadHref(m: ChatMessageView) {
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
}
async function MessageItem({ m, q, back, showThread, masterView, mine = false }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean }) {
async function MessageItem({ m, q, back, showThread, masterView, mine = false, files }: { files?: AttachmentView[]; m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: boolean }) {
const t = await getT();
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
const href = threadHref(m);
@ -351,6 +355,7 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false }:
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
{head}
<p className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(m.authorKind === "system" ? t.text(m.text) : m.authorKind === "agent" ? t.role(m.text) : m.text)}</p>
<Attachments files={files} />
{m.url && (
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
{m.url}

View File

@ -1,7 +1,7 @@
"use server";
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
import { chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
import { postToChat } from "@peppa/runner";
import { loadEnv } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
@ -32,7 +32,7 @@ export async function postChatAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const thread = str(f, "thread");
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" });
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web", attachmentIds: parseAttachmentIds(f.getAll("attachment")) });
});
}

View File

@ -10,6 +10,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 { AttachField } from "@/components/AttachField";
import { Dictate } from "@/components/Dictate";
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
@ -480,6 +481,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
<Input name="title" required placeholder={t("Что сделать")} aria-label={t("Название {task}", { task: w.task("gen") })} />
<Textarea id="new-story-description" name="description" rows={5} placeholder={t("Описание: кому и зачем, критерии готовности")} aria-label={t("Описание {task}", { task: w.task("gen") })} />
<Dictate target="new-story-description" className="self-start" />
<AttachField projectId={p.id} target="new-story-description" />
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label={t("Эпик")}>
<option value="">{t("Без эпика")}</option>
{epics.map((e) => (

View File

@ -386,7 +386,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
{tab === "design" && <ArtifactTab change={change} changeId={task.openspecChange} file="design" />}
{tab === "specs" && <SpecsTab change={change} changeId={task.openspecChange} />}
{tab === "tasks" && <TasksTab change={change} changeId={task.openspecChange} progress={progress} />}
{tab === "comments" && <CommentsTab taskKey={ref.key} taskStatus={task.status} questions={[...questions].reverse()} comments={comments} back={back} hasLive={!!live} refining={commentRefining} />}
{tab === "comments" && <CommentsTab taskId={task.id} projectId={project.id} taskKey={ref.key} taskStatus={task.status} questions={[...questions].reverse()} comments={comments} back={back} hasLive={!!live} refining={commentRefining} />}
{tab === "tests" && <TestsTab ci={ci} runs={runs} review={review} />}
{tab === "merge" && <MergeTab taskKey={ref.key} taskStatus={task.status} prUrl={task.prUrl} pull={gate?.pull ?? null} gate={gate} back={back} accepted={!!pendingAccept} />}
{tab === "activity" && <ActivityTab events={events} authors={authors} />}

View File

@ -3,7 +3,10 @@
import { AgentBadge } from "@/components/AgentBadge";
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
import { PENDING_ACCEPT_LABEL, reviewLabel } from "@peppa/core";
import { attachmentsByEvent, PENDING_ACCEPT_LABEL, reviewLabel, storyOwnAttachments } from "@peppa/core";
import { db } from "@/lib/db";
import { AttachField } from "@/components/AttachField";
import { Attachments } from "@/components/Attachments";
import { Hidden, QuestionCard } from "@/components/cards";
import { Dictate } from "@/components/Dictate";
import { ago, Disclosure, Empty } from "@/components/common";
@ -148,12 +151,21 @@ export async function ProgressBar({ done, total, current, compact = false }: { d
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
export async function CommentsTab({ taskKey, taskStatus, questions, comments, back, hasLive, refining = false }: { taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean; refining?: boolean }) {
export async function CommentsTab({ taskId, projectId, taskKey, taskStatus, questions, comments, back, hasLive, refining = false }: { taskId: number; projectId: number; taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean; refining?: boolean }) {
const t = await getT();
// PEP-159: the files of every comment and the story's own.
const files = await attachmentsByEvent(db, comments.map((c) => c.id));
const own = await storyOwnAttachments(db, taskId);
const thread: Thread[] = [...questions.map((q) => ({ at: q.createdAt.getTime(), kind: "q" as const, q })), ...comments.map((c) => ({ at: c.createdAt.getTime(), kind: "c" as const, c }))].sort((a, b) => a.at - b.at);
return (
<div className="flex flex-col gap-3">
{thread.length === 0 && <Empty>{t("Вопросов и комментариев пока нет.")}</Empty>}
{own.length > 0 && (
<section className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5" aria-label={t("Файлы задачи")}>
<h3 className="m-0 text-xs font-medium text-muted-foreground">{t("Файлы задачи")}</h3>
<Attachments files={own} />
</section>
)}
{thread.length === 0 && own.length === 0 && <Empty>{t("Вопросов и комментариев пока нет.")}</Empty>}
{thread.map((x) =>
x.kind === "q" ? (
<QuestionCard key={`q${x.q.id}`} q={x.q} taskStatus={taskStatus} back={back} />
@ -164,6 +176,7 @@ export async function CommentsTab({ taskKey, taskStatus, questions, comments, ba
{x.c.role ? (x.c.role === "product" ? t("зачем и что берём") : t("что должно получиться")) : <><span className="font-medium text-foreground">{x.c.login}</span> {t("комментарий PM")}</>} · {ago(x.c.createdAt, t)}
</header>
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{x.c.text}</p>
<Attachments files={files.get(x.c.id)} />
</article>
),
)}
@ -178,7 +191,8 @@ export async function CommentsTab({ taskKey, taskStatus, questions, comments, ba
<label htmlFor="story-comment" className="text-sm font-medium">
{t("Комментарий к стори")}
</label>
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
<Textarea id="story-comment" name="text" rows={3} maxLength={8000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
<AttachField projectId={projectId} target="story-comment" />
<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">

View File

@ -0,0 +1,42 @@
// PEP-159: a file — only for the project's people and superadmins. Pictures and PDFs open in the
// browser, everything else downloads; the browser never guesses a type (nosniff, sandbox).
import { attachmentForUser, discardAttachment } from "@peppa/core";
import { readFileSync } from "node:fs";
import { asWebActor, currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
export const dynamic = "force-dynamic";
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
const user = await currentUser();
const t = await getT();
if (!user) return new Response(t("Нужен вход"), { status: 401 });
const { id } = await params;
const found = /^\d+$/.test(id) ? await attachmentForUser(db, user, Number(id)) : null;
// Somebody else's file and a missing one look the same.
if (!found) return new Response(t("Не найдено"), { status: 404 });
const { row, path } = found;
const inline = (row.mime.startsWith("image/") || row.mime === "application/pdf") && new URL(req.url).searchParams.get("download") !== "1";
const name = encodeURIComponent(row.name).replace(/['()]/g, escape);
return new Response(new Uint8Array(readFileSync(path)), {
headers: {
"Content-Type": row.mime,
"Content-Length": String(row.size),
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
"Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${name}`,
// A PDF viewer does not run in a sandboxed response; everything else is locked down.
...(row.mime === "application/pdf" ? {} : { "Content-Security-Policy": "default-src 'none'; sandbox" }),
},
});
}
/** The cross next to a chosen file: takes it back before sending. */
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const me = await currentUser();
if (!me) return new Response(null, { status: 401 });
const { id } = await params;
const ok = /^\d+$/.test(id) && (await discardAttachment(db, asWebActor(me), Number(id)));
return new Response(null, { status: ok ? 204 : 404 });
}

View File

@ -0,0 +1,42 @@
// PEP-159: files for a chat message, a comment or a new story. The file is uploaded as soon as it is
// chosen (multipart: a server action's body is capped at 1 MB, files go up to 20 MB) and gets an id
// the form sends along; the action links it to the message. Access — the project's people.
import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_FILES, PeppaError, saveAttachment } from "@peppa/core";
import { m } from "@peppa/shared/i18n";
import { asWebActor, currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
const t = await getT();
const fail = (status: number, error: string) => Response.json({ error }, { status });
const me = await currentUser();
if (!me) return fail(401, t("Нужен вход"));
const user = asWebActor(me);
if (Number(req.headers.get("content-length") ?? 0) > ATTACHMENT_MAX_BYTES * ATTACHMENT_MAX_FILES + 512 * 1024) return fail(413, t("Файл больше 20 МБ. Приложите файл поменьше."));
let form: FormData;
try {
form = await req.formData();
} catch {
return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз."));
}
const projectId = Number(form.get("projectId"));
const files = form.getAll("files").filter((v): v is File => typeof v !== "string");
if (!Number.isInteger(projectId) || !files.length) return fail(400, t("Выберите файл."));
if (files.length > ATTACHMENT_MAX_FILES) return fail(400, t("Можно приложить не больше {n} файлов.", { n: ATTACHMENT_MAX_FILES }));
const saved = [];
const errors: string[] = [];
for (const f of files) {
try {
// Oversized files are refused before their bytes are read into memory.
if (f.size > ATTACHMENT_MAX_BYTES) throw new PeppaError(m("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name: f.name }));
saved.push(await saveAttachment(db, user, { projectId, name: f.name, data: new Uint8Array(await f.arrayBuffer()) }));
} catch (e) {
if (!(e instanceof PeppaError)) throw e;
errors.push(t.text(e.message));
}
}
return Response.json({ files: saved, errors });
}

View File

@ -0,0 +1,179 @@
"use client";
import { FileText, Loader2, Paperclip, X } from "lucide-react";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { useT } from "@/components/I18n";
import { cn } from "@/lib/utils";
const MAX_FILES = 5;
const MAX_BYTES = 20 * 1024 * 1024;
const ACCEPT = ".png,.jpg,.jpeg,.webp,.gif,.pdf,.txt,.md,.csv,.json,.docx,.xlsx,.pptx";
interface Item {
key: string;
name: string;
size: number;
/** Server id once uploaded. */
id?: number;
preview?: string;
state: "uploading" | "ok" | "error";
}
const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1).replace(/\.0$/, "")} MB`);
/**
* PEP-159: a paperclip next to a message field — pick files, drop them on the field or paste a
* picture (Ctrl+V). Each file goes up at once (`POST /api/attachments`); the form carries the
* returned ids as hidden `attachment` fields and the action links them to the message.
*/
export function AttachField({ projectId, target, className }: { projectId: number; /** id of the textarea that takes drops and pastes */ target?: string; className?: string }) {
const t = useT();
const inputId = useId();
const picker = useRef<HTMLInputElement>(null);
const root = useRef<HTMLDivElement>(null);
const [items, setItems] = useState<Item[]>([]);
const [error, setError] = useState<string | null>(null);
const [over, setOver] = useState(false);
// The latest list for handlers attached once (drop, paste, form submit).
const live = useRef<Item[]>([]);
live.current = items;
const upload = useCallback(
async (file: File, key: string) => {
const body = new FormData();
body.set("projectId", String(projectId));
body.append("files", file);
try {
const res = await fetch("/api/attachments", { method: "POST", body });
const json = (await res.json().catch(() => ({}))) as { files?: Array<{ id: number }>; errors?: string[]; error?: string };
const ok = json.files?.[0];
if (!res.ok || !ok) throw new Error(json.errors?.[0] ?? json.error ?? t("Не получилось загрузить файл. Попробуйте ещё раз."));
setItems((cur) => cur.map((i) => (i.key === key ? { ...i, id: ok.id, state: "ok" } : i)));
} catch (e) {
setItems((cur) => cur.filter((i) => i.key !== key));
setError((e as Error).message);
}
},
[projectId, t],
);
const add = useCallback(
(files: Iterable<File>) => {
setError(null);
const fresh: Array<{ file: Item; raw: File }> = [];
let count = live.current.length;
for (const raw of files) {
if (raw.size > MAX_BYTES) {
setError(t("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name: raw.name }));
continue;
}
if (count >= MAX_FILES) {
setError(t("Можно приложить не больше {n} файлов.", { n: MAX_FILES }));
break;
}
count++;
const key = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
fresh.push({ raw, file: { key, name: raw.name || "image.png", size: raw.size, state: "uploading", preview: raw.type.startsWith("image/") && raw.type !== "image/svg+xml" ? URL.createObjectURL(raw) : undefined } });
}
if (!fresh.length) return;
setItems((cur) => [...cur, ...fresh.map((f) => f.file)]);
for (const f of fresh) void upload(f.raw, f.file.key);
},
[t, upload],
);
const remove = (item: Item) => {
setItems((cur) => cur.filter((i) => i.key !== item.key));
if (item.preview) URL.revokeObjectURL(item.preview);
if (item.id) void fetch(`/api/attachments/${item.id}`, { method: "DELETE" }).catch(() => {});
};
// Drops and pastes on the message field; sending waits for files still going up.
useEffect(() => {
const form = root.current?.closest("form");
const field = (target ? document.getElementById(target) : form?.querySelector("textarea")) as HTMLElement | null;
if (!form) return;
const onDrop = (e: DragEvent) => {
if (!e.dataTransfer?.files.length) return;
e.preventDefault();
setOver(false);
add(Array.from(e.dataTransfer.files));
};
const onOver = (e: DragEvent) => {
if (!e.dataTransfer?.types.includes("Files")) return;
e.preventDefault();
setOver(true);
};
const onLeave = () => setOver(false);
const onPaste = (e: ClipboardEvent) => {
const files = Array.from(e.clipboardData?.files ?? []);
if (!files.length) return;
e.preventDefault();
add(files);
};
const onSubmit = (e: Event) => {
if (live.current.some((i) => i.state === "uploading")) {
e.preventDefault();
e.stopPropagation();
setError(t("Файлы ещё загружаются. Подождите секунду и отправьте снова."));
}
};
field?.addEventListener("drop", onDrop);
field?.addEventListener("dragover", onOver);
field?.addEventListener("dragleave", onLeave);
field?.addEventListener("paste", onPaste);
form.addEventListener("submit", onSubmit, true);
return () => {
field?.removeEventListener("drop", onDrop);
field?.removeEventListener("dragover", onOver);
field?.removeEventListener("dragleave", onLeave);
field?.removeEventListener("paste", onPaste);
form.removeEventListener("submit", onSubmit, true);
};
}, [add, target, t]);
return (
<div ref={root} className={cn("flex min-w-0 flex-col gap-1.5", className)} data-attach-field>
{items.map((i) => i.id && <input key={i.key} type="hidden" name="attachment" value={i.id} />)}
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => picker.current?.click()}
className={cn("inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", over && "border-primary bg-accent text-foreground")}
aria-label={t("Приложить файл")}
title={t("Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.")}
>
<Paperclip className="size-4" />
<span>{over ? t("Отпустите файл здесь") : t("Файл")}</span>
</button>
<input id={inputId} ref={picker} type="file" multiple accept={ACCEPT} className="sr-only" tabIndex={-1} onChange={(e) => (add(Array.from(e.target.files ?? [])), (e.target.value = ""))} />
</div>
{items.length > 0 && (
<ul className="m-0 flex list-none flex-wrap gap-2 p-0" aria-label={t("Приложенные файлы")}>
{items.map((i) => (
<li key={i.key} className="flex max-w-full items-center gap-2 rounded-md border bg-background py-1 pr-1 pl-2 text-xs" data-attachment-item>
{i.preview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={i.preview} alt="" className="size-8 rounded object-cover" />
) : (
<FileText className="size-4 shrink-0 text-muted-foreground" />
)}
<span className="min-w-0 max-w-[14rem] truncate" title={i.name}>
{i.name}
</span>
<span className="shrink-0 text-muted-foreground">{i.state === "uploading" ? <Loader2 className="size-3.5 animate-spin" aria-label={t("загружается")} /> : fmt(i.size)}</span>
<button type="button" onClick={() => remove(i)} className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" aria-label={t("Убрать файл {name}", { name: i.name })}>
<X className="size-3.5" />
</button>
</li>
))}
</ul>
)}
{error && (
<p role="alert" className="m-0 text-xs text-destructive">
{error}
</p>
)}
</div>
);
}

View File

@ -0,0 +1,42 @@
import { FileSpreadsheet, FileText, Presentation } from "lucide-react";
import { humanSize, type AttachmentView } from "@peppa/core";
/**
* PEP-159: files of a message, a comment or a story — pictures as thumbnails that open large,
* everything else as a row with the name and the size (a PDF opens, the rest downloads).
*/
export function Attachments({ files }: { files?: AttachmentView[] }) {
if (!files?.length) return null;
const images = files.filter((f) => f.kind === "image");
const rest = files.filter((f) => f.kind !== "image");
return (
<div className="flex min-w-0 flex-col gap-1.5" data-attachments>
{images.length > 0 && (
<div className="flex flex-wrap gap-2">
{images.map((f) => (
<a key={f.id} href={`/api/attachments/${f.id}`} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-md border bg-background" title={f.name}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`/api/attachments/${f.id}`} alt={f.name} loading="lazy" className="block h-24 max-w-[12rem] object-cover" />
</a>
))}
</div>
)}
{rest.length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1 p-0">
{rest.map((f) => {
const Icon = f.mime.includes("spreadsheet") ? FileSpreadsheet : f.mime.includes("presentation") ? Presentation : FileText;
return (
<li key={f.id}>
<a href={`/api/attachments/${f.id}${f.kind === "pdf" ? "" : "?download=1"}`} target={f.kind === "pdf" ? "_blank" : undefined} rel="noreferrer" className="inline-flex max-w-full items-center gap-2 rounded-md border bg-background px-2 py-1 text-xs hover:bg-accent hover:no-underline">
<Icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 truncate">{f.name}</span>
<span className="shrink-0 text-muted-foreground">{humanSize(f.size)}</span>
</a>
</li>
);
})}
</ul>
)}
</div>
);
}

View File

@ -0,0 +1,8 @@
## Решения
- **Загрузка двухшаговая.** Серверные действия Next ограничены 1 МБ, файлы — до 20 МБ. Поэтому файл уходит сразу после выбора в `POST /api/attachments` (multipart, `projectId`), получает id и остаётся «висящим» (без привязки, владелец — загрузивший). Форма несёт скрытые поля `attachment=<id>`; действие (`postChatAction`, `commentStoryAction`, `addTask`) привязывает их к сообщению/комментарию/задаче. Висящие файлы старше суток удаляет `pruneAttachments` (тик вачдога).
- **Тип по содержимому** (`sniffAttachment`): сигнатуры PNG/JPEG/WebP/GIF/PDF; DOCX/XLSX/PPTX — ZIP с `[Content_Types].xml` и каталогом `word/`, `xl/`, `ppt/`; текст (TXT/MD/CSV/JSON) — валидный UTF-8 без нулевых байтов, расширение из списка, JSON должен разбираться. SVG, HTML, скрипты, архивы, исполняемые — отказ.
- **Хранение:** `$PEPPA_HOME/files/<projectId>/<id>/<id>.<ext>` (имя на диске наше, имя пользователя — только в БД для показа), права 0600/0700.
- **Отдача:** доступ — `projectForUser` (владелец, участник, суперадмин). `X-Content-Type-Options: nosniff`; картинки и PDF — `inline`, остальное — `attachment`; `Content-Security-Policy: sandbox` для всего, кроме PDF.
- **Связи:** `attachments.project_id`, `user_id`, `task_id` (для агента: задача и всё её обсуждение), `chat_message_id`, `event_id` (комментарий). Агент берёт всё по `task_id`.
- **Аналитик:** `claudePrint` уже умеет копировать файлы в пустой рабочий каталог вызова (только `Read`). Картинки и PDF идут файлами, текстовые (до 20 КБ каждый) — содержимым в промпт, офисные — именем и типом.
- **Агент задачи:** при запуске `syncTaskAttachments` копирует вложения в `<workspace>/.peppa/attachments/` и кладёт туда `.gitignore` с `*` (каталог не попадает в коммиты, файлы репозитория не трогаются); `get_task` перечисляет пути и описание. На хосте и в контейнере (рабочая копия не на этой машине) копирование не делается — `get_task` честно говорит, что файлы лежат на сайте.

View File

@ -0,0 +1,12 @@
## Why
Продакт не может приложить к задаче или к разговору с аналитиком макет, скриншот, ТЗ, таблицу или логотип — только текст. Нужны вложения в трёх местах: чат с аналитиком, обсуждение задачи, форма «+ Задача».
## What Changes
- Общий модуль вложений (`core/attachments.ts`): проверка по содержимому, хранение на диске, права, привязка к сообщению чата / комментарию / задаче. Скриншоты обратной связи (PEP-143) смогут перейти на него позже.
- Загрузка файлов до отправки формы (`POST /api/attachments`, multipart), отдача `GET /api/attachments/<id>` с проверкой доступа к проекту.
- Поле с скрепкой, перетаскиванием и вставкой из буфера в трёх формах; показ миниатюр и строк файлов в сообщении и на странице задачи.
- Аналитик (чат и уточнение постановки) получает вложения; агент задачи — в `.peppa/attachments/` и в `get_task`.
- Вне первого PR: Telegram-бот, извлечение текста из DOCX/XLSX/PPTX.
## Impact
Новая таблица `attachments` (миграция), новые тексты на трёх языках, правки `runner/analyst-chat.ts`, `runner/story-refine.ts`, `runner/sessions.ts`, `mcp/format.ts`.

View File

@ -0,0 +1,39 @@
## ADDED Requirements
### Requirement: Вложения к сообщениям и задачам
Пользователь SHALL прикладывать до 5 файлов (до 20 МБ каждый) к сообщению чата с аналитиком, комментарию задачи и новой задаче; тип проверяется по содержимому.
#### Scenario: Приложить PDF и картинку в чате
- **GIVEN** участник проекта «SHOP» открыл чат с аналитиком
- **WHEN** он выбирает «ТЗ.pdf» и «макет.png» и отправляет сообщение
- **THEN** в сообщении видны миниатюра картинки и строка «ТЗ.pdf» с размером
- **AND** оба файла открываются
#### Scenario: Запрещённый тип
- **GIVEN** участник проекта выбирает файл «logo.svg»
- **WHEN** файл загружается
- **THEN** он отклонён с понятной причиной и не сохраняется
#### Scenario: Слишком большой файл
- **WHEN** выбран файл больше 20 МБ
- **THEN** показана ошибка «файл больше 20 МБ», сообщение остаётся неотправленным
### Requirement: Доступ к файлам
Файл SHALL открываться только владельцу проекта, его участникам и суперадмину.
#### Scenario: Чужой пользователь
- **GIVEN** файл проекта «SHOP»
- **WHEN** пользователь без доступа к «SHOP» просит его адрес
- **THEN** ответ «не найдено»
### Requirement: Аналитик и агент видят файлы
Аналитик SHALL получать вложения сообщения или комментария; агент задачи — находить вложения задачи в `.peppa/attachments/` и в `get_task`.
#### Scenario: Аналитик читает приложенную картинку
- **WHEN** сообщение с картинкой и текстовым файлом уходит аналитику
- **THEN** картинка доступна ему как файл, а содержимое текстового — в запросе
#### Scenario: Агент находит файлы
- **GIVEN** к задаче приложен файл в комментарии
- **WHEN** запускается агент
- **THEN** файл лежит в `.peppa/attachments/` рабочей копии и перечислен в `get_task`

View File

@ -0,0 +1,9 @@
- [x] 1.1 db: таблица `attachments`, миграция
- [x] 1.2 core: `attachments.ts` (проверка, хранение, права, привязка, уборка), экспорт, тесты
- [x] 2.1 веб: маршруты загрузки и отдачи
- [x] 2.2 веб: поле `AttachField` в трёх формах, показ в чате и на странице задачи
- [x] 2.3 действия: привязка вложений при отправке
- [x] 3.1 аналитик: чат и уточнение получают вложения; мок и тест
- [x] 3.2 агент: `.peppa/attachments/`, `get_task`; тест
- [x] 4.1 переводы en/kk, словарь, `pnpm lint`
- [x] 4.2 проверка в браузере (375 и 1280 px), память, AGENTS.md

View File

@ -78,7 +78,8 @@ export async function analystChatContext(db: Db, project: Project): Promise<stri
return [await intakeContext(db, project, { id: 0, goalId: null }), "", await projectStatusBlock(db, project)].join("\n");
}
export function analystChatPrompt(context: string, history: ChatTurn[]): string {
/** `files` — PEP-159: the files attached to the unanswered messages (core/attachments.ts `attachmentsForModel`). */
export function analystChatPrompt(context: string, history: ChatTurn[], files = ""): string {
return [
"Ты — аналитик проекта в чате софтвер-фабрики Peppa FACTORY. С тобой переписывается продакт-менеджер проекта — не программист. Ты ИИ-агент и не выдаёшь себя за человека.",
"Что ты делаешь:",
@ -89,6 +90,7 @@ export function analystChatPrompt(context: string, history: ChatTurn[]): string
"",
context,
"",
...(files ? [files, ""] : []),
"## Переписка (последние сообщения, старые сверху)",
...history.map((t) => `${t.who}: ${t.text.trim()}`),
"",

View File

@ -0,0 +1,358 @@
// PEP-159: files attached to a chat message, a story comment or a story. One module for storage,
// type checks (by content, never by name), access (project people) and the readers: the analyst,
// the story's agent and the web. A file is uploaded first (unlinked, owned by the uploader) and
// linked when the form is sent; unlinked leftovers are removed after a day (`pruneAttachments`).
import { attachments, events, chatMessages, type Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
import { m as tr } from "@peppa/shared/i18n";
import { and, asc, eq, inArray, isNull, lt } from "drizzle-orm";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { PeppaError } from "./errors.ts";
import { isSuperadmin } from "./monitor.ts";
import type { User } from "./users.ts";
import { projectForUser } from "./users.ts";
export type Attachment = typeof attachments.$inferSelect;
export type AttachmentKind = "image" | "pdf" | "text" | "office";
export const ATTACHMENT_MAX_FILES = 5;
export const ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
/** What a text attachment may add to a model's prompt, per file. */
export const ATTACHMENT_PROMPT_TEXT_MAX = 20_000;
const PENDING_MAX_AGE_MS = 24 * 3600_000;
const PENDING_PER_HOUR = 60;
export const attachmentsDir = (projectId: number, id: number) => join(peppaHome(), "files", String(projectId), String(id));
export const attachmentPath = (a: Pick<Attachment, "projectId" | "id" | "file">) => join(attachmentsDir(a.projectId, a.id), a.file);
// ── type by content ─────────────────────────────────────────────────────────────
export interface SniffedFile {
mime: string;
ext: string;
kind: AttachmentKind;
}
const rejected = (name: string) =>
new PeppaError(tr("Файл «{name}» не принят: такой тип не подходит. Можно приложить картинку (PNG, JPEG, WebP, GIF), PDF, текст (TXT, MD, CSV, JSON) или документ Word, Excel, PowerPoint.", { name }));
/** Names of a ZIP's entries from its central directory (null — not a readable ZIP). */
function zipEntries(b: Uint8Array): string[] | null {
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
let eocd = -1;
for (let i = b.length - 22; i >= Math.max(0, b.length - 22 - 65_535); i--) {
if (dv.getUint32(i, true) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd < 0) return null;
const count = dv.getUint16(eocd + 10, true);
let at = dv.getUint32(eocd + 16, true);
const names: string[] = [];
for (let n = 0; n < count && n < 5000; n++) {
if (at + 46 > b.length || dv.getUint32(at, true) !== 0x02014b50) return null;
const len = dv.getUint16(at + 28, true);
const extra = dv.getUint16(at + 30, true);
const comment = dv.getUint16(at + 32, true);
if (at + 46 + len > b.length) return null;
names.push(Buffer.from(b.subarray(at + 46, at + 46 + len)).toString("utf8"));
at += 46 + len + extra + comment;
}
return names;
}
const OFFICE = [
{ entry: "word/document.xml", ext: "docx", mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ entry: "xl/workbook.xml", ext: "xlsx", mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ entry: "ppt/presentation.xml", ext: "pptx", mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
] as const;
const TEXT_EXT: Record<string, string> = { txt: "text/plain", md: "text/markdown", csv: "text/csv", json: "application/json" };
/** The file's real type from its bytes; throws a plain-words PeppaError for anything not allowed. */
export function sniffAttachment(b: Uint8Array, name: string): SniffedFile {
const at = (i: number, ...bytes: number[]) => b.length >= i + bytes.length && bytes.every((x, j) => b[i + j] === x);
if (at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return { mime: "image/png", ext: "png", kind: "image" };
if (at(0, 0xff, 0xd8, 0xff)) return { mime: "image/jpeg", ext: "jpg", kind: "image" };
if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) return { mime: "image/webp", ext: "webp", kind: "image" };
if (at(0, 0x47, 0x49, 0x46, 0x38) && (b[4] === 0x37 || b[4] === 0x39) && b[5] === 0x61) return { mime: "image/gif", ext: "gif", kind: "image" };
if (Buffer.from(b.subarray(0, 1024)).includes("%PDF-")) return { mime: "application/pdf", ext: "pdf", kind: "pdf" };
if (at(0, 0x50, 0x4b, 0x03, 0x04)) {
const names = zipEntries(b);
const office = names && names.includes("[Content_Types].xml") ? OFFICE.find((o) => names.includes(o.entry)) : undefined;
if (office) return { mime: office.mime, ext: office.ext, kind: "office" };
throw rejected(name);
}
// Text: only by an allowed extension, and only if the bytes really are UTF-8 text without NULs.
const ext = /\.([A-Za-z0-9]+)$/.exec(name)?.[1]?.toLowerCase() ?? "";
const mime = TEXT_EXT[ext];
if (!mime || b.includes(0)) throw rejected(name);
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true }).decode(b);
} catch {
throw rejected(name);
}
// A page or a script saved as .txt is not text we take for a document.
if (/^\s*(<!doctype\s+html|<html|<svg|<\?xml|<script|#!)/i.test(text)) throw rejected(name);
if (ext === "json") {
try {
JSON.parse(text);
} catch {
throw new PeppaError(tr("Файл «{name}» не принят: это не настоящий JSON. Проверьте файл и приложите ещё раз.", { name }));
}
}
return { mime, ext, kind: "text" };
}
/** A name safe to show and to use inside a message: no paths, no control characters, ≤120 chars. */
export function displayName(raw: string): string {
const base = raw.replace(/\\/g, "/").split("/").pop() ?? "";
// eslint-disable-next-line no-control-regex
const clean = base.replace(/[\u0000-\u001f\u007f<>]/g, "").trim().slice(-120);
return clean || "file";
}
// ── saving and linking ──────────────────────────────────────────────────────────
export interface AttachmentView {
id: number;
name: string;
mime: string;
size: number;
kind: AttachmentKind;
}
const kindOf = (mime: string): AttachmentKind => (mime.startsWith("image/") ? "image" : mime === "application/pdf" ? "pdf" : mime.startsWith("application/vnd.") ? "office" : "text");
export const attachmentView = (a: Attachment): AttachmentView => ({ id: a.id, name: a.name, mime: a.mime, size: a.size, kind: kindOf(a.mime) });
export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
/** Stores an uploaded file for a project's person; it stays unlinked until a form takes it. */
export async function saveAttachment(db: Db, user: Pick<User, "id">, o: { projectId: number; name: string; data: Uint8Array; now?: Date }): Promise<AttachmentView> {
await projectForUser(db, user.id, o.projectId);
const name = displayName(o.name);
if (o.data.length > ATTACHMENT_MAX_BYTES) throw new PeppaError(tr("Файл «{name}» больше 20 МБ. Приложите файл поменьше.", { name }));
if (!o.data.length) throw new PeppaError(tr("Файл «{name}» пустой. Приложите другой файл.", { name }));
const now = o.now ?? new Date();
const recent = await db
.select({ id: attachments.id })
.from(attachments)
.where(and(eq(attachments.userId, user.id), isNull(attachments.taskId), isNull(attachments.chatMessageId), isNull(attachments.eventId)));
if (recent.length >= PENDING_PER_HOUR) throw new PeppaError(tr("Слишком много файлов без сообщения. Отправьте сообщение или попробуйте позже."));
const type = sniffAttachment(o.data, name);
const [row] = await db.insert(attachments).values({ projectId: o.projectId, userId: user.id, name, file: "pending", mime: type.mime, size: o.data.length, createdAt: now }).returning();
const file = `${row!.id}.${type.ext}`;
const dir = attachmentsDir(o.projectId, row!.id);
try {
mkdirSync(dir, { recursive: true, mode: 0o700 });
writeFileSync(join(dir, file), o.data, { mode: 0o600 });
} catch (e) {
await db.delete(attachments).where(eq(attachments.id, row!.id));
throw e;
}
const [saved] = await db.update(attachments).set({ file }).where(eq(attachments.id, row!.id)).returning();
return attachmentView(saved!);
}
/** «📎 макет.png, ТЗ.pdf» — stands for the words of a message that has only files. */
export async function attachmentLabel(db: Db, ids: number[]): Promise<string> {
if (!ids.length) return "";
const rows = await db.select({ name: attachments.name }).from(attachments).where(inArray(attachments.id, ids));
return `📎 ${rows.map((r) => r.name).join(", ")}`;
}
export interface AttachmentLink {
taskId?: number | null;
chatMessageId?: number | null;
eventId?: number | null;
}
/** Ids as the forms send them: numbers, deduplicated, at most five. */
export function parseAttachmentIds(raw: Array<FormDataEntryValue | number | string>): number[] {
const ids = [...new Set(raw.map((v) => Number(v)).filter((n) => Number.isInteger(n) && n > 0))];
if (ids.length > ATTACHMENT_MAX_FILES) throw new PeppaError(tr("Можно приложить не больше {n} файлов.", { n: ATTACHMENT_MAX_FILES }));
return ids;
}
/** Takes the user's own unlinked uploads of the project and links them to a message/comment/story. */
export async function linkAttachments(db: Db, user: Pick<User, "id">, projectId: number, ids: number[], link: AttachmentLink): Promise<AttachmentView[]> {
if (!ids.length) return [];
if (ids.length > ATTACHMENT_MAX_FILES) throw new PeppaError(tr("Можно приложить не больше {n} файлов.", { n: ATTACHMENT_MAX_FILES }));
const rows = await db.select().from(attachments).where(inArray(attachments.id, ids));
for (const id of ids) {
const a = rows.find((r) => r.id === id);
// Somebody else's, another project's or already used file: the same «not found».
if (!a || a.userId !== user.id || a.projectId !== projectId || a.taskId || a.chatMessageId || a.eventId) throw new PeppaError(tr("Файл не найден. Приложите его ещё раз."));
}
await db.update(attachments).set({ taskId: link.taskId ?? null, chatMessageId: link.chatMessageId ?? null, eventId: link.eventId ?? null }).where(inArray(attachments.id, ids));
return rows.map(attachmentView);
}
/** The uploader takes a file back before sending (the cross next to it). */
export async function discardAttachment(db: Db, user: Pick<User, "id">, id: number): Promise<boolean> {
const [a] = await db.select().from(attachments).where(eq(attachments.id, id));
if (!a || a.userId !== user.id || a.taskId || a.chatMessageId || a.eventId) return false;
removeFiles(a);
await db.delete(attachments).where(eq(attachments.id, id));
return true;
}
function removeFiles(a: Pick<Attachment, "projectId" | "id">) {
rmSync(attachmentsDir(a.projectId, a.id), { recursive: true, force: true });
}
/** Unlinked files older than a day (never sent) and files whose message was pruned. */
export async function pruneAttachments(db: Db, now = new Date()): Promise<number> {
const old = await db
.select()
.from(attachments)
.where(and(isNull(attachments.taskId), isNull(attachments.chatMessageId), isNull(attachments.eventId), lt(attachments.createdAt, new Date(now.getTime() - PENDING_MAX_AGE_MS))));
for (const a of old) {
removeFiles(a);
await db.delete(attachments).where(eq(attachments.id, a.id));
}
return old.length;
}
// ── reading ─────────────────────────────────────────────────────────────────────
/** The file for a project's person or a superadmin; null for anybody else (never says which). */
export async function attachmentForUser(db: Db, viewer: Pick<User, "id" | "login">, id: number): Promise<{ row: Attachment; path: string } | null> {
if (!Number.isInteger(id)) return null;
const [row] = await db.select().from(attachments).where(eq(attachments.id, id));
if (!row || !/^\d+\.[a-z0-9]+$/.test(row.file)) return null;
const mine = row.userId === viewer.id;
if (!mine) {
try {
await projectForUser(db, viewer.id, row.projectId);
} catch {
if (!(await isSuperadmin(db, viewer))) return null;
}
}
const path = attachmentPath(row);
return existsSync(path) ? { row, path } : null;
}
const group = <K extends number>(rows: Attachment[], key: (a: Attachment) => K | null) => {
const out = new Map<K, AttachmentView[]>();
for (const a of rows) {
const k = key(a);
if (k != null) out.set(k, [...(out.get(k) ?? []), attachmentView(a)]);
}
return out;
};
export async function attachmentsByMessage(db: Db, messageIds: number[]): Promise<Map<number, AttachmentView[]>> {
if (!messageIds.length) return new Map();
return group(await db.select().from(attachments).where(inArray(attachments.chatMessageId, messageIds)).orderBy(asc(attachments.id)), (a) => a.chatMessageId);
}
export async function attachmentsByEvent(db: Db, eventIds: number[]): Promise<Map<number, AttachmentView[]>> {
if (!eventIds.length) return new Map();
return group(await db.select().from(attachments).where(inArray(attachments.eventId, eventIds)).orderBy(asc(attachments.id)), (a) => a.eventId);
}
/** Files the story itself carries (attached at creation, no comment). */
export async function storyOwnAttachments(db: Db, taskId: number): Promise<AttachmentView[]> {
const rows = await db
.select()
.from(attachments)
.where(and(eq(attachments.taskId, taskId), isNull(attachments.eventId), isNull(attachments.chatMessageId)))
.orderBy(asc(attachments.id));
return rows.map(attachmentView);
}
export interface TaskAttachment extends AttachmentView {
/** Who attached it and with which words (the comment, the message or the story title). */
note: string;
login: string | null;
/** Path inside the working copy once copied. */
localPath: string;
}
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
export const localAttachmentName = (a: Pick<AttachmentView, "id" | "name">) => `${a.id}-${a.name.replace(/[^\p{L}\p{N}._-]+/gu, "_").slice(-80)}`;
export const ATTACHMENTS_DIR = ".peppa/attachments";
/** Every file of a story and of its discussion, with the words they came with. */
export async function taskAttachments(db: Db, taskId: number): Promise<TaskAttachment[]> {
const rows = await db.select().from(attachments).where(eq(attachments.taskId, taskId)).orderBy(asc(attachments.id));
if (!rows.length) return [];
const evIds = rows.map((r) => r.eventId).filter((x): x is number => x != null);
const msgIds = rows.map((r) => r.chatMessageId).filter((x): x is number => x != null);
const evs = evIds.length ? await db.select({ id: events.id, payload: events.payload }).from(events).where(inArray(events.id, evIds)) : [];
const msgs = msgIds.length ? await db.select({ id: chatMessages.id, text: chatMessages.text, login: chatMessages.authorLogin }).from(chatMessages).where(inArray(chatMessages.id, msgIds)) : [];
return rows.map((a) => {
const ev = evs.find((e) => e.id === a.eventId)?.payload as { text?: string; login?: string } | undefined;
const msg = msgs.find((x) => x.id === a.chatMessageId);
const note = ev?.text ?? msg?.text ?? "";
return { ...attachmentView(a), note: clip(note.replace(/\s+/g, " ").trim(), 300), login: ev?.login ?? msg?.login ?? null, localPath: `${ATTACHMENTS_DIR}/${localAttachmentName(a)}` };
});
}
/**
* Copies a story's files into the working copy (`.peppa/attachments/`, ignored by git) so the
* agent can open them. Returns what was copied; nothing is touched when the story has no files.
*/
export async function copyTaskAttachments(db: Db, taskId: number, workspace: string): Promise<TaskAttachment[]> {
const list = await taskAttachments(db, taskId);
if (!list.length) return [];
const dir = join(workspace, ATTACHMENTS_DIR);
mkdirSync(dir, { recursive: true });
// The folder ignores itself: nothing from it is ever committed, the repository's files stay as they are.
writeFileSync(join(dir, ".gitignore"), "*\n");
const rows = await db.select().from(attachments).where(eq(attachments.taskId, taskId));
const done: TaskAttachment[] = [];
for (const a of list) {
const row = rows.find((r) => r.id === a.id)!;
try {
copyFileSync(attachmentPath(row), join(dir, localAttachmentName(a)));
done.push(a);
} catch {}
}
// Files removed from the story (a pruned message) disappear from the folder too.
const keep = new Set(done.map((a) => localAttachmentName(a)));
for (const f of readdirSync(dir)) if (f !== ".gitignore" && !keep.has(f)) rmSync(join(dir, f), { force: true });
return done;
}
// ── for the analyst ─────────────────────────────────────────────────────────────
export interface ModelFiles {
/** Files the model may read (copied next to the call): images and PDFs. */
files: Array<{ name: string; path: string }>;
/** Text for the prompt: file names, text files' contents, office files by name and type. */
prompt: string;
}
/** What the analyst gets of the given messages'/comments' attachments. */
export async function attachmentsForModel(db: Db, o: { messageIds?: number[]; eventIds?: number[]; /** The story's own files (attached at creation). */ taskOnly?: number }): Promise<ModelFiles> {
const rows: Attachment[] = [];
if (o.messageIds?.length) rows.push(...(await db.select().from(attachments).where(inArray(attachments.chatMessageId, o.messageIds)).orderBy(asc(attachments.id))));
if (o.eventIds?.length) rows.push(...(await db.select().from(attachments).where(inArray(attachments.eventId, o.eventIds)).orderBy(asc(attachments.id))));
if (o.taskOnly) rows.push(...(await db.select().from(attachments).where(and(eq(attachments.taskId, o.taskOnly), isNull(attachments.eventId), isNull(attachments.chatMessageId))).orderBy(asc(attachments.id))));
const files: ModelFiles["files"] = [];
const lines: string[] = [];
for (const a of rows) {
const kind = kindOf(a.mime);
const label = `«${a.name}» (${humanSize(a.size)})`;
if (kind === "image" || kind === "pdf") {
const name = `file-${a.id}.${a.file.split(".").pop()}`;
files.push({ name, path: attachmentPath(a) });
lines.push(`- ${label} — ${kind === "image" ? "картинка" : "PDF"}, файл ${name} в рабочем каталоге: открой его инструментом Read`);
} else if (kind === "text") {
let body = "";
try {
body = readFileSync(attachmentPath(a), "utf8");
} catch {}
const cut = body.length > ATTACHMENT_PROMPT_TEXT_MAX;
lines.push(`- ${label} — текстовый файл${cut ? ` (первые ${ATTACHMENT_PROMPT_TEXT_MAX} знаков)` : ""}:\n---\n${body.slice(0, ATTACHMENT_PROMPT_TEXT_MAX)}\n---`);
} else {
lines.push(`- ${label} — документ Office (${a.file.split(".").pop()}); содержимое тебе пока недоступно, опирайся на название и слова продакта`);
}
}
return { files, prompt: lines.length ? ["Продакт приложил файлы:", ...lines].join("\n") : "" };
}

View File

@ -71,4 +71,5 @@ export * from "./chats.ts";
export * from "./subscription-care.ts";
export * from "./subscription-names.ts";
export * from "./transcribe.ts";
export * from "./attachments.ts";
export * from "./feedback.ts";

View File

@ -80,7 +80,7 @@ export function originalRequest(task: Pick<Task, "title" | "description">, state
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
export function refinePrompt(context: string, story: { title: string; description: string }, thread: StoryComment[], fresh: RefineComment[], product?: ProductNote): string {
export function refinePrompt(context: string, story: { title: string; description: string }, thread: StoryComment[], fresh: RefineComment[], product?: ProductNote, files = ""): string {
const freshIds = new Set(fresh.map((c) => c.id));
const earlier = thread.filter((c) => !freshIds.has(c.id)).slice(-10);
return [
@ -101,6 +101,7 @@ export function refinePrompt(context: string, story: { title: string; descriptio
...(product ? ["", "Решение продакт-менеджера фабрики:", `Цель: ${product.goal}`] : []),
...(earlier.length ? ["", "## Обсуждение стори раньше", ...earlier.map((c) => `${c.login}: ${clip(c.text, 1500)}`)] : []),
"",
...(files ? [files, ""] : []),
"## Новые комментарии продакта",
...fresh.map((c) => `${c.login}: ${clip(c.text, 4000)}`),
"",

View File

@ -14,6 +14,7 @@ import { reviewPreview, type ReviewPreview } from "./preview.ts";
import { blockersOf, dependentsOf, type Blocker } from "./deps.ts";
import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
import { productNeeds, type ProductNeedView } from "./product-needs.ts";
import { taskAttachments, type TaskAttachment } from "./attachments.ts";
import { raiseOnce, type MessageTopic } from "./message-state.ts";
import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts";
import { defaultMessageType, type MessageType } from "./questions.ts";
@ -250,6 +251,8 @@ export interface TaskDetails {
dependents: Array<{ id: number; key: string; title: string; status: TaskStatus }>;
/** PEP-112: what the owner has to give before the product works for real. */
needs?: ProductNeedView[];
/** PEP-159: files attached to the story and its discussion. */
attachments?: TaskAttachment[];
/** PEP-43/5: what the story spent and its budget. */
budget: TaskBudgetView;
}
@ -296,7 +299,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
.orderBy(desc(events.id))
.limit(20);
const incident = await incidentForTask(db, ref.task.id);
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task), needs: await productNeeds(db, ref.project.id) };
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref), budget: await taskBudgetView(db, ref.task), needs: await productNeeds(db, ref.project.id), attachments: await taskAttachments(db, ref.task.id) };
}
export interface NewQuestion {

View File

@ -815,6 +815,31 @@ export const feedback = sqliteTable(
(t) => [index("feedback_user").on(t.userId, t.createdAt), index("feedback_status").on(t.status)],
);
/**
* PEP-159: a file attached to a chat message, a story comment or a story. Uploaded first
* (task/message/event empty, `user_id` = uploader), linked when the form is sent. Bytes live in
* `$PEPPA_HOME/files/<project_id>/<id>/<file>` under a name of our own; `name` is for display only.
*/
export const attachments = sqliteTable(
"attachments",
{
id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
userId: integer("user_id").references(() => users.id, { onDelete: "set null" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
chatMessageId: integer("chat_message_id").references((): AnySQLiteColumn => chatMessages.id, { onDelete: "set null" }),
// The story comment (an `events` row).
eventId: integer("event_id").references(() => events.id, { onDelete: "set null" }),
name: text("name").notNull(),
// Name on disk inside the attachment's directory.
file: text("file").notNull(),
mime: text("mime").notNull(),
size: integer("size").notNull(),
createdAt: createdAt(),
},
(t) => [index("attachments_task").on(t.taskId), index("attachments_message").on(t.chatMessageId), index("attachments_event").on(t.eventId), index("attachments_project").on(t.projectId)],
);
export const projectsRelations = relations(projects, ({ many }) => ({
goals: many(goals),
tasks: many(tasks),

View File

@ -1,4 +1,4 @@
import { agentAutonomyNote, describeBudget, fmtCost, fmtHours, fmtPct, fmtTokens, PROVIDER_NAMES, type MetricsBucket, type ProjectMetrics, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
import { humanSize, agentAutonomyNote, describeBudget, fmtCost, fmtHours, fmtPct, fmtTokens, PROVIDER_NAMES, type MetricsBucket, type ProjectMetrics, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
import { stripAsIs } from "@peppa/shared/i18n";
const NEXT_STEP: Record<TaskStatus, string> = {
@ -54,6 +54,14 @@ export function formatTask(d: TaskDetails): string {
for (const n of d.needs) lines.push(`- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}${n.story ? ` · ${n.story}` : ""}`);
if (d.needs.some((n) => n.open)) lines.push("", "Пока пункт открыт, продукт работает на моке — не называй стори готовой молча.");
}
// PEP-159: files the PM attached to the story or its discussion.
if (d.attachments?.length) {
lines.push("", "## Приложенные файлы");
for (const a of d.attachments) {
lines.push(`- \`${a.localPath}\` — «${a.name}» (${a.mime}, ${humanSize(a.size)})${a.login ? `, приложил ${a.login}` : ""}${a.note ? `: ${a.note}` : ""}`);
}
lines.push("", "Файлы копируются в рабочую копию при запуске агента; в git они не попадают. Если файла в этой папке нет (запуск на отдельном хосте), он лежит на сайте Peppa: /api/attachments/<номер>, номер — в начале имени файла.");
}
// PEP-32: the PM's comments on the story — instructions to take into account.
if (d.comments?.length) {
lines.push("", "## Комментарии PM");

View File

@ -8,6 +8,7 @@ import {
analystChatContext,
analystChatPrompt,
analystCursor,
attachmentsForModel,
ANALYST_NAME,
createTask,
deliverToUser,
@ -21,19 +22,20 @@ import {
type Project,
} from "@peppa/core";
import { chatMessages, chats, projects, type Db } from "@peppa/db";
import { and, desc, eq, gt, isNull } from "drizzle-orm";
import { and, desc, eq, gt, isNull, lte } from "drizzle-orm";
import { localizeRoleMessage, m as tr, t } from "@peppa/shared/i18n";
import { claudePrint } from "./claude-print.ts";
const inFlight = new Set<number>();
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const ask = (db: Db, project: Project, prompt: string) =>
const ask = (db: Db, project: Project, prompt: string, files?: Array<{ name: string; path: string }>) =>
claudePrint(db, project, {
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
model: process.env.PEPPA_ANALYST_CHAT_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
prompt,
files,
who: "аналитик",
});
@ -72,7 +74,7 @@ export async function analystChatTick(db: Db, opts: AnalystChatOptions = {}): Pr
}
inFlight.add(chat.id);
jobs.push(
answer(db, project, chat.id, last.id, log)
answer(db, project, chat.id, cursor, last.id, log)
.catch((e) => log(`analyst chat ${project.key}: ${(e as Error).message}`))
.finally(() => inFlight.delete(chat.id)),
);
@ -112,9 +114,15 @@ export async function sayInDiscussion(db: Db, project: Project, chatId: number,
const say = (db: Db, project: Project, chatId: number, text: string, agent = true) => sayInDiscussion(db, project, chatId, text, agent ? ANALYST_NAME : null);
async function answer(db: Db, project: Project, chatId: number, upTo: number, log: (m: string) => void): Promise<void> {
async function answer(db: Db, project: Project, chatId: number, from: number, upTo: number, log: (m: string) => void): Promise<void> {
const history = await discussionHistory(db, chatId);
const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history));
// PEP-159: files of the messages not answered yet (everything after the cursor).
const fresh = await db
.select({ id: chatMessages.id })
.from(chatMessages)
.where(and(eq(chatMessages.chatId, chatId), isNull(chatMessages.threadKey), gt(chatMessages.id, from), lte(chatMessages.id, upTo)));
const attached = await attachmentsForModel(db, { messageIds: fresh.map((r) => r.id) });
const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history, attached.prompt), attached.files);
// Whatever happens, this message is dealt with: a failure is said once, not retried forever.
await setAnalystCursor(db, chatId, upTo);
if (!out.ok) {

View File

@ -5,6 +5,9 @@ import { asIs, m, m as tr } from "@peppa/shared/i18n";
import {
addChatMessage,
addStoryComment,
attachmentLabel,
linkAttachments,
parseAttachmentIds,
refinePending,
chatForUser,
deliverToUser,
@ -22,10 +25,10 @@ import {
type User,
PeppaError,
} from "@peppa/core";
import { projects, questions, tasks, type Db } from "@peppa/db";
import { attachments, projects, questions, tasks, type Db } from "@peppa/db";
import { and, desc, eq, isNull, ne } from "drizzle-orm";
import { moveTask, type BoardColumn } from "./flow.ts";
import { answerAndDeliver, sendToSession } from "./sessions.ts";
import { answerAndDeliver, sendToSession, syncSessionAttachments } from "./sessions.ts";
export interface ChatPost {
chatId: number;
@ -37,6 +40,8 @@ export interface ChatPost {
questionId?: number | null;
/** Where it was written in Telegram (a reply to it finds the thread). */
tg?: { chatId: number; messageId: number };
/** PEP-159: ids of the files uploaded for this message (core/attachments.ts). */
attachmentIds?: number[];
}
export interface ChatPostResult {
@ -76,7 +81,8 @@ const COLUMN_MOVED: Record<BoardColumn, string> = { backlog: m("{key} → Бэк
/** Posts a person's message and does what it means. Access: chatForUser (project people / master owner). */
export async function postToChat(db: Db, user: User, p: ChatPost): Promise<ChatPostResult> {
const chat = await chatForUser(db, user, p.chatId);
const text = p.text.trim();
const ids = parseAttachmentIds(p.attachmentIds ?? []);
const text = p.text.trim() || (await attachmentLabel(db, ids));
if (!text) throw new PeppaError(m("Пустое сообщение"));
if (text.length > MAX_TEXT) throw new PeppaError(m("Сообщение длиннее {n} символов", { n: MAX_TEXT }));
if (p.threadKey && !THREAD_KEY.test(p.threadKey)) throw new PeppaError(m("Неизвестный тред"));
@ -97,6 +103,7 @@ export async function postToChat(db: Db, user: User, p: ChatPost): Promise<ChatP
tgChatId: p.tg?.chatId ?? null,
tgMessageId: p.tg?.messageId ?? null,
}))!;
if (ids.length && chat.projectId) await linkAttachments(db, user, chat.projectId, ids, { chatMessageId: message.id, taskId });
const say = async (t: string) => {
const r = await addChatMessage(db, { chatId: chat.id, threadKey: p.threadKey, taskId, kind: "system", text: t });
return r;
@ -168,9 +175,11 @@ async function toAgent(db: Db, user: User, message: ChatMessage, taskId: number,
const ref = await resolveTaskById(db, taskId);
// The comment event carries this message's id: the projection doesn't repeat it in the thread.
const c = await addStoryComment(db, ref, user, text, { chatMessageId: message.id });
// PEP-159: the files of the message belong to the comment too (the story page shows them there).
await db.update(attachments).set({ eventId: c.id }).where(eq(attachments.chatMessageId, message.id));
const [live] = await listSessions(db, { active: true, taskId });
if (!live) return (await refinePending(db, ref.task)) ? m("Комментарий сохранён — агент ещё не начал, аналитик уточнит постановку и ответит в обсуждении задачи.") : m("Комментарий сохранён — агент увидит его, когда возьмётся за задачу.");
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`, { person: true });
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
return m("Комментарий ушёл агенту ✅");
}

View File

@ -3,6 +3,7 @@ import { chmodSync, existsSync, realpathSync, rmSync, writeFileSync } from "node
import { join } from "node:path";
import {
agentAutonomyNote,
copyTaskAttachments,
answerQuestion,
getAutonomy,
getBudgetState,
@ -185,6 +186,22 @@ export async function startRunner(
return launch(db, await getSession(db, session.id), cwd, opts);
}
/**
* PEP-159: the story's files copied into the runner's working copy (`.peppa/attachments/`);
* the note to append to a message typed into the live agent. Empty when there are none or the
* copy is on another host (`get_task` then says the files are on the site).
*/
export async function syncSessionAttachments(db: Db, sessionId: number): Promise<string> {
try {
const s = await getSession(db, sessionId);
if (!s.taskId || s.host) return "";
const files = await copyTaskAttachments(db, s.taskId, await runnerCwd(db, s));
return files.length ? `\n\nПриложенные файлы (в рабочей копии): ${files.map((f) => f.localPath).join(", ")}` : "";
} catch {
return "";
}
}
/** The runner's working copy: its own worktree (recreated if gone, PEP-27) or the project's. */
export async function runnerCwd(db: Db, s: SessionView): Promise<string> {
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
@ -255,6 +272,8 @@ async function launch(
const memory = await memoryContext(db, s.projectId, memDir).catch(() => "");
// PEP-75: the runner's persona (assigned on the first launch) — name and character in the prompt.
const persona = await ensureSessionAgent(db, s.id).catch(() => null);
// PEP-159: files attached to the story and its discussion lie in the working copy for the agent.
if (s.taskId && !s.host) await copyTaskAttachments(db, s.taskId, cwd).catch(() => []);
const extras = [memory, persona ? agentPrompt(persona) : ""].filter(Boolean).join("\n\n");
// The session's subscription (rotation changes it beforehand, PEP-39); none = this machine's login.
const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;

View File

@ -5,6 +5,7 @@
import { m } from "@peppa/shared/i18n";
import {
addIntakeNote,
attachmentsForModel,
getIntakeSettings,
getIntakeState,
intakeContext,
@ -65,12 +66,15 @@ async function refine(db: Db, taskId: number, fresh: RefineComment[], log: (m: s
// «Продакт» and «аналитик» (PEP-84) are still formulating the story: wait for them.
if (intakePending(await getIntakeSettings(db, ref.project.id), ref.task, state)) return;
const { project, task } = ref;
const prompt = refinePrompt(await intakeContext(db, project, task), { title: task.title, description: task.description ?? "" }, await storyComments(db, taskId), fresh, state?.product);
// PEP-159: files attached to the new comments (and to the story itself) go to the analyst too.
const attached = await attachmentsForModel(db, { eventIds: fresh.map((c) => c.id), taskOnly: taskId });
const prompt = refinePrompt(await intakeContext(db, project, task), { title: task.title, description: task.description ?? "" }, await storyComments(db, taskId), fresh, state?.product, attached.prompt);
const out = await claudePrint(db, project, {
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
model: process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
prompt,
files: attached.files,
who: m("аналитик"),
});
// Whatever happens, these comments are dealt with.

View File

@ -8,6 +8,7 @@ import {
digestTick,
platformDigestTick,
recheckPlatformChannel,
pruneAttachments,
pruneChats,
syncChats,
getBudgetState,
@ -130,6 +131,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
if (nowMs - lastChatPrune >= 3600_000) {
lastChatPrune = nowMs;
await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch(failed(db, log, "chats prune"));
// PEP-159: files that were chosen but never sent.
await pruneAttachments(db).then((n) => n && log(`attachments: pruned ${n}`)).catch(failed(db, log, "attachments prune"));
}
}
let lastChatPrune = 0;

View File

@ -0,0 +1,24 @@
import type { Dict } from "../index.ts";
// PEP-159: files in chats, comments and new stories.
export const attachments: Dict = {
"Файлы задачи": "Task files",
"Файл больше 20 МБ. Приложите файл поменьше.": "The file is larger than 20 MB. Attach a smaller file.",
"Выберите файл.": "Choose a file.",
"Можно приложить не больше {n} файлов.": "You can attach no more than {n} files.",
"Файл «{name}» больше 20 МБ. Приложите файл поменьше.": "The file “{name}” is larger than 20 MB. Attach a smaller file.",
"Не получилось загрузить файл. Попробуйте ещё раз.": "Could not upload the file. Please try again.",
"Файлы ещё загружаются. Подождите секунду и отправьте снова.": "The files are still uploading. Wait a second and send again.",
"Приложить файл": "Attach a file",
"Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.": "Pictures, PDF, text, Word, Excel, PowerPoint — up to 5 files, each up to 20 MB. You can drop a file onto the field or paste a picture from the clipboard.",
"Отпустите файл здесь": "Drop the file here",
"Файл": "File",
"Приложенные файлы": "Attached files",
"загружается": "uploading",
"Убрать файл {name}": "Remove the file {name}",
"Файл «{name}» не принят: такой тип не подходит. Можно приложить картинку (PNG, JPEG, WebP, GIF), PDF, текст (TXT, MD, CSV, JSON) или документ Word, Excel, PowerPoint.": "The file “{name}” was not accepted: this type is not allowed. You can attach a picture (PNG, JPEG, WebP, GIF), a PDF, text (TXT, MD, CSV, JSON) or a Word, Excel or PowerPoint document.",
"Файл «{name}» не принят: это не настоящий JSON. Проверьте файл и приложите ещё раз.": "The file “{name}” was not accepted: it is not valid JSON. Check the file and attach it again.",
"Файл «{name}» пустой. Приложите другой файл.": "The file “{name}” is empty. Attach another file.",
"Слишком много файлов без сообщения. Отправьте сообщение или попробуйте позже.": "Too many files without a message. Send a message or try later.",
"Файл не найден. Приложите его ещё раз.": "The file was not found. Attach it again.",
};

View File

@ -15,5 +15,6 @@ import { merge_b } from "./merge-b.ts";
import { merge_c } from "./merge-c.ts";
import { merge_d } from "./merge-d.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback };
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments };

View File

@ -0,0 +1,24 @@
import type { Dict } from "../index.ts";
/** Kazakh (PEP-99) for en/attachments.ts — keys are the Russian strings. */
export const attachments: Dict = {
"Файлы задачи": "Тапсырма файлдары",
"Файл больше 20 МБ. Приложите файл поменьше.": "Файл 20 МБ-тан үлкен. Кішірек файл тіркеңіз.",
"Выберите файл.": "Файлды таңдаңыз.",
"Можно приложить не больше {n} файлов.": "{n} файлдан артық тіркеуге болмайды.",
"Файл «{name}» больше 20 МБ. Приложите файл поменьше.": "«{name}» файлы 20 МБ-тан үлкен. Кішірек файл тіркеңіз.",
"Не получилось загрузить файл. Попробуйте ещё раз.": "Файлды жүктеу мүмкін болмады. Қайталап көріңіз.",
"Файлы ещё загружаются. Подождите секунду и отправьте снова.": "Файлдар әлі жүктелуде. Бір секунд күтіп, қайта жіберіңіз.",
"Приложить файл": "Файл тіркеу",
"Картинки, PDF, текст, Word, Excel, PowerPoint — до 5 файлов, каждый до 20 МБ. Можно перетащить файл в поле или вставить картинку из буфера.": "Суреттер, PDF, мәтін, Word, Excel, PowerPoint — 5 файлға дейін, әрқайсысы 20 МБ-қа дейін. Файлды өріске сүйреп апаруға немесе буферден суретті қоюға болады.",
"Отпустите файл здесь": "Файлды осы жерге жіберіңіз",
"Файл": "Файл",
"Приложенные файлы": "Тіркелген файлдар",
"загружается": "жүктелуде",
"Убрать файл {name}": "«{name}» файлын алып тастау",
"Файл «{name}» не принят: такой тип не подходит. Можно приложить картинку (PNG, JPEG, WebP, GIF), PDF, текст (TXT, MD, CSV, JSON) или документ Word, Excel, PowerPoint.": "«{name}» файлы қабылданбады: мұндай түр жарамайды. Сурет (PNG, JPEG, WebP, GIF), PDF, мәтін (TXT, MD, CSV, JSON) немесе Word, Excel, PowerPoint құжатын тіркеуге болады.",
"Файл «{name}» не принят: это не настоящий JSON. Проверьте файл и приложите ещё раз.": "«{name}» файлы қабылданбады: бұл дұрыс JSON емес. Файлды тексеріп, қайта тіркеңіз.",
"Файл «{name}» пустой. Приложите другой файл.": "«{name}» файлы бос. Басқа файл тіркеңіз.",
"Слишком много файлов без сообщения. Отправьте сообщение или попробуйте позже.": "Хабарламасыз файл тым көп. Хабарлама жіберіңіз немесе кейінірек көріңіз.",
"Файл не найден. Приложите его ещё раз.": "Файл табылмады. Оны қайта тіркеңіз.",
};

View File

@ -15,5 +15,6 @@ import { runner } from "./runner.ts";
import { settings } from "./settings.ts";
import { story } from "./story.ts";
import { feedback } from "./feedback.ts";
import { attachments } from "./attachments.ts";
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback };
export const kk: Dict = { ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments };

View File

@ -30,7 +30,7 @@ const prompt = readFileSync(0, "utf8");
const role = prompt.startsWith("Ты — агент обратной связи") ? "feedback" : prompt.startsWith("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst";
const answered = /Ответ продакта:\n/.test(prompt);
const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "feedback" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "feedback" || role === "chat" || role === "refine" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
if (!process.argv.includes("-p")) {
console.error("mock-intake: expected -p (non-interactive print mode)");
process.exit(2);

View File

@ -0,0 +1,196 @@
// PEP-159: files in the analyst chat, in story comments and in a new story — type by content,
// size, access, the analyst and the story's agent seeing them.
import assert from "node:assert/strict";
import { deflateRawSync } from "node:zlib";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { core, db, project as mockProject, runner, teardown, waitFor } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-attach-"));
const scenario = join(TMP, "scenario.json");
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; prompt: string; files?: string[] });
const { formatTask } = await import("../../mcp/src/format.ts");
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(64)]);
const PDF = Buffer.from("%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF\n");
const TXT = Buffer.from("Требования заказчика:\n- кнопка «Купить» зелёная\n");
/** A minimal ZIP (central directory with the given entry names) — enough for the type check. */
function zip(names: string[]): Buffer {
const locals: Buffer[] = [];
const centrals: Buffer[] = [];
let offset = 0;
for (const n of names) {
const name = Buffer.from(n);
const data = deflateRawSync(Buffer.from("x"));
const lh = Buffer.alloc(30);
lh.writeUInt32LE(0x04034b50, 0);
lh.writeUInt16LE(8, 8);
lh.writeUInt32LE(data.length, 18);
lh.writeUInt32LE(1, 22);
lh.writeUInt16LE(name.length, 26);
const local = Buffer.concat([lh, name, data]);
const ch = Buffer.alloc(46);
ch.writeUInt32LE(0x02014b50, 0);
ch.writeUInt16LE(8, 10);
ch.writeUInt32LE(data.length, 20);
ch.writeUInt32LE(1, 24);
ch.writeUInt16LE(name.length, 28);
ch.writeUInt32LE(offset, 42);
centrals.push(Buffer.concat([ch, name]));
locals.push(local);
offset += local.length;
}
const cd = Buffer.concat(centrals);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(names.length, 8);
end.writeUInt16LE(names.length, 10);
end.writeUInt32LE(cd.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...locals, cd, end]);
}
const DOCX = zip(["[Content_Types].xml", "word/document.xml"]);
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
let stranger: User;
let proj: Awaited<ReturnType<typeof core.createProject>>;
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
const upload = (name: string, data: Uint8Array, user: User = pm, projectId = proj.id) => core.saveAttachment(db, user, { projectId, name, data });
before(async () => {
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
process.env.MOCK_INTAKE_SCENARIO = scenario;
writeFileSync(scenario, "{}");
pm = await core.upsertUserFromGitea(db, { id: 1591, login: "asel" }, { access_token: "x" });
stranger = await core.upsertUserFromGitea(db, { id: 1592, login: "outsider" }, { access_token: "x" });
const ws = join(TMP, "ws");
mkdirSync(join(ws, ".peppa"), { recursive: true });
proj = await core.createProject(db, { slug: "mock-attach", key: "ATT", name: "Вложения", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
chat = await core.ensureProjectChat(db, proj.id);
});
after(teardown);
describe("PEP-159: type by content", () => {
test("Scenario: картинки, PDF, текст и документы Office принимаются по содержимому", async () => {
assert.deepEqual(core.sniffAttachment(PNG, "x.bin"), { mime: "image/png", ext: "png", kind: "image" }, "the name does not matter for a picture");
assert.equal(core.sniffAttachment(PDF, "тз").kind, "pdf");
assert.equal(core.sniffAttachment(TXT, "тз.txt").kind, "text");
assert.equal(core.sniffAttachment(Buffer.from("a,b\n1,2\n"), "t.csv").mime, "text/csv");
assert.equal(core.sniffAttachment(DOCX, "тз.docx").ext, "docx");
assert.equal(core.sniffAttachment(zip(["[Content_Types].xml", "xl/workbook.xml"]), "t.xlsx").ext, "xlsx");
assert.equal(core.sniffAttachment(zip(["[Content_Types].xml", "ppt/presentation.xml"]), "t.pptx").ext, "pptx");
});
test("Scenario: SVG, HTML, скрипт, архив и исполняемый файл отклоняются с причиной", async () => {
const bad: Array<[string, Uint8Array]> = [
["logo.svg", Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')],
["page.html", Buffer.from("<!doctype html><script>alert(1)</script>")],
["fake.txt", Buffer.from("<html><body onload=alert(1)>")],
["run.sh", Buffer.from("#!/bin/sh\nrm -rf /\n")],
["fake.txt", Buffer.from("#!/bin/sh\nrm -rf /\n")],
["a.zip", zip(["a.txt"])],
["app.exe", Buffer.concat([Buffer.from("MZ"), Buffer.alloc(64, 1)])],
["bin.txt", Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0, 0, 0])],
["notes.json", Buffer.from("{не json")],
];
for (const [name, data] of bad) assert.throws(() => core.sniffAttachment(data, name), /не принят/, name);
await assert.rejects(upload("logo.svg", bad[0]![1]), /не принят.*картинку.*PDF/s);
assert.equal((await db.select().from((await import("@peppa/db")).attachments)).length, 0, "nothing saved");
});
test("Scenario: файл больше 20 МБ — понятная ошибка", async () => {
await assert.rejects(upload("big.png", Buffer.concat([PNG, Buffer.alloc(20 * 1024 * 1024)])), /больше 20 МБ/);
});
});
describe("PEP-159: access", () => {
test("Scenario: посторонний не открывает файл чужого проекта", async () => {
const a = await upload("макет.png", PNG);
const mine = await core.attachmentForUser(db, pm, a.id);
assert.ok(mine && existsSync(mine.path) && mine.path.includes(`/files/${proj.id}/${a.id}/`), "stored under files/<project>/<id>/");
assert.equal(await core.attachmentForUser(db, stranger, a.id), null, "outsider: not found");
await assert.rejects(upload("x.png", PNG, stranger), /Не найдено/, "and cannot upload into the project either");
});
test("Scenario: чужой файл нельзя привязать к своему сообщению", async () => {
const a = await upload("секрет.png", PNG);
await assert.rejects(core.linkAttachments(db, stranger, proj.id, [a.id], { taskId: 1 }), /Файл не найден/);
await assert.rejects(core.linkAttachments(db, pm, proj.id + 999, [a.id], { taskId: 1 }), /Файл не найден/, "nor into another project");
});
});
describe("PEP-159: chat with the analyst", () => {
test("Scenario: приложенные PDF, картинка и текст доходят до аналитика", async () => {
const files = [await upload("макет.png", PNG), await upload("тз.pdf", PDF), await upload("требования.txt", TXT), await upload("тз.docx", DOCX)];
const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "Посмотрите файлы", via: "web", attachmentIds: files.map((f) => f.id) });
const shown = (await core.attachmentsByMessage(db, [message.id])).get(message.id)!;
assert.deepEqual(shown.map((f) => [f.name, f.kind]), [["макет.png", "image"], ["тз.pdf", "pdf"], ["требования.txt", "text"], ["тз.docx", "office"]]);
await runner.analystChatTick(db, { wait: true });
const c = calls().filter((x) => x.role === "chat").at(-1)!;
assert.deepEqual(c.files!.filter((f) => f.startsWith("file-")).sort(), [`file-${files[0]!.id}.png`, `file-${files[1]!.id}.pdf`], "image and PDF are files in the call's directory");
assert.match(c.prompt, /«макет.png» \(\d+ B\) — картинка, файл file-\d+\.png/);
assert.match(c.prompt, /«требования.txt»[^\n]* — текстовый файл:\n---\nТребования заказчика:\n- кнопка «Купить» зелёная/, "text files go in as content");
assert.match(c.prompt, /«тз.docx»[^\n]* документ Office/, "office files by name and type");
});
test("Scenario: сообщение только с файлом получает подпись из имён", async () => {
const f = await upload("логотип.png", PNG);
const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web", attachmentIds: [f.id] });
assert.equal(message.text, "📎 логотип.png");
await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web" }), /Пустое сообщение/);
});
test("Scenario: больше пяти файлов не принимается", () => {
assert.throws(() => core.parseAttachmentIds([1, 2, 3, 4, 5, 6]), /не больше 5/);
});
});
describe("PEP-159: story comment and the story's agent", () => {
test("Scenario: файл комментария к стори в бэклоге уходит аналитику", async () => {
const ref = await core.createTask(db, { projectId: proj.id, title: "Корзина", description: "Покупатель складывает товары в корзину" });
const f = await upload("скриншот.png", PNG);
const c = await core.addStoryComment(db, ref, pm, "Вот как должно выглядеть");
await core.linkAttachments(db, pm, proj.id, [f.id], { taskId: ref.task.id, eventId: c.id });
await runner.storyRefineTick(db, { wait: true });
const call = calls().filter((x) => x.role === "refine").at(-1)!;
assert.ok(call.files!.includes(`file-${f.id}.png`));
assert.match(call.prompt, /«скриншот.png»/);
assert.equal((await core.attachmentsByEvent(db, [c.id])).get(c.id)![0]!.name, "скриншот.png", "shown under the comment");
});
test("Scenario: агент находит файлы в .peppa/attachments/ и в get_task", async () => {
const p = await mockProject({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "ok" }]] });
const pr = await core.getProject(db, p.key);
const ref = await core.resolveTask(db, p.taskKey);
const a = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "ТЗ клиента.pdf", data: PDF });
const own = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "лого.png", data: PNG });
const c = await core.addStoryComment(db, ref, { id: pr.ownerId!, login: "asel" }, "Вот ТЗ от клиента");
await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [a.id], { taskId: ref.task.id, eventId: c.id });
await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [own.id], { taskId: ref.task.id });
const sid = await p.start();
const dir = join(p.dir, ".peppa/attachments");
await waitFor("files copied", async () => existsSync(dir) && readdirSync(dir).length >= 3);
assert.deepEqual(readdirSync(dir).sort(), [".gitignore", `${a.id}-ТЗ_клиента.pdf`, `${own.id}-лого.png`].sort());
assert.equal(readFileSync(join(dir, ".gitignore"), "utf8"), "*\n", "never committed");
const text = formatTask(await core.getTaskDetails(db, ref));
assert.match(text, new RegExp(`## Приложенные файлы\\n- \`.peppa/attachments/${a.id}-ТЗ_клиента.pdf\` — «ТЗ клиента.pdf» \\(application/pdf, \\d+ B\\), приложил asel: Вот ТЗ от клиента`));
assert.match(text, /`.peppa\/attachments\/\d+-лого.png` — «лого.png»/);
await runner.stopSession(db, sid);
});
test("Scenario: неотправленные файлы старше суток удаляются", async () => {
const f = await upload("забытый.png", PNG);
const found = (await core.attachmentForUser(db, pm, f.id))!;
assert.equal(await core.pruneAttachments(db, new Date()), 0, "fresh ones stay");
assert.ok(await core.pruneAttachments(db, new Date(Date.now() + 25 * 3600_000)) >= 1);
assert.equal(existsSync(found.path), false);
assert.equal(await core.attachmentForUser(db, pm, f.id), null);
});
});