diff --git a/cmd/fastnews/news_sources_test.go b/cmd/fastnews/news_sources_test.go index 48e34ed..94ea2a1 100644 --- a/cmd/fastnews/news_sources_test.go +++ b/cmd/fastnews/news_sources_test.go @@ -138,3 +138,49 @@ func TestFetchNewsRejectsNonFeedBeforePersistence(t *testing.T) { t.Fatal("invalid response created corpus files", err) } } + +func TestDailySummaryRequiresRecordedScoreWithinModelContract(t *testing.T) { + for _, test := range []struct { + name, score string + want int + }{ + {"missing", "", 0}, {"null", `,"recommendation_score":null`, 0}, + {"zero", `,"recommendation_score":0`, 0}, {"negative", `,"recommendation_score":-1`, 0}, + {"too-high", `,"recommendation_score":11`, 0}, {"wrong-type", `,"recommendation_score":"high"`, 0}, + {"minimum", `,"recommendation_score":1`, 1}, {"maximum", `,"recommendation_score":10`, 10}, + } { + t.Run(test.name, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + fmt.Fprint(w, `score-contractSecurity studyhttps://news.example/studyObserved facts`) + return + } + reply := `{"title_zh":"中文导读","summary_zh":"事实摘要","channel":"security"` + test.score + `}` + fmt.Fprintf(w, `{"choices":[{"finish_reason":"stop","message":{"content":%q}}]}`, reply) + })) + defer upstream.Close() + c := config.Config{Root: t.TempDir(), LLMKey: "fixture", LLMURL: upstream.URL} + if err := job(context.Background(), c, "fetch-news", []string{"--source", "bleepingcomputer", "--url", upstream.URL}); err != nil { + t.Fatal(err) + } + err := job(context.Background(), c, "daily-summary", nil) + file := filepath.Join(c.Root, "secnews/data/daily_summaries", time.Now().UTC().Format("2006-01-02")+".json") + if test.want == 0 { + if err == nil { + t.Fatal("missing or invalid score was turned into a recorded priority") + } + if _, err := os.Stat(file); !os.IsNotExist(err) { + t.Fatal("invalid summary was persisted", err) + } + return + } + if err != nil { + t.Fatal(err) + } + articles, err := (&catalog.Catalog{Root: c.Root}).News(time.Now().UTC().Format("2006-01-02")) + if err != nil || len(articles) != 1 || articles[0]["recommendation_score"] != float64(test.want) { + t.Fatal("valid model score was changed or lost", articles, err) + } + }) + } +} diff --git a/internal/jobs/news.go b/internal/jobs/news.go index 3b94334..1727983 100644 --- a/internal/jobs/news.go +++ b/internal/jobs/news.go @@ -288,7 +288,7 @@ func (p *Pipeline) Daily(ctx context.Context, day string) error { var summary struct { Title string `json:"title_zh"` Summary string `json:"summary_zh"` - Score int `json:"recommendation_score"` + Score *int `json:"recommendation_score"` Channel string `json:"channel"` } if e = p.AI.Complete(ctx, `你是安全与AI资讯编辑。保留事实,勿编造。返回JSON {"title_zh":"中文标题","summary_zh":"150字以内中文导读","recommendation_score":1到10的重要性整数,"channel":"security或ai"}。`, string(b), &summary); e != nil { @@ -297,9 +297,12 @@ func (p *Pipeline) Daily(ctx context.Context, day string) error { if summary.Title == "" || summary.Summary == "" { return fmt.Errorf("empty article summary") } + if summary.Score == nil || *summary.Score < 1 || *summary.Score > 10 { + return fmt.Errorf("recommendation_score must be an integer from 1 to 10") + } v["title_zh"] = summary.Title v["summary_zh"] = summary.Summary - v["recommendation_score"] = max(1, min(10, summary.Score)) + v["recommendation_score"] = *summary.Score v["channel"] = summary.Channel v["source_hash"] = hash out = append(out, v) diff --git a/web/src/pages/News.tsx b/web/src/pages/News.tsx index 7496f20..79c4332 100644 --- a/web/src/pages/News.tsx +++ b/web/src/pages/News.tsx @@ -25,22 +25,12 @@ function channel(a: NewsArticle) { } function score(a: NewsArticle) { const provided = a.recommendation_score ?? a.importance ?? a.score - if (provided !== undefined && Number.isFinite(provided)) - return Math.max(0, Math.min(10, provided)) - const text = [a.title, a.title_zh, a.summary_zh, a.description].join(' ').toLowerCase() - let value = channel(a) === 'bleepingcomputer' ? 4.6 : 4.2 - for (const term of [ - 'zero-day', - '0-day', - 'actively exploited', - 'vulnerability', - 'ransomware', - 'prompt injection', - 'jailbreak', - ]) - if (text.includes(term)) - value += ['zero-day', '0-day', 'actively exploited'].includes(term) ? 2 : 0.7 - return Math.min(10, value) + return typeof provided === 'number' && + Number.isFinite(provided) && + provided >= 0 && + provided <= 10 + ? provided + : null } export default function News() { const { catalog } = useApp() @@ -184,14 +174,20 @@ export default function News() { .filter((a) => board === 'top' ? kind === 'all' || channel(a) === kind : channel(a) === board, ) - .sort((a, b) => score(b) - score(a)) + .sort( + (a, b) => + (score(b) ?? -1) - (score(a) ?? -1) || + (Date.parse(b.published || '') || 0) - (Date.parse(a.published || '') || 0), + ) + const scored = sorted.filter((article) => score(article) !== null) + const prioritised = !showAll && scored.length ? scored : sorted return ( - {(showAll ? sorted : sorted.slice(0, 10)).map((a, i) => ( + {(showAll ? prioritised : prioritised.slice(0, 10)).map((a, i) => (
- 价值 {score(a).toFixed(1)} + + {score(a) === null ? '尚未评分' : `价值 ${score(a)!.toFixed(1)}`} + {a.published?.slice(0, 10)} {a.author && {a.author}}
))} - {!showAll && sorted.length > 10 && ( + {!showAll && prioritised.length > 10 && ( )} {sorted.length === 0 && } diff --git a/web/tests/workspace.spec.ts b/web/tests/workspace.spec.ts index 3b76135..19dd1fb 100644 --- a/web/tests/workspace.spec.ts +++ b/web/tests/workspace.spec.ts @@ -1,4 +1,5 @@ import { test, expect, type Page } from '@playwright/test' +import type { NewsArticle } from '../src/types' const route = (baseURL: string | undefined, p: string) => new URL(p.replace(/^\//, ''), baseURL!.replace(/\/?$/, '/')).href test('conference panorama uses the full selected corpus instead of a saved personal topic', async ({ @@ -463,3 +464,56 @@ test('paper filters survive reload and global search updates an already-open pap await expect(page.getByLabel('会议', { exact: true })).toHaveValue('') await expect(page.getByTestId('paper-row').first()).toBeVisible() }) + +test('news recommendations use stored scores and show unscored records honestly', async ({ + page, + baseURL, +}) => { + const catalog = await (await page.request.get(route(baseURL, 'api/catalog'))).json() + let date = '' + let articles: NewsArticle[] = [] + const storedScore = (article: NewsArticle) => + article.recommendation_score ?? article.importance ?? article.score + const hasScore = (article: NewsArticle) => { + const score = storedScore(article) + return typeof score === 'number' && Number.isFinite(score) && score >= 0 && score <= 10 + } + for (const candidate of catalog.dates) { + const response = await ( + await page.request.get(route(baseURL, `api/news?date=${candidate}`)) + ).json() + const news: NewsArticle[] = response.articles.filter( + (article: NewsArticle) => !article.source.toLowerCase().includes('arxiv'), + ) + if (news.some((article) => !hasScore(article))) { + date = candidate + articles = news + break + } + } + expect(date).not.toBe('') + await visit(page, baseURL, `secnews/?date=${date}`) + const scored = articles.filter(hasScore) + await expect(page.getByTestId('news-row')).toHaveCount( + Math.min(10, scored.length || articles.length), + ) + if (scored.length) { + for (const row of await page.getByTestId('news-row').all()) { + const link = await row.locator('h3 a').getAttribute('href') + expect(scored.some((article) => article.link === link)).toBeTruthy() + } + } + await page.getByRole('button', { name: '查看全部详情', exact: true }).click() + await expect(page.getByTestId('news-row')).toHaveCount(articles.length) + for (const row of await page.getByTestId('news-row').all()) { + const link = await row.locator('h3 a').getAttribute('href') + const article = articles.find((article) => article.link === link)! + expect(article).toBeTruthy() + if (hasScore(article)) { + await expect(row).toContainText(`价值 ${storedScore(article)!.toFixed(1)}`) + } else { + await expect(row).toContainText('尚未评分') + await expect(row).not.toContainText(/价值 \d/) + } + } +})