okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
16.3 KiB214 linesraw
1import { tr } from '../lib/i18n';
2import { modelFamilyIcon } from '../lib/model-icons';
3import { useEffect, useRef, useState } from 'react';
4import { FloatingMenu } from './FloatingMenu';
5import { DictationControl } from './DictationControl';
6import { Btn, Dialog, Icon, ErrorNotice } from './ui';
7import { MOD } from '../lib/commands';
8import { pushToast, setChatPreferences, useStore } from '../lib/store';
9import { artifactFromUrl, type PreviewArtifact } from '../lib/artifacts';
10import type { ChatMode, Session } from '../lib/types';
11import { attachChatPhoto } from '../lib/chat-photos';
12import { uploadChatFile, FILE_ACCEPT } from '../lib/chat-attach-file';
13import { useNative } from '../lib/native';
14import { pictureStatus } from '../lib/pictures';
15const modes: {
16    value: ChatMode;
17    label: string;
18    hint: string;
19}[] = [
20    { value: 'manual', label: 'Manual', hint: 'Ask before making changes' },
21    { value: 'plan', label: 'Plan', hint: 'Create a plan before making changes' },
22    { value: 'bypass', label: 'Bypass permissions', hint: 'Skip permission prompts' },
23];
24const efforts = ['Off', 'Low', 'Medium', 'High', 'Max'];
25/** The most tokens a reply may spend thinking (the server's reasoning_budget_tokens); 0 = no limit. */
26const THINKING_BUDGETS: [number, string][] = [[0, 'No limit'], [2048, '2K'], [8192, '8K'], [32768, '32K']];
27const textTypes = /\.(txt|md|markdown|csv|tsx?|jsx?|py|json|css|rs|go|sh|html?|ya?ml|toml|xml|log)$/i;
28const photoTypes = /\.(png|jpe?g|webp|gif|svg)$/i;
29export function ComposerControls({ session, onPreview, onAttach, onError, onSlash, streaming, draft, onDraft }: {
30    draft: string;
31    onDraft: (text: string) => void;
32    session: Session | null;
33    onPreview: (a: PreviewArtifact) => void;
34    streaming: boolean;
35    onAttach: (name: string, text: string) => void;
36    onError: (error: string) => void;
37    onSlash: () => void;
38}) {
39    const remoteModel = useStore(s => s.remoteModel);
40    const native = useNative();
41    const nativeModel = native?.instances.find(i => i.id === native.defaultId);
42    const [toolsOpen, setToolsOpen] = useState(false);
43    const library = useStore(s => s.library);
44    const loaded = library?.variants.find(v => v.id === library.loaded);
45    const remote = useStore(s => s.remoteModel), providers = useStore(s => s.providers);
46    const apiModel = providers?.connections.find(c => c.id === remote?.connectionId)?.models.find(m => m.id === remote?.modelId);
47    const [menu, setMenu] = useState(false), [preferences, setPreferences] = useState<'mode' | 'thinking' | null>(null), [reading, setReading] = useState(false);
48
49    // The mode menu prints 1–3 beside its rows. They were decoration: make those
50    // keys pick the mode while the menu is open, and leave modified keys to the app.
51    useEffect(() => {
52        if (preferences !== 'mode')
53            return;
54        const onKey = (event: KeyboardEvent) => {
55            if (event.metaKey || event.ctrlKey || event.altKey)
56                return;
57            const option = modes[Number(event.key) - 1];
58            if (!option)
59                return;
60            event.preventDefault();
61            setChatPreferences(session?.id, { mode: option.value });
62            setPreferences(null);
63        };
64        window.addEventListener('keydown', onKey);
65        return () => window.removeEventListener('keydown', onKey);
66    }, [preferences, session?.id]);
67    const [urlOpen, setUrlOpen] = useState(false), [url, setUrl] = useState(''), [error, setError] = useState('');
68    const files = useRef<HTMLInputElement>(null), folder = useRef<HTMLInputElement>(null), previewFile = useRef<HTMLInputElement>(null);
69    const trigger = useRef<HTMLButtonElement>(null), modeTrigger = useRef<HTMLButtonElement>(null), thinkingTrigger = useRef<HTMLButtonElement>(null);
70    const attachLatest = useRef(onAttach);
71    attachLatest.current = onAttach;
72    const addFilesLatest = useRef<(files: File[]) => Promise<void>>(async () => { });
73    // A model on an API takes a reasoning effort when its provider says it can think (OpenRouter's model list); otherwise the provider decides.
74    const apiOnlyDefault = !!apiModel && apiModel.thinks !== true;
75    const pictures = pictureStatus(native, remoteModel, providers);
76    const mode = modes.find(m => m.value === session?.preferences?.mode) ?? modes[0];
77    const effort = efforts.includes(session?.preferences?.thinking ?? '') ? session!.preferences!.thinking! : 'Medium';
78    const budget = session?.preferences?.thinkingBudget ?? 0;
79    const shortcut = MOD === '⌘' ? '⌘⇧A' : 'Ctrl+Shift+A';
80    async function openFile(selected: File | undefined) {
81        if (!selected)
82            return;
83        if (selected.size > 20 * 1024 * 1024) {
84            onError('Choose a file smaller than 20 MB.');
85            return;
86        }
87        const isPdf = /\.pdf$/i.test(selected.name), isImage = photoTypes.test(selected.name), isTable = /\.csv$/i.test(selected.name), isCode = /\.(tsx?|jsx?|py|json|css|rs|go|sh)$/i.test(selected.name), isHtml = /\.html?$/i.test(selected.name);
88        try {
89            onPreview({ id: crypto.randomUUID(), kind: isPdf ? 'pdf' : isImage ? 'image' : isTable ? 'table' : isCode ? 'code' : isHtml ? 'website' : 'markdown', title: selected.name, ...(isPdf || isImage ? { url: URL.createObjectURL(selected) } : { content: await selected.text() }) });
90        }
91        catch {
92            onError('Could not read the file.');
93        }
94    }
95    async function addFiles(selected: File[], directory = false) {
96        if (!selected.length)
97            return;
98        setReading(true);
99        onError('');
100        const texts: string[] = [];
101        let bytes = 0;
102        let skipped = 0;
103        try {
104            for (const file of selected.slice(0, 64)) {
105                const path = file.webkitRelativePath || file.name;
106                if (directory && /(^|\/)(node_modules|\.git|\.strata)(\/|$)/.test(path)) {
107                    skipped++;
108                    continue;
109                }
110                if (!directory && photoTypes.test(file.name) && pictures.ok) {
111                    await attachChatPhoto(file, session?.id);
112                    continue;
113                }
114                if (!directory && session?.id && /\.pdf$/i.test(file.name) && file.size <= 12 * 1024 * 1024) {
115                    // A PDF goes to the chat's folder and is named in the next message; "Open a file" still previews it.
116                    const saved = await uploadChatFile(file, session.id);
117                    pushToast('success', 'PDF added', `${saved.name} is in this chat. Ask about it in your next message.`);
118                    continue;
119                }
120                if (!directory && (photoTypes.test(file.name) || /\.pdf$/i.test(file.name))) {
121                    await openFile(file);
122                    if (photoTypes.test(file.name))
123                        onError(`${pictures.ok ? '' : tr(pictures.message)} ${tr('It is open in preview.')}`);
124                    continue;
125                }
126                if (!textTypes.test(file.name) || bytes + file.size > 256 * 1024) {
127                    skipped++;
128                    continue;
129                }
130                const text = await file.text();
131                if (text.includes('\u0000')) {
132                    skipped++;
133                    continue;
134                }
135                bytes += file.size;
136                texts.push(`File: ${path}\n\n${text}`);
137            }
138            if (texts.length)
139                attachLatest.current(directory ? (selected[0].webkitRelativePath.split('/')[0] || 'Folder') : selected.filter(f => textTypes.test(f.name)).map(f => f.name).join(', '), texts.join('\n\n'));
140            skipped += Math.max(0, selected.length - 64);
141            if (skipped)
142                onError(`${skipped} file${skipped === 1 ? ' was' : 's were'} skipped. Add up to 64 text files, with 256 KB of text in total. Photos and PDFs can be opened separately.`);
143        }
144        catch {
145            onError('Some files could not be read. Try adding them separately.');
146        }
147        finally {
148            setReading(false);
149        }
150    }
151    addFilesLatest.current = files => addFiles(files);
152    useEffect(() => {
153        folder.current?.setAttribute('webkitdirectory', '');
154        const key = (e: KeyboardEvent) => {
155            if (!e.defaultPrevented && (e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && e.key.toLowerCase() === 'a' && !document.querySelector('.dialog-layer') && !streaming && !reading) {
156                e.preventDefault();
157                files.current?.click();
158            }
159        };
160        const website = () => { setUrlOpen(true); setError(''); };
161        const preview = () => previewFile.current?.click();
162        const dropped = (e: Event) => { if (!streaming && !reading) void addFilesLatest.current((e as CustomEvent<File[]>).detail ?? []); };
163        window.addEventListener('strata:drop-files', dropped);
164        window.addEventListener('keydown', key);
165        window.addEventListener('strata:open-website', website);
166        window.addEventListener('strata:open-preview', preview);
167        return () => { window.removeEventListener('strata:drop-files', dropped); window.removeEventListener('keydown', key); window.removeEventListener('strata:open-website', website); window.removeEventListener('strata:open-preview', preview); };
168    }, [streaming, reading]);
169    useEffect(() => {
170        if (preferences !== 'mode')
171            return;
172        const key = (e: KeyboardEvent) => {
173            const i = Number(e.key) - 1;
174            if (i >= 0 && i < modes.length && !e.metaKey && !e.ctrlKey && !e.altKey) {
175                e.preventDefault();
176                setChatPreferences(session?.id, { mode: modes[i].value });
177                setPreferences(null);
178            }
179        };
180        window.addEventListener('keydown', key);
181        return () => window.removeEventListener('keydown', key);
182    }, [preferences, session?.id]);
183    return <>
184    {tr(!remoteModel && nativeModel?.metrics?.mcp?.servers?.length ? <button className="composer-choice" aria-label={tr("Use connected MCP tools")} aria-pressed={session?.preferences?.useTools === true} onClick={() => session?.preferences?.useTools ? setChatPreferences(session.id, { useTools: false }) : setToolsOpen(true)}><Icon name="skills" size={16}/>{tr("Tools")}{tr(session?.preferences?.useTools ? ' on' : '')}</button> : null)}
185    <Dialog open={toolsOpen} compact title={tr("Enable connected tools?")} onClose={() => setToolsOpen(false)} actions={<><Btn onClick={() => setToolsOpen(false)}>{tr("Keep tools off")}</Btn><Btn variant="primary" onClick={() => { setChatPreferences(session?.id, { useTools: true, mode: 'bypass' }); setToolsOpen(false); }}>{tr("Enable tools")}</Btn></>}><p>{tr("Connected servers can act on the resources you configured. Calls run automatically when the model chooses them, and their results appear in chat.")}</p><p className="small muted">{tr("This switches this conversation to Bypass permissions. Servers: ")}{tr((nativeModel?.metrics?.mcp?.servers ?? []).map((s: any) => s.name).join(', '))}.</p></Dialog>
186    <input ref={files} type="file" multiple hidden accept={FILE_ACCEPT} onChange={e => { void addFiles(Array.from(e.target.files ?? [])); e.target.value = ''; }}/>
187    <input ref={folder} type="file" multiple hidden onChange={e => { void addFiles(Array.from(e.target.files ?? []), true); e.target.value = ''; }}/>
188    <input ref={previewFile} type="file" hidden onChange={e => { void openFile(e.target.files?.[0]); e.target.value = ''; }}/>
189    <button ref={trigger} className="composer-add" aria-label={tr("Add or open")} title={tr("Add or open")} disabled={reading || streaming} aria-haspopup="menu" aria-expanded={menu} onClick={() => { setPreferences(null); setMenu(v => !v); }}><Icon name="plus" size={22}/></button>
190    <DictationControl draft={draft} onDraft={onDraft} sessionId={session?.id} disabled={streaming}/>
191    <button ref={modeTrigger} className="composer-choice composer-mode" aria-label={tr("Mode: {0}", [tr(mode.label)])} aria-haspopup="menu" aria-expanded={preferences === 'mode'} onClick={() => { setMenu(false); setPreferences(v => v === 'mode' ? null : 'mode'); }}><span>{tr(mode.label)}</span><Icon name="chevron" size={13}/></button>
192    <span className="spacer"/>
193    <button ref={thinkingTrigger} className="composer-choice composer-effort" disabled={apiOnlyDefault} title={tr(apiOnlyDefault ? "Reasoning uses the API provider’s defaults." : undefined)} aria-label={tr("Reasoning effort: {0}", [apiOnlyDefault ? tr('Provider default') : effort])} aria-haspopup="menu" aria-expanded={preferences === 'thinking'} onClick={() => { setMenu(false); setPreferences(v => v === 'thinking' ? null : 'thinking'); }}><Icon name="thinking" size={16}/><span>{tr(apiOnlyDefault ? 'Default' : effort)}</span><Icon name="chevron" size={13}/></button>
194    {tr(menu ? <FloatingMenu anchor={trigger.current} title={tr("Add or open")} width={292} onClose={() => setMenu(false)}>
195      <button role="menuitem" className="menu__item" onClick={() => { setMenu(false); files.current?.click(); }}><Icon name="attach"/><span>{tr("Add files or photos")}</span><kbd className="menu-shortcut">{tr(shortcut)}</kbd></button>
196      <button role="menuitem" className="menu__item" onClick={() => { setMenu(false); folder.current?.click(); }}><Icon name="folder-plus"/>{tr("Add folder")}</button>
197      <button role="menuitem" className="menu__item" onClick={() => { setMenu(false); onSlash(); }}><span className="slash-command-icon" aria-hidden="true">/</span>{tr("Slash commands")}</button>
198    </FloatingMenu> : null)}
199    {tr(preferences ? <FloatingMenu anchor={preferences === 'mode' ? modeTrigger.current : thinkingTrigger.current} title={tr(preferences === 'mode' ? 'Mode' : 'Reasoning effort')} width={preferences === 'mode' ? 330 : 280} onClose={() => setPreferences(null)}>
200      {tr(preferences === 'mode' ? <>{tr(modes.map((option, index) => <button key={option.value} role="menuitemradio" aria-checked={mode.value === option.value} className="menu__item composer-mode-option" onClick={() => { setChatPreferences(session?.id, { mode: option.value }); setPreferences(null); }}><span><strong>{tr(option.label)}</strong><small>{tr(option.hint)}</small></span>{tr(mode.value === option.value ? <Icon name="check" size={16}/> : null)}<kbd className="menu-shortcut">{tr(index + 1)}</kbd></button>))}</> : <><div className="reasoning-menu-model"><Icon name={apiModel ? 'link' : modelFamilyIcon(loaded?.family ?? nativeModel?.label)} size={18}/><strong>{tr(apiModel?.name ?? (nativeModel && nativeModel.status === 'ready' ? nativeModel.label : null) ?? loaded?.family ?? 'No model loaded')}</strong></div><p className="composer-menu-heading">{tr("Reasoning effort")}</p>{tr(efforts.map(option => <button key={option} role="menuitemradio" aria-checked={effort === option} className="menu__item" onClick={() => { setChatPreferences(session?.id, { thinking: option }); setPreferences(null); }}>{tr(option)}<span className="spacer"/>{tr(effort === option ? <Icon name="check" size={16}/> : null)}</button>))}{tr(apiModel ? null : <><p className="composer-menu-heading">{tr("Thinking budget")}</p>{tr(THINKING_BUDGETS.map(([value, label]) => <button key={value} role="menuitemradio" aria-checked={budget === value} disabled={effort === 'Off'} className="menu__item" onClick={() => { setChatPreferences(session?.id, { thinkingBudget: value }); setPreferences(null); }}>{tr(label)}<span className="spacer"/>{tr(budget === value ? <Icon name="check" size={16}/> : null)}</button>))}</>)}</>)}
201    </FloatingMenu> : null)}
202
203    <Dialog open={urlOpen} title={tr("Open a website")} onClose={() => setUrlOpen(false)} actions={<><Btn onClick={() => setUrlOpen(false)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!url.trim()} onClick={() => {
204                const a = artifactFromUrl(url.trim());
205                if (!a || !/^https?:\/\//i.test(url.trim())) {
206                    setError('Enter a full http:// or https:// address.');
207                    return;
208                }
209                onPreview(a);
210                setUrlOpen(false);
211                setUrl('');
212            }}>{tr("Open preview")}</Btn></>}><div className="form-stack"><label className="input-field"><span>{tr("Website address")}</span><input className="st-input" type="url" aria-invalid={!!error} value={url} onChange={e => { setUrl(e.target.value); setError(''); }} placeholder={tr("https://example.com")}/></label>{tr(error ? <ErrorNotice message={error}/> : null)}</div></Dialog>
213  </>;
214}