diff --git a/PROGRESS.md b/PROGRESS.md index 45a6753..d7a9ee4 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -1,7 +1,8 @@ # Study Desk V2 — progress and resume notes Updated 2026-11-11. Branch: **v2**. Original V1: **main**, preserved at `7bd0a9a`. -Work remains local; no push, repository creation or production deployment has been performed. +The owner authorized publishing progress and `v2` now tracks Forgejo `origin/v2`. +No production deployment has been performed. ## Product and architecture @@ -45,9 +46,10 @@ The earlier agent manually exercised quiz completion/results, flashcards, streak mock AI generation through the assistant, editable drafts, and a 375px home page without horizontal overflow. Treat these as historical evidence; record Terra's fresh results below. -Not verified: actual Docker image build/runtime, Unraid filesystem permissions and proxy, -paid provider inference, real ChatGPT OAuth/eligibility. Docker is not installed here. Do not -claim these have been tested. The installable app caches its shell, not private study data; +Docker Desktop is now installed. Image build and a disposable non-root container passed +login, document/card persistence across restart, full-backup ZIP, anonymous sharing and +private API denial. Still unverified: Unraid filesystem permissions/proxy, paid-provider +inference and real ChatGPT OAuth/eligibility. The installable app caches its shell, not private study data; full offline administrator study is not implemented. ## Remaining work @@ -67,9 +69,21 @@ full offline administrator study is not implemented. 3. `npm.cmd run check` (tests require localhost networking for their mock AI server). 4. `npm.cmd run dev` for Vite + API, or `npm.cmd run build` then `npm.cmd start` for the built app. See README and .env.example. All automated test databases are disposable copies. -5. Keep regular local commits on `v2`. Do not push until the owner explicitly changes the - original local-only instruction. Publishing later can use `git push -u origin v2` after - reviewing the diff and confirming credentials; no force push is needed. +5. Keep focused commits on `v2`. The owner has now authorized pushing progress to this branch; + Git Credential Manager works. Never force push or publish/deploy to production implicitly. + +## V1 comparison and follow-up usability work + +See `docs/V2-COMPARISON.md` for the requirement matrix, V1 differences and remaining priorities. +Fixed the flashcard entrance/exit CSS conflict; restored touch grading and shuffle-remaining; +reset review queues on scope changes; serialized note autosaves, protected navigation with +unsaved edits and added an explicit retry action. Verified a note survives immediate +navigation and reload, and shuffling keeps browse progress at 2/4 rather than restarting. + +The owner's rationale check passed using a synthetic three-question quiz with per-option +explanations: correct, incorrect and partial SATA feedback all show explanations inline under +their options. Results group explanations with each question. Screenshot is ignored at +`.test-data/rationale-check/correct-inline.png`. The temporary test server is stopped after QA. ## Fresh UI QA findings diff --git a/README.md b/README.md index 0f7c70e..c5c9c8f 100644 --- a/README.md +++ b/README.md @@ -62,8 +62,9 @@ docker compose up -d --build ``` Default V2 host port: **3727**, deliberately separate from the old application. Use a separate -data folder. Docker is not installed in this VM; image build/runtime checks remain to be run -on Unraid. No production deployment has been performed. +data folder. Docker Desktop image build and disposable-container runtime checks now pass; +Unraid-specific permissions and reverse-proxy checks remain. No production deployment has +been performed. ## Verification and resuming work diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index cdf3648..2e3854e 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -89,8 +89,11 @@ to open a newer schema. ## Verification still required on Unraid -Docker is unavailable in the development VM. Before production use: build the image, confirm +Docker Desktop is now installed in the development VM. The image builds, and a disposable +container passed non-root startup, login, class/card/document persistence across restart, +full ZIP download, anonymous deck sharing and private API denial. These checks used a new +test volume, which was removed afterward. Unraid has not been tested. Before production use: confirm health status and non-root volume permissions, complete setup over HTTPS, upload a PDF and PPTX, restart and check persistence, test public links from a private browser, confirm proxy streaming and upload limits, and perform the restore drill above. The Dockerfile and Compose -configuration are implemented, but container deployment has **not** been executed here. +configuration are implemented and verified locally; no production deployment has occurred. diff --git a/docs/V2-COMPARISON.md b/docs/V2-COMPARISON.md new file mode 100644 index 0000000..9277d56 --- /dev/null +++ b/docs/V2-COMPARISON.md @@ -0,0 +1,93 @@ +# V2 versus V1 and the rebuild brief + +Source review on 2026-11-11, comparing `main` V1 at 7bd0a9a with local V2. +This distinguishes implementation from verification. Passing mocked AI tests does not +establish real-provider compatibility, and sampled desktop/mobile QA is not exhaustive. + +## Original requirements + +| Area | Current state | +| --- | --- | +| New architecture and UI | Rebuilt: React/Vite, Hono, built-in SQLite; distinct responsive light/dark design | +| Single administrator and public visitors | Implemented: secure local login, revocable links, isolated visitor progress | +| Classes and organization | Classes/folders, edit/move/search/delete, quiz/deck duplication; manual ordering and duplication are not equally exposed for every content type | +| Quizzes | MC/SATA, per-option explanations, question rationale, partial credit, practice/exam, shuffle, resume, missed review and history implemented | +| Flashcards | Decks, browse/self-assessment, persistent FSRS, reviews, undo and class/deck scoping implemented | +| Imports/templates/export | Preview/validation/editing, JSON/text bulk input, reusable templates and exports implemented | +| Documents | Required common formats, extraction/chunks/FTS search, optional provider OCR, private storage and AI generation implemented | +| AI providers and models | Five adapters, encrypted keys, discovery/manual models, routing/settings/usage; live provider verification remains | +| Integrated AI actions | Search/read content, weak-area generation, editable drafts, confirmed modifications implemented | +| ChatGPT account | No configured account OAuth. Hosted-client eligibility/approval remains unresolved; conventional API access is available | +| Docker/persistence/backups | Single-container image now builds and passes disposable runtime checks; Unraid proxy/volume validation remains | +| Accessibility and polish | Keyboard shortcuts, focus styles, reduced-motion rules, responsive layouts and state components exist; full keyboard/screen-reader audit remains | + +The nursing-specific AI features are prompt-based tools using the same single/multi-choice +question engine. Dedicated interactive case-study/NGN question types and an adaptive NCLEX +exam engine are not implemented; the brief listed additional types as optional. + +## V1 features that are not equivalent in V2 + +- **Named spaced-repetition sets:** V1 could collect selected decks into named sets with + independent schedules and new-card limits. V2 schedules each card once, with a global + daily new-card limit and deck/class/all review scopes. A practical simplification, but + it cannot reproduce separate course/exam review sets or independent per-set schedules. +- **Manual material order:** V1 supported drag/drop ordering of decks within material groups. + V2 class lists sort by recent update or title; the visible drag/drop is for file upload. + Some reorder APIs exist without matching UI. Quiz questions do have move-up/down controls. +- **Migration fidelity:** V2 imports source content, completed attempts and one selected + schedule per card. V1 interrupted StudyProgress sessions, named sets and their independent + schedules are not recreated. Historical reviewSnapshotJson is not consumed: imported + attempts reconstruct questions from current source content rather than preserving every + historical question version. Existing V1 share links are deliberately not reused. + +These are not all mandatory requirements in the rebuild brief, but they matter when replacing +a V1 workflow. Extra visual effects should not obscure these functional tradeoffs. + +## Issues found and addressed in this pass + +- Card entrance utility overrode swipe-away CSS. Entrance and exit classes are now mutually + exclusive, restoring the intended grading transition. +- Added horizontal touch-to-grade after revealing a flashcard, while retaining vertical + scrolling. Browse uses learning/known; FSRS uses Again/Good. Desktop buttons/keys remain. +- Shuffle now rearranges only remaining cards, retaining completed cards and assessments. + Browser check confirmed the session stays at card 2/4 and 25% after shuffling. +- Review now remounts when its query scope changes, avoiding a stale deck queue when selecting + global Review from a scoped review screen. +- Note saves are serialized; navigation/read-mode waits for a successful save, and unsaved + changes trigger the browser's unload protection. Verified editing then immediately + navigating away and reopening retains the latest text. + +## Rationale check requested by the owner + +Created an isolated three-question quiz with a separate explanation on every option plus +each question's overall rationale. Through the actual internal browser, verified a correct +single-choice answer, an incorrect single-choice answer and partially correct SATA answer. + +Practice reveals each option's explanation **under that option**, including unselected +distractors and missed correct options. The overall rationale follows that question's choices. +Results retain the same per-option/per-question grouping. Exam mode intentionally delays +feedback until submission. The stored option explanation field is `why`; a legacy import +with only a question-level rationale cannot invent separate option explanations. + +Screenshot: ignored local `.test-data/rationale-check/correct-inline.png`. + +## Remaining usability/feature priorities + +1. Restore selected-deck named review collections if replacing that V1 workflow is important. +2. Expose consistent ordering and duplication controls across content types. +3. Make timed exams use an explicit wall-clock deadline. The current runner is an active-study + clock: it pauses when hidden, and server completion does not enforce a deadline. +4. Preserve shared quiz question snapshots if scores must remain stable across owner edits; + public saved sessions currently rebuild against the latest published quiz content. +5. Add better import reporting/preservation for V1 history and interrupted sessions. +6. Improve large scanned-document OCR: currently sent as one native vision/PDF request with + a 30 MB scanned-PDF limit and an output cap, rather than paginated OCR. Lexical retrieval + and sampled long-document generation are implemented; comprehensive textbook coverage + and semantic matching are not guaranteed. +7. Full offline private studying, rich-text WYSIWYG authoring, study-plan generation and + additional case/question types remain optional future enhancements. + +No obvious missing basic flip/streak/quiz-answer feedback remains by source review. Visual +polish still needs targeted long-content/mobile/empty/error-state passes beyond the sampled +screens already checked. Prioritize those user-visible improvements over expanding a test +count for its own sake. diff --git a/web/src/features/flashcards.tsx b/web/src/features/flashcards.tsx index ed6d0d9..3788943 100644 --- a/web/src/features/flashcards.tsx +++ b/web/src/features/flashcards.tsx @@ -99,6 +99,7 @@ export function FlipCard({ footer, leaving, burst, + onSwipe, }: { front: string; back: string; @@ -113,15 +114,19 @@ export function FlipCard({ /** Plays the swipe-away animation used when a card is graded. */ leaving?: 'left' | 'right' | null; burst?: { streak: number; tier: StreakTier; id: number } | null; + /** Horizontal touch gestures grade an answer without interfering with vertical scrolling. */ + onSwipe?: (known: boolean) => void; }) { const [showHint, setShowHint] = useState(false); + const touch = useRef<{ x: number; y: number } | null>(null); + const suppressClick = useRef(false); useEffect(() => setShowHint(false), [cardKey]); const face = 'flip-face flex min-h-[max(320px,min(60vh,680px))] flex-col rounded-[24px] border border-line bg-surface shadow-2'; // Short answers read best large and centred; long ones as normal text. const size = (text: string) => text.length < 60 ? 'text-[30px] sm:text-[38px] lg:text-[46px] leading-tight text-center' : text.length < 220 ? 'text-[22px] sm:text-[26px] lg:text-[30px] leading-snug text-center' : 'text-[17px] sm:text-[19px] lg:text-[21px]'; return ( -
+
{/* The whole card is the flip target, on both sides. Space, Enter and the arrow keys do the same. */}
{ + const target = e.target as HTMLElement; + if (!onSwipe || target.closest('button,a,input,textarea,select')) return; + const p = e.touches[0]; + touch.current = { x: p.clientX, y: p.clientY }; + suppressClick.current = false; + }} + onTouchCancel={() => { touch.current = null; }} + onTouchEnd={(e) => { + const start = touch.current; + touch.current = null; + if (!start || !onSwipe) return; + const p = e.changedTouches[0]; + const dx = p.clientX - start.x; + const dy = p.clientY - start.y; + if (Math.abs(dx) >= 80 && Math.abs(dx) > Math.abs(dy) * 1.5) { + suppressClick.current = true; + onSwipe(dx > 0); + } + }} + onClick={() => { + if (suppressClick.current) { suppressClick.current = false; return; } + onFlip(); + }} >
@@ -324,6 +353,14 @@ export function CramSession({ reset(); onState(freshCramState(cards, shuffled)); }; + const shuffleRemaining = () => { + if (busy) return; + const remaining = state.order.slice(state.index); + const ordered = state.shuffled + ? cards.filter((c) => remaining.includes(c.id)).map((c) => c.id) + : shuffle(remaining); + onState({ ...state, shuffled: !state.shuffled, order: [...state.order.slice(0, state.index), ...ordered] }); + }; const studyUnknown = () => { reset(); onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1)); @@ -357,7 +394,7 @@ export function CramSession({ {Math.min(state.index + 1, total)}/{total} - restart(!state.shuffled)}> + @@ -390,7 +427,7 @@ export function CramSession({
) : ( - + )} {!done && card && ( diff --git a/web/src/main.tsx b/web/src/main.tsx index 9b6ccf6..e1c2cb5 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -110,6 +110,11 @@ function NotFound() { const page = (el: ReactNode) => }>{el}; +function ScopedReview() { + const { search } = useLocation(); + return ; +} + const router = createBrowserRouter([ // Public share links: no login, no app chrome. { path: '/s/:token', element: page(), errorElement: }, @@ -129,7 +134,7 @@ const router = createBrowserRouter([ { path: '/quizzes/:quizId', element: page() }, { path: '/decks/:deckId', element: page() }, // Flashcard study keeps the sidebar on desktop and takes the whole screen on phones. - { path: '/review', element: page() }, + { path: '/review', element: page() }, { path: '/decks/:deckId/cram', element: page() }, { path: '/documents/:docId', element: page() }, { path: '/notes/:noteId', element: page() }, diff --git a/web/src/pages/NotePage.tsx b/web/src/pages/NotePage.tsx index 5079415..2d3e570 100644 --- a/web/src/pages/NotePage.tsx +++ b/web/src/pages/NotePage.tsx @@ -1,7 +1,7 @@ import { useQuery } from '@tanstack/react-query'; import { BookOpen, Check, ChevronRight, Download, Eye, FolderInput, Layers, MoreHorizontal, Pencil, Printer, Share2, Sparkles, Trash2 } from 'lucide-react'; -import { useEffect, useRef, useState } from 'react'; -import { Link, useNavigate, useParams, useSearchParams } from 'react-router'; +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Link, useBlocker, useNavigate, useParams, useSearchParams } from 'react-router'; import { toast } from 'sonner'; import { MoveDialog, ShareDialog } from '@/features/dialogs'; import { MarkdownArea } from '@/features/editors'; @@ -36,6 +36,14 @@ export default function NotePage() { const loaded = useRef(''); const timer = useRef | null>(null); const latest = useRef({ title: '', content: '' }); + const revision = useRef(0); + const savedRevision = useRef(0); + const saves = useRef>(Promise.resolve(true)); + const deleting = useRef(false); + const savingNavigation = useRef(false); + const blocker = useBlocker(({ currentLocation, nextLocation }) => + !deleting.current && revision.current > savedRevision.current && currentLocation.pathname !== nextLocation.pathname, + ); useEffect(() => { if (note && loaded.current !== note.id) { @@ -43,39 +51,68 @@ export default function NotePage() { setTitle(note.title); setContent(note.content); latest.current = { title: note.title, content: note.content }; + revision.current = 0; + savedRevision.current = 0; setEditing(Boolean(params.get('edit')) || note.content.trim() === ''); if (params.get('edit')) setParams({}, { replace: true }); } }, [note, params, setParams]); - const saveNow = async () => { + const saveNow = useCallback(() => { if (timer.current) clearTimeout(timer.current); timer.current = null; - setStatus('saving'); - try { - await api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }); - setStatus('saved'); - } catch { - setStatus('error'); - } - }; + const version = revision.current; + const payload = { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }; + // Save in order: a slower, older request must never overwrite a newer edit. + saves.current = saves.current.then(async () => { + if (savedRevision.current >= version) return true; + setStatus('saving'); + try { + await api.patch(`/api/notes/${noteId}`, payload); + savedRevision.current = version; + setStatus(version === revision.current ? 'saved' : 'dirty'); + return true; + } catch { + setStatus('error'); + return false; + } + }); + return saves.current; + }, [noteId]); const change = (patch: Partial<{ title: string; content: string }>) => { latest.current = { ...latest.current, ...patch }; + revision.current += 1; if (patch.title !== undefined) setTitle(patch.title); if (patch.content !== undefined) setContent(patch.content); setStatus('dirty'); if (timer.current) clearTimeout(timer.current); timer.current = setTimeout(() => void saveNow(), 900); }; - useEffect( - () => () => { - if (timer.current) { - clearTimeout(timer.current); - void api.patch(`/api/notes/${noteId}`, { title: latest.current.title.trim() || 'Untitled note', content: latest.current.content }).catch(() => undefined); + useEffect(() => { + if (blocker.state !== 'blocked' || savingNavigation.current) return; + savingNavigation.current = true; + void saveNow().then((ok) => { + savingNavigation.current = false; + if (ok && savedRevision.current >= revision.current) blocker.proceed?.(); + else { + blocker.reset?.(); + toast.error('Your note could not be saved. Stay here and retry when connected.'); } - }, - [noteId], - ); + }); + }, [blocker, saveNow]); + useEffect(() => { + const warn = (e: BeforeUnloadEvent) => { + if (revision.current > savedRevision.current && !deleting.current) { + e.preventDefault(); + e.returnValue = ''; + } + }; + window.addEventListener('beforeunload', warn); + return () => { + window.removeEventListener('beforeunload', warn); + if (timer.current) clearTimeout(timer.current); + }; + }, []); if (q.isError) return q.refetch()} />; if (!q.data || !note) { @@ -94,6 +131,7 @@ export default function NotePage() { if (timer.current) clearTimeout(timer.current); timer.current = null; await api.del(`/api/notes/${note.id}`); + deleting.current = true; await refresh(); navigate(`/classes/${note.classId}`); } catch (e) { @@ -134,6 +172,9 @@ export default function NotePage() { )} )} + {editing && status === 'error' && ( + + )} {q.data.share?.enabled && ( Shared @@ -145,8 +186,12 @@ export default function NotePage() { { - if (v === 'read' && status !== 'saved') void saveNow().then(() => void refresh(qk.note(noteId))); + onChange={async (v) => { + if (v === 'read' && status !== 'saved') { + const ok = await saveNow(); + if (!ok || savedRevision.current < revision.current) return; + void refresh(qk.note(noteId)); + } setEditing(v === 'edit'); }} options={[ diff --git a/web/src/pages/ReviewPage.tsx b/web/src/pages/ReviewPage.tsx index b49d688..481f3c4 100644 --- a/web/src/pages/ReviewPage.tsx +++ b/web/src/pages/ReviewPage.tsx @@ -274,6 +274,7 @@ export default function ReviewPage() { hint={current.card.hint} flipped={flipped} onFlip={flip} + onSwipe={seenAnswer && !busy ? (known) => void rate(known ? 3 : 1) : undefined} leaving={leaving} burst={burst} footer={ai.data?.ready ? : undefined}