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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(creative-commissions): add a Run Now button to test commissions outside their schedule
Adam Eivya8e8e96ac8b6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex eeec3768b2..454d101c08 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,8 @@## Added+- **Creative Commissions "Run Now" test button.** Each commission card gains a ⚡ button that fires the commission immediately, outside its schedule, so you can verify a standing brief actually works without waiting for the next cron tick. The manual fire runs the exact same gated path as a scheduled tick — autonomy-mode and budget gates included — so the outcome (started / skipped + reason / failed) is an honest preview of what the schedule will do; the toast reports it, and the run lands in the drawer's run history tagged with a **manual** badge (runs now persist a `trigger` field, older runs read as scheduled). A paused or half-configured commission is still testable: the manual path deliberately skips only the `enabled` and cron-validity guards. New `runCommissionNow()` in the scheduler (shared `fireCommission` core with the cron handler) + `POST /api/creative-commission/:id/run`, unit-tested at the store, scheduler, and route layers.+- **Durable agent feedback queue for CoS agents.** Completion notifications already accept a quick rating, but once a notification expired there was no way to find completed runs still awaiting feedback. The **Agents** tab's completed-agents list gains a **Needs feedback** filter (with a live count) that surfaces only unrated, non-system runs, and rating one now updates the list in place — the run drops out of the queue immediately without a full refetch. New `needsAgentFeedback` predicate + optimistic `handleFeedbackChange` in `AgentsTab.jsx`; `AgentCard` now hands the updated agent record back to its parent on submit. Unit-tested.- **Digital Twin → Avatar Bio: copy-ready persona for live avatars.** A new **Avatar Bio** tab (reachable via ⌘K and voice) assembles a concise three-part persona — **Who I Am / How I Speak / What I Know** — sized for live-avatar platforms (HeyGen, Tavus, Simli, ElevenLabs conversational agents) whose persona/knowledge fields want a tight blurb, not the full soul-document dump that Export produces. The bio is built **deterministically** from your existing twin data (SOUL/COMMUNICATION/PERSONALITY/COGNITIVE/TECHNICAL/CREATIVE/VALUES docs + stored voice traits + goals) with graceful per-section fallbacks, so it renders instantly on tab load with **no LLM call** (never trips the no-cold-bootstrap policy). A length toggle (Blurb / Persona / Knowledge) tunes verbosity; each section and the combined bio have their own **Copy** button. An optional **Refine with AI** action rewrites the draft into first-person prose via a chosen provider, preserving every fact and inventing nothing. When no numeric voice profile has been generated yet, a nudge banner links to the Personality and Voice tabs so the "How I Speak" section can be enriched with cadence and verbal markers. New service `server/services/digital-twin-avatar-bio.js` (`buildAvatarBio` deterministic + `polishAvatarBio` provider path) and routes `GET /api/digital-twin/avatar-bio` + `POST /api/digital-twin/avatar-bio/polish`, unit-tested.diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsxindex 00e3e9706f..3f51cda69f 100644--- a/client/src/pages/CreativeCommissions.jsx+++ b/client/src/pages/CreativeCommissions.jsx@@ -14,7 +14,7 @@import { useEffect, useMemo, useState, useCallback, useRef } from 'react';import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';-import { Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, ThumbsUp, ThumbsDown, ExternalLink } from 'lucide-react';+import { Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, ThumbsUp, ThumbsDown, ExternalLink, Zap } from 'lucide-react';import toast from '../components/ui/Toast';import Drawer from '../components/Drawer';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';@@ -24,7 +24,7 @@ import { isProcessProvider } from '../utils/providers';import ProviderModelSelector from '../components/ProviderModelSelector';import {listCommissions, getCommission, createCommission, updateCommission, deleteCommission,- submitCommissionFeedback, getProviders,+ submitCommissionFeedback, runCommissionNow, getProviders,} from '../services/api';const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];@@ -131,6 +131,7 @@ export default function CreativeCommissions() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(blankForm());const [saving, setSaving] = useState(false);+ const [runningIds, setRunningIds] = useState(() => new Set()); // per-card "Run Now" in flightconst { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const drawerOpen = id != null; // '/new' or an id@@ -265,6 +266,28 @@ export default function CreativeCommissions() {}}, [editing]);+ // Fire a commission immediately, outside its schedule — the "does this+ // actually work" test button. Runs the same gated path as a cron tick, so a+ // skip (autonomy off, over budget) is itself the test result and is toasted+ // with its reason. The response carries the refreshed record (new run+ // appended), which we swap into local state so run history updates reactively.+ const handleRunNow = async (commission) => {+ setRunningIds((prev) => new Set(prev).add(commission.id));+ try {+ const result = await runCommissionNow(commission.id, { silent: true });+ if (result?.commission?.id) {+ setCommissions((prev) => prev.map((c) => (c.id === result.commission.id ? result.commission : c)));+ }+ if (result?.status === 'started') toast.success('Run started — output will appear in run history');+ else if (result?.status === 'skipped') toast.error(`Run skipped: ${result.reason}`);+ else toast.error(`Run failed: ${result?.error || 'unknown error'}`);+ } catch (err) {+ toast.error(err?.message || 'Run failed');+ } finally {+ setRunningIds((prev) => { const next = new Set(prev); next.delete(commission.id); return next; });+ }+ };+const toggleEnabled = async (commission) => {const next = !commission.enabled;setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: next } : c)));@@ -346,6 +369,15 @@ export default function CreativeCommissions() {)}</div></button>+ <button+ onClick={() => handleRunNow(c)}+ disabled={runningIds.has(c.id)}+ title="Run now (ignores schedule)"+ aria-label={`Run commission ${c.name} now`}+ className="p-2 text-gray-400 hover:text-port-accent disabled:opacity-50"+ >+ <Zap className={`w-4 h-4 ${runningIds.has(c.id) ? 'animate-pulse text-port-accent' : ''}`} />+ </button><buttononClick={() => toggleEnabled(c)}title={c.enabled ? 'Pause' : 'Resume'}@@ -639,7 +671,13 @@ function CommissionForm({ form, patchForm, runs, feedback, onRate, saving, onSav{orderedRuns.map((r) => (<div key={r.id} className="text-xs bg-port-bg border border-port-border rounded px-2 py-1.5"><div className="flex items-center justify-between gap-2">- <span className="text-gray-400">{timeAgo(r.ranAt)}</span>+ <span className="text-gray-400">+ {timeAgo(r.ranAt)}+ {/* Runs persisted before the trigger field exist only from cron ticks — no badge. */}+ {r.trigger === 'manual' && (+ <span className="ml-1.5 text-[10px] uppercase px-1 py-0.5 rounded bg-port-accent/20 text-port-accent">manual</span>+ )}+ </span><span className={r.status === 'started' ? 'text-port-accent': r.status === 'skipped' ? 'text-port-warning'diff --git a/client/src/services/apiCreativeCommission.js b/client/src/services/apiCreativeCommission.jsindex 37f0746b5e..90908ef6c8 100644--- a/client/src/services/apiCreativeCommission.js+++ b/client/src/services/apiCreativeCommission.js@@ -31,6 +31,16 @@ export const deleteCommission = (id, options = {}) =>...options,});+// Fire a commission immediately, outside its schedule ("Run Now" — the test+// button). Resolves to the fire outcome `{ status, reason?, error?, run,+// projectId?, commission }` — `commission` is the refreshed record (new run+// appended) for reactive state.+export const runCommissionNow = (id, options = {}) =>+ request(`/creative-commission/${encodeURIComponent(id)}/run`, {+ method: 'POST',+ ...options,+ });+// Rate/annotate a specific run's output (#2657, Phase 2). `feedback` is// `{ runId, rating: 'up'|'down'|number, note?, tags? }`. Resolves to the full// updated commission (with the new reaction in `feedback[]`) for reactive state.diff --git a/server/routes/creativeCommissions.js b/server/routes/creativeCommissions.jsindex f4ff735451..5b7f0ff44d 100644--- a/server/routes/creativeCommissions.js+++ b/server/routes/creativeCommissions.js@@ -53,6 +53,19 @@ router.patch('/:id', asyncHandler(async (req, res) => {res.json(rec);}));+// Fire a commission immediately, outside its schedule ("Run Now" — the test+// button). Runs the same gated fire path as a cron tick, so the outcome reports+// exactly what the schedule would do (started / skipped + reason / failed).+// Lazy-imported so the route module stays off the scheduler graph for every+// other endpoint. 202: generation continues asynchronously after the response.+// The refreshed record rides along so the client updates run history reactively.+router.post('/:id/run', asyncHandler(async (req, res) => {+ const { runCommissionNow } = await import('../services/creativeCommissions/scheduler.js');+ const outcome = await runCommissionNow(req.params.id).catch((err) => { throw mapServiceError(err); });+ const commission = await svc.getCommission(req.params.id).catch(() => null);+ res.status(202).json({ ...outcome, commission });+}));+// Rate/annotate a specific run's output (#2657, Phase 2). The reaction is folded// into the next scheduled fire's directive via buildCommissionDirective. Returns// the full updated commission so the client updates its feedback state reactively.diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.jsindex f2309905d1..a6bd7a954d 100644--- a/server/routes/creativeCommissions.test.js+++ b/server/routes/creativeCommissions.test.js@@ -18,6 +18,13 @@ const svc = {};vi.mock('../services/creativeCommissions/store.js', () => svc);+// The scheduler is lazy-imported only by the /run handler; mocked so the manual+// fire path is asserted without dragging the eventScheduler/settings graph in.+const runNowMock = vi.fn();+vi.mock('../services/creativeCommissions/scheduler.js', () => ({+ runCommissionNow: (...a) => runNowMock(...a),+}));+const routes = (await import('./creativeCommissions.js')).default;const buildApp = () => {@@ -113,6 +120,35 @@ describe('PATCH /api/creative-commission/:id', () => {});});+describe('POST /api/creative-commission/:id/run', () => {+ it('fires the manual run and returns the outcome plus the refreshed record (202)', async () => {+ runNowMock.mockResolvedValue({ status: 'started', projectId: 'cd-xyz', run: { id: 'run-1' } });+ svc.getCommission.mockResolvedValue({ id: 'commission-1', runs: [{ id: 'run-1' }] });+ const res = await request(buildApp()).post('/api/creative-commission/commission-1/run');+ expect(res.status).toBe(202);+ expect(runNowMock).toHaveBeenCalledWith('commission-1');+ expect(res.body).toMatchObject({+ status: 'started',+ projectId: 'cd-xyz',+ commission: { id: 'commission-1' },+ });+ });++ it('returns a skipped outcome verbatim (the gate result IS the test result)', async () => {+ runNowMock.mockResolvedValue({ status: 'skipped', reason: 'autonomy-off', run: { id: 'run-1' } });+ svc.getCommission.mockResolvedValue({ id: 'commission-1' });+ const res = await request(buildApp()).post('/api/creative-commission/commission-1/run');+ expect(res.status).toBe(202);+ expect(res.body).toMatchObject({ status: 'skipped', reason: 'autonomy-off' });+ });++ it('maps a service NOT_FOUND to 404', async () => {+ runNowMock.mockRejectedValue(Object.assign(new Error('gone'), { code: 'NOT_FOUND' }));+ const res = await request(buildApp()).post('/api/creative-commission/missing/run');+ expect(res.status).toBe(404);+ });+});+describe('POST /api/creative-commission/:id/feedback', () => {it('validates and forwards the reaction to the service', async () => {svc.submitCommissionFeedback.mockResolvedValue({ id: 'commission-1', feedback: [{ runId: 'run-A', rating: 'up' }] });diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex 47582983b5..ab32e9d7df 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -134,20 +134,57 @@ export function stopCommissionScheduler() {}/**- * The fire handler. Runs outside the Express request lifecycle, so the whole- * body is wrapped — a throw here would crash Node. Re-reads the commission and- * the creative autonomy config every fire; gates on execute-mode + budget; then- * mints a directive-driven CD project and nudges the advance loop (which runs- * each plan step through the gated `dispatchCreativeTool`).+ * A scheduled cron tick. Runs outside the Express request lifecycle — every+ * throwable path is contained (getCommission is caught here, everything else+ * inside fireCommission), so a fire can't crash Node. Skips silently when the+ * commission vanished, was paused, or its schedule became invalid since+ * registration.*/export async function runScheduledCommission(commissionId) {- try {- const commission = await getCommission(commissionId).catch(() => null);- if (!commission || commission.enabled === false) return;+ const commission = await getCommission(commissionId).catch(() => null);+ if (!commission || commission.enabled === false) return;++ const cron = commissionToCron(commission.schedule);+ if (!cron || !isValidCron(cron)) return; // schedule became invalid since registration++ await fireCommission(commission, 'schedule');+}- const cron = commissionToCron(commission.schedule);- if (!cron || !isValidCron(cron)) return; // schedule became invalid since registration+/**+ * A user-initiated "Run Now" fire (the route's test button). Runs the SAME+ * gated fire path as a cron tick — so it's an end-to-end test of exactly what+ * the schedule will do — but deliberately skips the `enabled` and cron-validity+ * guards: a paused or half-configured commission is still testable. The+ * autonomy/budget gates stay: the downstream plan steps are gated on them in+ * `dispatchCreativeTool` anyway, so bypassing them here would only strand a+ * dead project — a skipped outcome with the reason is the honest test result.+ *+ * Throws ERR_NOT_FOUND (→404 via the route's error mapper) for an unknown id;+ * every other failure is recorded on the run history and returned as an outcome.+ */+export async function runCommissionNow(commissionId) {+ const commission = await getCommission(commissionId);+ return fireCommission(commission, 'manual');+}+/**+ * The shared fire core. Never throws (callers may be outside the Express+ * request lifecycle — a throw would crash Node). Re-reads the creative autonomy+ * config every fire; gates on execute-mode + budget; then mints a+ * directive-driven CD project and nudges the advance loop (which runs each plan+ * step through the gated `dispatchCreativeTool`). Every path records a run+ * (tagged with its trigger) and returns an outcome:+ * { status: 'started', projectId, run }+ * { status: 'skipped', reason, run }+ * { status: 'failed', error, run }+ */+async function fireCommission(commission, trigger) {+ const commissionId = commission.id;+ const skip = async (reason) => {+ const run = await recordCommissionRun(commissionId, { status: 'skipped', reason, trigger }).catch(() => null);+ return { status: 'skipped', reason, run };+ };+ try {// Gate on creative autonomy mode + daily cos budget BEFORE spawning anything// (the planner is itself an LLM call) — honors "off ⇒ no generation" and the// no-cold-LLM policy. Both reads FAIL CLOSED: if governance state can't be@@ -158,31 +195,16 @@ export async function runScheduledCommission(commissionId) {import('../domainUsage.js'),]);const state = await loadState().catch(() => null);- if (!state) {- await recordCommissionRun(commissionId, { status: 'skipped', reason: 'governance-unavailable' }).catch(() => {});- return;- }+ if (!state) return skip('governance-unavailable');const mode = getCreativeAutonomyMode(state.config);- if (mode !== 'execute') {- await recordCommissionRun(commissionId, { status: 'skipped', reason: `autonomy-${mode}` }).catch(() => {});- return;- }+ if (mode !== 'execute') return skip(`autonomy-${mode}`);const budget = await getDomainBudgetStatus('cos').catch(() => null);- if (!budget) {- await recordCommissionRun(commissionId, { status: 'skipped', reason: 'budget-unavailable' }).catch(() => {});- return;- }- if (!budget.withinBudget) {- await recordCommissionRun(commissionId, { status: 'skipped', reason: 'budget' }).catch(() => {});- return;- }+ if (!budget) return skip('budget-unavailable');+ if (!budget.withinBudget) return skip('budget');// Phase 1 supports video only. A non-video commission can't be created via// the UI (schema restricts the enum), but a hand-edited record is possible.- if (commission.targetAbility !== 'video') {- await recordCommissionRun(commissionId, { status: 'skipped', reason: 'unsupported-ability' }).catch(() => {});- return;- }+ if (commission.targetAbility !== 'video') return skip('unsupported-ability');// NOTE: we deliberately do NOT pre-charge the cos budget here. The planner// spawns as a normal CoS agent (a `cd-` task) and is accounted by@@ -259,6 +281,7 @@ export async function runScheduledCommission(commissionId) {const run = await recordCommissionRun(commissionId, {status: 'started',+ trigger,projectId: project.id,promptUsed: directive.goal,}).catch(() => null);@@ -273,8 +296,11 @@ export async function runScheduledCommission(commissionId) {// Kick the planner → plan → execute loop. Fire-and-forget within this// try/catch (already outside the request lifecycle).await advanceAfterPlanStepSettled(project.id);+ return { status: 'started', projectId: project.id, run };} catch (err) {- console.error(`❌ Creative commission ${commissionId} fire failed: ${err?.message || err}`);- await recordCommissionRun(commissionId, { status: 'failed', error: err?.message || String(err) }).catch(() => {});+ console.error(`❌ Creative commission ${commissionId} ${trigger} fire failed: ${err?.message || err}`);+ const error = err?.message || String(err);+ const run = await recordCommissionRun(commissionId, { status: 'failed', error, trigger }).catch(() => null);+ return { status: 'failed', error, run };}}diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsindex c6e2ed5708..7a69c0829f 100644--- a/server/services/creativeCommissions/scheduler.test.js+++ b/server/services/creativeCommissions/scheduler.test.js@@ -62,6 +62,7 @@ const {startCommissionScheduler,stopCommissionScheduler,runScheduledCommission,+ runCommissionNow,} = await import('./scheduler.js');const videoCommission = (over = {}) => ({@@ -280,4 +281,64 @@ describe('runScheduledCommission gates', () => {expect(createProjectMock).not.toHaveBeenCalled();expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'unsupported-ability' }));});++ it('tags scheduled runs with trigger "schedule"', async () => {+ getCommissionMock.mockResolvedValue(videoCommission());+ await runScheduledCommission('commission-1');+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', trigger: 'schedule' }));+ });+});++describe('runCommissionNow (manual "Run Now")', () => {+ it('fires through the CD pipeline, tags the run manual, and returns a started outcome', async () => {+ recordRunMock.mockResolvedValue({ id: 'run-1', status: 'started' });+ getCommissionMock.mockResolvedValue(videoCommission());+ const outcome = await runCommissionNow('commission-1');+ expect(outcome).toMatchObject({ status: 'started', projectId: 'cd-xyz' });+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', trigger: 'manual' }));+ expect(advanceMock).toHaveBeenCalledWith('cd-xyz');+ expect(surfaceMock).toHaveBeenCalledTimes(1);+ });++ it('fires even a PAUSED commission (a test run before enabling)', async () => {+ getCommissionMock.mockResolvedValue(videoCommission({ enabled: false }));+ const outcome = await runCommissionNow('commission-1');+ expect(outcome.status).toBe('started');+ expect(createProjectMock).toHaveBeenCalledTimes(1);+ });++ it('fires a commission whose schedule is not (yet) derivable to a cron', async () => {+ getCommissionMock.mockResolvedValue(videoCommission({ schedule: { kind: 'DAILY' } }));+ const outcome = await runCommissionNow('commission-1');+ expect(outcome.status).toBe('started');+ });++ it('keeps the autonomy gate and reports the skip as the test outcome', async () => {+ creativeModeMock.mockReturnValue('off');+ getCommissionMock.mockResolvedValue(videoCommission());+ const outcome = await runCommissionNow('commission-1');+ expect(outcome).toMatchObject({ status: 'skipped', reason: 'autonomy-off' });+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'autonomy-off', trigger: 'manual' }));+ });++ it('keeps the budget gate and reports the skip', async () => {+ budgetMock.mockResolvedValue({ withinBudget: false });+ getCommissionMock.mockResolvedValue(videoCommission());+ const outcome = await runCommissionNow('commission-1');+ expect(outcome).toMatchObject({ status: 'skipped', reason: 'budget' });+ });++ it('returns a failed outcome (recorded on run history) when the fire throws', async () => {+ createProjectMock.mockRejectedValueOnce(new Error('collection create failed'));+ getCommissionMock.mockResolvedValue(videoCommission());+ const outcome = await runCommissionNow('commission-1');+ expect(outcome).toMatchObject({ status: 'failed', error: 'collection create failed' });+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'failed', error: 'collection create failed', trigger: 'manual' }));+ });++ it('propagates NOT_FOUND for an unknown commission (route maps it to 404)', async () => {+ getCommissionMock.mockRejectedValue(Object.assign(new Error('gone'), { code: 'NOT_FOUND' }));+ await expect(runCommissionNow('missing')).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 7819af0421..58b9b821a2 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -384,6 +384,10 @@ export async function recordCommissionRun(id, runEntry) {id: runEntry.id || `run-${randomUUID()}`,ranAt: runEntry.ranAt || new Date().toISOString(),status: runEntry.status || 'started',+ // 'manual' = a user-initiated "Run Now" fire; anything else is a scheduled+ // cron tick. Pre-trigger runs (persisted without the field) read as+ // scheduled, which is what they were.+ trigger: runEntry.trigger === 'manual' ? 'manual' : 'schedule',projectId: runEntry.projectId || null,promptUsed: isStr(runEntry.promptUsed) ? runEntry.promptUsed : null,reason: isStr(runEntry.reason) ? runEntry.reason : null,diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex a78fd6e49b..791e49c7ee 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -180,6 +180,15 @@ describe('recordCommissionRun', () => {expect(after.runs[0]).toMatchObject({ status: 'started', projectId: 'cd-1', promptUsed: 'g' });expect(after.runs[0].id).toMatch(/^run-/);});++ it('persists a manual trigger and defaults everything else to schedule', async () => {+ const created = await createCommission(validInput());+ await recordCommissionRun(created.id, { status: 'started', trigger: 'manual' });+ await recordCommissionRun(created.id, { status: 'started' });+ await recordCommissionRun(created.id, { status: 'started', trigger: 'bogus' });+ const after = await getCommission(created.id);+ expect(after.runs.map((r) => r.trigger)).toEqual(['manual', 'schedule', 'schedule']);+ });});describe('deleteCommission', () => {