diff --git a/crates/archivr-core/src/capture_jobs.rs b/crates/archivr-core/src/capture_jobs.rs index 1cd1ffa..d6e4271 100644 --- a/crates/archivr-core/src/capture_jobs.rs +++ b/crates/archivr-core/src/capture_jobs.rs @@ -53,6 +53,34 @@ pub fn list_capture_jobs( Ok(rows) } +/// Lists all `pending` and `running` capture jobs for an archive, ordered oldest-first. +/// No creator scoping: any authorized user can see active jobs for cross-user skeleton display. +pub fn list_active_capture_jobs(conn: &Connection) -> Result> { + let mut stmt = conn.prepare( + "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, + created_at, updated_at, created_by + FROM capture_jobs + WHERE status IN ('pending', 'running') + ORDER BY created_at ASC, id ASC", + )?; + let rows = stmt + .query_map([], |row| { + Ok(CaptureJobSummary { + job_uid: row.get(0)?, + archive_id: row.get(1)?, + run_uid: row.get(2)?, + status: row.get(3)?, + error_text: row.get(4)?, + notes_json: row.get(5)?, + created_at: row.get(6)?, + updated_at: row.get(7)?, + created_by: row.get(8)?, + }) + })? + .collect::>>()?; + Ok(rows) +} + /// One `archive_run_items` row of a job's run. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct JobItem { diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 6f73c6c..a74ceb2 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -1789,6 +1789,16 @@ pub fn link_capture_job_run(conn: &Connection, job_uid: &str, run_uid: &str) -> Ok(()) } +/// Sets (or overwrites) the `notes_json` field of a capture job. +/// Used to store a display locator immediately after job creation. +pub fn update_capture_job_notes(conn: &Connection, job_uid: &str, notes_json: &str) -> Result<()> { + conn.execute( + "UPDATE capture_jobs SET notes_json = ?1, updated_at = ?2 WHERE job_uid = ?3", + params![notes_json, now_timestamp(), job_uid], + )?; + Ok(()) +} + /// Returns a capture job by uid. pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result> { conn.query_row( diff --git a/crates/archivr-server/src/jobs.rs b/crates/archivr-server/src/jobs.rs index eab359a..283b2d2 100644 --- a/crates/archivr-server/src/jobs.rs +++ b/crates/archivr-server/src/jobs.rs @@ -67,11 +67,18 @@ async fn list_capture_jobs_handler( Query(q): Query, ) -> Result>, ApiError> { auth.require_role(ROLE_USER)?; + // `status=active` is a special value meaning all pending+running jobs, visible to every + // authorized user (no creator scoping). Used by other users to render in-progress skeletons. + if q.status.as_deref() == Some("active") { + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + return Ok(Json(capture_jobs::list_active_capture_jobs(&conn)?)); + } if let Some(status) = q.status.as_deref() && !capture_jobs::JOB_STATUSES.contains(&status) { return Err(ApiError::bad_request( - "invalid status: must be pending, running, completed, or failed", + "invalid status: must be pending, running, completed, failed, or active", )); } let limit = parse_int_param("limit", q.limit.as_deref())? @@ -725,4 +732,48 @@ mod tests { .unwrap(); assert_eq!(body_json(resp).await[0]["archive_path"], expected.as_str()); } + + #[tokio::test] + async fn active_status_shows_pending_and_running_jobs_from_all_users() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let bob = make_role_session(&f.auth_path, "bob", &["user"]); + let alice_uid = user_uid(&f.auth_path, "alice"); + let bob_uid = user_uid(&f.auth_path, "bob"); + let base = "/api/archives/test/capture_jobs"; + + // Create pending jobs for alice and bob; set one running and one completed. + let (alice_pending, bob_running, alice_completed) = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + let a = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + let b = database::create_capture_job_as(&conn, "test", Some(&bob_uid)).unwrap(); + let c = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + database::update_capture_job_status(&conn, &b, "running", None, None, None).unwrap(); + database::update_capture_job_status(&conn, &c, "completed", Some("run-x"), None, None).unwrap(); + (a, b, c) + }; + + // Alice using status=active sees both the pending (own) and running (bob's) jobs, + // but not the completed one. + let (s, list) = get(&f.router, &format!("{base}?status=active"), Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + let visible = uids(&list); + assert!(visible.contains(&alice_pending), "alice_pending should be visible"); + assert!(visible.contains(&bob_running), "bob_running should be visible"); + assert!(!visible.contains(&alice_completed), "completed should not appear"); + + // Bob also sees both active jobs (including alice's pending). + let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&bob)).await; + let visible = uids(&list); + assert!(visible.contains(&alice_pending)); + assert!(visible.contains(&bob_running)); + + // Regular (non-active) status=pending still scopes to own jobs only. + let (_, list) = get(&f.router, &format!("{base}?status=pending"), Some(&alice)).await; + assert_eq!(uids(&list), vec![alice_pending]); + + // Regular listing without status filter still scopes to own jobs only. + let (_, list) = get(&f.router, base, Some(&bob)).await; + assert_eq!(uids(&list), vec![bob_running]); + } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 4188bf8..6612472 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -1720,6 +1720,8 @@ async fn capture_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let created_by = jobs::caller_user_uid(&state, &auth_user)?; let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; + let locator_notes = serde_json::json!({"locator": locator}).to_string(); + database::update_capture_job_notes(&conn, &job_uid, &locator_notes).ok(); drop(conn); // Load cookie rules and global uBlock / cookie-ext settings from the auth DB. let (cookie_rules, global_ublock, global_cookie_ext, global_modal_closer) = { @@ -1887,6 +1889,8 @@ async fn capture_text_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let created_by = jobs::caller_user_uid(&state, &auth_user)?; let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; + let text_notes = serde_json::json!({"locator": format!("text:{}", body.title.trim())}).to_string(); + database::update_capture_job_notes(&conn, &job_uid, &text_notes).ok(); drop(conn); // Spawn background text capture. diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 8829191..ec7319f 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useCallback, useRef, useMemo, createContext } from 'react' -import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections } from './api' +import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections, listActiveCaptureJobs } from './api' import LoginPage from './components/LoginPage.jsx' import SetupPage from './components/SetupPage.jsx' @@ -167,6 +167,48 @@ export default function App() { sessionStorage.setItem('pendingCaptures', JSON.stringify(pendingCaptures)) }, [pendingCaptures]) + // Foreign captures: active jobs started by other users (or other tabs) that this session + // didn't submit. Polled every 3 s so all authorized viewers see in-progress skeletons. + const [foreignCaptures, setForeignCaptures] = useState([]) + const pendingCapturesRef = useRef(pendingCaptures) + useEffect(() => { pendingCapturesRef.current = pendingCaptures }, [pendingCaptures]) + const handleCapturedRef = useRef(null) + + useEffect(() => { + if (!archiveId || !currentUser) { + setForeignCaptures([]) + return + } + // Track which foreign job UIDs were active on the last successful poll so we can + // detect when they settle (disappear from the active list) and refresh entries. + let prevForeignUids = new Set() + + const poll = async () => { + try { + const activeJobs = await listActiveCaptureJobs(archiveId) + // Exclude jobs the current session is already tracking locally. + const ownJobUids = new Set(pendingCapturesRef.current.map(c => c.jobUid)) + const foreign = activeJobs + .filter(job => !ownJobUids.has(job.job_uid)) + .map(job => { + let locator = '' + try { locator = JSON.parse(job.notes_json || '{}').locator || '' } catch {} + return { id: job.job_uid, jobUid: job.job_uid, locator, archiveId: job.archive_id } + }) + setForeignCaptures(foreign) + // If any previously-active foreign job no longer appears → it settled; refresh. + const newUids = new Set(foreign.map(j => j.jobUid)) + const hadSettled = [...prevForeignUids].some(uid => !newUids.has(uid)) + if (hadSettled) handleCapturedRef.current?.() + prevForeignUids = newUids + } catch {} + } + + poll() + const timer = setInterval(poll, 3000) + return () => { clearInterval(timer); setForeignCaptures([]) } + }, [archiveId, currentUser]) + const [ublockWarningIgnored, setUblockWarningIgnored] = useState( () => sessionStorage.getItem('ublockWarningIgnored') === 'true' ) @@ -647,6 +689,7 @@ export default function App() { fetchRuns(archiveId).then(setRuns), ]) }, [archiveId, searchQuery, tagFilter, selectedCollectionUid, loadEntries]) + useEffect(() => { handleCapturedRef.current = handleCaptured }, [handleCaptured]) const handleToast = useCallback((text, locator, type = 'error', headline = null) => { // Only suppress per-item ublock/cookie warnings (those carry a locator). @@ -798,6 +841,7 @@ export default function App() { onRowClick={handleRowClick} archiveId={archiveId} pendingCaptures={pendingCaptures} + foreignCaptures={foreignCaptures} deletedUids={deletedUids} renamedTitles={renamedTitles} isPublicSession={!currentUser} diff --git a/frontend/src/api.js b/frontend/src/api.js index 2efe474..42a6f31 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -334,6 +334,10 @@ export async function pollCaptureJob(archiveId, jobUid) { return getJson(`/api/archives/${archiveId}/capture_jobs/${jobUid}`); } +export async function listActiveCaptureJobs(archiveId) { + return getJson(`/api/archives/${archiveId}/capture_jobs?status=active`); +} + // ── Auth helpers ───────────────────────────────────────────────────────────── export async function checkSetup() { diff --git a/frontend/src/components/EntriesView.jsx b/frontend/src/components/EntriesView.jsx index 89bdb9d..97c4345 100644 --- a/frontend/src/components/EntriesView.jsx +++ b/frontend/src/components/EntriesView.jsx @@ -2,7 +2,7 @@ import SkeletonEntryRow from './SkeletonEntryRow'; import EntryRow from './EntryRow'; -export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) { +export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], foreignCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) { return (
@@ -18,6 +18,9 @@ export default function EntriesView({ entries, selectedUids, onRowClick, archive {pendingCaptures.filter(c => c.archiveId === archiveId).reverse().map(cap => ( ))} + {foreignCaptures.filter(c => c.archiveId === archiveId).map(cap => ( + + ))} {entries.map((entry, idx) => (