diff --git a/apps/mobile/src/agent-ui.tsx b/apps/mobile/src/agent-ui.tsx index 4939c12c7..d43c9b29d 100644 --- a/apps/mobile/src/agent-ui.tsx +++ b/apps/mobile/src/agent-ui.tsx @@ -1545,13 +1545,15 @@ function MonitorForm({ onDone }: { onDone: () => void }) { )} Notify me when - {(["change", "contains", "price_below"] as const).map((item) => ( + {(["change", "contains", "price_below", "price_above"] as const).map((item) => ( ))} @@ -1630,7 +1632,9 @@ function MonitorCard({ monitor, onOpenTask }: { monitor: Monitor; onOpenTask?: ( ? "Watch for a page change" : monitor.condition === "contains" ? `Watch for “${monitor.value}”` - : `Price below ${monitor.value}`} + : monitor.condition === "price_below" + ? `Price below ${monitor.value}` + : `Price above ${monitor.value}`} Every {monitor.intervalMinutes} min · {monitor.checks} checks diff --git a/apps/server/src/engine/service.ts b/apps/server/src/engine/service.ts index 54684937f..f7ad1714d 100644 --- a/apps/server/src/engine/service.ts +++ b/apps/server/src/engine/service.ts @@ -1104,7 +1104,11 @@ export class AgentService { ? Boolean(previousHash && previousHash !== currentHash) : monitor.condition === "contains" ? text.toLowerCase().includes(wanted) - : this.matchesPrice(text, Number(monitor.value)); + : this.matchesPrice( + text, + Number(monitor.value), + monitor.condition === "price_above" ? "above" : "below", + ); const previouslyMatched = Boolean(task.state.matched); // For change watches, keep the page lines and a relative-time-free fingerprint of the whole text. const change = monitor.condition === "change"; @@ -1202,8 +1206,11 @@ export class AgentService { plan: task.plan.map((s) => ({ ...s, status: "succeeded" })), }; } - private matchesPrice(text: string, threshold: number) { + private matchesPrice(text: string, threshold: number, direction: "above" | "below") { const matches = [...text.matchAll(/(?:\$|USD)\s*(\d+(?:,\d{3})*(?:\.\d{1,2})?)/g)]; - return matches.some((m) => Number(m[1].replace(/,/g, "")) < threshold); + return matches.some((m) => { + const price = Number(m[1].replace(/,/g, "")); + return direction === "above" ? price > threshold : price < threshold; + }); } } diff --git a/packages/domain/src/agent.ts b/packages/domain/src/agent.ts index c2d869bda..2fdc011d7 100644 --- a/packages/domain/src/agent.ts +++ b/packages/domain/src/agent.ts @@ -69,7 +69,7 @@ export interface Monitor { taskId: string; title: string; url: string; - condition: "change" | "contains" | "price_below"; + condition: "change" | "contains" | "price_below" | "price_above"; value: string; intervalMinutes: number; status: "active" | "paused" | "stopped"; @@ -145,7 +145,7 @@ export const monitorInputSchema = z .object({ title: z.string().min(1).max(160), url: z.url().max(4096), - condition: z.enum(["change", "contains", "price_below"]).default("change"), + condition: z.enum(["change", "contains", "price_below", "price_above"]).default("change"), value: z.string().max(300).default(""), intervalMinutes: z.number().int().min(1).max(10080).default(15), }) @@ -153,7 +153,7 @@ export const monitorInputSchema = z if (v.condition !== "change" && !v.value.trim()) c.addIssue({ code: "custom", message: "Enter a condition value" }); if ( - v.condition === "price_below" && + (v.condition === "price_below" || v.condition === "price_above") && (!Number.isFinite(Number(v.value)) || Number(v.value) <= 0) ) c.addIssue({ code: "custom", message: "Enter a positive price" }); diff --git a/tests/agent-api.test.ts b/tests/agent-api.test.ts index 432730180..e56057355 100644 --- a/tests/agent-api.test.ts +++ b/tests/agent-api.test.ts @@ -158,6 +158,14 @@ test("agent request validation rejects malformed input with useful JSON errors", "/monitors", { title: "Price", url: "https://example.com", condition: "price_below", value: "bad" }, ], + [ + "/monitors", + { title: "Price", url: "https://example.com", condition: "price_above", value: "bad" }, + ], + [ + "/monitors", + { title: "Price", url: "https://example.com", condition: "price_above", value: "" }, + ], ["/monitors/missing/control", { action: "delete" }], ["/ideas/missing", { action: "accept", prompt: " " }], ["/memories", { text: " " }], diff --git a/tests/monitor-conditions.test.ts b/tests/monitor-conditions.test.ts new file mode 100644 index 000000000..961a6525e --- /dev/null +++ b/tests/monitor-conditions.test.ts @@ -0,0 +1,134 @@ +import assert from "node:assert/strict"; +import { type TestContext, test } from "node:test"; +import { createApp } from "../apps/server/src/app.ts"; +import type { Store } from "../apps/server/src/db.ts"; +import type { AgentNotification } from "../packages/domain/src/agent.ts"; +import { browserFixture } from "./helpers/browser.ts"; + +const page = { url: "https://example.com/product", title: "Product page" }; + +async function priceFixture(t: TestContext) { + let pageText = ""; + const fixture = await browserFixture(t, (path, body) => { + if (path.endsWith("/read")) + return { data: { url: page.url, title: page.title, text: pageText, truncated: false } }; + return { + data: { + id: body.id, + title: page.title, + url: page.url, + status: "active", + updatedAt: new Date().toISOString(), + }, + }; + }); + const server = await createApp(fixture.db, fixture.config); + t.after(() => server.agent.stop()); + return { ...fixture, ...server, setPrice: (text: string) => (pageText = text) }; +} + +async function requeue(db: Store, owner: string, taskId: string) { + await db.compareAndSwap( + owner, + "tasks", + taskId, + { status: "scheduled" }, + { nextRunAt: "2020-01-01T00:00:00Z" }, + ); +} + +test("a price_above watch alerts when the tracked price rises past the threshold, then stays quiet", async (t) => { + const owner = "monitor-price-above"; + const f = await priceFixture(t); + f.setPrice("In stock today. Price: $72.50, was $61.00."); + const monitor = await f.agent.createMonitor(owner, { + title: "Resale price watch", + url: page.url, + condition: "price_above", + value: "60", + }); + await f.agent.worker.tick(); + const task = await f.agent.getTask(owner, monitor.taskId); + assert.equal(task.status, "scheduled"); + assert.equal(task.state.matched, true); + const alerts = () => + f.db + .list(owner, "notifications") + .then((all) => all.filter((n) => n.taskId === monitor.taskId)); + assert.equal((await alerts()).length, 1); + assert.ok((await alerts())[0].body.includes("72.50")); + // A repeat observation above the threshold must not raise a duplicate alert. + await requeue(f.db, owner, monitor.taskId); + await f.agent.worker.tick(); + assert.equal((await alerts()).length, 1); + // Falling back below the threshold clears the matched state without alerting. + f.setPrice("In stock today. Price: $52.00."); + await requeue(f.db, owner, monitor.taskId); + await f.agent.worker.tick(); + const settled = await f.agent.getTask(owner, monitor.taskId); + assert.equal(settled.status, "scheduled"); + assert.equal(settled.state.matched, false); + assert.equal((await alerts()).length, 1); + // Rising back above the threshold starts a new matching episode, so it alerts again even though + // the page renders the same text the first alert was about. + f.setPrice("In stock today. Price: $72.50, was $61.00."); + await requeue(f.db, owner, monitor.taskId); + await f.agent.worker.tick(); + const recovered = await f.agent.getTask(owner, monitor.taskId); + assert.equal(recovered.state.matched, true); + assert.equal((await alerts()).length, 2); + assert.ok((await alerts())[1].body.includes("72.50")); +}); + +test("a watch publishes one alert per matching episode, however often the outcome is replayed", async (t) => { + const owner = "monitor-replay"; + const f = await priceFixture(t); + f.setPrice("In stock today. Price: $72.50, was $61.00."); + const monitor = await f.agent.createMonitor(owner, { + title: "Resale price watch", + url: page.url, + condition: "price_above", + value: "60", + }); + await f.agent.worker.tick(); + const task = await f.agent.getTask(owner, monitor.taskId); + const alerts = () => + f.db + .list(owner, "notifications") + .then((all) => all.filter((n) => n.taskId === monitor.taskId)); + const [first] = await alerts(); + assert.equal((await alerts()).length, 1); + // Maintenance re-publishes settled outcomes after a restart, and the worker retries a run that + // lost its lease, so the notice it replays has to keep resolving to the notification it raised. + const notice = task.state.notice as { title: string; body: string; key: string }; + await f.agent.notify(owner, notice.title, notice.body, monitor.taskId, notice.key); + const replayed = await alerts(); + assert.equal(replayed.length, 1); + assert.equal(replayed[0].id, first.id); + assert.equal(replayed[0].createdAt, first.createdAt); +}); + +test("a price_below watch alerts under the threshold and ignores higher prices", async (t) => { + const owner = "monitor-price-below"; + const f = await priceFixture(t); + f.setPrice("Deal of the day: $41.25."); + const monitor = await f.agent.createMonitor(owner, { + title: "Deal watch", + url: page.url, + condition: "price_below", + value: "60", + }); + await f.agent.worker.tick(); + const alerts = () => + f.db + .list(owner, "notifications") + .then((all) => all.filter((n) => n.taskId === monitor.taskId)); + assert.equal((await alerts()).length, 1); + assert.ok((await alerts())[0].body.includes("41.25")); + f.setPrice("Sold out. Price: $89.00."); + await requeue(f.db, owner, monitor.taskId); + await f.agent.worker.tick(); + const settled = await f.agent.getTask(owner, monitor.taskId); + assert.equal(settled.state.matched, false); + assert.equal((await alerts()).length, 1); +});