Let the master dashboard drive this instance; drop the AutoBuyer switch
Three changes that ride together because they touch the same surface. A control link to the master. lib/master-link.ts dials out to <master>/ws/instance and holds it open, so the dashboard can trigger a trade or queue an AutoBuyer run here. Commands call the same functions the local pages call — runTrade, startScheduler, queueRun — so nothing reaches the broker by a path the UI does not also use. Reports prefer the socket and fall back to the existing POST, which keeps older masters working unchanged. startMasterLink is idempotent, and that matters more than it looks: getClients() is lazy and starts the link, so the first command re-enters it from inside a command the live socket is waiting to ack. Tearing the socket down there loses the ack and reports a trade that actually executed as a failure — which invites pressing the button twice. queueRun is lifted out of the automations route so the socket and HTTP share one copy of the input clamping that decides how many times a purchase fires. Page capture loses its switch and gains a scope. It now runs every tick, but only against the active tab of the last-focused window that matches host_permissions — so it follows the page in front of you and stops when you switch away, where before it would fall back to any firm tab left open in the background. autobuyer_enabled is gone entirely. The AutoBuyer is ready whenever the runner is; a run happens because someone asked for one. That does mean a queued run executes as soon as clicker/runner.py claims it, with no second gate — stopping the runner is now the way to make a machine idle. Extension to 0.10.0; it needs a manual reload at chrome://extensions. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
0ba27161ce
commit
25289cb9b3
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { FIRMS, findAutomation, automationKey, describeStep, resolveSteps } from '@/lib/automations';
|
||||
import { createRun, getSetting } from '@/lib/db';
|
||||
import { FIRMS, automationKey, describeStep } from '@/lib/automations';
|
||||
import { queueRun, QueueRunError } from '@/lib/queue-run';
|
||||
import { corsJson, corsPreflight } from '../cors';
|
||||
|
||||
/** The dashboard renders a tab per firm, and a button per automation inside it. */
|
||||
@@ -30,38 +30,12 @@ export async function POST(req: NextRequest) {
|
||||
if (typeof body.automationId !== 'string') {
|
||||
return corsJson({ error: '`automationId` is required' }, { status: 400 });
|
||||
}
|
||||
const found = findAutomation(body.automationId);
|
||||
if (!found) {
|
||||
return corsJson({ error: `No automation "${body.automationId}"` }, { status: 404 });
|
||||
}
|
||||
if (found.automation.steps.length === 0) {
|
||||
return corsJson({ error: `"${found.automation.label}" has no steps yet` }, { status: 400 });
|
||||
}
|
||||
// The dashboard switch is the master arm for anything that drives the mouse.
|
||||
if (getSetting('autobuyer_enabled') !== '1') {
|
||||
return corsJson({ error: 'AutoBuyer is switched off' }, { status: 409 });
|
||||
}
|
||||
|
||||
// Clamp every input to what the automation declared. The count decides how
|
||||
// many times a purchase runs, so it is not taken on trust from the client.
|
||||
const supplied = (body.inputs ?? {}) as Record<string, unknown>;
|
||||
const inputs: Record<string, number> = {};
|
||||
for (const declared of found.automation.inputs ?? []) {
|
||||
const raw = Number(supplied[declared.id]);
|
||||
const value = Number.isFinite(raw) ? Math.floor(raw) : declared.default;
|
||||
inputs[declared.id] = Math.min(declared.max, Math.max(declared.min, value));
|
||||
}
|
||||
|
||||
let resolved;
|
||||
try {
|
||||
resolved = resolveSteps(found.firm, found.automation, inputs);
|
||||
} catch (err: any) {
|
||||
return corsJson({ error: err?.message ?? 'Could not expand the steps' }, { status: 400 });
|
||||
}
|
||||
|
||||
const run = createRun(body.automationId, resolved.length, inputs);
|
||||
return corsJson({ runId: run.id, totalSteps: run.total_steps, inputs });
|
||||
return corsJson(queueRun(body.automationId, (body.inputs ?? {}) as Record<string, unknown>));
|
||||
} catch (err: any) {
|
||||
if (err instanceof QueueRunError) {
|
||||
return corsJson({ error: err.message }, { status: err.status });
|
||||
}
|
||||
return corsJson({ error: err?.message ?? 'Failed to queue run' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { claimRun, getSetting } from '@/lib/db';
|
||||
import { claimRun } from '@/lib/db';
|
||||
import { findAutomation, resolveSteps, resolveAuthSteps } from '@/lib/automations';
|
||||
import { corsJson, corsPreflight } from '../../cors';
|
||||
|
||||
/** The Python runner polls this. Returns the run plus the steps to execute, so
|
||||
* the runner never needs its own copy of the automation definitions. */
|
||||
export async function POST() {
|
||||
if (getSetting('autobuyer_enabled') !== '1') {
|
||||
return corsJson({ run: null, reason: 'AutoBuyer is switched off' });
|
||||
}
|
||||
|
||||
const row = claimRun();
|
||||
if (!row) return corsJson({ run: null });
|
||||
|
||||
|
||||
@@ -1,29 +1,11 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { getSetting, setSetting, countPendingLocate } from '@/lib/db';
|
||||
import { countPendingLocate } from '@/lib/db';
|
||||
import { corsJson, corsPreflight } from '../cors';
|
||||
|
||||
/** Polled by the Chromium extension every few seconds, and by the AutoBuyer page.
|
||||
* `pendingLocate` rides along so the extension learns about queued clicks without
|
||||
* a second request on every tick. */
|
||||
* The AutoBuyer has no on/off switch — it is ready whenever the runner is — so
|
||||
* the only thing worth reporting here is whether clicks are waiting to be served. */
|
||||
export async function GET() {
|
||||
return corsJson({
|
||||
enabled: getSetting('autobuyer_enabled') === '1',
|
||||
pendingLocate: countPendingLocate(),
|
||||
});
|
||||
}
|
||||
|
||||
/** Flipped by the ON/OFF button on the AutoBuyer page. */
|
||||
export async function PATCH(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json() as { enabled?: unknown };
|
||||
if (typeof body.enabled !== 'boolean') {
|
||||
return corsJson({ error: '`enabled` must be a boolean' }, { status: 400 });
|
||||
}
|
||||
setSetting('autobuyer_enabled', body.enabled ? '1' : '0');
|
||||
return corsJson({ enabled: body.enabled });
|
||||
} catch (err: any) {
|
||||
return corsJson({ error: err?.message ?? 'Failed to set status' }, { status: 500 });
|
||||
}
|
||||
return corsJson({ pendingLocate: countPendingLocate() });
|
||||
}
|
||||
|
||||
export async function OPTIONS() {
|
||||
|
||||
+9
-55
@@ -115,9 +115,7 @@ function withBaseTag(html: string, url: string): string {
|
||||
}
|
||||
|
||||
export default function AutoBuyer() {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [capture, setCapture] = useState<Capture | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [view, setView] = useState<'rendered' | 'source'>('source');
|
||||
// The extension posts a new capture every few seconds, and re-feeding srcDoc would
|
||||
@@ -137,10 +135,6 @@ export default function AutoBuyer() {
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
try {
|
||||
const s = await fetch('/api/autobuyer/status', { cache: 'no-store' }).then((r) => r.json());
|
||||
setEnabled(!!s.enabled);
|
||||
if (!s.enabled) return;
|
||||
|
||||
const url = lastAtRef.current
|
||||
? `/api/autobuyer/capture?since=${lastAtRef.current}`
|
||||
: '/api/autobuyer/capture';
|
||||
@@ -236,24 +230,6 @@ export default function AutoBuyer() {
|
||||
await pollRuns();
|
||||
}
|
||||
|
||||
async function toggle() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch('/api/autobuyer/status', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: !enabled }),
|
||||
});
|
||||
const data = await res.json();
|
||||
setEnabled(!!data.enabled);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message ?? 'Failed to toggle');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function showRendered() {
|
||||
setView('rendered');
|
||||
if (capture) setPinned(capture);
|
||||
@@ -273,28 +249,11 @@ export default function AutoBuyer() {
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h1 className="text-2xl font-bold text-slate-900 mb-6">AutoBuyer</h1>
|
||||
|
||||
{/* ── Capture switch and daemon status ── */}
|
||||
{/* ── Daemon status ──
|
||||
There is no on/off switch. Page capture follows whichever firm
|
||||
tab you are looking at, and the AutoBuyer is ready whenever the
|
||||
daemon below is up — so that row is the whole of the state. */}
|
||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm mb-6">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-100">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-800">Page capture</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">
|
||||
While on, the AutoFirmer Capture extension posts the target tab's HTML here every few seconds
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={toggle}
|
||||
disabled={busy}
|
||||
className={`text-sm px-4 py-1.5 rounded-lg font-medium transition-colors disabled:opacity-50 ${
|
||||
enabled
|
||||
? 'bg-green-500 hover:bg-green-600 text-white'
|
||||
: 'bg-slate-200 hover:bg-slate-300 text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{busy ? '…' : enabled ? 'ON' : 'OFF'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-800">Autoclicker daemon</p>
|
||||
@@ -411,11 +370,10 @@ export default function AutoBuyer() {
|
||||
))}
|
||||
<button
|
||||
onClick={() => startRun(a)}
|
||||
disabled={!enabled || busyRun || activeRun !== null || !runner?.online || !!runner?.stale}
|
||||
disabled={busyRun || activeRun !== null || !runner?.online || !!runner?.stale}
|
||||
title={
|
||||
!enabled ? 'AutoBuyer is switched off'
|
||||
: !runner?.online ? 'The runner is not running'
|
||||
: runner?.stale ? 'The runner is out of date — restart it'
|
||||
!runner?.online ? 'The runner is not running'
|
||||
: runner?.stale ? 'The runner is out of date — restart it'
|
||||
: activeRun !== null ? 'A run is already in progress'
|
||||
: undefined
|
||||
}
|
||||
@@ -484,13 +442,9 @@ export default function AutoBuyer() {
|
||||
Latest capture
|
||||
</h2>
|
||||
|
||||
{!enabled ? (
|
||||
{!capture ? (
|
||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-8 text-center text-slate-400">
|
||||
Capture is off
|
||||
</div>
|
||||
) : !capture ? (
|
||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm p-8 text-center text-slate-400">
|
||||
Waiting for the extension… open a page in Chrome with the extension installed
|
||||
Waiting for the extension… switch to a firm tab in the Chrome window that has it installed
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
|
||||
|
||||
@@ -201,7 +201,8 @@ export default function SettingsPage() {
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-800">Dashboard URL</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">
|
||||
Reports state to this URL every 30 seconds
|
||||
Reports state here every 30 seconds, and holds a control
|
||||
socket open so the dashboard can trigger trades and buys
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
|
||||
Reference in New Issue
Block a user