simple-module-chat 0.0.20__py3-none-any.whl
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.
- simple_module_chat-0.0.20.dist-info/METADATA +118 -0
- simple_module_chat-0.0.20.dist-info/RECORD +46 -0
- simple_module_chat-0.0.20.dist-info/WHEEL +4 -0
- simple_module_chat-0.0.20.dist-info/entry_points.txt +2 -0
- sm_chat/__init__.py +7 -0
- sm_chat/agent/__init__.py +3 -0
- sm_chat/agent/definition.py +72 -0
- sm_chat/agent/instructions.py +101 -0
- sm_chat/agent/toolset.py +102 -0
- sm_chat/contracts/__init__.py +21 -0
- sm_chat/contracts/registry.py +61 -0
- sm_chat/contracts/types.py +51 -0
- sm_chat/core/__init__.py +3 -0
- sm_chat/core/constants.py +55 -0
- sm_chat/core/settings.py +104 -0
- sm_chat/core/tenancy/__init__.py +125 -0
- sm_chat/core/tenancy/_mode.py +207 -0
- sm_chat/index.ts +26 -0
- sm_chat/locales/de.json +99 -0
- sm_chat/locales/en.json +99 -0
- sm_chat/module.py +85 -0
- sm_chat/package.json +20 -0
- sm_chat/pages/Index.tsx +108 -0
- sm_chat/ui/components/ApprovalCard.tsx +129 -0
- sm_chat/ui/components/ChatDrawerHost.tsx +248 -0
- sm_chat/ui/components/ChatExportActions.tsx +87 -0
- sm_chat/ui/components/ChatPanel.tsx +225 -0
- sm_chat/ui/components/MessageList.tsx +153 -0
- sm_chat/ui/components/SuggestedPrompts.tsx +65 -0
- sm_chat/ui/components/ThreadSidebar.tsx +222 -0
- sm_chat/ui/components/ToolCallPill.tsx +105 -0
- sm_chat/ui/hooks/threadMapping.ts +248 -0
- sm_chat/ui/hooks/useChatContext.ts +46 -0
- sm_chat/ui/hooks/useChatThread.ts +289 -0
- sm_chat/ui/hooks/useThreadStream.ts +87 -0
- sm_chat/ui/utils/api.ts +133 -0
- sm_chat/ui/utils/exportMarkdown.ts +66 -0
- sm_chat/ui/utils/i18n.ts +59 -0
- sm_chat/ui/utils/markdown.tsx +238 -0
- sm_chat/ui/utils/sse.ts +171 -0
- sm_chat/ui/utils/types.ts +111 -0
- sm_chat/web/__init__.py +3 -0
- sm_chat/web/endpoints/__init__.py +3 -0
- sm_chat/web/endpoints/api.py +117 -0
- sm_chat/web/endpoints/views.py +22 -0
- sm_chat/web/shared_props.py +33 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Collapsible indicator pill for a single agent tool call. */
|
|
2
|
+
|
|
3
|
+
import { Badge } from '@simple-module-py/ui/components/ui/badge';
|
|
4
|
+
import {
|
|
5
|
+
AlertCircle,
|
|
6
|
+
CheckCircle2,
|
|
7
|
+
ChevronDown,
|
|
8
|
+
ChevronRight,
|
|
9
|
+
Loader2,
|
|
10
|
+
Wrench,
|
|
11
|
+
} from 'lucide-react';
|
|
12
|
+
import { useState } from 'react';
|
|
13
|
+
|
|
14
|
+
import { keys, useT } from '../utils/i18n';
|
|
15
|
+
import type { ToolCallActivity } from '../utils/types';
|
|
16
|
+
|
|
17
|
+
export function formatToolIdentifier(rawName: string): {
|
|
18
|
+
provider: string | null;
|
|
19
|
+
action: string;
|
|
20
|
+
} {
|
|
21
|
+
const sep = rawName.indexOf('__');
|
|
22
|
+
const provider = sep > 0 ? rawName.slice(0, sep) : null;
|
|
23
|
+
const rawAction = sep > 0 ? rawName.slice(sep + 2) : rawName;
|
|
24
|
+
const action = rawAction
|
|
25
|
+
.replace(/[_-]+/g, ' ')
|
|
26
|
+
.trim()
|
|
27
|
+
.replace(/^\w/, (ch) => ch.toUpperCase());
|
|
28
|
+
return { provider, action: action || rawName };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type ToolCallPillProps = {
|
|
32
|
+
toolCall: ToolCallActivity;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function ToolCallPill({ toolCall }: ToolCallPillProps) {
|
|
36
|
+
const { t } = useT();
|
|
37
|
+
const [expanded, setExpanded] = useState(false);
|
|
38
|
+
const { provider, action } = formatToolIdentifier(toolCall.toolName);
|
|
39
|
+
const hasDetails = Boolean(toolCall.argsText || toolCall.result);
|
|
40
|
+
|
|
41
|
+
const statusLabel =
|
|
42
|
+
toolCall.status === 'running'
|
|
43
|
+
? t(keys.chat.tools.running, { tool: action })
|
|
44
|
+
: toolCall.status === 'failed'
|
|
45
|
+
? t(keys.chat.tools.failed, { tool: action })
|
|
46
|
+
: t(keys.chat.tools.completed, { tool: action });
|
|
47
|
+
|
|
48
|
+
return (
|
|
49
|
+
<div
|
|
50
|
+
className="rounded-md border bg-muted/40 text-xs"
|
|
51
|
+
data-testid="chat-tool-pill"
|
|
52
|
+
data-tool-status={toolCall.status}
|
|
53
|
+
>
|
|
54
|
+
<button
|
|
55
|
+
type="button"
|
|
56
|
+
disabled={!hasDetails}
|
|
57
|
+
onClick={() => setExpanded((open) => !open)}
|
|
58
|
+
aria-expanded={hasDetails ? expanded : undefined}
|
|
59
|
+
className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left disabled:cursor-default"
|
|
60
|
+
>
|
|
61
|
+
{toolCall.status === 'running' ? (
|
|
62
|
+
<Loader2 className="size-3.5 shrink-0 animate-spin text-primary" aria-hidden="true" />
|
|
63
|
+
) : toolCall.status === 'failed' ? (
|
|
64
|
+
<AlertCircle className="size-3.5 shrink-0 text-destructive" aria-hidden="true" />
|
|
65
|
+
) : (
|
|
66
|
+
<CheckCircle2 className="size-3.5 shrink-0 text-emerald-600" aria-hidden="true" />
|
|
67
|
+
)}
|
|
68
|
+
{provider ? (
|
|
69
|
+
<Badge variant="secondary" className="px-1.5 py-0 text-[10px] font-medium capitalize">
|
|
70
|
+
{provider}
|
|
71
|
+
</Badge>
|
|
72
|
+
) : (
|
|
73
|
+
<Wrench className="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
|
|
74
|
+
)}
|
|
75
|
+
<span className="min-w-0 flex-1 truncate text-foreground">{statusLabel}</span>
|
|
76
|
+
{hasDetails && (
|
|
77
|
+
<span className="flex items-center gap-1 text-muted-foreground">
|
|
78
|
+
<span className="sr-only">
|
|
79
|
+
{expanded ? t(keys.chat.tools.hide_details) : t(keys.chat.tools.show_details)}
|
|
80
|
+
</span>
|
|
81
|
+
{expanded ? (
|
|
82
|
+
<ChevronDown className="size-3.5" aria-hidden="true" />
|
|
83
|
+
) : (
|
|
84
|
+
<ChevronRight className="size-3.5" aria-hidden="true" />
|
|
85
|
+
)}
|
|
86
|
+
</span>
|
|
87
|
+
)}
|
|
88
|
+
</button>
|
|
89
|
+
{expanded && hasDetails && (
|
|
90
|
+
<div className="space-y-1.5 border-t px-2.5 py-2 font-mono text-[11px] text-muted-foreground">
|
|
91
|
+
{toolCall.argsText && (
|
|
92
|
+
<pre className="max-h-36 overflow-auto whitespace-pre-wrap break-all">
|
|
93
|
+
{toolCall.argsText}
|
|
94
|
+
</pre>
|
|
95
|
+
)}
|
|
96
|
+
{toolCall.result && (
|
|
97
|
+
<pre className="max-h-36 overflow-auto whitespace-pre-wrap break-all border-t pt-1.5">
|
|
98
|
+
{toolCall.result}
|
|
99
|
+
</pre>
|
|
100
|
+
)}
|
|
101
|
+
</div>
|
|
102
|
+
)}
|
|
103
|
+
</div>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/** Pure state helpers for mapping persisted thread messages and SSE chunks. */
|
|
2
|
+
|
|
3
|
+
import { type ParsedAiError, parseAiError } from '@simple-module-py/ai';
|
|
4
|
+
|
|
5
|
+
import { ChatApiError } from '../utils/api';
|
|
6
|
+
import { translate } from '../utils/i18n';
|
|
7
|
+
import type { SseChunk } from '../utils/sse';
|
|
8
|
+
import type {
|
|
9
|
+
ChatMessage,
|
|
10
|
+
ChatRequestMetadata,
|
|
11
|
+
PendingApprovalItem,
|
|
12
|
+
PersistedMessage,
|
|
13
|
+
ThreadSummary,
|
|
14
|
+
ToolCallActivity,
|
|
15
|
+
} from '../utils/types';
|
|
16
|
+
|
|
17
|
+
export type UseChatThreadOptions = {
|
|
18
|
+
agentId?: string;
|
|
19
|
+
enabled?: boolean;
|
|
20
|
+
csrfToken?: string;
|
|
21
|
+
initialThreadId?: string | null;
|
|
22
|
+
onThreadChange?: (threadId: string | null) => void;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type UseChatThreadResult = {
|
|
26
|
+
threads: ThreadSummary[];
|
|
27
|
+
threadsLoading: boolean;
|
|
28
|
+
activeThreadId: string | null;
|
|
29
|
+
messages: ChatMessage[];
|
|
30
|
+
pendingApprovals: PendingApprovalItem[];
|
|
31
|
+
streaming: boolean;
|
|
32
|
+
error: ParsedAiError | null;
|
|
33
|
+
sendMessage: (text: string, requestMetadata?: ChatRequestMetadata) => Promise<void>;
|
|
34
|
+
resumeApproval: (
|
|
35
|
+
approval: PendingApprovalItem,
|
|
36
|
+
approved: boolean,
|
|
37
|
+
denialReason?: string,
|
|
38
|
+
requestMetadata?: ChatRequestMetadata,
|
|
39
|
+
) => Promise<void>;
|
|
40
|
+
cancelRun: () => Promise<void>;
|
|
41
|
+
selectThread: (threadId: string) => Promise<void>;
|
|
42
|
+
startNewThread: () => void;
|
|
43
|
+
removeThread: (threadId: string) => Promise<void>;
|
|
44
|
+
renameThread: (threadId: string, title: string) => Promise<void>;
|
|
45
|
+
clearError: () => void;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export function nextId(prefix: string): string {
|
|
49
|
+
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function toParsedError(err: unknown, fallbackKey: string): ParsedAiError {
|
|
53
|
+
if (err instanceof ChatApiError) return err.parsed;
|
|
54
|
+
if (err instanceof Error && err.message) return parseAiError(err);
|
|
55
|
+
return { code: 'unknown', message: translate(fallbackKey), isQuota: false };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function parseRunErrorChunk(code: string | undefined, message: string): ParsedAiError {
|
|
59
|
+
const parsed = parseAiError({ code, detail: code ?? message });
|
|
60
|
+
return parsed.code === 'unknown' && message ? { ...parsed, message } : parsed;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function deriveThreadTitle(prompt: string): string {
|
|
64
|
+
const cleaned = prompt.replace(/\s+/g, ' ').trim();
|
|
65
|
+
if (cleaned.length <= 80) return cleaned;
|
|
66
|
+
return `${cleaned.slice(0, 77).trimEnd()}…`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function serializeUnknown(value: unknown): string {
|
|
70
|
+
if (value === undefined || value === null) return '';
|
|
71
|
+
if (typeof value === 'string') return value;
|
|
72
|
+
try {
|
|
73
|
+
return JSON.stringify(value, null, 2);
|
|
74
|
+
} catch {
|
|
75
|
+
return String(value);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Map `/api/ai/threads/{id}` persisted messages into UI `ChatMessage[]`. */
|
|
80
|
+
export function mapPersistedMessages(records: PersistedMessage[]): ChatMessage[] {
|
|
81
|
+
const out: ChatMessage[] = [];
|
|
82
|
+
const toolIndex = new Map<string, ToolCallActivity>();
|
|
83
|
+
|
|
84
|
+
for (const rec of records) {
|
|
85
|
+
if (rec.role === 'tool') {
|
|
86
|
+
for (const part of rec.parts ?? []) {
|
|
87
|
+
if (part.type === 'tool-result' && typeof part.toolCallId === 'string') {
|
|
88
|
+
const existing = toolIndex.get(part.toolCallId);
|
|
89
|
+
if (existing) {
|
|
90
|
+
existing.result = serializeUnknown(part.content);
|
|
91
|
+
existing.status = 'completed';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const role: 'user' | 'assistant' = rec.role === 'user' ? 'user' : 'assistant';
|
|
99
|
+
const toolCalls: ToolCallActivity[] = [];
|
|
100
|
+
for (const part of rec.parts ?? []) {
|
|
101
|
+
if (part.type === 'tool-call' && typeof part.toolCallId === 'string') {
|
|
102
|
+
const activity: ToolCallActivity = {
|
|
103
|
+
toolCallId: part.toolCallId,
|
|
104
|
+
toolName: typeof part.toolName === 'string' ? part.toolName : '',
|
|
105
|
+
argsText: serializeUnknown(part.args),
|
|
106
|
+
status: 'completed',
|
|
107
|
+
};
|
|
108
|
+
toolCalls.push(activity);
|
|
109
|
+
toolIndex.set(part.toolCallId, activity);
|
|
110
|
+
} else if (part.type === 'tool-result' && typeof part.toolCallId === 'string') {
|
|
111
|
+
const existing = toolIndex.get(part.toolCallId);
|
|
112
|
+
if (existing) {
|
|
113
|
+
existing.result = serializeUnknown(part.content);
|
|
114
|
+
existing.status = 'completed';
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (!rec.content && toolCalls.length === 0) continue;
|
|
120
|
+
out.push({
|
|
121
|
+
id: rec.id,
|
|
122
|
+
role,
|
|
123
|
+
content: rec.content,
|
|
124
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Apply a single streaming SSE chunk to the active assistant message. */
|
|
131
|
+
export function applyChunkToMessage(msg: ChatMessage, chunk: SseChunk): ChatMessage {
|
|
132
|
+
if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
|
|
133
|
+
return { ...msg, content: msg.content + chunk.delta };
|
|
134
|
+
}
|
|
135
|
+
if (chunk.type === 'TOOL_CALL_START') {
|
|
136
|
+
const prev = msg.toolCalls ?? [];
|
|
137
|
+
if (prev.some((tc) => tc.toolCallId === chunk.toolCallId)) return msg;
|
|
138
|
+
return {
|
|
139
|
+
...msg,
|
|
140
|
+
toolCalls: [
|
|
141
|
+
...prev,
|
|
142
|
+
{
|
|
143
|
+
toolCallId: chunk.toolCallId,
|
|
144
|
+
toolName: chunk.toolCallName,
|
|
145
|
+
argsText: '',
|
|
146
|
+
status: 'running',
|
|
147
|
+
},
|
|
148
|
+
],
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (chunk.type === 'TOOL_CALL_ARGS') {
|
|
152
|
+
const prev = msg.toolCalls ?? [];
|
|
153
|
+
return {
|
|
154
|
+
...msg,
|
|
155
|
+
toolCalls: prev.map((tc) =>
|
|
156
|
+
tc.toolCallId === chunk.toolCallId ? { ...tc, argsText: tc.argsText + chunk.delta } : tc,
|
|
157
|
+
),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
if (chunk.type === 'TOOL_CALL_END') {
|
|
161
|
+
const prev = msg.toolCalls ?? [];
|
|
162
|
+
return {
|
|
163
|
+
...msg,
|
|
164
|
+
toolCalls: prev.map((tc) =>
|
|
165
|
+
tc.toolCallId === chunk.toolCallId && tc.status === 'running'
|
|
166
|
+
? { ...tc, status: 'completed' }
|
|
167
|
+
: tc,
|
|
168
|
+
),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
if (chunk.type === 'TOOL_CALL_RESULT') {
|
|
172
|
+
const prev = msg.toolCalls ?? [];
|
|
173
|
+
return {
|
|
174
|
+
...msg,
|
|
175
|
+
toolCalls: prev.map((tc) =>
|
|
176
|
+
tc.toolCallId === chunk.toolCallId
|
|
177
|
+
? { ...tc, result: chunk.content, status: 'completed' }
|
|
178
|
+
: tc,
|
|
179
|
+
),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
return msg;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export type StagedApprovalEntry = {
|
|
186
|
+
decisions: Record<string, boolean>;
|
|
187
|
+
denialReasons: Record<string, string>;
|
|
188
|
+
batchItems: PendingApprovalItem[];
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
export type StagedApprovalMap = Record<string, StagedApprovalEntry>;
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Record one tool approval decision and return the remaining pending items plus
|
|
195
|
+
* the complete resume batch once every pending tool for `approval.runId` is decided.
|
|
196
|
+
*/
|
|
197
|
+
export function stageApprovalDecision(
|
|
198
|
+
staged: StagedApprovalMap,
|
|
199
|
+
pending: PendingApprovalItem[],
|
|
200
|
+
approval: PendingApprovalItem,
|
|
201
|
+
approved: boolean,
|
|
202
|
+
denialReason?: string,
|
|
203
|
+
): { remaining: PendingApprovalItem[]; ready?: StagedApprovalEntry } {
|
|
204
|
+
const entry = staged[approval.runId] ?? {
|
|
205
|
+
decisions: {},
|
|
206
|
+
denialReasons: {},
|
|
207
|
+
batchItems: pending.filter((item) => item.runId === approval.runId),
|
|
208
|
+
};
|
|
209
|
+
entry.decisions[approval.toolCallId] = approved;
|
|
210
|
+
const trimmed = denialReason?.trim();
|
|
211
|
+
if (!approved && trimmed) entry.denialReasons[approval.toolCallId] = trimmed;
|
|
212
|
+
staged[approval.runId] = entry;
|
|
213
|
+
|
|
214
|
+
const remaining = pending.filter((item) => item.toolCallId !== approval.toolCallId);
|
|
215
|
+
if (remaining.some((item) => item.runId === approval.runId)) {
|
|
216
|
+
return { remaining };
|
|
217
|
+
}
|
|
218
|
+
delete staged[approval.runId];
|
|
219
|
+
return { remaining, ready: entry };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function mergePendingApproval(
|
|
223
|
+
prev: PendingApprovalItem[],
|
|
224
|
+
approval: PendingApprovalItem,
|
|
225
|
+
): PendingApprovalItem[] {
|
|
226
|
+
return prev.some((item) => item.toolCallId === approval.toolCallId) ? prev : [...prev, approval];
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function buildResumePayload(runId: string, ready: StagedApprovalEntry) {
|
|
230
|
+
return {
|
|
231
|
+
runId,
|
|
232
|
+
decisions: ready.decisions,
|
|
233
|
+
denialReasons: Object.keys(ready.denialReasons).length > 0 ? ready.denialReasons : undefined,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export async function reloadPendingApprovals(
|
|
238
|
+
loadThread: (id: string) => Promise<{ pending_approvals?: PendingApprovalItem[] }>,
|
|
239
|
+
threadId: string,
|
|
240
|
+
fallback: PendingApprovalItem[],
|
|
241
|
+
): Promise<PendingApprovalItem[]> {
|
|
242
|
+
try {
|
|
243
|
+
const detail = await loadThread(threadId);
|
|
244
|
+
return detail.pending_approvals ?? [];
|
|
245
|
+
} catch {
|
|
246
|
+
return fallback;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Fetches `/api/chat/context` once when chat is enabled. */
|
|
2
|
+
|
|
3
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
4
|
+
|
|
5
|
+
import { fetchChatContext } from '../utils/api';
|
|
6
|
+
import { keys, translate } from '../utils/i18n';
|
|
7
|
+
import type { ChatContextData } from '../utils/types';
|
|
8
|
+
|
|
9
|
+
export type UseChatContextResult = {
|
|
10
|
+
context: ChatContextData | null;
|
|
11
|
+
loading: boolean;
|
|
12
|
+
error: string | null;
|
|
13
|
+
reload: () => Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function useChatContext(enabled = true): UseChatContextResult {
|
|
17
|
+
const [context, setContext] = useState<ChatContextData | null>(null);
|
|
18
|
+
const [loading, setLoading] = useState<boolean>(enabled);
|
|
19
|
+
const [error, setError] = useState<string | null>(null);
|
|
20
|
+
|
|
21
|
+
const reload = useCallback(async () => {
|
|
22
|
+
if (!enabled) return;
|
|
23
|
+
setLoading(true);
|
|
24
|
+
setError(null);
|
|
25
|
+
try {
|
|
26
|
+
const data = await fetchChatContext();
|
|
27
|
+
setContext(data);
|
|
28
|
+
} catch (err) {
|
|
29
|
+
setError(
|
|
30
|
+
err instanceof Error ? err.message : translate(keys.chat.errors.load_context_failed),
|
|
31
|
+
);
|
|
32
|
+
} finally {
|
|
33
|
+
setLoading(false);
|
|
34
|
+
}
|
|
35
|
+
}, [enabled]);
|
|
36
|
+
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (!enabled) {
|
|
39
|
+
setLoading(false);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
void reload();
|
|
43
|
+
}, [enabled, reload]);
|
|
44
|
+
|
|
45
|
+
return { context, loading, error, reload };
|
|
46
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/** Manages chat threads, SSE streaming turns, cancellation, and HITL approvals. */
|
|
2
|
+
|
|
3
|
+
import type { ParsedAiError } from '@simple-module-py/ai';
|
|
4
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
renameThread as apiRenameThread,
|
|
8
|
+
cancelThread,
|
|
9
|
+
createThread,
|
|
10
|
+
deleteThread,
|
|
11
|
+
getThread,
|
|
12
|
+
listThreads,
|
|
13
|
+
} from '../utils/api';
|
|
14
|
+
import { keys } from '../utils/i18n';
|
|
15
|
+
import type {
|
|
16
|
+
ChatMessage,
|
|
17
|
+
ChatRequestMetadata,
|
|
18
|
+
PendingApprovalItem,
|
|
19
|
+
ThreadSummary,
|
|
20
|
+
} from '../utils/types';
|
|
21
|
+
import {
|
|
22
|
+
buildResumePayload,
|
|
23
|
+
deriveThreadTitle,
|
|
24
|
+
mapPersistedMessages,
|
|
25
|
+
nextId,
|
|
26
|
+
reloadPendingApprovals,
|
|
27
|
+
type StagedApprovalMap,
|
|
28
|
+
stageApprovalDecision,
|
|
29
|
+
toParsedError,
|
|
30
|
+
type UseChatThreadOptions,
|
|
31
|
+
type UseChatThreadResult,
|
|
32
|
+
} from './threadMapping';
|
|
33
|
+
import { useThreadStream } from './useThreadStream';
|
|
34
|
+
|
|
35
|
+
export type { UseChatThreadOptions, UseChatThreadResult };
|
|
36
|
+
|
|
37
|
+
const DEFAULT_AGENT_ID = 'chat.assistant';
|
|
38
|
+
|
|
39
|
+
export function useChatThread(options: UseChatThreadOptions = {}): UseChatThreadResult {
|
|
40
|
+
const {
|
|
41
|
+
agentId = DEFAULT_AGENT_ID,
|
|
42
|
+
enabled = true,
|
|
43
|
+
csrfToken,
|
|
44
|
+
initialThreadId = null,
|
|
45
|
+
onThreadChange,
|
|
46
|
+
} = options;
|
|
47
|
+
|
|
48
|
+
const [threads, setThreads] = useState<ThreadSummary[]>([]);
|
|
49
|
+
const [threadsLoading, setThreadsLoading] = useState(false);
|
|
50
|
+
const [activeThreadId, setActiveThreadId] = useState<string | null>(initialThreadId);
|
|
51
|
+
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
52
|
+
const [pendingApprovals, setPendingApprovals] = useState<PendingApprovalItem[]>([]);
|
|
53
|
+
const [streaming, setStreaming] = useState(false);
|
|
54
|
+
const [error, setError] = useState<ParsedAiError | null>(null);
|
|
55
|
+
|
|
56
|
+
const abortRef = useRef<AbortController | null>(null);
|
|
57
|
+
const activeThreadRef = useRef<string | null>(activeThreadId);
|
|
58
|
+
activeThreadRef.current = activeThreadId;
|
|
59
|
+
const pendingApprovalsRef = useRef<PendingApprovalItem[]>(pendingApprovals);
|
|
60
|
+
pendingApprovalsRef.current = pendingApprovals;
|
|
61
|
+
const selectionGenRef = useRef(0);
|
|
62
|
+
const listGenRef = useRef(0);
|
|
63
|
+
const refreshIdRef = useRef(0);
|
|
64
|
+
const renameGenRef = useRef<Map<string, number>>(new Map());
|
|
65
|
+
const stagedDecisionsRef = useRef<StagedApprovalMap>({});
|
|
66
|
+
|
|
67
|
+
const updateActiveThread = useCallback(
|
|
68
|
+
(id: string | null) => {
|
|
69
|
+
activeThreadRef.current = id;
|
|
70
|
+
setActiveThreadId(id);
|
|
71
|
+
onThreadChange?.(id);
|
|
72
|
+
},
|
|
73
|
+
[onThreadChange],
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
const refreshThreads = useCallback(async () => {
|
|
77
|
+
if (!enabled) return;
|
|
78
|
+
const refreshId = ++refreshIdRef.current;
|
|
79
|
+
const gen = ++listGenRef.current;
|
|
80
|
+
setThreadsLoading(true);
|
|
81
|
+
try {
|
|
82
|
+
const next = await listThreads(agentId);
|
|
83
|
+
if (listGenRef.current !== gen) return;
|
|
84
|
+
setThreads(next);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (listGenRef.current !== gen) return;
|
|
87
|
+
setError(toParsedError(err, keys.chat.errors.load_threads_failed));
|
|
88
|
+
} finally {
|
|
89
|
+
if (refreshIdRef.current === refreshId) setThreadsLoading(false);
|
|
90
|
+
}
|
|
91
|
+
}, [agentId, enabled]);
|
|
92
|
+
|
|
93
|
+
const selectThread = useCallback(
|
|
94
|
+
async (threadId: string) => {
|
|
95
|
+
const gen = ++selectionGenRef.current;
|
|
96
|
+
abortRef.current?.abort();
|
|
97
|
+
stagedDecisionsRef.current = {};
|
|
98
|
+
setError(null);
|
|
99
|
+
setStreaming(false);
|
|
100
|
+
updateActiveThread(threadId);
|
|
101
|
+
try {
|
|
102
|
+
const detail = await getThread(threadId);
|
|
103
|
+
if (selectionGenRef.current !== gen) return;
|
|
104
|
+
setMessages(mapPersistedMessages(detail.messages));
|
|
105
|
+
setPendingApprovals(detail.pending_approvals ?? []);
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (selectionGenRef.current !== gen) return;
|
|
108
|
+
setError(toParsedError(err, keys.chat.errors.load_threads_failed));
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
[updateActiveThread],
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
if (!enabled) return;
|
|
116
|
+
void refreshThreads();
|
|
117
|
+
if (initialThreadId) {
|
|
118
|
+
void selectThread(initialThreadId);
|
|
119
|
+
}
|
|
120
|
+
return () => {
|
|
121
|
+
abortRef.current?.abort();
|
|
122
|
+
};
|
|
123
|
+
}, [enabled, initialThreadId, refreshThreads, selectThread]);
|
|
124
|
+
|
|
125
|
+
const runStream = useThreadStream({
|
|
126
|
+
csrfToken,
|
|
127
|
+
abortRef,
|
|
128
|
+
setStreaming,
|
|
129
|
+
setError,
|
|
130
|
+
setMessages,
|
|
131
|
+
setPendingApprovals,
|
|
132
|
+
refreshThreads,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const sendMessage = useCallback(
|
|
136
|
+
async (text: string, requestMetadata?: ChatRequestMetadata) => {
|
|
137
|
+
const trimmed = text.trim();
|
|
138
|
+
if (!trimmed || streaming) return;
|
|
139
|
+
selectionGenRef.current += 1;
|
|
140
|
+
setError(null);
|
|
141
|
+
|
|
142
|
+
let threadId = activeThreadRef.current;
|
|
143
|
+
if (!threadId) {
|
|
144
|
+
try {
|
|
145
|
+
const created = await createThread(agentId, deriveThreadTitle(trimmed), csrfToken);
|
|
146
|
+
threadId = created.id;
|
|
147
|
+
updateActiveThread(threadId);
|
|
148
|
+
setThreads((prev) => [created, ...prev]);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
setError(toParsedError(err, keys.chat.errors.send_failed));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const userMsgId = nextId('user');
|
|
156
|
+
const assistantMsgId = nextId('assistant');
|
|
157
|
+
setMessages((prev) => [
|
|
158
|
+
...prev,
|
|
159
|
+
{ id: userMsgId, role: 'user', content: trimmed },
|
|
160
|
+
{ id: assistantMsgId, role: 'assistant', content: '' },
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
await runStream(
|
|
164
|
+
threadId,
|
|
165
|
+
assistantMsgId,
|
|
166
|
+
{ content: trimmed, requestMetadata },
|
|
167
|
+
keys.chat.errors.send_failed,
|
|
168
|
+
);
|
|
169
|
+
},
|
|
170
|
+
[agentId, csrfToken, runStream, streaming, updateActiveThread],
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
const resumeApproval = useCallback(
|
|
174
|
+
async (
|
|
175
|
+
approval: PendingApprovalItem,
|
|
176
|
+
approved: boolean,
|
|
177
|
+
denialReason?: string,
|
|
178
|
+
requestMetadata?: ChatRequestMetadata,
|
|
179
|
+
) => {
|
|
180
|
+
const threadId = activeThreadRef.current;
|
|
181
|
+
if (!threadId || streaming) return;
|
|
182
|
+
|
|
183
|
+
const { remaining, ready } = stageApprovalDecision(
|
|
184
|
+
stagedDecisionsRef.current,
|
|
185
|
+
pendingApprovalsRef.current,
|
|
186
|
+
approval,
|
|
187
|
+
approved,
|
|
188
|
+
denialReason,
|
|
189
|
+
);
|
|
190
|
+
setPendingApprovals(remaining);
|
|
191
|
+
if (!ready) return;
|
|
192
|
+
|
|
193
|
+
const gen = ++selectionGenRef.current;
|
|
194
|
+
const assistantMsgId = nextId('assistant');
|
|
195
|
+
setMessages((prev) => [...prev, { id: assistantMsgId, role: 'assistant', content: '' }]);
|
|
196
|
+
|
|
197
|
+
const ok = await runStream(
|
|
198
|
+
threadId,
|
|
199
|
+
assistantMsgId,
|
|
200
|
+
{ resume: buildResumePayload(approval.runId, ready), requestMetadata },
|
|
201
|
+
keys.chat.errors.approval_failed,
|
|
202
|
+
);
|
|
203
|
+
if (!ok && selectionGenRef.current === gen && activeThreadRef.current === threadId) {
|
|
204
|
+
const restored = await reloadPendingApprovals(getThread, threadId, ready.batchItems);
|
|
205
|
+
if (selectionGenRef.current === gen && activeThreadRef.current === threadId) {
|
|
206
|
+
setPendingApprovals(restored);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
[runStream, streaming],
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
const cancelRun = useCallback(async () => {
|
|
214
|
+
abortRef.current?.abort();
|
|
215
|
+
const threadId = activeThreadRef.current;
|
|
216
|
+
if (!threadId) return;
|
|
217
|
+
try {
|
|
218
|
+
await cancelThread(threadId, csrfToken);
|
|
219
|
+
} catch (err) {
|
|
220
|
+
setError(toParsedError(err, keys.chat.errors.cancel_failed));
|
|
221
|
+
}
|
|
222
|
+
}, [csrfToken]);
|
|
223
|
+
|
|
224
|
+
const startNewThread = useCallback(() => {
|
|
225
|
+
selectionGenRef.current += 1;
|
|
226
|
+
stagedDecisionsRef.current = {};
|
|
227
|
+
abortRef.current?.abort();
|
|
228
|
+
setStreaming(false);
|
|
229
|
+
setMessages([]);
|
|
230
|
+
setPendingApprovals([]);
|
|
231
|
+
setError(null);
|
|
232
|
+
updateActiveThread(null);
|
|
233
|
+
}, [updateActiveThread]);
|
|
234
|
+
|
|
235
|
+
const removeThread = useCallback(
|
|
236
|
+
async (threadId: string) => {
|
|
237
|
+
try {
|
|
238
|
+
await deleteThread(threadId, csrfToken);
|
|
239
|
+
listGenRef.current += 1;
|
|
240
|
+
setThreads((prev) => prev.filter((t) => t.id !== threadId));
|
|
241
|
+
if (activeThreadRef.current === threadId) {
|
|
242
|
+
startNewThread();
|
|
243
|
+
}
|
|
244
|
+
} catch (err) {
|
|
245
|
+
setError(toParsedError(err, keys.chat.errors.delete_failed));
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
[csrfToken, startNewThread],
|
|
249
|
+
);
|
|
250
|
+
|
|
251
|
+
const renameThread = useCallback(
|
|
252
|
+
async (threadId: string, title: string) => {
|
|
253
|
+
const trimmed = title.trim();
|
|
254
|
+
if (!trimmed) return;
|
|
255
|
+
const gen = (renameGenRef.current.get(threadId) ?? 0) + 1;
|
|
256
|
+
renameGenRef.current.set(threadId, gen);
|
|
257
|
+
try {
|
|
258
|
+
const updated = await apiRenameThread(threadId, trimmed, csrfToken);
|
|
259
|
+
if (renameGenRef.current.get(threadId) !== gen) return;
|
|
260
|
+
listGenRef.current += 1;
|
|
261
|
+
setThreads((prev) => prev.map((t) => (t.id === threadId ? updated : t)));
|
|
262
|
+
} catch (err) {
|
|
263
|
+
if (renameGenRef.current.get(threadId) !== gen) return;
|
|
264
|
+
setError(toParsedError(err, keys.chat.errors.rename_failed));
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
[csrfToken],
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
const clearError = useCallback(() => setError(null), []);
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
threads,
|
|
274
|
+
threadsLoading,
|
|
275
|
+
activeThreadId,
|
|
276
|
+
messages,
|
|
277
|
+
pendingApprovals,
|
|
278
|
+
streaming,
|
|
279
|
+
error,
|
|
280
|
+
sendMessage,
|
|
281
|
+
resumeApproval,
|
|
282
|
+
cancelRun,
|
|
283
|
+
selectThread,
|
|
284
|
+
startNewThread,
|
|
285
|
+
removeThread,
|
|
286
|
+
renameThread,
|
|
287
|
+
clearError,
|
|
288
|
+
};
|
|
289
|
+
}
|