yaver-feedback-react-native 0.8.12 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,581 @@
1
+ // VibeChatScreen — the converged chat UI for the standalone feedback
2
+ // SDK. Mirrors Yaver mobile's Tasks tab + the in-Yaver native pane:
3
+ //
4
+ // 1. User sees a live SSE transcript of agent stdout (PhaseStatusLine
5
+ // style "searching… / compiling…" while running, full markdown
6
+ // output once it lands).
7
+ // 2. User can keep vibing — type a follow-up after the first turn
8
+ // lands and POST a /tasks/{id}/resume to multi-turn the same
9
+ // coding session.
10
+ // 3. Reload button at the bottom hits client.reloadApp() so the user
11
+ // can see the change without leaving the chat.
12
+ //
13
+ // State machine:
14
+ // idle — empty, waiting for first prompt (handled by parent screen)
15
+ // running — task is live, transcript streams, follow-up disabled
16
+ // done — task finished, follow-up enabled, Reload prominent
17
+ // failed — same as done but error tinted
18
+
19
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
20
+ import {
21
+ ActivityIndicator,
22
+ ScrollView,
23
+ StyleSheet,
24
+ Text,
25
+ TextInput,
26
+ TouchableOpacity,
27
+ View,
28
+ } from 'react-native';
29
+ import type { P2PClient } from './P2PClient';
30
+ import { SDKVoiceSession, pcmToTempWavURI, isVoiceStreamSupported } from './voice';
31
+ import { startPcmRecording, stopPcmRecording, isVoiceCaptureSupported } from './capture';
32
+
33
+ export type VibeTurnRole = 'user' | 'assistant' | 'status';
34
+
35
+ type VoiceState = 'idle' | 'recording' | 'uploading' | 'thinking' | 'speaking';
36
+
37
+ export interface VibeTurn {
38
+ id: string;
39
+ role: VibeTurnRole;
40
+ text: string;
41
+ timestamp: number;
42
+ }
43
+
44
+ interface Props {
45
+ client: P2PClient;
46
+ initialTaskId: string;
47
+ initialUserPrompt: string;
48
+ onClose?: () => void;
49
+ /** Called when the user taps Reload after a task completes — uses
50
+ * P2PClient.reloadApp() with the active project context. */
51
+ onReload?: () => Promise<void>;
52
+ /** Optional context forwarded to the voice stream so the agent runs
53
+ * the task against the right project / runner / model. */
54
+ project?: string;
55
+ model?: string;
56
+ runner?: string;
57
+ }
58
+
59
+ export function VibeChatScreen({
60
+ client,
61
+ initialTaskId,
62
+ initialUserPrompt,
63
+ onClose,
64
+ onReload,
65
+ project,
66
+ model,
67
+ runner,
68
+ }: Props) {
69
+ const [taskId, setTaskId] = useState(initialTaskId);
70
+ const [turns, setTurns] = useState<VibeTurn[]>(() => [
71
+ {
72
+ id: `user-${Date.now()}`,
73
+ role: 'user',
74
+ text: initialUserPrompt,
75
+ timestamp: Date.now(),
76
+ },
77
+ {
78
+ id: `status-${Date.now()}`,
79
+ role: 'status',
80
+ text: 'starting…',
81
+ timestamp: Date.now(),
82
+ },
83
+ ]);
84
+ const [streamBuffer, setStreamBuffer] = useState('');
85
+ const [status, setStatus] = useState<'running' | 'done' | 'failed'>('running');
86
+ const [followUp, setFollowUp] = useState('');
87
+ const [isResuming, setIsResuming] = useState(false);
88
+ const [isReloading, setIsReloading] = useState(false);
89
+ const scrollRef = useRef<ScrollView | null>(null);
90
+ const abortRef = useRef<(() => void) | null>(null);
91
+
92
+ // ── Voice vibe coding ──────────────────────────────────────────────
93
+ const [voiceState, setVoiceState] = useState<VoiceState>('idle');
94
+ const [voiceAvailable, setVoiceAvailable] = useState(false);
95
+ // "local" = whisper.cpp on the host (free, private); "flux" = Deepgram
96
+ // nova-3 streaming. fluxAvailable gates the toggle on whether the agent
97
+ // has a Deepgram key. activeEngine is echoed back by the agent.
98
+ const [voiceMode, setVoiceMode] = useState<'local' | 'flux'>('local');
99
+ const [fluxAvailable, setFluxAvailable] = useState(false);
100
+ const [activeEngine, setActiveEngine] = useState<string>('');
101
+ const voiceSessionRef = useRef<SDKVoiceSession | null>(null);
102
+
103
+ // Subscribe to the current task's SSE stream. Re-runs whenever the
104
+ // taskId changes (resumeTask reuses the same id, so this only fires
105
+ // once per task — which is fine).
106
+ useEffect(() => {
107
+ let live = true;
108
+ const acc: string[] = [];
109
+ const close = client.streamTaskOutput(
110
+ taskId,
111
+ (line) => {
112
+ if (!live) return;
113
+ // Filter our internal error sentinel from the SSE helper.
114
+ if (line.startsWith('__error__:')) {
115
+ setStatus('failed');
116
+ setStreamBuffer((prev) => prev + (prev ? '\n' : '') + line.slice('__error__:'.length).trim());
117
+ return;
118
+ }
119
+ acc.push(line);
120
+ // Throttle re-renders: flush every ~100ms.
121
+ setStreamBuffer(acc.join('\n'));
122
+ },
123
+ (terminal) => {
124
+ if (!live) return;
125
+ setStatus(terminal === 'completed' ? 'done' : 'failed');
126
+ // Move the buffered stream into a real assistant turn so the
127
+ // user sees a stable render and can scroll back, then clear
128
+ // the buffer for any follow-up.
129
+ setTurns((prev) => {
130
+ const collapsed = acc.join('\n').trim();
131
+ if (!collapsed) return prev.filter((t) => t.role !== 'status');
132
+ const next = prev.filter((t) => t.role !== 'status');
133
+ next.push({
134
+ id: `assistant-${taskId}-${Date.now()}`,
135
+ role: 'assistant',
136
+ text: collapsed,
137
+ timestamp: Date.now(),
138
+ });
139
+ return next;
140
+ });
141
+ setStreamBuffer('');
142
+ },
143
+ );
144
+ abortRef.current = close;
145
+ return () => {
146
+ live = false;
147
+ try { close(); } catch { /* ignore */ }
148
+ };
149
+ }, [client, taskId]);
150
+
151
+ // Auto-scroll the transcript when new content lands.
152
+ useEffect(() => {
153
+ const t = setTimeout(() => {
154
+ scrollRef.current?.scrollToEnd({ animated: true });
155
+ }, 50);
156
+ return () => clearTimeout(t);
157
+ }, [streamBuffer, turns]);
158
+
159
+ const handleSendFollowUp = useCallback(async () => {
160
+ const text = followUp.trim();
161
+ if (!text || isResuming) return;
162
+ setIsResuming(true);
163
+ // Add user turn immediately for snappy UX.
164
+ setTurns((prev) => [
165
+ ...prev,
166
+ { id: `user-${Date.now()}`, role: 'user', text, timestamp: Date.now() },
167
+ { id: `status-${Date.now()}`, role: 'status', text: 'thinking…', timestamp: Date.now() },
168
+ ]);
169
+ setFollowUp('');
170
+ setStatus('running');
171
+ setStreamBuffer('');
172
+ try {
173
+ await client.resumeTask({ taskId, userPrompt: text });
174
+ // resumeTask reuses the same taskId, so the SSE subscription
175
+ // above will pick up the new output stream automatically. To
176
+ // force a fresh subscription we momentarily flip taskId to a
177
+ // sentinel and back; cleaner than tearing down + re-attaching
178
+ // the SSE manually.
179
+ const same = taskId;
180
+ setTaskId(`${same}#`);
181
+ setTimeout(() => setTaskId(same), 0);
182
+ } catch (e) {
183
+ setStatus('failed');
184
+ setTurns((prev) => [
185
+ ...prev.filter((t) => t.role !== 'status'),
186
+ {
187
+ id: `assistant-err-${Date.now()}`,
188
+ role: 'assistant',
189
+ text: `Failed to send follow-up: ${e instanceof Error ? e.message : String(e)}`,
190
+ timestamp: Date.now(),
191
+ },
192
+ ]);
193
+ } finally {
194
+ setIsResuming(false);
195
+ }
196
+ }, [client, followUp, isResuming, taskId]);
197
+
198
+ const handleReload = useCallback(async () => {
199
+ if (isReloading || !onReload) return;
200
+ setIsReloading(true);
201
+ try {
202
+ await onReload();
203
+ } catch (e) {
204
+ setTurns((prev) => [
205
+ ...prev,
206
+ {
207
+ id: `assistant-reload-err-${Date.now()}`,
208
+ role: 'assistant',
209
+ text: `Reload failed: ${e instanceof Error ? e.message : String(e)}`,
210
+ timestamp: Date.now(),
211
+ },
212
+ ]);
213
+ } finally {
214
+ setIsReloading(false);
215
+ }
216
+ }, [isReloading, onReload]);
217
+
218
+ // Probe whether voice is usable: deps present (expo-av + expo-file-
219
+ // system + buffer) AND the agent reports STT/TTS ready. Hide the mic
220
+ // entirely otherwise so users never tap a dead button.
221
+ useEffect(() => {
222
+ let cancelled = false;
223
+ (async () => {
224
+ if (!isVoiceCaptureSupported() || !isVoiceStreamSupported()) return;
225
+ try {
226
+ const res = await fetch(`${client.agentBaseUrl}/voice/status`, { headers: client.voiceAuthHeaders() });
227
+ if (!res.ok) return;
228
+ const body = await res.json();
229
+ if (cancelled) return;
230
+ // Local whisper is always usable when voice is enabled; Flux needs
231
+ // a Deepgram key on the agent. Show the mic if either path works.
232
+ const localOk = !!body?.enabled;
233
+ const fluxOk = !!body?.enabled && !!body?.deepgramSet;
234
+ if (localOk || fluxOk) setVoiceAvailable(true);
235
+ setFluxAvailable(fluxOk);
236
+ if (!localOk && fluxOk) setVoiceMode('flux');
237
+ } catch { /* leave hidden */ }
238
+ })();
239
+ return () => { cancelled = true; };
240
+ }, [client]);
241
+
242
+ useEffect(() => () => { voiceSessionRef.current?.close(); }, []);
243
+
244
+ // Local TTS: the agent streams no audio for "local"/"device" engines,
245
+ // so the client speaks the result text with the device synthesizer.
246
+ // expo-speech is optional — if absent, the text is still shown.
247
+ const speakLocalText = useCallback((text: string) => {
248
+ if (!text) return;
249
+ try {
250
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
251
+ const Speech = require('expo-speech');
252
+ const headline = text.length > 280 ? `${text.slice(0, 280)} — see screen for the rest.` : text;
253
+ Speech.stop?.();
254
+ Speech.speak?.(headline);
255
+ } catch { /* expo-speech not installed — text remains visible */ }
256
+ }, []);
257
+
258
+ const playTTS = useCallback(async (pcm: Uint8Array, sampleRate: number) => {
259
+ try {
260
+ const wavUri = await pcmToTempWavURI(pcm, sampleRate);
261
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
262
+ const { Audio } = require('expo-av');
263
+ const { sound } = await Audio.Sound.createAsync({ uri: wavUri }, { shouldPlay: true });
264
+ sound.setOnPlaybackStatusUpdate((st: any) => {
265
+ if (st.didJustFinish) sound.unloadAsync().catch(() => {});
266
+ });
267
+ } catch { /* playback best-effort */ }
268
+ }, []);
269
+
270
+ const stopVoiceAndProcess = useCallback(async () => {
271
+ setVoiceState('uploading');
272
+ let uri: string | null = null;
273
+ try {
274
+ uri = await stopPcmRecording();
275
+ } catch (e) {
276
+ setVoiceState('idle');
277
+ setTurns((prev) => [...prev, { id: `status-verr-${Date.now()}`, role: 'status', text: `voice: ${e instanceof Error ? e.message : String(e)}`, timestamp: Date.now() }]);
278
+ return;
279
+ }
280
+ if (!uri) { setVoiceState('idle'); return; }
281
+
282
+ const useFlux = voiceMode === 'flux' && fluxAvailable;
283
+ const session = new SDKVoiceSession({
284
+ onProviders: (stt, tts) => setActiveEngine(stt === 'deepgram' ? 'Flux (Deepgram)' : stt === 'local' ? 'Local (whisper)' : stt),
285
+ onTranscriptPartial: (t) => {
286
+ setTurns((prev) => {
287
+ const next = prev.filter((x) => x.id !== 'voice-partial');
288
+ next.push({ id: 'voice-partial', role: 'status', text: `🎙 ${t}`, timestamp: Date.now() });
289
+ return next;
290
+ });
291
+ },
292
+ onTranscriptFinal: (t) => {
293
+ setVoiceState('thinking');
294
+ setTurns((prev) => [
295
+ ...prev.filter((x) => x.id !== 'voice-partial'),
296
+ { id: `user-voice-${Date.now()}`, role: 'user', text: t, timestamp: Date.now() },
297
+ { id: `status-${Date.now()}`, role: 'status', text: 'thinking…', timestamp: Date.now() },
298
+ ]);
299
+ },
300
+ onTaskCreated: (id) => {
301
+ // Hand the chat's SSE subscription the new task so its agent
302
+ // output streams into the transcript exactly like a typed turn.
303
+ if (id) { setStatus('running'); setStreamBuffer(''); setTaskId(id); }
304
+ },
305
+ onTaskResult: (_id, text) => {
306
+ setVoiceState('speaking');
307
+ // Local TTS path: agent sends no audio frames, so speak here.
308
+ if (!useFlux) speakLocalText(text);
309
+ },
310
+ onTTSReady: (pcm, sr) => { void playTTS(pcm, sr); },
311
+ onDone: () => setTimeout(() => setVoiceState('idle'), 1200),
312
+ onError: (msg) => {
313
+ setVoiceState('idle');
314
+ setTurns((prev) => [...prev.filter((x) => x.id !== 'voice-partial'), { id: `status-verr-${Date.now()}`, role: 'status', text: `voice: ${msg}`, timestamp: Date.now() }]);
315
+ },
316
+ });
317
+ voiceSessionRef.current = session;
318
+ try {
319
+ await session.start({
320
+ wsUrl: client.voiceStreamUrl(),
321
+ headers: client.voiceAuthHeaders(),
322
+ project,
323
+ model,
324
+ runner,
325
+ surface: 'feedback-sdk',
326
+ ttsBudget: 280,
327
+ // Local: whisper.cpp on the host + device synth. Flux: Deepgram
328
+ // nova-3 STT + Aura TTS streamed back as PCM.
329
+ sttProvider: useFlux ? 'deepgram' : 'local',
330
+ ttsProvider: useFlux ? 'deepgram' : 'local',
331
+ });
332
+ await session.streamAudioFile(uri, { skipWavHeader: true });
333
+ session.finalize();
334
+ } catch (e) {
335
+ setVoiceState('idle');
336
+ session.close();
337
+ setTurns((prev) => [...prev, { id: `status-verr-${Date.now()}`, role: 'status', text: `voice: ${e instanceof Error ? e.message : String(e)}`, timestamp: Date.now() }]);
338
+ }
339
+ }, [client, project, model, runner, playTTS, voiceMode, fluxAvailable, speakLocalText]);
340
+
341
+ const handleVoicePress = useCallback(async () => {
342
+ if (voiceState === 'recording') {
343
+ void stopVoiceAndProcess();
344
+ return;
345
+ }
346
+ if (voiceState !== 'idle') {
347
+ // Mid-flow tap cancels.
348
+ voiceSessionRef.current?.close();
349
+ voiceSessionRef.current = null;
350
+ setVoiceState('idle');
351
+ return;
352
+ }
353
+ try {
354
+ await startPcmRecording();
355
+ setVoiceState('recording');
356
+ } catch (e) {
357
+ setTurns((prev) => [...prev, { id: `status-verr-${Date.now()}`, role: 'status', text: `voice: ${e instanceof Error ? e.message : String(e)}`, timestamp: Date.now() }]);
358
+ }
359
+ }, [voiceState, stopVoiceAndProcess]);
360
+
361
+ const voiceLabel: Record<VoiceState, string> = {
362
+ idle: '🎙 speak',
363
+ recording: '■ stop',
364
+ uploading: 'sending…',
365
+ thinking: 'thinking…',
366
+ speaking: 'speaking…',
367
+ };
368
+
369
+ return (
370
+ <View style={styles.container}>
371
+ <View style={styles.header}>
372
+ <Text style={styles.title}>Vibe</Text>
373
+ {onClose && (
374
+ <TouchableOpacity onPress={onClose} accessibilityLabel="Close vibe chat">
375
+ <Text style={styles.close}>✕</Text>
376
+ </TouchableOpacity>
377
+ )}
378
+ </View>
379
+
380
+ <ScrollView
381
+ ref={scrollRef}
382
+ style={styles.transcript}
383
+ contentContainerStyle={styles.transcriptContent}
384
+ keyboardShouldPersistTaps="handled"
385
+ >
386
+ {turns.map((turn) => (
387
+ <View
388
+ key={turn.id}
389
+ style={[
390
+ styles.turn,
391
+ turn.role === 'user' && styles.turnUser,
392
+ turn.role === 'assistant' && styles.turnAssistant,
393
+ turn.role === 'status' && styles.turnStatus,
394
+ ]}
395
+ >
396
+ <Text style={styles.turnText}>{turn.text}</Text>
397
+ </View>
398
+ ))}
399
+ {/* Live streaming buffer rendered as a single trailing
400
+ assistant block while the task is running. Once the task
401
+ terminates the stream is moved into a real turn (above)
402
+ and this block clears. */}
403
+ {streamBuffer && status === 'running' && (
404
+ <View style={[styles.turn, styles.turnAssistant]}>
405
+ <Text style={styles.turnText}>{streamBuffer}</Text>
406
+ </View>
407
+ )}
408
+ {status === 'running' && (
409
+ <View style={styles.spinnerRow}>
410
+ <ActivityIndicator size="small" color="#9ca3af" />
411
+ <Text style={styles.spinnerText}>working…</Text>
412
+ </View>
413
+ )}
414
+ </ScrollView>
415
+
416
+ <View style={styles.footer}>
417
+ {voiceAvailable && voiceState !== 'idle' && (
418
+ <Text style={styles.engineCaption}>
419
+ {voiceState === 'recording' ? 'listening' : voiceState === 'uploading' ? 'sending' : voiceState === 'thinking' ? 'agent working' : 'speaking'}
420
+ {activeEngine ? ` · ${activeEngine}` : ` · ${voiceMode === 'flux' ? 'Flux (Deepgram)' : 'Local (whisper)'}`}
421
+ </Text>
422
+ )}
423
+ <TextInput
424
+ style={styles.input}
425
+ value={followUp}
426
+ onChangeText={setFollowUp}
427
+ placeholder={status === 'running' ? 'wait for the agent…' : 'follow up…'}
428
+ placeholderTextColor="#666"
429
+ editable={status !== 'running' && !isResuming}
430
+ multiline
431
+ />
432
+ <View style={styles.actions}>
433
+ {voiceAvailable && (
434
+ <>
435
+ {/* Local ↔ Flux engine toggle. Only shows Flux when the
436
+ agent has a Deepgram key; otherwise the label just
437
+ states "Local" so the active engine is always clear. */}
438
+ {fluxAvailable ? (
439
+ <TouchableOpacity
440
+ style={[styles.actionBtn, styles.engineToggle]}
441
+ onPress={() => setVoiceMode((m) => (m === 'local' ? 'flux' : 'local'))}
442
+ disabled={voiceState !== 'idle'}
443
+ accessibilityLabel="Toggle voice engine"
444
+ >
445
+ <Text style={styles.engineToggleText}>{voiceMode === 'flux' ? '⚡ Flux' : '🔒 Local'}</Text>
446
+ </TouchableOpacity>
447
+ ) : (
448
+ <View style={[styles.actionBtn, styles.engineToggle]}>
449
+ <Text style={styles.engineToggleText}>🔒 Local</Text>
450
+ </View>
451
+ )}
452
+ <TouchableOpacity
453
+ style={[
454
+ styles.actionBtn,
455
+ styles.voiceBtn,
456
+ voiceState === 'recording' && styles.voiceBtnActive,
457
+ (voiceState === 'uploading' || voiceState === 'thinking' || voiceState === 'speaking') && styles.actionBtnDisabled,
458
+ ]}
459
+ onPress={handleVoicePress}
460
+ disabled={voiceState === 'uploading' || voiceState === 'thinking' || voiceState === 'speaking'}
461
+ accessibilityLabel="Vibe code by voice"
462
+ >
463
+ <Text style={styles.actionText}>{voiceLabel[voiceState]}</Text>
464
+ </TouchableOpacity>
465
+ </>
466
+ )}
467
+ {onReload && (
468
+ <TouchableOpacity
469
+ style={[
470
+ styles.actionBtn,
471
+ styles.reloadBtn,
472
+ (isReloading || status === 'running') && styles.actionBtnDisabled,
473
+ ]}
474
+ onPress={handleReload}
475
+ disabled={isReloading || status === 'running'}
476
+ >
477
+ <Text style={styles.actionText}>
478
+ {isReloading ? 'reloading…' : '⟳ reload'}
479
+ </Text>
480
+ </TouchableOpacity>
481
+ )}
482
+ <TouchableOpacity
483
+ style={[
484
+ styles.actionBtn,
485
+ styles.sendBtn,
486
+ (isResuming || status === 'running' || !followUp.trim()) && styles.actionBtnDisabled,
487
+ ]}
488
+ onPress={handleSendFollowUp}
489
+ disabled={isResuming || status === 'running' || !followUp.trim()}
490
+ >
491
+ <Text style={styles.actionText}>
492
+ {isResuming ? '…' : '↑ send'}
493
+ </Text>
494
+ </TouchableOpacity>
495
+ </View>
496
+ </View>
497
+ </View>
498
+ );
499
+ }
500
+
501
+ const styles = StyleSheet.create({
502
+ container: { flex: 1, backgroundColor: '#0a0a0a' },
503
+ header: {
504
+ flexDirection: 'row',
505
+ alignItems: 'center',
506
+ justifyContent: 'space-between',
507
+ paddingHorizontal: 16,
508
+ paddingTop: 14,
509
+ paddingBottom: 8,
510
+ borderBottomWidth: 1,
511
+ borderBottomColor: 'rgba(255,255,255,0.08)',
512
+ },
513
+ title: { color: '#fff', fontSize: 17, fontWeight: '600' },
514
+ close: { color: '#9ca3af', fontSize: 18 },
515
+ transcript: { flex: 1 },
516
+ transcriptContent: { padding: 12, paddingBottom: 24 },
517
+ turn: {
518
+ marginVertical: 4,
519
+ padding: 10,
520
+ borderRadius: 12,
521
+ maxWidth: '92%',
522
+ },
523
+ turnUser: {
524
+ backgroundColor: '#7582f5',
525
+ alignSelf: 'flex-end',
526
+ },
527
+ turnAssistant: {
528
+ backgroundColor: 'rgba(255,255,255,0.06)',
529
+ borderColor: 'rgba(255,255,255,0.10)',
530
+ borderWidth: 1,
531
+ alignSelf: 'flex-start',
532
+ },
533
+ turnStatus: {
534
+ backgroundColor: 'transparent',
535
+ alignSelf: 'flex-start',
536
+ paddingHorizontal: 4,
537
+ },
538
+ turnText: { color: '#f1f5f9', fontSize: 14, lineHeight: 20 },
539
+ spinnerRow: {
540
+ flexDirection: 'row',
541
+ alignItems: 'center',
542
+ marginTop: 8,
543
+ paddingHorizontal: 4,
544
+ },
545
+ spinnerText: { color: '#9ca3af', fontSize: 12, marginLeft: 8 },
546
+ footer: {
547
+ borderTopWidth: 1,
548
+ borderTopColor: 'rgba(255,255,255,0.08)',
549
+ padding: 10,
550
+ },
551
+ input: {
552
+ minHeight: 40,
553
+ maxHeight: 120,
554
+ color: '#f1f5f9',
555
+ fontSize: 14,
556
+ backgroundColor: 'rgba(255,255,255,0.04)',
557
+ borderRadius: 10,
558
+ paddingHorizontal: 12,
559
+ paddingVertical: 8,
560
+ },
561
+ actions: {
562
+ flexDirection: 'row',
563
+ justifyContent: 'flex-end',
564
+ marginTop: 8,
565
+ },
566
+ actionBtn: {
567
+ paddingHorizontal: 14,
568
+ paddingVertical: 8,
569
+ borderRadius: 10,
570
+ marginLeft: 8,
571
+ },
572
+ actionBtnDisabled: { opacity: 0.5 },
573
+ reloadBtn: { backgroundColor: 'rgba(255,255,255,0.08)' },
574
+ voiceBtn: { backgroundColor: 'rgba(16,185,129,0.18)' },
575
+ voiceBtnActive: { backgroundColor: '#ef4444' },
576
+ engineToggle: { backgroundColor: 'rgba(255,255,255,0.06)', marginRight: 'auto', marginLeft: 0 },
577
+ engineToggleText: { color: '#cbd5e1', fontSize: 12, fontWeight: '600' },
578
+ engineCaption: { color: '#9ca3af', fontSize: 11, marginBottom: 6, marginLeft: 4 },
579
+ sendBtn: { backgroundColor: '#7582f5' },
580
+ actionText: { color: '#fff', fontSize: 13, fontWeight: '600' },
581
+ });
@@ -0,0 +1,102 @@
1
+ // buildFeedbackPrompt — shared prompt enrichment used by every Yaver
2
+ // feedback surface, in-Yaver native pane (mirrored in Swift + Kotlin)
3
+ // AND the standalone RN feedback SDK (this file). Keep all three
4
+ // implementations in lockstep — the wording is what the AI on the
5
+ // remote is conditioned to expect.
6
+ //
7
+ // The bare user text on its own loses crucial context: WHICH app the
8
+ // user is testing, WHICH screen they're looking at, and whether a
9
+ // screenshot is attached for visual reference. Without that the agent
10
+ // guesses, edits the wrong project, or asks clarifying questions
11
+ // instead of acting. The wrapper below tells the agent:
12
+ // - this feedback comes from the in-app drawer while the user is
13
+ // mid-test,
14
+ // - which project the user is in (when known),
15
+ // - that the FIRST attached image (when present) is a snapshot of
16
+ // the current screen — open it to see what the user is pointing
17
+ // at,
18
+ // - that changes should be applied to that project's source +
19
+ // saved so the user can trigger a Hermes reload to see them.
20
+ //
21
+ // Cross-reference: mobile/ios/Yaver/YaverFeedbackPane.swift's
22
+ // `buildFeedbackPrompt` and mobile/android/.../YaverFeedbackPane.kt's
23
+ // `buildFeedbackPrompt`. All three must match.
24
+
25
+ export interface BuildFeedbackPromptInput {
26
+ userPrompt: string;
27
+ /** Hot-Reload project name when running inside Yaver mobile, OR
28
+ * the host app's bundle/package name when running standalone. */
29
+ projectName?: string;
30
+ /** Absolute path on the host where the project lives (only known
31
+ * when running inside Yaver mobile via Hot Reload). */
32
+ projectPath?: string;
33
+ /** True when the caller has attached a screenshot of the current
34
+ * screen as the first image in the task's images array. */
35
+ hasScreenshot: boolean;
36
+ }
37
+
38
+ export function buildFeedbackPrompt(input: BuildFeedbackPromptInput): string {
39
+ const userPrompt = input.userPrompt ?? "";
40
+ const projectName = (input.projectName ?? "").trim();
41
+ const projectPath = (input.projectPath ?? "").trim();
42
+ const hasScreenshot = !!input.hasScreenshot;
43
+
44
+ const lines: string[] = [];
45
+ lines.push("[Mobile feedback from inside Yaver]");
46
+ lines.push(
47
+ "The user is providing this feedback while running a mobile app inside the Yaver mobile container " +
48
+ "and is currently looking at a specific screen of that app."
49
+ );
50
+ lines.push("");
51
+ if (projectName || projectPath) {
52
+ lines.push("App being tested:");
53
+ if (projectName) lines.push(` name: ${projectName}`);
54
+ if (projectPath) lines.push(` path: ${projectPath}`);
55
+ lines.push("");
56
+ }
57
+ if (hasScreenshot) {
58
+ lines.push(
59
+ "A screenshot of the current screen is attached as the first image. " +
60
+ "Open it before deciding what to change — the user is pointing at what they SEE, " +
61
+ "not necessarily what is named most prominently in the source."
62
+ );
63
+ lines.push("");
64
+ } else {
65
+ lines.push("(The user chose not to attach a screenshot for this round.)");
66
+ lines.push("");
67
+ }
68
+ lines.push("Operation contract:");
69
+ lines.push(
70
+ "1. Locate the file(s) responsible for what the user described and EDIT them in place. " +
71
+ "Save the changes — that is the deliverable."
72
+ );
73
+ lines.push(
74
+ "2. Stream a CONCISE Claude-Code / Codex-style narration as you work: " +
75
+ "one short line per step (e.g. \"Reading app/index.tsx\", " +
76
+ "\"Editing safe.backgroundColor\", \"Saved app/index.tsx\"). Show small diffs only — " +
77
+ "never dump entire files, never paste node_modules contents, never echo build / install logs."
78
+ );
79
+ lines.push(
80
+ "3. Do NOT run npm install / yarn / pnpm / git clone / cargo build / docker pull or any other " +
81
+ "long-running install / fetch command. The repo is already prepared on this machine. " +
82
+ "If a dependency is genuinely missing, say so in one line and stop — the user will install it."
83
+ );
84
+ lines.push(
85
+ "4. Do NOT trigger a Hermes reload yourself. The user has a Reload button in the drawer " +
86
+ "and decides when to refresh."
87
+ );
88
+ lines.push(
89
+ "5. Keep total output under a few hundred lines. Heavy ripgrep / find / cat with no filter " +
90
+ "are usually the wrong tool — use targeted reads."
91
+ );
92
+ if (!projectName && !projectPath) {
93
+ lines.push(
94
+ "6. If you can identify the project from the prompt or the screenshot, work there. " +
95
+ "Otherwise ask the user briefly which project to target — one short line, no exhaustive list."
96
+ );
97
+ }
98
+ lines.push("");
99
+ lines.push("User feedback:");
100
+ lines.push(userPrompt);
101
+ return lines.join("\n");
102
+ }