mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
feat: show in-progress captures to all authorized users
Store the locator in notes_json immediately on job creation so other users have a display label. Add list_active_capture_jobs (no creator scoping) and a status=active shorthand on the job list endpoint so any ROLE_USER can poll pending+running jobs for the current archive. Frontend polls GET /api/archives/:id/capture_jobs?status=active every 3 s, injects SkeletonEntryRow for foreign jobs (not in local pendingCaptures), and refreshes the entry list when a foreign job settles.
This commit is contained in:
parent
151c18eb61
commit
64ef4ca313
7 changed files with 147 additions and 3 deletions
|
|
@ -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<Vec<CaptureJobSummary>> {
|
||||
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::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// One `archive_run_items` row of a job's run.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct JobItem {
|
||||
|
|
|
|||
|
|
@ -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<Option<CaptureJobRecord>> {
|
||||
conn.query_row(
|
||||
|
|
|
|||
|
|
@ -67,11 +67,18 @@ async fn list_capture_jobs_handler(
|
|||
Query(q): Query<JobListQuery>,
|
||||
) -> Result<Json<Vec<archive::CaptureJobSummary>>, 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]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<section id="archive-view" className="view is-active">
|
||||
<div className="entry-table">
|
||||
|
|
@ -18,6 +18,9 @@ export default function EntriesView({ entries, selectedUids, onRowClick, archive
|
|||
{pendingCaptures.filter(c => c.archiveId === archiveId).reverse().map(cap => (
|
||||
<SkeletonEntryRow key={cap.id} locator={cap.locator} />
|
||||
))}
|
||||
{foreignCaptures.filter(c => c.archiveId === archiveId).map(cap => (
|
||||
<SkeletonEntryRow key={cap.id} locator={cap.locator} />
|
||||
))}
|
||||
{entries.map((entry, idx) => (
|
||||
<EntryRow
|
||||
key={entry.entry_uid}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue