@witqq/agent-sdk 0.6.1 → 0.8.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.
- package/README.md +539 -6
- package/dist/{types-BvwNzZCj.d.cts → agent-CW9XbmG_.d.ts} +148 -95
- package/dist/{types-BvwNzZCj.d.ts → agent-DxY68NZL.d.cts} +148 -95
- package/dist/auth/index.cjs +260 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +21 -138
- package/dist/auth/index.d.ts +21 -138
- package/dist/auth/index.js +260 -3
- package/dist/auth/index.js.map +1 -1
- package/dist/backends/claude.cjs +653 -140
- package/dist/backends/claude.cjs.map +1 -1
- package/dist/backends/claude.d.cts +4 -1
- package/dist/backends/claude.d.ts +4 -1
- package/dist/backends/claude.js +653 -140
- package/dist/backends/claude.js.map +1 -1
- package/dist/backends/copilot.cjs +428 -88
- package/dist/backends/copilot.cjs.map +1 -1
- package/dist/backends/copilot.d.cts +13 -4
- package/dist/backends/copilot.d.ts +13 -4
- package/dist/backends/copilot.js +428 -88
- package/dist/backends/copilot.js.map +1 -1
- package/dist/backends/vercel-ai.cjs +349 -77
- package/dist/backends/vercel-ai.cjs.map +1 -1
- package/dist/backends/vercel-ai.d.cts +3 -1
- package/dist/backends/vercel-ai.d.ts +3 -1
- package/dist/backends/vercel-ai.js +349 -77
- package/dist/backends/vercel-ai.js.map +1 -1
- package/dist/backends-BSrsBYFn.d.cts +39 -0
- package/dist/backends-BSrsBYFn.d.ts +39 -0
- package/dist/chat/accumulator.cjs +147 -0
- package/dist/chat/accumulator.cjs.map +1 -0
- package/dist/chat/accumulator.d.cts +64 -0
- package/dist/chat/accumulator.d.ts +64 -0
- package/dist/chat/accumulator.js +145 -0
- package/dist/chat/accumulator.js.map +1 -0
- package/dist/chat/backends.cjs +3524 -0
- package/dist/chat/backends.cjs.map +1 -0
- package/dist/chat/backends.d.cts +66 -0
- package/dist/chat/backends.d.ts +66 -0
- package/dist/chat/backends.js +3512 -0
- package/dist/chat/backends.js.map +1 -0
- package/dist/chat/context.cjs +280 -0
- package/dist/chat/context.cjs.map +1 -0
- package/dist/chat/context.d.cts +191 -0
- package/dist/chat/context.d.ts +191 -0
- package/dist/chat/context.js +277 -0
- package/dist/chat/context.js.map +1 -0
- package/dist/chat/core.cjs +305 -0
- package/dist/chat/core.cjs.map +1 -0
- package/dist/chat/core.d.cts +84 -0
- package/dist/chat/core.d.ts +84 -0
- package/dist/chat/core.js +282 -0
- package/dist/chat/core.js.map +1 -0
- package/dist/chat/errors.cjs +273 -0
- package/dist/chat/errors.cjs.map +1 -0
- package/dist/chat/errors.d.cts +97 -0
- package/dist/chat/errors.d.ts +97 -0
- package/dist/chat/errors.js +266 -0
- package/dist/chat/errors.js.map +1 -0
- package/dist/chat/events.cjs +203 -0
- package/dist/chat/events.cjs.map +1 -0
- package/dist/chat/events.d.cts +245 -0
- package/dist/chat/events.d.ts +245 -0
- package/dist/chat/events.js +196 -0
- package/dist/chat/events.js.map +1 -0
- package/dist/chat/index.cjs +5550 -0
- package/dist/chat/index.cjs.map +1 -0
- package/dist/chat/index.d.cts +77 -0
- package/dist/chat/index.d.ts +77 -0
- package/dist/chat/index.js +5505 -0
- package/dist/chat/index.js.map +1 -0
- package/dist/chat/react/theme.css +2517 -0
- package/dist/chat/react.cjs +3589 -0
- package/dist/chat/react.cjs.map +1 -0
- package/dist/chat/react.d.cts +1088 -0
- package/dist/chat/react.d.ts +1088 -0
- package/dist/chat/react.js +3547 -0
- package/dist/chat/react.js.map +1 -0
- package/dist/chat/runtime.cjs +1245 -0
- package/dist/chat/runtime.cjs.map +1 -0
- package/dist/chat/runtime.d.cts +182 -0
- package/dist/chat/runtime.d.ts +182 -0
- package/dist/chat/runtime.js +1243 -0
- package/dist/chat/runtime.js.map +1 -0
- package/dist/chat/server.cjs +2668 -0
- package/dist/chat/server.cjs.map +1 -0
- package/dist/chat/server.d.cts +648 -0
- package/dist/chat/server.d.ts +648 -0
- package/dist/chat/server.js +2628 -0
- package/dist/chat/server.js.map +1 -0
- package/dist/chat/sessions.cjs +380 -0
- package/dist/chat/sessions.cjs.map +1 -0
- package/dist/chat/sessions.d.cts +158 -0
- package/dist/chat/sessions.d.ts +158 -0
- package/dist/chat/sessions.js +376 -0
- package/dist/chat/sessions.js.map +1 -0
- package/dist/chat/sqlite.cjs +441 -0
- package/dist/chat/sqlite.cjs.map +1 -0
- package/dist/chat/sqlite.d.cts +128 -0
- package/dist/chat/sqlite.d.ts +128 -0
- package/dist/chat/sqlite.js +435 -0
- package/dist/chat/sqlite.js.map +1 -0
- package/dist/chat/state.cjs +190 -0
- package/dist/chat/state.cjs.map +1 -0
- package/dist/chat/state.d.cts +95 -0
- package/dist/chat/state.d.ts +95 -0
- package/dist/chat/state.js +180 -0
- package/dist/chat/state.js.map +1 -0
- package/dist/chat/storage.cjs +249 -0
- package/dist/chat/storage.cjs.map +1 -0
- package/dist/chat/storage.d.cts +197 -0
- package/dist/chat/storage.d.ts +197 -0
- package/dist/chat/storage.js +245 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/errors-C-so0M4t.d.cts +33 -0
- package/dist/errors-C-so0M4t.d.ts +33 -0
- package/dist/errors-CmVvczxZ.d.cts +28 -0
- package/dist/errors-CmVvczxZ.d.ts +28 -0
- package/dist/in-process-transport-C1JnJGVR.d.ts +228 -0
- package/dist/in-process-transport-C7DSqPyX.d.cts +228 -0
- package/dist/index.cjs +365 -59
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +322 -125
- package/dist/index.d.ts +322 -125
- package/dist/index.js +359 -60
- package/dist/index.js.map +1 -1
- package/dist/provider-types-PTSlRPNB.d.cts +39 -0
- package/dist/provider-types-PTSlRPNB.d.ts +39 -0
- package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
- package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
- package/dist/testing.cjs +383 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +132 -0
- package/dist/testing.d.ts +132 -0
- package/dist/testing.js +377 -0
- package/dist/testing.js.map +1 -0
- package/dist/token-store-CSUBgYwn.d.ts +48 -0
- package/dist/token-store-CuC4hB9Z.d.cts +48 -0
- package/dist/transport-Cdh3M0tS.d.cts +68 -0
- package/dist/transport-Ciap4PWK.d.ts +68 -0
- package/dist/types-4vbcmPTp.d.cts +143 -0
- package/dist/types-BxggH0Yh.d.ts +143 -0
- package/dist/types-DRgd_9R7.d.cts +363 -0
- package/dist/types-ajANVzf7.d.ts +363 -0
- package/package.json +178 -6
|
@@ -0,0 +1,3547 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, useState, useRef, useEffect, useCallback, useSyncExternalStore, useMemo } from 'react';
|
|
2
|
+
|
|
3
|
+
// src/chat/react/ChatProvider.ts
|
|
4
|
+
var ChatRuntimeContext = createContext(null);
|
|
5
|
+
function ChatProvider({ runtime, children }) {
|
|
6
|
+
return createElement(ChatRuntimeContext.Provider, { value: runtime }, children);
|
|
7
|
+
}
|
|
8
|
+
function useChatRuntime() {
|
|
9
|
+
const runtime = useContext(ChatRuntimeContext);
|
|
10
|
+
if (!runtime) {
|
|
11
|
+
throw new Error("useChatRuntime must be used within a ChatProvider");
|
|
12
|
+
}
|
|
13
|
+
return runtime;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/chat/types.ts
|
|
17
|
+
function createChatId() {
|
|
18
|
+
return crypto.randomUUID();
|
|
19
|
+
}
|
|
20
|
+
function isObservableSession(session) {
|
|
21
|
+
return "subscribe" in session && typeof session.subscribe === "function" && "getSnapshot" in session && typeof session.getSnapshot === "function";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/chat/bridge.ts
|
|
25
|
+
function chatEventToAgentEvent(event) {
|
|
26
|
+
switch (event.type) {
|
|
27
|
+
case "message:delta":
|
|
28
|
+
return { type: "text_delta", text: event.text };
|
|
29
|
+
case "thinking:start":
|
|
30
|
+
return { type: "thinking_start" };
|
|
31
|
+
case "thinking:delta":
|
|
32
|
+
return { type: "thinking_delta", text: event.text };
|
|
33
|
+
case "thinking:end":
|
|
34
|
+
return { type: "thinking_end" };
|
|
35
|
+
case "tool:start":
|
|
36
|
+
return {
|
|
37
|
+
type: "tool_call_start",
|
|
38
|
+
toolCallId: event.toolCallId,
|
|
39
|
+
toolName: event.toolName,
|
|
40
|
+
args: event.args
|
|
41
|
+
};
|
|
42
|
+
case "tool:complete":
|
|
43
|
+
return {
|
|
44
|
+
type: "tool_call_end",
|
|
45
|
+
toolCallId: event.toolCallId,
|
|
46
|
+
toolName: event.toolName,
|
|
47
|
+
result: event.result
|
|
48
|
+
};
|
|
49
|
+
case "error":
|
|
50
|
+
return { type: "error", error: event.error, recoverable: event.recoverable, code: event.code };
|
|
51
|
+
default:
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/chat/accumulator.ts
|
|
57
|
+
var MessageAccumulator = class {
|
|
58
|
+
messageId;
|
|
59
|
+
parts = [];
|
|
60
|
+
status = "pending";
|
|
61
|
+
currentTextPart = null;
|
|
62
|
+
currentReasoningPart = null;
|
|
63
|
+
toolCallParts = /* @__PURE__ */ new Map();
|
|
64
|
+
_finalized = false;
|
|
65
|
+
constructor(messageId) {
|
|
66
|
+
this.messageId = messageId ?? createChatId();
|
|
67
|
+
}
|
|
68
|
+
/** Get current message ID */
|
|
69
|
+
get id() {
|
|
70
|
+
return this.messageId;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Apply an AgentEvent to accumulate into the message
|
|
74
|
+
* @param event - AgentEvent to process
|
|
75
|
+
* @throws Error if accumulator is already finalized
|
|
76
|
+
*/
|
|
77
|
+
apply(event) {
|
|
78
|
+
if (this._finalized) throw new Error("Cannot apply events to finalized accumulator");
|
|
79
|
+
if (this.status === "pending") {
|
|
80
|
+
this.status = "streaming";
|
|
81
|
+
}
|
|
82
|
+
switch (event.type) {
|
|
83
|
+
case "text_delta":
|
|
84
|
+
this.handleTextDelta(event.text);
|
|
85
|
+
break;
|
|
86
|
+
case "thinking_start":
|
|
87
|
+
this.finalizeCurrentText();
|
|
88
|
+
this.currentReasoningPart = { type: "reasoning", text: "", status: "streaming" };
|
|
89
|
+
this.parts.push(this.currentReasoningPart);
|
|
90
|
+
break;
|
|
91
|
+
case "thinking_delta":
|
|
92
|
+
if (this.currentReasoningPart) {
|
|
93
|
+
this.currentReasoningPart.text += event.text;
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
case "thinking_end":
|
|
97
|
+
if (this.currentReasoningPart) {
|
|
98
|
+
this.currentReasoningPart.status = "complete";
|
|
99
|
+
this.currentReasoningPart = null;
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
case "tool_call_start": {
|
|
103
|
+
this.finalizeCurrentText();
|
|
104
|
+
const toolPart = {
|
|
105
|
+
type: "tool_call",
|
|
106
|
+
toolCallId: event.toolCallId,
|
|
107
|
+
name: event.toolName,
|
|
108
|
+
args: event.args,
|
|
109
|
+
status: "running"
|
|
110
|
+
};
|
|
111
|
+
this.toolCallParts.set(event.toolCallId, toolPart);
|
|
112
|
+
this.parts.push(toolPart);
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
case "tool_call_end": {
|
|
116
|
+
const existing = this.toolCallParts.get(event.toolCallId);
|
|
117
|
+
if (existing) {
|
|
118
|
+
existing.result = event.result;
|
|
119
|
+
existing.status = "complete";
|
|
120
|
+
}
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case "error":
|
|
124
|
+
this.status = "error";
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
handleTextDelta(text) {
|
|
129
|
+
if (!this.currentTextPart) {
|
|
130
|
+
this.currentTextPart = { type: "text", text: "", status: "streaming" };
|
|
131
|
+
this.parts.push(this.currentTextPart);
|
|
132
|
+
}
|
|
133
|
+
this.currentTextPart.text += text;
|
|
134
|
+
}
|
|
135
|
+
finalizeCurrentText() {
|
|
136
|
+
if (this.currentTextPart) {
|
|
137
|
+
this.currentTextPart.status = "complete";
|
|
138
|
+
this.currentTextPart = null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Get a snapshot of the current accumulated message (for streaming UI)
|
|
143
|
+
* @returns ChatMessage with current parts and "streaming" status
|
|
144
|
+
*/
|
|
145
|
+
snapshot() {
|
|
146
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
147
|
+
return {
|
|
148
|
+
id: this.messageId,
|
|
149
|
+
role: "assistant",
|
|
150
|
+
parts: this.parts.map((p) => ({ ...p })),
|
|
151
|
+
status: this.status === "pending" ? "pending" : "streaming",
|
|
152
|
+
createdAt: now,
|
|
153
|
+
updatedAt: now
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Finalize the accumulator and return the complete ChatMessage
|
|
158
|
+
* @returns Completed ChatMessage with all parts finalized
|
|
159
|
+
* @throws Error if accumulator is already finalized
|
|
160
|
+
*/
|
|
161
|
+
finalize() {
|
|
162
|
+
if (this._finalized) throw new Error("Accumulator already finalized");
|
|
163
|
+
this._finalized = true;
|
|
164
|
+
this.finalizeCurrentText();
|
|
165
|
+
if (this.currentReasoningPart) {
|
|
166
|
+
this.currentReasoningPart.status = "complete";
|
|
167
|
+
this.currentReasoningPart = null;
|
|
168
|
+
}
|
|
169
|
+
for (const [, toolPart] of this.toolCallParts) {
|
|
170
|
+
if (toolPart.status === "running" || toolPart.status === "pending") {
|
|
171
|
+
toolPart.status = "error";
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (this.status !== "error" && this.status !== "cancelled") {
|
|
175
|
+
this.status = "complete";
|
|
176
|
+
}
|
|
177
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
178
|
+
return {
|
|
179
|
+
id: this.messageId,
|
|
180
|
+
role: "assistant",
|
|
181
|
+
parts: this.parts,
|
|
182
|
+
status: this.status,
|
|
183
|
+
createdAt: now,
|
|
184
|
+
updatedAt: now
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/** Check if the accumulator has been finalized */
|
|
188
|
+
get finalized() {
|
|
189
|
+
return this._finalized;
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// src/chat/react/useChat.ts
|
|
194
|
+
function useChat(options = {}) {
|
|
195
|
+
const runtime = useChatRuntime();
|
|
196
|
+
const [sessionId, setSessionId] = useState(
|
|
197
|
+
options.sessionId ?? null
|
|
198
|
+
);
|
|
199
|
+
const [messages, setMessages] = useState([]);
|
|
200
|
+
const [isGenerating, setIsGenerating] = useState(false);
|
|
201
|
+
const [status, setStatus] = useState("idle");
|
|
202
|
+
const [error, setError] = useState(null);
|
|
203
|
+
const [usage, setUsage] = useState(null);
|
|
204
|
+
const generatingRef = useRef(false);
|
|
205
|
+
const lastUserMessageRef = useRef(null);
|
|
206
|
+
const onErrorRef = useRef(options.onError);
|
|
207
|
+
onErrorRef.current = options.onError;
|
|
208
|
+
const dismissTimerRef = useRef(null);
|
|
209
|
+
const autoDismissMs = options.autoDismissMs ?? 0;
|
|
210
|
+
useEffect(() => {
|
|
211
|
+
if (!error || autoDismissMs <= 0) return;
|
|
212
|
+
dismissTimerRef.current = setTimeout(() => {
|
|
213
|
+
setError(null);
|
|
214
|
+
dismissTimerRef.current = null;
|
|
215
|
+
}, autoDismissMs);
|
|
216
|
+
return () => {
|
|
217
|
+
if (dismissTimerRef.current) {
|
|
218
|
+
clearTimeout(dismissTimerRef.current);
|
|
219
|
+
dismissTimerRef.current = null;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}, [error, autoDismissMs]);
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (!sessionId) {
|
|
225
|
+
setMessages([]);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
runtime.getSession(sessionId).then((session) => {
|
|
229
|
+
if (session) {
|
|
230
|
+
setMessages([...session.messages]);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}, [sessionId, runtime]);
|
|
234
|
+
useEffect(() => {
|
|
235
|
+
return runtime.onSessionChange(() => {
|
|
236
|
+
const activeId = runtime.activeSessionId;
|
|
237
|
+
if (activeId && activeId !== sessionId) {
|
|
238
|
+
setSessionId(activeId);
|
|
239
|
+
setError(null);
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}, [runtime, sessionId]);
|
|
243
|
+
const ensureSession = useCallback(async () => {
|
|
244
|
+
if (sessionId) return sessionId;
|
|
245
|
+
const session = await runtime.createSession({
|
|
246
|
+
config: { model: "", backend: "" }
|
|
247
|
+
});
|
|
248
|
+
setSessionId(session.id);
|
|
249
|
+
return session.id;
|
|
250
|
+
}, [sessionId, runtime]);
|
|
251
|
+
const sendMessage = useCallback(
|
|
252
|
+
async (content) => {
|
|
253
|
+
if (generatingRef.current) return;
|
|
254
|
+
lastUserMessageRef.current = content;
|
|
255
|
+
setError(null);
|
|
256
|
+
generatingRef.current = true;
|
|
257
|
+
setIsGenerating(true);
|
|
258
|
+
setStatus("streaming");
|
|
259
|
+
const accumulator = new MessageAccumulator();
|
|
260
|
+
let hasEvents = false;
|
|
261
|
+
try {
|
|
262
|
+
const sid = await ensureSession();
|
|
263
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
264
|
+
const userMsg = {
|
|
265
|
+
id: crypto.randomUUID(),
|
|
266
|
+
role: "user",
|
|
267
|
+
parts: [{ type: "text", text: content, status: "complete" }],
|
|
268
|
+
status: "complete",
|
|
269
|
+
createdAt: now,
|
|
270
|
+
updatedAt: now
|
|
271
|
+
};
|
|
272
|
+
setMessages((prev) => [...prev, userMsg]);
|
|
273
|
+
for await (const event of runtime.send(sid, content)) {
|
|
274
|
+
if (event.type === "usage") {
|
|
275
|
+
setUsage({
|
|
276
|
+
promptTokens: event.promptTokens,
|
|
277
|
+
completionTokens: event.completionTokens,
|
|
278
|
+
totalTokens: event.promptTokens + event.completionTokens,
|
|
279
|
+
model: event.model
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
const agentEvent = chatEventToAgentEvent(event);
|
|
283
|
+
if (agentEvent) {
|
|
284
|
+
accumulator.apply(agentEvent);
|
|
285
|
+
hasEvents = true;
|
|
286
|
+
const snapshot = accumulator.snapshot();
|
|
287
|
+
setMessages((prev) => {
|
|
288
|
+
const last = prev[prev.length - 1];
|
|
289
|
+
if (last && last.id === snapshot.id) {
|
|
290
|
+
return [...prev.slice(0, -1), snapshot];
|
|
291
|
+
}
|
|
292
|
+
return [...prev, snapshot];
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const session = await runtime.getSession(sid);
|
|
297
|
+
if (session) {
|
|
298
|
+
setMessages([...session.messages]);
|
|
299
|
+
} else if (hasEvents) {
|
|
300
|
+
const final = accumulator.finalize();
|
|
301
|
+
setMessages((prev) => {
|
|
302
|
+
const last = prev[prev.length - 1];
|
|
303
|
+
if (last && last.id === final.id) {
|
|
304
|
+
return [...prev.slice(0, -1), final];
|
|
305
|
+
}
|
|
306
|
+
return [...prev, final];
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
} catch (err) {
|
|
310
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
311
|
+
setError(e);
|
|
312
|
+
onErrorRef.current?.(e);
|
|
313
|
+
if (hasEvents && !accumulator.finalized) {
|
|
314
|
+
accumulator.apply({ type: "error", error: e.message, recoverable: false });
|
|
315
|
+
const errorSnapshot = accumulator.finalize();
|
|
316
|
+
setMessages((prev) => {
|
|
317
|
+
const last = prev[prev.length - 1];
|
|
318
|
+
if (last && last.id === errorSnapshot.id) {
|
|
319
|
+
return [...prev.slice(0, -1), errorSnapshot];
|
|
320
|
+
}
|
|
321
|
+
return prev;
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
} finally {
|
|
325
|
+
generatingRef.current = false;
|
|
326
|
+
setIsGenerating(false);
|
|
327
|
+
setStatus(runtime.status);
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
[ensureSession, runtime]
|
|
331
|
+
);
|
|
332
|
+
const stop = useCallback(() => {
|
|
333
|
+
runtime.abort();
|
|
334
|
+
}, [runtime]);
|
|
335
|
+
const clearError = useCallback(() => {
|
|
336
|
+
setError(null);
|
|
337
|
+
}, []);
|
|
338
|
+
const retryLastMessage = useCallback(async () => {
|
|
339
|
+
if (!lastUserMessageRef.current || generatingRef.current) return;
|
|
340
|
+
await sendMessage(lastUserMessageRef.current);
|
|
341
|
+
}, [sendMessage]);
|
|
342
|
+
const newSession = useCallback(async () => {
|
|
343
|
+
const session = await runtime.createSession({
|
|
344
|
+
config: { model: "", backend: "" }
|
|
345
|
+
});
|
|
346
|
+
setSessionId(session.id);
|
|
347
|
+
setMessages([]);
|
|
348
|
+
setError(null);
|
|
349
|
+
lastUserMessageRef.current = null;
|
|
350
|
+
return session.id;
|
|
351
|
+
}, [runtime]);
|
|
352
|
+
return {
|
|
353
|
+
sessionId,
|
|
354
|
+
messages,
|
|
355
|
+
sendMessage,
|
|
356
|
+
stop,
|
|
357
|
+
isGenerating,
|
|
358
|
+
status,
|
|
359
|
+
error,
|
|
360
|
+
clearError,
|
|
361
|
+
retryLastMessage,
|
|
362
|
+
newSession,
|
|
363
|
+
usage
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
var EMPTY_MESSAGES = [];
|
|
367
|
+
function useMessages(options) {
|
|
368
|
+
const runtime = useChatRuntime();
|
|
369
|
+
const { sessionId } = options;
|
|
370
|
+
const sessionRef = useRef(null);
|
|
371
|
+
const messagesRef = useRef(EMPTY_MESSAGES);
|
|
372
|
+
const isLoadedRef = useRef(false);
|
|
373
|
+
const versionRef = useRef(0);
|
|
374
|
+
const listenersRef = useRef(/* @__PURE__ */ new Set());
|
|
375
|
+
const emitChange = useCallback(() => {
|
|
376
|
+
versionRef.current++;
|
|
377
|
+
for (const listener of listenersRef.current) {
|
|
378
|
+
listener();
|
|
379
|
+
}
|
|
380
|
+
}, []);
|
|
381
|
+
const subscribe = useCallback(
|
|
382
|
+
(callback) => {
|
|
383
|
+
listenersRef.current.add(callback);
|
|
384
|
+
return () => {
|
|
385
|
+
listenersRef.current.delete(callback);
|
|
386
|
+
};
|
|
387
|
+
},
|
|
388
|
+
[]
|
|
389
|
+
);
|
|
390
|
+
const getSnapshot = useCallback(() => {
|
|
391
|
+
return messagesRef.current;
|
|
392
|
+
}, []);
|
|
393
|
+
useEffect(() => {
|
|
394
|
+
let cancelled = false;
|
|
395
|
+
let unsubscribe;
|
|
396
|
+
let pollInterval;
|
|
397
|
+
async function load() {
|
|
398
|
+
const session = await runtime.getSession(sessionId);
|
|
399
|
+
if (cancelled) return;
|
|
400
|
+
if (!session) {
|
|
401
|
+
sessionRef.current = null;
|
|
402
|
+
messagesRef.current = EMPTY_MESSAGES;
|
|
403
|
+
isLoadedRef.current = false;
|
|
404
|
+
emitChange();
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
sessionRef.current = session;
|
|
408
|
+
messagesRef.current = session.messages;
|
|
409
|
+
isLoadedRef.current = true;
|
|
410
|
+
emitChange();
|
|
411
|
+
if (isObservableSession(session)) {
|
|
412
|
+
unsubscribe = session.subscribe(() => {
|
|
413
|
+
const snapshot = session.getSnapshot();
|
|
414
|
+
messagesRef.current = snapshot.messages;
|
|
415
|
+
emitChange();
|
|
416
|
+
});
|
|
417
|
+
} else {
|
|
418
|
+
pollInterval = setInterval(async () => {
|
|
419
|
+
if (cancelled) return;
|
|
420
|
+
const updated = await runtime.getSession(sessionId);
|
|
421
|
+
if (cancelled || !updated) return;
|
|
422
|
+
if (updated.messages.length !== messagesRef.current.length) {
|
|
423
|
+
messagesRef.current = updated.messages;
|
|
424
|
+
emitChange();
|
|
425
|
+
}
|
|
426
|
+
}, 500);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
load();
|
|
430
|
+
return () => {
|
|
431
|
+
cancelled = true;
|
|
432
|
+
unsubscribe?.();
|
|
433
|
+
if (pollInterval) clearInterval(pollInterval);
|
|
434
|
+
};
|
|
435
|
+
}, [sessionId, runtime, emitChange]);
|
|
436
|
+
const messages = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
437
|
+
return {
|
|
438
|
+
messages,
|
|
439
|
+
isLoaded: isLoadedRef.current
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
function toSessionInfo(s) {
|
|
443
|
+
return {
|
|
444
|
+
id: s.id,
|
|
445
|
+
title: s.title,
|
|
446
|
+
status: s.status,
|
|
447
|
+
messageCount: s.metadata.messageCount,
|
|
448
|
+
lastMessage: s.messages[s.messages.length - 1],
|
|
449
|
+
createdAt: s.createdAt,
|
|
450
|
+
updatedAt: s.updatedAt
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
function useSessions() {
|
|
454
|
+
const runtime = useChatRuntime();
|
|
455
|
+
const [sessions, setSessions] = useState([]);
|
|
456
|
+
const [loading, setLoading] = useState(true);
|
|
457
|
+
const [error, setError] = useState(null);
|
|
458
|
+
const fetchSessions = useCallback(async () => {
|
|
459
|
+
try {
|
|
460
|
+
const list = await runtime.listSessions();
|
|
461
|
+
setSessions(list.map(toSessionInfo));
|
|
462
|
+
setError(null);
|
|
463
|
+
} catch (err) {
|
|
464
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
465
|
+
} finally {
|
|
466
|
+
setLoading(false);
|
|
467
|
+
}
|
|
468
|
+
}, [runtime]);
|
|
469
|
+
useEffect(() => {
|
|
470
|
+
fetchSessions();
|
|
471
|
+
}, [fetchSessions]);
|
|
472
|
+
useEffect(() => {
|
|
473
|
+
return runtime.onSessionChange(() => {
|
|
474
|
+
fetchSessions();
|
|
475
|
+
});
|
|
476
|
+
}, [runtime, fetchSessions]);
|
|
477
|
+
const refresh = useCallback(() => {
|
|
478
|
+
setLoading(true);
|
|
479
|
+
fetchSessions();
|
|
480
|
+
}, [fetchSessions]);
|
|
481
|
+
return { sessions, loading, error, refresh };
|
|
482
|
+
}
|
|
483
|
+
function parseBlocks(text) {
|
|
484
|
+
const tokens = [];
|
|
485
|
+
const lines = text.split("\n");
|
|
486
|
+
let i = 0;
|
|
487
|
+
while (i < lines.length) {
|
|
488
|
+
const line = lines[i];
|
|
489
|
+
const fenceMatch = line.match(/^```(\w*)/);
|
|
490
|
+
if (fenceMatch) {
|
|
491
|
+
const language = fenceMatch[1] || void 0;
|
|
492
|
+
const codeLines = [];
|
|
493
|
+
i++;
|
|
494
|
+
while (i < lines.length && !lines[i].startsWith("```")) {
|
|
495
|
+
codeLines.push(lines[i]);
|
|
496
|
+
i++;
|
|
497
|
+
}
|
|
498
|
+
i++;
|
|
499
|
+
tokens.push({ type: "code_block", code: codeLines.join("\n"), language });
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
|
|
503
|
+
if (headingMatch) {
|
|
504
|
+
tokens.push({ type: "heading", level: headingMatch[1].length, content: headingMatch[2] });
|
|
505
|
+
i++;
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (line.startsWith("> ")) {
|
|
509
|
+
const quoteLines = [];
|
|
510
|
+
while (i < lines.length && lines[i].startsWith("> ")) {
|
|
511
|
+
quoteLines.push(lines[i].slice(2));
|
|
512
|
+
i++;
|
|
513
|
+
}
|
|
514
|
+
tokens.push({ type: "blockquote", content: quoteLines.join("\n") });
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (/^[-*]\s+/.test(line)) {
|
|
518
|
+
const items = [];
|
|
519
|
+
while (i < lines.length && /^[-*]\s+/.test(lines[i])) {
|
|
520
|
+
items.push(lines[i].replace(/^[-*]\s+/, ""));
|
|
521
|
+
i++;
|
|
522
|
+
}
|
|
523
|
+
tokens.push({ type: "list", ordered: false, items });
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (/^\d+\.\s+/.test(line)) {
|
|
527
|
+
const items = [];
|
|
528
|
+
while (i < lines.length && /^\d+\.\s+/.test(lines[i])) {
|
|
529
|
+
items.push(lines[i].replace(/^\d+\.\s+/, ""));
|
|
530
|
+
i++;
|
|
531
|
+
}
|
|
532
|
+
tokens.push({ type: "list", ordered: true, items });
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (line.trim() === "") {
|
|
536
|
+
i++;
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
const paraLines = [];
|
|
540
|
+
while (i < lines.length && lines[i].trim() !== "" && !lines[i].match(/^(#{1,6}\s|```|>\s|[-*]\s|\d+\.\s)/)) {
|
|
541
|
+
paraLines.push(lines[i]);
|
|
542
|
+
i++;
|
|
543
|
+
}
|
|
544
|
+
if (paraLines.length > 0) {
|
|
545
|
+
tokens.push({ type: "paragraph", content: paraLines.join("\n") });
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return tokens;
|
|
549
|
+
}
|
|
550
|
+
function parseInline(text, props) {
|
|
551
|
+
const nodes = [];
|
|
552
|
+
const regex = /(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(_[^_]+_)|(\[[^\]]+\]\([^)]+\))/g;
|
|
553
|
+
let lastIndex = 0;
|
|
554
|
+
let match;
|
|
555
|
+
while ((match = regex.exec(text)) !== null) {
|
|
556
|
+
if (match.index > lastIndex) {
|
|
557
|
+
nodes.push(text.slice(lastIndex, match.index));
|
|
558
|
+
}
|
|
559
|
+
const fragment = match[0];
|
|
560
|
+
if (fragment.startsWith("`")) {
|
|
561
|
+
const code = fragment.slice(1, -1);
|
|
562
|
+
nodes.push(createElement("code", { key: `ic-${match.index}`, "data-md-inline-code": true }, code));
|
|
563
|
+
} else if (fragment.startsWith("**")) {
|
|
564
|
+
const content = fragment.slice(2, -2);
|
|
565
|
+
nodes.push(createElement("strong", { key: `b-${match.index}` }, content));
|
|
566
|
+
} else if (fragment.startsWith("*") || fragment.startsWith("_")) {
|
|
567
|
+
const content = fragment.slice(1, -1);
|
|
568
|
+
nodes.push(createElement("em", { key: `i-${match.index}` }, content));
|
|
569
|
+
} else if (fragment.startsWith("[")) {
|
|
570
|
+
const linkMatch = fragment.match(/\[([^\]]+)\]\(([^)]+)\)/);
|
|
571
|
+
if (linkMatch) {
|
|
572
|
+
nodes.push(
|
|
573
|
+
props?.renderLink ? props.renderLink(linkMatch[2], linkMatch[1]) : createElement("a", { key: `a-${match.index}`, href: linkMatch[2] }, linkMatch[1])
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
lastIndex = match.index + fragment.length;
|
|
578
|
+
}
|
|
579
|
+
if (lastIndex < text.length) {
|
|
580
|
+
nodes.push(text.slice(lastIndex));
|
|
581
|
+
}
|
|
582
|
+
return nodes;
|
|
583
|
+
}
|
|
584
|
+
function renderBlock(token, index, props) {
|
|
585
|
+
switch (token.type) {
|
|
586
|
+
case "heading":
|
|
587
|
+
return createElement(
|
|
588
|
+
`h${token.level}`,
|
|
589
|
+
{ key: index, "data-md-heading": true },
|
|
590
|
+
...parseInline(token.content, props)
|
|
591
|
+
);
|
|
592
|
+
case "paragraph":
|
|
593
|
+
return createElement(
|
|
594
|
+
"p",
|
|
595
|
+
{ key: index, "data-md-paragraph": true },
|
|
596
|
+
...parseInline(token.content, props)
|
|
597
|
+
);
|
|
598
|
+
case "code_block":
|
|
599
|
+
if (props.renderCode) {
|
|
600
|
+
return props.renderCode(token.code, token.language);
|
|
601
|
+
}
|
|
602
|
+
return createElement(
|
|
603
|
+
"pre",
|
|
604
|
+
{ key: index, "data-md-code-block": true },
|
|
605
|
+
createElement(
|
|
606
|
+
"code",
|
|
607
|
+
{ className: token.language ? `language-${token.language}` : void 0 },
|
|
608
|
+
token.code
|
|
609
|
+
)
|
|
610
|
+
);
|
|
611
|
+
case "blockquote":
|
|
612
|
+
return createElement(
|
|
613
|
+
"blockquote",
|
|
614
|
+
{ key: index, "data-md-blockquote": true },
|
|
615
|
+
...parseInline(token.content, props)
|
|
616
|
+
);
|
|
617
|
+
case "list": {
|
|
618
|
+
const tag = token.ordered ? "ol" : "ul";
|
|
619
|
+
const items = token.items.map(
|
|
620
|
+
(item, i) => createElement("li", { key: i }, ...parseInline(item, props))
|
|
621
|
+
);
|
|
622
|
+
return createElement(tag, { key: index, "data-md-list": true }, ...items);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
function MarkdownRenderer(props) {
|
|
627
|
+
const tokens = parseBlocks(props.content);
|
|
628
|
+
const children = tokens.map((token, i) => renderBlock(token, i, props));
|
|
629
|
+
return createElement("div", { "data-md-root": true }, ...children);
|
|
630
|
+
}
|
|
631
|
+
function ThinkingBlock({ text, isStreaming, defaultOpen }) {
|
|
632
|
+
const attrs = {
|
|
633
|
+
"data-thinking": "true"
|
|
634
|
+
};
|
|
635
|
+
if (isStreaming) {
|
|
636
|
+
attrs["data-streaming"] = "true";
|
|
637
|
+
}
|
|
638
|
+
if (defaultOpen) {
|
|
639
|
+
attrs.open = true;
|
|
640
|
+
}
|
|
641
|
+
return createElement(
|
|
642
|
+
"details",
|
|
643
|
+
attrs,
|
|
644
|
+
createElement("summary", null, isStreaming ? "Thinking..." : "Reasoning"),
|
|
645
|
+
createElement("div", null, text)
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
function ToolCallView({ part, onApprove, onDeny, renderArgs, renderResult }) {
|
|
649
|
+
const children = [];
|
|
650
|
+
children.push(
|
|
651
|
+
createElement(
|
|
652
|
+
"div",
|
|
653
|
+
{ key: "header", "data-tool-header": "true" },
|
|
654
|
+
createElement("span", { "data-tool-label": "name" }, part.name),
|
|
655
|
+
createElement("span", { "data-tool-label": "status" }, part.status)
|
|
656
|
+
)
|
|
657
|
+
);
|
|
658
|
+
if (part.args !== void 0) {
|
|
659
|
+
children.push(
|
|
660
|
+
renderArgs ? renderArgs(part.args) : createElement(
|
|
661
|
+
"details",
|
|
662
|
+
{ key: "args", "data-tool-details": "args" },
|
|
663
|
+
createElement("summary", null, "Arguments"),
|
|
664
|
+
createElement("pre", { "data-tool-label": "args" }, JSON.stringify(part.args, null, 2))
|
|
665
|
+
)
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
if (part.result !== void 0) {
|
|
669
|
+
children.push(
|
|
670
|
+
renderResult ? renderResult(part.result) : createElement(
|
|
671
|
+
"details",
|
|
672
|
+
{ key: "result", "data-tool-details": "result", open: true },
|
|
673
|
+
createElement("summary", null, "Result"),
|
|
674
|
+
createElement("pre", { "data-tool-label": "result" }, JSON.stringify(part.result, null, 2))
|
|
675
|
+
)
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
if (part.error) {
|
|
679
|
+
children.push(
|
|
680
|
+
createElement("span", { key: "error", "data-tool-label": "error", role: "alert" }, part.error)
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
if (part.status === "requires_approval") {
|
|
684
|
+
children.push(
|
|
685
|
+
createElement(
|
|
686
|
+
"div",
|
|
687
|
+
{ key: "actions", "data-tool-actions": "true" },
|
|
688
|
+
createElement("button", { key: "approve", onClick: onApprove, "data-action": "approve" }, "Approve"),
|
|
689
|
+
createElement("button", { key: "deny", onClick: onDeny, "data-action": "deny" }, "Deny")
|
|
690
|
+
)
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
return createElement(
|
|
694
|
+
"div",
|
|
695
|
+
{
|
|
696
|
+
"data-tool-status": part.status,
|
|
697
|
+
"data-tool-name": part.name
|
|
698
|
+
},
|
|
699
|
+
...children
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// src/chat/react/Message.ts
|
|
704
|
+
function defaultRenderText(part, index) {
|
|
705
|
+
return createElement(
|
|
706
|
+
"div",
|
|
707
|
+
{ key: index, "data-part": "text" },
|
|
708
|
+
createElement(MarkdownRenderer, { content: part.text })
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
function defaultRenderReasoning(part, index) {
|
|
712
|
+
return createElement(ThinkingBlock, {
|
|
713
|
+
key: index,
|
|
714
|
+
text: part.text,
|
|
715
|
+
isStreaming: part.status === "streaming"
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
function defaultRenderToolCall(part, index) {
|
|
719
|
+
return createElement(
|
|
720
|
+
"div",
|
|
721
|
+
{ key: index, "data-part": "tool_call" },
|
|
722
|
+
createElement(ToolCallView, { part })
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
function defaultRenderSource(part, index) {
|
|
726
|
+
return createElement("a", { key: index, href: part.url, "data-part": "source" }, part.title ?? part.url);
|
|
727
|
+
}
|
|
728
|
+
function defaultRenderFile(part, index) {
|
|
729
|
+
return createElement("span", { key: index, "data-part": "file" }, part.name);
|
|
730
|
+
}
|
|
731
|
+
function renderPart(props, part, index) {
|
|
732
|
+
switch (part.type) {
|
|
733
|
+
case "text":
|
|
734
|
+
return (props.renderText ?? defaultRenderText)(part, index);
|
|
735
|
+
case "reasoning":
|
|
736
|
+
return (props.renderReasoning ?? defaultRenderReasoning)(part, index);
|
|
737
|
+
case "tool_call":
|
|
738
|
+
return (props.renderToolCall ?? defaultRenderToolCall)(part, index);
|
|
739
|
+
case "source":
|
|
740
|
+
return (props.renderSource ?? defaultRenderSource)(part, index);
|
|
741
|
+
case "file":
|
|
742
|
+
return (props.renderFile ?? defaultRenderFile)(part, index);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
function Message(props) {
|
|
746
|
+
const { message } = props;
|
|
747
|
+
const children = message.parts.map((part, i) => renderPart(props, part, i));
|
|
748
|
+
return createElement(
|
|
749
|
+
"div",
|
|
750
|
+
{
|
|
751
|
+
"data-role": message.role,
|
|
752
|
+
"data-status": message.status
|
|
753
|
+
},
|
|
754
|
+
...children
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
function useToolApproval(messages, onApprove, onDeny) {
|
|
758
|
+
const pendingRequests = useMemo(() => {
|
|
759
|
+
const requests = [];
|
|
760
|
+
for (const msg of messages) {
|
|
761
|
+
for (const part of msg.parts) {
|
|
762
|
+
if (part.type === "tool_call" && part.status === "requires_approval") {
|
|
763
|
+
requests.push({
|
|
764
|
+
toolCallId: part.toolCallId,
|
|
765
|
+
toolName: part.name,
|
|
766
|
+
toolArgs: part.args ?? {},
|
|
767
|
+
messageId: msg.id
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return requests;
|
|
773
|
+
}, [messages]);
|
|
774
|
+
const approve = useCallback((toolCallId) => {
|
|
775
|
+
onApprove?.(toolCallId);
|
|
776
|
+
}, [onApprove]);
|
|
777
|
+
const deny = useCallback((toolCallId) => {
|
|
778
|
+
onDeny?.(toolCallId);
|
|
779
|
+
}, [onDeny]);
|
|
780
|
+
return { pendingRequests, approve, deny };
|
|
781
|
+
}
|
|
782
|
+
var ThreadSlotsContext = createContext(null);
|
|
783
|
+
function ThreadProvider({
|
|
784
|
+
children,
|
|
785
|
+
renderMessage,
|
|
786
|
+
renderToolCall,
|
|
787
|
+
renderThinkingBlock
|
|
788
|
+
}) {
|
|
789
|
+
const value = { renderMessage, renderToolCall, renderThinkingBlock };
|
|
790
|
+
return createElement(ThreadSlotsContext.Provider, { value }, children);
|
|
791
|
+
}
|
|
792
|
+
function useThreadSlots() {
|
|
793
|
+
const ctx = useContext(ThreadSlotsContext);
|
|
794
|
+
if (!ctx) {
|
|
795
|
+
throw new Error("useThreadSlots must be used within a ThreadProvider");
|
|
796
|
+
}
|
|
797
|
+
return ctx;
|
|
798
|
+
}
|
|
799
|
+
function useOptionalThreadSlots() {
|
|
800
|
+
return useContext(ThreadSlotsContext);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/chat/react/Thread.ts
|
|
804
|
+
function Thread({
|
|
805
|
+
messages,
|
|
806
|
+
isGenerating,
|
|
807
|
+
autoScroll = true,
|
|
808
|
+
className
|
|
809
|
+
}) {
|
|
810
|
+
const sentinelRef = useRef(null);
|
|
811
|
+
const containerRef = useRef(null);
|
|
812
|
+
const [userScrolledUp, setUserScrolledUp] = useState(false);
|
|
813
|
+
const isScrollingProgrammatically = useRef(false);
|
|
814
|
+
const handleScroll = useCallback(() => {
|
|
815
|
+
if (isScrollingProgrammatically.current) return;
|
|
816
|
+
const el = containerRef.current;
|
|
817
|
+
if (!el) return;
|
|
818
|
+
const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 1;
|
|
819
|
+
setUserScrolledUp(!atBottom);
|
|
820
|
+
}, []);
|
|
821
|
+
const scrollToBottom = useCallback(() => {
|
|
822
|
+
isScrollingProgrammatically.current = true;
|
|
823
|
+
sentinelRef.current?.scrollIntoView({ behavior: "smooth" });
|
|
824
|
+
setUserScrolledUp(false);
|
|
825
|
+
setTimeout(() => {
|
|
826
|
+
isScrollingProgrammatically.current = false;
|
|
827
|
+
}, 500);
|
|
828
|
+
}, []);
|
|
829
|
+
useEffect(() => {
|
|
830
|
+
if (!autoScroll || userScrolledUp) return;
|
|
831
|
+
sentinelRef.current?.scrollIntoView({ behavior: "smooth" });
|
|
832
|
+
}, [messages, autoScroll, userScrolledUp]);
|
|
833
|
+
const slots = useOptionalThreadSlots();
|
|
834
|
+
const attrs = { "data-thread": "true", className };
|
|
835
|
+
if (isGenerating) {
|
|
836
|
+
attrs["data-thread-loading"] = "true";
|
|
837
|
+
}
|
|
838
|
+
attrs.ref = containerRef;
|
|
839
|
+
attrs.onScroll = handleScroll;
|
|
840
|
+
const children = [];
|
|
841
|
+
if (messages.length === 0 && !isGenerating) {
|
|
842
|
+
children.push(
|
|
843
|
+
createElement(
|
|
844
|
+
"div",
|
|
845
|
+
{ key: "__empty", "data-thread-empty": "true" },
|
|
846
|
+
"Start a conversation"
|
|
847
|
+
)
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
for (let i = 0; i < messages.length; i++) {
|
|
851
|
+
const msg = messages[i];
|
|
852
|
+
const content = slots?.renderMessage ? slots.renderMessage(msg, i) : createElement(Message, {
|
|
853
|
+
key: msg.id,
|
|
854
|
+
message: msg,
|
|
855
|
+
renderToolCall: slots?.renderToolCall,
|
|
856
|
+
renderReasoning: slots?.renderThinkingBlock ? (part, idx) => slots.renderThinkingBlock(part, idx) : void 0
|
|
857
|
+
});
|
|
858
|
+
children.push(
|
|
859
|
+
createElement(
|
|
860
|
+
"div",
|
|
861
|
+
{ key: msg.id, "data-thread-message": "true", "data-role": msg.role },
|
|
862
|
+
content
|
|
863
|
+
)
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
if (isGenerating) {
|
|
867
|
+
children.push(
|
|
868
|
+
createElement(
|
|
869
|
+
"div",
|
|
870
|
+
{ key: "__loading", "data-thread-loading-indicator": "true" },
|
|
871
|
+
createElement("span", null),
|
|
872
|
+
createElement("span", null),
|
|
873
|
+
createElement("span", null)
|
|
874
|
+
)
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
children.push(createElement("div", { key: "__sentinel", ref: sentinelRef }));
|
|
878
|
+
if (userScrolledUp) {
|
|
879
|
+
children.push(
|
|
880
|
+
createElement("button", {
|
|
881
|
+
key: "__scroll-to-bottom",
|
|
882
|
+
"data-action": "scroll-to-bottom",
|
|
883
|
+
type: "button",
|
|
884
|
+
onClick: scrollToBottom,
|
|
885
|
+
"aria-label": "Scroll to bottom"
|
|
886
|
+
})
|
|
887
|
+
);
|
|
888
|
+
}
|
|
889
|
+
return createElement("div", attrs, ...children);
|
|
890
|
+
}
|
|
891
|
+
function Composer({
|
|
892
|
+
onSend,
|
|
893
|
+
onStop,
|
|
894
|
+
isGenerating,
|
|
895
|
+
disabled,
|
|
896
|
+
placeholder = "Type a message...",
|
|
897
|
+
maxRows = 5,
|
|
898
|
+
className
|
|
899
|
+
}) {
|
|
900
|
+
const textareaRef = useRef(null);
|
|
901
|
+
const [value, setValue] = useState("");
|
|
902
|
+
const resize = useCallback(() => {
|
|
903
|
+
const el = textareaRef.current;
|
|
904
|
+
if (!el) return;
|
|
905
|
+
el.style.height = "auto";
|
|
906
|
+
const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 20;
|
|
907
|
+
const maxHeight = lineHeight * maxRows;
|
|
908
|
+
el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`;
|
|
909
|
+
}, [maxRows]);
|
|
910
|
+
useEffect(() => {
|
|
911
|
+
resize();
|
|
912
|
+
}, [value, resize]);
|
|
913
|
+
const handleSend = useCallback(() => {
|
|
914
|
+
const trimmed = value.trim();
|
|
915
|
+
if (!trimmed || isGenerating) return;
|
|
916
|
+
onSend(trimmed);
|
|
917
|
+
setValue("");
|
|
918
|
+
}, [value, isGenerating, onSend]);
|
|
919
|
+
const handleKeyDown = useCallback(
|
|
920
|
+
(e) => {
|
|
921
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
922
|
+
e.preventDefault();
|
|
923
|
+
handleSend();
|
|
924
|
+
}
|
|
925
|
+
},
|
|
926
|
+
[handleSend]
|
|
927
|
+
);
|
|
928
|
+
const handleChange = useCallback(
|
|
929
|
+
(e) => {
|
|
930
|
+
setValue(e.target.value);
|
|
931
|
+
},
|
|
932
|
+
[]
|
|
933
|
+
);
|
|
934
|
+
const children = [
|
|
935
|
+
createElement(
|
|
936
|
+
"div",
|
|
937
|
+
{ key: "input-wrapper", "data-input": "" },
|
|
938
|
+
createElement("textarea", {
|
|
939
|
+
ref: textareaRef,
|
|
940
|
+
value,
|
|
941
|
+
onChange: handleChange,
|
|
942
|
+
onKeyDown: handleKeyDown,
|
|
943
|
+
placeholder,
|
|
944
|
+
disabled: disabled || false,
|
|
945
|
+
"aria-label": "Message input",
|
|
946
|
+
rows: 1
|
|
947
|
+
}),
|
|
948
|
+
isGenerating ? createElement(
|
|
949
|
+
"button",
|
|
950
|
+
{
|
|
951
|
+
key: "stop",
|
|
952
|
+
"data-action": "stop",
|
|
953
|
+
onClick: onStop,
|
|
954
|
+
type: "button"
|
|
955
|
+
},
|
|
956
|
+
"Stop"
|
|
957
|
+
) : createElement(
|
|
958
|
+
"button",
|
|
959
|
+
{
|
|
960
|
+
key: "send",
|
|
961
|
+
"data-action": "send",
|
|
962
|
+
onClick: handleSend,
|
|
963
|
+
disabled: !value.trim() || isGenerating,
|
|
964
|
+
type: "button"
|
|
965
|
+
},
|
|
966
|
+
"Send"
|
|
967
|
+
)
|
|
968
|
+
)
|
|
969
|
+
];
|
|
970
|
+
return createElement(
|
|
971
|
+
"div",
|
|
972
|
+
{ "data-composer": "true", className },
|
|
973
|
+
...children
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
function isFullSession(item) {
|
|
977
|
+
return "messages" in item && Array.isArray(item.messages);
|
|
978
|
+
}
|
|
979
|
+
function formatRelativeTime(date) {
|
|
980
|
+
const now = Date.now();
|
|
981
|
+
const diff = now - date.getTime();
|
|
982
|
+
const seconds = Math.floor(diff / 1e3);
|
|
983
|
+
if (seconds < 60) return "now";
|
|
984
|
+
const minutes = Math.floor(seconds / 60);
|
|
985
|
+
if (minutes < 60) return `${minutes}m`;
|
|
986
|
+
const hours = Math.floor(minutes / 60);
|
|
987
|
+
if (hours < 24) return `${hours}h`;
|
|
988
|
+
const days = Math.floor(hours / 24);
|
|
989
|
+
if (days < 30) return `${days}d`;
|
|
990
|
+
const months = Math.floor(days / 30);
|
|
991
|
+
return `${months}mo`;
|
|
992
|
+
}
|
|
993
|
+
function normalizeSession(item) {
|
|
994
|
+
if (isFullSession(item)) {
|
|
995
|
+
return {
|
|
996
|
+
id: item.id,
|
|
997
|
+
title: item.title,
|
|
998
|
+
status: item.status,
|
|
999
|
+
messageCount: item.metadata?.messageCount ?? item.messages.length,
|
|
1000
|
+
lastMessage: item.messages[item.messages.length - 1],
|
|
1001
|
+
createdAt: item.createdAt,
|
|
1002
|
+
updatedAt: item.updatedAt
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
return item;
|
|
1006
|
+
}
|
|
1007
|
+
function ThreadList({
|
|
1008
|
+
sessions,
|
|
1009
|
+
activeSessionId,
|
|
1010
|
+
onSelect,
|
|
1011
|
+
onCreate,
|
|
1012
|
+
onDelete,
|
|
1013
|
+
searchQuery,
|
|
1014
|
+
onSearchChange,
|
|
1015
|
+
className
|
|
1016
|
+
}) {
|
|
1017
|
+
const handleSearchChange = useCallback(
|
|
1018
|
+
(e) => {
|
|
1019
|
+
onSearchChange?.(e.target.value);
|
|
1020
|
+
},
|
|
1021
|
+
[onSearchChange]
|
|
1022
|
+
);
|
|
1023
|
+
const normalized = useMemo(() => sessions.map(normalizeSession), [sessions]);
|
|
1024
|
+
const filtered = useMemo(() => {
|
|
1025
|
+
if (!searchQuery) return normalized;
|
|
1026
|
+
const q = searchQuery.toLowerCase();
|
|
1027
|
+
return normalized.filter((s) => (s.title ?? "").toLowerCase().includes(q));
|
|
1028
|
+
}, [normalized, searchQuery]);
|
|
1029
|
+
const children = [];
|
|
1030
|
+
children.push(
|
|
1031
|
+
createElement(
|
|
1032
|
+
"div",
|
|
1033
|
+
{ key: "header", "data-thread-list-header": "true" },
|
|
1034
|
+
createElement("input", {
|
|
1035
|
+
"data-thread-list-search": "true",
|
|
1036
|
+
value: searchQuery ?? "",
|
|
1037
|
+
onChange: handleSearchChange,
|
|
1038
|
+
placeholder: "Search..."
|
|
1039
|
+
}),
|
|
1040
|
+
createElement(
|
|
1041
|
+
"button",
|
|
1042
|
+
{
|
|
1043
|
+
"data-action": "create-session",
|
|
1044
|
+
onClick: onCreate,
|
|
1045
|
+
type: "button"
|
|
1046
|
+
},
|
|
1047
|
+
"+"
|
|
1048
|
+
)
|
|
1049
|
+
)
|
|
1050
|
+
);
|
|
1051
|
+
const items = filtered.map((session) => {
|
|
1052
|
+
const isActive = session.id === activeSessionId;
|
|
1053
|
+
const itemChildren = [
|
|
1054
|
+
createElement("span", { key: "title", "data-session-title": "true" }, session.title ?? "Untitled")
|
|
1055
|
+
];
|
|
1056
|
+
if (session.updatedAt) {
|
|
1057
|
+
const timeStr = formatRelativeTime(new Date(session.updatedAt));
|
|
1058
|
+
itemChildren.push(
|
|
1059
|
+
createElement("span", { key: "time", "data-session-time": "true" }, timeStr)
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
if (onDelete) {
|
|
1063
|
+
itemChildren.push(
|
|
1064
|
+
createElement(
|
|
1065
|
+
"button",
|
|
1066
|
+
{
|
|
1067
|
+
key: "delete",
|
|
1068
|
+
"data-action": "delete-session",
|
|
1069
|
+
onClick: (e) => {
|
|
1070
|
+
e.stopPropagation();
|
|
1071
|
+
onDelete(session.id);
|
|
1072
|
+
},
|
|
1073
|
+
type: "button"
|
|
1074
|
+
},
|
|
1075
|
+
"\xD7"
|
|
1076
|
+
)
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
return createElement(
|
|
1080
|
+
"div",
|
|
1081
|
+
{
|
|
1082
|
+
key: session.id,
|
|
1083
|
+
"data-session-item": "true",
|
|
1084
|
+
"data-session-active": isActive ? "true" : "false",
|
|
1085
|
+
"data-session-status": session.status ?? "active",
|
|
1086
|
+
onClick: () => onSelect(session.id)
|
|
1087
|
+
},
|
|
1088
|
+
...itemChildren
|
|
1089
|
+
);
|
|
1090
|
+
});
|
|
1091
|
+
children.push(
|
|
1092
|
+
createElement(
|
|
1093
|
+
"div",
|
|
1094
|
+
{ key: "items", "data-thread-list-items": "true" },
|
|
1095
|
+
...items
|
|
1096
|
+
)
|
|
1097
|
+
);
|
|
1098
|
+
return createElement(
|
|
1099
|
+
"div",
|
|
1100
|
+
{ "data-thread-list": "true", className },
|
|
1101
|
+
...children
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
function useSSE(url, options = {}) {
|
|
1105
|
+
const [status, setStatus] = useState(url === null ? "idle" : "idle");
|
|
1106
|
+
const [lastEvent, setLastEvent] = useState(null);
|
|
1107
|
+
const abortRef = useRef(null);
|
|
1108
|
+
const reconnectTimerRef = useRef(null);
|
|
1109
|
+
const optionsRef = useRef(options);
|
|
1110
|
+
optionsRef.current = options;
|
|
1111
|
+
const disconnect = useCallback(() => {
|
|
1112
|
+
if (reconnectTimerRef.current !== null) {
|
|
1113
|
+
clearTimeout(reconnectTimerRef.current);
|
|
1114
|
+
reconnectTimerRef.current = null;
|
|
1115
|
+
}
|
|
1116
|
+
if (abortRef.current) {
|
|
1117
|
+
abortRef.current.abort();
|
|
1118
|
+
abortRef.current = null;
|
|
1119
|
+
}
|
|
1120
|
+
setStatus("closed");
|
|
1121
|
+
}, []);
|
|
1122
|
+
const connect = useCallback(() => {
|
|
1123
|
+
if (!url) return;
|
|
1124
|
+
if (reconnectTimerRef.current !== null) {
|
|
1125
|
+
clearTimeout(reconnectTimerRef.current);
|
|
1126
|
+
reconnectTimerRef.current = null;
|
|
1127
|
+
}
|
|
1128
|
+
if (abortRef.current) {
|
|
1129
|
+
abortRef.current.abort();
|
|
1130
|
+
}
|
|
1131
|
+
const controller = new AbortController();
|
|
1132
|
+
abortRef.current = controller;
|
|
1133
|
+
setStatus("connecting");
|
|
1134
|
+
(async () => {
|
|
1135
|
+
try {
|
|
1136
|
+
const fetchInit = {
|
|
1137
|
+
method: optionsRef.current.method ?? "GET",
|
|
1138
|
+
headers: {
|
|
1139
|
+
Accept: "text/event-stream",
|
|
1140
|
+
...optionsRef.current.headers
|
|
1141
|
+
},
|
|
1142
|
+
signal: controller.signal
|
|
1143
|
+
};
|
|
1144
|
+
if (fetchInit.method === "POST" && optionsRef.current.body !== void 0) {
|
|
1145
|
+
fetchInit.headers["Content-Type"] = "application/json";
|
|
1146
|
+
fetchInit.body = JSON.stringify(optionsRef.current.body);
|
|
1147
|
+
}
|
|
1148
|
+
const response = await fetch(url, fetchInit);
|
|
1149
|
+
if (!response.ok) {
|
|
1150
|
+
throw new Error(`SSE request failed: ${response.status}`);
|
|
1151
|
+
}
|
|
1152
|
+
if (!response.body) {
|
|
1153
|
+
throw new Error("SSE response has no body");
|
|
1154
|
+
}
|
|
1155
|
+
setStatus("open");
|
|
1156
|
+
const reader = response.body.getReader();
|
|
1157
|
+
const decoder = new TextDecoder();
|
|
1158
|
+
let buffer = "";
|
|
1159
|
+
let dataLines = [];
|
|
1160
|
+
const dispatchEvent = () => {
|
|
1161
|
+
if (dataLines.length === 0) return;
|
|
1162
|
+
const data = dataLines.join("\n");
|
|
1163
|
+
dataLines = [];
|
|
1164
|
+
try {
|
|
1165
|
+
const parsed = JSON.parse(data);
|
|
1166
|
+
setLastEvent(parsed);
|
|
1167
|
+
optionsRef.current.onEvent?.(parsed);
|
|
1168
|
+
} catch {
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
while (true) {
|
|
1172
|
+
const { done, value } = await reader.read();
|
|
1173
|
+
if (done) break;
|
|
1174
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1175
|
+
const lines = buffer.split("\n");
|
|
1176
|
+
buffer = lines.pop();
|
|
1177
|
+
for (const line of lines) {
|
|
1178
|
+
if (line === "") {
|
|
1179
|
+
dispatchEvent();
|
|
1180
|
+
} else if (line.startsWith("data:")) {
|
|
1181
|
+
dataLines.push(line.slice(5).trimStart());
|
|
1182
|
+
} else if (line.startsWith("event:")) {
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (dataLines.length > 0) {
|
|
1187
|
+
dispatchEvent();
|
|
1188
|
+
}
|
|
1189
|
+
if (!controller.signal.aborted) {
|
|
1190
|
+
setStatus("closed");
|
|
1191
|
+
}
|
|
1192
|
+
} catch (err) {
|
|
1193
|
+
if (controller.signal.aborted) return;
|
|
1194
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
1195
|
+
setStatus("error");
|
|
1196
|
+
optionsRef.current.onError?.(error);
|
|
1197
|
+
if (optionsRef.current.reconnect && !controller.signal.aborted) {
|
|
1198
|
+
const delay = optionsRef.current.reconnectInterval ?? 3e3;
|
|
1199
|
+
reconnectTimerRef.current = setTimeout(() => {
|
|
1200
|
+
if (abortRef.current && !abortRef.current.signal.aborted) {
|
|
1201
|
+
connect();
|
|
1202
|
+
}
|
|
1203
|
+
}, delay);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
})();
|
|
1207
|
+
}, [url]);
|
|
1208
|
+
useEffect(() => {
|
|
1209
|
+
return () => {
|
|
1210
|
+
if (reconnectTimerRef.current !== null) {
|
|
1211
|
+
clearTimeout(reconnectTimerRef.current);
|
|
1212
|
+
reconnectTimerRef.current = null;
|
|
1213
|
+
}
|
|
1214
|
+
if (abortRef.current) {
|
|
1215
|
+
abortRef.current.abort();
|
|
1216
|
+
abortRef.current = null;
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
}, []);
|
|
1220
|
+
return { status, connect, disconnect, lastEvent };
|
|
1221
|
+
}
|
|
1222
|
+
function useModels() {
|
|
1223
|
+
const runtime = useChatRuntime();
|
|
1224
|
+
const [models, setModels] = useState([]);
|
|
1225
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
1226
|
+
const [error, setError] = useState(null);
|
|
1227
|
+
const mountedRef = useRef(true);
|
|
1228
|
+
const fetchModels = useCallback(async () => {
|
|
1229
|
+
setIsLoading(true);
|
|
1230
|
+
setError(null);
|
|
1231
|
+
try {
|
|
1232
|
+
const result = await runtime.listModels();
|
|
1233
|
+
if (!mountedRef.current) return;
|
|
1234
|
+
const mapped = result.map((m) => ({
|
|
1235
|
+
id: m.id,
|
|
1236
|
+
name: m.name ?? m.id,
|
|
1237
|
+
tier: m.provider,
|
|
1238
|
+
provider: m.provider
|
|
1239
|
+
}));
|
|
1240
|
+
setModels(mapped);
|
|
1241
|
+
} catch (err) {
|
|
1242
|
+
if (!mountedRef.current) return;
|
|
1243
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
1244
|
+
} finally {
|
|
1245
|
+
if (mountedRef.current) {
|
|
1246
|
+
setIsLoading(false);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
}, [runtime]);
|
|
1250
|
+
useEffect(() => {
|
|
1251
|
+
mountedRef.current = true;
|
|
1252
|
+
fetchModels();
|
|
1253
|
+
return () => {
|
|
1254
|
+
mountedRef.current = false;
|
|
1255
|
+
};
|
|
1256
|
+
}, [fetchModels]);
|
|
1257
|
+
const search = useCallback(
|
|
1258
|
+
(query) => {
|
|
1259
|
+
const q = query.toLowerCase();
|
|
1260
|
+
return models.filter((m) => m.name.toLowerCase().includes(q));
|
|
1261
|
+
},
|
|
1262
|
+
[models]
|
|
1263
|
+
);
|
|
1264
|
+
return { models, isLoading, error, refresh: fetchModels, search };
|
|
1265
|
+
}
|
|
1266
|
+
function ModelSelector({
|
|
1267
|
+
models,
|
|
1268
|
+
selectedModel,
|
|
1269
|
+
onSelect,
|
|
1270
|
+
placeholder = "Select model",
|
|
1271
|
+
className,
|
|
1272
|
+
allowFreeText = true
|
|
1273
|
+
}) {
|
|
1274
|
+
const [open, setOpen] = useState(false);
|
|
1275
|
+
const [search, setSearch] = useState("");
|
|
1276
|
+
const [highlightIndex, setHighlightIndex] = useState(0);
|
|
1277
|
+
const [freeText, setFreeText] = useState(selectedModel ?? "");
|
|
1278
|
+
const containerRef = useRef(null);
|
|
1279
|
+
const filtered = useMemo(() => {
|
|
1280
|
+
if (!search) return models;
|
|
1281
|
+
const q = search.toLowerCase();
|
|
1282
|
+
return models.filter((m) => m.name.toLowerCase().includes(q));
|
|
1283
|
+
}, [models, search]);
|
|
1284
|
+
useEffect(() => {
|
|
1285
|
+
setHighlightIndex(0);
|
|
1286
|
+
}, [filtered.length]);
|
|
1287
|
+
const selectedInfo = useMemo(
|
|
1288
|
+
() => models.find((m) => m.id === selectedModel),
|
|
1289
|
+
[models, selectedModel]
|
|
1290
|
+
);
|
|
1291
|
+
const handleToggle = useCallback(() => {
|
|
1292
|
+
setOpen((prev) => {
|
|
1293
|
+
if (!prev) {
|
|
1294
|
+
setSearch("");
|
|
1295
|
+
setHighlightIndex(0);
|
|
1296
|
+
}
|
|
1297
|
+
return !prev;
|
|
1298
|
+
});
|
|
1299
|
+
}, []);
|
|
1300
|
+
const handleSelect = useCallback(
|
|
1301
|
+
(modelId) => {
|
|
1302
|
+
onSelect(modelId);
|
|
1303
|
+
setOpen(false);
|
|
1304
|
+
setSearch("");
|
|
1305
|
+
},
|
|
1306
|
+
[onSelect]
|
|
1307
|
+
);
|
|
1308
|
+
const handleSearchChange = useCallback((e) => {
|
|
1309
|
+
setSearch(e.target.value);
|
|
1310
|
+
}, []);
|
|
1311
|
+
const handleKeyDown = useCallback(
|
|
1312
|
+
(e) => {
|
|
1313
|
+
if (e.key === "ArrowDown") {
|
|
1314
|
+
e.preventDefault();
|
|
1315
|
+
setHighlightIndex((prev) => Math.min(prev + 1, filtered.length - 1));
|
|
1316
|
+
} else if (e.key === "ArrowUp") {
|
|
1317
|
+
e.preventDefault();
|
|
1318
|
+
setHighlightIndex((prev) => Math.max(prev - 1, 0));
|
|
1319
|
+
} else if (e.key === "Enter") {
|
|
1320
|
+
e.preventDefault();
|
|
1321
|
+
if (filtered[highlightIndex]) {
|
|
1322
|
+
handleSelect(filtered[highlightIndex].id);
|
|
1323
|
+
}
|
|
1324
|
+
} else if (e.key === "Escape") {
|
|
1325
|
+
e.preventDefault();
|
|
1326
|
+
setOpen(false);
|
|
1327
|
+
}
|
|
1328
|
+
},
|
|
1329
|
+
[filtered, highlightIndex, handleSelect]
|
|
1330
|
+
);
|
|
1331
|
+
if (models.length === 0 && allowFreeText) {
|
|
1332
|
+
return createElement(
|
|
1333
|
+
"div",
|
|
1334
|
+
{
|
|
1335
|
+
"data-model-selector": "true",
|
|
1336
|
+
"data-model-selector-freetext": "true",
|
|
1337
|
+
className,
|
|
1338
|
+
ref: containerRef
|
|
1339
|
+
},
|
|
1340
|
+
createElement("input", {
|
|
1341
|
+
"data-model-input": "true",
|
|
1342
|
+
value: freeText,
|
|
1343
|
+
placeholder: "Enter model name...",
|
|
1344
|
+
onChange: (e) => setFreeText(e.target.value),
|
|
1345
|
+
onKeyDown: (e) => {
|
|
1346
|
+
if (e.key === "Enter") {
|
|
1347
|
+
e.preventDefault();
|
|
1348
|
+
const val = freeText.trim();
|
|
1349
|
+
if (val) onSelect(val);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}),
|
|
1353
|
+
createElement(
|
|
1354
|
+
"button",
|
|
1355
|
+
{
|
|
1356
|
+
type: "button",
|
|
1357
|
+
"data-action": "apply-model",
|
|
1358
|
+
onClick: () => {
|
|
1359
|
+
const val = freeText.trim();
|
|
1360
|
+
if (val) onSelect(val);
|
|
1361
|
+
}
|
|
1362
|
+
},
|
|
1363
|
+
"Apply"
|
|
1364
|
+
)
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
const children = [];
|
|
1368
|
+
children.push(
|
|
1369
|
+
createElement(
|
|
1370
|
+
"button",
|
|
1371
|
+
{
|
|
1372
|
+
key: "trigger",
|
|
1373
|
+
"data-model-selector-trigger": "true",
|
|
1374
|
+
onClick: handleToggle,
|
|
1375
|
+
type: "button"
|
|
1376
|
+
},
|
|
1377
|
+
selectedInfo ? selectedInfo.name : placeholder
|
|
1378
|
+
)
|
|
1379
|
+
);
|
|
1380
|
+
if (open) {
|
|
1381
|
+
const dropdownChildren = [];
|
|
1382
|
+
dropdownChildren.push(
|
|
1383
|
+
createElement("input", {
|
|
1384
|
+
key: "search",
|
|
1385
|
+
"data-model-selector-search": "true",
|
|
1386
|
+
value: search,
|
|
1387
|
+
onChange: handleSearchChange,
|
|
1388
|
+
onKeyDown: handleKeyDown,
|
|
1389
|
+
placeholder: "Search models...",
|
|
1390
|
+
autoFocus: true
|
|
1391
|
+
})
|
|
1392
|
+
);
|
|
1393
|
+
const hasMultipleProviders = new Set(filtered.map((m) => m.provider).filter(Boolean)).size > 1;
|
|
1394
|
+
filtered.forEach((model, idx) => {
|
|
1395
|
+
const isSelected = model.id === selectedModel;
|
|
1396
|
+
const isHighlighted = idx === highlightIndex;
|
|
1397
|
+
const attrs = {
|
|
1398
|
+
key: model.id,
|
|
1399
|
+
"data-model-option": "true",
|
|
1400
|
+
onClick: () => handleSelect(model.id)
|
|
1401
|
+
};
|
|
1402
|
+
if (model.tier) {
|
|
1403
|
+
attrs["data-tier"] = model.tier;
|
|
1404
|
+
}
|
|
1405
|
+
if (model.provider && hasMultipleProviders) {
|
|
1406
|
+
attrs["data-model-provider"] = model.provider;
|
|
1407
|
+
}
|
|
1408
|
+
if (isSelected) {
|
|
1409
|
+
attrs["data-model-selected"] = "true";
|
|
1410
|
+
}
|
|
1411
|
+
if (isHighlighted) {
|
|
1412
|
+
attrs["data-model-highlighted"] = "true";
|
|
1413
|
+
}
|
|
1414
|
+
const label = model.provider && hasMultipleProviders ? `${model.name} (${model.provider})` : model.name;
|
|
1415
|
+
dropdownChildren.push(createElement("div", attrs, label));
|
|
1416
|
+
});
|
|
1417
|
+
children.push(
|
|
1418
|
+
createElement(
|
|
1419
|
+
"div",
|
|
1420
|
+
{ key: "dropdown", "data-model-selector-dropdown": "true" },
|
|
1421
|
+
...dropdownChildren
|
|
1422
|
+
)
|
|
1423
|
+
);
|
|
1424
|
+
}
|
|
1425
|
+
return createElement(
|
|
1426
|
+
"div",
|
|
1427
|
+
{
|
|
1428
|
+
"data-model-selector": "true",
|
|
1429
|
+
className,
|
|
1430
|
+
ref: containerRef
|
|
1431
|
+
},
|
|
1432
|
+
...children
|
|
1433
|
+
);
|
|
1434
|
+
}
|
|
1435
|
+
function useCopilotAuth(options) {
|
|
1436
|
+
const { baseUrl, headers } = options;
|
|
1437
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1438
|
+
const [status, setStatus] = useState("idle");
|
|
1439
|
+
const [error, setError] = useState(null);
|
|
1440
|
+
const [token, setToken] = useState(null);
|
|
1441
|
+
const [deviceCode, setDeviceCode] = useState(null);
|
|
1442
|
+
const [verificationUrl, setVerificationUrl] = useState(null);
|
|
1443
|
+
const onAuthenticatedRef = useRef(options.onAuthenticated);
|
|
1444
|
+
onAuthenticatedRef.current = options.onAuthenticated;
|
|
1445
|
+
const onErrorRef = useRef(options.onError);
|
|
1446
|
+
onErrorRef.current = options.onError;
|
|
1447
|
+
const post = useCallback(
|
|
1448
|
+
async (path, body) => {
|
|
1449
|
+
const res = await fetchFn(`${baseUrl}${path}`, {
|
|
1450
|
+
method: "POST",
|
|
1451
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
1452
|
+
body: body ? JSON.stringify(body) : void 0
|
|
1453
|
+
});
|
|
1454
|
+
const data = await res.json();
|
|
1455
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
1456
|
+
return data;
|
|
1457
|
+
},
|
|
1458
|
+
[baseUrl, fetchFn, headers]
|
|
1459
|
+
);
|
|
1460
|
+
const start = useCallback(async () => {
|
|
1461
|
+
setStatus("pending");
|
|
1462
|
+
setError(null);
|
|
1463
|
+
try {
|
|
1464
|
+
const result = await post("/auth/start", { provider: "copilot" });
|
|
1465
|
+
setDeviceCode(result.userCode);
|
|
1466
|
+
setVerificationUrl(result.verificationUrl);
|
|
1467
|
+
await post("/auth/copilot/poll");
|
|
1468
|
+
const authToken = {
|
|
1469
|
+
accessToken: "server-managed",
|
|
1470
|
+
tokenType: "bearer",
|
|
1471
|
+
obtainedAt: Date.now()
|
|
1472
|
+
};
|
|
1473
|
+
setToken(authToken);
|
|
1474
|
+
setStatus("authenticated");
|
|
1475
|
+
onAuthenticatedRef.current?.(authToken);
|
|
1476
|
+
} catch (err) {
|
|
1477
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1478
|
+
setError(e);
|
|
1479
|
+
setStatus("error");
|
|
1480
|
+
onErrorRef.current?.(e);
|
|
1481
|
+
}
|
|
1482
|
+
}, [post]);
|
|
1483
|
+
const reset = useCallback(() => {
|
|
1484
|
+
setStatus("idle");
|
|
1485
|
+
setError(null);
|
|
1486
|
+
setToken(null);
|
|
1487
|
+
setDeviceCode(null);
|
|
1488
|
+
setVerificationUrl(null);
|
|
1489
|
+
}, []);
|
|
1490
|
+
return { status, error, token, deviceCode, verificationUrl, start, reset };
|
|
1491
|
+
}
|
|
1492
|
+
function useClaudeAuth(options) {
|
|
1493
|
+
const { baseUrl, headers } = options;
|
|
1494
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1495
|
+
const [status, setStatus] = useState("idle");
|
|
1496
|
+
const [error, setError] = useState(null);
|
|
1497
|
+
const [token, setToken] = useState(null);
|
|
1498
|
+
const [authorizeUrl, setAuthorizeUrl] = useState(null);
|
|
1499
|
+
const onAuthenticatedRef = useRef(options.onAuthenticated);
|
|
1500
|
+
onAuthenticatedRef.current = options.onAuthenticated;
|
|
1501
|
+
const onErrorRef = useRef(options.onError);
|
|
1502
|
+
onErrorRef.current = options.onError;
|
|
1503
|
+
const post = useCallback(
|
|
1504
|
+
async (path, body) => {
|
|
1505
|
+
const res = await fetchFn(`${baseUrl}${path}`, {
|
|
1506
|
+
method: "POST",
|
|
1507
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
1508
|
+
body: body ? JSON.stringify(body) : void 0
|
|
1509
|
+
});
|
|
1510
|
+
const data = await res.json();
|
|
1511
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
1512
|
+
return data;
|
|
1513
|
+
},
|
|
1514
|
+
[baseUrl, fetchFn, headers]
|
|
1515
|
+
);
|
|
1516
|
+
const start = useCallback(async () => {
|
|
1517
|
+
setStatus("pending");
|
|
1518
|
+
setError(null);
|
|
1519
|
+
try {
|
|
1520
|
+
const result = await post("/auth/start", { provider: "claude" });
|
|
1521
|
+
setAuthorizeUrl(result.authorizeUrl);
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1524
|
+
setError(e);
|
|
1525
|
+
setStatus("error");
|
|
1526
|
+
onErrorRef.current?.(e);
|
|
1527
|
+
}
|
|
1528
|
+
}, [post]);
|
|
1529
|
+
const complete = useCallback(async (codeOrUrl) => {
|
|
1530
|
+
try {
|
|
1531
|
+
await post("/auth/claude/complete", { code: codeOrUrl });
|
|
1532
|
+
const authToken = {
|
|
1533
|
+
accessToken: "server-managed",
|
|
1534
|
+
tokenType: "bearer",
|
|
1535
|
+
obtainedAt: Date.now()
|
|
1536
|
+
};
|
|
1537
|
+
setToken(authToken);
|
|
1538
|
+
setStatus("authenticated");
|
|
1539
|
+
onAuthenticatedRef.current?.(authToken);
|
|
1540
|
+
} catch (err) {
|
|
1541
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1542
|
+
setError(e);
|
|
1543
|
+
setStatus("error");
|
|
1544
|
+
onErrorRef.current?.(e);
|
|
1545
|
+
}
|
|
1546
|
+
}, [post]);
|
|
1547
|
+
const reset = useCallback(() => {
|
|
1548
|
+
setStatus("idle");
|
|
1549
|
+
setError(null);
|
|
1550
|
+
setToken(null);
|
|
1551
|
+
setAuthorizeUrl(null);
|
|
1552
|
+
}, []);
|
|
1553
|
+
return { status, error, token, authorizeUrl, start, complete, reset };
|
|
1554
|
+
}
|
|
1555
|
+
function useApiKeyAuth(options) {
|
|
1556
|
+
const { baseUrl, headers } = options;
|
|
1557
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1558
|
+
const [status, setStatus] = useState("idle");
|
|
1559
|
+
const [error, setError] = useState(null);
|
|
1560
|
+
const [token, setToken] = useState(null);
|
|
1561
|
+
const onAuthenticatedRef = useRef(options.onAuthenticated);
|
|
1562
|
+
onAuthenticatedRef.current = options.onAuthenticated;
|
|
1563
|
+
const onErrorRef = useRef(options.onError);
|
|
1564
|
+
onErrorRef.current = options.onError;
|
|
1565
|
+
const submit = useCallback(async (key, apiBaseUrl) => {
|
|
1566
|
+
if (!key || !key.trim()) {
|
|
1567
|
+
const e = new Error("API key cannot be empty");
|
|
1568
|
+
setError(e);
|
|
1569
|
+
setStatus("error");
|
|
1570
|
+
onErrorRef.current?.(e);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
setStatus("pending");
|
|
1574
|
+
setError(null);
|
|
1575
|
+
try {
|
|
1576
|
+
const res = await fetchFn(`${baseUrl}/auth/vercel/complete`, {
|
|
1577
|
+
method: "POST",
|
|
1578
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
1579
|
+
body: JSON.stringify({
|
|
1580
|
+
apiKey: key.trim(),
|
|
1581
|
+
...apiBaseUrl ? { baseUrl: apiBaseUrl } : {}
|
|
1582
|
+
})
|
|
1583
|
+
});
|
|
1584
|
+
const data = await res.json();
|
|
1585
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
1586
|
+
const authToken = {
|
|
1587
|
+
accessToken: "server-managed",
|
|
1588
|
+
tokenType: "bearer",
|
|
1589
|
+
obtainedAt: Date.now()
|
|
1590
|
+
};
|
|
1591
|
+
setToken(authToken);
|
|
1592
|
+
setStatus("authenticated");
|
|
1593
|
+
onAuthenticatedRef.current?.(authToken);
|
|
1594
|
+
} catch (err) {
|
|
1595
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
1596
|
+
setError(e);
|
|
1597
|
+
setStatus("error");
|
|
1598
|
+
onErrorRef.current?.(e);
|
|
1599
|
+
}
|
|
1600
|
+
}, [baseUrl, fetchFn, headers]);
|
|
1601
|
+
const reset = useCallback(() => {
|
|
1602
|
+
setStatus("idle");
|
|
1603
|
+
setError(null);
|
|
1604
|
+
setToken(null);
|
|
1605
|
+
}, []);
|
|
1606
|
+
return { status, error, token, submit, reset };
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// src/chat/react/useRemoteAuth.ts
|
|
1610
|
+
function useRemoteAuth(options) {
|
|
1611
|
+
const { backend, baseUrl, onAuthenticated, headers } = options;
|
|
1612
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1613
|
+
const [status, setStatus] = useState("idle");
|
|
1614
|
+
const [error, setError] = useState(null);
|
|
1615
|
+
const [token, setToken] = useState(null);
|
|
1616
|
+
const [savedProviders, setSavedProviders] = useState([]);
|
|
1617
|
+
const onAuthenticatedRef = useRef(onAuthenticated);
|
|
1618
|
+
onAuthenticatedRef.current = onAuthenticated;
|
|
1619
|
+
const handleSuccess = useCallback((authToken) => {
|
|
1620
|
+
setToken(authToken);
|
|
1621
|
+
setStatus("authenticated");
|
|
1622
|
+
onAuthenticatedRef.current?.(authToken);
|
|
1623
|
+
}, []);
|
|
1624
|
+
const handleError = useCallback((err) => {
|
|
1625
|
+
setError(err);
|
|
1626
|
+
setStatus("error");
|
|
1627
|
+
}, []);
|
|
1628
|
+
const hookOpts = { baseUrl, headers, fetch: fetchFn, onAuthenticated: handleSuccess, onError: handleError };
|
|
1629
|
+
const copilot = useCopilotAuth(hookOpts);
|
|
1630
|
+
const claude = useClaudeAuth(hookOpts);
|
|
1631
|
+
const apiKey = useApiKeyAuth(hookOpts);
|
|
1632
|
+
const post = useCallback(
|
|
1633
|
+
async (path, body) => {
|
|
1634
|
+
const res = await fetchFn(`${baseUrl}${path}`, {
|
|
1635
|
+
method: "POST",
|
|
1636
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
1637
|
+
body: body ? JSON.stringify(body) : void 0
|
|
1638
|
+
});
|
|
1639
|
+
const data = await res.json();
|
|
1640
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
1641
|
+
return data;
|
|
1642
|
+
},
|
|
1643
|
+
[baseUrl, fetchFn, headers]
|
|
1644
|
+
);
|
|
1645
|
+
const get = useCallback(
|
|
1646
|
+
async (path) => {
|
|
1647
|
+
const res = await fetchFn(`${baseUrl}${path}`, {
|
|
1648
|
+
method: "GET",
|
|
1649
|
+
headers: { ...headers }
|
|
1650
|
+
});
|
|
1651
|
+
const data = await res.json();
|
|
1652
|
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
1653
|
+
return data;
|
|
1654
|
+
},
|
|
1655
|
+
[baseUrl, fetchFn, headers]
|
|
1656
|
+
);
|
|
1657
|
+
const startDeviceFlow = useCallback(async () => {
|
|
1658
|
+
if (backend !== "copilot") return;
|
|
1659
|
+
setStatus("pending");
|
|
1660
|
+
setError(null);
|
|
1661
|
+
await copilot.start();
|
|
1662
|
+
}, [backend, copilot]);
|
|
1663
|
+
const startOAuthFlow = useCallback(async () => {
|
|
1664
|
+
if (backend !== "claude") return;
|
|
1665
|
+
setStatus("pending");
|
|
1666
|
+
setError(null);
|
|
1667
|
+
await claude.start();
|
|
1668
|
+
}, [backend, claude]);
|
|
1669
|
+
const completeOAuth = useCallback(
|
|
1670
|
+
async (codeOrUrl) => {
|
|
1671
|
+
await claude.complete(codeOrUrl);
|
|
1672
|
+
},
|
|
1673
|
+
[claude]
|
|
1674
|
+
);
|
|
1675
|
+
const submitApiKey = useCallback(
|
|
1676
|
+
async (key, apiBaseUrl) => {
|
|
1677
|
+
if (backend !== "vercel-ai") return;
|
|
1678
|
+
await apiKey.submit(key, apiBaseUrl);
|
|
1679
|
+
},
|
|
1680
|
+
[backend, apiKey]
|
|
1681
|
+
);
|
|
1682
|
+
const loadSavedTokens = useCallback(async () => {
|
|
1683
|
+
try {
|
|
1684
|
+
const data = await get("/tokens/saved");
|
|
1685
|
+
setSavedProviders(data.saved || []);
|
|
1686
|
+
} catch {
|
|
1687
|
+
}
|
|
1688
|
+
}, [get]);
|
|
1689
|
+
const useSavedToken = useCallback(
|
|
1690
|
+
async (provider) => {
|
|
1691
|
+
try {
|
|
1692
|
+
await post("/tokens/use", { provider });
|
|
1693
|
+
const authToken = {
|
|
1694
|
+
accessToken: "server-managed",
|
|
1695
|
+
tokenType: "bearer",
|
|
1696
|
+
obtainedAt: Date.now()
|
|
1697
|
+
};
|
|
1698
|
+
setToken(authToken);
|
|
1699
|
+
setStatus("authenticated");
|
|
1700
|
+
onAuthenticatedRef.current?.(authToken);
|
|
1701
|
+
} catch (err) {
|
|
1702
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
1703
|
+
setStatus("error");
|
|
1704
|
+
}
|
|
1705
|
+
},
|
|
1706
|
+
[post]
|
|
1707
|
+
);
|
|
1708
|
+
const clearTokens = useCallback(async () => {
|
|
1709
|
+
try {
|
|
1710
|
+
await post("/tokens/clear");
|
|
1711
|
+
setSavedProviders([]);
|
|
1712
|
+
} catch {
|
|
1713
|
+
}
|
|
1714
|
+
}, [post]);
|
|
1715
|
+
const reset = useCallback(() => {
|
|
1716
|
+
setStatus("idle");
|
|
1717
|
+
setError(null);
|
|
1718
|
+
setToken(null);
|
|
1719
|
+
copilot.reset();
|
|
1720
|
+
claude.reset();
|
|
1721
|
+
apiKey.reset();
|
|
1722
|
+
setSavedProviders([]);
|
|
1723
|
+
}, [copilot, claude, apiKey]);
|
|
1724
|
+
const start = useCallback(async (provider) => {
|
|
1725
|
+
const target = provider ?? backend;
|
|
1726
|
+
setStatus("pending");
|
|
1727
|
+
setError(null);
|
|
1728
|
+
switch (target) {
|
|
1729
|
+
case "copilot":
|
|
1730
|
+
await copilot.start();
|
|
1731
|
+
break;
|
|
1732
|
+
case "claude":
|
|
1733
|
+
await claude.start();
|
|
1734
|
+
break;
|
|
1735
|
+
case "vercel-ai": {
|
|
1736
|
+
const e = new Error("vercel-ai requires submitApiKey(key, baseUrl) \u2014 cannot auto-start");
|
|
1737
|
+
setError(e);
|
|
1738
|
+
setStatus("error");
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
default: {
|
|
1742
|
+
const e = new Error(`Unknown auth provider: ${target}`);
|
|
1743
|
+
setError(e);
|
|
1744
|
+
setStatus("error");
|
|
1745
|
+
return;
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
}, [backend, copilot, claude]);
|
|
1749
|
+
return {
|
|
1750
|
+
status,
|
|
1751
|
+
error,
|
|
1752
|
+
startDeviceFlow,
|
|
1753
|
+
deviceCode: copilot.deviceCode,
|
|
1754
|
+
verificationUrl: copilot.verificationUrl,
|
|
1755
|
+
startOAuthFlow,
|
|
1756
|
+
authorizeUrl: claude.authorizeUrl,
|
|
1757
|
+
completeOAuth,
|
|
1758
|
+
submitApiKey,
|
|
1759
|
+
start,
|
|
1760
|
+
token,
|
|
1761
|
+
reset,
|
|
1762
|
+
savedProviders,
|
|
1763
|
+
loadSavedTokens,
|
|
1764
|
+
useSavedToken,
|
|
1765
|
+
clearTokens
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
// src/chat/listener-set.ts
|
|
1770
|
+
var ListenerSet = class {
|
|
1771
|
+
_listeners = /* @__PURE__ */ new Set();
|
|
1772
|
+
/** Add a listener. Returns an unsubscribe function. */
|
|
1773
|
+
add(callback) {
|
|
1774
|
+
this._listeners.add(callback);
|
|
1775
|
+
return () => {
|
|
1776
|
+
this._listeners.delete(callback);
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
/** Notify all listeners with the given arguments. Errors are isolated per listener. */
|
|
1780
|
+
notify(...args) {
|
|
1781
|
+
for (const cb of this._listeners) {
|
|
1782
|
+
try {
|
|
1783
|
+
cb(...args);
|
|
1784
|
+
} catch {
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
/** Remove all listeners. */
|
|
1789
|
+
clear() {
|
|
1790
|
+
this._listeners.clear();
|
|
1791
|
+
}
|
|
1792
|
+
/** Current number of listeners. */
|
|
1793
|
+
get size() {
|
|
1794
|
+
return this._listeners.size;
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
|
|
1798
|
+
// src/chat/react/RemoteChatClient.ts
|
|
1799
|
+
var RemoteChatClient = class {
|
|
1800
|
+
_status = "idle";
|
|
1801
|
+
_activeSessionId = null;
|
|
1802
|
+
_selectedProviderId = null;
|
|
1803
|
+
_abortController = null;
|
|
1804
|
+
baseUrl;
|
|
1805
|
+
headers;
|
|
1806
|
+
_fetch;
|
|
1807
|
+
_selectionListeners = new ListenerSet();
|
|
1808
|
+
constructor(options) {
|
|
1809
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
1810
|
+
this.headers = options.headers ?? {};
|
|
1811
|
+
this._fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
1812
|
+
}
|
|
1813
|
+
// ─── Lifecycle ──────────────────────────────────────────────
|
|
1814
|
+
get status() {
|
|
1815
|
+
return this._status;
|
|
1816
|
+
}
|
|
1817
|
+
async dispose() {
|
|
1818
|
+
this.abort();
|
|
1819
|
+
this._status = "disposed";
|
|
1820
|
+
}
|
|
1821
|
+
assertNotDisposed() {
|
|
1822
|
+
if (this._status === "disposed") {
|
|
1823
|
+
throw new Error("Runtime is disposed");
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
// ─── Provider Selection ────────────────────────────────────
|
|
1827
|
+
get selectedProviderId() {
|
|
1828
|
+
return this._selectedProviderId;
|
|
1829
|
+
}
|
|
1830
|
+
selectProvider(providerId) {
|
|
1831
|
+
this.assertNotDisposed();
|
|
1832
|
+
this._selectedProviderId = providerId;
|
|
1833
|
+
this._notifySelectionChange(providerId);
|
|
1834
|
+
}
|
|
1835
|
+
onSelectionChange(callback) {
|
|
1836
|
+
return this._selectionListeners.add(callback);
|
|
1837
|
+
}
|
|
1838
|
+
_notifySelectionChange(providerId) {
|
|
1839
|
+
this._selectionListeners.notify(providerId);
|
|
1840
|
+
}
|
|
1841
|
+
// ─── Sessions ───────────────────────────────────────────────
|
|
1842
|
+
get activeSessionId() {
|
|
1843
|
+
return this._activeSessionId;
|
|
1844
|
+
}
|
|
1845
|
+
async createSession(options) {
|
|
1846
|
+
this.assertNotDisposed();
|
|
1847
|
+
const res = await this._post("/sessions/create", options);
|
|
1848
|
+
const session = await res.json();
|
|
1849
|
+
this._activeSessionId = session.id;
|
|
1850
|
+
this._notifySessionChange();
|
|
1851
|
+
return session;
|
|
1852
|
+
}
|
|
1853
|
+
async getSession(id) {
|
|
1854
|
+
this.assertNotDisposed();
|
|
1855
|
+
const res = await this._get(`/sessions/${id}`);
|
|
1856
|
+
if (res.status === 404) return null;
|
|
1857
|
+
return await res.json();
|
|
1858
|
+
}
|
|
1859
|
+
async listSessions(_options) {
|
|
1860
|
+
this.assertNotDisposed();
|
|
1861
|
+
const res = await this._get("/sessions");
|
|
1862
|
+
return await res.json();
|
|
1863
|
+
}
|
|
1864
|
+
async deleteSession(id) {
|
|
1865
|
+
this.assertNotDisposed();
|
|
1866
|
+
await this._delete(`/sessions/${id}`);
|
|
1867
|
+
if (this._activeSessionId === id) {
|
|
1868
|
+
this._activeSessionId = null;
|
|
1869
|
+
}
|
|
1870
|
+
this._notifySessionChange();
|
|
1871
|
+
}
|
|
1872
|
+
/**
|
|
1873
|
+
* Fetch context window stats from server.
|
|
1874
|
+
* Returns null if stats not available (e.g. no messages sent yet).
|
|
1875
|
+
*/
|
|
1876
|
+
async getContextStats(sessionId) {
|
|
1877
|
+
this.assertNotDisposed();
|
|
1878
|
+
const res = await this._get(`/sessions/${sessionId}/context-stats`);
|
|
1879
|
+
const data = await res.json();
|
|
1880
|
+
return data;
|
|
1881
|
+
}
|
|
1882
|
+
async switchSession(id) {
|
|
1883
|
+
this.assertNotDisposed();
|
|
1884
|
+
const session = await this.getSession(id);
|
|
1885
|
+
if (!session) throw new Error(`Session not found: ${id}`);
|
|
1886
|
+
this._activeSessionId = session.id;
|
|
1887
|
+
this._notifySessionChange();
|
|
1888
|
+
return session;
|
|
1889
|
+
}
|
|
1890
|
+
// ─── Messaging ──────────────────────────────────────────────
|
|
1891
|
+
async *send(sessionId, message, options) {
|
|
1892
|
+
this.assertNotDisposed();
|
|
1893
|
+
this._status = "streaming";
|
|
1894
|
+
this._abortController = new AbortController();
|
|
1895
|
+
try {
|
|
1896
|
+
const res = await this._fetch(`${this.baseUrl}/send`, {
|
|
1897
|
+
method: "POST",
|
|
1898
|
+
headers: {
|
|
1899
|
+
"Content-Type": "application/json",
|
|
1900
|
+
Accept: "text/event-stream",
|
|
1901
|
+
...this.headers
|
|
1902
|
+
},
|
|
1903
|
+
body: JSON.stringify({
|
|
1904
|
+
sessionId,
|
|
1905
|
+
message,
|
|
1906
|
+
model: options?.model,
|
|
1907
|
+
providerId: this._selectedProviderId ?? void 0
|
|
1908
|
+
}),
|
|
1909
|
+
signal: this._abortController.signal
|
|
1910
|
+
});
|
|
1911
|
+
if (!res.ok) {
|
|
1912
|
+
throw new Error(`Send failed: ${res.status} ${res.statusText}`);
|
|
1913
|
+
}
|
|
1914
|
+
if (!res.body) {
|
|
1915
|
+
throw new Error("No response body for SSE stream");
|
|
1916
|
+
}
|
|
1917
|
+
yield* this._parseSSEStream(res.body, this._abortController.signal);
|
|
1918
|
+
} catch (err) {
|
|
1919
|
+
if (err instanceof DOMException && err.name === "AbortError") ; else {
|
|
1920
|
+
this._status = "error";
|
|
1921
|
+
throw err;
|
|
1922
|
+
}
|
|
1923
|
+
} finally {
|
|
1924
|
+
this._abortController = null;
|
|
1925
|
+
if (this._status === "streaming") {
|
|
1926
|
+
this._status = "idle";
|
|
1927
|
+
}
|
|
1928
|
+
this._notifySessionChange();
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
abort() {
|
|
1932
|
+
if (this._abortController) {
|
|
1933
|
+
this._abortController.abort();
|
|
1934
|
+
this._abortController = null;
|
|
1935
|
+
}
|
|
1936
|
+
if (this._status === "streaming") {
|
|
1937
|
+
this._status = "idle";
|
|
1938
|
+
}
|
|
1939
|
+
this._post("/abort", {}).catch(() => {
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
// ─── Discovery ─────────────────────────────────────────────
|
|
1943
|
+
async listModels() {
|
|
1944
|
+
this.assertNotDisposed();
|
|
1945
|
+
const res = await this._get("/models");
|
|
1946
|
+
return await res.json();
|
|
1947
|
+
}
|
|
1948
|
+
async listBackends() {
|
|
1949
|
+
this.assertNotDisposed();
|
|
1950
|
+
const res = await this._get("/backends");
|
|
1951
|
+
return await res.json();
|
|
1952
|
+
}
|
|
1953
|
+
// ─── Providers ──────────────────────────────────────────────
|
|
1954
|
+
async listProviders() {
|
|
1955
|
+
this.assertNotDisposed();
|
|
1956
|
+
const res = await this._get("/providers");
|
|
1957
|
+
return await res.json();
|
|
1958
|
+
}
|
|
1959
|
+
async createProvider(config) {
|
|
1960
|
+
this.assertNotDisposed();
|
|
1961
|
+
const res = await this._post("/providers", config);
|
|
1962
|
+
return await res.json();
|
|
1963
|
+
}
|
|
1964
|
+
async updateProvider(id, changes) {
|
|
1965
|
+
this.assertNotDisposed();
|
|
1966
|
+
await this._put(`/providers/${id}`, changes);
|
|
1967
|
+
}
|
|
1968
|
+
async deleteProvider(id) {
|
|
1969
|
+
this.assertNotDisposed();
|
|
1970
|
+
await this._delete(`/providers/${id}`);
|
|
1971
|
+
}
|
|
1972
|
+
// ─── Session Change Notifications ────────────────────────────
|
|
1973
|
+
_sessionListeners = new ListenerSet();
|
|
1974
|
+
onSessionChange(callback) {
|
|
1975
|
+
return this._sessionListeners.add(callback);
|
|
1976
|
+
}
|
|
1977
|
+
_notifySessionChange() {
|
|
1978
|
+
this._sessionListeners.notify();
|
|
1979
|
+
}
|
|
1980
|
+
// ─── Internal HTTP helpers ──────────────────────────────────
|
|
1981
|
+
async _get(path) {
|
|
1982
|
+
const res = await this._fetch(`${this.baseUrl}${path}`, {
|
|
1983
|
+
method: "GET",
|
|
1984
|
+
headers: { ...this.headers }
|
|
1985
|
+
});
|
|
1986
|
+
if (!res.ok && res.status !== 404) {
|
|
1987
|
+
throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);
|
|
1988
|
+
}
|
|
1989
|
+
return res;
|
|
1990
|
+
}
|
|
1991
|
+
async _post(path, body) {
|
|
1992
|
+
const res = await this._fetch(`${this.baseUrl}${path}`, {
|
|
1993
|
+
method: "POST",
|
|
1994
|
+
headers: {
|
|
1995
|
+
"Content-Type": "application/json",
|
|
1996
|
+
...this.headers
|
|
1997
|
+
},
|
|
1998
|
+
body: JSON.stringify(body)
|
|
1999
|
+
});
|
|
2000
|
+
if (!res.ok) {
|
|
2001
|
+
throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);
|
|
2002
|
+
}
|
|
2003
|
+
return res;
|
|
2004
|
+
}
|
|
2005
|
+
async _delete(path) {
|
|
2006
|
+
const res = await this._fetch(`${this.baseUrl}${path}`, {
|
|
2007
|
+
method: "DELETE",
|
|
2008
|
+
headers: { ...this.headers }
|
|
2009
|
+
});
|
|
2010
|
+
if (!res.ok) {
|
|
2011
|
+
throw new Error(`DELETE ${path} failed: ${res.status} ${res.statusText}`);
|
|
2012
|
+
}
|
|
2013
|
+
return res;
|
|
2014
|
+
}
|
|
2015
|
+
async _put(path, body) {
|
|
2016
|
+
const res = await this._fetch(`${this.baseUrl}${path}`, {
|
|
2017
|
+
method: "PUT",
|
|
2018
|
+
headers: {
|
|
2019
|
+
"Content-Type": "application/json",
|
|
2020
|
+
...this.headers
|
|
2021
|
+
},
|
|
2022
|
+
body: JSON.stringify(body)
|
|
2023
|
+
});
|
|
2024
|
+
if (!res.ok) {
|
|
2025
|
+
throw new Error(`PUT ${path} failed: ${res.status} ${res.statusText}`);
|
|
2026
|
+
}
|
|
2027
|
+
return res;
|
|
2028
|
+
}
|
|
2029
|
+
// ─── SSE Parser ─────────────────────────────────────────────
|
|
2030
|
+
async *_parseSSEStream(body, signal) {
|
|
2031
|
+
const reader = body.getReader();
|
|
2032
|
+
const decoder = new TextDecoder();
|
|
2033
|
+
let buffer = "";
|
|
2034
|
+
const abortPromise = new Promise((_, reject) => {
|
|
2035
|
+
if (signal.aborted) {
|
|
2036
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
signal.addEventListener("abort", () => {
|
|
2040
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
2041
|
+
}, { once: true });
|
|
2042
|
+
});
|
|
2043
|
+
try {
|
|
2044
|
+
while (true) {
|
|
2045
|
+
if (signal.aborted) break;
|
|
2046
|
+
const { done, value } = await Promise.race([
|
|
2047
|
+
reader.read(),
|
|
2048
|
+
abortPromise
|
|
2049
|
+
]);
|
|
2050
|
+
if (done) break;
|
|
2051
|
+
buffer += decoder.decode(value, { stream: true });
|
|
2052
|
+
const lines = buffer.split("\n");
|
|
2053
|
+
buffer = lines.pop();
|
|
2054
|
+
for (const line of lines) {
|
|
2055
|
+
if (signal.aborted) return;
|
|
2056
|
+
if (line.startsWith("data: ")) {
|
|
2057
|
+
const data = line.slice(6).trim();
|
|
2058
|
+
if (data === "[DONE]") return;
|
|
2059
|
+
try {
|
|
2060
|
+
yield JSON.parse(data);
|
|
2061
|
+
} catch {
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
} catch (err) {
|
|
2067
|
+
if (err instanceof DOMException && err.name === "AbortError") ; else {
|
|
2068
|
+
throw err;
|
|
2069
|
+
}
|
|
2070
|
+
} finally {
|
|
2071
|
+
reader.releaseLock();
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
};
|
|
2075
|
+
|
|
2076
|
+
// src/chat/react/useRemoteChat.ts
|
|
2077
|
+
function useRemoteChat(options) {
|
|
2078
|
+
const {
|
|
2079
|
+
chatBaseUrl,
|
|
2080
|
+
authBaseUrl,
|
|
2081
|
+
backend,
|
|
2082
|
+
onReady,
|
|
2083
|
+
headers
|
|
2084
|
+
} = options;
|
|
2085
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
2086
|
+
const [phase, setPhase] = useState("initializing");
|
|
2087
|
+
const [runtime, setRuntime] = useState(null);
|
|
2088
|
+
const [sessionId, setSessionId] = useState(null);
|
|
2089
|
+
const [error, setError] = useState(null);
|
|
2090
|
+
const onReadyRef = useRef(onReady);
|
|
2091
|
+
onReadyRef.current = onReady;
|
|
2092
|
+
const mountedRef = useRef(true);
|
|
2093
|
+
useEffect(() => {
|
|
2094
|
+
return () => {
|
|
2095
|
+
mountedRef.current = false;
|
|
2096
|
+
};
|
|
2097
|
+
}, []);
|
|
2098
|
+
const auth = useRemoteAuth({
|
|
2099
|
+
backend,
|
|
2100
|
+
baseUrl: authBaseUrl,
|
|
2101
|
+
fetch: fetchFn,
|
|
2102
|
+
headers
|
|
2103
|
+
});
|
|
2104
|
+
const restoredRef = useRef(false);
|
|
2105
|
+
const [tokensLoaded, setTokensLoaded] = useState(false);
|
|
2106
|
+
useEffect(() => {
|
|
2107
|
+
if (restoredRef.current) return;
|
|
2108
|
+
restoredRef.current = true;
|
|
2109
|
+
(async () => {
|
|
2110
|
+
try {
|
|
2111
|
+
await auth.loadSavedTokens();
|
|
2112
|
+
} catch {
|
|
2113
|
+
}
|
|
2114
|
+
if (mountedRef.current) setTokensLoaded(true);
|
|
2115
|
+
})();
|
|
2116
|
+
}, []);
|
|
2117
|
+
useEffect(() => {
|
|
2118
|
+
if (!tokensLoaded) return;
|
|
2119
|
+
if (auth.status === "idle" && auth.savedProviders.includes(backend) && phase === "initializing") {
|
|
2120
|
+
auth.useSavedToken(backend).catch(() => {
|
|
2121
|
+
if (mountedRef.current) setPhase("unauthenticated");
|
|
2122
|
+
});
|
|
2123
|
+
} else if (auth.status === "idle" && !auth.savedProviders.includes(backend) && phase === "initializing") {
|
|
2124
|
+
setPhase("unauthenticated");
|
|
2125
|
+
}
|
|
2126
|
+
}, [tokensLoaded, auth.status, auth.savedProviders, backend, phase]);
|
|
2127
|
+
useEffect(() => {
|
|
2128
|
+
if (auth.status === "pending") {
|
|
2129
|
+
setPhase("authenticating");
|
|
2130
|
+
} else if (auth.status === "error" && auth.error) {
|
|
2131
|
+
setError(auth.error);
|
|
2132
|
+
setPhase("error");
|
|
2133
|
+
}
|
|
2134
|
+
}, [auth.status, auth.error]);
|
|
2135
|
+
const creatingRef = useRef(false);
|
|
2136
|
+
useEffect(() => {
|
|
2137
|
+
if (auth.status !== "authenticated" || creatingRef.current || runtime !== null) return;
|
|
2138
|
+
creatingRef.current = true;
|
|
2139
|
+
setPhase("creating");
|
|
2140
|
+
setError(null);
|
|
2141
|
+
(async () => {
|
|
2142
|
+
try {
|
|
2143
|
+
const rt = new RemoteChatClient({
|
|
2144
|
+
baseUrl: chatBaseUrl,
|
|
2145
|
+
headers,
|
|
2146
|
+
fetch: fetchFn
|
|
2147
|
+
});
|
|
2148
|
+
const session = await rt.createSession({});
|
|
2149
|
+
if (!mountedRef.current) return;
|
|
2150
|
+
setRuntime(rt);
|
|
2151
|
+
setSessionId(session.id);
|
|
2152
|
+
setPhase("ready");
|
|
2153
|
+
onReadyRef.current?.();
|
|
2154
|
+
} catch (err) {
|
|
2155
|
+
if (!mountedRef.current) return;
|
|
2156
|
+
creatingRef.current = false;
|
|
2157
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2158
|
+
setPhase("error");
|
|
2159
|
+
}
|
|
2160
|
+
})();
|
|
2161
|
+
}, [auth.status, chatBaseUrl]);
|
|
2162
|
+
const newSession = useCallback(async () => {
|
|
2163
|
+
if (!runtime) throw new Error("Runtime not ready");
|
|
2164
|
+
const session = await runtime.createSession({});
|
|
2165
|
+
setSessionId(session.id);
|
|
2166
|
+
return session.id;
|
|
2167
|
+
}, [runtime]);
|
|
2168
|
+
const logout = useCallback(async () => {
|
|
2169
|
+
try {
|
|
2170
|
+
await auth.clearTokens();
|
|
2171
|
+
} catch {
|
|
2172
|
+
}
|
|
2173
|
+
if (runtime) {
|
|
2174
|
+
try {
|
|
2175
|
+
runtime.dispose();
|
|
2176
|
+
} catch {
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
auth.reset();
|
|
2180
|
+
setRuntime(null);
|
|
2181
|
+
setSessionId(null);
|
|
2182
|
+
setError(null);
|
|
2183
|
+
setTokensLoaded(false);
|
|
2184
|
+
creatingRef.current = false;
|
|
2185
|
+
restoredRef.current = false;
|
|
2186
|
+
setPhase("unauthenticated");
|
|
2187
|
+
}, [auth.clearTokens, auth.reset, runtime]);
|
|
2188
|
+
return {
|
|
2189
|
+
phase,
|
|
2190
|
+
runtime,
|
|
2191
|
+
sessionId,
|
|
2192
|
+
auth,
|
|
2193
|
+
error,
|
|
2194
|
+
newSession,
|
|
2195
|
+
logout
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
function CopilotAuthForm({ auth, onAuthComplete }) {
|
|
2199
|
+
const children = [];
|
|
2200
|
+
if (auth.status === "idle") {
|
|
2201
|
+
children.push(
|
|
2202
|
+
createElement("button", {
|
|
2203
|
+
key: "start",
|
|
2204
|
+
type: "button",
|
|
2205
|
+
"data-action": "start-auth",
|
|
2206
|
+
onClick: () => {
|
|
2207
|
+
auth.startDeviceFlow().then(() => onAuthComplete());
|
|
2208
|
+
}
|
|
2209
|
+
}, "Authenticate with GitHub")
|
|
2210
|
+
);
|
|
2211
|
+
}
|
|
2212
|
+
if (auth.deviceCode) {
|
|
2213
|
+
children.push(
|
|
2214
|
+
createElement("div", { key: "code", "data-device-code": "true" }, auth.deviceCode)
|
|
2215
|
+
);
|
|
2216
|
+
if (auth.verificationUrl) {
|
|
2217
|
+
children.push(
|
|
2218
|
+
createElement("a", {
|
|
2219
|
+
key: "url",
|
|
2220
|
+
href: auth.verificationUrl,
|
|
2221
|
+
target: "_blank",
|
|
2222
|
+
rel: "noreferrer"
|
|
2223
|
+
}, "Open GitHub \u2192")
|
|
2224
|
+
);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
if (auth.status === "pending") {
|
|
2228
|
+
children.push(
|
|
2229
|
+
createElement("span", { key: "wait", "data-auth-loading": "true" }, "Waiting...")
|
|
2230
|
+
);
|
|
2231
|
+
}
|
|
2232
|
+
if (auth.status === "authenticated") {
|
|
2233
|
+
children.push(
|
|
2234
|
+
createElement(
|
|
2235
|
+
"div",
|
|
2236
|
+
{ key: "done", "data-auth-success": "true" },
|
|
2237
|
+
"\u2713 Authenticated",
|
|
2238
|
+
createElement("button", {
|
|
2239
|
+
type: "button",
|
|
2240
|
+
"data-action": "continue",
|
|
2241
|
+
onClick: onAuthComplete
|
|
2242
|
+
}, "Continue \u2192")
|
|
2243
|
+
)
|
|
2244
|
+
);
|
|
2245
|
+
}
|
|
2246
|
+
if (auth.error) {
|
|
2247
|
+
children.push(
|
|
2248
|
+
createElement("div", { key: "error", "data-auth-error-display": "true" }, auth.error.message)
|
|
2249
|
+
);
|
|
2250
|
+
}
|
|
2251
|
+
return createElement("div", { "data-auth-flow": "copilot" }, ...children);
|
|
2252
|
+
}
|
|
2253
|
+
function ClaudeAuthForm({ auth, onAuthComplete }) {
|
|
2254
|
+
const codeRef = useRef(null);
|
|
2255
|
+
const children = [];
|
|
2256
|
+
if (auth.status === "idle") {
|
|
2257
|
+
children.push(
|
|
2258
|
+
createElement("button", {
|
|
2259
|
+
key: "start",
|
|
2260
|
+
type: "button",
|
|
2261
|
+
"data-action": "start-auth",
|
|
2262
|
+
onClick: () => auth.startOAuthFlow()
|
|
2263
|
+
}, "Authenticate with Claude")
|
|
2264
|
+
);
|
|
2265
|
+
}
|
|
2266
|
+
if (auth.authorizeUrl) {
|
|
2267
|
+
children.push(
|
|
2268
|
+
createElement("a", {
|
|
2269
|
+
key: "url",
|
|
2270
|
+
href: auth.authorizeUrl,
|
|
2271
|
+
target: "_blank",
|
|
2272
|
+
rel: "noreferrer"
|
|
2273
|
+
}, "Open authorization page \u2192")
|
|
2274
|
+
);
|
|
2275
|
+
children.push(
|
|
2276
|
+
createElement(
|
|
2277
|
+
"div",
|
|
2278
|
+
{ key: "complete", "data-auth-complete": "true" },
|
|
2279
|
+
createElement("input", {
|
|
2280
|
+
ref: codeRef,
|
|
2281
|
+
placeholder: "Paste code or redirect URL..."
|
|
2282
|
+
}),
|
|
2283
|
+
createElement("button", {
|
|
2284
|
+
type: "button",
|
|
2285
|
+
"data-action": "complete-auth",
|
|
2286
|
+
onClick: () => {
|
|
2287
|
+
const v = codeRef.current?.value?.trim();
|
|
2288
|
+
if (v) auth.completeOAuth(v).then(() => onAuthComplete());
|
|
2289
|
+
}
|
|
2290
|
+
}, "Submit")
|
|
2291
|
+
)
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
if (auth.status === "authenticated") {
|
|
2295
|
+
children.push(
|
|
2296
|
+
createElement(
|
|
2297
|
+
"div",
|
|
2298
|
+
{ key: "done", "data-auth-success": "true" },
|
|
2299
|
+
"\u2713 Authenticated",
|
|
2300
|
+
createElement("button", {
|
|
2301
|
+
type: "button",
|
|
2302
|
+
"data-action": "continue",
|
|
2303
|
+
onClick: onAuthComplete
|
|
2304
|
+
}, "Continue \u2192")
|
|
2305
|
+
)
|
|
2306
|
+
);
|
|
2307
|
+
}
|
|
2308
|
+
if (auth.error) {
|
|
2309
|
+
children.push(
|
|
2310
|
+
createElement("div", { key: "error", "data-auth-error-display": "true" }, auth.error.message)
|
|
2311
|
+
);
|
|
2312
|
+
}
|
|
2313
|
+
return createElement("div", { "data-auth-flow": "claude" }, ...children);
|
|
2314
|
+
}
|
|
2315
|
+
function VercelAIAuthForm({ auth, onAuthComplete }) {
|
|
2316
|
+
const apiKeyRef = useRef(null);
|
|
2317
|
+
const baseUrlRef = useRef(null);
|
|
2318
|
+
const children = [];
|
|
2319
|
+
if (auth.status !== "authenticated") {
|
|
2320
|
+
children.push(
|
|
2321
|
+
createElement(
|
|
2322
|
+
"div",
|
|
2323
|
+
{ key: "apikey", "data-auth-apikey": "true" },
|
|
2324
|
+
createElement("input", {
|
|
2325
|
+
ref: baseUrlRef,
|
|
2326
|
+
placeholder: "Base URL (default: openai.com/v1)"
|
|
2327
|
+
}),
|
|
2328
|
+
createElement("input", {
|
|
2329
|
+
ref: apiKeyRef,
|
|
2330
|
+
type: "password",
|
|
2331
|
+
placeholder: "API Key (sk-...)"
|
|
2332
|
+
}),
|
|
2333
|
+
createElement("button", {
|
|
2334
|
+
type: "button",
|
|
2335
|
+
"data-action": "submit-apikey",
|
|
2336
|
+
onClick: () => {
|
|
2337
|
+
const k = apiKeyRef.current?.value?.trim();
|
|
2338
|
+
if (k) {
|
|
2339
|
+
auth.submitApiKey(k, baseUrlRef.current?.value?.trim() || void 0).then(() => onAuthComplete());
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
}, "Connect")
|
|
2343
|
+
)
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
2346
|
+
if (auth.status === "authenticated") {
|
|
2347
|
+
children.push(
|
|
2348
|
+
createElement(
|
|
2349
|
+
"div",
|
|
2350
|
+
{ key: "done", "data-auth-success": "true" },
|
|
2351
|
+
"\u2713 Connected",
|
|
2352
|
+
createElement("button", {
|
|
2353
|
+
type: "button",
|
|
2354
|
+
"data-action": "continue",
|
|
2355
|
+
onClick: onAuthComplete
|
|
2356
|
+
}, "Continue \u2192")
|
|
2357
|
+
)
|
|
2358
|
+
);
|
|
2359
|
+
}
|
|
2360
|
+
if (auth.error) {
|
|
2361
|
+
children.push(
|
|
2362
|
+
createElement("div", { key: "error", "data-auth-error-display": "true" }, auth.error.message)
|
|
2363
|
+
);
|
|
2364
|
+
}
|
|
2365
|
+
return createElement("div", { "data-auth-flow": "vercel-ai" }, ...children);
|
|
2366
|
+
}
|
|
2367
|
+
function BackendSelector({
|
|
2368
|
+
backends,
|
|
2369
|
+
onSelect,
|
|
2370
|
+
className
|
|
2371
|
+
}) {
|
|
2372
|
+
const handleClick = useCallback(
|
|
2373
|
+
(name) => () => onSelect(name),
|
|
2374
|
+
[onSelect]
|
|
2375
|
+
);
|
|
2376
|
+
const items = backends.map(
|
|
2377
|
+
(backend) => createElement(
|
|
2378
|
+
"button",
|
|
2379
|
+
{
|
|
2380
|
+
key: backend.name,
|
|
2381
|
+
type: "button",
|
|
2382
|
+
"data-backend-item": "true",
|
|
2383
|
+
"data-backend-name": backend.name,
|
|
2384
|
+
onClick: handleClick(backend.name)
|
|
2385
|
+
},
|
|
2386
|
+
backend.name
|
|
2387
|
+
)
|
|
2388
|
+
);
|
|
2389
|
+
return createElement(
|
|
2390
|
+
"div",
|
|
2391
|
+
{ "data-backend-selector": "true", className },
|
|
2392
|
+
...items
|
|
2393
|
+
);
|
|
2394
|
+
}
|
|
2395
|
+
function useBackends() {
|
|
2396
|
+
const runtime = useChatRuntime();
|
|
2397
|
+
const [backends, setBackends] = useState([]);
|
|
2398
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
2399
|
+
const [error, setError] = useState(null);
|
|
2400
|
+
const mountedRef = useRef(true);
|
|
2401
|
+
const fetchBackends = useCallback(() => {
|
|
2402
|
+
setIsLoading(true);
|
|
2403
|
+
setError(null);
|
|
2404
|
+
try {
|
|
2405
|
+
const result = runtime.listBackends();
|
|
2406
|
+
if (result instanceof Promise) {
|
|
2407
|
+
result.then((data) => {
|
|
2408
|
+
if (mountedRef.current) {
|
|
2409
|
+
setBackends(data);
|
|
2410
|
+
setIsLoading(false);
|
|
2411
|
+
}
|
|
2412
|
+
}).catch((err) => {
|
|
2413
|
+
if (mountedRef.current) {
|
|
2414
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2415
|
+
setIsLoading(false);
|
|
2416
|
+
}
|
|
2417
|
+
});
|
|
2418
|
+
} else {
|
|
2419
|
+
if (mountedRef.current) {
|
|
2420
|
+
setBackends(result);
|
|
2421
|
+
setIsLoading(false);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
} catch (err) {
|
|
2425
|
+
if (mountedRef.current) {
|
|
2426
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2427
|
+
setIsLoading(false);
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
}, [runtime]);
|
|
2431
|
+
useEffect(() => {
|
|
2432
|
+
mountedRef.current = true;
|
|
2433
|
+
fetchBackends();
|
|
2434
|
+
return () => {
|
|
2435
|
+
mountedRef.current = false;
|
|
2436
|
+
};
|
|
2437
|
+
}, [fetchBackends]);
|
|
2438
|
+
return { backends, isLoading, error, refresh: fetchBackends };
|
|
2439
|
+
}
|
|
2440
|
+
function isProviderCapable(runtime) {
|
|
2441
|
+
return typeof runtime === "object" && runtime !== null && typeof runtime.listProviders === "function";
|
|
2442
|
+
}
|
|
2443
|
+
function useProviders() {
|
|
2444
|
+
const runtime = useChatRuntime();
|
|
2445
|
+
const [providers, setProviders] = useState([]);
|
|
2446
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
2447
|
+
const [error, setError] = useState(null);
|
|
2448
|
+
const mountedRef = useRef(true);
|
|
2449
|
+
const fetchProviders = useCallback(() => {
|
|
2450
|
+
setIsLoading(true);
|
|
2451
|
+
setError(null);
|
|
2452
|
+
if (!isProviderCapable(runtime)) {
|
|
2453
|
+
setIsLoading(false);
|
|
2454
|
+
return;
|
|
2455
|
+
}
|
|
2456
|
+
runtime.listProviders().then((data) => {
|
|
2457
|
+
if (mountedRef.current) {
|
|
2458
|
+
setProviders(data);
|
|
2459
|
+
setIsLoading(false);
|
|
2460
|
+
}
|
|
2461
|
+
}).catch((err) => {
|
|
2462
|
+
if (mountedRef.current) {
|
|
2463
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2464
|
+
setIsLoading(false);
|
|
2465
|
+
}
|
|
2466
|
+
});
|
|
2467
|
+
}, [runtime]);
|
|
2468
|
+
useEffect(() => {
|
|
2469
|
+
mountedRef.current = true;
|
|
2470
|
+
fetchProviders();
|
|
2471
|
+
return () => {
|
|
2472
|
+
mountedRef.current = false;
|
|
2473
|
+
};
|
|
2474
|
+
}, [fetchProviders]);
|
|
2475
|
+
const createProvider = useCallback(
|
|
2476
|
+
async (config) => {
|
|
2477
|
+
if (!isProviderCapable(runtime)) return;
|
|
2478
|
+
try {
|
|
2479
|
+
await runtime.createProvider(config);
|
|
2480
|
+
fetchProviders();
|
|
2481
|
+
} catch (err) {
|
|
2482
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2483
|
+
}
|
|
2484
|
+
},
|
|
2485
|
+
[runtime, fetchProviders]
|
|
2486
|
+
);
|
|
2487
|
+
const updateProvider = useCallback(
|
|
2488
|
+
async (id, changes) => {
|
|
2489
|
+
if (!isProviderCapable(runtime)) return;
|
|
2490
|
+
try {
|
|
2491
|
+
await runtime.updateProvider(id, changes);
|
|
2492
|
+
fetchProviders();
|
|
2493
|
+
} catch (err) {
|
|
2494
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2495
|
+
}
|
|
2496
|
+
},
|
|
2497
|
+
[runtime, fetchProviders]
|
|
2498
|
+
);
|
|
2499
|
+
const deleteProvider = useCallback(
|
|
2500
|
+
async (id) => {
|
|
2501
|
+
if (!isProviderCapable(runtime)) return;
|
|
2502
|
+
try {
|
|
2503
|
+
await runtime.deleteProvider(id);
|
|
2504
|
+
fetchProviders();
|
|
2505
|
+
} catch (err) {
|
|
2506
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
2507
|
+
}
|
|
2508
|
+
},
|
|
2509
|
+
[runtime, fetchProviders]
|
|
2510
|
+
);
|
|
2511
|
+
const selectProvider = useCallback(
|
|
2512
|
+
(id) => {
|
|
2513
|
+
if (!isProviderCapable(runtime)) return;
|
|
2514
|
+
runtime.selectProvider(id);
|
|
2515
|
+
},
|
|
2516
|
+
[runtime]
|
|
2517
|
+
);
|
|
2518
|
+
return { providers, isLoading, error, refresh: fetchProviders, createProvider, updateProvider, deleteProvider, selectProvider };
|
|
2519
|
+
}
|
|
2520
|
+
function ProviderSelector({
|
|
2521
|
+
providers,
|
|
2522
|
+
activeProviderId,
|
|
2523
|
+
onSelect,
|
|
2524
|
+
onSettingsClick,
|
|
2525
|
+
className
|
|
2526
|
+
}) {
|
|
2527
|
+
const [open, setOpen] = useState(false);
|
|
2528
|
+
const [highlightIndex, setHighlightIndex] = useState(0);
|
|
2529
|
+
const containerRef = useRef(null);
|
|
2530
|
+
const activeProvider = useMemo(
|
|
2531
|
+
() => providers.find((p) => p.id === activeProviderId),
|
|
2532
|
+
[providers, activeProviderId]
|
|
2533
|
+
);
|
|
2534
|
+
useEffect(() => {
|
|
2535
|
+
if (!open) return;
|
|
2536
|
+
const handler = (e) => {
|
|
2537
|
+
if (containerRef.current && !containerRef.current.contains(e.target)) {
|
|
2538
|
+
setOpen(false);
|
|
2539
|
+
}
|
|
2540
|
+
};
|
|
2541
|
+
document.addEventListener("mousedown", handler);
|
|
2542
|
+
return () => document.removeEventListener("mousedown", handler);
|
|
2543
|
+
}, [open]);
|
|
2544
|
+
useEffect(() => {
|
|
2545
|
+
setHighlightIndex(0);
|
|
2546
|
+
}, [providers.length]);
|
|
2547
|
+
const handleToggle = useCallback(() => {
|
|
2548
|
+
setOpen((prev) => {
|
|
2549
|
+
if (!prev) setHighlightIndex(0);
|
|
2550
|
+
return !prev;
|
|
2551
|
+
});
|
|
2552
|
+
}, []);
|
|
2553
|
+
const handleSelect = useCallback(
|
|
2554
|
+
(id) => {
|
|
2555
|
+
onSelect(id);
|
|
2556
|
+
setOpen(false);
|
|
2557
|
+
},
|
|
2558
|
+
[onSelect]
|
|
2559
|
+
);
|
|
2560
|
+
const handleKeyDown = useCallback(
|
|
2561
|
+
(e) => {
|
|
2562
|
+
if (e.key === "ArrowDown") {
|
|
2563
|
+
e.preventDefault();
|
|
2564
|
+
setHighlightIndex((prev) => Math.min(prev + 1, providers.length - 1));
|
|
2565
|
+
} else if (e.key === "ArrowUp") {
|
|
2566
|
+
e.preventDefault();
|
|
2567
|
+
setHighlightIndex((prev) => Math.max(prev - 1, 0));
|
|
2568
|
+
} else if (e.key === "Enter") {
|
|
2569
|
+
e.preventDefault();
|
|
2570
|
+
if (providers[highlightIndex]) {
|
|
2571
|
+
handleSelect(providers[highlightIndex].id);
|
|
2572
|
+
}
|
|
2573
|
+
} else if (e.key === "Escape") {
|
|
2574
|
+
e.preventDefault();
|
|
2575
|
+
setOpen(false);
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
2578
|
+
[providers, highlightIndex, handleSelect]
|
|
2579
|
+
);
|
|
2580
|
+
const children = [];
|
|
2581
|
+
children.push(
|
|
2582
|
+
createElement(
|
|
2583
|
+
"button",
|
|
2584
|
+
{
|
|
2585
|
+
key: "trigger",
|
|
2586
|
+
type: "button",
|
|
2587
|
+
"data-provider-trigger": "true",
|
|
2588
|
+
onClick: handleToggle,
|
|
2589
|
+
onKeyDown: handleKeyDown
|
|
2590
|
+
},
|
|
2591
|
+
activeProvider ? activeProvider.label : "Select provider"
|
|
2592
|
+
)
|
|
2593
|
+
);
|
|
2594
|
+
if (open) {
|
|
2595
|
+
const dropdownChildren = [];
|
|
2596
|
+
providers.forEach((provider, idx) => {
|
|
2597
|
+
const isActive = provider.id === activeProviderId;
|
|
2598
|
+
const isHighlighted = idx === highlightIndex;
|
|
2599
|
+
const attrs = {
|
|
2600
|
+
key: provider.id,
|
|
2601
|
+
"data-provider-item": "true",
|
|
2602
|
+
onClick: () => handleSelect(provider.id)
|
|
2603
|
+
};
|
|
2604
|
+
if (isActive) attrs["data-provider-active"] = "true";
|
|
2605
|
+
if (isHighlighted) attrs["data-provider-highlighted"] = "true";
|
|
2606
|
+
dropdownChildren.push(
|
|
2607
|
+
createElement(
|
|
2608
|
+
"div",
|
|
2609
|
+
attrs,
|
|
2610
|
+
createElement("span", { "data-provider-label": "true" }, provider.label),
|
|
2611
|
+
createElement("span", { "data-provider-model": "true" }, provider.model)
|
|
2612
|
+
)
|
|
2613
|
+
);
|
|
2614
|
+
});
|
|
2615
|
+
if (onSettingsClick) {
|
|
2616
|
+
dropdownChildren.push(
|
|
2617
|
+
createElement(
|
|
2618
|
+
"button",
|
|
2619
|
+
{
|
|
2620
|
+
key: "settings",
|
|
2621
|
+
type: "button",
|
|
2622
|
+
"data-provider-settings-btn": "true",
|
|
2623
|
+
onClick: (e) => {
|
|
2624
|
+
e.stopPropagation();
|
|
2625
|
+
setOpen(false);
|
|
2626
|
+
onSettingsClick();
|
|
2627
|
+
}
|
|
2628
|
+
},
|
|
2629
|
+
"\u2699 Settings"
|
|
2630
|
+
)
|
|
2631
|
+
);
|
|
2632
|
+
}
|
|
2633
|
+
children.push(
|
|
2634
|
+
createElement(
|
|
2635
|
+
"div",
|
|
2636
|
+
{ key: "dropdown", "data-provider-dropdown": "true", onKeyDown: handleKeyDown },
|
|
2637
|
+
...dropdownChildren
|
|
2638
|
+
)
|
|
2639
|
+
);
|
|
2640
|
+
}
|
|
2641
|
+
return createElement(
|
|
2642
|
+
"div",
|
|
2643
|
+
{
|
|
2644
|
+
"data-provider-selector": "true",
|
|
2645
|
+
className,
|
|
2646
|
+
ref: containerRef
|
|
2647
|
+
},
|
|
2648
|
+
...children
|
|
2649
|
+
);
|
|
2650
|
+
}
|
|
2651
|
+
function ProviderModelSelector({
|
|
2652
|
+
providers = [],
|
|
2653
|
+
models = [],
|
|
2654
|
+
activeProviderId,
|
|
2655
|
+
selectedModel,
|
|
2656
|
+
onSelectProvider,
|
|
2657
|
+
onSelectModel,
|
|
2658
|
+
onSettingsClick,
|
|
2659
|
+
placeholder = "Select model",
|
|
2660
|
+
className
|
|
2661
|
+
}) {
|
|
2662
|
+
const [open, setOpen] = useState(false);
|
|
2663
|
+
const [search, setSearch] = useState("");
|
|
2664
|
+
const [highlightIndex, setHighlightIndex] = useState(0);
|
|
2665
|
+
const containerRef = useRef(null);
|
|
2666
|
+
const isProviderMode = providers.length > 0;
|
|
2667
|
+
const items = useMemo(() => {
|
|
2668
|
+
if (isProviderMode) {
|
|
2669
|
+
return providers.map((p) => ({
|
|
2670
|
+
id: p.id,
|
|
2671
|
+
label: p.label,
|
|
2672
|
+
sublabel: p.model,
|
|
2673
|
+
type: "provider"
|
|
2674
|
+
}));
|
|
2675
|
+
}
|
|
2676
|
+
return models.map((m) => ({
|
|
2677
|
+
id: m.id,
|
|
2678
|
+
label: m.name,
|
|
2679
|
+
sublabel: m.provider,
|
|
2680
|
+
tier: m.tier,
|
|
2681
|
+
type: "model"
|
|
2682
|
+
}));
|
|
2683
|
+
}, [isProviderMode, providers, models]);
|
|
2684
|
+
const filtered = useMemo(() => {
|
|
2685
|
+
if (!search) return items;
|
|
2686
|
+
const q = search.toLowerCase();
|
|
2687
|
+
return items.filter(
|
|
2688
|
+
(item) => item.label.toLowerCase().includes(q) || item.sublabel && item.sublabel.toLowerCase().includes(q)
|
|
2689
|
+
);
|
|
2690
|
+
}, [items, search]);
|
|
2691
|
+
useEffect(() => {
|
|
2692
|
+
setHighlightIndex(0);
|
|
2693
|
+
}, [filtered.length]);
|
|
2694
|
+
useEffect(() => {
|
|
2695
|
+
if (!open) return;
|
|
2696
|
+
const handler = (e) => {
|
|
2697
|
+
if (containerRef.current && !containerRef.current.contains(e.target)) {
|
|
2698
|
+
setOpen(false);
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
document.addEventListener("mousedown", handler);
|
|
2702
|
+
return () => document.removeEventListener("mousedown", handler);
|
|
2703
|
+
}, [open]);
|
|
2704
|
+
const triggerLabel = useMemo(() => {
|
|
2705
|
+
if (isProviderMode && activeProviderId) {
|
|
2706
|
+
const p = providers.find((prov) => prov.id === activeProviderId);
|
|
2707
|
+
return p ? p.label : placeholder;
|
|
2708
|
+
}
|
|
2709
|
+
if (!isProviderMode && selectedModel) {
|
|
2710
|
+
const m = models.find((mod) => mod.id === selectedModel);
|
|
2711
|
+
return m ? m.name : selectedModel;
|
|
2712
|
+
}
|
|
2713
|
+
return placeholder;
|
|
2714
|
+
}, [isProviderMode, activeProviderId, providers, selectedModel, models, placeholder]);
|
|
2715
|
+
const handleToggle = useCallback(() => {
|
|
2716
|
+
setOpen((prev) => {
|
|
2717
|
+
if (!prev) {
|
|
2718
|
+
setSearch("");
|
|
2719
|
+
setHighlightIndex(0);
|
|
2720
|
+
}
|
|
2721
|
+
return !prev;
|
|
2722
|
+
});
|
|
2723
|
+
}, []);
|
|
2724
|
+
const handleSelect = useCallback(
|
|
2725
|
+
(item) => {
|
|
2726
|
+
if (item.type === "provider" && onSelectProvider) {
|
|
2727
|
+
onSelectProvider(item.id);
|
|
2728
|
+
} else if (item.type === "model" && onSelectModel) {
|
|
2729
|
+
onSelectModel(item.id);
|
|
2730
|
+
}
|
|
2731
|
+
setOpen(false);
|
|
2732
|
+
setSearch("");
|
|
2733
|
+
},
|
|
2734
|
+
[onSelectProvider, onSelectModel]
|
|
2735
|
+
);
|
|
2736
|
+
const handleSearchChange = useCallback((e) => {
|
|
2737
|
+
setSearch(e.target.value);
|
|
2738
|
+
}, []);
|
|
2739
|
+
const handleKeyDown = useCallback(
|
|
2740
|
+
(e) => {
|
|
2741
|
+
if (e.key === "ArrowDown") {
|
|
2742
|
+
e.preventDefault();
|
|
2743
|
+
setHighlightIndex((prev) => Math.min(prev + 1, filtered.length - 1));
|
|
2744
|
+
} else if (e.key === "ArrowUp") {
|
|
2745
|
+
e.preventDefault();
|
|
2746
|
+
setHighlightIndex((prev) => Math.max(prev - 1, 0));
|
|
2747
|
+
} else if (e.key === "Enter") {
|
|
2748
|
+
e.preventDefault();
|
|
2749
|
+
if (filtered[highlightIndex]) {
|
|
2750
|
+
handleSelect(filtered[highlightIndex]);
|
|
2751
|
+
}
|
|
2752
|
+
} else if (e.key === "Escape") {
|
|
2753
|
+
e.preventDefault();
|
|
2754
|
+
setOpen(false);
|
|
2755
|
+
}
|
|
2756
|
+
},
|
|
2757
|
+
[filtered, highlightIndex, handleSelect]
|
|
2758
|
+
);
|
|
2759
|
+
const children = [];
|
|
2760
|
+
children.push(
|
|
2761
|
+
createElement(
|
|
2762
|
+
"button",
|
|
2763
|
+
{
|
|
2764
|
+
key: "trigger",
|
|
2765
|
+
type: "button",
|
|
2766
|
+
"data-pms-trigger": "true",
|
|
2767
|
+
onClick: handleToggle
|
|
2768
|
+
},
|
|
2769
|
+
triggerLabel
|
|
2770
|
+
)
|
|
2771
|
+
);
|
|
2772
|
+
if (open) {
|
|
2773
|
+
const dropdownChildren = [];
|
|
2774
|
+
if (items.length > 3) {
|
|
2775
|
+
dropdownChildren.push(
|
|
2776
|
+
createElement("input", {
|
|
2777
|
+
key: "search",
|
|
2778
|
+
"data-pms-search": "true",
|
|
2779
|
+
value: search,
|
|
2780
|
+
onChange: handleSearchChange,
|
|
2781
|
+
onKeyDown: handleKeyDown,
|
|
2782
|
+
placeholder: isProviderMode ? "Search providers..." : "Search models...",
|
|
2783
|
+
autoFocus: true
|
|
2784
|
+
})
|
|
2785
|
+
);
|
|
2786
|
+
}
|
|
2787
|
+
filtered.forEach((item, idx) => {
|
|
2788
|
+
const isActive = isProviderMode ? item.id === activeProviderId : item.id === selectedModel;
|
|
2789
|
+
const isHighlighted = idx === highlightIndex;
|
|
2790
|
+
const attrs = {
|
|
2791
|
+
key: item.id,
|
|
2792
|
+
"data-pms-item": "true",
|
|
2793
|
+
"data-pms-type": item.type,
|
|
2794
|
+
onClick: () => handleSelect(item)
|
|
2795
|
+
};
|
|
2796
|
+
if (item.tier) attrs["data-tier"] = item.tier;
|
|
2797
|
+
if (isActive) attrs["data-pms-active"] = "true";
|
|
2798
|
+
if (isHighlighted) attrs["data-pms-highlighted"] = "true";
|
|
2799
|
+
const itemChildren = [
|
|
2800
|
+
createElement("span", { key: "label", "data-pms-label": "true" }, item.label)
|
|
2801
|
+
];
|
|
2802
|
+
if (item.sublabel) {
|
|
2803
|
+
itemChildren.push(
|
|
2804
|
+
createElement("span", { key: "sub", "data-pms-sublabel": "true" }, item.sublabel)
|
|
2805
|
+
);
|
|
2806
|
+
}
|
|
2807
|
+
dropdownChildren.push(createElement("div", attrs, ...itemChildren));
|
|
2808
|
+
});
|
|
2809
|
+
if (onSettingsClick) {
|
|
2810
|
+
dropdownChildren.push(
|
|
2811
|
+
createElement(
|
|
2812
|
+
"button",
|
|
2813
|
+
{
|
|
2814
|
+
key: "settings",
|
|
2815
|
+
type: "button",
|
|
2816
|
+
"data-pms-settings": "true",
|
|
2817
|
+
onClick: (e) => {
|
|
2818
|
+
e.stopPropagation();
|
|
2819
|
+
setOpen(false);
|
|
2820
|
+
onSettingsClick();
|
|
2821
|
+
}
|
|
2822
|
+
},
|
|
2823
|
+
"\u2699 Settings"
|
|
2824
|
+
)
|
|
2825
|
+
);
|
|
2826
|
+
}
|
|
2827
|
+
children.push(
|
|
2828
|
+
createElement(
|
|
2829
|
+
"div",
|
|
2830
|
+
{ key: "dropdown", "data-pms-dropdown": "true", onKeyDown: handleKeyDown },
|
|
2831
|
+
...dropdownChildren
|
|
2832
|
+
)
|
|
2833
|
+
);
|
|
2834
|
+
}
|
|
2835
|
+
return createElement(
|
|
2836
|
+
"div",
|
|
2837
|
+
{
|
|
2838
|
+
"data-provider-model-selector": "true",
|
|
2839
|
+
"data-pms-mode": isProviderMode ? "provider" : "model",
|
|
2840
|
+
className,
|
|
2841
|
+
ref: containerRef
|
|
2842
|
+
},
|
|
2843
|
+
...children
|
|
2844
|
+
);
|
|
2845
|
+
}
|
|
2846
|
+
var BACKENDS = [
|
|
2847
|
+
{ id: "copilot", label: "GitHub Copilot" },
|
|
2848
|
+
{ id: "claude", label: "Claude" },
|
|
2849
|
+
{ id: "vercel-ai", label: "Vercel AI" }
|
|
2850
|
+
];
|
|
2851
|
+
var AUTH_FORMS = {
|
|
2852
|
+
copilot: CopilotAuthForm,
|
|
2853
|
+
claude: ClaudeAuthForm,
|
|
2854
|
+
"vercel-ai": VercelAIAuthForm
|
|
2855
|
+
};
|
|
2856
|
+
function ProviderSettings({
|
|
2857
|
+
providers,
|
|
2858
|
+
onClose,
|
|
2859
|
+
onProviderCreated,
|
|
2860
|
+
onProviderDeleted,
|
|
2861
|
+
onProviderUpdated,
|
|
2862
|
+
onAuthCompleted,
|
|
2863
|
+
authBaseUrl = "/api/auth",
|
|
2864
|
+
className
|
|
2865
|
+
}) {
|
|
2866
|
+
const [view, setView] = useState("list");
|
|
2867
|
+
const [addStep, setAddStep] = useState("select-backend");
|
|
2868
|
+
const [selectedBackend, setSelectedBackend] = useState("copilot");
|
|
2869
|
+
const [editingId, setEditingId] = useState(null);
|
|
2870
|
+
const [availableModels, setAvailableModels] = useState([]);
|
|
2871
|
+
const modelRef = useRef(null);
|
|
2872
|
+
const labelRef = useRef(null);
|
|
2873
|
+
const editModelRef = useRef(null);
|
|
2874
|
+
const editLabelRef = useRef(null);
|
|
2875
|
+
const runtime = useChatRuntime();
|
|
2876
|
+
const auth = useRemoteAuth({
|
|
2877
|
+
backend: selectedBackend,
|
|
2878
|
+
baseUrl: authBaseUrl
|
|
2879
|
+
});
|
|
2880
|
+
const handleBackendSelect = useCallback((backend) => {
|
|
2881
|
+
setSelectedBackend(backend);
|
|
2882
|
+
auth.reset();
|
|
2883
|
+
setAddStep("auth");
|
|
2884
|
+
}, [auth]);
|
|
2885
|
+
const handleAuthComplete = useCallback(() => {
|
|
2886
|
+
onAuthCompleted?.(selectedBackend);
|
|
2887
|
+
setAddStep("configure");
|
|
2888
|
+
}, [selectedBackend, onAuthCompleted]);
|
|
2889
|
+
useEffect(() => {
|
|
2890
|
+
if (addStep !== "configure" && view !== "edit") return;
|
|
2891
|
+
const load = async () => {
|
|
2892
|
+
try {
|
|
2893
|
+
const models = await runtime.listModels();
|
|
2894
|
+
setAvailableModels(models);
|
|
2895
|
+
} catch {
|
|
2896
|
+
}
|
|
2897
|
+
};
|
|
2898
|
+
load();
|
|
2899
|
+
}, [addStep, view, runtime]);
|
|
2900
|
+
const handleCreate = useCallback(() => {
|
|
2901
|
+
const modelEl = modelRef.current;
|
|
2902
|
+
const model = modelEl?.value?.trim();
|
|
2903
|
+
const label = labelRef.current?.value?.trim() || model;
|
|
2904
|
+
if (!model) return;
|
|
2905
|
+
const existing = providers.find((p) => p.backend === selectedBackend);
|
|
2906
|
+
if (existing) {
|
|
2907
|
+
onProviderUpdated?.(existing.id, { model, label });
|
|
2908
|
+
} else {
|
|
2909
|
+
onProviderCreated?.({ backend: selectedBackend, model, label });
|
|
2910
|
+
}
|
|
2911
|
+
setView("list");
|
|
2912
|
+
setAddStep("select-backend");
|
|
2913
|
+
setAvailableModels([]);
|
|
2914
|
+
auth.reset();
|
|
2915
|
+
}, [selectedBackend, providers, onProviderCreated, onProviderUpdated, auth]);
|
|
2916
|
+
const handleEdit = useCallback((id) => {
|
|
2917
|
+
setEditingId(id);
|
|
2918
|
+
setView("edit");
|
|
2919
|
+
}, []);
|
|
2920
|
+
const handleUpdate = useCallback(() => {
|
|
2921
|
+
if (!editingId) return;
|
|
2922
|
+
const modelEl = editModelRef.current;
|
|
2923
|
+
const model = modelEl?.value?.trim();
|
|
2924
|
+
const label = editLabelRef.current?.value?.trim();
|
|
2925
|
+
if (!model && !label) return;
|
|
2926
|
+
const changes = {};
|
|
2927
|
+
if (model) changes.model = model;
|
|
2928
|
+
if (label) changes.label = label;
|
|
2929
|
+
onProviderUpdated?.(editingId, changes);
|
|
2930
|
+
setView("list");
|
|
2931
|
+
setEditingId(null);
|
|
2932
|
+
}, [editingId, onProviderUpdated]);
|
|
2933
|
+
const handleDelete = useCallback((id) => {
|
|
2934
|
+
onProviderDeleted?.(id);
|
|
2935
|
+
}, [onProviderDeleted]);
|
|
2936
|
+
const handleStartAdd = useCallback(() => {
|
|
2937
|
+
setView("add");
|
|
2938
|
+
setAddStep("select-backend");
|
|
2939
|
+
auth.reset();
|
|
2940
|
+
}, [auth]);
|
|
2941
|
+
if (view === "list") {
|
|
2942
|
+
const items = providers.map(
|
|
2943
|
+
(p) => createElement(
|
|
2944
|
+
"div",
|
|
2945
|
+
{ key: p.id, "data-provider-settings-item": "true" },
|
|
2946
|
+
createElement("span", { "data-provider-settings-label": "true" }, p.label),
|
|
2947
|
+
createElement("span", { "data-provider-settings-model": "true" }, `${p.backend} / ${p.model}`),
|
|
2948
|
+
createElement(
|
|
2949
|
+
"div",
|
|
2950
|
+
{ "data-provider-settings-actions": "true" },
|
|
2951
|
+
createElement("button", {
|
|
2952
|
+
type: "button",
|
|
2953
|
+
"data-action": "edit-provider",
|
|
2954
|
+
onClick: () => handleEdit(p.id)
|
|
2955
|
+
}, "Edit"),
|
|
2956
|
+
createElement("button", {
|
|
2957
|
+
type: "button",
|
|
2958
|
+
"data-action": "delete-provider",
|
|
2959
|
+
onClick: () => handleDelete(p.id)
|
|
2960
|
+
}, "Delete")
|
|
2961
|
+
)
|
|
2962
|
+
)
|
|
2963
|
+
);
|
|
2964
|
+
return createElement(
|
|
2965
|
+
"div",
|
|
2966
|
+
{ "data-provider-settings": "true", className },
|
|
2967
|
+
createElement(
|
|
2968
|
+
"div",
|
|
2969
|
+
{ "data-provider-settings-header": "true" },
|
|
2970
|
+
createElement("span", null, "Providers"),
|
|
2971
|
+
onClose ? createElement("button", {
|
|
2972
|
+
type: "button",
|
|
2973
|
+
"data-provider-settings-close": "true",
|
|
2974
|
+
onClick: onClose
|
|
2975
|
+
}, "\u2715") : null
|
|
2976
|
+
),
|
|
2977
|
+
createElement(
|
|
2978
|
+
"div",
|
|
2979
|
+
{ "data-provider-settings-list": "true" },
|
|
2980
|
+
...items,
|
|
2981
|
+
items.length === 0 ? createElement("div", { "data-provider-settings-empty": "true" }, "No providers configured") : null
|
|
2982
|
+
),
|
|
2983
|
+
createElement("button", {
|
|
2984
|
+
type: "button",
|
|
2985
|
+
"data-action": "add-provider",
|
|
2986
|
+
onClick: handleStartAdd
|
|
2987
|
+
}, "+ Add Provider")
|
|
2988
|
+
);
|
|
2989
|
+
}
|
|
2990
|
+
if (view === "add") {
|
|
2991
|
+
const formChildren = [];
|
|
2992
|
+
formChildren.push(
|
|
2993
|
+
createElement(
|
|
2994
|
+
"div",
|
|
2995
|
+
{ "data-provider-settings-header": "true", key: "header" },
|
|
2996
|
+
createElement("span", null, "Add Provider"),
|
|
2997
|
+
createElement("button", {
|
|
2998
|
+
type: "button",
|
|
2999
|
+
"data-provider-settings-close": "true",
|
|
3000
|
+
onClick: () => {
|
|
3001
|
+
setView("list");
|
|
3002
|
+
setAddStep("select-backend");
|
|
3003
|
+
}
|
|
3004
|
+
}, "\u2190 Back")
|
|
3005
|
+
)
|
|
3006
|
+
);
|
|
3007
|
+
if (addStep === "select-backend") {
|
|
3008
|
+
formChildren.push(
|
|
3009
|
+
createElement(
|
|
3010
|
+
"div",
|
|
3011
|
+
{ key: "backends", "data-provider-settings-backends": "true" },
|
|
3012
|
+
...BACKENDS.map(
|
|
3013
|
+
(b) => createElement("button", {
|
|
3014
|
+
key: b.id,
|
|
3015
|
+
type: "button",
|
|
3016
|
+
"data-provider-backend-option": b.id,
|
|
3017
|
+
onClick: () => handleBackendSelect(b.id)
|
|
3018
|
+
}, b.label)
|
|
3019
|
+
)
|
|
3020
|
+
)
|
|
3021
|
+
);
|
|
3022
|
+
} else if (addStep === "auth") {
|
|
3023
|
+
const FormComponent = selectedBackend ? AUTH_FORMS[selectedBackend] : null;
|
|
3024
|
+
formChildren.push(
|
|
3025
|
+
createElement(
|
|
3026
|
+
"div",
|
|
3027
|
+
{ key: "auth", "data-provider-settings-auth": "true" },
|
|
3028
|
+
FormComponent ? createElement(FormComponent, { auth, onAuthComplete: handleAuthComplete }) : null
|
|
3029
|
+
)
|
|
3030
|
+
);
|
|
3031
|
+
} else if (addStep === "configure") {
|
|
3032
|
+
const modelInput = availableModels.length > 0 ? createElement(
|
|
3033
|
+
"select",
|
|
3034
|
+
{
|
|
3035
|
+
ref: modelRef,
|
|
3036
|
+
"data-input": "model",
|
|
3037
|
+
defaultValue: ""
|
|
3038
|
+
},
|
|
3039
|
+
createElement("option", { value: "", disabled: true }, "Select a model\u2026"),
|
|
3040
|
+
...availableModels.map(
|
|
3041
|
+
(m) => createElement("option", { key: m.id, value: m.id }, m.name || m.id)
|
|
3042
|
+
)
|
|
3043
|
+
) : createElement("input", {
|
|
3044
|
+
ref: modelRef,
|
|
3045
|
+
placeholder: "Model name (e.g. gpt-5-mini)",
|
|
3046
|
+
"data-input": "model"
|
|
3047
|
+
});
|
|
3048
|
+
formChildren.push(
|
|
3049
|
+
createElement(
|
|
3050
|
+
"div",
|
|
3051
|
+
{ key: "config", "data-provider-settings-form": "true" },
|
|
3052
|
+
modelInput,
|
|
3053
|
+
createElement("input", {
|
|
3054
|
+
ref: labelRef,
|
|
3055
|
+
placeholder: "Display label (e.g. GPT-5 Mini)",
|
|
3056
|
+
"data-input": "label"
|
|
3057
|
+
}),
|
|
3058
|
+
createElement("button", {
|
|
3059
|
+
type: "button",
|
|
3060
|
+
"data-action": "save-provider",
|
|
3061
|
+
onClick: handleCreate
|
|
3062
|
+
}, "Save Provider")
|
|
3063
|
+
)
|
|
3064
|
+
);
|
|
3065
|
+
}
|
|
3066
|
+
return createElement(
|
|
3067
|
+
"div",
|
|
3068
|
+
{ "data-provider-settings": "true", className },
|
|
3069
|
+
...formChildren
|
|
3070
|
+
);
|
|
3071
|
+
}
|
|
3072
|
+
const editingProvider = providers.find((p) => p.id === editingId);
|
|
3073
|
+
return createElement(
|
|
3074
|
+
"div",
|
|
3075
|
+
{ "data-provider-settings": "true", className },
|
|
3076
|
+
createElement(
|
|
3077
|
+
"div",
|
|
3078
|
+
{ "data-provider-settings-header": "true" },
|
|
3079
|
+
createElement("span", null, "Edit Provider"),
|
|
3080
|
+
createElement("button", {
|
|
3081
|
+
type: "button",
|
|
3082
|
+
"data-provider-settings-close": "true",
|
|
3083
|
+
onClick: () => {
|
|
3084
|
+
setView("list");
|
|
3085
|
+
setEditingId(null);
|
|
3086
|
+
}
|
|
3087
|
+
}, "\u2190 Back")
|
|
3088
|
+
),
|
|
3089
|
+
createElement(
|
|
3090
|
+
"div",
|
|
3091
|
+
{ "data-provider-settings-form": "true" },
|
|
3092
|
+
availableModels.length > 0 ? createElement(
|
|
3093
|
+
"select",
|
|
3094
|
+
{
|
|
3095
|
+
ref: editModelRef,
|
|
3096
|
+
defaultValue: editingProvider?.model ?? "",
|
|
3097
|
+
"data-input": "model"
|
|
3098
|
+
},
|
|
3099
|
+
createElement("option", { value: "", disabled: true }, "Select a model\u2026"),
|
|
3100
|
+
...availableModels.map(
|
|
3101
|
+
(m) => createElement("option", { key: m.id, value: m.id }, m.name || m.id)
|
|
3102
|
+
)
|
|
3103
|
+
) : createElement("input", {
|
|
3104
|
+
ref: editModelRef,
|
|
3105
|
+
defaultValue: editingProvider?.model ?? "",
|
|
3106
|
+
placeholder: "Model name",
|
|
3107
|
+
"data-input": "model"
|
|
3108
|
+
}),
|
|
3109
|
+
createElement("input", {
|
|
3110
|
+
ref: editLabelRef,
|
|
3111
|
+
defaultValue: editingProvider?.label ?? "",
|
|
3112
|
+
placeholder: "Display label",
|
|
3113
|
+
"data-input": "label"
|
|
3114
|
+
}),
|
|
3115
|
+
createElement("button", {
|
|
3116
|
+
type: "button",
|
|
3117
|
+
"data-action": "update-provider",
|
|
3118
|
+
onClick: handleUpdate
|
|
3119
|
+
}, "Update")
|
|
3120
|
+
)
|
|
3121
|
+
);
|
|
3122
|
+
}
|
|
3123
|
+
function formatTokens(n) {
|
|
3124
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
3125
|
+
return String(n);
|
|
3126
|
+
}
|
|
3127
|
+
function ContextStatsDisplay({ stats, className }) {
|
|
3128
|
+
if (!stats) return null;
|
|
3129
|
+
const hasRealData = stats.realPromptTokens != null && stats.modelContextWindow != null;
|
|
3130
|
+
if (!hasRealData) return null;
|
|
3131
|
+
const promptTokens = stats.realPromptTokens;
|
|
3132
|
+
const contextWindow = stats.modelContextWindow;
|
|
3133
|
+
const availableBudget = Math.max(0, contextWindow - promptTokens);
|
|
3134
|
+
const usagePercent = contextWindow > 0 ? Math.round(promptTokens / contextWindow * 100) : 0;
|
|
3135
|
+
return createElement(
|
|
3136
|
+
"div",
|
|
3137
|
+
{
|
|
3138
|
+
"data-context-stats": "",
|
|
3139
|
+
"data-context-truncated": stats.wasTruncated ? "true" : "false",
|
|
3140
|
+
className
|
|
3141
|
+
},
|
|
3142
|
+
createElement(
|
|
3143
|
+
"span",
|
|
3144
|
+
{ "data-context-tokens": "" },
|
|
3145
|
+
`${formatTokens(promptTokens)} tokens`
|
|
3146
|
+
),
|
|
3147
|
+
createElement(
|
|
3148
|
+
"span",
|
|
3149
|
+
{ "data-context-budget": "" },
|
|
3150
|
+
`${formatTokens(availableBudget)} available`
|
|
3151
|
+
),
|
|
3152
|
+
createElement(
|
|
3153
|
+
"span",
|
|
3154
|
+
{ "data-context-usage": "", "data-usage-percent": String(usagePercent) },
|
|
3155
|
+
`${usagePercent}%`
|
|
3156
|
+
),
|
|
3157
|
+
stats.removedCount > 0 ? createElement(
|
|
3158
|
+
"span",
|
|
3159
|
+
{ "data-context-removed": "" },
|
|
3160
|
+
`${stats.removedCount} trimmed`
|
|
3161
|
+
) : null
|
|
3162
|
+
);
|
|
3163
|
+
}
|
|
3164
|
+
function ChatLayout({ children, sidebar, overlay, className }) {
|
|
3165
|
+
const overlayNodes = Array.isArray(overlay) ? overlay : [overlay ?? null];
|
|
3166
|
+
return createElement(
|
|
3167
|
+
"div",
|
|
3168
|
+
{ "data-chat-ui": "", className },
|
|
3169
|
+
...overlayNodes,
|
|
3170
|
+
sidebar ?? null,
|
|
3171
|
+
children
|
|
3172
|
+
);
|
|
3173
|
+
}
|
|
3174
|
+
function ChatHeader({
|
|
3175
|
+
showBackendSelector = false,
|
|
3176
|
+
showModelSelector = true,
|
|
3177
|
+
hasProviders = false,
|
|
3178
|
+
backends = [],
|
|
3179
|
+
models = [],
|
|
3180
|
+
selectedModel,
|
|
3181
|
+
onBackendSelect,
|
|
3182
|
+
onModelSelect,
|
|
3183
|
+
BackendSelectorComponent: BSC = BackendSelector,
|
|
3184
|
+
ModelSelectorComponent: MSC = ModelSelector
|
|
3185
|
+
}) {
|
|
3186
|
+
const children = [];
|
|
3187
|
+
if (showBackendSelector) {
|
|
3188
|
+
children.push(
|
|
3189
|
+
createElement(BSC, {
|
|
3190
|
+
key: "backend-selector",
|
|
3191
|
+
backends,
|
|
3192
|
+
onSelect: onBackendSelect ?? (() => {
|
|
3193
|
+
})
|
|
3194
|
+
})
|
|
3195
|
+
);
|
|
3196
|
+
}
|
|
3197
|
+
if (showModelSelector && !hasProviders && models.length > 0) {
|
|
3198
|
+
children.push(
|
|
3199
|
+
createElement(MSC, {
|
|
3200
|
+
key: "model-selector",
|
|
3201
|
+
models,
|
|
3202
|
+
selectedModel,
|
|
3203
|
+
onSelect: onModelSelect ?? (() => {
|
|
3204
|
+
})
|
|
3205
|
+
})
|
|
3206
|
+
);
|
|
3207
|
+
}
|
|
3208
|
+
if (children.length === 0) return null;
|
|
3209
|
+
return createElement("div", { "data-chat-header": "" }, ...children);
|
|
3210
|
+
}
|
|
3211
|
+
function UsageBadge({ usage, className }) {
|
|
3212
|
+
if (!usage) return null;
|
|
3213
|
+
return createElement(
|
|
3214
|
+
"span",
|
|
3215
|
+
{ "data-usage-badge": "true", className },
|
|
3216
|
+
createElement("span", { "data-usage-tokens": "prompt" }, `\u2191${usage.promptTokens}`),
|
|
3217
|
+
createElement("span", { "data-usage-tokens": "completion" }, `\u2193${usage.completionTokens}`),
|
|
3218
|
+
createElement("span", { "data-usage-tokens": "total" }, `\u03A3${usage.totalTokens}`)
|
|
3219
|
+
);
|
|
3220
|
+
}
|
|
3221
|
+
|
|
3222
|
+
// src/chat/react/ChatInputArea.ts
|
|
3223
|
+
function ChatInputArea({
|
|
3224
|
+
onSend,
|
|
3225
|
+
onStop,
|
|
3226
|
+
isGenerating,
|
|
3227
|
+
placeholder,
|
|
3228
|
+
providers = [],
|
|
3229
|
+
models = [],
|
|
3230
|
+
activeProviderId,
|
|
3231
|
+
selectedModel,
|
|
3232
|
+
onSelectProvider,
|
|
3233
|
+
onSelectModel,
|
|
3234
|
+
onSettingsClick,
|
|
3235
|
+
ComposerComponent: CC = Composer,
|
|
3236
|
+
ProviderModelSelectorComponent: PMSC = ProviderModelSelector,
|
|
3237
|
+
usage
|
|
3238
|
+
}) {
|
|
3239
|
+
const selectorRow = createElement(
|
|
3240
|
+
"div",
|
|
3241
|
+
{ "data-chat-input-controls": "" },
|
|
3242
|
+
createElement(PMSC, {
|
|
3243
|
+
providers,
|
|
3244
|
+
models,
|
|
3245
|
+
activeProviderId,
|
|
3246
|
+
selectedModel,
|
|
3247
|
+
onSelectProvider,
|
|
3248
|
+
onSelectModel,
|
|
3249
|
+
onSettingsClick
|
|
3250
|
+
}),
|
|
3251
|
+
usage ? createElement(UsageBadge, { usage }) : null
|
|
3252
|
+
);
|
|
3253
|
+
return createElement(
|
|
3254
|
+
"div",
|
|
3255
|
+
{ "data-chat-input-area": "" },
|
|
3256
|
+
createElement(
|
|
3257
|
+
"div",
|
|
3258
|
+
{ "data-chat-input-container": "" },
|
|
3259
|
+
selectorRow,
|
|
3260
|
+
createElement(CC, {
|
|
3261
|
+
onSend,
|
|
3262
|
+
onStop,
|
|
3263
|
+
isGenerating,
|
|
3264
|
+
placeholder
|
|
3265
|
+
})
|
|
3266
|
+
)
|
|
3267
|
+
);
|
|
3268
|
+
}
|
|
3269
|
+
var FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
|
|
3270
|
+
var CLOSE_ANIMATION_MS = 150;
|
|
3271
|
+
function ChatSettingsOverlay({
|
|
3272
|
+
open,
|
|
3273
|
+
onClose,
|
|
3274
|
+
providers = [],
|
|
3275
|
+
authBaseUrl,
|
|
3276
|
+
onProviderCreated,
|
|
3277
|
+
onProviderDeleted,
|
|
3278
|
+
onProviderUpdated,
|
|
3279
|
+
onAuthCompleted,
|
|
3280
|
+
ProviderSettingsComponent: PSC = ProviderSettings
|
|
3281
|
+
}) {
|
|
3282
|
+
const [isClosing, setIsClosing] = useState(false);
|
|
3283
|
+
const contentRef = useRef(null);
|
|
3284
|
+
const previousFocusRef = useRef(null);
|
|
3285
|
+
const handleClose = useCallback(() => {
|
|
3286
|
+
setIsClosing(true);
|
|
3287
|
+
setTimeout(() => {
|
|
3288
|
+
setIsClosing(false);
|
|
3289
|
+
onClose();
|
|
3290
|
+
}, CLOSE_ANIMATION_MS);
|
|
3291
|
+
}, [onClose]);
|
|
3292
|
+
const handleKeyDown = useCallback((e) => {
|
|
3293
|
+
if (e.key === "Escape") {
|
|
3294
|
+
e.stopPropagation();
|
|
3295
|
+
handleClose();
|
|
3296
|
+
return;
|
|
3297
|
+
}
|
|
3298
|
+
if (e.key === "Tab" && contentRef.current) {
|
|
3299
|
+
const focusable = Array.from(contentRef.current.querySelectorAll(FOCUSABLE));
|
|
3300
|
+
if (focusable.length === 0) return;
|
|
3301
|
+
const first = focusable[0];
|
|
3302
|
+
const last = focusable[focusable.length - 1];
|
|
3303
|
+
if (e.shiftKey && document.activeElement === first) {
|
|
3304
|
+
e.preventDefault();
|
|
3305
|
+
last.focus();
|
|
3306
|
+
} else if (!e.shiftKey && document.activeElement === last) {
|
|
3307
|
+
e.preventDefault();
|
|
3308
|
+
first.focus();
|
|
3309
|
+
}
|
|
3310
|
+
}
|
|
3311
|
+
}, [handleClose]);
|
|
3312
|
+
const handleBackdropClick = useCallback((e) => {
|
|
3313
|
+
if (e.target === e.currentTarget) handleClose();
|
|
3314
|
+
}, [handleClose]);
|
|
3315
|
+
useEffect(() => {
|
|
3316
|
+
if (!open) return;
|
|
3317
|
+
previousFocusRef.current = document.activeElement;
|
|
3318
|
+
document.addEventListener("keydown", handleKeyDown);
|
|
3319
|
+
const timer = setTimeout(() => {
|
|
3320
|
+
if (contentRef.current) {
|
|
3321
|
+
const first = contentRef.current.querySelector(FOCUSABLE);
|
|
3322
|
+
if (first) first.focus();
|
|
3323
|
+
}
|
|
3324
|
+
}, 50);
|
|
3325
|
+
return () => {
|
|
3326
|
+
document.removeEventListener("keydown", handleKeyDown);
|
|
3327
|
+
clearTimeout(timer);
|
|
3328
|
+
const prev = previousFocusRef.current;
|
|
3329
|
+
if (prev && typeof prev.focus === "function") prev.focus();
|
|
3330
|
+
};
|
|
3331
|
+
}, [open, handleKeyDown]);
|
|
3332
|
+
if (!open && !isClosing) return null;
|
|
3333
|
+
return createElement(
|
|
3334
|
+
"div",
|
|
3335
|
+
{
|
|
3336
|
+
"data-provider-settings-overlay": "true",
|
|
3337
|
+
"data-closing": isClosing ? "true" : void 0,
|
|
3338
|
+
onClick: handleBackdropClick,
|
|
3339
|
+
role: "dialog",
|
|
3340
|
+
"aria-modal": "true",
|
|
3341
|
+
"aria-label": "Provider settings"
|
|
3342
|
+
},
|
|
3343
|
+
createElement(
|
|
3344
|
+
"div",
|
|
3345
|
+
{
|
|
3346
|
+
ref: contentRef,
|
|
3347
|
+
"data-provider-settings-content": "true",
|
|
3348
|
+
"data-closing": isClosing ? "true" : void 0
|
|
3349
|
+
},
|
|
3350
|
+
createElement(PSC, {
|
|
3351
|
+
providers,
|
|
3352
|
+
authBaseUrl,
|
|
3353
|
+
onClose: handleClose,
|
|
3354
|
+
onProviderCreated: onProviderCreated ?? void 0,
|
|
3355
|
+
onProviderDeleted: onProviderDeleted ?? void 0,
|
|
3356
|
+
onProviderUpdated: onProviderUpdated ?? void 0,
|
|
3357
|
+
onAuthCompleted: onAuthCompleted ?? void 0
|
|
3358
|
+
})
|
|
3359
|
+
)
|
|
3360
|
+
);
|
|
3361
|
+
}
|
|
3362
|
+
|
|
3363
|
+
// src/chat/react/ChatUI.ts
|
|
3364
|
+
function ChatUIInner({
|
|
3365
|
+
slots,
|
|
3366
|
+
className,
|
|
3367
|
+
showSidebar = true,
|
|
3368
|
+
showModelSelector = true,
|
|
3369
|
+
showBackendSelector: showBackendSelectorProp,
|
|
3370
|
+
showProviderSelector: _showProviderSelectorProp,
|
|
3371
|
+
authBaseUrl,
|
|
3372
|
+
placeholder
|
|
3373
|
+
}) {
|
|
3374
|
+
const runtime = useChatRuntime();
|
|
3375
|
+
const { messages, sendMessage, stop, isGenerating, newSession, error, clearError, retryLastMessage, usage } = useChat();
|
|
3376
|
+
const { sessions } = useSessions();
|
|
3377
|
+
const { models, refresh: refreshModels } = useModels();
|
|
3378
|
+
const { backends } = useBackends();
|
|
3379
|
+
const { providers, createProvider, updateProvider, deleteProvider, selectProvider, refresh } = useProviders();
|
|
3380
|
+
const [settingsOpen, setSettingsOpen] = useState(false);
|
|
3381
|
+
const [activeProviderId, setActiveProviderId] = useState(void 0);
|
|
3382
|
+
const [selectedModelId, setSelectedModelId] = useState(void 0);
|
|
3383
|
+
const [searchQuery, setSearchQuery] = useState("");
|
|
3384
|
+
const hasProviders = providers.length > 0;
|
|
3385
|
+
useEffect(() => {
|
|
3386
|
+
if (providers.length > 0 && !activeProviderId) {
|
|
3387
|
+
setActiveProviderId(providers[0].id);
|
|
3388
|
+
selectProvider(providers[0].id);
|
|
3389
|
+
}
|
|
3390
|
+
}, [providers, activeProviderId, selectProvider]);
|
|
3391
|
+
const showBackendSelectorResolved = showBackendSelectorProp ?? false;
|
|
3392
|
+
const handleSelect = useCallback(async (id) => {
|
|
3393
|
+
try {
|
|
3394
|
+
await runtime.switchSession(id);
|
|
3395
|
+
} catch {
|
|
3396
|
+
}
|
|
3397
|
+
}, [runtime]);
|
|
3398
|
+
const handleCreate = useCallback(async () => {
|
|
3399
|
+
try {
|
|
3400
|
+
await newSession();
|
|
3401
|
+
} catch {
|
|
3402
|
+
}
|
|
3403
|
+
}, [newSession]);
|
|
3404
|
+
const handleDelete = useCallback(async (id) => {
|
|
3405
|
+
try {
|
|
3406
|
+
await runtime.deleteSession(id);
|
|
3407
|
+
} catch {
|
|
3408
|
+
}
|
|
3409
|
+
}, [runtime]);
|
|
3410
|
+
const handleModelSelect = useCallback((modelId) => {
|
|
3411
|
+
setSelectedModelId(modelId);
|
|
3412
|
+
}, []);
|
|
3413
|
+
const handleBackendSelect = useCallback((_name) => {
|
|
3414
|
+
refreshModels();
|
|
3415
|
+
}, [refreshModels]);
|
|
3416
|
+
const handleProviderSelect = useCallback((id) => {
|
|
3417
|
+
selectProvider(id);
|
|
3418
|
+
setActiveProviderId(id);
|
|
3419
|
+
}, [selectProvider]);
|
|
3420
|
+
const hasSlotOverrides = !!(slots?.renderToolCall || slots?.renderMessage || slots?.renderThinkingBlock);
|
|
3421
|
+
const ThreadComponent = slots?.thread ?? Thread;
|
|
3422
|
+
const ThreadListComponent = slots?.threadList ?? ThreadList;
|
|
3423
|
+
const ContextStatsComponent = slots?.contextStats ?? ContextStatsDisplay;
|
|
3424
|
+
const [contextStats, setContextStats] = useState(null);
|
|
3425
|
+
useEffect(() => {
|
|
3426
|
+
if (!runtime.activeSessionId) {
|
|
3427
|
+
setContextStats(null);
|
|
3428
|
+
return;
|
|
3429
|
+
}
|
|
3430
|
+
const result = runtime.getContextStats(runtime.activeSessionId);
|
|
3431
|
+
if (result instanceof Promise) {
|
|
3432
|
+
result.then(setContextStats, () => setContextStats(null));
|
|
3433
|
+
} else {
|
|
3434
|
+
setContextStats(result);
|
|
3435
|
+
}
|
|
3436
|
+
}, [runtime, runtime.activeSessionId, messages.length]);
|
|
3437
|
+
const showEmptyState = !hasProviders && messages.length === 0;
|
|
3438
|
+
const mainContent = createElement(
|
|
3439
|
+
"div",
|
|
3440
|
+
{ "data-chat-main": "" },
|
|
3441
|
+
createElement(ChatHeader, {
|
|
3442
|
+
showBackendSelector: showBackendSelectorResolved,
|
|
3443
|
+
showModelSelector,
|
|
3444
|
+
hasProviders,
|
|
3445
|
+
backends,
|
|
3446
|
+
models,
|
|
3447
|
+
selectedModel: selectedModelId,
|
|
3448
|
+
onBackendSelect: handleBackendSelect,
|
|
3449
|
+
onModelSelect: handleModelSelect,
|
|
3450
|
+
BackendSelectorComponent: slots?.backendSelector,
|
|
3451
|
+
ModelSelectorComponent: slots?.modelSelector
|
|
3452
|
+
}),
|
|
3453
|
+
contextStats ? createElement(ContextStatsComponent, { stats: contextStats }) : null,
|
|
3454
|
+
error ? createElement(
|
|
3455
|
+
"div",
|
|
3456
|
+
{ "data-chat-error": "" },
|
|
3457
|
+
createElement("span", { "data-chat-error-text": "" }, error.message),
|
|
3458
|
+
createElement(
|
|
3459
|
+
"div",
|
|
3460
|
+
{ "data-chat-error-actions": "" },
|
|
3461
|
+
createElement("button", {
|
|
3462
|
+
"data-action": "retry",
|
|
3463
|
+
type: "button",
|
|
3464
|
+
onClick: retryLastMessage
|
|
3465
|
+
}, "Retry"),
|
|
3466
|
+
createElement("button", {
|
|
3467
|
+
"data-action": "dismiss-error",
|
|
3468
|
+
type: "button",
|
|
3469
|
+
onClick: clearError
|
|
3470
|
+
}, "\u2715")
|
|
3471
|
+
),
|
|
3472
|
+
error.stack ? createElement(
|
|
3473
|
+
"details",
|
|
3474
|
+
{ "data-chat-error-details": "" },
|
|
3475
|
+
createElement("summary", null, "Details"),
|
|
3476
|
+
createElement("pre", null, error.stack)
|
|
3477
|
+
) : null
|
|
3478
|
+
) : null,
|
|
3479
|
+
showEmptyState ? createElement(
|
|
3480
|
+
"div",
|
|
3481
|
+
{ "data-chat-empty-state": "" },
|
|
3482
|
+
createElement("div", { "data-chat-empty-title": "" }, "Connect a provider to start chatting"),
|
|
3483
|
+
createElement("button", {
|
|
3484
|
+
"data-action": "open-settings",
|
|
3485
|
+
onClick: () => setSettingsOpen(true)
|
|
3486
|
+
}, "+ Connect Provider")
|
|
3487
|
+
) : createElement(ThreadComponent, { messages, isGenerating, autoScroll: true }),
|
|
3488
|
+
createElement(ChatInputArea, {
|
|
3489
|
+
onSend: sendMessage,
|
|
3490
|
+
onStop: stop,
|
|
3491
|
+
isGenerating,
|
|
3492
|
+
placeholder,
|
|
3493
|
+
providers,
|
|
3494
|
+
models,
|
|
3495
|
+
activeProviderId,
|
|
3496
|
+
selectedModel: selectedModelId,
|
|
3497
|
+
onSelectProvider: handleProviderSelect,
|
|
3498
|
+
onSelectModel: handleModelSelect,
|
|
3499
|
+
onSettingsClick: () => setSettingsOpen(true),
|
|
3500
|
+
ComposerComponent: slots?.composer,
|
|
3501
|
+
ProviderModelSelectorComponent: slots?.providerModelSelector,
|
|
3502
|
+
usage
|
|
3503
|
+
})
|
|
3504
|
+
);
|
|
3505
|
+
const wrappedMain = hasSlotOverrides ? createElement(ThreadProvider, {
|
|
3506
|
+
renderToolCall: slots.renderToolCall,
|
|
3507
|
+
renderMessage: slots.renderMessage,
|
|
3508
|
+
renderThinkingBlock: slots.renderThinkingBlock,
|
|
3509
|
+
children: mainContent
|
|
3510
|
+
}) : mainContent;
|
|
3511
|
+
const sidebar = showSidebar ? createElement(ThreadListComponent, {
|
|
3512
|
+
sessions,
|
|
3513
|
+
activeSessionId: runtime.activeSessionId ?? void 0,
|
|
3514
|
+
onSelect: handleSelect,
|
|
3515
|
+
onCreate: handleCreate,
|
|
3516
|
+
onDelete: handleDelete,
|
|
3517
|
+
searchQuery,
|
|
3518
|
+
onSearchChange: setSearchQuery
|
|
3519
|
+
}) : void 0;
|
|
3520
|
+
const settingsOverlay = createElement(ChatSettingsOverlay, {
|
|
3521
|
+
open: settingsOpen,
|
|
3522
|
+
onClose: () => setSettingsOpen(false),
|
|
3523
|
+
providers,
|
|
3524
|
+
authBaseUrl,
|
|
3525
|
+
onProviderCreated: (p) => createProvider({ backend: p.backend, model: p.model, label: p.label ?? "" }),
|
|
3526
|
+
onProviderDeleted: (id) => deleteProvider(id),
|
|
3527
|
+
onProviderUpdated: (id, changes) => updateProvider(id, changes),
|
|
3528
|
+
onAuthCompleted: () => refresh(),
|
|
3529
|
+
ProviderSettingsComponent: slots?.providerSettings
|
|
3530
|
+
});
|
|
3531
|
+
return createElement(ChatLayout, {
|
|
3532
|
+
className,
|
|
3533
|
+
sidebar,
|
|
3534
|
+
overlay: [slots?.authDialog ?? null, settingsOverlay],
|
|
3535
|
+
children: wrappedMain
|
|
3536
|
+
});
|
|
3537
|
+
}
|
|
3538
|
+
function ChatUI({ runtime, ...rest }) {
|
|
3539
|
+
return createElement(ChatProvider, {
|
|
3540
|
+
runtime,
|
|
3541
|
+
children: createElement(ChatUIInner, rest)
|
|
3542
|
+
});
|
|
3543
|
+
}
|
|
3544
|
+
|
|
3545
|
+
export { BackendSelector, ChatHeader, ChatInputArea, ChatLayout, ChatProvider, ChatSettingsOverlay, ChatUI, ClaudeAuthForm, Composer, ContextStatsDisplay, CopilotAuthForm, MarkdownRenderer, Message, ModelSelector, ProviderModelSelector, ProviderSelector, ProviderSettings, RemoteChatClient, ThinkingBlock, Thread, ThreadList, ThreadProvider, ToolCallView, UsageBadge, VercelAIAuthForm, useApiKeyAuth, useBackends, useChat, useChatRuntime, useClaudeAuth, useCopilotAuth, useMessages, useModels, useOptionalThreadSlots, useProviders, useRemoteAuth, useRemoteChat, useSSE, useSessions, useThreadSlots, useToolApproval };
|
|
3546
|
+
//# sourceMappingURL=react.js.map
|
|
3547
|
+
//# sourceMappingURL=react.js.map
|