From 1057be6d2b1c0ed7fb6d00a8c5dc2ef4ce92d4a4 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Sun, 8 Nov 2026 06:35:53 +0900 Subject: [PATCH] feat(feeds): expose retained operation history and read-only rechecks --- docs/design/ja/feeds.md | 38 +++- internal/server/feeds_actions.go | 3 + internal/server/feeds_history.go | 56 ++++++ internal/server/feeds_history_test.go | 260 ++++++++++++++++++++++++++ internal/server/feeds_test.go | 24 ++- internal/server/testdata/feeds.js | 14 +- internal/store/feeds.go | 11 ++ internal/store/feeds_actions.go | 2 +- internal/store/feeds_history.go | 109 +++++++++++ static/css/feeds.css | 3 + static/js/feeds.js | 33 +++- templates/pages/feeds.gohtml | 4 +- 12 files changed, 547 insertions(+), 10 deletions(-) create mode 100644 internal/server/feeds_history.go create mode 100644 internal/server/feeds_history_test.go create mode 100644 internal/store/feeds_history.go diff --git a/docs/design/ja/feeds.md b/docs/design/ja/feeds.md index 49254fa..5d08850 100644 --- a/docs/design/ja/feeds.md +++ b/docs/design/ja/feeds.md @@ -77,6 +77,8 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用 | `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 | | `POST remote-state` | FreshRSSの一記事・一項目の変更を予約。request_id、source、id、field、desired、source_versionを指定 | | `GET action?source=…&id=…` | 本人の記事の最新操作記録。外部通信なし | +| `GET actions` | 本人の操作履歴。status/sourceで絞り込み、50件単位のkeysetページング | +| `GET action/export?request_id=…` | 本人の操作記録1件をJSON attachmentで保存。資格情報・本文・worker claimは含めない | | `POST action/check` | request_idで結果不明操作の読取専用再確認を予約 | | `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 | | `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード | @@ -174,6 +176,39 @@ readbackは観測結果であり、exactly-onceやリモートCASの保証とは 背景タブでは停止します。記事の既読・star表示は遠隔の状態を確認するまで切り替えません。 再確認で希望値と異なる場合はconflictを表示し、新しい変更は利用者が明示的に操作します。 +### 操作履歴の一覧と保全 + +ツールバーの時計アイコンから、リーダー内に操作履歴を開きます。モーダルは増やしません。 +日時、記事・購読元、変更対象と希望値、状態をまとめ、記事がcache内なら本文へ戻れます。 +スマホ幅では日時・件名・状態を縦にまとめ、再確認・保存のアイコンをタッチできる大きさにします。 + +既定の「未解決」はconfirmed/cancelled以外を表示し、処理中、結果不明、すべて、確認済み、 +未送信、不一致、中止で絞り込めます。一覧はローカルDBだけを読み、外部通信や自動再試行を行いません。 +履歴の更新は再読込アイコンと絞り込み操作で行い、記事画面の2秒pollは履歴画面では停止します。 +`GET actions`のstatusは`unresolved`(省略時も同じ)、`pending`、`unknown`、`all`、 +`confirmed`、`failed`、`conflict`、`cancelled`です。sourceは削除済みUUIDも指定できます。 +続きは末尾のcreated_msとrequest_idを`before`/`key`として渡します。同時刻の操作も重複・欠落なく辿ります。 +1回50件+続き判定の1件を読み、所有者の10,000件上限でソート量を制限します。 + +sourceや記事へのinner joinは使わず、削除済み購読元やcache窓から外れた記事の記録も残します。 +記事名・購読元名は現在の取得済み情報であり、操作時点の監査snapshotではありません。 +取得できない場合は元のsource UUID/記事IDと「削除済み」「キャッシュ外」を表示します。 +結果不明の記録は、同じDomain・本人の有効なFreshRSS sourceが残り、claim期限を過ぎた場合だけ +読取専用再確認を予約できます。書戻しOFFでも再確認でき、readonlyアカウントは閲覧・保存のみです。 +削除済みsourceは自動再接続しません。本人の記録に残るsource UUID、および全体の未解決操作に +残るsource UUIDの新規登録を拒否し、別接続先への誤った結び付けを防ぎます。 + +各行からJSON形式(`pageswiki.feed-action`、version 1)の記録を書き出せます。 +Domain/本人/request ID、操作内容、状態、日時、現在の表示用メタデータを含み、 +外部URL・資格情報・本文・内部claimは出力しません。ただし元の記事ID自体がURLの場合はそのIDを保持します。 +一覧・保存ともDomain・本人で制限し、private/no-storeで返します。schemaはv5のままです。 + +保存操作はDBからの削除を意味しません。receiptを削除すると同じrequest_idの再送を防げなくなるため、 +自動削除・一括削除は未実装です。後段の整理機能では、保全manifest・hash・対象件数を照合した上で、 +成功/中止/失敗等の終端記録だけをarchiveへ移し、重複防止に必要なrequest_idと入力識別子を +tombstoneとして保持します。unknownや実行中の記録は移動・削除対象にしません。 +tombstoneの保持期間・容量上限・旧クライアントからの再送時応答を決めるまで、現在の10,000件上限を維持します。 + 外部APIはlogin、記事参照、変更token、edit-tag、記事再参照の順です。記事の個別参照は `POST stream/items/contents`(読取操作)、変更は`POST edit-tag`に`i`・`T`・`a`または`r`一項目を送ります。 URLや本文、資格情報を操作記録・ログへ保存しません。[FreshRSS API実装](https://github.com/FreshRSS/FreshRSS/blob/edge/p/api/greader.php)。 @@ -241,7 +276,8 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。 - [x] RSS-1:read-only FreshRSS connectorと合成fixture。実接続の受入は別。 - [x] RSS-2:安全な共通一覧、出典付きWiki保存、任意のタスク化、ダッシュボード。 - [x] RSS-3:opt-inの既読/star書戻し、操作receipt、背景処理、readback、結果不明の再確認、失効・競合・排他の合成試験。 -- [ ] RSS-3b:未解決操作の総覧、cache窓から落ちた記事や削除sourceの操作記録確認、保全付きreceiptの整理。既存のGET action/action/checkは記事IDで利用できる。 +- [x] RSS-3b1:未解決操作の総覧、cache窓外・削除sourceの記録、再送しない再確認、個別JSON保存。50件ページング、本人分離、readonly、1440px/390pxの合成試験。 +- [ ] RSS-3b2:保全manifestの照合、終端receiptのarchive、重複防止tombstoneと保持期間・容量上限。未知結果の記録を捨てない。 - [x] RSS-4a:内蔵簡易reader、購読設定、既読・star、背景取得。 - [x] RSS-4b:OPML export/importのpreview、選択追加、重複確認、原子的な保存と再送防止。置換・状態移行は範囲外。 - [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。 diff --git a/internal/server/feeds_actions.go b/internal/server/feeds_actions.go index 414ca3d..0d1b4c9 100644 --- a/internal/server/feeds_actions.go +++ b/internal/server/feeds_actions.go @@ -132,6 +132,9 @@ func (s *Server) syncFeedActions(ctx context.Context, client *http.Client) error } func (s *Server) handleFeedAction(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool { + if s.handleFeedHistory(w, r, domain, actor, key) { + return true + } switch { case key == "action" && r.Method == "GET": a, e := s.store.FeedAction(r.Context(), domain, actor, r.URL.Query().Get("source"), r.URL.Query().Get("id")) diff --git a/internal/server/feeds_history.go b/internal/server/feeds_history.go new file mode 100644 index 0000000..1f09a44 --- /dev/null +++ b/internal/server/feeds_history.go @@ -0,0 +1,56 @@ +package server + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + "github.com/google/uuid" + "pageswiki/internal/store" +) + +func writeFeedHistoryJSON(w http.ResponseWriter, value any) { + w.Header().Set("Cache-Control", "private, no-store") + w.Header().Set("Content-Type", "application/json; charset=utf-8") + _ = json.NewEncoder(w).Encode(value) +} + +func (s *Server) handleFeedHistory(w http.ResponseWriter, r *http.Request, domain, actor, key string) bool { + if r.Method != "GET" || (key != "actions" && key != "action/export") { + return false + } + if key == "action/export" { + a, e := s.store.FeedActionRecord(r.Context(), domain, actor, r.URL.Query().Get("request_id")) + if e != nil { + taskError(w, e) + return true + } + id, _ := uuid.Parse(a.RequestID) + w.Header().Set("Content-Disposition", `attachment; filename="pageswiki-feed-action-`+id.String()+`.json"`) + w.Header().Set("X-Content-Type-Options", "nosniff") + writeFeedHistoryJSON(w, map[string]any{"format": "pageswiki.feed-action", "version": 1, "exported_ms": time.Now().UnixMilli(), "domain_uuid": domain, "owner_uuid": actor, "action": a}) + return true + } + q := r.URL.Query() + query := store.FeedActionQuery{Source: q.Get("source"), Status: q.Get("status"), Before: -1, Key: q.Get("key")} + if q.Has("before") { + var e error + query.Before, e = strconv.ParseInt(q.Get("before"), 10, 64) + if e != nil || query.Before < 0 { + taskError(w, store.ErrTaskInvalid) + return true + } + } + items, e := s.store.FeedActionHistory(r.Context(), domain, actor, query) + if e != nil { + taskError(w, e) + return true + } + more := len(items) > 50 + if more { + items = items[:50] + } + writeFeedHistoryJSON(w, map[string]any{"actions": items, "more": more}) + return true +} diff --git a/internal/server/feeds_history_test.go b/internal/server/feeds_history_test.go new file mode 100644 index 0000000..23acd96 --- /dev/null +++ b/internal/server/feeds_history_test.go @@ -0,0 +1,260 @@ +package server + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "pageswiki/internal/store" +) + +func feedHistoryResponse(t *testing.T, s *Server, token, query string) ([]store.FeedActionRecord, bool) { + t.Helper() + w := feedRequestTest(s, token, "GET", "actions"+query, nil) + if w.Code != 200 { + t.Fatal(w.Code, w.Body) + } + if w.Header().Get("Cache-Control") != "private, no-store" { + t.Fatal("private response cache policy") + } + var data struct { + Actions []store.FeedActionRecord `json:"actions"` + More bool `json:"more"` + } + if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil { + t.Fatal(e) + } + return data.Actions, data.More +} + +func TestFeedHistoryOrphansExportAndRecheck(t *testing.T) { + s, token, domain, actor, source := feedActionFixture(t) + ctx := context.Background() + a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source)) + if e != nil { + t.Fatal(e) + } + queued, _ := feedHistoryResponse(t, s, token, "?status=pending") + if len(queued) != 1 || queued[0].Status != "queued" || queued[0].CanCheck { + t.Fatal("queued history", queued) + } + fake := &feedRemoteFake{timeout: true} + if e = s.syncFeedActions(ctx, fake.client(t)); e != nil { + t.Fatal(e) + } + list, _ := feedHistoryResponse(t, s, token, "") + if len(list) != 1 || list[0].Status != "unknown" || list[0].CanCheck || list[0].CheckAfterMS <= time.Now().UnixMilli() || !list[0].ItemPresent || !list[0].SourcePresent { + t.Fatal("unknown cooldown", list) + } + if _, e = s.store.DB.Exec(`DELETE FROM feed_items WHERE source_uuid=?`, source.UUID); e != nil { + t.Fatal(e) + } + if _, e = s.store.DB.Exec(`UPDATE feed_actions SET until_ms=0 WHERE request_id=?`, a.RequestID); e != nil { + t.Fatal(e) + } + // Read-only connector opt-out does not disable read-only result checks. + source.Credential, source.WriteEnabled = "", false + if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil { + t.Fatal(e) + } + list, _ = feedHistoryResponse(t, s, token, "?status=unknown") + if len(list) != 1 || list[0].ItemPresent || !list[0].CanCheck || list[0].ItemTitle != "" || list[0].SourceTitle != "Remote" { + t.Fatal("evicted item lost", list) + } + w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil) + if w.Code != 200 || !strings.Contains(w.Header().Get("Content-Disposition"), a.RequestID+".json") || w.Header().Get("X-Content-Type-Options") != "nosniff" { + t.Fatal("export", w.Code, w.Header()) + } + var exported struct { + Format string `json:"format"` + Action store.FeedActionRecord `json:"action"` + } + if e = json.Unmarshal(w.Body.Bytes(), &exported); e != nil || exported.Format != "pageswiki.feed-action" || exported.Action.RequestID != a.RequestID || exported.Action.Status != "unknown" { + t.Fatal("export data", exported, e) + } + for _, secret := range []string{"credential", "secret", source.URL, `"claim"`, `"until_ms"`} { + if strings.Contains(w.Body.String(), secret) { + t.Fatal("export leaked internal credentials or worker metadata", secret) + } + } + if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 202 { + t.Fatal(w.Code, w.Body) + } + if e = s.syncFeedActions(ctx, fake.client(t)); e != nil || fake.edits != 1 { + t.Fatal("recheck sent a second mutation", fake.edits, e) + } + list, _ = feedHistoryResponse(t, s, token, "") + if len(list) != 0 { + t.Fatal("confirmed action unresolved", list) + } + list, _ = feedHistoryResponse(t, s, token, "?status=confirmed") + if len(list) != 1 || list[0].Status != "confirmed" || list[0].ItemPresent { + t.Fatal("evicted receipt missing", list) + } + if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown' WHERE request_id=?`, a.RequestID); e != nil { + t.Fatal(e) + } + if _, e = s.store.DB.Exec(`DELETE FROM feed_sources WHERE uuid=?`, source.UUID); e != nil { + t.Fatal(e) + } + list, _ = feedHistoryResponse(t, s, token, "?source="+source.UUID) + if len(list) != 1 || list[0].SourcePresent || list[0].ItemPresent || list[0].CanCheck || list[0].Error != "source_deleted" { + t.Fatal("deleted source receipt lost", list) + } + if w = feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 412 { + t.Fatal("deleted source recheck accepted", w.Code) + } + if w = feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 { + t.Fatal("deleted source export", w.Code) + } + source.Version, source.Credential = 0, "" + source.URL = "https://different.example.org/api/greader.php" + if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) { + t.Fatal("rebound orphan receipt", e) + } + other, e := s.store.CreatePasswordAccount(domain, "historyreuse", "long test password", "Other", "") + if e != nil { + t.Fatal(e) + } + if _, e = s.store.SaveFeedSource(ctx, domain, other.UUID, source); !errors.Is(e, store.ErrTaskConflict) { + t.Fatal("rebound unresolved receipt across owners", e) + } + if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='confirmed' WHERE request_id=?`, a.RequestID); e != nil { + t.Fatal(e) + } + if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); !errors.Is(e, store.ErrTaskConflict) { + t.Fatal("rebound terminal receipt", e) + } +} + +func TestFeedHistoryPaginationValidationAndIsolation(t *testing.T) { + s, token, domain, actor, source := feedActionFixture(t) + ctx := context.Background() + // Same millisecond, stable unique tie-breaker; well above a page boundary. + for i := 0; i < 107; i++ { + if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'confirmed',1234)`, domain, actor, uuid.NewString(), source.UUID, fmt.Sprint(i)); e != nil { + t.Fatal(e) + } + } + query, seen := "?status=all", map[string]bool{} + for { + list, more := feedHistoryResponse(t, s, token, query) + if len(list) > 50 { + t.Fatal("unbounded list") + } + for _, a := range list { + if seen[a.RequestID] { + t.Fatal("duplicate cursor record") + } + seen[a.RequestID] = true + } + if !more { + break + } + last := list[len(list)-1] + query = fmt.Sprintf("?status=all&before=%d&key=%s", last.CreatedMS, last.RequestID) + } + if len(seen) != 107 { + t.Fatal("cursor omissions", len(seen)) + } + for _, query := range []string{"?status=bogus", "?source=bad", "?before=bad", "?before=-1", "?before=1", "?key=" + uuid.NewString(), "?before=1&key=bad"} { + if w := feedRequestTest(s, token, "GET", "actions"+query, nil); w.Code != 422 { + t.Fatal("invalid query", query, w.Code) + } + } + other, e := s.store.CreatePasswordAccount(domain, "historyother", "long test password", "Other", "") + if e != nil { + t.Fatal(e) + } + otherToken, e := s.store.CreateAuthSession(domain, other.UUID) + if e != nil { + t.Fatal(e) + } + otherList, _ := feedHistoryResponse(t, s, otherToken, "?status=all&source="+source.UUID) + if len(otherList) != 0 { + t.Fatal("other owner's HTTP history leaked") + } + list, e := s.store.FeedActionHistory(ctx, domain, other.UUID, store.FeedActionQuery{Source: source.UUID, Status: "all", Before: -1}) + if e != nil || len(list) != 0 { + t.Fatal("other owner's actions leaked", list, e) + } + for request := range seen { + if w := feedRequestTest(s, otherToken, "GET", "action/export?request_id="+request, nil); w.Code != 404 { + t.Fatal("other owner's HTTP export", w.Code) + } + if _, e = s.store.FeedActionRecord(ctx, domain, other.UUID, request); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("other owner's receipt leaked", e) + } + break + } + if _, e = s.store.FeedActionHistory(ctx, uuid.NewString(), actor, store.FeedActionQuery{Status: "all", Before: -1}); !errors.Is(e, store.ErrAccessDenied) { + t.Fatal("other domain", e) + } + for _, key := range []string{"actions", "action/export?request_id=" + uuid.NewString()} { + if w := feedRequestTest(s, "", "GET", key, nil); w.Code != 401 { + t.Fatal("anonymous access", w.Code) + } + } + if w := feedRequestTest(s, token, "GET", "action/export?request_id=invalid", nil); w.Code != 422 { + t.Fatal("invalid receipt identifier", w.Code) + } + if e = s.setSystemExtensionEnabled(domain, "organizer.feeds", false); e != nil { + t.Fatal(e) + } + if w := feedRequestTest(s, token, "GET", "actions", nil); w.Code != 404 { + t.Fatal("extension disabled", w.Code) + } + if _, e = s.store.FeedActionRecord(ctx, domain, actor, uuid.NewString()); !errors.Is(e, store.ErrAccessDenied) { + t.Fatal("store disabled", e) + } +} + +func TestFeedHistoryReadonlyAndSourceDisabled(t *testing.T) { + s, token, domain, actor, source := feedActionFixture(t) + ctx := context.Background() + a, e := s.store.QueueFeedAction(ctx, domain, actor, newFeedAction(source)) + if e != nil { + t.Fatal(e) + } + if _, e = s.store.DB.Exec(`UPDATE feed_actions SET status='unknown',until_ms=0 WHERE request_id=?`, a.RequestID); e != nil { + t.Fatal(e) + } + if e = s.store.SetPrincipalState(domain, actor, "readonly"); e != nil { + t.Fatal(e) + } + token, e = s.store.CreateAuthSession(domain, actor) + if e != nil { + t.Fatal(e) + } + list, _ := feedHistoryResponse(t, s, token, "") + if len(list) != 1 || list[0].CanCheck { + t.Fatal("readonly check permission", list) + } + if w := feedRequestTest(s, token, "POST", "action/check", map[string]string{"request_id": a.RequestID}); w.Code != 403 { + t.Fatal("readonly mutation", w.Code) + } + if w := feedRequestTest(s, token, "GET", "action/export?request_id="+a.RequestID, nil); w.Code != 200 { + t.Fatal("readonly export", w.Code) + } + if e = s.store.SetPrincipalState(domain, actor, "active"); e != nil { + t.Fatal(e) + } + token, e = s.store.CreateAuthSession(domain, actor) + if e != nil { + t.Fatal(e) + } + source.Credential, source.Enabled = "", false + if _, e = s.store.SaveFeedSource(ctx, domain, actor, source); e != nil { + t.Fatal(e) + } + list, _ = feedHistoryResponse(t, s, token, "") + if len(list) != 1 || list[0].CanCheck || !list[0].SourcePresent { + t.Fatal("disabled source recheck", list) + } +} diff --git a/internal/server/feeds_test.go b/internal/server/feeds_test.go index 5dcd936..7e09e75 100644 --- a/internal/server/feeds_test.go +++ b/internal/server/feeds_test.go @@ -591,6 +591,28 @@ func TestFeedsChromium(t *testing.T) { w.WriteHeader(204) return } + if r.URL.Path == "/fixture/feed-history" && r.Method == "POST" { + missing, orphan := uuid.NewString(), uuid.NewString() + for _, entry := range []struct{ request, source, item string }{{missing, fresh.UUID, "history-evicted"}, {orphan, uuid.NewString(), ``}} { + if _, e := s.store.DB.Exec(`INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES(?,?,?,?,?,'read',1,1,'unknown',?)`, domain, actor, entry.request, entry.source, entry.item, time.Now().UnixMilli()); e != nil { + t.Error(e) + http.Error(w, "fixture insert failed", 500) + return + } + } + writeEventJSON(w, 200, map[string]string{"missing": missing, "orphan": orphan}) + return + } + if r.URL.Path == "/fixture/check-feed-history" && r.Method == "POST" { + fake := &feedRemoteFake{id: "history-evicted", read: true} + if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil || fake.edits != 0 { + t.Errorf("history read-only check: %v edits=%d", e, fake.edits) + http.Error(w, "test recheck failed", 500) + return + } + w.WriteHeader(204) + return + } if r.URL.Path == "/fixture" { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(w, "") @@ -600,7 +622,7 @@ func TestFeedsChromium(t *testing.T) { })) defer web.Close() for _, width := range []string{"1440", "390"} { - if _, e = s.store.DB.Exec(`DELETE FROM feed_actions WHERE source_uuid=?`, fresh.UUID); e != nil { + if _, e = s.store.DB.Exec(`DELETE FROM feed_actions`); e != nil { t.Fatal(e) } if _, e = s.store.DB.Exec(`UPDATE feed_items SET is_read=0 WHERE source_uuid=?`, fresh.UUID); e != nil { diff --git a/internal/server/testdata/feeds.js b/internal/server/testdata/feeds.js index 8810d6b..8620a85 100644 --- a/internal/server/testdata/feeds.js +++ b/internal/server/testdata/feeds.js @@ -41,7 +41,17 @@ // Restore the synthetic source to read-only for the second viewport run. const api='/_/api/v1/extension/organizer.feeds/',source=(await (await w.fetch(api+'sources')).json()).sources.find(s=>s.title==='FreshRSS fixture'); await w.fetch(api+'sources',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({uuid:source.uuid,version:source.version,provider:source.provider,title:source.title,folder:source.folder,url:source.url,interval_seconds:source.interval_seconds,enabled:true,write_enabled:false})}); - if(w.innerWidth<=600)d.querySelector('#feed-toolbar button').click(); - assert(d.documentElement.scrollWidth<=w.innerWidth,'Catalog overflow');document.body.dataset.vimReady='1'; + const seed=await (await w.fetch('/fixture/feed-history',{method:'POST'})).json(); + d.getElementById('feed-history').click();await wait(()=>d.querySelectorAll('#feed-history-panel tbody tr').length===2); + const receipt=id=>d.querySelector('#feed-history-panel tr[data-request-id="'+id+'"]'); + assert(d.querySelector('.feed-layout').classList.contains('action-history'),'History full panel');assert(!receipt(seed.missing).querySelector('.feed-history-check').disabled,'Evicted item check unavailable');assert(receipt(seed.orphan).querySelector('.feed-history-check').disabled,'Deleted source check available');assert(!receipt(seed.orphan).querySelector('img'),'Untrusted ID rendered as HTML'); + const exported=await (await w.fetch(receipt(seed.orphan).querySelector('.feed-history-export').href)).json();assert(exported.format==='pageswiki.feed-action'&&exported.action.request_id===seed.orphan&&!exported.action.source_present,'Orphan receipt export'); + assert(d.documentElement.scrollWidth<=w.innerWidth,'History overflow'); + receipt(seed.missing).querySelector('.feed-history-check').click();await wait(()=>receipt(seed.missing)?.querySelector('[data-state=check_queued]')); + assert((await w.fetch('/fixture/check-feed-history',{method:'POST'})).status===204,'Recheck worker failed');d.getElementById('feed-history-reload').click();await wait(()=>!receipt(seed.missing)&&receipt(seed.orphan)); + const hs=d.getElementById('feed-history-state');hs.value='all';hs.dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]')); + d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));assert(!d.querySelector('.feed-layout').classList.contains('action-history'),'History escape'); + d.getElementById('feed-history').click();await wait(()=>receipt(seed.orphan));d.getElementById('feed-history-state').value='all';d.getElementById('feed-history-state').dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]')); + assert(d.documentElement.scrollWidth<=w.innerWidth,'History final overflow');document.body.dataset.vimReady='1'; }catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);} })(); diff --git a/internal/store/feeds.go b/internal/store/feeds.go index 7f63ee8..89a767d 100644 --- a/internal/store/feeds.go +++ b/internal/store/feeds.go @@ -263,6 +263,17 @@ func (s *Store) SaveFeedSource(ctx context.Context, domain, owner string, v Feed if !errors.Is(lookup, sql.ErrNoRows) { return lookup } + // Do not rebind retained receipts to a different remote identity. + // Both predicates use existing indexes: owner history and the global + // partial index of unresolved operations. Other owners' terminal + // receipts remain isolated by domain/owner in metadata lookups. + var retired bool + if e := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM feed_actions WHERE domain_uuid=? AND owner_uuid=? AND source_uuid=?) OR EXISTS(SELECT 1 FROM feed_actions WHERE source_uuid=? AND status IN ('queued','preparing','sending','unknown','check_queued','checking'))`, domain, owner, v.UUID, v.UUID).Scan(&retired); e != nil { + return e + } + if retired { + return ErrTaskConflict + } var n int if e := tx.QueryRowContext(ctx, `SELECT count(*) FROM feed_sources WHERE domain_uuid=? AND owner_uuid=?`, domain, owner).Scan(&n); e != nil { return e diff --git a/internal/store/feeds_actions.go b/internal/store/feeds_actions.go index 4895e4e..45da32c 100644 --- a/internal/store/feeds_actions.go +++ b/internal/store/feeds_actions.go @@ -92,7 +92,7 @@ func (s *Store) QueueFeedAction(ctx context.Context, domain, owner string, a Fee // Recheck is deliberately read-only at the remote side, even with writeback OFF. func (s *Store) RecheckFeedAction(ctx context.Context, domain, owner, request string) error { return s.feedWrite(ctx, domain, owner, func(tx *sql.Tx) error { - r, e := tx.ExecContext(ctx, `UPDATE feed_actions SET status='check_queued',error='' WHERE domain_uuid=? AND owner_uuid=? AND request_id=? AND status='unknown' AND until_ms= 0 { + if _, e := uuid.Parse(q.Key); e != nil { + return nil, ErrTaskInvalid + } + where += ` AND (a.created_msspan,.feed-history small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-history small{font-size:.72rem;opacity:.7}.feed-history-buttons{display:flex;gap:.2rem;justify-content:flex-end}.feed-history-buttons a{display:inline-flex;align-items:center;justify-content:center;min-width:1.8rem;min-height:1.8rem;border:1px solid var(--border,#6666);border-radius:.2rem;text-decoration:none}.feed-history [data-state=unknown],.feed-history [data-state=conflict],.feed-history [data-state=failed]{color:var(--danger,#e57a7a)}.feed-history .feed-warning:empty{display:none} +@media(max-width:1100px){.feed-layout.action-history{grid-template-columns:10rem minmax(0,1fr)}} +@media(max-width:600px){.feed-history thead{display:none}.feed-history tbody,.feed-history tr{display:block}.feed-history tr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.15rem .3rem;padding:.5rem 0;border-bottom:1px solid var(--border,#8885)}.feed-history td{display:block;border:0;padding:0 .2rem;min-width:0}.feed-history td:first-child{grid-column:1;grid-row:1;font-size:.7rem;opacity:.7}.feed-history td:nth-child(2){grid-column:1;grid-row:2}.feed-history td:nth-child(3){grid-column:1;grid-row:3;font-size:.75rem}.feed-history td:last-child{grid-column:2;grid-row:1/4;align-self:center}.feed-history-buttons a{min-width:2.3rem;min-height:2.3rem}} .feed-catalog{padding:.3rem 0 .4rem .5rem;display:grid;gap:.3rem;border-left:2px solid var(--border,#8885)}#feeds-app .feed-catalog select,#feeds-app .feed-catalog input{width:100%;min-width:0;box-sizing:border-box;font-size:.75rem}.feed-subscriptions{display:grid;gap:0}.feed-subscriptions button{text-align:left;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:.75rem!important;border:0!important;content-visibility:auto;contain-intrinsic-size:auto 29px}.feed-subscriptions button[aria-current=true]{background:color-mix(in srgb,var(--accent,#659de4) 22%,transparent)!important} .feed-opml{display:grid;gap:.6rem;min-width:0}.feed-opml>label{display:grid;gap:.25rem}.feed-opml input[type=file]{width:100%;box-sizing:border-box}.feed-opml table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:.8rem}.feed-opml th,.feed-opml td{text-align:left;vertical-align:top;padding:.3rem;border-bottom:1px solid var(--border,#8885);overflow-wrap:anywhere}.feed-opml th:first-child{width:1.6rem}.feed-opml th:nth-child(3){width:20%}.feed-opml th:last-child{width:20%}.feed-opml small{display:block;font-size:.7rem;opacity:.7;overflow-wrap:anywhere}#feeds-app .feed-opml input[type=checkbox]{width:auto;min-height:1.2rem}.feed-import-options{display:flex;gap:.75rem;align-items:center;flex-wrap:wrap}#feeds-app .feed-import-options label:has(input[type=checkbox]){display:flex;align-items:center}.feed-opml input:disabled{opacity:.4} #feed-status:empty{display:none}#feed-reader .feed-body-html{white-space:normal}.feed-original{display:inline-flex;align-items:center;justify-content:center;min-width:2rem;min-height:2rem;border-radius:.2rem}.feed-original:hover{background:var(--border,#8883)}.feed-original svg{width:1.1rem;height:1.1rem;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round} diff --git a/static/js/feeds.js b/static/js/feeds.js index 9bfd793..7c4e414 100644 --- a/static/js/feeds.js +++ b/static/js/feeds.js @@ -24,12 +24,13 @@ toolbar.append(button('☰',t('Sources','購読元'),()=>layout.classList.toggle('sources-open')),sourceLabel,searchbox,filters,refresh); if(writable)toolbar.append(button('+',t('Add source','購読元を追加'),()=>sourceForm())); const transfer=button('⇄','OPML',opmlForm);transfer.id='feed-opml';toolbar.append(transfer); + const history=button('◷',t('Operation history','操作履歴'),actionHistory);history.id='feed-history';toolbar.append(history); toolbar.append(button('?',t('Keyboard shortcuts','キー操作'),showHelp)); let debounce;searchbox.addEventListener('input',()=>{clearTimeout(debounce);debounce=setTimeout(()=>{search=searchbox.value.trim();load(false).catch(report);},180);}); const columns=document.getElementById('feed-columns');for(const s of ['',t('Date','日付'),t('Feed','配信元'),t('Subject','件名')])columns.append(el('span',s)); function showHelp(){status.textContent=t('j/k move · Enter read · Esc index · / search · n unread · m read/unread · * star · r refresh','j/k 移動 · Enter 本文 · Esc 一覧 · / 検索 · n 次の未読 · m 既読/未読 · * star · r 更新');} function date(ms){return ms?new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit'}).format(new Date(ms)):'—';} - function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading');rows.focus();} + function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading','action-history');rows.focus();} function drawSources(){sourcesView.replaceChildren();const all=button(t('All sources','すべての購読元'),'',()=>chooseSource(''));sourcesView.append(all);let folder=null; for(const source of sources){if(folder!==source.folder){folder=source.folder;sourcesView.append(el('h3',folder||t('Sources','購読元')));}const row=el('div',undefined,'feed-source');row.setAttribute('aria-current',String(currentSource===source.uuid)); const b=button((source.enabled?'':'⏸ ')+source.title,source.title,()=>chooseSource(source.uuid));if(source.error){b.classList.add('feed-source-error');b.title+=' · '+source.error;}row.append(b);if(writable)row.append(button('⚙',t('Source settings','購読元設定'),()=>sourceForm(source)));sourcesView.append(row); @@ -55,7 +56,7 @@ function drawRows(){rows.replaceChildren(...items.map(rowNode));more.hidden=!next;more.textContent='↓';more.title=more.ariaLabel=t('More articles','続きを表示');if(!items.length)rows.append(el('p',t('No articles','記事なし'),'feed-warning'));} async function load(append){if(append&&(!next||loading))return;controller?.abort();controller=new AbortController();const version=++seq;loading=true;more.disabled=true; try{const q=new URLSearchParams({source:currentSource,filter,q:search,feed:remoteFeed,category:remoteCategory});if(append){q.set('before',next.ms);q.set('key',next.key);}const data=await request('items?'+q,{signal:controller.signal});if(version!==seq)return; - if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading');editing=false;}items.push(...data.items);const last=data.items.at(-1);next=data.more&&last?{ms:last.published_ms,key:last.source+':'+last.id}:null;drawRows();status.textContent=''; + if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading','action-history');editing=false;}items.push(...data.items);const last=data.items.at(-1);next=data.more&&last?{ms:last.published_ms,key:last.source+':'+last.id}:null;drawRows();status.textContent=''; }finally{if(version===seq){loading=false;more.disabled=false;}} } more.onclick=()=>load(true).catch(report); @@ -63,7 +64,7 @@ async function queueRefresh(){const targets=sources.filter(s=>s.enabled&&(!currentSource||currentSource===s.uuid));for(const s of targets)await post('sources/'+s.uuid+'/refresh',{version:s.version});status.textContent=t('Refresh queued','更新を予約しました');} toolbar.append(button('⟳',t('Reload cached list','取得済み一覧を再読込'),reload)); async function open(index){if(index<0||index>=items.length)return;editing=false;selected=index;detailController?.abort();detailController=new AbortController();const version=++detailSeq;for(const [i,row]of [...rows.querySelectorAll('.feed-row')].entries())row.setAttribute('aria-selected',String(i===index));rows.setAttribute('aria-activedescendant','feed-row-'+index);document.getElementById('feed-row-'+index)?.scrollIntoView({block:'nearest'}); - layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;if(item.provider==='freshrss'){item.actionLoading=true;renderItem(item);await updateAction(item);}else renderItem(item); + layout.classList.remove('action-history');layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;if(item.provider==='freshrss'){item.actionLoading=true;renderItem(item);await updateAction(item);}else renderItem(item); } function renderItem(item){reader.replaceChildren();const actions=el('div',undefined,'feed-actions');actions.append(button('←',t('Back to list','一覧へ戻る'),closeReader)); const canWrite=item.provider==='local'||sources.some(s=>s.uuid===item.source&&s.enabled&&s.write_enabled); @@ -84,6 +85,32 @@ if(item.provider==='freshrss'){const config=sources.find(s=>s.uuid===source);if(!config?.enabled||!config?.write_enabled)return;const field=read!==item.read?'read':'starred',desired=field==='read'?read:starred;if(item[field]===desired)return;item.actionLoading=true;renderItem(item);try{await post('remote-state',{request_id:crypto.randomUUID(),source,id,field,desired,source_version:config.version});}finally{await updateAction(item);}return;} const data=await post('state',{source,id,read,starred,version:item.version});Object.assign(item,{read,starred,version:data.version});drawRows();if(items[selected]===item&&!editing)renderItem(item);} function field(form,label,value='',type='text'){const wrap=el('label',label),input=el('input');input.type=type;input.value=value;wrap.append(input);form.append(wrap);return input;} + function actionHistory(){ + editing=true;const version=++detailSeq;detailController?.abort();controller?.abort();seq++;loading=false;more.disabled=false;clearTimeout(actionTimer);layout.classList.add('reading','action-history');status.textContent='';reader.replaceChildren(); + const section=el('section',undefined,'feed-history'),heading=el('div',undefined,'feed-actions');section.id='feed-history-panel';reader.append(section); + heading.append(button('←',t('Back to list','一覧へ戻る'),closeReader),el('h1',t('Operation history','操作履歴')));section.append(heading); + const controls=el('div',undefined,'feed-history-controls'),states=el('select'),sourceFilter=el('select');states.id='feed-history-state';states.ariaLabel=t('Operation status','操作状態');sourceFilter.ariaLabel=t('Source','購読元'); + for(const [value,en,jp]of [['unresolved','Needs attention','未解決'],['pending','In progress','処理中'],['unknown','Result unknown','結果不明'],['all','All','すべて'],['confirmed','Confirmed','確認済み'],['failed','Not sent','未送信'],['conflict','Conflict','不一致'],['cancelled','Cancelled','中止']]){const o=el('option',t(en,jp));o.value=value;states.append(o);} + for(const [value,label]of [['',t('All sources','すべての購読元')],...sources.filter(s=>s.provider==='freshrss').map(s=>[s.uuid,s.title])]){const o=el('option',label);o.value=value;sourceFilter.append(o);} + const reloadHistory=button('↻',t('Reload history','履歴を再読込'),()=>fetchHistory(false));reloadHistory.id='feed-history-reload';controls.append(states,sourceFilter,reloadHistory);section.append(controls); + const table=el('table'),head=el('thead'),headRow=el('tr'),body=el('tbody');for(const label of [t('Date','日時'),t('Article / operation','記事・操作'),t('Status','状態'),t('Actions','操作')]){const th=el('th',label);th.scope='col';headRow.append(th);}head.append(headRow);table.append(head,body);section.append(table); + const empty=el('p',t('No operations','操作なし'),'feed-warning'),notice=el('p',undefined,'feed-warning'),nextPage=button('↓',t('More operations','続きを表示'),()=>fetchHistory(true));notice.role='status';empty.hidden=true;nextPage.hidden=true;section.append(empty,notice,nextPage); + let cursor=null,generation=0,busy=false,abort; + const labels={queued:t('Queued','送信待ち'),preparing:t('Checking','確認中'),sending:t('Sending','送信中'),check_queued:t('Recheck queued','再確認待ち'),checking:t('Rechecking','再確認中'),unknown:t('Result unknown','結果不明'),confirmed:t('Confirmed','確認済み'),failed:t('Not sent','未送信'),conflict:t('Conflict','不一致'),cancelled:t('Cancelled','中止')}; + const errors={network:t('Network error','通信エラー'),credentials:t('Authentication failed','認証失敗'),remote_error:t('Remote error','接続先エラー'),invalid_feed:t('Invalid response','応答不正'),limit:t('Limit exceeded','上限超過'),expired:t('Expired','期限切れ'),source_changed:t('Source settings changed','購読元設定が変更されました'),source_deleted:t('Source deleted','購読元削除済み'),conflict:t('Remote state differs','外部の状態が一致しません')}; + function row(a){const tr=el('tr');tr.dataset.requestId=a.request_id;const when=el('td',new Date(a.created_ms).toLocaleString(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'})),subject=el('td'),state=el('td',labels[a.status]||a.status),actions=el('td');when.title=new Date(a.created_ms).toLocaleString();state.dataset.state=a.status;state.title=errors[a.error]||a.error||''; + const title=a.item_title||a.id,name=a.source_title||a.source,operation=a.field==='read'?(a.desired?t('Read','既読'):t('Unread','未読')):(a.desired?t('Star','star追加'):t('Unstar','star解除')); + const text=el('span',title);text.title=title;subject.append(text,el('small',name+' · '+operation));if(!a.source_present)subject.append(el('small',t('Source deleted','購読元削除済み')));else if(!a.item_present)subject.append(el('small',t('Outside article cache','記事キャッシュ外'))); + const tools=el('div',undefined,'feed-history-buttons');actions.append(tools); + if(a.item_present){const view=button('↗',t('Read article','記事を読む'),async()=>{let index=items.findIndex(i=>i.source===a.source&&i.id===a.id);if(index<0){const data=await request('item?'+new URLSearchParams({source:a.source,id:a.id}));if(detailSeq!==version)return;items.unshift(data.item);index=0;drawRows();}await open(index);});tools.append(view);} + if(a.status==='unknown'){const check=button('↻',t('Recheck remote state without resending','再送せず外部状態を再確認'),async()=>{check.disabled=true;try{await post('action/check',{request_id:a.request_id});await fetchHistory(false);}catch(e){notice.textContent=e.message;check.disabled=false;}});check.className='feed-history-check';check.disabled=!writable||!a.can_check;if(!a.source_present)check.title=t('Deleted source cannot be rechecked','削除した購読元は再確認できません');else if(a.check_after_ms>Date.now())check.title=t('Recheck after ','再確認可能時刻: ')+new Date(a.check_after_ms).toLocaleTimeString();else if(!a.can_check)check.title=t('Requires an enabled source and write permission','購読元の有効化と操作権限が必要です');tools.append(check);} + const save=el('a','↓');save.className='feed-history-export';save.href=api+'action/export?'+new URLSearchParams({request_id:a.request_id});save.download='pageswiki-feed-action.json';save.title=save.ariaLabel=t('Save operation receipt (JSON)','操作記録を保存(JSON)');tools.append(save);tr.append(when,subject,state,actions);return tr;} + async function fetchHistory(append){if(version!==detailSeq||!section.isConnected||append&&(busy||!cursor))return;abort?.abort();abort=new AbortController();const n=++generation;busy=true;nextPage.disabled=true;notice.textContent='';if(!append){cursor=null;nextPage.hidden=true;empty.hidden=true;body.replaceChildren();} + try{const q=new URLSearchParams({status:states.value,source:sourceFilter.value});if(append){q.set('before',cursor.created_ms);q.set('key',cursor.request_id);}const data=await request('actions?'+q,{signal:abort.signal});if(n!==generation||version!==detailSeq||!section.isConnected)return;if(!append)body.replaceChildren();body.append(...data.actions.map(row));cursor=data.more?data.actions.at(-1):null;nextPage.hidden=!cursor;empty.hidden=body.children.length!==0; + }catch(e){if(e.name!=='AbortError'&&n===generation&§ion.isConnected)notice.textContent=e.message;}finally{if(n===generation){busy=false;nextPage.disabled=false;}} + } + states.onchange=sourceFilter.onchange=()=>fetchHistory(false);fetchHistory(false); + } function opmlForm(){ editing=true;detailSeq++;detailController?.abort();layout.classList.add('reading');reader.replaceChildren(); const section=el('section',undefined,'feed-opml'),heading=el('div',undefined,'feed-actions');heading.append(el('h1','OPML'),button('←',t('Back','戻る'),closeReader));section.append(heading);reader.append(section); diff --git a/templates/pages/feeds.gohtml b/templates/pages/feeds.gohtml index 1627d8c..333b785 100644 --- a/templates/pages/feeds.gohtml +++ b/templates/pages/feeds.gohtml @@ -1,9 +1,9 @@ {{ define "feeds.gohtml" }} {{ T "feeds.title" }} · {{ .WikiName }} - +
{{ template "auth-menu" . }}
{{ template "organizer-nav" . }}

-
{{ end }} +{{ end }}