Files
triggershell/src/components/forms/dynamic-form.tsx
T
valknarandClaude Sonnet 5 e13b7e3b1a Add triggershell run/scripts - execute configured scripts from the CLI
`run <scriptId>` auto-detects whether the web server is already
reachable (a quick /api/healthz check):

- If it is, the run goes through the existing POST
  /api/scripts/:id/runs endpoint (token-authenticated, same as any
  other API client) and the CLI subscribes over /ws/runs exactly like
  a browser tab - so the run shows up live in Run History and any open
  browser watching it, with zero server-side changes, since the
  broadcast path has no idea a run was triggered by a click vs a CLI
  invocation.
- If nothing's reachable, it calls startRun() directly in its own
  process (after its own migrateOnBoot/reconcileOrphanedRuns, so a
  from-scratch .triggershell/ works standalone) and streams output by
  listening on the same in-process runEvents emitter a WS client would
  otherwise be fed from - read-log-then-listen, the same ordering
  ws/server.ts's subscribe() already uses, so a fast script finishing
  before the listener attaches still gets its output printed.

Both modes support --var name=value (repeatable; repeat a name for
multiselect), --no-wait, and Ctrl-C cancellation through the same
mechanism the web UI's Cancel button uses (a WS cancel message
remotely, cancelRun() directly locally). `scripts list`/`scripts show`
are local-only, no network - same direct-config-read pattern as
`validate`/`doctor`.

Extracts defaultValuesForScript() out of dynamic-form.tsx into
src/lib/config/defaults.ts so the CLI's --var handling and the web
form fill in a script's configured defaults identically instead of
duplicating that logic.

Verified live end-to-end: a CLI-triggered remote run was observed
streaming to both the triggering CLI process and an independent WS
client (simulating a browser tab) simultaneously; local-mode Ctrl-C
confirmed to actually kill the spawned child process, not just the
CLI; token, wrong-token, and TRIGGERSHELL_API_TOKEN auth paths all
verified against a running auth-enabled server.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-16 12:29:55 +02:00

115 lines
3.7 KiB
TypeScript

"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Play, Loader2, Info } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Form } from "@/components/ui/form";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { buildVariableSchemaFromList } from "@/lib/validation/variable-schema";
import { defaultValuesForScript } from "@/lib/config/defaults";
import type { ClientScript } from "@/lib/config/serialize";
import { FieldRenderer } from "./field-renderer";
/** `initialValues` comes from a previous run's (already-redacted) variables when re-running -
* secret fields are deliberately excluded there (their stored value is just "***", not the real
* one), so those always fall through to the normal default/empty state and have to be re-entered. */
function defaultValuesFor(
script: ClientScript,
initialValues?: Record<string, unknown>,
): Record<string, unknown> {
const values = defaultValuesForScript(script.variables);
if (!initialValues) return values;
for (const variable of script.variables) {
if (variable.secret) continue;
const fromPreviousRun = initialValues[variable.name];
if (fromPreviousRun !== undefined) values[variable.name] = fromPreviousRun;
}
return values;
}
export function DynamicForm({
script,
initialValues,
}: {
script: ClientScript;
initialValues?: Record<string, unknown>;
}) {
const router = useRouter();
const [submitError, setSubmitError] = useState<string | null>(null);
const schema = buildVariableSchemaFromList(script.variables);
const hasSecretVariable = script.variables.some((v) => v.secret);
const form = useForm({
resolver: zodResolver(schema),
defaultValues: defaultValuesFor(script, initialValues),
});
async function onSubmit(values: Record<string, unknown>) {
setSubmitError(null);
const response = await fetch(`/api/scripts/${script.id}/runs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ variables: values }),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
setSubmitError(data.error ?? "Failed to start run");
return;
}
const data = await response.json();
toast.success(`${script.name} started`);
router.push(`/runs/${data.runId}`);
}
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-5"
>
{submitError && (
<Alert variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
{initialValues && (
<Alert>
<Info />
<AlertDescription>
Pre-filled from a previous run.
{hasSecretVariable &&
" Secret fields aren't carried over and need to be entered again."}
</AlertDescription>
</Alert>
)}
{script.variables.length === 0 && (
<p className="text-muted-foreground text-sm">
This script takes no parameters.
</p>
)}
{script.variables.map((variable) => (
<FieldRenderer key={variable.name} variable={variable} />
))}
<Button
type="submit"
disabled={form.formState.isSubmitting}
className="w-fit"
>
{form.formState.isSubmitting ? (
<Loader2 className="animate-spin" />
) : (
<Play />
)}
Run
</Button>
</form>
</Form>
);
}