-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathChatComposer.tsx
More file actions
431 lines (428 loc) · 18 KB
/
Copy pathChatComposer.tsx
File metadata and controls
431 lines (428 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { KvStrategyChip } from "../../components/KvStrategyChip";
import { SamplerPanel } from "../../components/SamplerPanel";
import { TemperatureChip } from "../../components/TemperatureChip";
import type { ChatSession, ChatThinkingMode, LaunchPreferences, ModelCapabilities, SamplerOverrides, SystemStats, WarmModel } from "../../types";
import { MidThreadSwapMenu } from "./MidThreadSwapMenu";
import type { KvStrategyOverride } from "./kvStrategyOverride";
import type { SlashCommand } from "./slashCommands";
import { ChatComposerDflashHint } from "./ChatComposerDflashHint";
/**
* Phase 2.1: extracted from ChatTab.tsx. The composer area — image
* previews, slash-command popover, textarea, attach / thinking effort /
* tools / send / stop buttons, plus the per-thread temperature chip.
*
* Slash-menu state and the temperature override are owned by the
* parent (ChatTab) so the data flow stays unidirectional and so other
* consumers (e.g. the upcoming compare view) can reuse the chip
* without re-implementing the localStorage glue.
*/
export type ReasoningEffortLevel = "low" | "medium" | "high";
export interface ChatComposerProps {
draftMessage: string;
pendingImages: string[];
loadedModelRef: string | undefined;
loadedModelCapabilities?: ModelCapabilities | null;
thinkingMode: ChatThinkingMode;
reasoningEffort: ReasoningEffortLevel;
enableTools: boolean;
chatBusySessionId: string | null;
activeChat: ChatSession | undefined;
warmModels: WarmModel[];
oneTurnOverride: WarmModel | null;
onOneTurnOverrideChange: (warm: WarmModel | null) => void;
launchSettings: LaunchPreferences;
temperatureOverride: number | null;
samplerOverrides: SamplerOverrides;
/** Phase 3.2: per-thread KV strategy override (null = use session default). */
kvStrategyOverride: KvStrategyOverride | null;
onKvStrategyOverrideChange: (override: KvStrategyOverride | null) => void;
/** Phase 3.2: list of installable cache strategies for the picker. */
availableCacheStrategies: SystemStats["availableCacheStrategies"];
/** Phase 3.2 hotfix: loaded model's engine, used to filter the picker. */
loadedModelEngine?: string | null;
showSlashMenu: boolean;
slashMatches: SlashCommand[];
slashIndex: number;
setSlashIndex: Dispatch<SetStateAction<number>>;
onDraftMessageChange: (message: string) => void;
onPendingImagesChange: Dispatch<SetStateAction<string[]>>;
onSendMessage: () => void;
onCancelGeneration: () => void;
onClearDraft: () => void;
onChatFileDrop: (files: FileList) => void;
onToggleTools: (enabled: boolean) => void;
onSetError: (msg: string | null) => void;
onTemperatureOverrideChange: (value: number | null) => void;
onSamplerOverridesChange: (overrides: SamplerOverrides) => void;
runSlashCommand: (cmd: SlashCommand) => void;
handleEffortOff: () => void;
handleEffortChange: (level: ReasoningEffortLevel) => void;
// FU-056 Phase 5: optional DFlash install nudge. The composer shows
// an inline "Install DFlash" hint when (a) the loaded model has a
// registered draft, (b) the package isn't installed yet on the
// active backend, and (c) the user is on a backend that supports
// it. All three props must be present for the hint to render —
// omit any to silently hide the affordance.
dflashInfo?: SystemStats["dflash"];
loadedModelCanonicalRepo?: string | null;
loadedModelName?: string | null;
onInstallPackage?: (pipPackage: string) => void;
installingPackage?: string | null;
}
export function ChatComposer({
draftMessage,
pendingImages,
loadedModelRef,
loadedModelCapabilities,
thinkingMode,
reasoningEffort,
enableTools,
chatBusySessionId,
activeChat,
warmModels,
oneTurnOverride,
onOneTurnOverrideChange,
launchSettings,
temperatureOverride,
samplerOverrides,
kvStrategyOverride,
onKvStrategyOverrideChange,
availableCacheStrategies,
loadedModelEngine,
showSlashMenu,
slashMatches,
slashIndex,
setSlashIndex,
onDraftMessageChange,
onPendingImagesChange,
onSendMessage,
onCancelGeneration,
onClearDraft,
onChatFileDrop,
onToggleTools,
onSetError,
onTemperatureOverrideChange,
onSamplerOverridesChange,
runSlashCommand,
handleEffortOff,
handleEffortChange,
dflashInfo,
loadedModelCanonicalRepo,
loadedModelName,
onInstallPackage,
installingPackage,
}: ChatComposerProps) {
// FU-042: chat surface uses the ``chat`` namespace for prompt /
// affordance copy, falling back to literal English when a key isn't
// present yet. Hook lives at the top so every render gets a stable
// ``t`` reference (re-renders only when the active language flips).
const { t } = useTranslation("chat");
// Phase 2.11: when capabilities are known, hide affordances the loaded
// model can't honour. When capabilities are absent (unknown model or
// freshly downloaded HF entry without a catalog mapping) all
// affordances stay visible so the user isn't blocked from trying.
const showImageAttach = !loadedModelCapabilities || loadedModelCapabilities.supportsVision;
const showToolsToggle = !loadedModelCapabilities || loadedModelCapabilities.supportsTools;
const showThinkingControl = !loadedModelCapabilities || loadedModelCapabilities.supportsReasoning;
return (
<div className="composer">
{pendingImages.length > 0 ? (
<div className="composer-image-previews">
{pendingImages.map((img, i) => (
<div key={i} className="composer-image-thumb">
<img src={`data:image/png;base64,${img}`} alt={`Attachment ${i + 1}`} />
<button
className="composer-image-remove"
type="button"
onClick={() => onPendingImagesChange((prev) => prev.filter((_, j) => j !== i))}
>
×
</button>
</div>
))}
</div>
) : null}
<div className="composer-input-wrap">
{showSlashMenu ? (
<div
className="slash-command-menu"
role="listbox"
aria-label={t("slashCommands.menuAriaLabel", { defaultValue: "Slash commands" })}
>
{slashMatches.map((cmd, idx) => (
<button
key={cmd.command}
type="button"
role="option"
aria-selected={idx === slashIndex}
className={`slash-command-menu__item${idx === slashIndex ? " slash-command-menu__item--active" : ""}`}
onMouseEnter={() => setSlashIndex(idx)}
onClick={() => runSlashCommand(cmd)}
>
<span className="slash-command-menu__command">{cmd.command}</span>
<span className="slash-command-menu__desc">{cmd.description}</span>
</button>
))}
</div>
) : null}
{/* FU-056 Phase 5: DFlash install nudge above the textarea.
Self-gating — renders nothing when conditions aren't met
(no draft for this model, package already installed,
unsupported backend, missing dispatcher). */}
<ChatComposerDflashHint
dflashInfo={dflashInfo}
loadedModelEngine={loadedModelEngine}
loadedModelRef={loadedModelRef}
loadedModelCanonicalRepo={loadedModelCanonicalRepo}
loadedModelName={loadedModelName}
onInstallPackage={onInstallPackage}
installingPackage={installingPackage}
/>
<textarea
className="text-area"
placeholder={
loadedModelRef
? t("composer.placeholderReady", {
defaultValue: "Type a message... (Enter to send, Shift+Enter for new line, / for commands)",
})
: t("composer.placeholderNoModel", {
defaultValue: "Load a model first — pick one from My Models or Discover, then hit CHAT.",
})
}
rows={3}
value={draftMessage}
onChange={(event) => onDraftMessageChange(event.target.value)}
onKeyDown={(event) => {
// FU-042: when an IME composition is active (Japanese / Pinyin
// Chinese / Korean Hangul), the Enter key confirms the
// composition and must NOT trigger send / slash-pick. Browsers
// surface this via `event.nativeEvent.isComposing` (modern path)
// or `event.keyCode === 229` (legacy Webkit / older Safari).
// Guard both for safety — premature send on a half-typed
// Japanese sentence is the canonical "this app feels broken on
// CJK" experience and easy to ship by accident.
const isComposing = event.nativeEvent.isComposing || event.keyCode === 229;
if (showSlashMenu) {
if (event.key === "ArrowDown") {
event.preventDefault();
setSlashIndex((current) => (current + 1) % slashMatches.length);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setSlashIndex((current) => (current - 1 + slashMatches.length) % slashMatches.length);
return;
}
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault();
const target = slashMatches[slashIndex];
if (target) runSlashCommand(target);
return;
}
if (event.key === "Escape") {
event.preventDefault();
onDraftMessageChange("");
return;
}
if (event.key === "Tab") {
event.preventDefault();
const target = slashMatches[slashIndex];
if (target) onDraftMessageChange(`${target.command} `);
return;
}
}
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault();
// Mirror the Send button's disabled state — no-op when no
// model is loaded so users don't trigger a confusing 500.
if (!loadedModelRef) return;
void onSendMessage();
}
}}
onDrop={(event) => {
const files = event.dataTransfer?.files;
if (!files?.length) return;
event.preventDefault();
void onChatFileDrop(files);
}}
onDragOver={(event) => event.preventDefault()}
/>
</div>
<div className="button-row composer-button-row">
<div className="composer-button-group composer-button-group--left">
{showImageAttach ? (
<label
className="secondary-button composer-attach-btn"
title={t("attachments.image", { defaultValue: "Attach image" })}
>
<input
type="file"
accept="image/*"
multiple
hidden
onChange={(event) => {
const files = event.target.files;
if (!files) return;
for (const file of Array.from(files)) {
if (file.size > 10 * 1024 * 1024) {
onSetError(t("attachments.imageTooLarge", { defaultValue: "Image must be under 10MB" }));
continue;
}
const reader = new FileReader();
reader.onload = () => {
const b64 = (reader.result as string).split(",")[1];
if (b64) onPendingImagesChange((prev) => [...prev, b64]);
};
reader.readAsDataURL(file);
}
event.target.value = "";
}}
/>
{"📎"}
</label>
) : null}
{showThinkingControl ? (
<div
className="composer-mode-control"
title={t("thinkingMode.tooltip", {
defaultValue:
"Choose how much reasoning the model performs before answering. Off = direct answers; Low / Medium / High = increasing reasoning depth for capable models.",
})}
>
<span className="composer-mode-label">
{t("thinkingMode.label", { defaultValue: "Thinking" })}
</span>
<div
className="thread-mode-toggle composer-thinking-toggle"
role="group"
aria-label={t("thinkingMode.label", { defaultValue: "Thinking mode" })}
>
<button
type="button"
className={`thread-mode-button${thinkingMode === "off" ? " thread-mode-button--active" : ""}`}
disabled={chatBusySessionId === activeChat?.id}
onClick={handleEffortOff}
title={t("thinkingMode.offTooltip", { defaultValue: "No reasoning — model answers directly" })}
>
{t("thinkingMode.off", { defaultValue: "Off" })}
</button>
<button
type="button"
className={`thread-mode-button${thinkingMode === "auto" && reasoningEffort === "low" ? " thread-mode-button--active" : ""}`}
disabled={chatBusySessionId === activeChat?.id}
onClick={() => handleEffortChange("low")}
title={t("thinkingMode.lowTooltip", { defaultValue: "Brief reasoning" })}
>
{t("thinkingMode.low", { defaultValue: "Low" })}
</button>
<button
type="button"
className={`thread-mode-button${thinkingMode === "auto" && reasoningEffort === "medium" ? " thread-mode-button--active" : ""}`}
disabled={chatBusySessionId === activeChat?.id}
onClick={() => handleEffortChange("medium")}
title={t("thinkingMode.mediumTooltip", { defaultValue: "Default reasoning depth" })}
>
{t("thinkingMode.medium", { defaultValue: "Med" })}
</button>
<button
type="button"
className={`thread-mode-button${thinkingMode === "auto" && reasoningEffort === "high" ? " thread-mode-button--active" : ""}`}
disabled={chatBusySessionId === activeChat?.id}
onClick={() => handleEffortChange("high")}
title={t("thinkingMode.highTooltip", { defaultValue: "Extended reasoning" })}
>
{t("thinkingMode.high", { defaultValue: "High" })}
</button>
</div>
</div>
) : null}
<TemperatureChip
defaultValue={launchSettings.temperature}
override={temperatureOverride}
onChange={onTemperatureOverrideChange}
disabled={chatBusySessionId === activeChat?.id}
/>
<SamplerPanel
overrides={samplerOverrides}
onChange={onSamplerOverridesChange}
disabled={chatBusySessionId === activeChat?.id}
/>
<KvStrategyChip
override={kvStrategyOverride}
defaultStrategy={activeChat?.cacheStrategy ?? launchSettings.cacheStrategy}
defaultBits={activeChat?.cacheBits ?? launchSettings.cacheBits}
availableStrategies={availableCacheStrategies}
engine={loadedModelEngine}
onChange={onKvStrategyOverrideChange}
disabled={chatBusySessionId === activeChat?.id}
/>
<MidThreadSwapMenu
warmModels={warmModels}
sessionModelRef={activeChat?.modelRef ?? undefined}
overrideRef={oneTurnOverride?.ref ?? null}
onSelect={onOneTurnOverrideChange}
disabled={chatBusySessionId === activeChat?.id}
/>
{showToolsToggle ? (
<button
className={`secondary-button${enableTools ? " active-toggle" : ""}`}
type="button"
onClick={() => onToggleTools(!enableTools)}
title={
enableTools
? t("tools.enabledTooltip", {
defaultValue: "Tools enabled (web search, code, calculator, file reader)",
})
: t("tools.enableTooltip", { defaultValue: "Enable agent tools" })
}
style={{
background: enableTools ? "#1e3a5f" : undefined,
borderColor: enableTools ? "#3b82f6" : undefined,
color: enableTools ? "#8fb4ff" : undefined,
fontSize: 12,
padding: "4px 10px",
}}
>
{enableTools
? t("tools.toggleOn", { defaultValue: "Tools ON" })
: t("tools.toggleLabel", { defaultValue: "Tools" })}
</button>
) : null}
</div>
<div className="composer-button-group composer-button-group--right">
<button className="secondary-button" type="button" onClick={onClearDraft}>
{t("composer.clear", { defaultValue: "Clear" })}
</button>
{chatBusySessionId !== null ? (
<button
className="secondary-button"
type="button"
onClick={onCancelGeneration}
style={{ background: "#7f1d1d", borderColor: "#dc2626", color: "#fca5a5" }}
>
{t("composer.stop", { defaultValue: "Stop" })}
</button>
) : (
<button
className="primary-button"
type="button"
onClick={() => void onSendMessage()}
disabled={!loadedModelRef}
title={
!loadedModelRef
? t("composer.sendDisabledTooltip", {
defaultValue: "Load a model first to send messages",
})
: undefined
}
>
{t("composer.send", { defaultValue: "Send" })}
</button>
)}
</div>
</div>
</div>
);
}