Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : apps/navigator-web/src/screens/Sessions.tsx9 * Module : screens10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Screen A — the sessions of the remote browser, their real state, and the actions an administrator may take.43import { useCallback, useState, type FormEvent, type MouseEvent } from 'react';44import { get, post, type Me } from '../../../shared/api.ts';45import { tCode, useLang, useT } from '../i18n.ts';46import type { SessionList, SessionRow, WorkerRow } from '../types.ts';47import { ErrorLine, StateBadge, fmtTime, shortId, usePoll } from '../ui.tsx';48import { AddPasskey } from './Auth.tsx';4950type Props = { me: Me; emergency: boolean; navigate: (to: string) => void; refreshMe: () => Promise<void> };5152export function Sessions({ me, emergency, navigate, refreshMe }: Props) {53 const t = useT(); const { lang } = useLang();54 const [data, setData] = useState<SessionList | null>(null);55 const [workers, setWorkers] = useState<WorkerRow[] | null>(null);56 const [err, setErr] = useState<unknown>(null);57 const [reminder, setReminder] = useState<{ label: string; text: string } | null>(null);58 const load = useCallback(async () => {59 try {60 const [s, w] = await Promise.all([get<SessionList>('/v1/navigator/sessions'), get<{ workers: WorkerRow[] }>('/v1/workers')]);61 setData(s); setWorkers(w.workers); setErr(null);62 } catch (e) { setErr(e); }63 }, []);64 usePoll(load, 4000);6566 return (67 <main className="page">68 {me.passkeysHere === 0 && <AddPasskey onDone={refreshMe} />}69 <header className="page-head">70 <h1>{t('list.title')}</h1>71 <p className="lead">{t('list.lead')}</p>72 </header>73 <div aria-live="polite"><ErrorLine error={err} /></div>74 {reminder && (75 <section className="note strong" role="status">76 <h2>{t('list.revoked_title', { label: reminder.label })}</h2>77 <p>{reminder.text}</p>78 <button type="button" className="btn" onClick={() => setReminder(null)}>{t('list.reminder_ack')}</button>79 </section>80 )}81 {data === null && !err && <p role="status">{t('common.loading')}</p>}82 {data && data.sessions.length === 0 && <p className="empty">{t('list.empty')}</p>}83 {data && data.sessions.length > 0 && (84 <ul className="sessions">85 {data.sessions.map((s) => <SessionItem key={s.id} s={s} me={me} emergency={emergency} navigate={navigate} reload={load} onRevoked={(text) => setReminder({ label: s.label, text })} />)}86 </ul>87 )}8889 <CreateSession workers={workers} onCreated={load} />9091 <section aria-labelledby="wk">92 <h2 id="wk">{t('workers.title')}</h2>93 {workers === null ? <p>{t('common.loading')}</p> : workers.length === 0 ? <p className="empty">{t('workers.empty')}</p> : (94 <table className="tbl">95 <thead><tr><th scope="col">{t('workers.name')}</th><th scope="col">{t('workers.status')}</th><th scope="col">{t('workers.host')}</th><th scope="col">{t('workers.beat')}</th></tr></thead>96 <tbody>{workers.map((w) => (97 <tr key={w.id}><th scope="row">{w.name}</th><td><WorkerStatus status={w.status} /></td><td className="mono">{w.host || '—'}</td><td className="num">{fmtTime(w.last_heartbeat_at, lang)}</td></tr>98 ))}</tbody>99 </table>100 )}101 </section>102103 {data && data.revoked.length > 0 && (104 <details className="revoked">105 <summary>{t('list.revoked', { n: data.revoked.length })}</summary>106 <ul>{data.revoked.map((s) => <li key={s.id}><span>{s.label}</span> <code>{shortId(s.id)}</code> <span>{s.worker_name}</span></li>)}</ul>107 </details>108 )}109 </main>110 );111}112113function WorkerStatus({ status }: { status: string }) {114 const t = useT();115 const mark = status === 'online' ? '●' : status === 'disabled' ? '×' : '○';116 return <span className={`wstat wstat-${status}`}><span aria-hidden="true">{mark}</span> {tCode(t, 'wstatus', status)}</span>;117}118119function SessionItem({ s, me, emergency, navigate, reload, onRevoked }: { s: SessionRow; me: Me; emergency: boolean; navigate: (to: string) => void; reload: () => Promise<void>; onRevoked: (reminder: string) => void }) {120 const t = useT(); const { lang } = useLang();121 const [busy, setBusy] = useState<string | null>(null);122 const [err, setErr] = useState<unknown>(null);123 const [confirmRevoke, setConfirmRevoke] = useState(false);124 const mine = s.lease?.holderKind === 'human' && s.lease.holderId === me.user.id;125 const holder = !s.lease ? t('lease.none') : mine ? t('lease.you') : s.lease.holderKind === 'human' ? t('lease.other_human') : s.lease.holderKind === 'agent' ? t('lease.agent') : s.lease.holderKind;126 const stopped = s.wanted === 'stopped';127 const act = async (name: 'takeover' | 'release' | 'pause' | 'resume' | 'close' | 'revoke') => {128 setBusy(name); setErr(null);129 try {130 const r = await post<{ state?: string; reminder?: string }>(`/v1/navigator/sessions/${s.id}/${name}`);131 if (name === 'revoke') { setConfirmRevoke(false); onRevoked(r.reminder ?? t('list.reminder_default')); }132 await reload();133 if (name === 'takeover') navigate(`/s/${s.id}`);134 } catch (e) { setErr(e); } finally { setBusy(null); }135 };136 const open = (e: MouseEvent) => { if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; e.preventDefault(); navigate(`/s/${s.id}`); };137 const b = (name: Parameters<typeof act>[0], label: string, disabled = false, cls = '') => (138 <button type="button" className={`btn ${cls}`} disabled={busy !== null || disabled} onClick={() => act(name)}>{busy === name ? t('common.working') : label}</button>139 );140 return (141 <li className="session" aria-labelledby={`s-${s.id}`}>142 <div className="session-head">143 <h2 id={`s-${s.id}`}>{s.label}</h2>144 <code title={s.id}>{shortId(s.id)}</code>145 </div>146 <StateBadge state={s.state} explain />147 <dl className="facts">148 <div><dt>{t('list.worker')}</dt><dd>{s.worker_name} · <WorkerStatus status={s.worker_status} /></dd></div>149 <div><dt>{t('list.browser')}</dt><dd>{stopped ? t('list.browser_closed') : t('list.browser_wanted')}</dd></div>150 <div><dt>{t('list.control')}</dt><dd>{holder}</dd></div>151 <div><dt>{t('list.last_host')}</dt><dd className="mono">{s.last_url_host || '—'}</dd></div>152 <div><dt>{t('list.scope')}</dt><dd className="num">{s.confirmed_at ? t('list.scope_n', { n: s.scope_page_ids?.length ?? 0, when: fmtTime(s.confirmed_at, lang) }) : t('list.scope_none')}</dd></div>153 {s.state_reason && <div><dt>{t('list.reason')}</dt><dd>{s.state_reason}</dd></div>}154 </dl>155 <div className="row actions">156 <a className="btn primary" href={`/s/${s.id}`} onClick={open}>{t('list.open')}</a>157 {mine ? b('release', t('act.release')) : b('takeover', t('act.take'), emergency)}158 {s.state === 'PAUSED' || stopped ? b('resume', stopped ? t('act.reopen') : t('act.resume'), emergency) : b('pause', t('act.pause'))}159 {!stopped && b('close', t('act.close'))}160 {!confirmRevoke && <button type="button" className="btn danger-outline" disabled={busy !== null} onClick={() => setConfirmRevoke(true)}>{t('act.revoke')}</button>}161 </div>162 {confirmRevoke && (163 <div className="confirm" role="group" aria-label={t('act.revoke')}>164 <p>{t('list.revoke_warn')}</p>165 <div className="row">{b('revoke', t('list.revoke_confirm'), false, 'danger')}<button type="button" className="btn" disabled={busy !== null} onClick={() => setConfirmRevoke(false)}>{t('common.cancel')}</button></div>166 </div>167 )}168 <div aria-live="polite"><ErrorLine error={err} onDismiss={() => setErr(null)} /></div>169 </li>170 );171}172173function CreateSession({ workers, onCreated }: { workers: WorkerRow[] | null; onCreated: () => Promise<void> }) {174 const t = useT();175 const [label, setLabel] = useState(''); const [workerId, setWorkerId] = useState(''); const [startUrl, setStartUrl] = useState('');176 const [busy, setBusy] = useState(false); const [err, setErr] = useState<unknown>(null); const [done, setDone] = useState<string | null>(null);177 const usable = (workers ?? []).filter((w) => w.status !== 'disabled');178 const chosen = workerId || usable[0]?.id || '';179 const submit = async (e: FormEvent) => {180 e.preventDefault(); setBusy(true); setErr(null); setDone(null);181 try {182 const r = await post<{ id: string }>('/v1/navigator/sessions', { label: label.trim(), workerId: chosen, ...(startUrl.trim() ? { startUrl: startUrl.trim() } : {}) });183 setDone(r.id); setLabel(''); setStartUrl(''); await onCreated();184 } catch (x) { setErr(x); } finally { setBusy(false); }185 };186 return (187 <section aria-labelledby="new">188 <h2 id="new">{t('create.title')}</h2>189 <p className="lead">{t('create.lead')}</p>190 <form className="form" onSubmit={submit}>191 <div className="field"><label htmlFor="c-label">{t('create.label')}</label><input id="c-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} required autoComplete="off" /></div>192 <div className="field"><label htmlFor="c-worker">{t('create.worker')}</label>193 <select id="c-worker" value={chosen} onChange={(e) => setWorkerId(e.target.value)} required>194 {usable.length === 0 && <option value="">{t('create.no_worker')}</option>}195 {usable.map((w) => <option key={w.id} value={w.id}>{w.name} — {tCode(t, 'wstatus', w.status)}</option>)}196 </select></div>197 <div className="field"><label htmlFor="c-url">{t('create.url')}</label><input id="c-url" type="url" inputMode="url" value={startUrl} onChange={(e) => setStartUrl(e.target.value)} maxLength={500} placeholder="https://" autoComplete="off" autoCapitalize="off" spellCheck={false} aria-describedby="c-url-h" /><p id="c-url-h" className="hint">{t('create.url_hint')}</p></div>198 <div className="row"><button type="submit" className="btn primary" disabled={busy || !chosen || !label.trim()}>{busy ? t('common.working') : t('create.submit')}</button></div>199 <div aria-live="polite"><ErrorLine error={err} />{done && <p className="ok" role="status">{t('create.done')} <code>{shortId(done)}</code></p>}</div>200 </form>201 </section>202 );203}204