Open History to see the last commit
1import { For, Show, createEffect, createMemo, createSignal } from 'solid-js'
2import { useAIStore } from '../../store/ai-context'
3import { useStyles } from '../../styles/use-styles'
4import { FixtureNamePopover } from './FixtureNamePopover'
5import type {
6 HookRecord,
7 RegisteredTool,
8 ToolFixtureRecord,
9} from '../../store/hook-registry'
10import type { Component } from 'solid-js'
11
12interface ToolFixtureFormProps {
13 hook: HookRecord
14 tool: RegisteredTool
15 onFire: (fixture: ToolFixtureRecord) => void
16}
17
18interface SchemaField {
19 name: string
20 type: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array'
21 required: boolean
22 description?: string
23}
24
25export const ToolFixtureForm: Component<ToolFixtureFormProps> = (props) => {
26 const { saveToolFixture } = useAIStore()
27 const styles = useStyles()
28 const fields = createMemo(() => fieldsFromSchema(props.tool.inputSchema))
29 const [inputValues, setInputValues] = createSignal<Record<string, string>>(
30 defaultValues(fields()),
31 )
32 const [rawInput, setRawInput] = createSignal('{}')
33 const [output, setOutput] = createSignal('null')
34 const [error, setError] = createSignal<string | null>(null)
35 const [pendingSaveName, setPendingSaveName] = createSignal<string | null>(
36 null,
37 )
38
39 createEffect(() => {
40 void props.tool.name
41 setInputValues(defaultValues(fields()))
42 setRawInput('{}')
43 setOutput('null')
44 setError(null)
45 setPendingSaveName(null)
46 })
47
48 const setFieldValue = (name: string, value: string) => {
49 setInputValues((current) => ({ ...current, [name]: value }))
50 }
51
52 const createFixture = (name?: string): ToolFixtureRecord | undefined => {
53 try {
54 setError(null)
55 const createdAt = Date.now()
56 const parsedInput =
57 fields().length > 0
58 ? parseObjectInput(fields(), inputValues())
59 : parseJson(rawInput(), 'Input')
60 const parsedOutput = parseJson(output(), 'Output')
61 return {
62 id: `fixture:${props.hook.id}:${props.tool.name}:${createdAt}:${Math.random()
63 .toString(36)
64 .slice(2)}`,
65 createdAt,
66 ...(name ? { name } : {}),
67 hookId: props.hook.id,
68 ...(props.hook.threadId ? { threadId: props.hook.threadId } : {}),
69 toolName: props.tool.name,
70 input: parsedInput,
71 output: parsedOutput,
72 execute: true,
73 }
74 } catch (fixtureError) {
75 setError(
76 fixtureError instanceof Error
77 ? fixtureError.message
78 : 'Unable to create fixture.',
79 )
80 return undefined
81 }
82 }
83
84 const handleFire = () => {
85 const fixture = createFixture()
86 if (!fixture) return
87 props.onFire(fixture)
88 }
89
90 const handleSave = () => {
91 setPendingSaveName(`${props.tool.name} fixture`)
92 }
93
94 const handleConfirmSave = (name: string) => {
95 const fixture = createFixture(name)
96 if (!fixture) return
97 saveToolFixture(fixture)
98 setPendingSaveName(null)
99 }
100
101 return (
102 <div
103 class={styles().hookDetails.fixtureForm}
104 data-testid="ai-devtools-tool-fixture-form"
105 data-tool-name={props.tool.name}
106 >
107 <div class={styles().hookDetails.sectionTitle}>Tool Fixture</div>
108 <div class={styles().hookDetails.fixtureHelp}>
109 {props.tool.description || props.tool.name}
110 </div>
111
112 <Show
113 when={fields().length > 0}
114 fallback={
115 <label class={styles().hookDetails.fixtureField}>
116 <span class={styles().hookDetails.fixtureLabel}>Input JSON</span>
117 <textarea
118 class={styles().hookDetails.fixtureTextarea}
119 value={rawInput()}
120 onInput={(event) => setRawInput(event.currentTarget.value)}
121 spellcheck={false}
122 />
123 </label>
124 }
125 >
126 <For each={fields()}>
127 {(field) => (
128 <label class={styles().hookDetails.fixtureField}>
129 <span class={styles().hookDetails.fixtureLabel}>
130 {field.name}
131 <Show when={field.required}>
132 <span class={styles().hookDetails.requiredMark}>*</span>
133 </Show>
134 </span>
135 <Show when={field.description}>
136 <span class={styles().hookDetails.fixtureHelp}>
137 {field.description}
138 </span>
139 </Show>
140 <FieldInput
141 field={field}
142 value={inputValues()[field.name] ?? ''}
143 onInput={(value) => setFieldValue(field.name, value)}
144 />
145 </label>
146 )}
147 </For>
148 </Show>
149
150 <label class={styles().hookDetails.fixtureField}>
151 <span class={styles().hookDetails.fixtureLabel}>Output JSON</span>
152 <textarea
153 class={styles().hookDetails.fixtureTextarea}
154 value={output()}
155 onInput={(event) => setOutput(event.currentTarget.value)}
156 spellcheck={false}
157 />
158 </label>
159
160 <Show when={error()}>
161 {(message) => (
162 <div class={styles().hookDetails.fixtureError}>{message()}</div>
163 )}
164 </Show>
165
166 <div class={styles().hookDetails.fixtureActions}>
167 <button
168 class={styles().hookDetails.fixtureButton}
169 data-testid="ai-devtools-tool-fire"
170 type="button"
171 onClick={handleFire}
172 >
173 Fire
174 </button>
175 <button
176 class={`${styles().hookDetails.fixtureButton} ${styles().hookDetails.fixtureButtonSecondary}`}
177 data-testid="ai-devtools-tool-save"
178 type="button"
179 onClick={handleSave}
180 >
181 Save
182 </button>
183 </div>
184 <Show when={pendingSaveName()}>
185 {(defaultName) => (
186 <FixtureNamePopover
187 defaultName={defaultName()}
188 onCancel={() => setPendingSaveName(null)}
189 onSave={handleConfirmSave}
190 />
191 )}
192 </Show>
193 </div>
194 )
195}
196
197const FieldInput: Component<{
198 field: SchemaField
199 value: string
200 onInput: (value: string) => void
201}> = (props) => {
202 const styles = useStyles()
203
204 if (props.field.type === 'boolean') {
205 return (
206 <select
207 class={styles().hookDetails.fixtureInput}
208 value={props.value}
209 onInput={(event) => props.onInput(event.currentTarget.value)}
210 >
211 <option value="false">false</option>
212 <option value="true">true</option>
213 </select>
214 )
215 }
216
217 if (props.field.type === 'object' || props.field.type === 'array') {
218 return (
219 <textarea
220 class={styles().hookDetails.fixtureTextarea}
221 value={props.value}
222 onInput={(event) => props.onInput(event.currentTarget.value)}
223 spellcheck={false}
224 />
225 )
226 }
227
228 return (
229 <input
230 class={styles().hookDetails.fixtureInput}
231 type={props.field.type === 'string' ? 'text' : 'number'}
232 value={props.value}
233 onInput={(event) => props.onInput(event.currentTarget.value)}
234 />
235 )
236}
237
238function fieldsFromSchema(schema: unknown): Array<SchemaField> {
239 if (!isJsonSchemaObject(schema)) return []
240 const properties = schema.properties
241 if (!isRecord(properties)) return []
242 const required = Array.isArray(schema.required)
243 ? new Set(
244 schema.required.filter(
245 (item): item is string => typeof item === 'string',
246 ),
247 )
248 : new Set<string>()
249
250 return Object.entries(properties).map(([name, property]) => {
251 const propertySchema = isJsonSchemaObject(property) ? property : undefined
252 const type = normalizeType(propertySchema?.type)
253 return {
254 name,
255 type,
256 required: required.has(name),
257 ...(typeof propertySchema?.description === 'string'
258 ? { description: propertySchema.description }
259 : {}),
260 }
261 })
262}
263
264function defaultValues(fields: Array<SchemaField>): Record<string, string> {
265 const values: Record<string, string> = {}
266 for (const field of fields) {
267 if (field.type === 'boolean') {
268 values[field.name] = 'false'
269 } else if (field.type === 'number' || field.type === 'integer') {
270 values[field.name] = '0'
271 } else if (field.type === 'array') {
272 values[field.name] = '[]'
273 } else if (field.type === 'object') {
274 values[field.name] = '{}'
275 } else {
276 values[field.name] = ''
277 }
278 }
279 return values
280}
281
282function parseObjectInput(
283 fields: Array<SchemaField>,
284 values: Record<string, string>,
285): Record<string, unknown> {
286 const input: Record<string, unknown> = {}
287 for (const field of fields) {
288 const rawValue = values[field.name] ?? ''
289 if (!field.required && rawValue.length === 0) {
290 continue
291 }
292 input[field.name] = parseFieldValue(field, rawValue)
293 }
294 return input
295}
296
297function parseFieldValue(field: SchemaField, rawValue: string): unknown {
298 if (field.type === 'boolean') return rawValue === 'true'
299 if (field.type === 'number') {
300 const value = Number(rawValue)
301 if (!Number.isFinite(value)) {
302 throw new Error(`${field.name} must be a number.`)
303 }
304 return value
305 }
306 if (field.type === 'integer') {
307 const value = Number(rawValue)
308 if (!Number.isInteger(value)) {
309 throw new Error(`${field.name} must be an integer.`)
310 }
311 return value
312 }
313 if (field.type === 'object' || field.type === 'array') {
314 return parseJson(rawValue, field.name)
315 }
316 return rawValue
317}
318
319function parseJson(value: string, label: string): unknown {
320 try {
321 return JSON.parse(value)
322 } catch {
323 throw new Error(`${label} must be valid JSON.`)
324 }
325}
326
327function normalizeType(value: unknown): SchemaField['type'] {
328 if (value === 'boolean') return 'boolean'
329 if (value === 'number') return 'number'
330 if (value === 'integer') return 'integer'
331 if (value === 'array') return 'array'
332 if (value === 'object') return 'object'
333 return 'string'
334}
335
336function isJsonSchemaObject(value: unknown): value is {
337 type?: unknown
338 description?: unknown
339 properties?: unknown
340 required?: unknown
341} {
342 return isRecord(value)
343}
344
345function isRecord(value: unknown): value is Record<string, unknown> {
346 return typeof value === 'object' && value !== null
347}