@micha.bigler/ui-core-micha 3.13.2 → 3.14.4

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 (77) hide show
  1. package/.github/workflows/ci.yml +35 -0
  2. package/.github/workflows/publish.yml +4 -4
  3. package/CHANGELOG.md +35 -0
  4. package/WORK_ORDERS.md +7 -1
  5. package/dist/auth/UserMenu.js +1 -1
  6. package/dist/auth/apiClient.js +7 -6
  7. package/dist/chat/ChatComposer.js +23 -0
  8. package/dist/chat/ChatList.js +30 -0
  9. package/dist/chat/ChatThread.js +70 -0
  10. package/dist/chat/ChatWorkspace.js +218 -0
  11. package/dist/chat/MarkdownReply.js +21 -0
  12. package/dist/chat/ModelPicker.js +35 -0
  13. package/dist/chat/api.js +17 -0
  14. package/dist/chat/useChatSocket.js +68 -0
  15. package/dist/chat/wire.js +7 -0
  16. package/dist/components/LoginForm.js +1 -1
  17. package/dist/components/SecurityComponent.js +1 -1
  18. package/dist/components/UserListComponent.js +2 -8
  19. package/dist/components/charts/ChartFrame.js +1 -1
  20. package/dist/components/charts/ScatterChart.js +2 -1
  21. package/dist/i18n/chatTranslations.js +55 -0
  22. package/dist/i18n/uiCoreTranslations.js +2 -1
  23. package/dist/index.js +10 -0
  24. package/dist/layout/SectionNav.js +1 -1
  25. package/dist/messaging/AttachmentList.js +2 -2
  26. package/dist/messaging/Composer.js +2 -1
  27. package/dist/messaging/ConversationLaunchers.js +1 -4
  28. package/dist/messaging/ConversationList.js +1 -1
  29. package/dist/messaging/DirectMessageLauncher.js +1 -1
  30. package/dist/messaging/MessagingProvider.js +0 -0
  31. package/dist/messaging/PollCard.js +7 -5
  32. package/dist/messaging/ReadTicks.js +2 -2
  33. package/dist/messaging/Thread.js +5 -3
  34. package/dist/notifications/NotificationBell.js +4 -7
  35. package/dist/notifications/NotificationSettings.js +1 -1
  36. package/dist/onboarding/OnboardingProvider.js +3 -6
  37. package/dist/pages/LoginPage.js +1 -1
  38. package/dist/pages/PasswordChangePage.js +1 -1
  39. package/dist/pages/PasswordInvitePage.js +1 -1
  40. package/dist/pages/PasswordResetRequestPage.js +1 -1
  41. package/dist/pages/SignUpPage.js +1 -1
  42. package/dist/pages/SignupConfirmPage.js +1 -1
  43. package/dist/theme/createAppTheme.js +5 -4
  44. package/dist/theme/kitSxRegistry.js +10 -0
  45. package/dist/theme/themeCompleteness.js +3 -12
  46. package/dist/utils/auth-errors.js +4 -3
  47. package/package.json +13 -11
  48. package/src/chat/ChatComposer.jsx +36 -0
  49. package/src/chat/ChatList.jsx +87 -0
  50. package/src/chat/ChatThread.jsx +128 -0
  51. package/src/chat/ChatWorkspace.jsx +244 -0
  52. package/src/chat/MarkdownReply.jsx +22 -0
  53. package/src/chat/ModelPicker.jsx +85 -0
  54. package/src/chat/api.js +18 -0
  55. package/src/chat/useChatSocket.js +32 -0
  56. package/src/chat/wire.js +7 -0
  57. package/src/i18n/chatTranslations.ts +55 -0
  58. package/src/i18n/uiCoreTranslations.js +2 -0
  59. package/src/index.js +11 -0
  60. package/src/theme/kitSxRegistry.js +10 -0
  61. package/tests/chatApi.test.js +48 -0
  62. package/tests/chatDriverNames.test.jsx +71 -0
  63. package/tests/chatExports.test.js +3 -0
  64. package/tests/chatList.test.jsx +84 -0
  65. package/tests/chatPicker.test.jsx +82 -0
  66. package/tests/chatSocket.test.jsx +26 -0
  67. package/tests/chatThread.test.jsx +116 -0
  68. package/tests/chatTranslations.test.js +47 -0
  69. package/tests/chatWorkspace.test.jsx +234 -0
  70. package/tests/i18nAggregate.test.js +2 -0
  71. package/tsconfig.build.json +1 -1
  72. package/work-orders/UCM-AUTH-13.md +2 -0
  73. package/work-orders/UCM-CHAT-1.md +190 -0
  74. package/work-orders/UCM-CHAT-2.md +75 -0
  75. package/work-orders/UCM-CI-1.md +65 -0
  76. package/work-orders/UCM-DEP-1.md +63 -0
  77. package/work-orders/assets/UCM-CHAT-1-ai-chat.html +447 -0
@@ -33,6 +33,8 @@ import { LOGIN_PAGE_ALERT_SX } from '../pages/LoginPage';
33
33
  import { SIGN_UP_PAGE_ALERT_SX } from '../pages/SignUpPage';
34
34
  import { SIGNUP_CONFIRM_PAGE_ALERT_SX } from '../pages/SignupConfirmPage';
35
35
  import { REAUTH_MODAL_ALERT_SX, REAUTH_MODAL_TEXT_FIELD_SX } from '../auth/ReauthModal';
36
+ import { CHAT_LIST_ARCHIVED_ACTION_SX, CHAT_LIST_ROW_ACTION_SX } from '../chat/ChatList';
37
+ import { CHAT_THREAD_NOTICE_SX, CHAT_THREAD_TOOL_CHIP_SX } from '../chat/ChatThread';
36
38
  const SX_EXPORTS = {
37
39
  ACCESS_CODE_ACTION_SX,
38
40
  ACCESS_CODE_ALERT_SX,
@@ -103,6 +105,10 @@ const SX_EXPORTS = {
103
105
  SUPPORT_RECOVERY_AGENT_PAPER_SX,
104
106
  SUPPORT_RECOVERY_ALERT_SX,
105
107
  THREAD_DAY_SEPARATOR_SX,
108
+ CHAT_LIST_ARCHIVED_ACTION_SX,
109
+ CHAT_LIST_ROW_ACTION_SX,
110
+ CHAT_THREAD_NOTICE_SX,
111
+ CHAT_THREAD_TOOL_CHIP_SX,
106
112
  USER_INVITE_ACTION_SX,
107
113
  USER_INVITE_ALERT_SX,
108
114
  USER_LIST_ACTION_SX,
@@ -202,4 +208,8 @@ export const KIT_COMPONENT_SX_REGISTRY = [
202
208
  entry('SignupConfirmPage.alert', 'MuiAlert', SIGNUP_CONFIRM_PAGE_ALERT_SX),
203
209
  entry('ReauthModal.alert', 'MuiAlert', REAUTH_MODAL_ALERT_SX),
204
210
  entry('ReauthModal.field', 'MuiTextField', REAUTH_MODAL_TEXT_FIELD_SX),
211
+ entry('ChatList.rowAction', 'MuiIconButton', CHAT_LIST_ROW_ACTION_SX),
212
+ entry('ChatList.archivedAction', 'MuiButton', CHAT_LIST_ARCHIVED_ACTION_SX),
213
+ entry('ChatThread.toolChip', 'MuiChip', CHAT_THREAD_TOOL_CHIP_SX),
214
+ entry('ChatThread.notice', 'MuiAlert', CHAT_THREAD_NOTICE_SX),
205
215
  ];
@@ -22,10 +22,7 @@ const TYPOGRAPHY_SURFACES = TYPOGRAPHY_VARIANTS.flatMap((variant) => ['fontSize'
22
22
  const componentPath = (component, path) => pathSurface(`components.${component}.${path}`);
23
23
  const componentKeyLeaf = (component, path, key, leaf) => keyedSurface(`components.${component}.${path}.${key}.${leaf}`, (theme) => { var _a, _b; return (_b = (_a = getPath(theme, `components.${component}.${path}`)) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b[leaf]; });
24
24
  const COMPONENT_SURFACES = [
25
- keyedSurface('components.MuiCssBaseline.reduced-motion.transitionDuration', (theme) => {
26
- var _a, _b, _c, _d, _e;
27
- return (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiCssBaseline) === null || _b === void 0 ? void 0 : _b.styleOverrides) === null || _c === void 0 ? void 0 : _c['@media (prefers-reduced-motion: reduce)']) === null || _d === void 0 ? void 0 : _d['*, *::before, *::after']) === null || _e === void 0 ? void 0 : _e.transitionDuration;
28
- }),
25
+ keyedSurface('components.MuiCssBaseline.reduced-motion.transitionDuration', (theme) => { var _a, _b, _c, _d, _e; return (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiCssBaseline) === null || _b === void 0 ? void 0 : _b.styleOverrides) === null || _c === void 0 ? void 0 : _c['@media (prefers-reduced-motion: reduce)']) === null || _d === void 0 ? void 0 : _d['*, *::before, *::after']) === null || _e === void 0 ? void 0 : _e.transitionDuration; }),
29
26
  componentPath('MuiButton', 'defaultProps.disableElevation'),
30
27
  componentPath('MuiButton', 'styleOverrides.root.minHeight'),
31
28
  componentPath('MuiButton', 'styleOverrides.root.borderRadius'),
@@ -69,10 +66,7 @@ const COMPONENT_SURFACES = [
69
66
  componentPath('MuiChip', 'styleOverrides.root.height'),
70
67
  componentPath('MuiChip', 'styleOverrides.root.borderRadius'),
71
68
  componentPath('MuiChip', 'styleOverrides.root.fontSize'),
72
- keyedSurface('components.MuiChip.styleOverrides.root.coarse-hit-area.inset', (theme) => {
73
- var _a, _b, _c, _d, _e, _f;
74
- return (_f = (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiChip) === null || _b === void 0 ? void 0 : _b.styleOverrides) === null || _c === void 0 ? void 0 : _c.root) === null || _d === void 0 ? void 0 : _d['@media (any-pointer: coarse)']) === null || _e === void 0 ? void 0 : _e['&::after']) === null || _f === void 0 ? void 0 : _f.inset;
75
- }),
69
+ keyedSurface('components.MuiChip.styleOverrides.root.coarse-hit-area.inset', (theme) => { var _a, _b, _c, _d, _e, _f; return (_f = (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiChip) === null || _b === void 0 ? void 0 : _b.styleOverrides) === null || _c === void 0 ? void 0 : _c.root) === null || _d === void 0 ? void 0 : _d['@media (any-pointer: coarse)']) === null || _e === void 0 ? void 0 : _e['&::after']) === null || _f === void 0 ? void 0 : _f.inset; }),
76
70
  componentPath('MuiBottomNavigation', 'styleOverrides.root.boxShadow'),
77
71
  componentPath('MuiBottomNavigation', 'styleOverrides.root.backgroundColor'),
78
72
  componentPath('MuiBottomNavigationAction', 'styleOverrides.root.padding'),
@@ -95,10 +89,7 @@ const COMPONENT_SURFACES = [
95
89
  componentKeyLeaf('MuiTextField', 'styleOverrides.root', '@media (any-pointer: coarse)', 'minWidth'),
96
90
  componentPath('MuiOutlinedInput', 'styleOverrides.root.minHeight'),
97
91
  componentPath('MuiOutlinedInput', 'styleOverrides.root.borderRadius'),
98
- keyedSurface('components.MuiOutlinedInput.variants.non-multiline-height', (theme) => {
99
- var _a, _b, _c, _d, _e;
100
- return (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiOutlinedInput) === null || _b === void 0 ? void 0 : _b.variants) === null || _c === void 0 ? void 0 : _c.find(({ props }) => (props === null || props === void 0 ? void 0 : props.multiline) === false)) === null || _d === void 0 ? void 0 : _d.style) === null || _e === void 0 ? void 0 : _e.height;
101
- }),
92
+ keyedSurface('components.MuiOutlinedInput.variants.non-multiline-height', (theme) => { var _a, _b, _c, _d, _e; return (_e = (_d = (_c = (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a.MuiOutlinedInput) === null || _b === void 0 ? void 0 : _b.variants) === null || _c === void 0 ? void 0 : _c.find(({ props }) => (props === null || props === void 0 ? void 0 : props.multiline) === false)) === null || _d === void 0 ? void 0 : _d.style) === null || _e === void 0 ? void 0 : _e.height; }),
102
93
  componentKeyLeaf('MuiOutlinedInput', 'styleOverrides.root', '@media (any-pointer: coarse)', 'minHeight'),
103
94
  componentKeyLeaf('MuiOutlinedInput', 'styleOverrides.root', '@media (any-pointer: coarse)', 'minWidth'),
104
95
  componentKeyLeaf('MuiOutlinedInput', 'styleOverrides.root', '& .MuiOutlinedInput-notchedOutline', 'borderColor'),
@@ -1,8 +1,9 @@
1
1
  // src/utils/auth-errors.js
2
2
  export function extractErrorInfo(error) {
3
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
4
- const status = (_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : null;
5
- const data = (_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) !== null && _d !== void 0 ? _d : null;
3
+ var _a, _b;
4
+ var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
5
+ const status = (_c = (_a = error.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _c !== void 0 ? _c : null;
6
+ const data = (_d = (_b = error.response) === null || _b === void 0 ? void 0 : _b.data) !== null && _d !== void 0 ? _d : null;
6
7
  if (!data) {
7
8
  return {
8
9
  status,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "3.13.2",
3
+ "version": "3.14.4",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "sideEffects": [
@@ -21,7 +21,9 @@
21
21
  },
22
22
  "private": false,
23
23
  "dependencies": {
24
- "@fontsource/dm-sans": "^5.2.8"
24
+ "@fontsource/dm-sans": "^5.3.0",
25
+ "react-markdown": "^10.1.0",
26
+ "remark-gfm": "^4.0.1"
25
27
  },
26
28
  "peerDependencies": {
27
29
  "@emotion/react": "^11.14.0",
@@ -44,14 +46,14 @@
44
46
  },
45
47
  "devDependencies": {
46
48
  "@mui/icons-material": "^7.3.11",
47
- "@mui/x-charts": "^8.0.0",
48
- "@testing-library/react": "^16.3.2",
49
- "@vitejs/plugin-react": "^6.0.5",
50
- "i18next": "^26.2.0",
51
- "jsdom": "^29.1.1",
52
- "react-i18next": "^17.0.8",
53
- "typescript": "^6.0.3",
54
- "vite": "^8.2.0",
55
- "vitest": "^4.1.10"
49
+ "@mui/x-charts": "^8.29.3",
50
+ "@testing-library/react": "^16.3.3",
51
+ "@vitejs/plugin-react": "^6.1.2",
52
+ "i18next": "^26.4.2",
53
+ "jsdom": "^30.1.2",
54
+ "react-i18next": "^17.0.16",
55
+ "typescript": "^7.0.2",
56
+ "vite": "^8.3.4",
57
+ "vitest": "^5.0.3"
56
58
  }
57
59
  }
@@ -0,0 +1,36 @@
1
+ import React from 'react';
2
+ import { Button, Stack, TextField } from '@mui/material';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ /**
6
+ * Message input. Send is disabled while a turn runs, for an archived chat and while the connection is down;
7
+ * Stop replaces it during a turn. Enter sends, Shift+Enter inserts a line break.
8
+ */
9
+ export function ChatComposer({ value = '', onChange, onSend, onStop, running = false, archived = false, connected = true, sx }) {
10
+ const { t } = useTranslation();
11
+ const blocked = archived || !connected;
12
+ const canSend = !running && !blocked && value.trim().length > 0;
13
+ const submit = () => { if (canSend) onSend?.(); };
14
+ return (
15
+ <Stack direction="row" alignItems="flex-end" gap={1} sx={{ p: { xs: 1, md: 2 }, borderTop: 1, borderColor: 'divider', ...sx }}>
16
+ <TextField
17
+ multiline
18
+ maxRows={6}
19
+ fullWidth
20
+ size="small"
21
+ value={value}
22
+ disabled={blocked}
23
+ placeholder={t('Chat.message')}
24
+ slotProps={{ htmlInput: { 'aria-label': t('Chat.message') } }}
25
+ onChange={(event) => onChange?.(event.target.value)}
26
+ onKeyDown={(event) => {
27
+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent?.isComposing) { event.preventDefault(); submit(); }
28
+ }}
29
+ />
30
+ {running ? <Button variant="outlined" onClick={onStop}>{t('Chat.stop')}</Button> : null}
31
+ <Button variant="contained" onClick={submit} disabled={!canSend}>{t('Chat.send')}</Button>
32
+ </Stack>
33
+ );
34
+ }
35
+
36
+ export default ChatComposer;
@@ -0,0 +1,87 @@
1
+ import React, { useState } from 'react';
2
+ import { Badge, Box, Button, Collapse, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, IconButton, List, ListItem, ListItemButton, ListItemText, Menu, MenuItem, Stack, TextField } from '@mui/material';
3
+ import { MoreVert } from '@mui/icons-material';
4
+ import { useTranslation } from 'react-i18next';
5
+
6
+ export const CHAT_LIST_ROW_ACTION_SX = { width: 40, height: 40 };
7
+ export const CHAT_LIST_ARCHIVED_ACTION_SX = { justifyContent: 'space-between', px: 2 };
8
+
9
+ /**
10
+ * The chat list: active chats, then an "Archived" entry that expands the archived ones (read-only, restorable).
11
+ * Rename, Archive/Restore and Delete sit in each row's overflow menu; Delete asks for confirmation first.
12
+ */
13
+ export function ChatList({ chats = [], archivedChats = [], activeId, hasMore = false, onSelect, onNew, onRename, onArchive, onRestore, onDelete, onLoadMore, sx }) {
14
+ const { t } = useTranslation();
15
+ const [menu, setMenu] = useState(null); // { anchor, chat, archived }
16
+ const [dialog, setDialog] = useState(null); // { kind: 'rename' | 'delete', chat }
17
+ const [title, setTitle] = useState('');
18
+ const [showArchived, setShowArchived] = useState(false);
19
+
20
+ const openMenu = (event, chat, archived) => { event.stopPropagation(); setMenu({ anchor: event.currentTarget, chat, archived }); };
21
+ const closeMenu = () => setMenu(null);
22
+ const startRename = () => { setTitle(menu.chat.title || ''); setDialog({ kind: 'rename', chat: menu.chat }); closeMenu(); };
23
+ const startDelete = () => { setDialog({ kind: 'delete', chat: menu.chat }); closeMenu(); };
24
+ const toggleArchive = () => { (menu.archived ? onRestore : onArchive)?.(menu.chat); closeMenu(); };
25
+ const closeDialog = () => setDialog(null);
26
+ const confirmRename = () => { onRename?.(dialog.chat, title.trim()); closeDialog(); };
27
+ const confirmDelete = () => { onDelete?.(dialog.chat); closeDialog(); };
28
+
29
+ const row = (chat, archived) => (
30
+ <ListItem
31
+ key={chat.id}
32
+ disablePadding
33
+ secondaryAction={<IconButton edge="end" aria-label={t('Chat.actions')} onClick={(event) => openMenu(event, chat, archived)} sx={CHAT_LIST_ROW_ACTION_SX}><MoreVert fontSize="small" /></IconButton>}
34
+ >
35
+ <ListItemButton selected={chat.id === activeId} onClick={() => onSelect?.(chat)} sx={{ minHeight: 48, pr: 6 }}>
36
+ <ListItemText primary={chat.title || t('Chat.untitled')} slotProps={{ primary: { noWrap: true } }} />
37
+ </ListItemButton>
38
+ </ListItem>
39
+ );
40
+
41
+ return (
42
+ <Stack sx={{ minWidth: 0, height: '100%', overflowY: 'auto', ...sx }} component="nav" aria-label={t('Chat.chats')}>
43
+ <Box sx={{ p: 1.5 }}>
44
+ <Button fullWidth variant="contained" onClick={onNew}>{t('Chat.newChat')}</Button>
45
+ </Box>
46
+ <List disablePadding>{chats.map((chat) => row(chat, false))}</List>
47
+ {hasMore ? <Button onClick={onLoadMore}>{t('Chat.loadMore')}</Button> : null}
48
+ {archivedChats.length > 0 ? (
49
+ <>
50
+ <Button color="inherit" onClick={() => setShowArchived((value) => !value)} aria-expanded={showArchived} sx={CHAT_LIST_ARCHIVED_ACTION_SX}>
51
+ {t('Chat.archived')}
52
+ <Badge color="default" badgeContent={archivedChats.length} sx={{ mr: 1.5 }} />
53
+ </Button>
54
+ <Collapse in={showArchived} unmountOnExit><List disablePadding>{archivedChats.map((chat) => row(chat, true))}</List></Collapse>
55
+ </>
56
+ ) : null}
57
+
58
+ <Menu anchorEl={menu?.anchor} open={Boolean(menu)} onClose={closeMenu}>
59
+ <MenuItem onClick={startRename}>{t('Chat.rename')}</MenuItem>
60
+ <MenuItem onClick={toggleArchive}>{menu?.archived ? t('Chat.restore') : t('Chat.archive')}</MenuItem>
61
+ <MenuItem onClick={startDelete}>{t('Chat.delete')}</MenuItem>
62
+ </Menu>
63
+
64
+ <Dialog open={dialog?.kind === 'rename'} onClose={closeDialog} fullWidth maxWidth="xs">
65
+ <DialogTitle>{t('Chat.rename')}</DialogTitle>
66
+ <DialogContent>
67
+ <TextField autoFocus fullWidth margin="dense" value={title} onChange={(event) => setTitle(event.target.value)} slotProps={{ htmlInput: { 'aria-label': t('Chat.renameLabel'), maxLength: 120 } }} onKeyDown={(event) => { if (event.key === 'Enter' && title.trim()) confirmRename(); }} />
68
+ </DialogContent>
69
+ <DialogActions>
70
+ <Button onClick={closeDialog}>{t('Chat.cancel')}</Button>
71
+ <Button variant="contained" disabled={!title.trim()} onClick={confirmRename}>{t('Chat.save')}</Button>
72
+ </DialogActions>
73
+ </Dialog>
74
+
75
+ <Dialog open={dialog?.kind === 'delete'} onClose={closeDialog} fullWidth maxWidth="xs">
76
+ <DialogTitle>{t('Chat.delete')}</DialogTitle>
77
+ <DialogContent><DialogContentText>{t('Chat.deleteConfirm')}</DialogContentText></DialogContent>
78
+ <DialogActions>
79
+ <Button onClick={closeDialog}>{t('Chat.cancel')}</Button>
80
+ <Button color="error" variant="contained" onClick={confirmDelete}>{t('Chat.delete')}</Button>
81
+ </DialogActions>
82
+ </Dialog>
83
+ </Stack>
84
+ );
85
+ }
86
+
87
+ export default ChatList;
@@ -0,0 +1,128 @@
1
+ import React, { useEffect, useLayoutEffect, useRef } from 'react';
2
+ import { Alert, Box, Button, Chip, Stack, Tooltip, Typography } from '@mui/material';
3
+ import { useTranslation } from 'react-i18next';
4
+ import MarkdownReply from './MarkdownReply';
5
+
6
+ export const CHAT_THREAD_TOOL_CHIP_SX = { alignSelf: 'flex-start' };
7
+ export const CHAT_THREAD_NOTICE_SX = { mb: 2 };
8
+
9
+ const selectionLine = (turn, t) => [turn.model, turn.effort && t(`Chat.effort.${turn.effort}`)].filter(Boolean).join(' · ');
10
+ const sameSelection = (a, b) => a.driver === b.driver && a.model === b.model && a.effort === b.effort;
11
+
12
+ function SourceChips({ sources }) {
13
+ const { t } = useTranslation();
14
+ if (!sources?.length) return null;
15
+ return (
16
+ <Stack direction="row" flexWrap="wrap" gap={0.75} role="list" aria-label={t('Chat.sources')}>
17
+ {sources.map((source, index) => (
18
+ <Tooltip key={`${source.label}-${index}`} title={source.reference || ''} describeChild>
19
+ <Chip role="listitem" size="small" variant="outlined" label={source.label} />
20
+ </Tooltip>
21
+ ))}
22
+ </Stack>
23
+ );
24
+ }
25
+
26
+ function Answer({ turn, tool, onRetry }) {
27
+ const { t } = useTranslation();
28
+ const generating = turn.state === 'generating';
29
+ const failed = ['failed', 'cancelled'].includes(turn.state) && turn.error_code;
30
+ return (
31
+ <Stack spacing={1} aria-busy={generating}>
32
+ {turn.assistant_text ? <MarkdownReply text={turn.assistant_text} /> : null}
33
+ {generating && !turn.assistant_text && !tool ? <Typography variant="body2" color="text.secondary">{t('Chat.typing')}</Typography> : null}
34
+ {generating && tool ? <Chip size="small" color="primary" variant="outlined" label={tool.label} sx={CHAT_THREAD_TOOL_CHIP_SX} /> : null}
35
+ <SourceChips sources={turn.sources} />
36
+ {!generating && selectionLine(turn, t) ? <Typography variant="caption" color="text.secondary">{selectionLine(turn, t)}</Typography> : null}
37
+ {turn.state === 'interrupted' ? (
38
+ <Stack direction="row" alignItems="center" gap={1}>
39
+ <Chip size="small" color="warning" label={t('Chat.interrupted')} />
40
+ {onRetry ? <Button size="small" onClick={() => onRetry(turn)}>{t('Chat.retry')}</Button> : null}
41
+ </Stack>
42
+ ) : null}
43
+ {failed ? (
44
+ <Alert severity="error" action={onRetry ? <Button color="inherit" size="small" onClick={() => onRetry(turn)}>{t('Chat.retry')}</Button> : null}>
45
+ {t('Chat.answerIncomplete')}
46
+ </Alert>
47
+ ) : null}
48
+ </Stack>
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The turns of one chat. The streaming answer is simply the last turn in state `generating`; the caller keeps its text
54
+ * up to date. `notice` is a connection or limit message shown under the last turn. `readOnly` (an archived chat) hides Retry.
55
+ */
56
+ export function ChatThread({ turns = [], tool = null, notice = null, hasOlder = false, olderBusy = false, onLoadOlder, onRetry, readOnly = false, sx }) {
57
+ const { t } = useTranslation();
58
+ const end = useRef(null);
59
+ const scroller = useRef(null);
60
+ const heightBeforeOlder = useRef(null);
61
+ const pinned = useRef(true); // follow the stream only while the reader is at the bottom
62
+ const last = turns[turns.length - 1];
63
+ // Follow the stream, but only when new content arrives at the end (not when older turns are prepended).
64
+ useEffect(() => { if (pinned.current) end.current?.scrollIntoView?.({ block: 'end' }); }, [last?.id, last?.assistant_text, last?.state]);
65
+
66
+ // Keep the reader's position when older turns are prepended.
67
+ useLayoutEffect(() => {
68
+ const el = scroller.current;
69
+ if (el && heightBeforeOlder.current !== null) el.scrollTop += el.scrollHeight - heightBeforeOlder.current;
70
+ heightBeforeOlder.current = null;
71
+ }, [turns[0]?.id]);
72
+ const loadingOlder = useRef(false); // one request at a time, also across rapid scroll events
73
+ const loadOlder = async () => {
74
+ if (loadingOlder.current) return;
75
+ loadingOlder.current = true;
76
+ heightBeforeOlder.current = scroller.current?.scrollHeight ?? null;
77
+ try { await onLoadOlder?.(); } finally { loadingOlder.current = false; }
78
+ };
79
+
80
+ return (
81
+ <Box ref={scroller} onScroll={(event) => {
82
+ const el = event.currentTarget;
83
+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
84
+ if (hasOlder && !olderBusy && el.scrollTop <= 40) loadOlder();
85
+ }} role="log" aria-live="polite" aria-label={t('Chat.thread')} sx={{ minHeight: 0, flex: 1, overflowY: 'auto', p: { xs: 1.5, md: 2.5 }, ...sx }}>
86
+ {hasOlder ? (
87
+ <Box sx={{ textAlign: 'center', mb: 2 }}>
88
+ <Button size="small" onClick={loadOlder} disabled={olderBusy}>{t('Chat.loadOlder')}</Button>
89
+ </Box>
90
+ ) : null}
91
+ {turns.length === 0 ? (
92
+ <Typography variant="h6" color="text.secondary" align="center" sx={{ mt: 6 }}>{t('Chat.emptyTitle')}</Typography>
93
+ ) : null}
94
+ {turns.map((turn, index) => {
95
+ const previous = turns[index - 1];
96
+ return (
97
+ <Box key={turn.id ?? index} sx={{ mb: 3 }}>
98
+ {previous && !sameSelection(previous, turn) ? (
99
+ <Stack direction="row" alignItems="center" gap={1} sx={{ mb: 2, color: 'text.secondary' }} role="separator">
100
+ <Box sx={{ flex: 1, borderTop: 1, borderColor: 'divider' }} />
101
+ <Typography variant="caption">{t('Chat.modelChanged', { model: selectionLine(turn, t) })}</Typography>
102
+ <Box sx={{ flex: 1, borderTop: 1, borderColor: 'divider' }} />
103
+ </Stack>
104
+ ) : null}
105
+ <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 1.5 }}>
106
+ <Typography sx={{ maxWidth: '85%', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', bgcolor: 'action.hover', borderRadius: 2, px: 1.5, py: 1 }}>
107
+ {turn.user_text}
108
+ </Typography>
109
+ </Box>
110
+ <Answer turn={turn} tool={index === turns.length - 1 ? tool : null} onRetry={readOnly ? undefined : onRetry} />
111
+ </Box>
112
+ );
113
+ })}
114
+ {notice ? (
115
+ <Alert
116
+ severity={notice.severity || 'warning'}
117
+ sx={CHAT_THREAD_NOTICE_SX}
118
+ action={notice.action ? <Button color="inherit" size="small" onClick={notice.action.onClick}>{notice.action.label}</Button> : null}
119
+ >
120
+ {notice.text}
121
+ </Alert>
122
+ ) : null}
123
+ <div ref={end} />
124
+ </Box>
125
+ );
126
+ }
127
+
128
+ export default ChatThread;
@@ -0,0 +1,244 @@
1
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
+ import { Alert, Box, Button, Chip, Drawer, Stack, Typography, useMediaQuery, useTheme } from '@mui/material';
3
+ import { useTranslation } from 'react-i18next';
4
+ import { createChatApi } from './api';
5
+ import { useChatSocket } from './useChatSocket';
6
+ import ChatList from './ChatList';
7
+ import ChatThread from './ChatThread';
8
+ import ChatComposer from './ChatComposer';
9
+ import ModelPicker from './ModelPicker';
10
+
11
+ const PENDING_ID = 'pending';
12
+ const bySeq = (a, b) => (a.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER);
13
+ const chronological = (turns) => [...(turns || [])].sort(bySeq);
14
+ const isGenerating = (turn) => turn.state === 'generating';
15
+
16
+ /** Replaces the turn that was generating (or has the same id) with the final one; appends it when neither exists. */
17
+ const settleTurn = (turns, final) => {
18
+ const index = turns.findIndex((turn) => turn.id === final.id || isGenerating(turn));
19
+ if (index < 0) return chronological([...turns, final]);
20
+ return [...turns.slice(0, index), final, ...turns.slice(index + 1)];
21
+ };
22
+ const failGenerating = (turns, code) => turns.map((turn) => (isGenerating(turn)
23
+ ? { ...turn, state: 'failed', error_code: code === 'quota_exceeded' ? null : code }
24
+ : turn));
25
+ const appendDelta = (turns, text) => {
26
+ const index = turns.findLastIndex(isGenerating);
27
+ if (index < 0) return turns;
28
+ return turns.map((turn, i) => (i === index ? { ...turn, assistant_text: `${turn.assistant_text || ''}${text}` } : turn));
29
+ };
30
+
31
+ /**
32
+ * The complete chat surface: chat list, thread, composer and model picker for one user.
33
+ *
34
+ * Props: `apiBase` and `wsUrl` (where the app mounted the chat routes), `api` (partial overrides of the REST
35
+ * calls; every function not given keeps its default), `scope` (passed when creating a chat), `sx`.
36
+ */
37
+ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, sx }) {
38
+ const { t } = useTranslation();
39
+ const theme = useTheme();
40
+ const narrow = useMediaQuery(theme.breakpoints.down('md'));
41
+ const api = useMemo(() => createChatApi(apiOverrides, { apiBase }), [apiOverrides, apiBase]);
42
+
43
+ const [status, setStatus] = useState('loading'); // loading | available | not_configured | error
44
+ const [catalogue, setCatalogue] = useState({ entries: [], default: null });
45
+ const [chats, setChats] = useState([]);
46
+ const [archived, setArchived] = useState([]);
47
+ const [nextChats, setNextChats] = useState(null);
48
+ const [chat, setChat] = useState(null);
49
+ const [turns, setTurns] = useState([]);
50
+ const [olderCursor, setOlderCursor] = useState(null);
51
+ const [olderBusy, setOlderBusy] = useState(false);
52
+ const [tool, setTool] = useState(null);
53
+ const [draft, setDraft] = useState('');
54
+ const [problem, setProblem] = useState(null); // an error code or close reason, shown as a notice
55
+ const [listOpen, setListOpen] = useState(false);
56
+ const [pickerOpen, setPickerOpen] = useState(false);
57
+ const [openedOnce, setOpenedOnce] = useState(false); // distinguishes a reconnect from the first connect
58
+
59
+ const running = turns.some(isGenerating);
60
+ const isArchived = Boolean(chat?.archived_at);
61
+ const selection = chat?.selection || catalogue.default;
62
+ const activeEntry = catalogue.entries.find((entry) => entry.id === selection?.entry);
63
+
64
+ const loadLists = useCallback(async () => {
65
+ const [active, old] = await Promise.all([api.listChats(), api.listChats({ archived: true })]);
66
+ setChats(active.results || []);
67
+ setNextChats(active.next || null);
68
+ setArchived(old.results || []);
69
+ }, [api]);
70
+
71
+ useEffect(() => {
72
+ let live = true;
73
+ api.getStatus()
74
+ .then(async (state) => {
75
+ if (state.status !== 'available') { if (live) setStatus(state.status); return; }
76
+ const [entries] = await Promise.all([api.getCatalogue(), loadLists()]);
77
+ if (live) { setStatus(state.status); setCatalogue(entries); }
78
+ })
79
+ .catch(() => { if (live) setStatus('error'); });
80
+ return () => { live = false; };
81
+ }, [api, loadLists]);
82
+
83
+ useEffect(() => {
84
+ setTurns([]); setOlderCursor(null); setTool(null); setProblem(null); setDraft(''); setOpenedOnce(false);
85
+ if (!chat?.id) return undefined;
86
+ let live = true;
87
+ api.listTurns(chat.id)
88
+ .then((page) => { if (live) { setTurns(chronological(page.results)); setOlderCursor(page.next || null); } })
89
+ .catch(() => { if (live) setProblem('load_error'); });
90
+ return () => { live = false; };
91
+ }, [api, chat?.id]);
92
+
93
+ const onFrame = useCallback((frame, chatId) => {
94
+ if (chatId !== chat?.id) return;
95
+ if (frame.type === 'history') setTurns(chronological(frame.turns));
96
+ else if (frame.type === 'delta') setTurns((current) => appendDelta(current, frame.text || ''));
97
+ else if (frame.type === 'tool') setTool(frame.phase === 'start' ? { label: frame.label, name: frame.name } : null);
98
+ else if (frame.type === 'turn' && frame.turn) {
99
+ setTool(null);
100
+ setTurns((current) => settleTurn(current, frame.turn));
101
+ if (frame.turn.error_code === 'quota_exceeded') setProblem('quota_exceeded');
102
+ } else if (frame.type === 'error') {
103
+ setTool(null);
104
+ setTurns((current) => failGenerating(current, frame.code));
105
+ setProblem(frame.code);
106
+ }
107
+ }, [chat?.id]);
108
+ const onOpen = useCallback(() => { setOpenedOnce(true); setProblem((current) => (current === 'connection_lost' ? null : current)); }, []);
109
+ const onClose = useCallback(({ reason, retrying }) => { if (!retrying) setProblem(reason); }, []);
110
+ const socket = useChatSocket(chat?.id, { wsUrl, onFrame, onOpen, onClose });
111
+
112
+ const guarded = (action) => async (...args) => {
113
+ try { return await action(...args); } catch { setProblem('action_error'); return null; }
114
+ };
115
+
116
+ const selectChat = (next) => { setChat(next); setListOpen(false); };
117
+ const createChat = guarded(async () => {
118
+ const created = await api.createChat(scope ? { scope } : {});
119
+ setChats((current) => [created, ...current]);
120
+ selectChat(created);
121
+ });
122
+ const updateChat = guarded(async (target, patch) => {
123
+ const updated = await api.updateChat(target.id, patch);
124
+ if (chat?.id === target.id) setChat(updated);
125
+ await loadLists();
126
+ });
127
+ const deleteChat = guarded(async (target) => {
128
+ await api.deleteChat(target.id);
129
+ setChats((current) => current.filter((item) => item.id !== target.id));
130
+ setArchived((current) => current.filter((item) => item.id !== target.id));
131
+ if (chat?.id === target.id) setChat(null);
132
+ });
133
+ const loadMoreChats = guarded(async () => {
134
+ const page = await api.listChats({ cursor: nextChats });
135
+ setChats((current) => [...current, ...(page.results || [])]);
136
+ setNextChats(page.next || null);
137
+ });
138
+ const loadOlder = guarded(async () => {
139
+ setOlderBusy(true);
140
+ try {
141
+ const page = await api.listTurns(chat.id, { cursor: olderCursor });
142
+ setTurns((current) => chronological([...(page.results || []), ...current]));
143
+ setOlderCursor(page.next || null);
144
+ } finally { setOlderBusy(false); }
145
+ });
146
+
147
+ const startTurn = (message) => {
148
+ if (!socket.send({ type: 'send', message })) return false;
149
+ setProblem(null);
150
+ setTurns((current) => [...current, {
151
+ id: PENDING_ID, user_text: message, assistant_text: '', state: 'generating', sources: [],
152
+ driver: activeEntry?.driver, model: activeEntry?.label || activeEntry?.model, effort: selection?.effort,
153
+ }]);
154
+ return true;
155
+ };
156
+ const send = () => { if (startTurn(draft)) setDraft(''); };
157
+ const retry = (turn) => {
158
+ if (!socket.connected) return;
159
+ setTurns((current) => current.filter((item) => item.id !== turn.id));
160
+ startTurn(turn.user_text);
161
+ };
162
+
163
+ const noticeFor = () => {
164
+ const texts = {
165
+ session_ended: 'Chat.sessionEnded', access_lost: 'Chat.accessLost', rate_limited: 'Chat.rateLimited',
166
+ load_error: 'Chat.loadError', action_error: 'Chat.actionError',
167
+ };
168
+ if (problem === 'quota_exceeded') {
169
+ return { text: t('Chat.usageLimit', { model: activeEntry?.label || activeEntry?.model || '' }), action: { label: t('Chat.changeModel'), onClick: () => setPickerOpen(true) } };
170
+ }
171
+ if (problem === 'connection_lost') return { text: t('Chat.connectionLost'), action: { label: t('Chat.reconnect'), onClick: socket.reconnect } };
172
+ if (problem === 'not_configured') return null;
173
+ if (texts[problem]) return { text: t(texts[problem]), severity: 'warning' };
174
+ return null;
175
+ };
176
+
177
+ const list = (
178
+ <ChatList
179
+ chats={chats}
180
+ archivedChats={archived}
181
+ activeId={chat?.id}
182
+ hasMore={Boolean(nextChats)}
183
+ onSelect={selectChat}
184
+ onNew={createChat}
185
+ onRename={(target, title) => updateChat(target, { title })}
186
+ onArchive={(target) => updateChat(target, { archived: true })}
187
+ onRestore={(target) => updateChat(target, { archived: false })}
188
+ onDelete={deleteChat}
189
+ onLoadMore={loadMoreChats}
190
+ />
191
+ );
192
+
193
+ const unavailable = status === 'not_configured' || problem === 'not_configured';
194
+ if (status === 'loading') return <Box sx={sx} aria-busy="true" />;
195
+ if (status === 'error') return <Box sx={sx}><Alert severity="error">{t('Chat.loadError')}</Alert></Box>;
196
+ if (unavailable) {
197
+ return (
198
+ <Stack alignItems="center" justifyContent="center" spacing={1} sx={{ minHeight: 320, p: 3, textAlign: 'center', ...sx }}>
199
+ <Typography variant="h6">{t('Chat.unavailable')}</Typography>
200
+ <Typography color="text.secondary">{t('Chat.noModel')}</Typography>
201
+ </Stack>
202
+ );
203
+ }
204
+
205
+ return (
206
+ <Box sx={{ display: 'grid', gridTemplateColumns: narrow ? 'minmax(0, 1fr)' : 'minmax(240px, 320px) minmax(0, 1fr)', height: '100%', minHeight: 480, border: 1, borderColor: 'divider', borderRadius: 1, overflow: 'hidden', bgcolor: 'background.paper', ...sx }}>
207
+ {narrow ? null : <Box sx={{ borderRight: 1, borderColor: 'divider', minHeight: 0 }}>{list}</Box>}
208
+ <Stack sx={{ minWidth: 0, minHeight: 0 }}>
209
+ <Stack direction="row" alignItems="center" gap={1} sx={{ px: 1.5, py: 0.5, borderBottom: 1, borderColor: 'divider', minHeight: 56 }}>
210
+ {narrow ? <Button color="inherit" onClick={() => setListOpen(true)}>{t('Chat.chats')}</Button> : null}
211
+ <Typography noWrap sx={{ flex: 1, fontWeight: 600 }}>{chat ? (chat.title || t('Chat.untitled')) : ''}</Typography>
212
+ {socket.status === 'connecting' && openedOnce ? <Chip size="small" color="warning" variant="outlined" label={t('Chat.reconnecting')} /> : null}
213
+ {isArchived ? <Chip size="small" label={t('Chat.archived')} /> : null}
214
+ {isArchived ? <Button size="small" onClick={() => updateChat(chat, { archived: false })}>{t('Chat.restore')}</Button> : null}
215
+ {chat ? (
216
+ <ModelPicker
217
+ entries={catalogue.entries}
218
+ selection={selection}
219
+ disabled={isArchived || running}
220
+ open={pickerOpen}
221
+ onOpenChange={setPickerOpen}
222
+ onChange={(next) => updateChat(chat, { selection: next })}
223
+ />
224
+ ) : null}
225
+ </Stack>
226
+ {chat ? (
227
+ <>
228
+ <ChatThread turns={turns} tool={tool} notice={noticeFor()} hasOlder={Boolean(olderCursor)} olderBusy={olderBusy} onLoadOlder={loadOlder} onRetry={retry} readOnly={isArchived} />
229
+ {isArchived ? <Typography variant="caption" color="text.secondary" sx={{ px: 2, pb: 1 }}>{t('Chat.archivedReadOnly')}</Typography> : null}
230
+ <ChatComposer value={draft} onChange={setDraft} onSend={send} onStop={() => socket.send({ type: 'stop' })} running={running} archived={isArchived} connected={socket.connected} />
231
+ </>
232
+ ) : (
233
+ <Stack alignItems="center" justifyContent="center" spacing={2} sx={{ flex: 1, p: 3 }}>
234
+ <Typography color="text.secondary" align="center">{t('Chat.selectChat')}</Typography>
235
+ <Button variant="contained" onClick={createChat}>{t('Chat.newChat')}</Button>
236
+ </Stack>
237
+ )}
238
+ </Stack>
239
+ {narrow ? <Drawer open={listOpen} onClose={() => setListOpen(false)} slotProps={{ paper: { sx: { width: 'min(320px, 86vw)' } } }}>{list}</Drawer> : null}
240
+ </Box>
241
+ );
242
+ }
243
+
244
+ export default ChatWorkspace;
@@ -0,0 +1,22 @@
1
+ import React, { memo } from 'react';
2
+ import { Box } from '@mui/material';
3
+ import { useTranslation } from 'react-i18next';
4
+ import ReactMarkdown from 'react-markdown';
5
+ import remarkGfm from 'remark-gfm';
6
+
7
+ export const MARKDOWN_LIMIT = 200000;
8
+ const allowed = ['p','br','hr','h1','h2','h3','h4','h5','h6','strong','em','del','ul','ol','li','blockquote','code','pre','table','thead','tbody','tr','th','td','a','img'];
9
+ const plainText = (children) => (Array.isArray(children) ? children : [children]).map((child) => typeof child === 'string' ? child : '').join('');
10
+ function MarkdownReply({ text = '' }) {
11
+ const { t } = useTranslation();
12
+ if (text.length > MARKDOWN_LIMIT) return <Box sx={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{text}</Box>;
13
+ return <Box sx={{ minWidth: 0, overflowWrap: 'anywhere', '& p': { my: 1 }, '& table': { borderCollapse: 'collapse' }, '& th,& td': { border: 1, borderColor: 'divider', p: 1 }, '& pre': { overflowX: 'auto', bgcolor: 'action.hover', p: 1, borderRadius: 1 }, '& blockquote': { borderLeft: 2, borderColor: 'divider', pl: 1, color: 'text.secondary' } }}>
14
+ <ReactMarkdown remarkPlugins={[remarkGfm]} allowedElements={allowed} unwrapDisallowed components={{
15
+ a: ({ href, children }) => { const label = plainText(children); return <span>{children}{href && href !== label ? ' (' + href + ')' : ''}</span>; },
16
+ img: ({ alt, src }) => <span>{alt || src || ''}</span>,
17
+ table: ({ children }) => <Box role="region" tabIndex={0} aria-label={t('Chat.markdownTable')} sx={{ overflowX: 'auto', maxWidth: '100%' }}><table>{children}</table></Box>,
18
+ pre: ({ children }) => <pre tabIndex={0} aria-label={t('Chat.markdownCode')}>{children}</pre>,
19
+ }}>{text}</ReactMarkdown>
20
+ </Box>;
21
+ }
22
+ export default memo(MarkdownReply);