okami.mom/strata

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

Niko1221rc1 merge gui-fb2 (35d4781f1): two files conflicted (apps/host/server/native-control.mjs, apps/host/src/components/NativeModels.tsx), resolved at token level; images/visionPrepared take both the DeepSeek tower check and picturesMissinga2f602398

main
12.8 KiB156 linesraw
1import { useEffect, useId, useRef, useState } from 'react';
2import { tr } from '../lib/i18n';
3import { deliveryFolder, dirOf, fileAction, fileSize, fileTypeLabel, previewOf, rawUrlOf, rootOf, type ActivityGroup, type Deliverable } from '../lib/deliverables';
4import { useChatFolder } from '../lib/chat-folder';
5import type { PreviewArtifact } from '../lib/artifacts';
6import { draftSize, groupFromDraft } from '../lib/draft-view';
7import type { ToolDraft } from '../lib/types';
8import { pushToast } from '../lib/store';
9import { plainFailureText } from '../lib/plain-errors';
10import { FloatingMenu } from './FloatingMenu';
11import { CopyMenuItem } from './CopyBtn';
12import { Icon } from './ui';
13
14const problem = (title: string, e: unknown) => pushToast('error', tr(title), plainFailureText(e instanceof Error ? e.message : String(e)).message);
15
16/** A line's numbers ("+225 −0") shown as a pair of small figures; the sentence itself stays plain grey. */
17export function Plusminus({ added, removed }: { added: number; removed: number }) {
18  return <span className="pm" aria-label={tr('{0} lines added, {1} removed', [added, removed])}><span className="pm__a">+{added}</span><span className="pm__d">−{removed}</span></span>;
19}
20
21const showOf = (file: { path: string; name: string }, sessionId: string, onPreview: (a: PreviewArtifact) => void, kind?: string) =>
22  previewOf(sessionId, file).then(onPreview, e => {
23    // A file with no preview opens in its own app instead.
24    if (kind === 'other') return fileAction.open(sessionId, file.path, 'app').catch(err => problem('The file was not opened', err));
25    return problem('The file has no preview', e);
26  });
27
28/** One file the assistant made or changed: its type, name and size, and Open (in the file's own app or the browser) with a menu for the other things to do with it, among them Open in sidebar. */
29export function FileCard({ file, sessionId, onPreview }: { file: Deliverable; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
30  const more = useRef<HTMLButtonElement>(null);
31  const [menu, setMenu] = useState(false), [busy, setBusy] = useState(false);
32  const run = async (fn: () => Promise<unknown>, failed: string) => { setMenu(false); try { await fn(); } catch (e) { problem(failed, e); } };
33  return <div className="fcard" data-kind={file.kind}>
34    <span className="fcard__type">{fileTypeLabel(file)}</span>
35    <span className="fcard__name"><strong title={file.path}>{file.name}</strong><span>{fileSize(file.size)}</span></span>
36    <span className="fcard__split">
37      <button type="button" className="fcard__open" disabled={busy} onClick={() => { setBusy(true); void fileAction.open(sessionId, file.path, 'app').catch(err => problem('The file was not opened', err)).finally(() => setBusy(false)); }}>{tr("Open")}</button>
38      <button ref={more} type="button" className="fcard__more" aria-haspopup="menu" aria-expanded={menu} aria-label={tr("More ways to open {0}", [file.name])} onClick={() => setMenu(v => !v)}><Icon name="chevron" size={14} className="fcard__chev"/></button>
39    </span>
40    {tr(menu ? <FloatingMenu anchor={more.current} title={tr("File actions")} width={220} onClose={() => setMenu(false)}>
41      <button role="menuitem" className="menu__item" onClick={() => { setMenu(false); void showOf(file, sessionId, onPreview, file.kind); }}><Icon name="panel"/>{tr("Open in sidebar")}</button>
42      <button role="menuitem" className="menu__item" onClick={() => void run(() => fileAction.open(sessionId, file.path, 'folder'), 'The folder was not opened')}><Icon name="folder"/>{tr("Show in folder")}</button>
43      <CopyMenuItem text={() => fileAction.fullPath(sessionId, file.path)} label="Path" onClose={() => setMenu(false)}>Copy path</CopyMenuItem>
44      <button role="menuitem" className="menu__item" onClick={() => void run(async () => { await fileAction.attach(sessionId, file.path); pushToast('info', tr('Attached to your next message'), file.name); }, 'The file was not attached')}><Icon name="attach"/>{tr("Attach as context")}</button>
45    </FloatingMenu> : null)}
46  </div>;
47}
48
49/** "Edited N files": each with its lines added and removed, and the total under See all. */
50export function EditedFiles({ files, sessionId, onPreview }: { files: Deliverable[]; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
51  const [all, setAll] = useState(false);
52  const textual = files.filter(f => f.lines !== null);
53  if (textual.length < 2) return null;
54  const shown = all ? textual : textual.slice(0, 3);
55  const added = textual.reduce((n, f) => n + f.added, 0), removed = textual.reduce((n, f) => n + f.removed, 0);
56  return <div className="edited">
57    <div className="edited__head"><b>{tr('Edited {0} files', [textual.length])}</b></div>
58    {shown.map(f => <button type="button" className="edited__row" key={f.path} onClick={() => void showOf(f, sessionId, onPreview, f.kind)}><Icon name="file" size={16}/><span>{f.name}</span><Plusminus added={f.added} removed={f.removed}/></button>)}
59    <button type="button" className="edited__row edited__row--all" disabled={textual.length <= 3 && !all} onClick={() => setAll(v => !v)}><span>{tr(all ? 'Show fewer' : 'See all')}</span><Plusminus added={added} removed={removed}/></button>
60  </div>;
61}
62
63/**
64 * A run that made many files (379 after one stopped agent run) as one compact block instead of a card per file: where the result was delivered, the folder the
65 * chat works in, and the count ("379 files") that opens the full list. The list is closed by default, scrolls inside the block, and every row is a button.
66 */
67export function FilesSummary({ files, answer, sessionId, onPreview }: { files: Deliverable[]; answer: string; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
68  const [open, setOpen] = useState(false), id = useId(), folder = useChatFolder(sessionId);
69  const delivery = deliveryFolder(files, answer);
70  const rootPath = folder?.path ?? rootOf(files[0]), rootName = folder?.name ?? (rootPath.split(/[\\/]/).filter(Boolean).at(-1) ?? '');
71  const added = files.reduce((n, f) => n + f.added, 0), removed = files.reduce((n, f) => n + f.removed, 0);
72  const openFolder = (path: string) => void fileAction.open(sessionId, path, 'app').catch(err => problem('The folder was not opened', err));
73  const places: { key: string; label: string; name: string; full: string; open: string }[] = [];
74  if (delivery) places.push({ key: 'delivered', label: 'Delivered to', name: delivery, full: rootPath ? `${rootPath}/${delivery}` : delivery, open: delivery });
75  if (rootPath) places.push({ key: 'working', label: delivery ? 'Working folder' : 'Delivered to', name: rootName, full: rootPath, open: rootPath });
76  return <section className="fsum" aria-label={tr("Files")}>
77    {places.length ? <ul className="fsum__places">{places.map(p => <li key={p.key}>
78      <Icon name="folder" size={16}/><span className="fsum__label">{tr(p.label)}</span><span className="fsum__name" title={p.full}>{p.name}</span>
79      <button type="button" className="fsum__open" aria-label={tr("Open {0}", [p.name])} onClick={() => openFolder(p.open)}>{tr("Open")}</button>
80    </li>)}</ul> : null}
81    <button type="button" className="fsum__toggle" aria-expanded={open} aria-controls={id} onClick={() => setOpen(v => !v)}>
82      <Icon name="chevron" size={14} className="fsum__chev"/><span>{tr('{0} files', [files.length.toLocaleString()])}</span>{added || removed ? <Plusminus added={added} removed={removed}/> : null}
83    </button>
84    {open ? <ul className="fsum__list" id={id}>{files.map(f => { const dir = dirOf(f.path); return <li key={f.path}>
85      <button type="button" className="fsum__file" title={f.path} onClick={() => void showOf(f, sessionId, onPreview, f.kind)}>
86        <span className="fsum__type">{fileTypeLabel(f)}</span><span className="fsum__fname">{f.name}</span>{dir ? <span className="fsum__dir">{dir}</span> : null}<span className="fsum__size">{fileSize(f.size)}</span>
87      </button>
88    </li>; })}</ul> : null}
89  </section>;
90}
91
92/**
93 * The saved skills an answer used, as one quiet line under the answer in the same style as the activity line ("Ran 2 commands, read a file"):
94 * "Used 2 skills: Weekly report, Brand voice"; opened, each skill with its one-line description.
95 */
96export function SkillsUsed({ skills }: { skills: { name: string; description: string }[] }) {
97  const [open, setOpen] = useState(false);
98  if (!skills.length) return null;
99  const names = skills.map(s => s.name).join(', ');
100  return <div className="act" data-open={open || undefined}>
101    <button type="button" className="act__line" aria-expanded={open} onClick={() => setOpen(v => !v)}>
102      <Icon name="skills" size={15}/><span>{skills.length === 1 ? tr('Used 1 skill: {0}', [names]) : tr('Used {0} skills: {1}', [skills.length, names])}</span>
103      <Icon name="chevron" size={14} className="act__chev"/>
104    </button>
105    {open ? <ul className="act__files">{skills.map(s => <li key={s.name}><span className="act__skill"><Icon name="skills" size={14}/>{s.name}{s.description ? <span className="small muted">{s.description}</span> : null}</span></li>)}</ul> : null}
106  </div>;
107}
108
109/** A run of tool use between two pieces of text, as one quiet line: "Ran 2 commands, read monitor.png", with a thumbnail when it touched a picture. */
110export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityGroup; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
111  const [open, setOpen] = useState(false);
112  const picture = group.files.find(f => f.kind === 'image');
113  // The host's sentence may end with the numbers ("… +225 −0"): they are drawn as figures instead.
114  const sentence = group.line.replace(/\s*\+\d+\s*[−-]\s*\d+\s*$/, '');
115  // While the run is open this is the live step: the host's own words for it when it sends them, else the line it already had.
116  const live = !group.closed;
117  return <><div className="act" data-open={open || undefined} data-live={live || undefined}>
118    <button type="button" className="act__line" aria-expanded={open} disabled={!group.files.length} onClick={() => setOpen(v => !v)}>
119      <span>{live && group.live?.label ? group.live.label : sentence}</span>{live && group.live?.bytes ? <span className="act__meta">{draftSize(group.live.bytes)}{group.live.lines && group.live.lines > 1 ? <> {"\u00B7"} {tr("{0} lines", [group.live.lines])}</> : null}</span> : null}{group.added || group.removed ? <Plusminus added={group.added} removed={group.removed}/> : null}
120      {group.files.length ? <Icon name="chevron" size={14} className="act__chev"/> : null}
121      {!group.closed ? <span className="act__live" aria-hidden="true"/> : null}
122    </button>
123    {picture ? <img className="act__thumb" src={rawUrlOf(sessionId, picture.path)} alt="" loading="lazy" onClick={() => void showOf(picture, sessionId, onPreview)}/> : null}
124    {open ? <ul className="act__files">{group.files.map(f => <li key={f.path}><button type="button" onClick={() => void showOf(f, sessionId, onPreview, f.kind)}><Icon name="file" size={14}/>{f.name}{f.added || f.removed ? <Plusminus added={f.added} removed={f.removed}/> : null}</button></li>)}</ul> : null}
125  </div>
126    {live && group.live?.output ? <p className="act__output" title={group.live.output}>{group.live.output}</p> : null}
127    {live && group.live?.tail !== undefined ? <div className="act__tail" aria-hidden="true">{group.live.tail.split('\n').filter(Boolean).map((line, i) => <span key={i}>{line}</span>)}</div> : null}
128  </>;
129}
130
131/** The value, at most every `ms` (a file arrives about five times a second; the eye needs two). A cleared value is shown at once. */
132function useThrottled<T>(value: T, ms: number, cleared: (v: T) => boolean): T {
133  const [shown, setShown] = useState(value), last = useRef(0), timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
134  useEffect(() => {
135    clearTimeout(timer.current);
136    if (cleared(value)) { setShown(value); return; }
137    const wait = Math.max(0, last.current + ms - Date.now());
138    timer.current = setTimeout(() => { last.current = Date.now(); setShown(value); }, wait);
139    return () => clearTimeout(timer.current);
140  }, [value, ms]);
141  return shown;
142}
143
144/**
145 * The files (or commands) the model is writing right now, from `message.drafts`: each is one open activity line with the file's name, its growing size
146 * and the last lines of its text. It draws nothing while there is nothing being written, and takes the place of the ordinary card when the call is whole.
147 */
148export function DraftLines({ drafts, sessionId, onPreview }: { drafts: ToolDraft[] | undefined; sessionId: string; onPreview: (a: PreviewArtifact) => void }) {
149  const shown = useThrottled(drafts, 350, v => !v?.length);
150  if (!drafts?.length || !shown?.length) return null;
151  return <>{shown.map(d => {
152    const file = d.target ? d.target.split(/[\\/]/).filter(Boolean).at(-1) : '';
153    const verb = tr(d.verb ?? (d.scope === 'shell' ? 'Running a command' : 'Writing a file'));
154    return <ActivityLine key={d.id} group={groupFromDraft(d, file ? `${verb} · ${file}` : verb)} sessionId={sessionId} onPreview={onPreview}/>;
155  })}</>;
156}