@truefoundry/trueforge-ui 0.0.0 → 0.1.0-rc.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +340 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +17 -0
  4. package/README.md +640 -3
  5. package/dist/ConnectorSettings-CLBEWGQJ.js +898 -0
  6. package/dist/ConnectorSettings-CLBEWGQJ.js.map +1 -0
  7. package/dist/DockLayout-WRF7EQLD.js +35 -0
  8. package/dist/DockLayout-WRF7EQLD.js.map +1 -0
  9. package/dist/DrawerLayout-X2UXYTOS.js +156 -0
  10. package/dist/DrawerLayout-X2UXYTOS.js.map +1 -0
  11. package/dist/ModelSettings-IJ55QJQO.js +1082 -0
  12. package/dist/ModelSettings-IJ55QJQO.js.map +1 -0
  13. package/dist/OpenUiFenceBlock-SLLZSTMJ.js +9 -0
  14. package/dist/OpenUiFenceBlock-SLLZSTMJ.js.map +1 -0
  15. package/dist/SandboxSettings-S5XGZWOL.js +505 -0
  16. package/dist/SandboxSettings-S5XGZWOL.js.map +1 -0
  17. package/dist/SettingsBuilder-64Y33NP3.js +128 -0
  18. package/dist/SettingsBuilder-64Y33NP3.js.map +1 -0
  19. package/dist/SidebarLayout-M7HEOZVK.js +236 -0
  20. package/dist/SidebarLayout-M7HEOZVK.js.map +1 -0
  21. package/dist/SkillSettings-MXK4ZEI7.js +389 -0
  22. package/dist/SkillSettings-MXK4ZEI7.js.map +1 -0
  23. package/dist/WidgetLayout-7MDOKLHU.js +101 -0
  24. package/dist/WidgetLayout-7MDOKLHU.js.map +1 -0
  25. package/dist/assistant-ui.d.ts +1 -0
  26. package/dist/assistant-ui.js +9 -0
  27. package/dist/assistant-ui.js.map +1 -0
  28. package/dist/chunk-42GF723P.js +24 -0
  29. package/dist/chunk-42GF723P.js.map +1 -0
  30. package/dist/chunk-CFLVPV5M.js +29 -0
  31. package/dist/chunk-CFLVPV5M.js.map +1 -0
  32. package/dist/chunk-M6MHLVSO.js +8 -0
  33. package/dist/chunk-M6MHLVSO.js.map +1 -0
  34. package/dist/chunk-NBMP2XNL.js +89 -0
  35. package/dist/chunk-NBMP2XNL.js.map +1 -0
  36. package/dist/chunk-UBOFEI77.js +567 -0
  37. package/dist/chunk-UBOFEI77.js.map +1 -0
  38. package/dist/chunk-UHGSHDBM.js +633 -0
  39. package/dist/chunk-UHGSHDBM.js.map +1 -0
  40. package/dist/chunk-UXZOL5GO.js +2088 -0
  41. package/dist/chunk-UXZOL5GO.js.map +1 -0
  42. package/dist/chunk-WFC3W4C3.js +73 -0
  43. package/dist/chunk-WFC3W4C3.js.map +1 -0
  44. package/dist/chunk-XSHXH6EI.js +6800 -0
  45. package/dist/chunk-XSHXH6EI.js.map +1 -0
  46. package/dist/createTrueFoundryServer-B72bU-J7.d.ts +28 -0
  47. package/dist/index.d.ts +1569 -0
  48. package/dist/index.js +781 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/plugins/trueforge-agent-server-adapter/index.d.ts +479 -0
  51. package/dist/plugins/trueforge-agent-server-adapter/index.js +830 -0
  52. package/dist/plugins/trueforge-agent-server-adapter/index.js.map +1 -0
  53. package/dist/styles.css +2 -0
  54. package/package.json +129 -6
  55. package/index.js +0 -1
@@ -0,0 +1,2088 @@
1
+ import {
2
+ useAui,
3
+ useAuiState
4
+ } from "./chunk-M6MHLVSO.js";
5
+ import {
6
+ ASK_USER_CUSTOM_OPTION,
7
+ BottomSheet,
8
+ Button,
9
+ DraftCatalogProvider,
10
+ SearchInput_default,
11
+ SlotsProvider,
12
+ USER_MESSAGE_ATTACHMENT_PREVIEW_REM,
13
+ canReuseMutableShell,
14
+ preloadMarkdownOpenUI,
15
+ readThreadAgentName,
16
+ threadListIndicesByRecency,
17
+ threadListItemIsMutable,
18
+ useIsMobile,
19
+ useSearchAgentsList,
20
+ useSlot,
21
+ useSlotIsDefault,
22
+ useToasterOptional
23
+ } from "./chunk-XSHXH6EI.js";
24
+ import {
25
+ Icon,
26
+ auiButtonClass,
27
+ libraryAgentId,
28
+ useCompactLayout,
29
+ useOptionalServer,
30
+ useOptionalShellMode
31
+ } from "./chunk-UHGSHDBM.js";
32
+ import {
33
+ cn
34
+ } from "./chunk-UBOFEI77.js";
35
+
36
+ // src/containers/AgentStepsContainer.tsx
37
+ import { useEffect, useRef, useState } from "react";
38
+ import { jsx } from "react/jsx-runtime";
39
+ function AgentStepsContainer({
40
+ children,
41
+ toolCount,
42
+ thinkingCount,
43
+ hasFinal
44
+ }) {
45
+ const AgentStepsCard = useSlot("AgentStepsCard");
46
+ const [expanded, setExpanded] = useState(true);
47
+ const collapsedByFinal = useRef(false);
48
+ useEffect(() => {
49
+ if (hasFinal && !collapsedByFinal.current) {
50
+ collapsedByFinal.current = true;
51
+ setExpanded(false);
52
+ }
53
+ }, [hasFinal]);
54
+ return /* @__PURE__ */ jsx(
55
+ AgentStepsCard,
56
+ {
57
+ toolCount,
58
+ thinkingCount,
59
+ expanded,
60
+ onToggle: () => setExpanded((prev) => !prev),
61
+ children
62
+ }
63
+ );
64
+ }
65
+
66
+ // src/containers/AskUserContainer.tsx
67
+ import { useThreadIsRunning } from "@assistant-ui/core/react";
68
+ import { useTrueFoundryToolResponses } from "@truefoundry/assistant-ui-runtime";
69
+ import { useCallback, useEffect as useEffect2, useMemo, useState as useState2 } from "react";
70
+ import { jsx as jsx2 } from "react/jsx-runtime";
71
+ var EMPTY_ANSWER = { radioValue: "", custom: "" };
72
+ function AskUserContainer() {
73
+ const AskUserPrompt = useSlot("AskUserPrompt");
74
+ const { pending, respond } = useTrueFoundryToolResponses();
75
+ const isRunning = useThreadIsRunning();
76
+ const item = pending[0];
77
+ const questions = useMemo(
78
+ () => item == null ? [] : [
79
+ {
80
+ id: item.toolCallId,
81
+ question: item.question ?? "Answer required",
82
+ options: item.options ?? []
83
+ }
84
+ ],
85
+ [item]
86
+ );
87
+ const [currentQuestionIndex, setCurrentQuestionIndex] = useState2(0);
88
+ const [answers, setAnswers] = useState2({});
89
+ useEffect2(() => {
90
+ setCurrentQuestionIndex(0);
91
+ setAnswers({});
92
+ }, [item?.toolCallId]);
93
+ const safeIndex = Math.min(currentQuestionIndex, Math.max(questions.length - 1, 0));
94
+ const currentQuestion = questions[safeIndex];
95
+ const currentAnswer = currentQuestion == null ? EMPTY_ANSWER : answers[currentQuestion.id] ?? EMPTY_ANSWER;
96
+ const getResponseForQuestion = useCallback(
97
+ (questionId) => {
98
+ const answer = answers[questionId] ?? EMPTY_ANSWER;
99
+ return answer.radioValue === ASK_USER_CUSTOM_OPTION ? answer.custom.trim() : answer.radioValue.trim();
100
+ },
101
+ [answers]
102
+ );
103
+ const allQuestionsAnswered = useMemo(
104
+ () => questions.every((question) => getResponseForQuestion(question.id)),
105
+ [getResponseForQuestion, questions]
106
+ );
107
+ const selectedResponse = currentAnswer.radioValue === ASK_USER_CUSTOM_OPTION ? currentAnswer.custom.trim() : currentAnswer.radioValue.trim();
108
+ const isSubmitDisabled = isRunning || currentQuestion == null || selectedResponse.length === 0;
109
+ const isSubmitAllDisabled = isSubmitDisabled || !allQuestionsAnswered;
110
+ const onCurrentAnswerChange = useCallback((questionId, update) => {
111
+ setAnswers((previous) => ({
112
+ ...previous,
113
+ [questionId]: {
114
+ ...previous[questionId] ?? EMPTY_ANSWER,
115
+ ...update
116
+ }
117
+ }));
118
+ }, []);
119
+ const onSubmit = useCallback(() => {
120
+ if (item == null || !allQuestionsAnswered) return;
121
+ const content = getResponseForQuestion(item.toolCallId);
122
+ if (!content) return;
123
+ respond({ toolCallId: item.toolCallId, content });
124
+ }, [allQuestionsAnswered, getResponseForQuestion, item, respond]);
125
+ if (item == null || currentQuestion == null) return null;
126
+ return /* @__PURE__ */ jsx2(
127
+ AskUserPrompt,
128
+ {
129
+ questions,
130
+ readOnly: isRunning,
131
+ currentQuestion,
132
+ currentQuestionIndex: safeIndex,
133
+ currentAnswer,
134
+ totalQuestions: questions.length,
135
+ isMultiQuestion: questions.length > 1,
136
+ isLastQuestion: safeIndex === questions.length - 1,
137
+ allQuestionsAnswered,
138
+ isSubmitDisabled,
139
+ isSubmitAllDisabled,
140
+ onCurrentQuestionIndexChange: setCurrentQuestionIndex,
141
+ onCurrentAnswerChange,
142
+ onSubmit
143
+ }
144
+ );
145
+ }
146
+
147
+ // src/utils/computeAgentStepsSplit.ts
148
+ function computeAgentStepsSplit(parts, isRunning) {
149
+ const finalTexts = [];
150
+ let cutIdx = parts.length;
151
+ for (let i = parts.length - 1; i >= 0; i--) {
152
+ const part = parts[i];
153
+ if (!part) continue;
154
+ if (part.type === "text") {
155
+ const text = part.text ?? "";
156
+ const trimmed = text.trim();
157
+ if (trimmed) {
158
+ finalTexts.unshift({ index: i, content: text });
159
+ cutIdx = i;
160
+ } else {
161
+ cutIdx = i;
162
+ }
163
+ } else {
164
+ break;
165
+ }
166
+ }
167
+ const trailingChars = finalTexts.reduce((sum, t) => sum + t.content.length, 0);
168
+ const hasAgentStepsBeforeCut = parts.slice(0, cutIdx).some((p) => p.type === "tool-call" || p.type === "reasoning");
169
+ const finalConfirmed = finalTexts.length > 0 && (!isRunning || trailingChars >= 500 || !hasAgentStepsBeforeCut);
170
+ const actualCutIndex = finalConfirmed ? cutIdx : parts.length;
171
+ let toolCount = 0;
172
+ let thinkingCount = 0;
173
+ for (let i = 0; i < actualCutIndex; i++) {
174
+ const part = parts[i];
175
+ if (!part) continue;
176
+ if (part.type === "tool-call") {
177
+ toolCount++;
178
+ } else if (part.type === "reasoning") {
179
+ thinkingCount++;
180
+ }
181
+ }
182
+ return {
183
+ cutIndex: actualCutIndex,
184
+ hasFinal: finalConfirmed,
185
+ toolCount,
186
+ thinkingCount
187
+ };
188
+ }
189
+
190
+ // src/containers/AssistantTextContainer.tsx
191
+ import {
192
+ useAuiState as useAuiState2,
193
+ useSmooth
194
+ } from "@assistant-ui/react";
195
+ import { useTrueFoundryDownloadSandboxFile } from "@truefoundry/assistant-ui-runtime";
196
+ import { useCallback as useCallback2, useMemo as useMemo2, useRef as useRef3 } from "react";
197
+
198
+ // src/hooks/useThrottledMarkdownText.ts
199
+ import { useEffect as useEffect3, useRef as useRef2, useState as useState3 } from "react";
200
+ var MARKDOWN_SMOOTH_BACKLOG_CHARS = 4 * 1024;
201
+ var LARGE_MARKDOWN_THROTTLE_MS = 100;
202
+ function useThrottledMarkdownText(text, {
203
+ isComplete,
204
+ enabled,
205
+ throttleMs = LARGE_MARKDOWN_THROTTLE_MS
206
+ }) {
207
+ const [committed, setCommitted] = useState3(text);
208
+ const lastCommittedRef = useRef2(text);
209
+ const lastCommitAtRef = useRef2(Date.now());
210
+ const pendingRef = useRef2(text);
211
+ const wasEnabledRef = useRef2(enabled);
212
+ useEffect3(() => {
213
+ pendingRef.current = text;
214
+ const commit = (value) => {
215
+ if (value.length < lastCommittedRef.current.length && value !== lastCommittedRef.current) {
216
+ return;
217
+ }
218
+ lastCommittedRef.current = value;
219
+ lastCommitAtRef.current = Date.now();
220
+ setCommitted(value);
221
+ };
222
+ if (!enabled) {
223
+ wasEnabledRef.current = false;
224
+ lastCommittedRef.current = text;
225
+ lastCommitAtRef.current = Date.now();
226
+ setCommitted(text);
227
+ return;
228
+ }
229
+ if (!wasEnabledRef.current) {
230
+ wasEnabledRef.current = true;
231
+ commit(text);
232
+ return;
233
+ }
234
+ if (lastCommittedRef.current === text) return;
235
+ if (isComplete) {
236
+ commit(text);
237
+ return;
238
+ }
239
+ const elapsed = Date.now() - lastCommitAtRef.current;
240
+ if (elapsed >= throttleMs) {
241
+ commit(text);
242
+ return;
243
+ }
244
+ const id = setTimeout(() => {
245
+ commit(pendingRef.current);
246
+ }, throttleMs - elapsed);
247
+ return () => clearTimeout(id);
248
+ }, [text, isComplete, enabled, throttleMs]);
249
+ return enabled ? committed : text;
250
+ }
251
+
252
+ // src/containers/AssistantTextContainer.tsx
253
+ import { jsx as jsx3 } from "react/jsx-runtime";
254
+ function filenameFromPath(path) {
255
+ return path.split("/").pop() || "download";
256
+ }
257
+ function triggerBrowserDownload(blob, filename) {
258
+ if (typeof document === "undefined") return;
259
+ const url = URL.createObjectURL(blob);
260
+ const anchor = document.createElement("a");
261
+ anchor.href = url;
262
+ anchor.download = filename;
263
+ anchor.click();
264
+ URL.revokeObjectURL(url);
265
+ }
266
+ function AssistantTextContainer() {
267
+ const Markdown = useSlot("Markdown");
268
+ const toaster = useToasterOptional();
269
+ const downloadSandboxFile = useTrueFoundryDownloadSandboxFile();
270
+ const downloadRef = useRef3({ downloadSandboxFile, toaster });
271
+ downloadRef.current = { downloadSandboxFile, toaster };
272
+ const partState = useAuiState2((s) => s.part);
273
+ const pacedModeRef = useRef3(false);
274
+ const smoothedPart = useSmooth(
275
+ partState,
276
+ pacedModeRef.current ? false : {
277
+ drainMs: 150,
278
+ maxCharIntervalMs: 4,
279
+ maxCharsPerFrame: 128,
280
+ minCommitMs: 48
281
+ }
282
+ );
283
+ const networkComplete = partState.status?.type !== "running";
284
+ const smoothLag = partState.text.length - smoothedPart.text.length;
285
+ if (!pacedModeRef.current && !networkComplete && smoothLag >= MARKDOWN_SMOOTH_BACKLOG_CHARS) {
286
+ pacedModeRef.current = true;
287
+ }
288
+ const usePacedMode = pacedModeRef.current;
289
+ const pacedText = useThrottledMarkdownText(partState.text, {
290
+ enabled: usePacedMode,
291
+ isComplete: networkComplete
292
+ });
293
+ const text = usePacedMode ? pacedText : smoothedPart.text;
294
+ const isStreaming = usePacedMode ? !networkComplete || text !== partState.text : smoothedPart.status?.type === "running";
295
+ const handleDownloadArtifact = useCallback2(async (path) => {
296
+ const { downloadSandboxFile: downloadSandboxFile2, toaster: toaster2 } = downloadRef.current;
297
+ try {
298
+ triggerBrowserDownload(await downloadSandboxFile2(path), filenameFromPath(path));
299
+ } catch (error) {
300
+ if (toaster2 != null) {
301
+ toaster2.showError(error);
302
+ } else {
303
+ console.error("Failed to download sandbox artifact", error);
304
+ }
305
+ }
306
+ }, []);
307
+ return useMemo2(
308
+ () => /* @__PURE__ */ jsx3(Markdown, { content: text, isStreaming, onDownloadArtifact: handleDownloadArtifact }),
309
+ [Markdown, text, isStreaming, handleDownloadArtifact]
310
+ );
311
+ }
312
+
313
+ // src/containers/ReasoningContainer.tsx
314
+ import { useAuiState as useAuiState3 } from "@assistant-ui/react";
315
+ import { useCallback as useCallback3, useRef as useRef4, useState as useState4 } from "react";
316
+ import { jsx as jsx4 } from "react/jsx-runtime";
317
+ function ReasoningContainer({ group }) {
318
+ const ReasoningCard = useSlot("ReasoningCard");
319
+ const content = useAuiState3(
320
+ (s) => group.indices.map((i) => s.message.parts[i]).filter((p) => p != null && p.type === "reasoning").map((p) => p.text ?? "").join("")
321
+ );
322
+ const streaming = useAuiState3((s) => {
323
+ if (s.message.status?.type !== "running") return false;
324
+ const lastIndex = s.message.parts.length - 1;
325
+ if (lastIndex < 0) return false;
326
+ if (s.message.parts[lastIndex]?.type !== "reasoning") return false;
327
+ const lastGroupIndex = group.indices[group.indices.length - 1];
328
+ return lastGroupIndex !== void 0 && lastIndex >= group.indices[0] && lastIndex <= lastGroupIndex;
329
+ });
330
+ const [expanded, setExpanded] = useState4(streaming);
331
+ const [prevStreaming, setPrevStreaming] = useState4(streaming);
332
+ const [isMultiLine, setIsMultiLine] = useState4(false);
333
+ const observerRef = useRef4(null);
334
+ if (streaming !== prevStreaming) {
335
+ setPrevStreaming(streaming);
336
+ if (streaming) setExpanded(true);
337
+ }
338
+ const contentRef = useCallback3(
339
+ (node) => {
340
+ observerRef.current?.disconnect();
341
+ observerRef.current = null;
342
+ if (node == null || streaming) return;
343
+ const check = () => {
344
+ const lineHeight = Number.parseFloat(getComputedStyle(node).lineHeight) || 24;
345
+ setIsMultiLine(node.scrollHeight > lineHeight * 1.5);
346
+ };
347
+ check();
348
+ observerRef.current = new ResizeObserver(check);
349
+ observerRef.current.observe(node);
350
+ },
351
+ [streaming]
352
+ );
353
+ const reasoningTimeText = null;
354
+ const previewText = content.replace(/\s+/g, " ").trim();
355
+ const isShortText = !streaming && content.length > 0 && !isMultiLine;
356
+ const headingText = "Reasoning";
357
+ return /* @__PURE__ */ jsx4(
358
+ ReasoningCard,
359
+ {
360
+ content,
361
+ isStreaming: streaming,
362
+ expanded,
363
+ isMultiLine,
364
+ reasoningTimeText,
365
+ previewText,
366
+ headingText,
367
+ contentRef: isShortText ? contentRef : void 0,
368
+ onToggle: () => setExpanded((prev) => !prev)
369
+ }
370
+ );
371
+ }
372
+
373
+ // src/containers/ToolApprovalContainer.tsx
374
+ import { useCallback as useCallback4, useMemo as useMemo3, useState as useState5 } from "react";
375
+ import { jsx as jsx5 } from "react/jsx-runtime";
376
+ function ToolApprovalContainer({ toolName = "", options, onSelectOption }) {
377
+ const ToolApprovalBar = useSlot("ToolApprovalBar");
378
+ const [selectedDenyOptionId, setSelectedDenyOptionId] = useState5(null);
379
+ const [denialReason, setDenialReason] = useState5("");
380
+ const [showReasonError, setShowReasonError] = useState5(false);
381
+ const approveOptions = useMemo3(
382
+ () => options.filter((option) => option.isAllow).map((option, index) => ({
383
+ ...option,
384
+ variant: index === 0 ? "primary" : "secondary",
385
+ requiresReason: false
386
+ })),
387
+ [options]
388
+ );
389
+ const denyOptions = useMemo3(
390
+ () => options.filter((option) => !option.isAllow).map((option) => ({
391
+ ...option,
392
+ variant: "secondary",
393
+ requiresReason: option.confirm != null
394
+ })),
395
+ [options]
396
+ );
397
+ const selectedDenyOption = denyOptions.find((option) => option.id === selectedDenyOptionId);
398
+ const onDenyOptionChange = useCallback4((optionId) => {
399
+ setSelectedDenyOptionId(optionId);
400
+ setDenialReason("");
401
+ setShowReasonError(false);
402
+ }, []);
403
+ const onDenialReasonChange = useCallback4((reason) => {
404
+ setDenialReason(reason);
405
+ setShowReasonError(false);
406
+ }, []);
407
+ const onReasonSubmit = useCallback4(() => {
408
+ const reason = denialReason.trim();
409
+ if (!reason) {
410
+ setShowReasonError(true);
411
+ return;
412
+ }
413
+ if (selectedDenyOptionId) {
414
+ onSelectOption(selectedDenyOptionId, reason);
415
+ onDenyOptionChange(null);
416
+ }
417
+ }, [denialReason, onDenyOptionChange, onSelectOption, selectedDenyOptionId]);
418
+ return /* @__PURE__ */ jsx5(
419
+ ToolApprovalBar,
420
+ {
421
+ toolName,
422
+ approveOptions: approveOptions.length > 0 ? approveOptions : void 0,
423
+ denyOptions: denyOptions.length > 0 ? denyOptions : void 0,
424
+ selectedDenyOption,
425
+ denialReason,
426
+ showReasonError,
427
+ onSelect: onSelectOption,
428
+ onDenyOptionChange,
429
+ onDenialReasonChange,
430
+ onReasonSubmit
431
+ }
432
+ );
433
+ }
434
+
435
+ // src/containers/ToolCallContentBlockContainer.tsx
436
+ import { useCallback as useCallback5, useEffect as useEffect4, useRef as useRef5, useState as useState6 } from "react";
437
+ import { jsx as jsx6 } from "react/jsx-runtime";
438
+ function ToolCallContentBlockContainer(props) {
439
+ const ToolCallContentBlock = useSlot("ToolCallContentBlock");
440
+ const { isJson, onContentHeightChange: notifyContentHeightChange, resizable } = props;
441
+ const [fullscreen, setFullscreen] = useState6(false);
442
+ const [contentHeightRem, setContentHeightRem] = useState6();
443
+ const observerRef = useRef5(null);
444
+ const contentNodeRef = useRef5(null);
445
+ const hasMeasuredRef = useRef5(false);
446
+ const contentRef = useCallback5(
447
+ (node) => {
448
+ observerRef.current?.disconnect();
449
+ observerRef.current = null;
450
+ contentNodeRef.current = node;
451
+ hasMeasuredRef.current = false;
452
+ if (node == null) return;
453
+ setContentHeightRem(void 0);
454
+ if (!resizable) return;
455
+ const updateHeight = () => {
456
+ if (!hasMeasuredRef.current && isJson !== false) return;
457
+ const renderedHeight = node.getBoundingClientRect().height;
458
+ const height = hasMeasuredRef.current && renderedHeight > 0 ? renderedHeight : node.scrollHeight;
459
+ hasMeasuredRef.current = true;
460
+ setContentHeightRem(height / 16);
461
+ };
462
+ updateHeight();
463
+ observerRef.current = new ResizeObserver(updateHeight);
464
+ observerRef.current.observe(node);
465
+ },
466
+ [isJson, resizable]
467
+ );
468
+ const onContentHeightChange = useCallback5(
469
+ (height) => {
470
+ const node = contentNodeRef.current;
471
+ if (node == null) return;
472
+ const renderedHeight = node.getBoundingClientRect().height;
473
+ hasMeasuredRef.current = true;
474
+ setContentHeightRem((renderedHeight > 0 ? renderedHeight : Math.max(height, node.scrollHeight)) / 16);
475
+ notifyContentHeightChange?.(height);
476
+ },
477
+ [notifyContentHeightChange]
478
+ );
479
+ useEffect4(
480
+ () => () => {
481
+ observerRef.current?.disconnect();
482
+ },
483
+ []
484
+ );
485
+ return /* @__PURE__ */ jsx6(
486
+ ToolCallContentBlock,
487
+ {
488
+ ...props,
489
+ fullscreen,
490
+ onFullscreenChange: setFullscreen,
491
+ contentHeightRem,
492
+ contentRef,
493
+ onContentHeightChange
494
+ }
495
+ );
496
+ }
497
+
498
+ // src/containers/ToolCallContainer.tsx
499
+ import {
500
+ MessagePartPrimitive,
501
+ MessagePrimitive,
502
+ useToolCallElapsed
503
+ } from "@assistant-ui/react";
504
+ import { useTrueFoundryRespondToToolApproval } from "@truefoundry/assistant-ui-runtime";
505
+ import { useState as useState8 } from "react";
506
+
507
+ // src/utils/toolCallParsing.ts
508
+ import { parse as parsePartialJson } from "partial-json";
509
+ var SUB_AGENT_TOOL_NAME = "create_sub_agent";
510
+ var ASK_USER_TOOL_NAME = "ask_user_question";
511
+ var SANDBOX_TOOL_NAMES = /* @__PURE__ */ new Set(["exec", "sandbox_exec"]);
512
+ var MCP_META_TOOLS = /* @__PURE__ */ new Set(["call_tool", "list_tools", "get_tool_info"]);
513
+ var APPROVAL_OPTION_DEFAULT_LABELS = {
514
+ "allow-once": "Allow",
515
+ "allow-always": "Always allow",
516
+ "reject-once": "Deny",
517
+ "reject-always": "Always deny"
518
+ };
519
+ var isAllowKind = (kind) => kind === "allow-once" || kind === "allow-always";
520
+ function parseJsonIncrementally(content) {
521
+ try {
522
+ return { success: true, value: JSON.parse(content), isPartial: false };
523
+ } catch {
524
+ const trimmed = content.trim();
525
+ if (trimmed[0] !== "{" && trimmed[0] !== "[") return { success: false };
526
+ try {
527
+ return { success: true, value: parsePartialJson(content), isPartial: true };
528
+ } catch {
529
+ return { success: false };
530
+ }
531
+ }
532
+ }
533
+ function isUnknownRecord(value) {
534
+ return value != null && typeof value === "object" && !Array.isArray(value);
535
+ }
536
+ function parseAskUserQuestionArgs(argsText) {
537
+ if (!argsText) return {};
538
+ try {
539
+ const parsed = JSON.parse(argsText);
540
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
541
+ return {};
542
+ }
543
+ const record = parsed;
544
+ const question = typeof record.question === "string" ? record.question : void 0;
545
+ const options = Array.isArray(record.options) ? record.options.filter((item) => typeof item === "string") : void 0;
546
+ return { question, options };
547
+ } catch {
548
+ return {};
549
+ }
550
+ }
551
+ function getAskUserAnswerResult(result) {
552
+ if (result === void 0 || result === null) return void 0;
553
+ if (typeof result === "string") {
554
+ const trimmed = result.trim();
555
+ return trimmed.length > 0 ? trimmed : void 0;
556
+ }
557
+ if (typeof result === "object" && "content" in result) {
558
+ const content = result.content;
559
+ if (typeof content === "string" && content.trim()) {
560
+ return content.trim();
561
+ }
562
+ }
563
+ return void 0;
564
+ }
565
+ function hasPendingAskUserResponse(part) {
566
+ return part.interrupt != null && part.result === void 0;
567
+ }
568
+ function hasPendingToolApproval(approval) {
569
+ return approval != null && approval.approved === void 0 && approval.resolution === void 0;
570
+ }
571
+ function buildApprovalOptions(options) {
572
+ const declared = options?.filter((o) => Object.hasOwn(APPROVAL_OPTION_DEFAULT_LABELS, o.kind));
573
+ if (declared && declared.length > 0) {
574
+ const allow = declared.filter((o) => isAllowKind(o.kind));
575
+ const reject = declared.filter((o) => !isAllowKind(o.kind));
576
+ const mapped = [...allow, ...reject].map((o) => ({
577
+ id: o.id,
578
+ label: o.label ?? APPROVAL_OPTION_DEFAULT_LABELS[o.kind] ?? o.id,
579
+ isAllow: isAllowKind(o.kind),
580
+ grants: o.grants,
581
+ confirm: o.confirm != null ? typeof o.confirm === "object" ? o.confirm : {} : void 0
582
+ }));
583
+ if (reject.length === 0) {
584
+ mapped.push({ id: "__deny", label: "Deny", isAllow: false, confirm: {} });
585
+ }
586
+ return mapped;
587
+ }
588
+ return [
589
+ { id: "__allow", label: "Allow", isAllow: true },
590
+ { id: "__deny", label: "Deny", isAllow: false, confirm: {} }
591
+ ];
592
+ }
593
+ function formatDuration(ms) {
594
+ if (ms < 1e3) return "<1s";
595
+ const seconds = ms / 1e3;
596
+ if (seconds < 10) return `${(Math.floor(seconds * 10) / 10).toFixed(1)}s`;
597
+ if (seconds < 60) return `${Math.floor(seconds)}s`;
598
+ return `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`;
599
+ }
600
+ function toStatus(statusType) {
601
+ if (statusType === "complete") return "success";
602
+ if (statusType === "incomplete") return "error";
603
+ return "running";
604
+ }
605
+ function parseSandboxArgs(argsText) {
606
+ if (!argsText) return {};
607
+ const parsed = parseJsonIncrementally(argsText);
608
+ if (!parsed.success || !isUnknownRecord(parsed.value)) return { argsJson: argsText };
609
+ return {
610
+ command: typeof parsed.value.command === "string" ? parsed.value.command : void 0,
611
+ intent: typeof parsed.value.intent === "string" ? parsed.value.intent : void 0,
612
+ argsJson: parsed.isPartial ? argsText : JSON.stringify(parsed.value, null, 2)
613
+ };
614
+ }
615
+ function parseSandboxResult(result) {
616
+ if (result === void 0) return {};
617
+ const parsed = parseJsonIncrementally(result);
618
+ if (!parsed.success || !isUnknownRecord(parsed.value)) return { resultText: result };
619
+ const response = isUnknownRecord(parsed.value.response) ? parsed.value.response : void 0;
620
+ const exitCode = typeof response?.exitCode === "number" ? response.exitCode : null;
621
+ const resultText = typeof response?.result === "string" ? response.result : void 0;
622
+ return {
623
+ exitCode,
624
+ resultText,
625
+ resultJson: parsed.isPartial ? result : JSON.stringify(parsed.value, null, 2)
626
+ };
627
+ }
628
+ function parseMcpToolArgs(argsText) {
629
+ if (!argsText) return {};
630
+ try {
631
+ const parsed = JSON.parse(argsText);
632
+ return {
633
+ mcpServer: parsed.mcp_server,
634
+ innerToolName: parsed.tool_name,
635
+ input: parsed.input
636
+ };
637
+ } catch {
638
+ return {};
639
+ }
640
+ }
641
+ function getJsonDisplayValue(content) {
642
+ if (!content?.trim()) return { value: "", isJson: false };
643
+ const trimmed = content.trim();
644
+ if (trimmed[0] !== "{" && trimmed[0] !== "[") {
645
+ return { value: content, isJson: false };
646
+ }
647
+ try {
648
+ const parsed = JSON.parse(content);
649
+ return { value: JSON.stringify(parsed, null, 2), isJson: true };
650
+ } catch {
651
+ return { value: content, isJson: false };
652
+ }
653
+ }
654
+ function getToolResultContent(content) {
655
+ try {
656
+ if (!content) return { isJson: false, data: "" };
657
+ const parsedResult = typeof content === "string" && content.trim().startsWith("{") ? JSON.parse(content) : content;
658
+ if (typeof parsedResult === "object" && parsedResult != null && Array.isArray(parsedResult.content)) {
659
+ const text = parsedResult.content[0]?.text || "";
660
+ const display2 = getJsonDisplayValue(typeof text === "string" ? text : JSON.stringify(text));
661
+ return { data: display2.value, isJson: display2.isJson };
662
+ }
663
+ const display = getJsonDisplayValue(typeof parsedResult === "string" ? parsedResult : JSON.stringify(parsedResult));
664
+ return { data: display.value, isJson: display.isJson };
665
+ } catch {
666
+ return { data: String(content), isJson: false };
667
+ }
668
+ }
669
+ function resolveSubAgentMeta(part) {
670
+ const artifactSubAgent = part.artifact?.subAgents?.[0];
671
+ const firstNested = part.messages?.[0];
672
+ const subAgent = firstNested?.metadata?.custom?.subAgent;
673
+ return {
674
+ agentName: subAgent?.title ?? subAgent?.name ?? artifactSubAgent?.title ?? artifactSubAgent?.agentInfo?.name ?? part.toolName,
675
+ instruction: subAgent?.input ?? artifactSubAgent?.agentInfo?.input ?? "",
676
+ stepCount: part.messages?.length ?? 0
677
+ };
678
+ }
679
+ function mcpDisplayName(toolName, mcpServer, innerToolName) {
680
+ if (toolName === "call_tool" && innerToolName) {
681
+ return mcpServer ? `call_tool: ${innerToolName} (${mcpServer})` : `call_tool: ${innerToolName}`;
682
+ }
683
+ if (toolName === "get_tool_info" && innerToolName && mcpServer) {
684
+ return `get_tool_info: ${innerToolName} (${mcpServer})`;
685
+ }
686
+ return toolName;
687
+ }
688
+
689
+ // src/containers/nestedApprovalBridge.ts
690
+ import { createContext, useContext } from "react";
691
+ var NestedApprovalBridgeContext = createContext(null);
692
+ function useNestedApprovalBridge() {
693
+ return useContext(NestedApprovalBridgeContext);
694
+ }
695
+
696
+ // src/containers/SandboxToolCallContainer.tsx
697
+ import { useMemo as useMemo4, useState as useState7 } from "react";
698
+ import { jsx as jsx7 } from "react/jsx-runtime";
699
+ function SandboxToolCallContainer(props) {
700
+ const SandboxToolCallCard = useSlot("SandboxToolCallCard");
701
+ const [viewMode, setViewMode] = useState7("terminal");
702
+ const hasContent = useMemo4(() => {
703
+ if (viewMode === "code") return Boolean(props.argsJson || props.resultJson);
704
+ return Boolean(props.command || props.resultText || props.resultJson);
705
+ }, [props.argsJson, props.command, props.resultJson, props.resultText, viewMode]);
706
+ return /* @__PURE__ */ jsx7(SandboxToolCallCard, { ...props, viewMode, hasContent, onViewModeChange: setViewMode });
707
+ }
708
+
709
+ // src/containers/ToolCallContainer.tsx
710
+ import { jsx as jsx8 } from "react/jsx-runtime";
711
+ function NestedSubAgentAssistantMessage() {
712
+ const AssistantMessageBubble = useSlot("AssistantMessageBubble");
713
+ return /* @__PURE__ */ jsx8("div", { className: "mb-3 min-w-0", children: /* @__PURE__ */ jsx8(MessagePrimitive.Root, { "data-role": "assistant", children: /* @__PURE__ */ jsx8(AssistantMessageBubble, { children: /* @__PURE__ */ jsx8(
714
+ MessagePrimitive.Parts,
715
+ {
716
+ components: {
717
+ Text: AssistantTextContainer,
718
+ Reasoning: AssistantTextContainer,
719
+ tools: { Fallback: ToolCallContainer }
720
+ }
721
+ }
722
+ ) }) }) });
723
+ }
724
+ function ToolApprovalSlot({ part }) {
725
+ const nestedBridge = useNestedApprovalBridge();
726
+ const respond = (response) => {
727
+ if (nestedBridge) {
728
+ nestedBridge(response);
729
+ return;
730
+ }
731
+ part.respondToApproval(response);
732
+ };
733
+ const onSelectOption = (optionId, reason) => {
734
+ if (optionId === "__allow") return respond({ approved: true });
735
+ if (optionId === "__deny") return respond({ approved: false, reason });
736
+ return respond({ optionId, reason });
737
+ };
738
+ return /* @__PURE__ */ jsx8(
739
+ ToolApprovalContainer,
740
+ {
741
+ toolName: part.toolName,
742
+ options: buildApprovalOptions(part.approval?.options),
743
+ onSelectOption
744
+ }
745
+ );
746
+ }
747
+ function RequestResponseSlots({
748
+ request,
749
+ response
750
+ }) {
751
+ return {
752
+ requestSlot: request.value ? /* @__PURE__ */ jsx8(
753
+ ToolCallContentBlockContainer,
754
+ {
755
+ title: "Request",
756
+ content: request.value,
757
+ isJson: request.isJson,
758
+ maxHeight: "10.5rem"
759
+ }
760
+ ) : response.data ? /* @__PURE__ */ jsx8(ToolCallContentBlockContainer, { title: "Request", content: "{}", isJson: true, maxHeight: "10.5rem" }) : void 0,
761
+ responseSlot: response.data ? /* @__PURE__ */ jsx8(ToolCallContentBlockContainer, { title: "Response", content: response.data, isJson: response.isJson, resizable: true }) : void 0
762
+ };
763
+ }
764
+ var ToolCallContainer = (part) => {
765
+ const ToolCallCard = useSlot("ToolCallCard");
766
+ const SubAgentCard = useSlot("SubAgentCard");
767
+ const AskUserPrompt = useSlot("AskUserPrompt");
768
+ const respondToNestedApproval = useTrueFoundryRespondToToolApproval();
769
+ const elapsedMs = useToolCallElapsed();
770
+ const isRequiresAction = part.status?.type === "requires-action";
771
+ const isSubAgent = part.toolName === SUB_AGENT_TOOL_NAME;
772
+ const isSandbox = SANDBOX_TOOL_NAMES.has(part.toolName);
773
+ const [expanded, setExpanded] = useState8(isRequiresAction);
774
+ const [prevRequiresAction, setPrevRequiresAction] = useState8(isRequiresAction);
775
+ if (isRequiresAction !== prevRequiresAction) {
776
+ setPrevRequiresAction(isRequiresAction);
777
+ if (isRequiresAction) setExpanded(true);
778
+ }
779
+ const showApproval = isRequiresAction && hasPendingToolApproval(part.approval);
780
+ const durationText = elapsedMs === void 0 ? void 0 : formatDuration(elapsedMs);
781
+ const status = toStatus(part.status?.type);
782
+ const onToggle = () => setExpanded((prev) => !prev);
783
+ if (part.toolName === ASK_USER_TOOL_NAME) {
784
+ if (hasPendingAskUserResponse(part)) {
785
+ return null;
786
+ }
787
+ const answer = getAskUserAnswerResult(part.result);
788
+ if (answer == null) {
789
+ return null;
790
+ }
791
+ const { question, options = [] } = parseAskUserQuestionArgs(part.argsText);
792
+ const isCustom = options.length > 0 && !options.includes(answer);
793
+ return /* @__PURE__ */ jsx8(
794
+ AskUserPrompt,
795
+ {
796
+ questions: [],
797
+ answeredQuestions: [
798
+ {
799
+ id: part.toolCallId,
800
+ question: question ?? "Question",
801
+ options,
802
+ answer,
803
+ isCustom
804
+ }
805
+ ],
806
+ onSubmit: () => {
807
+ },
808
+ readOnly: true
809
+ }
810
+ );
811
+ }
812
+ if (isSubAgent) {
813
+ const { agentName, instruction, stepCount } = resolveSubAgentMeta(part);
814
+ const bridge = (response) => {
815
+ if (part.approval == null) return;
816
+ const approved = "approved" in response ? response.approved : void 0;
817
+ if (approved === void 0) return;
818
+ respondToNestedApproval({ approvalId: part.approval.id, approved });
819
+ };
820
+ return /* @__PURE__ */ jsx8("div", { "data-slot": "tool-call-card", "data-variant": "sub-agent", className: "w-full", children: /* @__PURE__ */ jsx8(
821
+ SubAgentCard,
822
+ {
823
+ status,
824
+ expanded,
825
+ onToggle,
826
+ durationText,
827
+ agentName,
828
+ instruction,
829
+ stepCount,
830
+ children: /* @__PURE__ */ jsx8(NestedApprovalBridgeContext.Provider, { value: bridge, children: /* @__PURE__ */ jsx8(
831
+ MessagePartPrimitive.Messages,
832
+ {
833
+ components: {
834
+ AssistantMessage: NestedSubAgentAssistantMessage,
835
+ UserMessage: () => null
836
+ }
837
+ }
838
+ ) })
839
+ }
840
+ ) });
841
+ }
842
+ const resultString = part.result === void 0 ? void 0 : typeof part.result === "string" ? part.result : JSON.stringify(part.result, null, 2);
843
+ if (isSandbox) {
844
+ const { command, intent, argsJson } = parseSandboxArgs(part.argsText);
845
+ const { exitCode, resultText, resultJson } = parseSandboxResult(resultString);
846
+ return /* @__PURE__ */ jsx8(
847
+ SandboxToolCallContainer,
848
+ {
849
+ name: part.toolName,
850
+ intent,
851
+ status,
852
+ expanded,
853
+ onToggle,
854
+ durationText,
855
+ command,
856
+ exitCode,
857
+ argsJson,
858
+ resultText,
859
+ resultJson
860
+ }
861
+ );
862
+ }
863
+ if (MCP_META_TOOLS.has(part.toolName)) {
864
+ const { mcpServer, innerToolName, input } = parseMcpToolArgs(part.argsText);
865
+ const argsDisplay2 = getJsonDisplayValue(part.argsText);
866
+ const resultDisplay2 = getToolResultContent(part.result);
867
+ if (part.toolName === "list_tools" && mcpServer) {
868
+ const slots3 = RequestResponseSlots({
869
+ request: argsDisplay2,
870
+ response: resultDisplay2
871
+ });
872
+ return /* @__PURE__ */ jsx8(
873
+ ToolCallCard,
874
+ {
875
+ toolName: `Listing tools \xB7 ${mcpServer}`,
876
+ icon: "mcp-server",
877
+ expanded,
878
+ onToggle,
879
+ awaiting: status === "running",
880
+ awaitingText: durationText ?? "Awaiting Response\u2026",
881
+ showResponseLine: status !== "running" && !!resultDisplay2.data,
882
+ mcpServerName: mcpServer,
883
+ ...slots3
884
+ }
885
+ );
886
+ }
887
+ const inputDisplay = input !== void 0 ? getJsonDisplayValue(JSON.stringify(input, null, 2)) : argsDisplay2;
888
+ const slots2 = RequestResponseSlots({
889
+ request: inputDisplay,
890
+ response: resultDisplay2
891
+ });
892
+ return /* @__PURE__ */ jsx8(
893
+ ToolCallCard,
894
+ {
895
+ toolName: mcpDisplayName(part.toolName, mcpServer, innerToolName),
896
+ icon: "mcp-server",
897
+ expanded,
898
+ onToggle,
899
+ awaiting: status === "running",
900
+ awaitingText: durationText ?? "Awaiting Response\u2026",
901
+ showResponseLine: status !== "running" && resultDisplay2.data !== void 0,
902
+ mcpServerName: mcpServer,
903
+ ...slots2,
904
+ approvalSlot: showApproval ? /* @__PURE__ */ jsx8(ToolApprovalSlot, { part }) : void 0
905
+ }
906
+ );
907
+ }
908
+ const argsDisplay = getJsonDisplayValue(part.argsText);
909
+ const resultDisplay = getToolResultContent(part.result);
910
+ const slots = RequestResponseSlots({
911
+ request: argsDisplay,
912
+ response: resultDisplay
913
+ });
914
+ return /* @__PURE__ */ jsx8(
915
+ ToolCallCard,
916
+ {
917
+ toolName: part.toolName,
918
+ expanded,
919
+ onToggle,
920
+ awaiting: status === "running",
921
+ awaitingText: durationText ?? "Awaiting Response\u2026",
922
+ showResponseLine: status !== "running" && resultDisplay.data !== void 0,
923
+ ...slots,
924
+ approvalSlot: showApproval ? /* @__PURE__ */ jsx8(ToolApprovalSlot, { part }) : void 0
925
+ }
926
+ );
927
+ };
928
+
929
+ // src/containers/AssistantMessageContainer.tsx
930
+ import { useActionBarCopy, useMessageError, useThreadIsRunning as useThreadIsRunning2 } from "@assistant-ui/core/react";
931
+ import { MessagePrimitive as MessagePrimitive2, useAuiState as useAuiState5 } from "@assistant-ui/react";
932
+ import { useTrueFoundryResumeUnavailable } from "@truefoundry/assistant-ui-runtime";
933
+
934
+ // src/containers/MessageImageContainer.tsx
935
+ import { useAuiState as useAuiState4 } from "@assistant-ui/react";
936
+ import { jsx as jsx9 } from "react/jsx-runtime";
937
+ function MessageImageContainer() {
938
+ const AttachmentCard = useSlot("AttachmentCard");
939
+ const AttachmentPreviewDialog = useSlot("AttachmentPreviewDialog");
940
+ const image = useAuiState4((s) => s.part.type === "image" ? s.part.image : "");
941
+ const filename = useAuiState4((s) => s.part.type === "image" ? s.part.filename : void 0);
942
+ if (!image) {
943
+ return null;
944
+ }
945
+ const card = /* @__PURE__ */ jsx9(
946
+ AttachmentCard,
947
+ {
948
+ name: filename ?? "image",
949
+ previewSrc: image,
950
+ isImage: true,
951
+ size: "preview",
952
+ previewRem: USER_MESSAGE_ATTACHMENT_PREVIEW_REM
953
+ }
954
+ );
955
+ return /* @__PURE__ */ jsx9(AttachmentPreviewDialog, { previewSrc: image, children: /* @__PURE__ */ jsx9("div", { className: "aui-message-image", children: card }) });
956
+ }
957
+
958
+ // src/containers/AssistantMessageContainer.tsx
959
+ import { jsx as jsx10 } from "react/jsx-runtime";
960
+ function AssistantLeafPartContainer({ part }) {
961
+ switch (part.type) {
962
+ case "text":
963
+ case "reasoning":
964
+ return /* @__PURE__ */ jsx10(AssistantTextContainer, {});
965
+ case "image":
966
+ return /* @__PURE__ */ jsx10(MessageImageContainer, {});
967
+ case "tool-call":
968
+ return /* @__PURE__ */ jsx10(ToolCallContainer, { ...part });
969
+ default:
970
+ return null;
971
+ }
972
+ }
973
+ function AssistantMessageContainer() {
974
+ const AssistantMessageBubble = useSlot("AssistantMessageBubble");
975
+ const MessageActionBar = useSlot("MessageActionBar");
976
+ const MessageErrorBanner = useSlot("MessageErrorBanner");
977
+ const MessageIndicator = useSlot("MessageIndicator");
978
+ const isThreadRunning = useThreadIsRunning2();
979
+ const resumeUnavailable = useTrueFoundryResumeUnavailable();
980
+ const error = useMessageError();
981
+ const createdAt = useAuiState5((s) => s.message.createdAt);
982
+ const isMessageRunning = useAuiState5((s) => s.message.status?.type === "running");
983
+ const { copy, isCopied } = useActionBarCopy({
984
+ copyToClipboard: (text) => navigator.clipboard.writeText(text)
985
+ });
986
+ const parts = useAuiState5((s) => s.message.parts);
987
+ const { cutIndex, hasFinal, toolCount, thinkingCount } = computeAgentStepsSplit(parts, isMessageRunning);
988
+ const groupBy = (part, _context) => {
989
+ const index = parts.findIndex((p) => p === part);
990
+ if (index === -1) return null;
991
+ if (part.type === "text" && index >= cutIndex) {
992
+ return null;
993
+ }
994
+ if (index < cutIndex) {
995
+ if (part.type === "reasoning") {
996
+ return ["group-agentSteps", "group-reasoning"];
997
+ }
998
+ return ["group-agentSteps"];
999
+ }
1000
+ return null;
1001
+ };
1002
+ return /* @__PURE__ */ jsx10(MessagePrimitive2.Root, { "data-role": "assistant", children: /* @__PURE__ */ jsx10(
1003
+ AssistantMessageBubble,
1004
+ {
1005
+ error: error !== void 0 ? /* @__PURE__ */ jsx10(MessageErrorBanner, { message: String(error) }) : void 0,
1006
+ actionBar: !isThreadRunning ? /* @__PURE__ */ jsx10(MessageActionBar, { isCopied, onCopy: copy, createdAt }) : void 0,
1007
+ children: /* @__PURE__ */ jsx10(MessagePrimitive2.GroupedParts, { groupBy, children: ({ part, children }) => {
1008
+ switch (part.type) {
1009
+ case "group-agentSteps":
1010
+ return /* @__PURE__ */ jsx10(AgentStepsContainer, { toolCount, thinkingCount, hasFinal, children });
1011
+ case "group-reasoning":
1012
+ return /* @__PURE__ */ jsx10(ReasoningContainer, { group: part });
1013
+ case "text": {
1014
+ const index = parts.findIndex((p) => p === part);
1015
+ if (index >= 0 && index < cutIndex) {
1016
+ return /* @__PURE__ */ jsx10("div", { className: "mb-2 ml-[1.75rem] text-xs text-text-secondary [&_.markdown-body]:text-inherit", children: /* @__PURE__ */ jsx10(AssistantTextContainer, {}) });
1017
+ }
1018
+ return /* @__PURE__ */ jsx10(AssistantTextContainer, {});
1019
+ }
1020
+ case "reasoning":
1021
+ case "tool-call":
1022
+ case "image":
1023
+ case "data":
1024
+ return /* @__PURE__ */ jsx10(AssistantLeafPartContainer, { part });
1025
+ case "indicator":
1026
+ return resumeUnavailable ? null : /* @__PURE__ */ jsx10(MessageIndicator, {});
1027
+ default:
1028
+ return null;
1029
+ }
1030
+ } })
1031
+ }
1032
+ ) });
1033
+ }
1034
+
1035
+ // src/containers/AttachmentsContainer.tsx
1036
+ import { ComposerPrimitive, MessagePrimitive as MessagePrimitive3, useAui as useAui2, useAuiState as useAuiState7 } from "@assistant-ui/react";
1037
+
1038
+ // src/containers/useAttachmentPreviewSrc.ts
1039
+ import { useAuiState as useAuiState6 } from "@assistant-ui/react";
1040
+ import { useEffect as useEffect5, useState as useState9 } from "react";
1041
+ function isImageAttachment(type, contentType) {
1042
+ return type === "image" || (contentType?.startsWith("image/") ?? false);
1043
+ }
1044
+ function useFileObjectUrl(file) {
1045
+ const [src, setSrc] = useState9(void 0);
1046
+ useEffect5(() => {
1047
+ if (!file) {
1048
+ setSrc(void 0);
1049
+ return;
1050
+ }
1051
+ const objectUrl = URL.createObjectURL(file);
1052
+ setSrc(objectUrl);
1053
+ return () => URL.revokeObjectURL(objectUrl);
1054
+ }, [file]);
1055
+ return src;
1056
+ }
1057
+ function useAttachmentPreviewSrc() {
1058
+ const type = useAuiState6((s) => s.attachment.type);
1059
+ const contentType = useAuiState6((s) => s.attachment.contentType);
1060
+ const file = useAuiState6((s) => "file" in s.attachment ? s.attachment.file : void 0);
1061
+ const contentSrc = useAuiState6((s) => {
1062
+ if (!isImageAttachment(s.attachment.type, s.attachment.contentType)) return void 0;
1063
+ const imagePart = s.attachment.content?.find((part) => part.type === "image");
1064
+ if (imagePart?.type === "image" && imagePart.image) return imagePart.image;
1065
+ return void 0;
1066
+ });
1067
+ const image = isImageAttachment(type, contentType);
1068
+ const fileSrc = useFileObjectUrl(image ? file : void 0);
1069
+ if (!image) return void 0;
1070
+ return fileSrc ?? contentSrc;
1071
+ }
1072
+
1073
+ // src/containers/AttachmentsContainer.tsx
1074
+ import { jsx as jsx11 } from "react/jsx-runtime";
1075
+ function ComposerAttachmentItem() {
1076
+ const AttachmentPreviewDialog = useSlot("AttachmentPreviewDialog");
1077
+ const AttachmentCard = useSlot("AttachmentCard");
1078
+ const aui = useAui2();
1079
+ const name = useAuiState7((s) => s.attachment.name);
1080
+ const contentType = useAuiState7((s) => s.attachment.contentType);
1081
+ const type = useAuiState7((s) => s.attachment.type);
1082
+ const isImage = isImageAttachment(type, contentType);
1083
+ const previewSrc = useAttachmentPreviewSrc();
1084
+ return /* @__PURE__ */ jsx11(AttachmentPreviewDialog, { previewSrc, children: /* @__PURE__ */ jsx11(
1085
+ AttachmentCard,
1086
+ {
1087
+ name,
1088
+ contentType,
1089
+ previewSrc,
1090
+ isImage,
1091
+ size: "chip",
1092
+ onRemove: () => void aui.attachment().remove()
1093
+ }
1094
+ ) });
1095
+ }
1096
+ function MessageAttachmentItem() {
1097
+ const AttachmentPreviewDialog = useSlot("AttachmentPreviewDialog");
1098
+ const AttachmentCard = useSlot("AttachmentCard");
1099
+ const name = useAuiState7((s) => s.attachment.name);
1100
+ const contentType = useAuiState7((s) => s.attachment.contentType);
1101
+ const type = useAuiState7((s) => s.attachment.type);
1102
+ const isImage = isImageAttachment(type, contentType);
1103
+ const previewSrc = useAttachmentPreviewSrc();
1104
+ const card = /* @__PURE__ */ jsx11(
1105
+ AttachmentCard,
1106
+ {
1107
+ name,
1108
+ contentType,
1109
+ previewSrc,
1110
+ isImage,
1111
+ size: isImage ? "preview" : "chip",
1112
+ previewRem: USER_MESSAGE_ATTACHMENT_PREVIEW_REM
1113
+ }
1114
+ );
1115
+ if (isImage && previewSrc) {
1116
+ return /* @__PURE__ */ jsx11(AttachmentPreviewDialog, { previewSrc, children: card });
1117
+ }
1118
+ return card;
1119
+ }
1120
+ function ComposerAttachmentsContainer() {
1121
+ return /* @__PURE__ */ jsx11("div", { className: "aui-composer-attachments flex w-full flex-row flex-wrap items-center gap-2 empty:hidden", children: /* @__PURE__ */ jsx11(ComposerPrimitive.Attachments, { children: () => /* @__PURE__ */ jsx11(ComposerAttachmentItem, {}) }) });
1122
+ }
1123
+ function MessageAttachmentsContainer() {
1124
+ return /* @__PURE__ */ jsx11("div", { className: "aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2", children: /* @__PURE__ */ jsx11(MessagePrimitive3.Attachments, { children: () => /* @__PURE__ */ jsx11(MessageAttachmentItem, {}) }) });
1125
+ }
1126
+ function ComposerAttachmentPickerContainer() {
1127
+ const AttachmentPickerButton = useSlot("AttachmentPickerButton");
1128
+ return /* @__PURE__ */ jsx11(ComposerPrimitive.AddAttachment, { asChild: true, children: /* @__PURE__ */ jsx11(AttachmentPickerButton, {}) });
1129
+ }
1130
+
1131
+ // src/hooks/useComposerBusyState.ts
1132
+ import { useThreadIsRunning as useThreadIsRunning3 } from "@assistant-ui/core/react";
1133
+ import { createContext as createContext2, createElement, useCallback as useCallback6, useContext as useContext2, useEffect as useEffect6, useState as useState10 } from "react";
1134
+ var ComposerBusyContext = createContext2(null);
1135
+ var busyFailureListeners = /* @__PURE__ */ new Set();
1136
+ function notifyComposerBusyFailure() {
1137
+ for (const listener of busyFailureListeners) {
1138
+ listener();
1139
+ }
1140
+ }
1141
+ function useComposerBusyStateValue() {
1142
+ const isRunning = useThreadIsRunning3();
1143
+ const [isSubmitting, setIsSubmitting] = useState10(false);
1144
+ useEffect6(() => {
1145
+ if (!isRunning) {
1146
+ setIsSubmitting(false);
1147
+ }
1148
+ }, [isRunning]);
1149
+ useEffect6(() => {
1150
+ const clearSubmitting = () => {
1151
+ setIsSubmitting(false);
1152
+ };
1153
+ busyFailureListeners.add(clearSubmitting);
1154
+ return () => {
1155
+ busyFailureListeners.delete(clearSubmitting);
1156
+ };
1157
+ }, []);
1158
+ const isBusy = isRunning || isSubmitting;
1159
+ const resetBusy = useCallback6(() => {
1160
+ setIsSubmitting(false);
1161
+ }, []);
1162
+ const send = useCallback6((sendFn) => {
1163
+ setIsSubmitting(true);
1164
+ try {
1165
+ const result = sendFn();
1166
+ if (result != null && typeof result.then === "function") {
1167
+ void result.catch(() => {
1168
+ setIsSubmitting(false);
1169
+ });
1170
+ }
1171
+ } catch {
1172
+ setIsSubmitting(false);
1173
+ }
1174
+ }, []);
1175
+ return { isBusy, isRunning, isSubmitting, send, resetBusy };
1176
+ }
1177
+ function ComposerBusyProvider({ children }) {
1178
+ const value = useComposerBusyStateValue();
1179
+ return createElement(ComposerBusyContext.Provider, { value }, children);
1180
+ }
1181
+ function useComposerBusyState() {
1182
+ const value = useContext2(ComposerBusyContext);
1183
+ if (value == null) {
1184
+ throw new Error("useComposerBusyState must be used within ComposerBusyProvider");
1185
+ }
1186
+ return value;
1187
+ }
1188
+
1189
+ // src/hooks/useComposerPauseView.ts
1190
+ import { useAuiState as useAuiState8 } from "@assistant-ui/react";
1191
+ import { useTrueFoundryToolResponses as useTrueFoundryToolResponses2 } from "@truefoundry/assistant-ui-runtime";
1192
+ function threadHasPendingMcpAuth(s) {
1193
+ const messages = s.thread.messages;
1194
+ const last = messages[messages.length - 1];
1195
+ if (last?.role !== "assistant") return false;
1196
+ if (last.status?.type !== "requires-action") return false;
1197
+ return last.metadata?.custom?.pendingMcpAuth === true;
1198
+ }
1199
+ function useComposerPauseView() {
1200
+ const mcpPending = useAuiState8(threadHasPendingMcpAuth);
1201
+ const { pending: toolResponsesPending } = useTrueFoundryToolResponses2();
1202
+ if (mcpPending) {
1203
+ return { kind: "mcp" };
1204
+ }
1205
+ if (toolResponsesPending.length > 0) {
1206
+ return { kind: "ask-user" };
1207
+ }
1208
+ return { kind: "compose" };
1209
+ }
1210
+
1211
+ // src/containers/McpAuthContainer.tsx
1212
+ import { useThreadIsRunning as useThreadIsRunning4 } from "@assistant-ui/core/react";
1213
+ import { useTrueFoundryMcpAuth } from "@truefoundry/assistant-ui-runtime";
1214
+ import { jsx as jsx12 } from "react/jsx-runtime";
1215
+ function McpAuthContainer() {
1216
+ const McpAuthPrompt = useSlot("McpAuthPrompt");
1217
+ const { pending, resume } = useTrueFoundryMcpAuth();
1218
+ const isRunning = useThreadIsRunning4();
1219
+ if (!pending) return null;
1220
+ const handleConnect = (serverId) => {
1221
+ const server = pending.mcpServers.find((s) => s.id === serverId);
1222
+ if (server?.authUrl) {
1223
+ window.open(server.authUrl, "_blank", "noopener,noreferrer");
1224
+ }
1225
+ };
1226
+ return /* @__PURE__ */ jsx12(
1227
+ McpAuthPrompt,
1228
+ {
1229
+ servers: pending.mcpServers,
1230
+ onConnect: handleConnect,
1231
+ onContinue: () => void resume(),
1232
+ readOnly: isRunning
1233
+ }
1234
+ );
1235
+ }
1236
+
1237
+ // src/containers/ComposerContainer.tsx
1238
+ import { ComposerPrimitive as ComposerPrimitive2, useAui as useAui3, useAuiState as useAuiState9 } from "@assistant-ui/react";
1239
+ import { useTrueFoundryAgentSpec, useTrueFoundryCancel } from "@truefoundry/assistant-ui-runtime";
1240
+ import { useRef as useRef6 } from "react";
1241
+ import { Fragment, jsx as jsx13, jsxs } from "react/jsx-runtime";
1242
+ function ComposerBody({ placeholder }) {
1243
+ const ComposerShell = useSlot("ComposerShell");
1244
+ const aui = useAui3();
1245
+ const shell = useOptionalShellMode();
1246
+ const hasText = useAuiState9((s) => s.composer.text.trim().length > 0);
1247
+ const { agentSpec } = useTrueFoundryAgentSpec();
1248
+ const requiresModel = shell == null || shell.mode.status === "active" && shell.mode.isMutable;
1249
+ const hasModel = Boolean(agentSpec?.model?.name?.trim());
1250
+ const { isBusy, send, resetBusy } = useComposerBusyState();
1251
+ const cancel = useTrueFoundryCancel();
1252
+ const fileInputRef = useRef6(null);
1253
+ const canSubmit = !isBusy && hasText && (!requiresModel || hasModel);
1254
+ const submit = () => {
1255
+ if (!canSubmit) return;
1256
+ send(() => aui.composer().send());
1257
+ };
1258
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1259
+ /* @__PURE__ */ jsx13(
1260
+ "input",
1261
+ {
1262
+ ref: fileInputRef,
1263
+ type: "file",
1264
+ multiple: true,
1265
+ hidden: true,
1266
+ onChange: (event) => {
1267
+ const files = event.target.files;
1268
+ if (files) {
1269
+ for (const file of files) {
1270
+ void aui.composer().addAttachment(file);
1271
+ }
1272
+ }
1273
+ event.target.value = "";
1274
+ }
1275
+ }
1276
+ ),
1277
+ /* @__PURE__ */ jsx13(
1278
+ ComposerPrimitive2.AttachmentDropzone,
1279
+ {
1280
+ disabled: isBusy,
1281
+ "data-slot": "aui_composer-attachment-dropzone",
1282
+ className: "w-full rounded-[var(--composer-radius,1.5rem)] transition-[box-shadow] data-[dragging=true]:ring-focus-ring/20 data-[dragging=true]:ring-3",
1283
+ children: /* @__PURE__ */ jsx13(
1284
+ ComposerPrimitive2.Root,
1285
+ {
1286
+ "data-slot": "aui_composer-root",
1287
+ className: "w-full",
1288
+ onSubmit: (event) => {
1289
+ event.preventDefault();
1290
+ submit();
1291
+ },
1292
+ children: /* @__PURE__ */ jsx13(
1293
+ ComposerShell,
1294
+ {
1295
+ attachments: /* @__PURE__ */ jsx13(ComposerAttachmentsContainer, {}),
1296
+ input: /* @__PURE__ */ jsx13(
1297
+ ComposerPrimitive2.Input,
1298
+ {
1299
+ "data-slot": "aui_composer-input",
1300
+ placeholder,
1301
+ disabled: isBusy,
1302
+ submitMode: "enter",
1303
+ "aria-label": "Message input",
1304
+ className: "text-text-primary placeholder:text-text-secondary/80 max-h-[10lh] min-h-10 w-full resize-none overflow-y-auto rounded-lg border-none bg-transparent px-1 py-1 text-base leading-normal shadow-none outline-none disabled:cursor-not-allowed"
1305
+ }
1306
+ ),
1307
+ disabled: isBusy,
1308
+ canSubmit,
1309
+ isRunning: isBusy,
1310
+ onSubmit: submit,
1311
+ onCancel: () => {
1312
+ resetBusy();
1313
+ void cancel();
1314
+ },
1315
+ onAttach: () => fileInputRef.current?.click()
1316
+ }
1317
+ )
1318
+ }
1319
+ )
1320
+ }
1321
+ )
1322
+ ] });
1323
+ }
1324
+ function ComposerContainer({
1325
+ placeholder = "Ask anything... (Shift+Enter for new line)"
1326
+ }) {
1327
+ const pauseView = useComposerPauseView();
1328
+ const shell = useOptionalShellMode();
1329
+ const parentLeftSection = useSlot("ComposerLeftSection");
1330
+ const parentRightSection = useSlot("ComposerRightSection");
1331
+ const usesDefaultLeftSection = useSlotIsDefault("ComposerLeftSection");
1332
+ const usesDefaultRightSection = useSlotIsDefault("ComposerRightSection");
1333
+ const DraftComposerLeftSection = useSlot("DraftComposerLeftSection");
1334
+ const DraftComposerRightSection = useSlot("DraftComposerRightSection");
1335
+ const canMutateSpec = shell?.mode.status === "active" && shell.mode.isMutable;
1336
+ if (pauseView.kind === "mcp") {
1337
+ return /* @__PURE__ */ jsx13(McpAuthContainer, {});
1338
+ }
1339
+ if (pauseView.kind === "ask-user") {
1340
+ return /* @__PURE__ */ jsx13(AskUserContainer, {});
1341
+ }
1342
+ if (canMutateSpec) {
1343
+ return /* @__PURE__ */ jsx13(DraftCatalogProvider, { children: /* @__PURE__ */ jsx13(
1344
+ SlotsProvider,
1345
+ {
1346
+ overrides: {
1347
+ ComposerLeftSection: usesDefaultLeftSection ? DraftComposerLeftSection : parentLeftSection,
1348
+ ComposerRightSection: usesDefaultRightSection ? DraftComposerRightSection : parentRightSection
1349
+ },
1350
+ children: /* @__PURE__ */ jsx13(ComposerBody, { placeholder })
1351
+ }
1352
+ ) });
1353
+ }
1354
+ return /* @__PURE__ */ jsx13(ComposerBody, { placeholder });
1355
+ }
1356
+
1357
+ // src/containers/HistoryLoaderContainer.tsx
1358
+ import { useTrueFoundryHistoryPagination } from "@truefoundry/assistant-ui-runtime";
1359
+ import { useCallback as useCallback7, useEffect as useEffect7, useRef as useRef7, useState as useState11 } from "react";
1360
+ import { jsx as jsx14 } from "react/jsx-runtime";
1361
+ var TOP_THRESHOLD_PX = 200;
1362
+ var VIEWPORT_SELECTOR = '[data-slot="aui_thread-viewport"]';
1363
+ function HistoryLoaderContainer() {
1364
+ const HistoryLoader = useSlot("HistoryLoader");
1365
+ const { hasOlderHistory, isLoadingOlderHistory, loadOlderHistory } = useTrueFoundryHistoryPagination();
1366
+ const [sentinel, setSentinel] = useState11(null);
1367
+ const inflightRef = useRef7(false);
1368
+ const maybeLoadOlder = useCallback7(async () => {
1369
+ if (inflightRef.current) return;
1370
+ inflightRef.current = true;
1371
+ const viewport = sentinel?.closest(VIEWPORT_SELECTOR) ?? null;
1372
+ const prevScrollHeight = viewport?.scrollHeight ?? 0;
1373
+ const prevScrollTop = viewport?.scrollTop ?? 0;
1374
+ try {
1375
+ await loadOlderHistory();
1376
+ requestAnimationFrame(() => {
1377
+ if (viewport == null) return;
1378
+ const delta = viewport.scrollHeight - prevScrollHeight;
1379
+ if (delta > 0) {
1380
+ viewport.scrollTo({ top: prevScrollTop + delta, behavior: "instant" });
1381
+ }
1382
+ });
1383
+ } catch {
1384
+ } finally {
1385
+ inflightRef.current = false;
1386
+ }
1387
+ }, [sentinel, loadOlderHistory]);
1388
+ useEffect7(() => {
1389
+ if (sentinel == null || !hasOlderHistory) return;
1390
+ const viewport = sentinel.closest(VIEWPORT_SELECTOR);
1391
+ const observer = new IntersectionObserver(
1392
+ (entries) => {
1393
+ if (entries.some((entry) => entry.isIntersecting)) {
1394
+ void maybeLoadOlder();
1395
+ }
1396
+ },
1397
+ { root: viewport, rootMargin: `${TOP_THRESHOLD_PX}px 0px 0px 0px` }
1398
+ );
1399
+ observer.observe(sentinel);
1400
+ return () => observer.disconnect();
1401
+ }, [sentinel, hasOlderHistory, maybeLoadOlder]);
1402
+ if (!hasOlderHistory) return null;
1403
+ return /* @__PURE__ */ jsx14(HistoryLoader, { ref: setSentinel, isLoading: isLoadingOlderHistory });
1404
+ }
1405
+
1406
+ // src/containers/ResumeUnavailableContainer.tsx
1407
+ import { useTrueFoundryResumeUnavailable as useTrueFoundryResumeUnavailable2 } from "@truefoundry/assistant-ui-runtime";
1408
+ import { jsx as jsx15 } from "react/jsx-runtime";
1409
+ function ResumeUnavailableContainer() {
1410
+ const ResumeUnavailable = useSlot("ResumeUnavailable");
1411
+ const resumeUnavailable = useTrueFoundryResumeUnavailable2();
1412
+ if (!resumeUnavailable) return null;
1413
+ return /* @__PURE__ */ jsx15(ResumeUnavailable, {});
1414
+ }
1415
+
1416
+ // src/containers/UserEditComposerContainer.tsx
1417
+ import { useComposerCancel, useComposerSend, useThreadIsRunning as useThreadIsRunning5 } from "@assistant-ui/core/react";
1418
+ import { ComposerPrimitive as ComposerPrimitive3, MessagePrimitive as MessagePrimitive4, useAuiState as useAuiState10 } from "@assistant-ui/react";
1419
+ import { jsx as jsx16, jsxs as jsxs2 } from "react/jsx-runtime";
1420
+ function ReadOnlyMessageAttachments() {
1421
+ const hasAttachments = useAuiState10((s) => (s.message.attachments?.length ?? 0) > 0);
1422
+ if (!hasAttachments) {
1423
+ return null;
1424
+ }
1425
+ return /* @__PURE__ */ jsx16("div", { className: "pointer-events-none mb-2 opacity-90", children: /* @__PURE__ */ jsx16(MessageAttachmentsContainer, {}) });
1426
+ }
1427
+ function UserEditComposerContainer() {
1428
+ const UserMessageEdit = useSlot("UserMessageEdit");
1429
+ const MessageTimestamp = useSlot("MessageTimestamp");
1430
+ const isRunning = useThreadIsRunning5();
1431
+ const createdAt = useAuiState10((s) => s.message.createdAt);
1432
+ const { cancel, disabled: cancelDisabled } = useComposerCancel();
1433
+ const { disabled: sendDisabled } = useComposerSend();
1434
+ return /* @__PURE__ */ jsx16(MessagePrimitive4.Root, { "data-role": "user", children: /* @__PURE__ */ jsx16(
1435
+ ComposerPrimitive3.Root,
1436
+ {
1437
+ "data-slot": "aui_user-edit-composer-root",
1438
+ className: "fade-in slide-in-from-bottom-1 animate-in flex w-full justify-end px-2 duration-150",
1439
+ children: /* @__PURE__ */ jsx16(
1440
+ UserMessageEdit,
1441
+ {
1442
+ timestamp: /* @__PURE__ */ jsx16(MessageTimestamp, { createdAt }),
1443
+ attachments: /* @__PURE__ */ jsx16(ReadOnlyMessageAttachments, {}),
1444
+ input: /* @__PURE__ */ jsx16("div", { className: "mt-1 rounded border border-border bg-secondary-bg p-2 text-text-primary", children: /* @__PURE__ */ jsx16(
1445
+ ComposerPrimitive3.Input,
1446
+ {
1447
+ "data-slot": "aui_user-edit-input",
1448
+ disabled: isRunning,
1449
+ submitMode: "enter",
1450
+ "aria-label": "Edit message",
1451
+ className: "max-h-32 min-h-10 w-full resize-none border-none bg-transparent p-0 text-base leading-[1.34] outline-none focus:shadow-none"
1452
+ }
1453
+ ) }),
1454
+ footer: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-2", children: [
1455
+ /* @__PURE__ */ jsx16(Button, { variant: "secondary", type: "button", disabled: cancelDisabled, onClick: cancel, children: "Cancel" }),
1456
+ /* @__PURE__ */ jsx16(ComposerPrimitive3.Send, { asChild: true, children: /* @__PURE__ */ jsx16(Button, { type: "submit", disabled: sendDisabled || isRunning, children: "Save & Rerun" }) })
1457
+ ] })
1458
+ }
1459
+ )
1460
+ }
1461
+ ) });
1462
+ }
1463
+
1464
+ // src/containers/UserMessageContainer.tsx
1465
+ import { useActionBarCopy as useActionBarCopy2, useActionBarEdit, useThreadIsRunning as useThreadIsRunning6 } from "@assistant-ui/core/react";
1466
+ import { MessagePrimitive as MessagePrimitive5, useAui as useAui4, useAuiState as useAuiState11 } from "@assistant-ui/react";
1467
+ import { jsx as jsx17 } from "react/jsx-runtime";
1468
+ function UserMessageContainer() {
1469
+ const UserMessageBubble = useSlot("UserMessageBubble");
1470
+ const UserMessageActionBar = useSlot("UserMessageActionBar");
1471
+ const isRunning = useThreadIsRunning6();
1472
+ const aui = useAui4();
1473
+ const createdAt = useAuiState11((s) => s.message.createdAt);
1474
+ const text = useAuiState11(
1475
+ (s) => s.message.content.filter((part) => part.type === "text").map((part) => part.text).join("\n")
1476
+ );
1477
+ const { edit, disabled: editDisabled } = useActionBarEdit();
1478
+ const { copy, isCopied } = useActionBarCopy2({
1479
+ copyToClipboard: (value) => navigator.clipboard.writeText(value)
1480
+ });
1481
+ return /* @__PURE__ */ jsx17(MessagePrimitive5.Root, { "data-role": "user", children: /* @__PURE__ */ jsx17(
1482
+ UserMessageBubble,
1483
+ {
1484
+ text,
1485
+ attachments: /* @__PURE__ */ jsx17(MessageAttachmentsContainer, {}),
1486
+ editAction: !isRunning ? /* @__PURE__ */ jsx17(
1487
+ UserMessageActionBar,
1488
+ {
1489
+ isCopied,
1490
+ editDisabled,
1491
+ createdAt,
1492
+ onCopy: copy,
1493
+ onEdit: edit,
1494
+ onRetry: () => {
1495
+ aui.message().composer().beginEdit();
1496
+ aui.message().composer().send({ startRun: true });
1497
+ }
1498
+ }
1499
+ ) : void 0
1500
+ }
1501
+ ) });
1502
+ }
1503
+
1504
+ // src/containers/ThreadContainer.tsx
1505
+ import { ThreadPrimitive, useAuiState as useAuiState12 } from "@assistant-ui/react";
1506
+ import { useEffect as useEffect9 } from "react";
1507
+
1508
+ // src/hooks/useSyncSessionTitle.ts
1509
+ import { useThreadIsRunning as useThreadIsRunning7 } from "@assistant-ui/core/react";
1510
+ import { useEffect as useEffect8, useRef as useRef8 } from "react";
1511
+ function useSyncSessionTitle() {
1512
+ const server = useOptionalServer();
1513
+ const aui = useAui();
1514
+ const remoteId = useAuiState((s) => s.threadListItem.remoteId);
1515
+ const title = useAuiState((s) => s.threadListItem.title);
1516
+ const isRunning = useThreadIsRunning7();
1517
+ const wasRunningRef = useRef8(false);
1518
+ const syncedRemoteIdRef = useRef8(void 0);
1519
+ useEffect8(() => {
1520
+ syncedRemoteIdRef.current = void 0;
1521
+ }, [remoteId]);
1522
+ useEffect8(() => {
1523
+ const finishedTurn = wasRunningRef.current && !isRunning;
1524
+ wasRunningRef.current = isRunning;
1525
+ if (!finishedTurn || server == null || remoteId == null) {
1526
+ return;
1527
+ }
1528
+ if (syncedRemoteIdRef.current === remoteId) {
1529
+ return;
1530
+ }
1531
+ if (title != null && title.trim() !== "") {
1532
+ syncedRemoteIdRef.current = remoteId;
1533
+ return;
1534
+ }
1535
+ let cancelled = false;
1536
+ void server.getSession({ sessionId: remoteId }).then((session) => {
1537
+ if (cancelled) return;
1538
+ const nextTitle = typeof session.title === "string" ? session.title.trim() : "";
1539
+ if (nextTitle.length === 0) return;
1540
+ syncedRemoteIdRef.current = remoteId;
1541
+ return aui.threadListItem().rename(nextTitle);
1542
+ }).catch(() => void 0);
1543
+ return () => {
1544
+ cancelled = true;
1545
+ };
1546
+ }, [aui, isRunning, remoteId, server, title]);
1547
+ }
1548
+
1549
+ // src/utils/isNewChatView.ts
1550
+ var isNewChatView = (s) => s.thread.messages.length === 0 && (!s.thread.isLoading || s.threads.isLoading) && s.threadListItem.remoteId == null;
1551
+
1552
+ // src/containers/ThreadContainer.tsx
1553
+ import { Fragment as Fragment2, jsx as jsx18, jsxs as jsxs3 } from "react/jsx-runtime";
1554
+ function AnimatedMessageShell({ children }) {
1555
+ return /* @__PURE__ */ jsx18("div", { className: "animate-in fade-in slide-in-from-bottom-1 fill-mode-both duration-200", children });
1556
+ }
1557
+ function ThreadMessage({ isEditing }) {
1558
+ const role = useAuiState12((s) => s.message.role);
1559
+ if (role === "user") {
1560
+ if (isEditing) {
1561
+ return /* @__PURE__ */ jsx18(UserEditComposerContainer, {});
1562
+ }
1563
+ return /* @__PURE__ */ jsx18(UserMessageContainer, {});
1564
+ }
1565
+ return /* @__PURE__ */ jsx18(AssistantMessageContainer, {});
1566
+ }
1567
+ function ThreadContainer({ composer }) {
1568
+ useEffect9(() => {
1569
+ void preloadMarkdownOpenUI();
1570
+ }, []);
1571
+ useSyncSessionTitle();
1572
+ const shell = useOptionalShellMode();
1573
+ const WelcomeScreen = useSlot("WelcomeScreen");
1574
+ const MessageListSkeleton = useSlot("MessageListSkeleton");
1575
+ const ScrollToBottomButton = useSlot("ScrollToBottomButton");
1576
+ const MessageGroup = useSlot("MessageGroup");
1577
+ const ThreadComposerAreaShell = useSlot("ThreadComposerAreaShell");
1578
+ const ThreadRootShell = useSlot("ThreadRootShell");
1579
+ const ThreadViewportShell = useSlot("ThreadViewportShell");
1580
+ const isEmpty = useAuiState12(isNewChatView);
1581
+ const isLoading = useAuiState12((s) => s.thread.isLoading);
1582
+ const welcomeHeading = shell?.mode.status === "active" ? shell.mode.agentName : void 0;
1583
+ return /* @__PURE__ */ jsx18(ComposerBusyProvider, { children: /* @__PURE__ */ jsx18(ThreadPrimitive.Root, { asChild: true, children: /* @__PURE__ */ jsxs3(ThreadRootShell, { children: [
1584
+ /* @__PURE__ */ jsx18(ThreadPrimitive.Viewport, { asChild: true, autoScroll: true, children: /* @__PURE__ */ jsxs3(ThreadViewportShell, { isEmpty, children: [
1585
+ isEmpty && /* @__PURE__ */ jsx18(WelcomeScreen, { heading: welcomeHeading }),
1586
+ isEmpty && !isLoading && composer,
1587
+ isLoading ? /* @__PURE__ */ jsx18(MessageListSkeleton, {}) : !isEmpty && /* @__PURE__ */ jsxs3(Fragment2, { children: [
1588
+ /* @__PURE__ */ jsx18(HistoryLoaderContainer, {}),
1589
+ /* @__PURE__ */ jsxs3(MessageGroup, { children: [
1590
+ /* @__PURE__ */ jsx18(ThreadPrimitive.Messages, { children: ({ message }) => /* @__PURE__ */ jsx18(AnimatedMessageShell, { children: /* @__PURE__ */ jsx18(ThreadMessage, { isEditing: message.role === "user" && message.composer.isEditing }) }) }),
1591
+ /* @__PURE__ */ jsx18(ResumeUnavailableContainer, {})
1592
+ ] })
1593
+ ] })
1594
+ ] }) }),
1595
+ !isLoading && !isEmpty && /* @__PURE__ */ jsxs3(ThreadComposerAreaShell, { isEmpty, children: [
1596
+ /* @__PURE__ */ jsx18(ThreadPrimitive.ScrollToBottom, { asChild: true, children: /* @__PURE__ */ jsx18(ScrollToBottomButton, {}) }),
1597
+ composer
1598
+ ] })
1599
+ ] }) }) });
1600
+ }
1601
+
1602
+ // src/containers/Thread.tsx
1603
+ import { jsx as jsx19 } from "react/jsx-runtime";
1604
+ function Thread() {
1605
+ return /* @__PURE__ */ jsx19(ThreadContainer, { composer: /* @__PURE__ */ jsx19(ComposerContainer, {}) });
1606
+ }
1607
+
1608
+ // src/containers/ThreadListContainer.tsx
1609
+ import {
1610
+ ThreadListItemByIndexProvider,
1611
+ ThreadListItemMorePrimitive,
1612
+ ThreadListItemPrimitive,
1613
+ ThreadListPrimitive,
1614
+ useAui as useAui5,
1615
+ useAuiState as useAuiState13
1616
+ } from "@assistant-ui/react";
1617
+ import { useEffect as useEffect12, useMemo as useMemo5, useRef as useRef11, useState as useState14 } from "react";
1618
+
1619
+ // src/atoms/AgentHistoryFilterButton.tsx
1620
+ import { useEffect as useEffect11, useId as useId2, useLayoutEffect, useRef as useRef10, useState as useState13 } from "react";
1621
+ import { createPortal } from "react-dom";
1622
+
1623
+ // src/atoms/primitives/DropdownMenu.tsx
1624
+ import React, { useEffect as useEffect10, useId, useRef as useRef9, useState as useState12 } from "react";
1625
+ import { jsx as jsx20, jsxs as jsxs4 } from "react/jsx-runtime";
1626
+ function DropdownMenuItem({ className, ...props }) {
1627
+ return /* @__PURE__ */ jsx20(
1628
+ "button",
1629
+ {
1630
+ role: "menuitem",
1631
+ type: "button",
1632
+ className: cn(
1633
+ "flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none",
1634
+ "transition-colors hover:bg-ghost-button-hover",
1635
+ "focus:bg-dropdown-selected-item-bg focus:text-dropdown-selected-item-text",
1636
+ "aria-selected:bg-dropdown-selected-item-bg aria-selected:text-dropdown-selected-item-text",
1637
+ "disabled:pointer-events-none disabled:opacity-50",
1638
+ className
1639
+ ),
1640
+ ...props
1641
+ }
1642
+ );
1643
+ }
1644
+
1645
+ // src/atoms/AgentHistoryFilterButton.tsx
1646
+ import { Fragment as Fragment3, jsx as jsx21, jsxs as jsxs5 } from "react/jsx-runtime";
1647
+ function themePortalRoot(from) {
1648
+ return from?.closest(".aui-theme-root") ?? document.body;
1649
+ }
1650
+ function AgentHistoryFilterButton() {
1651
+ const shell = useOptionalShellMode();
1652
+ const server = useOptionalServer();
1653
+ const isMobile = useIsMobile();
1654
+ const compact = useCompactLayout();
1655
+ const useSheet = isMobile || compact;
1656
+ const [open, setOpen] = useState13(false);
1657
+ const [query, setQuery] = useState13("");
1658
+ const [menuPos, setMenuPos] = useState13(null);
1659
+ const buttonRef = useRef10(null);
1660
+ const menuRef = useRef10(null);
1661
+ const menuId = useId2();
1662
+ const enabled = shell?.isLibraryEnabled === true && server != null;
1663
+ const selected = shell?.historyAgentFilter ?? null;
1664
+ useEffect11(() => {
1665
+ if (!open) setQuery("");
1666
+ }, [open]);
1667
+ const { agents, isInitialLoading, isSearching, loadingMore, hasMore, listRef, sentinelRef } = useSearchAgentsList({
1668
+ enabled: open && enabled,
1669
+ query
1670
+ });
1671
+ useLayoutEffect(() => {
1672
+ if (!open || useSheet) {
1673
+ setMenuPos(null);
1674
+ return;
1675
+ }
1676
+ const update = () => {
1677
+ const rect = buttonRef.current?.getBoundingClientRect();
1678
+ if (!rect) return;
1679
+ setMenuPos({ top: rect.top, left: rect.right + 4 });
1680
+ };
1681
+ update();
1682
+ window.addEventListener("resize", update);
1683
+ window.addEventListener("scroll", update, true);
1684
+ return () => {
1685
+ window.removeEventListener("resize", update);
1686
+ window.removeEventListener("scroll", update, true);
1687
+ };
1688
+ }, [open, useSheet]);
1689
+ useEffect11(() => {
1690
+ if (!open || useSheet) return;
1691
+ const handler = (e) => {
1692
+ const target = e.target;
1693
+ if (buttonRef.current?.contains(target) || menuRef.current?.contains(target)) return;
1694
+ setOpen(false);
1695
+ };
1696
+ document.addEventListener("mousedown", handler);
1697
+ return () => document.removeEventListener("mousedown", handler);
1698
+ }, [open, useSheet]);
1699
+ if (!enabled) return null;
1700
+ const pick = (agentId) => {
1701
+ shell?.setHistoryAgentFilter(agentId);
1702
+ setOpen(false);
1703
+ };
1704
+ const filterBody = /* @__PURE__ */ jsxs5(Fragment3, { children: [
1705
+ /* @__PURE__ */ jsxs5("div", { className: "p-1", onMouseDown: (e) => e.stopPropagation(), children: [
1706
+ /* @__PURE__ */ jsx21(SearchInput_default, { query, setQuery, placeholder: "Search agents" }),
1707
+ isSearching ? /* @__PURE__ */ jsx21("p", { className: "text-text-secondary px-1 pt-1 text-[11px]", role: "status", children: "Searching\u2026" }) : null
1708
+ ] }),
1709
+ /* @__PURE__ */ jsxs5(
1710
+ "div",
1711
+ {
1712
+ ref: listRef,
1713
+ className: cn("mt-1 overflow-y-auto", useSheet ? "min-h-0 flex-1 px-1 pb-2" : "min-h-48 max-h-64"),
1714
+ children: [
1715
+ query.trim() === "" ? /* @__PURE__ */ jsxs5(
1716
+ DropdownMenuItem,
1717
+ {
1718
+ className: cn(
1719
+ "justify-between",
1720
+ selected == null && "bg-dropdown-selected-item-bg text-dropdown-selected-item-text"
1721
+ ),
1722
+ onClick: () => pick(null),
1723
+ children: [
1724
+ "All chats",
1725
+ selected == null ? /* @__PURE__ */ jsx21(Icon, { name: "check", className: "size-3.5 shrink-0" }) : null
1726
+ ]
1727
+ }
1728
+ ) : null,
1729
+ isInitialLoading ? /* @__PURE__ */ jsx21("p", { className: "px-2 py-3 text-center text-xs text-text-secondary", children: "Loading\u2026" }) : agents.length === 0 ? /* @__PURE__ */ jsx21("p", { className: "text-text-secondary px-2 py-6 text-center text-xs", role: "status", children: query.trim() ? `No agents match "${query.trim()}".` : "No agents yet." }) : /* @__PURE__ */ jsxs5(Fragment3, { children: [
1730
+ agents.map((agent) => {
1731
+ const id = libraryAgentId(agent);
1732
+ const active = selected === id;
1733
+ return /* @__PURE__ */ jsxs5(
1734
+ DropdownMenuItem,
1735
+ {
1736
+ className: cn(
1737
+ "justify-between gap-2 text-left",
1738
+ active && "bg-dropdown-selected-item-bg text-dropdown-selected-item-text"
1739
+ ),
1740
+ onClick: () => pick(id),
1741
+ children: [
1742
+ /* @__PURE__ */ jsx21("span", { className: "min-w-0 truncate", children: agent.name }),
1743
+ active ? /* @__PURE__ */ jsx21(Icon, { name: "check", className: "size-3.5 shrink-0" }) : null
1744
+ ]
1745
+ },
1746
+ id
1747
+ );
1748
+ }),
1749
+ hasMore ? /* @__PURE__ */ jsx21("div", { ref: sentinelRef, className: "flex h-6 shrink-0 items-center justify-center", "aria-hidden": true, children: loadingMore ? /* @__PURE__ */ jsx21("span", { className: "text-text-secondary text-[11px]", role: "status", children: "Loading more\u2026" }) : null }) : null
1750
+ ] })
1751
+ ]
1752
+ }
1753
+ )
1754
+ ] });
1755
+ return /* @__PURE__ */ jsxs5("div", { className: "relative shrink-0", children: [
1756
+ /* @__PURE__ */ jsxs5(
1757
+ "button",
1758
+ {
1759
+ ref: buttonRef,
1760
+ type: "button",
1761
+ "aria-label": selected != null ? `Filter chat history by agent (${selected})` : "Filter chat history by agent",
1762
+ "aria-haspopup": useSheet ? "dialog" : "menu",
1763
+ "aria-expanded": open,
1764
+ "aria-controls": open ? menuId : void 0,
1765
+ title: "Filter by agent",
1766
+ className: auiButtonClass({
1767
+ variant: "ghost",
1768
+ size: "icon",
1769
+ className: cn(
1770
+ "relative size-7 shrink-0 text-text-secondary hover:bg-ghost-button-hover hover:text-ghost-button-text",
1771
+ selected != null && "text-text-primary"
1772
+ )
1773
+ }),
1774
+ onClick: () => setOpen((v) => !v),
1775
+ children: [
1776
+ /* @__PURE__ */ jsx21(Icon, { name: "funnel", className: "size-3.5" }),
1777
+ selected != null ? /* @__PURE__ */ jsx21(
1778
+ "span",
1779
+ {
1780
+ className: "bg-primary-button-bg absolute top-1 right-1 size-1.5 rounded-full",
1781
+ "aria-hidden": true,
1782
+ "data-testid": "history-filter-active-dot"
1783
+ }
1784
+ ) : null
1785
+ ]
1786
+ }
1787
+ ),
1788
+ useSheet && open ? /* @__PURE__ */ jsx21(BottomSheet, { open: true, onOpenChange: setOpen, id: menuId, "aria-label": "Filter agents", children: /* @__PURE__ */ jsx21("div", { className: "flex min-h-0 flex-1 flex-col p-2", role: "menu", children: filterBody }) }) : null,
1789
+ !useSheet && open && menuPos != null ? createPortal(
1790
+ /* @__PURE__ */ jsx21(
1791
+ "div",
1792
+ {
1793
+ ref: menuRef,
1794
+ id: menuId,
1795
+ role: "menu",
1796
+ "aria-label": "Filter agents",
1797
+ style: { top: menuPos.top, left: menuPos.left },
1798
+ className: "font-sans-flex fixed z-50 w-56 rounded-md border border-border bg-card-bg p-1 text-text-primary shadow-md",
1799
+ children: filterBody
1800
+ }
1801
+ ),
1802
+ themePortalRoot(buttonRef.current)
1803
+ ) : null
1804
+ ] });
1805
+ }
1806
+
1807
+ // src/containers/ThreadListContainer.tsx
1808
+ import { Fragment as Fragment4, jsx as jsx22, jsxs as jsxs6 } from "react/jsx-runtime";
1809
+ var deleteItemClass = "flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none text-failure-bg hover:bg-ghost-button-hover hover:text-failure-bg focus:bg-ghost-button-hover focus:text-failure-bg data-[highlighted]:bg-ghost-button-hover data-[highlighted]:text-failure-bg";
1810
+ function ThreadListItemDeleteMenu() {
1811
+ const compact = useCompactLayout();
1812
+ const isMobile = useIsMobile();
1813
+ const [sheetOpen, setSheetOpen] = useState14(false);
1814
+ const useSheet = isMobile || compact;
1815
+ const moreButtonClass = auiButtonClass({
1816
+ variant: "ghost",
1817
+ size: "icon",
1818
+ className: "size-7 shrink-0 text-text-secondary hover:bg-transparent hover:text-text-primary"
1819
+ });
1820
+ if (useSheet) {
1821
+ return /* @__PURE__ */ jsxs6(Fragment4, { children: [
1822
+ /* @__PURE__ */ jsx22(
1823
+ "button",
1824
+ {
1825
+ type: "button",
1826
+ "aria-label": "Session actions",
1827
+ title: "Session actions",
1828
+ "aria-haspopup": "dialog",
1829
+ "aria-expanded": sheetOpen,
1830
+ className: moreButtonClass,
1831
+ onClick: () => setSheetOpen(true),
1832
+ children: /* @__PURE__ */ jsx22(Icon, { name: "ellipsis", className: "size-3.5" })
1833
+ }
1834
+ ),
1835
+ sheetOpen ? /* @__PURE__ */ jsx22(BottomSheet, { open: true, onOpenChange: setSheetOpen, "aria-label": "Session actions", children: /* @__PURE__ */ jsx22("div", { className: "flex flex-col gap-1 p-2", role: "menu", children: /* @__PURE__ */ jsxs6(ThreadListItemPrimitive.Delete, { className: deleteItemClass, onClick: () => setSheetOpen(false), children: [
1836
+ /* @__PURE__ */ jsx22(Icon, { name: "trash", className: "size-3.5" }),
1837
+ "Delete"
1838
+ ] }) }) }) : null
1839
+ ] });
1840
+ }
1841
+ return /* @__PURE__ */ jsxs6(ThreadListItemMorePrimitive.Root, { sharedFocusGroup: true, children: [
1842
+ /* @__PURE__ */ jsx22(
1843
+ ThreadListItemMorePrimitive.Trigger,
1844
+ {
1845
+ "aria-label": "Session actions",
1846
+ title: "Session actions",
1847
+ className: moreButtonClass,
1848
+ children: /* @__PURE__ */ jsx22(Icon, { name: "ellipsis", className: "size-3.5" })
1849
+ }
1850
+ ),
1851
+ /* @__PURE__ */ jsx22(
1852
+ ThreadListItemMorePrimitive.Content,
1853
+ {
1854
+ align: "end",
1855
+ sideOffset: 4,
1856
+ className: "z-50 min-w-[8rem] rounded-md border border-border bg-card-bg p-1 text-text-primary shadow-md",
1857
+ children: /* @__PURE__ */ jsx22(ThreadListItemPrimitive.Delete, { asChild: true, children: /* @__PURE__ */ jsxs6(ThreadListItemMorePrimitive.Item, { className: deleteItemClass, children: [
1858
+ /* @__PURE__ */ jsx22(Icon, { name: "trash", className: "size-3.5" }),
1859
+ "Delete"
1860
+ ] }) })
1861
+ }
1862
+ )
1863
+ ] });
1864
+ }
1865
+ function ThreadListItemRow({
1866
+ onThreadOpen,
1867
+ canDeleteSession
1868
+ }) {
1869
+ const aui = useAui5();
1870
+ const shell = useOptionalShellMode();
1871
+ const ThreadListRow = useSlot("ThreadListRow");
1872
+ const id = useAuiState13((s) => s.threadListItem.id);
1873
+ const remoteId = useAuiState13((s) => s.threadListItem.remoteId);
1874
+ const title = useAuiState13((s) => s.threadListItem.title);
1875
+ const lastMessageAt = useAuiState13((s) => s.threadListItem.lastMessageAt);
1876
+ const custom = useAuiState13((s) => s.threadListItem.custom);
1877
+ const mainThreadId = useAuiState13((s) => s.threads.mainThreadId);
1878
+ const agentName = readThreadAgentName(custom);
1879
+ const showDelete = canDeleteSession && remoteId != null;
1880
+ return /* @__PURE__ */ jsx22(ThreadListItemPrimitive.Root, { className: "min-w-0", children: /* @__PURE__ */ jsx22(
1881
+ ThreadListRow,
1882
+ {
1883
+ title: title ?? "New Chat",
1884
+ active: id === mainThreadId,
1885
+ agentName,
1886
+ lastMessageAt,
1887
+ onSelect: () => {
1888
+ onThreadOpen?.();
1889
+ shell?.setSettingsOpen(false);
1890
+ const sessionMutable = threadListItemIsMutable(custom);
1891
+ const sameImmutable = !sessionMutable && shell?.mode.status === "active" && !shell.mode.isMutable && (agentName == null ? shell.mode.agentName == null && shell.mode.agentId == null : shell.mode.agentName === agentName || shell.mode.agentId === agentName);
1892
+ const sameMutable = canReuseMutableShell({
1893
+ sessionMutable,
1894
+ shellMutable: shell?.mode.status === "active" && shell.mode.isMutable,
1895
+ ...shell?.mode.status === "active" && shell.mode.isMutable ? { shellAgentName: shell.mode.agentName, shellAgentId: shell.mode.agentId } : {},
1896
+ remoteId,
1897
+ pendingSessionId: shell?.pendingSessionId
1898
+ });
1899
+ if ((sameImmutable || sameMutable) && remoteId != null) {
1900
+ void Promise.resolve(aui.threads().switchToThread(id)).catch(() => void 0);
1901
+ return;
1902
+ }
1903
+ if (remoteId != null) {
1904
+ shell?.openHistorySession({
1905
+ sessionId: remoteId,
1906
+ isMutable: sessionMutable,
1907
+ ...agentName != null ? { agentName } : {}
1908
+ });
1909
+ return;
1910
+ }
1911
+ void Promise.resolve(aui.threads().switchToThread(id)).catch(() => void 0);
1912
+ },
1913
+ actions: showDelete ? /* @__PURE__ */ jsx22(ThreadListItemDeleteMenu, {}) : void 0
1914
+ }
1915
+ ) });
1916
+ }
1917
+ function useThreadListIndicesByRecency() {
1918
+ const threadIds = useAuiState13((s) => s.threads.threadIds);
1919
+ const threadItems = useAuiState13((s) => s.threads.threadItems);
1920
+ return useMemo5(() => threadListIndicesByRecency({ threadIds, threadItems }), [threadIds, threadItems]);
1921
+ }
1922
+ function ThreadListItemsByRecency({
1923
+ onThreadOpen,
1924
+ canDeleteSession
1925
+ }) {
1926
+ const indices = useThreadListIndicesByRecency();
1927
+ const threadIds = useAuiState13((s) => s.threads.threadIds);
1928
+ return /* @__PURE__ */ jsx22(Fragment4, { children: indices.map((index) => {
1929
+ const key = threadIds[index] ?? String(index);
1930
+ return /* @__PURE__ */ jsx22(ThreadListItemByIndexProvider, { index, archived: false, children: /* @__PURE__ */ jsx22(ThreadListItemRow, { onThreadOpen, canDeleteSession }) }, key);
1931
+ }) });
1932
+ }
1933
+ var THREAD_LIST_VIEWPORT_SLOT = "aui_thread-list-viewport";
1934
+ var LOAD_MORE_BOTTOM_PX = 80;
1935
+ function ChatHistorySection({ children, viewportRef }) {
1936
+ const [expanded, setExpanded] = useState14(true);
1937
+ const shell = useOptionalShellMode();
1938
+ const showFilter = shell?.isLibraryEnabled === true;
1939
+ return /* @__PURE__ */ jsxs6("div", { className: "flex min-h-0 flex-1 flex-col", children: [
1940
+ /* @__PURE__ */ jsxs6("div", { className: "flex shrink-0 items-center gap-1 px-1 py-1", children: [
1941
+ /* @__PURE__ */ jsxs6(
1942
+ "button",
1943
+ {
1944
+ type: "button",
1945
+ "aria-expanded": expanded,
1946
+ className: "flex min-w-0 flex-1 items-center gap-1 rounded-md px-1.5 py-1 text-left text-sm font-medium text-text-secondary hover:bg-ghost-button-hover hover:text-text-primary",
1947
+ onClick: () => setExpanded((v) => !v),
1948
+ children: [
1949
+ /* @__PURE__ */ jsx22("span", { className: "truncate", children: "Chat History" }),
1950
+ /* @__PURE__ */ jsx22(
1951
+ Icon,
1952
+ {
1953
+ name: "chevron-down",
1954
+ className: cn("size-3.5 shrink-0 transition-transform", !expanded && "-rotate-90")
1955
+ }
1956
+ )
1957
+ ]
1958
+ }
1959
+ ),
1960
+ showFilter ? /* @__PURE__ */ jsx22(AgentHistoryFilterButton, {}) : null
1961
+ ] }),
1962
+ expanded ? /* @__PURE__ */ jsx22(
1963
+ "div",
1964
+ {
1965
+ ref: viewportRef,
1966
+ "data-slot": THREAD_LIST_VIEWPORT_SLOT,
1967
+ className: "flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto",
1968
+ children
1969
+ }
1970
+ ) : null
1971
+ ] });
1972
+ }
1973
+ function ThreadListContainer({ onThreadOpen } = {}) {
1974
+ const aui = useAui5();
1975
+ const server = useOptionalServer();
1976
+ const isLoading = useAuiState13((s) => s.threads.isLoading);
1977
+ const hasMore = useAuiState13((s) => s.threads.hasMore);
1978
+ const threadIds = useAuiState13((s) => s.threads.threadIds);
1979
+ const shell = useOptionalShellMode();
1980
+ const ThreadListShell = useSlot("ThreadListShell");
1981
+ const ThreadListNewButton = useSlot("ThreadListNewButton");
1982
+ const AgentsLibraryButton = useSlot("AgentsLibraryButton");
1983
+ const ThreadListRowSkeleton = useSlot("ThreadListRowSkeleton");
1984
+ const ThreadListEmptyState = useSlot("ThreadListEmptyState");
1985
+ const viewportRef = useRef11(null);
1986
+ const loadMoreInflightRef = useRef11(false);
1987
+ const hasMoreRef = useRef11(hasMore);
1988
+ const auiRef = useRef11(aui);
1989
+ hasMoreRef.current = hasMore;
1990
+ auiRef.current = aui;
1991
+ const showNewChat = shell?.isNewChatEnabled !== false;
1992
+ const isIdle = shell?.mode.status === "idle";
1993
+ const canDeleteSession = typeof server?.deleteSession === "function";
1994
+ useEffect12(() => {
1995
+ if (isIdle) return;
1996
+ const viewport = viewportRef.current;
1997
+ if (!viewport) return;
1998
+ let cancelled = false;
1999
+ let chainRaf = 0;
2000
+ const tryLoadMore = () => {
2001
+ if (cancelled || !hasMoreRef.current || loadMoreInflightRef.current) return;
2002
+ if (viewport.scrollTop <= 0) return;
2003
+ const remaining = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
2004
+ if (remaining > LOAD_MORE_BOTTOM_PX) return;
2005
+ loadMoreInflightRef.current = true;
2006
+ void Promise.resolve(auiRef.current.threads().loadMore()).finally(() => {
2007
+ loadMoreInflightRef.current = false;
2008
+ if (cancelled) return;
2009
+ chainRaf = requestAnimationFrame(() => tryLoadMore());
2010
+ });
2011
+ };
2012
+ viewport.addEventListener("scroll", tryLoadMore, { passive: true });
2013
+ return () => {
2014
+ cancelled = true;
2015
+ cancelAnimationFrame(chainRaf);
2016
+ viewport.removeEventListener("scroll", tryLoadMore);
2017
+ };
2018
+ }, [isIdle]);
2019
+ const handleNewChat = () => {
2020
+ onThreadOpen?.();
2021
+ if (shell?.isComposerEnabled) {
2022
+ shell.openDraft();
2023
+ return;
2024
+ }
2025
+ shell?.setSettingsOpen(false);
2026
+ void Promise.resolve(aui.threads().switchToNewThread()).catch(() => void 0);
2027
+ };
2028
+ let listBody;
2029
+ if (isIdle) {
2030
+ listBody = /* @__PURE__ */ jsx22(ThreadListEmptyState, {});
2031
+ } else if (isLoading) {
2032
+ listBody = /* @__PURE__ */ jsx22(ThreadListRowSkeleton, {});
2033
+ } else if (threadIds.length === 0) {
2034
+ listBody = /* @__PURE__ */ jsx22(ThreadListEmptyState, {});
2035
+ } else {
2036
+ listBody = /* @__PURE__ */ jsx22(ThreadListPrimitive.Root, { className: "flex min-h-0 flex-col gap-0.5", children: /* @__PURE__ */ jsx22(ThreadListItemsByRecency, { onThreadOpen, canDeleteSession }) });
2037
+ }
2038
+ return /* @__PURE__ */ jsx22(
2039
+ ThreadListShell,
2040
+ {
2041
+ header: /* @__PURE__ */ jsxs6("div", { className: "flex flex-col gap-1", children: [
2042
+ showNewChat ? /* @__PURE__ */ jsx22(ThreadListNewButton, { onClick: handleNewChat }) : null,
2043
+ /* @__PURE__ */ jsx22(
2044
+ AgentsLibraryButton,
2045
+ {
2046
+ onSelectAgent: () => {
2047
+ onThreadOpen?.();
2048
+ }
2049
+ }
2050
+ )
2051
+ ] }),
2052
+ children: /* @__PURE__ */ jsxs6(ChatHistorySection, { viewportRef, children: [
2053
+ listBody,
2054
+ !isIdle && hasMore ? /* @__PURE__ */ jsx22("div", { className: "h-4 shrink-0", "aria-hidden": true }) : null
2055
+ ] })
2056
+ }
2057
+ );
2058
+ }
2059
+
2060
+ export {
2061
+ AgentStepsContainer,
2062
+ AskUserContainer,
2063
+ computeAgentStepsSplit,
2064
+ AssistantTextContainer,
2065
+ ReasoningContainer,
2066
+ ToolApprovalContainer,
2067
+ ToolCallContentBlockContainer,
2068
+ ToolCallContainer,
2069
+ AssistantMessageContainer,
2070
+ ComposerAttachmentsContainer,
2071
+ MessageAttachmentsContainer,
2072
+ ComposerAttachmentPickerContainer,
2073
+ notifyComposerBusyFailure,
2074
+ ComposerBusyProvider,
2075
+ useComposerBusyState,
2076
+ threadHasPendingMcpAuth,
2077
+ useComposerPauseView,
2078
+ McpAuthContainer,
2079
+ ComposerContainer,
2080
+ HistoryLoaderContainer,
2081
+ ResumeUnavailableContainer,
2082
+ UserEditComposerContainer,
2083
+ UserMessageContainer,
2084
+ ThreadContainer,
2085
+ Thread,
2086
+ ThreadListContainer
2087
+ };
2088
+ //# sourceMappingURL=chunk-UXZOL5GO.js.map