PEP-235: блок «Ждут подтверждения» в «Подключениях», переводы

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-30 11:14:39 +00:00
parent 5e772bfb32
commit 51b72611f8
6 changed files with 102 additions and 5 deletions

View File

@ -71,7 +71,7 @@ import {
} from "@peppa/core";
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
import { deleteProject, decideConnectionApproval, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { pauseProject, resumeProject, startAcceptAll, processAcceptQueue, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, 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, requestSubscription } from "@peppa/runner";
@ -1197,6 +1197,16 @@ export async function denyAccessRequestAction(f: FormData) {
});
}
/** PEP-235: «Разрешить один раз» / «Отклонить» on a call waiting for the owner's confirmation. */
export async function decideApprovalAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const allow = str(f, "decision") === "allow";
await decideConnectionApproval(db, user.id, Number(str(f, "approvalId")), allow, { via: "web" });
return `/connections?approval=${allow ? "allowed" : "denied"}#approvals`;
});
}
export async function revokeGrantAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {

View File

@ -18,6 +18,7 @@ import {
listConnections,
listUserProjects,
ownerAccessRequests,
ownerPendingApprovals,
connectionsForRequest,
oauthOffer,
scopeLabel,
@ -33,6 +34,7 @@ import {
GATEWAY_PROTOCOLS,
} from "@peppa/core";
import { AccessRequestList } from "@/components/AccessRequests";
import { ApprovalList } from "@/components/ConnectionApprovals";
import { Hidden } from "@/components/cards";
import { intlLocale } from "@peppa/shared/i18n";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
@ -52,7 +54,7 @@ export async function generateMetadata() {
return { title: t("Подключения — FORGE") };
}
type Params = { error?: string; created?: string; checked?: string; check?: string; signed?: string; revoked?: string; remote?: string; service?: string; q?: string; kind?: string };
type Params = { approval?: string; error?: string; created?: string; checked?: string; check?: string; signed?: string; revoked?: string; remote?: string; service?: string; q?: string; kind?: string };
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
const BACK = "/connections";
@ -653,6 +655,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
const t = await getT();
const engineer = (await uiMode()) === "engineer";
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
const approvals = await ownerPendingApprovals(db, user.id);
// PEP-261: «Дать» right in the list — only where a fitting connection exists.
const grantable = new Set((await Promise.all(requests.map(async (r) => ((await connectionsForRequest(db, user.id, r)).fit.length ? r.id : 0)))).filter(Boolean));
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
@ -669,6 +672,14 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
</p>
</PageHeader>
{q.approval === "allowed" && <Notice>{t("Разрешено один раз. Агент получит результат.")}</Notice>}
{q.approval === "denied" && <Notice>{t("Отклонено. Действие не выполнено, агент узнает об этом.")}</Notice>}
{approvals.length > 0 && (
<Section id="approvals" title={t("Ждут подтверждения")} count={approvals.length}>
<ApprovalList list={approvals} t={t} />
</Section>
)}
{requests.length > 0 && (
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
<AccessRequestList list={requests} grantable={grantable} t={t} />

View File

@ -0,0 +1,42 @@
import { ShieldQuestion } from "lucide-react";
import type { ApprovalView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n";
import { decideApprovalAction } from "@/app/(app)/actions";
import { Hidden } from "@/components/cards";
import { ago } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
/**
* PEP-235: «Ждут подтверждения» on «Подключения» — agents' calls that run only after the owner's
* «Разрешить один раз». The card shows who, where and what (values that look like keys hidden).
*/
export function ApprovalList({ list, t }: { list: ApprovalView[]; t: Translator }) {
return (
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{list.map((a) => (
<li key={a.id} id={`approval-${a.id}`}>
<Card className="flex flex-wrap items-center gap-x-3 gap-y-1 p-3 text-sm" data-approval={a.id}>
<ShieldQuestion className="size-4 text-primary" />
<span className="font-medium">{a.connectionName}</span>
<span className="text-muted-foreground">
· {a.agentName ? t("агент {name}", { name: a.agentName }) : t("агент")} · {a.taskKey ? `${a.taskKey}${a.taskTitle ? ` «${a.taskTitle}»` : ""}` : a.projectKey}
</span>
<span className="ml-auto text-xs text-muted-foreground">{ago(a.createdAt, t)}</span>
<pre className="m-0 basis-full overflow-x-auto whitespace-pre-wrap rounded-md bg-muted p-2 font-mono text-xs">{a.summary}</pre>
<span className="basis-full text-xs text-muted-foreground">{t("До вашего ответа действие не выполняется. Без ответа запрос отменится сам.")}</span>
<form action={decideApprovalAction} className="flex basis-full flex-wrap items-center gap-2 pt-1">
<Hidden fields={{ back: "/connections#approvals", approvalId: a.id }} />
<Button size="sm" name="decision" value="allow" data-approval-decision="allow">
{t("Разрешить один раз")}
</Button>
<Button size="sm" variant="secondary" name="decision" value="deny" data-approval-decision="deny">
{t("Отклонить")}
</Button>
</form>
</Card>
</li>
))}
</ul>
);
}

View File

@ -830,7 +830,7 @@ export async function agentConnections(db: Db, sessionId: number, o: { now?: Dat
/**
* The gateway's decision for one agent request over its grants (PEP-249): a «Тонкая настройка»
* line allows; otherwise the request is read or write by the catalog rule and the widest mode
* decides — auto runs, ask waits for the owner (PEP-235; until then refused), off refuses.
* decides — auto runs, ask waits for the owner (PEP-235: connection-approvals.ts), off refuses.
*/
export function grantDecision(catalogId: string | null, grants: Array<{ operations: string[]; readMode: GrantMode; writeMode: GrantMode }>, method: string, path: string): ConnectionReason | null {
if (operationAllows(grants.flatMap((g) => g.operations), method, path)) return null;

View File

@ -140,7 +140,6 @@ export const accessHub: Record<string, string> = {
"Кабинет 2GIS Platform Manager → ключи доступа: создайте ключ для Places API.": "2GIS Platform Manager cabinet → access keys: create a key for the Places API.",
"чтение не разрешено": "reading isn't allowed",
"запись не разрешена": "writing isn't allowed",
"нужно подтверждение владельца, а подтверждения пока не поддерживаются": "the owner's confirmation is needed, and confirmations aren't supported yet",
"проверка ключа владельцем": "key check by the owner",
"ключ работает": "key works",
"ключ не подходит": "key not accepted",
@ -381,4 +380,22 @@ export const accessHub: Record<string, string> = {
"Полные права — на какой срок?": "Full rights — for how long?",
"Чтение — на какой срок?": "Read — for how long?",
"Подключения ещё нет — откройте запрос и подключите сервис": "No connection yet — open the request and connect the service",
// PEP-235: owner confirmations
"Разрешено один раз. Агент получит результат.": "Allowed once. The agent will get the result.",
"Отклонено. Действие не выполнено, агент узнает об этом.": "Refused. The action did not run; the agent will be told.",
"Ждут подтверждения": "Waiting for confirmation",
"До вашего ответа действие не выполняется. Без ответа запрос отменится сам.": "Nothing runs until you answer. Without an answer the request is cancelled by itself.",
"Разрешить один раз": "Allow once",
"Подтверждение не найдено": "Confirmation not found",
"Срок подтверждения истёк: агент спросит снова, если действие ещё нужно": "The confirmation has expired: the agent will ask again if the action is still needed",
"✅ Разрешить один раз": "✅ Allow once",
"❌ Отклонить": "❌ Refuse",
"{who} просит разрешить действие через подключение «{name}»": "{who} asks to allow an action through the connection «{name}»",
"Задача: {task}": "Task: {task}",
"Что: {what}": "What: {what}",
"Агент просит подтверждение": "An agent asks for confirmation",
"ждёт подтверждения владельца": "waiting for the owner's confirmation",
"владелец отклонил действие": "the owner refused the action",
"владелец не ответил вовремя, действие не выполнено": "the owner did not answer in time; the action did not run",
"выполнение прервал перезапуск, исход у сервиса неизвестен": "a restart cut the run; the outcome at the service is unknown",
};

View File

@ -140,7 +140,6 @@ export const accessHub: Record<string, string> = {
"Кабинет 2GIS Platform Manager → ключи доступа: создайте ключ для Places API.": "2GIS Platform Manager кабинеті → қолжетімділік кілттері: Places API үшін кілт жасаңыз.",
"чтение не разрешено": "оқуға рұқсат жоқ",
"запись не разрешена": "жазуға рұқсат жоқ",
"нужно подтверждение владельца, а подтверждения пока не поддерживаются": "иесінің растауы керек, ал растау әзірге қолдау көрсетілмейді",
"проверка ключа владельцем": "иесінің кілтті тексеруі",
"ключ работает": "кілт жұмыс істейді",
"ключ не подходит": "кілт сәйкес келмейді",
@ -381,4 +380,22 @@ export const accessHub: Record<string, string> = {
"Полные права — на какой срок?": "Толық құқық — қанша мерзімге?",
"Чтение — на какой срок?": "Оқу — қанша мерзімге?",
"Подключения ещё нет — откройте запрос и подключите сервис": "Қосылым әлі жоқ — сұрауды ашып, сервисті қосыңыз",
// PEP-235: owner confirmations
"Разрешено один раз. Агент получит результат.": "Бір рет рұқсат етілді. Агент нәтижені алады.",
"Отклонено. Действие не выполнено, агент узнает об этом.": "Қабылданбады. Әрекет орындалмады, агент бұл туралы біледі.",
"Ждут подтверждения": "Растауды күтуде",
"До вашего ответа действие не выполняется. Без ответа запрос отменится сам.": "Сіз жауап бермейінше әрекет орындалмайды. Жауап болмаса, сұрау өзі тоқтатылады.",
"Разрешить один раз": "Бір рет рұқсат ету",
"Подтверждение не найдено": "Растау табылмады",
"Срок подтверждения истёк: агент спросит снова, если действие ещё нужно": "Растау мерзімі өтті: әрекет әлі керек болса, агент қайта сұрайды",
"✅ Разрешить один раз": "✅ Бір рет рұқсат ету",
"❌ Отклонить": "❌ Қабылдамау",
"{who} просит разрешить действие через подключение «{name}»": "{who} «{name}» қосылымы арқылы әрекетке рұқсат сұрайды",
"Задача: {task}": "Тапсырма: {task}",
"Что: {what}": "Не: {what}",
"Агент просит подтверждение": "Агент растау сұрайды",
"ждёт подтверждения владельца": "иесінің растауын күтуде",
"владелец отклонил действие": "иесі әрекетті қабылдамады",
"владелец не ответил вовремя, действие не выполнено": "иесі уақытында жауап бермеді, әрекет орындалмады",
"выполнение прервал перезапуск, исход у сервиса неизвестен": "орындауды қайта іске қосу үзді, сервистегі нәтиже белгісіз",
};