Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions cmd/fastnews/news_sources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<rss><channel><item><guid>score-contract</guid><title>Security study</title><link>https://news.example/study</link><description>Observed facts</description></item></channel></rss>`)
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)
}
})
}
}
7 changes: 5 additions & 2 deletions internal/jobs/news.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
42 changes: 20 additions & 22 deletions web/src/pages/News.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 (
<InspectorSection
key={board}
open
label={`${board === 'top' ? '优先推荐 · Top 10' : board === 'bleepingcomputer' ? 'BleepingComputer' : '其他来源'} · ${sorted.length} 条`}
label={`${board === 'top' ? (scored.length ? '优先推荐 · Top 10' : '最新资讯 · 尚未评分') : board === 'bleepingcomputer' ? 'BleepingComputer' : '其他来源'} · ${prioritised.length} 条`}
>
{(showAll ? sorted : sorted.slice(0, 10)).map((a, i) => (
{(showAll ? prioritised : prioritised.slice(0, 10)).map((a, i) => (
<article
data-testid="news-row"
className="flex gap-3 p-4 border-b border-b-solid border-b-[var(--fastui-border)]"
Expand Down Expand Up @@ -225,16 +221,18 @@ export default function News() {
? 'BleepingComputer'
: sourceLabels[a.source] || '其他来源'}
</Badge>
<span title={a.score_reason}>价值 {score(a).toFixed(1)}</span>
<span title={a.score_reason}>
{score(a) === null ? '尚未评分' : `价值 ${score(a)!.toFixed(1)}`}
</span>
<span>{a.published?.slice(0, 10)}</span>
{a.author && <span>{a.author}</span>}
</div>
</div>
</article>
))}
{!showAll && sorted.length > 10 && (
{!showAll && prioritised.length > 10 && (
<Button className="m-3" onClick={() => setShowAll(true)}>
展开剩余 {sorted.length - 10} 条
展开全部 {sorted.length} 条资讯
</Button>
)}
{sorted.length === 0 && <EmptyState title="该频道当天暂无资讯" />}
Expand Down
54 changes: 54 additions & 0 deletions web/tests/workspace.spec.ts
Original file line number Diff line number Diff line change
@@ -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 ({
Expand Down Expand Up @@ -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/)
}
}
})
Loading