Имя: восстановление display_name после распознавания + гард пустого входа
Голый magnet без dn/контекста заставлял namer звать LLM на пустом входе, и модель галлюцинировала мусорное имя («Unknown»), которое писалось и в display_name, и в rename qBittorrent, а заодно ломало UI-фолбэк на распознанное название. Верное каноническое имя, вычисляемое позже при распознавании, никуда не переливалось. - naming: гард пустого входа в DeriveName (нет контекста и подсказки → "" без вызова LLM) + детерминированный форматтер FormatTitleYear. - qbt: операция RenameTorrent (переименование существующей раздачи). - store: SetDisplayName — обновление имени постфактум без гарда состояния. - worker: refreshDisplayNameLocked/RefreshDisplayName — перелив канонического имени (эффективный план) в display_name + best-effort rename раздачи по реальному t.Hash; авто-триггер при подтверждении матча (choose/manual add). - web-ui: кнопка «Обновить имя» на странице загрузки (htmx-своп заголовка, деградация без JS), видимая при наличии распознавания (вкл. done/orphaned). Спека: дельты ingest/review/web-ui влиты в openspec/specs; change refresh-display-name заархивирован. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -306,6 +306,47 @@ func (c *Client) Delete(ctx context.Context, hashes []string, deleteFiles bool)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenameTorrent задаёт отображаемое имя уже добавленной раздачи (в отличие от
|
||||
// параметра rename при Add, действующего только в момент добавления). hash —
|
||||
// ключ раздачи в qBittorrent (Torrent.Hash), а не сырой infohash загрузки:
|
||||
// вызывающий резолвит его листингом. Косметика: имя раздачи не влияет на файлы.
|
||||
func (c *Client) RenameTorrent(ctx context.Context, hash, name string) error {
|
||||
hash = strings.TrimSpace(hash)
|
||||
if hash == "" {
|
||||
return fmt.Errorf("qbittorrent rename: empty hash")
|
||||
}
|
||||
form := url.Values{"hash": {hash}, "name": {name}}
|
||||
body := form.Encode()
|
||||
|
||||
log := logctx.FromOr(ctx, c.log)
|
||||
call := logging.ExtCall{Service: logging.ServiceQBittorrent, Operation: "torrents/rename", Start: time.Now()}
|
||||
resp, err := c.do(ctx, func() (*http.Request, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
c.endpoint("/api/v2/torrents/rename"), strings.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Referer", c.base.String())
|
||||
return req, nil
|
||||
})
|
||||
if err != nil {
|
||||
call.Failure(log, err)
|
||||
return fmt.Errorf("qbittorrent rename: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
call.Status = resp.StatusCode
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<10))
|
||||
err := fmt.Errorf("qbittorrent rename: status %d body %q",
|
||||
resp.StatusCode, strings.TrimSpace(string(respBody)))
|
||||
call.Failure(log, err)
|
||||
return err
|
||||
}
|
||||
call.Success(log)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Torrents возвращает задачи указанной категории (пустая — все).
|
||||
func (c *Client) Torrents(ctx context.Context, category string) ([]Torrent, error) {
|
||||
log := logctx.FromOr(ctx, c.log)
|
||||
|
||||
@@ -139,6 +139,51 @@ func TestDeleteSendsHashesAndDeleteFiles(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameTorrentSendsHashAndName(t *testing.T) {
|
||||
var gotHash, gotName string
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/torrents/rename", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
gotHash = r.PostForm.Get("hash")
|
||||
gotName = r.PostForm.Get("name")
|
||||
_, _ = w.Write([]byte("Ok."))
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newClient(t, srv.URL)
|
||||
if err := c.RenameTorrent(context.Background(), "aaa", "Harold and the Purple Crayon (2024)"); err != nil {
|
||||
t.Fatalf("RenameTorrent: %v", err)
|
||||
}
|
||||
if gotHash != "aaa" {
|
||||
t.Errorf("hash = %q, want aaa", gotHash)
|
||||
}
|
||||
if gotName != "Harold and the Purple Crayon (2024)" {
|
||||
t.Errorf("name = %q", gotName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameTorrentEmptyHashIsError(t *testing.T) {
|
||||
c := newClient(t, "http://unused")
|
||||
if err := c.RenameTorrent(context.Background(), " ", "x"); err == nil {
|
||||
t.Fatal("RenameTorrent with empty hash must error before any request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameTorrentNon200IsError(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/torrents/rename", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newClient(t, srv.URL)
|
||||
if err := c.RenameTorrent(context.Background(), "aaa", "x"); err == nil {
|
||||
t.Fatal("RenameTorrent must error on non-200")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteNoHashesIsError(t *testing.T) {
|
||||
c := newClient(t, "http://unused")
|
||||
if err := c.Delete(context.Background(), []string{"", " "}, true); err == nil {
|
||||
|
||||
Reference in New Issue
Block a user