Files
Agent-Workbench/src/client/InputAttachments.tsx
T

38 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect,useRef,useState } from 'react';
import { ImagePlus,Download,X,LoaderCircle } from 'lucide-react';
import { api,downloadBlob,inputImageBlob } from './api';
import { Modal } from './components';
import type { InputAttachment,Session } from './types';
import './input-attachments.css';
export function InputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(error:unknown)=>void}){
const [url,setUrl]=useState(''),[open,setOpen]=useState(false),[error,setError]=useState('');
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void inputImageBlob(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive)setError(cause.message);});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
return <div className="input-receipt"><button type="button" className="input-thumbnail" aria-label={'查看截图 '+image.name} disabled={!url} onClick={()=>setOpen(true)}>{url?<img src={url} alt={image.name} width={72} height={48}/>:<span>{error?'读取失败':'核对中'}</span>}</button><div><strong>{image.name}</strong><span>发送副本 {image.sentWidth} × {image.sentHeight} · {Math.ceil(image.sentBytes/1024)} KB</span><small>{error|| (url?'SHA-256 已核对':'核对原字节…')}</small></div>
{open&&<Modal title="任务截图" description={image.name+' · 原图 '+image.width+' × '+image.height} onClose={()=>setOpen(false)} wide><img className="input-preview" src={url} alt={image.name}/><p className="input-sha">原图 SHA-256 {image.sha256}<br/>发送副本 SHA-256 {image.sentSha256}</p><p>发送副本已去除元数据并归正方向,实际尺寸 {image.sentWidth} × {image.sentHeight},{Math.ceil(image.sentBytes/1024)} KB;原图完整保留。</p><div className="modal-actions"><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image,true).then(blob=>downloadBlob(blob,image.name)).catch(onError)}><Download size={14}/>下载原图</button><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image).then(blob=>downloadBlob(blob,'sent-'+image.id+'.png')).catch(onError)}>下载发送副本</button></div></Modal>}
</div>;
}
export function AttachmentComposer({session,selectedIds,onSelection,onEnsureSession,onSession,onError,disabled,routeName,onModels}:{session:Session|null;selectedIds:string[];onSelection:(id:string,ids:string[])=>void;onEnsureSession:()=>Promise<Session|null>;onSession:(value:Session)=>void;onError:(error:unknown)=>void;disabled:boolean;routeName:string;onModels:()=>void}){
const input=useRef<HTMLInputElement>(null),[busy,setBusy]=useState(false);
const drafts=session?.inputAttachments?.filter(value=>value.status==='draft')??[];
async function upload(files:File[]){
setBusy(true);
try{
const target=session??await onEnsureSession();if(!target)return;
const ids=target.id===session?.id?[...selectedIds]:[];
for(const file of files){
if(!['image/png','image/jpeg'].includes(file.type))throw new Error('请选择静态PNG或JPEG截图。');
const bytes=new Uint8Array(await file.arrayBuffer());let binary='';for(let p=0;p<bytes.length;p+=8192)binary+=String.fromCharCode(...bytes.subarray(p,p+8192));
const row=await api<InputAttachment>('/sessions/'+target.id+'/input-attachments',{name:file.name,mediaType:file.type,base64:btoa(binary)});
ids.push(row.id);onSession(await api<Session>('/sessions/'+target.id));onSelection(target.id,[...ids]);
}
}catch(error){onError(error);}finally{setBusy(false);if(input.current)input.current.value='';}
}
async function remove(id:string){if(!session)return;setBusy(true);try{await api('/sessions/'+session.id+'/input-attachments/'+id,{},'DELETE');onSession(await api<Session>('/sessions/'+session.id));if(selectedIds.includes(id))onSelection(session.id,selectedIds.filter(value=>value!==id));}catch(error){onError(error);}finally{setBusy(false);}}
return <div className="input-composer"><div className="input-composer-tools"><button type="button" className="input-add" disabled={disabled||busy} onClick={()=>input.current?.click()}>{busy?<LoaderCircle size={15} className="spin"/>:<ImagePlus size={15}/>}添加截图</button><span>可多选 · PNG/JPEG · 保留原图</span><input ref={input} type="file" multiple accept="image/png,image/jpeg" aria-label="选择工程截图" hidden onChange={event=>{const files=Array.from(event.target.files??[]);if(files.length)void upload(files);}}/></div>
{!!drafts.length&&<div className="input-drafts">{drafts.map(image=><div className={'input-draft '+(selectedIds.includes(image.id)?'selected':'')} key={image.id}><label><input type="checkbox" checked={selectedIds.includes(image.id)} disabled={disabled||busy} onChange={event=>onSelection(session!.id,event.target.checked?[...selectedIds,image.id]:selectedIds.filter(id=>id!==image.id))}/><span>随任务发送</span></label><InputImage sessionId={session!.id} image={image} onError={onError}/><button type="button" className="input-remove" aria-label={'移除截图 '+image.name} disabled={disabled||busy} onClick={()=>void remove(image.id)}><X size={15}/></button></div>)}</div>}
{!!selectedIds.length&&<p className="input-route">将随文字发送至 <strong>{routeName}</strong>,池仅使用声明或检测支持视觉的成员。<button type="button" onClick={onModels}>核对模型能力</button><span>开放模式不缩小图片;图片预留单独估算,实际用量以服务返回为准。</span></p>}
</div>;
}