diff --git a/README.md b/README.md index 647414f..7b1bcb4 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,18 @@ The application is written in TypeScript for Bun. It has no third-party runtime configuration, feed parsing, CLI handling, web serving, streaming, and tests all use repository code, Web APIs, or Bun and Node-compatible built-ins. +## See Distil in action + +Collect recent items, review every relevance decision, then generate a focused Markdown +digest. Include and Exclude choices remain reversible until generation starts. + +[![Distil's three-step workflow with collection activity and source-level review summaries](assets/screenshots/workflow.png)](assets/screenshots/workflow.png) + +

+ Distil's generation step showing a saved Markdown research digest + The key takeaways section of a Distil research digest +

+ ## Requirements - [Bun 1.4.3 or newer](https://bun.sh/docs/installation) @@ -139,9 +151,14 @@ Then enable its loopback endpoint: [decision] enabled = true base_url = "http://127.0.0.1:8000" - confidence_threshold = 0.9 + confidence_threshold = 0.85 timeout_seconds = 10 +The default threshold of `0.85` accepts common high-confidence decisions while leaving +less certain items for review. Raise it toward `1` for stricter manual oversight or lower +it cautiously to automate more decisions. Existing explicit configuration values are not +changed automatically. + Distil accepts a Strands include or exclude classification only when it meets the configured confidence threshold. The preview labels those results **Include** or **Exclude**, previously processed items **Seen**, and lower-confidence results **Review**. @@ -161,8 +178,9 @@ Preview selection without calling the generative LLM: bun run distil preview --days 7 The web UI offers Include and Exclude controls beside every unresolved item, plus explicit -bulk controls. CLI `run` stops when review is required; after inspecting `preview`, opt in -to a deterministic bulk decision when appropriate: +bulk controls. Every settled item can be changed from Include to Exclude or back again +until generation starts. CLI `run` stops when review is required; after inspecting +`preview`, opt in to a deterministic bulk decision when appropriate: bun run distil run --review-policy=include bun run distil run --review-policy=exclude diff --git a/assets/screenshots/generated-digest.png b/assets/screenshots/generated-digest.png new file mode 100644 index 0000000..480e0a1 Binary files /dev/null and b/assets/screenshots/generated-digest.png differ diff --git a/assets/screenshots/key-takeaways.png b/assets/screenshots/key-takeaways.png new file mode 100644 index 0000000..cc21f7c Binary files /dev/null and b/assets/screenshots/key-takeaways.png differ diff --git a/assets/screenshots/workflow.png b/assets/screenshots/workflow.png new file mode 100644 index 0000000..1730d6f Binary files /dev/null and b/assets/screenshots/workflow.png differ diff --git a/config.toml b/config.toml index c4238a4..6b12d69 100644 --- a/config.toml +++ b/config.toml @@ -9,7 +9,7 @@ retries = 2 [decision] enabled = true base_url = "http://127.0.0.1:8000" -confidence_threshold = 0.9 +confidence_threshold = 0.85 timeout_seconds = 10 [output] diff --git a/src/config.ts b/src/config.ts index 08bf307..cdb654d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -11,6 +11,7 @@ type TomlValue = string | number | boolean | TomlValue[] | TomlTable; const DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434/v1"; const DEFAULT_OPENAI_URL = "https://api.mistral.ai/v1"; const DEFAULT_DECISION_URL = "http://127.0.0.1:8000"; +const DEFAULT_DECISION_CONFIDENCE = 0.85; export interface EditableConfig { llm: { @@ -82,7 +83,7 @@ export function setupConfig(): Config { decision: { enabled: false, baseUrl: DEFAULT_DECISION_URL, - confidenceThreshold: 0.9, + confidenceThreshold: DEFAULT_DECISION_CONFIDENCE, timeoutMs: 10_000, }, output: { directory: "~/distils", readingTimeMinutes: 5 }, @@ -355,7 +356,7 @@ export function normalizeConfig(raw: TomlTable): Config { baseUrl: decisionBaseUrl, confidenceThreshold: boundedNumber( decisionRaw.confidence_threshold, - 0.9, + DEFAULT_DECISION_CONFIDENCE, 0, 1, "decision.confidence_threshold", diff --git a/src/selection.ts b/src/selection.ts index a9625bc..6878dee 100644 --- a/src/selection.ts +++ b/src/selection.ts @@ -207,14 +207,18 @@ export function unresolvedSelections(result: SelectionResult): ItemSelection[] { return result.items.filter(isPendingSelection); } -export function resolvePendingSelection( +export function resolveSelection( result: SelectionResult, fingerprint: string, policy: ReviewPolicy, ): SelectionResult { const target = result.items.find((selection) => selection.fingerprint === fingerprint); if (!target) throw new Error("Unknown selection fingerprint"); - if (!isPendingSelection(target)) throw new Error("Selection does not require review"); + if (target.kind === "seen") { + throw new Error( + "Seen items must be recollected with Include seen before changing them", + ); + } return resolvedResult( result, result.items.map((selection) => @@ -376,11 +380,18 @@ function manualResolution( source: "user review" | "explicit bulk review", ): ItemSelection { const included = policy === "include"; + const evidence = + selection.kind === "manual" + ? selection.reason.replace( + /^(?:Included|Excluded) by (?:user review|explicit bulk review)\. /, + "", + ) + : selection.reason; return { ...selection, selected: included, kind: "manual", - reason: `${included ? "Included" : "Excluded"} by ${source}. ${selection.reason}`, + reason: `${included ? "Included" : "Excluded"} by ${source}. ${evidence}`, }; } diff --git a/src/web.ts b/src/web.ts index b61c10a..669cd73 100644 --- a/src/web.ts +++ b/src/web.ts @@ -7,7 +7,7 @@ import { streamDistil } from "./prompts.ts"; import { ContentSelector, resolveAllPending, - resolvePendingSelection, + resolveSelection, type SelectionKind, type SelectionPipeline, type SelectionResult, @@ -404,6 +404,12 @@ export class DistilWebApp { if (job?.status !== "complete" || !job.collection || !this.#cachedSelection) { return json({ error: "No completed fetch is available for review" }, 409); } + if (this.#generationInProgress) { + return json( + { error: "The selection cannot change while generation is running" }, + 409, + ); + } let resolution: SelectionResolution; try { @@ -416,7 +422,7 @@ export class DistilWebApp { const policy = resolution.selected ? "include" : "exclude"; const selection = resolution.all ? resolveAllPending(this.#cachedSelection, policy) - : resolvePendingSelection(this.#cachedSelection, resolution.fingerprint, policy); + : resolveSelection(this.#cachedSelection, resolution.fingerprint, policy); this.#cachedSelection = selection; this.#cachedItems = selection.selected; job.result = fetchPayload(job.collection, selection); diff --git a/src/web_ui.ts b/src/web_ui.ts index 0c95773..a09e2e5 100644 --- a/src/web_ui.ts +++ b/src/web_ui.ts @@ -44,7 +44,7 @@ export function homePage( '
    ', "", '
    ', - '

    Step 2

    Review the selection

    Check what will shape the digest and resolve any uncertain items.

    ', + '

    Step 2

    Review the selection

    Check what will shape the digest. You can change any included or excluded item before generating.

    ', '

    Collect items to begin reviewing.

    ', '
    ", @@ -563,6 +563,9 @@ const CSS = String.raw` .field-grid { display:grid; gap:1rem; margin-top:1rem; } .field-grid.two { grid-template-columns:repeat(2,minmax(0,1fr)); } .field-grid.three { grid-template-columns:repeat(3,minmax(0,1fr)); } + .field-grid > label { display:flex; flex-direction:column; gap:.35rem; } + .field-grid > label > input,.field-grid > label > select, + .field-grid > label > textarea { margin-top:auto; } .hint { display:block; color:var(--muted); font-size:.78rem; font-weight:400; } .field-help { margin:.5rem 0 0; color:var(--muted); font-size:.9rem; } .advanced { margin-top:1rem; padding:.75rem 0 0; } @@ -842,8 +845,7 @@ const HOME_SCRIPT = String.raw` setWorkflowStep("collect", "current", "Collect again"); setWorkflowStep("review", "complete", "No items included"); setWorkflowStep("generate", "blocked", "No included items"); - generateStatus.textContent = - "No items are included. Adjust the collection and fetch again."; + generateStatus.textContent = "No items are included. Include one to continue."; } return; } @@ -986,13 +988,24 @@ const HOME_SCRIPT = String.raw` if (meta.childNodes.length > 0) content.append(meta); content.append(reason); row.append(tag, content); - if (item.kind === "review" || item.kind === "fallback") { + if (item.kind !== "seen") { const actions = document.createElement("div"); actions.className = "decision-actions"; - actions.append( - reviewButton("Include", item.title, item.fingerprint, true), - reviewButton("Exclude", item.title, item.fingerprint, false), - ); + if (item.kind === "review" || item.kind === "fallback") { + actions.append( + reviewButton("Include", item.title, item.fingerprint, true), + reviewButton("Exclude", item.title, item.fingerprint, false), + ); + } else { + actions.append( + reviewButton( + item.selected ? "Exclude instead" : "Include instead", + item.title, + item.fingerprint, + !item.selected, + ), + ); + } row.append(actions); } list.append(row); @@ -1072,6 +1085,7 @@ const HOME_SCRIPT = String.raw` generateButton.addEventListener("click", async () => { generateButton.disabled = true; generateButton.textContent = "Generating…"; + setReviewControlsDisabled(true); generatePanel.setAttribute("aria-busy", "true"); setWorkflowStep("generate", "current", "Generating digest"); let completed = false; @@ -1112,6 +1126,7 @@ const HOME_SCRIPT = String.raw` generatePanel.setAttribute("aria-busy", "false"); generateButton.disabled = completed; generateButton.textContent = "Generate digest"; + if (!completed) setReviewControlsDisabled(false); } }); diff --git a/tests/config_test.ts b/tests/config_test.ts index efed5e8..a88bffe 100644 --- a/tests/config_test.ts +++ b/tests/config_test.ts @@ -41,6 +41,7 @@ test("parses and normalizes the existing TOML shape", () => { assertEquals(config.llm.retries, 3); assertEquals(config.decision.enabled, false); assertEquals(config.decision.baseUrl, "http://127.0.0.1:8000"); + assertEquals(config.decision.confidenceThreshold, 0.85); assertEquals(config.output.readingTimeMinutes, 7); assertEquals(config.feeds[0].keywords, ["drug", "protein"]); }); diff --git a/tests/selection_test.ts b/tests/selection_test.ts index f2187d4..d78ba56 100644 --- a/tests/selection_test.ts +++ b/tests/selection_test.ts @@ -6,7 +6,7 @@ import { FileSeenStore, itemFingerprint, resolveAllPending, - resolvePendingSelection, + resolveSelection, type SeenStore, unresolvedSelections, } from "../src/selection.ts"; @@ -81,12 +81,12 @@ test("selection skips seen items and trusts only confident Strands choices", asy assertEquals(progress.at(-1)?.completed, 4); assertMatch(progress.at(-1)?.message ?? "", /top choice was exclude/); - await assertRejects(() => selector.markReviewed(result), /1 unresolved item/); - const resolved = resolvePendingSelection( - result, - result.items[3].fingerprint, - "include", + await assertRejects( + () => resolveSelection(result, result.items[0].fingerprint, "include"), + /Include seen/, ); + await assertRejects(() => selector.markReviewed(result), /1 unresolved item/); + const resolved = resolveSelection(result, result.items[3].fingerprint, "include"); assertEquals(resolved.items[3].kind, "manual"); assertEquals(resolved.items[3].selected, true); assertMatch(resolved.items[3].reason, /^Included by user review\./); @@ -151,7 +151,7 @@ test("selection requires review when the local decision service is unavailable", assertMatch(resolved.items[0].reason, /^Excluded by explicit bulk review\./); }); -test("selection resolution rejects unknown and final decisions", async () => { +test("selection decisions can be reversed while preserving their evidence", async () => { const decisions = new FakeDecisionClient(); decisions.verdicts = [{ choice: "include", confidence: 0.95 }]; const selector = new ContentSelector(config, "research", { @@ -160,13 +160,21 @@ test("selection resolution rejects unknown and final decisions", async () => { }); const result = await selector.select([item(1)]); - await assertRejects( - () => resolvePendingSelection(result, "missing", "include"), - /Unknown selection fingerprint/, + await assertRejects(() => resolveSelection(result, "missing", "include"), /Unknown/); + + const excluded = resolveSelection(result, result.items[0].fingerprint, "exclude"); + assertEquals(excluded.items[0].kind, "manual"); + assertEquals(excluded.items[0].selected, false); + assertEquals( + excluded.items[0].reason, + "Excluded by user review. Strands chose include with 95% confidence in its relevance classification", ); - await assertRejects( - () => resolvePendingSelection(result, result.items[0].fingerprint, "exclude"), - /does not require review/, + + const included = resolveSelection(excluded, result.items[0].fingerprint, "include"); + assertEquals(included.items[0].selected, true); + assertEquals( + included.items[0].reason, + "Included by user review. Strands chose include with 95% confidence in its relevance classification", ); }); diff --git a/tests/web_test.ts b/tests/web_test.ts index 38b0776..aafa356 100644 --- a/tests/web_test.ts +++ b/tests/web_test.ts @@ -34,6 +34,21 @@ class WebClient implements ChatClient { } } +class PausedWebClient implements ChatClient { + complete(): Promise { + return Promise.resolve("summary"); + } + + async *stream(_messages: ChatMessage[], signal?: AbortSignal): AsyncIterable { + await new Promise((resolve) => { + if (signal?.aborted) resolve(); + else signal?.addEventListener("abort", () => resolve(), { once: true }); + }); + signal?.throwIfAborted(); + yield ""; + } +} + class WebSelector implements SelectionPipeline { marked = 0; @@ -267,11 +282,22 @@ test("web requires explicit resolution of uncertain selections", async () => { assertEquals(includedState.result.items[0].kind, "manual"); assertMatch(includedState.result.items[0].reason, /^Included by user review\./); - const duplicate = await resolveSelection(app, { + const changedToExcluded = await resolveSelection(app, { fingerprint: "a".repeat(64), selected: false, }); - assertEquals(duplicate.status, 409); + assertEquals(changedToExcluded.status, 200); + const excludedState = await changedToExcluded.json(); + assertEquals(excludedState.result.itemCount, 0); + assertMatch(excludedState.result.items[0].reason, /^Excluded by user review\./); + assertEquals(excludedState.result.items[0].reason.includes("Included by"), false); + + const changedBackToIncluded = await resolveSelection(app, { + fingerprint: "a".repeat(64), + selected: true, + }); + assertEquals(changedBackToIncluded.status, 200); + assertEquals((await changedBackToIncluded.json()).result.itemCount, 1); const excluded = await resolveSelection(app, { all: true, selected: false }); assertEquals(excluded.status, 200); @@ -297,6 +323,35 @@ test("web requires explicit resolution of uncertain selections", async () => { } }); +test("web locks selection changes while generation is running", async () => { + const app = new DistilWebApp({ + config: testConfig(), + client: new PausedWebClient(), + selector: new WebSelector(), + collect: () => + Promise.resolve({ + items: [testItem()], + health: {}, + }), + }); + + await app.handler(new Request("http://localhost/api/fetch", { method: "POST" })); + await completedFetch(app); + const generation = await app.handler( + new Request("http://localhost/api/generate", { method: "POST" }), + ); + assertEquals(generation.status, 200); + + const change = await resolveSelection(app, { + fingerprint: "a".repeat(64), + selected: false, + }); + assertEquals(change.status, 409); + assertMatch((await change.json()).error, /generation is running/); + + await generation.body?.cancel(); +}); + test("web validates days and confines history paths", async () => { const app = new DistilWebApp({ config: testConfig(), @@ -399,6 +454,12 @@ test("web settings recover first-run setup and apply a validated configuration", assertMatch(settingsHtml, /Add another source/); assertMatch(settingsHtml, /The key itself is never saved/); assertMatch(settingsHtml, /Service URL loopback only<\/span>/); + assertMatch(settingsHtml, /id="confidence"[^>]+value="0\.85"/); + assertMatch( + settingsHtml, + /\.field-grid > label \{ display:flex; flex-direction:column; gap:\.35rem; \}/, + ); + assertMatch(settingsHtml, /\.field-grid > label > textarea \{ margin-top:auto; \}/); assertMatch( settingsHtml, /\.switch-row input \{ flex:0 0 1rem; width:1rem; height:1rem; min-height:1rem;\s+margin:\.25rem 0 0; padding:0;/, @@ -488,6 +549,11 @@ test("home page includes security headers and accessible controls", async () => assertMatch(content, /generateProgress\.hidden = true/); assertMatch(content, /Include all/); assertMatch(content, /Exclude all/); + assertMatch(content, /You can change any included or excluded item before generating/); + assertMatch(content, /item\.selected \? "Exclude instead" : "Include instead"/); + assertMatch(content, /if \(item\.kind !== "seen"\)/); + assertMatch(content, /setReviewControlsDisabled\(true\)/); + assertMatch(content, /if \(!completed\) setReviewControlsDisabled\(false\)/); assertMatch(content, /\/api\/fetch\/status/); assertMatch(content, /\/api\/fetch\/selection/); assertMatch(content, /details\[data-source\]\[open\]/); diff --git a/tsconfig.json b/tsconfig.json index 83501b3..87c149f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,5 +12,5 @@ "skipLibCheck": true, "types": [] }, - "include": ["src/**/*.ts", "tests/**/*.ts", "types/**/*.d.ts"] + "include": ["src/**/*.ts", "tests/**/*.ts", "scripts/**/*.ts", "types/**/*.d.ts"] }