From d3c153f702993ccc5d12b991d86113e979a190d0 Mon Sep 17 00:00:00 2001 From: TAskMAster339 Date: Thu, 5 Nov 2026 23:48:42 +0300 Subject: [PATCH] =?UTF-8?q?=D0=90=D0=B4=D0=B0=D0=BF=D1=82=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20frontend=20=D0=BA=20=D0=B0?= =?UTF-8?q?=D1=81=D0=B8=D0=BD=D1=85=D1=80=D0=BE=D0=BD=D0=BD=D1=8B=D0=BC=20?= =?UTF-8?q?=D0=B2=D0=BB=D0=BE=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/frontend/src/App.tsx | 17 +++++-- src/frontend/src/AttachmentImage.tsx | 73 ++++++++++++++++++++-------- src/frontend/src/UploadStatus.tsx | 17 +++++++ src/frontend/src/api.ts | 13 +++-- src/frontend/src/styles.css | 20 ++++++++ src/frontend/src/useAttachment.ts | 41 ++++++++++++++++ 6 files changed, 152 insertions(+), 29 deletions(-) create mode 100644 src/frontend/src/UploadStatus.tsx create mode 100644 src/frontend/src/useAttachment.ts diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx index 59f545a..c7b36e9 100644 --- a/src/frontend/src/App.tsx +++ b/src/frontend/src/App.tsx @@ -3,6 +3,7 @@ import { api, ApiError, type Attachment, type Chat, type Session, type User } fr import AttachmentImage from "./AttachmentImage"; import { uploadDirect, type DirectProgress } from "./directUpload"; +import UploadStatus from "./UploadStatus"; import Pagination from "./Pagination"; import { useCursorPage } from "./useCursorPage"; @@ -122,7 +123,10 @@ function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) { ); } -type UploadDraft = { localId: string; file: File; mode: "proxy" | "direct"; direct: DirectProgress; status: "preparing" | "uploading" | "checking" | "ready" | "error"; attachment?: Attachment; error?: string }; +type UploadDraft = { localId: string; file: File; mode: "proxy" | "direct"; direct: DirectProgress; status: "preparing" | "uploading" | "checking" | "accepted" | "error"; attachment?: Attachment; error?: string }; +function canSendUpload(item: UploadDraft) { + return item.status === "accepted" && item.attachment && item.attachment.status !== "failed"; +} function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) { const [selectedChat, setSelectedChat] = useState(null); @@ -148,6 +152,9 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog if (cause instanceof ApiError && cause.status === 401) onLogout("Сессия истекла. Войдите снова."); else setError(errorText(cause)); }, [onLogout]); + const updateAttachment = useCallback((chat: string, local: string, attachment: Attachment) => { + setUploads(current => ({ ...current, [chat]: (current[chat] || []).map(item => item.localId === local ? { ...item, attachment } : item) })); + }, []); const fetchChats = useCallback((cursor: string | undefined, limit: number) => api.chats(token, cursor, limit), [token]); const chatId = selectedChat?.id || ""; const fetchMessages = useCallback((cursor: string | undefined, limit: number) => api.messages(token, chatId, cursor, limit), [token, chatId]); @@ -182,7 +189,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog ? await uploadDirect(token, targetChat, item.file, item.direct, signal, status => { if (!signal.aborted) update(item.localId, { status }); }) : await api.uploadAttachment(token, targetChat, item.file, signal); if (signal.aborted) break; - update(item.localId, { status: "ready", attachment }); + update(item.localId, { status: "accepted", attachment }); } catch (cause) { if (signal.aborted) break; update(item.localId, { status: "error", error: errorText(cause) }); @@ -210,7 +217,7 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog event.preventDefault(); const text = (drafts[chatId] || "").trim(); const selected = uploads[chatId] || []; - if (uploading || selected.some(item => item.status !== "ready") || (!text && selected.length === 0)) return; + if (uploading || selected.some(item => !canSendUpload(item)) || (!text && selected.length === 0)) return; const attachmentIds = selected.map(item => item.attachment!.id); const body = JSON.stringify({ text, attachment_ids: attachmentIds }); const previous = pendingMessages.current[chatId]; @@ -287,12 +294,12 @@ function Workspace({ token, user, onLogout }: { token: string; user: User; onLog - + } diff --git a/src/frontend/src/AttachmentImage.tsx b/src/frontend/src/AttachmentImage.tsx index 7c679c4..95d07a2 100644 --- a/src/frontend/src/AttachmentImage.tsx +++ b/src/frontend/src/AttachmentImage.tsx @@ -1,41 +1,72 @@ -import { useEffect, useState } from "react"; -import { api } from "./api"; +import { useEffect, useRef, useState } from "react"; +import { api, ApiError, type VariantName } from "./api"; +import { attachmentStatus, processingError, useAttachment } from "./useAttachment"; export default function AttachmentImage({ id, token, onError }: { id: string; token: string; onError: (error: unknown) => void; }) { const [source, setSource] = useState(""); - const [filename, setFilename] = useState("Изображение"); - const [failed, setFailed] = useState(false); + const [error, setError] = useState(""); + const [variant, setVariant] = useState("thumbnail"); const [attempt, setAttempt] = useState(0); + const [downloading, setDownloading] = useState(false); + const downloadController = useRef(null); + useEffect(() => () => downloadController.current?.abort(), []); + const { attachment, error: statusError, busy, retry } = useAttachment(token, id, onError); useEffect(() => { + if (attachment?.status !== "ready") { setSource(""); return; } const controller = new AbortController(); let objectURL = ""; - setSource(""); setFailed(false); + setSource(""); setError(""); async function load() { try { - let attachment = await api.attachment(token, id, controller.signal); - while (attachment.status === "queued" || attachment.status === "processing") { - await new Promise(resolve => setTimeout(resolve, 1000)); - if (controller.signal.aborted) return; - attachment = await api.attachment(token,id,controller.signal); - } - if (attachment.status === "failed") throw new Error("Обработка изображения завершилась ошибкой"); - const content = await api.attachmentContent(token, id, controller.signal); + const content = await api.attachmentContent(token, id, controller.signal, variant); if (controller.signal.aborted) return; objectURL = URL.createObjectURL(content); - setFilename(attachment.filename); setSource(objectURL); - } catch (error) { - if (!controller.signal.aborted) { setFailed(true); onError(error); } + setSource(objectURL); + } catch (cause) { + if (!controller.signal.aborted) { + setError(cause instanceof Error ? cause.message : "Не удалось загрузить изображение."); + if (cause instanceof ApiError && cause.status === 401) onError(cause); + } } } void load(); return () => { controller.abort(); if (objectURL) URL.revokeObjectURL(objectURL); }; - }, [id, token, attempt, onError]); + }, [id, token, attachment, variant, attempt, onError]); + + async function downloadOriginal() { + const controller = new AbortController(); + downloadController.current = controller; + setDownloading(true); setError(""); + try { + const content = await api.attachmentContent(token, id, controller.signal); + if (controller.signal.aborted) return; + const url = URL.createObjectURL(content); + const link = document.createElement("a"); + link.href = url; link.download = attachment?.filename || "image"; + document.body.append(link); link.click(); link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } catch (cause) { + if (controller.signal.aborted) return; + setError(cause instanceof Error ? cause.message : "Не удалось скачать оригинал."); + if (cause instanceof ApiError && cause.status === 401) onError(cause); + } finally { if (!controller.signal.aborted) setDownloading(false); } + } + return
- {source ? {filename} - : failed ? - : Загрузка изображения…} - {source &&
{filename} · нажмите, чтобы скачать
} + {attachment?.status === "ready" ? <> + {source ? {attachment.filename} : !error && Загрузка изображения…} +
{attachment.filename}
+
+ + +
+ : {attachment ? attachment.status === "failed" ? processingError(attachment.error_code) : attachmentStatus[attachment.status] : "Проверка состояния изображения…"}} + {attachment?.status === "failed" && !statusError && } + {statusError &&

{statusError}

} + {error &&

{error}

}
; } diff --git a/src/frontend/src/UploadStatus.tsx b/src/frontend/src/UploadStatus.tsx new file mode 100644 index 0000000..40e7696 --- /dev/null +++ b/src/frontend/src/UploadStatus.tsx @@ -0,0 +1,17 @@ +import { useEffect } from "react"; +import type { Attachment } from "./api"; +import { attachmentStatus, processingError, useAttachment } from "./useAttachment"; + +export default function UploadStatus({ token, id, chatId, localId, onUpdate, onError }: { + token: string; id: string; chatId: string; localId: string; + onUpdate: (chat: string, local: string, attachment: Attachment) => void; + onError: (cause: unknown) => void; +}) { + const { attachment, error, busy, retry } = useAttachment(token, id, onError); + useEffect(() => { if (attachment) onUpdate(chatId, localId, attachment); }, [attachment, chatId, localId, onUpdate]); + return + {attachment ? attachment.status === "failed" ? processingError(attachment.error_code) : attachmentStatus[attachment.status] : "Файл принят. Проверка состояния…"} + {attachment?.status === "failed" && !error && } + {error && <> · {error} } + ; +} diff --git a/src/frontend/src/api.ts b/src/frontend/src/api.ts index 4d45719..1a7f9f6 100644 --- a/src/frontend/src/api.ts +++ b/src/frontend/src/api.ts @@ -12,10 +12,16 @@ export interface Chat { created_at: string; } +export type VariantName = "thumbnail" | "crop" | "optimized"; +export interface AttachmentVariant { + name: VariantName; content_type: "image/jpeg" | "image/webp"; + width: number; height: number; size_bytes: number; sha256: string; +} + export interface Attachment { id: string; chat_id: string; owner_id: string; filename: string; content_type: "image/png" | "image/jpeg"; size_bytes: number; sha256: string; - status: "queued" | "processing" | "ready" | "failed"; variants: unknown[]; error_code: string | null; created_at: string; updated_at: string; + status: "queued" | "processing" | "ready" | "failed"; variants: AttachmentVariant[]; error_code: string | null; created_at: string; updated_at: string; } export interface DirectUpload { @@ -150,8 +156,9 @@ export const api = { }), attachment: (token: string, id: string, signal?: AbortSignal) => request(`/api/v1/attachments/${encodeURIComponent(id)}`, { headers: bearer(token), signal }), - attachmentContent: async (token: string, id: string, signal?: AbortSignal) => { - const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content`, { headers: bearer(token), signal }); + attachmentContent: async (token: string, id: string, signal?: AbortSignal, variant?: VariantName) => { + const query = variant ? `?${new URLSearchParams({ variant })}` : ""; + const response = await fetch(`/api/v1/attachments/${encodeURIComponent(id)}/content${query}`, { headers: bearer(token), signal }); if (!response.ok) { const data = await response.json().catch(() => null); throw new ApiError(data?.error?.message || `Ошибка HTTP ${response.status}`, response.status, response.headers.get("X-Request-Id") || undefined); diff --git a/src/frontend/src/styles.css b/src/frontend/src/styles.css index 4f08608..b1d1063 100644 --- a/src/frontend/src/styles.css +++ b/src/frontend/src/styles.css @@ -842,3 +842,23 @@ textarea { color: inherit; font: inherit; } + +.attachment-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 8px; +} + +.attachment-actions select { + max-width: 100%; + font: inherit; +} + +.attachment-actions label { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} diff --git a/src/frontend/src/useAttachment.ts b/src/frontend/src/useAttachment.ts new file mode 100644 index 0000000..9af44d6 --- /dev/null +++ b/src/frontend/src/useAttachment.ts @@ -0,0 +1,41 @@ +import { useEffect, useState } from "react"; +import { api, ApiError, type Attachment } from "./api"; + +export const attachmentStatus: Record = { + queued: "В очереди на обработку", processing: "Обработка изображения…", + ready: "Изображение готово", failed: "Не удалось обработать изображение", +}; + +export function processingError(code: string | null) { + if (code === "invalid_image") return "Файл повреждён или превышает лимит обработки (8 млн пикселей)."; + if (code === "retry_exhausted") return "Обработка не завершилась после нескольких попыток. Обратитесь к администратору."; + return "Не удалось обработать изображение. Обратитесь к администратору."; +} + +export function useAttachment(token: string, id: string, onError: (error: unknown) => void) { + const [attachment, setAttachment] = useState(); + const [error, setError] = useState(""); + const [attempt, setAttempt] = useState(0); + const [busy, setBusy] = useState(true); + useEffect(() => { + const controller = new AbortController(); + let timer: ReturnType; + setAttachment(undefined); setError(""); setBusy(true); + async function poll() { + try { + const value = await api.attachment(token, id, controller.signal); + if (controller.signal.aborted) return; + setAttachment(value); setBusy(false); + if (value.status === "queued" || value.status === "processing") timer = setTimeout(poll, 1000); + } catch (cause) { + if (controller.signal.aborted) return; + setBusy(false); + setError(cause instanceof Error ? cause.message : "Не удалось проверить состояние файла."); + if (cause instanceof ApiError && cause.status === 401) onError(cause); + } + } + void poll(); + return () => { controller.abort(); clearTimeout(timer); }; + }, [token, id, attempt, onError]); + return { attachment, error, busy, retry: () => setAttempt(value => value + 1) }; +}