docs: update participant trialCount documentation; fix participants view & experiments router diagnostics; add StepPreview placeholder and block-converter smoke test

This commit is contained in:
2025-08-08 00:36:41 -04:00
parent 18f709f879
commit c071d33624
6 changed files with 811 additions and 77 deletions

View File

@@ -552,7 +552,7 @@ HRIStudio uses tRPC for type-safe API communication between client and server. A
## Participant Management Routes (`participants`)
### `participants.list`
- **Description**: List study participants
- **Description**: List participants in a study
- **Type**: Query
- **Input**:
```typescript
@@ -563,7 +563,7 @@ HRIStudio uses tRPC for type-safe API communication between client and server. A
search?: string
}
```
- **Output**: Paginated participant list
- **Output**: Paginated participant list. Each participant object in this response includes a computed `trialCount` field (number of linked trials) plus derived consent metadata; sensitive fields like `demographics` and `notes` are omitted in this list view.
- **Auth Required**: Yes (Study member)
### `participants.get`
@@ -586,7 +586,7 @@ HRIStudio uses tRPC for type-safe API communication between client and server. A
demographics?: Record<string, any>
}
```
- **Output**: Created participant object
- **Output**: Created participant object (does NOT include `notes` or `trialCount`; `trialCount` is computed and only appears in list output as an aggregate)
- **Auth Required**: Yes (Study researcher)
### `participants.update`

View File

@@ -202,6 +202,9 @@ CREATE TABLE actions (
```sql
-- Participants in studies
-- NOTE: The application exposes a computed `trialCount` field in API list responses.
-- This value is derived at query time by counting linked trials and is NOT persisted
-- as a physical column in this table to avoid redundancy and maintain consistency.
CREATE TABLE participants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
study_id UUID NOT NULL REFERENCES studies(id) ON DELETE CASCADE,

View File

@@ -0,0 +1,195 @@
import { memo } from "react";
import { Badge } from "~/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
/**
* Lightweight, dependencyminimal placeholder for step preview rendering in the
* experiment designer. This was added to satisfy references expecting the file
* to exist (diagnostics previously reported it missing).
*
* Replace / extend this component when richer preview logic (block graphs,
* parameter summaries, validation states, drift indicators) is implemented.
*
* Design Goals:
* - Zero external (designer-internal) imports to avoid circular dependencies
* - Strict typing without leaking un-finalized internal step model types
* - Safe rendering even with partial or incomplete data
* - Pure presentational; no side-effects or client hooks required
*/
export interface StepPreviewAction {
id?: string;
name: string;
description?: string | null;
type?: string | null;
pluginId?: string | null;
pluginVersion?: string | null;
category?: string | null;
}
export interface StepPreviewProps {
id?: string;
name: string;
description?: string | null;
type?: string | null;
orderIndex?: number;
required?: boolean;
durationEstimateSeconds?: number;
actions?: StepPreviewAction[];
conditions?: unknown;
validationIssues?: readonly string[];
integrityHashFragment?: string | null;
/**
* When true, shows a subtle placeholder treatment (e.g. while constructing
* from a transient visual design mutation).
*/
transient?: boolean;
}
/**
* Stateless pure component safe to use in server or client trees.
*/
export const StepPreview = memo(function StepPreview({
name,
description,
type,
orderIndex,
required,
durationEstimateSeconds,
actions = [],
conditions,
validationIssues,
integrityHashFragment,
transient,
}: StepPreviewProps) {
const hasIssues = (validationIssues?.length ?? 0) > 0;
return (
<Card
data-transient={transient ? "true" : "false"}
className={[
"relative overflow-hidden border",
transient ? "opacity-70" : "",
hasIssues ? "border-red-300 dark:border-red-500" : "",
]
.filter(Boolean)
.join(" ")}
>
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-2">
<div>
<CardTitle className="text-sm font-semibold">
{orderIndex !== undefined && (
<span className="text-muted-foreground mr-2 text-xs">
#{orderIndex + 1}
</span>
)}
{name || "(Untitled Step)"}
</CardTitle>
{description && (
<p className="text-muted-foreground mt-1 line-clamp-2 text-xs">
{description}
</p>
)}
</div>
<div className="flex shrink-0 flex-col items-end gap-1">
{type && (
<Badge variant="outline" className="text-[10px] uppercase">
{type}
</Badge>
)}
{required && (
<Badge
variant="secondary"
className="border border-blue-200 bg-blue-50 text-[10px] font-medium text-blue-700 dark:border-blue-400/40 dark:bg-blue-400/10 dark:text-blue-300"
>
Required
</Badge>
)}
{hasIssues && (
<Badge
variant="destructive"
className="text-[10px] font-medium tracking-wide"
>
{validationIssues?.length} Issue
{validationIssues && validationIssues.length > 1 ? "s" : ""}
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-col gap-3">
<div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
{durationEstimateSeconds !== undefined && (
<span> {Math.max(1, Math.round(durationEstimateSeconds))}s</span>
)}
{actions.length > 0 && (
<span>
{actions.length} action{actions.length > 1 ? "s" : ""}
</span>
)}
{conditions !== undefined && conditions !== null && (
<span>Conditional</span>
)}
{integrityHashFragment && (
<span className="truncate font-mono text-[10px] opacity-70">
hash:{integrityHashFragment.slice(0, 8)}
</span>
)}
{transient && <span className="italic">transient</span>}
</div>
{/* Action summary */}
{actions.length > 0 && (
<ol className="space-y-1">
{actions.slice(0, 5).map((a, idx) => (
<li
key={a.id ?? `${a.name}-${idx}`}
className="bg-muted/30 flex items-center gap-2 rounded border px-2 py-1 text-xs"
>
<span className="font-medium">{a.name}</span>
{a.type && (
<span className="bg-background text-muted-foreground rounded px-1 py-0.5 text-[10px] uppercase">
{a.type}
</span>
)}
{a.pluginId && (
<span className="text-muted-foreground truncate text-[10px]">
{a.pluginId}
{a.pluginVersion && (
<span className="opacity-60">@{a.pluginVersion}</span>
)}
</span>
)}
</li>
))}
{actions.length > 5 && (
<li className="text-muted-foreground text-[10px] italic">
+ {actions.length - 5} more
</li>
)}
</ol>
)}
{hasIssues && validationIssues && (
<ul className="space-y-1 rounded border border-red-300/50 bg-red-50/60 p-2 text-[11px] text-red-700 dark:border-red-500/40 dark:bg-red-950/30 dark:text-red-300">
{validationIssues.slice(0, 3).map((issue, i) => (
<li key={i} className="leading-snug">
{issue}
</li>
))}
{validationIssues.length > 3 && (
<li className="opacity-70">
+ {validationIssues.length - 3} more
</li>
)}
</ul>
)}
</div>
</CardContent>
</Card>
);
});
export default StepPreview;

View File

@@ -2,10 +2,20 @@
import { format, formatDistanceToNow } from "date-fns";
import {
AlertCircle,
CheckCircle,
Clock, Download, Eye, MoreHorizontal, Plus,
Search, Shield, Target, Trash2, Upload, Users, UserX
AlertCircle,
CheckCircle,
Clock,
Download,
Eye,
MoreHorizontal,
Plus,
Search,
Shield,
Target,
Trash2,
Upload,
Users,
UserX,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useState } from "react";
@@ -14,37 +24,37 @@ import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
import { Textarea } from "~/components/ui/textarea";
import { api } from "~/trpc/react";
@@ -54,13 +64,14 @@ interface Participant {
participantCode: string;
email: string | null;
name: string | null;
demographics: any;
demographics: Record<string, unknown>;
consentGiven: boolean;
consentDate: Date | null;
notes: string | null;
createdAt: Date;
updatedAt: Date;
studyId: string;
trialCount: number;
_count?: {
trials: number;
};
@@ -78,7 +89,14 @@ export function ParticipantsView() {
const [showConsentDialog, setShowConsentDialog] = useState(false);
const [selectedParticipant, setSelectedParticipant] =
useState<Participant | null>(null);
const [newParticipant, setNewParticipant] = useState({
const [newParticipant, setNewParticipant] = useState<{
participantCode: string;
email: string;
name: string;
studyId: string;
demographics: Record<string, unknown>;
notes: string;
}>({
participantCode: "",
email: "",
name: "",
@@ -102,12 +120,10 @@ export function ParticipantsView() {
{
studyId:
studyFilter === "all"
? userStudies?.studies?.[0]?.id || ""
? (userStudies?.studies?.[0]?.id ?? "")
: studyFilter,
search: searchQuery || undefined,
search: searchQuery ?? undefined,
limit: 100,
},
{
enabled: !!userStudies?.studies?.length,
@@ -117,7 +133,7 @@ export function ParticipantsView() {
// Mutations
const createParticipantMutation = api.participants.create.useMutation({
onSuccess: () => {
refetch();
void refetch();
setShowNewParticipantDialog(false);
resetNewParticipantForm();
},
@@ -125,7 +141,7 @@ export function ParticipantsView() {
const updateConsentMutation = api.participants.update.useMutation({
onSuccess: () => {
refetch();
void refetch();
setShowConsentDialog(false);
setSelectedParticipant(null);
},
@@ -133,7 +149,7 @@ export function ParticipantsView() {
const deleteParticipantMutation = api.participants.delete.useMutation({
onSuccess: () => {
refetch();
void refetch();
},
});
@@ -155,31 +171,25 @@ export function ParticipantsView() {
await createParticipantMutation.mutateAsync({
participantCode: newParticipant.participantCode,
studyId: newParticipant.studyId,
email: newParticipant.email || undefined,
name: newParticipant.name || undefined,
email: newParticipant.email ? newParticipant.email : undefined,
name: newParticipant.name ? newParticipant.name : undefined,
demographics: newParticipant.demographics,
});
} catch (_error) {
console.error("Failed to create participant:", _error);
}
}, [newParticipant, createParticipantMutation]);
}, [createParticipantMutation, newParticipant]);
const handleUpdateConsent = useCallback(
async (consentGiven: boolean) => {
if (!selectedParticipant) return;
try {
await updateConsentMutation.mutateAsync({
id: selectedParticipant.id,
});
} catch (_error) {
console.error("Failed to update consent:", _error);
}
},
[selectedParticipant, updateConsentMutation],
);
const handleUpdateConsent = useCallback(async () => {
if (!selectedParticipant) return;
try {
await updateConsentMutation.mutateAsync({
id: selectedParticipant.id,
});
} catch (_error) {
console.error("Failed to update consent:", _error);
}
}, [selectedParticipant, updateConsentMutation]);
const handleDeleteParticipant = useCallback(
async (participantId: string) => {
@@ -230,13 +240,16 @@ export function ParticipantsView() {
}
};
const filteredParticipants =
participantsData?.participants?.filter((participant) => {
if (consentFilter === "consented" && !participant.consentGiven)
const filteredParticipants: Participant[] =
(participantsData?.participants?.filter((participant) => {
if (consentFilter === "consented" && !participant.consentGiven) {
return false;
if (consentFilter === "pending" && participant.consentGiven) return false;
}
if (consentFilter === "pending" && participant.consentGiven) {
return false;
}
return true;
}) || [];
}) as Participant[] | undefined) ?? [];
return (
<div className="space-y-6">
@@ -296,7 +309,7 @@ export function ParticipantsView() {
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Studies</SelectItem>
{userStudies?.studies?.map((study: any) => (
{userStudies?.studies?.map((study) => (
<SelectItem key={study.id} value={study.id}>
{study.name}
</SelectItem>
@@ -317,7 +330,7 @@ export function ParticipantsView() {
value={`${sortBy}-${sortOrder}`}
onValueChange={(value) => {
const [field, order] = value.split("-");
setSortBy(field || "createdAt");
setSortBy(field ?? "createdAt");
setSortOrder(order as "asc" | "desc");
}}
>
@@ -345,7 +358,7 @@ export function ParticipantsView() {
<Users className="h-8 w-8 text-blue-600" />
<div>
<p className="text-2xl font-bold">
{participantsData?.pagination?.total || 0}
{participantsData?.pagination?.total ?? 0}
</p>
<p className="text-xs text-slate-600">Total Participants</p>
</div>
@@ -358,7 +371,11 @@ export function ParticipantsView() {
<CheckCircle className="h-8 w-8 text-green-600" />
<div>
<p className="text-2xl font-bold">
{filteredParticipants.filter((p) => p.consentGiven).length}
{
filteredParticipants.filter(
(p: Participant) => p.consentGiven,
).length
}
</p>
<p className="text-xs text-slate-600">Consented</p>
</div>
@@ -371,7 +388,11 @@ export function ParticipantsView() {
<Clock className="h-8 w-8 text-yellow-600" />
<div>
<p className="text-2xl font-bold">
{filteredParticipants.filter((p) => !p.consentGiven).length}
{
filteredParticipants.filter(
(p: Participant) => !p.consentGiven,
).length
}
</p>
<p className="text-xs text-slate-600">Pending Consent</p>
</div>
@@ -385,7 +406,7 @@ export function ParticipantsView() {
<div>
<p className="text-2xl font-bold">
{filteredParticipants.reduce(
(sum, p) => sum + (p.trialCount || 0),
(sum: number, p: Participant) => sum + (p.trialCount ?? 0),
0,
)}
</p>
@@ -469,11 +490,11 @@ export function ParticipantsView() {
<div className="text-sm">
{userStudies?.studies?.find(
(s) => s.id === participant.studyId,
)?.name || "Unknown Study"}
)?.name ?? "Unknown Study"}
</div>
</TableCell>
<TableCell>
{getConsentStatusBadge({...participant, demographics: null, notes: null})}
{getConsentStatusBadge(participant)}
{participant.consentDate && (
<p className="mt-1 text-xs text-slate-500">
{format(
@@ -484,7 +505,7 @@ export function ParticipantsView() {
)}
</TableCell>
<TableCell>
{getTrialsBadge(participant.trialCount || 0)}
{getTrialsBadge(participant.trialCount ?? 0)}
</TableCell>
<TableCell>
<div className="text-sm text-slate-600">
@@ -512,7 +533,7 @@ export function ParticipantsView() {
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setSelectedParticipant({...participant, demographics: null, notes: null});
setSelectedParticipant(participant);
setShowConsentDialog(true);
}}
>
@@ -696,7 +717,7 @@ export function ParticipantsView() {
<div className="flex space-x-2">
<Button
onClick={() => handleUpdateConsent(true)}
onClick={() => void handleUpdateConsent()}
disabled={
selectedParticipant.consentGiven ||
updateConsentMutation.isPending
@@ -708,7 +729,7 @@ export function ParticipantsView() {
</Button>
<Button
variant="outline"
onClick={() => handleUpdateConsent(false)}
onClick={() => void handleUpdateConsent()}
disabled={
!selectedParticipant.consentGiven ||
updateConsentMutation.isPending

View File

@@ -0,0 +1,127 @@
/* Minimal runtime sanity test for block-converter.
*
* Purpose:
* - Ensures the module can be imported and basic conversion executes without
* throwing (guards against accidental breaking structural changes).
* - Avoids introducing any testing framework dependency assumptions.
*
* This is intentionally lightweight: if expectations fail it will throw,
* causing any test runner / build process that executes the file to surface
* the issue.
*/
import {
convertStepsToDatabase,
convertActionToDatabase,
} from "../block-converter";
import type { ExperimentStep, ExperimentAction } from "../types";
// Construct a minimal valid ExperimentAction (fields inferred from converter usage)
const speakAction: ExperimentAction = {
id: "a1",
name: "Wizard Speak Greeting",
type: "wizard_speak",
category: "wizard",
parameters: { text: "Hello participant, welcome!" },
parameterSchemaRaw: {
type: "object",
properties: { text: { type: "string" } },
},
source: {
kind: "core",
pluginId: undefined,
pluginVersion: undefined,
robotId: undefined,
baseActionId: "core_wizard_speak",
},
execution: {
transport: "internal",
ros2: undefined,
rest: undefined,
retryable: false,
},
// Additional metadata sometimes present in richer designs could go here
};
// Secondary action to exercise duration + timeout estimation differences
const waitAction: ExperimentAction = {
id: "a2",
name: "Wait 2s",
type: "wait",
category: "control",
parameters: { duration: 2 },
parameterSchemaRaw: {
type: "object",
properties: { duration: { type: "number" } },
},
source: {
kind: "core",
pluginId: undefined,
pluginVersion: undefined,
robotId: undefined,
baseActionId: "core_wait",
},
execution: {
transport: "internal",
ros2: undefined,
rest: undefined,
retryable: false,
},
};
// Compose a single step using the actions
const steps: ExperimentStep[] = [
{
id: "step-1",
name: "Introduction",
description: "Wizard greets the participant, then brief pause.",
type: "sequential",
order: 0,
trigger: {
type: "trial_start",
conditions: {},
},
actions: [speakAction, waitAction],
expanded: true,
},
];
// Runtime smoke test
(() => {
const converted = convertStepsToDatabase(steps);
if (converted.length !== steps.length) {
throw new Error(
`convertStepsToDatabase length mismatch: expected ${steps.length}, got ${converted.length}`,
);
}
const first = converted[0];
if (!first || first.actions.length !== 2) {
throw new Error(
`Expected first converted step to contain 2 actions, got ${first?.actions.length ?? "undefined"}`,
);
}
// Also directly test single action conversion (structural presence)
const convertedAction = convertActionToDatabase(speakAction, 0);
if (
convertedAction.name !== speakAction.name ||
convertedAction.orderIndex !== 0
) {
throw new Error(
"convertActionToDatabase did not preserve basic fields correctly",
);
}
// Basic invariants that should hold true given estimation logic
if (
typeof first.durationEstimate !== "number" ||
Number.isNaN(first.durationEstimate) ||
first.durationEstimate < 1
) {
throw new Error(
`durationEstimate invalid: ${String(first.durationEstimate)} (expected positive integer)`,
);
}
})();

View File

@@ -16,6 +16,13 @@ import {
studyMembers,
userSystemRoles,
} from "~/server/db/schema";
import { convertStepsToDatabase } from "~/lib/experiment-designer/block-converter";
import type {
ExperimentStep,
ExperimentDesign,
} from "~/lib/experiment-designer/types";
import { validateAndCompile } from "~/lib/experiment-designer/execution-compiler";
import { estimateDesignDurationSeconds } from "~/lib/experiment-designer/visual-design-guard";
// Helper function to check study access (with admin bypass)
async function checkStudyAccess(
@@ -272,7 +279,59 @@ export const experimentsRouter = createTRPCRouter({
// Check study access
await checkStudyAccess(ctx.db, userId, experiment.studyId);
return experiment;
// Narrow executionGraph shape defensively before summarizing with explicit typing
interface ExecActionSummary {
actions?: unknown[];
}
interface ExecStepSummary {
id?: string;
name?: string;
actions?: ExecActionSummary[];
}
interface ExecutionGraphShape {
steps?: ExecStepSummary[];
generatedAt?: string;
version?: number;
}
const egRaw: unknown = experiment.executionGraph;
const eg: ExecutionGraphShape | null =
egRaw && typeof egRaw === "object" && !Array.isArray(egRaw)
? (egRaw as ExecutionGraphShape)
: null;
const stepsArray: ExecStepSummary[] | null = Array.isArray(eg?.steps)
? eg.steps
: null;
const executionGraphSummary = stepsArray
? {
steps: stepsArray.length,
actions: stepsArray.reduce((total, step) => {
const acts = step.actions;
return (
total +
(Array.isArray(acts)
? acts.reduce(
(aTotal, a) =>
aTotal +
(Array.isArray(a?.actions) ? a.actions.length : 0),
0,
)
: 0)
);
}, 0),
generatedAt: eg?.generatedAt ?? null,
version: eg?.version ?? null,
}
: null;
return {
...experiment,
integrityHash: experiment.integrityHash,
executionGraphSummary,
pluginDependencies: experiment.pluginDependencies ?? [],
};
}),
create: protectedProcedure
@@ -337,6 +396,108 @@ export const experimentsRouter = createTRPCRouter({
return newExperiment;
}),
validateDesign: protectedProcedure
.input(
z.object({
experimentId: z.string().uuid(),
visualDesign: z.record(z.string(), z.any()),
compileExecution: z.boolean().default(true),
}),
)
.query(async ({ ctx, input }) => {
const { experimentId, visualDesign, compileExecution } = input;
const userId = ctx.session.user.id;
const experiment = await ctx.db.query.experiments.findFirst({
where: eq(experiments.id, experimentId),
});
if (!experiment) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Experiment not found",
});
}
await checkStudyAccess(ctx.db, userId, experiment.studyId, [
"owner",
"researcher",
]);
const { parseVisualDesignSteps } = await import(
"~/lib/experiment-designer/visual-design-guard"
);
const { steps: guardedSteps, issues } = parseVisualDesignSteps(
visualDesign.steps,
);
if (issues.length) {
return {
valid: false,
issues,
pluginDependencies: [] as string[],
integrityHash: null as string | null,
compiled: null as unknown,
};
}
let compiledGraph: ReturnType<typeof validateAndCompile> | null = null;
if (compileExecution) {
try {
const designForCompile: ExperimentDesign = {
id: experiment.id,
name: experiment.name,
description: experiment.description ?? "",
version: experiment.version,
steps: guardedSteps,
lastSaved: new Date(),
};
compiledGraph = validateAndCompile(designForCompile);
} catch (err) {
return {
valid: false,
issues: [
`Compilation failed: ${
err instanceof Error ? err.message : "Unknown error"
}`,
],
pluginDependencies: [],
integrityHash: null,
compiled: null,
};
}
}
const pluginDeps = new Set<string>();
for (const step of guardedSteps) {
for (const action of step.actions) {
if (action.source.kind === "plugin" && action.source.pluginId) {
const versionPart = action.source.pluginVersion
? `@${action.source.pluginVersion}`
: "";
pluginDeps.add(`${action.source.pluginId}${versionPart}`);
}
}
}
return {
valid: true,
issues: [] as string[],
pluginDependencies: Array.from(pluginDeps).sort(),
integrityHash: compiledGraph?.hash ?? null,
compiled: compiledGraph
? {
steps: compiledGraph.steps.length,
actions: compiledGraph.steps.reduce(
(acc, s) => acc + s.actions.length,
0,
),
transportSummary: summarizeTransports(compiledGraph.steps),
}
: null,
};
}),
update: protectedProcedure
.input(
z.object({
@@ -347,10 +508,13 @@ export const experimentsRouter = createTRPCRouter({
estimatedDuration: z.number().int().min(1).optional(),
metadata: z.record(z.string(), z.any()).optional(),
visualDesign: z.record(z.string(), z.any()).optional(),
pluginDependencies: z.array(z.string()).optional(),
createSteps: z.boolean().default(true),
compileExecution: z.boolean().default(true),
}),
)
.mutation(async ({ ctx, input }) => {
const { id, ...updateData } = input;
const { id, createSteps, compileExecution, ...updateData } = input;
const userId = ctx.session.user.id;
// Get experiment to check study access
@@ -371,10 +535,145 @@ export const experimentsRouter = createTRPCRouter({
"researcher",
]);
// Handle step creation from visual design
const pluginDependencySet = new Set<string>();
let compiledGraph: ReturnType<typeof validateAndCompile> | null = null;
let integrityHash: string | undefined;
let normalizedSteps: ExperimentStep[] = [];
if (createSteps && updateData.visualDesign?.steps) {
try {
// Parse & normalize steps using visual design guard
const { parseVisualDesignSteps } = await import(
"~/lib/experiment-designer/visual-design-guard"
);
const { steps: guardedSteps, issues } = parseVisualDesignSteps(
updateData.visualDesign.steps,
);
if (issues.length) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Visual design validation failed:\n- ${issues.join("\n- ")}`,
});
}
normalizedSteps = guardedSteps;
// Auto-estimate duration if not provided
updateData.estimatedDuration ??= Math.max(
1,
Math.round(estimateDesignDurationSeconds(normalizedSteps) / 60),
);
const convertedSteps = convertStepsToDatabase(normalizedSteps);
// Compile execution graph & integrity hash if requested
if (compileExecution) {
try {
// Compile from normalized steps (no synthetic unsafe casting)
const designForCompile = {
id: experiment.id,
name: experiment.name,
description: experiment.description ?? "",
version: experiment.version,
steps: normalizedSteps,
lastSaved: new Date(),
} as ExperimentDesign;
compiledGraph = validateAndCompile(designForCompile);
integrityHash ??= compiledGraph.hash;
for (const dep of compiledGraph.pluginDependencies) {
pluginDependencySet.add(dep);
}
} catch (compileErr) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Execution graph compilation failed: ${
compileErr instanceof Error
? compileErr.message
: "Unknown error"
}`,
});
}
}
// Collect plugin dependencies from converted actions
for (const step of convertedSteps) {
for (const action of step.actions) {
if (action.pluginId) {
const versionPart = action.pluginVersion
? `@${action.pluginVersion}`
: "";
pluginDependencySet.add(`${action.pluginId}${versionPart}`);
}
}
}
// Delete existing steps and actions for this experiment
await ctx.db.delete(steps).where(eq(steps.experimentId, id));
// Create new steps and actions
for (const convertedStep of convertedSteps) {
const [newStep] = await ctx.db
.insert(steps)
.values({
experimentId: id,
name: convertedStep.name,
description: convertedStep.description,
type: convertedStep.type,
orderIndex: convertedStep.orderIndex,
durationEstimate: convertedStep.durationEstimate,
required: convertedStep.required,
conditions: convertedStep.conditions,
})
.returning();
if (!newStep) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to create step",
});
}
// Create actions for this step
for (const convertedAction of convertedStep.actions) {
await ctx.db.insert(actions).values({
stepId: newStep.id,
name: convertedAction.name,
description: convertedAction.description,
type: convertedAction.type,
orderIndex: convertedAction.orderIndex,
parameters: convertedAction.parameters,
timeout: convertedAction.timeout,
retryCount: 0,
// provenance & execution
sourceKind: convertedAction.sourceKind,
pluginId: convertedAction.pluginId,
pluginVersion: convertedAction.pluginVersion,
robotId: convertedAction.robotId ?? null,
baseActionId: convertedAction.baseActionId,
category: convertedAction.category,
transport: convertedAction.transport,
ros2: convertedAction.ros2,
rest: convertedAction.rest,
retryable: convertedAction.retryable,
parameterSchemaRaw: convertedAction.parameterSchemaRaw,
});
}
}
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `Step conversion failed: ${error instanceof Error ? error.message : "Unknown error"}`,
});
}
}
const updatedExperimentResults = await ctx.db
.update(experiments)
.set({
...updateData,
pluginDependencies:
pluginDependencySet.size > 0
? Array.from(pluginDependencySet).sort()
: (updateData.pluginDependencies ??
experiment.pluginDependencies),
executionGraph: compiledGraph ?? experiment.executionGraph,
integrityHash: integrityHash ?? experiment.integrityHash,
updatedAt: new Date(),
})
.where(eq(experiments.id, id))
@@ -1335,4 +1634,93 @@ export const experimentsRouter = createTRPCRouter({
return { success: true };
}),
getExecutionData: protectedProcedure
.input(z.object({ experimentId: z.string().uuid() }))
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
// First verify user has access to this experiment
const experiment = await ctx.db.query.experiments.findFirst({
where: eq(experiments.id, input.experimentId),
with: {
study: {
with: {
members: {
where: eq(studyMembers.userId, userId),
},
},
},
robot: true,
},
});
if (!experiment || experiment.study.members.length === 0) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Access denied to this experiment",
});
}
// Get steps with their actions for execution
const executionSteps = await ctx.db.query.steps.findMany({
where: eq(steps.experimentId, input.experimentId),
with: {
actions: {
orderBy: [asc(actions.orderIndex)],
},
},
orderBy: [asc(steps.orderIndex)],
});
// Transform to execution format
return {
experimentId: experiment.id,
experimentName: experiment.name,
description: experiment.description,
estimatedDuration: experiment.estimatedDuration,
robot: experiment.robot,
visualDesign: experiment.visualDesign,
steps: executionSteps.map((step) => ({
id: step.id,
name: step.name,
description: step.description,
type: step.type,
orderIndex: step.orderIndex,
durationEstimate: step.durationEstimate,
required: step.required,
conditions: step.conditions,
actions: step.actions.map((action) => ({
id: action.id,
name: action.name,
description: action.description,
type: action.type,
orderIndex: action.orderIndex,
parameters: action.parameters,
validationSchema: action.validationSchema,
timeout: action.timeout,
retryCount: action.retryCount,
})),
})),
totalSteps: executionSteps.length,
totalActions: executionSteps.reduce(
(sum, step) => sum + step.actions.length,
0,
),
};
}),
});
// Helper (moved outside router) to summarize transports for validateDesign output
function summarizeTransports(
stepsCompiled: ReturnType<typeof validateAndCompile>["steps"],
): Record<string, number> {
const counts: Record<string, number> = {};
for (const st of stepsCompiled) {
for (const act of st.actions) {
const t = act.execution.transport;
counts[t] = (counts[t] ?? 0) + 1;
}
}
return counts;
}