Skip to content

Commit 094e58a

Browse files
committed
feature: show what changed when a watched page changes
1 parent f5534c7 commit 094e58a

4 files changed

Lines changed: 233 additions & 4 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/** Lines of page text for comparing two checks of a watched page. */
2+
export function pageLines(text: string, limit = 2000): string[] {
3+
const lines = new Set<string>();
4+
for (const raw of text.split(/\r?\n/)) {
5+
const line = raw.replace(/\s+/g, " ").trim().slice(0, 300);
6+
if (line) lines.add(line);
7+
if (lines.size >= limit) break;
8+
}
9+
return [...lines];
10+
}
11+
12+
export type PageDiff = { added: string[]; updated: string[]; removed: string[] };
13+
14+
// Lines that differ only in numbers or relative times ("posted 1 day ago" → "posted 2 days
15+
// ago", "58 minutes ago" → "1 hour ago", "3 comments") are updates, not news.
16+
const relativeTime =
17+
/\b(?:\d+|an?|one)\s+(?:sec(?:ond)?|min(?:ute)?|hour|hr|day|week|month|year)s?\s+ago\b|\bvor\s+(?:\d+|einer?|einem)\s+(?:sekunde|minute|stunde|tag|woche|monat|jahr)(?:e|en|n)?\b/giu;
18+
const shape = (line: string) =>
19+
line
20+
.replace(relativeTime, "<time>")
21+
.replace(/\d+(?:[.,]\d+)*/g, "#")
22+
.replace(/(\p{L})s\b/gu, "$1")
23+
.toLowerCase();
24+
25+
/** Whether anything besides numbers and relative times changed. */
26+
export function meaningfulPageDiff(diff: PageDiff) {
27+
return diff.added.length > 0 || diff.removed.length > 0;
28+
}
29+
30+
export function diffPage(previous: string[], current: string[]): PageDiff {
31+
const before = new Set(previous);
32+
const after = new Set(current);
33+
const beforeShapes = new Set(previous.map(shape));
34+
const afterShapes = new Set(current.map(shape));
35+
const changed = current.filter((line) => !before.has(line));
36+
return {
37+
added: changed.filter((line) => !beforeShapes.has(shape(line))),
38+
updated: changed.filter((line) => beforeShapes.has(shape(line))),
39+
removed: previous.filter((line) => !after.has(line) && !afterShapes.has(shape(line))),
40+
};
41+
}
42+
43+
/** A short "New / Updated / Removed" summary, or "" when no line changed. */
44+
export function describePageDiff(diff: PageDiff) {
45+
const section = (title: string, lines: string[], limit: number) => {
46+
if (!lines.length) return [];
47+
const shown = lines.slice(0, limit).map((line) => `• ${line.slice(0, 160)}`);
48+
const more = lines.length > limit ? [`+${lines.length - limit} more`] : [];
49+
return [`${title}:`, ...shown, ...more];
50+
};
51+
return [
52+
...section("New", diff.added, 8),
53+
...section("Updated", diff.updated, 4),
54+
...section("Removed", diff.removed, 4),
55+
].join("\n");
56+
}
57+
58+
/** A one-line count for task results, such as "3 lines changed (2 new, 1 updated)". */
59+
export function countPageDiff(diff: PageDiff) {
60+
const total = diff.added.length + diff.updated.length + diff.removed.length;
61+
if (!total) return "";
62+
const parts = [
63+
diff.added.length && `${diff.added.length} new`,
64+
diff.updated.length && `${diff.updated.length} updated`,
65+
diff.removed.length && `${diff.removed.length} removed`,
66+
].filter(Boolean);
67+
return `${total} line${total === 1 ? "" : "s"} changed (${parts.join(", ")})`;
68+
}

‎apps/server/src/engine/service.ts‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ import { backgroundFailure } from "../log.ts";
3434
import type { WorkspaceService } from "../workspace.ts";
3535
import { analyzeSpending } from "./finance.ts";
3636
import { executeModelTask } from "./model.ts";
37+
import {
38+
countPageDiff,
39+
describePageDiff,
40+
diffPage,
41+
meaningfulPageDiff,
42+
pageLines,
43+
} from "./page-diff.ts";
3744
import { LostLeaseError, type TaskContext, TaskWorker } from "./worker.ts";
3845

3946
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
@@ -933,7 +940,18 @@ export class AgentService {
933940
? text.toLowerCase().includes(monitor.value.toLowerCase())
934941
: this.matchesPrice(text, Number(monitor.value));
935942
const previouslyMatched = Boolean(task.state.matched);
936-
const shouldNotify = matched && (monitor.condition === "change" || !previouslyMatched);
943+
// For change watches, compare the page line by line with the previous check.
944+
const lines = monitor.condition === "change" ? pageLines(observation.text) : [];
945+
const previousPage =
946+
matched && monitor.condition === "change"
947+
? await this.db.get<{ lines: string[] }>(owner, "monitor-pages", monitor.id)
948+
: null;
949+
const diff = previousPage ? diffPage(previousPage.lines, lines) : undefined;
950+
// Only numbers or relative times changed ("3 minutes ago"): keep watching quietly.
951+
const quiet = Boolean(diff && !meaningfulPageDiff(diff));
952+
const shouldNotify =
953+
matched && !quiet && (monitor.condition === "change" || !previouslyMatched);
954+
const changes = diff && shouldNotify ? describePageDiff(diff) : "";
937955
const nextCheckAt = new Date(Date.now() + monitor.intervalMinutes * 60000).toISOString();
938956
await ctx.guard();
939957
// Worker lease is checked before each publication; monitor control also invalidates that lease.
@@ -952,20 +970,25 @@ export class AgentService {
952970
},
953971
);
954972
if (!savedMonitor) throw new LostLeaseError();
973+
if (monitor.condition === "change")
974+
await this.db.put(owner, "monitor-pages", { id: monitor.id, lines });
955975
await ctx.event(
956976
"observation",
957977
previousHash ? "Checked for changes" : "Saved the first observation",
958978
text.slice(0, 1000),
959979
);
960980
if (shouldNotify) {
961981
await ctx.guard();
962-
await ctx.event("result", "A meaningful change was found", text.slice(0, 500));
982+
await ctx.event("result", "A meaningful change was found", changes || text.slice(0, 500));
963983
}
984+
const count = diff ? countPageDiff(diff) : "";
964985
return {
965986
status: "scheduled",
966987
nextRunAt: nextCheckAt,
967988
result: shouldNotify
968-
? "Change found. A notification is ready."
989+
? count
990+
? `Change found: ${count}. A notification is ready.`
991+
: "Change found. A notification is ready."
969992
: "Watching. I'll check again on schedule.",
970993
state: {
971994
...task.state,
@@ -975,7 +998,9 @@ export class AgentService {
975998
notice: shouldNotify
976999
? {
9771000
title: monitor.title,
978-
body: `Condition met at ${observation.url}: ${text.slice(0, 240)}`,
1001+
body: changes
1002+
? `Changed at ${observation.url}\n${changes}`
1003+
: `Condition met at ${observation.url}: ${text.slice(0, 240)}`,
9791004
key: `monitor:${monitor.id}:${currentHash}`,
9801005
}
9811006
: null,

‎tests/agent-api.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,3 +344,69 @@ test("live mode rejects sample sources and hides the fixture mutation endpoint",
344344
await live.agent.stop();
345345
}
346346
});
347+
348+
test("a change watch alert lists the new and updated lines of the page", async () => {
349+
await read("/sample-page", {
350+
text: "AI jobs in Munich\nSiemens · Werkstudent AI · posted 1 day ago\nBCG · Intern",
351+
});
352+
const monitor = await read<Monitor>(
353+
"/monitors",
354+
{
355+
title: "Munich AI jobs",
356+
url: "sample://availability",
357+
condition: "change",
358+
intervalMinutes: 1,
359+
},
360+
201,
361+
);
362+
await server.agent.worker.tick();
363+
await read("/sample-page", {
364+
text: "AI jobs in Munich\nSAP · Working Student AI Engineer\nSiemens · Werkstudent AI · posted 2 days ago\nBCG · Intern",
365+
});
366+
await read(`/monitors/${monitor.id}/control`, { action: "check" });
367+
await server.agent.worker.tick();
368+
const [alert] = (await read<AgentNotification[]>("/notifications")).filter(
369+
(item) => item.taskId === monitor.taskId,
370+
);
371+
assert.equal(
372+
alert?.body,
373+
"Changed at sample://availability\nNew:\n• SAP · Working Student AI Engineer\nUpdated:\n• Siemens · Werkstudent AI · posted 2 days ago",
374+
);
375+
const { task } = await read<{ task: AgentTask }>(`/tasks/${monitor.taskId}`);
376+
assert.equal(
377+
task.result,
378+
"Change found: 2 lines changed (1 new, 1 updated). A notification is ready.",
379+
);
380+
await read(`/monitors/${monitor.id}/control`, { action: "stop" });
381+
});
382+
383+
test("a change watch stays quiet when only numbers and relative times change", async () => {
384+
await read("/sample-page", { text: "Jobs\nSiemens · Werkstudent AI · 3 minutes ago" });
385+
const monitor = await read<Monitor>(
386+
"/monitors",
387+
{ title: "Quiet jobs", url: "sample://availability", condition: "change", intervalMinutes: 1 },
388+
201,
389+
);
390+
const alerts = async () =>
391+
(await read<AgentNotification[]>("/notifications")).filter(
392+
(item) => item.taskId === monitor.taskId,
393+
);
394+
await server.agent.worker.tick();
395+
for (const text of [
396+
"Jobs\nSiemens · Werkstudent AI · 58 minutes ago",
397+
"Jobs\nSiemens · Werkstudent AI · 1 hour ago",
398+
]) {
399+
await read("/sample-page", { text });
400+
await read(`/monitors/${monitor.id}/control`, { action: "check" });
401+
await server.agent.worker.tick();
402+
}
403+
assert.equal((await alerts()).length, 0, "ticking timestamps are not news");
404+
await read("/sample-page", {
405+
text: "Jobs\nSAP · Working Student AI\nSiemens · Werkstudent AI · 2 hours ago",
406+
});
407+
await read(`/monitors/${monitor.id}/control`, { action: "check" });
408+
await server.agent.worker.tick();
409+
const [alert] = await alerts();
410+
assert.match(alert?.body ?? "", /New:\n• SAP · Working Student AI/);
411+
await read(`/monitors/${monitor.id}/control`, { action: "stop" });
412+
});

‎tests/page-diff.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import assert from "node:assert/strict";
2+
import { test } from "node:test";
3+
import {
4+
countPageDiff,
5+
describePageDiff,
6+
diffPage,
7+
meaningfulPageDiff,
8+
pageLines,
9+
} from "../apps/server/src/engine/page-diff.ts";
10+
11+
test("page lines are trimmed, collapsed, deduplicated and bounded", () => {
12+
assert.deepEqual(pageLines(" Jobs \n\n Siemens AI\r\nSiemens AI\n"), ["Jobs", "Siemens AI"]);
13+
assert.equal(pageLines("a\nb\nc", 2).length, 2);
14+
assert.equal(pageLines("x".repeat(500))[0].length, 300);
15+
});
16+
17+
test("new lines are separated from lines where only a number changed", () => {
18+
const before = [
19+
"AI jobs in Munich",
20+
"Siemens · Werkstudent AI · posted 1 day ago",
21+
"BCG · Intern",
22+
];
23+
const after = [
24+
"AI jobs in Munich",
25+
"SAP · Working Student AI Engineer",
26+
"Siemens · Werkstudent AI · posted 2 days ago",
27+
];
28+
assert.deepEqual(diffPage(before, after), {
29+
added: ["SAP · Working Student AI Engineer"],
30+
updated: ["Siemens · Werkstudent AI · posted 2 days ago"],
31+
removed: ["BCG · Intern"],
32+
});
33+
assert.deepEqual(diffPage(before, before), { added: [], updated: [], removed: [] });
34+
});
35+
36+
test("the change summary lists sections, clips long lists, and counts lines", () => {
37+
const diff = {
38+
added: Array.from({ length: 10 }, (_, i) => `Role ${i}`),
39+
updated: ["Price $12"],
40+
removed: [],
41+
};
42+
const text = describePageDiff(diff);
43+
assert.match(text, /^New:\n• Role 0\n/);
44+
assert.match(text, /\+2 more\nUpdated:\n• Price \$12$/);
45+
assert.doesNotMatch(text, /Removed/);
46+
assert.equal(countPageDiff(diff), "11 lines changed (10 new, 1 updated)");
47+
assert.equal(countPageDiff({ added: ["a"], updated: [], removed: [] }), "1 line changed (1 new)");
48+
assert.equal(describePageDiff({ added: [], updated: [], removed: [] }), "");
49+
assert.equal(countPageDiff({ added: [], updated: [], removed: [] }), "");
50+
});
51+
52+
test("relative times count as updates, and only new or removed lines are meaningful", () => {
53+
const before = [
54+
"3 points by ada 58 minutes ago | hide",
55+
"Vor 2 Stunden veröffentlicht",
56+
"Show HN: A new tool",
57+
];
58+
const after = [
59+
"3 points by ada 1 hour ago | hide",
60+
"Vor einer Stunde veröffentlicht",
61+
"Show HN: A new tool",
62+
];
63+
const timesOnly = diffPage(before, after);
64+
assert.deepEqual(timesOnly.added, []);
65+
assert.deepEqual(timesOnly.removed, []);
66+
assert.equal(timesOnly.updated.length, 2);
67+
assert.equal(meaningfulPageDiff(timesOnly), false);
68+
assert.equal(meaningfulPageDiff(diffPage(before, [...after, "Ask HN: Another post"])), true);
69+
assert.equal(meaningfulPageDiff(diffPage(before, after.slice(0, 2))), true);
70+
});

0 commit comments

Comments
 (0)