-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathAskUserQuestionView.tsx
More file actions
562 lines (528 loc) · 21.7 KB
/
AskUserQuestionView.tsx
File metadata and controls
562 lines (528 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import * as React from 'react';
import { View, TouchableOpacity, ActivityIndicator, TextInput } from 'react-native';
import { StyleSheet, useUnistyles } from 'react-native-unistyles';
import { ToolViewProps } from '../core/_registry';
import { ToolSectionView } from '../../shell/presentation/ToolSectionView';
import { sessionAllowWithAnswers, sessionDeny } from '@/sync/ops';
import { storage } from '@/sync/domains/state/storage';
import { sync } from '@/sync/sync';
import { Modal } from '@/modal';
import { t } from '@/text';
import { Ionicons } from '@expo/vector-icons';
import { Text } from '@/components/ui/text/Text';
interface QuestionOption {
label: string;
description: string;
}
interface Question {
question: string;
header: string;
options: QuestionOption[];
multiSelect: boolean;
freeform?: {
placeholder?: string;
description?: string;
};
}
interface AskUserQuestionInput {
questions: Question[];
}
function parseAskUserQuestionAnswersFromToolResult(result: unknown): Record<string, string> | null {
if (!result || typeof result !== 'object') return null;
const maybeAnswers = (result as any).answers;
if (!maybeAnswers || typeof maybeAnswers !== 'object' || Array.isArray(maybeAnswers)) return null;
const answers: Record<string, string> = {};
for (const [key, value] of Object.entries(maybeAnswers as Record<string, unknown>)) {
if (typeof value === 'string') {
answers[key] = value;
}
}
return answers;
}
// Styles MUST be defined outside the component to prevent infinite re-renders
// with react-native-unistyles. The theme is passed as a function parameter.
const styles = StyleSheet.create((theme) => ({
container: {
gap: 16,
},
questionSection: {
gap: 8,
},
headerChip: {
alignSelf: 'flex-start',
backgroundColor: theme.colors.surfaceHighest,
paddingHorizontal: 8,
paddingVertical: 4,
borderRadius: 4,
marginBottom: 4,
},
headerText: {
fontSize: 12,
fontWeight: '600',
color: theme.colors.textSecondary,
textTransform: 'uppercase',
},
questionText: {
fontSize: 15,
fontWeight: '500',
color: theme.colors.text,
marginBottom: 8,
},
optionsContainer: {
gap: 4,
},
optionButton: {
flexDirection: 'row',
alignItems: 'flex-start',
paddingVertical: 12,
paddingHorizontal: 12,
borderRadius: 8,
backgroundColor: 'transparent',
borderWidth: 1,
borderColor: theme.colors.divider,
gap: 10,
minHeight: 44, // Minimum touch target for mobile
},
optionButtonSelected: {
backgroundColor: theme.colors.surfaceHigh,
borderColor: theme.colors.radio.active,
},
optionButtonDisabled: {
opacity: 0.6,
},
radioOuter: {
width: 20,
height: 20,
borderRadius: 10,
borderWidth: 2,
borderColor: theme.colors.textSecondary,
alignItems: 'center',
justifyContent: 'center',
marginTop: 2,
},
radioOuterSelected: {
borderColor: theme.colors.radio.active,
},
radioInner: {
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: theme.colors.radio.dot,
},
checkboxOuter: {
width: 20,
height: 20,
borderRadius: 4,
borderWidth: 2,
borderColor: theme.colors.textSecondary,
alignItems: 'center',
justifyContent: 'center',
marginTop: 2,
},
checkboxOuterSelected: {
borderColor: theme.colors.radio.active,
backgroundColor: theme.colors.radio.active,
},
optionContent: {
flex: 1,
},
optionLabel: {
fontSize: 14,
fontWeight: '500',
color: theme.colors.text,
},
optionDescription: {
fontSize: 13,
color: theme.colors.textSecondary,
marginTop: 2,
},
freeformInput: {
borderWidth: 1,
borderColor: theme.colors.divider,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 12,
fontSize: 14,
color: theme.colors.text,
backgroundColor: theme.colors.surface,
minHeight: 44,
},
freeformDescription: {
fontSize: 13,
color: theme.colors.textSecondary,
marginTop: 6,
marginLeft: 2,
},
actionsContainer: {
flexDirection: 'row',
gap: 12,
marginTop: 8,
justifyContent: 'flex-end',
},
submitButton: {
backgroundColor: theme.colors.button.primary.background,
paddingHorizontal: 20,
paddingVertical: 12,
borderRadius: 8,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
minHeight: 44, // Minimum touch target for mobile
},
submitButtonDisabled: {
opacity: 0.5,
},
submitButtonText: {
color: theme.colors.button.primary.tint,
fontSize: 14,
fontWeight: '600',
},
submittedContainer: {
gap: 8,
},
submittedItem: {
flexDirection: 'row',
gap: 8,
},
submittedHeader: {
fontSize: 13,
fontWeight: '600',
color: theme.colors.textSecondary,
},
submittedValue: {
fontSize: 13,
color: theme.colors.text,
flex: 1,
},
tabBar: {
flexDirection: 'row',
gap: 2,
borderBottomWidth: 1,
borderBottomColor: theme.colors.divider,
},
tab: {
flexDirection: 'row',
alignItems: 'center',
gap: 4,
paddingHorizontal: 12,
paddingVertical: 8,
borderBottomWidth: 2,
borderBottomColor: 'transparent',
},
tabActive: {
borderBottomColor: theme.colors.button.primary.background,
},
tabText: {
fontSize: 13,
fontWeight: '500',
color: theme.colors.textSecondary,
},
tabTextActive: {
color: theme.colors.text,
fontWeight: '600',
},
}));
export const AskUserQuestionView = React.memo<ToolViewProps>(({ tool, sessionId, interaction }) => {
const { theme } = useUnistyles();
const [selections, setSelections] = React.useState<Map<number, Set<number>>>(new Map());
const [freeformAnswers, setFreeformAnswers] = React.useState<Map<number, string>>(new Map());
const [isSubmitting, setIsSubmitting] = React.useState(false);
const [isSubmitted, setIsSubmitted] = React.useState(false);
const [activeTab, setActiveTab] = React.useState(0);
// Parse input
const input = tool.input as AskUserQuestionInput | undefined;
const questions = input?.questions;
if (!questions || !Array.isArray(questions) || questions.length === 0) {
return null;
}
const isRunning = tool.state === 'running';
const canApprovePermissions = interaction?.canApprovePermissions ?? true;
const canInteract = isRunning && !isSubmitted && canApprovePermissions;
const disabledMessage =
interaction?.permissionDisabledReason === 'public'
? t('session.sharing.permissionApprovalsDisabledPublic')
: interaction?.permissionDisabledReason === 'readOnly'
? t('session.sharing.permissionApprovalsDisabledReadOnly')
: t('session.sharing.permissionApprovalsDisabledNotGranted');
const showTabs = questions.length > 1;
// Check if all questions have at least one selection
const allQuestionsAnswered = questions.every((_, qIndex) => {
const q = questions[qIndex];
const options = Array.isArray(q?.options) ? q.options : [];
if (options.length === 0) {
const value = freeformAnswers.get(qIndex);
return typeof value === 'string' && value.trim().length > 0;
}
const selected = selections.get(qIndex);
return Boolean(selected && selected.size > 0);
});
// Helper: check if a specific question is answered
const isQuestionAnswered = React.useCallback((qIndex: number): boolean => {
const q = questions[qIndex];
const options = Array.isArray(q?.options) ? q.options : [];
if (options.length === 0) {
const value = freeformAnswers.get(qIndex);
return typeof value === 'string' && value.trim().length > 0;
}
const selected = selections.get(qIndex);
return Boolean(selected && selected.size > 0);
}, [questions, selections, freeformAnswers]);
const handleOptionToggle = React.useCallback((questionIndex: number, optionIndex: number, multiSelect: boolean) => {
if (!canInteract) return;
setSelections(prev => {
const newMap = new Map(prev);
const currentSet = newMap.get(questionIndex) || new Set();
if (multiSelect) {
// Toggle for multi-select
const newSet = new Set(currentSet);
if (newSet.has(optionIndex)) {
newSet.delete(optionIndex);
} else {
newSet.add(optionIndex);
}
newMap.set(questionIndex, newSet);
} else {
// Replace for single-select
newMap.set(questionIndex, new Set([optionIndex]));
}
return newMap;
});
}, [canInteract]);
const handleSubmit = React.useCallback(async () => {
if (!sessionId || !allQuestionsAnswered || isSubmitting) return;
setIsSubmitting(true);
// HACK: Disable the form immediately by switching to the submitted view.
// Without this, users could edit their selections while the network calls
// are in flight, but those edits would be ignored since we've already
// captured the values above. TODO: Revisit this logic.
setIsSubmitted(true);
// Format answers as readable text
const responseLines: string[] = [];
const answers: Record<string, string> = {};
questions.forEach((q, qIndex) => {
const questionKey = typeof q.question === 'string' && q.question.trim().length > 0 ? q.question : q.header;
const options = Array.isArray(q.options) ? q.options : [];
if (options.length === 0) {
const typed = freeformAnswers.get(qIndex);
const typedText = typeof typed === 'string' ? typed.trim() : '';
if (typedText.length > 0) {
responseLines.push(`${q.header}: ${typedText}`);
answers[questionKey] = typedText;
}
return;
}
const selected = selections.get(qIndex);
if (selected && selected.size > 0) {
const selectedLabelsArray = Array.from(selected)
.map(optIndex => options[optIndex]?.label)
.filter(Boolean);
const selectedLabelsText = selectedLabelsArray.join(', ');
responseLines.push(`${q.header}: ${selectedLabelsText}`);
answers[questionKey] = selectedLabelsText;
}
});
const responseText = responseLines.join('\n');
try {
const toolCallId = tool.permission?.id;
if (!toolCallId) {
Modal.alert(t('common.error'), t('errors.missingPermissionId'));
return;
}
const session = storage.getState().sessions[sessionId];
const supportsAnswersInPermission = Boolean(
(session as any)?.agentState?.capabilities?.askUserQuestionAnswersInPermission,
);
if (supportsAnswersInPermission) {
// Preferred: attach answers directly to the existing permission approval RPC.
// This matches how Claude Code expects AskUserQuestion to be completed.
await sessionAllowWithAnswers(sessionId, toolCallId, answers);
} else {
// Back-compat: older agents won't understand answers-on-permission. Abort the tool call and
// send a normal user message so the agent can continue using the same information.
await sessionDeny(sessionId, toolCallId);
await sync.sendMessage(sessionId, responseText);
}
setIsSubmitted(true);
} catch (error) {
Modal.alert(t('common.error'), error instanceof Error ? error.message : t('errors.failedToSendMessage'));
} finally {
setIsSubmitting(false);
}
}, [sessionId, questions, selections, freeformAnswers, allQuestionsAnswered, isSubmitting, tool.permission?.id]);
// Show submitted state
if (isSubmitted || tool.state === 'completed') {
const answersFromResult = parseAskUserQuestionAnswersFromToolResult(tool.result);
return (
<ToolSectionView>
<View style={styles.submittedContainer}>
{questions.map((q, qIndex) => {
const selected = selections.get(qIndex);
const questionKey = typeof q.question === 'string' && q.question.trim().length > 0 ? q.question : q.header;
const options = Array.isArray(q.options) ? q.options : [];
const freeform = freeformAnswers.get(qIndex);
const selectedLabels =
options.length === 0
? ((typeof freeform === 'string' && freeform.trim().length > 0)
? freeform.trim()
: (answersFromResult?.[questionKey] ?? '-'))
: (selected && selected.size > 0
? Array.from(selected)
.map(optIndex => options[optIndex]?.label)
.filter(Boolean)
.join(', ')
: (answersFromResult?.[questionKey] ?? '-'));
return (
<View key={qIndex} style={styles.submittedItem}>
<Text style={styles.submittedHeader}>{q.header}:</Text>
<Text style={styles.submittedValue}>{selectedLabels}</Text>
</View>
);
})}
</View>
</ToolSectionView>
);
}
const renderQuestionContent = (question: Question, qIndex: number) => {
const selectedOptions = selections.get(qIndex) || new Set();
const options = Array.isArray(question.options) ? question.options : [];
return (
<View key={qIndex} style={styles.questionSection}>
{!showTabs && (
<View style={styles.headerChip}>
<Text style={styles.headerText}>{question.header}</Text>
</View>
)}
<Text style={styles.questionText}>{question.question}</Text>
<View style={styles.optionsContainer}>
{options.length === 0 ? (
<View>
<TextInput
style={styles.freeformInput}
value={freeformAnswers.get(qIndex) ?? ''}
onChangeText={(text) => {
if (!canInteract) return;
setFreeformAnswers((prev) => {
const next = new Map(prev);
next.set(qIndex, text);
return next;
});
}}
placeholder={question.freeform?.placeholder ?? t('tools.askUserQuestion.otherPlaceholder')}
placeholderTextColor={theme.colors.textSecondary}
editable={canInteract}
autoCapitalize="none"
autoCorrect={false}
/>
{question.freeform?.description ? (
<Text style={styles.freeformDescription}>{question.freeform.description}</Text>
) : null}
</View>
) : null}
{options.map((option, oIndex) => {
const isSelected = selectedOptions.has(oIndex);
return (
<TouchableOpacity
key={oIndex}
style={[
styles.optionButton,
isSelected && styles.optionButtonSelected,
!canInteract && styles.optionButtonDisabled,
]}
onPress={() => handleOptionToggle(qIndex, oIndex, question.multiSelect)}
disabled={!canInteract}
activeOpacity={0.7}
>
{question.multiSelect ? (
<View style={[
styles.checkboxOuter,
isSelected && styles.checkboxOuterSelected,
]}>
{isSelected && (
<Ionicons name="checkmark" size={14} color={theme.colors.button.primary.tint} />
)}
</View>
) : (
<View style={[
styles.radioOuter,
isSelected && styles.radioOuterSelected,
]}>
{isSelected && <View style={styles.radioInner} />}
</View>
)}
<View style={styles.optionContent}>
<Text style={styles.optionLabel}>{option.label}</Text>
{option.description && (
<Text style={styles.optionDescription}>{option.description}</Text>
)}
</View>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
return (
<ToolSectionView>
<View style={styles.container}>
{!canApprovePermissions && isRunning ? (
<Text style={{ color: theme.colors.textSecondary }}>
{disabledMessage}
</Text>
) : null}
{showTabs ? (
<>
<View style={styles.tabBar}>
{questions.map((q, qIndex) => {
const isActive = qIndex === activeTab;
const answered = isQuestionAnswered(qIndex);
return (
<TouchableOpacity
key={qIndex}
style={[styles.tab, isActive && styles.tabActive]}
onPress={() => setActiveTab(qIndex)}
activeOpacity={0.7}
>
<Text style={[styles.tabText, isActive && styles.tabTextActive]}>
{q.header}
</Text>
{answered && (
<Ionicons
name="checkmark-circle"
size={14}
color={isActive ? theme.colors.button.primary.background : theme.colors.textSecondary}
/>
)}
</TouchableOpacity>
);
})}
</View>
{renderQuestionContent(questions[activeTab]!, activeTab)}
</>
) : (
renderQuestionContent(questions[0]!, 0)
)}
{canInteract && (
<View style={styles.actionsContainer}>
<TouchableOpacity
style={[
styles.submitButton,
(!allQuestionsAnswered || isSubmitting) && styles.submitButtonDisabled,
]}
onPress={handleSubmit}
disabled={!allQuestionsAnswered || isSubmitting}
activeOpacity={0.7}
>
{isSubmitting ? (
<ActivityIndicator size="small" color={theme.colors.button.primary.tint} />
) : (
<Text style={styles.submitButtonText}>{t('tools.askUserQuestion.submit')}</Text>
)}
</TouchableOpacity>
</View>
)}
</View>
</ToolSectionView>
);
});