forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamingMessage.tsx
More file actions
263 lines (238 loc) · 8.58 KB
/
StreamingMessage.tsx
File metadata and controls
263 lines (238 loc) · 8.58 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
'use client';
import { useState, useEffect, useRef } from 'react';
import {
Message as AIMessage,
MessageContent,
MessageResponse,
} from '@/components/ai-elements/message';
import { ToolActionsGroup } from '@/components/ai-elements/tool-actions-group';
import {
Confirmation,
ConfirmationTitle,
ConfirmationRequest,
ConfirmationAccepted,
ConfirmationRejected,
ConfirmationActions,
ConfirmationAction,
} from '@/components/ai-elements/confirmation';
import { Shimmer } from '@/components/ai-elements/shimmer';
import type { ToolUIPart } from 'ai';
import type { PermissionRequestEvent } from '@/types';
interface ToolUseInfo {
id: string;
name: string;
input: unknown;
}
interface ToolResultInfo {
tool_use_id: string;
content: string;
is_error?: boolean;
}
interface StreamingMessageProps {
content: string;
isStreaming: boolean;
toolUses?: ToolUseInfo[];
toolResults?: ToolResultInfo[];
streamingToolOutput?: string;
statusText?: string;
pendingPermission?: PermissionRequestEvent | null;
onPermissionResponse?: (decision: 'allow' | 'allow_session' | 'deny') => void;
permissionResolved?: 'allow' | 'deny' | null;
onForceStop?: () => void;
}
function ElapsedTimer() {
const [elapsed, setElapsed] = useState(0);
const startRef = useRef(0);
useEffect(() => {
startRef.current = Date.now();
const interval = setInterval(() => {
setElapsed(Math.floor((Date.now() - startRef.current) / 1000));
}, 1000);
return () => clearInterval(interval);
}, []);
const mins = Math.floor(elapsed / 60);
const secs = elapsed % 60;
return (
<span className="tabular-nums">
{mins > 0 ? `${mins}m ${secs}s` : `${secs}s`}
</span>
);
}
function StreamingStatusBar({ statusText, onForceStop }: { statusText?: string; onForceStop?: () => void }) {
const displayText = statusText || 'Thinking';
// Parse elapsed seconds from statusText like "Running bash... (45s)"
const elapsedMatch = statusText?.match(/\((\d+)s\)/);
const toolElapsed = elapsedMatch ? parseInt(elapsedMatch[1], 10) : 0;
const isWarning = toolElapsed >= 60;
const isCritical = toolElapsed >= 90;
return (
<div className="flex items-center gap-3 py-2 px-1 text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<span className={isCritical ? 'text-red-500' : isWarning ? 'text-yellow-500' : undefined}>
<Shimmer duration={1.5}>{displayText}</Shimmer>
</span>
{isWarning && !isCritical && (
<span className="text-yellow-500 text-[10px]">Running longer than usual</span>
)}
{isCritical && (
<span className="text-red-500 text-[10px]">Tool may be stuck</span>
)}
</div>
<span className="text-muted-foreground/50">|</span>
<ElapsedTimer />
{isCritical && onForceStop && (
<button
type="button"
onClick={onForceStop}
className="ml-auto rounded-md border border-red-500/30 bg-red-500/10 px-2 py-0.5 text-[10px] font-medium text-red-500 transition-colors hover:bg-red-500/20"
>
Force stop
</button>
)}
</div>
);
}
export function StreamingMessage({
content,
isStreaming,
toolUses = [],
toolResults = [],
streamingToolOutput,
statusText,
pendingPermission,
onPermissionResponse,
permissionResolved,
onForceStop,
}: StreamingMessageProps) {
const runningTools = toolUses.filter(
(tool) => !toolResults.some((r) => r.tool_use_id === tool.id)
);
// Determine confirmation state for the AI Elements component
const getConfirmationState = (): ToolUIPart['state'] => {
if (permissionResolved) return 'approval-responded';
if (pendingPermission) return 'approval-requested';
return 'input-available';
};
const getApproval = () => {
if (!pendingPermission && !permissionResolved) return undefined;
if (permissionResolved === 'allow') {
return { id: pendingPermission?.permissionRequestId || '', approved: true as const };
}
if (permissionResolved === 'deny') {
return { id: pendingPermission?.permissionRequestId || '', approved: false as const };
}
// Pending - no decision yet
return { id: pendingPermission?.permissionRequestId || '' };
};
const formatToolInput = (input: Record<string, unknown>): string => {
if (input.command) return String(input.command);
if (input.file_path) return String(input.file_path);
if (input.path) return String(input.path);
return JSON.stringify(input, null, 2);
};
// Extract a human-readable summary of the running command
const getRunningCommandSummary = (): string | undefined => {
if (runningTools.length === 0) {
// All tools completed but still streaming — AI is generating text
if (toolUses.length > 0) return 'Generating response...';
return undefined;
}
const tool = runningTools[runningTools.length - 1];
const input = tool.input as Record<string, unknown>;
if (tool.name === 'Bash' && input.command) {
const cmd = String(input.command);
return cmd.length > 80 ? cmd.slice(0, 80) + '...' : cmd;
}
if (input.file_path) return `${tool.name}: ${String(input.file_path)}`;
if (input.path) return `${tool.name}: ${String(input.path)}`;
return `Running ${tool.name}...`;
};
return (
<AIMessage from="assistant">
<MessageContent>
{/* Tool calls — compact collapsible group */}
{toolUses.length > 0 && (
<ToolActionsGroup
tools={toolUses.map((tool) => {
const result = toolResults.find((r) => r.tool_use_id === tool.id);
return {
id: tool.id,
name: tool.name,
input: tool.input,
result: result?.content,
isError: result?.is_error,
};
})}
isStreaming={isStreaming}
streamingToolOutput={streamingToolOutput}
/>
)}
{/* Permission approval confirmation */}
{(pendingPermission || permissionResolved) && (
<Confirmation
approval={getApproval()}
state={getConfirmationState()}
>
<ConfirmationTitle>
<span className="font-medium">{pendingPermission?.toolName}</span>
{pendingPermission?.decisionReason && (
<span className="text-muted-foreground ml-2">
— {pendingPermission.decisionReason}
</span>
)}
</ConfirmationTitle>
{pendingPermission && (
<div className="mt-1 rounded bg-muted/50 px-3 py-2 font-mono text-xs">
{formatToolInput(pendingPermission.toolInput)}
</div>
)}
<ConfirmationRequest>
<ConfirmationActions>
<ConfirmationAction
variant="outline"
onClick={() => onPermissionResponse?.('deny')}
>
Deny
</ConfirmationAction>
<ConfirmationAction
variant="outline"
onClick={() => onPermissionResponse?.('allow')}
>
Allow Once
</ConfirmationAction>
{pendingPermission?.suggestions && pendingPermission.suggestions.length > 0 && (
<ConfirmationAction
variant="default"
onClick={() => onPermissionResponse?.('allow_session')}
>
Allow for Session
</ConfirmationAction>
)}
</ConfirmationActions>
</ConfirmationRequest>
<ConfirmationAccepted>
<p className="text-xs text-green-600 dark:text-green-400">Allowed</p>
</ConfirmationAccepted>
<ConfirmationRejected>
<p className="text-xs text-red-600 dark:text-red-400">Denied</p>
</ConfirmationRejected>
</Confirmation>
)}
{/* Streaming text content rendered via Streamdown */}
{content && (
<MessageResponse>{content}</MessageResponse>
)}
{/* Loading indicator when no content yet */}
{isStreaming && !content && toolUses.length === 0 && !pendingPermission && (
<div className="py-2">
<Shimmer>Thinking...</Shimmer>
</div>
)}
{/* Status bar during streaming */}
{isStreaming && !pendingPermission && <StreamingStatusBar statusText={
statusText || getRunningCommandSummary()
} onForceStop={onForceStop} />}
</MessageContent>
</AIMessage>
);
}