Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: name the Stacker News account on every tab and move account config into a tabbed drawer (#3319)

[._.]/ Adam Eivy5f4655049943
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5d5c176522..9d562ff01a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -135,6 +135,7 @@
## UI Consistency
+- **[issue-3319] Stacker News now says which account you are looking at, on every tab.** Territories, monitored items, and queued actions were always filtered to the selected account, but nothing on screen said so — the only hint was a small grey `@username` in the header, and the account list lived on the Accounts tab, so switching accounts meant leaving whatever you were working in. The header now carries an account switcher that works from any tab and keeps you on it, and every scoped heading and empty state names the account: "Communities for @…", "Approval queue for @…", "Add community to @…". The account form — nineteen fields that used to render twice at once, side by side, in one flat scroll — moved into the shared drawer, grouped into Identity, Monitoring & models, Stewardship, and Budgets tabs with the open tab kept in the URL. Because the drawer unmounts inactive tabs, Save re-validates every field itself and jumps to the tab holding the bad one instead of letting an emptied number box through as a zero.
- **[issue-3293] Sprite approve/lock confirmations, the near-black canvases, and the final music-video player now follow the shared conventions.** The shared `ConfirmButtonPair` had no positive tone, so the "Approve this walk" and "Freeze this reference version" confirmations in the sprite workflows hand-rolled their own confirm/cancel markup and each drifted on busy text, spinner, and touch-target height; a `success` tone closes that gap and five hand-rolled pairs now share one implementation, with a 36px minimum height on every pair in the app. The four piano-roll/ambient surfaces that hardcoded a near-black hex now say why they don't follow the theme — the rolls read their background from the same `ROLL_BG` constant their canvas paints with, so the CSS fallback can never drift from the painted pixels, and Ambient mode is explicitly `bg-black` because its white-on-black layers would be unreadable under a day theme. The rendered music video also reserves its 16:9 box like the scene thumbnails already do, so the Download row above it stops jumping when the video's dimensions resolve.
## Internal
diff --git a/client/src/pages/StackerNews.jsx b/client/src/pages/StackerNews.jsx
index bb42f260e3..75b3e78a06 100644
--- a/client/src/pages/StackerNews.jsx
+++ b/client/src/pages/StackerNews.jsx
@@ -1,10 +1,12 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Newspaper, Plus, RefreshCw, ShieldCheck, ShieldAlert } from 'lucide-react';
import * as api from '../services/api';
+import Drawer from '../components/Drawer';
import PageHeader from '../components/PageHeader';
import PageSkeleton from '../components/ui/PageSkeleton';
import TabPills from '../components/ui/TabPills';
+import useDrawerTab from '../hooks/useDrawerTab';
import useLocalModels from '../hooks/useLocalModels';
import useVisionModelIds from '../hooks/useVisionModelIds';
import { useValidTab } from '../hooks/useValidTab';
@@ -21,6 +23,38 @@ const TABS = [
{ id: 'activity', label: 'Activity', icon: RefreshCw },
{ id: 'accounts', label: 'Accounts & Safety', icon: ShieldAlert },
];
+// The account form is a 19-field config surface, so it lives in the shared
+// tabbed Drawer rather than a page-length flat scroll (client/src/CLAUDE.md).
+const ACCOUNT_TABS = [
+ { id: 'identity', label: 'Identity' },
+ { id: 'monitoring', label: 'Monitoring & models' },
+ { id: 'stewardship', label: 'Stewardship' },
+ { id: 'budgets', label: 'Budgets' },
+];
+const ACCOUNT_TAB_IDS = ACCOUNT_TABS.map((accountTab) => accountTab.id);
+// Every numeric account field, with the tab it lives on, so a Save fired from a
+// different tab can still report which one is wrong.
+const ACCOUNT_NUMBER_FIELDS = [
+ { key: 'monitoringIntervalMinutes', label: 'Monitoring interval (minutes)', tab: 'monitoring', min: 5, max: 1440 },
+ { key: 'maxPerHour', label: 'Max/hour', tab: 'budgets', min: 1, max: 50 },
+ { key: 'maxPerDay', label: 'Max/day', tab: 'budgets', min: 1, max: 200 },
+ { key: 'minMinutesBetween', label: 'Spacing min', tab: 'budgets', min: 0, max: 1440 },
+];
+// The Drawer body remounts per tab, so fields on an inactive tab are unmounted
+// and the browser's `required` / `min` / `max` constraint validation never runs
+// for them. Re-check every rule here and return the tab to surface. Note the
+// explicit digits test: `Number('')` is 0, so an emptied box would otherwise
+// slip past a `min: 0` bound.
+const validateAccountForm = (form) => {
+ if (!String(form.label || '').trim() || !String(form.username || '').trim()) {
+ return { tab: 'identity', message: 'Local label and Stacker News username are required.' };
+ }
+ const invalid = ACCOUNT_NUMBER_FIELDS.find((field) => {
+ const raw = String(form[field.key] ?? '').trim();
+ return !/^\d+$/.test(raw) || Number(raw) < field.min || Number(raw) > field.max;
+ });
+ return invalid ? { tab: invalid.tab, message: `${invalid.label} must be a whole number from ${invalid.min} to ${invalid.max}.` } : null;
+};
const emptyAccount = { label: '', username: '', apiKey: '', clearApiKey: false, enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 30, analysisEnabled: false, textModel: '', visionModel: '', guidance: '', tone: '', allowedThemes: '', disallowedThemes: '', escalationCues: '', desiredEngagement: '', maxPerHour: 3, maxPerDay: 12, minMinutesBetween: 5 };
const emptyTerritory = { slug: '', label: '', isOwned: false, monitoringEnabled: '', inheritAccountRules: true, guidance: '', tone: '', allowedThemes: '', disallowedThemes: '', escalationCues: '' };
const emptyDraft = { kind: 'publish_comment', itemId: '', territoryId: '', title: '', body: '', destination: 'item' };
@@ -65,6 +99,8 @@ export default function StackerNews() {
const navigate = useNavigate();
const { accountId } = useParams();
const tab = useValidTab(TABS, 'review');
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [accountDrawerTab, setAccountDrawerTab] = useDrawerTab('snAccountTab', 'identity', ACCOUNT_TAB_IDS);
const localModels = useLocalModels();
const { idsByProvider: visionIds, loaded: visionLoaded } = useVisionModelIds();
const [accounts, setAccounts] = useState([]);
@@ -84,6 +120,7 @@ export default function StackerNews() {
const [editTerritory, setEditTerritory] = useState(emptyTerritory);
const [deleteTerritoryId, setDeleteTerritoryId] = useState(null);
const [draft, setDraft] = useState(emptyDraft);
+ const [accountFormError, setAccountFormError] = useState('');
const [analysisResults, setAnalysisResults] = useState({});
const [feedbackDrafts, setFeedbackDrafts] = useState({});
const selectedLoadRef = useRef(0);
@@ -95,6 +132,21 @@ export default function StackerNews() {
const selected = accounts.find((account) => account.id === accountId) || null;
const activeTab = selected ? tab : 'accounts';
const accountPath = (id, nextTab = tab) => `/stacker-news/${id}/${nextTab}`;
+ // Which account form the drawer is showing, in the URL so the open panel is
+ // shareable and reload-safe. `edit` needs a selected account to edit; every
+ // account switch navigates by path, which drops the param and closes the drawer.
+ const accountFormMode = searchParams.get('snAccount');
+ const accountDrawerOpen = accountFormMode === 'new' || (accountFormMode === 'edit' && Boolean(selected));
+ const openAccountForm = useCallback((mode) => {
+ setAccountFormError('');
+ setSearchParams((previous) => {
+ const next = new URLSearchParams(previous);
+ if (mode) next.set('snAccount', mode);
+ else { next.delete('snAccount'); next.delete('snAccountTab'); }
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
+ const closeAccountForm = useCallback(() => openAccountForm(null), [openAccountForm]);
const models = useMemo(() => [...new Set(localModels.ollama)], [localModels.ollama]);
// The vision stage sends images to whatever id is configured, so only models
// that can actually see one belong in that picker: the server's capability map
@@ -168,8 +220,19 @@ export default function StackerNews() {
promise.then(onSuccess, (err) => setError(err.message)).finally(() => setBusy(''));
};
+ // Save can fire from any drawer tab, so reject on the first invalid field and
+ // switch to the tab that holds it rather than failing silently server-side.
+ const rejectInvalidAccount = (form) => {
+ const invalid = validateAccountForm(form);
+ if (!invalid) { setAccountFormError(''); return false; }
+ setAccountDrawerTab(invalid.tab);
+ setAccountFormError(invalid.message);
+ return true;
+ };
+
const createAccount = (event) => {
event.preventDefault();
+ if (rejectInvalidAccount(newAccount)) return;
finish('create-account', api.createStackerNewsAccount({
label: newAccount.label, username: newAccount.username, enabled: newAccount.enabled, ...(newAccount.apiKey ? { apiKey: newAccount.apiKey } : {}),
monitoringEnabled: newAccount.monitoringEnabled, monitoringIntervalMinutes: Number(newAccount.monitoringIntervalMinutes),
@@ -183,6 +246,7 @@ export default function StackerNews() {
const saveAccount = (event) => {
event.preventDefault();
if (!selected) return;
+ if (rejectInvalidAccount(editAccount)) return;
const savedAccountId = selected.id;
finish('save-account', api.updateStackerNewsAccount(savedAccountId, {
label: editAccount.label, username: editAccount.username, enabled: editAccount.enabled,
@@ -197,6 +261,7 @@ export default function StackerNews() {
savedAccountRef.current = nextSaved;
setSavedAccount(nextSaved);
setEditAccount(nextSaved);
+ closeAccountForm();
setNotice('Account rules and schedule saved.');
});
};
@@ -276,10 +341,14 @@ export default function StackerNews() {
setNotice(result.state === 'completed' ? 'Reviewed action completed.' : `Action failed safely: ${result.error}`);
});
+ // Every scoped list is filtered to the selected account, so each section says
+ // whose workspace it is showing rather than reading as a global list.
+ const scope = selected ? `@${selected.username}` : '';
+
const renderReview = () => (
<div className="grid gap-3 xl:grid-cols-2">
<section className="rounded border border-port-border bg-port-card p-4">
- <h2 className="font-semibold text-white">Approval queue</h2>
+ <h2 className="font-semibold text-white">Approval queue for {scope}</h2>
<p className="mt-1 text-sm text-gray-400">Approval and execution are separate. Identity, content freshness, rules, budgets, and idempotency are rechecked at execution.</p>
<div className="mt-3 space-y-2">
{visibleActions.filter((action) => ['pending_review', 'approved'].includes(action.state)).map((action) => (
@@ -292,12 +361,12 @@ export default function StackerNews() {
{action.state === 'approved' && <button className={`${buttonClass} mt-2`} disabled={busy === `execute-${action.id}`} onClick={() => executeAction(action)}>Execute reviewed action</button>}
</div>
))}
- {!visibleActions.some((action) => ['pending_review', 'approved'].includes(action.state)) && <p className="text-sm text-gray-500">No actions are waiting.</p>}
+ {!visibleActions.some((action) => ['pending_review', 'approved'].includes(action.state)) && <p className="text-sm text-gray-500">No actions are waiting for {scope}.</p>}
</div>
</section>
<section className="rounded border border-port-border bg-port-card p-4">
- <div className="flex flex-wrap items-center justify-between gap-2"><div><h2 className="font-semibold text-white">Monitored content</h2><p className="text-sm text-gray-400">Remote text and images remain untrusted data.</p></div><button className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div>
- <div className="mt-3 space-y-2">{visibleItems.map((item) => <div key={item.id} className="rounded border border-port-border p-3"><div className="text-sm font-medium text-white">{item.title || `${item.kind} by @${item.authorName}`}</div><div className="mt-1 line-clamp-3 text-sm text-gray-400">{item.body}</div>{analysisResults[item.id] && <div className="mt-2 rounded bg-port-bg p-2 text-xs text-gray-300">Policy: {analysisResults[item.id].stale ? 'stale' : analysisResults[item.id].policy?.decision || 'review'}{analysisResults[item.id].policy?.reasons?.length ? ` · ${analysisResults[item.id].policy.reasons.join(', ')}` : ''}<div className="mt-2 flex gap-2"><input aria-label={`Feedback for ${item.title || item.id}`} className={fieldClass} placeholder="Moderator feedback" value={feedbackDrafts[item.id] || ''} onChange={(event) => setFeedbackDrafts((previous) => ({ ...previous, [item.id]: event.target.value }))} /><button className={secondaryButton} disabled={!analysisResults[item.id].analysisId || busy === `feedback-${item.id}`} onClick={() => saveFeedback(item)}>Save feedback</button></div></div>}<button className={`${secondaryButton} mt-2`} disabled={busy === `analyze-${item.id}`} onClick={() => analyze(item)}>Run local analysis</button></div>)}{!visibleItems.length && <p className="text-sm text-gray-500">No stored content. Add a territory, then sync explicitly or enable a schedule.</p>}</div>
+ <div className="flex flex-wrap items-center justify-between gap-2"><div><h2 className="font-semibold text-white">Monitored content for {scope}</h2><p className="text-sm text-gray-400">Remote text and images remain untrusted data.</p></div><button className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div>
+ <div className="mt-3 space-y-2">{visibleItems.map((item) => <div key={item.id} className="rounded border border-port-border p-3"><div className="text-sm font-medium text-white">{item.title || `${item.kind} by @${item.authorName}`}</div><div className="mt-1 line-clamp-3 text-sm text-gray-400">{item.body}</div>{analysisResults[item.id] && <div className="mt-2 rounded bg-port-bg p-2 text-xs text-gray-300">Policy: {analysisResults[item.id].stale ? 'stale' : analysisResults[item.id].policy?.decision || 'review'}{analysisResults[item.id].policy?.reasons?.length ? ` · ${analysisResults[item.id].policy.reasons.join(', ')}` : ''}<div className="mt-2 flex gap-2"><input aria-label={`Feedback for ${item.title || item.id}`} className={fieldClass} placeholder="Moderator feedback" value={feedbackDrafts[item.id] || ''} onChange={(event) => setFeedbackDrafts((previous) => ({ ...previous, [item.id]: event.target.value }))} /><button className={secondaryButton} disabled={!analysisResults[item.id].analysisId || busy === `feedback-${item.id}`} onClick={() => saveFeedback(item)}>Save feedback</button></div></div>}<button className={`${secondaryButton} mt-2`} disabled={busy === `analyze-${item.id}`} onClick={() => analyze(item)}>Run local analysis</button></div>)}{!visibleItems.length && <p className="text-sm text-gray-500">No stored content for {scope}. Add a territory, then sync explicitly or enable a schedule.</p>}</div>
</section>
</div>
);
@@ -305,7 +374,7 @@ export default function StackerNews() {
const renderTerritory = () => (
<div className="grid gap-3 lg:grid-cols-2">
<section className="rounded border border-port-border bg-port-card p-4">
- <h2 className="font-semibold text-white">Configured communities</h2>
+ <h2 className="font-semibold text-white">Communities for {scope}</h2>
<div className="mt-3 space-y-2">
{visibleTerritories.map((territory) => editingTerritoryId === territory.id ? (
<TerritoryForm key={territory.id} prefix={`edit-territory-${territory.id}`} title={`Edit ${territory.label || territory.slug}`} form={editTerritory} setForm={setEditTerritory} onSubmit={saveTerritory} busy={busy === `save-territory-${territory.id}`} onCancel={() => { setEditingTerritoryId(null); setEditTerritory(emptyTerritory); }} submitLabel="Save community" />
@@ -320,45 +389,156 @@ export default function StackerNews() {
</div>
</div>
))}
- {!visibleTerritories.length && <p className="text-sm text-gray-500">Add communities this account monitors or owns.</p>}
+ {!visibleTerritories.length && <p className="text-sm text-gray-500">Add communities {scope} monitors or owns.</p>}
</div>
</section>
- <TerritoryForm prefix="new-territory" title="Add community" form={newTerritory} setForm={setNewTerritory} onSubmit={createTerritory} busy={busy === 'create-territory'} submitLabel="Add community" />
+ <TerritoryForm prefix="new-territory" title={`Add community to ${scope}`} form={newTerritory} setForm={setNewTerritory} onSubmit={createTerritory} busy={busy === 'create-territory'} submitLabel="Add community" />
</div>
);
const renderDrafts = () => {
const post = draft.kind.endsWith('_post');
const comment = draft.kind.endsWith('_comment');
- return <form className="mx-auto max-w-2xl rounded border border-port-border bg-port-card p-4" onSubmit={createAction}><h2 className="font-semibold text-white">Prepare a review-gated action</h2><p className="mt-1 text-sm text-gray-400">Wallet actions are browser handoffs only. Publishing uses the constrained API after separate approval.</p><div className="mt-3 space-y-3"><Field id="action-kind" label="Action"><select id="action-kind" className={fieldClass} value={draft.kind} onChange={(event) => setDraft({ ...draft, kind: event.target.value })}><option value="draft_comment">Local comment draft</option><option value="publish_comment">Publish comment after review</option><option value="draft_post">Local post draft</option><option value="publish_post">Publish post after review</option><option value="open_browser">Open fixed browser handoff</option></select></Field>{draft.kind === 'open_browser' && <Field id="action-destination" label="Handoff"><select id="action-destination" className={fieldClass} value={draft.destination} onChange={(event) => setDraft({ ...draft, destination: event.target.value })}><option value="item">Item (zap, downzap, boost, or manual interaction)</option><option value="territory_settings">Territory settings</option></select></Field>}{(comment || (draft.kind === 'open_browser' && draft.destination === 'item')) && <Field id="action-item" label="Source item"><select id="action-item" required className={fieldClass} value={draft.itemId} onChange={(event) => setDraft({ ...draft, itemId: event.target.value })}><option value="">Choose item</option>{visibleItems.map((item) => <option key={item.id} value={item.id}>{item.title || `${item.kind} by ${item.authorName}`}</option>)}</select></Field>}{(post || (draft.kind === 'open_browser' && draft.destination === 'territory_settings')) && <Field id="action-territory" label="Territory"><select id="action-territory" required className={fieldClass} value={draft.territoryId} onChange={(event) => setDraft({ ...draft, territoryId: event.target.value })}><option value="">Choose territory</option>{visibleTerritories.map((territory) => <option key={territory.id} value={territory.id}>{territory.label || territory.slug}</option>)}</select></Field>}{post && <Field id="action-title" label="Title"><input id="action-title" required className={fieldClass} value={draft.title} onChange={(event) => setDraft({ ...draft, title: event.target.value })} /></Field>}{(post || comment) && <Field id="action-body" label="Draft text"><textarea id="action-body" required className={fieldClass} rows="6" value={draft.body} onChange={(event) => setDraft({ ...draft, body: event.target.value })} /></Field>}<button className={buttonClass} disabled={busy === 'create-action'}>Send to approval queue</button></div></form>;
+ return <form className="mx-auto max-w-2xl rounded border border-port-border bg-port-card p-4" onSubmit={createAction}><h2 className="font-semibold text-white">Prepare a review-gated action for {scope}</h2><p className="mt-1 text-sm text-gray-400">Wallet actions are browser handoffs only. Publishing uses the constrained API after separate approval.</p><div className="mt-3 space-y-3"><Field id="action-kind" label="Action"><select id="action-kind" className={fieldClass} value={draft.kind} onChange={(event) => setDraft({ ...draft, kind: event.target.value })}><option value="draft_comment">Local comment draft</option><option value="publish_comment">Publish comment after review</option><option value="draft_post">Local post draft</option><option value="publish_post">Publish post after review</option><option value="open_browser">Open fixed browser handoff</option></select></Field>{draft.kind === 'open_browser' && <Field id="action-destination" label="Handoff"><select id="action-destination" className={fieldClass} value={draft.destination} onChange={(event) => setDraft({ ...draft, destination: event.target.value })}><option value="item">Item (zap, downzap, boost, or manual interaction)</option><option value="territory_settings">Territory settings</option></select></Field>}{(comment || (draft.kind === 'open_browser' && draft.destination === 'item')) && <Field id="action-item" label="Source item"><select id="action-item" required className={fieldClass} value={draft.itemId} onChange={(event) => setDraft({ ...draft, itemId: event.target.value })}><option value="">Choose item</option>{visibleItems.map((item) => <option key={item.id} value={item.id}>{item.title || `${item.kind} by ${item.authorName}`}</option>)}</select></Field>}{(post || (draft.kind === 'open_browser' && draft.destination === 'territory_settings')) && <Field id="action-territory" label="Territory"><select id="action-territory" required className={fieldClass} value={draft.territoryId} onChange={(event) => setDraft({ ...draft, territoryId: event.target.value })}><option value="">Choose territory</option>{visibleTerritories.map((territory) => <option key={territory.id} value={territory.id}>{territory.label || territory.slug}</option>)}</select></Field>}{post && <Field id="action-title" label="Title"><input id="action-title" required className={fieldClass} value={draft.title} onChange={(event) => setDraft({ ...draft, title: event.target.value })} /></Field>}{(post || comment) && <Field id="action-body" label="Draft text"><textarea id="action-body" required className={fieldClass} rows="6" value={draft.body} onChange={(event) => setDraft({ ...draft, body: event.target.value })} /></Field>}<button className={buttonClass} disabled={busy === 'create-action'}>Send to approval queue</button></div></form>;
};
const renderAccounts = () => (
- <div className="grid gap-3 xl:grid-cols-3">
- <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Accounts</h2><div className="mt-3 space-y-2">{accounts.map((account) => <button key={account.id} className={`block w-full rounded border p-3 text-left ${account.id === selected?.id ? 'border-port-accent' : 'border-port-border'}`} onClick={() => navigate(accountPath(account.id, 'accounts'))}><div className="flex justify-between gap-2"><span className="font-medium text-white">{account.label}</span><span className="text-xs text-gray-400">{account.apiKeyConfigured ? 'Key protected' : 'No key'}</span></div><div className="mt-1 text-sm text-gray-400">@{account.username} · {account.monitoringEnabled ? `every ${account.monitoringIntervalMinutes}m` : 'monitoring off'}</div></button>)}{!accounts.length && <p className="text-sm text-gray-500">No accounts configured.</p>}</div></section>
- {selected ? <AccountForm title="Selected account" submitLabel="Save account" form={editAccount} setForm={setEditAccount} models={models} visionModels={visionModels} visionPending={visionPending} onSubmit={saveAccount} busy={busy === 'save-account'} canClearCredential={selected.apiKeyConfigured} extra={<div className="flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkConnection}>Check API identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkBrowser}>Check browser identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div>} /> : <div className="rounded border border-port-border bg-port-card p-4 text-sm text-gray-400">Choose an account to edit its independent rules, models, and monitoring schedule.</div>}
- <AccountForm title="Add account" submitLabel="Add protected account" form={newAccount} setForm={setNewAccount} models={models} visionModels={visionModels} visionPending={visionPending} onSubmit={createAccount} busy={busy === 'create-account'} showCredential />
+ <div className="grid gap-3 lg:grid-cols-2">
+ <section className="rounded border border-port-border bg-port-card p-4">
+ <div className="flex flex-wrap items-center justify-between gap-2"><h2 className="font-semibold text-white">Accounts</h2><button type="button" className={buttonClass} onClick={() => openAccountForm('new')}>Add account</button></div>
+ <div className="mt-3 space-y-2">{accounts.map((account) => <button key={account.id} className={`block w-full rounded border p-3 text-left ${account.id === selected?.id ? 'border-port-accent' : 'border-port-border'}`} onClick={() => navigate(accountPath(account.id, 'accounts'))}><div className="flex justify-between gap-2"><span className="font-medium text-white">{account.label}</span><span className="text-xs text-gray-400">{account.apiKeyConfigured ? 'Key protected' : 'No key'}</span></div><div className="mt-1 text-sm text-gray-400">@{account.username} · {account.monitoringEnabled ? `every ${account.monitoringIntervalMinutes}m` : 'monitoring off'}</div></button>)}{!accounts.length && <p className="text-sm text-gray-500">No accounts configured.</p>}</div>
+ </section>
+ {selected ? (
+ <section className="rounded border border-port-border bg-port-card p-4">
+ <h2 className="font-semibold text-white">Settings and safety for {scope}</h2>
+ <p className="mt-1 text-sm text-gray-400">{selected.label} · {selected.monitoringEnabled ? `monitored every ${selected.monitoringIntervalMinutes}m` : 'monitoring off'} · {selected.apiKeyConfigured ? 'API key stored' : 'no API key stored'}</p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button type="button" className={buttonClass} onClick={() => openAccountForm('edit')}>Edit account settings</button>
+ <button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkConnection}>Check API identity</button>
+ <button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkBrowser}>Check browser identity</button>
+ <button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button>
+ </div>
+ {/* These three read server-side saved state, so an unsaved edit would
+ silently not apply — say why they are disabled instead of leaving
+ the user to guess (the checks are also disabled mid-save). */}
+ {accountFormDirty && <p className="mt-3 text-sm text-port-warning">Unsaved changes to {scope}. Save the account before running these checks.</p>}
+ </section>
+ ) : <div className="rounded border border-port-border bg-port-card p-4 text-sm text-gray-400">Choose an account to edit its independent rules, models, and monitoring schedule.</div>}
</div>
);
+ const accountDrawer = accountDrawerOpen && (
+ <AccountDrawer
+ mode={accountFormMode}
+ username={accountFormMode === 'edit' ? selected?.username : ''}
+ activeTab={accountDrawerTab}
+ onTabChange={setAccountDrawerTab}
+ onClose={closeAccountForm}
+ formError={accountFormError}
+ form={accountFormMode === 'edit' ? editAccount : newAccount}
+ setForm={accountFormMode === 'edit' ? setEditAccount : setNewAccount}
+ models={models}
+ visionModels={visionModels}
+ visionPending={visionPending}
+ onSubmit={accountFormMode === 'edit' ? saveAccount : createAccount}
+ busy={busy === (accountFormMode === 'edit' ? 'save-account' : 'create-account')}
+ submitLabel={accountFormMode === 'edit' ? 'Save account' : 'Add protected account'}
+ canClearCredential={accountFormMode === 'edit' && Boolean(selected?.apiKeyConfigured)}
+ />
+ );
+
+ // Rendered into the page header, so the account in scope is switchable from
+ // every tab instead of only from Accounts & Safety. Switching keeps the
+ // current tab (accountPath defaults to it) and drops the drawer search params.
+ const accountSwitcher = accounts.length ? (
+ <>
+ <label htmlFor="sn-account-switcher" className="sr-only">Stacker News account in scope</label>
+ <select id="sn-account-switcher" className="max-w-[16rem] rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-white" value={selected?.id || ''} onChange={(event) => navigate(accountPath(event.target.value, activeTab))}>
+ {!selected && <option value="">Choose an account</option>}
+ {accounts.map((account) => <option key={account.id} value={account.id}>{account.label} · @{account.username}</option>)}
+ </select>
+ </>
+ ) : null;
+
if (loading) return <PageSkeleton header="bar" label="Loading Stacker News" tabs={TABS.length} cards={3} />;
const notFound = accountId && !selected;
- return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={Newspaper} title="Stacker News" subtitle="Review-gated multi-account community stewardship" actions={selected && <span className="text-sm text-gray-400">@{selected.username}</span>} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/stacker-news')} ariaLabel="Stacker News sections" /><main className="flex-1 overflow-auto p-4">{error && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{error}</div>}{notice && <div className="mb-3 rounded border border-port-border p-3 text-sm text-gray-200">{notice}</div>}{notFound && <div className="mb-3 rounded border border-port-error p-4 text-sm text-port-error">This Stacker News account was not found. <button className="underline" onClick={() => navigate('/stacker-news')}>Return to accounts.</button></div>}{activeTab === 'review' && selected && renderReview()}{activeTab === 'territory' && selected && renderTerritory()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'activity' && selected && <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Action ledger</h2><div className="mt-3 space-y-2">{visibleActions.map((action) => <div key={action.id} className="rounded border border-port-border p-3 text-sm text-gray-300"><div>{action.kind.replaceAll('_', ' ')} · {action.state}</div>{action.error && <div className="mt-1 text-port-error">{action.error}</div>}{action.result?.handoffOpened && <div className="mt-1 text-gray-400">Fixed browser handoff opened.</div>}</div>)}{!visibleActions.length && <p className="text-sm text-gray-500">No actions recorded.</p>}</div></section>}{activeTab === 'accounts' && renderAccounts()}</main></div>;
+ return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={Newspaper} title="Stacker News" subtitle="Review-gated multi-account community stewardship" actions={accountSwitcher} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/stacker-news')} ariaLabel="Stacker News sections" /><main className="flex-1 overflow-auto p-4">{error && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{error}</div>}{notice && <div className="mb-3 rounded border border-port-border p-3 text-sm text-gray-200">{notice}</div>}{notFound && <div className="mb-3 rounded border border-port-error p-4 text-sm text-port-error">This Stacker News account was not found. <button className="underline" onClick={() => navigate('/stacker-news')}>Return to accounts.</button></div>}{activeTab === 'review' && selected && renderReview()}{activeTab === 'territory' && selected && renderTerritory()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'activity' && selected && <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Action ledger for {scope}</h2><div className="mt-3 space-y-2">{visibleActions.map((action) => <div key={action.id} className="rounded border border-port-border p-3 text-sm text-gray-300"><div>{action.kind.replaceAll('_', ' ')} · {action.state}</div>{action.error && <div className="mt-1 text-port-error">{action.error}</div>}{action.result?.handoffOpened && <div className="mt-1 text-gray-400">Fixed browser handoff opened.</div>}</div>)}{!visibleActions.length && <p className="text-sm text-gray-500">No actions recorded for {scope}.</p>}</div></section>}{activeTab === 'accounts' && renderAccounts()}</main>{accountDrawer}</div>;
}
function Field({ id, label, children }) {
return <div><label htmlFor={id} className="mb-1 block text-sm text-gray-300">{label}</label>{children}</div>;
}
-function AccountForm({ title, submitLabel, form, setForm, models, visionModels, visionPending, onSubmit, busy, showCredential = false, canClearCredential = false, extra = null }) {
+// The 19-field account config, grouped into Drawer tabs. All of its state lives
+// in the page (newAccount / editAccount) because the Drawer body remounts on
+// every tab switch (`key={currentTab}`) — an uncontrolled input here would
+// silently lose what the user typed the moment they changed tabs.
+function AccountDrawer({ mode, username, activeTab, onTabChange, onClose, formError, form, setForm, models, visionModels, visionPending, onSubmit, busy, submitLabel, canClearCredential }) {
const update = (key, value) => setForm((previous) => ({
...previous,
[key]: value,
...(key === 'apiKey' && value ? { clearApiKey: false } : {}),
...(key === 'clearApiKey' && value ? { apiKey: '' } : {}),
}));
- const prefix = showCredential ? 'new-account' : 'edit-account';
- return <form className="rounded border border-port-border bg-port-card p-4" onSubmit={onSubmit}><h2 className="font-semibold text-white">{title}</h2><p className="mt-1 text-sm text-gray-400">Credentials are encrypted separately and never sent to a model.</p><div className="mt-3 space-y-3"><Field id={`${prefix}-label`} label="Local label"><input id={`${prefix}-label`} required className={fieldClass} value={form.label} onChange={(event) => update('label', event.target.value)} /></Field><Field id={`${prefix}-username`} label="Stacker News username"><input id={`${prefix}-username`} required className={fieldClass} value={form.username} onChange={(event) => update('username', event.target.value)} /></Field><Field id={`${prefix}-api-key`} label={showCredential ? 'API key (optional)' : 'Replace API key (leave blank to keep)'}><input id={`${prefix}-api-key`} type="password" className={fieldClass} disabled={form.clearApiKey} value={form.apiKey} onChange={(event) => update('apiKey', event.target.value)} /></Field>{canClearCredential && <label className="flex gap-2 text-sm text-gray-300"><input type="checkbox" checked={form.clearApiKey} onChange={(event) => update('clearApiKey', event.target.checked)} /> Remove stored API key when saving</label>}<div className="grid grid-cols-2 gap-2"><Field id={`${prefix}-text-model`} label="Ollama text model"><ModelSelect id={`${prefix}-text-model`} value={form.textModel} models={models} onChange={(value) => update('textModel', value)} /></Field><Field id={`${prefix}-vision-model`} label="Ollama vision model"><ModelSelect id={`${prefix}-vision-model`} value={form.visionModel} models={visionModels} onChange={(value) => update('visionModel', value)} />{visionPending ? <p className="mt-1 text-xs text-gray-400">Checking which installed Ollama models can read an image…</p> : !visionModels.length ? <p className="mt-1 text-xs text-port-warning">No vision-capable Ollama model installed. Install one (e.g. a qwen-vl or llava model) to analyze images.</p> : null}</Field></div><label className="flex gap-2 text-sm text-gray-300"><input type="checkbox" checked={form.enabled} onChange={(event) => update('enabled', event.target.checked)} /> Account enabled</label><label className="flex gap-2 text-sm text-gray-300"><input type="checkbox" checked={form.monitoringEnabled} onChange={(event) => update('monitoringEnabled', event.target.checked)} /> Enable scheduled monitoring</label><label className="flex gap-2 text-sm text-gray-300"><input type="checkbox" checked={form.analysisEnabled} onChange={(event) => update('analysisEnabled', event.target.checked)} /> Run configured local analysis during monitoring</label><Field id={`${prefix}-interval`} label="Monitoring interval (minutes)"><input id={`${prefix}-interval`} type="number" min="5" max="1440" className={fieldClass} value={form.monitoringIntervalMinutes} onChange={(event) => update('monitoringIntervalMinutes', event.target.value)} /></Field><Field id={`${prefix}-guidance`} label="Stewardship guidance"><textarea id={`${prefix}-guidance`} className={fieldClass} rows="3" value={form.guidance} onChange={(event) => update('guidance', event.target.value)} /></Field><Field id={`${prefix}-tone`} label="Tone"><input id={`${prefix}-tone`} className={fieldClass} value={form.tone} onChange={(event) => update('tone', event.target.value)} /></Field><Field id={`${prefix}-allowed`} label="Allowed themes"><input id={`${prefix}-allowed`} className={fieldClass} value={form.allowedThemes} onChange={(event) => update('allowedThemes', event.target.value)} /></Field><Field id={`${prefix}-disallowed`} label="Disallowed themes"><input id={`${prefix}-disallowed`} className={fieldClass} value={form.disallowedThemes} onChange={(event) => update('disallowedThemes', event.target.value)} /></Field><Field id={`${prefix}-escalation`} label="Escalation cues"><input id={`${prefix}-escalation`} className={fieldClass} value={form.escalationCues} onChange={(event) => update('escalationCues', event.target.value)} /></Field><Field id={`${prefix}-engagement`} label="Desired engagement"><input id={`${prefix}-engagement`} className={fieldClass} value={form.desiredEngagement} onChange={(event) => update('desiredEngagement', event.target.value)} /></Field><div className="grid grid-cols-3 gap-2"><Field id={`${prefix}-hour-budget`} label="Max/hour"><input id={`${prefix}-hour-budget`} type="number" min="1" max="50" className={fieldClass} value={form.maxPerHour} onChange={(event) => update('maxPerHour', event.target.value)} /></Field><Field id={`${prefix}-day-budget`} label="Max/day"><input id={`${prefix}-day-budget`} type="number" min="1" max="200" className={fieldClass} value={form.maxPerDay} onChange={(event) => update('maxPerDay', event.target.value)} /></Field><Field id={`${prefix}-spacing`} label="Spacing min"><input id={`${prefix}-spacing`} type="number" min="0" max="1440" className={fieldClass} value={form.minMinutesBetween} onChange={(event) => update('minMinutesBetween', event.target.value)} /></Field></div>{extra}<button className={buttonClass} disabled={busy}>{submitLabel}</button></div></form>;
+ const isNew = mode !== 'edit';
+ const prefix = isNew ? 'new-account' : 'edit-account';
+ const checkbox = (key, label) => <label className="flex gap-2 text-sm text-gray-300"><input type="checkbox" checked={form[key]} onChange={(event) => update(key, event.target.checked)} /> {label}</label>;
+ const textField = (id, label, key) => <Field id={`${prefix}-${id}`} label={label}><input id={`${prefix}-${id}`} className={fieldClass} value={form[key]} onChange={(event) => update(key, event.target.value)} /></Field>;
+ const numberField = (id, label, key, min, max) => <Field id={`${prefix}-${id}`} label={label}><input id={`${prefix}-${id}`} type="number" min={min} max={max} className={fieldClass} value={form[key]} onChange={(event) => update(key, event.target.value)} /></Field>;
+ return (
+ <Drawer
+ open
+ onClose={onClose}
+ title={isNew ? 'Add account' : 'Edit account'}
+ subtitle={isNew ? 'Credentials are encrypted separately and never sent to a model.' : `@${username}`}
+ size="lg"
+ tabs={ACCOUNT_TABS}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ // Long-lived form: an Esc keystroke or a stray backdrop click mid-edit
+ // must not discard 19 fields of configuration.
+ closeOnEsc={false}
+ closeOnBackdrop={false}
+ closeLabel="Close account settings"
+ >
+ {formError && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{formError}</div>}
+ <form className="space-y-3" onSubmit={onSubmit}>
+ {activeTab === 'identity' && <>
+ <Field id={`${prefix}-label`} label="Local label"><input id={`${prefix}-label`} required className={fieldClass} value={form.label} onChange={(event) => update('label', event.target.value)} /></Field>
+ <Field id={`${prefix}-username`} label="Stacker News username"><input id={`${prefix}-username`} required className={fieldClass} value={form.username} onChange={(event) => update('username', event.target.value)} /></Field>
+ <Field id={`${prefix}-api-key`} label={isNew ? 'API key (optional)' : 'Replace API key (leave blank to keep)'}><input id={`${prefix}-api-key`} type="password" className={fieldClass} disabled={form.clearApiKey} value={form.apiKey} onChange={(event) => update('apiKey', event.target.value)} /></Field>
+ {canClearCredential && checkbox('clearApiKey', 'Remove stored API key when saving')}
+ {checkbox('enabled', 'Account enabled')}
+ </>}
+ {activeTab === 'monitoring' && <>
+ {checkbox('monitoringEnabled', 'Enable scheduled monitoring')}
+ {numberField('interval', 'Monitoring interval (minutes)', 'monitoringIntervalMinutes', 5, 1440)}
+ {checkbox('analysisEnabled', 'Run configured local analysis during monitoring')}
+ <div className="grid gap-2 sm:grid-cols-2">
+ <Field id={`${prefix}-text-model`} label="Ollama text model"><ModelSelect id={`${prefix}-text-model`} value={form.textModel} models={models} onChange={(value) => update('textModel', value)} /></Field>
+ <Field id={`${prefix}-vision-model`} label="Ollama vision model"><ModelSelect id={`${prefix}-vision-model`} value={form.visionModel} models={visionModels} onChange={(value) => update('visionModel', value)} />{visionPending ? <p className="mt-1 text-xs text-gray-400">Checking which installed Ollama models can read an image…</p> : !visionModels.length ? <p className="mt-1 text-xs text-port-warning">No vision-capable Ollama model installed. Install one (e.g. a qwen-vl or llava model) to analyze images.</p> : null}</Field>
+ </div>
+ </>}
+ {activeTab === 'stewardship' && <>
+ <Field id={`${prefix}-guidance`} label="Stewardship guidance"><textarea id={`${prefix}-guidance`} className={fieldClass} rows="3" value={form.guidance} onChange={(event) => update('guidance', event.target.value)} /></Field>
+ {textField('tone', 'Tone', 'tone')}
+ {textField('allowed', 'Allowed themes', 'allowedThemes')}
+ {textField('disallowed', 'Disallowed themes', 'disallowedThemes')}
+ {textField('escalation', 'Escalation cues', 'escalationCues')}
+ {textField('engagement', 'Desired engagement', 'desiredEngagement')}
+ </>}
+ {activeTab === 'budgets' && <div className="grid gap-2 sm:grid-cols-3">
+ {numberField('hour-budget', 'Max/hour', 'maxPerHour', 1, 50)}
+ {numberField('day-budget', 'Max/day', 'maxPerDay', 1, 200)}
+ {numberField('spacing', 'Spacing min', 'minMinutesBetween', 0, 1440)}
+ </div>}
+ <div className="flex flex-wrap justify-end gap-2 pt-2">
+ <button type="button" className={secondaryButton} onClick={onClose}>Close</button>
+ <button className={buttonClass} disabled={busy}>{submitLabel}</button>
+ </div>
+ </form>
+ </Drawer>
+ );
}
function TerritoryForm({ prefix, title, form, setForm, onSubmit, busy, submitLabel, onCancel = null }) {
diff --git a/client/src/pages/StackerNews.test.jsx b/client/src/pages/StackerNews.test.jsx
index af99be3501..19893ca9d0 100644
--- a/client/src/pages/StackerNews.test.jsx
+++ b/client/src/pages/StackerNews.test.jsx
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
const api = {
getStackerNewsAccounts: vi.fn(),
@@ -44,10 +44,22 @@ const accounts = [
{ id: 'a2', label: 'Personal', username: 'personal_stacker', enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 60, analysisEnabled: false, textModel: '', visionModel: '', rules: { guidance: 'Personal rules' }, apiKeyConfigured: false },
];
+// Surfaces the URL so tests can assert the deep-linkable bits — the selected
+// account/tab path and the drawer's `snAccount` / `snAccountTab` search params.
+function LocationProbe() {
+ const location = useLocation();
+ return <div data-testid="location">{`${location.pathname}${location.search}`}</div>;
+}
+
function renderPage(path) {
- return render(<MemoryRouter initialEntries={[path]}><Routes><Route path="/stacker-news" element={<StackerNews />} /><Route path="/stacker-news/:accountId/:tab" element={<StackerNews />} /></Routes></MemoryRouter>);
+ return render(<MemoryRouter initialEntries={[path]}><Routes><Route path="/stacker-news" element={<StackerNews />} /><Route path="/stacker-news/:accountId/:tab" element={<StackerNews />} /></Routes><LocationProbe /></MemoryRouter>);
}
+const currentUrl = () => screen.getByTestId('location').textContent;
+const accountSwitcher = () => screen.getByLabelText('Stacker News account in scope');
+const drawerTab = (name) => screen.getByRole('tab', { name });
+const intervalField = (prefix = 'edit') => screen.getByLabelText('Monitoring interval (minutes)', { selector: `#${prefix}-account-interval` });
+
function deferred() {
let resolve;
const promise = new Promise((done) => { resolve = done; });
@@ -66,28 +78,83 @@ describe('StackerNews', () => {
});
it('deep-links to one account and shows its independent schedule and rules', async () => {
+ const user = userEvent.setup();
renderPage('/stacker-news/a1/accounts');
expect(await screen.findByText('@art_steward · every 15m')).toBeInTheDocument();
- expect(await screen.findByDisplayValue('Curate visual work')).toBeInTheDocument();
- expect(screen.getByDisplayValue('15')).toBeInTheDocument();
expect(screen.getByText('@personal_stacker · monitoring off')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Edit account settings' }));
+ await user.click(drawerTab('Monitoring & models'));
+ expect(intervalField()).toHaveValue(15);
+ await user.click(drawerTab('Stewardship'));
+ expect(screen.getByDisplayValue('Curate visual work')).toBeInTheDocument();
});
it('opens account setup on the bare route so a first-time install is usable', async () => {
+ const user = userEvent.setup();
renderPage('/stacker-news');
- expect(await screen.findByRole('heading', { name: 'Add account' })).toBeInTheDocument();
+ await user.click(await screen.findByRole('button', { name: 'Add account' }));
+ expect(await screen.findByRole('dialog', { name: 'Add account' })).toBeInTheDocument();
+ expect(currentUrl()).toContain('snAccount=new');
});
it('saves only the selected account configuration', async () => {
const user = userEvent.setup();
api.updateStackerNewsAccount.mockResolvedValue({ ...accounts[0], monitoringIntervalMinutes: 20 });
- renderPage('/stacker-news/a1/accounts');
- await screen.findByDisplayValue('Curate visual work');
- const interval = screen.getByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' });
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=monitoring');
+ const interval = await screen.findByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' });
await user.clear(interval);
await user.type(interval, '20');
await user.click(screen.getByRole('button', { name: 'Save account' }));
await waitFor(() => expect(api.updateStackerNewsAccount).toHaveBeenCalledWith('a1', expect.objectContaining({ monitoringIntervalMinutes: 20 }), { silent: true }));
+ // A successful save closes the drawer and clears its search params.
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ expect(currentUrl()).not.toContain('snAccount');
+ });
+
+ it('switches the account in scope from a non-account tab without leaving it', async () => {
+ const user = userEvent.setup();
+ renderPage('/stacker-news/a1/territory');
+ expect(await screen.findByRole('heading', { name: 'Communities for @art_steward' })).toBeInTheDocument();
+ await user.selectOptions(accountSwitcher(), 'a2');
+ expect(await screen.findByRole('heading', { name: 'Communities for @personal_stacker' })).toBeInTheDocument();
+ expect(currentUrl()).toBe('/stacker-news/a2/territory');
+ expect(screen.getByRole('tab', { name: 'Territory' })).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('names the account in scope on every scoped section', async () => {
+ const user = userEvent.setup();
+ renderPage('/stacker-news/a1/review');
+ expect(await screen.findByRole('heading', { name: 'Approval queue for @art_steward' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Monitored content for @art_steward' })).toBeInTheDocument();
+ expect(screen.getByText(/No actions are waiting for @art_steward/)).toBeInTheDocument();
+ await user.click(screen.getByRole('tab', { name: 'Territory' }));
+ expect(await screen.findByRole('heading', { name: 'Add community to @art_steward' })).toBeInTheDocument();
+ expect(screen.getByText(/Add communities @art_steward monitors or owns/)).toBeInTheDocument();
+ await user.click(screen.getByRole('tab', { name: 'Activity' }));
+ expect(await screen.findByRole('heading', { name: 'Action ledger for @art_steward' })).toBeInTheDocument();
+ });
+
+ it('keeps entered account values across drawer tab switches and deep-links the open tab', async () => {
+ const user = userEvent.setup();
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=stewardship');
+ const tone = await screen.findByLabelText('Tone', { selector: '#edit-account-tone' });
+ await user.type(tone, 'measured');
+ await user.click(drawerTab('Budgets'));
+ expect(currentUrl()).toContain('snAccountTab=budgets');
+ expect(screen.getByLabelText('Max/hour', { selector: '#edit-account-hour-budget' })).toBeInTheDocument();
+ await user.click(drawerTab('Stewardship'));
+ expect(screen.getByLabelText('Tone', { selector: '#edit-account-tone' })).toHaveValue('measured');
+ });
+
+ it('reports an invalid field from an unmounted drawer tab and switches to it', async () => {
+ const user = userEvent.setup();
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=monitoring');
+ await user.clear(await screen.findByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' }));
+ await user.click(drawerTab('Budgets'));
+ await user.click(screen.getByRole('button', { name: 'Save account' }));
+ expect(await screen.findByText(/Monitoring interval \(minutes\) must be a whole number from 5 to 1440/)).toBeInTheDocument();
+ expect(intervalField()).toBeInTheDocument();
+ expect(api.updateStackerNewsAccount).not.toHaveBeenCalled();
});
it('renders a recovery path for a stale account URL', async () => {
@@ -129,10 +196,11 @@ describe('StackerNews', () => {
const user = userEvent.setup();
const save = deferred();
api.updateStackerNewsAccount.mockReturnValue(save.promise);
- renderPage('/stacker-news/a1/accounts');
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=monitoring');
const interval = await screen.findByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' });
await user.clear(interval);
await user.type(interval, '20');
+ expect(screen.getByText(/Unsaved changes to @art_steward/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Check API identity' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Check browser identity' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Sync now' })).toBeDisabled();
@@ -145,7 +213,7 @@ describe('StackerNews', () => {
it('can explicitly remove a stored API key', async () => {
const user = userEvent.setup();
api.updateStackerNewsAccount.mockResolvedValue({ ...accounts[0], apiKeyConfigured: false });
- renderPage('/stacker-news/a1/accounts');
+ renderPage('/stacker-news/a1/accounts?snAccount=edit');
await user.click(await screen.findByRole('checkbox', { name: 'Remove stored API key when saving' }));
await user.click(screen.getByRole('button', { name: 'Save account' }));
await waitFor(() => expect(api.updateStackerNewsAccount).toHaveBeenCalledWith('a1', expect.objectContaining({ apiKey: '' }), { silent: true }));
@@ -155,21 +223,24 @@ describe('StackerNews', () => {
const user = userEvent.setup();
const save = deferred();
api.updateStackerNewsAccount.mockReturnValue(save.promise);
- renderPage('/stacker-news/a1/accounts');
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=monitoring');
const interval = await screen.findByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' });
await user.clear(interval);
await user.type(interval, '20');
await user.click(screen.getByRole('button', { name: 'Save account' }));
+ // Selecting another account navigates by path, which drops the drawer params.
await user.click(screen.getByRole('button', { name: /Personal/ }));
- expect(await screen.findByDisplayValue('personal_stacker')).toBeInTheDocument();
+ expect(await screen.findByRole('heading', { name: 'Settings and safety for @personal_stacker' })).toBeInTheDocument();
await act(async () => save.resolve({ ...accounts[0], monitoringIntervalMinutes: 20 }));
- expect(screen.getByDisplayValue('personal_stacker')).toBeInTheDocument();
- expect(screen.getByLabelText('Monitoring interval (minutes)', { selector: '#edit-account-interval' })).toHaveValue(60);
+ expect(screen.getByRole('heading', { name: 'Settings and safety for @personal_stacker' })).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Edit account settings' }));
+ await user.click(drawerTab('Monitoring & models'));
+ expect(intervalField()).toHaveValue(60);
});
it('offers only vision-capable models for the vision stage and every model for text', async () => {
- renderPage('/stacker-news');
- await screen.findByRole('heading', { name: 'Add account' });
+ renderPage('/stacker-news?snAccount=new&snAccountTab=monitoring');
+ await screen.findByRole('dialog', { name: 'Add account' });
const { text, vision } = modelSelects();
expect(optionsOf(text)).toEqual(['Disabled', 'example-text', 'example-embed', 'example-vision', 'futuremodel:9b']);
// Subset of the text list, with the text-only and embedding ids dropped.
@@ -181,8 +252,8 @@ describe('StackerNews', () => {
it('offers a server-classified vision model the id regex does not recognize', async () => {
local.vision = { idsByProvider: { ollama: new Set() }, loaded: true };
- renderPage('/stacker-news');
- await screen.findByRole('heading', { name: 'Add account' });
+ renderPage('/stacker-news?snAccount=new&snAccountTab=monitoring');
+ await screen.findByRole('dialog', { name: 'Add account' });
// Without the server map only the regex-recognizable id survives.
expect(optionsOf(modelSelects().vision)).toEqual(['Disabled', 'example-vision']);
});
@@ -192,11 +263,10 @@ describe('StackerNews', () => {
const retired = { ...accounts[0], visionModel: 'retired-multimodal:7b' };
api.getStackerNewsAccounts.mockResolvedValue({ accounts: [retired, accounts[1]] });
api.updateStackerNewsAccount.mockResolvedValue(retired);
- renderPage('/stacker-news/a1/accounts');
- await screen.findByDisplayValue('Curate visual work');
- const vision = screen.getByLabelText('Ollama vision model', { selector: '#edit-account-vision-model' });
+ renderPage('/stacker-news/a1/accounts?snAccount=edit&snAccountTab=monitoring');
+ const vision = await screen.findByLabelText('Ollama vision model', { selector: '#edit-account-vision-model' });
+ await waitFor(() => expect(vision).toHaveValue('retired-multimodal:7b'));
expect(optionsOf(vision)).toContain('retired-multimodal:7b (configured)');
- expect(vision).toHaveValue('retired-multimodal:7b');
await user.click(screen.getByRole('button', { name: 'Save account' }));
await waitFor(() => expect(api.updateStackerNewsAccount).toHaveBeenCalledWith('a1', expect.objectContaining({ visionModel: 'retired-multimodal:7b' }), { silent: true }));
});
@@ -204,8 +274,8 @@ describe('StackerNews', () => {
it('does not claim there is no vision model while the capability fetch is in flight', async () => {
local.models = { ollama: ['example-text'], loading: false };
local.vision = { idsByProvider: null, loaded: false };
- renderPage('/stacker-news');
- await screen.findByRole('heading', { name: 'Add account' });
+ renderPage('/stacker-news?snAccount=new&snAccountTab=monitoring');
+ await screen.findByRole('dialog', { name: 'Add account' });
expect(screen.getByText(/Checking which installed Ollama models can read an image/)).toBeInTheDocument();
expect(screen.queryByText(/No vision-capable Ollama model installed/)).not.toBeInTheDocument();
});
@@ -213,8 +283,8 @@ describe('StackerNews', () => {
it('says so explicitly once the capability fetch settles with no vision model installed', async () => {
local.models = { ollama: ['example-text'], loading: false };
local.vision = { idsByProvider: { ollama: new Set() }, loaded: true };
- renderPage('/stacker-news');
- await screen.findByRole('heading', { name: 'Add account' });
+ renderPage('/stacker-news?snAccount=new&snAccountTab=monitoring');
+ await screen.findByRole('dialog', { name: 'Add account' });
expect(screen.getByText(/No vision-capable Ollama model installed/)).toBeInTheDocument();
expect(optionsOf(modelSelects().vision)).toEqual(['Disabled']);
});
diff --git a/docs/features/stacker-news.md b/docs/features/stacker-news.md
index bfba9b0c77..2d0ccd9371 100644
--- a/docs/features/stacker-news.md
+++ b/docs/features/stacker-news.md
@@ -77,7 +77,9 @@ handoff for the user to complete.
## Setup
-1. Open **Comms > Stacker News > Accounts & Safety** and add an account.
+1. Open **Comms > Stacker News > Accounts & Safety** and choose **Add account**.
+ The account form opens in a drawer grouped into Identity, Monitoring & models,
+ Stewardship, and Budgets tabs; the open tab is kept in the URL.
2. Add an API key if API reads or reviewed publishing are needed, then verify
that the returned identity matches the configured username.
3. Add each territory, mark whether the account owns it, and choose whether it
@@ -92,6 +94,10 @@ handoff for the user to complete.
7. If browser handoffs are needed, sign the pinned PortOS browser into the same
account and run **Check browser identity**.
+Every tab is scoped to one account. The header carries an account switcher that
+keeps the current tab, and each section names the account it operates on, so a
+Territory, Review, Drafts, or Activity list is never mistaken for a global one.
+
Monitoring is off by default. Boot may arm a schedule the user already enabled,
including a territory override on an otherwise quiet account, but it never
performs an immediate sync or cold-start model call. The account form can also