okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
7.3 KiB129 linesraw
1import { useEffect, useState } from 'react';
2import { localeTag, tr } from '../lib/i18n';
3import { Bar, Btn, Dialog } from './ui';
4import { nativeAction, useNative, type NativeJob } from '../lib/native';
5
6/** "A", "A and B", "A, B and C" in the language of the app. */
7const listOf = (names: string[]) => {
8  try { return new Intl.ListFormat(localeTag(), { style: 'long', type: 'conjunction' }).format(names); } catch { return names.join(', '); }
9};
10
11/**
12 * Update engine with a model loaded (Settings > About). Strata Control does the work (`strata update --stop-model --output jsonl`, through the host); this is the
13 * conversation around it, in four plain steps:
14 *  1. Warn, naming the model, and ask. Nothing happens before the yes. With no model loaded the older dialog of Settings is used instead.
15 *  2. Progress in words: the new engine downloads while the model keeps working; then the model stops; then the engine is updated.
16 *  3. Offer to start the model again with the same settings. Never automatic.
17 *  4. A failed update leaves the old engine as it was and offers to start the model again on it.
18 * The dialog follows the host's state, so it also shows the offer when the update finished while Settings was closed.
19 */
20export function EngineUpdateDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
21  const native = useNative();
22  const [jobId, setJobId] = useState('');
23  const [restartId, setRestartId] = useState('');
24  const [error, setError] = useState('');
25  const [hidden, setHidden] = useState(false);
26  const loaded = native?.instances ?? [];
27  const offer = native?.stoppedForUpdate ?? null;
28  const job: NativeJob | undefined = native?.jobs.find(j => j.id === jobId);
29  const restart: NativeJob | undefined = native?.jobs.find(j => j.id === restartId);
30  const offerKey = offer?.at ?? '';
31  useEffect(() => { setHidden(false); }, [offerKey]);
32
33  const restarting = restart?.state === 'running';
34  const updating = job?.state === 'running';
35  const names = listOf(offer?.models.map(m => m.label) ?? loaded.map(i => i.label));
36  const showOffer = !!offer && !hidden && !updating && !restarting;
37  const failedRestart = restart?.state === 'error' && !offer ? restart : undefined;
38  const ended = job?.state === 'done' || job?.state === 'error';
39  const visible = open || updating || restarting || showOffer || !!failedRestart || ended;
40  if (!visible) return null;
41
42  async function start() {
43    setError('');
44    try {
45      const started = await nativeAction<NativeJob>('operations', { kind: 'update-engine', args: { stopModel: true } });
46      setJobId(started.id);
47      onClose();                                  // the dialog now follows the job; the caller's "open" is spent
48    } catch (e) {
49      setError(e instanceof Error ? e.message : String(e));
50    }
51  }
52  async function startAgain() {
53    setError('');
54    try {
55      const started = await nativeAction<NativeJob>('operations', { kind: 'restart-models' });
56      setRestartId(started.id);
57    } catch (e) {
58      setError(e instanceof Error ? e.message : String(e));
59    }
60  }
61  async function notNow() {
62    setHidden(true);
63    try { await nativeAction('engine-restart/dismiss'); } catch { /* the offer stays hidden here either way */ }
64    setJobId('');
65    onClose();
66  }
67  function close() {
68    if (showOffer) { void notNow(); return; }
69    if (failedRestart) setRestartId('');
70    onClose();
71  }
72
73  const percent = Number(job?.result?.install?.download?.percent);
74  const details = (j: NativeJob) => j.details ? <details className="native-settings-diagnostic"><summary className="small">{tr("Details")}</summary><p className="small muted">{j.details}</p></details> : null;
75
76  // 3 and 4: the model was stopped for the update.
77  if (showOffer && offer) {
78    const done = offer.updated;
79    return <Dialog open compact title={tr(done ? 'The engine is updated' : "The engine was not updated")} onClose={close}
80      actions={<><Btn onClick={() => void notNow()}>{tr("Not now")}</Btn><Btn variant="primary" onClick={() => void startAgain()}>{tr("Start again")}</Btn></>}>
81      <p>{done ? tr("The engine is updated. Start {0} again with the same settings?", [names]) : tr("The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?", [names])}</p>
82      {!done && job ? details(job) : null}
83      {error ? <p className="small inline-error" role="alert">{tr(error)}</p> : null}
84    </Dialog>;
85  }
86  // The model is starting again.
87  if (restarting) {
88    return <Dialog open compact title={tr("Starting {0} again", [names])} onClose={onClose}>
89      <p role="status">{tr("Starting {0}. Loading can take a few minutes.", [names])}</p>
90      <div className="engine-update-progress"><Bar value={0} indeterminate label={tr("Starting {0} again", [names])}/></div>
91    </Dialog>;
92  }
93  if (failedRestart) {
94    return <Dialog open compact title={tr("The model did not start again")} onClose={close} actions={<Btn variant="primary" onClick={close}>{tr("Close")}</Btn>}>
95      <p>{tr("You can load it again from Models.")}</p>
96      {failedRestart.error ? <p className="small muted">{failedRestart.error}</p> : null}
97    </Dialog>;
98  }
99  // 2: the update is running.
100  if (updating && job) {
101    const step = job.step, label = listOf(job.models ?? loaded.map(i => i.label));
102    return <Dialog open compact title={tr("Updating the engine")} onClose={onClose}>
103      <p role="status" aria-live="polite">{step === 'stopping' ? tr("Stopping {0}. Answers in progress finish first.", [label])
104        : step === 'stopped' ? tr("{0} is stopped. Updating the engine…", [label])
105        : step === 'getting-ready' ? tr("Getting the new engine ready. {0} keeps working until it is ready.", [label])
106        : tr(job.summary || 'Starting…')}</p>
107      <div className="engine-update-progress">{step === 'getting-ready' && Number.isFinite(percent) ? <Bar value={percent} label={tr("Downloading…")}/> : <Bar value={0} indeterminate label={tr("Updating the engine")}/>}</div>
108    </Dialog>;
109  }
110  // The update ended without stopping anything (declined, refused, or failed before the model was touched).
111  if (job?.state === 'error') {
112    return <Dialog open compact title={tr("The engine was not updated")} onClose={() => { setJobId(''); onClose(); }} actions={<Btn variant="primary" onClick={() => { setJobId(''); onClose(); }}>{tr("Close")}</Btn>}>
113      <p>{tr(job.error ?? job.summary)}</p>
114      {details(job)}
115    </Dialog>;
116  }
117  if (job?.state === 'done') {
118    return <Dialog open compact title={tr("The engine is updated")} onClose={() => { setJobId(''); onClose(); }} actions={<Btn variant="primary" onClick={() => { setJobId(''); onClose(); }}>{tr("Close")}</Btn>}>
119      <p>{tr(job.summary)}</p>
120    </Dialog>;
121  }
122  // 1: warn and ask.
123  return <Dialog open compact title={tr("Update engine?")} onClose={close}
124    actions={<><Btn onClick={close}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!loaded.length} onClick={() => void start()}>{tr("Stop and update")}</Btn></>}>
125    <p>{tr("To update the engine, Strata has to stop the model that is loaded: {0}.", [names])}</p>
126    <p className="small muted">{tr("The new engine downloads first while the model keeps answering. Then the model stops (answers in progress finish first), the engine is updated, and you can start the model again with the same settings. Your models and settings are kept.")}</p>
127    {error ? <p className="small inline-error" role="alert">{tr(error)}</p> : null}
128  </Dialog>;
129}