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/ui/utils/sse.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/** TanStack AI / AG-UI Server-Sent Events parser and streaming client. */
|
|
2
|
+
|
|
3
|
+
import { buildCsrfHeaders, parseResponseError } from './api';
|
|
4
|
+
import type { ChatRequestMetadata, PendingApprovalItem } from './types';
|
|
5
|
+
|
|
6
|
+
export type SseChunk =
|
|
7
|
+
| { type: 'RUN_STARTED'; threadId: string; runId: string }
|
|
8
|
+
| { type: 'TEXT_MESSAGE_START'; messageId: string; role?: string }
|
|
9
|
+
| { type: 'TEXT_MESSAGE_CONTENT'; messageId: string; delta: string }
|
|
10
|
+
| { type: 'TEXT_MESSAGE_END'; messageId: string }
|
|
11
|
+
| {
|
|
12
|
+
type: 'TOOL_CALL_START';
|
|
13
|
+
toolCallId: string;
|
|
14
|
+
toolCallName: string;
|
|
15
|
+
parentMessageId?: string;
|
|
16
|
+
}
|
|
17
|
+
| { type: 'TOOL_CALL_ARGS'; toolCallId: string; delta: string }
|
|
18
|
+
| { type: 'TOOL_CALL_END'; toolCallId: string }
|
|
19
|
+
| { type: 'TOOL_CALL_RESULT'; messageId?: string; toolCallId: string; content: string }
|
|
20
|
+
| { type: 'CUSTOM'; name: string; value?: unknown }
|
|
21
|
+
| { type: 'RUN_FINISHED'; threadId?: string; runId?: string; finishReason?: string }
|
|
22
|
+
| { type: 'RUN_ERROR'; code?: string; message: string };
|
|
23
|
+
|
|
24
|
+
export type ResumeTurnPayload = {
|
|
25
|
+
runId: string;
|
|
26
|
+
decisions: Record<string, boolean>;
|
|
27
|
+
denialReasons?: Record<string, string>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export type StreamTurnRequest =
|
|
31
|
+
| {
|
|
32
|
+
content: string;
|
|
33
|
+
requestMetadata?: ChatRequestMetadata;
|
|
34
|
+
resume?: undefined;
|
|
35
|
+
}
|
|
36
|
+
| {
|
|
37
|
+
content?: undefined;
|
|
38
|
+
requestMetadata?: ChatRequestMetadata;
|
|
39
|
+
resume: ResumeTurnPayload;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type StreamTurnOptions = {
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
csrfToken?: string;
|
|
45
|
+
onChunk: (chunk: SseChunk) => void;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** Extract a typed `PendingApprovalItem` from a `CUSTOM` `tool-approval` event. */
|
|
49
|
+
export function parseApprovalEvent(chunk: SseChunk): PendingApprovalItem | null {
|
|
50
|
+
if (chunk.type !== 'CUSTOM' || chunk.name !== 'tool-approval') return null;
|
|
51
|
+
const val = chunk.value;
|
|
52
|
+
if (!val || typeof val !== 'object') return null;
|
|
53
|
+
const rec = val as Record<string, unknown>;
|
|
54
|
+
const toolCallId = typeof rec.toolCallId === 'string' ? rec.toolCallId : '';
|
|
55
|
+
const toolName = typeof rec.toolName === 'string' ? rec.toolName : '';
|
|
56
|
+
const runId = typeof rec.runId === 'string' ? rec.runId : '';
|
|
57
|
+
if (!toolCallId || !toolName || !runId) return null;
|
|
58
|
+
const interruptId =
|
|
59
|
+
typeof rec.interruptId === 'string' && rec.interruptId
|
|
60
|
+
? rec.interruptId
|
|
61
|
+
: `${runId}:${toolCallId}`;
|
|
62
|
+
const args =
|
|
63
|
+
rec.args && typeof rec.args === 'object' && !Array.isArray(rec.args)
|
|
64
|
+
? (rec.args as Record<string, unknown>)
|
|
65
|
+
: {};
|
|
66
|
+
const metadata =
|
|
67
|
+
rec.metadata && typeof rec.metadata === 'object' && !Array.isArray(rec.metadata)
|
|
68
|
+
? (rec.metadata as Record<string, unknown>)
|
|
69
|
+
: undefined;
|
|
70
|
+
return { interruptId, toolCallId, toolName, args, runId, metadata };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Incrementally parse raw SSE text into `SseChunk` items, returning any
|
|
75
|
+
* trailing incomplete line to buffer for the next chunk.
|
|
76
|
+
*/
|
|
77
|
+
export function consumeSseBuffer(
|
|
78
|
+
buffer: string,
|
|
79
|
+
onChunk: (chunk: SseChunk) => void,
|
|
80
|
+
flush = false,
|
|
81
|
+
): string {
|
|
82
|
+
const normalized = buffer.replace(/\r\n/g, '\n');
|
|
83
|
+
const lines = normalized.split('\n');
|
|
84
|
+
const remainder = flush ? '' : (lines.pop() ?? '');
|
|
85
|
+
|
|
86
|
+
for (const rawLine of lines) {
|
|
87
|
+
const line = rawLine.trim();
|
|
88
|
+
if (!line || line.startsWith(':')) continue;
|
|
89
|
+
if (!line.startsWith('data:')) continue;
|
|
90
|
+
const payload = line.slice(5).trim();
|
|
91
|
+
if (!payload || payload === '[DONE]') continue;
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(payload) as { type?: unknown };
|
|
94
|
+
if (parsed && typeof parsed.type === 'string') {
|
|
95
|
+
onChunk(parsed as SseChunk);
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
// Ignore malformed SSE frames so one bad frame does not break the stream.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return remainder;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function buildRequestBody(turn: StreamTurnRequest): Record<string, unknown> {
|
|
105
|
+
const body: Record<string, unknown> = {};
|
|
106
|
+
if (turn.requestMetadata && Object.keys(turn.requestMetadata).length > 0) {
|
|
107
|
+
body.request_metadata = turn.requestMetadata;
|
|
108
|
+
}
|
|
109
|
+
if (turn.resume) {
|
|
110
|
+
const resumeBody: Record<string, unknown> = {
|
|
111
|
+
runId: turn.resume.runId,
|
|
112
|
+
decisions: turn.resume.decisions,
|
|
113
|
+
};
|
|
114
|
+
const reasons = turn.resume.denialReasons;
|
|
115
|
+
if (reasons && Object.keys(reasons).length > 0) {
|
|
116
|
+
resumeBody.denial_reasons = reasons;
|
|
117
|
+
}
|
|
118
|
+
body.resume = resumeBody;
|
|
119
|
+
} else {
|
|
120
|
+
body.content = turn.content;
|
|
121
|
+
}
|
|
122
|
+
return body;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Send a chat turn or HITL approval resume to `POST /api/ai/threads/{id}/messages`
|
|
127
|
+
* and stream parsed AG-UI SSE chunks to `options.onChunk`.
|
|
128
|
+
*/
|
|
129
|
+
export async function streamThreadTurn(
|
|
130
|
+
threadId: string,
|
|
131
|
+
turn: StreamTurnRequest,
|
|
132
|
+
options: StreamTurnOptions,
|
|
133
|
+
): Promise<void> {
|
|
134
|
+
const response = await fetch(`/api/ai/threads/${encodeURIComponent(threadId)}/messages`, {
|
|
135
|
+
method: 'POST',
|
|
136
|
+
credentials: 'same-origin',
|
|
137
|
+
signal: options.signal,
|
|
138
|
+
headers: {
|
|
139
|
+
'Content-Type': 'application/json',
|
|
140
|
+
Accept: 'text/event-stream',
|
|
141
|
+
...buildCsrfHeaders('POST', options.csrfToken),
|
|
142
|
+
},
|
|
143
|
+
body: JSON.stringify(buildRequestBody(turn)),
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
if (!response.ok) {
|
|
147
|
+
throw await parseResponseError(response);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (!response.body) {
|
|
151
|
+
const text = await response.text();
|
|
152
|
+
consumeSseBuffer(text, options.onChunk, true);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const reader = response.body.getReader();
|
|
157
|
+
const decoder = new TextDecoder();
|
|
158
|
+
let buffer = '';
|
|
159
|
+
try {
|
|
160
|
+
while (true) {
|
|
161
|
+
const { value, done } = await reader.read();
|
|
162
|
+
if (done) break;
|
|
163
|
+
buffer += decoder.decode(value, { stream: true });
|
|
164
|
+
buffer = consumeSseBuffer(buffer, options.onChunk, false);
|
|
165
|
+
}
|
|
166
|
+
buffer += decoder.decode();
|
|
167
|
+
consumeSseBuffer(buffer, options.onChunk, true);
|
|
168
|
+
} finally {
|
|
169
|
+
reader.releaseLock();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Shared frontend types for `@simple-module-py/chat`. */
|
|
2
|
+
|
|
3
|
+
export type ChatProviderInfo = {
|
|
4
|
+
id: string;
|
|
5
|
+
title: string;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export type ChatSuggestedPrompt = {
|
|
9
|
+
id: string;
|
|
10
|
+
provider_id: string;
|
|
11
|
+
provider_title: string;
|
|
12
|
+
label: string;
|
|
13
|
+
prompt: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type ChatContextData = {
|
|
17
|
+
agent_id: string;
|
|
18
|
+
drawer_enabled: boolean;
|
|
19
|
+
ai_configured: boolean;
|
|
20
|
+
providers: ChatProviderInfo[];
|
|
21
|
+
suggested_prompts: ChatSuggestedPrompt[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type ThreadUsage = {
|
|
25
|
+
input_tokens: number;
|
|
26
|
+
output_tokens: number;
|
|
27
|
+
requests: number;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export type ThreadSummary = {
|
|
31
|
+
id: string;
|
|
32
|
+
agent_id: string;
|
|
33
|
+
scope_type: string | null;
|
|
34
|
+
scope_id: string | null;
|
|
35
|
+
title: string;
|
|
36
|
+
status: string;
|
|
37
|
+
usage: ThreadUsage;
|
|
38
|
+
created_at: string;
|
|
39
|
+
updated_at: string;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type ThreadListResponse = {
|
|
43
|
+
threads: ThreadSummary[];
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type PersistedMessagePart =
|
|
47
|
+
| { type: 'text'; content: string }
|
|
48
|
+
| { type: 'tool-call'; toolCallId: string; toolName: string; args?: unknown }
|
|
49
|
+
| { type: 'tool-result'; toolCallId: string; toolName: string; content?: unknown }
|
|
50
|
+
| { type: string; [key: string]: unknown };
|
|
51
|
+
|
|
52
|
+
export type PersistedMessage = {
|
|
53
|
+
id: string;
|
|
54
|
+
seq: number;
|
|
55
|
+
run_id: string;
|
|
56
|
+
role: 'user' | 'assistant' | 'tool' | string;
|
|
57
|
+
content: string;
|
|
58
|
+
parts?: PersistedMessagePart[];
|
|
59
|
+
input_tokens?: number;
|
|
60
|
+
output_tokens?: number;
|
|
61
|
+
model_name?: string;
|
|
62
|
+
created_at?: string;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export type PendingApprovalItem = {
|
|
66
|
+
interruptId: string;
|
|
67
|
+
toolCallId: string;
|
|
68
|
+
toolName: string;
|
|
69
|
+
args: Record<string, unknown>;
|
|
70
|
+
runId: string;
|
|
71
|
+
metadata?: Record<string, unknown>;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export type ThreadDetail = ThreadSummary & {
|
|
75
|
+
messages: PersistedMessage[];
|
|
76
|
+
pending_approvals: PendingApprovalItem[];
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type ThreadCancelResponse = {
|
|
80
|
+
cancelled: boolean;
|
|
81
|
+
local_signalled: boolean;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export type ToolCallStatus = 'running' | 'completed' | 'failed';
|
|
85
|
+
|
|
86
|
+
export type ToolCallActivity = {
|
|
87
|
+
toolCallId: string;
|
|
88
|
+
toolName: string;
|
|
89
|
+
argsText: string;
|
|
90
|
+
result?: string;
|
|
91
|
+
status: ToolCallStatus;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export type ChatMessage = {
|
|
95
|
+
id: string;
|
|
96
|
+
role: 'user' | 'assistant';
|
|
97
|
+
content: string;
|
|
98
|
+
toolCalls?: ToolCallActivity[];
|
|
99
|
+
cancelled?: boolean;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export type ChatRequestMetadata = {
|
|
103
|
+
current_path?: string;
|
|
104
|
+
current_component?: string;
|
|
105
|
+
locale?: string;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export type ChatSharedProp = {
|
|
109
|
+
enabled: boolean;
|
|
110
|
+
drawer_enabled: boolean;
|
|
111
|
+
};
|
sm_chat/web/__init__.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""REST API endpoints for ``sm_chat``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
from simple_module_core.access.permissions import grants
|
|
10
|
+
from simple_module_hosting.auth.permissions import (
|
|
11
|
+
RequiresPermission,
|
|
12
|
+
ensure_resolved_permissions,
|
|
13
|
+
)
|
|
14
|
+
from sm_ai.contracts import AiRequestContext
|
|
15
|
+
from sm_ai.contracts import status as ai_status
|
|
16
|
+
|
|
17
|
+
from sm_chat.agent.toolset import provider_has_permitted_tools
|
|
18
|
+
from sm_chat.contracts import list_chat_providers
|
|
19
|
+
from sm_chat.core import constants, tenancy
|
|
20
|
+
from sm_chat.core.settings import current_settings
|
|
21
|
+
|
|
22
|
+
router = APIRouter(dependencies=[Depends(tenancy.bind_admin)])
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ChatProviderOut(BaseModel):
|
|
26
|
+
id: str
|
|
27
|
+
title: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ChatSuggestedPromptOut(BaseModel):
|
|
31
|
+
id: str
|
|
32
|
+
provider_id: str
|
|
33
|
+
provider_title: str
|
|
34
|
+
label: str
|
|
35
|
+
prompt: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ChatContextOut(BaseModel):
|
|
39
|
+
agent_id: str
|
|
40
|
+
drawer_enabled: bool
|
|
41
|
+
ai_configured: bool
|
|
42
|
+
providers: list[ChatProviderOut]
|
|
43
|
+
suggested_prompts: list[ChatSuggestedPromptOut]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _extract_roles(user: Any) -> frozenset[str]:
|
|
47
|
+
raw = getattr(user, "roles", None) or ()
|
|
48
|
+
roles: set[str] = set()
|
|
49
|
+
for item in raw:
|
|
50
|
+
name = getattr(item, "name", None)
|
|
51
|
+
roles.add(str(name if name is not None else item))
|
|
52
|
+
return frozenset(roles)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def _extract_permissions(request: Request) -> frozenset[str]:
|
|
56
|
+
try:
|
|
57
|
+
resolved = await ensure_resolved_permissions(request)
|
|
58
|
+
return frozenset(str(p) for p in resolved)
|
|
59
|
+
except Exception:
|
|
60
|
+
fallback = getattr(request.state, "resolved_permissions", None) or ()
|
|
61
|
+
return frozenset(str(p) for p in fallback)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@router.get(
|
|
65
|
+
constants.ROUTE_CONTEXT,
|
|
66
|
+
response_model=ChatContextOut,
|
|
67
|
+
dependencies=[Depends(RequiresPermission(constants.PERM_USE))],
|
|
68
|
+
)
|
|
69
|
+
async def get_chat_context(request: Request) -> ChatContextOut:
|
|
70
|
+
"""Return permitted chat providers, starter prompts, and drawer/AI status."""
|
|
71
|
+
user = getattr(request.state, "user", None)
|
|
72
|
+
if user is None:
|
|
73
|
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
74
|
+
user_id = str(getattr(user, "id", "") or "").strip()
|
|
75
|
+
if not user_id:
|
|
76
|
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
77
|
+
|
|
78
|
+
permissions = await _extract_permissions(request)
|
|
79
|
+
ai_ctx = AiRequestContext(
|
|
80
|
+
tenant_id=tenancy.bound_tenant(),
|
|
81
|
+
user_id=user_id,
|
|
82
|
+
roles=_extract_roles(user),
|
|
83
|
+
permissions=permissions,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
permitted_providers = [
|
|
87
|
+
provider
|
|
88
|
+
for provider in list_chat_providers(request.app)
|
|
89
|
+
if provider_has_permitted_tools(provider, ai_ctx)
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
prompts: list[ChatSuggestedPromptOut] = []
|
|
93
|
+
for provider in permitted_providers:
|
|
94
|
+
for item in provider.suggested_prompts:
|
|
95
|
+
if item.required_permissions and not all(
|
|
96
|
+
grants(permissions, perm) for perm in item.required_permissions
|
|
97
|
+
):
|
|
98
|
+
continue
|
|
99
|
+
prompts.append(
|
|
100
|
+
ChatSuggestedPromptOut(
|
|
101
|
+
id=item.id,
|
|
102
|
+
provider_id=provider.id,
|
|
103
|
+
provider_title=provider.title,
|
|
104
|
+
label=item.label,
|
|
105
|
+
prompt=item.prompt,
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
settings = current_settings(request.app)
|
|
110
|
+
slot_status = ai_status()
|
|
111
|
+
return ChatContextOut(
|
|
112
|
+
agent_id=constants.AGENT_ID,
|
|
113
|
+
drawer_enabled=settings.drawer_enabled,
|
|
114
|
+
ai_configured=bool(slot_status.get(constants.AGENT_TIER, False)),
|
|
115
|
+
providers=[ChatProviderOut(id=p.id, title=p.title) for p in permitted_providers],
|
|
116
|
+
suggested_prompts=prompts,
|
|
117
|
+
)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Inertia view endpoints for ``sm_chat``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends
|
|
6
|
+
from simple_module_hosting.auth.permissions import RequiresPermission
|
|
7
|
+
from simple_module_hosting.frontend.inertia_deps import InertiaDep
|
|
8
|
+
from simple_module_inertia import InertiaResponse
|
|
9
|
+
|
|
10
|
+
from sm_chat.core import constants, tenancy
|
|
11
|
+
|
|
12
|
+
router = APIRouter(dependencies=[Depends(tenancy.bind_admin)])
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@router.get(
|
|
16
|
+
constants.VIEW_INDEX,
|
|
17
|
+
response_model=None,
|
|
18
|
+
dependencies=[Depends(RequiresPermission(constants.PERM_USE))],
|
|
19
|
+
)
|
|
20
|
+
async def chat_index(inertia: InertiaDep) -> InertiaResponse:
|
|
21
|
+
"""Render the dedicated ``/chat`` console workspace."""
|
|
22
|
+
return await inertia.render(constants._PAGE_INDEX, {})
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Inertia shared props exposing chat drawer availability for permitted users."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from fastapi import Request
|
|
6
|
+
from simple_module_core.access.permissions import grants
|
|
7
|
+
from simple_module_hosting.auth.permissions import ensure_resolved_permissions
|
|
8
|
+
from simple_module_hosting.auth.token_guard import is_token_principal
|
|
9
|
+
|
|
10
|
+
from sm_chat.core import constants
|
|
11
|
+
from sm_chat.core.settings import current_settings
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def chat_shared_props(request: Request) -> dict[str, dict[str, bool]]:
|
|
15
|
+
"""Return ``{"chat": {"enabled": True, "drawer_enabled": ...}}`` when permitted."""
|
|
16
|
+
user = getattr(request.state, "user", None)
|
|
17
|
+
if user is None or is_token_principal(user):
|
|
18
|
+
return {}
|
|
19
|
+
try:
|
|
20
|
+
resolved = await ensure_resolved_permissions(request)
|
|
21
|
+
permissions = frozenset(str(p) for p in resolved)
|
|
22
|
+
except Exception:
|
|
23
|
+
fallback = getattr(request.state, "resolved_permissions", None) or ()
|
|
24
|
+
permissions = frozenset(str(p) for p in fallback)
|
|
25
|
+
if not grants(permissions, constants.PERM_USE):
|
|
26
|
+
return {}
|
|
27
|
+
settings = current_settings(getattr(request, "app", None))
|
|
28
|
+
return {
|
|
29
|
+
"chat": {
|
|
30
|
+
"enabled": True,
|
|
31
|
+
"drawer_enabled": settings.drawer_enabled,
|
|
32
|
+
}
|
|
33
|
+
}
|