diff --git a/components/command-center/command-center-toolbar.tsx b/components/command-center/command-center-toolbar.tsx index 8a6fa40b0..24005f6e5 100644 --- a/components/command-center/command-center-toolbar.tsx +++ b/components/command-center/command-center-toolbar.tsx @@ -79,7 +79,8 @@ export function CommandCenterFilters({ {sortOptions.map((option) => {option.label})} - + {/* Under its field and as wide as it, as every field's list opens. */} + {sortOptions.map((option) => ( {option.label} diff --git a/components/models/model-picker.tsx b/components/models/model-picker.tsx index 440283505..ca8353c8f 100644 --- a/components/models/model-picker.tsx +++ b/components/models/model-picker.tsx @@ -243,6 +243,7 @@ export function ModelPicker({ tasks = [], exclude, price, + width = "w-[38rem]", }: { current: Current | undefined; /** The picked model, and its effort when the picker asked for one. */ @@ -259,6 +260,8 @@ export function ModelPicker({ tasks?: AiTask[]; /** Slugs to leave out, such as models already added. */ exclude?: string[]; + /** How wide the list opens: narrower inside a dialog than its own width, so it never runs past the dialog's edge. */ + width?: string; /** The cost column in the place's own unit, where it charges in one. */ price?: PickerPrice; }) { @@ -362,7 +365,7 @@ export function ModelPicker({ = { created: t("activity.started"), renamed: t("activity.renamed", { name: words.quoted(detail) }), edited: detail || t("activity.changedIt"), added: detail ? t("activity.added", { what: detail }) : t("activity.addedPapers"), removed: detail ? t("activity.removed", { what: detail }) : t("activity.removedPapers"), screened: t("activity.screened", { count }), paused: t("activity.paused"), resumed: t("activity.resumed"), retried: t("activity.readAgain"), stopped: t("activity.stopped"), moved: detail ? t("activity.movedFrom", { from: detail }) : t("activity.movedAway"), shared: detail ? t("activity.shared", { who: detail }) : t("activity.sharedSomeone") }; + const KIND: Record = { created: t("activity.started"), renamed: t("activity.renamed", { name: words.quoted(detail) }), edited: detail || t("activity.changedIt"), added: detail ? t("activity.added", { what: detail }) : t("activity.addedPapers"), removed: detail ? t("activity.removed", { what: detail }) : t("activity.removedPapers"), screened: t("activity.screened", { count }), paused: t("activity.paused"), resumed: t("activity.resumed"), retried: t("activity.readAgain"), stopped: t("activity.stopped"), moved: detail ? t("activity.movedFrom", { from: detail }) : t("activity.movedAway"), shared: detail ? t("activity.shared", { who: detail }) : t("activity.sharedSomeone"), unshared: t("activity.unshared", { who: detail }) }; return { what: KIND[row.happened] ?? (detail || t("activity.changedIt")) }; } diff --git a/components/screening/dialogs.tsx b/components/screening/dialogs.tsx index 9312799fe..c49ecfa89 100644 --- a/components/screening/dialogs.tsx +++ b/components/screening/dialogs.tsx @@ -240,7 +240,7 @@ export function PeopleDialog({ open, onClose, state, onAdd, onRemove, onDemote } )} {finished ? null : ( - modelKey(model.model!))} pdfs={pdfsOf(screening.sources)} onPick={(model) => onAdd(modelReviewer(model, Date.now()))}> + modelKey(model.model!))} pdfs={pdfsOf(screening.sources)} onPick={(model) => onAdd(modelReviewer(model, Date.now()))}> )} @@ -285,7 +285,7 @@ export function PeopleDialog({ open, onClose, state, onAdd, onRemove, onDemote } key: one.id, avatar: , name: one.name, - detail: t("peopleDialog.modelRead", { failed: String(Boolean(one.tally?.failed)), price: perPaper({ words, t: list }, one.model!), done: gotThrough(one.tally), of: theirsOf(one.tally) }), + detail: t("peopleDialog.modelRead", { failed: String(Boolean(one.tally?.failed)), price: perPaper({ words, t: list }, one.model!, one.tally), done: gotThrough(one.tally), of: theirsOf(one.tally) }), role: { kind: "edit" as const, label: t("peopleDialog.model") }, ...(may ? { onRemove: () => onRemove(one) } : {}), })), diff --git a/components/screening/export-dialog.tsx b/components/screening/export-dialog.tsx index f3c75e9e2..9392d7767 100644 --- a/components/screening/export-dialog.tsx +++ b/components/screening/export-dialog.tsx @@ -310,7 +310,7 @@ export function ExportDialog({ open, onClose, state, tab, onTab }: { open: boole {row.vote.note ?? t("votes.none")} - {words.ago(row.vote.at)} + {words.ago(row.vote.castAt ?? row.vote.at)} ))} diff --git a/components/screening/export.ts b/components/screening/export.ts index 934cd9732..18ecb2c7f 100644 --- a/components/screening/export.ts +++ b/components/screening/export.ts @@ -296,7 +296,7 @@ export const votesCsv = (screening: Screening, papers: Paper[], whose?: string) return [ paper.id, doiOf(paper) ?? "", paper.title, paper.year ?? "", reviewer.name, kindOf(reviewer), status, vote ? DECISION_LABEL[vote.decision] : "", vote?.reason ? failedLabel(vote.reason, reasonCriteria(screening)) : "", ...criteria.map((criterion) => vote?.answers[criterion.key] ?? ""), vote?.note ?? "", RESULT_LABEL[settled.result], - settled.resolvedBy ? nameOn(screening, settled.resolvedBy) : "", settled.note ?? "", vote ? iso(vote.at) : "", + settled.resolvedBy ? nameOn(screening, settled.resolvedBy) : "", settled.note ?? "", vote ? iso(vote.castAt ?? vote.at) : "", ]; }), ]); @@ -469,7 +469,7 @@ export function methodsOf(out: Taken) { `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.` : ""}`, + `${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")}${(figures?.changedParts ?? []).includes("criteria") ? " as they were last set" : ""}${((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.` : ""}`, // Who a record is given to, which is the method. How many of them voted is in the votes themselves: a record can be settled before each has. readers ? `${readers} ${one(Math.min(each, pool))} assigned to ${short.length ? "the records" : `each record${late.length ? " still open when they joined" : ""}`}${screening.rule.blind !== "after" ? `. Every vote on a record ${running ? "is" : "was"} visible to the reviewers at any time, before they cast their own` : hidesVotes(screening.rule, hidingReaders(screening, out.invited), modelsVoting(screening)) ? `. A reviewer ${running ? "does" : "did"} not see the other ${advised ? "human reviewers' votes" : "votes"} on a record before casting their own${advised ? `, and ${running ? "can" : "could"} see the AI models' votes already cast on it` : ""}` : advised ? `. The reviewer ${running ? "sees" : "saw"} the AI models' votes on a record before casting their own` : ""}.${short.length ? ` ${short.map((person) => `${person.name} was given ${num(person.tally?.dealt ?? 0)} of the ${num(kept)}`).join(", and ")}.` : ""}${late.length ? ` ${listed(late.map((person) => person.name))} joined after screening began and ${late.length === 1 ? "was" : "were"} given only records still open then.` : ""}${offPeople.length ? ` ${listed(offPeople.map((person) => person.name))} ${offPeople.length === 1 ? "was" : "were"} taken off after screening began, and the votes they cast until then were kept.` : ""}` : offPeople.length ? `${listed(offPeople.map((person) => person.name))} ${offPeople.length === 1 ? "was a human reviewer" : "were human reviewers"} until taken off, and the votes cast until then were kept.` : "No human reviewer was assigned to the records.", everyModel.length ? `${everyModel.length === 1 ? "One AI model" : `${everyModel.length} AI models`} (${everyModel.map((m) => { const effort = m.model ? (m.model.effort ?? effortOf(m.model)) : null; return m.model ? (effort && effort !== "none" ? `${m.model.name}, ${EFFORT_WORDS[effort]} reasoning effort` : m.model.name) : m.name; }).join("; ")}) ${running && !offModels.length ? (models.length === 1 ? "votes" : "vote") : running ? "have voted" : "voted"} on the records${people.length ? (advised ? ` as advice only (the human reviewers ${running ? "decide" : "decided"} each record they ${running ? "are" : "were"} given)` : ` as ${everyModel.length === 1 ? "an additional reviewer" : "additional reviewers"}`) : ""}, giving an answer for every criterion${unread ? `; ${plural(unread, "reading", "readings")} by a model failed, and ${unread === 1 ? "that record" : "those records"} ${one(unread)} ${othersLeft}` : ""}.${offModels.length ? ` ${listed(offModels.map((m) => m.name))} ${offModels.length === 1 ? "was" : "were"} taken off after screening began, and ${offModels.length === 1 ? "its" : "their"} votes cast until then were kept.` : ""}${modelsShort.length ? ` ${modelsShort.join(" ")}` : ""}${failedOffSays}` : failedOff.length ? failedOffSays.trim() : "No AI model took part.", @@ -557,7 +557,8 @@ export async function recordOf(convex: ConvexReactClient, workspaceId: Id<"works reason: vote.reason ?? null, answers: vote.answers, note: vote.note ?? null, - voted_at: iso(vote.at), + voted_at: iso(vote.castAt ?? vote.at), + ...(vote.castAt ? { answers_changed_at: iso(vote.at) } : {}), ...(reviewer.kind === "model" ? { read: Object.fromEntries(reasonCriteria(screening).flatMap((criterion) => { const [sentence, confidence] = [vote.passages?.[criterion.key], vote.confidences?.[criterion.key]]; return vote.answers[criterion.key] ? [[criterion.key, { passage: sentence === undefined || sentence === null ? null : (sentencesOf(paper.abstract)[sentence] ?? null), confidence: confidence === undefined ? null : Number(confidence.toFixed(2)) }]] : []; })) } : {}), }] : [])), // Who was on a paper and cast no vote on it: someone who has yet to, someone the paper was settled without, a model that couldn't read it. diff --git a/components/screening/index-page.tsx b/components/screening/index-page.tsx index f48fc59e3..50fa0df9b 100644 --- a/components/screening/index-page.tsx +++ b/components/screening/index-page.tsx @@ -40,7 +40,7 @@ import { searchHistory } from "./address"; import { askedHref, newHref, overviewHref, papersHref, reviewerHref, screenHref } from "./links"; import { draftOf, useKept } from "./drafts"; import { OVERS, ScreeningMenuItems, useScreeningOverlays, type Over } from "./overlays"; -import { Faces, FilterMenu, Help, LinkChip, StateChip, votesBy, RESULT_ICON, ResultBar, TabCount, tinted, MODELS_READING, MODELS_SAY, FIGURE_LINK } from "./pieces"; +import { Faces, FilterMenu, Help, LinkChip, votesBy, RESULT_ICON, ResultBar, TabCount, tinted, MODELS_READING, MODELS_SAY, FIGURE_LINK } from "./pieces"; import { toReviewers, useOpenScreening, type Summary } from "./store"; import { ScrollArea } from "@/components/ui/scroll-area"; import { useWords } from "./words"; @@ -271,8 +271,8 @@ export function ScreeningsIndex() { at: (chunks) => {chunks}, })} {elsewhere ? : null} - {/* Found by a search or under All, a finished one says so on its card, as the Show filter would. */} - {row.finishedAt ? {t("show.finished")} : row.living ? {words.living(row.living.every)} : null} + {/* Found by a search or under All, a finished one says so on its card, as the Show filter would: under Finished every one is. */} + {row.finishedAt ? (show !== "finished" ? {t("show.finished")} : null) : row.living ? {words.living(row.living.every)} : null} {/* A member who isn't one of its reviewers can still change it: only someone it was shared with is a viewer. */} {!row.isReviewer ? {words.looker(row.member)} : null} @@ -303,8 +303,8 @@ export function ScreeningsIndex() { : models ? {tp(`modelsSay.${models}.says`)} : null} {/* Where its papers stand shows where nothing waits for you. */} - {forYou || conflicts ? null - : row.finishedAt ? (stands.include ? {t("finishedIncluded", { included: words.num(stands.include) })} : {t("finishedIncluded", { included: words.num(0) })}) + {/* A finished one's papers are said once, under its bar. */} + {forYou || conflicts || row.finishedAt ? null : models ? null : stands.waiting ? {t("waitingForVotes", { count: words.num(stands.waiting) })} : stands.conflict ? {t("inConflictFor", { count: words.num(stands.conflict), who: resolver })} diff --git a/components/screening/overview.tsx b/components/screening/overview.tsx index 246deaf25..b740beb8c 100644 --- a/components/screening/overview.tsx +++ b/components/screening/overview.tsx @@ -923,7 +923,7 @@ function Facts({ open }: { open: Open }) { className="flex flex-col" title={t("credits.title")} help={ - {t("credits.modelCost", { name: model.name, cost: perPaper({ words, t: tl }, model.model!) })}) : {t("credits.peopleOnly")}}> + {t("credits.modelCost", { name: model.name, cost: perPaper({ words, t: tl }, model.model!, model.tally) })}) : {t("credits.peopleOnly")}}>

{t("credits.free")}

} diff --git a/components/screening/papers.tsx b/components/screening/papers.tsx index 5df5a14d5..3710e941e 100644 --- a/components/screening/papers.tsx +++ b/components/screening/papers.tsx @@ -811,7 +811,8 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) => return {theirs ? ; }) : criteria.map((criterion) => { - const given = [...new Set(cast.flatMap((entry) => entry.vote?.answers[criterion.key] ?? []))]; + // Narrowed to reviewers, the answers are theirs alone: never another's under their name. + const given = [...new Set(cast.flatMap((entry) => (everyone.length && !everyone.includes(entry.reviewer.id) ? [] : (entry.vote?.answers[criterion.key] ?? []))))]; return ( {given.length === 1 ? : given.length > 1 ? : null} @@ -970,13 +971,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; + // It gives way before the reason beside it: the note is cut first, the reason only where it can't fit alone. + const settledNote = state.resolvedBy && state.note ? {words.quoted(state.note)} : null; if (!visible) return settledNote; 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}; + 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)); @@ -984,7 +986,7 @@ function Why({ paper, open, reasonKey }: { paper: Paper; open: Open; reasonKey?: 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; - if (written) return {words.quoted(written)}; + if (written) return {words.quoted(written)}; return ( {/* An excluded paper's reason narrows the table to it. A Maybe's unclear criterion names why and opens nothing: the list narrows by exclusion reasons only, and a link to it would open empty. */} diff --git a/components/screening/pieces.tsx b/components/screening/pieces.tsx index a362d8aab..68b53485c 100644 --- a/components/screening/pieces.tsx +++ b/components/screening/pieces.tsx @@ -368,6 +368,9 @@ export function FilterMenu({ name, lead, value, onChange, choi const t = useTranslations("screening.pieces"); const picked = choices.find((one) => one.value === value) ?? choices[0]!; const changed = picked !== choices[0]; + // A reason several choices are shut for is said once, under them all, never under each. + const shut = choices.flatMap((one) => (one.shut ? [one.shut] : [])); + const once = shut.length > 1 && shut.every((reason) => reason === shut[0]) ? shut[0] : undefined; return ( @@ -390,13 +393,20 @@ export function FilterMenu({ name, lead, value, onChange, choi // A long name runs onto a second line, and the sign, the count and the tick stay on its first. onChange(one.value)} className="items-start data-[disabled]:opacity-100"> {one.icon ? {one.icon} : null} - {one.label}{/* The lock sits on the reason's first line, in a box one line high, however far the reason runs. */}{one.shut ? {one.shut} : null} + {one.label}{/* The lock sits on the reason's first line, in a box one line high, however far the reason runs. */}{one.shut && !once ? {one.shut} : null} + {one.shut && once ? : null} {one.count !== undefined ? , : null} ))} ))} + {once ? ( + <> + +

{once}

+ + ) : null}
); diff --git a/components/screening/screen.tsx b/components/screening/screen.tsx index 091bc0b00..5b740e1e8 100644 --- a/components/screening/screen.tsx +++ b/components/screening/screen.tsx @@ -40,7 +40,7 @@ import { useProtectedQuery } from "@/lib/auth/use-auth-query"; 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"; +import { decide, givenReason, leansOpen, NOTE_LENGTH, OTHER_REASON } from "@/lib/screening/rules"; import { ANSWERS, type Answer } from "@/lib/screening/rules"; import { getErrorMessage } from "@/lib/toast/use-app-toast"; import { cn } from "@/lib/utils"; @@ -434,12 +434,9 @@ function Screen({ open, castByMe, moved }: { open: Open; /** The person's votes, // It stamps the vote anew: the step that cast it names the new moment, and Undo waits for it, so Undo still takes the vote back. if (mine && !resolving) { const cast = history.findLast((one) => one.paper.id === paper.id && !one.resolved); - // An exclusion that rested on this criterion failing rests on what the answers say now: another failed must-have, the note, or no reason. - // And one that had no reason takes the must-have its answers now fail, as an exclusion cast with them would. - 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 } : {}) }; + // Only this answer goes: it joins the vote as it stands now, which works out what an exclusion rests on (convex/screening/voting.ts), so another tab's answer to another criterion stays. // 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, { answersOnly: true }).then((at) => { + const saving = open.vote(paper.id, ballotOf(mine), { answered: { key: criterion, answer: given[criterion] ?? null } }).then((at) => { if (at !== null && cast) cast.saved = at; setAnswers(({ [paper.id]: was, ...rest }) => (was === given || was === undefined ? rest : { ...rest, [paper.id]: was })); }, failed); diff --git a/components/screening/screening-form.tsx b/components/screening/screening-form.tsx index 5dbff3e40..44af3f152 100644 --- a/components/screening/screening-form.tsx +++ b/components/screening/screening-form.tsx @@ -878,6 +878,8 @@ export function ScreeningForm({ id }: { id?: string }) { if (!saved || !id || !change || busy || counting || countFailed) return; setBusy(true); try { + // The save is checked before anything goes out: an invitation, a guest's place or a community's collection is never given for a save that is then refused. + if (workspaceId) await convex.query(api.screening.settings.checkChange, { workspaceId, jobId: saved.id as Id<"screeningJobs">, change }); // People from outside the workspace join by sharing: a reviewer as a guest who votes. // Someone with an invitation already waiting (an earlier try of this save, before a reload too) isn't invited again: the server's list of waiting invitations says who. const waiting = new Set((open?.invited ?? []).filter((one) => !one.undelivered).flatMap((one) => one.email?.toLowerCase() ?? [])); @@ -1587,7 +1589,7 @@ export function ScreeningForm({ id }: { id?: string }) { {reviewer.model ? ( <> {paused ? {pieces("modelsSay.paused.row")} : null} - {perPaper({ words, t: list }, reviewer.model)} + {perPaper({ words, t: list }, reviewer.model, reviewer.tally)} {/* A model that takes no files is given no paper that is only its PDF: said where it is picked, before it is paid for. */} {pdfsMissed(reviewer.model, pdfs).papers ? {t("reviewers.pdfsMissed", { why: pdfsMissed(reviewer.model, pdfs).why === "text" ? "text" : "long", count: pdfsMissed(reviewer.model, pdfs).papers })} : null} {due(reviewer) ? ( diff --git a/components/screening/store.tsx b/components/screening/store.tsx index 96adf9538..338942f99 100644 --- a/components/screening/store.tsx +++ b/components/screening/store.tsx @@ -13,12 +13,12 @@ import { stripProviderPrefix } from "@/lib/ai/model-display"; import { readsPdfs } from "@/lib/assistant/files"; import { useProtectedQuery } from "@/lib/auth/use-auth-query"; import { longestPdfs, pdfsFor, pricingOf, screeningPaperCredits, screeningPdfsCredits, type Pdfs } from "@/lib/pricing/estimate"; -import { modelsProgress, twinsNamed, type Answer } from "@/lib/screening/rules"; +import { gotThrough, modelsProgress, twinsNamed, type Answer } from "@/lib/screening/rules"; import { inWorkspace, useWorkspace, useWorkspaceMutation } from "@/lib/workspaces/url"; import { useTranslations } from "next-intl"; import { showStyledToast } from "@/components/ui/sonner"; import { getErrorMessage } from "@/lib/toast/use-app-toast"; -import { DAY, GROWS, baseTaken, keptOf, modelsOf, paperTotal, peopleOf, refOf, type Criterion, type Decision, type Person, type Result, type Reviewer, type Screening, type Source, type Workspace } from "./data"; +import { DAY, GROWS, baseTaken, keptOf, modelsOf, paperTotal, peopleOf, refOf, type Criterion, type Decision, type Person, type Result, type Reviewer, type Screening, type Source, type Tally, type Workspace } from "./data"; import { useWords, type Words } from "./words"; type View = NonNullable>; @@ -83,7 +83,11 @@ export function pdfReadingCredits(model: Priced, ahead: number, pdfs: Pdfs) { /** What `count` of one screening's papers cost a model at most. */ export const readingOf = (screening: Pick, model: Priced, count: number) => readingCredits(model, count, pdfsOf(screening.sources)); /** What a model charges to read one paper, as every page says it. */ -export const perPaper = ({ words, t }: { words: Words; t: ReturnType> }, model: Pick) => t("perPaper", { credits: words.creditsOf(paperCredits(model)) }); +/** What a model costs a paper: what it has spent a paper where it has read some, which is what it is charged, else what one paper is reckoned to cost. */ +export const perPaper = ({ words, t }: { words: Words; t: ReturnType> }, model: Pick, tally?: Pick) => { + const read = tally ? gotThrough(tally) : 0; + return t("perPaper", { credits: words.creditsOf(read && tally!.spent ? tally!.spent / read : paperCredits(model)) }); +}; /** * What a screening's models are doing, worked out on the server in one place, so the list's row, the frame's notice, @@ -294,8 +298,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). - // `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 } : {}) }), + // `answered`: one answer joining a vote already cast, or taken back, which leaves the vote as it stands otherwise (in Vote again too). + vote: (paperId: Id<"screeningResults">, ballot: Ballot | null, { onlyWaiting = false, onlyAt, answered }: { onlyWaiting?: boolean; onlyAt?: number; answered?: { key: string; answer: Answer | null } } = {}) => vote({ jobId, paperId, ...(onlyWaiting ? { onlyWaiting } : {}), ...(onlyAt === undefined ? {} : { onlyAt }), ...(answered ? { answered } : {}), 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/team.tsx b/components/screening/team.tsx index 29f908d59..03f02ee78 100644 --- a/components/screening/team.tsx +++ b/components/screening/team.tsx @@ -146,7 +146,7 @@ export function AddPerson({ exclude, screening, freeing = 0, onPick, children }: * server has it (convex/screening/reviewers.ts): the same model at another effort can be added beside it, and the * same one at the same effort can't be added twice. */ -export function AddModel({ taken, pdfs, onPick, children }: { /** The models on it already, each as its model and effort (./data.ts `modelKey`). */ taken: string[]; /** Its papers that are only a PDF: a pick that can't read them says so before it is made. */ pdfs: Pdfs; onPick: (model: MapModel) => void; children: ReactNode }) { +export function AddModel({ taken, pdfs, onPick, align = "start", width, children }: { /** Which edge of its button the list lines up with: the end, where the button ends its row. */ align?: "start" | "end"; /** How wide the list opens, inside a dialog as wide as the dialog (../models/model-picker.tsx). */ width?: string; /** The models on it already, each as its model and effort (./data.ts `modelKey`). */ taken: string[]; /** Its papers that are only a PDF: a pick that can't read them says so before it is made. */ pdfs: Pdfs; onPick: (model: MapModel) => void; children: ReactNode }) { const t = useTranslations("screening.list"); const tf = useTranslations("screening.form"); const words = useWords(); @@ -157,7 +157,7 @@ export function AddModel({ taken, pdfs, onPick, children }: { /** The models on const picks = presetModel ? PRESET_KEYS.flatMap((id) => { const model = presetModel(id, "screenAll"); return model && !taken.includes(modelKey(model)) ? [{ id, model }] : []; }) : undefined; const presets = picks?.filter((one, at) => picks.findIndex((other) => modelKey(other.model) === modelKey(one.model)) === at).map(({ id, model }) => ({ id, models: [model], onSelect: () => pick(model), ...(missed(model) ? { note: missed(model) } : {}) })); return ( - words.credits(paperCredits(model)) }} align="start" trigger={children} onChange={(model, effort) => pick({ ...model, ...(effort ? { effort } : {}) })} /> + words.credits(paperCredits(model)) }} align={align} {...(width ? { width } : {})} trigger={children} onChange={(model, effort) => pick({ ...model, ...(effort ? { effort } : {}) })} /> ); } diff --git a/components/screening/workspace.tsx b/components/screening/workspace.tsx index 23803d5da..cc83375c4 100644 --- a/components/screening/workspace.tsx +++ b/components/screening/workspace.tsx @@ -518,7 +518,7 @@ function Banner({ kind, open, workspace, onReopen, onResume }: { kind: BannerKin {pieces("modelsSay.credits.says")} - {t("banner.modelPrice", { name: model.name, price: perPaper({ words, t: list }, model.model!) })})}> + {t("banner.modelPrice", { name: model.name, price: perPaper({ words, t: list }, model.model!, model.tally) })})}> {t("banner.creditsHelp", { you: String(open.canChange), workspace })} diff --git a/components/workspaces/activity.tsx b/components/workspaces/activity.tsx index 5d4b1c473..eda8788c2 100644 --- a/components/workspaces/activity.tsx +++ b/components/workspaces/activity.tsx @@ -9,7 +9,7 @@ import { GuestChips, type From } from "./shared"; import { MoveDialog, type Movable } from "./move-dialog"; import { usePaginatedQuery, type UsePaginatedQueryReturnType } from "convex/react"; import { useFormatter, useNow, useTranslations } from "next-intl"; -import { AiIcon, ArrowRight, FileSearch, FolderPlus, History, ListChecks, Move, Pause, PenLine, Play, Plus, RotateCcw, Share2, Square, Star, Trash2, type AppIcon } from "@/components/icons"; +import { AiIcon, ArrowRight, FileSearch, FolderPlus, History, ListChecks, Move, Pause, PenLine, Play, Plus, RotateCcw, Share2, Square, Star, Trash2, Unlink, type AppIcon } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { IdentityAvatar } from "@/components/ui/identity-avatar"; import { PersonTag, YouTag } from "@/components/ui/identity"; @@ -42,6 +42,7 @@ const LOOK: Record stopped: { icon: Square, tint: "#f87171", counted: false }, moved: { icon: ArrowRight, tint: "#fb923c", counted: false }, shared: { icon: Share2, tint: "#60a5fa", counted: false }, + unshared: { icon: Unlink, tint: "#94a3b8", counted: false }, }; /** Changes one page of Activity shows, and each page more. */ @@ -182,7 +183,7 @@ function ActivityRow({ row, now }: { row: Row; now: Date }) { const look = LOOK[row.happened]; const Icon = look.icon; // A renamed item shows the name it had beside the verb, a moved one the workspace it came from, a shared one who it went to; other details sit in a chip under it. - const inline = (row.happened === "renamed" || row.happened === "moved" || row.happened === "shared") && row.detail; + const inline = (row.happened === "renamed" || row.happened === "moved" || row.happened === "shared" || row.happened === "unshared") && row.detail; return (
diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 0b462860f..a3220f19c 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -372,6 +372,7 @@ import type * as migrations_screeningOutcomes from "../migrations/screeningOutco import type * as migrations_screeningPeopleFirst from "../migrations/screeningPeopleFirst.js"; import type * as migrations_screeningReviewers from "../migrations/screeningReviewers.js"; import type * as migrations_screeningSearch from "../migrations/screeningSearch.js"; +import type * as migrations_screeningTitleKeys from "../migrations/screeningTitleKeys.js"; import type * as migrations_searchSuggestions from "../migrations/searchSuggestions.js"; import type * as migrations_searchText from "../migrations/searchText.js"; import type * as migrations_teamLists from "../migrations/teamLists.js"; @@ -484,6 +485,7 @@ import type * as screening_reviewers from "../screening/reviewers.js"; import type * as screening_sampling from "../screening/sampling.js"; import type * as screening_scoring from "../screening/scoring.js"; import type * as screening_screenings from "../screening/screenings.js"; +import type * as screening_seats from "../screening/seats.js"; import type * as screening_sending from "../screening/sending.js"; import type * as screening_settings from "../screening/settings.js"; import type * as screening_settling from "../screening/settling.js"; @@ -932,6 +934,7 @@ declare const fullApi: ApiFromModules<{ "migrations/screeningPeopleFirst": typeof migrations_screeningPeopleFirst; "migrations/screeningReviewers": typeof migrations_screeningReviewers; "migrations/screeningSearch": typeof migrations_screeningSearch; + "migrations/screeningTitleKeys": typeof migrations_screeningTitleKeys; "migrations/searchSuggestions": typeof migrations_searchSuggestions; "migrations/searchText": typeof migrations_searchText; "migrations/teamLists": typeof migrations_teamLists; @@ -1044,6 +1047,7 @@ declare const fullApi: ApiFromModules<{ "screening/sampling": typeof screening_sampling; "screening/scoring": typeof screening_scoring; "screening/screenings": typeof screening_screenings; + "screening/seats": typeof screening_seats; "screening/sending": typeof screening_sending; "screening/settings": typeof screening_settings; "screening/settling": typeof screening_settling; diff --git a/convex/activity/validators.ts b/convex/activity/validators.ts index 7f3632707..ba8bdafd7 100644 --- a/convex/activity/validators.ts +++ b/convex/activity/validators.ts @@ -9,7 +9,7 @@ export const itemKindValidator = v.union(...itemKinds.map((kind) => v.literal(ki export type ItemKind = Infer; /** What happened to it. */ -export const activityKinds = ["created", "renamed", "edited", "added", "removed", "rated", "answered", "screened", "extracted", "paused", "resumed", "retried", "stopped", "moved", "shared"] as const; +export const activityKinds = ["created", "renamed", "edited", "added", "removed", "rated", "answered", "screened", "extracted", "paused", "resumed", "retried", "stopped", "moved", "shared", "unshared"] as const; export const activityKindValidator = v.union(...activityKinds.map((kind) => v.literal(kind))); /** diff --git a/convex/lib/triggers.ts b/convex/lib/triggers.ts index 2dca51030..855a6cab1 100644 --- a/convex/lib/triggers.ts +++ b/convex/lib/triggers.ts @@ -19,6 +19,7 @@ import { countAnswerChange, countPaperChange as countPaperFacets } from "../extr import { tallyAnswerChange } from "../extraction/tallies"; import { adminText, jobText, keepSearchText, keepTextOfUser, memberText, searchText, shortcutText } from "./searchText"; import { keepCard } from "../screening/cards"; +import { takeVotingSeat } from "../screening/seats"; import { countPaperFacets as countScreeningPaper, countVoteFacets as countScreeningVote } from "../screening/facets"; import { ADMIN_LIST, countList, libraryVersionList, personWaitingApplicationsOf, screeningFileList, screeningList, waitingApplicationsOf, walletKeyList, workspaceLibrariesOf } from "./listCounts"; import { followShared, itemGuestsOf, sharedWithOf } from "../sharing/items"; @@ -105,11 +106,15 @@ triggers.register("screeningVotes", countScreeningVote); triggers.register("itemAccess", async (ctx, change) => { const grant = change.newDoc ?? change.oldDoc; if (grant.kind !== "screening" || (change.operation === "update" && change.oldDoc.role === change.newDoc.role)) return; + // One given it to vote takes a reviewer's place now, or is refused: never "Can vote" with no queue. + if (change.newDoc?.role === "editor") await takeVotingSeat(ctx, grant.item); await ctx.scheduler.runAfter(0, makeFunctionReference<"mutation", { item: string; userId: Id<"users"> }, null>("screening/reviewers:guestChanged"), { item: grant.item, userId: grant.userId }); }); // An invitation to vote on a screening that stops waiting: the papers that waited for its person are settled again (../screening/settings.ts `follow`). Accepted, its person is a reviewer by then (`guestChanged`, scheduled first) and is given the places; declined or cancelled, they are settled without them; and accepted by someone who had joined the workspace meanwhile, who isn't made a reviewer, likewise. triggers.register("itemInvitations", async (ctx, change) => { const waits = (one: Doc<"itemInvitations"> | null) => one?.kind === "screening" && one.state === "pending" && one.role === "editor"; + // An invitation to vote holds a reviewer's place from when it is sent (./screening/seats.ts). + if (waits(change.newDoc) && !waits(change.oldDoc)) await takeVotingSeat(ctx, change.newDoc!.item, change.newDoc!.email); if (!waits(change.oldDoc) || waits(change.newDoc)) return; await ctx.scheduler.runAfter(0, makeFunctionReference<"mutation", { jobId: string; cursor: null; results: Array<"waiting">; recheck: boolean; stricter: string[]; reread: boolean }, null>("screening/settings:follow"), { jobId: change.oldDoc!.item, cursor: null, results: ["waiting"], recheck: false, stricter: [], reread: false }); }); diff --git a/convex/migrations/screeningTitleKeys.ts b/convex/migrations/screeningTitleKeys.ts new file mode 100644 index 000000000..05807f006 --- /dev/null +++ b/convex/migrations/screeningTitleKeys.ts @@ -0,0 +1,28 @@ +import { Migrations } from "@convex-dev/migrations"; +import { components, internal } from "../_generated/api"; +import type { DataModel } from "../_generated/dataModel"; +import { internalMutation } from "../lib/functions"; +import { titleKeyOf } from "../screening/checks"; + +/** + * Works out again the title key each screening paper is matched on (../screening/checks.ts `titleKeyOf`), since it + * keeps the marks of scripts other than Latin, Greek and Cyrillic: a paper whose title has them is found by a later + * record of it, and two papers whose titles differ only by them stay two. Safe to run again: a paper whose key is + * right is passed over. + * + * npx convex run migrations/screeningTitleKeys:run '{"dryRun": true}' + * npx convex run migrations/screeningTitleKeys:run + */ +const migrations = new Migrations(components.migrations, { internalMutation }); + +export const papers = migrations.define({ + table: "screeningResults", + batchSize: 200, + migrateOne: (_ctx, paper) => { + if (paper.titleKey === undefined) return; + const titleKey = titleKeyOf(paper.title, paper.publicationYear); + return titleKey === paper.titleKey ? undefined : { titleKey }; + }, +}); + +export const run = migrations.runner(internal.migrations.screeningTitleKeys.papers); diff --git a/convex/schema.ts b/convex/schema.ts index 35c91c276..38d8162f2 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -1364,6 +1364,8 @@ export default defineSchema({ paused: v.optional(v.literal(true)), // When its settings last changed without its settled papers being checked again: a paper settled by then keeps its result (convex/screening/settling.ts). heldAt: v.optional(v.number()), + // A draft let go of (replaced, discarded or left a week), its rows being deleted: no form takes it up again, whatever reaches it before the last of them goes. + erasing: v.optional(v.literal(true)), // When something last happened in it, to within a minute: what its list orders by. activeAt: v.optional(v.number()), createdAt: v.number(), diff --git a/convex/screening/dealing.ts b/convex/screening/dealing.ts index 1d390ef11..6a330d328 100644 --- a/convex/screening/dealing.ts +++ b/convex/screening/dealing.ts @@ -87,11 +87,10 @@ 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)); -/** 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; +/** How many of the papers a check brought still wait for one reviewer's vote: kept counts (./facets.ts), however many it brought. */ +export async function newFor(ctx: QueryCtx, reviewerId: Id<"screeningReviewers">, check: Pick, "_id">) { + const tally = await tallyOfReviewer(ctx, reviewerId, ["waiting"], { check: check._id }); + return tally.include + tally.maybe + tally.exclude + tally.conflict + tally.waiting; } /** Checks of its sources looked through for the last that brought papers. */ diff --git a/convex/screening/effects.ts b/convex/screening/effects.ts index 014423b60..5a87a3071 100644 --- a/convex/screening/effects.ts +++ b/convex/screening/effects.ts @@ -88,10 +88,10 @@ export const step = internalQuery({ } const was: Result = paper.result ?? "waiting"; const thrown = before.some((place) => discards.get(place.reviewer) && place.status === "cast"); - // As the save leaves them: the votes of a reviewer taken off stay unless they are thrown out, the models answer a new criterion on the papers still open, and whoever joins takes their share of the places nobody voted from. + // As the save leaves them: the votes of a reviewer taken off stay unless they are thrown out, the models answer a new criterion on the papers still open and on those checked again, and whoever joins takes their share of the places nobody voted from. const left = before.map((place): Place => { if (discards.get(place.reviewer) && place.status === "cast") return { ...place, status: "discarded" }; - if (plan.added.length && !isFinal(was) && place.status === "cast" && readers.includes(place.reviewer)) return { ...place, status: "waiting" }; + if (plan.added.length && job.finishedAt === undefined && (recheck || !isFinal(was)) && place.status === "cast" && readers.includes(place.reviewer)) return { ...place, status: "waiting" }; return place; }); const places = withJoined({ id: paper._id, result: was }, left, joiners, plan.rule.each === "all"); diff --git a/convex/screening/gathering.ts b/convex/screening/gathering.ts index e451fb837..8e0695d23 100644 --- a/convex/screening/gathering.ts +++ b/convex/screening/gathering.ts @@ -102,15 +102,16 @@ export const begin = internalMutation({ /** 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"), pass: v.number(), run: v.optional(v.number()), reason: v.optional(v.string()) }, + args: { checkId: v.id("screeningChecks"), sourceId: v.id("screeningSources"), pass: v.number(), run: v.optional(v.number()), /** How far into the source the failed step began. */ from: v.optional(v.number()), reason: v.optional(v.string()) }, returns: v.null(), - handler: async (ctx, { checkId, sourceId, pass, run, reason }) => { - // A reading of the source from before it was changed fails nothing: the source is being read again. Nor does a reader the check has moved past. - if (((await ctx.db.get("screeningSources", sourceId))?.pass ?? 0) !== pass) return null; - if (run !== undefined && ((await ctx.db.get("screeningChecks", checkId))?.run ?? 0) !== run) return null; + handler: async (ctx, { checkId, sourceId, pass, run, from, reason }) => { + // Only the reading going on now fails the source: never one from before it was changed (it is being read again), a reader the check has moved past, one + // of a check that has ended, or a second reader of a step the first has taken in since. + const [source, check] = await Promise.all([ctx.db.get("screeningSources", sourceId), ctx.db.get("screeningChecks", checkId)]); + if (!source || !check || check.state !== "running" || (source.pass ?? 0) !== pass || (source.state !== "waiting" && source.state !== "reading")) return null; + if ((run !== undefined && (check.run ?? 0) !== run) || (from !== undefined && source.read !== from)) 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) }); + if (!check.unread?.includes(sourceId)) await ctx.db.patch("screeningChecks", checkId, { unread: [...(check.unread ?? []), sourceId].slice(-MAX_SOURCE_ROWS) }); return null; }, }); @@ -146,7 +147,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, pass: source.pass, run: source.run, ...(readConvexErrorData(error)?.message ? { reason: readConvexErrorData(error)!.message } : {}) }); + await ctx.runMutation(internal.screening.gathering.fail, { checkId, sourceId: source.sourceId, pass: source.pass, run: source.run, from: source.read, ...(readConvexErrorData(error)?.message ? { reason: readConvexErrorData(error)!.message } : {}) }); } } }, @@ -167,8 +168,6 @@ export const beat = internalMutation({ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Reading): Promise<"wait" | void> { const { sourceId, set } = source; const reader = { userId: source.userId, workspaceId: source.workspaceId }; - // Where the source stands as this step hands its papers in: a step that hands them in parts (a Zotero library's) moves it on with each. - let handedTo = source.read; const give = async (papers: SearchPaper[], read: number, ended: boolean, resume?: string, leftOut?: LeftOut[]) => { // A paper that came with no abstract takes the one OpenAlex holds, and failing that the one registered under its DOI, whichever source brought it. A PDF's was asked for when the file was first read (./heldPdfs.ts): it comes with what that found. const bare = set.kind !== "pdf" && papers.some((paper) => !paper.abstract?.trim()); @@ -179,14 +178,13 @@ 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, pass: source.pass, run: source.run, from: handedTo, 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, run: source.run, from: source.read, 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; } catch (error) { if (readConvexErrorData(error) || tries >= FILL_TRIES) throw error; await new Promise((wait) => setTimeout(wait, 500 * 2 ** tries)); } } } - handedTo += read; }; const held = set.kind === "upload" || set.kind === "dois" || set.kind === "pdf" ? { ...source, set } : null; if (source.state === "waiting") { @@ -249,14 +247,9 @@ async function step(ctx: ActionCtx, checkId: Id<"screeningChecks">, source: Read const files: Array<{ key: string; file: Id<"_storage">; pages: number; shape?: number }> = fresh.length ? await ctx.runAction(internal.zotero.actions.pdfsOf, { userId: source.userId, ...(set.groupId ? { groupId: set.groupId } : {}), itemKeys: [...new Set(bare.filter((one) => fresh.includes(one.paper)).map((one) => one.key))] }) : []; return read.map(({ key, ...paper }) => { const own = files.find((one) => one.key === key); return own ? { ...paper, file: own.file, pages: own.pages, ...(own.shape ? { shape: own.shape } : {}) } : paper; }); }; - // A step's papers go to `fill` a step of an index's at a time, the reading's end with the last of them. - // Where the reading goes on is kept with the last of them only: one cut short before that reads these collections again, and the papers it gave already are passed over. - const hand = async (papers: SearchPaper[], ended: boolean, resume?: string) => { - for (let at = 0; at === 0 || at < papers.length; at += READ_STEP) { - const lastOne = at + READ_STEP >= papers.length; - await give(papers.slice(at, at + READ_STEP), Math.min(READ_STEP, papers.length - at), ended && lastOne, lastOne ? resume : source.resume); - } - }; + // A step's papers go to `fill` together: how far the reading got and where it goes on in the tree move with the last of them only, so one cut short + // before that reads these collections again from where the source stands, and the papers it gave already are passed over. + const hand = (papers: SearchPaper[], ended: boolean, resume?: string) => give(papers, papers.length, ended, resume); const room = last - from + 1; /** How many of these papers one step takes: as far as the room left, and no more with no abstract than one call fetches the PDFs of. */ const within = (papers: Array<{ key: string; abstract?: string }>) => { diff --git a/convex/screening/living.ts b/convex/screening/living.ts index e3723f286..9f01683f3 100644 --- a/convex/screening/living.ts +++ b/convex/screening/living.ts @@ -136,6 +136,9 @@ export const due = internalMutation({ }); /** What a check that has ended leaves behind: its note in the screening's activity, an email to the people the new papers went to, and a finished screening open again. */ +/** How long after a check its email waits: the papers it brought are counted by then (./facets.ts, a moment behind), so the email names them all. */ +const PAPERS_AFTER_MS = 60_000; + export async function checked(ctx: MutationCtx, job: Doc<"screeningJobs">, check: Doc<"screeningChecks">) { // The look it started with says nothing: it is the screening starting. A later look from no papers (one that started empty) is a check like any other, and reopens it. if ((await firstCheck(ctx, job._id))?._id === check._id) return; @@ -151,6 +154,6 @@ export async function checked(ctx: MutationCtx, job: Doc<"screeningJobs">, check 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 && reviewer.userId !== check.by) 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(PAPERS_AFTER_MS, internal.screening.noticeMail.send, { jobId: job._id, userId: reviewer.userId, about: "papers" }); } } diff --git a/convex/screening/noticeMail.ts b/convex/screening/noticeMail.ts index dfa4fe944..876d2737e 100644 --- a/convex/screening/noticeMail.ts +++ b/convex/screening/noticeMail.ts @@ -21,7 +21,7 @@ export const send = internalAction({ return null; } try { - await sendInvitationEmail(requireInvitationMail(), { senderName: "Openscholar", to: notice.email, ...screeningNoticeMessage({ origin: requireAppUrl(), path: notice.path, name: notice.name, about: args.about, count: notice.count, ...(notice.more ? { more: true } : {}), ...(notice.finished ? { finished: true } : {}), ...(notice.living ? { living: true } : {}), ...(notice.by ? { by: notice.by } : {}) }) }); + await sendInvitationEmail(requireInvitationMail(), { senderName: "Openscholar", to: notice.email, ...screeningNoticeMessage({ origin: requireAppUrl(), path: notice.path, name: notice.name, about: args.about, count: notice.count, ...(notice.finished ? { finished: true } : {}), ...(notice.living ? { living: true } : {}), ...(notice.by ? { by: notice.by } : {}) }) }); } catch (error) { // An email that didn't go changes nothing in the screening: what it said is on its page. console.error("Screening email failed", { jobId: args.jobId, about: args.about, error }); diff --git a/convex/screening/notices.ts b/convex/screening/notices.ts index 54f0d1d11..c389101ce 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, NEW_COUNTED, newFor, waitsOn } from "./dealing"; +import { laterChecks, nameOf, 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")); @@ -50,7 +50,7 @@ export const conflictsUnsent = internalMutation({ /** What one email says, read when it is sent: null where the person turned the screening's emails off, has it no more, or nothing waits for them. */ export const context = internalQuery({ args: { jobId: v.id("screeningJobs"), userId: v.id("users"), about: aboutValidator, by: v.optional(v.id("users")) }, - returns: v.union(v.null(), v.object({ email: v.string(), name: v.string(), path: v.string(), count: v.number(), more: v.optional(v.boolean()), finished: v.optional(v.boolean()), living: v.optional(v.boolean()), by: v.optional(v.string()) })), + returns: v.union(v.null(), v.object({ email: v.string(), name: v.string(), path: v.string(), count: v.number(), finished: v.optional(v.boolean()), living: v.optional(v.boolean()), by: v.optional(v.string()) })), handler: async (ctx, { jobId, userId, about, by }) => { const [job, user, row] = await Promise.all([ctx.db.get("screeningJobs", jobId), ctx.db.get("users", userId), noticeOf(ctx, jobId, userId)]); // A finished screening sends nothing, except to someone just given it to vote on: they are told it is theirs once reopened. @@ -75,7 +75,7 @@ export const context = internalQuery({ // 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; const sender = by ? await ctx.db.get("users", by) : null; - return { email: user.email, name: job.name ?? "Screening", path: `${member && organization ? `/o/${organization.slug}` : ""}${screeningPath(jobId)}`, count, ...(about === "papers" && count >= NEW_COUNTED ? { more: true } : {}), ...(finished ? { finished: true } : {}), ...(job.living ? { living: true } : {}), ...(sender ? { by: nameOf(sender) } : {}) }; + return { email: user.email, name: job.name ?? "Screening", path: `${member && organization ? `/o/${organization.slug}` : ""}${screeningPath(jobId)}`, count, ...(finished ? { finished: true } : {}), ...(job.living ? { living: true } : {}), ...(sender ? { by: nameOf(sender) } : {}) }; }, }); diff --git a/convex/screening/paperViews.ts b/convex/screening/paperViews.ts index a66669a49..7f23637ec 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.edited ?? 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.edited && vote.at ? { castAt: vote.at } : {}), ...(vote.flagged ? { flagged: true } : {}), ...(vote.confidences ? { confidences: vote.confidences } : {}), ...(vote.passages ? { passages: vote.passages } : {}) }; } /** diff --git a/convex/screening/readings.ts b/convex/screening/readings.ts index c455aa108..96452b2b6 100644 --- a/convex/screening/readings.ts +++ b/convex/screening/readings.ts @@ -104,7 +104,8 @@ export const done = screeningPool.defineOnComplete({ await startWaitingVotes(ctx, job.workspaceId, vote.slot ? 1 : 0); } else if (reading?.read && vote.status === "waiting") { // Its decision follows its answers: the worker reads it from them as it settles the paper (lib/screening/project.ts `ballotOf`). - await ctx.db.patch("screeningVotes", vote._id, { status: "cast", answers: reading.answers, confidences: reading.confidences, passages: reading.passages, at: reading.askedAt ?? Date.now(), credits: (vote.credits ?? 0) + reading.credits, workId: undefined, error: undefined }); + // It is cast when it comes back, never when it was asked: under "first vote decides" a slower reading started earlier never overturns a vote cast before it. + await ctx.db.patch("screeningVotes", vote._id, { status: "cast", answers: reading.answers, confidences: reading.confidences, passages: reading.passages, at: Date.now(), credits: (vote.credits ?? 0) + reading.credits, workId: undefined, error: undefined }); } else if ((result.kind === "failed" || (reading && !reading.read && reading.why === "unreadable")) && vote.status === "waiting") { await ctx.db.patch("screeningVotes", vote._id, { status: "failed", error: (result.kind === "failed" ? result.error : (reading as { error: string }).error).slice(0, ERROR_SHOWN), workId: undefined }); } else { diff --git a/convex/screening/reviewers.ts b/convex/screening/reviewers.ts index 198f1bad4..e8c582b37 100644 --- a/convex/screening/reviewers.ts +++ b/convex/screening/reviewers.ts @@ -49,6 +49,12 @@ const JOINED_AFTER_MS = 2 * 60_000; /** How soon after a screening is made the form's own shares arrive (components/screening/screening-form.tsx `outside`). */ const FROM_THE_START = 60_000; +/** + * Holds the papers settled so far at their results: a change of who reviews (a person or a model added or taken + * off, wherever it is made) never sends a paper back for votes it was settled without (./settling.ts `held`). + */ +export const holdSettled = (ctx: MutationCtx, jobId: Id<"screeningJobs">) => ctx.db.patch("screeningJobs", jobId, { heldAt: Date.now() }); + export async function addPerson(ctx: MutationCtx, job: Doc<"screeningJobs">, userId: Id<"users">, by: Id<"users">, { tell = false }: { /** A colleague put them on it: an email says so, with the papers that wait for them once their share is given out. */ tell?: boolean } = {}) { const reviewers = await reviewersOf(ctx, job._id); const before = reviewers.filter(dealable).length; @@ -59,6 +65,7 @@ export async function addPerson(ctx: MutationCtx, job: Doc<"screeningJobs">, use const addedAt = Date.now() - job.createdAt < FROM_THE_START ? job.createdAt : Date.now(); const reviewerId = old?._id ?? (await ctx.db.insert("screeningReviewers", { jobId: job._id, kind: "person", userId, addedAt, addedBy: by, dealt: 0 })); if (old) await ctx.db.patch("screeningReviewers", old._id, { left: undefined, discarded: undefined }); + await holdSettled(ctx, job._id); await ctx.scheduler.runAfter(0, internal.screening.reviewers.join, { jobId: job._id, reviewerId, before, cursor: null, result: "waiting" }); if (tell && by !== userId) await ctx.scheduler.runAfter(JOINED_AFTER_MS, internal.screening.noticeMail.send, { jobId: job._id, userId, about: "joined", by }); return reviewerId; @@ -152,6 +159,7 @@ export async function takeOff(ctx: MutationCtx, job: Doc<"screeningJobs">, revie const grant = reviewer.userId ? await grantOf(ctx, job._id, reviewer.userId) : null; if (grant?.role === "editor") await ctx.db.patch("itemAccess", grant._id, { role: "viewer" }); await ctx.db.patch("screeningReviewers", reviewer._id, { left: now, discarded: discard ? now : undefined }); + await holdSettled(ctx, job._id); const rule = job.rule; let settler: Id<"users"> | undefined = settlerNow; if (rule && reviewer.kind === "person" && rule.resolver === reviewer.userId) { @@ -181,6 +189,7 @@ export async function addModel(ctx: MutationCtx, job: Doc<"screeningJobs">, mode if (!old && reviewers.length >= MAX_REVIEWERS) throw createError("VALIDATION_ERROR", `A screening has up to ${MAX_REVIEWERS} reviewers.`); const reviewerId = old?._id ?? (await ctx.db.insert("screeningReviewers", { jobId: job._id, kind: "model", modelId: picked._id, ...(model.effort ? { effort: model.effort } : {}), addedAt: Date.now(), addedBy: by, dealt: 0 })); if (old) await ctx.db.patch("screeningReviewers", old._id, { left: undefined, discarded: undefined }); + await holdSettled(ctx, job._id); await ctx.scheduler.runAfter(0, internal.screening.reviewers.enlist, { jobId: job._id, reviewerId, cursor: null, result: "waiting" }); return picked; } diff --git a/convex/screening/screenings.ts b/convex/screening/screenings.ts index 606c3a9cd..7d744d9fa 100644 --- a/convex/screening/screenings.ts +++ b/convex/screening/screenings.ts @@ -123,9 +123,15 @@ const sameSource = (row: Doc<"screeningSources">, sent: Infer) { + await ctx.db.patch("screeningJobs", jobId, { erasing: true }); + await ctx.scheduler.runAfter(0, internal.screening.screenings.erase, { jobId }); +} + async function draftOf(ctx: Pick, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, jobId: Id<"screeningJobs"> | undefined) { const job = jobId ? await ctx.db.get("screeningJobs", jobId) : null; - return job?.status === "draft" && job.createdBy === actor.userId && job.workspaceId === actor.workspaceId ? job : null; + return job?.status === "draft" && !job.erasing && job.createdBy === actor.userId && job.workspaceId === actor.workspaceId ? job : null; } /** @@ -155,7 +161,7 @@ export const sync = workspaceMutation({ } return { jobId: was._id, sources: [...rows.map((row) => row._id), ...added] }; } - if (was) await ctx.scheduler.runAfter(0, internal.screening.screenings.erase, { jobId: was._id }); + if (was) await letGo(ctx, was._id); if (!sources.length) return null; const stars = starsFrom(undefined, 0); const jobId = await ctx.db.insert("screeningJobs", { @@ -217,7 +223,7 @@ export const sweepDrafts = internalMutation({ returns: v.null(), handler: async (ctx) => { const old = await ctx.db.query("screeningJobs").withIndex("by_status_and_updatedAt", (q) => q.eq("status", "draft").lt("updatedAt", Date.now() - DRAFT_KEPT_MS)).take(DRAFTS_A_SWEEP); - for (const job of old) await ctx.scheduler.runAfter(0, internal.screening.screenings.erase, { jobId: job._id }); + for (const job of old) if (!job.erasing) await letGo(ctx, job._id); return null; }, }); @@ -280,7 +286,7 @@ export const open = internalMutation({ const read = await draftOf(ctx, writer, draft); const rows = read ? await sourcesOf(ctx, read._id) : []; const adopted = read && rows.length === sources.length && rows.every((row, at) => sameSource(row, sources[at]!)) ? read : null; - if (read && !adopted) await ctx.scheduler.runAfter(0, internal.screening.screenings.erase, { jobId: read._id }); + if (read && !adopted) await letGo(ctx, read._id); const jobId = adopted?._id ?? (await ctx.db.insert("screeningJobs", { workspaceId, createdBy: user._id, totalPapers: 0, reading: true, shape: 2, screeningId: await ctx.db.insert("screenings", { workspaceId, version: 0, createdAt: now }), ...settings })); if (adopted) await ctx.db.patch("screeningJobs", jobId, settings); else { diff --git a/convex/screening/seats.ts b/convex/screening/seats.ts new file mode 100644 index 000000000..555786750 --- /dev/null +++ b/convex/screening/seats.ts @@ -0,0 +1,30 @@ +/** + * A place on a screening for someone it is shared with to vote: taken when they are invited by email or given it by + * name, so a "Can vote" never leaves its guest without a queue. Each is a reviewer to come, counted against the most a + * screening has (people and models who left it included, whose votes it keeps), and a change of who reviews: the + * papers settled so far keep their results (./reviewers.ts `holdSettled`). + * + * This module holds no Convex functions, so the triggers can load it. + */ +import type { Id } from "../_generated/dataModel"; +import type { MutationCtx } from "../_generated/server"; +import { createError } from "../lib/errors"; +import { MAX_REVIEWERS } from "./validators"; + +export async function takeVotingSeat(ctx: MutationCtx, item: string, /** The address an invitation went to: someone who reviewed it before comes back to their own place. */ email?: string) { + const jobId = ctx.db.normalizeId("screeningJobs", item); + const job = jobId ? await ctx.db.get("screeningJobs", jobId) : null; + if (!job || job.shape !== 2) return; + const reviewers = await ctx.db.query("screeningReviewers").withIndex("by_job", (q) => q.eq("jobId", job._id)).take(MAX_REVIEWERS); + const on = new Set(reviewers.flatMap((one) => (one.userId ? [one.userId] : []))); + const now = Date.now(); + // The addresses of those who reviewed it: an invitation to one of them brings them back to their own place, and takes no other. + const theirs = new Set((await Promise.all([...on].map((userId) => ctx.db.get("users", userId)))).flatMap((one) => (one?.email ? [one.email.toLowerCase()] : []))); + const returning = email !== undefined && theirs.has(email.toLowerCase()); + // The places to come: invitations to vote still waiting, and guests let vote whose place the reviewers' worker hasn't made yet. An invitation just + // answered is no longer waiting, and its guest is counted once, by their grant. Read in the transaction that takes the place, so two never take the last. + const waiting = (await ctx.db.query("itemInvitations").withIndex("by_item_and_state", (q) => q.eq("item", item).eq("state", "pending")).take(MAX_REVIEWERS)).filter((one) => one.role === "editor" && one.expiresAt > now && !theirs.has(one.email.toLowerCase())); + const given = (await ctx.db.query("itemAccess").withIndex("by_item_and_grantedAt", (q) => q.eq("item", item)).take(MAX_REVIEWERS)).filter((one) => one.role === "editor" && !on.has(one.userId as Id<"users">)); + if (!returning && reviewers.length + waiting.length + given.length > MAX_REVIEWERS) throw createError("VALIDATION_ERROR", `A screening has up to ${MAX_REVIEWERS} reviewers, people and models who left it included. Invite them to look at it instead.`); + await ctx.db.patch("screeningJobs", job._id, { heldAt: now }); +} diff --git a/convex/screening/settings.ts b/convex/screening/settings.ts index 6ffe2440e..4c778d50c 100644 --- a/convex/screening/settings.ts +++ b/convex/screening/settings.ts @@ -12,7 +12,7 @@ import { queueLibraryWrite } from "../evidenceLibraries/writes"; import { createError } from "../lib/errors"; import { internalMutation } from "../lib/functions"; import { screeningDestination } from "../library/collections"; -import { workspaceAction, workspaceMutation } from "../lib/userActions"; +import { workspaceAction, workspaceMutation, workspaceQuery } from "../lib/userActions"; import { actorIn } from "../workspaces/actor"; import { type Criterion } from "../../lib/screening/rules"; import { requireMember } from "./access"; @@ -157,10 +157,14 @@ export const saveSent = internalMutation({ handler: (ctx, { userId, workspaceId, jobId, change, libraryDestination }) => apply(ctx, { userId, workspaceId }, jobId, change, libraryDestination), }); -async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId: Id<"workspaces">; author?: "user" | "assistant" }, jobId: Id<"screeningJobs">, change: Change, libraryDestination?: Infer): Promise { +/** + * Everything a save checks before it changes anything, read only: the form asks it first (`check`), so nothing it sends + * or gives (an invitation, a guest's place, a community's collection) goes out for a save that would then be refused. + * `libraryDestination` "unasked": the community's collection isn't checked or made yet. + */ +async function validate(ctx: QueryCtx, actor: { userId: Id<"users">; workspaceId: Id<"workspaces"> }, jobId: Id<"screeningJobs">, change: Change, libraryDestination?: Infer | "unasked") { const job = await requireMember(ctx, actor, jobId); const plan = await planned(ctx, job, change); - const now = Date.now(); const name = change.name?.trim(); if (change.name !== undefined && (!name || name.length > SCREENING_TEXT.name)) throw createError("VALIDATION_ERROR", "Give the screening a name of up to 200 characters."); if ((change.question?.length ?? 0) > SCREENING_TEXT.question) throw createError("VALIDATION_ERROR", "That research question is too long."); @@ -171,11 +175,27 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId const writer = { userId: actor.userId, workspaceId: job.workspaceId }; const later = change.saveTo?.kind === "new" ? change.saveTo.name.trim() : undefined; // A community's collection is checked, or made, before the save (`saveToCommunity`). - if (toCommunity(change.saveTo) !== Boolean(libraryDestination)) throw createError("VALIDATION_ERROR", "Pick the collection its included papers go to again."); + if (libraryDestination !== "unasked" && toCommunity(change.saveTo) !== Boolean(libraryDestination)) throw createError("VALIDATION_ERROR", "Pick the collection its included papers go to again."); const prune = change.prune ?? job.prune === true; // Checked against the sources as the save leaves them: those it takes out don't count, and those it adds do. const canTake = (set: (typeof sources)[number]["set"]) => prunable(set.kind === "upload" || set.kind === "pdf" || set.kind === "dois" ? undefined : set); if (prune && !sources.some((source) => source.removedAt === undefined && !change.removeSources?.includes(source._id) && canTake(source.set)) && !(change.addSources ?? []).some((source) => canTake(source.set as (typeof sources)[number]["set"]))) throw createError("VALIDATION_ERROR", "Only a collection's papers can leave it."); + return { job, plan, name, sources, writer, later }; +} + +/** Whether a save would be taken as it is, without making it: refused with the save's own reason where it wouldn't. */ +export const checkChange = workspaceQuery({ + args: { jobId: v.id("screeningJobs"), change: changeValidator }, + returns: v.null(), + handler: async (ctx, actor, { jobId, change }) => { + await validate(ctx, actor, jobId, change, "unasked"); + return null; + }, +}); + +async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId: Id<"workspaces">; author?: "user" | "assistant" }, jobId: Id<"screeningJobs">, change: Change, libraryDestination?: Infer): Promise { + const { job, plan, name, sources, writer, later } = await validate(ctx, actor, jobId, change, libraryDestination); + const now = Date.now(); // Settled papers keep their result from here on, unless this save checks them again: said before any paper is stamped, so the worker holds them. await ctx.db.patch("screeningJobs", jobId, { @@ -186,7 +206,8 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId ...(change.living !== undefined ? { living: change.living ? { every: change.living, next: now + EVERY_MS[change.living] } : undefined } : {}), ...(change.saveTo ? { targetCollectionId: undefined, newCollection: undefined, unsaved: undefined, libraryDestination, libraryWriteProblem: undefined, libraryPruneProblem: undefined, ...(later ? { newCollection: later } : await screeningDestination(ctx, writer, change.saveTo)) } : {}), ...(change.prune !== undefined ? { prune: change.prune ? (true as const) : undefined } : {}), - ...(plan.decides && !change.recheck ? { heldAt: now } : {}), + // Settled papers keep their results through any save that doesn't check them again: one that only re-scores them, or takes out a source another still holds, moves none back for votes. + ...(!change.recheck ? { heldAt: now } : {}), ...touched(now), }); const saved = (await ctx.db.get("screeningJobs", jobId))!; @@ -227,7 +248,7 @@ async function apply(ctx: MutationCtx, actor: { userId: Id<"users">; workspaceId // What follows on its papers, a step at a time: the open ones are settled again under the new settings, with people's votes marked where a criterion became a must-have and the models reading again where one was added. if (plan.decides || change.recheck || plan.added.length || plan.stricter.length || plan.rescores) { - await ctx.scheduler.runAfter(0, internal.screening.settings.follow, { jobId, cursor: null, results: change.recheck || plan.rescores ? ["waiting", "conflict", "include", "maybe", "exclude"] : ["waiting", "conflict"], recheck: change.recheck === true, stricter: plan.stricter, reread: plan.added.length > 0 }); + await ctx.scheduler.runAfter(0, internal.screening.settings.follow, { jobId, cursor: null, results: change.recheck || plan.rescores ? ["waiting", "conflict", "include", "maybe", "exclude"] : ["waiting", "conflict"], recheck: change.recheck === true, stricter: [...plan.stricter, ...(change.recheck ? plan.added.filter((criterion) => criterion.must).map((criterion) => criterion.key) : [])], reread: plan.added.length > 0 }); } // The papers it has included go to a collection it is newly sent to. if (change.saveTo && change.saveTo.kind !== "none") await ctx.scheduler.runAfter(0, internal.screening.settings.shelveIncluded, { jobId, cursor: null }); @@ -250,9 +271,9 @@ const resultValidator = v.union(v.literal("waiting"), v.literal("conflict"), v.l /** * What a save does to a screening's papers, a step at a time: each paper of the results it names is stamped for the * bookkeeping worker, which settles it under the settings as they are now. With `recheck`, a settled paper lets go of - * its result first. Where a criterion became a must-have, the votes people cast on the papers still open are marked - * for a new one, unless they exclude already. Where a criterion was added, the models that read an open paper read it - * again, to answer it. + * its result first. Where a criterion became a must-have, the votes people cast on the papers still open, and on those + * checked again, are marked for a new one, unless they exclude already or answered it Yes. Where a criterion was added, + * the models that read those papers read them again, to answer it. */ export const follow = internalMutation({ args: { jobId: v.id("screeningJobs"), cursor: v.union(v.string(), v.null()), results: v.array(resultValidator), recheck: v.boolean(), stricter: v.array(v.string()), reread: v.boolean() }, @@ -266,11 +287,15 @@ export const follow = internalMutation({ const page = await ctx.db.query("screeningResults").withIndex("by_job_and_result", (q) => q.eq("jobId", jobId).eq("result", result)).paginate({ cursor, numItems: papersAStep(reviewers.size, FOLLOW) }); let queued = 0; for (const paper of page.page) { - if (open && (stricter.length || reread)) { + // A settled paper checked again is asked again as an open one is: the models answer a new criterion on it, and a person's vote is asked for anew. + // A finished screening asks nobody: its models read nothing until it is reopened, and a vote cleared now would never be cast again. + if ((open || recheck) && (stricter.length || reread) && job.finishedAt === undefined) { for (const vote of await votesOf(ctx, paper._id)) { const reviewer = reviewers.get(vote.reviewerId); if (vote.status !== "cast" || !reviewer) continue; - if (reviewer.kind === "person" && stricter.length && vote.decision !== "exclude" && !vote.flagged) await ctx.db.patch("screeningVotes", vote._id, { flagged: true }); + // A vote whose answers already meet each new must-have stands as it is: nobody is asked what they answered Yes to. + const meets = stricter.every((key) => (vote.answers as Record | undefined)?.[key] === "yes"); + if (reviewer.kind === "person" && stricter.length && vote.decision !== "exclude" && !vote.flagged && !meets) await ctx.db.patch("screeningVotes", vote._id, { flagged: true }); if (reviewer.kind === "model" && reread && readingModel(reviewer)) { await ctx.db.patch("screeningVotes", vote._id, { ...modelRow(job, paper, reviewer), decision: undefined, answers: undefined, confidences: undefined, passages: undefined, reason: undefined, at: undefined }); queued++; diff --git a/convex/screening/settling.test.ts b/convex/screening/settling.test.ts index 583af4a97..24f1ce309 100644 --- a/convex/screening/settling.test.ts +++ b/convex/screening/settling.test.ts @@ -591,8 +591,12 @@ describe("a vote asked for again", () => { 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 }); + await made.as.ann!.mutation(api.screening.voting.vote, { workspaceId: made.workspaceId, jobId, paperId, decision: "include", answered: { key, answer: "yes" } }); expect(await flagged()).toBe(true); + // An answer to another criterion, from another tab that never saw the first, joins it: neither takes the other's place. + const other = criteria[1]!.key; + await made.as.ann!.mutation(api.screening.voting.vote, { workspaceId: made.workspaceId, jobId, paperId, decision: "include", answered: { key: other, answer: "unclear" } }); + expect(await 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)!.answers)).toEqual({ [key]: "yes", [other]: "unclear" }); 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/validators.ts b/convex/screening/validators.ts index 64af6bad2..0dc848e85 100644 --- a/convex/screening/validators.ts +++ b/convex/screening/validators.ts @@ -422,6 +422,8 @@ export const voteViewValidator = v.object({ reason: v.optional(v.string()), note: v.optional(v.string()), at: v.number(), + /** When it was cast, where its answers were changed since (`at` is then when they were): what the files call when it was voted. */ + castAt: v.optional(v.number()), flagged: v.optional(v.boolean()), confidences: voteConfidencesValidator, passages: optionalPassagesValidator, diff --git a/convex/screening/voting.ts b/convex/screening/voting.ts index c120a63a3..17842c8fe 100644 --- a/convex/screening/voting.ts +++ b/convex/screening/voting.ts @@ -12,7 +12,7 @@ import { givenReason, NAMED_REASONS, NO_REASON, type Answer } from "../../lib/sc import { requireReviewer, standingOn } from "./access"; import { bookkeepLater } from "./bookkeeping"; import { countDealt, personRow, votesOf } from "./dealing"; -import { decisionValidator, SCREENING_TEXT, voteAnswersValidator } from "./validators"; +import { answerValidator, decisionValidator, SCREENING_TEXT, voteAnswersValidator } from "./validators"; /** A paper of a screening, by its ID there. */ async function paperOf(ctx: Pick, jobId: Id<"screeningJobs">, resultId: Id<"screeningResults">) { @@ -32,19 +32,20 @@ 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()), /** 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()) }; +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()), /** One answer given to a vote already cast, or taken back (null): it changes that answer of the vote as it stands now, and nothing else, so another tab's answer to another criterion stays. It is not a new vote, and a vote asked for again is still asked for. */ answered: v.optional(v.object({ key: v.string(), answer: v.union(answerValidator, v.null()) })) }; /** 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, answersOnly }: { paperId: Id<"screeningResults">; onlyWaiting?: boolean; onlyAt?: number; answersOnly?: boolean; 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, answered }: { paperId: Id<"screeningResults">; onlyWaiting?: boolean; onlyAt?: number; answered?: { key: string; answer: Answer | null }; 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); + // An answer joining a vote keeps its reason, even one whose criterion was taken off since: only a vote cast names one. + if (!answered) requireReason(job, reason, onlyAt !== undefined); 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.edited ?? mine.at) !== onlyAt)) return false; - // Answers to a vote taken back meanwhile, in another tab, cast nothing. - if (answersOnly && mine?.status !== "cast") return false; + // An answer to a vote taken back meanwhile, in another tab, casts nothing. + if (answered && mine?.status !== "cast") 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; @@ -55,12 +56,15 @@ 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 } : {}) }; - // Answers joining a vote already cast change only the answers: it stays the vote it was, whatever another tab saved meanwhile, cast when it was, which - // "first vote decides" reads, and asked for again if it was. An exclusion that rested on a criterion answered otherwise now rests on what the answers say. - const kept = answersOnly ? mine : undefined; - const keptReason = kept?.decision === "exclude" ? ((kept.reason && (job.criteria ?? []).some((one) => one.key === kept.reason) && given[kept.reason] !== "no") || kept.reason === NO_REASON ? (givenReason(job.criteria ?? [], given, kept.note ?? "") ?? NO_REASON) : kept.reason) : undefined; + // An answer joining a vote already cast changes only that answer, on the answers the vote holds now (those to criteria taken off since stay): it stays + // the vote it was, whatever another tab saved meanwhile, cast when it was, which "first vote decides" reads, and asked for again if it was. An exclusion + // that rested on that criterion failing now rests on what the answers say, and one that had no reason takes the must-have its answers now fail. + const kept = answered && known.has(answered.key) ? mine : undefined; + if (answered && !kept) return false; + const keptAnswers = kept ? (({ [answered!.key]: _old, ...rest }) => (answered!.answer ? { ...rest, [answered!.key]: answered!.answer } : rest))({ ...(kept.answers as Record | undefined) }) : given; + const keptReason = kept?.decision === "exclude" ? ((kept.reason === answered!.key && answered!.answer !== "no") || (kept.reason === NO_REASON && answered!.answer === "no") ? (givenReason(job.criteria ?? [], keptAnswers, kept.note ?? "") ?? NO_REASON) : kept.reason) : undefined; const vote = kept - ? { status: "cast" as const, decision: kept.decision!, answers: given, reason: keptReason, note: kept.note, at: kept.at ?? Date.now(), edited: Date.now(), flagged: kept.flagged } + ? { status: "cast" as const, decision: kept.decision!, answers: keptAnswers, reason: keptReason, note: kept.note, at: kept.at ?? Date.now(), edited: Date.now(), flagged: kept.flagged } : { status: "cast" as const, decision, answers: given, reason: decision === "exclude" ? reason : undefined, note: note?.trim() || undefined, at: Date.now(), edited: undefined, flagged: undefined }; if (mine) await ctx.db.patch("screeningVotes", mine._id, vote); else { diff --git a/convex/sharing/access.ts b/convex/sharing/access.ts index b809c6964..4e54165c3 100644 --- a/convex/sharing/access.ts +++ b/convex/sharing/access.ts @@ -61,6 +61,12 @@ export const noteShared = async (ctx: Pick, shared: Shared, b await noteActivity(ctx, { workspaceId: shared.workspaceId, by: by.userId, viaAssistant: by.author === "assistant" }, { kind: shared.kind, id: shared.pageId ?? shared.id, happened: "shared", detail: withWhom }); }; +/** Writes to an item's Activity that `by` took it back from someone, or took back the invitation to them, named as given. */ +export const noteUnshared = async (ctx: Pick, shared: Shared, by: Pick, fromWhom: string) => { + if (shared.kind === "chat") return; + await noteActivity(ctx, { workspaceId: shared.workspaceId, by: by.userId, viaAssistant: by.author === "assistant" }, { kind: shared.kind, id: shared.pageId ?? shared.id, happened: "unshared", detail: fromWhom }); +}; + /** * Gives a person the item, or changes what they may do with it. An invitation to their address * that still waits is answered by it, and its place becomes theirs. diff --git a/convex/sharing/guests.ts b/convex/sharing/guests.ts index aa25cf3de..dc4144a0b 100644 --- a/convex/sharing/guests.ts +++ b/convex/sharing/guests.ts @@ -14,7 +14,7 @@ import { MAX_ACCOUNTS_PER_EMAIL } from "../lib/queryBounds"; import { assistantMutation, assistantQuery, defineUserMutation, defineUserQuery, userMutation, userQuery } from "../lib/userActions"; import { readMemberOrganizations } from "../organizationFeatures"; import schema from "../schema"; -import { give, holds, invitationTo, roomFor } from "./access"; +import { give, holds, invitationTo, noteUnshared, roomFor } from "./access"; import { grantOf, itemGuestsOf, requireRole, sharedIn, shares } from "./items"; import { guestRoleValidator, sharedKindValidator } from "./validators"; @@ -103,11 +103,18 @@ export const removeAction = defineUserMutation({ const shared = await sharedIn(ctx, actor, kind, id); if ("userId" in guest) { const grant = await grantOf(ctx, shared.id, guest.userId); - if (grant) await ctx.db.delete("itemAccess", grant._id); + if (grant) { + await ctx.db.delete("itemAccess", grant._id); + const person = await ctx.db.get("users", guest.userId); + await noteUnshared(ctx, shared, actor, person ? personName(person) || person.email : ""); + } return null; } const invitation = await invitationTo(ctx, shared.id, guest.email.trim().toLowerCase()); - if (invitation?.state === "pending") await ctx.db.patch("itemInvitations", invitation._id, { state: "cancelled" }); + if (invitation?.state === "pending") { + await ctx.db.patch("itemInvitations", invitation._id, { state: "cancelled" }); + await noteUnshared(ctx, shared, actor, invitation.email); + } return null; }, }); diff --git a/convex/sharing/invitations.ts b/convex/sharing/invitations.ts index 3c32c918c..a508697da 100644 --- a/convex/sharing/invitations.ts +++ b/convex/sharing/invitations.ts @@ -17,7 +17,7 @@ import { MAX_ACCOUNTS_PER_EMAIL, MAX_PENDING_ITEM_INVITATIONS_PER_EMAIL } from " import { rateLimit } from "../lib/rateLimit"; import { actingAs, assistantAction, assistantQuery, defineChangingAction, defineUserQuery, userAction, userQuery } from "../lib/userActions"; import { workspaceFrom, workspaceName } from "../workspaces/personal"; -import { holds, invitationTo, listedBy, noteShared, requireRoom } from "./access"; +import { holds, invitationTo, listedBy, noteShared, noteUnshared, requireRoom } from "./access"; import { findShared, grantOf, kindWord, open, requireRole, sharedIn, shares } from "./items"; import { guestRoleValidator, sharedFromValidator, sharedKindValidator, type SharedKind } from "./validators"; @@ -36,7 +36,10 @@ export const prepare = internalMutation({ if (replacing.length > MAX_PENDING_ITEM_INVITATIONS_PER_EMAIL) throw createError("VALIDATION_ERROR", "Too many invitations to take back at once."); for (const address of replacing) { const old = await invitationTo(ctx, shared.id, address.trim().toLowerCase()); - if (old?.state === "pending") await ctx.db.patch("itemInvitations", old._id, { state: "cancelled" }); + if (old?.state === "pending") { + await ctx.db.patch("itemInvitations", old._id, { state: "cancelled" }); + await noteUnshared(ctx, shared, actor, old.email); + } } await rateLimit(ctx, { name: "item-invitation", key: String(userId), throws: true }); const email = args.email.trim().toLowerCase(); @@ -107,11 +110,12 @@ export const unreplace = internalMutation({ handler: async (ctx, { invitationId, emails, attempt }) => { const invitation = await ctx.db.get("itemInvitations", invitationId); if (invitation?.state !== "pending" || invitation.expiresAt !== attempt) return null; + // Taken back first: the place it holds goes back to the invitations it replaced. + await ctx.db.patch("itemInvitations", invitationId, { state: "cancelled" }); for (const email of emails.slice(0, MAX_PENDING_ITEM_INVITATIONS_PER_EMAIL)) { const old = await invitationTo(ctx, invitation.item, email.trim().toLowerCase()); if (old?.state === "cancelled" && old.expiresAt > Date.now()) await ctx.db.patch("itemInvitations", old._id, { state: "pending" }); } - await ctx.db.patch("itemInvitations", invitationId, { state: "cancelled" }); return null; }, }); @@ -151,11 +155,11 @@ export const respondVerified = internalMutation({ if (accept && shared && invitation.state === "accepted" && ((await grantOf(ctx, shared.id, userId)) || (await holds(ctx, shared, person)))) return { kind: shared.kind, id: shared.id }; if (invitation.state !== "pending" || invitation.expiresAt <= Date.now()) throw createError("CONFLICT", "Invitation expired or already answered"); if (!shared) throw createError("NOT_FOUND", "What you were invited to is no longer there."); - // Its place becomes theirs. Someone who joined its workspace since has it without one. + // Answered first, then its place becomes theirs, so the place is counted once (../screening/seats.ts). Someone who joined its workspace since has it without one. + await ctx.db.patch("itemInvitations", invitationId, { state: accept ? "accepted" : "declined" }); if (accept && !(await holds(ctx, shared, person)) && !(await grantOf(ctx, shared.id, userId))) { await ctx.db.insert("itemAccess", { kind: shared.kind, item: shared.id, name: shared.name, userId, role: invitation.role, grantedBy: invitation.invitedBy, grantedAt: Date.now(), ...listedBy(shared) }); } - await ctx.db.patch("itemInvitations", invitationId, { state: accept ? "accepted" : "declined" }); return accept ? { kind: shared.kind, id: shared.id } : null; }, }); diff --git a/lib/emails/screening-notice.ts b/lib/emails/screening-notice.ts index 9cb1bcac5..1dac23060 100644 --- a/lib/emails/screening-notice.ts +++ b/lib/emails/screening-notice.ts @@ -5,13 +5,13 @@ import { emailButton, emailStyles, renderLibraryEmail } from "./library-template export type NoticeAbout = "papers" | "conflicts" | "reminder" | "joined"; const num = (n: number) => n.toLocaleString("en-GB"); -const papers = (n: number, more = false) => `${num(n)} ${more ? "or more papers" : n === 1 ? "paper" : "papers"}`; +const papers = (n: number) => `${num(n)} ${n === 1 ? "paper" : "papers"}`; /** * The email a screening sends one person (convex/screening/noticeMail.ts): what waits for them, a link to it, and * the link that turns this screening's emails off for them alone. */ -export function screeningNoticeMessage({ origin, path, name, about, count, more = false, finished = false, living = false, by }: { +export function screeningNoticeMessage({ origin, path, name, about, count, finished = false, living = false, by }: { origin: string; /** The screening's own page, with its workspace's prefix where it has one. */ path: string; @@ -19,8 +19,6 @@ export function screeningNoticeMessage({ origin, path, name, about, count, more about: NoticeAbout; /** How many papers wait for them: to vote on, or to settle. */ count: number; - /** The count is where counting stopped: there are at least that many. */ - more?: boolean; /** Someone given a finished screening to vote on: they vote once it is reopened. */ finished?: boolean; /** It looks for new papers on a schedule: more come to its reviewers as they arrive. */ @@ -39,7 +37,7 @@ export function screeningNoticeMessage({ origin, path, name, about, count, more ? [`You review "${name}"`, `${by ?? "A colleague"} ${finished ? "gave you a place to vote on" : "added you as a reviewer of"} "${name}". ${finished ? "The screening is marked finished. You can vote once it is reopened." : count ? `${papers(count)} ${count === 1 ? "waits" : "wait"} for your vote.` : living ? "No paper waits for your vote yet. New ones come to you as they arrive." : "No paper waits for your vote."}`, count === 1 ? "Screen it" : count ? "Screen them" : "Open it"] : about === "reminder" ? [`${papers(count)} ${count === 1 ? "waits" : "wait"} for your vote in "${name}"`, `${by ?? "A colleague"} reminds you that ${papers(count)} of "${name}" ${count === 1 ? "waits" : "wait"} for your vote.`, count === 1 ? "Screen it" : "Screen them"] - : [`${papers(count, more)} to screen in "${name}"`, `${count === 1 ? "A new paper" : more ? `${num(count)} or more new papers` : `${num(count)} new papers`} arrived in "${name}" and ${count === 1 ? "waits" : "wait"} for your vote.`, count === 1 ? "Screen it" : "Screen them"]; + : [`${papers(count)} to screen in "${name}"`, `${count === 1 ? "A new paper" : `${num(count)} new papers`} arrived in "${name}" and ${count === 1 ? "waits" : "wait"} for your vote.`, count === 1 ? "Screen it" : "Screen them"]; return { subject, text: `${line}\n\n${open}\n\nStop receiving emails from this screening\n${off}`, diff --git a/lib/papers/paper-ref.test.ts b/lib/papers/paper-ref.test.ts index 975369377..666c080e6 100644 --- a/lib/papers/paper-ref.test.ts +++ b/lib/papers/paper-ref.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { crossRefsOf, legacyPaperRef, openalexWorkOf, paperKey, paperPage, parsePaperKey, toPaperKey, type PaperRef } from "./paper-ref"; +import { crossRefsOf, legacyPaperRef, openalexWorkOf, paperKey, paperPage, parsePaperKey, plainTitle, toPaperKey, type PaperRef } from "./paper-ref"; const refs: PaperRef[] = [ { source: "openalex", work: "W2741809807" }, @@ -80,3 +80,13 @@ describe("where a paper opens", () => { expect(paperPage("W5")).toBe("https://openalex.org/W5"); }); }); + +describe("a title as two sources of one paper give it", () => { + it("drops case, spacing, punctuation and Latin accents, and keeps the marks that make another word in other scripts", () => { + expect(plainTitle("Café, School Meals!")).toBe(plainTitle("cafe school meals")); + expect(plainTitle("कल")).not.toBe(plainTitle("काल")); + expect(plainTitle("カ")).not.toBe(plainTitle("ガ")); + // One written as a letter and its mark, the other as the single letter, are one title. + expect(plainTitle("ガ")).toBe(plainTitle("ガ")); + }); +}); diff --git a/lib/papers/paper-ref.ts b/lib/papers/paper-ref.ts index a964b5cf3..616d85da4 100644 --- a/lib/papers/paper-ref.ts +++ b/lib/papers/paper-ref.ts @@ -169,8 +169,12 @@ export function crossRefsOf(ref: PaperRef, given: { openalexId?: string | null; return { ...(openalexId ? { openalexId } : {}), ...(doi ? { doi } : {}) }; } -/** A title as two sources of one paper would both give it: its letters and digits, in lower case. */ -export const plainTitle = (title: string) => title.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, ""); +/** + * A title as two sources of one paper would both give it: its letters and digits, in lower case, without the accents + * Latin, Greek and Cyrillic letters take ("é" is "e"). The marks of other scripts are letters' own: a Devanagari vowel + * sign or a Japanese voicing mark makes another word ("कल" and "काल", "カ" and "ガ"), so they stay. + */ +export const plainTitle = (title: string) => title.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").normalize("NFC").replace(/[^\p{L}\p{M}\p{N}]+/gu, ""); /** Whether two titles name one paper: one holds the other, a subtitle or not, and neither is too short to tell. */ export function sameTitle(one: string, other: string) { const [a, b] = [plainTitle(one), plainTitle(other)]; diff --git a/messages/af.json b/messages/af.json index 644320105..3f6b5dd79 100644 --- a/messages/af.json +++ b/messages/af.json @@ -4899,6 +4899,7 @@ "stopped": "het dit gestop", "moved": "het dit hiernatoe verskuif van", "shared": "het dit met gedeel", + "unshared": "het opgehou om dit te deel met", "viaAssistant": "Deur die assistent", "today": "Vandag", "yesterday": "Gister", @@ -7942,6 +7943,7 @@ "readAgain": "Het sommige artikels weer gelees", "stopped": "Het die siftering gestop", "shared": "Het dit met {who} gedeel", + "unshared": "Het opgehou om dit met {who} te deel", "sharedSomeone": "Het dit met iemand gedeel", "votesDiscarded": "Hul stemme bly op rekord en tel nie meer nie", "votesKept": "{count, plural, one {# stem tel} other {# stemme tel}} steeds", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, other {# vir jou om te sif}}", "conflictsToSettle": "{count, plural, one {# konflik om te beslis} other {# konflikte om te beslis}}", "questionsForYou": "{count, plural, one {# vraag vir jou} other {# vrae vir jou}}", - "finishedIncluded": "{included} ingesluit", "waitingForVotes": "{count} wag vir stemme", "inConflictFor": "{count} in konflik, vir {who} om te beslis", "upToDate": "Op datum", diff --git a/messages/ar.json b/messages/ar.json index ee6f7c38f..ec15270f5 100644 --- a/messages/ar.json +++ b/messages/ar.json @@ -4899,6 +4899,7 @@ "stopped": "أوقفها", "moved": "نقلها إلى هنا من", "shared": "شاركها مع", + "unshared": "أوقف مشاركته مع", "viaAssistant": "عبر المساعد", "today": "اليوم", "yesterday": "أمس", @@ -7942,6 +7943,7 @@ "readAgain": "أعاد قراءة بعض الأوراق", "stopped": "أوقف الفرز", "shared": "شاركه مع {who}", + "unshared": "أوقف مشاركته مع {who}", "sharedSomeone": "شاركه مع شخص ما", "votesDiscarded": "تبقى أصواتهم مسجلة ويتوقف احتسابها", "votesKept": "{count, plural, zero {يبقى # صوت محتسبًا} one {يبقى صوت واحد محتسبًا} two {يبقى صوتان محتسبين} few {تبقى # أصوات محتسبة} many {يبقى # صوتًا محتسبًا} other {يبقى # صوت محتسبًا}}", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, zero {# ورقة لتفرزها} one {ورقة واحدة لتفرزها} two {ورقتان لتفرزهما} few {# أوراق لتفرزها} many {# ورقة لتفرزها} other {# ورقة لتفرزها}}", "conflictsToSettle": "{count, plural, zero {# تعارض لتحسمها} one {تعارض واحد لتحسمه} two {تعارضان لتحسمهما} few {# تعارضات لتحسمها} many {# تعارضًا لتحسمها} other {# تعارض لتحسمها}}", "questionsForYou": "{count, plural, zero {# سؤال لك} one {سؤال واحد لك} two {سؤالان لك} few {# أسئلة لك} many {# سؤالًا لك} other {# سؤال لك}}", - "finishedIncluded": "{included} مُدرَجة", "waitingForVotes": "{count} بانتظار الأصوات", "inConflictFor": "{count} في تعارض، يحسمها {who}", "upToDate": "محدّث", diff --git a/messages/de.json b/messages/de.json index db977ee05..b1fc8f9b6 100644 --- a/messages/de.json +++ b/messages/de.json @@ -4899,6 +4899,7 @@ "stopped": "hat sie gestoppt", "moved": "hat sie hierher verschoben von", "shared": "hat sie geteilt mit", + "unshared": "hat die Freigabe beendet für", "viaAssistant": "Über den Assistenten", "today": "Heute", "yesterday": "Gestern", @@ -7942,6 +7943,7 @@ "readAgain": "Hat einige Artikel erneut gelesen", "stopped": "Hat das Screening gestoppt", "shared": "Hat es mit {who} geteilt", + "unshared": "Freigabe für {who} beendet", "sharedSomeone": "Hat es mit jemandem geteilt", "votesDiscarded": "Die Stimmen dieser Person bleiben gespeichert und zählen nicht mehr", "votesKept": "{count, plural, one {# Stimme zählt} other {# Stimmen zählen}} weiter", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, other {# für Sie zu prüfen}}", "conflictsToSettle": "{count, plural, one {# Konflikt zu entscheiden} other {# Konflikte zu entscheiden}}", "questionsForYou": "{count, plural, one {# Frage an Sie} other {# Fragen an Sie}}", - "finishedIncluded": "{included} eingeschlossen", "waitingForVotes": "{count} warten auf Stimmen", "inConflictFor": "{count} im Konflikt, {who} entscheidet", "upToDate": "Aktuell", diff --git a/messages/en-GB.json b/messages/en-GB.json index 3cbcdeacf..a2f47b86e 100644 --- a/messages/en-GB.json +++ b/messages/en-GB.json @@ -4898,6 +4898,7 @@ "stopped": "stopped it", "moved": "moved it here from", "shared": "shared it with", + "unshared": "stopped sharing it with", "viaAssistant": "Through the assistant", "today": "Today", "yesterday": "Yesterday", @@ -7941,6 +7942,7 @@ "readAgain": "Read some papers again", "stopped": "Stopped the screening", "shared": "Shared it with {who}", + "unshared": "Stopped sharing it with {who}", "sharedSomeone": "Shared it with someone", "votesDiscarded": "Their votes stay on record and stop counting", "votesKept": "{count, plural, one {# vote keeps} other {# votes keep}} counting", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {# for you to screen}}", "conflictsToSettle": "{count, plural, one {# conflict to settle} other {# conflicts to settle}}", "questionsForYou": "{count, plural, one {# question for you} other {# questions for you}}", - "finishedIncluded": "{included} included", "waitingForVotes": "{count} waiting for votes", "inConflictFor": "{count} in conflict, for {who} to settle", "upToDate": "Up to date", diff --git a/messages/en-US.json b/messages/en-US.json index e148db27f..a6ee104b7 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -4898,6 +4898,7 @@ "stopped": "stopped it", "moved": "moved it here from", "shared": "shared it with", + "unshared": "stopped sharing it with", "viaAssistant": "Through the assistant", "today": "Today", "yesterday": "Yesterday", @@ -7941,6 +7942,7 @@ "readAgain": "Read some papers again", "stopped": "Stopped the screening", "shared": "Shared it with {who}", + "unshared": "Stopped sharing it with {who}", "sharedSomeone": "Shared it with someone", "votesDiscarded": "Their votes stay on record and stop counting", "votesKept": "{count, plural, one {# vote keeps} other {# votes keep}} counting", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {# for you to screen}}", "conflictsToSettle": "{count, plural, one {# conflict to settle} other {# conflicts to settle}}", "questionsForYou": "{count, plural, one {# question for you} other {# questions for you}}", - "finishedIncluded": "{included} included", "waitingForVotes": "{count} waiting for votes", "inConflictFor": "{count} in conflict, for {who} to settle", "upToDate": "Up to date", diff --git a/messages/es.json b/messages/es.json index 3b228f69b..4ca06b931 100644 --- a/messages/es.json +++ b/messages/es.json @@ -4899,6 +4899,7 @@ "stopped": "lo detuvo", "moved": "lo movió aquí desde", "shared": "lo compartió con", + "unshared": "dejó de compartirlo con", "viaAssistant": "A través del asistente", "today": "Hoy", "yesterday": "Ayer", @@ -7942,6 +7943,7 @@ "readAgain": "Volvió a leer algunos artículos", "stopped": "Detuvo el cribado", "shared": "Lo compartió con {who}", + "unshared": "Dejó de compartirlo con {who}", "sharedSomeone": "Lo compartió con alguien", "votesDiscarded": "Sus votos quedan registrados y dejan de contar", "votesKept": "{count, plural, one {# voto sigue contando} other {# votos siguen contando}}", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, other {# para que usted cribe}}", "conflictsToSettle": "{count, plural, one {# conflicto que resolver} other {# conflictos que resolver}}", "questionsForYou": "{count, plural, one {# pregunta para usted} other {# preguntas para usted}}", - "finishedIncluded": "{included} incluidos", "waitingForVotes": "{count} esperando votos", "inConflictFor": "{count} en conflicto, que resuelve {who}", "upToDate": "Al día", diff --git a/messages/fr.json b/messages/fr.json index 10c30c857..ff2601711 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -4898,6 +4898,7 @@ "stopped": "l'a arrêté", "moved": "l'a déplacé ici depuis", "shared": "l'a partagé avec", + "unshared": "a cessé de le partager avec", "viaAssistant": "Par l'assistant", "today": "Aujourd'hui", "yesterday": "Hier", @@ -7941,6 +7942,7 @@ "readAgain": "A relu certains articles", "stopped": "A arrêté le criblage", "shared": "L'a partagé avec {who}", + "unshared": "A cessé de le partager avec {who}", "sharedSomeone": "L'a partagé avec quelqu'un", "votesDiscarded": "Ses votes restent consignés et ne comptent plus", "votesKept": "{count, plural, one {# vote continue} other {# votes continuent}} de compter", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {# à cribler pour vous}}", "conflictsToSettle": "{count, plural, one {# désaccord à trancher} other {# désaccords à trancher}}", "questionsForYou": "{count, plural, one {# question pour vous} other {# questions pour vous}}", - "finishedIncluded": "{included} inclus", "waitingForVotes": "{count} en attente de votes", "inConflictFor": "{count} en désaccord, à trancher par {who}", "upToDate": "À jour", diff --git a/messages/hi.json b/messages/hi.json index 30c76ad4f..09f877dfd 100644 --- a/messages/hi.json +++ b/messages/hi.json @@ -4898,6 +4898,7 @@ "stopped": "ने इसे बंद किया", "moved": "इसे यहाँ ले आए, यहाँ से:", "shared": "इसे साझा किया, इनके साथ:", + "unshared": "ने इसे साझा करना बंद किया", "viaAssistant": "सहायक के माध्यम से", "today": "आज", "yesterday": "कल", @@ -7941,6 +7942,7 @@ "readAgain": "कुछ लेख फिर से पढ़े", "stopped": "स्क्रीनिंग बंद की", "shared": "इसे {who} के साथ साझा किया", + "unshared": "{who} के साथ साझा करना बंद किया", "sharedSomeone": "इसे किसी के साथ साझा किया", "votesDiscarded": "उनके वोट रिकॉर्ड में रहते हैं, पर अब गिने नहीं जाते", "votesKept": "{count, plural, one {# वोट गिना जाता रहेगा} other {# वोट गिने जाते रहेंगे}}", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {आपके स्क्रीन करने को #}}", "conflictsToSettle": "{count, plural, one {सुलझाने को # मतभेद} other {सुलझाने को # मतभेद}}", "questionsForYou": "{count, plural, one {आपके लिए # प्रश्न} other {आपके लिए # प्रश्न}}", - "finishedIncluded": "{included} शामिल", "waitingForVotes": "{count} वोट की प्रतीक्षा में", "inConflictFor": "{count} मतभेद में, {who} के सुलझाने को", "upToDate": "अद्यतन", diff --git a/messages/ja.json b/messages/ja.json index 08dff626d..413918875 100644 --- a/messages/ja.json +++ b/messages/ja.json @@ -4898,6 +4898,7 @@ "stopped": "が停止しました", "moved": "ここに移動しました。移動元:", "shared": "共有しました。共有先:", + "unshared": "が共有を停止しました:", "viaAssistant": "アシスタント経由", "today": "今日", "yesterday": "昨日", @@ -7941,6 +7942,7 @@ "readAgain": "一部の論文をもう一度読み取りました", "stopped": "スクリーニングを停止しました", "shared": "{who} と共有しました", + "unshared": "{who} との共有を停止しました", "sharedSomeone": "ある人と共有しました", "votesDiscarded": "この人の投票は記録に残りますが、数えられなくなります", "votesKept": "{count, plural, other {# 票}}は引き続き数えられます", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {あなたがスクリーニングする論文 # 件}}", "conflictsToSettle": "{count, plural, other {判定する不一致 # 件}}", "questionsForYou": "{count, plural, other {あなたへの質問 # 件}}", - "finishedIncluded": "{included} 件を採用", "waitingForVotes": "投票待ち {count} 件", "inConflictFor": "不一致 {count} 件、{who} が判定", "upToDate": "最新です", diff --git a/messages/pt.json b/messages/pt.json index a2161cf49..3e37d6add 100644 --- a/messages/pt.json +++ b/messages/pt.json @@ -4899,6 +4899,7 @@ "stopped": "parou-a", "moved": "moveu-a para aqui a partir de", "shared": "partilhou-a com", + "unshared": "deixou de compartilhar com", "viaAssistant": "Através do assistente", "today": "Hoje", "yesterday": "Ontem", @@ -7942,6 +7943,7 @@ "readAgain": "Voltou a ler alguns artigos", "stopped": "Parou a triagem", "shared": "Partilhou-a com {who}", + "unshared": "Deixou de compartilhar com {who}", "sharedSomeone": "Partilhou-a com alguém", "votesDiscarded": "Os seus votos ficam registados e deixam de contar", "votesKept": "{count, plural, one {# voto continua} other {# votos continuam}} a contar", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, other {# para triar}}", "conflictsToSettle": "{count, plural, one {# conflito a resolver} other {# conflitos a resolver}}", "questionsForYou": "{count, plural, one {# pergunta para si} other {# perguntas para si}}", - "finishedIncluded": "{included} incluídos", "waitingForVotes": "{count} à espera de votos", "inConflictFor": "{count} em conflito, para {who} resolver", "upToDate": "Atualizada", diff --git a/messages/sw.json b/messages/sw.json index be292b5bf..d23ddb4c0 100644 --- a/messages/sw.json +++ b/messages/sw.json @@ -4899,6 +4899,7 @@ "stopped": "ameisimamisha", "moved": "ameihamisha hapa kutoka", "shared": "ameishiriki na", + "unshared": "aliacha kushiriki na", "viaAssistant": "Kupitia msaidizi", "today": "Leo", "yesterday": "Jana", @@ -7942,6 +7943,7 @@ "readAgain": "Baadhi ya makala zilisomwa tena", "stopped": "Uchujaji ulisimamishwa", "shared": "Ulishirikiwa na {who}", + "unshared": "Aliacha kushiriki na {who}", "sharedSomeone": "Ulishirikiwa na mtu", "votesDiscarded": "Kura zake zinabaki kwenye kumbukumbu na zinaacha kuhesabiwa", "votesKept": "{count, plural, one {kura # inaendelea} other {kura # zinaendelea}} kuhesabiwa", @@ -8765,7 +8767,6 @@ "forYouToScreen": "{count, plural, other {# za wewe kuchuja}}", "conflictsToSettle": "{count, plural, one {mgongano # wa kuamua} other {migongano # ya kuamua}}", "questionsForYou": "{count, plural, one {swali # kwako} other {maswali # kwako}}", - "finishedIncluded": "{included} zimejumuishwa", "waitingForVotes": "{count} zinasubiri kura", "inConflictFor": "{count} zenye mgongano, {who} aamue", "upToDate": "Uko sasa", diff --git a/messages/zh.json b/messages/zh.json index 0c652a5e2..9335a031d 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -4898,6 +4898,7 @@ "stopped": "停止了它", "moved": "把它移到这里,来自", "shared": "把它共享给了", + "unshared": "停止与以下人员共享", "viaAssistant": "通过助手", "today": "今天", "yesterday": "昨天", @@ -7941,6 +7942,7 @@ "readAgain": "重新读取了部分论文", "stopped": "停止了筛选", "shared": "共享给了 {who}", + "unshared": "停止与 {who} 共享", "sharedSomeone": "共享给了某人", "votesDiscarded": "其投票保留在记录中,但不再计入", "votesKept": "{count, plural, other {# 票}}仍然计入", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {# 篇待你筛选}}", "conflictsToSettle": "{count, plural, other {# 个冲突待裁决}}", "questionsForYou": "{count, plural, other {# 个问你的问题}}", - "finishedIncluded": "{included} 篇入选", "waitingForVotes": "{count} 篇等待投票", "inConflictFor": "{count} 篇有冲突,由 {who} 裁决", "upToDate": "已是最新", diff --git a/messages/zu.json b/messages/zu.json index ef6abfb3d..528e2eb02 100644 --- a/messages/zu.json +++ b/messages/zu.json @@ -4898,6 +4898,7 @@ "stopped": "yayimisa", "moved": "yayidlulisela lapha kusuka ku-", "shared": "yabelana nayo ne-", + "unshared": "uyekile ukwabelana nalo no", "viaAssistant": "Ngomsizi", "today": "Namuhla", "yesterday": "Izolo", @@ -7941,6 +7942,7 @@ "readAgain": "Amanye amaphepha afundwe futhi", "stopped": "Ukuskrini kumisiwe", "shared": "Kwabelwane ngakho no-{who}", + "unshared": "Uyekile ukwabelana nalo no-{who}", "sharedSomeone": "Kwabelwane ngakho nomuntu", "votesDiscarded": "Amavoti abo ahlala erekhodini futhi ayeka ukubalwa", "votesKept": "{count, plural, one {# ivoti liqhubeka libalwa} other {# amavoti aqhubeka ebalwa}}", @@ -8764,7 +8766,6 @@ "forYouToScreen": "{count, plural, other {# okokuthi uskrine}}", "conflictsToSettle": "{count, plural, one {# ukungqubuzana okuxazululwayo} other {# ukungqubuzana okuxazululwayo}}", "questionsForYou": "{count, plural, one {# umbuzo wakho} other {# imibuzo yakho}}", - "finishedIncluded": "{included} afakiwe", "waitingForVotes": "{count} alinde amavoti", "inConflictFor": "{count} ayangqubuzana, alinde u-{who} ukuthi akuxazulule", "upToDate": "Kusesikhathini", diff --git a/scripts/convex-rules.json b/scripts/convex-rules.json index 57d4f7d1e..f0e10413d 100644 --- a/scripts/convex-rules.json +++ b/scripts/convex-rules.json @@ -123,7 +123,6 @@ "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", - "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." diff --git a/scripts/user-actions-exempt.json b/scripts/user-actions-exempt.json index 4c4be9e89..e3c9bd612 100644 --- a/scripts/user-actions-exempt.json +++ b/scripts/user-actions-exempt.json @@ -125,6 +125,7 @@ "screening/living:checkNow": "A screening's own pages. The assistant reads screenings and changes nothing in them (plans/screening-reviewers).", "screening/living:readSourceAgain": "A screening's own pages. The assistant reads screenings and changes nothing in them (plans/screening-reviewers).", "screening/discussion:say": "A screening's own pages. The assistant reads screenings and changes nothing in them (plans/screening-reviewers).", + "screening/settings:checkChange": "A screening's own Settings page, asking whether a save would be taken before it sends invitations. The assistant changes nothing in screenings (plans/screening-reviewers).", "screening/settings:save": "A screening's own pages. The assistant reads screenings and changes nothing in them (plans/screening-reviewers).", "screening/sampling:sample": "The screening form's preview of the first papers a source's range takes. The assistant starts no screening, and reads a source's papers with the tools for searches, collections and Zotero.", "screening/settings:saveToCommunity": "A screening's own pages. The assistant reads screenings and changes nothing in them (plans/screening-reviewers).",