From d9b146736556f291321c67ad2a408883cfbe32f6 Mon Sep 17 00:00:00 2001 From: David Young Date: Sat, 21 Nov 2026 10:31:04 -0700 Subject: [PATCH] Suggest subreddits when filling in an inventory entry, checked with Reddit If the Subreddits box is empty, the AI suggests up to eight, by the relationship, each with who is there. Each is looked up on Reddit (with the app's client ID and secret) and left out if it doesn't exist, is private, 18+, restricted or archived; the first five kept fill the box. The form lists every suggestion with members, post types and why any was left out. Lookups are cached for drafting. Without Reddit keys the suggestions are kept and the form says they weren't checked. The Reddit client now returns ErrNotFound and ErrForbidden, and treats an empty about listing as not found. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- internal/api/reddit/client.go | 16 ++++- internal/inventory/draft.go | 109 ++++++++++++++++++++++++++---- internal/inventory/draft_test.go | 66 +++++++++++++++++- internal/web/inventory.go | 34 +++++++++- internal/web/static/app.css | 9 +++ internal/web/templates/entry.html | 19 +++++- 7 files changed, 233 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index b470c59..ce2805c 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Then open Supermarket and: 1. **Settings → AI**: Anthropic, with Hermes' key (shared by `supermarket hermes`) or your own, or an LLM server on your network, such as Ollama. Servers found by CoreDesktop's `configure ai-servers` are offered. 2. **Settings → Profile**: enter your website and press *Draft*. Correct the draft and save it. -3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords and hashtags. What you typed stays; nothing is saved until you press Save. +3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits are checked with Reddit first (with the Reddit client ID and secret saved), and ones that don't exist, are private or are restricted are left out. What you typed stays; nothing is saved until you press Save. 4. **Settings → Social accounts**: connect X, LinkedIn and Reddit. The menu on the left has a search box at the top (press `/` to jump to it), then the **Overview** with a card per module, the **Inventory**, and the modules: **Content** (Inbox, Sources, Scheduled, Published), and the ones still to come. **Settings**, at the bottom, holds the Profile, Social accounts, Core & Hermes, and AI. Search finds posts, fetched items, inventory entries, your products and settings pages. The look follows brain (Federated's superbrain), including a dark theme that follows your system's setting. diff --git a/internal/api/reddit/client.go b/internal/api/reddit/client.go index 5757f97..51a65f5 100644 --- a/internal/api/reddit/client.go +++ b/internal/api/reddit/client.go @@ -54,6 +54,13 @@ func UserAgent(version, username string) string { // ErrUnauthorized means the token was refused even after a refresh. var ErrUnauthorized = errors.New("Reddit refused the sign-in: connect Reddit again under Settings → Social accounts") +// ErrNotFound and ErrForbidden are what Reddit answers for a subreddit or +// user that doesn't exist (or was banned), and for a private one. +var ( + ErrNotFound = errors.New("Reddit said 404: no such subreddit or user") + ErrForbidden = errors.New("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it") +) + func (c *Client) do(ctx context.Context, method, path string, form url.Values, out any) error { for attempt := 0; ; attempt++ { var body io.Reader @@ -87,9 +94,9 @@ func (c *Client) do(ctx context.Context, method, path string, form url.Values, o case res.StatusCode == http.StatusUnauthorized: return ErrUnauthorized case res.StatusCode == http.StatusForbidden: - return fmt.Errorf("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it") + return ErrForbidden case res.StatusCode == http.StatusNotFound: - return fmt.Errorf("Reddit said 404: no such subreddit or user") + return ErrNotFound case res.StatusCode == http.StatusTooManyRequests: return fmt.Errorf("Reddit is rate-limiting this app; try again in a few minutes") case res.StatusCode != http.StatusOK: @@ -214,6 +221,11 @@ func (c *Client) SubredditInfo(ctx context.Context, name string) (*Subreddit, er if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about", nil, &about); err != nil { return nil, err } + if about.Data.DisplayName == "" { + // Reddit sometimes answers a missing subreddit with an empty listing + // rather than a 404. + return nil, ErrNotFound + } var rules struct { Rules []struct { ShortName string `json:"short_name"` diff --git a/internal/inventory/draft.go b/internal/inventory/draft.go index dc67e58..98c4eb6 100644 --- a/internal/inventory/draft.go +++ b/internal/inventory/draft.go @@ -2,10 +2,12 @@ package inventory import ( "context" + "errors" "fmt" "strings" "supermarket/internal/ai" + "supermarket/internal/api/reddit" "supermarket/internal/profile" "supermarket/internal/site" ) @@ -13,6 +15,28 @@ import ( // maxFeeds is how many of a site's feeds Fill takes. const maxFeeds = 3 +// maxSubreddits is how many suggested subreddits Fill puts in the box. +const maxSubreddits = 5 + +// SubredditCheck looks a subreddit up on Reddit. It returns reddit.ErrNotFound +// or reddit.ErrForbidden for one that doesn't exist or is private. +type SubredditCheck func(ctx context.Context, name string) (*reddit.Subreddit, error) + +// Suggestion is a subreddit the AI suggested, and what Reddit said about it. +type Suggestion struct { + Name string + Why string // the model's reason + Info *reddit.Subreddit // nil if not checked + Kept bool // put in the Subreddits box + Problem string // why it was left out, or why it's unchecked +} + +// FillResult says what Fill did. +type FillResult struct { + Filled []string // labels of the fields filled + Suggestions []Suggestion // subreddits the AI suggested, if it was asked +} + // Fill fills the entry's empty fields from its website, for the user to check // before saving. Fields that already have a value are kept as they are. // @@ -20,24 +44,26 @@ const maxFeeds = 3 // YouTube and Instagram accounts, subreddits and feeds the site links to. // The model writes what needs judgement: the name if missing, description, // talking points (set against ours, the user's own company profile, if -// there is one), keywords and hashtags. It returns the labels of the fields -// it filled. -func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile) ([]string, error) { +// there is one), keywords and hashtags. If the site links to no subreddit, +// the model suggests some, and check (if not nil) drops the ones that don't +// exist or that can't be posted to; models invent believable names. +func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile, check SubredditCheck) (*FillResult, error) { + res := &FillResult{} st, err := site.Read(ctx, siteURL, "Supermarket/1 (inventory draft)") if err != nil { - return nil, err + return res, err } - var filled []string + filled := &res.Filled setStr := func(label string, field *string, v string) { if strings.TrimSpace(*field) == "" && strings.TrimSpace(v) != "" { *field = strings.TrimSpace(v) - filled = append(filled, label) + *filled = append(*filled, label) } } setList := func(label string, field *[]string, v []string) { if len(profile.CleanList(*field)) == 0 && len(profile.CleanList(v)) > 0 { *field = profile.CleanList(v) - filled = append(filled, label) + *filled = append(*filled, label) } } @@ -61,11 +87,12 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours setList("feeds", &e.RSS, feeds) // The rest from the model, only if something is still empty. + wantSubs := len(profile.CleanList(e.Subreddits)) == 0 needs := strings.TrimSpace(e.Name) == "" || strings.TrimSpace(e.Description) == "" || strings.TrimSpace(e.TalkingPoints) == "" || len(profile.CleanList(e.Keywords)) == 0 || - len(profile.CleanList(e.Hashtags)) == 0 + len(profile.CleanList(e.Hashtags)) == 0 || wantSubs if !needs { - return filled, nil + return res, nil } var d struct { Name string `json:"name"` @@ -73,6 +100,10 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours TalkingPoints string `json:"talking_points"` Keywords []string `json:"keywords"` Hashtags []string `json:"hashtags"` + Subreddits []struct { + Name string `json:"name"` + Why string `json:"why"` + } `json:"subreddits"` } err = ai.GenerateJSON(ctx, client, ai.Request{ Task: ai.TaskProfile, @@ -82,14 +113,62 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours Schema: fillSchema(), }, &d) if err != nil { - return filled, err + return res, err } setStr("name", &e.Name, d.Name) setStr("description", &e.Description, d.Description) setStr("talking points", &e.TalkingPoints, d.TalkingPoints) setList("keywords", &e.Keywords, d.Keywords) setList("hashtags", &e.Hashtags, d.Hashtags) - return filled, nil + + if wantSubs { + var keep []string + seen := map[string]bool{} + for _, sub := range d.Subreddits { + name := reddit.CleanName(sub.Name) + if name == "" || seen[strings.ToLower(name)] { + continue + } + seen[strings.ToLower(name)] = true + sg := checkSubreddit(ctx, check, name, sub.Why) + if sg.Kept && len(keep) < maxSubreddits { + keep = append(keep, sg.Name) + } else if sg.Kept { + sg.Kept, sg.Problem = false, "more than enough already" + } + res.Suggestions = append(res.Suggestions, sg) + } + setList("subreddits", &e.Subreddits, keep) + } + return res, nil +} + +// checkSubreddit asks Reddit about a suggested subreddit. One Reddit can't +// be asked about (no keys, rate limit) is kept, marked unchecked. +func checkSubreddit(ctx context.Context, check SubredditCheck, name, why string) Suggestion { + sg := Suggestion{Name: name, Why: strings.TrimSpace(why), Kept: true} + if check == nil { + sg.Problem = "not checked" + return sg + } + info, err := check(ctx, name) + switch { + case errors.Is(err, reddit.ErrNotFound): + sg.Kept, sg.Problem = false, "doesn't exist, or was banned" + case errors.Is(err, reddit.ErrForbidden): + sg.Kept, sg.Problem = false, "private" + case err != nil: + sg.Problem = "not checked: " + err.Error() + case info.Type == "private": + sg.Kept, sg.Problem = false, "private" + case info.Over18: + sg.Kept, sg.Problem = false, "marked 18+" + case info.Type == "restricted" || info.Type == "archived": + sg.Kept, sg.Problem = false, info.Type+": only approved accounts can post" + default: + sg.Name, sg.Info = info.Name, info // Reddit's spelling of the name + } + return sg } const fillSystem = `You fill in an entry in a company's marketing inventory: another company or project it posts about, as a partner, a competitor, or one to watch. The marketing team reviews and corrects what you write. @@ -105,7 +184,8 @@ Rules: - watch: what they cover that matters to the company's audience. Without a company profile, leave talking_points empty. - keywords: up to eight phrases they own or compete on. -- hashtags: up to five, only ones their pages use or that name them or their product.` +- hashtags: up to five, only ones their pages use or that name them or their product. +- subreddits: up to eight subreddits where talking about them would reach the company's audience: for a partner, where their users and the company's customers talk; for a competitor, where people compare or ask about tools like theirs; for one to watch, where their field is discussed. Names without r/, real subreddits you're confident exist, active and on topic; general ones (like technology) only if nothing narrower fits. why: one short phrase on who is there. They'll be checked against Reddit before use.` func fillPrompt(e *Entry, ours *profile.Profile, st *site.Site) string { var b strings.Builder @@ -132,7 +212,10 @@ func fillPrompt(e *Entry, ours *profile.Profile, st *site.Site) string { func fillSchema() map[string]any { str := map[string]any{"type": "string"} list := map[string]any{"type": "array", "items": str} - props := map[string]any{"name": str, "description": str, "talking_points": str, "keywords": list, "hashtags": list} + sub := map[string]any{"type": "object", "properties": map[string]any{"name": str, "why": str}, + "required": []string{"name", "why"}, "additionalProperties": false} + props := map[string]any{"name": str, "description": str, "talking_points": str, "keywords": list, "hashtags": list, + "subreddits": map[string]any{"type": "array", "items": sub}} req := make([]string, 0, len(props)) for k := range props { req = append(req, k) diff --git a/internal/inventory/draft_test.go b/internal/inventory/draft_test.go index b824442..0aa1ee6 100644 --- a/internal/inventory/draft_test.go +++ b/internal/inventory/draft_test.go @@ -3,12 +3,15 @@ package inventory import ( "context" "encoding/json" + "errors" + "fmt" "net/http" "net/http/httptest" "strings" "testing" "supermarket/internal/ai" + "supermarket/internal/api/reddit" "supermarket/internal/profile" ) @@ -49,10 +52,11 @@ func TestFillKeepsWhatWasTyped(t *testing.T) { }} e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"} ours := &profile.Profile{Name: "Acme", Description: "Self-hosted widgets."} - filled, err := Fill(context.Background(), fake, e, srv.URL, ours) + res, err := Fill(context.Background(), fake, e, srv.URL, ours, nil) if err != nil { t.Fatal(err) } + filled := res.Filled if e.Name != "Rival" || e.TwitterHandle != "typed" { t.Errorf("typed values changed: %+v", e) } @@ -78,8 +82,8 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) { srv := rivalSite(t) fake := &fakeAI{} e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t", - Keywords: []string{"k"}, Hashtags: []string{"#h"}} - if _, err := Fill(context.Background(), fake, e, srv.URL, nil); err != nil { + Keywords: []string{"k"}, Hashtags: []string{"#h"}, Subreddits: []string{"selfhosted"}} + if _, err := Fill(context.Background(), fake, e, srv.URL, nil, nil); err != nil { t.Fatal(err) } if fake.calls != 0 { @@ -89,3 +93,59 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) { t.Errorf("links not read: %+v", e) } } + +func TestFillChecksSuggestedSubreddits(t *testing.T) { + srv := rivalSite(t) + fake := &fakeAI{reply: map[string]any{ + "name": "", "description": "", "talking_points": "", "keywords": []string{}, "hashtags": []string{}, + "subreddits": []map[string]string{ + {"name": "r/selfhosted", "why": "self-hosters"}, + {"name": "SelfHosted", "why": "again"}, + {"name": "madeupwidgets", "why": "invented"}, + {"name": "secretclub", "why": "private"}, + {"name": "announcements", "why": "restricted"}, + {"name": "homelab", "why": "home servers"}, + {"name": "slowreddit", "why": "rate limited"}, + }, + }} + check := func(_ context.Context, name string) (*reddit.Subreddit, error) { + switch name { + case "selfhosted": + return &reddit.Subreddit{Name: "selfhosted", Type: "public", Subscribers: 500000}, nil + case "homelab": + return &reddit.Subreddit{Name: "homelab", Type: "public"}, nil + case "secretclub": + return nil, reddit.ErrForbidden + case "announcements": + return &reddit.Subreddit{Name: "announcements", Type: "restricted"}, nil + case "slowreddit": + return nil, errors.New("rate limited") + } + return nil, reddit.ErrNotFound + } + e := &Entry{Name: "Rival", Relationship: Partner} + res, err := Fill(context.Background(), fake, e, srv.URL, nil, check) + if err != nil { + t.Fatal(err) + } + if got := strings.Join(e.Subreddits, ","); got != "selfhosted,homelab,slowreddit" { + t.Errorf("subreddits = %q", got) + } + var notes []string + for _, sg := range res.Suggestions { + notes = append(notes, fmt.Sprintf("%s:%v", sg.Name, sg.Kept)) + } + if got := strings.Join(notes, " "); got != "selfhosted:true madeupwidgets:false secretclub:false announcements:false homelab:true slowreddit:true" { + t.Errorf("suggestions = %s", got) + } + if res.Suggestions[5].Problem == "" || res.Suggestions[0].Info == nil { + t.Errorf("unchecked one should say so, checked one should carry its info: %+v", res.Suggestions) + } + + // Without a check, suggestions are kept, marked unchecked. + e = &Entry{Name: "Rival", Relationship: Partner} + res, _ = Fill(context.Background(), fake, e, srv.URL, nil, nil) + if len(e.Subreddits) != 5 || !strings.Contains(res.Suggestions[0].Problem, "not checked") { + t.Errorf("unchecked: %q %+v", e.Subreddits, res.Suggestions) + } +} diff --git a/internal/web/inventory.go b/internal/web/inventory.go index aba78e9..48f593d 100644 --- a/internal/web/inventory.go +++ b/internal/web/inventory.go @@ -11,6 +11,8 @@ import ( "supermarket/examples" "supermarket/internal/ai" + "supermarket/internal/api/reddit" + "supermarket/internal/content" "supermarket/internal/inventory" "supermarket/internal/profile" ) @@ -35,6 +37,8 @@ type entryData struct { NoAI bool // no AI provider yet: filling in from the website can't work DraftURL string // the address to fill in from Filled []string // after filling in: what was filled + Suggestions []inventory.Suggestion + CanCheck bool // Reddit could be asked about the suggestions Drafted bool } @@ -148,8 +152,10 @@ func (s *Server) inventoryFill(w http.ResponseWriter, r *http.Request) { } ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute) defer cancel() - filled, err := inventory.Fill(ctx, client, e, d.DraftURL, ours) - d.Filled, d.Drafted = filled, true + check := s.subredditCheck(ctx) + d.CanCheck = check != nil + res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check) + d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true if err != nil { // Links read before the model failed are kept. show("Couldn't fill in everything: " + err.Error()) @@ -243,3 +249,27 @@ func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Disposition", `attachment; filename="supermarket-inventory.yaml"`) w.Write(data) } + +// subredditCheck looks subreddits up on Reddit for Fill, using the cache +// and caching what it reads (drafting for the subreddit uses it later). It's +// nil if Reddit can't be asked: no client ID and secret. +func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck { + c, err := s.redditReader(ctx) + if err != nil { + return nil + } + return func(ctx context.Context, name string) (*reddit.Subreddit, error) { + if cached, err := content.GetSubreddit(s.DB, name); err == nil && cached != nil && + time.Since(cached.FetchedAt) < content.SubredditMaxAge { + return cached, nil + } + info, err := c.SubredditInfo(ctx, name) + if err != nil { + return nil, err + } + if err := content.SaveSubreddit(s.DB, info); err != nil { + s.Log.Error("caching subreddit", "name", name, "err", err) + } + return info, nil + } +} diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 8372171..2516446 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -349,3 +349,12 @@ form.inline { display: inline-block; margin: 0 0 0.75rem; } .results .detail { display: block; color: hsl(var(--muted-foreground)); font-size: 0.85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .search-page { display: flex; gap: 0.5rem; margin-bottom: 1.25rem; max-width: 40rem; } .search-page input { margin: 0; } + +/* Subreddits suggested when filling in an inventory entry */ +.suggestions { margin-top: 0.75rem; font-size: 0.92rem; } +.suggestions summary { cursor: pointer; font-weight: 600; } +.suggestions ul { list-style: none; padding: 0; margin: 0.5rem 0; } +.suggestions li { padding: 0.35rem 0; border-bottom: 1px solid hsl(var(--border)); display: flex; flex-wrap: wrap; gap: 0 0.6rem; align-items: baseline; } +.suggestions li:last-child { border-bottom: 0; } +.suggestions li .help { flex-basis: 100%; margin: 0; } +.suggestions li.dropped a { text-decoration: line-through; color: hsl(var(--muted-foreground)); } diff --git a/internal/web/templates/entry.html b/internal/web/templates/entry.html index f0ed3c5..fae6855 100644 --- a/internal/web/templates/entry.html +++ b/internal/web/templates/entry.html @@ -6,7 +6,7 @@

Fill in with AI

-

Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords and hashtags from the AI, set against your company profile. What you've typed stays. Nothing is saved until you press Save.

+

Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords, hashtags and subreddits from the AI (subreddits checked with Reddit first), set against your company profile. What you've typed stays. Nothing is saved until you press Save.

{{if .NoAI}}

This needs the AI: first set up the AI, then come back. Or fill in the form by hand.

{{end}}
@@ -14,6 +14,23 @@

Takes up to a minute or two.

{{if .Drafted}}{{if .Filled}}

Filled in: {{join .Filled ", "}}. Check them, correct what's wrong, then Save.

{{else}}

Nothing to fill in: every box the website could answer is already filled, or the site doesn't say.

{{end}}{{end}} + {{with .Suggestions}} +
+ Subreddits the AI suggested + {{if not $.Data.CanCheck}}

Not checked with Reddit, so some may not exist: add Reddit's client ID and secret under Settings → Social accounts and fill in again to check them.

{{end}} +
    + {{range .}} +
  • + r/{{.Name}} + {{with .Info}}{{.Subscribers}} members · {{if eq .SubmissionType "self"}}text posts only{{else if eq .SubmissionType "link"}}link posts only{{else}}text or links{{end}}{{end}} + {{if .Kept}}{{if and .Problem $.Data.CanCheck}}{{.Problem}}{{end}}{{else}}left out: {{.Problem}}{{end}} + {{with .Why}}{{.}}{{end}} +
  • + {{end}} +
+

The ones kept are in the Subreddits box below. Look at each on Reddit before posting there: the AI picks by topic, not by how a community treats companies.

+
+ {{end}}