From 9c8c116b6be2f9e8b6b65b690af5d44427613821 Mon Sep 17 00:00:00 2001
From: sickerine
Date: Sat, 28 Nov 2026 14:00:03 +0000
Subject: [PATCH 1/3] fix(screening): production pass round 1, what the council
and seven walkers found
Data kept and shown right:
- A rule change that asked for fewer people could mark one closed place both
removed and reopened, and the paper's bookkeeping then rolled back its whole
batch. Each place is now one or the other, and a paper that can't be
bookkept is tried alone, so only it waits.
- Under "first vote decides" the reason now comes from the vote that settled
the paper, the same votes the rule reads (lib/screening/rules.ts
`decidingVotes`).
- Excluded papers by reason and included papers by source are read from the
kept counts. The progress row's hand-kept copies go, and so does the limit
of 52 reasons that could stop a batch from settling.
- A model's vote shows as it was counted, so pages, filters, counts and files
agree on a paper whose result was held through a change of criteria.
- The whole record lists every reviewer, those whose votes stopped counting
included, and its preview counts the same.
- Activity says how many settled papers were checked again. Papers gives the
reason a hand-settled exclusion was made for. Answering a criterion on a
paper asked for again keeps it in Vote again until a new vote.
- One audit (convex/screening/audit.ts) checks a screening's papers, votes,
cards and counts against one another: run by the rules test after every
change made mid-course, and by hand on a live screening.
The plan's cap and sources:
- One paper limit, the plan's within 5,000, for the form and the reading. Papers
taken out with their source are counted in the same write, so papers
brought back can't take the same room twice. A full screening asks no
source for another page.
- A source read again after a change ignores the answers of its earlier
reading. A Zotero range inside a collection with subcollections starts at
its first record. An outage at OpenAlex or a DOI registry stops the reading
with why instead of leaving papers out.
- A source or a drop of PDFs takes only files the person added in that
workspace. The whole record leaves file handles out.
Speed:
- Papers lists narrowed in added order, and counts narrowed two ways, read the
small cards through an index for each filter.
- What waits for the person (the rail, Needs you, other workspaces, emails) is
read from their own votes and the papers in conflict, never from the
screening's running counts.
- Checks, the latest batch, and whether votes are hidden no longer read whole
papers or the progress row. The Settings preview counts again only for a
change that can move a paper.
On the pages:
- To do, Done, the bar and the Screen tab move together after a vote.
- One rule for skeletons or an empty list on the Screening list, Papers and
Screen; one "another reason" form on Screen and Papers; one CSV cell writer.
- "Not in this list now" no longer shows for a voted paper in Done. Activity's
links land on the Settings part they name. Included papers show no stars
where nothing earns a point. Agreement is named Cohen's kappa. The Finished
tab leaves out open work from other workspaces.
Also: the old Screen all answer and stop refuse a screening with reviewers,
extraction takes a screening's PDF-only papers as their file, a check that
couldn't read a source doesn't say it found nothing new, and a guest isn't
told the name of another workspace's screening ahead of theirs.
---
components/screening/data.ts | 22 ++--
components/screening/dialogs.tsx | 6 +-
components/screening/export-dialog.tsx | 4 +-
components/screening/export.ts | 34 +++---
components/screening/index-page.tsx | 13 +-
components/screening/links.ts | 11 ++
components/screening/overview.tsx | 9 +-
components/screening/papers.tsx | 43 ++++---
components/screening/pieces.tsx | 19 +++
components/screening/screen.tsx | 53 ++++----
components/screening/screening-form.tsx | 29 +++--
components/screening/store.tsx | 33 ++++-
components/screening/workspace.tsx | 16 +--
convex/_generated/api.d.ts | 2 +
convex/bench/screening-team.bench.ts | 4 +-
convex/extraction/actions.ts | 3 +-
convex/migrations/screeningFacets.ts | 10 ++
convex/schema.ts | 15 ++-
convex/screening/audit.ts | 135 +++++++++++++++++++++
convex/screening/bookkeeping.ts | 32 +++--
convex/screening/cards.ts | 12 +-
convex/screening/changes.test.ts | 89 +-------------
convex/screening/dealing.ts | 20 ++-
convex/screening/doiRecords.ts | 9 +-
convex/screening/facets.ts | 9 +-
convex/screening/files.test.ts | 40 +++---
convex/screening/files.ts | 7 +-
convex/screening/gathering.ts | 68 ++++++-----
convex/screening/held.ts | 4 +-
convex/screening/living.ts | 3 +-
convex/screening/mutations.ts | 2 +
convex/screening/notices.ts | 8 +-
convex/screening/paperViews.ts | 67 +++++-----
convex/screening/papers.ts | 2 +
convex/screening/readings.ts | 4 +-
convex/screening/reviewers.test-support.ts | 12 +-
convex/screening/screenings.ts | 17 ++-
convex/screening/settings.ts | 5 +-
convex/screening/settling.test.ts | 28 ++++-
convex/screening/settling.ts | 23 +---
convex/screening/slots.ts | 5 +
convex/screening/validators.ts | 5 +-
convex/screening/view.ts | 80 ++++++------
convex/screening/voting.ts | 6 +-
lib/export.ts | 14 ++-
lib/hooks/use-cursor-page.ts | 14 +++
lib/screening/file-words.test.ts | 11 ++
lib/screening/project.test.ts | 10 ++
lib/screening/project.ts | 8 +-
lib/screening/rules.test.ts | 10 +-
lib/screening/rules.ts | 24 ++--
messages/af.json | 3 +-
messages/ar.json | 3 +-
messages/de.json | 3 +-
messages/en-GB.json | 11 +-
messages/en-US.json | 11 +-
messages/es.json | 3 +-
messages/fr.json | 3 +-
messages/hi.json | 3 +-
messages/ja.json | 3 +-
messages/pt.json | 3 +-
messages/sw.json | 3 +-
messages/zh.json | 3 +-
messages/zu.json | 3 +-
scripts/convex-rules.json | 5 +-
65 files changed, 743 insertions(+), 426 deletions(-)
create mode 100644 convex/screening/audit.ts
create mode 100644 lib/screening/file-words.test.ts
diff --git a/components/screening/data.ts b/components/screening/data.ts
index b86e31f73..2d277f521 100644
--- a/components/screening/data.ts
+++ b/components/screening/data.ts
@@ -129,10 +129,6 @@ export type Source = {
addedAt: number;
/** The thing it reads, where two can share a name: a Zotero library or one of its collections, a pasted list. */
ref?: string;
- /** What it held and the screening doesn't take, each with why, where the form itself read them. */
- left?: LeftOut[];
- /** How many of the papers it held have no abstract, where they aren't named in `left`. `total` counts none of them. */
- bare?: number;
};
/** What finds the words the criteria mark in a text, each with whatever ending the text gives it ("programme" marks "programmes" too). Splitting a text by it leaves the marked words at the odd places. Null with no word to find. */
export function termsPattern(terms: string[]) {
@@ -154,15 +150,11 @@ export function termsPattern(terms: string[]) {
const UNSPACED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
const JOINED = /\p{Script=Arabic}/u;
-/** Why a paper that was found isn't screened. */
-const NO_ABSTRACT = "No abstract";
/** How many things a source held that the screening doesn't take. */
-export const leftOf = (source: Source) => source.read?.left ?? (source.left?.length ?? 0) + (source.bare ?? 0);
+export const leftOf = (source: Source) => source.read?.left ?? 0;
/** How many of those are papers with no abstract. */
-export const bareOf = (source: Source) => source.read?.bare ?? (source.bare ?? 0) + (source.left ?? []).filter((one) => one.why === NO_ABSTRACT).length;
+export const bareOf = (source: Source) => source.read?.bare ?? 0;
export const leftTotal = (sources: Source[]) => sources.reduce((sum, source) => sum + leftOf(source), 0);
-/** Something a source held that isn't screened: a record with no title, a DOI that isn't found, a file with nothing to read. */
-export type LeftOut = { name: string; why: string };
/** Sources that gain papers over time, which a living screening checks again. A file or a pasted list holds what it held. */
export const GROWS: SourceKind[] = ["search", "collection", "saved", "screening", "evidenceLibrary", "zotero"];
/** Sources whose papers can come with no abstract and their PDF, which a model is sent whole and charges for by the page. */
@@ -181,9 +173,15 @@ export const foundTotal = (sources: Source[]) => sources.reduce((sum, source) =>
/** What was removed before screening, named the same on the Overview and in the flow diagram. */
export const REMOVED_LABEL = { merged: "Duplicates merged", bare: "No abstract", unread: "Could not be read or found" } as const;
/** What its sources held that it doesn't screen: what they left out, how much of that for having no abstract, and the duplicates merged. One count for the progress line and the flow. */
-export function removedOf(sources: Source[]) {
+/**
+ * What a screening's sources held, as its flow counts them: `found`, every record they gave; `removed`, the ones left
+ * before screening (duplicates merged, and what was left out, no abstract (`bare`) among it); `kept`, the papers screened.
+ * The Overview's flow, the diagram and the methods paragraph all count from this.
+ */
+export function removedOf(sources: Source[], kept = paperTotal(sources)) {
const left = leftTotal(sources);
- return { left, bare: sources.reduce((sum, source) => sum + bareOf(source), 0), merged: foundTotal(sources) - paperTotal(sources) };
+ const merged = foundTotal(sources) - paperTotal(sources);
+ return { left, bare: sources.reduce((sum, source) => sum + bareOf(source), 0), merged, found: kept + merged + left, removed: merged + left };
}
/** The rule as the pages hold it: the shared one (lib/screening/rules.ts), with how many people read each paper as the text a control holds. */
diff --git a/components/screening/dialogs.tsx b/components/screening/dialogs.tsx
index f734d7c4c..9312799fe 100644
--- a/components/screening/dialogs.tsx
+++ b/components/screening/dialogs.tsx
@@ -32,7 +32,7 @@ import { inWorkspace, useWorkspace, useWorkspaceAction, useWorkspaceMutation } f
import { changeOpens, changeSays } from "./activity-words";
import { blindOf, modelKey, inOrder, invitedReviewer, lookOf, modelReviewer, modelsOf, peopleOf, personReviewer, type Reviewer } from "./data";
import { gotThrough, theirsOf } from "@/lib/screening/rules";
-import { papersHref, reviewerHref } from "./links";
+import { papersHref, reviewerHref, bringPartIntoView } from "./links";
import { blindSays, Help, ReviewerMark, ReviewerName, ShutNote } from "./pieces";
import { pdfsOf, perPaper, type Open } from "./store";
import { AddModel } from "./team";
@@ -95,7 +95,7 @@ export function ActivitySheet({ open, onClose, state }: { open: boolean; onClose
{words.ago(change.at)}
{href ? (
-
+ bringPartIntoView(href)} className="-mx-2 flex items-start gap-2 rounded-lg px-2 py-1 outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50">
{body}
@@ -262,7 +262,7 @@ export function PeopleDialog({ open, onClose, state, onAdd, onRemove, onDemote }
// Someone invited to vote goes through the same question as anyone added as a reviewer.
invite: (email) => (addAs === "reviewer" ? onAdd(invitedReviewer(email, Date.now())) : void invite({ kind: "screening", id, email, role: "viewer" }).catch(failed)),
// A member typed by address is offered as the member, never invited: an invitation to them can't be sent.
- has: (email) => invited.results.some((invitation) => invitation.email === email) || guests.results.some((guest) => guest.email.toLowerCase() === email) || (members?.page ?? []).some((person) => person.email?.toLowerCase() === email),
+ has: (email) => invited.results.some((invitation) => invitation.email.toLowerCase() === email) || guests.results.some((guest) => guest.email.toLowerCase() === email) || (members?.page ?? []).some((person) => person.email?.toLowerCase() === email),
// The plan's guest places are for people from outside: an organization's own members can still be added as reviewers once they are full.
...(limit !== null && (room?.used ?? 0) >= limit ? (workspace.kind === "organization" && addAs === "reviewer" ? { outsideFull: t("peopleDialog.fullHere", { own: "false", workspace: workspace.name, count: limit }) } : { full: t("peopleDialog.fullHere", { own: String(workspace.kind !== "organization"), workspace: workspace.name, count: limit }) }) : {}),
}
diff --git a/components/screening/export-dialog.tsx b/components/screening/export-dialog.tsx
index 102445451..842d4cd9d 100644
--- a/components/screening/export-dialog.tsx
+++ b/components/screening/export-dialog.tsx
@@ -34,7 +34,7 @@ import type { Id } from "@/convex/_generated/dataModel";
import { blindOf, reasonCriteria, RESULTS, type Result, slug, bylineOf, questionOf, inOrder, nameOn, votingReviewers } from "./data";
import { papersHref } from "./links";
import { FilterMenu, RESULT_STYLE, EmptyNote, Help, Panel, ShutNote, QuestionName, Reason, ResultChip, ReviewerMark, ReviewerName, Section, VoteMark, OpenPapersChips } from "./pieces";
-import { bibOf, everyPaper, papersCsv, recordOf, risOf, save, voteRows, votesCsv, type Taken, fileName, flowOf, flowSvg, methodsOf, PAPER_GUIDE, VOTE_GUIDE } from "./export";
+import { bibOf, everyPaper, papersCsv, recordOf, recordReviewers, risOf, save, voteRows, votesCsv, type Taken, fileName, flowOf, flowSvg, methodsOf, PAPER_GUIDE, VOTE_GUIDE } from "./export";
import { useFigures, type Open } from "./store";
import { useWords } from "./words";
@@ -345,7 +345,7 @@ export function ExportDialog({ open, onClose, state, tab, onTab }: { open: boole
["votes", everyones.votes],
["withoutVote", everyones.yet + everyones.none + everyones.failed],
["criteria", screening.criteria.length],
- ["reviewers", reviewers.length],
+ ["reviewers", recordReviewers(screening).length],
["sources", screening.sources.length],
["messages", null],
["changes", null],
diff --git a/components/screening/export.ts b/components/screening/export.ts
index 2bd9eab53..bb14fd475 100644
--- a/components/screening/export.ts
+++ b/components/screening/export.ts
@@ -8,6 +8,7 @@ import { hidesVotes, modelsAdvise } from "@/lib/screening/rules";
import { effortOf } from "@/components/settings/model-map";
import type { EFFORTS } from "@/lib/ai/core/call-options";
import { api } from "@/convex/_generated/api";
+import { csvCell } from "@/lib/export";
import type { Id } from "@/convex/_generated/dataModel";
import { sentencesOf } from "@/lib/screening/passages";
import { createFormatter, createTranslator } from "next-intl";
@@ -44,7 +45,6 @@ import {
settledOf,
slug,
taken,
- votingReviewers,
type Paper,
type Pending,
type Result,
@@ -76,6 +76,13 @@ const kindOf = (reviewer: { kind: "person" | "model" }) => (reviewer.kind === "m
/** The records that are read as their own PDF, having no abstract. */
const filedOf = (sources: Screening["sources"]) => sources.reduce((sum, source) => sum + (source.read?.filed ?? 0), 0);
/** Its excluded papers by the reason, the most common first. */
+/** A source's set as a file gives it: an upload's, a list's or a drop's handle opens nothing outside the app, so it is left out. */
+/** Everyone the whole record lists as a reviewer: all who were on the screening, taken off or not; someone invited who never joined is counted apart. */
+export const recordReviewers = (screening: Pick) => screening.reviewers.filter((reviewer) => !reviewer.email);
+const withoutFiles = (set: NonNullable) => {
+ const { file: _file, batch: _batch, ...rest } = set as typeof set & { file?: unknown; batch?: unknown };
+ return rest;
+};
const excludedBy = (figures: Figures | undefined) => Object.entries(figures?.reasons ?? {}).sort((a, b) => b[1] - a[1]);
/**
@@ -87,12 +94,8 @@ const excludedBy = (figures: Figures | undefined) => Object.entries(figures?.rea
export const fileName = ({ screening, counts, me }: Pick, what: string, ending: string, at: number) =>
`${slug(screening.name)}-${what}${!(counts.conflict + counts.waiting) ? "" : screening.finishedAt ? "-with-open-papers" : "-unfinished"}-${iso(at).slice(0, 10)}-${iso(at).slice(11, 16).replace(":", "")}utc${screening.rule.blind === "after" && !screening.finishedAt ? `-${slug(nameOn(screening, me))}` : ""}.${ending}`;
-/**
- * A file of rows, as a spreadsheet opens it: every cell quoted, a quote in a cell doubled. A text that begins the way
- * a formula does (=, +, -, @) takes an apostrophe in front, so a spreadsheet keeps a title or a note as text and
- * never runs it. A number stays a number.
- */
-const toCsv = (lines: unknown[][]) => lines.map((line) => line.map((cell) => `"${(typeof cell === "string" && /^[=+\-@\t\r]/.test(cell) ? `'${cell}` : String(cell ?? "")).replace(/"/g, '""')}"`).join(",")).join("\n");
+/** A file of rows, as a spreadsheet opens it: each cell as the app writes every CSV cell (lib/export.ts `csvCell`). */
+const toCsv = (lines: unknown[][]) => lines.map((line) => line.map(csvCell).join(",")).join("\n");
/** Papers one read of a file's rows takes. */
const EXPORT_PAGE = 100;
@@ -305,16 +308,15 @@ export function flowOf(out: Taken): FlowRow[] {
const { screening, counts, figures } = out;
const [kept, open] = [totalIn(out), openIn(out)];
// What the sources held and the screening never took: the duplicates merged, papers with no abstract, and what couldn't be read or found.
- const { left, bare, merged } = removedOf(screening.sources);
- const found = kept + merged;
+ const { left, bare, merged, found, removed } = removedOf(screening.sources, kept);
const looks = figures?.checks ?? { later: 0, listed: 0, found: 0, added: 0 };
// The records with no abstract that came with their own PDF are read as that: the stage then says how many were read each way.
const filed = filedOf(screening.sources);
const on = filed ? "" : " on title and abstract";
return [
{
- main: { title: "Records identified", n: found + left, lines: [...screening.sources.map((source) => ({ label: source.name, n: taken(source) + leftOf(source) })), ...(looks.added && looks.lastAt ? [{ label: looks.later === 1 ? `Of these, by the later search on ${fullDay(looks.lastAt)}` : `Of these, by ${looks.later} later searches, the last on ${fullDay(looks.lastAt)}`, n: looks.added }] : [])] },
- side: [{ title: "Records removed before screening", n: found - kept + left, lines: [{ label: REMOVED_LABEL.merged, n: merged }, ...(bare ? [{ label: REMOVED_LABEL.bare, n: bare }] : []), ...(left - bare ? [{ label: REMOVED_LABEL.unread, n: left - bare }] : [])] }],
+ main: { title: "Records identified", n: found, lines: [...screening.sources.map((source) => ({ label: source.name, n: taken(source) + leftOf(source) })), ...(looks.added && looks.lastAt ? [{ label: looks.later === 1 ? `Of these, by the later search on ${fullDay(looks.lastAt)}` : `Of these, by ${looks.later} later searches, the last on ${fullDay(looks.lastAt)}`, n: looks.added }] : [])] },
+ side: [{ title: "Records removed before screening", n: removed, lines: [{ label: REMOVED_LABEL.merged, n: merged }, ...(bare ? [{ label: REMOVED_LABEL.bare, n: bare }] : []), ...(left - bare ? [{ label: REMOVED_LABEL.unread, n: left - bare }] : [])] }],
},
{
main: { title: open ? `Records in screening${on}` : `Records screened${on}`, n: kept, ...(filed ? { lines: [{ label: "On title and abstract", n: kept - filed }, { label: "On the full text, having no abstract", n: filed }] } : {}) },
@@ -381,12 +383,11 @@ const advisedIn = (screening: Screening, pending: Pending[] = []) =>
export function methodsOf(out: Taken) {
const { screening, counts, figures } = out;
const [kept, open] = [totalIn(out), openIn(out)];
- const { left, bare, merged } = removedOf(screening.sources);
+ const { left, bare, merged, found } = removedOf(screening.sources, kept);
// Sources that failed before they gave any record: what they hold isn't among the records counted. One that failed a later check has its records counted, and the sentence on later searches says that search was incomplete.
const unreadNow = screening.sources.filter((source) => source.read?.state === "failed" && taken(source) + leftOf(source) === 0);
// Sources that gave some records and then failed: what they gave is counted, the rest isn't.
const partlyRead = screening.sources.filter((source) => source.read?.state === "failed" && taken(source) + leftOf(source) > 0);
- const found = kept + merged;
const looks = figures?.checks ?? { later: 0, listed: 0, found: 0, added: 0 };
// The people per record the rule asks for, counting invitations still waiting, as every page counts them.
const { people, each, invited } = readersOf(screening, out.invited ?? []);
@@ -461,7 +462,7 @@ export function methodsOf(out: Taken) {
});
return [
!open ? "" : running ? `Screening was still in progress when this was written, with ${num(kept - open)} of ${num(kept)} records settled${stillOpen}.` : `The screening was marked finished with ${plural(open, "record", "records")} still open, with ${num(kept - open)} of ${num(kept)} records settled${stillOpen}.`,
- `Records from ${plural(screening.sources.length, "source", "sources")} (${screening.sources.map((source) => source.name).join("; ")}; n = ${num(found + left)}) were brought into Openscholar.${unreadNow.length ? ` ${listed(unreadNow.map((source) => source.name))} could not be read when last tried, so ${unreadNow.length === 1 ? "its records are" : "their records are"} not among those counted here.` : ""}${partlyRead.length ? ` ${listed(partlyRead.map((source) => source.name))} could not be read in full when last tried; the records ${partlyRead.length === 1 ? "it gave" : "they gave"} before that are counted, and the rest ${partlyRead.length === 1 ? "is" : "are"} not.` : ""}${bare ? ` ${plural(bare, "record", "records")} with no abstract and no PDF ${bare === 1 ? "was" : "were"} left out.` : ""}${left - bare ? ` ${plural(left - bare, "more", "more")} could not be read or found.` : ""} ${found === kept ? "No duplicates were found, and" : `After ${plural(found - kept, "duplicate was", "duplicates were")} merged,`} ${num(kept)} ${open ? "went into screening" : kept === 1 ? "was screened" : "were screened"}.`,
+ `Records from ${plural(screening.sources.length, "source", "sources")} (${screening.sources.map((source) => source.name).join("; ")}; n = ${num(found)}) were brought into Openscholar.${unreadNow.length ? ` ${listed(unreadNow.map((source) => source.name))} could not be read when last tried, so ${unreadNow.length === 1 ? "its records are" : "their records are"} not among those counted here.` : ""}${partlyRead.length ? ` ${listed(partlyRead.map((source) => source.name))} could not be read in full when last tried; the records ${partlyRead.length === 1 ? "it gave" : "they gave"} before that are counted, and the rest ${partlyRead.length === 1 ? "is" : "are"} not.` : ""}${bare ? ` ${plural(bare, "record", "records")} with no abstract and no PDF ${bare === 1 ? "was" : "were"} left out.` : ""}${left - bare ? ` ${plural(left - bare, "more", "more")} could not be read or found.` : ""} ${!merged ? "No duplicates were found, and" : `After ${plural(merged, "duplicate was", "duplicates were")} merged,`} ${num(kept)} ${open ? "went into screening" : kept === 1 ? "was screened" : "were screened"}.`,
looks.later && looks.lastAt ? `${[0, screening.sources.length].includes(growing(screening).length) ? "The sources were" : `The ${growing(screening).length} of the ${screening.sources.length} sources that gain records over time (${growing(screening).map((source) => source.name).join("; ")}) were`} searched again ${looks.later === 1 ? "once" : `${looks.later} times`} after screening began, most recently on ${fullDay(looks.lastAt)}; ${looks.added ? `${looks.added} of the records identified came from ${looks.later === 1 ? "that search" : "those searches"}` : "no further records were found"}.${looks.unread ? ` ${looks.unread === looks.later ? (looks.later === 1 ? "That search" : "Each of those searches") : `${looks.unread} of those searches`} could not read every source, so ${looks.unread === 1 ? "it is" : "they are"} incomplete.` : ""}${screening.living && running ? ` A further search is scheduled ${EVERY_LABEL[screening.living.every].toLowerCase()}.` : ""}` : "",
// Said of the records, not of work done: true before the first vote and after the last.
`${partial ? "Records were" : `Each record ${is}`} assessed on ${partial ? "title and abstract" : "its title and abstract"}${screening.criteria.length ? ` against ${plural(screening.criteria.length, "criterion", "criteria")}${((musts) => (musts && models.length ? `, ${musts === screening.criteria.length ? (musts === 1 ? "a must-have" : "all must-haves") : `${musts} of them must-haves`}; an AI model ${running ? "votes" : "voted"} to include a record only where it ${running ? "finds" : "found"} ${musts === 1 ? "that criterion" : "them all"} met` : ""))(screening.criteria.filter((c) => c.must).length)}` : ""}.${filed ? ` ${plural(filed, "record", "records")} with no abstract but a PDF ${filed === 1 ? is : are} assessed on ${filed === 1 ? "its" : "their"} full text instead.` : ""}`,
@@ -530,9 +531,10 @@ export async function recordOf(convex: ConvexReactClient, workspaceId: Id<"works
retired_criteria: screening.retired.map((criterion) => ({ key: criterion.key, short_name: criterion.short, question: criterion.text, must_have: criterion.must })),
// Someone invited who hasn't joined is waited for as a reviewer: counted, since papers can wait for them.
invited_not_joined: readersOf(screening, out.invited ?? []).invited,
- reviewers: votingReviewers(screening).map((reviewer) => ({ id: reviewer.id, name: reviewer.name, kind: kindOf(reviewer), ...(reviewer.model ? { model: reviewer.model.id, effort: reviewer.model.effort ?? effortOf(reviewer.model) } : {}), added_at: since(reviewer.addedAt), taken_off_at: reviewer.left ? iso(reviewer.left) : null })),
+ // Everyone who was on it, those taken off included: one whose votes were made to stop counting says so, and their votes are not among `votes`.
+ reviewers: recordReviewers(screening).map((reviewer) => ({ id: reviewer.id, name: reviewer.name, kind: kindOf(reviewer), ...(reviewer.model ? { model: reviewer.model.id, effort: reviewer.model.effort ?? effortOf(reviewer.model) } : {}), added_at: since(reviewer.addedAt), taken_off_at: reviewer.left ? iso(reviewer.left) : null, ...(reviewer.discarded ? { votes_stopped_counting: true } : {}) })),
// Each source with the records it held and the screening didn't take, by name and with why, and the records it merged, each with the paper that stands for it (in `papers`, under the source that brought it first).
- sources: screening.sources.map((source, at) => ({ id: source.id, kind: source.kind, name: source.name, detail: source.detail, set: source.set ?? null, filters: source.filters ?? [], records_taken: source.scope === "range" ? { first: source.range[0], last: source.range[1] } : "all", last_checked_at: source.read?.checkedAt ? iso(source.read.checkedAt) : null, last_read_failed: source.read?.state === "failed" ? (source.read.failure ?? true) : null, left_out_count: leftOf(source), left_out_without_abstract: bareOf(source), left_out: leftOut[at]!.map((row) => ({ name: row.name, why: english.words.t(`leftWhy.${row.why}`) })), duplicates_merged: merged[at]!.map((row) => ({ name: row.name, same_as_paper_id: row.paper?.id ?? null })), added_at: since(source.addedAt), found: taken(source) + leftOf(source), after_duplicates: keptOf(source) })),
+ sources: screening.sources.map((source, at) => ({ id: source.id, kind: source.kind, name: source.name, detail: source.detail, set: source.set ? withoutFiles(source.set) : null, filters: source.filters ?? [], records_taken: source.scope === "range" ? { first: source.range[0], last: source.range[1] } : "all", last_checked_at: source.read?.checkedAt ? iso(source.read.checkedAt) : null, last_read_failed: source.read?.state === "failed" ? (source.read.failure ?? true) : null, left_out_count: leftOf(source), left_out_without_abstract: bareOf(source), left_out: leftOut[at]!.map((row) => ({ name: row.name, why: english.words.t(`leftWhy.${row.why}`) })), duplicates_merged: merged[at]!.map((row) => ({ name: row.name, same_as_paper_id: row.paper?.id ?? null })), added_at: since(source.addedAt), found: taken(source) + leftOf(source), after_duplicates: keptOf(source) })),
papers: paperRows(out, papers).map((row, i) => ({ ...row, source_id: papers[i]!.source ?? null, settled_at: papers[i]!.settledAt ? iso(papers[i]!.settledAt!) : null })),
// What its rule and criteria were from each moment on, the first first: a paper's result is read against the version in force at its settled_at. Changes made before these were kept are not in it.
history: versions.map((one) => ({
diff --git a/components/screening/index-page.tsx b/components/screening/index-page.tsx
index 4c86c7fb4..f48fc59e3 100644
--- a/components/screening/index-page.tsx
+++ b/components/screening/index-page.tsx
@@ -29,7 +29,7 @@ import { useRunBy } from "@/components/workspaces/run-by";
import { api } from "@/convex/_generated/api";
import { useProtectedQuery } from "@/lib/auth/use-auth-query";
import { useDebouncedValue } from "@/lib/hooks/use-debounced-value";
-import { useCursorPageAt } from "@/lib/hooks/use-cursor-page";
+import { listDraws, useCursorPageAt } from "@/lib/hooks/use-cursor-page";
import { nameHas } from "@/lib/screening/rules";
import { cn } from "@/lib/utils";
import { workspaceHref } from "@/lib/workspaces/href";
@@ -120,6 +120,8 @@ export function ScreeningsIndex() {
const loading = mine === undefined || tally === undefined || elsewhere === undefined || invitations === undefined || (show !== "you" && listed.isLoading);
// An invitation needs the person as much as a vote does, and so does a screening waiting in another workspace (the rows above the list): counted in Needs you, as the rail's badge counts them.
const counts = tally && mine ? { all: tally.open + tally.finished + mine.page.filter((row) => !row.member).length, you: mine.page.filter(needing).length + (invitations ?? []).filter((row) => row.kind === "screening").length + (elsewhere?.length ?? 0), open: tally.open + mine.page.filter((row) => !row.member && !row.finishedAt).length, finished: tally.finished + mine.page.filter((row) => !row.member && row.finishedAt).length } : undefined;
+ // Skeletons, the empty list at once, or the rows: as every list decides it (lib/hooks/use-cursor-page.ts `listDraws`). Needs you is read with the page.
+ const drawn = show === "you" ? ({ draw: "rows" } as const) : listDraws(listed, counts?.[show], PAGE);
// The first-use block is for someone with no screening of their own: an invitation waiting doesn't make them a user of the list.
const invitedCount = (invitations ?? []).filter((row) => row.kind === "screening").length;
// Something needs the person outside this workspace's list too: what needs them in it says where, beside the tab's count of all of it.
@@ -157,8 +159,9 @@ export function ScreeningsIndex() {
) : null}
-
- nameHas(row.name, searched))} />
+ {/* What waits for the person is open work: the Finished tab lists none of it. */}
+
+ nameHas(row.name, searched))} />
{empty ? (
@@ -231,8 +234,8 @@ export function ScreeningsIndex() {
{/* The rows and what stands in for them while they are read are different heights: the frame around them slides from one to the other. */}
- {(loading && !rows.length) || (otherList && counts?.[show] !== 0) ? (
-
+ {drawn.draw === "skeleton" || (loading && !rows.length && drawn.draw !== "empty") ? (
+
) : (
{listRows.map(({ row, group }, i) => {
diff --git a/components/screening/links.ts b/components/screening/links.ts
index 9ea2bc1fe..c71717972 100644
--- a/components/screening/links.ts
+++ b/components/screening/links.ts
@@ -54,3 +54,14 @@ export const reviewerHref = (id: string, reviewer: { id: string; tally?: { cast:
};
/** Its settings, at one of their sections. */
export const settingsHref = (id: string, section?: "papers" | "new-papers" | "criteria" | "reviewers" | "decided" | "goes-to") => withQuery(`${BASE}/${id}/settings`, undefined, section);
+
+/**
+ * A link to a part of a page, followed from inside something laid over the frame (Activity): the frame lands a part
+ * only as its page opens, and a page already open, under a sheet that holds the scroll while it closes, is not
+ * opening. Once the sheet has let go, the part the link named is brought into view.
+ */
+export function bringPartIntoView(href: string) {
+ const part = href.split("#")[1];
+ if (!part) return;
+ window.setTimeout(() => document.getElementById(decodeURIComponent(part))?.scrollIntoView({ block: "start", behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }), 350);
+}
diff --git a/components/screening/overview.tsx b/components/screening/overview.tsx
index 5b30e6ddc..0d11d4135 100644
--- a/components/screening/overview.tsx
+++ b/components/screening/overview.tsx
@@ -385,7 +385,7 @@ function Reviewers({ open, figures, now }: { open: Open; figures: Figures | unde
{pair ? (
- {t("reviewers.agreement")}
+ {t("kappa.title")}{kappaText(format, pair.kappa, t("kappa.none"))}{sameText(t, pair)}
@@ -1080,7 +1080,7 @@ function Checks({ open, figures }: { open: Open; figures: Figures | undefined })
{/* It opens the papers it started with, where there are any: a count of none, or one not yet known, opens nothing. */}
{/* Its papers are counted with the figures: until then the chip's room is held, so its words never change in place. */}
- {figures === undefined ? : (() => { const says = t("checks.startedWith", { known: String(Boolean(figures)), papers: figures?.startedWith ?? 0, sources: screening.sources.filter((source) => source.addedAt <= screening.createdAt).length }); return figures?.startedWith ? {says} : {says}; })()}
+ {figures === undefined ? : (() => { const says = t("checks.startedWith", { known: String(Boolean(figures)), papers: figures?.startedWith ?? 0, sources: figures?.startedFrom ?? 0 }); return figures?.startedWith ? {says} : {says}; })()}
@@ -1100,9 +1100,8 @@ function Flow({ open, figures, onExport }: { open: Open; figures: Figures | unde
const words = useWords();
const id = screening.id;
// What the sources held: the papers they brought, and what they left out for having no abstract or nothing to read.
- const { left, bare, merged } = removedOf(screening.sources);
const kept = open.total;
- const found = kept + merged + left;
+ const { left, bare, merged, found, removed } = removedOf(screening.sources, kept);
const arriving = open.gathering ? Math.max(0, open.gathering.of - open.gathering.done) : 0;
// In conflict is a step only where a paper can be in conflict, or one is.
const splits = splitsIn(screening, open.counts.conflict, open.invited);
@@ -1114,7 +1113,7 @@ function Flow({ open, figures, onExport }: { open: Open; figures: Figures | unde
{ title: t("flow.found"), total: found, rows: screening.sources.map((source) => ({ key: source.id, label: source.name, value: taken(source) + leftOf(source), ...(open.canChange ? { href: settingsHref(id, "papers") } : {}), fill: neutral })) },
{
title: t("flow.removed"),
- total: found - kept,
+ total: removed,
// Its sources are in its settings, which its workspace's members open: for anyone else these are counts.
...(open.canChange ? { href: settingsHref(id, "papers") } : {}),
rows: [{ key: "duplicates", label: words.t("removed.merged"), value: merged }, { key: "bare", label: words.t("removed.bare"), value: bare }, { key: "unread", label: words.t("removed.unread"), value: left - bare }].flatMap((row) => (row.value ? [{ ...row, ...(open.canChange ? { href: settingsHref(id, "papers") } : {}), fill: neutral }] : [])),
diff --git a/components/screening/papers.tsx b/components/screening/papers.tsx
index efc48b5ff..5a84e167d 100644
--- a/components/screening/papers.tsx
+++ b/components/screening/papers.tsx
@@ -40,15 +40,15 @@ import { TooltipHint } from "@/components/ui/tooltip";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useProtectedQuery } from "@/lib/auth/use-auth-query";
-import { useCursorPage, useCursorPageAt } from "@/lib/hooks/use-cursor-page";
+import { listDraws, useCursorPage, useCursorPageAt } from "@/lib/hooks/use-cursor-page";
import { useDebouncedValue } from "@/lib/hooks/use-debounced-value";
import { getErrorMessage } from "@/lib/toast/use-app-toast";
import { cn } from "@/lib/utils";
import { EXTRACT_HREF, pickForExtraction } from "./extract";
import { inWorkspace, useWorkspace as usePageWorkspace } from "@/lib/workspaces/url";
-import { blindOf, type Blind, invitedSaid, reasonCriteria, inOrder, growing, bylineOf, awaitedOn, splitsIn, readersOf, modelsOf, type Criterion, resolves, DECISIONS, RESULTS, castOf, keptOf, personIn, pointsMax, questionOf, sentencesOf, settledOf, taken, voteOn, votingReviewers, type Decision, type Paper, type Reviewer, type Result, shortName, othersRead } from "./data";
+import { blindOf, type Blind, invitedSaid, reasonCriteria, inOrder, growing, bylineOf, awaitedOn, splitsIn, readersOf, modelsOf, type Criterion, resolves, DECISIONS, RESULTS, castOf, keptOf, personIn, pointsMax, questionOf, sentencesOf, settledOf, taken, voteOn, votingReviewers, type Decision, type Paper, type Reviewer, type Result, type Screening, shortName, othersRead } from "./data";
import { papersHref, screenHref } from "./links";
-import { PdfRoom, Sentence, HeldChip, NoPdfVote, votedReasonGroup, ReasonNoteField, VoteFacts, Byline, Faces, votesBy, AnswerMark, FILTER_ON, FilterMenu, Help, Kbd, LinkChip, Note, PaperStepper, ReasonChip, PaperFacts, ReasonRows, VoteButton, RetryRead, VotesHelp, ShutChip, ShutNote, VOTES_SHUT, votesShutOf, votesTitle, HiddenChip, blindSays, youFirst, Named, Panel, QuestionHint, QuestionName, RESULT_ICON, RESULT_STYLE, Reason, ResultChip, ReviewerMark, ReviewerName, Section, StateChip, TONE, Tally, VoteMark, BELOW_HEADER, UNDER_FRAME, kindIcon, SEARCH_PILL } from "./pieces";
+import { PdfRoom, Sentence, HeldChip, NoPdfVote, votedReasonGroup, ReasonNoteForm, VoteFacts, Byline, Faces, votesBy, AnswerMark, FILTER_ON, FilterMenu, Help, Kbd, LinkChip, Note, PaperStepper, ReasonChip, PaperFacts, ReasonRows, VoteButton, RetryRead, VotesHelp, ShutChip, ShutNote, VOTES_SHUT, votesShutOf, votesTitle, HiddenChip, blindSays, youFirst, Named, Panel, QuestionHint, QuestionName, RESULT_ICON, RESULT_STYLE, Reason, ResultChip, ReviewerMark, ReviewerName, Section, StateChip, TONE, Tally, VoteMark, BELOW_HEADER, UNDER_FRAME, kindIcon, SEARCH_PILL } from "./pieces";
import { Evidence, Matrix, Said } from "./screen";
import type { Open } from "./store";
import { useTranslations } from "next-intl";
@@ -244,8 +244,10 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) =>
// Another list asked for (another tab or filter), not another page, search or order of the same: its rows show as skeletons under the table's head until they come, and a tab the counts say is empty says so at once. Never the last list's rows under the new tab.
// A search typed or another order keeps the rows up, dimmed, as Screen's search does: only another tab or filter is another list.
const otherList = listed.isOther;
- // Empty by the counts, from the first read too.
- const emptyNow = (otherList || listed.isLoading) && total === 0;
+ // Empty by the counts, from the first read too, and skeleton rows as many as the counts say: as every list decides it (lib/hooks/use-cursor-page.ts `listDraws`).
+ const drawn = listDraws(listed, total, PAGE);
+ const emptyNow = drawn.draw === "empty";
+ const skeletonRows = drawn.draw === "skeleton" ? drawn.rows : Math.min(total ?? PAGE, PAGE);
const rowsPending = otherList && !emptyNow;
// A count the server is still reading holds a digit's room, so the tabs don't widen when it arrives. Where none will come the tab has no number.
const pending = countable && !under ? 0 : undefined;
@@ -516,7 +518,8 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) =>
...DECISIONS.map((decision) => { const { icon: Icon, tone } = RESULT_STYLE[decision]; return { value: decision as Voted, label: words.decision(decision), icon: , tone, ...(tally?.kept ? { shut: words.t("hiddenWhileToDo") } : { count: countVoted(decision) }) }; }),
{ value: "none" as Voted, label: words.t("noVote.yet"), icon: , count: countVoted("none"), group: t("filter.noVote") },
...(countVoted("failed") ? [{ value: "failed" as Voted, label: words.t("noVote.failed"), icon: , tone: "destructive" as const, count: countVoted("failed"), group: t("filter.noVote") }] : []),
- ...(settles(who) ? [{ value: "settled" as Voted, label: t("filter.settled"), icon: , tone: "info" as const, count: countVoted("settled"), group: t("filter.decisions") }] : []),
+ // Papers settled by hand, where the rule can leave a paper split: under "first vote decides" the votes settle every paper, and the list would be of none.
+ ...(settles(who) && splitsIn(screening, open.counts.conflict, open.invited) ? [{ value: "settled" as Voted, label: t("filter.settled"), icon: , tone: "info" as const, count: countVoted("settled"), group: t("filter.decisions") }] : []),
]}
/>
) : null}
@@ -666,12 +669,12 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) =>
<>
{/* The table's two head rows, then as many rows as the page will hold. */}
-
+
>
) : (shown.length || rowsPending) && !emptyNow ? (
<>
{/* As wide as the column and no wider: the frame around it scrolls sideways for the table, and would let a long title stretch the list. */}
- {rowsPending ? : (
+ {rowsPending ? : (
{shown.map((one) => {
const isOpen = paper?.id === one.id;
@@ -967,13 +970,14 @@ function Why({ paper, open, reasonKey }: { paper: Paper; open: Open; reasonKey?:
// What whoever settled it wrote down, beside the votes they settled: the reason a settled paper has.
const settledNote = state.resolvedBy && state.note ? {words.quoted(state.note)} : null;
if (!visible) return settledNote;
- if (state.result === "conflict" || state.resolvedBy) return {settledNote};
+ // A paper excluded by hand gives the reason it was excluded for, as one its votes excluded does: the settler's.
+ if (state.result === "conflict" || (state.resolvedBy && !(state.result === "exclude" && reasonKey))) return {settledNote};
if (reasonKey && (state.result === "exclude" || state.result === "maybe")) {
const label = state.result === "exclude" ? words.failed(reasonKey, reasonCriteria(open.screening)) : words.unclear(reasonKey, reasonCriteria(open.screening));
// Pressed again while the table is narrowed to this reason, it takes the reason away and keeps the result.
const link = narrow({ result: state.result, reason: reasonKey }, ["reason"]);
// Another reason is what its voter wrote: it stands beside the reason, as a settled paper's note does.
- const written = reasonKey === OTHER_REASON ? cast.find((vote) => vote.reason === OTHER_REASON && vote.note)?.note : undefined;
+ const written = reasonKey === OTHER_REASON ? (state.resolvedBy ? state.note : cast.find((vote) => vote.reason === OTHER_REASON && vote.note)?.note) : undefined;
if (written) return {words.quoted(written)};
return (
@@ -987,7 +991,7 @@ function Why({ paper, open, reasonKey }: { paper: Paper; open: Open; reasonKey?:
);
}
// An included paper carries the stars its answers earn, as it is saved with them.
- const score = state.result === "include" && paper.points !== undefined ? { points: paper.points, stars: paper.stars ?? 0, of: pointsMax(open.screening) } : null;
+ const score = scoreShown(open.screening, paper, state.result);
return score ? {t("pointsOf", { points: score.points, max: score.of })} : null;
}
@@ -1006,14 +1010,7 @@ function ReasonPicker({ criteria, many = false, extra, note: given, onNote, onPi
const setNote = onNote ?? setOwn;
if (writing) {
return (
-
+ setWriting(false)} onExclude={(text) => onPick(OTHER_REASON, text)} className="h-9" fieldClassName="bg-card" />
);
}
return (
@@ -1070,7 +1067,7 @@ function PaperPanel({ paper, open, notes, setNotes, talk, onTalk, onClose, onSte
const added = paper.batch !== undefined ? narrow({ added: paper.batch }) : null;
const from = source ? narrow({ source: source.id }) : null;
const failed = cast.filter((one) => one.failed);
- const score = state.result === "include" && paper.points !== undefined ? { points: paper.points, stars: paper.stars ?? 0, of: pointsMax(screening) } : null;
+ const score = scoreShown(screening, paper, state.result);
// The reviewers the paper still waits for: who an override settles it without.
const awaited = awaitedOn(screening, paper);
const settle = (kind: "vote" | "result", decision: Decision, reason?: string, withNote?: string) => {
@@ -1255,3 +1252,9 @@ function PaperPanel({ paper, open, notes, setNotes, talk, onTalk, onClose, onSte
);
}
+
+/** The stars an included paper earns, as it is saved with them, and its points out of the most it could have: none where no answer is worth a point, as with no criteria. */
+function scoreShown(screening: Screening, paper: Pick, result: Result) {
+ const of = pointsMax(screening);
+ return result === "include" && paper.points !== undefined && of > 0 ? { points: paper.points, stars: paper.stars ?? 0, of } : null;
+}
diff --git a/components/screening/pieces.tsx b/components/screening/pieces.tsx
index 8cc98df8a..7338fa467 100644
--- a/components/screening/pieces.tsx
+++ b/components/screening/pieces.tsx
@@ -925,6 +925,25 @@ export function PdfRoom({ pages, shape = A4_SHAPE, children }: { pages: number;
* The field "Another reason" is written in, on Screen and in the Papers drawer: two lines on a phone and one up from
* there, wrapping so a long reason stays in view. Enter excludes, as the form's button shows; Shift+Enter starts a line.
*/
+/**
+ * "Another reason" written down, in place of the reasons or the vote buttons: Enter excludes, as the button beside it
+ * shows, and Escape anywhere in it goes back, as its Back button shows, never closing what it sits in. A note with
+ * nothing in it excludes nothing. `className`: the buttons' height, the height of the buttons it stands in for.
+ */
+export function ReasonNoteForm({ value, onChange, onBack, onExclude, className, fieldClassName }: { value: string; onChange: (text: string) => void; onBack: () => void; onExclude: (note: string) => void; className?: string; fieldClassName?: string }) {
+ const t = useTranslations("screening.screen");
+ const words = useWords();
+ return (
+
+ );
+}
+
export function ReasonNoteField({ value, onChange, className }: { value: string; onChange: (text: string) => void; className?: string }) {
const t = useTranslations("screening.screen");
return (
diff --git a/components/screening/screen.tsx b/components/screening/screen.tsx
index 0549634c8..e534ee992 100644
--- a/components/screening/screen.tsx
+++ b/components/screening/screen.tsx
@@ -37,7 +37,7 @@ import { TooltipHint } from "@/components/ui/tooltip";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useProtectedQuery } from "@/lib/auth/use-auth-query";
-import { useCursorPageAt } from "@/lib/hooks/use-cursor-page";
+import { skeletonRows, useCursorPageAt } from "@/lib/hooks/use-cursor-page";
import { useDebouncedValue } from "@/lib/hooks/use-debounced-value";
import { useIsTablet } from "@/lib/hooks";
import { decide, givenReason, leansOpen, NO_REASON, NOTE_LENGTH, OTHER_REASON } from "@/lib/screening/rules";
@@ -49,9 +49,9 @@ import { useWorkspaceRouter } from "@/lib/workspaces/href";
import { blindOf, invitedSaid, reasonCriteria, termsPattern, bylineOf, awaitedOn, DECISIONS, castOf, splitsIn, questionOf, sentencesOf, settledOf, voteOn, type Criterion, type Decision, type Paper, type Reviewer, type Settled, type Vote, shortName, othersRead } from "./data";
import { Discussion, DiscussionShut, type DiscussionDraft } from "./discussion";
import { askedHref, papersHref, screenHref, settingsHref } from "./links";
-import { PdfRoom, Sentence, HeldChip, NoPdfVote, votedReasonGroup, ReasonNoteField, VoteFacts, Byline, ANSWER_SIGN, ActionBar, AnswerMark, BELOW_HEADER, DiscussionLink, PaperStepper, ReasonChip, PaperFacts, ReasonLabel, ReasonRows, VoteButton, DIFFER, VotesHelp, ShutChip, ShutNote, VOTES_SHUT, votesShutOf, votesTitle, HiddenChip, youFirst, CriterionText, FilterMenu, Help, Kbd, LinkChip, Panel, QuestionName, RESULT_STYLE, ResultChip, ReviewerMark, ReviewerName, Section, StateChip, TONE, TabCount, Tally, VoteMark, Named, RESULT_ICON, type Tone, notReviewerSays, SEARCH_PILL } from "./pieces";
+import { PdfRoom, Sentence, HeldChip, NoPdfVote, votedReasonGroup, ReasonNoteForm, VoteFacts, Byline, ANSWER_SIGN, ActionBar, AnswerMark, BELOW_HEADER, DiscussionLink, PaperStepper, ReasonChip, PaperFacts, ReasonLabel, ReasonRows, VoteButton, DIFFER, VotesHelp, ShutChip, ShutNote, VOTES_SHUT, votesShutOf, votesTitle, HiddenChip, youFirst, CriterionText, FilterMenu, Help, Kbd, LinkChip, Panel, QuestionName, RESULT_STYLE, ResultChip, ReviewerMark, ReviewerName, Section, StateChip, TONE, TabCount, Tally, VoteMark, Named, RESULT_ICON, type Tone, notReviewerSays, SEARCH_PILL } from "./pieces";
import { useInHand, useKept } from "./drafts";
-import type { Ballot, Open } from "./store";
+import type { Ballot, Moved, Open } from "./store";
import { useWorkspace } from "./workspace";
import { useRtl, useWords } from "./words";
@@ -127,11 +127,11 @@ const PLACE = {
/** Screen as a page of the open screening. */
export function ScreenPage() {
- const { open } = useWorkspace();
- return ;
+ const { open, cast, moved } = useWorkspace();
+ return ;
}
-function Screen({ open }: { open: Open }) {
+function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes, theirs made here counted before the server's count does. */ castByMe: number; moved: (kind: Moved, by: 1 | -1) => void }) {
const backwards = useRtl();
const { screening } = open;
const t = useTranslations("screening.screen");
@@ -293,13 +293,12 @@ function Screen({ open }: { open: Open }) {
const noteKey = (id: string) => (resolving ? `settle:${id}` : id);
// `saved`: when the server stamped the vote or settlement, once it has: Undo puts back what stood before only while that one still stands.
const [history, setHistory] = useState }>>([]);
- // The server's counts move a moment after a vote. Until they do, the votes and settlings made here since are taken off them, so To do and the bar never read one behind the paper that has moved on.
+ // The frame's counts take in the votes made here before the server's do (./store.tsx `useUnheardMoves`): To do, Done, the bar and the tabs above read one number.
+ const { toDo, conflicts } = open;
+ // The votes and settlings made here since the counts last moved: a queue they emptied is said empty from them.
const [base, setBase] = useState({ toDo: open.toDo, conflicts: open.conflicts, at: 0 });
if (base.toDo !== open.toDo || base.conflicts !== open.conflicts) setBase({ toDo: open.toDo, conflicts: open.conflicts, at: history.length });
const since = history.slice(base.at);
- // A first vote on a paper takes it off To do; settling a paper that was in conflict takes it off Conflicts. Changing a vote or a settled result moves neither.
- const toDo = Math.max(0, open.toDo - since.filter((one) => !one.resolved && one.queue === "todo" && one.before === null).length);
- const conflicts = Math.max(0, open.conflicts - since.filter((one) => one.resolved && one.paper.result === "conflict").length);
const last = history.findLast((one) => one.queue === queue) ?? null;
const [shown, setShown] = useState<{ reviewer: string; criterion: string } | null>(null);
// The criterion being looked at on the open paper: the words marked for it stand out in the abstract, and Y, N and U answer it. It belongs to its paper, so another paper starts with none.
@@ -365,8 +364,12 @@ function Screen({ open }: { open: Open }) {
// Undo puts back only what you did: a settlement someone else made is theirs, and saving it again would put it in your name (the drawer's `mayUndo` is the same rule).
const cast = { paper, decision, reason, noted: Boolean(note), before: resolving ? null : (mine ?? null), resolved: resolving, settledBefore: resolving && settled.resolvedBy ? settled : null, mayUndo: !resolving || !settled.resolvedBy || settled.resolvedBy === open.me, queue, at: Date.now() };
setHistory((all) => [...all, cast]);
+ // A first vote on a paper takes it off To do and adds one to Done; settling a paper in conflict takes it off Conflicts. Changing a vote or a settled result moves neither.
+ const moves = movesOf(cast);
+ for (const [kind, by] of moves) moved(kind, by);
// A vote the server refuses was never cast: it leaves "your last vote", and its paper is the open one again.
const refused = (error: unknown) => {
+ for (const [kind, by] of moves) moved(kind, by === 1 ? -1 : 1);
setHistory((all) => all.filter((one) => one !== cast));
openIt(paper, { inPlace: true });
failed(error);
@@ -429,7 +432,7 @@ function Screen({ open }: { open: Open }) {
const rested = mine.decision === "exclude" && ((mine.reason === criterion && given[criterion] !== "no") || (mine.reason === NO_REASON && given[criterion] === "no"));
const ballot = { ...ballotOf(mine), answers: given, ...(rested ? { reason: givenReason(criteria, given, mine.note ?? "") ?? NO_REASON } : {}) };
// Saved, the answers are the vote's own: in hand they would stand over a change made since on another page. Any given while it saved stay.
- const saving = open.vote(paper.id, ballot).then((at) => {
+ const saving = open.vote(paper.id, ballot, { answersOnly: true }).then((at) => {
if (at !== null && cast) cast.saved = at;
setAnswers(({ [paper.id]: was, ...rest }) => (was === given || was === undefined ? rest : { ...rest, [paper.id]: was }));
}, failed);
@@ -460,6 +463,7 @@ function Screen({ open }: { open: Open }) {
// Undo pressed again at once waits for this one, so it names the moment this one stamps.
if (earlier) earlier.pending = Promise.all([earlier.pending, undoing]);
openIt(last.paper);
+ for (const [kind, by] of movesOf(last)) moved(kind, by === 1 ? -1 : 1);
setHistory((all) => all.filter((one) => one !== last));
};
@@ -597,7 +601,7 @@ function Screen({ open }: { open: Open }) {
options={queues.map((which) => ({
id: which,
label: t(`queue.${which}`),
- detail: ,
+ detail: ,
}))}
/>
);
@@ -632,7 +636,7 @@ function Screen({ open }: { open: Open }) {
);
};
// How many the queue holds, where it is counted: Done by your votes (all of them, or the decision it is narrowed to), the others by what is left. A search isn't counted, and its pager says only the page.
- const queueTotal = searched || (queue === "again" && open.flaggedMore) ? undefined : queue === "done" ? (voted === "any" ? (counted?.cast ?? 0) : (counted?.[voted] ?? 0)) : left;
+ const queueTotal = searched || (queue === "again" && open.flaggedMore) ? undefined : queue === "done" ? (voted === "any" ? castByMe : (counted?.[voted] ?? 0)) : left;
const pager = (className: string) => (listed.hasPages ? turn(listed.previous)} onNext={() => turn(listed.next)} /> : null);
const findField = (className: string) => (
setFind(event.target.value)} placeholder={t("queue.find")} aria-label={t("queue.findLabel")} className={SEARCH_PILL} />
@@ -651,7 +655,7 @@ function Screen({ open }: { open: Open }) {
onChange={(next) => namedThen(() => void setPlace({ voted: next, paper: null }))}
className={className}
choices={[
- { value: "any" as typeof voted, label: t("filter.any"), icon: , count: counted?.cast ?? 0 },
+ { value: "any" as typeof voted, label: t("filter.any"), icon: , count: castByMe },
...DECISIONS.map((decision) => { const { icon: Icon, tone } = RESULT_STYLE[decision]; return { value: decision as typeof voted, label: words.decision(decision), icon: , tone, count: counted?.[decision] ?? 0 }; }),
]}
/>
@@ -693,7 +697,7 @@ function Screen({ open }: { open: Open }) {
-
+
@@ -872,7 +876,7 @@ function Screen({ open }: { open: Open }) {
{queueFilters(QUEUE_FILTER)}
- {otherQueue ? : (
+ {otherQueue ? : (
{items.map((one) => row(one, openIt))}
@@ -1076,7 +1080,7 @@ function Screen({ open }: { open: Open }) {
{/* How many are left, and from 1400px how long they take at the person's pace. On a phone the queue's tab already counts them, and the row keeps its room for the last vote and the note. */}
- {queue === "done" && kept && !otherQueue ? t("bar.notInList") : queue === "done" || !decideLook || floor ? ((!otherQueue && at < 0) || (queueTotal !== undefined && shownAt > queueTotal) ? t("bar.notInList") : queueTotal === undefined && listed.canNext ? words.num(shownAt) : t("bar.atOf", { at: shownAt, count: queueTotal ?? listed.offset + items.length })) : t("bar.left", { count: left })}
+ {queue === "done" && kept && !otherQueue ? (mine ? null : t("bar.notInList")) : queue === "done" || !decideLook || floor ? ((!otherQueue && at < 0) || (queueTotal !== undefined && shownAt > queueTotal) ? t("bar.notInList") : queueTotal === undefined && listed.canNext ? words.num(shownAt) : t("bar.atOf", { at: shownAt, count: queueTotal ?? listed.offset + items.length })) : t("bar.left", { count: left })}
{timeLeft ? {timeLeft} : null}
go(at + by)} canPrevious={at > 0 || listed.canPrevious || Boolean(back)} canNext={at < items.length - 1 || listed.canNext} />
@@ -1139,14 +1143,7 @@ function Screen({ open }: { open: Open }) {
{!decideLook ? (
{gone ? t("shut.left") : finished && (resolving ? open.canResolve : open.isReviewer) ? t("shut.finished", { canChange: String(open.canChange) }) : resolving ? t("shut.settler", { you: String(settlesHere), name: settler }) : notReviewerSays(pieces, open.canChange, finished)}
) : writing === paper.id ? (
-
+ setNotes((all) => ({ ...all, [noteKey(paper.id)]: text }))} onBack={() => setWriting(null)} onExclude={() => decideOn("exclude", OTHER_REASON)} className="h-10" />
) : (
<>
{/* With every paper in the queue voted on, the line above the buttons says so: the buttons stay, to change a vote. */}
@@ -1517,3 +1514,9 @@ function PaperSkeleton({ label, className }: { label?: string; className?: strin
);
}
+
+/** The counts a vote or a settlement made on Screen moves, before the server's say so: a first vote on a paper in To do takes it off and adds one to Done, and settling a paper in conflict takes it off Conflicts. */
+function movesOf(made: { resolved: boolean; queue: string; before: unknown; paper: { result: string } }): Array<[Moved, 1 | -1]> {
+ if (made.resolved) return made.paper.result === "conflict" ? [["conflicts", -1]] : [];
+ return made.queue === "todo" && made.before === null ? [["toDo", -1], ["cast", 1]] : [];
+}
diff --git a/components/screening/screening-form.tsx b/components/screening/screening-form.tsx
index af8c4837a..dbfe9e6f7 100644
--- a/components/screening/screening-form.tsx
+++ b/components/screening/screening-form.tsx
@@ -145,7 +145,8 @@ const SOURCES_SETTLE_MS = 1_200;
*/
const heldBy = (source: Source) => (source.set?.kind === "zotero" && source.set.deep ? (source.read?.state === "done" ? source.read.taken + source.read.duplicates + source.read.left : null) : baseTotal(source));
/** The papers a source's open row shows a sample of: what it brought, or, while it is still read, what its range promises. */
-const promised = (source: Source) => (source.read?.state === "waiting" || source.read?.state === "reading" ? Math.max(taken(source), baseTaken(source)) : taken(source));
+/** The papers a source gives, as its card counts them: what its range promises while it is read, and once read, what it gave after duplicates were merged. */
+const promised = (source: Source) => (source.read?.state === "waiting" || source.read?.state === "reading" ? Math.max(taken(source), baseTaken(source)) : keptOf(source));
/** Whether a list of sources, as sent to the server, begins with another, the same sources in the same order. */
const startsWith = (list: string, first: string) => {
const [all, some] = [JSON.parse(list) as unknown[], JSON.parse(first) as unknown[]];
@@ -219,6 +220,18 @@ function changeOf(say: Say, saved: Screening, draft: Screening, recheck: boolean
};
}
+/**
+ * The part of a change the preview counts anything for: a new name, question or star scale counts nothing, and of the
+ * criteria only which there are and which are must-haves do. Typing in a field then never asks the server to count the
+ * screening again.
+ */
+function movingOf(saved: Screening, change: ReturnType) {
+ const { name: _name, question: _question, stars: _stars, criteria, ...rest } = change;
+ // A criterion added in this edit has no key yet: it is told by its place, so typing its words counts nothing again.
+ const musts = (criteria: Array<{ key?: string; must?: boolean }>) => criteria.map(({ key, must }, at) => [key ?? `new:${at}`, Boolean(must)]);
+ return { ...rest, ...(criteria && JSON.stringify(musts(criteria)) !== JSON.stringify(musts(saved.criteria)) ? { criteria: musts(criteria) } : {}) };
+}
+
/** The Discard question, open in the address (./address.ts). */
const DISCARD_OPEN = ["edits"] as const;
@@ -549,14 +562,16 @@ export function ScreeningForm({ id }: { id?: string }) {
// What a save would do to a running screening, counted by the server for the change as it stands: the lines and the moves both read it.
const change = saved && draft ? changeOf(say, saved, draft, recheck) : null;
const changing = change && Object.keys(change).length > 0 ? JSON.stringify(change) : null;
- const counted = useSWR(saved && changing && workspaceId ? ["screening-preview", saved.id, changing] : null, () => previewChange({ jobId: saved!.id, change: change! }), { revalidateOnFocus: false });
+ const moving = saved && change ? movingOf(saved, change) : null;
+ const toCount = moving && Object.keys(moving).length > 0 ? JSON.stringify(moving) : null;
+ const counted = useSWR(saved && toCount && workspaceId ? ["screening-preview", saved.id, toCount] : null, () => previewChange({ jobId: saved!.id, change: change! }), { revalidateOnFocus: false });
// Until the server has counted the change as it now stands, nothing it would do is known: no figure from an earlier change stands in.
- const known = !changing || counted.data !== undefined;
+ const known = !toCount || counted.data !== undefined;
// A count that failed is said, with a way to ask again: a save waits for it, since nothing it would do is known.
- const countFailed = Boolean(changing) && Boolean(counted.error) && counted.data === undefined;
- const preview: Preview = (changing ? counted.data : undefined) ?? NO_PREVIEW;
+ const countFailed = Boolean(toCount) && Boolean(counted.error) && counted.data === undefined;
+ const preview: Preview = (toCount ? counted.data : undefined) ?? NO_PREVIEW;
// While the server counts a change, what it would do isn't known: the save waits for it.
- const counting = Boolean(changing) && (counted.isLoading || counted.isValidating) && !counted.error;
+ const counting = Boolean(toCount) && (counted.isLoading || counted.isValidating) && !counted.error;
// A new form waits for whoever makes it, and a screening that is gone, or not shared with the person, is said by the frame its settings open in.
if (!draft || !origin || (id && !saved)) return id ? null : ;
@@ -1273,7 +1288,7 @@ export function ScreeningForm({ id }: { id?: string }) {
{source.set?.kind === "pdf" && !own ?
) : null}
{/* A range of a Zotero source is counted in the order its papers were added there, which holds from one read to the next. */}
diff --git a/components/screening/store.tsx b/components/screening/store.tsx
index 368f4fa65..96adf9538 100644
--- a/components/screening/store.tsx
+++ b/components/screening/store.tsx
@@ -169,6 +169,36 @@ function toScreening(view: View, words: Pick
};
}
+/** The counts a vote moves for the person who cast it: the papers waiting for them, the conflicts waiting, and the votes they cast. */
+export type Moved = "toDo" | "conflicts" | "cast";
+type Unheard = Record;
+/**
+ * The server's counts move a moment after a vote is saved. Until they do, the moves this person's votes and Undos made
+ * here are put on them, so the frame's tabs, To do, Done and the bar all read the same number, never one behind the
+ * paper that moved on. Each count, as it comes in again, takes back as many moves as it moved itself, the oldest first,
+ * and only in the direction it moved: a paper dealt to them meanwhile is never taken for a vote counted.
+ */
+export function useUnheardMoves(heard: Record) {
+ const fresh = (): Unheard => ({ toDo: { seen: heard.toDo, moves: [] }, conflicts: { seen: heard.conflicts, moves: [] }, cast: { seen: heard.cast, moves: [] } });
+ const [unheard, setUnheard] = useState(fresh);
+ const kinds = Object.keys(heard) as Moved[];
+ if (kinds.some((kind) => unheard[kind].seen !== heard[kind])) {
+ const next = { ...unheard };
+ for (const kind of kinds) {
+ let by = heard[kind] - unheard[kind].seen;
+ const moves = [...unheard[kind].moves];
+ for (let at = 0; at < moves.length && by !== 0; ) {
+ if (Math.sign(moves[at]!) === Math.sign(by)) { by -= moves[at]!; moves.splice(at, 1); } else at++;
+ }
+ next[kind] = { seen: heard[kind], moves };
+ }
+ setUnheard(next);
+ }
+ const counts = Object.fromEntries(kinds.map((kind) => [kind, Math.max(0, heard[kind] + unheard[kind].moves.reduce((sum, move) => sum + move, 0))])) as Record;
+ const move = (kind: Moved, by: 1 | -1) => setUnheard((now) => ({ ...now, [kind]: { ...now[kind], moves: [...now[kind].moves, by] } }));
+ return { counts, move };
+}
+
/** A vote as a page casts it: a decision, a reason on Exclude, and the answers and note the person gave with it. */
export type Ballot = { decision: Decision; reason?: string; note?: string; answers?: Record };
@@ -264,7 +294,8 @@ export function useOpenScreening(id: string) {
return { papers, cost, short: Math.max(0, cost - (view.credits ?? Infinity)) };
},
// `onlyAt` takes back a vote only while it is still the one cast at that moment (convex/screening/voting.ts).
- vote: (paperId: Id<"screeningResults">, ballot: Ballot | null, { onlyWaiting = false, onlyAt }: { onlyWaiting?: boolean; onlyAt?: number } = {}) => vote({ jobId, paperId, ...(onlyWaiting ? { onlyWaiting } : {}), ...(onlyAt === undefined ? {} : { onlyAt }), decision: ballot?.decision ?? null, ...(ballot?.reason ? { reason: ballot.reason } : {}), ...(ballot?.note ? { note: ballot.note } : {}), ...(ballot?.answers ? { answers: ballot.answers } : {}) }),
+ // `answersOnly`: answers joining a vote already cast, which stays the vote it was (in Vote again too).
+ vote: (paperId: Id<"screeningResults">, ballot: Ballot | null, { onlyWaiting = false, onlyAt, answersOnly = false }: { onlyWaiting?: boolean; onlyAt?: number; answersOnly?: boolean } = {}) => vote({ jobId, paperId, ...(onlyWaiting ? { onlyWaiting } : {}), ...(onlyAt === undefined ? {} : { onlyAt }), ...(answersOnly ? { answersOnly } : {}), decision: ballot?.decision ?? null, ...(ballot?.reason ? { reason: ballot.reason } : {}), ...(ballot?.note ? { note: ballot.note } : {}), ...(ballot?.answers ? { answers: ballot.answers } : {}) }),
// A vote on a selection, on the papers that still wait for it; `null` with `onlyAt` takes back what one call cast. Returns the papers it changed, and the moment it cast them.
voteMany: (paperIds: Id<"screeningResults">[], ballot: Omit | null, onlyAt?: number) => voteMany({ jobId, paperIds, decision: ballot?.decision ?? null, ...(ballot?.reason ? { reason: ballot.reason } : {}), ...(ballot?.note ? { note: ballot.note } : {}), ...(onlyAt === undefined ? {} : { onlyAt }) }),
// Returns when the settlement was made, for an Undo to name; `onlyAt` takes one back only while it is still that one.
diff --git a/components/screening/workspace.tsx b/components/screening/workspace.tsx
index 4afe9e5f1..23803d5da 100644
--- a/components/screening/workspace.tsx
+++ b/components/screening/workspace.tsx
@@ -6,7 +6,7 @@
import { useWorkspaceSlug } from "@/lib/workspaces/href";
import { useItemHome } from "@/components/workspaces/item-home";
import { leaveBehind } from "./address";
-import { createContext, use, useEffect, useLayoutEffect, useReducer, useRef, type ReactNode } from "react";
+import { createContext, use, useEffect, useLayoutEffect, useMemo, useReducer, useRef, type ReactNode } from "react";
import { modelsAdvise } from "@/lib/screening/rules";
import { useFormatter, useTranslations } from "next-intl";
import { AnimatePresence, MotionConfig } from "motion/react";
@@ -39,7 +39,7 @@ import { useKept } from "./drafts";
import { SCREENINGS, useScreeningsCrumb, overviewHref, papersHref, reviewerHref, screenHref, settingsHref } from "./links";
import { ScreeningMenuItems, useScreeningOverlays } from "./overlays";
import { blindSays, settleMeans, settleSays, Faces, votesBy, StateChip, Help, LinkChip, TONE, TabCount, type Tone, INLINE_LINK } from "./pieces";
-import { useOpenScreening, type Open, modelsRead, perPaper } from "./store";
+import { useOpenScreening, useUnheardMoves, type Moved, type Open, modelsRead, perPaper } from "./store";
import { useWords, type Words } from "./words";
/** This part's messages, for a function that is handed them. */
@@ -84,7 +84,7 @@ if (typeof window !== "undefined" && "navigation" in window) {
export const listedNames = new Map();
/** What the frame gives the page inside it: the screening as the person sees it, and the ways to open what opens over it. */
-const Workspace = createContext<{ open: Open; exportTo: (tab: ExportTab) => void; finish: () => void; openActivity: () => void; takeOff: (reviewer: Reviewer) => void } | null>(null);
+const Workspace = createContext<{ open: Open; /** The votes the person cast, with theirs made here not counted yet. */ cast: number; /** A count a vote or an Undo made here moved, before the server's says so (./store.tsx `useUnheardMoves`). */ moved: (kind: Moved, by: 1 | -1) => void; exportTo: (tab: ExportTab) => void; finish: () => void; openActivity: () => void; takeOff: (reviewer: Reviewer) => void } | null>(null);
export function useWorkspace() {
const workspace = use(Workspace);
if (!workspace) throw new Error("A screening's page is shown inside its frame");
@@ -126,7 +126,9 @@ export function ScreeningWorkspace({ children }: { children: ReactNode }) {
const search = useSearchParams();
const view: View = segment === "screen" || segment === "papers" || segment === "settings" ? segment : "overview";
const read = useOpenScreening(id);
- const open = read ?? null;
+ // The counts a vote moves read the same everywhere in the frame, the moves of votes made here included, until the server's counts catch up.
+ const unheard = useUnheardMoves({ toDo: read?.toDo ?? 0, conflicts: read?.conflicts ?? 0, cast: read?.screening.reviewers.find((one) => one.id === read.me)?.tally?.cast ?? 0 });
+ const open = useMemo(() => (read ? { ...read, toDo: unheard.counts.toDo, conflicts: unheard.counts.conflicts } : null), [read, unheard.counts.toDo, unheard.counts.conflicts]);
// "Nothing new" stops being true by the clock alone, with nothing else to draw the strip again: a timer ends it.
useRedrawAt(open?.lastCheck?.added === 0 ? open.lastCheck.at + NOTHING_SHOWN_MS : null);
// Changes to its settings that were started and not saved.
@@ -436,7 +438,7 @@ export function ScreeningWorkspace({ children }: { children: ReactNode }) {
>
{/* A tab's page takes the place of the last at once, as every other page with tabs does: no fade that reads as the page loading again. */}
@@ -473,8 +475,8 @@ function passingKind(open: Open): PassingKind | null {
if (modelsNow === "gathering" || modelsNow === "checking" || modelsNow === "waiting" || modelsNow === "reading") return modelsNow;
// The papers that came in for the person are said here on every tab, a chip in the strip: as a row on some tabs and a chip on Screen, going from one to the other moved everything under the strip.
if (!open.screening.finishedAt && open.latest?.mine) return "arrived";
- // A check that found nothing says so, where nothing else has to be said.
- if (open.lastCheck?.added === 0 && Date.now() - open.lastCheck.at < NOTHING_SHOWN_MS) return "nothing";
+ // A check that found nothing says so, where nothing else has to be said: one that couldn't read a source didn't look everywhere, and its source says why.
+ if (open.lastCheck?.added === 0 && !open.lastCheck.unread && Date.now() - open.lastCheck.at < NOTHING_SHOWN_MS) return "nothing";
return null;
}
diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts
index e20ca2252..0b462860f 100644
--- a/convex/_generated/api.d.ts
+++ b/convex/_generated/api.d.ts
@@ -450,6 +450,7 @@ import type * as research_topics from "../research/topics.js";
import type * as research_web from "../research/web.js";
import type * as screening_access from "../screening/access.js";
import type * as screening_accounting from "../screening/accounting.js";
+import type * as screening_audit from "../screening/audit.js";
import type * as screening_bookkeeping from "../screening/bookkeeping.js";
import type * as screening_cards from "../screening/cards.js";
import type * as screening_checks from "../screening/checks.js";
@@ -1009,6 +1010,7 @@ declare const fullApi: ApiFromModules<{
"research/web": typeof research_web;
"screening/access": typeof screening_access;
"screening/accounting": typeof screening_accounting;
+ "screening/audit": typeof screening_audit;
"screening/bookkeeping": typeof screening_bookkeeping;
"screening/cards": typeof screening_cards;
"screening/checks": typeof screening_checks;
diff --git a/convex/bench/screening-team.bench.ts b/convex/bench/screening-team.bench.ts
index 443c50458..6cd8a2575 100644
--- a/convex/bench/screening-team.bench.ts
+++ b/convex/bench/screening-team.bench.ts
@@ -48,10 +48,10 @@ describe("a screening with reviewers, read by its pages", () => {
checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id,
sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id,
}));
- await t.mutation(internal.screening.gathering.begin, { sourceId });
+ await t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
for (let from = 0; from < size; from += 200) {
const step = Array.from({ length: Math.min(200, size - from) }, (_, n) => paper(from + n + 1, { title: `Paper ${from + n + 1}: ${text(100, from + n)}`, abstract: text(1_400, from + n) }));
- await t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: step, read: step.length, ended: from + 200 >= size });
+ await t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: step, read: step.length, ended: from + 200 >= size });
}
const ids = (await papersOf(t, jobId)).map((one) => one._id as Id<"screeningResults">);
// Ann votes on every paper, a third each way; Ben on the first half, agreeing on most, so some are in conflict.
diff --git a/convex/extraction/actions.ts b/convex/extraction/actions.ts
index 66afc4e04..cf3b61b31 100644
--- a/convex/extraction/actions.ts
+++ b/convex/extraction/actions.ts
@@ -279,7 +279,8 @@ async function readStep(ctx: ActionCtx, job: Doc<"extractionJobs">, clerkId: str
// From the first paper of its range, as many as the start counted.
const from = (selection.first ?? 1) + place.read;
const { papers: held, resume } = await heldPapers(ctx, await jobReader(ctx, job), { kind: "screening", jobId: selection.jobId }, { first: from, last: Math.min((selection.first ?? 1) + selection.count - 1, from + SETUP_STEP - 1) }, place.resume, selection.revision);
- const papers = held.map(({ venue, ...paper }): SetupPaper => ({ ...paper, venueName: venue, sourceType: "screening", sourceId: selection.jobId, screeningRevision: selection.revision }));
+ // A paper the screening had only as its PDF goes on as that file, which extraction reads as a paper's own PDF.
+ const papers = held.map(({ venue, file, pages: _pages, ...paper }): SetupPaper => ({ ...paper, ...(file ? { storageId: file } : {}), venueName: venue, sourceType: "screening", sourceId: selection.jobId, screeningRevision: selection.revision }));
const read = place.read + papers.length;
if (resume && read < selection.count) return { papers, next: { ...place, read, resume } };
if (read !== selection.count) throw createError("CONFLICT", "Screening inputs changed. Select the screening again before starting extraction.");
diff --git a/convex/migrations/screeningFacets.ts b/convex/migrations/screeningFacets.ts
index 50d4e5361..6982a8682 100644
--- a/convex/migrations/screeningFacets.ts
+++ b/convex/migrations/screeningFacets.ts
@@ -16,6 +16,8 @@ import { countEntries, paperEntries, recountVote, screeningCounts, staleWaiting,
* npx convex run migrations/screeningFacets:verify
*
* `verify` finds counts missing. `readVotes` takes out the stale ones a model's reading left (#1617).
+ *
+ * npx convex run migrations/screeningFacets:clearCopies
*/
const migrations = new Migrations(components.migrations, { internalMutation });
@@ -44,6 +46,14 @@ export const readVotes = migrations.define({
},
});
+/** The totals by reason and by source the progress row kept by hand beside these counts (#1619): read from the counts now, the copies go. */
+export const progressCopies = migrations.define({
+ table: "screeningJobProgress",
+ batchSize: 200,
+ migrateOne: async (_ctx, progress) => (progress.reasons !== undefined || progress.included !== undefined ? { reasons: undefined, included: undefined } : undefined),
+});
+export const clearCopies = migrations.runner([internal.migrations.screeningFacets.progressCopies]);
+
export const run = migrations.runner([internal.migrations.screeningFacets.papers, internal.migrations.screeningFacets.votes, internal.migrations.screeningFacets.readVotes]);
const tableValidator = v.union(v.literal("screeningResults"), v.literal("screeningVotes"));
diff --git a/convex/schema.ts b/convex/schema.ts
index b73f20040..ca85276a6 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -1693,7 +1693,10 @@ export default defineSchema({
capped: v.optional(v.literal(true)),
// Where a living check goes on from: when it last looked.
checkedAt: v.optional(v.number()),
- }).index("by_job", ["jobId"]),
+ })
+ .index("by_job", ["jobId"])
+ // The file an upload or a list of DOIs was read from: who else's screening reads it (./screening/screenings.ts `addSource`).
+ .index("by_file", ["set.file"]),
// The few facts of a paper that a screening's lists are narrowed by, a small row beside each paper, kept in step by
// a trigger (./screening/cards.ts): how many papers stand each way under any narrowing is counted from these.
@@ -1707,7 +1710,12 @@ export default defineSchema({
withdrawn: v.optional(v.literal(true)),
})
.index("by_result", ["resultId"])
- .index("by_job", ["jobId"]),
+ .index("by_job", ["jobId"])
+ // Papers' lists narrowed one way, in the order the papers were added, the other narrowings asked of each card in passing.
+ .index("by_job_and_result", ["jobId", "result"])
+ .index("by_job_and_source", ["jobId", "sourceId"])
+ .index("by_job_and_check", ["jobId", "checkId"])
+ .index("by_job_and_reason", ["jobId", "reason"]),
// A person's Zotero libraries as last read, and each library's collections, a row each (./zotero/tree.ts): the
// form that starts a screening pages through them and finds one by name here. `under`: what a collection holds
@@ -1766,7 +1774,8 @@ export default defineSchema({
workId: v.optional(v.string()),
})
.index("by_batch_and_at", ["batch", "at"])
- .index("by_workId", ["workId"]),
+ .index("by_workId", ["workId"])
+ .index("by_file", ["file"]),
// A record a source held that the screening already had: the record, and the paper it was merged into.
screeningMerged: defineTable({
diff --git a/convex/screening/audit.ts b/convex/screening/audit.ts
new file mode 100644
index 000000000..8df01e36f
--- /dev/null
+++ b/convex/screening/audit.ts
@@ -0,0 +1,135 @@
+/**
+ * A screening's rows checked against one another: what its pages and files show must follow from what is stored.
+ * The rules test runs it after every change made mid-course (./changes.test.ts), and it runs on a live screening:
+ *
+ * npx convex run screening/audit:check '{"jobId": "..."}'
+ *
+ * Reads a whole screening: for one person's look at a screening of a few thousand papers, not for a page.
+ */
+import { v } from "convex/values";
+import type { Id } from "../_generated/dataModel";
+import { internalQuery, type QueryCtx } from "../_generated/server";
+import { isFinal, settle, type Ballot, type Result } from "../../lib/screening/rules";
+import { tallyOfReviewer, tallyUnder, type Tally } from "./facets";
+
+const DECISIONS = ["include", "maybe", "exclude"] as const;
+/** Rows of one kind an audit reads: a screening's papers, votes or cards, which a screening of 5,000 papers stays well within. */
+const AUDIT_ROWS = 30_000;
+
+/** What doesn't add up, how many votes each reviewer cast (by Clerk id, "a model" for a model), and where each paper stands. */
+export async function auditJob(ctx: QueryCtx, jobId: Id<"screeningJobs">) {
+ const job = (await ctx.db.get("screeningJobs", jobId))!;
+ const rule = job.rule!;
+ const reviewers = await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(AUDIT_ROWS);
+ const byId = new Map(reviewers.map((one) => [one._id, one]));
+ const names = new Map(await Promise.all(reviewers.map(async (one) => [one._id, one.userId ? (await ctx.db.get("users", one.userId))!.clerkId : "a model"] as const)));
+ const papers = await ctx.db.query("screeningResults").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(AUDIT_ROWS);
+ const votes = await ctx.db.query("screeningVotes").withIndex("by_job_and_place", (q) => q.eq("jobId", jobId)).take(AUDIT_ROWS);
+ const cards = await ctx.db.query("screeningCards").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(AUDIT_ROWS);
+ const progress = (await ctx.db.query("screeningJobProgress").withIndex("by_job", (q) => q.eq("jobId", jobId)).unique())!;
+ const pairs = await ctx.db.query("screeningAgreement").withIndex("by_job_and_a_and_b", (q) => q.eq("jobId", jobId)).take(AUDIT_ROWS);
+ const problems: string[] = [];
+ const placed = papers.filter((paper) => paper.place !== undefined);
+ const live = placed.filter((paper) => !paper.withdrawn);
+ const liveIds = new Set(live.map((paper) => paper._id));
+ const active = reviewers.filter((one) => one.kind === "person" && one.left === undefined);
+
+ // Where its papers stand, as the progress row counts them.
+ const counts = { include: 0, maybe: 0, exclude: 0, conflict: 0 };
+ for (const paper of live) if (paper.result && paper.result !== "waiting") counts[paper.result]++;
+ if (JSON.stringify(counts) !== JSON.stringify({ include: 0, maybe: 0, exclude: 0, conflict: 0, ...progress.counts })) problems.push(`counts say ${JSON.stringify(progress.counts)}, the papers ${JSON.stringify(counts)}`);
+ const reasons = Object.values(progress.reasons ?? {}).reduce((sum, n) => sum + n, 0);
+ if (reasons !== counts.exclude) problems.push(`${reasons} reasons for ${counts.exclude} excluded papers`);
+
+ // Each paper's card, which the Papers page lists and narrows by, says what the paper says.
+ const cardOf = new Map(cards.map((card) => [card.resultId, card]));
+ for (const paper of placed) {
+ const card = cardOf.get(paper._id);
+ const want = { result: paper.result ?? "waiting", sourceId: paper.sourceId, checkId: paper.checkId, reason: paper.reason, withdrawn: paper.withdrawn };
+ if (!card) problems.push(`${paper.title}: has no card`);
+ else if (JSON.stringify(want) !== JSON.stringify({ result: card.result, sourceId: card.sourceId, checkId: card.checkId, reason: card.reason, withdrawn: card.withdrawn })) problems.push(`${paper.title}: its card says ${card.result}${card.withdrawn ? ", withdrawn" : ""}, the paper ${want.result}${want.withdrawn ? ", withdrawn" : ""}`);
+ }
+ if (cards.length !== placed.length) problems.push(`${cards.length} cards for ${placed.length} papers`);
+
+ // Each reviewer's votes, as the progress row counts them, and the papers their row says they hold.
+ for (const reviewer of reviewers) {
+ const mine = votes.filter((vote) => vote.reviewerId === reviewer._id);
+ const cast = mine.filter((vote) => vote.status === "cast" && liveIds.has(vote.resultId));
+ const kept = progress.reviewers?.[reviewer._id];
+ if ((kept?.cast ?? 0) !== cast.length) problems.push(`${names.get(reviewer._id)}: counted ${kept?.cast ?? 0} votes, has ${cast.length}`);
+ for (const decision of DECISIONS) if ((kept?.[decision] ?? 0) !== cast.filter((vote) => vote.decision === decision).length) problems.push(`${names.get(reviewer._id)}: counted ${kept?.[decision] ?? 0} ${decision}, has ${cast.filter((vote) => vote.decision === decision).length}`);
+ const holds = mine.filter((vote) => vote.status !== "discarded").length;
+ if (reviewer.dealt !== holds) problems.push(`${names.get(reviewer._id)}: said to hold ${reviewer.dealt} papers, holds ${holds}`);
+ }
+
+ for (const paper of live) {
+ const on = votes.filter((vote) => vote.resultId === paper._id);
+ const result: Result = paper.result ?? "waiting";
+ const ballots: Ballot[] = on.map((vote) => ({ status: vote.status, decision: vote.decision, at: vote.at, reason: vote.reason }));
+ // A paper settled before the settings last changed keeps its result. Any other stands where its votes put it.
+ const held = isFinal(result) && !paper.resolved && !paper.reopen && (paper.settledAt ?? 0) <= (job.heldAt ?? 0);
+ const voted = paper.resolved ? paper.resolved.decision : settle(rule.settle, ballots);
+ if (!held && result !== voted) problems.push(`${paper.title}: stands at ${result}, its votes say ${voted}`);
+ const people = on.filter((vote) => byId.get(vote.reviewerId)?.kind === "person");
+ const places = people.filter((vote) => vote.status === "waiting" || vote.status === "cast");
+ const taken = people.filter((vote) => vote.status !== "discarded").map((vote) => vote.reviewerId);
+ if (new Set(taken).size !== taken.length) problems.push(`${paper.title}: someone holds two places`);
+ if (isFinal(result)) {
+ if (people.some((vote) => vote.status === "waiting")) problems.push(`${paper.title}: settled, and still waits for someone`);
+ continue;
+ }
+ for (const vote of people) if (vote.status === "waiting" && byId.get(vote.reviewerId)?.left !== undefined) problems.push(`${paper.title}: waits for ${names.get(vote.reviewerId)}, who left`);
+ // A split under "everyone agrees" can't become agreement: it keeps the places it had, and its resolver settles it.
+ if (result === "conflict" && rule.settle === "all") continue;
+ // An open paper has the places its rule asks for: its votes, and the people still to vote up to the rule's number.
+ const cast = places.filter((vote) => vote.status === "cast");
+ const free = active.filter((one) => !cast.some((vote) => vote.reviewerId === one._id)).length;
+ const asked = cast.length + Math.min(free, Math.max(0, (rule.each === "all" ? Infinity : rule.each) - cast.length));
+ if (places.length !== asked) problems.push(`${paper.title}: ${places.length} places (${places.map((vote) => `${names.get(vote.reviewerId)} ${vote.status}`).join(", ")}), its rule asks for ${asked}`);
+ }
+
+ // How far each pair agrees, counted again from their votes.
+ const order = new Map(reviewers.map((one, at) => [one._id, at]));
+ const matrices = new Map();
+ for (const paper of live) {
+ const cast = votes.filter((vote) => vote.resultId === paper._id && vote.status === "cast" && vote.decision);
+ for (const [i, x] of cast.entries()) for (const y of cast.slice(i + 1)) {
+ const [a, b] = order.get(x.reviewerId)! <= order.get(y.reviewerId)! ? [x, y] : [y, x];
+ const key = `${a.reviewerId}:${b.reviewerId}`;
+ const cells = matrices.get(key) ?? matrices.set(key, Array.from({ length: 9 }, () => 0)).get(key)!;
+ cells[DECISIONS.indexOf(a.decision!) * 3 + DECISIONS.indexOf(b.decision!)]!++;
+ }
+ }
+ for (const pair of pairs) {
+ const counted = matrices.get(`${pair.a}:${pair.b}`) ?? Array.from({ length: 9 }, () => 0);
+ if (pair.matrix.join() !== counted.join()) problems.push(`${names.get(pair.a)} and ${names.get(pair.b)}: agreement kept as ${pair.matrix.join()}, their votes give ${counted.join()}`);
+ matrices.delete(`${pair.a}:${pair.b}`);
+ }
+ for (const [key, counted] of matrices) if (counted.some((n) => n > 0)) problems.push(`a pair's agreement isn't kept: ${key}`);
+
+ // The counts Papers narrows by (./facets.ts), against the cards and votes: a moment behind the writes, so read once they settle.
+ const tally = (results: Result[]): Tally => ({ include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0, ...Object.fromEntries((["include", "maybe", "exclude", "conflict", "waiting"] as const).map((result) => [result, results.filter((one) => one === result).length])) });
+ const liveCards = cards.filter((card) => !card.withdrawn);
+ for (const sourceId of new Set(liveCards.flatMap((card) => (card.sourceId ? [card.sourceId] : [])))) {
+ const [counted, read] = [await tallyUnder(ctx, jobId, { source: sourceId }), tally(liveCards.filter((card) => card.sourceId === sourceId).map((card) => card.result))];
+ if (JSON.stringify(counted) !== JSON.stringify(read)) problems.push(`source ${sourceId}: counted ${JSON.stringify(counted)}, its papers ${JSON.stringify(read)}`);
+ }
+ for (const reviewer of reviewers) {
+ const on = votes.filter((vote) => vote.reviewerId === reviewer._id && (vote.status === "waiting" || vote.status === "cast" || vote.status === "failed")).flatMap((vote) => {
+ const card = cardOf.get(vote.resultId);
+ return card && !card.withdrawn && card.result ? [card.result] : [];
+ });
+ const counted = await tallyOfReviewer(ctx, reviewer._id, ["include", "maybe", "exclude", "cast", "waiting", "failed"]);
+ if (JSON.stringify(counted) !== JSON.stringify(tally(on))) problems.push(`${names.get(reviewer._id)}: counted on ${JSON.stringify(counted)}, their papers ${JSON.stringify(tally(on))}`);
+ }
+
+ const cast = Object.fromEntries(reviewers.map((one) => [names.get(one._id)!, progress.reviewers?.[one._id]?.cast ?? 0]));
+ return { problems, cast, stands: Object.fromEntries(placed.map((paper) => [paper._id, paper.withdrawn ? "withdrawn" : (paper.result ?? "waiting")])) as Record };
+}
+
+/** What doesn't add up in one screening; an empty list when its rows agree. */
+export const check = internalQuery({
+ args: { jobId: v.id("screeningJobs") },
+ returns: v.array(v.string()),
+ handler: async (ctx, { jobId }) => (await auditJob(ctx, jobId)).problems,
+});
diff --git a/convex/screening/bookkeeping.ts b/convex/screening/bookkeeping.ts
index 3efcf2c7f..1e666cada 100644
--- a/convex/screening/bookkeeping.ts
+++ b/convex/screening/bookkeeping.ts
@@ -367,19 +367,29 @@ export const bookkeep = internalMutation({
const freedVotes = new Map, number>();
for (const [jobId, jobResults] of byJob) {
const workspaceId = (await ctx.db.get("screeningJobs", jobId))?.workspaceId;
- try {
- const done: { papers?: number; votes?: number } = await ctx.runMutation(internal.screening.bookkeeping.bookkeepJob, { jobId, results: jobResults.map((result) => result._id) });
+ const keep = async (batch: Doc<"screeningResults">[]) => {
+ const done: { papers?: number; votes?: number } = await ctx.runMutation(internal.screening.bookkeeping.bookkeepJob, { jobId, results: batch.map((result) => result._id) });
if (workspaceId && done.papers !== undefined) freed.set(workspaceId, (freed.get(workspaceId) ?? 0) + done.papers);
if (workspaceId && done.votes !== undefined) freedVotes.set(workspaceId, (freedVotes.get(workspaceId) ?? 0) + done.votes);
- } catch (error) {
- // Every screening of the deployment waits behind this queue: one whose papers can't be bookkept must not hold the
- // others up. Its papers leave the queue as they stood, to be tried again when one of them next changes, and what
- // went wrong is logged with the screening it happened in.
- console.error("[screening] A screening's papers couldn't be bookkept", { jobId, papers: jobResults.length, error: String(error instanceof Error ? (error.stack ?? error.message) : error).slice(0, 1500) });
- for (const result of jobResults) await ctx.db.patch("screeningResults", result._id, { doneAt: undefined });
- // The readings that came back on them held slots of the workspace, which its other screenings wait for: those are given back whatever is wrong with this one.
- const released: number = await ctx.runMutation(internal.screening.bookkeeping.releaseSlots, { jobId, results: jobResults.map((result) => result._id) }).catch(() => 0);
- if (workspaceId && released) freedVotes.set(workspaceId, (freedVotes.get(workspaceId) ?? 0) + released);
+ };
+ try {
+ await keep(jobResults);
+ } catch {
+ // One paper that can't be bookkept rolls back its whole batch: each is tried alone, so only that one is held back.
+ for (const result of jobResults) {
+ try {
+ await keep([result]);
+ } catch (error) {
+ // Every screening of the deployment waits behind this queue: a paper that can't be bookkept must not hold the
+ // others up. It leaves the queue as it stood, to be tried again when it next changes, and what went wrong is
+ // logged with the screening it happened in.
+ console.error("[screening] A screening's paper couldn't be bookkept", { jobId, paper: result._id, error: String(error instanceof Error ? (error.stack ?? error.message) : error).slice(0, 1500) });
+ await ctx.db.patch("screeningResults", result._id, { doneAt: undefined });
+ // The readings that came back on it held slots of the workspace, which its other screenings wait for: those are given back whatever is wrong with it.
+ const released: number = await ctx.runMutation(internal.screening.bookkeeping.releaseSlots, { jobId, results: [result._id] }).catch(() => 0);
+ if (workspaceId && released) freedVotes.set(workspaceId, (freedVotes.get(workspaceId) ?? 0) + released);
+ }
+ }
}
}
for (const [workspaceId, finished] of freed) await startWaitingPapers(ctx, workspaceId, finished, facts);
diff --git a/convex/screening/cards.ts b/convex/screening/cards.ts
index 3b67aae9f..d16bd36ff 100644
--- a/convex/screening/cards.ts
+++ b/convex/screening/cards.ts
@@ -12,9 +12,19 @@ import type { MutationCtx } from "../_generated/server";
const FACTS = ["result", "sourceId", "checkId", "reason", "withdrawn"] as const satisfies ReadonlyArray>;
-/** The trigger that keeps a paper's card in step with it. Only a paper of a screening with reviewers has a place, and a card. */
+/**
+ * The trigger that keeps a paper's card in step with it. Only a paper of a screening with reviewers has a place, and a
+ * card. Its papers taken out with their source are counted on its progress row in the same write, so how many papers
+ * the screening holds is exact at every moment: what the plan's cap reads (./gathering.ts `fill`).
+ */
export async function keepCard(ctx: MutationCtx, change: Change) {
const [was, now] = [change.oldDoc, change.newDoc];
+ const out = (paper: typeof was) => (paper?.place !== undefined && paper.withdrawn ? 1 : 0);
+ const moved = out(now) - out(was);
+ if (moved) {
+ const progress = await ctx.db.query("screeningJobProgress").withIndex("by_job", (q) => q.eq("jobId", (now ?? was)!.jobId)).unique();
+ if (progress) await ctx.db.patch("screeningJobProgress", progress._id, { withdrawn: Math.max(0, (progress.withdrawn ?? 0) + moved) });
+ }
const held = was?.place === undefined ? null : await ctx.db.query("screeningCards").withIndex("by_result", (q) => q.eq("resultId", change.id)).unique();
if (!now || now.place === undefined) {
if (held) await ctx.db.delete("screeningCards", held._id);
diff --git a/convex/screening/changes.test.ts b/convex/screening/changes.test.ts
index 1648f394b..5eb344f81 100644
--- a/convex/screening/changes.test.ts
+++ b/convex/screening/changes.test.ts
@@ -1,10 +1,11 @@
// Changing a running screening (plans/screening-reviewers): every rule against every change made mid-course.
-// After each change the screening's rows are audited against one another (counts, tallies, places, results), and
+// After each change the screening's rows are audited against one another (./audit.ts), and
// what the change was said to do before it was made is compared with what it then did.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { api } from "../_generated/api";
import type { Id } from "../_generated/dataModel";
-import { isFinal, settle, type Ballot, type Result } from "../../lib/screening/rules";
+import { isFinal, type Result } from "../../lib/screening/rules";
+import { auditJob } from "./audit";
import { runAll, settleAll, started, team, type Team } from "./reviewers.test-support";
beforeEach(() => vi.useFakeTimers());
@@ -18,89 +19,7 @@ const PAPERS = 9;
const run = (t: T) => runAll(t, vi.runAllTimers);
-/** A screening's rows, checked against one another. Returns what doesn't add up, and where each paper stands. */
-async function audit(t: T, jobId: Id<"screeningJobs">) {
- return t.run(async (ctx) => {
- const job = (await ctx.db.get("screeningJobs", jobId))!;
- const rule = job.rule!;
- const reviewers = await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect();
- const byId = new Map(reviewers.map((one) => [one._id, one]));
- const names = new Map(await Promise.all(reviewers.map(async (one) => [one._id, one.userId ? (await ctx.db.get("users", one.userId))!.clerkId : "a model"] as const)));
- const papers = await ctx.db.query("screeningResults").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect();
- const votes = await ctx.db.query("screeningVotes").withIndex("by_job_and_place", (q) => q.eq("jobId", jobId)).collect();
- const progress = (await ctx.db.query("screeningJobProgress").withIndex("by_job", (q) => q.eq("jobId", jobId)).unique())!;
- const pairs = await ctx.db.query("screeningAgreement").withIndex("by_job_and_a_and_b", (q) => q.eq("jobId", jobId)).collect();
- const problems: string[] = [];
- const live = papers.filter((paper) => !paper.withdrawn);
- const liveIds = new Set(live.map((paper) => paper._id));
- const active = reviewers.filter((one) => one.kind === "person" && one.left === undefined);
-
- // Where its papers stand, as the progress row counts them.
- const counts = { include: 0, maybe: 0, exclude: 0, conflict: 0 };
- for (const paper of live) if (paper.result && paper.result !== "waiting") counts[paper.result]++;
- if (JSON.stringify(counts) !== JSON.stringify({ include: 0, maybe: 0, exclude: 0, conflict: 0, ...progress.counts })) problems.push(`counts say ${JSON.stringify(progress.counts)}, the papers ${JSON.stringify(counts)}`);
- const reasons = Object.values(progress.reasons ?? {}).reduce((sum, n) => sum + n, 0);
- if (reasons !== counts.exclude) problems.push(`${reasons} reasons for ${counts.exclude} excluded papers`);
-
- // Each reviewer's votes, as the progress row counts them, and the papers their row says they hold.
- for (const reviewer of reviewers) {
- const mine = votes.filter((vote) => vote.reviewerId === reviewer._id);
- const cast = mine.filter((vote) => vote.status === "cast" && liveIds.has(vote.resultId));
- const kept = progress.reviewers?.[reviewer._id];
- if ((kept?.cast ?? 0) !== cast.length) problems.push(`${names.get(reviewer._id)}: counted ${kept?.cast ?? 0} votes, has ${cast.length}`);
- for (const decision of DECISIONS) if ((kept?.[decision] ?? 0) !== cast.filter((vote) => vote.decision === decision).length) problems.push(`${names.get(reviewer._id)}: counted ${kept?.[decision] ?? 0} ${decision}, has ${cast.filter((vote) => vote.decision === decision).length}`);
- const holds = mine.filter((vote) => vote.status !== "discarded").length;
- if (reviewer.dealt !== holds) problems.push(`${names.get(reviewer._id)}: said to hold ${reviewer.dealt} papers, holds ${holds}`);
- }
-
- for (const paper of live) {
- const on = votes.filter((vote) => vote.resultId === paper._id);
- const result: Result = paper.result ?? "waiting";
- const ballots: Ballot[] = on.map((vote) => ({ status: vote.status, decision: vote.decision, at: vote.at, reason: vote.reason }));
- // A paper settled before the settings last changed keeps its result. Any other stands where its votes put it.
- const held = isFinal(result) && !paper.resolved && !paper.reopen && (paper.settledAt ?? 0) <= (job.heldAt ?? 0);
- const voted = paper.resolved ? paper.resolved.decision : settle(rule.settle, ballots);
- if (!held && result !== voted) problems.push(`${paper.title}: stands at ${result}, its votes say ${voted}`);
- const people = on.filter((vote) => byId.get(vote.reviewerId)?.kind === "person");
- const places = people.filter((vote) => vote.status === "waiting" || vote.status === "cast");
- const taken = people.filter((vote) => vote.status !== "discarded").map((vote) => vote.reviewerId);
- if (new Set(taken).size !== taken.length) problems.push(`${paper.title}: someone holds two places`);
- if (isFinal(result)) {
- if (people.some((vote) => vote.status === "waiting")) problems.push(`${paper.title}: settled, and still waits for someone`);
- continue;
- }
- for (const vote of people) if (vote.status === "waiting" && byId.get(vote.reviewerId)?.left !== undefined) problems.push(`${paper.title}: waits for ${names.get(vote.reviewerId)}, who left`);
- // A split under "everyone agrees" can't become agreement: it keeps the places it had, and its resolver settles it.
- if (result === "conflict" && rule.settle === "all") continue;
- // An open paper has the places its rule asks for: its votes, and the people still to vote up to the rule's number.
- const cast = places.filter((vote) => vote.status === "cast");
- const free = active.filter((one) => !cast.some((vote) => vote.reviewerId === one._id)).length;
- const asked = cast.length + Math.min(free, Math.max(0, (rule.each === "all" ? Infinity : rule.each) - cast.length));
- if (places.length !== asked) problems.push(`${paper.title}: ${places.length} places (${places.map((vote) => `${names.get(vote.reviewerId)} ${vote.status}`).join(", ")}), its rule asks for ${asked}`);
- }
-
- // How far each pair agrees, counted again from their votes.
- const order = new Map(reviewers.map((one, at) => [one._id, at]));
- const matrices = new Map();
- for (const paper of live) {
- const cast = votes.filter((vote) => vote.resultId === paper._id && vote.status === "cast" && vote.decision);
- for (const [i, x] of cast.entries()) for (const y of cast.slice(i + 1)) {
- const [a, b] = order.get(x.reviewerId)! <= order.get(y.reviewerId)! ? [x, y] : [y, x];
- const cells = matrices.get(`${a.reviewerId}:${b.reviewerId}`) ?? matrices.set(`${a.reviewerId}:${b.reviewerId}`, Array.from({ length: 9 }, () => 0)).get(`${a.reviewerId}:${b.reviewerId}`)!;
- cells[DECISIONS.indexOf(a.decision!) * 3 + DECISIONS.indexOf(b.decision!)]!++;
- }
- }
- for (const pair of pairs) {
- const counted = matrices.get(`${pair.a}:${pair.b}`) ?? Array.from({ length: 9 }, () => 0);
- if (pair.matrix.join() !== counted.join()) problems.push(`${names.get(pair.a)} and ${names.get(pair.b)}: agreement kept as ${pair.matrix.join()}, their votes give ${counted.join()}`);
- matrices.delete(`${pair.a}:${pair.b}`);
- }
- for (const [key, counted] of matrices) if (counted.some((n) => n > 0)) problems.push(`a pair's agreement isn't kept: ${key}`);
-
- const cast = Object.fromEntries(reviewers.map((one) => [names.get(one._id)!, progress.reviewers?.[one._id]?.cast ?? 0]));
- return { problems, cast, stands: Object.fromEntries(papers.map((paper) => [paper._id, paper.withdrawn ? "withdrawn" : (paper.result ?? "waiting")])) as Record };
- });
-}
+const audit = (t: T, jobId: Id<"screeningJobs">) => t.run((ctx) => auditJob(ctx, jobId));
/** Votes on a screening's papers in a fixed pattern: every holder includes one, the first two split on the next, and one alone votes Maybe on the third. */
async function voteAround({ t, as, workspaceId }: Team, jobId: Id<"screeningJobs">) {
diff --git a/convex/screening/dealing.ts b/convex/screening/dealing.ts
index fc723b30f..1d390ef11 100644
--- a/convex/screening/dealing.ts
+++ b/convex/screening/dealing.ts
@@ -14,6 +14,7 @@ import { actorIn } from "../workspaces/actor";
import { readsPdfs } from "../../lib/assistant/files";
import { readsPdfOf } from "../../lib/pricing/estimate";
import { MAX_REVIEWERS, MAX_SOURCE_ROWS } from "./validators";
+import { tallyOfReviewer } from "./facets";
type Reviewer = Doc<"screeningReviewers">;
@@ -86,9 +87,11 @@ export const papersOf = (job: Pick, "totalPapers">, progres
/** The papers that still wait for a reviewer: the ones they were given, less the ones they voted on, a model couldn't read, and the ones settled without them. */
export const waitingOf = (reviewer: Pick, tally: { cast?: number; failed?: number; closed?: number } | undefined) => Math.max(0, theirsOf({ dealt: reviewer.dealt, closed: tally?.closed }) - gotThrough(tally));
-/** How many of the papers a check brought still wait for one reviewer's vote, counted up to `most`. */
-export async function newFor(ctx: Pick, reviewerId: Id<"screeningReviewers">, check: Pick, "from" | "added">, most: number) {
- return (await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_place", (q) => q.eq("reviewerId", reviewerId).eq("status", "waiting").gte("place", check.from).lt("place", check.from + check.added)).take(most)).length;
+/** New papers of a check counted for one reviewer, past which a banner or an email says so many and more. */
+export const NEW_COUNTED = 500;
+/** How many of the papers a check brought still wait for one reviewer's vote, counted up to `NEW_COUNTED`. */
+export async function newFor(ctx: Pick, reviewerId: Id<"screeningReviewers">, check: Pick, "from" | "added">) {
+ return (await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_place", (q) => q.eq("reviewerId", reviewerId).eq("status", "waiting").gte("place", check.from).lt("place", check.from + check.added)).take(NEW_COUNTED)).length;
}
/** Checks of its sources looked through for the last that brought papers. */
@@ -144,11 +147,15 @@ export async function askedOf(ctx: Pick, jobId: Id<"screeningJob
/** Where a question put to someone is opened for them to answer. */
export type AskedWhere = "conflicts" | "screen" | "done" | "papers";
+/** Papers in conflict counted for whoever settles them, past which the count says so many. */
+const CONFLICTS_COUNTED = 500;
+const waitingIn = (tally: Record) => Object.values(tally).reduce((sum, n) => sum + n, 0);
+
/**
* What waits for one person on one screening: papers for their vote and conflicts for them to settle, none once it
* is finished, and the papers someone asked them about. One function, for the list, the rail and every summary.
*/
-export async function waitsOn(ctx: Pick, job: Doc<"screeningJobs">, userId: Id<"users">, reviewer: Doc<"screeningReviewers"> | null, progress: Doc<"screeningJobProgress"> | null) {
+export async function waitsOn(ctx: Pick, job: Doc<"screeningJobs">, userId: Id<"users">, reviewer: Doc<"screeningReviewers"> | null) {
const open = job.finishedAt === undefined;
const asked = await askedOf(ctx, job._id, userId);
// Where the first question is answered: on Screen among the conflicts by whoever settles a paper in conflict, on Screen by one of its reviewers (in Done once they voted on it), and in Papers by anyone else.
@@ -156,9 +163,10 @@ export async function waitsOn(ctx: Pick, job: Doc<"screeningJobs
// A reviewer who has voted on the paper finds it in Done, never under a To do that doesn't hold it.
const voted = first && reviewer && reviewer.left === undefined ? (await ctx.db.query("screeningVotes").withIndex("by_result_and_reviewer", (q) => q.eq("resultId", first._id).eq("reviewerId", reviewer._id)).first())?.status === "cast" : false;
const askedWhere: AskedWhere | undefined = first ? (job.rule?.resolver === userId && first.result === "conflict" ? "conflicts" : reviewer && reviewer.left === undefined ? (voted ? "done" : "screen") : "papers") : undefined;
+ // Read from the person's own votes and the papers in conflict, never from the screening's running counts: a vote anyone else casts doesn't make every page that says what waits for the person read again.
return {
- forYou: open && reviewer && reviewer.left === undefined ? waitingOf(reviewer, progress?.reviewers?.[reviewer._id]) : 0,
- conflicts: open && job.rule?.resolver === userId ? (progress?.counts?.conflict ?? 0) : 0,
+ forYou: open && reviewer && reviewer.left === undefined ? waitingIn(await tallyOfReviewer(ctx as QueryCtx, reviewer._id, ["waiting"])) : 0,
+ conflicts: open && job.rule?.resolver === userId ? (await ctx.db.query("screeningCards").withIndex("by_job_and_result", (q) => q.eq("jobId", job._id).eq("result", "conflict")).take(CONFLICTS_COUNTED)).length : 0,
asked,
...(askedWhere ? { askedWhere } : {}),
};
diff --git a/convex/screening/doiRecords.ts b/convex/screening/doiRecords.ts
index a81bd243e..f3c820673 100644
--- a/convex/screening/doiRecords.ts
+++ b/convex/screening/doiRecords.ts
@@ -5,6 +5,7 @@
* is known of.
*/
import type { FileRecord } from "../../lib/screening/files";
+import { createError } from "../lib/errors";
/** DOIs asked of the registries at once, and how long one may take. */
const AT_ONCE = 16;
@@ -13,14 +14,18 @@ const HEADERS = { Accept: "application/json", "User-Agent": "Openscholar (https:
/** A registry's abstract as plain text: Crossref sends JATS markup, with a heading that says "Abstract". */
const plain = (text: string | undefined) => text?.replace(/<[^>]+>/g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/\s+/g, " ").trim().replace(/^abstract[:.]?\s+/i, "") || undefined;
-/** A registry's answer. One that didn't come, or came as a refusal other than "no such DOI", is asked for once more: a busy registry is not a DOI nothing is known of. */
+/**
+ * A registry's answer, or null for a DOI it has no record of. One that didn't come, or came as a refusal other than "no
+ * such DOI", is asked for once more, and then the reading stops with why: a busy registry is not a DOI nothing is
+ * known of, and the source is read again once it answers.
+ */
const read = async (url: string): Promise => {
for (let tries = 0; tries < 2; tries++) {
const response = await fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(WAIT_MS) }).catch(() => null);
if (response?.ok) return await response.json().catch(() => null);
if (response?.status === 404) return null;
}
- return null;
+ throw createError("EXTERNAL_SERVICE_ERROR", "Crossref or DataCite didn't answer. Read this source again in a few minutes.");
};
type Crossref = { message?: { title?: string[]; abstract?: string; author?: Array<{ given?: string; family?: string; name?: string }>; issued?: { "date-parts"?: number[][] }; "container-title"?: string[] } };
diff --git a/convex/screening/facets.ts b/convex/screening/facets.ts
index e6f556b8f..27b7ca687 100644
--- a/convex/screening/facets.ts
+++ b/convex/screening/facets.ts
@@ -149,10 +149,15 @@ export async function tallyUnder(ctx: QueryCtx, jobId: Id<"screeningJobs">, unde
return Object.fromEntries(RESULTS.map((result, at) => [result, counts[at]!])) as Tally;
}
+/** How many of a screening's papers are excluded for each of `reasons`, those with none left out. */
+export async function excludedFor(ctx: QueryCtx, jobId: Id<"screeningJobs">, reasons: string[]): Promise> {
+ const counts = await countEach(ctx, reasonsOf(jobId), reasons);
+ return Object.fromEntries(reasons.flatMap((reason, at) => (counts[at] ? [[reason, counts[at]!]] : [])));
+}
+
/** How many of a screening's papers are excluded for `reason`: they are the only ones that stand that way. */
export async function tallyForReason(ctx: QueryCtx, jobId: Id<"screeningJobs">, reason: string): Promise {
- const [excluded] = await countEach(ctx, reasonsOf(jobId), [reason]);
- return { ...none(), exclude: excluded! };
+ return { ...none(), exclude: (await excludedFor(ctx, jobId, [reason]))[reason] ?? 0 };
}
/** How many of the papers a reviewer stands one of `ways` on stand each way. */
diff --git a/convex/screening/files.test.ts b/convex/screening/files.test.ts
index a13f10e6f..7a768bfec 100644
--- a/convex/screening/files.test.ts
+++ b/convex/screening/files.test.ts
@@ -51,10 +51,10 @@ describe("what a source leaves out", () => {
const { checkId, sourceId } = await made.t.run(async (ctx) => ({ checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id }));
const sourceOf = () => made.t.run((ctx) => ctx.db.get("screeningSources", sourceId));
const leftOut = () => made.t.run((ctx) => ctx.db.query("screeningLeftOut").collect());
- await made.t.mutation(internal.screening.gathering.begin, { sourceId });
+ await made.t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
// A Zotero library reads a paper filed in two collections twice: in one step, and again in a later one.
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [bare, bare, paper(2)], read: 3, ended: false });
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [bare], read: 1, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: [bare, bare, paper(2)], read: 3, ended: false });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: [bare], read: 1, ended: true });
expect(await sourceOf()).toMatchObject({ taken: 1, left: 1, bare: 1 });
expect(await leftOut()).toHaveLength(1);
@@ -63,10 +63,10 @@ describe("what a source leaves out", () => {
await ctx.db.patch("screeningSources", sourceId, { ...readAgain((await ctx.db.get("screeningSources", sourceId))!), state: "reading" });
return checkId;
});
- await made.t.mutation(internal.screening.gathering.fill, { checkId: await again(checkId), sourceId, papers: [bare, bare], read: 2, ended: false });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId: await again(checkId), sourceId, pass: 1, papers: [bare, bare], read: 2, ended: false });
expect(await sourceOf()).toMatchObject({ left: 1, bare: 1 });
const later = await made.t.run((ctx) => ctx.db.insert("screeningChecks", { jobId, at: 2, state: "running", beat: 2, from: 1, found: 0, added: 0 }));
- await made.t.mutation(internal.screening.gathering.fill, { checkId: await again(later), sourceId, papers: [bare, bare], read: 2, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId: await again(later), sourceId, pass: 2, papers: [bare, bare], read: 2, ended: true });
expect(await sourceOf()).toMatchObject({ left: 1, bare: 1 });
expect(await leftOut()).toHaveLength(1);
});
@@ -77,16 +77,16 @@ describe("what a source leaves out", () => {
const { checkId, sourceId } = await made.t.run(async (ctx) => ({ checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id }));
const sourceOf = () => made.t.run((ctx) => ctx.db.get("screeningSources", sourceId));
const listed = async () => (await made.as.ann!.query(api.screening.view.leftOut, { workspaceId: made.workspaceId, jobId, sourceId, paginationOpts: { cursor: null, numItems: 10 } })).page.map((row) => row.name).sort();
- await made.t.mutation(internal.screening.gathering.begin, { sourceId });
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [{ ...paper(1), abstract: undefined }, { ...paper(2), abstract: undefined }], read: 2, ended: true });
+ await made.t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: [{ ...paper(1), abstract: undefined }, { ...paper(2), abstract: undefined }], read: 2, ended: true });
expect(await sourceOf()).toMatchObject({ left: 2, bare: 2 });
// A check reads it again, and has met the first paper and one that is new so far: the page still says two were left out, and lists the two it counted.
await made.t.run(async (ctx) => ctx.db.patch("screeningSources", sourceId, { ...readAgain((await ctx.db.get("screeningSources", sourceId))!), state: "reading" }));
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [{ ...paper(1), abstract: undefined }, { ...paper(3), abstract: undefined }], read: 2, ended: false });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: [{ ...paper(1), abstract: undefined }, { ...paper(3), abstract: undefined }], read: 2, ended: false });
expect(await sourceOf()).toMatchObject({ left: 2, bare: 2 });
expect(await listed()).toEqual(["Paper 1", "Paper 2"]);
// The second paper is gone from the source: once the reading is whole, the count and the list are this reading's.
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [], read: 0, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: [], read: 0, ended: true });
expect(await sourceOf()).toMatchObject({ left: 2, bare: 2 });
expect((await sourceOf())!.next).toBeUndefined();
expect(await listed()).toEqual(["Paper 1", "Paper 3"]);
@@ -98,10 +98,10 @@ describe("what a source leaves out", () => {
const { jobId } = await started(made, ["ann"], 0, { sources: [{ set: { kind: "upload", file }, name: "export.csv" }] });
const { checkId, sourceId } = await made.t.run(async (ctx) => ({ checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id }));
const sourceOf = () => made.t.run((ctx) => ctx.db.get("screeningSources", sourceId));
- await made.t.mutation(internal.screening.gathering.begin, { sourceId });
+ await made.t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
// Two records of one export with the same DOI, each under its own key, a third paper, and that third paper's record once more. A file hands each over as the record it is.
const held = [paper(1, { doi: "10.1000/same" }), paper(2, { doi: "10.1000/same" }), paper(3), paper(3)].map((one, at) => ({ ...one, record: String(at + 1) }));
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: held, read: 4, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: held, read: 4, ended: true });
expect(await sourceOf()).toMatchObject({ read: 4, taken: 2, duplicates: 2, left: 0 });
expect(await made.t.run((ctx) => ctx.db.query("screeningLeftOut").collect())).toHaveLength(0);
// Each repeat is named with the paper that stands for it, which this same file brought.
@@ -110,12 +110,12 @@ describe("what a source leaves out", () => {
// Its range is widened by two records, a new paper twice, so it is read again from its start, and a step that was cut short gives its records twice. Until the reading is whole, the count and the list are the first reading's.
await made.t.run(async (ctx) => ctx.db.patch("screeningSources", sourceId, { ...readAgain((await ctx.db.get("screeningSources", sourceId))!), state: "reading" }));
- for (const read of [0, 4]) await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: held, read, ended: false });
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [{ ...paper(4), record: "5" }, { ...paper(4), record: "6" }], read: 2, ended: false });
+ for (const read of [0, 4]) await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: held, read, ended: false });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: [{ ...paper(4), record: "5" }, { ...paper(4), record: "6" }], read: 2, ended: false });
expect(await sourceOf()).toMatchObject({ taken: 3, duplicates: 2 });
expect(await merged()).toEqual([["Paper 2", "Paper 1", sourceId], ["Paper 3", "Paper 3", sourceId]]);
// Whole, it counts each repeat once: the two it met before, and the new one.
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [], read: 0, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: [], read: 0, ended: true });
expect(await sourceOf()).toMatchObject({ read: 6, taken: 3, duplicates: 3, left: 0 });
expect(await merged()).toEqual([["Paper 2", "Paper 1", sourceId], ["Paper 3", "Paper 3", sourceId], ["Paper 4", "Paper 4", sourceId]]);
});
@@ -125,10 +125,10 @@ describe("what a source leaves out", () => {
const { jobId } = await started(made, ["ann"], 0, { sources: [{ set: { kind: "saved" }, name: "Saved papers" }, { set: { kind: "saved" }, name: "Saved again" }] });
const { checkId, sources } = await made.t.run(async (ctx) => ({ checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, sources: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect()).map((one) => one._id) }));
const [first, second] = sources as [Id<"screeningSources">, Id<"screeningSources">];
- for (const sourceId of sources) await made.t.mutation(internal.screening.gathering.begin, { sourceId });
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId: first, papers: [paper(1)], read: 1, ended: true });
+ for (const sourceId of sources) await made.t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId: first, pass: 0, papers: [paper(1)], read: 1, ended: true });
// The second source holds that paper too, and lists it under two of its folders, as a Zotero library does.
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId: second, papers: [paper(1), paper(1), paper(2)], read: 3, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId: second, pass: 0, papers: [paper(1), paper(1), paper(2)], read: 3, ended: true });
expect(await made.t.run((ctx) => ctx.db.get("screeningSources", second))).toMatchObject({ taken: 1, duplicates: 1 });
const merged = (await made.as.ann!.query(api.screening.view.merged, { workspaceId: made.workspaceId, jobId, sourceId: second, paginationOpts: { cursor: null, numItems: 10 } })).page;
expect(merged.map((row) => [row.name, row.paper?.sourceId])).toEqual([["Paper 1", first]]);
@@ -138,10 +138,10 @@ describe("what a source leaves out", () => {
const made = await team(["ann"]);
const { jobId } = await started(made, ["ann"], 0);
const { checkId, sourceId } = await made.t.run(async (ctx) => ({ checkId: (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id, sourceId: (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).first())!._id }));
- await made.t.mutation(internal.screening.gathering.begin, { sourceId });
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [paper(1)], read: 1, ended: true });
+ await made.t.mutation(internal.screening.gathering.begin, { sourceId, pass: 0 });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 0, papers: [paper(1)], read: 1, ended: true });
await made.t.run(async (ctx) => ctx.db.patch("screeningSources", sourceId, { ...readAgain((await ctx.db.get("screeningSources", sourceId))!), state: "reading" }));
- await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers: [{ ...paper(1), abstract: undefined }, { ...paper(2), abstract: undefined }], read: 2, ended: true });
+ await made.t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass: 1, papers: [{ ...paper(1), abstract: undefined }, { ...paper(2), abstract: undefined }], read: 2, ended: true });
expect(await made.t.run((ctx) => ctx.db.get("screeningSources", sourceId))).toMatchObject({ taken: 1, left: 1, bare: 1 });
expect(await made.t.run((ctx) => ctx.db.query("screeningLeftOut").collect())).toMatchObject([{ name: "Paper 2", why: "abstract" }]);
});
diff --git a/convex/screening/files.ts b/convex/screening/files.ts
index 45c732867..054733040 100644
--- a/convex/screening/files.ts
+++ b/convex/screening/files.ts
@@ -29,8 +29,8 @@ const STANDINGS = ["waiting", "known", "file", "broken"] as const satisfies read
const placed = (ctx: Pick, batch: string, at: number) => ctx.db.query("screeningFiles").withIndex("by_batch_and_at", (q) => q.eq("batch", batch).eq("at", at)).unique();
const lastOf = (ctx: Pick, batch: string) => ctx.db.query("screeningFiles").withIndex("by_batch_and_at", (q) => q.eq("batch", batch)).order("desc").first();
-/** A drop is its adder's, in the workspace it was added in: nobody else adds to it or reads it. */
-async function own(ctx: Pick, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, batch: string) {
+/** A drop is its adder's, in the workspace it was added in: nobody else adds to it, reads it, or makes a source of it. */
+export async function own(ctx: Pick, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, batch: string) {
const last = await lastOf(ctx, batch);
if (last && (last.userId !== actor.userId || last.workspaceId !== actor.workspaceId)) throw createError("FORBIDDEN", "These files were added by someone else.");
return last;
@@ -55,6 +55,9 @@ export const add = workspaceMutation({
const starting: Id<"screeningFiles">[] = [];
for (const [i, { file, name, bytes }] of files.entries()) {
if (bytes > MAX_PDF_BYTES) throw createError("VALIDATION_ERROR", `${name} is over ${MAX_PDF_MB} MB.`);
+ // A file is the drop's that uploaded it: one already in someone else's drop is theirs.
+ const held = await ctx.db.query("screeningFiles").withIndex("by_file", (q) => q.eq("file", file)).first();
+ if (held && (held.userId !== actor.userId || held.workspaceId !== actor.workspaceId)) throw createError("FORBIDDEN", "These files were added by someone else.");
const at = from + i;
const fileId = await ctx.db.insert("screeningFiles", { userId: actor.userId, workspaceId: actor.workspaceId, batch, at, file, name: name.slice(0, MAX_FILE_NAME), bytes, state: "waiting" });
// Its lane is free where the file `LANES` places before it has landed already: that landing found no file to start.
diff --git a/convex/screening/gathering.ts b/convex/screening/gathering.ts
index 3c28bf2f2..6f7e8293a 100644
--- a/convex/screening/gathering.ts
+++ b/convex/screening/gathering.ts
@@ -27,14 +27,13 @@ import { countDealt, dealable, dealNew, readingModel, readsOf, reviewersOf, sour
import { progressRow, shelve, withMoved } from "./bookkeeping";
import { checked } from "./living";
import { unglued } from "../../lib/papers/abstract-sections";
-import { planLimit } from "../billing/accounts";
import { papersIn } from "./estimate";
import { pdfBand } from "../../lib/pricing/estimate";
import { readersFor } from "../../lib/screening/rules";
import { handedPapers, handedStart, withAbstracts, type LeftOut } from "./held";
import { searchTextOf } from "./mutations";
import { doiKeyOf, nextPlace, QUIET_MS, titleKeyOf } from "./checks";
-import { startWaitingVotes } from "./slots";
+import { papersLimit, startWaitingVotes } from "./slots";
import { leftOutWhyValidator, MAX_SOURCE_ROWS, SCREENING_TEXT, screeningPaperInputValidator, sourceSetValidator } from "./validators";
type SourceSet = Infer;
@@ -56,12 +55,12 @@ const FAILURE_SHOWN = 600;
const FILL_TRIES = 5;
-type Reading = { gone?: true; places: number; sourceId: Id<"screeningSources">; part: number; set: SourceSet; first: number; last?: number; read: number; resume?: string; snapshot?: SearchSnapshot; state: "waiting" | "reading"; total?: number; userId: Id<"users">; workspaceId: Id<"workspaces"> };
+type Reading = { gone?: true; full?: true; pass: number; places: number; sourceId: Id<"screeningSources">; part: number; set: SourceSet; first: number; last?: number; read: number; resume?: string; snapshot?: SearchSnapshot; state: "waiting" | "reading"; total?: number; userId: Id<"users">; workspaceId: Id<"workspaces"> };
/** The next of a check's sources that still has papers to read, with where its reading stands. Null once every source is read, or the check has ended. */
export const next = internalQuery({
args: { checkId: v.id("screeningChecks") },
- returns: v.union(v.null(), v.object({ places: v.number(), sourceId: v.id("screeningSources"), part: v.number(), set: sourceSetValidator, first: v.number(), last: v.optional(v.number()), read: v.number(), resume: v.optional(v.string()), snapshot: v.optional(searchSnapshotValidator), state: v.union(v.literal("waiting"), v.literal("reading")), total: v.optional(v.number()), userId: v.id("users"), workspaceId: v.id("workspaces"), gone: v.optional(v.literal(true)) })),
+ returns: v.union(v.null(), v.object({ places: v.number(), sourceId: v.id("screeningSources"), part: v.number(), set: sourceSetValidator, first: v.number(), last: v.optional(v.number()), read: v.number(), resume: v.optional(v.string()), snapshot: v.optional(searchSnapshotValidator), state: v.union(v.literal("waiting"), v.literal("reading")), total: v.optional(v.number()), userId: v.id("users"), workspaceId: v.id("workspaces"), gone: v.optional(v.literal(true)), full: v.optional(v.literal(true)), pass: v.number() })),
handler: async (ctx, { checkId }): Promise => {
const check = await ctx.db.get("screeningChecks", checkId);
const job = check?.state === "running" ? await ctx.db.get("screeningJobs", check.jobId) : null;
@@ -77,7 +76,9 @@ export const next = internalQuery({
// The places a paper is given as it arrives: its people, as many as the rule asks for, and every model that reads.
const reviewers = await reviewersOf(ctx, job._id);
const places = readersFor(job.rule?.each ?? "all", reviewers.filter(dealable).length) + reviewers.filter(readingModel).length;
- return { ...(gone ? { gone: true as const } : {}), places, sourceId: source._id, part, set: source.set, first: source.first ?? 1, ...(source.last === undefined ? {} : { last: source.last }), read: source.read, ...(source.resume ? { resume: source.resume } : {}), ...(source.snapshot ? { snapshot: source.snapshot } : {}), state: source.state as "waiting" | "reading", ...(source.total === undefined ? {} : { total: source.total }), userId: source.addedBy, workspaceId: source.workspaceId ?? job.workspaceId };
+ // A screening that holds as many papers as its plan takes asks no source for more: the source stops at once, and says why.
+ const full = job.totalPapers - ((await progressRow(ctx, job._id))?.withdrawn ?? 0) >= (await papersLimit(ctx, job.workspaceId));
+ return { ...(gone ? { gone: true as const } : {}), ...(full ? { full: true as const } : {}), pass: source.pass ?? 0, places, sourceId: source._id, part, set: source.set, first: source.first ?? 1, ...(source.last === undefined ? {} : { last: source.last }), read: source.read, ...(source.resume ? { resume: source.resume } : {}), ...(source.snapshot ? { snapshot: source.snapshot } : {}), state: source.state as "waiting" | "reading", ...(source.total === undefined ? {} : { total: source.total }), userId: source.addedBy, workspaceId: source.workspaceId ?? job.workspaceId };
},
});
@@ -90,20 +91,22 @@ export const heldTotal = internalQuery({
/** A source's reading begins: what it holds, and for a search the search as it was then, which every step reads. */
export const begin = internalMutation({
- args: { sourceId: v.id("screeningSources"), total: v.optional(v.number()), snapshot: v.optional(searchSnapshotValidator), resume: v.optional(v.string()) },
+ args: { sourceId: v.id("screeningSources"), pass: v.number(), total: v.optional(v.number()), snapshot: v.optional(searchSnapshotValidator), resume: v.optional(v.string()) },
returns: v.null(),
- handler: async (ctx, { sourceId, total, snapshot, resume }) => {
+ handler: async (ctx, { sourceId, pass, total, snapshot, resume }) => {
const source = await ctx.db.get("screeningSources", sourceId);
- if (source?.state === "waiting") await ctx.db.patch("screeningSources", sourceId, { state: "reading", ...(total === undefined ? {} : { total }), ...(snapshot ? { snapshot } : {}), ...(resume ? { resume } : {}) });
+ if (source?.state === "waiting" && (source.pass ?? 0) === pass) await ctx.db.patch("screeningSources", sourceId, { state: "reading", ...(total === undefined ? {} : { total }), ...(snapshot ? { snapshot } : {}), ...(resume ? { resume } : {}) });
return null;
},
});
/** A source that couldn't be read is left as failed, with why in words for the person where it is something they can act on, and the check goes on to the next. The check counts it as one of its own it couldn't read. */
export const fail = internalMutation({
- args: { checkId: v.id("screeningChecks"), sourceId: v.id("screeningSources"), reason: v.optional(v.string()) },
+ args: { checkId: v.id("screeningChecks"), sourceId: v.id("screeningSources"), pass: v.number(), reason: v.optional(v.string()) },
returns: v.null(),
- handler: async (ctx, { checkId, sourceId, reason }) => {
+ handler: async (ctx, { checkId, sourceId, pass, reason }) => {
+ // A reading of the source from before it was changed fails nothing: the source is being read again.
+ if (((await ctx.db.get("screeningSources", sourceId))?.pass ?? 0) !== pass) return null;
await ctx.db.patch("screeningSources", sourceId, { state: "failed", failure: reason?.slice(0, FAILURE_SHOWN) });
const check = await ctx.db.get("screeningChecks", checkId);
if (check && !check.unread?.includes(sourceId)) await ctx.db.patch("screeningChecks", checkId, { unread: [...(check.unread ?? []), sourceId].slice(-MAX_SOURCE_ROWS) });
@@ -127,6 +130,11 @@ export const gather = internalAction({
if (Date.now() - started > READ_ACTION_MS) return void (await ctx.scheduler.runAfter(0, internal.screening.gathering.gather, { checkId }));
try {
if (source.gone) throw createError("FORBIDDEN", "Whoever added this source is no longer in the workspace it is in. Add it again from this workspace.");
+ if (source.full) {
+ await ctx.runMutation(internal.screening.gathering.begin, { sourceId: source.sourceId, pass: source.pass });
+ await ctx.runMutation(internal.screening.gathering.fill, { checkId, sourceId: source.sourceId, pass: source.pass, papers: [], read: 0, ended: false, full: true });
+ continue;
+ }
// Its next PDFs are still being read for the first time: the check comes back for them, and is not taken for one gone quiet.
if ((await step(ctx, checkId, source)) === "wait") {
await ctx.runMutation(internal.screening.gathering.beat, { checkId });
@@ -134,7 +142,7 @@ export const gather = internalAction({
}
} catch (error) {
console.error(`[screening] Source ${source.sourceId} couldn't be read`, error);
- await ctx.runMutation(internal.screening.gathering.fail, { checkId, sourceId: source.sourceId, ...(readConvexErrorData(error)?.message ? { reason: readConvexErrorData(error)!.message } : {}) });
+ await ctx.runMutation(internal.screening.gathering.fail, { checkId, sourceId: source.sourceId, pass: source.pass, ...(readConvexErrorData(error)?.message ? { reason: readConvexErrorData(error)!.message } : {}) });
}
}
},
@@ -165,7 +173,7 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
for (let at = 0; at === 0 || at < ready.length; at += each) {
const last = at + each >= ready.length;
const goesOn = last ? resume : source.resume;
- const args = { checkId, sourceId, papers: ready.slice(at, at + each), read: last ? read : 0, ended: ended && last, ...(goesOn ? { resume: goesOn } : {}), ...(at === 0 && leftOut?.length ? { leftOut } : {}) };
+ const args = { checkId, sourceId, pass: source.pass, papers: ready.slice(at, at + each), read: last ? read : 0, ended: ended && last, ...(goesOn ? { resume: goesOn } : {}), ...(at === 0 && leftOut?.length ? { leftOut } : {}) };
// A fill writes the reviewers' counts that voting and settling write too: one that loses to them every time Convex tries it is tried again here, with the papers it already has.
for (let tries = 1; ; tries++) {
try { await ctx.runMutation(internal.screening.gathering.fill, args); break; }
@@ -176,17 +184,17 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
const held = set.kind === "upload" || set.kind === "dois" || set.kind === "pdf" ? { ...source, set } : null;
if (source.state === "waiting") {
// A file, a pasted list or PDFs: what it holds is counted from the file itself.
- if (held) return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, ...(await handedStart(ctx, held)) }));
+ if (held) return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, pass: source.pass, ...(await handedStart(ctx, held)) }));
// What it holds is counted once, before its first paper: a search as it is now, a community's source as the person may read it.
if (set.kind === "search") {
const found: SavedSearchRequest = await ctx.runQuery(internal.paperSets.search.readSearch, { ...reader, searchId: set.searchId });
const snapshot = snapshotOf(found);
- return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, snapshot, total: await countSearch(snapshot.request, spender(ctx, found.clerkId)) }));
+ return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, pass: source.pass, snapshot, total: await countSearch(snapshot.request, spender(ctx, found.clerkId)) }));
}
if (set.kind === "evidenceLibrary") {
const keys = await resolveLibraryKeys(ctx, { libraryId: set.libraryId, userId: source.userId, source: set.source, first: source.first, last: source.last ?? Number.MAX_SAFE_INTEGER });
await keepLibraryKeys(ctx, (await ctx.runQuery(internal.screening.gathering.jobOf, { checkId }))!, keys, { part: source.part });
- return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, total: source.first - 1 + keys.length }));
+ return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, pass: source.pass, total: source.first - 1 + keys.length }));
}
// With the collections under it: the library's collections are kept as rows (../zotero/tree.ts), and the check comes back while they are still being read. `resume` keeps the collections still to read, this one first, and how far into the first the reading is. What it holds with everything under it is what Zotero counts in each, so a paper filed in two of them is counted twice until it is read.
if (set.kind === "zotero" && set.deep && set.collectionKey) {
@@ -195,10 +203,10 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
if (tree === "failed") throw createError("EXTERNAL_SERVICE_ERROR", "Zotero didn't give this library's collections. Check that Zotero is still connected.");
if (tree === "wait") return "wait";
const root: { under: number } | null = await ctx.runQuery(internal.zotero.tree.one, { ...library, key: set.collectionKey });
- return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, ...(root ? { total: root.under } : {}), resume: JSON.stringify({ keys: [set.collectionKey], at: 0 }) }));
+ return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, pass: source.pass, ...(root ? { total: root.under } : {}), resume: JSON.stringify({ keys: [set.collectionKey], at: 0, skip: source.first - 1 }) }));
}
const total: number | null = await ctx.runQuery(internal.screening.gathering.heldTotal, { ...reader, set });
- return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, ...(total === null ? {} : { total }) }));
+ return void (await ctx.runMutation(internal.screening.gathering.begin, { sourceId, pass: source.pass, ...(total === null ? {} : { total }) }));
}
const last = Math.min(source.last ?? Number.MAX_SAFE_INTEGER, source.total ?? Number.MAX_SAFE_INTEGER);
const from = source.first + source.read;
@@ -251,8 +259,9 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
return Math.min(room, cut === -1 ? papers.length : cut);
};
// The collections still to read, in a line. One is a collection's key, or a key with where the list of the collections inside it goes on, for one that has more of them than a page.
+ // `skip`: the papers before the range's first, across the whole tree in the order it is read, still to pass over.
type Waiting = string | [key: string, inside: string];
- const deep: { keys: Waiting[]; at: number } | null = set.deep && source.resume ? JSON.parse(source.resume) : null;
+ const deep: { keys: Waiting[]; at: number; skip?: number } | null = set.deep && source.resume ? JSON.parse(source.resume) : null;
if (deep) {
if (!deep.keys.length) return void (await give([], 0, true));
const library = { userId: source.userId, ...(set.groupId ? { groupId: set.groupId } : {}) };
@@ -263,7 +272,8 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
const open = reads.findIndex((read) => !read.ended);
const pages = (open === -1 ? reads : reads.slice(0, open + 1)).map(asPapers);
const all = pages.flat();
- const taking = within(all);
+ const skip = Math.min(deep.skip ?? 0, all.length);
+ const taking = skip + within(all.slice(skip));
// Where this step stops short of a collection's end: at the end of a page of one that has more, or part way into a page, where the step holds all the papers with no abstract it takes.
let stop = open === -1 ? null : { at: open, read: ZOTERO_LIST_PAGE };
if (taking < all.length) {
@@ -271,12 +281,12 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read
while (read >= pages[at]!.length) read -= pages[at++]!.length;
stop = { at, read };
}
- const papers = await withFiles(all.slice(0, taking));
+ const papers = await withFiles(all.slice(skip, taking));
// A collection read to its end hands on to the ones inside it, which join the end of the line.
const ended = stop ? front.slice(0, stop.at) : front;
const under: Array<{ page: Array<{ key: string }>; isDone: boolean; continueCursor: string }> = await Promise.all(ended.map((one) => ctx.runQuery(internal.zotero.tree.inside, { ...library, parent: one.key, paginationOpts: { cursor: one.inside, numItems: ZOTERO_LIST_PAGE } })));
const joining = under.flatMap((found, at): Waiting[] => [...found.page.map((one) => one.key), ...(found.isDone ? [] : [[ended[at]!.key, found.continueCursor] as [string, string]])]);
- const next = { keys: [...deep.keys.slice(ended.length), ...joining], at: stop ? (stop.at === 0 ? deep.at : 0) + stop.read : 0 };
+ const next = { keys: [...deep.keys.slice(ended.length), ...joining], at: stop ? (stop.at === 0 ? deep.at : 0) + stop.read : 0, ...(deep.skip && deep.skip > skip ? { skip: deep.skip - skip } : {}) };
return void (await hand(papers, !next.keys.length || papers.length >= room, JSON.stringify(next)));
}
// A library or one collection is read by its papers' places in it, several pages at once: each is asked for by where it starts, so they come back in order.
@@ -338,12 +348,12 @@ async function twinOf(ctx: Pick, jobId: Id<"screeningJobs">,
* reviewers.
*/
export const fill = internalMutation({
- args: { checkId: v.id("screeningChecks"), sourceId: v.id("screeningSources"), papers: v.array(screeningPaperInputValidator), read: v.number(), resume: v.optional(v.string()), ended: v.boolean(), /** What the source's own reading left out before any paper was made of it: a DOI nothing is known of, a file that doesn't open. */ leftOut: v.optional(v.array(v.object({ name: v.string(), why: leftOutWhyValidator, key: v.optional(v.string()) }))) },
+ args: { checkId: v.id("screeningChecks"), sourceId: v.id("screeningSources"), /** The reading of the source this step belongs to: one from before the source was changed takes nothing in. */ pass: v.number(), papers: v.array(screeningPaperInputValidator), read: v.number(), resume: v.optional(v.string()), ended: v.boolean(), /** The screening is full before this source gave anything: it stops as one that met the cap. */ full: v.optional(v.boolean()), /** What the source's own reading left out before any paper was made of it: a DOI nothing is known of, a file that doesn't open. */ leftOut: v.optional(v.array(v.object({ name: v.string(), why: leftOutWhyValidator, key: v.optional(v.string()) }))) },
returns: v.null(),
- handler: async (ctx, { checkId, sourceId, papers, read, resume, ended, leftOut }) => {
+ handler: async (ctx, { checkId, sourceId, pass: reading, papers, read, resume, ended, full, leftOut }) => {
const [check, source] = await Promise.all([ctx.db.get("screeningChecks", checkId), ctx.db.get("screeningSources", sourceId)]);
- // A source taken out while its reading was out takes nothing in: its papers would arrive after it left.
- const job = check?.state === "running" && source?.state === "reading" && source.removedAt === undefined ? await ctx.db.get("screeningJobs", check.jobId) : null;
+ // A source taken out while its reading was out takes nothing in: its papers would arrive after it left. Nor does an earlier reading of one changed since.
+ const job = check?.state === "running" && source?.state === "reading" && source.removedAt === undefined && (source.pass ?? 0) === reading ? await ctx.db.get("screeningJobs", check.jobId) : null;
if (!check || !source || !job) return null;
const reviewers = await reviewersOf(ctx, job._id);
const reads = await readsOf(ctx, reviewers);
@@ -352,10 +362,10 @@ export const fill = internalMutation({
let [taken, duplicates, left, bare, back, filed, filePages] = [0, 0, 0, 0, 0, 0, 0];
const fileSpread = { ...source.fileSpread };
// The most papers the workspace's plan gives one screening: past it, a source's reading stops, and says so.
- const most = await planLimit(ctx, job.workspaceId, "request_papers");
+ const most = await papersLimit(ctx, job.workspaceId);
// The papers of sources taken out leave room for others: the limit counts the papers the screening has now (`present`).
const gone = (await progressRow(ctx, job._id))?.withdrawn ?? 0;
- let capped = false;
+ let capped = full === true;
// This reading of the source: each time it is read from its start is a pass of its own (./dealing.ts `readAgain`).
const pass = source.pass ?? 0;
// A record a reading still going meets again keeps the last whole reading that met it: the source's lists show that one until this one is whole (./view.ts `leftOut`, `merged`).
@@ -399,7 +409,7 @@ export const fill = internalMutation({
// The papers the screening has now: every one it took, less those taken out, with any brought back in this step. Bringing one back takes room as a new one does.
const present = start + taken - gone + back;
if (twin?.withdrawn) {
- if (typeof most === "number" && present >= most) { capped = true; break; }
+ if (present >= most) { capped = true; break; }
// Its source was taken out, and this one holds it too: it comes back as this source's paper, in the place it had, with the votes cast on it. The worker gives its open places out again.
await ctx.db.patch("screeningResults", twin._id, { withdrawn: undefined, sourceId, record: paper.record, doneAt: ctx.db.vars.commitTs });
back++;
@@ -426,7 +436,7 @@ export const fill = internalMutation({
// A paper the screening already holds is passed over above, whatever it now lacks: an abstract that a lookup failed to bring this time leaves out only a paper that is new.
if (!abstract && !paper.file) { await leave(title, "abstract", named); continue; }
const place = start + taken;
- if (typeof most === "number" && present >= most) { capped = true; break; }
+ if (present >= most) { capped = true; break; }
const resultId = await ctx.db.insert("screeningResults", {
...sourceMetadata(paper),
jobId: job._id,
diff --git a/convex/screening/held.ts b/convex/screening/held.ts
index 7176042d1..0b21f6ebc 100644
--- a/convex/screening/held.ts
+++ b/convex/screening/held.ts
@@ -125,8 +125,8 @@ export async function withAbstracts(papers: SearchPaper[], spend: Spend | null):
const sameWork = (one: string, other: string) => sameTitle(one, other) || (plainTitle(one) !== "" && plainTitle(one) === plainTitle(other));
for (let at = 0; at < bare.length; at += DOIS_A_REQUEST) {
const ids = bare.slice(at, at + DOIS_A_REQUEST).map((paper) => paper.paper.slice("openalex:".length));
- // A paper OpenAlex can't be asked about now is screened, or left out, as it came.
- const { works } = await readSearchPage({ filter: `openalex:${ids.join("|")}`, sort: BY_DOI_SORT, source: "openalex" }, { page: 1, size: DOIS_A_REQUEST, select: "id,title,abstract_inverted_index" }, spend!).catch((error) => { console.error("[screening] OpenAlex couldn't be asked for abstracts", error); return { works: [] as Work[] }; });
+ // OpenAlex not answering is no reason to leave a paper out for having no abstract: the reading stops with why, and the source is read again once it answers.
+ const { works } = await readSearchPage({ filter: `openalex:${ids.join("|")}`, sort: BY_DOI_SORT, source: "openalex" }, { page: 1, size: DOIS_A_REQUEST, select: "id,title,abstract_inverted_index" }, spend!).catch((error) => { console.error("[screening] OpenAlex couldn't be asked for abstracts", error); throw createError("EXTERNAL_SERVICE_ERROR", "OpenAlex didn't answer while abstracts were looked up. Read this source again in a few minutes."); });
for (const work of works) {
const paper = work.id ? toPaper(work) : null;
if (!paper?.abstract) continue;
diff --git a/convex/screening/living.ts b/convex/screening/living.ts
index c6bc1eb62..1f1498dff 100644
--- a/convex/screening/living.ts
+++ b/convex/screening/living.ts
@@ -149,7 +149,8 @@ export async function checked(ctx: MutationCtx, job: Doc<"screeningJobs">, check
}
await logChange(ctx, { userId: check.by ?? job.createdBy }, job, !check.by ? "scheduledCheck" : check.search ? "checked" : "sourcesRead", { count: check.found, more: [...(check.found - check.added - (check.left ?? 0) > 0 ? [{ code: "known", count: check.found - check.added - (check.left ?? 0) }] : []), ...(check.left ? [{ code: "leftOut", count: check.left }] : []), ...(check.unread?.length ? [{ code: "unread", count: check.unread.length }] : []), ...(check.added ? [{ code: "joined", count: check.added }] : []), ...(reopens ? [{ code: "reopened" }] : [])] });
if (!check.added) return;
+ // Whoever asked for the check, or added the source it read, sees the papers arrive: the email is for the others.
for (const reviewer of await reviewersOf(ctx, job._id)) {
- if (reviewer.kind === "person" && reviewer.userId && reviewer.left === undefined) await ctx.scheduler.runAfter(0, internal.screening.noticeMail.send, { jobId: job._id, userId: reviewer.userId, about: "papers" });
+ if (reviewer.kind === "person" && reviewer.userId && reviewer.left === undefined && reviewer.userId !== check.by) await ctx.scheduler.runAfter(0, internal.screening.noticeMail.send, { jobId: job._id, userId: reviewer.userId, about: "papers" });
}
}
diff --git a/convex/screening/mutations.ts b/convex/screening/mutations.ts
index 56c0f5351..2e456213c 100644
--- a/convex/screening/mutations.ts
+++ b/convex/screening/mutations.ts
@@ -368,6 +368,8 @@ export const cancelScreeningJobAction = defineUserMutation({
run: async (ctx, actor, args) => {
const job = await ctx.db.get("screeningJobs", args.jobId);
if (!job || job.workspaceId !== actor.workspaceId) throw createError("SCREENING_JOB_NOT_FOUND", "Screening job not found");
+ // A screening with reviewers is paused or finished on its own page: this stop would leave its models reading.
+ if (job.shape === 2) throw createError("VALIDATION_ERROR", "This screening has reviewers. Pause its models or mark it finished on its page.");
requireMakerOrAdmin(actor, job.createdBy);
// Terminal states are idempotent no-ops for the page; a chat is told, so it doesn't say it stopped it.
diff --git a/convex/screening/notices.ts b/convex/screening/notices.ts
index 9bd92c373..54f0d1d11 100644
--- a/convex/screening/notices.ts
+++ b/convex/screening/notices.ts
@@ -13,7 +13,7 @@ import { internalMutation, internalQuery } from "../lib/functions";
import { workspaceMutation } from "../lib/userActions";
import { standingOn } from "./access";
import { progressRow } from "./bookkeeping";
-import { laterChecks, nameOf, newFor, waitsOn } from "./dealing";
+import { laterChecks, nameOf, NEW_COUNTED, newFor, waitsOn } from "./dealing";
import { screeningPath } from "../../lib/screening/links";
export const aboutValidator = v.union(v.literal("papers"), v.literal("conflicts"), v.literal("reminder"), v.literal("joined"));
@@ -22,7 +22,6 @@ export const aboutValidator = v.union(v.literal("papers"), v.literal("conflicts"
export const noticeOf = (ctx: Pick, jobId: Id<"screeningJobs">, userId: Id<"users">) => ctx.db.query("screeningNotices").withIndex("by_job_and_user", (q) => q.eq("jobId", jobId).eq("userId", userId)).unique();
/** New papers counted for one person's email: past it the email says so many. */
-const NEW_COUNTED = 500;
/** How long after a conflict arises its email goes, so a burst of them is one email, and how long before the next. */
const CONFLICTS_AFTER_MS = 10 * 60_000;
@@ -65,14 +64,13 @@ export const context = internalQuery({
const organization = workspace?.kind === "organization" ? await ctx.db.get("organizations", workspace.organizationId) : null;
// A member opens it in its workspace, and a guest in their own: membership was read just above.
const member = Boolean(organization) && inside;
- const progress = await progressRow(ctx, jobId);
const reviewer = await ctx.db.query("screeningReviewers").withIndex("by_job_and_user", (q) => q.eq("jobId", jobId).eq("userId", userId)).first();
const on = reviewer && reviewer.left === undefined ? reviewer : null;
// New papers: the ones its last check gave this person, which still wait for their vote. A reminder: everything that waits for them.
const brought = about === "papers" ? (await laterChecks(ctx, jobId)).find((check) => check.added > 0) : undefined;
// What waits for them is counted as every page counts it (./dealing.ts `waitsOn`).
- const waits = await waitsOn(ctx, job, userId, on, progress);
- const count = about === "conflicts" ? waits.conflicts : about === "papers" ? (on && brought ? await newFor(ctx, on._id, brought, NEW_COUNTED) : 0) : waits.forYou;
+ const waits = await waitsOn(ctx, job, userId, on);
+ const count = about === "conflicts" ? waits.conflicts : about === "papers" ? (on && brought ? await newFor(ctx, on._id, brought) : 0) : waits.forYou;
// Someone put on a screening is told so whether or not a paper waits for them yet.
// On a finished one, only someone who votes once it is reopened: a guest given it to vote on, never one made a viewer since.
if (!count && !(about === "joined" && (on || (finished && grant?.role === "editor")))) return null;
diff --git a/convex/screening/paperViews.ts b/convex/screening/paperViews.ts
index bd29d6578..0b1046cad 100644
--- a/convex/screening/paperViews.ts
+++ b/convex/screening/paperViews.ts
@@ -14,11 +14,10 @@ import type { InWorkspace } from "../workspaces/actor";
import { ballotOf } from "../../lib/screening/project";
import { isFinal, leansOpen, nameHas, NO_REASON, showsEarly, type Answer } from "../../lib/screening/rules";
import { standingOn, type Standing } from "./access";
-import { askedOf, invitationsTo, reviewersOf, seesPaper, viewId, votesOf } from "./dealing";
+import { askedOf, reviewersOf, seesPaper, viewId, votesOf } from "./dealing";
import { placeOf } from "./settling";
import { decisionValidator, paperResultValidator, paperViewValidator, voteViewValidator } from "./validators";
-import { progressRow } from "./bookkeeping";
-import { keepsVotes } from "./view";
+import { keepsVotesNow } from "./view";
import { tallyForReason, tallyOfReviewer, tallyUnder } from "./facets";
type Paper = Doc<"screeningResults">;
@@ -33,18 +32,22 @@ export type PaperView = Infer;
/** A screening as the paper reads need it: who is on it, and what the person looking is to it. */
type Looking = Standing & { reviewers: Map, Reviewer>; first: Id<"screeningChecks"> | undefined; asked: Set> };
-async function lookingAt(ctx: Pick, actor: InWorkspace, jobId: Id<"screeningJobs">): Promise {
+/** `rows`: the read lists papers, so it needs the ones the person has been asked about; a count or a file doesn't. */
+async function lookingAt(ctx: Pick, actor: InWorkspace, jobId: Id<"screeningJobs">, { rows = true } = {}): Promise {
const standing = await standingOn(ctx, actor, jobId);
if (!standing || standing.job.shape !== 2 || !standing.job.rule) return null;
- const [first, reviewers, asked] = await Promise.all([ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first(), reviewersOf(ctx, jobId), askedOf(ctx, jobId, actor.userId)]);
+ const [first, reviewers, asked] = await Promise.all([ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).first(), reviewersOf(ctx, jobId), rows ? askedOf(ctx, jobId, actor.userId) : []]);
return { ...standing, reviewers: new Map(reviewers.map((one) => [one._id, one])), first: first?._id, asked: new Set(asked) };
}
-/** A vote as a page shows it. A model's decision follows its answers under the criteria as they are now, as the rule reads it. */
+/**
+ * A vote as a page shows it: as it was counted (../screening/settling.ts), which every count, filter and file reads.
+ * A model's vote not yet counted is worked out from its answers under the criteria as they are now, as the rule reads it.
+ */
function voteOf(job: Doc<"screeningJobs">, vote: Vote, reviewer: Reviewer | undefined): VoteView | undefined {
if (vote.status !== "cast") return undefined;
const answers = (vote.answers ?? {}) as Record;
- const read = ballotOf(placeOf(vote, reviewer), job.criteria ?? []);
+ const read = vote.decision ? { decision: vote.decision, reason: vote.reason } : ballotOf(placeOf(vote, reviewer), job.criteria ?? []);
if (!read.decision) return undefined;
return { decision: read.decision, answers, ...(read.reason ? { reason: read.reason } : {}), ...(vote.note ? { note: vote.note } : {}), at: vote.at ?? vote._creationTime, ...(vote.flagged ? { flagged: true } : {}), ...(vote.confidences ? { confidences: vote.confidences } : {}), ...(vote.passages ? { passages: vote.passages } : {}) };
}
@@ -105,6 +108,20 @@ export function shown({ job, reviewer, reviewers, first, asked }: Looking, paper
const holdsAll = (paper: Paper, needle: string) => nameHas(paper.searchText ?? "", needle);
const views = (ctx: Pick, looking: Looking, papers: Paper[]) => Promise.all(papers.map(async (paper) => shown(looking, paper, await votesOf(ctx, paper._id))));
const NONE = { page: [], isDone: true, continueCursor: "" };
+const cardOf = (ctx: Pick, resultId: Id<"screeningResults">) => ctx.db.query("screeningCards").withIndex("by_result", (q) => q.eq("resultId", resultId)).unique();
+/** A screening's cards narrowed the most telling way asked for, in the order their papers were added: the rest is asked of each card. */
+const cardsOf = (ctx: Pick, jobId: Id<"screeningJobs">, { result, reason, check, source }: { result?: Doc<"screeningCards">["result"]; reason?: string; check?: Id<"screeningChecks">; source?: Id<"screeningSources"> }) => {
+ const cards = stream(ctx.db, schema).query("screeningCards");
+ return reason
+ ? cards.withIndex("by_job_and_reason", (q) => q.eq("jobId", jobId).eq("reason", reason))
+ : check
+ ? cards.withIndex("by_job_and_check", (q) => q.eq("jobId", jobId).eq("checkId", check))
+ : source
+ ? cards.withIndex("by_job_and_source", (q) => q.eq("jobId", jobId).eq("sourceId", source))
+ : result
+ ? cards.withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result))
+ : cards.withIndex("by_job", (q) => q.eq("jobId", jobId));
+};
const byJob = { jobId: v.id("screeningJobs") };
/** Papers one page holds at most, and rows a page looks through for the ones its filters keep. */
const PAGE_MAX = 100;
@@ -157,7 +174,7 @@ export const pdf = workspaceQuery({
args: { ...byJob, paperId: v.id("screeningResults") },
returns: v.union(v.string(), v.null()),
handler: async (ctx, actor, { jobId, paperId }) => {
- const looking = await lookingAt(ctx, actor, jobId);
+ const looking = await lookingAt(ctx, actor, jobId, { rows: false });
const paper = looking ? await ctx.db.get("screeningResults", paperId) : null;
return paper?.jobId === jobId && paper.file ? await ctx.storage.getUrl(paper.file) : null;
},
@@ -183,7 +200,7 @@ export const counts = workspaceQuery({
},
returns: v.union(v.null(), v.object({ include: v.number(), maybe: v.number(), exclude: v.number(), conflict: v.number(), waiting: v.number() })),
handler: async (ctx, actor, { jobId, source, check: asked, reason, reviewer, voted }) => {
- const looking = await lookingAt(ctx, actor, jobId);
+ const looking = await lookingAt(ctx, actor, jobId, { rows: false });
if (!looking) return null;
const check = asked === "start" ? looking.first : asked;
if (asked === "start" && !check) return null;
@@ -191,7 +208,7 @@ export const counts = workspaceQuery({
if (reviewer && !row) return null;
// Which way someone else voted is kept from a reviewer who still has papers to vote on (./view.ts `keepsVotes`): so is how many they voted each way.
const others = row && voted && voted !== "none" && voted !== "failed" && row._id !== looking.reviewer?._id;
- if (others && !showsEarly(looking.job.rule!, row.kind) && keepsVotes(looking.job, looking.reviewer, (await progressRow(ctx as QueryCtx, jobId))?.reviewers, looking.reviewers.values(), (await invitationsTo(ctx, jobId)).length)) return null;
+ if (others && !showsEarly(looking.job.rule!, row.kind) && (await keepsVotesNow(ctx, looking.job, looking.reviewer, looking.reviewers.values()))) return null;
// Narrowed one way, the counts are kept already (./facets.ts): a few counted reads, whatever the screening's size.
const narrowed = [source, check, reason, row].filter(Boolean).length;
if (narrowed === 1) {
@@ -200,12 +217,13 @@ export const counts = workspaceQuery({
if (check) return await tallyUnder(ctx, jobId, { check });
return await tallyForReason(ctx, jobId, reason!);
}
- // Narrowed two ways at once, the papers' cards are counted one by one. ponytail: a namespace per pair of narrowings would count those too, if they come to be used on large screenings.
+ // Narrowed two ways at once, the cards of the narrower way are counted one by one: a reviewer's votes, or the papers of one reason, check or source.
+ // ponytail: a namespace per pair of narrowings would count those too, if they come to be used on screenings past a few thousand papers.
const keeps = (card: Doc<"screeningCards">) => !card.withdrawn && (!source || card.sourceId === source) && (!check || card.checkId === check) && (!reason || (card.result === "exclude" && (card.reason ?? NO_REASON) === reason));
const tally = { include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0 };
- const cards = await ctx.db.query("screeningCards").withIndex("by_job", (q) => q.eq("jobId", jobId)).take(COUNTED + 1);
- if (cards.length > COUNTED) return null;
if (!row) {
+ const cards = await cardsOf(ctx, jobId, { reason, check, source }).take(COUNTED + 1);
+ if (cards.length > COUNTED) return null;
for (const card of cards) if (keeps(card)) tally[card.result]++;
return tally;
}
@@ -217,9 +235,8 @@ export const counts = workspaceQuery({
: votes.withIndex("by_reviewer_and_status_and_at", (q) => q.eq("reviewerId", row._id).eq("status", "cast"))
).take(COUNTED + 1);
if (theirs.length > COUNTED) return null;
- // Their votes are matched to the screening's cards here: two reads, however many papers they voted on.
- const cardOf = new Map(cards.map((card) => [card.resultId, card]));
- for (const vote of theirs) { const card = cardOf.get(vote.resultId); if (card && keeps(card)) tally[card.result]++; }
+ // Each of their votes is matched to its paper's card.
+ for (const card of await Promise.all(theirs.map((vote) => cardOf(ctx, vote.resultId)))) if (card && keeps(card)) tally[card.result]++;
return tally;
},
});
@@ -307,7 +324,7 @@ export const listAction = defineUserQuery({
if (asked === "start" && !check) return NONE;
const options = { ...paginationOpts, numItems: Math.min(paginationOpts.numItems, PAGE_MAX) };
// While the others' votes are kept from the person (./view.ts `keepsVotes`), nothing worked out from those votes orders or narrows what they are given.
- const kept = keepsVotes(looking.job, looking.reviewer, (await progressRow(ctx as QueryCtx, jobId))?.reviewers, looking.reviewers.values(), (await invitationsTo(ctx, jobId)).length);
+ const kept = (await keepsVotesNow(ctx, looking.job, looking.reviewer, looking.reviewers.values()));
// How divided a paper's votes are, and the points their answers give it, put the papers in an order that says how the others voted: asked for then, the papers come as they were added.
const sort = kept && (asked_sort === "split" || asked_sort === "points") ? "added" : asked_sort;
const rowOf = (id: string) => [...looking.reviewers.values()].find((one) => viewId(one) === id || one._id === id);
@@ -381,6 +398,12 @@ export const listAction = defineUserQuery({
const theirs = (await Promise.all(read.page.map((vote) => ctx.db.get("screeningResults", vote.resultId)))).filter((one): one is Paper => one !== null && keeps(one));
return { ...read, page: (await withVotes(theirs)).filter((paper) => !told || paper.sees) };
}
+ if (sort === "added") {
+ // In the order they were added, narrowed on the papers' cards, their few facts: only the page's papers are read whole.
+ const read = await cardsOf(ctx, jobId, { result, reason, check, source }).filterWith(async (card) => keeps(card)).paginate({ ...options, maximumRowsRead: FILTER_ROWS });
+ const theirs = (await Promise.all(read.page.map((card) => ctx.db.get("screeningResults", card.resultId)))).filter((one): one is Paper => one !== null && keeps(one));
+ return { ...read, page: await withVotes(theirs) };
+ }
const field = { title: "title", "title-desc": "title", newest: "publicationYear", split: "split", points: "score" } as const;
const down = sort === "title-desc" || sort === "newest" || sort === "split" || sort === "points";
// The one filter an index takes with each order, most telling first; whatever else was asked for is kept in passing.
@@ -390,16 +413,6 @@ export const listAction = defineUserQuery({
? result
? papers.withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result))
: papers.withIndex("by_job_and_result", (q) => q.eq("jobId", jobId))
- : sort === "added"
- ? reason
- ? papers.withIndex("by_job_and_reason", (q) => q.eq("jobId", jobId).eq("reason", reason))
- : check
- ? papers.withIndex("by_job_and_check", (q) => q.eq("jobId", jobId).eq("checkId", check))
- : source
- ? papers.withIndex("by_job_and_source", (q) => q.eq("jobId", jobId).eq("sourceId", source))
- : result
- ? papers.withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result))
- : papers.withIndex("by_job", (q) => q.eq("jobId", jobId))
: result
? papers.withIndex(`by_job_and_result_and_${field[sort]}`, (q) => q.eq("jobId", jobId).eq("result", result))
: papers.withIndex(`by_job_and_${field[sort]}`, (q) => q.eq("jobId", jobId))
diff --git a/convex/screening/papers.ts b/convex/screening/papers.ts
index 3d953014f..1c8a89666 100644
--- a/convex/screening/papers.ts
+++ b/convex/screening/papers.ts
@@ -112,6 +112,8 @@ export const answerAction = defineUserMutation({
run: async (ctx, { userId, workspaceId, author }, { jobId, paperId: given, questionKey, answer, expect }) => {
let job = await ctx.db.get("screeningJobs", jobId);
if (!job || !(job.workspaceId === workspaceId)) throw createError("SCREENING_JOB_NOT_FOUND", "Screening job not found");
+ // A screening with reviewers decides a paper on its votes, cast on its own pages: an answer changed here would move nothing they show.
+ if (job.shape === 2) throw createError("VALIDATION_ERROR", "This screening is decided by its reviewers' votes. Vote on the paper on its Screen page.");
const question = job.questions.find((q) => q.key === questionKey);
if (!question) throw createError("VALIDATION_ERROR", "This screening doesn't ask that question");
let result = await screened(ctx, jobId, given);
diff --git a/convex/screening/readings.ts b/convex/screening/readings.ts
index e94af7f21..c455aa108 100644
--- a/convex/screening/readings.ts
+++ b/convex/screening/readings.ts
@@ -134,8 +134,10 @@ export const hold = internalMutation({
args: { jobId: v.id("screeningJobs"), cursor: v.union(v.string(), v.null()), model: v.optional(v.number()) },
returns: v.null(),
handler: async (ctx, { jobId, cursor, model = 0 }) => {
+ const job = await ctx.db.get("screeningJobs", jobId);
const reviewer = (await modelReviewers(ctx, jobId))[model];
- if (!reviewer) return null;
+ // Let go again since this sweep began (resumed, reopened): the release under way puts every reading back, and this one stops.
+ if (!job || !reviewer || modelsFree(job)) return null;
const page = await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_place", (q) => q.eq("reviewerId", reviewer._id).eq("status", "waiting")).paginate({ cursor, numItems: SWEEP });
for (const vote of page.page) if (vote.waitingWorkspace !== undefined) await ctx.db.patch("screeningVotes", vote._id, { waitingWorkspace: undefined, waitingSince: undefined });
await ctx.scheduler.runAfter(0, internal.screening.readings.hold, page.isDone ? { jobId, cursor: null, model: model + 1 } : { jobId, cursor: page.continueCursor, model });
diff --git a/convex/screening/reviewers.test-support.ts b/convex/screening/reviewers.test-support.ts
index c59f3b1dd..f22a5586d 100644
--- a/convex/screening/reviewers.test-support.ts
+++ b/convex/screening/reviewers.test-support.ts
@@ -1,3 +1,5 @@
+import { excludedFor } from "./facets";
+import { NAMED_REASONS } from "../../lib/screening/rules";
import { convexTest } from "convex-test";
import type { FunctionArgs } from "convex/server";
import { internal } from "../_generated/api";
@@ -56,13 +58,13 @@ type T = Team["t"];
/** Gives a screening's source `at` these records in one step, and returns the papers it took, in their order. */
export async function give(t: T, jobId: Id<"screeningJobs">, at: number, papers: FunctionArgs["papers"]) {
- const { checkId, sourceId } = await t.run(async (ctx) => {
+ const { checkId, sourceId, pass } = await t.run(async (ctx) => {
const check = (await ctx.db.query("screeningChecks").withIndex("by_job", (q) => q.eq("jobId", jobId)).order("desc").first())!;
const source = (await ctx.db.query("screeningSources").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect())[at]!;
- return { checkId: check._id, sourceId: source._id };
+ return { checkId: check._id, sourceId: source._id, pass: source.pass ?? 0 };
});
- await t.mutation(internal.screening.gathering.begin, { sourceId });
- await t.mutation(internal.screening.gathering.fill, { checkId, sourceId, papers, read: papers.length, ended: true });
+ await t.mutation(internal.screening.gathering.begin, { sourceId, pass });
+ await t.mutation(internal.screening.gathering.fill, { checkId, sourceId, pass, papers, read: papers.length, ended: true });
return { checkId, sourceId, papers: await papersOf(t, jobId) };
}
@@ -100,7 +102,7 @@ export async function standingOf(t: T, jobId: Id<"screeningJobs">) {
return {
papers: papers.map((one) => ({ title: one.title, result: one.result, reason: one.reason, on: Object.fromEntries(votes.filter((vote) => vote.resultId === one._id).map((vote) => [users.get(vote.reviewerId)!, vote.decision ?? vote.status])) })),
counts: progress.counts,
- reasons: progress.reasons,
+ reasons: await excludedFor(ctx as never, jobId, [...((await ctx.db.get("screeningJobs", jobId))!.criteria ?? []).map((one) => one.key), ...NAMED_REASONS]),
reviewers: Object.fromEntries(reviewers.map((one) => [users.get(one._id)!, { dealt: one.dealt, ...progress.reviewers?.[one._id] }])),
agreement: await ctx.db.query("screeningAgreement").withIndex("by_job_and_a_and_b", (q) => q.eq("jobId", jobId)).collect(),
};
diff --git a/convex/screening/screenings.ts b/convex/screening/screenings.ts
index aceb5a0e0..6c6d03a94 100644
--- a/convex/screening/screenings.ts
+++ b/convex/screening/screenings.ts
@@ -19,6 +19,7 @@ import { usableFor } from "../../lib/ai/tasks";
import { defaultPoints, defaultStars, EVERY_MS, MAX_SOURCES, shortOf, type Criterion } from "../../lib/screening/rules";
import { requireMember } from "./access";
import { MAX_REVIEWERS, MAX_SOURCE_ROWS, countDealt, keepVersion, placeGuests, dealNew, readingModel, readsOf, reviewersOf, sourcesOf, touched, votesOf, papersOf } from "./dealing";
+import { own } from "./files";
import { readInTurn } from "./living";
import { modelsLimit, startWaitingVotes } from "./slots";
import { screeningDestination } from "../library/collections";
@@ -143,7 +144,7 @@ export const sync = workspaceMutation({
const rows = was ? await sourcesOf(ctx, was._id) : [];
if (was && sources.length >= rows.length && rows.length > 0 && rows.every((row, at) => sameSource(row, sources[at]!))) {
const added = [];
- for (const source of sources.slice(rows.length)) added.push(await addSource(ctx, was._id, actor.userId, source, now));
+ for (const source of sources.slice(rows.length)) added.push(await addSource(ctx, was._id, actor, source, now));
if (added.length) {
await ctx.db.patch("screeningJobs", was._id, touched(now));
await readOn(ctx, was, actor.userId);
@@ -170,7 +171,7 @@ export const sync = workspaceMutation({
});
await ctx.db.insert("screeningJobProgress", { jobId, completed: 0, skipped: 0, failed: 0, qualified: 0, counts: NO_RESULTS });
const made = [];
- for (const source of sources) made.push(await addSource(ctx, jobId, actor.userId, source, now));
+ for (const source of sources) made.push(await addSource(ctx, jobId, actor, source, now));
await readOn(ctx, (await ctx.db.get("screeningJobs", jobId))!, actor.userId);
return { jobId, sources: made };
},
@@ -280,7 +281,7 @@ export const open = internalMutation({
if (adopted) await ctx.db.patch("screeningJobs", jobId, settings);
else {
await ctx.db.insert("screeningJobProgress", { jobId, completed: 0, skipped: 0, failed: 0, qualified: 0, counts: NO_RESULTS });
- for (const source of sources) await addSource(ctx, jobId, userId, source, now);
+ for (const source of sources) await addSource(ctx, jobId, { userId, workspaceId }, source, now);
}
for (const person of people) await ctx.db.insert("screeningReviewers", { jobId, kind: "person", userId: person, addedAt: now, addedBy: userId, dealt: 0 });
for (const { model, effort } of picked) await ctx.db.insert("screeningReviewers", { jobId, kind: "model", modelId: model._id, ...(effort ? { effort } : {}), addedAt: now, addedBy: userId, dealt: 0 });
@@ -294,7 +295,15 @@ export const open = internalMutation({
});
/** A source's row, waiting to be read. */
-export async function addSource(ctx: MutationCtx, jobId: Id<"screeningJobs">, userId: Id<"users">, { set, name, detail, facts, first, last }: Infer, now: number) {
+export async function addSource(ctx: MutationCtx, jobId: Id<"screeningJobs">, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, { set, name, detail, facts, first, last }: Infer, now: number) {
+ const { userId } = actor;
+ // A drop of PDFs is its adder's, and a file is the screening's that read it first: one another workspace's screening reads isn't this one's to read.
+ if (set.kind === "pdf") await own(ctx, actor, set.batch);
+ if (set.kind === "upload" || set.kind === "dois") {
+ for (const other of await ctx.db.query("screeningSources").withIndex("by_file", (q) => q.eq("set.file", set.file)).take(MAX_SOURCE_ROWS)) {
+ if ((await ctx.db.get("screeningJobs", other.jobId))?.workspaceId !== actor.workspaceId) throw createError("FORBIDDEN", "This file was added by someone else.");
+ }
+ }
if (first !== undefined && (!Number.isSafeInteger(first) || first < 1)) throw createError("VALIDATION_ERROR", "Pick papers from 1 up, with the first before the last");
if (last !== undefined && (!Number.isSafeInteger(last) || last < (first ?? 1))) throw createError("VALIDATION_ERROR", "Pick papers from 1 up, with the first before the last");
if ((await sourcesOf(ctx, jobId)).length >= MAX_SOURCE_ROWS) throw createError("VALIDATION_ERROR", "This screening has had as many sources as one can have. Start another screening for more.");
diff --git a/convex/screening/settings.ts b/convex/screening/settings.ts
index 12705fc78..fc41abd5e 100644
--- a/convex/screening/settings.ts
+++ b/convex/screening/settings.ts
@@ -214,7 +214,7 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId
const source = sources.find((one) => one._id === range.sourceId && one.removedAt === undefined);
if (source) await ctx.db.patch("screeningSources", source._id, { first: range.first, last: range.last, ...readAgain(source) });
}
- for (const source of change.addSources ?? []) await addSource(ctx, jobId, actor.userId, source, now);
+ for (const source of change.addSources ?? []) await addSource(ctx, jobId, actor, source, now);
// New papers arrive by a look in its sources: the ones just added or widened are read, and a screening made living looks in the others too.
const reads = Boolean(change.addSources?.length || change.ranges?.length);
// Made living in the same save that adds a source, it looks in every source at once, as it said it would: the added ones are read in that same look.
@@ -230,7 +230,8 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId
const more: Line[] = [
...partsOf(change).map((part) => ({ code: "part", detail: part })),
- ...(change.recheck ? [{ code: "rechecked" }] : []),
+ // Every settled paper is checked again: as many as stood settled when it was saved.
+ ...(change.recheck ? [{ code: "rechecked", count: ((counts) => (counts?.include ?? 0) + (counts?.maybe ?? 0) + (counts?.exclude ?? 0))((await progressRow(ctx, jobId))?.counts) }] : []),
...(await Promise.all(plan.joining.map(async ({ userId }) => { const user = await ctx.db.get("users", userId); return { code: "joinedBy", detail: nameOf(user) }; }))),
...plan.leaving.flatMap(({ discard }) => (discard ? [{ code: "votesDiscarded" }] : [])),
];
diff --git a/convex/screening/settling.test.ts b/convex/screening/settling.test.ts
index 905c2e0c8..8d8e52356 100644
--- a/convex/screening/settling.test.ts
+++ b/convex/screening/settling.test.ts
@@ -46,7 +46,8 @@ describe("a paper settled on its votes", () => {
await expect(made.as.ben!.mutation(api.screening.voting.resolve, { workspaceId: made.workspaceId, jobId, paperId: second, decision: "include" })).rejects.toMatchObject({ data: { code: "FORBIDDEN" } });
const criterion = (await made.t.run((ctx) => ctx.db.get("screeningJobs", jobId)))!.criteria![0]!.key;
await made.as.ann!.mutation(api.screening.voting.resolve, { workspaceId: made.workspaceId, jobId, paperId: second, decision: "exclude", reason: criterion });
- await settleAll(made.t);
+ // The reasons are counted a moment after the papers: once that has run.
+ await runAll(made.t, vi.runAllTimers);
const settled = await standingOf(made.t, jobId);
expect(settled.papers[1]).toMatchObject({ result: "exclude", reason: criterion });
expect(settled.counts).toEqual({ include: 1, maybe: 0, exclude: 1, conflict: 0 });
@@ -107,7 +108,7 @@ describe("a paper settled on its votes", () => {
const made = await team(["ann"]);
const { jobId, papers } = await started(made, ["ann"], 1, { rule: { each: 1, settle: "one", blind: "after" } });
await made.as.ann!.mutation(api.screening.voting.vote, { workspaceId: made.workspaceId, jobId, paperId: papers[0]!._id, decision: "exclude" });
- await settleAll(made.t);
+ await runAll(made.t, vi.runAllTimers);
const settled = await standingOf(made.t, jobId);
expect(settled.papers[0]).toMatchObject({ result: "exclude", reason: "unstated" });
expect(settled.reasons).toEqual({ unstated: 1 });
@@ -546,3 +547,26 @@ describe("a search through a reviewer's queue", () => {
expect(firstShownAfter).toBeLessThanOrEqual(5);
});
});
+
+describe("a vote asked for again", () => {
+ it("stays asked for while answers join it, and is answered by a new vote", async () => {
+ // Ben hasn't voted, so the paper is still open when the criterion changes.
+ const made = await team(["ann", "ben"]);
+ const { jobId, papers } = await started(made, ["ann", "ben"], 1, { rule: { each: 2, settle: "all", blind: "after" } });
+ const paperId = papers[0]!._id;
+ await voter(made, jobId)("ann", paperId, "include");
+ await runAll(made.t, vi.runAllTimers);
+ // A criterion made a must-have asks for her vote again.
+ const criteria = (await made.t.run((ctx) => ctx.db.get("screeningJobs", jobId)))!.criteria!.map(({ key, text, short, terms, points }) => ({ key, text, short, terms, points, must: true }));
+ await made.as.ann!.mutation(api.screening.settings.save, { workspaceId: made.workspaceId, jobId, change: { criteria } });
+ await runAll(made.t, vi.runAllTimers);
+ const ann = await made.t.run(async (ctx) => (await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect()).find((one) => one.userId === made.ids.ann)!._id);
+ const flagged = () => made.t.run(async (ctx) => (await ctx.db.query("screeningVotes").withIndex("by_job_and_place", (q) => q.eq("jobId", jobId)).collect()).find((one) => one.reviewerId === ann)!.flagged);
+ expect(await flagged()).toBe(true);
+ const key = criteria[0]!.key;
+ await made.as.ann!.mutation(api.screening.voting.vote, { workspaceId: made.workspaceId, jobId, paperId, decision: "include", answers: { [key]: "yes" }, answersOnly: true });
+ expect(await flagged()).toBe(true);
+ await made.as.ann!.mutation(api.screening.voting.vote, { workspaceId: made.workspaceId, jobId, paperId, decision: "include", answers: { [key]: "yes" } });
+ expect(await flagged()).toBeFalsy();
+ });
+});
diff --git a/convex/screening/settling.ts b/convex/screening/settling.ts
index ec96435da..2faa9bb88 100644
--- a/convex/screening/settling.ts
+++ b/convex/screening/settling.ts
@@ -11,7 +11,7 @@
*/
import type { Doc, Id } from "../_generated/dataModel";
import type { MutationCtx } from "../_generated/server";
-import { advisory, cellOf, DECISIONS, emptyMatrix, isFinal, NO_REASON, reasonOf, scoreOf, type Answer, type Decision, type Result } from "../../lib/screening/rules";
+import { cellOf, decidingVotes, DECISIONS, emptyMatrix, isFinal, NO_REASON, reasonOf, scoreOf, type Answer, type Decision, type Result } from "../../lib/screening/rules";
import { newCollection } from "../library/collections";
import { progressOf, shelve, withMoved } from "./bookkeeping";
import { ballotOf, project, type Place, type Projected } from "../../lib/screening/project";
@@ -100,8 +100,6 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
const order = new Map(reviewers.map((one, at) => [one._id, at]));
const progress = await progressOf(ctx, job._id);
const counts = { ...NO_RESULTS, ...progress.counts };
- const reasons = { ...progress.reasons };
- const included: Record = { ...progress.included };
const perReviewer = new Map, Counts>();
const countsOf = (id: Id<"screeningReviewers">) => perReviewer.get(id) ?? perReviewer.set(id, { ...NO_COUNTS, ...progress.reviewers?.[id] }).get(id)!;
const pairs = new Map; b: Id<"screeningReviewers">; cells: number[] }>();
@@ -111,7 +109,6 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
held.cells[cell]! += sign;
};
const moved = { saved: 0, removed: 0 };
- let withdrawn = 0;
// Rows this pass made or took away, by reviewer: what it adds to their count of papers.
const dealt = new Map, number>();
let freed = 0;
@@ -142,7 +139,6 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
const now = plan.result;
// The papers an extraction takes from it are its included ones: only a paper entering or leaving them is a change an extraction under way has to hear of (../paperSets/held.ts).
if ((now === "include") !== (was === "include")) moves++;
- if (Boolean(paper.withdrawn) !== Boolean(paper.out)) withdrawn += paper.withdrawn ? 1 : -1;
const rowOf = (place: Place) => votes[places.indexOf(place)]!;
// A reading under way finishes and is paid for: its place goes once the reading has come back.
const leaving = plan.gone.map(rowOf).filter((vote) => vote.workId === undefined);
@@ -202,8 +198,6 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
// The papers the screening included that a reviewer voted to exclude: counted for each of them as the paper's result and their vote stand.
if (was === "include") for (const one of before) if (one.decision === "exclude") countsOf(one.id).missed = Math.max(0, (countsOf(one.id).missed ?? 0) - 1);
if (now === "include" && !paper.withdrawn) for (const one of after) if (one.decision === "exclude") countsOf(one.id).missed = (countsOf(one.id).missed ?? 0) + 1;
- if (paper.sourceId && was === "include") included[paper.sourceId] = Math.max(0, (included[paper.sourceId] ?? 1) - 1);
- if (paper.sourceId && now === "include" && !paper.withdrawn) included[paper.sourceId] = (included[paper.sourceId] ?? 0) + 1;
const cast = ballots();
// How many of its models would include it goes on the places its people have yet to vote from, for the order that puts those papers first.
@@ -211,11 +205,8 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
for (const vote of votes) if (vote.status === "waiting" && byId.get(vote.reviewerId)?.kind === "person" && (vote.lean ?? 0) !== lean) await ctx.db.patch("screeningVotes", vote._id, { lean });
const given = cast.flatMap((one) => (one.status === "cast" && one.decision ? [one.decision] : []));
const split = given.length - Math.max(0, ...DECISIONS.map((decision) => given.filter((one) => one === decision).length));
- // The reason comes from the votes that decide the paper: where the models' votes are advice, or "first vote decides" gives a person's vote the say, the people's.
- const voters = job.rule && advisory(job.rule) && cast.some((one) => one.kind === "person" && one.status === "cast") ? cast.filter((one) => one.kind === "person") : cast;
- // Under "first vote decides", the one vote that settled it gives the reason too, whatever later votes say.
- const first = job.rule?.settle === "one" ? voters.filter((one) => one.status === "cast" && one.decision).reduce<(typeof voters)[number] | undefined>((earliest, one) => (!earliest || (one.at ?? 0) < (earliest.at ?? 0) ? one : earliest), undefined) : undefined;
- const deciding = first ? [first] : voters;
+ // The reason comes from the votes that decide the paper, as the rule reads them: under "first vote decides", the one vote that settled it, whatever later votes say.
+ const deciding = job.rule ? decidingVotes(job.rule.settle, cast, job.rule.models).votes : cast;
// An exclusion cast with no reason counts as no reason given, among the others and when it settles a conflict: it never takes another vote's reason.
// A result held through a change of settings keeps the reason it was excluded for: the votes that decide it under the new rule didn't decide it.
const reason = now === "exclude" ? (paper.resolved?.decision === "exclude" ? (paper.resolved.reason ?? NO_REASON) : held && (carried ?? was) === "exclude" && paper.reason ? paper.reason : (reasonOf(deciding.map((one) => (one.status === "cast" && one.decision === "exclude" && !one.reason ? { ...one, reason: NO_REASON } : one))) ?? NO_REASON)) : undefined;
@@ -223,8 +214,6 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
if (now === "conflict" && was !== "conflict") conflicts = true;
if (was !== "waiting") counts[was] = Math.max(0, counts[was] - 1);
if (now !== "waiting") counts[now]++;
- if (was === "exclude") reasons[paper.reason ?? NO_REASON] = (reasons[paper.reason ?? NO_REASON] ?? 1) - 1;
- if (reason) reasons[reason] = (reasons[reason] ?? 0) + 1;
const patch = paper.withdrawn ? { result: undefined, outcome: undefined, qualified: undefined, reason: undefined, split: undefined, settledAt: undefined, reopen: undefined, out: true as const } : { result: now, outcome: OUTCOME[now], qualified: now === "include", reason, score: points, stars, split, reopen: undefined, out: undefined, ...(paper.kept && carried === undefined ? { kept: undefined } : {}), ...(isFinal(now) && (now !== was || paper.reopen !== undefined) ? { settledAt: Date.now() } : {}), ...(isFinal(now) ? {} : { settledAt: undefined }) };
await ctx.db.patch("screeningResults", paper._id, patch);
if (paper.withdrawn) continue;
@@ -246,11 +235,11 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
await ctx.db.patch("screeningJobProgress", progress._id, {
counts,
qualified: counts.include,
- reasons: Object.fromEntries(Object.entries(reasons).filter(([, n]) => n > 0)),
- included: Object.fromEntries(Object.entries(included).filter(([, n]) => n > 0)),
+ // Excluded papers by reason and included ones by source are counted with the papers (./facets.ts): the copies once kept here go.
+ reasons: undefined,
+ included: undefined,
...(perReviewer.size ? { reviewers: { ...progress.reviewers, ...Object.fromEntries(perReviewer) } } : {}),
...(freed && progress.running ? { running: Math.max(0, progress.running - freed) } : {}),
- ...(withdrawn ? { withdrawn: Math.max(0, (progress.withdrawn ?? 0) + withdrawn) } : {}),
...withMoved(progress, moved),
...(moves ? { exportRevision: (progress.exportRevision ?? 0) + 1 } : {}),
});
diff --git a/convex/screening/slots.ts b/convex/screening/slots.ts
index eb566c068..6691f6686 100644
--- a/convex/screening/slots.ts
+++ b/convex/screening/slots.ts
@@ -27,6 +27,11 @@ const MODELS_A_SCREENING = 5;
/** How many models one screening in the workspace may have reading: its plan's number (lib/billing/plans.ts `screening_models`). */
export const modelsLimit = async (ctx: QueryCtx | MutationCtx, workspaceId: Id<"workspaces">) => (await planLimit(ctx, workspaceId, "screening_models")) ?? MODELS_A_SCREENING;
+/** The most papers one screening takes where its plan sets no number, and never more, whatever a plan says: 1,000 or 5,000 by plan. */
+const PAPERS_A_SCREENING = 5_000;
+/** How many papers one screening in the workspace may hold: its plan's number, within the most any screening takes. */
+export const papersLimit = async (ctx: QueryCtx | MutationCtx, workspaceId: Id<"workspaces">) => Math.min((await planLimit(ctx, workspaceId, "request_papers")) ?? PAPERS_A_SCREENING, PAPERS_A_SCREENING);
+
/** How many papers a workspace may have running at once, never more than the pool. */
export async function paperLimit(ctx: QueryCtx | MutationCtx, workspaceId: Id<"workspaces">) {
const concurrency = (await planLimit(ctx, workspaceId, "concurrency")) ?? DEFAULT_PAPER_CONCURRENCY;
diff --git a/convex/screening/validators.ts b/convex/screening/validators.ts
index e5b8f56b4..c0c3fd6b1 100644
--- a/convex/screening/validators.ts
+++ b/convex/screening/validators.ts
@@ -1,7 +1,7 @@
import { v, type Infer } from "convex/values";
import { MAX_AUTHORS, MAX_QUESTIONS, MAX_STARS, capped } from "../lib/listCaps";
import { PDF_BANDS } from "../../lib/pricing/estimate";
-import { CRITERION_LENGTH, GUIDANCE_LENGTH, MAX_TERMS, NOTE_LENGTH, SHORT_NAME_LENGTH } from "../../lib/screening/rules";
+import { CRITERION_LENGTH, GUIDANCE_LENGTH, MAX_TERMS, NAMED_REASONS, NOTE_LENGTH, SHORT_NAME_LENGTH } from "../../lib/screening/rules";
import { answerSourceValidator } from "../../lib/research/records";
import { sourceMetadataFields } from "../lib/paperMetadata";
import { crossRefsValidator } from "../lib/paperRef";
@@ -472,13 +472,14 @@ export const PAIRS_MAX = 400;
/** The figures a screening's overview and its files are drawn from (./view.ts `figures`). */
export const figuresValidator = v.object({
// Its excluded papers by the reason, and its included ones by the source that brought each.
- reasons: capped(v.record(v.string(), v.number()), MAX_QUESTIONS + 2),
+ reasons: capped(v.record(v.string(), v.number()), MAX_QUESTIONS + RETIRED_CRITERIA + NAMED_REASONS.length),
included: capped(v.record(v.string(), v.number()), MAX_SOURCE_ROWS),
// Each pair of reviewers' votes on the papers both voted on: include, maybe and exclude by the same three, row by row.
pairs: capped(v.array(v.object({ a: v.string(), b: v.string(), matrix: capped(v.array(v.number()), 9) })), PAIRS_MAX),
// The votes each person cast since the time asked for.
recent: capped(v.record(v.string(), v.number()), MAX_REVIEWERS),
startedWith: v.number(),
+ startedFrom: v.number(),
// Its checks for new papers after the start: how many, when the last one was, and what they found and added.
checks: v.object({ later: v.number(), /** The rows the list of checks has: every look but the first and one still running, as the Overview lists them. */ listed: v.number(), lastAt: v.optional(v.number()), found: v.number(), added: v.number(), /** The later checks with a source they couldn't read. */ unread: v.optional(v.number()) }),
// How many times its settings were changed, and which parts: the parts a save named (`partsOf` in ./settings.ts), and "reviewers" for each added or taken off.
diff --git a/convex/screening/view.ts b/convex/screening/view.ts
index 0288e9846..82141e94f 100644
--- a/convex/screening/view.ts
+++ b/convex/screening/view.ts
@@ -9,14 +9,14 @@ import { v, type Infer } from "convex/values";
import type { Doc, Id } from "../_generated/dataModel";
import type { QueryCtx } from "../_generated/server";
import { itemKey, moreValidator } from "../activity/validators";
-import { availableCredits, planLimit } from "../billing/accounts";
-import { modelsLimit, paperLimit } from "./slots";
+import { availableCredits } from "../billing/accounts";
+import { modelsLimit, paperLimit, papersLimit } from "./slots";
import { countOf, screeningsOf } from "../lib/listCounts";
import { personName } from "../lib/people";
import { assistantQuery, defineUserQuery, userQuery, workspaceQuery } from "../lib/userActions";
import schema from "../schema";
import { grantOf, itemGuestsOf } from "../sharing/items";
-import { hidesVotes, isFinal, modelsProgress, nameHas, readersFor, showsEarly, twinsNamed } from "../../lib/screening/rules";
+import { hidesVotes, modelsProgress, NAMED_REASONS, nameHas, readersFor, showsEarly, twinsNamed } from "../../lib/screening/rules";
import { readsPdfs } from "../../lib/assistant/files";
import { actorIn, inOwnWorkspace, type InWorkspace } from "../workspaces/actor";
import { standingOn, type Standing } from "./access";
@@ -25,7 +25,7 @@ import { dealable, firstCheck, inWhole, invitationsTo, laterChecks, modelName, m
import { noticeOf } from "./notices";
import { NO_RESULTS } from "./settling";
import { askedWhereValidator, ruleValidator, invitedViewValidator, libraryWriteProblemValidator, retiredCriteriaValidator, unreadSourcesValidator, modelVotesValidator, checkSourcesValidator, criteriaValidator, ELSEWHERE_MAX, elsewhereValidator, everyValidator, figuresValidator, leftOutWhyValidator, PAIRS_MAX, reviewerViewsValidator, reviewerViewValidator, sourceViewsValidator, starsValidator } from "./validators";
-import { castSince } from "./facets";
+import { castSince, excludedFor, tallyUnder } from "./facets";
const personValidator = v.object({ id: v.id("users"), name: v.string(), imageUrl: v.optional(v.string()) });
@@ -105,10 +105,24 @@ type Counts = NonNullable["reviewers"]>[Id<"screenin
* the person has yet to vote on. A finished screening keeps nothing: no vote can be cast in it any more. One
* function, for every figure a page or a file shows of the others.
*/
-export const keepsVotes = (job: Pick, "rule" | "finishedAt">, reviewer: Doc<"screeningReviewers"> | null, counts: Record | undefined, reviewers: Iterable>, /** People invited who haven't answered: they count among its readers, as do people taken off whose votes stay, as its pages count them (components/screening/data.ts `hidingReaders`). */ invited: number) => {
+export const keepsVotes = (job: Pick, "rule" | "finishedAt">, reviewer: Doc<"screeningReviewers"> | null, counts: Record | undefined, reviewers: Iterable>, /** People invited who haven't answered: they count among its readers, as do people taken off whose votes stay, as its pages count them (components/screening/data.ts `hidingReaders`). */ invited: number) =>
+ keeps(job, reviewer !== null && waitingOf(reviewer, counts?.[reviewer._id]) > 0, (id) => (counts?.[id]?.cast ?? 0) > 0, reviewers, invited);
+
+/** `keepsVotes` from the votes themselves, for a read that would otherwise run again whenever anyone's counts move: whether the person looking still has a paper to vote on, and whether each reviewer taken off voted. */
+export async function keepsVotesNow(ctx: Pick, job: Doc<"screeningJobs">, reviewer: Doc<"screeningReviewers"> | null, reviewers: Iterable>) {
const all = [...reviewers];
- return job.rule !== undefined && hidesVotes(job.rule, readersFor(job.rule.each, all.filter((one) => dealable(one) || (one.kind === "person" && one.left !== undefined && one.discarded === undefined && (counts?.[one._id]?.cast ?? 0) > 0)).length + invited), all.filter((one) => one.kind === "model" && (readingModel(one) || (one.left !== undefined && one.discarded === undefined && (counts?.[one._id]?.cast ?? 0) > 0))).length) && job.finishedAt === undefined && reviewer !== null && waitingOf(reviewer, counts?.[reviewer._id]) > 0;
-};
+ if (!job.rule || job.finishedAt !== undefined || !reviewer) return false;
+ const has = async (id: Id<"screeningReviewers">, status: "waiting" | "cast") => (await ctx.db.query("screeningVotes").withIndex("by_reviewer_and_status_and_place", (q) => q.eq("reviewerId", id).eq("status", status)).first()) !== null;
+ if (!(await has(reviewer._id, "waiting"))) return false;
+ const voted = new Set(await Promise.all(all.filter((one) => one.left !== undefined && one.discarded === undefined).map(async (one) => ((await has(one._id, "cast")) ? one._id : null))));
+ return keeps(job, true, (id) => voted.has(id), all, (await invitationsTo(ctx, job._id)).length);
+}
+
+function keeps(job: Pick, "rule" | "finishedAt">, waiting: boolean, voted: (id: Id<"screeningReviewers">) => boolean, reviewers: Iterable>, invited: number) {
+ const all = [...reviewers];
+ const kept = (one: Doc<"screeningReviewers">) => one.left !== undefined && one.discarded === undefined && voted(one._id);
+ return job.rule !== undefined && hidesVotes(job.rule, readersFor(job.rule.each, all.filter((one) => dealable(one) || (one.kind === "person" && kept(one))).length + invited), all.filter((one) => one.kind === "model" && (readingModel(one) || kept(one))).length) && job.finishedAt === undefined && waiting;
+}
/** A reviewer's row as the pages read it, with their counts. `kept`: how they voted is kept from whoever looks (`keepsVotes`). */
async function reviewerView(ctx: Pick, job: Doc<"screeningJobs">, reviewer: Doc<"screeningReviewers">, counts: Counts | undefined, members: Map, boolean>, kept = false): Promise {
@@ -127,7 +141,7 @@ async function reviewerView(ctx: Pick, job: Doc<"screeningJobs">
}
/** What a screening's models are doing, and the screening whose models read first where its own wait their turn. */
-async function modelsNow(ctx: Pick, job: Doc<"screeningJobs">, reviewers: ReviewerView[], progress: Doc<"screeningJobProgress"> | null, check: Doc<"screeningChecks"> | null, starting: boolean) {
+async function modelsNow(ctx: Pick, job: Doc<"screeningJobs">, reviewers: ReviewerView[], progress: Doc<"screeningJobProgress"> | null, check: Doc<"screeningChecks"> | null, starting: boolean, member: boolean) {
if (check) return { state: starting ? ("gathering" as const) : ("checking" as const) };
if (job.finishedAt !== undefined) return { state: null };
const models = reviewers.filter((one) => one.kind === "model" && one.left === undefined);
@@ -136,9 +150,9 @@ async function modelsNow(ctx: Pick, job: Doc<"screeningJobs">, r
if (!models.some((model) => model.waiting > 0)) return { state: null };
if (job.outOfCredits) return { state: "credits" as const };
if (!(progress?.running ?? 0)) {
- // None of its papers is being read: the workspace's slots are taken by a screening that started before it.
+ // None of its papers is being read: the workspace's slots are taken by a screening that started before it. Which one is its workspace's to know: a guest is told only that its models wait their turn.
const ahead = await readingFirst(ctx, job.workspaceId, job._id);
- if (ahead) return { state: "waiting" as const, ahead };
+ if (ahead) return member ? { state: "waiting" as const, ahead } : { state: "waiting" as const };
}
return { state: "reading" as const };
}
@@ -189,8 +203,8 @@ export async function summaryOf(ctx: Pick, actor: InWorkspace, {
const total = papersOf(job, progress);
const counts = { ...settled, waiting: Math.max(0, total - settled.include - settled.maybe - settled.exclude - settled.conflict) };
const canResolve = job.rule?.resolver === actor.userId;
- const { state, ahead } = await modelsNow(ctx, job, reviewers, progress, check, check !== null && check._id === first?._id);
- const waits = await waitsOn(ctx, job, actor.userId, reviewer, progress);
+ const { state, ahead } = await modelsNow(ctx, job, reviewers, progress, check, check !== null && check._id === first?._id, member);
+ const waits = await waitsOn(ctx, job, actor.userId, reviewer);
return {
id: job._id,
name: job.name ?? "Screening",
@@ -229,10 +243,10 @@ export async function summaryOf(ctx: Pick, actor: InWorkspace, {
*/
export const setup = workspaceQuery({
args: {},
- returns: v.object({ me: personValidator, credits: v.number(), limits: v.object({ papers: v.union(v.number(), v.null()), models: v.number(), atOnce: v.number() }), reading: v.optional(aheadValidator) }),
+ returns: v.object({ me: personValidator, credits: v.number(), limits: v.object({ papers: v.number(), models: v.number(), atOnce: v.number() }), reading: v.optional(aheadValidator) }),
handler: async (ctx, { userId, workspaceId }) => {
- const [me, credits, papers, models, atOnce, reading] = await Promise.all([ctx.db.get("users", userId), availableCredits(ctx, workspaceId), planLimit(ctx, workspaceId, "request_papers"), modelsLimit(ctx, workspaceId), paperLimit(ctx, workspaceId), readingFirst(ctx, workspaceId)]);
- return { me: personOf(me, userId), credits, limits: { papers: papers ?? null, models, atOnce }, ...(reading ? { reading } : {}) };
+ const [me, credits, papers, models, atOnce, reading] = await Promise.all([ctx.db.get("users", userId), availableCredits(ctx, workspaceId), papersLimit(ctx, workspaceId), modelsLimit(ctx, workspaceId), paperLimit(ctx, workspaceId), readingFirst(ctx, workspaceId)]);
+ return { me: personOf(me, userId), credits, limits: { papers, models, atOnce }, ...(reading ? { reading } : {}) };
},
});
@@ -289,7 +303,7 @@ export const mine = workspaceQuery({
if (standing?.job.shape !== 2) return [];
const { job, member, reviewer } = standing;
if (member) {
- const waits = await waitsOn(ctx, job, userId, reviewer, await progressRow(ctx as QueryCtx, job._id));
+ const waits = await waitsOn(ctx, job, userId, reviewer);
// A finished screening asks for no vote, and still for the answer to a question put to the person.
if (!(waits.forYou + waits.conflicts + waits.asked.length)) return [];
}
@@ -308,8 +322,8 @@ async function waitsFor(ctx: Pick, userId: Id<"users">) {
const job = await ctx.db.get("screeningJobs", jobId);
// A finished one waits on the person only for an answer to a question (./dealing.ts `waitsOn`).
if (!job || job.shape !== 2) return [];
- const [reviewer, progress] = await Promise.all([ctx.db.query("screeningReviewers").withIndex("by_job_and_user", (q) => q.eq("jobId", jobId).eq("userId", userId)).first(), progressRow(ctx as QueryCtx, jobId)]);
- const waits = await waitsOn(ctx, job, userId, reviewer, progress);
+ const reviewer = await ctx.db.query("screeningReviewers").withIndex("by_job_and_user", (q) => q.eq("jobId", jobId).eq("userId", userId)).first();
+ const waits = await waitsOn(ctx, job, userId, reviewer);
return waits.forYou + waits.conflicts + waits.asked.length ? [{ job, forYou: waits.forYou, conflicts: waits.conflicts, asked: waits.asked.length, ...(waits.asked[0] ? { askedFirst: waits.asked[0], ...(waits.askedWhere ? { askedWhere: waits.askedWhere } : {}) } : {}) }] : [];
}));
return found.flat();
@@ -388,15 +402,10 @@ const checkValidator = v.object({
// The papers a later check added, by the source that brought them.
sources: checkSourcesValidator,
});
-/** The most papers a check may have added for where they stand to be counted with it. */
-const CHECK_COUNTED = 200;
-
/** Checks one page of a screening's checks holds at most, and the latest of them looked through for the last that brought papers. */
const CHECKS_PAGE = 50;
/** Votes that ask for a new one, counted for their reviewer's tab: past it the tab says so many and more. */
const FLAGGED_COUNTED = 500;
-/** Papers of its last check counted for what is still open among them. */
-const LATEST_COUNTED = 500;
export const getAction = defineUserQuery({
path: "screening/view:get",
@@ -438,7 +447,7 @@ export const getAction = defineUserQuery({
// The last check of its sources that brought papers: how many, how many of them still wait for votes, and how many wait for the person's own.
latest: v.optional(v.object({ id: v.id("screeningChecks"), at: v.number(), added: v.number(), open: v.number(), mine: v.number() })),
// The last check there was, whatever it found, and how many checks it has had since it started.
- lastCheck: v.optional(v.object({ at: v.number(), found: v.number(), added: v.number() })),
+ lastCheck: v.optional(v.object({ at: v.number(), found: v.number(), added: v.number(), /** Sources it couldn't read: it found nothing new in the rest, which isn't the same as nothing new. */ unread: v.optional(v.number()) })),
}),
),
run: async (ctx, actor, { jobId }) => {
@@ -456,8 +465,8 @@ export const getAction = defineUserQuery({
// The first look in its sources is the screening starting: only a later one "brought new papers".
const lately = await laterChecks(ctx, jobId);
const last = lately.find((check) => check.added > 0);
- const brought = last ? await ctx.db.query("screeningResults").withIndex("by_job_and_check", (q) => q.eq("jobId", jobId).eq("checkId", last._id)).take(LATEST_COUNTED) : [];
- const theirs = last && reviewer ? await newFor(ctx, reviewer._id, last, LATEST_COUNTED) : 0;
+ const brought = last ? await tallyUnder(ctx, jobId, { check: last._id }) : null;
+ const theirs = last && reviewer ? await newFor(ctx, reviewer._id, last) : 0;
return {
...summary,
atOnce: await paperLimit(ctx, job.workspaceId),
@@ -486,8 +495,8 @@ export const getAction = defineUserQuery({
guests: await countOf(ctx, itemGuestsOf(jobId)),
// The invitations still waiting, which papers wait for as for anyone: a guest is told how many, and never whose address.
invited: (await invitationsTo(ctx, jobId)).map((one) => (member ? { email: one.email, expiresAt: one.expiresAt, ...(one.delivery === "failed" ? { undelivered: true as const } : {}) } : {})),
- ...(lately[0] ? { lastCheck: { at: lately[0].endedAt ?? lately[0].at, found: lately[0].found, added: lately[0].added } } : {}),
- ...(last ? { latest: { id: last._id, at: last.endedAt ?? last.at, added: last.added, open: brought.filter((paper) => !paper.withdrawn && !isFinal(paper.result)).length, mine: theirs } } : {}),
+ ...(lately[0] ? { lastCheck: { at: lately[0].endedAt ?? lately[0].at, found: lately[0].found, added: lately[0].added, ...(lately[0].unread?.length ? { unread: lately[0].unread.length } : {}) } } : {}),
+ ...(last ? { latest: { id: last._id, at: last.endedAt ?? last.at, added: last.added, open: brought!.waiting + brought!.conflict, mine: theirs } } : {}),
};
},
});
@@ -521,13 +530,17 @@ export const figuresAction = defineUserQuery({
const recent = await Promise.all(people.map(async (one) => [viewId(one), await castSince(ctx as QueryCtx, one._id, since)] as const));
// The searches for papers its sources gained. A save that read a source it added or widened searched nothing again.
const later = checks.filter((check) => check.search && check.state === "done");
+ const job = standing.job;
+ const sources = await sourcesOf(ctx, jobId);
return {
- reasons: progress?.reasons ?? {},
- included: progress?.included ?? {},
+ reasons: await excludedFor(ctx as QueryCtx, jobId, [...(job.criteria ?? []).map((one) => one.key), ...(job.retiredCriteria ?? []).map((one) => one.key), ...NAMED_REASONS]),
+ included: Object.fromEntries(await Promise.all(sources.map(async (source) => [source._id, (await tallyUnder(ctx as QueryCtx, jobId, { source: source._id })).include] as const))),
// How far two reviewers agree is how they voted, for someone who still has papers to vote on.
pairs: keepsVotes(standing.job, standing.reviewer, progress?.reviewers, reviewers, (await invitationsTo(ctx, jobId)).length) ? [] : pairs.flatMap((pair) => (idOf.has(pair.a) && idOf.has(pair.b) ? [{ a: idOf.get(pair.a)!, b: idOf.get(pair.b)!, matrix: pair.matrix }] : [])),
recent: Object.fromEntries(recent),
startedWith: checks[0]?.added ?? 0,
+ // The sources it started with, those taken out since among them: what "at the start" says it read.
+ startedFrom: sources.filter((source) => source.addedAt <= job.createdAt).length,
checks: { later: later.length, listed: checks.slice(1).filter((check) => check.state !== "running").length, ...(later.length ? { lastAt: later.at(-1)!.endedAt ?? later.at(-1)!.at } : {}), found: later.reduce((sum, check) => sum + check.found, 0), added: later.reduce((sum, check) => sum + check.added, 0), unread: later.filter((check) => (check.unread?.length ?? 0) > 0).length },
// What the methods paragraph says was changed: the settings, and who reviews.
changes: saves.filter((row) => CHANGED.has(row.code ?? "")).length,
@@ -630,11 +643,8 @@ export const checksAction = defineUserQuery({
const people = new Map, Person>();
for (const check of read.page) if (check.by && !people.has(check.by)) { const user = await ctx.db.get("users", check.by); people.set(check.by, personOf(user, check.by)); }
const stand = async (check: Doc<"screeningChecks">) => {
- if (isFirst(check) || !check.added || check.added > CHECK_COUNTED) return undefined;
- const papers = await ctx.db.query("screeningResults").withIndex("by_job_and_check", (q) => q.eq("jobId", jobId).eq("checkId", check._id)).take(CHECK_COUNTED);
- const counts = { include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0 };
- for (const paper of papers) if (!paper.withdrawn) counts[paper.result ?? "waiting"]++;
- return counts;
+ if (isFirst(check) || !check.added) return undefined;
+ return tallyUnder(ctx, jobId, { check: check._id });
};
return { ...read, page: await Promise.all(read.page.map(async (check) => { const counts = await stand(check); return { id: check._id, at: check.at, ...(check.search ? { search: true } : {}), ...(check.by ? { by: people.get(check.by)! } : {}), state: check.state, first: isFirst(check), found: check.found, added: check.added, ...(check.left ? { left: check.left } : {}), ...(check.unread?.length ? { unread: check.unread } : {}), ...(counts ? { counts } : {}), ...(isFirst(check) || !check.bySource ? {} : { sources: Object.entries(check.bySource).map(([id, added]) => ({ id: id as Id<"screeningSources">, added })) }) }; })) };
},
diff --git a/convex/screening/voting.ts b/convex/screening/voting.ts
index c2a4c38bc..254c17736 100644
--- a/convex/screening/voting.ts
+++ b/convex/screening/voting.ts
@@ -32,10 +32,10 @@ function requireReason(job: Doc<"screeningJobs">, reason: string | undefined, un
if (reason !== undefined && !criteria.some((criterion) => criterion.key === reason) && !(NAMED_REASONS as readonly string[]).includes(reason)) throw createError("VALIDATION_ERROR", "Pick one of the reasons listed.");
}
-const voteArgs = { jobId: v.id("screeningJobs"), paperId: v.id("screeningResults"), decision: v.union(decisionValidator, v.null()), answers: v.optional(voteAnswersValidator), reason: v.optional(v.string()), note: v.optional(v.string()), /** A vote on a selection: cast only where the place still waits for one, never over a vote cast since. */ onlyWaiting: v.optional(v.boolean()), /** A vote taken back by Undo or Take back: only while it is still the one cast at that moment, never one changed since. */ onlyAt: v.optional(v.number()) };
+const voteArgs = { jobId: v.id("screeningJobs"), paperId: v.id("screeningResults"), decision: v.union(decisionValidator, v.null()), answers: v.optional(voteAnswersValidator), reason: v.optional(v.string()), note: v.optional(v.string()), /** A vote on a selection: cast only where the place still waits for one, never over a vote cast since. */ onlyWaiting: v.optional(v.boolean()), /** A vote taken back by Undo or Take back: only while it is still the one cast at that moment, never one changed since. */ onlyAt: v.optional(v.number()), /** Answers given to a vote already cast: it is not a new vote, and a vote asked for again is still asked for. */ answersOnly: v.optional(v.boolean()) };
/** One person's vote on one paper, or their vote taken back. The paper is stamped: whoever calls wakes the worker once for all it cast. */
-async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJobs">; reviewer: Doc<"screeningReviewers"> }, { paperId, decision, answers, reason, note, onlyWaiting, onlyAt }: { paperId: Id<"screeningResults">; onlyWaiting?: boolean; onlyAt?: number; decision: "include" | "maybe" | "exclude" | null; answers?: Record; reason?: string; note?: string }) {
+async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJobs">; reviewer: Doc<"screeningReviewers"> }, { paperId, decision, answers, reason, note, onlyWaiting, onlyAt, answersOnly }: { paperId: Id<"screeningResults">; onlyWaiting?: boolean; onlyAt?: number; answersOnly?: boolean; decision: "include" | "maybe" | "exclude" | null; answers?: Record; reason?: string; note?: string }) {
const jobId = job._id;
const paper = await paperOf(ctx, jobId, paperId);
requireReason(job, reason, onlyAt !== undefined);
@@ -53,7 +53,7 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
const known = new Set([...(job.criteria ?? []), ...(onlyAt !== undefined ? (job.retiredCriteria ?? []) : [])].map((criterion) => criterion.key));
// A criterion given as the reason to exclude is one the voter says is not met, so its answer is No wherever the vote was cast from.
const given = { ...Object.fromEntries(Object.entries(answers ?? {}).filter(([key]) => known.has(key))), ...(decision === "exclude" && reason && known.has(reason) ? { [reason]: "no" as const } : {}) };
- const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: Date.now(), flagged: undefined };
+ const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: Date.now(), flagged: answersOnly && mine?.status === "cast" ? mine.flagged : undefined };
if (mine) await ctx.db.patch("screeningVotes", mine._id, vote);
else {
// A reviewer who votes on a paper that wasn't given to them is on it from then on.
diff --git a/lib/export.ts b/lib/export.ts
index 461fb01b6..6b043956e 100644
--- a/lib/export.ts
+++ b/lib/export.ts
@@ -10,9 +10,15 @@ import { openalexWorkOfRow } from "./papers/paper-ref";
type Cell = string | number | boolean | string[];
type Row = Record;
-function csvValue(value: Cell) {
- const text = Array.isArray(value) ? JSON.stringify(value) : String(value);
- return /[",\n\r]/.test(text) || text === "" ? `"${text.replace(/"/g, '""')}"` : text;
+/**
+ * One cell of a CSV file, as a spreadsheet opens it: quoted where it must be, a quote in it doubled. A text that begins the way a
+ * formula does (=, +, -, @) takes an apostrophe in front, so a spreadsheet keeps a title or a note as text and never
+ * runs it. A number stays a number, and a list is written as JSON.
+ */
+export function csvCell(value: unknown) {
+ const text = Array.isArray(value) ? JSON.stringify(value) : String(value ?? "");
+ const safe = typeof value === "string" && /^[=+\-@\t\r]/.test(value) ? `'${text}` : text;
+ return /[",\n\r']/.test(safe) || safe === "" ? `"${safe.replace(/"/g, '""')}"` : safe;
}
/** A CSV as it streams: its columns, then a line for each item. */
@@ -23,7 +29,7 @@ function csvFile(columns: string[], row: (item: Item) => Row) {
start: () => `${columns.join(",")}`,
item: (item: Item) => {
const values = row(item);
- return `\n${columns.map((column) => csvValue(values[column])).join(",")}`;
+ return `\n${columns.map((column) => csvCell(values[column])).join(",")}`;
},
end: () => "\n",
};
diff --git a/lib/hooks/use-cursor-page.ts b/lib/hooks/use-cursor-page.ts
index 965477f52..271a15810 100644
--- a/lib/hooks/use-cursor-page.ts
+++ b/lib/hooks/use-cursor-page.ts
@@ -255,3 +255,17 @@ function usePages(place: Place | null, query: Query, ar
},
};
}
+
+/**
+ * What a list draws while it is read, decided one way for every list: a list its count already says is empty says so
+ * at once, from its first read and on another tab alike, never skeletons first; a list being read, or another list
+ * asked for, shows as many skeleton rows as its count says it will hold, up to a page; the rows otherwise.
+ */
+export function listDraws(listed: { isLoading: boolean; isOther: boolean }, total: number | undefined, page: number): { draw: "empty" } | { draw: "skeleton"; rows: number } | { draw: "rows" } {
+ if (!listed.isLoading && !listed.isOther) return { draw: "rows" };
+ if (total === 0) return { draw: "empty" };
+ return { draw: "skeleton", rows: skeletonRows(total, page) };
+}
+
+/** Skeleton rows for a list being read: as many as its count says it holds, up to a page, and one where none is known. */
+export const skeletonRows = (total: number | undefined, page: number) => Math.max(1, Math.min(total ?? page, page));
diff --git a/lib/screening/file-words.test.ts b/lib/screening/file-words.test.ts
new file mode 100644
index 000000000..3efaf7bbb
--- /dev/null
+++ b/lib/screening/file-words.test.ts
@@ -0,0 +1,11 @@
+// A file's English (messages/screening-fragments/words.json) is a copy of the pages' own words, kept apart so a file
+// doesn't load every message: it must say what the English pages say.
+import { expect, it } from "vitest";
+import FILE_WORDS from "@/messages/screening-fragments/words.json";
+import US from "@/messages/en-US.json";
+import GB from "@/messages/en-GB.json";
+
+it("names everything as the English pages do", () => {
+ expect(FILE_WORDS).toEqual(US.screening.words);
+ expect(FILE_WORDS).toEqual(GB.screening.words);
+});
diff --git a/lib/screening/project.test.ts b/lib/screening/project.test.ts
index dff5b7f32..e8f6c15e3 100644
--- a/lib/screening/project.test.ts
+++ b/lib/screening/project.test.ts
@@ -40,4 +40,14 @@ describe("project", () => {
expect(after.result).toBe("conflict");
expect(after.made).toEqual([]);
});
+
+ it("takes a closed place away or opens it again, never both, when a settlement is taken back under a rule that asks for fewer", () => {
+ // Settled by hand while two people each held a place, then the rule went to one a paper and the settlement was taken back.
+ const closed = (reviewer: string): Place => ({ reviewer, kind: "person", status: "closed" });
+ const team = { people: ["ann", "ben"], models: [] };
+ const after = project(paper, [closed("ann"), closed("ben")], team, { each: 1, settle: "all" }, criteria, { models: false });
+ expect(after.reopened.map((place) => place.reviewer)).toEqual(["ann"]);
+ expect(after.gone.map((place) => place.reviewer)).toEqual(["ben"]);
+ expect(after.places.map((place) => [place.reviewer, place.status])).toEqual([["ann", "waiting"]]);
+ });
});
diff --git a/lib/screening/project.ts b/lib/screening/project.ts
index 0d7ed2017..30ed76873 100644
--- a/lib/screening/project.ts
+++ b/lib/screening/project.ts
@@ -75,14 +75,14 @@ export function project(paper: PaperState, places: Place[], team: Team, rule: Pi
const open = persons.filter((place) => place.status === "waiting" || place.status === "closed");
// A place whose holder has left the screening is free again.
const kept = open.filter((place) => team.people.includes(place.reviewer));
- reopened.push(...kept.filter((place) => place.status === "closed"));
- // A model's place closed when a person's vote settled the paper first (below) is open again with it.
- reopened.push(...list.filter((place) => place.kind === "model" && place.status === "closed" && team.models.includes(place.reviewer)));
// Whoever voted counts toward the rule's number, though they have since left. The places still free are for the people who haven't.
const cast = persons.filter((place) => place.status === "cast");
const free = Math.max(0, Math.min(team.people.length - cast.filter((place) => team.people.includes(place.reviewer)).length, readersFor(rule.each, Infinity) - cast.length));
- // More places than the rule asks for: the ones dealt last go.
+ // More places than the rule asks for: the ones dealt last go. Of those that stay, the closed ones open again: a place is either.
gone.push(...open.filter((place) => !team.people.includes(place.reviewer)), ...kept.slice(free));
+ reopened.push(...kept.slice(0, free).filter((place) => place.status === "closed"));
+ // A model's place closed when a person's vote settled the paper first (below) is open again with it.
+ reopened.push(...list.filter((place) => place.kind === "model" && place.status === "closed" && team.models.includes(place.reviewer)));
const holding = persons.filter((place) => !gone.includes(place)).map((place) => place.reviewer);
made.push(...fillPlaces(team.people.map((id) => ({ id })), holding, paper.away, free - Math.min(kept.length, free), paper.place).map(({ id }) => ({ reviewer: id, kind: "person" as const, status: "waiting" as const })));
if (models) made.push(...team.models.filter((id) => !list.some((place) => place.reviewer === id && place.status !== "discarded")).map((id) => ({ reviewer: id, kind: "model" as const, status: "waiting" as const })));
diff --git a/lib/screening/rules.test.ts b/lib/screening/rules.test.ts
index b02d1f4af..b670eaa4f 100644
--- a/lib/screening/rules.test.ts
+++ b/lib/screening/rules.test.ts
@@ -1,6 +1,6 @@
// A screening's rules (plans/screening-reviewers): each setting against each state of a paper's votes.
import { describe, expect, it } from "vitest";
-import { cellOf, decide, emptyMatrix, fillPlaces, kappa, reasonOf, scoreOf, seesVotes, settle, takesOver, twinsNamed, type Ballot, type Decision } from "./rules";
+import { cellOf, decide, decidingVotes, emptyMatrix, fillPlaces, kappa, reasonOf, scoreOf, seesVotes, settle, takesOver, twinsNamed, type Ballot, type Decision } from "./rules";
import { project } from "./project";
const cast = (decision: Decision, at = 1, reason?: string): Ballot => ({ status: "cast", decision, at, ...(reason ? { reason } : {}) });
@@ -79,6 +79,14 @@ describe("the reason an excluded paper is counted under", () => {
expect(reasonOf(ballots, "other")).toBe("other");
expect(reasonOf([cast("include")])).toBeUndefined();
});
+
+ it("under the first vote decides, is the reason of the person's vote that settled it, not an earlier model's", () => {
+ const model: Ballot = { status: "cast", decision: "exclude", reason: "c1", at: 1, kind: "model" };
+ const person: Ballot = { status: "cast", decision: "exclude", reason: "other", at: 2, kind: "person" };
+ const deciding = decidingVotes("one", [model, person]).votes;
+ expect(deciding).toEqual([person]);
+ expect(reasonOf(deciding)).toBe("other");
+ });
});
describe("points and stars", () => {
diff --git a/lib/screening/rules.ts b/lib/screening/rules.ts
index bd2fe2b1b..ff8b484d9 100644
--- a/lib/screening/rules.ts
+++ b/lib/screening/rules.ts
@@ -91,18 +91,26 @@ export const givenReason = (criteria: Pick[], answers
export type Ballot = { status: "waiting" | "cast" | "failed" | "closed" | "discarded"; decision?: Decision; at?: number; reason?: string; answers?: Record; /** Whose place it is: under "first vote decides" a person given the paper decides it, not a model. */ kind?: "person" | "model" };
/** Where a paper stands on its votes, under the rule. A person who settled it outranks this, and so does a result held through a change of settings. */
-export function settle(rule: Rule["settle"], ballots: Ballot[], models: Rule["models"] = "vote"): Result {
+/**
+ * The votes a paper's result is decided on, which give its reason too: every vote counted, the people's alone where the
+ * models advise and a person has the paper. Under "first vote decides", the earliest of them: where a person is given
+ * the paper it is the first person's, since a model reads faster than anyone and its vote would settle every paper
+ * before its people got to one. A model's vote decides only a paper no person has. `whole`: whether every place has voted.
+ */
+export function decidingVotes(rule: Rule["settle"], ballots: Ballot[], models: Rule["models"] = "vote"): { votes: Array; whole: boolean } {
const held = ballots.filter((one) => one.status === "waiting" || one.status === "cast" || one.status === "closed");
- // With the models' votes as advice, a paper a person has is settled on its people's votes alone.
const cast = models === "advice" && held.some((one) => one.kind === "person") ? held.filter((one) => one.kind === "person") : held;
const given = cast.filter((one): one is Ballot & { decision: Decision } => one.status === "cast" && one.decision !== undefined);
+ if (rule !== "one") return { votes: given, whole: given.length === cast.length };
+ const first = (cast.some((one) => one.kind === "person") ? given.filter((one) => one.kind === "person") : given).reduce<(Ballot & { decision: Decision }) | undefined>((earliest, vote) => (!earliest || (vote.at ?? 0) < (earliest.at ?? 0) ? vote : earliest), undefined);
+ return { votes: first ? [first] : [], whole: true };
+}
+
+export function settle(rule: Rule["settle"], ballots: Ballot[], models: Rule["models"] = "vote"): Result {
+ const { votes: given, whole } = decidingVotes(rule, ballots, models);
if (!given.length) return "waiting";
- // The first vote is the earliest one cast. Where a person is given the paper it is the first person's: a model reads faster than anyone, and its vote would settle every paper before its people got to one. A model's vote decides only a paper no person has.
- if (rule === "one") {
- const deciding = cast.some((one) => one.kind === "person") ? given.filter((one) => one.kind === "person") : given;
- return deciding.length ? deciding.reduce((first, vote) => ((vote.at ?? 0) < (first.at ?? 0) ? vote : first)).decision : "waiting";
- }
- if (given.length < cast.length) return "waiting";
+ if (rule === "one") return given[0]!.decision;
+ if (!whole) return "waiting";
const tally = DECISIONS.map((decision) => given.filter((vote) => vote.decision === decision).length);
const top = Math.max(...tally);
if (rule === "all") return top === given.length ? given[0]!.decision : "conflict";
diff --git a/messages/af.json b/messages/af.json
index 8663f50bb..b895b2eaf 100644
--- a/messages/af.json
+++ b/messages/af.json
@@ -8863,7 +8863,6 @@
"title": "Beoordelaars",
"everyoneDone": "Almal klaar oor omtrent {weeks, plural, =0 {{days, plural, =1 {’n dag} other {# dae}}} one {# week} other {# weke}}, teen hierdie tempo",
"move": "Skuif artikels",
- "agreement": "Ooreenstemming",
"helpTitle": "Hoe artikels verdeel word",
"eachOf": "{each, plural, one {# van die {people, plural, other {# mense}} stem} other {# van die {people, plural, other {# mense}} stem}} op elke artikel",
"everyPerson": "Elke persoon stem op elke artikel",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/ar.json b/messages/ar.json
index 920dd4d5d..0e147a917 100644
--- a/messages/ar.json
+++ b/messages/ar.json
@@ -8863,7 +8863,6 @@
"title": "المراجعون",
"everyoneDone": "ينتهي الجميع في نحو {weeks, plural, =0 {{days, plural, =1 {يوم واحد} zero {# يوم} one {يوم واحد} two {يومين} few {# أيام} many {# يومًا} other {# يوم}}} zero {# أسبوع} one {أسبوع واحد} two {أسبوعين} few {# أسابيع} many {# أسبوعًا} other {# أسبوع}}، بهذه الوتيرة",
"move": "نقل الأوراق",
- "agreement": "الاتفاق",
"helpTitle": "كيف تُوزَّع الأوراق",
"eachOf": "{each, plural, zero {يصوّت # من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}} one {يصوّت واحد من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}} two {يصوّت اثنان من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}} few {يصوّت # من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}} many {يصوّت # من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}} other {يصوّت # من أصل {people, plural, zero {# شخص} one {شخص واحد} two {شخصين} few {# أشخاص} many {# شخصًا} other {# شخص}}}} على كل ورقة",
"everyPerson": "يصوّت كل شخص على كل ورقة",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/de.json b/messages/de.json
index ba9e220ce..5a82a4d29 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -8863,7 +8863,6 @@
"title": "Reviewer",
"everyoneDone": "Alle fertig in etwa {weeks, plural, =0 {{days, plural, =1 {einem Tag} other {# Tagen}}} one {# Woche} other {# Wochen}}, bei diesem Tempo",
"move": "Artikel verschieben",
- "agreement": "Übereinstimmung",
"helpTitle": "Wie Artikel verteilt werden",
"eachOf": "{each, plural, one {# der {people, plural, other {# Personen}} stimmt} other {# der {people, plural, other {# Personen}} stimmen}} über jeden Artikel ab",
"everyPerson": "Jede Person stimmt über jeden Artikel ab",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/en-GB.json b/messages/en-GB.json
index 126c60422..9d3e9ce4a 100644
--- a/messages/en-GB.json
+++ b/messages/en-GB.json
@@ -8862,7 +8862,6 @@
"title": "Reviewers",
"everyoneDone": "Everyone done in about {weeks, plural, =0 {{days, plural, =1 {a day} other {# days}}} one {# week} other {# weeks}}, at this pace",
"move": "Move papers",
- "agreement": "Agreement",
"helpTitle": "How papers are shared out",
"eachOf": "{each, plural, one {# of the {people, plural, other {# people}} votes} other {# of the {people, plural, other {# people}} vote}} on each paper",
"everyPerson": "Every person votes on every paper",
@@ -9416,7 +9415,7 @@
},
"bar": {
"notInList": "Not in this list now",
- "atOf": "{at, number} of {count, number}",
+ "atOf": "{at, number} of {count, number}",
"left": "{count, plural, other {# left}}",
"underMinute": "under a minute",
"minutes": "about {minutes, number} min",
@@ -9484,7 +9483,7 @@
},
"matrix": {
"earlierWording": "Some answers here were given to an earlier wording of this criterion",
- "nameYou": "{name}, you",
+ "nameYou": "{name}, you",
"theirVote": "{name}'s vote",
"on": "{name}, {criterion}",
"differFor": "Show the answer that differs on {criterion}",
@@ -9588,8 +9587,8 @@
},
"zotero": {
"gone": "This collection is no longer in Zotero",
- "openAbove": "Open {name}",
- "myLibrary": "My library",
+ "openAbove": "Open {name}",
+ "myLibrary": "My library",
"loading": "Loading Zotero",
"loadingCollections": "Loading the collections",
"notConnected": "Zotero isn't connected",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/en-US.json b/messages/en-US.json
index cb7c9328d..624d5d395 100644
--- a/messages/en-US.json
+++ b/messages/en-US.json
@@ -8862,7 +8862,6 @@
"title": "Reviewers",
"everyoneDone": "Everyone done in about {weeks, plural, =0 {{days, plural, =1 {a day} other {# days}}} one {# week} other {# weeks}}, at this pace",
"move": "Move papers",
- "agreement": "Agreement",
"helpTitle": "How papers are shared out",
"eachOf": "{each, plural, one {# of the {people, plural, other {# people}} votes} other {# of the {people, plural, other {# people}} vote}} on each paper",
"everyPerson": "Every person votes on every paper",
@@ -9416,7 +9415,7 @@
},
"bar": {
"notInList": "Not in this list now",
- "atOf": "{at, number} of {count, number}",
+ "atOf": "{at, number} of {count, number}",
"left": "{count, plural, other {# left}}",
"underMinute": "under a minute",
"minutes": "about {minutes, number} min",
@@ -9484,7 +9483,7 @@
},
"matrix": {
"earlierWording": "Some answers here were given to an earlier wording of this criterion",
- "nameYou": "{name}, you",
+ "nameYou": "{name}, you",
"theirVote": "{name}'s vote",
"on": "{name}, {criterion}",
"differFor": "Show the answer that differs on {criterion}",
@@ -9588,8 +9587,8 @@
},
"zotero": {
"gone": "This collection is no longer in Zotero",
- "openAbove": "Open {name}",
- "myLibrary": "My library",
+ "openAbove": "Open {name}",
+ "myLibrary": "My library",
"loading": "Loading Zotero",
"loadingCollections": "Loading the collections",
"notConnected": "Zotero isn't connected",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/es.json b/messages/es.json
index aa461fd9e..c947ce5a2 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -8863,7 +8863,6 @@
"title": "Revisores",
"everyoneDone": "Todos terminan en {weeks, plural, =0 {{days, plural, =1 {un día} other {unos # días}}} one {una semana} other {unas # semanas}}, a este ritmo",
"move": "Mover artículos",
- "agreement": "Acuerdo",
"helpTitle": "Cómo se reparten los artículos",
"eachOf": "{each, plural, one {# de las {people, plural, one {# persona} other {# personas}} vota} other {# de las {people, plural, one {# persona} other {# personas}} votan}} cada artículo",
"everyPerson": "Cada persona vota todos los artículos",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/fr.json b/messages/fr.json
index 9d34fb2f0..1cab946da 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -8862,7 +8862,6 @@
"title": "Évaluateurs",
"everyoneDone": "Tout le monde aura fini dans environ {weeks, plural, =0 {{days, plural, =1 {un jour} other {# jours}}} one {# semaine} other {# semaines}}, à ce rythme",
"move": "Déplacer des articles",
- "agreement": "Accord",
"helpTitle": "Comment les articles sont répartis",
"eachOf": "{each, plural, one {# des {people, plural, other {# personnes}} vote} other {# des {people, plural, other {# personnes}} votent}} sur chaque article",
"everyPerson": "Chaque personne vote sur chaque article",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/hi.json b/messages/hi.json
index 29d945cf8..b31ac3108 100644
--- a/messages/hi.json
+++ b/messages/hi.json
@@ -8862,7 +8862,6 @@
"title": "समीक्षक",
"everyoneDone": "इसी गति से सभी लगभग {weeks, plural, =0 {{days, plural, =1 {एक दिन} other {# दिन}}} one {# सप्ताह} other {# सप्ताह}} में पूरा कर लेंगे",
"move": "लेख सौंपें",
- "agreement": "सहमति",
"helpTitle": "लेख कैसे बाँटे जाते हैं",
"eachOf": "{each, plural, one {{people, plural, other {# लोगों}} में से # हर लेख पर वोट देता है} other {{people, plural, other {# लोगों}} में से # हर लेख पर वोट देते हैं}}",
"everyPerson": "हर व्यक्ति हर लेख पर वोट देता है",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/ja.json b/messages/ja.json
index bc5fdc93d..b1e250313 100644
--- a/messages/ja.json
+++ b/messages/ja.json
@@ -8862,7 +8862,6 @@
"title": "レビュアー",
"everyoneDone": "このペースなら全員が約 {weeks, plural, =0 {{days, plural, other {# 日}}} other {# 週間}}で終わります",
"move": "論文を移す",
- "agreement": "一致度",
"helpTitle": "論文の割り当て方",
"eachOf": "各論文に{each, plural, other {{people, plural, other {# 人}}中 # 人}}が投票します",
"everyPerson": "全員がすべての論文に投票します",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/pt.json b/messages/pt.json
index e7afabc82..f61a52431 100644
--- a/messages/pt.json
+++ b/messages/pt.json
@@ -8863,7 +8863,6 @@
"title": "Revisores",
"everyoneDone": "Todos terminam dentro de cerca de {weeks, plural, =0 {{days, plural, =1 {um dia} other {# dias}}} one {# semana} other {# semanas}}, a este ritmo",
"move": "Mover artigos",
- "agreement": "Concordância",
"helpTitle": "Como os artigos são distribuídos",
"eachOf": "{each, plural, one {# das {people, plural, other {# pessoas}} vota} other {# das {people, plural, other {# pessoas}} votam}} em cada artigo",
"everyPerson": "Cada pessoa vota em todos os artigos",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/sw.json b/messages/sw.json
index 85cb0afae..042284393 100644
--- a/messages/sw.json
+++ b/messages/sw.json
@@ -8863,7 +8863,6 @@
"title": "Wakaguzi",
"everyoneDone": "Wote watamaliza baada ya takriban {weeks, plural, =0 {{days, plural, =1 {siku moja} other {siku #}}} one {wiki #} other {wiki #}}, kwa kasi hii",
"move": "Hamisha makala",
- "agreement": "Makubaliano",
"helpTitle": "Jinsi makala zinavyogawanywa",
"eachOf": "{each, plural, one {# kati ya {people, plural, other {watu #}} anapigia} other {# kati ya {people, plural, other {watu #}} wanapigia}} kura kila makala",
"everyPerson": "Kila mtu anapigia kura kila makala",
@@ -9778,4 +9777,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/zh.json b/messages/zh.json
index efcc68295..3f8636429 100644
--- a/messages/zh.json
+++ b/messages/zh.json
@@ -8862,7 +8862,6 @@
"title": "审核人",
"everyoneDone": "按目前的速度,大约 {weeks, plural, =0 {{days, plural, =1 {一天} other {# 天}}} other {# 周}}后全部完成",
"move": "转移论文",
- "agreement": "一致性",
"helpTitle": "论文如何分配",
"eachOf": "{each, plural, other {{people, plural, other {# 人}}中有 # 人}}对每篇论文投票",
"everyPerson": "每个人对每篇论文投票",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/messages/zu.json b/messages/zu.json
index 9ae5319fa..6decca7bf 100644
--- a/messages/zu.json
+++ b/messages/zu.json
@@ -8862,7 +8862,6 @@
"title": "Ababuyekezi",
"everyoneDone": "Bonke bazoqeda cishe {weeks, plural, =0 {{days, plural, =1 {ngosuku olulodwa} other {ezinsukwini ezingu-#}}} one {evikini elilodwa} other {emavikini angu-#}}, ngalesi sivinini",
"move": "Hambisa amaphepha",
- "agreement": "Ukuvumelana",
"helpTitle": "Indlela amaphepha ahlukaniswa ngayo",
"eachOf": "{each, plural, one {# {people, plural, other {kubantu abangu-#}} uvota} other {# {people, plural, other {kubantu abangu-#}} bavota}} ephepheni ngalinye",
"everyPerson": "Wonke umuntu uvota kuwo wonke amaphepha",
@@ -9777,4 +9776,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/scripts/convex-rules.json b/scripts/convex-rules.json
index d025f06c3..e9335bd85 100644
--- a/scripts/convex-rules.json
+++ b/scripts/convex-rules.json
@@ -116,7 +116,6 @@
"MINE_MAX": "the screenings one person reviews or is given, newest first, looked through for the ones that wait for them; the workspace's own list pages through every one",
"CHECKS_LOOKED": "a screening's latest checks of its sources, looked through for the last one that brought papers; its checks are listed a page at a time",
"FLAGGED_COUNTED": "a reviewer's votes cast before a criterion became a must-have, counted for their tab; their queue pages through every one",
- "LATEST_COUNTED": "the papers a screening's last check brought, counted for the ones still open; its Papers page lists every one",
"SAME_TITLE": "papers of one title and year in a screening, looked at for the one a new record is; versions of a paper share them and seldom more than a few do",
"MOVE_LOOKED": "the far end of one person's queue, looked through for papers another person isn't on; a second move goes on from there",
"ANSWERED": "the open questions to one person on one paper, all closed by their reply",
@@ -124,7 +123,9 @@
"PAIRS_MAX": "the pairs of reviewers a screening's overview draws agreement for; a screening with more reviewers than that many pairs shows the first",
"CHECKS_COUNTED": "a screening's checks for new papers counted for its methods paragraph: the first of them",
"CHANGES_COUNTED": "a screening's latest activity, looked through for how often its settings were changed",
- "CHECK_COUNTED": "the papers one check added, looked at for where they stand; a check that added more shows no such count",
+ "NEW_COUNTED": "the new papers of a screening's last check still waiting for one reviewer, counted for their banner and their email; past it they say so many and more",
+ "CONFLICTS_COUNTED": "a screening's papers in conflict, counted for whoever settles them on the rail and the lists; past it the count says so many",
+ "AUDIT_ROWS": "one screening's papers, votes and cards, read whole by its audit (screening/audit.ts), run by hand and by the rules test; a screening holds 5,000 papers at most",
"READING_LOOKED": "The rail looks at a workspace's newest open screenings for one whose models are reading: the first few, since the ring shows one."
},
"batches": {
From 74b8ff1bdf4dfd3e55f17af9d1e494056b2035ba Mon Sep 17 00:00:00 2001
From: sickerine
Date: Sat, 28 Nov 2026 14:09:41 +0000
Subject: [PATCH 2/3] fix(screening): what the cross-family review of round 1
found
- Answers given to a cast vote keep its cast time, which "first vote decides"
reads, and an Undo changed since in another tab leaves the counts it moved.
- Counts narrowed by a reviewer and a source match their votes to cards read
in one range, inside a transaction's index ranges on a 5,000-paper screening.
- A reading stopped by a full screening keeps the source's last figures. Once a
removed source's papers have left, sources stopped at the cap read again to
fill the room, a source added in the same save among them.
- Papers brought back by a check reopen a finished screening.
- A model's exclusion reason follows its answers, as its decision does.
- The audit compares the kept reason counts with the papers, and the rules test
settles a paper everyone excludes.
- Papers keeps the votes and the settler's note beside a hand-settled reason.
- The last hand-kept copy of included papers by source goes.
- Other fixes from round 1 walkers: a whole source asked for as a range reads
nothing again, criterion keys are listed only where answers can be given,
and a model's row in Settings starts on one line with its mark.
---
components/screening/papers.tsx | 8 +++++--
components/screening/screen.tsx | 5 ++--
components/screening/screening-form.tsx | 5 ++--
convex/schema.ts | 2 ++
convex/screening/audit.ts | 10 ++++----
convex/screening/changes.test.ts | 6 +++--
convex/screening/gathering.ts | 6 +++--
convex/screening/living.ts | 2 +-
convex/screening/paperViews.ts | 8 ++++---
convex/screening/screenings.ts | 6 ++++-
convex/screening/settings.ts | 32 ++++++++++++++-----------
convex/screening/settling.ts | 7 +++---
convex/screening/voting.ts | 15 +++++++-----
13 files changed, 70 insertions(+), 42 deletions(-)
diff --git a/components/screening/papers.tsx b/components/screening/papers.tsx
index 5a84e167d..a0837edf1 100644
--- a/components/screening/papers.tsx
+++ b/components/screening/papers.tsx
@@ -970,14 +970,18 @@ function Why({ paper, open, reasonKey }: { paper: Paper; open: Open; reasonKey?:
// What whoever settled it wrote down, beside the votes they settled: the reason a settled paper has.
const settledNote = state.resolvedBy && state.note ? {words.quoted(state.note)} : null;
if (!visible) return settledNote;
- // A paper excluded by hand gives the reason it was excluded for, as one its votes excluded does: the settler's.
if (state.result === "conflict" || (state.resolvedBy && !(state.result === "exclude" && reasonKey))) return {settledNote};
+ // A paper excluded by hand gives the reason the settler gave, beside the votes they settled and what they wrote.
+ if (state.resolvedBy && reasonKey) {
+ const link = narrow({ result: "exclude", reason: reasonKey }, ["reason"]);
+ return {settledNote};
+ }
if (reasonKey && (state.result === "exclude" || state.result === "maybe")) {
const label = state.result === "exclude" ? words.failed(reasonKey, reasonCriteria(open.screening)) : words.unclear(reasonKey, reasonCriteria(open.screening));
// Pressed again while the table is narrowed to this reason, it takes the reason away and keeps the result.
const link = narrow({ result: state.result, reason: reasonKey }, ["reason"]);
// Another reason is what its voter wrote: it stands beside the reason, as a settled paper's note does.
- const written = reasonKey === OTHER_REASON ? (state.resolvedBy ? state.note : cast.find((vote) => vote.reason === OTHER_REASON && vote.note)?.note) : undefined;
+ const written = reasonKey === OTHER_REASON ? cast.find((vote) => vote.reason === OTHER_REASON && vote.note)?.note : undefined;
if (written) return {words.quoted(written)};
return (
diff --git a/components/screening/screen.tsx b/components/screening/screen.tsx
index e534ee992..ba32787b3 100644
--- a/components/screening/screen.tsx
+++ b/components/screening/screen.tsx
@@ -64,7 +64,7 @@ const QUEUE_PAGE = 12;
const QUEUE_TONE: Record = { todo: "primary", again: "warning", done: "neutral", conflicts: "info" };
const KEYS: Record = { include: "I", maybe: "M", exclude: "E" };
/** The keys, each with who it is for: a vote's are for whoever may vote here, an answer's for whoever answers the criteria. */
-const SHORTCUTS: Array<[string[], "select" | "answer" | "include" | "maybe" | "exclude" | "next" | "previous" | "undo" | "queue" | "keys", ("vote" | "answer")?]> = [[["1…9"], "select"], [["Y", "N", "U"], "answer", "answer"], [["I"], "include", "vote"], [["M"], "maybe", "vote"], [["E"], "exclude", "vote"], [["S", "J", "→"], "next"], [["K", "←"], "previous"], [["Z"], "undo", "vote"], [["Q"], "queue"], [["?"], "keys"]];
+const SHORTCUTS: Array<[string[], "select" | "answer" | "include" | "maybe" | "exclude" | "next" | "previous" | "undo" | "queue" | "keys", ("vote" | "answer")?]> = [[["1…9"], "select", "answer"], [["Y", "N", "U"], "answer", "answer"], [["I"], "include", "vote"], [["M"], "maybe", "vote"], [["E"], "exclude", "vote"], [["S", "J", "→"], "next"], [["K", "←"], "previous"], [["Z"], "undo", "vote"], [["Q"], "queue"], [["?"], "keys"]];
/** The queue's sheet is open: the one value its key in the address takes. */
const LIST_OPEN = ["open"] as const;
const WHY_OPEN = ["reasons"] as const;
@@ -458,7 +458,8 @@ function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes,
// A save the server refused was never made: there is nothing to take back.
if (last.saved === undefined) return;
if (last.resolved) return open.resolve(last.paper.id, last.settledBefore ? (last.settledBefore.final ?? null) : null, last.settledBefore?.note, last.settledBefore?.reason, last.saved).then(restamp, failed);
- return open.vote(last.paper.id, last.before ? ballotOf(last.before) : null, { onlyAt: last.saved }).then(restamp, failed);
+ // Changed since in another tab, the vote stands: the counts it moved here stand with it.
+ return open.vote(last.paper.id, last.before ? ballotOf(last.before) : null, { onlyAt: last.saved }).then((at) => { if (at === null) for (const [kind, by] of movesOf(last)) moved(kind, by); restamp(last.before ? at : null); }, failed);
});
// Undo pressed again at once waits for this one, so it names the moment this one stamps.
if (earlier) earlier.pending = Promise.all([earlier.pending, undoing]);
diff --git a/components/screening/screening-form.tsx b/components/screening/screening-form.tsx
index dbfe9e6f7..5dbff3e40 100644
--- a/components/screening/screening-form.tsx
+++ b/components/screening/screening-form.tsx
@@ -1937,8 +1937,9 @@ function ReviewerRow({ reviewer, you, detail, chips, href, gone, onRemove, onKee
const name = ;
return (
-
-
+ {/* Mark, name and chips start on one line: where the chips run onto more lines, the name stays beside the mark, never centred below it. */}
+
+
{/* The name keeps its room: where the chips beside it are many, they run onto a second line among themselves. */}
{href && !gone ? {name} : name}
diff --git a/convex/schema.ts b/convex/schema.ts
index ca85276a6..19894c71e 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -1824,6 +1824,8 @@ export default defineSchema({
from: v.number(),
found: v.number(),
added: v.number(),
+ // Papers taken out with a source that it brought back: in the screening again, in the places they had.
+ restored: v.optional(v.number()),
// Of what it found, the records left out (no abstract, nothing to read): neither added nor already in the screening.
left: v.optional(v.number()),
// The sources it couldn't read (each failed, with why, on its own row): a check that read none of them found nothing it can vouch for.
diff --git a/convex/screening/audit.ts b/convex/screening/audit.ts
index 8df01e36f..86ee9b856 100644
--- a/convex/screening/audit.ts
+++ b/convex/screening/audit.ts
@@ -9,8 +9,8 @@
import { v } from "convex/values";
import type { Id } from "../_generated/dataModel";
import { internalQuery, type QueryCtx } from "../_generated/server";
-import { isFinal, settle, type Ballot, type Result } from "../../lib/screening/rules";
-import { tallyOfReviewer, tallyUnder, type Tally } from "./facets";
+import { isFinal, NAMED_REASONS, NO_REASON, settle, type Ballot, type Result } from "../../lib/screening/rules";
+import { excludedFor, tallyOfReviewer, tallyUnder, type Tally } from "./facets";
const DECISIONS = ["include", "maybe", "exclude"] as const;
/** Rows of one kind an audit reads: a screening's papers, votes or cards, which a screening of 5,000 papers stays well within. */
@@ -38,8 +38,6 @@ export async function auditJob(ctx: QueryCtx, jobId: Id<"screeningJobs">) {
const counts = { include: 0, maybe: 0, exclude: 0, conflict: 0 };
for (const paper of live) if (paper.result && paper.result !== "waiting") counts[paper.result]++;
if (JSON.stringify(counts) !== JSON.stringify({ include: 0, maybe: 0, exclude: 0, conflict: 0, ...progress.counts })) problems.push(`counts say ${JSON.stringify(progress.counts)}, the papers ${JSON.stringify(counts)}`);
- const reasons = Object.values(progress.reasons ?? {}).reduce((sum, n) => sum + n, 0);
- if (reasons !== counts.exclude) problems.push(`${reasons} reasons for ${counts.exclude} excluded papers`);
// Each paper's card, which the Papers page lists and narrows by, says what the paper says.
const cardOf = new Map(cards.map((card) => [card.resultId, card]));
@@ -108,6 +106,10 @@ export async function auditJob(ctx: QueryCtx, jobId: Id<"screeningJobs">) {
for (const [key, counted] of matrices) if (counted.some((n) => n > 0)) problems.push(`a pair's agreement isn't kept: ${key}`);
// The counts Papers narrows by (./facets.ts), against the cards and votes: a moment behind the writes, so read once they settle.
+ const byReason = new Map();
+ for (const paper of live) if (paper.result === "exclude") byReason.set(paper.reason ?? NO_REASON, (byReason.get(paper.reason ?? NO_REASON) ?? 0) + 1);
+ const keptReasons = await excludedFor(ctx, jobId, [...new Set([...byReason.keys(), ...(job.criteria ?? []).map((one) => one.key), ...NAMED_REASONS])]);
+ for (const key of new Set([...byReason.keys(), ...Object.keys(keptReasons)])) if ((byReason.get(key) ?? 0) !== (keptReasons[key] ?? 0)) problems.push(`reason ${key}: counted ${keptReasons[key] ?? 0} excluded, the papers ${byReason.get(key) ?? 0}`);
const tally = (results: Result[]): Tally => ({ include: 0, maybe: 0, exclude: 0, conflict: 0, waiting: 0, ...Object.fromEntries((["include", "maybe", "exclude", "conflict", "waiting"] as const).map((result) => [result, results.filter((one) => one === result).length])) });
const liveCards = cards.filter((card) => !card.withdrawn);
for (const sourceId of new Set(liveCards.flatMap((card) => (card.sourceId ? [card.sourceId] : [])))) {
diff --git a/convex/screening/changes.test.ts b/convex/screening/changes.test.ts
index 5eb344f81..075b51c51 100644
--- a/convex/screening/changes.test.ts
+++ b/convex/screening/changes.test.ts
@@ -21,7 +21,7 @@ const run = (t: T) => runAll(t, vi.runAllTimers);
const audit = (t: T, jobId: Id<"screeningJobs">) => t.run((ctx) => auditJob(ctx, jobId));
-/** Votes on a screening's papers in a fixed pattern: every holder includes one, the first two split on the next, and one alone votes Maybe on the third. */
+/** Votes on a screening's papers in a fixed pattern: every holder includes one, the first two split on the next, and one alone votes Maybe on the third; every holder excludes the last. */
async function voteAround({ t, as, workspaceId }: Team, jobId: Id<"screeningJobs">) {
const { papers, holders } = await t.run(async (ctx) => {
const papers = await ctx.db.query("screeningResults").withIndex("by_job", (q) => q.eq("jobId", jobId)).collect();
@@ -33,7 +33,9 @@ async function voteAround({ t, as, workspaceId }: Team, jobId: Id<"screeningJobs
const vote = (name: string, paperId: Id<"screeningResults">, decision: (typeof DECISIONS)[number]) => as[name]!.mutation(api.screening.voting.vote, { workspaceId, jobId, paperId, decision, ...(decision === "exclude" ? { reason: "other" } : {}) });
for (const [i, paperId] of papers.entries()) {
const on = holders[paperId] ?? [];
- if (i % 3 === 0) for (const name of on) await vote(name, paperId, "include");
+ // The last paper everyone excludes, so the reasons it is counted under are audited too.
+ if (i === papers.length - 1) for (const name of on) await vote(name, paperId, "exclude");
+ else if (i % 3 === 0) for (const name of on) await vote(name, paperId, "include");
else if (i % 3 === 1) for (const [k, name] of on.slice(0, 2).entries()) await vote(name, paperId, k ? "exclude" : "include");
else if (on[0]) await vote(on[0], paperId, "maybe");
// Each vote is settled before the next is cast, as it is when people vote: under "the first vote decides", a second vote on a settled paper is refused.
diff --git a/convex/screening/gathering.ts b/convex/screening/gathering.ts
index 6f7e8293a..23fcdb548 100644
--- a/convex/screening/gathering.ts
+++ b/convex/screening/gathering.ts
@@ -476,9 +476,11 @@ export const fill = internalMutation({
if (back) await bookkeepLater(ctx);
// A first reading counts as it goes. One read again counts beside the figures it has, and takes their place once it is whole.
const next = source.next && { ...source.next, duplicates: source.next.duplicates + duplicates, left: source.next.left + left, bare: source.next.bare + bare };
- const counted = !next ? { duplicates: source.duplicates + duplicates, left: source.left + left, ...(bare ? { bare: (source.bare ?? 0) + bare } : {}) } : ended || capped ? { duplicates: next.duplicates, left: next.left, bare: next.bare, next: undefined } : { next };
+ // A reading stopped by a full screening before it gave anything keeps the figures of the last whole reading: it read nothing that would replace them.
+ const counted = full ? { next: undefined } : !next ? { duplicates: source.duplicates + duplicates, left: source.left + left, ...(bare ? { bare: (source.bare ?? 0) + bare } : {}) } : ended || capped ? { duplicates: next.duplicates, left: next.left, bare: next.bare, next: undefined } : { next };
await ctx.db.patch("screeningSources", sourceId, { read: source.read + read, resume, taken: source.taken + taken + back, ...counted, ...(filed ? { filed: (source.filed ?? 0) + filed, filePages: (source.filePages ?? 0) + filePages, fileSpread } : {}), ...(ended || capped ? { state: "done" as const, checkedAt: now } : {}), ...(capped ? { capped: true as const } : {}) });
- await ctx.db.patch("screeningChecks", checkId, { found: check.found + papers.length + (leftOut?.length ?? 0), added: check.added + taken, ...(left ? { left: (check.left ?? 0) + left } : {}), beat: now, ...(taken ? { bySource: { ...check.bySource, [sourceId]: (check.bySource?.[sourceId] ?? 0) + taken } } : {}), ...((ended || capped) && check.unread?.includes(sourceId) ? { unread: check.unread.filter((one) => one !== sourceId) } : {}) });
+ // Papers brought back with this source are counted apart from the new ones, which take new places: a finished screening they wait in opens again all the same (./living.ts `checked`).
+ await ctx.db.patch("screeningChecks", checkId, { found: check.found + papers.length + (leftOut?.length ?? 0), added: check.added + taken, ...(back ? { restored: (check.restored ?? 0) + back } : {}), ...(left ? { left: (check.left ?? 0) + left } : {}), beat: now, ...(taken ? { bySource: { ...check.bySource, [sourceId]: (check.bySource?.[sourceId] ?? 0) + taken } } : {}), ...((ended || capped) && check.unread?.includes(sourceId) ? { unread: check.unread.filter((one) => one !== sourceId) } : {}) });
await countDealt(ctx, dealt);
if (taken && reviewers.some((one) => one.kind === "model" && one.left === undefined)) await startWaitingVotes(ctx, job.workspaceId);
return null;
diff --git a/convex/screening/living.ts b/convex/screening/living.ts
index 1f1498dff..e3723f286 100644
--- a/convex/screening/living.ts
+++ b/convex/screening/living.ts
@@ -141,7 +141,7 @@ export async function checked(ctx: MutationCtx, job: Doc<"screeningJobs">, check
if ((await firstCheck(ctx, job._id))?._id === check._id) return;
const now = Date.now();
// Only a check asked for once it was finished reopens it: one already under way when it was marked finished doesn't undo that.
- const reopens = Boolean(check.added) && job.finishedAt !== undefined && check.at >= job.finishedAt;
+ const reopens = Boolean(check.added || check.restored) && job.finishedAt !== undefined && check.at >= job.finishedAt;
if (reopens) {
await ctx.db.patch("screeningJobs", job._id, { finishedAt: undefined, status: "processing", completedAt: undefined, ...touched(now) });
await placeGuests(ctx, job._id);
diff --git a/convex/screening/paperViews.ts b/convex/screening/paperViews.ts
index 0b1046cad..aee35f362 100644
--- a/convex/screening/paperViews.ts
+++ b/convex/screening/paperViews.ts
@@ -108,7 +108,6 @@ export function shown({ job, reviewer, reviewers, first, asked }: Looking, paper
const holdsAll = (paper: Paper, needle: string) => nameHas(paper.searchText ?? "", needle);
const views = (ctx: Pick, looking: Looking, papers: Paper[]) => Promise.all(papers.map(async (paper) => shown(looking, paper, await votesOf(ctx, paper._id))));
const NONE = { page: [], isDone: true, continueCursor: "" };
-const cardOf = (ctx: Pick, resultId: Id<"screeningResults">) => ctx.db.query("screeningCards").withIndex("by_result", (q) => q.eq("resultId", resultId)).unique();
/** A screening's cards narrowed the most telling way asked for, in the order their papers were added: the rest is asked of each card. */
const cardsOf = (ctx: Pick, jobId: Id<"screeningJobs">, { result, reason, check, source }: { result?: Doc<"screeningCards">["result"]; reason?: string; check?: Id<"screeningChecks">; source?: Id<"screeningSources"> }) => {
const cards = stream(ctx.db, schema).query("screeningCards");
@@ -235,8 +234,11 @@ export const counts = workspaceQuery({
: votes.withIndex("by_reviewer_and_status_and_at", (q) => q.eq("reviewerId", row._id).eq("status", "cast"))
).take(COUNTED + 1);
if (theirs.length > COUNTED) return null;
- // Each of their votes is matched to its paper's card.
- for (const card of await Promise.all(theirs.map((vote) => cardOf(ctx, vote.resultId)))) if (card && keeps(card)) tally[card.result]++;
+ // Their votes are matched to the cards of the other narrowing, read in one range: one read a vote would pass a transaction's index ranges on a large screening.
+ const cards = await cardsOf(ctx, jobId, { reason, check, source }).take(COUNTED + 1);
+ if (cards.length > COUNTED) return null;
+ const cardOn = new Map(cards.map((card) => [card.resultId, card]));
+ for (const vote of theirs) { const card = cardOn.get(vote.resultId); if (card && keeps(card)) tally[card.result]++; }
return tally;
},
});
diff --git a/convex/screening/screenings.ts b/convex/screening/screenings.ts
index 6c6d03a94..606c3a9cd 100644
--- a/convex/screening/screenings.ts
+++ b/convex/screening/screenings.ts
@@ -116,7 +116,11 @@ export { EVERY_MS };
/** Whether a source's row is the source the form holds: the same thing read, and the same papers of it. */
const stable = (value: unknown): string => (Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((key) => `${key}:${stable((value as Record)[key])}`).join(",")}}` : JSON.stringify(value) ?? "");
-const sameSource = (row: Doc<"screeningSources">, sent: Infer) => row.removedAt === undefined && stable(row.set) === stable(sent.set) && row.first === sent.first && row.last === sent.last;
+/** The same source asked for again: a range from its first paper to its last, or past it, is the whole of it, and reads nothing again. */
+const sameSource = (row: Doc<"screeningSources">, sent: Infer) => {
+ const end = (last: number | undefined) => (last === undefined || (row.total !== undefined && last >= row.total) ? Infinity : last);
+ return row.removedAt === undefined && stable(row.set) === stable(sent.set) && (row.first ?? 1) === (sent.first ?? 1) && end(row.last) === end(sent.last);
+};
/** A screening that isn't started yet, if it is this person's to go on with. */
async function draftOf(ctx: Pick, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, jobId: Id<"screeningJobs"> | undefined) {
diff --git a/convex/screening/settings.ts b/convex/screening/settings.ts
index fc41abd5e..5515627f6 100644
--- a/convex/screening/settings.ts
+++ b/convex/screening/settings.ts
@@ -24,7 +24,7 @@ import { check } from "./living";
import { logChange, type Line } from "./log";
import { addModel, addPerson, takeOff } from "./reviewers";
import { addSource, criteriaFrom, criterionInput, EVERY_MS, legacyOf, MAX_SOURCES, modelInput, NEEDS_CRITERIA, ruleFrom, ruleInput, sourceInput, starsFrom } from "./screenings";
-import { startWaitingVotes } from "./slots";
+import { papersLimit, startWaitingVotes } from "./slots";
import { everyValidator, libraryDestinationValidator, prunable, RETIRED_CRITERIA, saveToValidator, SCREENING_TEXT } from "./validators";
/** The criteria taken off by a save, kept by key and name with the ones taken off before: a criterion put back is no longer one of them. */
@@ -207,7 +207,7 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId
const source = sources.find((one) => one._id === sourceId && one.removedAt === undefined);
if (!source) continue;
await ctx.db.patch("screeningSources", sourceId, { removedAt: now });
- await ctx.scheduler.runAfter(0, internal.screening.settings.withdraw, { jobId, sourceId, cursor: null });
+ await ctx.scheduler.runAfter(0, internal.screening.settings.withdraw, { jobId, sourceId, cursor: null, by: actor.userId });
}
// A range that takes more of a source reads the source again: what it has stays, and the rest joins.
for (const range of change.ranges ?? []) {
@@ -286,9 +286,9 @@ export const follow = internalMutation({
/** Takes a removed source's papers out of the screening, a step at a time: each is stamped, and the worker takes it out of the counts and keeps its votes on record. */
export const withdraw = internalMutation({
- args: { jobId: v.id("screeningJobs"), sourceId: v.id("screeningSources"), cursor: v.union(v.string(), v.null()) },
+ args: { jobId: v.id("screeningJobs"), sourceId: v.id("screeningSources"), cursor: v.union(v.string(), v.null()), /** Who took the source out: the reading that fills the room it leaves is theirs. */ by: v.optional(v.id("users")) },
returns: v.null(),
- handler: async (ctx, { jobId, sourceId, cursor }) => {
+ handler: async (ctx, { jobId, sourceId, cursor, by }) => {
const page = await ctx.db.query("screeningResults").withIndex("by_job_and_source", (q) => q.eq("jobId", jobId).eq("sourceId", sourceId)).paginate({ cursor, numItems: FOLLOW });
const sources = await sourcesOf(ctx, jobId);
for (const paper of page.page) {
@@ -305,7 +305,6 @@ export const withdraw = internalMutation({
const spread = { ...keeper.fileSpread };
if (filed && paper.pages) spread[band] = { papers: (spread[band]?.papers ?? 0) + 1, pages: (spread[band]?.pages ?? 0) + paper.pages, most: Math.max(spread[band]?.most ?? 0, paper.pages) };
await ctx.db.patch("screeningSources", keeper._id, { taken: keeper.taken + 1, duplicates: Math.max(0, keeper.duplicates - 1), ...(filed ? { filed: (keeper.filed ?? 0) + 1, filePages: (keeper.filePages ?? 0) + (paper.pages ?? 0), fileSpread: spread } : {}) });
- if (paper.result === "include") await moveIncluded(ctx, jobId, sourceId, keeper._id);
await ctx.db.delete("screeningMerged", row._id);
continue;
}
@@ -314,19 +313,24 @@ export const withdraw = internalMutation({
for (const vote of await votesOf(ctx, paper._id)) if (vote.flagged) await ctx.db.patch("screeningVotes", vote._id, { flagged: undefined });
}
if (page.page.length) await bookkeepLater(ctx);
- if (!page.isDone) await ctx.scheduler.runAfter(0, internal.screening.settings.withdraw, { jobId, sourceId, cursor: page.continueCursor });
+ if (!page.isDone) await ctx.scheduler.runAfter(0, internal.screening.settings.withdraw, { jobId, sourceId, cursor: page.continueCursor, ...(by ? { by } : {}) });
+ else await refill(ctx, jobId, by);
return null;
},
});
-/** An included paper that moved from one source to another is counted under the one it moved to (the Overview's and the flow's included papers by source). */
-async function moveIncluded(ctx: MutationCtx, jobId: Id<"screeningJobs">, from: Id<"screeningSources">, to: Id<"screeningSources">) {
- const progress = await progressRow(ctx, jobId);
- if (!progress) return;
- const included = { ...progress.included };
- included[from] = Math.max(0, (included[from] ?? 1) - 1);
- included[to] = (included[to] ?? 0) + 1;
- await ctx.db.patch("screeningJobProgress", progress._id, { included });
+/**
+ * Once a source's papers have left, the room they leave under the plan's cap is filled: the sources that stopped at the
+ * cap are read again from their start, passing over the papers the screening holds, until it is full again. A source
+ * added in the same save that met the cap while the papers were still leaving is one of them.
+ */
+async function refill(ctx: MutationCtx, jobId: Id<"screeningJobs">, by: Id<"users"> | undefined) {
+ const job = await ctx.db.get("screeningJobs", jobId);
+ if (!job || job.finishedAt !== undefined) return;
+ const capped = (await sourcesOf(ctx, jobId)).filter((source) => source.capped && source.removedAt === undefined && source.state === "done");
+ if (!capped.length || job.totalPapers - ((await progressRow(ctx, jobId))?.withdrawn ?? 0) >= (await papersLimit(ctx, job.workspaceId))) return;
+ for (const source of capped) await ctx.db.patch("screeningSources", source._id, readAgain(source));
+ await startCheck(ctx, job, by);
}
/** Saves the papers a screening has included to the collection it was just sent to, a step at a time. */
diff --git a/convex/screening/settling.ts b/convex/screening/settling.ts
index 2faa9bb88..78447dfe2 100644
--- a/convex/screening/settling.ts
+++ b/convex/screening/settling.ts
@@ -182,14 +182,15 @@ export async function settlePapers(ctx: MutationCtx, made: Doc<"screeningJobs">,
// The slot is free once the reading has come back, whatever it left on the row: a reading that didn't go ahead leaves it waiting.
const finished = vote.slot && vote.workId === undefined;
if (finished) freed++;
- if (same(vote.counted, counted) && !finished && vote.decision === cast.decision) continue;
+ const decided = cast.status !== "cast" || (vote.decision === cast.decision && vote.reason === cast.reason);
+ if (same(vote.counted, counted) && !finished && decided) continue;
changed = true;
// A vote that stops counting is no longer one of its reviewer's papers, and one that counts again is.
if ((vote.counted?.status === "discarded") !== (counted.status === "discarded")) dealt.set(vote.reviewerId, (dealt.get(vote.reviewerId) ?? 0) + (counted.status === "discarded" ? -1 : 1));
add(countsOf(vote.reviewerId), vote.counted, -1);
add(countsOf(vote.reviewerId), counted, 1);
- // A model's vote follows its answers under the criteria as they are now, so its decision can move with them.
- await ctx.db.patch("screeningVotes", vote._id, { counted, ...(cast.status === "cast" && vote.decision !== cast.decision ? { decision: cast.decision, reason: cast.reason } : {}), ...(finished ? { slot: undefined } : {}) });
+ // A model's vote follows its answers under the criteria as they are now: its decision, and the criterion it excludes for, can move with them.
+ await ctx.db.patch("screeningVotes", vote._id, { counted, ...(!decided ? { decision: cast.decision, reason: cast.reason } : {}), ...(finished ? { slot: undefined } : {}) });
}
if (changed || before.length !== after.length) {
for (const [i, x] of before.entries()) for (const y of before.slice(i + 1)) pair(x.id, y.id, x.decision, y.decision, -1);
diff --git a/convex/screening/voting.ts b/convex/screening/voting.ts
index 254c17736..5da7a1b2f 100644
--- a/convex/screening/voting.ts
+++ b/convex/screening/voting.ts
@@ -44,8 +44,8 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
if (onlyWaiting && mine?.status !== "waiting") return false;
if (onlyAt !== undefined && (mine?.status !== "cast" || mine.at !== onlyAt)) return false;
if (decision === null) {
- // Taken back: the place is theirs again to vote from.
- if (mine?.status !== "cast") return;
+ // Taken back: the place is theirs again to vote from. One with no vote to take back changes nothing.
+ if (mine?.status !== "cast") return false;
await ctx.db.patch("screeningVotes", mine._id, { status: "waiting", decision: undefined, answers: undefined, reason: undefined, note: undefined, at: undefined, flagged: undefined });
return void (await stamp(ctx, paperId));
}
@@ -53,7 +53,9 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
const known = new Set([...(job.criteria ?? []), ...(onlyAt !== undefined ? (job.retiredCriteria ?? []) : [])].map((criterion) => criterion.key));
// A criterion given as the reason to exclude is one the voter says is not met, so its answer is No wherever the vote was cast from.
const given = { ...Object.fromEntries(Object.entries(answers ?? {}).filter(([key]) => known.has(key))), ...(decision === "exclude" && reason && known.has(reason) ? { [reason]: "no" as const } : {}) };
- const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: Date.now(), flagged: answersOnly && mine?.status === "cast" ? mine.flagged : undefined };
+ // Answers joining a vote already cast leave it the vote it was: cast when it was, which "first vote decides" reads, and asked for again if it was.
+ const kept = answersOnly && mine?.status === "cast" ? mine : undefined;
+ const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: kept?.at ?? Date.now(), flagged: kept?.flagged };
if (mine) await ctx.db.patch("screeningVotes", mine._id, vote);
else {
// A reviewer who votes on a paper that wasn't given to them is on it from then on.
@@ -61,6 +63,7 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
await countDealt(ctx, new Map([[reviewer._id, 1]]));
}
await stamp(ctx, paperId);
+ return vote.at;
}
/**
@@ -73,10 +76,10 @@ export const vote = workspaceMutation({
// When the vote it cast was cast, for an Undo to name (`onlyAt`); null where it took a vote back or changed nothing.
returns: v.union(v.number(), v.null()),
handler: async (ctx, actor, args) => {
- const done = (await cast(ctx, await requireReviewer(ctx, actor, args.jobId), { ...args, answers: args.answers as Record | undefined })) !== false;
+ const at = await cast(ctx, await requireReviewer(ctx, actor, args.jobId), { ...args, answers: args.answers as Record | undefined });
await bookkeepLater(ctx);
- // A mutation's clock stands still: this is the moment the vote was stamped with.
- return done && args.decision !== null ? Date.now() : null;
+ // The moment the vote stands stamped with, which an Undo names, or the moment one was taken back; null where nothing changed.
+ return at === false ? null : (at ?? Date.now());
},
});
From f67ca8311efc6d32775354dd1e51b5d8fa718efa Mon Sep 17 00:00:00 2001
From: sickerine
Date: Sat, 28 Nov 2026 14:21:31 +0000
Subject: [PATCH 3/3] fix(screening): what Codex found on #1619
- Extraction takes a copy of a screening paper's PDF: deleting the extraction
deletes its copy, never the screening's file.
- A vote keeps when it was cast apart from when it was last changed: answers
joining it leave its cast time for "first vote decides", and an Undo kept
from before the change is refused.
- A reading a full screening stopped before it gave anything leaves the source
as its last whole reading left it, its lists of merged and left-out records
included.
- An Undo pressed while its vote is still saving, which the server then refuses,
moves the counts back once.
---
components/screening/screen.tsx | 18 ++++++++++++++----
convex/extraction/actions.ts | 5 +++--
convex/schema.ts | 2 ++
convex/screening/gathering.ts | 4 ++--
convex/screening/paperViews.ts | 2 +-
convex/screening/voting.ts | 8 ++++----
6 files changed, 26 insertions(+), 13 deletions(-)
diff --git a/components/screening/screen.tsx b/components/screening/screen.tsx
index ba32787b3..ad51bc8e1 100644
--- a/components/screening/screen.tsx
+++ b/components/screening/screen.tsx
@@ -292,7 +292,14 @@ function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes,
// A paper's vote and its settlement each have their own note: the draft of one never stands in for the other.
const noteKey = (id: string) => (resolving ? `settle:${id}` : id);
// `saved`: when the server stamped the vote or settlement, once it has: Undo puts back what stood before only while that one still stands.
- const [history, setHistory] = useState }>>([]);
+ // `unmoved`: the counts it moved were moved back already, by an Undo or a refusal, so neither moves them back twice.
+ const [history, setHistory] = useState; unmoved?: boolean }>>([]);
+ /** Moves back the counts a vote or settlement made here moved, once. */
+ const unmove = (made: { unmoved?: boolean } & Parameters[0]) => {
+ if (made.unmoved) return;
+ made.unmoved = true;
+ for (const [kind, by] of movesOf(made)) moved(kind, by === 1 ? -1 : 1);
+ };
// The frame's counts take in the votes made here before the server's do (./store.tsx `useUnheardMoves`): To do, Done, the bar and the tabs above read one number.
const { toDo, conflicts } = open;
// The votes and settlings made here since the counts last moved: a queue they emptied is said empty from them.
@@ -369,7 +376,7 @@ function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes,
for (const [kind, by] of moves) moved(kind, by);
// A vote the server refuses was never cast: it leaves "your last vote", and its paper is the open one again.
const refused = (error: unknown) => {
- for (const [kind, by] of moves) moved(kind, by === 1 ? -1 : 1);
+ unmove(cast);
setHistory((all) => all.filter((one) => one !== cast));
openIt(paper, { inPlace: true });
failed(error);
@@ -459,12 +466,15 @@ function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes,
if (last.saved === undefined) return;
if (last.resolved) return open.resolve(last.paper.id, last.settledBefore ? (last.settledBefore.final ?? null) : null, last.settledBefore?.note, last.settledBefore?.reason, last.saved).then(restamp, failed);
// Changed since in another tab, the vote stands: the counts it moved here stand with it.
- return open.vote(last.paper.id, last.before ? ballotOf(last.before) : null, { onlyAt: last.saved }).then((at) => { if (at === null) for (const [kind, by] of movesOf(last)) moved(kind, by); restamp(last.before ? at : null); }, failed);
+ return open.vote(last.paper.id, last.before ? ballotOf(last.before) : null, { onlyAt: last.saved }).then((at) => {
+ if (at === null && last.unmoved) { last.unmoved = false; for (const [kind, by] of movesOf(last)) moved(kind, by); }
+ restamp(last.before ? at : null);
+ }, failed);
});
// Undo pressed again at once waits for this one, so it names the moment this one stamps.
if (earlier) earlier.pending = Promise.all([earlier.pending, undoing]);
openIt(last.paper);
- for (const [kind, by] of movesOf(last)) moved(kind, by === 1 ? -1 : 1);
+ unmove(last);
setHistory((all) => all.filter((one) => one !== last));
};
diff --git a/convex/extraction/actions.ts b/convex/extraction/actions.ts
index cf3b61b31..dc3a4555e 100644
--- a/convex/extraction/actions.ts
+++ b/convex/extraction/actions.ts
@@ -279,8 +279,9 @@ async function readStep(ctx: ActionCtx, job: Doc<"extractionJobs">, clerkId: str
// From the first paper of its range, as many as the start counted.
const from = (selection.first ?? 1) + place.read;
const { papers: held, resume } = await heldPapers(ctx, await jobReader(ctx, job), { kind: "screening", jobId: selection.jobId }, { first: from, last: Math.min((selection.first ?? 1) + selection.count - 1, from + SETUP_STEP - 1) }, place.resume, selection.revision);
- // A paper the screening had only as its PDF goes on as that file, which extraction reads as a paper's own PDF.
- const papers = held.map(({ venue, file, pages: _pages, ...paper }): SetupPaper => ({ ...paper, ...(file ? { storageId: file } : {}), venueName: venue, sourceType: "screening", sourceId: selection.jobId, screeningRevision: selection.revision }));
+ // A paper the screening had only as its PDF goes on as a copy of that file, which extraction reads as a paper's own PDF and deletes with the extraction: the screening keeps its own.
+ const copyOf = async (file: Id<"_storage">) => { const blob = await ctx.storage.get(file); return blob ? await ctx.storage.store(blob) : null; };
+ const papers = await Promise.all(held.map(async ({ venue, file, pages: _pages, ...paper }): Promise => { const copied = file ? await copyOf(file) : null; return { ...paper, ...(copied ? { storageId: copied } : {}), venueName: venue, sourceType: "screening", sourceId: selection.jobId, screeningRevision: selection.revision }; }));
const read = place.read + papers.length;
if (resume && read < selection.count) return { papers, next: { ...place, read, resume } };
if (read !== selection.count) throw createError("CONFLICT", "Screening inputs changed. Select the screening again before starting extraction.");
diff --git a/convex/schema.ts b/convex/schema.ts
index 19894c71e..c6201b7d4 100644
--- a/convex/schema.ts
+++ b/convex/schema.ts
@@ -1621,6 +1621,8 @@ export default defineSchema({
note: v.optional(v.string()),
// When it was cast.
at: v.optional(v.number()),
+ // When the vote was last changed, where answers joined it after it was cast: `at` stays when it was cast, which "first vote decides" reads, and an Undo names this.
+ edited: v.optional(v.number()),
// A person's vote cast before a criterion became a must-have: it stands, and asks for a new one.
flagged: v.optional(v.literal(true)),
// On a place a person has yet to vote from: how many of the paper's models would include it, as a negative number, so the papers the models lean to come first in the order of an index.
diff --git a/convex/screening/gathering.ts b/convex/screening/gathering.ts
index 23fcdb548..783892e71 100644
--- a/convex/screening/gathering.ts
+++ b/convex/screening/gathering.ts
@@ -476,8 +476,8 @@ export const fill = internalMutation({
if (back) await bookkeepLater(ctx);
// A first reading counts as it goes. One read again counts beside the figures it has, and takes their place once it is whole.
const next = source.next && { ...source.next, duplicates: source.next.duplicates + duplicates, left: source.next.left + left, bare: source.next.bare + bare };
- // A reading stopped by a full screening before it gave anything keeps the figures of the last whole reading: it read nothing that would replace them.
- const counted = full ? { next: undefined } : !next ? { duplicates: source.duplicates + duplicates, left: source.left + left, ...(bare ? { bare: (source.bare ?? 0) + bare } : {}) } : ended || capped ? { duplicates: next.duplicates, left: next.left, bare: next.bare, next: undefined } : { next };
+ // A reading stopped by a full screening before it gave anything leaves the source as its last whole reading left it, figures and lists: it read nothing that would replace them.
+ const counted = full ? {} : !next ? { duplicates: source.duplicates + duplicates, left: source.left + left, ...(bare ? { bare: (source.bare ?? 0) + bare } : {}) } : ended || capped ? { duplicates: next.duplicates, left: next.left, bare: next.bare, next: undefined } : { next };
await ctx.db.patch("screeningSources", sourceId, { read: source.read + read, resume, taken: source.taken + taken + back, ...counted, ...(filed ? { filed: (source.filed ?? 0) + filed, filePages: (source.filePages ?? 0) + filePages, fileSpread } : {}), ...(ended || capped ? { state: "done" as const, checkedAt: now } : {}), ...(capped ? { capped: true as const } : {}) });
// Papers brought back with this source are counted apart from the new ones, which take new places: a finished screening they wait in opens again all the same (./living.ts `checked`).
await ctx.db.patch("screeningChecks", checkId, { found: check.found + papers.length + (leftOut?.length ?? 0), added: check.added + taken, ...(back ? { restored: (check.restored ?? 0) + back } : {}), ...(left ? { left: (check.left ?? 0) + left } : {}), beat: now, ...(taken ? { bySource: { ...check.bySource, [sourceId]: (check.bySource?.[sourceId] ?? 0) + taken } } : {}), ...((ended || capped) && check.unread?.includes(sourceId) ? { unread: check.unread.filter((one) => one !== sourceId) } : {}) });
diff --git a/convex/screening/paperViews.ts b/convex/screening/paperViews.ts
index aee35f362..6c8464d2d 100644
--- a/convex/screening/paperViews.ts
+++ b/convex/screening/paperViews.ts
@@ -49,7 +49,7 @@ function voteOf(job: Doc<"screeningJobs">, vote: Vote, reviewer: Reviewer | unde
const answers = (vote.answers ?? {}) as Record;
const read = vote.decision ? { decision: vote.decision, reason: vote.reason } : ballotOf(placeOf(vote, reviewer), job.criteria ?? []);
if (!read.decision) return undefined;
- return { decision: read.decision, answers, ...(read.reason ? { reason: read.reason } : {}), ...(vote.note ? { note: vote.note } : {}), at: vote.at ?? vote._creationTime, ...(vote.flagged ? { flagged: true } : {}), ...(vote.confidences ? { confidences: vote.confidences } : {}), ...(vote.passages ? { passages: vote.passages } : {}) };
+ return { decision: read.decision, answers, ...(read.reason ? { reason: read.reason } : {}), ...(vote.note ? { note: vote.note } : {}), at: vote.edited ?? vote.at ?? vote._creationTime, ...(vote.flagged ? { flagged: true } : {}), ...(vote.confidences ? { confidences: vote.confidences } : {}), ...(vote.passages ? { passages: vote.passages } : {}) };
}
/**
diff --git a/convex/screening/voting.ts b/convex/screening/voting.ts
index 5da7a1b2f..c7f9ff23e 100644
--- a/convex/screening/voting.ts
+++ b/convex/screening/voting.ts
@@ -42,11 +42,11 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
if ((note?.length ?? 0) > SCREENING_TEXT.voteNote) throw createError("VALIDATION_ERROR", "That note is too long.");
const mine = (await votesOf(ctx, paperId)).find((vote) => vote.reviewerId === reviewer._id);
if (onlyWaiting && mine?.status !== "waiting") return false;
- if (onlyAt !== undefined && (mine?.status !== "cast" || mine.at !== onlyAt)) return false;
+ if (onlyAt !== undefined && (mine?.status !== "cast" || (mine.edited ?? mine.at) !== onlyAt)) return false;
if (decision === null) {
// Taken back: the place is theirs again to vote from. One with no vote to take back changes nothing.
if (mine?.status !== "cast") return false;
- await ctx.db.patch("screeningVotes", mine._id, { status: "waiting", decision: undefined, answers: undefined, reason: undefined, note: undefined, at: undefined, flagged: undefined });
+ await ctx.db.patch("screeningVotes", mine._id, { status: "waiting", decision: undefined, answers: undefined, reason: undefined, note: undefined, at: undefined, edited: undefined, flagged: undefined });
return void (await stamp(ctx, paperId));
}
// Undo puts back the answers as they were, to criteria taken off since too.
@@ -55,7 +55,7 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
const given = { ...Object.fromEntries(Object.entries(answers ?? {}).filter(([key]) => known.has(key))), ...(decision === "exclude" && reason && known.has(reason) ? { [reason]: "no" as const } : {}) };
// Answers joining a vote already cast leave it the vote it was: cast when it was, which "first vote decides" reads, and asked for again if it was.
const kept = answersOnly && mine?.status === "cast" ? mine : undefined;
- const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: kept?.at ?? Date.now(), flagged: kept?.flagged };
+ const vote = { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: kept?.at ?? Date.now(), edited: kept ? Date.now() : undefined, flagged: kept?.flagged };
if (mine) await ctx.db.patch("screeningVotes", mine._id, vote);
else {
// A reviewer who votes on a paper that wasn't given to them is on it from then on.
@@ -63,7 +63,7 @@ async function cast(ctx: MutationCtx, { job, reviewer }: { job: Doc<"screeningJo
await countDealt(ctx, new Map([[reviewer._id, 1]]));
}
await stamp(ctx, paperId);
- return vote.at;
+ return vote.edited ?? vote.at;
}
/**