From f9540704718713e6133ab67175c18b76c1ab8c8b Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 16:37:35 -0300 Subject: [PATCH 1/3] =?UTF-8?q?mensagens,=20e-mails=20e=20PDF=20chamam=20a?= =?UTF-8?q?=20m=C3=A1quina=20do=20backup=20de=20agente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- internal/agentcore/core.go | 2 +- internal/agentcore/localdir.go | 4 ++-- internal/httpapi/handlers_jobs.go | 2 +- internal/report/html.go | 6 +++--- internal/report/pdf.go | 2 +- internal/report/text.go | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/agentcore/core.go b/internal/agentcore/core.go index 09b38bd..d938aaa 100644 --- a/internal/agentcore/core.go +++ b/internal/agentcore/core.go @@ -104,7 +104,7 @@ func New(cfg Config, st *State, log *slog.Logger) *Core { if chosen, err = c.localDir(job.Subdir); err != nil { return Result{}, err } - h.log("info", "pasta do backup local no servidor: %s", job.Subdir) + h.log("info", "pasta do backup local: %s", job.Subdir) } if job.DB != nil { if chosen != "" { diff --git a/internal/agentcore/localdir.go b/internal/agentcore/localdir.go index 861b0da..62fa977 100644 --- a/internal/agentcore/localdir.go +++ b/internal/agentcore/localdir.go @@ -31,7 +31,7 @@ func CheckLocalDir(p string) (string, error) { } clean := path.Clean(p) if clean == "/" { - return "", errors.New("escolha uma pasta: o backup não pode ser gravado direto na raiz do servidor") + return "", errors.New("escolha uma pasta: o backup não pode ser gravado direto na raiz do agente") } for _, f := range forbiddenLocalDirs { if clean == f || strings.HasPrefix(clean, f+"/") { @@ -41,7 +41,7 @@ func CheckLocalDir(p string) (string, error) { return clean, nil } -var errNoWriteMount = errors.New("este agente não pode gravar no servidor: adicione o volume \"- /:/host-rw\" à stack do agente e recrie o contêiner") +var errNoWriteMount = errors.New("este agente não pode gravar fora das próprias pastas: adicione o volume \"- /:/host-rw\" à stack do agente e recrie o contêiner") // writeRoot devolve a raiz gravável do servidor, como o agente a enxerga. func (c *Core) writeRoot() (string, error) { diff --git a/internal/httpapi/handlers_jobs.go b/internal/httpapi/handlers_jobs.go index c44114c..9ac9125 100644 --- a/internal/httpapi/handlers_jobs.go +++ b/internal/httpapi/handlers_jobs.go @@ -281,7 +281,7 @@ func (s *Server) applyJobIn(ctx context.Context, j *store.Job, in jobIn) string } else { j.DestSubdir = strings.TrimRight(j.DestSubdir, "/") if !subdirRE.MatchString(j.DestSubdir) || strings.Contains(j.DestSubdir, "..") { - return "pasta de destino inválida: use um caminho completo do servidor ou um nome relativo (letras, números, ponto, hífen, sublinhado e /), sem .." + return "pasta de destino inválida: use um caminho completo do agente ou um nome relativo (letras, números, ponto, hífen, sublinhado e /), sem .." } } if in.Keep != nil { diff --git a/internal/report/html.go b/internal/report/html.go index 15fd932..c7240c0 100644 --- a/internal/report/html.go +++ b/internal/report/html.go @@ -166,7 +166,7 @@ func (e RunEvent) HTML() string { var sb strings.Builder sb.WriteString(``) sb.WriteString(kv(b, "Job", ""+esc(r.Job)+"")) - sb.WriteString(kv(b, "Servidor", esc(r.Agent))) + sb.WriteString(kv(b, "Agente", esc(r.Agent))) sb.WriteString(kv(b, "Estado", badge(b, r.Status))) sb.WriteString(kv(b, "Início", esc(fmtTime(r.StartedAt, loc)))) sb.WriteString(kv(b, "Duração", esc(fmtDur(r.StartedAt, r.FinishedAt)))) @@ -197,7 +197,7 @@ func (e AgentEvent) HTML() string { if loc == nil { loc = timeUTC } - body := fmt.Sprintf(`
%s%s%s

O servidor não dá sinal há mais de %d minutos. Se ele estiver desligado ou sem rede, os backups agendados não vão rodar.

`, - kv(b, "Servidor", ""+esc(e.Agent.Name)+""), kv(b, "Visto por último", esc(fmtTime(e.Agent.LastSeen, loc))), kv(b, "Versão do agente", esc(e.Agent.Version)), b.Muted, e.Minutes) + body := fmt.Sprintf(`%s%s%s

O agente não dá sinal há mais de %d minutos. Se a máquina dele estiver desligada ou sem rede, os backups agendados não vão rodar.

`, + kv(b, "Agente", ""+esc(e.Agent.Name)+""), kv(b, "Visto por último", esc(fmtTime(e.Agent.LastSeen, loc))), kv(b, "Versão do agente", esc(e.Agent.Version)), b.Muted, e.Minutes) return shell(b, e.Subject(), "Agente offline", b.Danger, body, len(b.LogoPNG) > 0) } diff --git a/internal/report/pdf.go b/internal/report/pdf.go index 34125f6..e037e95 100644 --- a/internal/report/pdf.go +++ b/internal/report/pdf.go @@ -339,7 +339,7 @@ func (dl Daily) PDF() ([]byte, error) { } ar = append(ar, []string{a.Name, st, a.Version}) } - d.table([]col{{"Servidor", 70, "L"}, {"Estado", 80, "L"}, {"Versão", 30, "L"}}, ar) + d.table([]col{{"Agente", 70, "L"}, {"Estado", 80, "L"}, {"Versão", 30, "L"}}, ar) if len(dl.Runs) > 0 { p.AddPage() diff --git a/internal/report/text.go b/internal/report/text.go index 8272752..03b2224 100644 --- a/internal/report/text.go +++ b/internal/report/text.go @@ -113,7 +113,7 @@ func (e RunEvent) Telegram() string { func (e RunEvent) Text() string { r, loc := e.Run, e.loc() - s := fmt.Sprintf("%s\n\nJob: %s\nServidor: %s\nEstado: %s\nInício: %s\nDuração: %s\n", e.Subject(), r.Job, r.Agent, StatusLabel(r.Status), fmtTime(r.StartedAt, loc), fmtDur(r.StartedAt, r.FinishedAt)) + s := fmt.Sprintf("%s\n\nJob: %s\nAgente: %s\nEstado: %s\nInício: %s\nDuração: %s\n", e.Subject(), r.Job, r.Agent, StatusLabel(r.Status), fmtTime(r.StartedAt, loc), fmtDur(r.StartedAt, r.FinishedAt)) if r.BytesOut > 0 { s += "Arquivo: " + FmtBytes(r.BytesOut) + "\n" } @@ -142,5 +142,5 @@ func (e AgentEvent) Text() string { if loc == nil { loc = timeUTC } - return fmt.Sprintf("%s\n\nO servidor %s não dá sinal há mais de %d minutos.\nVisto por último: %s\n\n%s - Versão %s\n", e.Subject(), e.Agent.Name, e.Minutes, fmtTime(e.Agent.LastSeen, loc), e.Name, e.Version) + return fmt.Sprintf("%s\n\nO agente %s não dá sinal há mais de %d minutos.\nVisto por último: %s\n\n%s - Versão %s\n", e.Subject(), e.Agent.Name, e.Minutes, fmtTime(e.Agent.LastSeen, loc), e.Name, e.Version) } From f82cc7fc25618125ef8268ec317d1e24610eb5b8 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 16:37:35 -0300 Subject: [PATCH 2/3] =?UTF-8?q?web:=20pastas,=20arquivos,=20atalhos=20e=20?= =?UTF-8?q?padr=C3=B5es=20identificados=20nas=20listas;=20agente=20n=C3=A3?= =?UTF-8?q?o=20=C3=A9=20chamado=20de=20servidor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- web/src/App.tsx | 4 +- web/src/LocalDir.tsx | 6 +-- web/src/Picker.tsx | 73 +++++++++++++++++++++++++++++--- web/src/pages/Agents.tsx | 6 +-- web/src/pages/Auth.tsx | 2 +- web/src/pages/Jobs.tsx | 20 ++++----- web/src/pages/NetDestination.tsx | 2 +- web/src/pages/Notifications.tsx | 2 +- 8 files changed, 89 insertions(+), 26 deletions(-) diff --git a/web/src/App.tsx b/web/src/App.tsx index 21ac5b8..cb9ce5b 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -30,7 +30,7 @@ export default function App() { const [theme, setTheme] = useState('coruja') const [phase, setPhase] = useState('loading') const [me, setMe] = useState(null) - const [version, setVersion] = useState('0.0.14') + const [version, setVersion] = useState('0.0.15') const route = useRoute() useFavicon(brand) @@ -169,7 +169,7 @@ function Dashboard({ name, canReport }: { name: string; canReport: boolean }) { {agents && active.length === 0 && ( Comece adicionando um agente. -

Vá em Agentes e gere um token de matrícula para o primeiro servidor.

+

Vá em Agentes e gere um token de matrícula para o primeiro agente.

)} diff --git a/web/src/LocalDir.tsx b/web/src/LocalDir.tsx index ad9471d..4b4b00f 100644 --- a/web/src/LocalDir.tsx +++ b/web/src/LocalDir.tsx @@ -1,4 +1,4 @@ -// Pasta do backup local: escolhida no disco do servidor do agente, com o espaço disponível. +// Pasta do backup local: escolhida no disco do agente, com o espaço disponível. import { useEffect, useRef, useState } from 'react' import { api, ApiError } from './api' import { FolderField, FolderList, SpaceBar } from './Picker' @@ -45,12 +45,12 @@ export function LocalDirField({ agentId, agentName, agentVersion, value, onChang const legacy = value && !chosen ? `pasta padrão do agente › ${value}` : '' return (
- onChange(v ? '/' + v.replace(/^\/+/, '') : '')} - picker={{ title: `Pasta do backup local em ${agentName}`, intro: 'Discos e pastas do servidor. O espaço mostrado é o do disco onde a pasta fica.', rootLabel: 'Servidor', load: (p) => load(p) }} /> + picker={{ title: `Pasta do backup local em ${agentName}`, intro: 'Discos e pastas do agente. O espaço mostrado é o do disco onde a pasta fica.', rootLabel: 'Raiz', load: (p) => load(p) }} /> {space?.total ? : null} {space && !space.exists &&

Esta pasta será criada no primeiro backup.

} {space?.blocked &&

{space.blocked}

} diff --git a/web/src/Picker.tsx b/web/src/Picker.tsx index abfdf43..f489c87 100644 --- a/web/src/Picker.tsx +++ b/web/src/Picker.tsx @@ -120,7 +120,7 @@ export function TreePicker({ title, intro, agentId, roots, initial, lockRoots, c

{intro}

{/* Node é chamado como função, e não como componente, para a árvore não se remontar a cada clique */} -
    {roots.map((r) =>
    • {Node({ path: r, label: r === '/' ? '/ (servidor inteiro)' : r, entry: { name: r, dir: true }, depth: 0 })}
  • )}
+
    {roots.map((r) =>
    • {Node({ path: r, label: r === '/' ? '/ (tudo)' : r, entry: { name: r, dir: true }, depth: 0 })}
  • )}
{chosen.length === 0 ? 'Nada marcado.' : `${chosen.length} item(ns) marcado(s).`} @@ -252,11 +252,72 @@ export function FolderField({ label, hint, value, autoText, disabledReason, rese ) } +/** O que um item da lista é no agente. "pattern" é um padrão de exclusão (*.tmp); "unknown", quando não deu para conferir. */ +export type Kind = 'dir' | 'file' | 'link' | 'pattern' | 'missing' | 'unknown' + +const isPattern = (p: string) => !p.startsWith('/') || /[*?]/.test(p) + +/** + * Descobre o que é cada caminho listando a pasta que o contém. Assim vale também para jobs já salvos e caminhos digitados. + * Enquanto consulta, o item fica sem tipo. + */ +function useKinds(agentId: number, items: string[]): Record { + const [kinds, setKinds] = useState>({}) + const key = items.join('\n') + useEffect(() => { + let live = true + const set = (p: string, k: Kind) => live && setKinds((c) => ({ ...c, [p]: k })) + setKinds({}) + const parents = new Map() + for (const p of key ? key.split('\n') : []) { + if (isPattern(p)) { set(p, 'pattern'); continue } + const clean = p.replace(/\/+$/, '') + if (!clean) { set(p, 'dir'); continue } + const cut = clean.lastIndexOf('/') + const parent = clean.slice(0, cut) || '/' + parents.set(parent, [...(parents.get(parent) ?? []), { path: p, name: clean.slice(cut + 1) }]) + } + parents.forEach((children, parent) => { + api<{ entries: Entry[]; truncated?: boolean }>('GET', `/api/agents/${agentId}/browse?area=host&path=${encodeURIComponent(parent)}`) + .then((r) => children.forEach((c) => { + const e = r.entries.find((x) => x.name === c.name) + set(c.path, e ? (e.link ? 'link' : e.dir ? 'dir' : 'file') : r.truncated ? 'unknown' : 'missing') + })) + .catch((x) => children.forEach((c) => set(c.path, /não existe|não é uma pasta/.test((x as ApiError).message) ? 'missing' : 'unknown'))) + }) + return () => { live = false } + }, [agentId, key]) + return kinds +} + +const KIND: Record = { + dir: { label: 'Pasta', title: 'Pasta: entra tudo o que há dentro dela', tag: 'border-accent/60 bg-accent/15 text-text' }, + file: { label: 'Arquivo', title: 'Arquivo: só ele', tag: 'border-border bg-bg text-muted' }, + link: { label: 'Atalho', title: 'Atalho: entra só o atalho, não o conteúdo para onde ele aponta', tag: 'border-border bg-bg text-muted' }, + pattern: { label: 'Padrão', title: 'Padrão: vale para tudo o que combinar com ele', tag: 'border-primary/40 bg-primary/10 text-text' }, + missing: { label: 'Não encontrado', title: 'Este caminho não existe no agente agora', tag: 'border-danger/40 bg-danger/10 text-danger' }, + unknown: { label: 'Não conferido', title: 'Não foi possível consultar o agente (offline, versão antiga ou sem permissão)', tag: 'border-dashed border-border text-muted' }, +} + +const LinkIcon = () => ( + +) +const PatternIcon = () => + +function KindIcon({ kind }: { kind?: Kind }) { + if (kind === 'dir') return + if (kind === 'file') return + if (kind === 'link') return + if (kind === 'pattern') return + return +} + /** Lista de itens escolhidos, com remover, o botão que abre a árvore e (recolhida) a digitação, para casos especiais. */ -export function PathList({ label, hint, items, empty, pickLabel, pickDisabled, typeLabel, placeholder, onPick, onChange }: { - label: string; hint: string; items: string[]; empty: string; pickLabel: string; pickDisabled?: string +export function PathList({ agentId, label, hint, items, empty, pickLabel, pickDisabled, typeLabel, placeholder, onPick, onChange }: { + agentId: number; label: string; hint: string; items: string[]; empty: string; pickLabel: string; pickDisabled?: string typeLabel: string; placeholder: string; onPick: () => void; onChange: (items: string[]) => void }) { + const kinds = useKinds(agentId, items) const [typing, setTyping] = useState(false) const [text, setText] = useState('') function add() { @@ -271,8 +332,10 @@ export function PathList({ label, hint, items, empty, pickLabel, pickDisabled, t {items.length === 0 ?

{empty}

: (
    {items.map((p) => ( -
  • - {p} +
  • + + {p}{kinds[p] === 'dir' && !p.endsWith('/') ? '/' : ''} + {kinds[p] && {KIND[kinds[p]].label}}
  • ))} diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx index 2008f63..ed61ce7 100644 --- a/web/src/pages/Agents.tsx +++ b/web/src/pages/Agents.tsx @@ -39,7 +39,7 @@ export default function Agents({ me }: { me: User }) {

    Agentes

    -

    Servidores que executam os backups. Cada um se conecta ao Server com IP:porta e um token de matrícula.

    +

    Cada agente executa os backups da máquina em que está instalado e se conecta ao Server com IP:porta e um token de matrícula.

    {canEdit && }
    @@ -140,7 +140,7 @@ function NewToken({ onCreated }: { onCreated: (c: { token: string; name: string; } return (
    - setName(e.target.value)} required /> + setName(e.target.value)} required /> setF({ ...f, setup_code: e.target.value })} required />} setF({ ...f, username: e.target.value })} required /> diff --git a/web/src/pages/Jobs.tsx b/web/src/pages/Jobs.tsx index d054087..ea21dae 100644 --- a/web/src/pages/Jobs.tsx +++ b/web/src/pages/Jobs.tsx @@ -110,7 +110,7 @@ function JobForm({ job, agents, clouds, onDone }: { job: Job | null; agents: Age if (f.kind === 'files' && f.paths.length === 0) { setErr('Selecione pelo menos uma pasta ou arquivo para salvar.'); return } // job novo (ou que trocou de agente): a pasta local é escolhida no painel; jobs antigos podem continuar na pasta padrão const mustChoose = !job || job.agent_id !== Number(f.agent_id) - if (mustChoose && agentHasDiskPicker(agentVersion) && noWriteAgent !== Number(f.agent_id) && !f.dest_subdir.startsWith('/')) { setErr('Escolha a pasta do backup local no servidor.'); return } + if (mustChoose && agentHasDiskPicker(agentVersion) && noWriteAgent !== Number(f.agent_id) && !f.dest_subdir.startsWith('/')) { setErr('Escolha a pasta do backup local no agente.'); return } setBusy(true) const body: Record = { name: f.name, agent_id: Number(f.agent_id), kind: f.kind, paths: f.paths, excludes: f.excludes, cron: f.cron, timezone: f.timezone, dest_subdir: f.dest_subdir, keep: Number(f.keep), enabled: f.enabled } if (f.cloud_account_id) Object.assign(body, { cloud_account_id: Number(f.cloud_account_id), cloud_folder: f.cloud_folder, cloud_keep: Number(f.cloud_keep), cloud_keep_days: Number(f.cloud_keep_days) }) @@ -124,7 +124,7 @@ function JobForm({ job, agents, clouds, onDone }: { job: Job | null; agents: Age
    setF({ ...f, name: e.target.value })} required /> - + @@ -137,10 +137,10 @@ function JobForm({ job, agents, clouds, onDone }: { job: Job | null; agents: Age {f.kind === 'files' ? (<> - setTree('paths')} onChange={(paths) => setF((v) => ({ ...v, paths }))} - hint="Os caminhos são os do servidor do agente. O agente precisa estar online para navegar." /> - + setTree('excludes')} onChange={(excludes) => setF((v) => ({ ...v, excludes }))} hint="Num padrão, * vale para qualquer coisa. Sem / vale para o nome em qualquer pasta (*.tmp); com / vale para o caminho (*/data/cache/*)." /> @@ -187,7 +187,7 @@ function JobForm({ job, agents, clouds, onDone }: { job: Job | null; agents: Age {f.cloud_account_id !== 0 && (<> - setF((v) => ({ ...v, cloud_folder }))} picker={{ title: `Pasta em ${dest?.name ?? 'destino'}`, rootLabel: dest?.name ?? 'Destino', intro: dest?.type === 'gdrive' ? 'Por segurança, o Google Drive só mostra ao Coruja Backup as pastas criadas por ele.' @@ -246,7 +246,7 @@ function DbSection({ db, setDb, agentId, job }: { db: DbState; setDb: (d: DbStat {Object.entries(ENGINE_LABEL).map(([k, v]) => )} - + upd({ host: e.target.value })} placeholder="10.0.0.5 ou db.exemplo.com" />
    +
    upd({ host: e.target.value })} placeholder="10.0.0.5 ou db.exemplo.com" />
    upd({ port: Number(e.target.value) })} />
)} @@ -285,14 +285,14 @@ function DbSection({ db, setDb, agentId, job }: { db: DbState; setDb: (d: DbStat