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
sm_chat/module.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Chat module — generic cross-module workspace assistant built on ``simple_module_ai``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
import importlib.resources
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, FastAPI
|
|
10
|
+
from simple_module_core.access.permissions import PermissionRegistry
|
|
11
|
+
from simple_module_core.modules.module import ModuleBase, ModuleMeta
|
|
12
|
+
from simple_module_core.web.menu import MenuItem, MenuRegistry, MenuSection
|
|
13
|
+
|
|
14
|
+
from sm_chat.core import constants
|
|
15
|
+
|
|
16
|
+
_VERSION = importlib.metadata.version("simple_module_chat")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ChatModule(ModuleBase):
|
|
20
|
+
meta = ModuleMeta(
|
|
21
|
+
name=constants.MODULE_NAME,
|
|
22
|
+
route_prefix=constants.ROUTE_PREFIX_API,
|
|
23
|
+
view_prefix=constants.VIEW_PREFIX,
|
|
24
|
+
depends_on=[constants._MODULE_AI, constants._MODULE_SETTINGS],
|
|
25
|
+
version=_VERSION,
|
|
26
|
+
i18n_audience="admin",
|
|
27
|
+
requires_framework=">=1.0,<2.0",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
def register_settings(self, app: FastAPI) -> None:
|
|
31
|
+
from simple_module_core.settings.module_settings import register_module_settings
|
|
32
|
+
|
|
33
|
+
from sm_chat.core.settings import ChatServices, ChatSettings, install
|
|
34
|
+
|
|
35
|
+
register_module_settings(
|
|
36
|
+
app,
|
|
37
|
+
constants.PACKAGE,
|
|
38
|
+
ChatSettings,
|
|
39
|
+
lambda s: install(ChatServices(settings=s)),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
def register_permissions(self, registry: PermissionRegistry) -> None:
|
|
43
|
+
registry.add_group(
|
|
44
|
+
constants.PERM_GROUP,
|
|
45
|
+
list(constants.PERMISSIONS),
|
|
46
|
+
label_key=constants.PERM_GROUP_KEY,
|
|
47
|
+
)
|
|
48
|
+
for role in constants.DEFAULT_ROLES:
|
|
49
|
+
registry.map_role(role, list(constants.PERMISSIONS))
|
|
50
|
+
|
|
51
|
+
def register_menu_items(self, registry: MenuRegistry) -> None:
|
|
52
|
+
registry.add(
|
|
53
|
+
MenuItem(
|
|
54
|
+
label=constants.MENU_LABEL,
|
|
55
|
+
label_key=constants.MENU_LABEL_KEY,
|
|
56
|
+
url=constants.MENU_URL,
|
|
57
|
+
icon=constants.MENU_ICON,
|
|
58
|
+
order=constants.MENU_ORDER,
|
|
59
|
+
section=MenuSection.SIDEBAR,
|
|
60
|
+
permissions=[constants.PERM_USE],
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def register_routes(self, api_router: APIRouter, view_router: APIRouter) -> None:
|
|
65
|
+
from sm_chat.web.endpoints.api import router as api
|
|
66
|
+
from sm_chat.web.endpoints.views import router as views
|
|
67
|
+
|
|
68
|
+
api_router.include_router(api)
|
|
69
|
+
view_router.include_router(views)
|
|
70
|
+
|
|
71
|
+
def locale_dirs(self) -> dict[str, Path]:
|
|
72
|
+
base = Path(str(importlib.resources.files(__package__) / "locales"))
|
|
73
|
+
return {constants.LOCALE_NAMESPACE: base}
|
|
74
|
+
|
|
75
|
+
async def on_startup(self, app: FastAPI) -> None:
|
|
76
|
+
from simple_module_hosting.frontend.shared_props import register_inertia_shared_provider
|
|
77
|
+
from sm_ai.contracts import register_agent
|
|
78
|
+
|
|
79
|
+
from sm_chat.agent.definition import build_chat_agent_definition
|
|
80
|
+
from sm_chat.core import tenancy
|
|
81
|
+
from sm_chat.web.shared_props import chat_shared_props
|
|
82
|
+
|
|
83
|
+
tenancy.configure(app)
|
|
84
|
+
register_agent(app, build_chat_agent_definition(app), overwrite=True)
|
|
85
|
+
register_inertia_shared_provider(app, chat_shared_props)
|
sm_chat/package.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@simple-module-py/chat",
|
|
3
|
+
"version": "0.0.20",
|
|
4
|
+
"private": true,
|
|
5
|
+
"main": "./index.ts",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./index.ts"
|
|
8
|
+
},
|
|
9
|
+
"description": "Frontend assets for the Chat module",
|
|
10
|
+
"peerDependencies": {
|
|
11
|
+
"@inertiajs/react": "^3.9.1",
|
|
12
|
+
"@simple-module-py/ai": ">=0.0.18",
|
|
13
|
+
"@simple-module-py/ui": ">=0.0.38",
|
|
14
|
+
"react": "^19.3.1",
|
|
15
|
+
"react-dom": "^19.3.1"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@simple-module-py/tsconfig": "*"
|
|
19
|
+
}
|
|
20
|
+
}
|
sm_chat/pages/Index.tsx
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Dedicated `/chat/` console workspace page. */
|
|
2
|
+
|
|
3
|
+
import { Head, usePage } from '@inertiajs/react';
|
|
4
|
+
import { AuthenticatedLayout } from '@simple-module-py/ui/layouts/AuthenticatedLayout';
|
|
5
|
+
import { useCallback, useMemo } from 'react';
|
|
6
|
+
|
|
7
|
+
import { ChatPanel } from '../ui/components/ChatPanel';
|
|
8
|
+
import { ThreadSidebar } from '../ui/components/ThreadSidebar';
|
|
9
|
+
import { useChatContext } from '../ui/hooks/useChatContext';
|
|
10
|
+
import { useChatThread } from '../ui/hooks/useChatThread';
|
|
11
|
+
import { keys, useT } from '../ui/utils/i18n';
|
|
12
|
+
import type { ChatRequestMetadata } from '../ui/utils/types';
|
|
13
|
+
|
|
14
|
+
function readInitialThreadId(): string | null {
|
|
15
|
+
if (typeof window === 'undefined') return null;
|
|
16
|
+
const params = new URLSearchParams(window.location.search);
|
|
17
|
+
const value = params.get('thread')?.trim();
|
|
18
|
+
return value || null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function syncThreadQueryParam(threadId: string | null): void {
|
|
22
|
+
if (typeof window === 'undefined') return;
|
|
23
|
+
const url = new URL(window.location.href);
|
|
24
|
+
if (threadId) {
|
|
25
|
+
url.searchParams.set('thread', threadId);
|
|
26
|
+
} else {
|
|
27
|
+
url.searchParams.delete('thread');
|
|
28
|
+
}
|
|
29
|
+
window.history.replaceState(window.history.state, '', url.toString());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ChatIndex() {
|
|
33
|
+
const { t } = useT();
|
|
34
|
+
const page = usePage();
|
|
35
|
+
const props = page.props as { i18n?: { locale?: string }; csrfToken?: string };
|
|
36
|
+
|
|
37
|
+
const initialThreadId = useMemo(readInitialThreadId, []);
|
|
38
|
+
const handleThreadChange = useCallback((id: string | null) => {
|
|
39
|
+
syncThreadQueryParam(id);
|
|
40
|
+
}, []);
|
|
41
|
+
|
|
42
|
+
const { context, error: contextError } = useChatContext(true);
|
|
43
|
+
const thread = useChatThread({
|
|
44
|
+
agentId: context?.agent_id,
|
|
45
|
+
enabled: true,
|
|
46
|
+
csrfToken: props.csrfToken,
|
|
47
|
+
initialThreadId,
|
|
48
|
+
onThreadChange: handleThreadChange,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const requestMetadata = useMemo<ChatRequestMetadata>(
|
|
52
|
+
() => ({
|
|
53
|
+
current_path: page.url,
|
|
54
|
+
current_component: page.component,
|
|
55
|
+
locale: props.i18n?.locale,
|
|
56
|
+
}),
|
|
57
|
+
[page.url, page.component, props.i18n?.locale],
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
const activeThreadTitle = useMemo(
|
|
61
|
+
() => thread.threads.find((item) => item.id === thread.activeThreadId)?.title,
|
|
62
|
+
[thread.threads, thread.activeThreadId],
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
return (
|
|
66
|
+
<>
|
|
67
|
+
<Head title={t(keys.chat.page.head_title)} />
|
|
68
|
+
<div className="flex h-[calc(100vh-4rem)] flex-col">
|
|
69
|
+
<div className="border-b px-6 py-3">
|
|
70
|
+
<h1 className="text-lg font-semibold tracking-tight">{t(keys.chat.page.title)}</h1>
|
|
71
|
+
<p className="text-xs text-muted-foreground">{t(keys.chat.page.subtitle)}</p>
|
|
72
|
+
</div>
|
|
73
|
+
|
|
74
|
+
<div className="flex min-h-0 flex-1 overflow-hidden">
|
|
75
|
+
<div className="hidden md:flex">
|
|
76
|
+
<ThreadSidebar
|
|
77
|
+
threads={thread.threads}
|
|
78
|
+
loading={thread.threadsLoading}
|
|
79
|
+
activeThreadId={thread.activeThreadId}
|
|
80
|
+
onSelect={(id) => void thread.selectThread(id)}
|
|
81
|
+
onNewChat={thread.startNewThread}
|
|
82
|
+
onDelete={(id) => void thread.removeThread(id)}
|
|
83
|
+
onRename={(id, title) => void thread.renameThread(id, title)}
|
|
84
|
+
/>
|
|
85
|
+
</div>
|
|
86
|
+
|
|
87
|
+
<ChatPanel
|
|
88
|
+
context={context}
|
|
89
|
+
contextError={contextError}
|
|
90
|
+
messages={thread.messages}
|
|
91
|
+
pendingApprovals={thread.pendingApprovals}
|
|
92
|
+
streaming={thread.streaming}
|
|
93
|
+
error={thread.error}
|
|
94
|
+
threadTitle={activeThreadTitle}
|
|
95
|
+
requestMetadata={requestMetadata}
|
|
96
|
+
onSendMessage={thread.sendMessage}
|
|
97
|
+
onDecideApproval={thread.resumeApproval}
|
|
98
|
+
onCancel={thread.cancelRun}
|
|
99
|
+
onClearError={thread.clearError}
|
|
100
|
+
/>
|
|
101
|
+
</div>
|
|
102
|
+
</div>
|
|
103
|
+
</>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
ChatIndex.layout = [AuthenticatedLayout];
|
|
108
|
+
export default ChatIndex;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** Interactive HITL confirmation card for draft-creating tool actions. */
|
|
2
|
+
|
|
3
|
+
import { Badge } from '@simple-module-py/ui/components/ui/badge';
|
|
4
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
5
|
+
import {
|
|
6
|
+
Card,
|
|
7
|
+
CardContent,
|
|
8
|
+
CardDescription,
|
|
9
|
+
CardFooter,
|
|
10
|
+
CardHeader,
|
|
11
|
+
CardTitle,
|
|
12
|
+
} from '@simple-module-py/ui/components/ui/card';
|
|
13
|
+
import { Input } from '@simple-module-py/ui/components/ui/input';
|
|
14
|
+
import { Check, ShieldAlert, X } from 'lucide-react';
|
|
15
|
+
import { useState } from 'react';
|
|
16
|
+
|
|
17
|
+
import { keys, useT } from '../utils/i18n';
|
|
18
|
+
import type { PendingApprovalItem } from '../utils/types';
|
|
19
|
+
import { formatToolIdentifier } from './ToolCallPill';
|
|
20
|
+
|
|
21
|
+
export type ApprovalCardProps = {
|
|
22
|
+
approval: PendingApprovalItem;
|
|
23
|
+
disabled?: boolean;
|
|
24
|
+
onDecide: (approval: PendingApprovalItem, approved: boolean, denialReason?: string) => void;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function formatArgValue(value: unknown): string {
|
|
28
|
+
if (value === null || value === undefined) return '—';
|
|
29
|
+
if (typeof value === 'string') return value;
|
|
30
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
31
|
+
try {
|
|
32
|
+
return JSON.stringify(value);
|
|
33
|
+
} catch {
|
|
34
|
+
return String(value);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function formatFieldLabel(key: string): string {
|
|
39
|
+
return key
|
|
40
|
+
.replace(/[_-]+/g, ' ')
|
|
41
|
+
.trim()
|
|
42
|
+
.replace(/^\w/, (ch) => ch.toUpperCase());
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function ApprovalCard({ approval, disabled = false, onDecide }: ApprovalCardProps) {
|
|
46
|
+
const { t } = useT();
|
|
47
|
+
const [denialReason, setDenialReason] = useState('');
|
|
48
|
+
const [submitting, setSubmitting] = useState<'approve' | 'deny' | null>(null);
|
|
49
|
+
|
|
50
|
+
const { provider, action } = formatToolIdentifier(approval.toolName);
|
|
51
|
+
const entries = Object.entries(approval.args ?? {});
|
|
52
|
+
const isBusy = disabled || submitting !== null;
|
|
53
|
+
|
|
54
|
+
const handleDecision = (approved: boolean) => {
|
|
55
|
+
setSubmitting(approved ? 'approve' : 'deny');
|
|
56
|
+
onDecide(approval, approved, approved ? undefined : denialReason.trim() || undefined);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
<Card
|
|
61
|
+
className="border-amber-500/40 bg-amber-500/5"
|
|
62
|
+
data-testid="chat-approval-card"
|
|
63
|
+
data-tool-call-id={approval.toolCallId}
|
|
64
|
+
>
|
|
65
|
+
<CardHeader className="pb-3">
|
|
66
|
+
<div className="flex items-center gap-2">
|
|
67
|
+
<ShieldAlert className="size-4 shrink-0 text-amber-600" aria-hidden="true" />
|
|
68
|
+
<CardTitle className="text-sm">{t(keys.chat.approval.title)}</CardTitle>
|
|
69
|
+
</div>
|
|
70
|
+
<CardDescription className="text-xs">{t(keys.chat.approval.subtitle)}</CardDescription>
|
|
71
|
+
</CardHeader>
|
|
72
|
+
<CardContent className="space-y-3 text-xs">
|
|
73
|
+
<div className="flex flex-wrap items-center gap-2">
|
|
74
|
+
{provider && (
|
|
75
|
+
<span className="inline-flex items-center gap-1.5">
|
|
76
|
+
<span className="text-muted-foreground">{t(keys.chat.approval.provider_label)}:</span>
|
|
77
|
+
<Badge variant="secondary" className="capitalize">
|
|
78
|
+
{provider}
|
|
79
|
+
</Badge>
|
|
80
|
+
</span>
|
|
81
|
+
)}
|
|
82
|
+
<span className="inline-flex items-center gap-1.5">
|
|
83
|
+
<span className="text-muted-foreground">{t(keys.chat.approval.action_label)}:</span>
|
|
84
|
+
<span className="font-medium text-foreground">{action}</span>
|
|
85
|
+
</span>
|
|
86
|
+
</div>
|
|
87
|
+
|
|
88
|
+
{entries.length > 0 && (
|
|
89
|
+
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 rounded-md border bg-background/80 p-2.5">
|
|
90
|
+
{entries.map(([key, value]) => (
|
|
91
|
+
<div key={key} className="contents">
|
|
92
|
+
<dt className="font-medium text-muted-foreground">{formatFieldLabel(key)}</dt>
|
|
93
|
+
<dd className="min-w-0 break-words text-foreground">{formatArgValue(value)}</dd>
|
|
94
|
+
</div>
|
|
95
|
+
))}
|
|
96
|
+
</dl>
|
|
97
|
+
)}
|
|
98
|
+
|
|
99
|
+
<Input
|
|
100
|
+
type="text"
|
|
101
|
+
value={denialReason}
|
|
102
|
+
disabled={isBusy}
|
|
103
|
+
onChange={(event) => setDenialReason(event.target.value)}
|
|
104
|
+
placeholder={t(keys.chat.approval.denial_reason_placeholder)}
|
|
105
|
+
aria-label={t(keys.chat.approval.denial_reason_placeholder)}
|
|
106
|
+
className="h-8 text-xs"
|
|
107
|
+
/>
|
|
108
|
+
</CardContent>
|
|
109
|
+
<CardFooter className="flex justify-end gap-2 pt-0">
|
|
110
|
+
<Button
|
|
111
|
+
type="button"
|
|
112
|
+
size="sm"
|
|
113
|
+
variant="outline"
|
|
114
|
+
disabled={isBusy}
|
|
115
|
+
onClick={() => handleDecision(false)}
|
|
116
|
+
>
|
|
117
|
+
<X className="mr-1 size-3.5" aria-hidden="true" />
|
|
118
|
+
{submitting === 'deny' ? t(keys.chat.approval.denying) : t(keys.chat.approval.deny)}
|
|
119
|
+
</Button>
|
|
120
|
+
<Button type="button" size="sm" disabled={isBusy} onClick={() => handleDecision(true)}>
|
|
121
|
+
<Check className="mr-1 size-3.5" aria-hidden="true" />
|
|
122
|
+
{submitting === 'approve'
|
|
123
|
+
? t(keys.chat.approval.approving)
|
|
124
|
+
: t(keys.chat.approval.approve)}
|
|
125
|
+
</Button>
|
|
126
|
+
</CardFooter>
|
|
127
|
+
</Card>
|
|
128
|
+
);
|
|
129
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent floating slide-over assistant drawer mounted alongside Inertia `<App />`.
|
|
3
|
+
*
|
|
4
|
+
* Stays mounted across Inertia page navigations, tracks `current_path` and
|
|
5
|
+
* `current_component`, hides on public pages and on `/chat`, and supports
|
|
6
|
+
* `Ctrl/Cmd + Shift + K`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { router } from '@inertiajs/react';
|
|
10
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
11
|
+
import { ExternalLink, MessageSquare, Plus, X } from 'lucide-react';
|
|
12
|
+
import { useEffect, useMemo, useState } from 'react';
|
|
13
|
+
|
|
14
|
+
import { useChatContext } from '../hooks/useChatContext';
|
|
15
|
+
import { useChatThread } from '../hooks/useChatThread';
|
|
16
|
+
import { keys, useT } from '../utils/i18n';
|
|
17
|
+
import type { ChatRequestMetadata, ChatSharedProp } from '../utils/types';
|
|
18
|
+
import { ChatPanel } from './ChatPanel';
|
|
19
|
+
|
|
20
|
+
export type InertiaPageLike = {
|
|
21
|
+
url: string;
|
|
22
|
+
component?: string;
|
|
23
|
+
props?: Record<string, unknown>;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type ChatDrawerHostProps = {
|
|
27
|
+
initialPage: InertiaPageLike;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type PageState = {
|
|
31
|
+
url: string;
|
|
32
|
+
component?: string;
|
|
33
|
+
chat?: ChatSharedProp;
|
|
34
|
+
locale?: string;
|
|
35
|
+
csrfToken?: string;
|
|
36
|
+
principalKey: string;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function extractPrincipalKey(props: Record<string, unknown>, enabled: boolean): string {
|
|
40
|
+
if (!enabled) return 'anon';
|
|
41
|
+
const auth = props.auth as { user?: { id?: unknown; email?: unknown } } | undefined;
|
|
42
|
+
const user = auth?.user;
|
|
43
|
+
const userId = String(user?.id ?? user?.email ?? 'auth');
|
|
44
|
+
const tenant = props.tenant as
|
|
45
|
+
| { id?: unknown; slug?: unknown; active?: { id?: unknown; slug?: unknown } }
|
|
46
|
+
| undefined;
|
|
47
|
+
const tenantId = String(
|
|
48
|
+
tenant?.active?.id ??
|
|
49
|
+
tenant?.active?.slug ??
|
|
50
|
+
tenant?.id ??
|
|
51
|
+
tenant?.slug ??
|
|
52
|
+
props.tenant_id ??
|
|
53
|
+
'default',
|
|
54
|
+
);
|
|
55
|
+
return `${userId}:${tenantId}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function extractPageState(page: InertiaPageLike): PageState {
|
|
59
|
+
const props = page.props ?? {};
|
|
60
|
+
const rawChat = props.chat as Partial<ChatSharedProp> | undefined;
|
|
61
|
+
const chat =
|
|
62
|
+
rawChat && typeof rawChat.enabled === 'boolean'
|
|
63
|
+
? { enabled: rawChat.enabled, drawer_enabled: Boolean(rawChat.drawer_enabled) }
|
|
64
|
+
: undefined;
|
|
65
|
+
const i18n = props.i18n as { locale?: string } | undefined;
|
|
66
|
+
const csrfToken = typeof props.csrfToken === 'string' ? props.csrfToken : undefined;
|
|
67
|
+
return {
|
|
68
|
+
url: page.url,
|
|
69
|
+
component: page.component,
|
|
70
|
+
chat,
|
|
71
|
+
locale: i18n?.locale,
|
|
72
|
+
csrfToken,
|
|
73
|
+
principalKey: extractPrincipalKey(props, Boolean(chat?.enabled)),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isChatRoute(url: string): boolean {
|
|
78
|
+
const path = url.split('?')[0]?.split('#')[0] ?? '';
|
|
79
|
+
return path === '/chat' || path.startsWith('/chat/');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function ChatDrawerHost({ initialPage }: ChatDrawerHostProps) {
|
|
83
|
+
const [page, setPage] = useState<PageState>(() => extractPageState(initialPage));
|
|
84
|
+
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
const onPage = (event: unknown) => {
|
|
87
|
+
const next = (event as { detail?: { page?: InertiaPageLike } }).detail?.page;
|
|
88
|
+
if (next) setPage(extractPageState(next));
|
|
89
|
+
};
|
|
90
|
+
const offSuccess = router.on('success', onPage);
|
|
91
|
+
const offNavigate = router.on('navigate', onPage);
|
|
92
|
+
return () => {
|
|
93
|
+
if (typeof offSuccess === 'function') offSuccess();
|
|
94
|
+
if (typeof offNavigate === 'function') offNavigate();
|
|
95
|
+
};
|
|
96
|
+
}, []);
|
|
97
|
+
|
|
98
|
+
if (!page.chat?.enabled || !page.chat?.drawer_enabled) return null;
|
|
99
|
+
return <ChatDrawerSession key={page.principalKey} page={page} />;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function ChatDrawerSession({ page }: { page: PageState }) {
|
|
103
|
+
const { t } = useT();
|
|
104
|
+
const [open, setOpen] = useState(false);
|
|
105
|
+
const [hasOpened, setHasOpened] = useState(false);
|
|
106
|
+
|
|
107
|
+
const canShow = !isChatRoute(page.url);
|
|
108
|
+
|
|
109
|
+
useEffect(() => {
|
|
110
|
+
if (!canShow) return;
|
|
111
|
+
const onKeyDown = (event: KeyboardEvent) => {
|
|
112
|
+
if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === 'k') {
|
|
113
|
+
event.preventDefault();
|
|
114
|
+
setOpen((prev) => {
|
|
115
|
+
const next = !prev;
|
|
116
|
+
if (next) setHasOpened(true);
|
|
117
|
+
return next;
|
|
118
|
+
});
|
|
119
|
+
} else if (event.key === 'Escape' && open) {
|
|
120
|
+
event.preventDefault();
|
|
121
|
+
setOpen(false);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
window.addEventListener('keydown', onKeyDown);
|
|
125
|
+
return () => window.removeEventListener('keydown', onKeyDown);
|
|
126
|
+
}, [canShow, open]);
|
|
127
|
+
|
|
128
|
+
const active = canShow && hasOpened;
|
|
129
|
+
const { context, error: contextError } = useChatContext(active);
|
|
130
|
+
const thread = useChatThread({
|
|
131
|
+
agentId: context?.agent_id,
|
|
132
|
+
enabled: active,
|
|
133
|
+
csrfToken: page.csrfToken,
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const requestMetadata = useMemo<ChatRequestMetadata>(
|
|
137
|
+
() => ({
|
|
138
|
+
current_path: page.url,
|
|
139
|
+
current_component: page.component,
|
|
140
|
+
locale: page.locale,
|
|
141
|
+
}),
|
|
142
|
+
[page.url, page.component, page.locale],
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
if (!canShow) return null;
|
|
146
|
+
|
|
147
|
+
const fullPageUrl = thread.activeThreadId
|
|
148
|
+
? `/chat/?thread=${encodeURIComponent(thread.activeThreadId)}`
|
|
149
|
+
: '/chat/';
|
|
150
|
+
|
|
151
|
+
const handleOpenFullPage = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
|
152
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
153
|
+
event.preventDefault();
|
|
154
|
+
setOpen(false);
|
|
155
|
+
router.visit(fullPageUrl);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
return (
|
|
159
|
+
<>
|
|
160
|
+
{!open && (
|
|
161
|
+
<Button
|
|
162
|
+
type="button"
|
|
163
|
+
size="lg"
|
|
164
|
+
onClick={() => {
|
|
165
|
+
setHasOpened(true);
|
|
166
|
+
setOpen(true);
|
|
167
|
+
}}
|
|
168
|
+
aria-label={t(keys.chat.drawer.open)}
|
|
169
|
+
title={t(keys.chat.drawer.shortcut_hint, { shortcut: 'Ctrl+Shift+K' })}
|
|
170
|
+
className="fixed right-5 bottom-5 z-40 rounded-full shadow-lg"
|
|
171
|
+
data-testid="chat-drawer-trigger"
|
|
172
|
+
>
|
|
173
|
+
<MessageSquare className="mr-2 size-4" aria-hidden="true" />
|
|
174
|
+
{t(keys.chat.drawer.title)}
|
|
175
|
+
</Button>
|
|
176
|
+
)}
|
|
177
|
+
|
|
178
|
+
{open && (
|
|
179
|
+
<div className="fixed inset-0 z-50 flex justify-end">
|
|
180
|
+
<div
|
|
181
|
+
className="fixed inset-0 bg-black/30 backdrop-blur-[1px]"
|
|
182
|
+
aria-hidden="true"
|
|
183
|
+
onClick={() => setOpen(false)}
|
|
184
|
+
/>
|
|
185
|
+
<div
|
|
186
|
+
role="dialog"
|
|
187
|
+
aria-modal="true"
|
|
188
|
+
aria-label={t(keys.chat.drawer.title)}
|
|
189
|
+
className="relative z-10 flex h-full w-full max-w-md flex-col border-l bg-background shadow-2xl"
|
|
190
|
+
data-testid="chat-drawer"
|
|
191
|
+
>
|
|
192
|
+
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
|
193
|
+
<div className="flex items-center gap-2">
|
|
194
|
+
<MessageSquare className="size-4 text-primary" aria-hidden="true" />
|
|
195
|
+
<h2 className="text-sm font-semibold">{t(keys.chat.drawer.title)}</h2>
|
|
196
|
+
</div>
|
|
197
|
+
<div className="flex items-center gap-1">
|
|
198
|
+
<Button
|
|
199
|
+
type="button"
|
|
200
|
+
variant="ghost"
|
|
201
|
+
size="xs"
|
|
202
|
+
onClick={thread.startNewThread}
|
|
203
|
+
title={t(keys.chat.sidebar.new_chat)}
|
|
204
|
+
>
|
|
205
|
+
<Plus className="mr-1 size-3.5" aria-hidden="true" />
|
|
206
|
+
{t(keys.chat.sidebar.new_chat)}
|
|
207
|
+
</Button>
|
|
208
|
+
<a
|
|
209
|
+
href={fullPageUrl}
|
|
210
|
+
onClick={handleOpenFullPage}
|
|
211
|
+
className="inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
|
212
|
+
data-testid="chat-drawer-fullpage-link"
|
|
213
|
+
>
|
|
214
|
+
<ExternalLink className="size-3.5" aria-hidden="true" />
|
|
215
|
+
<span>{t(keys.chat.drawer.open_full_page)}</span>
|
|
216
|
+
</a>
|
|
217
|
+
<Button
|
|
218
|
+
type="button"
|
|
219
|
+
variant="ghost"
|
|
220
|
+
size="icon-xs"
|
|
221
|
+
aria-label={t(keys.chat.drawer.close)}
|
|
222
|
+
onClick={() => setOpen(false)}
|
|
223
|
+
>
|
|
224
|
+
<X className="size-4" aria-hidden="true" />
|
|
225
|
+
</Button>
|
|
226
|
+
</div>
|
|
227
|
+
</header>
|
|
228
|
+
|
|
229
|
+
<ChatPanel
|
|
230
|
+
compact
|
|
231
|
+
context={context}
|
|
232
|
+
contextError={contextError}
|
|
233
|
+
messages={thread.messages}
|
|
234
|
+
pendingApprovals={thread.pendingApprovals}
|
|
235
|
+
streaming={thread.streaming}
|
|
236
|
+
error={thread.error}
|
|
237
|
+
requestMetadata={requestMetadata}
|
|
238
|
+
onSendMessage={thread.sendMessage}
|
|
239
|
+
onDecideApproval={thread.resumeApproval}
|
|
240
|
+
onCancel={thread.cancelRun}
|
|
241
|
+
onClearError={thread.clearError}
|
|
242
|
+
/>
|
|
243
|
+
</div>
|
|
244
|
+
</div>
|
|
245
|
+
)}
|
|
246
|
+
</>
|
|
247
|
+
);
|
|
248
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Header actions to copy or download the current chat conversation as Markdown. */
|
|
2
|
+
|
|
3
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
4
|
+
import { Check, Copy, Download } from 'lucide-react';
|
|
5
|
+
import { useEffect, useRef, useState } from 'react';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
buildMarkdownFilename,
|
|
9
|
+
downloadMarkdown,
|
|
10
|
+
formatConversationMarkdown,
|
|
11
|
+
} from '../utils/exportMarkdown';
|
|
12
|
+
import { keys, useT } from '../utils/i18n';
|
|
13
|
+
import type { ChatMessage } from '../utils/types';
|
|
14
|
+
|
|
15
|
+
export type ChatExportActionsProps = {
|
|
16
|
+
messages: ChatMessage[];
|
|
17
|
+
threadTitle?: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function ChatExportActions({ messages, threadTitle }: ChatExportActionsProps) {
|
|
21
|
+
const { t } = useT();
|
|
22
|
+
const [copied, setCopied] = useState(false);
|
|
23
|
+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
24
|
+
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
return () => {
|
|
27
|
+
if (timerRef.current !== null) clearTimeout(timerRef.current);
|
|
28
|
+
};
|
|
29
|
+
}, []);
|
|
30
|
+
|
|
31
|
+
if (messages.length === 0) return null;
|
|
32
|
+
|
|
33
|
+
const buildMarkdown = () =>
|
|
34
|
+
formatConversationMarkdown(messages, {
|
|
35
|
+
title: threadTitle,
|
|
36
|
+
userLabel: t(keys.chat.messages.you),
|
|
37
|
+
assistantLabel: t(keys.chat.messages.assistant),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const handleCopy = async () => {
|
|
41
|
+
const md = buildMarkdown();
|
|
42
|
+
if (!md || !navigator.clipboard) return;
|
|
43
|
+
try {
|
|
44
|
+
await navigator.clipboard.writeText(md);
|
|
45
|
+
setCopied(true);
|
|
46
|
+
if (timerRef.current !== null) clearTimeout(timerRef.current);
|
|
47
|
+
timerRef.current = setTimeout(() => setCopied(false), 2000);
|
|
48
|
+
} catch {
|
|
49
|
+
// Clipboard write unavailable or denied
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const handleDownload = () => {
|
|
54
|
+
const md = buildMarkdown();
|
|
55
|
+
if (!md) return;
|
|
56
|
+
downloadMarkdown(md, buildMarkdownFilename(threadTitle));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
<div className="flex items-center justify-end gap-1.5 border-b px-4 py-1.5">
|
|
61
|
+
<Button
|
|
62
|
+
type="button"
|
|
63
|
+
variant="ghost"
|
|
64
|
+
size="xs"
|
|
65
|
+
onClick={() => void handleCopy()}
|
|
66
|
+
data-testid="chat-copy-markdown"
|
|
67
|
+
>
|
|
68
|
+
{copied ? (
|
|
69
|
+
<Check className="mr-1 size-3.5" aria-hidden="true" />
|
|
70
|
+
) : (
|
|
71
|
+
<Copy className="mr-1 size-3.5" aria-hidden="true" />
|
|
72
|
+
)}
|
|
73
|
+
{copied ? t(keys.chat.messages.copied_markdown) : t(keys.chat.messages.copy_markdown)}
|
|
74
|
+
</Button>
|
|
75
|
+
<Button
|
|
76
|
+
type="button"
|
|
77
|
+
variant="ghost"
|
|
78
|
+
size="xs"
|
|
79
|
+
onClick={handleDownload}
|
|
80
|
+
data-testid="chat-download-markdown"
|
|
81
|
+
>
|
|
82
|
+
<Download className="mr-1 size-3.5" aria-hidden="true" />
|
|
83
|
+
{t(keys.chat.messages.download_markdown)}
|
|
84
|
+
</Button>
|
|
85
|
+
</div>
|
|
86
|
+
);
|
|
87
|
+
}
|