@micha.bigler/ui-core-micha 4.27.1 → 4.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.29.0 - UCM-CHAT-16
4
+
5
+ Chat opens at its end, no empty chat entries, usable thread on phones. Found in the Maana staging acceptance of 2026-11-03.
6
+
7
+ - **Opening position.** The thread's bottom pin could be lost on open: the scroll event of the first move to the (still estimated)
8
+ bottom arrives a frame later, when off-screen turns (`content-visibility`) have taken their real height, and was read as the
9
+ reader leaving the bottom. The thread now remembers the position it set itself and ignores that event; only the reader moving
10
+ away unpins, being near the bottom pins again. The scroll region sets `overflow-anchor: none` (browser scroll anchoring would
11
+ move it a second time). Position-on-prepend and follow-only-at-bottom are unchanged.
12
+ - **Empty chats.** `ChatWorkspace` does not list a chat that has no turn. "New chat" creates the chat as before but lists it only
13
+ from its first message on; pressing it while an empty chat is open (or exists) shows that chat instead of creating another.
14
+ Chats that still carry the server's default title ("New chat", not named by the person) are read once (first page of turns) and
15
+ hidden when empty; a failed read keeps the chat listed, a chat with a streaming or failed first turn is listed from the send.
16
+ - **Narrow screens (the workspace's narrow layout).** The thread keeps at least 45 % of the screen height, the header is 44 px, and
17
+ the composer notice (long-conversation banner) wraps below the small breakpoint instead of being cut mid-word; its action stays
18
+ beside it. From the small breakpoint up the notice is the one-line ellipsis as before.
19
+
20
+ No new props, no API change.
21
+
22
+ ## 4.28.0 - UCM-CHAT-15
23
+
24
+ New optional `ChatWorkspace` prop `onComposeStart({ chatId })`: called when the composer of a shown chat gains focus
25
+ and when its draft goes from empty to non-empty, once each until the draft is cleared again (sent or emptied); never
26
+ per keystroke and without re-rendering the workspace. `ChatComposer` takes the matching optional `onComposeStart()`.
27
+ A shown chat now costs one catalogue request: the general catalogue is requested only while no chat is shown (at start
28
+ only when no `activeChatId` names a chat, and again when the requested chat cannot be shown); the picker-open and
29
+ after-turn refreshes are unchanged.
30
+
3
31
  ## 4.27.1 - UCM-CHAT-14 follow-up
4
32
 
5
33
  The thread's bottom pin no longer depends on scroll events: switching chats re-pins explicitly, and the thread also
package/README.md CHANGED
@@ -222,6 +222,13 @@ codes it knows; return `null` for everything else:
222
222
  />
223
223
  ```
224
224
 
225
+ ## Shared chat: composer start signal
226
+
227
+ Since 4.28.0 `onComposeStart({ chatId })` tells the host that the person started composing in a chat: on the first
228
+ focus of the composer and when the draft goes from empty to non-empty, again after it was cleared. Use it to prepare
229
+ something before the send (for example a context-size check), not per keystroke. A shown chat requests its catalogue
230
+ once; the general catalogue is only requested while no chat is shown.
231
+
225
232
  ## Shared chat: host controls
226
233
 
227
234
  `ChatWorkspace` (from `@micha.bigler/ui-core-micha/chat`) takes optional props for apps that put UI around the surface;
@@ -25,7 +25,8 @@ export const CHAT_COMPOSER_ACTION_SX = { width: 36, height: 36, flex: '0 0 36px'
25
25
  // Send is the filled primary action of the input row, as in the prototype; Stop keeps the plain icon button.
26
26
  export const CHAT_COMPOSER_SEND_SX = Object.assign(Object.assign({}, CHAT_COMPOSER_ACTION_SX), { bgcolor: 'primary.main', color: 'primary.contrastText', '&:hover': { bgcolor: 'primary.dark' }, '&.Mui-disabled': { bgcolor: 'action.disabledBackground', color: 'action.disabled' } });
27
27
  export const CHAT_COMPOSER_NOTICE_SX = { display: 'flex', alignItems: 'center', gap: 0.75, minWidth: 0, minHeight: 32, px: 1, color: 'text.secondary', bgcolor: 'action.hover', borderRadius: 1 };
28
- export const CHAT_COMPOSER_NOTICE_TEXT_SX = { minWidth: 0, flex: '1 1 auto', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' };
28
+ // One line from the small breakpoint up; on a phone the text wraps instead of being cut mid-word, and its action stays beside it.
29
+ export const CHAT_COMPOSER_NOTICE_TEXT_SX = { minWidth: 0, flex: '1 1 auto', overflow: { xs: 'visible', sm: 'hidden' }, whiteSpace: { xs: 'normal', sm: 'nowrap' }, overflowWrap: 'anywhere', textOverflow: 'ellipsis', fontSize: { xs: '0.8125rem', sm: 'inherit' }, lineHeight: 1.3, py: { xs: 0.5, sm: 0 } };
29
30
  export const CHAT_COMPOSER_NOTICE_ACTION_SX = { flex: '0 0 auto', minWidth: 0, p: 0.25, whiteSpace: 'nowrap' };
30
31
  export const CHAT_COMPOSER_NOTICE_CLOSE_SX = { width: 28, height: 28, flex: '0 0 28px' };
31
32
  export const CHAT_COMPOSER_USAGE_METER_SX = { height: 3 };
@@ -49,12 +50,20 @@ function UsageLimit({ usageLimit, t, language }) {
49
50
  ? _jsxs(_Fragment, { children: [_jsx(Typography, { variant: "caption", color: "text.secondary", children: t(`Chat.limitReached.${usageLimit.period}`) }), _jsx(Typography, { variant: "caption", color: "text.secondary", children: t('Chat.limitResets', { date: resetDate }) })] })
50
51
  : _jsx(Typography, { variant: "caption", color: "text.secondary", children: usageText }), _jsx(LinearProgress, { variant: "determinate", "aria-label": usageText, value: reached ? 100 : Math.min(100, (usageLimit.usedUsdMicros / usageLimit.limitUsdMicros) * 100), sx: CHAT_COMPOSER_USAGE_METER_SX })] });
51
52
  }
52
- export function ChatComposer({ value, onChange, onSend, onStop, running = false, archived = false, connected = true, inputRef, sx, actions, layout = 'standard', context, notice, usageLimit = null, draftRequest, onDraftRequestApplied }) {
53
+ export function ChatComposer({ value, onChange, onSend, onStop, onComposeStart, running = false, archived = false, connected = true, inputRef, sx, actions, layout = 'standard', context, notice, usageLimit = null, draftRequest, onDraftRequestApplied }) {
53
54
  const { t, i18n } = useTranslation();
54
55
  const [internalDraft, setInternalDraft] = React.useState('');
55
56
  const appliedDraftRequest = React.useRef(undefined);
57
+ const focusSignalled = React.useRef(false);
58
+ const draftSignalled = React.useRef(false);
56
59
  const controlled = value !== undefined;
57
60
  const draft = controlled ? value : internalDraft;
61
+ React.useEffect(() => {
62
+ if (draft === '') {
63
+ focusSignalled.current = false;
64
+ draftSignalled.current = false;
65
+ }
66
+ }, [draft]);
58
67
  React.useLayoutEffect(() => {
59
68
  if (controlled || !draftRequest || draftRequest.seq === appliedDraftRequest.current)
60
69
  return;
@@ -66,17 +75,36 @@ export function ChatComposer({ value, onChange, onSend, onStop, running = false,
66
75
  const blocked = archived || !connected || limitReached;
67
76
  const language = typeof (i18n === null || i18n === void 0 ? void 0 : i18n.language) === 'string' ? i18n.language.split('_')[0] || undefined : undefined;
68
77
  const canSend = !running && !blocked && draft.trim().length > 0;
69
- const changeDraft = (next) => { if (controlled)
70
- onChange === null || onChange === void 0 ? void 0 : onChange(next);
71
- else
72
- setInternalDraft(next); };
78
+ const changeDraft = (next) => {
79
+ if (next === '') {
80
+ focusSignalled.current = false;
81
+ draftSignalled.current = false;
82
+ }
83
+ if (next !== '' && draft === '' && !draftSignalled.current) {
84
+ draftSignalled.current = true;
85
+ onComposeStart === null || onComposeStart === void 0 ? void 0 : onComposeStart();
86
+ }
87
+ if (controlled)
88
+ onChange === null || onChange === void 0 ? void 0 : onChange(next);
89
+ else
90
+ setInternalDraft(next);
91
+ };
92
+ const handleFocus = () => {
93
+ if (!focusSignalled.current) {
94
+ focusSignalled.current = true;
95
+ onComposeStart === null || onComposeStart === void 0 ? void 0 : onComposeStart();
96
+ }
97
+ };
73
98
  const submit = () => {
74
99
  if (!canSend)
75
100
  return;
76
101
  if (controlled)
77
102
  onSend === null || onSend === void 0 ? void 0 : onSend();
78
- else if ((onSend === null || onSend === void 0 ? void 0 : onSend(draft)) === true)
103
+ else if ((onSend === null || onSend === void 0 ? void 0 : onSend(draft)) === true) {
104
+ focusSignalled.current = false;
105
+ draftSignalled.current = false;
79
106
  setInternalDraft('');
107
+ }
80
108
  };
81
109
  const handleKeyDown = (event) => {
82
110
  var _a;
@@ -86,9 +114,9 @@ export function ChatComposer({ value, onChange, onSend, onStop, running = false,
86
114
  }
87
115
  };
88
116
  if (layout === 'compact')
89
- return (_jsxs(Stack, { sx: sx ? [CHAT_COMPOSER_COMPACT_ROOT_SX, sx] : CHAT_COMPOSER_COMPACT_ROOT_SX, children: [_jsx(CompactNotice, { notice: notice, t: t }), _jsx(UsageLimit, { usageLimit: usageLimit, t: t, language: language }), _jsxs(Stack, { direction: "row", alignItems: "center", sx: CHAT_COMPOSER_CONTEXT_ROW_SX, children: [_jsx(Box, { sx: CHAT_COMPOSER_CONTEXT_SX, children: context }), actions ? _jsx(Box, { sx: CHAT_COMPOSER_CONTEXT_ACTIONS_SX, children: actions }) : null] }), _jsxs(Stack, { direction: "row", alignItems: "flex-end", sx: CHAT_COMPOSER_INPUT_ROW_SX, children: [_jsx(TextField, { multiline: true, maxRows: 5, variant: "outlined", sx: CHAT_COMPOSER_COMPACT_FIELD_SX, size: "small", value: draft, inputRef: inputRef, disabled: blocked, placeholder: t('Chat.message'), slotProps: { htmlInput: { 'aria-label': t('Chat.message') } }, onChange: (event) => changeDraft(event.target.value), onKeyDown: handleKeyDown }), running
117
+ return (_jsxs(Stack, { sx: sx ? [CHAT_COMPOSER_COMPACT_ROOT_SX, sx] : CHAT_COMPOSER_COMPACT_ROOT_SX, children: [_jsx(CompactNotice, { notice: notice, t: t }), _jsx(UsageLimit, { usageLimit: usageLimit, t: t, language: language }), _jsxs(Stack, { direction: "row", alignItems: "center", sx: CHAT_COMPOSER_CONTEXT_ROW_SX, children: [_jsx(Box, { sx: CHAT_COMPOSER_CONTEXT_SX, children: context }), actions ? _jsx(Box, { sx: CHAT_COMPOSER_CONTEXT_ACTIONS_SX, children: actions }) : null] }), _jsxs(Stack, { direction: "row", alignItems: "flex-end", sx: CHAT_COMPOSER_INPUT_ROW_SX, children: [_jsx(TextField, { multiline: true, maxRows: 5, variant: "outlined", sx: CHAT_COMPOSER_COMPACT_FIELD_SX, size: "small", value: draft, inputRef: inputRef, disabled: blocked, placeholder: t('Chat.message'), slotProps: { htmlInput: { 'aria-label': t('Chat.message') } }, onFocus: handleFocus, onChange: (event) => changeDraft(event.target.value), onKeyDown: handleKeyDown }), running
90
118
  ? _jsx(IconButton, { "aria-label": t('Chat.stopAnswer'), title: t('Chat.stopAnswer'), sx: CHAT_COMPOSER_ACTION_SX, onClick: onStop, children: _jsx(StopIcon, {}) })
91
119
  : _jsx(IconButton, { "aria-label": t('Chat.send'), sx: CHAT_COMPOSER_SEND_SX, onClick: submit, disabled: !canSend, children: _jsx(SendIcon, { fontSize: "small" }) })] })] }));
92
- return (_jsxs(Stack, { direction: "row", alignItems: "flex-end", flexWrap: "wrap", gap: 1, sx: Object.assign(Object.assign({}, CHAT_COMPOSER_STANDARD_ROOT_SX), sx), children: [usageLimit ? _jsx(Stack, { flexBasis: "100%", children: _jsx(UsageLimit, { usageLimit: usageLimit, t: t, language: language }) }) : null, _jsx(TextField, { multiline: true, maxRows: 6, sx: CHAT_COMPOSER_INPUT_SX, size: "small", value: draft, inputRef: inputRef, disabled: blocked, placeholder: t('Chat.message'), slotProps: { htmlInput: { 'aria-label': t('Chat.message') } }, onChange: (event) => changeDraft(event.target.value), onKeyDown: handleKeyDown }), actions ? _jsx(Stack, { direction: "row", alignItems: "flex-end", children: actions }) : null, running ? _jsx(Button, { variant: "outlined", onClick: onStop, children: t('Chat.stop') }) : null, _jsx(Button, { variant: "contained", onClick: submit, disabled: !canSend, children: t('Chat.send') })] }));
120
+ return (_jsxs(Stack, { direction: "row", alignItems: "flex-end", flexWrap: "wrap", gap: 1, sx: Object.assign(Object.assign({}, CHAT_COMPOSER_STANDARD_ROOT_SX), sx), children: [usageLimit ? _jsx(Stack, { flexBasis: "100%", children: _jsx(UsageLimit, { usageLimit: usageLimit, t: t, language: language }) }) : null, _jsx(TextField, { multiline: true, maxRows: 6, sx: CHAT_COMPOSER_INPUT_SX, size: "small", value: draft, inputRef: inputRef, disabled: blocked, placeholder: t('Chat.message'), slotProps: { htmlInput: { 'aria-label': t('Chat.message') } }, onFocus: handleFocus, onChange: (event) => changeDraft(event.target.value), onKeyDown: handleKeyDown }), actions ? _jsx(Stack, { direction: "row", alignItems: "flex-end", children: actions }) : null, running ? _jsx(Button, { variant: "outlined", onClick: onStop, children: t('Chat.stop') }) : null, _jsx(Button, { variant: "contained", onClick: submit, disabled: !canSend, children: t('Chat.send') })] }));
93
121
  }
94
122
  export default ChatComposer;
@@ -3,7 +3,9 @@ import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
3
  import { Alert, Box, Button, Chip, Stack, Tooltip, Typography } from '@mui/material';
4
4
  import { useTranslation } from 'react-i18next';
5
5
  import MarkdownReply from './MarkdownReply';
6
- export const CHAT_THREAD_SCROLL_SX = { minHeight: 0, flex: 1, overflowY: 'auto', p: { xs: 1.5, md: 2.5 }, contain: 'strict' };
6
+ // overflowAnchor: the thread keeps its own position (bottom, or the reader's place after older turns are prepended); the browser's scroll anchoring
7
+ // would move it a second time whenever an off-screen turn takes its real height.
8
+ export const CHAT_THREAD_SCROLL_SX = { minHeight: 0, flex: 1, overflowY: 'auto', p: { xs: 1.5, md: 2.5 }, contain: 'strict', overflowAnchor: 'none' };
7
9
  export const CHAT_THREAD_TURN_SX = { mb: 3, contentVisibility: 'auto', containIntrinsicSize: 'auto 320px' };
8
10
  export const CHAT_THREAD_TOOL_CHIP_SX = { alignSelf: 'flex-start' };
9
11
  export const CHAT_THREAD_NOTICE_SX = { mb: 2 };
@@ -47,10 +49,21 @@ export function ChatThread({ turns = [], tool = null, notice = null, hasOlder =
47
49
  const scroller = useRef(null);
48
50
  const heightBeforeOlder = useRef(null);
49
51
  const pinned = useRef(true); // follow the stream only while the reader is at the bottom
52
+ // The scroll position this component set itself. The scroll event of such a move arrives a frame later, when off-screen turns may have
53
+ // taken their real height and the bottom moved away: that event must not be read as the reader leaving the bottom (UCM-CHAT-16).
54
+ const ownTop = useRef(null);
55
+ const scrollToEnd = () => { const el = scroller.current; if (!el)
56
+ return; el.scrollTop = el.scrollHeight; ownTop.current = el.scrollTop; };
50
57
  const last = turns[turns.length - 1];
51
58
  // Follow the stream, but only when new content arrives at the end (not when older turns are prepended).
52
- useEffect(() => { var _a, _b; if (pinned.current)
53
- (_b = (_a = end.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, { block: 'end' }); }, [last === null || last === void 0 ? void 0 : last.id, last === null || last === void 0 ? void 0 : last.assistant_text, last === null || last === void 0 ? void 0 : last.state]);
59
+ useEffect(() => {
60
+ var _a, _b;
61
+ if (!pinned.current)
62
+ return;
63
+ (_b = (_a = end.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, { block: 'end' });
64
+ if (scroller.current)
65
+ ownTop.current = scroller.current.scrollTop;
66
+ }, [last === null || last === void 0 ? void 0 : last.id, last === null || last === void 0 ? void 0 : last.assistant_text, last === null || last === void 0 ? void 0 : last.state]);
54
67
  // Turns skip layout off-screen (content-visibility, UCM-CHAT-14) and take their real height only once rendered, so the
55
68
  // content can still grow after the scroll above. While pinned, follow that growth to stay at the bottom. The scroll
56
69
  // region itself is observed too: a thread mounted in a hidden host panel gets its real size only when shown.
@@ -60,7 +73,7 @@ export function ChatThread({ turns = [], tool = null, notice = null, hasOlder =
60
73
  if (!el || !content.current || typeof ResizeObserver === 'undefined')
61
74
  return undefined;
62
75
  const observer = new ResizeObserver(() => { if (pinned.current)
63
- el.scrollTop = el.scrollHeight; });
76
+ scrollToEnd(); });
64
77
  observer.observe(content.current);
65
78
  observer.observe(el);
66
79
  return () => observer.disconnect();
@@ -97,7 +110,12 @@ export function ChatThread({ turns = [], tool = null, notice = null, hasOlder =
97
110
  let summaryRendered = false;
98
111
  return (_jsx(Box, { ref: scroller, onScroll: (event) => {
99
112
  const el = event.currentTarget;
100
- pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
113
+ const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
114
+ const own = ownTop.current !== null && Math.abs(el.scrollTop - ownTop.current) < 1;
115
+ if (atBottom)
116
+ pinned.current = true;
117
+ else if (!own)
118
+ pinned.current = false; // only the reader moving away leaves the bottom, not content growing under a move of ours
101
119
  if (hasOlder && !olderBusy && el.scrollTop <= 40)
102
120
  loadOlder();
103
121
  }, role: "log", "aria-live": "polite", "aria-label": t('Chat.thread'), sx: Object.assign(Object.assign({}, CHAT_THREAD_SCROLL_SX), sx), children: _jsxs("div", { ref: content, children: [hasOlder ? (_jsx(Box, { sx: { textAlign: 'center', mb: 2 }, children: _jsx(Button, { size: "small", onClick: loadOlder, disabled: olderBusy, children: t('Chat.loadOlder') }) })) : null, turns.length === 0 ? (_jsx(Typography, { variant: "h6", color: "text.secondary", align: "center", sx: { mt: 6 }, children: t('Chat.emptyTitle') })) : null, turns.map((turn, index) => {
@@ -64,8 +64,10 @@ const appendDelta = (turns, text) => {
64
64
  * `preloadedChats` (optional active-list response `{ scope, results, next }` already loaded for that exact scope), `sx`,
65
65
  * `renderTurnError({ turn, chat, retry })` (optional failed-turn message; return `null` to show the default alert).
66
66
  */
67
+ // On a phone the thread keeps at least half the screen: composer, notice and header take what is left (UCM-CHAT-16).
68
+ const CHAT_WORKSPACE_NARROW_THREAD_SX = { minHeight: '50vh' };
67
69
  export const CHAT_WORKSPACE_SIDE_PANEL_SX = { borderLeft: 1, borderColor: 'divider', minHeight: 0, overflow: 'auto', contain: 'strict' };
68
- export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloadedChats, sx, unavailableReasonText, sidePanel, sidePanelLabel, renderAnswerExtra, renderTurnError, renderComposerExtra, composerLayout = 'standard', renderComposerContext, onAppFrame, onNavigate, activeChatId, onActiveChatChange, composerPrefill, getSendContext, sendRequest, onSendRequestHandled, layout = 'viewport', compactBelow = 720, tokenBalance = null, usageToTokens, longChatTokens = 40000 }) {
70
+ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloadedChats, sx, unavailableReasonText, sidePanel, sidePanelLabel, renderAnswerExtra, renderTurnError, renderComposerExtra, composerLayout = 'standard', renderComposerContext, onAppFrame, onNavigate, activeChatId, onActiveChatChange, onComposeStart, composerPrefill, getSendContext, sendRequest, onSendRequestHandled, layout = 'viewport', compactBelow = 720, tokenBalance = null, usageToTokens, longChatTokens = 40000 }) {
69
71
  var _a;
70
72
  const { t } = useTranslation();
71
73
  const theme = useTheme();
@@ -76,6 +78,10 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
76
78
  const narrow = layout === 'compact' || (layout === 'container' ? containerNarrow : viewportNarrow);
77
79
  const appFrameCallback = useRef(onAppFrame);
78
80
  useEffect(() => { appFrameCallback.current = onAppFrame; }, [onAppFrame]);
81
+ const composeStartCallback = useRef(onComposeStart);
82
+ composeStartCallback.current = onComposeStart;
83
+ const composeChatRef = useRef(null);
84
+ const composeStart = useCallback(() => { var _a; return (_a = composeStartCallback.current) === null || _a === void 0 ? void 0 : _a.call(composeStartCallback, { chatId: composeChatRef.current }); }, []);
79
85
  useEffect(() => {
80
86
  if (layout !== 'container')
81
87
  return undefined;
@@ -95,6 +101,15 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
95
101
  // The chat the current catalogue was requested for: a general catalogue must never drive the stored selection of a chat.
96
102
  const [catalogueChatId, setCatalogueChatId] = useState(null);
97
103
  const [chats, setChats] = useState([]);
104
+ // Chats without a message are not listed (UCM-CHAT-16): the server creates the chat when "New chat" is pressed, the list shows it from its
105
+ // first message on. emptyIds are the chats known to be empty; emptyChecks remembers what was found per chat so each is read once.
106
+ const [emptyIds, setEmptyIds] = useState(() => new Set());
107
+ const emptyChecks = useRef(new Map()); // id -> 'pending' | 'empty' | 'used'
108
+ const markUsed = (id) => {
109
+ emptyChecks.current.set(id, 'used');
110
+ setEmptyIds((current) => { if (!current.has(id))
111
+ return current; const next = new Set(current); next.delete(id); return next; });
112
+ };
98
113
  const [archived, setArchived] = useState([]);
99
114
  const [nextChats, setNextChats] = useState(null);
100
115
  const [chat, setChat] = useState(null);
@@ -170,6 +185,13 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
170
185
  }
171
186
  }, [api]);
172
187
  const shownChatId = useRef(null);
188
+ const generalCatalogueRequested = useRef(false);
189
+ const requestGeneralCatalogue = useCallback(() => {
190
+ if (generalCatalogueRequested.current)
191
+ return null;
192
+ generalCatalogueRequested.current = true;
193
+ return refreshCatalogue();
194
+ }, [refreshCatalogue]);
173
195
  // Bumped on every scope change so that a list response of the previous scope is dropped.
174
196
  const scopeVersion = useRef(0);
175
197
  const limitRequest = useRef(0);
@@ -225,7 +247,9 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
225
247
  ? { results: offered.results, next: offered.next }
226
248
  : undefined;
227
249
  const statusRequest = Promise.resolve().then(() => (scope === undefined ? api.getStatus() : api.getStatus({ scope })));
228
- const catalogueRequest = Promise.resolve().then(() => api.getCatalogue());
250
+ const catalogueRequest = latestWantedId.current == null
251
+ ? Promise.resolve().then(() => requestGeneralCatalogue())
252
+ : Promise.resolve(null);
229
253
  const listsRequest = Promise.resolve().then(() => loadLists({ initial: true, preloaded }));
230
254
  // These may finish after an unavailable status; attach rejection handlers immediately and never expose their answers.
231
255
  catalogueRequest.catch(() => { });
@@ -240,11 +264,10 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
240
264
  return;
241
265
  }
242
266
  refreshLimit();
243
- Promise.all([catalogueRequest, listsRequest]).then(([entries, lists]) => {
267
+ Promise.all([catalogueRequest, listsRequest]).then(([, lists]) => {
244
268
  if (!live || lists === undefined)
245
269
  return;
246
270
  const { active, old } = lists;
247
- setCatalogue(entries);
248
271
  setChats(active.results || []);
249
272
  setNextChats(active.next || null);
250
273
  setArchived(old.results || []);
@@ -257,9 +280,19 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
257
280
  .catch(() => { if (live)
258
281
  setStatus('error'); });
259
282
  return () => { live = false; };
260
- }, [api, loadLists, refreshLimit, scope]);
261
- useEffect(() => { if ((chat === null || chat === void 0 ? void 0 : chat.id) !== undefined)
262
- refreshCatalogue(chat.id); }, [chat === null || chat === void 0 ? void 0 : chat.id, refreshCatalogue]);
283
+ }, [api, loadLists, refreshLimit, requestGeneralCatalogue, scope]);
284
+ // Once a chat was shown, closing it needs the general catalogue again (also when that chat's own request failed);
285
+ // before any chat was shown, the start effect has already decided about the general request.
286
+ const chatWasShown = useRef(false);
287
+ useEffect(() => {
288
+ if ((chat === null || chat === void 0 ? void 0 : chat.id) !== undefined) {
289
+ chatWasShown.current = true;
290
+ generalCatalogueRequested.current = false;
291
+ refreshCatalogue(chat.id);
292
+ }
293
+ else if (!generalCatalogueRequested.current && chatWasShown.current)
294
+ requestGeneralCatalogue();
295
+ }, [chat === null || chat === void 0 ? void 0 : chat.id, refreshCatalogue, requestGeneralCatalogue]);
263
296
  useEffect(() => { if (pickerOpen)
264
297
  refreshCatalogue(chat === null || chat === void 0 ? void 0 : chat.id); }, [pickerOpen]);
265
298
  useEffect(() => {
@@ -296,22 +329,26 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
296
329
  if (!live || loaded === undefined || latestWantedId.current === undefined || String(latestWantedId.current) !== wantedKey)
297
330
  return;
298
331
  const found = loaded.all.find((item) => String(item.id) === wantedKey);
299
- if (!found)
332
+ if (!found) {
300
333
  unloadableIds.current.add(wantedKey);
334
+ requestGeneralCatalogue();
335
+ }
301
336
  setChat(found || null);
302
337
  }).catch(() => {
303
338
  if (live && latestWantedId.current !== undefined && String(latestWantedId.current) === wantedKey) {
304
339
  unloadableIds.current.add(wantedKey);
340
+ requestGeneralCatalogue();
305
341
  setChat(null);
306
342
  }
307
343
  });
308
344
  return () => { live = false; };
309
- }, [activeChatId, status, listsLoaded]);
345
+ }, [activeChatId, status, listsLoaded, requestGeneralCatalogue]);
310
346
  // Clear the previous chat's content before the browser paints, so a host-driven switch never flashes it under the new title.
311
347
  useLayoutEffect(() => {
312
- var _a;
348
+ var _a, _b;
313
349
  connectedChatId.current = null; // the socket of the new chat has not opened yet
314
350
  shownChatId.current = (_a = chat === null || chat === void 0 ? void 0 : chat.id) !== null && _a !== void 0 ? _a : null;
351
+ composeChatRef.current = (_b = chat === null || chat === void 0 ? void 0 : chat.id) !== null && _b !== void 0 ? _b : null;
315
352
  setTurns([]);
316
353
  setOlderCursor(null);
317
354
  setTool(null);
@@ -334,6 +371,27 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
334
371
  setProblem('load_error'); });
335
372
  return () => { live = false; };
336
373
  }, [api, chat === null || chat === void 0 ? void 0 : chat.id]);
374
+ // Chats that still carry the server's default title may be empty ones left behind by earlier "New chat" presses: read their first
375
+ // page once and keep the empty ones out of the list. A failed read keeps the chat listed (never hide what might hold a conversation).
376
+ useEffect(() => {
377
+ const untitled = (item) => !item.title || (item.title === 'New chat' && item.title_source !== 'user');
378
+ [...chats, ...archived].filter(untitled).forEach((item) => {
379
+ if (emptyChecks.current.has(item.id))
380
+ return;
381
+ emptyChecks.current.set(item.id, 'pending');
382
+ api.listTurns(item.id)
383
+ .then((page) => {
384
+ if (emptyChecks.current.get(item.id) !== 'pending')
385
+ return; // a first message was sent meanwhile
386
+ const empty = !((page === null || page === void 0 ? void 0 : page.results) || []).length && !(page === null || page === void 0 ? void 0 : page.next);
387
+ emptyChecks.current.set(item.id, empty ? 'empty' : 'used');
388
+ if (empty)
389
+ setEmptyIds((current) => new Set(current).add(item.id));
390
+ })
391
+ .catch(() => { if (emptyChecks.current.get(item.id) === 'pending')
392
+ emptyChecks.current.set(item.id, 'used'); });
393
+ });
394
+ }, [api, chats, archived]);
337
395
  const onFrame = useCallback((frame, chatId) => {
338
396
  var _a;
339
397
  if (chatId !== (chat === null || chat === void 0 ? void 0 : chat.id))
@@ -467,8 +525,19 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
467
525
  }
468
526
  };
469
527
  const selectChat = (next) => { setChat(next); setListOpen(false); };
528
+ // "New chat" while an empty chat is open (or exists) shows that one instead of creating another.
470
529
  const createChat = guarded(async () => {
530
+ // Only a list of the current scope may offer a chat: after a scope change the old list stays until the new one has loaded.
531
+ const reusable = chat && emptyIds.has(chat.id) && !running ? chat : (listsLoaded ? chats.find((item) => emptyIds.has(item.id)) : undefined);
532
+ if (reusable) {
533
+ selectChat(reusable);
534
+ focusPending.current = true;
535
+ setFocusRequest((count) => count + 1);
536
+ return;
537
+ }
471
538
  const created = await api.createChat(scope !== undefined ? { scope } : {});
539
+ emptyChecks.current.set(created.id, 'empty');
540
+ setEmptyIds((current) => new Set(current).add(created.id));
472
541
  setChats((current) => [created, ...current]);
473
542
  selectChat(created);
474
543
  });
@@ -525,6 +594,8 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
525
594
  if (!socket.send(built.frame))
526
595
  return false;
527
596
  setProblem(null);
597
+ if (chat)
598
+ markUsed(chat.id);
528
599
  setTurns((current) => [...current, {
529
600
  id: PENDING_ID, user_text: message, assistant_text: '', state: 'generating', sources: [],
530
601
  driver: activeEntry === null || activeEntry === void 0 ? void 0 : activeEntry.driver, model: (activeEntry === null || activeEntry === void 0 ? void 0 : activeEntry.label) || (activeEntry === null || activeEntry === void 0 ? void 0 : activeEntry.model), effort: selection === null || selection === void 0 ? void 0 : selection.effort,
@@ -569,7 +640,7 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
569
640
  return { text: t(texts[problem]), severity: 'warning' };
570
641
  return null;
571
642
  };
572
- const list = (_jsx(ChatList, { chats: chats, archivedChats: archived, activeId: chat === null || chat === void 0 ? void 0 : chat.id, hasMore: Boolean(nextChats), onSelect: selectChat, onNew: createChat, onRename: (target, title) => updateChat(target, { title }), onArchive: (target) => updateChat(target, { archived: true }), onRestore: (target) => updateChat(target, { archived: false }), onDelete: deleteChat, onLoadMore: loadMoreChats }));
643
+ const list = (_jsx(ChatList, { chats: chats.filter((item) => !emptyIds.has(item.id)), archivedChats: archived.filter((item) => !emptyIds.has(item.id)), activeId: chat === null || chat === void 0 ? void 0 : chat.id, hasMore: Boolean(nextChats), onSelect: selectChat, onNew: createChat, onRename: (target, title) => updateChat(target, { title }), onArchive: (target) => updateChat(target, { archived: true }), onRestore: (target) => updateChat(target, { archived: false }), onDelete: deleteChat, onLoadMore: loadMoreChats }));
573
644
  const notConfigured = status === 'not_configured' || problem === 'not_configured';
574
645
  const unavailable = status === 'unavailable' || problem === 'unavailable';
575
646
  const unavailableText = typeof unavailableReasonText === 'function' ? unavailableReasonText(unavailableReason) : unavailableReasonText === null || unavailableReasonText === void 0 ? void 0 : unavailableReasonText[unavailableReason];
@@ -583,7 +654,7 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloa
583
654
  if (unavailable) {
584
655
  return (_jsx(Stack, { alignItems: "center", justifyContent: "center", spacing: 1, sx: Object.assign({ minHeight: 320, p: 3, textAlign: 'center' }, sx), children: _jsx(Typography, { color: "text.secondary", children: unavailableText || t('Chat.notAvailableHere') }) }));
585
656
  }
586
- return (_jsxs(Box, { ref: rootRef, sx: Object.assign({ display: 'grid', gridTemplateColumns: narrow ? 'minmax(0, 1fr)' : `minmax(240px, 320px) minmax(0, 1fr)${chat && sidePanel ? ' minmax(240px, 320px)' : ''}`, height: '100%', minHeight: 480, border: 1, borderColor: 'divider', borderRadius: 1, overflow: 'hidden', bgcolor: 'background.paper' }, sx), children: [narrow ? null : _jsx(Box, { sx: { borderRight: 1, borderColor: 'divider', minHeight: 0 }, children: list }), _jsxs(Stack, { sx: { minWidth: 0, minHeight: 0 }, children: [_jsxs(Stack, { direction: "row", alignItems: "center", gap: 1, sx: { px: 1.5, py: 0.5, borderBottom: 1, borderColor: 'divider', minHeight: 56 }, children: [narrow ? _jsx(Button, { color: "inherit", onClick: () => setListOpen(true), children: t('Chat.chats') }) : null, _jsx(Typography, { noWrap: true, sx: { flex: 1, fontWeight: 600 }, children: chat ? (chat.title || t('Chat.untitled')) : '' }), socket.status === 'connecting' && openedOnce ? _jsx(Chip, { size: "small", color: "warning", variant: "outlined", label: t('Chat.reconnecting') }) : null, isArchived ? _jsx(Chip, { size: "small", label: t('Chat.archived') }) : null, isArchived ? _jsx(Button, { size: "small", onClick: () => updateChat(chat, { archived: false }), children: t('Chat.restore') }) : null, chat && sidePanel && narrow ? _jsx(Button, { color: "inherit", onClick: () => setSidePanelOpen(true), children: sidePanelLabel || t('Chat.sidePanel') }) : null] }), chat ? (_jsxs(_Fragment, { children: [_jsx(ChatThread, { turns: turns, chat: chat, renderAnswerExtra: answerExtra, renderTurnError: renderTurnError, tool: tool, notice: noticeFor(), hasOlder: Boolean(olderCursor), olderBusy: olderBusy, onLoadOlder: loadOlder, onRetry: retry, readOnly: isArchived, summary: summary, usageToTokens: usageToTokens, onNavigate: onNavigate }), isArchived ? _jsx(Typography, { variant: "caption", color: "text.secondary", sx: { px: 2, pb: 1 }, children: t('Chat.archivedReadOnly') }) : null, renderComposerExtra ? _jsx(Box, { children: renderComposerExtra({ chat }) }, chat.id) : null, composerLayout !== 'compact' && longChat ? _jsx(Alert, { severity: "info", action: _jsx(Button, { color: "inherit", size: "small", onClick: createChat, children: t('Chat.newConversation') }), children: t('Chat.longChat') }) : null, _jsx(ChatComposer, { layout: composerLayout, context: composerLayout === 'compact' ? renderComposerContext === null || renderComposerContext === void 0 ? void 0 : renderComposerContext({ chat }) : undefined, notice: composerLayout === 'compact' && longChat && !dismissedComposerNotices.has(`${chat.id}:long-chat`) ? {
657
+ return (_jsxs(Box, { ref: rootRef, sx: Object.assign({ display: 'grid', gridTemplateColumns: narrow ? 'minmax(0, 1fr)' : `minmax(240px, 320px) minmax(0, 1fr)${chat && sidePanel ? ' minmax(240px, 320px)' : ''}`, height: '100%', minHeight: 480, border: 1, borderColor: 'divider', borderRadius: 1, overflow: 'hidden', bgcolor: 'background.paper' }, sx), children: [narrow ? null : _jsx(Box, { sx: { borderRight: 1, borderColor: 'divider', minHeight: 0 }, children: list }), _jsxs(Stack, { sx: { minWidth: 0, minHeight: 0 }, children: [_jsxs(Stack, { direction: "row", alignItems: "center", gap: 1, sx: { px: 1.5, py: 0.5, borderBottom: 1, borderColor: 'divider', minHeight: narrow ? 44 : 56 }, children: [narrow ? _jsx(Button, { color: "inherit", onClick: () => setListOpen(true), children: t('Chat.chats') }) : null, _jsx(Typography, { noWrap: true, sx: { flex: 1, fontWeight: 600 }, children: chat ? (chat.title || t('Chat.untitled')) : '' }), socket.status === 'connecting' && openedOnce ? _jsx(Chip, { size: "small", color: "warning", variant: "outlined", label: t('Chat.reconnecting') }) : null, isArchived ? _jsx(Chip, { size: "small", label: t('Chat.archived') }) : null, isArchived ? _jsx(Button, { size: "small", onClick: () => updateChat(chat, { archived: false }), children: t('Chat.restore') }) : null, chat && sidePanel && narrow ? _jsx(Button, { color: "inherit", onClick: () => setSidePanelOpen(true), children: sidePanelLabel || t('Chat.sidePanel') }) : null] }), chat ? (_jsxs(_Fragment, { children: [_jsx(ChatThread, { sx: narrow ? CHAT_WORKSPACE_NARROW_THREAD_SX : undefined, turns: turns, chat: chat, renderAnswerExtra: answerExtra, renderTurnError: renderTurnError, tool: tool, notice: noticeFor(), hasOlder: Boolean(olderCursor), olderBusy: olderBusy, onLoadOlder: loadOlder, onRetry: retry, readOnly: isArchived, summary: summary, usageToTokens: usageToTokens, onNavigate: onNavigate }), isArchived ? _jsx(Typography, { variant: "caption", color: "text.secondary", sx: { px: 2, pb: 1 }, children: t('Chat.archivedReadOnly') }) : null, renderComposerExtra ? _jsx(Box, { children: renderComposerExtra({ chat }) }, chat.id) : null, composerLayout !== 'compact' && longChat ? _jsx(Alert, { severity: "info", action: _jsx(Button, { color: "inherit", size: "small", onClick: createChat, children: t('Chat.newConversation') }), children: t('Chat.longChat') }) : null, _jsx(ChatComposer, { layout: composerLayout, onComposeStart: composeStart, context: composerLayout === 'compact' ? renderComposerContext === null || renderComposerContext === void 0 ? void 0 : renderComposerContext({ chat }) : undefined, notice: composerLayout === 'compact' && longChat && !dismissedComposerNotices.has(`${chat.id}:long-chat`) ? {
587
658
  id: 'long-chat', text: t('Chat.longChatShort'), action: t('Chat.newChat'), onAction: createChat,
588
659
  onDismiss: () => setDismissedComposerNotices((current) => new Set(current).add(`${chat.id}:long-chat`)),
589
660
  } : null, draftRequest: (draftRequest === null || draftRequest === void 0 ? void 0 : draftRequest.chatId) === chat.id ? draftRequest : null, onDraftRequestApplied: onDraftRequestApplied, onSend: (text) => startTurn(text), onStop: () => socket.send({ type: 'stop' }), running: running, archived: isArchived, connected: socket.connected, inputRef: composerInputRef, usageLimit: usageLimit, actions: _jsx(ModelPicker, { entries: catalogue.entries, selection: selection, disabled: isArchived || running || (catalogueLoading && catalogueChatId !== chat.id), open: pickerOpen, onOpenChange: setPickerOpen, onChange: (next) => updateChat(chat, { selection: next }), balance: tokenBalance, shortLabel: composerLayout === 'compact' }) }, `composer-${chat.id}`)] })) : (_jsxs(Stack, { alignItems: "center", justifyContent: "center", spacing: 2, sx: { flex: 1, p: 3 }, children: [_jsx(Typography, { color: "text.secondary", align: "center", children: t('Chat.selectChat') }), _jsx(Button, { variant: "contained", onClick: createChat, children: t('Chat.newChat') })] }))] }), chat && sidePanel && !narrow ? _jsx(Box, { sx: CHAT_WORKSPACE_SIDE_PANEL_SX, children: sidePanel(chat) }, chat.id) : null, narrow && chat && sidePanel ? _jsx(Drawer, { anchor: "right", open: sidePanelOpen, onClose: () => setSidePanelOpen(false), slotProps: { paper: { 'aria-label': sidePanelLabel || t('Chat.sidePanel') } }, children: _jsx(Box, { children: sidePanel(chat) }, chat.id) }) : null, narrow ? _jsx(Drawer, { open: listOpen, onClose: () => setListOpen(false), slotProps: { paper: { sx: { width: 'min(320px, 86vw)' } } }, children: list }) : null] }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "4.27.1",
3
+ "version": "4.29.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "exports": {
@@ -71,13 +71,13 @@
71
71
  "@mui/x-charts": "^8.29.3",
72
72
  "@testing-library/react": "^16.3.3",
73
73
  "@vitejs/plugin-react": "^6.1.2",
74
- "i18next": "^26.4.2",
75
- "jsdom": "^30.1.2",
76
- "react-i18next": "^17.0.16",
74
+ "i18next": "^26.5.11",
75
+ "jsdom": "^30.1.3",
76
+ "react-i18next": "^17.1.9",
77
77
  "react-markdown": "^10.1.0",
78
78
  "remark-gfm": "^4.0.1",
79
79
  "typescript": "^7.0.2",
80
- "vite": "^8.3.4",
81
- "vitest": "^5.0.3"
80
+ "vite": "^8.3.5",
81
+ "vitest": "^5.0.5"
82
82
  }
83
83
  }