okami.mom/strata

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

Niko1221Merge f-0215-asknotify: chat: an agent's question notifies like an approval does (#5617)e9a1215f0

main
120.8 KiB2416 linesraw
1import { workspaceIdForSession } from './session-workspace';
2import { shortTitle } from './title-text';
3import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes';
4import { detectLanguage } from './language-detect';
5import { validWhileBusy, type WhileBusy } from './while-busy';
6import { addToQuotes, type Quote } from './quotes';
7import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask';
8import { plainFailure, plainFailureText } from './plain-errors';
9import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';
10import { settleAgents, updateAgent } from './agents';
11import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop';
12import { LoopScheduler } from './loop-runner';
13import { applyStatusFrame, clearStatus } from './live-status';
14import { approvalNeeded, questionAsked, workFinished } from './attention';
15import { applyGoalFrame } from './goal';
16import { tidyAnswer } from './answer-text';
17import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables';
18import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan';
19import { forkFields, isForkJob, TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip';
20import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts';
21import { lifecyclePolicy } from './lifecycle';
22import { newestServingState } from './serving-state';
23import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos';
24import { applyNativeEvent, nativeState } from './native';
25import { pictureStatus } from './pictures';
26import { noModelNotice } from './no-model';
27import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover';
28import type { Task } from './tasks';
29import { postWithFolderFallback } from './folder-pick';
30import { createSessionWriter, exportSessions, readBrowserSessions, HOST_FLAG_KEY, PENDING_KEY, type SaveResult, type StorageLike } from './session-persist';
31import { createHttpTransport, hydrateChats, keepLastMomentCopy, WINDOW_ID } from './chat-sync';
32import { copyText } from './clipboard';
33import { catalogLoaded, loadCatalog, setTranslationLanguage, tr, validLanguage, type Language } from './i18n';
34/**
35 * Strata app store.
36 *
37 * A single immutable state object + a tiny subscribe/emit pair, consumed through
38 * useSyncExternalStore. Data comes from the engine host over /api; live updates
39 * arrive on the event stream. No state library, no dependencies.
40 */
41import { useSyncExternalStore } from 'react';
42import { api, ApiError, onEvent, streamPost, type StreamEvent } from './client';
43import type {
44  Workspace,
45  ChatMessage,
46  ToolCall,
47  EngineConfig,
48  Hardware,
49  ModelLibrary,
50  RuntimeModels,
51  ImageModelLibrary,
52  ImageModelChoice,
53  ModelProviders,
54  ModelConnectionDraft,
55  RemoteModelSelection,
56  MonitorState,
57  ServingState,
58  Session,
59  SetupState,
60  Skill,
61  WorkspaceFile,
62  ToolDraft,
63} from './types';
64import { navigate, type Route } from './router';
65import { estimate, execution, contextTokens } from './experience';
66
67export interface Toast {
68  id: string;
69  tone: 'info' | 'success' | 'warn' | 'error';
70  title: string;
71  body?: string;
72  leaving?: boolean;
73  /** A button under the text. A toast with one stays until it is dismissed. */
74  action?: { label: string; run: () => void };
75}
76
77export interface AppState {
78  language: Language;
79  fontFamily: string;
80  configDraft: string | null;
81  navOpen: boolean;
82  ready: boolean;
83  connection: 'connecting' | 'live' | 'offline';
84  theme: 'dark' | 'light' | 'system';
85  contrast: 'standard' | 'increased';
86  rail: boolean;
87  /** Distraction-free reading: chrome recedes, the transcript narrows. */
88  focus: boolean;
89  /** Conversation prose size in px, 10–22. Does not touch the UI chrome. */
90  contentFontSize: number;
91  density: 'comfortable' | 'compact';
92  motion: 'system' | 'full' | 'reduced';
93  /** Translucent materials, or flat surfaces for anyone who prefers them. */
94  transparency: 'translucent' | 'opaque';
95  /** Chrome scale, independent of the conversation's reading size. */
96  uiScale: number;
97  /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */
98  electricityPrice: number;
99  electricityCurrency: string;
100  /** Opt-in: a short sound when a task finishes (#3586). */
101  doneSound: boolean;
102  /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */
103  approvalNotify: boolean;
104  /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */
105  whileBusy: WhileBusy;
106  /** Governs anonymous usage reporting. Nothing is sent in this build; the
107   *  choice is recorded so a version that does offer it starts from it. */
108  shareTelemetry: boolean;
109  paletteOpen: boolean;
110  shortcutsOpen: boolean;
111  settingsSection: 'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About';
112  hardware: Hardware | null;
113  library: ModelLibrary | null;
114  imageModels: ImageModelLibrary | null;
115  runtime: RuntimeModels | null;
116  providers: ModelProviders | null;
117  remoteModel: RemoteModelSelection | null;
118  engine: EngineConfig | null;
119  serving: ServingState | null;
120  monitor: MonitorState | null;
121  setup: SetupState | null;
122  skills: Skill[];
123  files: WorkspaceFile[];
124  workspacePath: string;
125  workspaces: Workspace[];
126  /** Id of the workspace the file tree is scoped to. */
127  activeWorkspace: string | null;
128  /** First run, and "run setup again", both present the wizard as a modal. */
129  setupOpen: boolean;
130  sessions: Session[];
131  activeSession: string | null;
132  streaming: boolean;
133  /** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */
134  parked: Record<string, string[]>;
135  /** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */
136  quotes: Record<string, Quote[]>;
137  /** The questions the agent asked the person and is waiting for, by chat (#4244). */
138  agentAsks: Record<string, AgentAsk[]>;
139  /** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */
140  liveChats: number;
141  toasts: Toast[];
142  /** Files the model has been granted read access to, and when. */
143  touchedPaths: Record<string, string>;
144  /** The last action that failed, kept until it is retried or dismissed.
145   *  A toast disappears after five seconds; a failure the reader has not dealt
146   *  with should not. */
147  actionError: { message: string; label: string; retry: () => void } | null;
148  busy: Record<string, boolean>;
149  /** Set while the host cannot write some chats (disk full, no permission); null when every chat is saved (#5192).
150   *  The chats stay whole in memory and are tried again at every save; `unsavedSessionsJson()` gives them as text.
151   *  A host that does not answer is not this: those saves are simply retried. */
152  sessionSave: { failedIds: string[]; reason: 'disk-full' | 'permission' | 'other' } | null;
153}
154
155const PREFS_KEY = 'strata.prefs.v2';
156/** What the model has been allowed to read, kept across restarts. */
157const TOUCHED_KEY = 'strata.touched.v1';
158/** Kept one release so downgrading does not lose the theme and sidebar state. */
159const PREFS_KEY_V1 = 'strata.prefs.v1';
160
161const CONTENT_FS_MIN = 10;
162const CONTENT_FS_MAX = 22;
163
164export interface Prefs {
165  /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */
166  sizeDefaults?: number;
167  language: Language;
168  fontFamily: string;
169  theme: 'dark' | 'light' | 'system';
170  contrast: 'standard' | 'increased';
171  rail: boolean;
172  focus: boolean;
173  contentFontSize: number;
174  density: 'comfortable' | 'compact';
175  motion: 'system' | 'full' | 'reduced';
176  transparency: 'translucent' | 'opaque';
177  uiScale: number;
178  electricityPrice: number;
179  electricityCurrency: string;
180  doneSound: boolean;
181  approvalNotify: boolean;
182  /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */
183  whileBusy: WhileBusy;
184  /** Governs anonymous usage reporting. Nothing is sent in this build; the
185   *  choice is recorded so a version that does offer it starts from it. */
186  shareTelemetry: boolean;
187}
188
189const PREFS_DEFAULTS: Prefs = {
190  language: 'en',
191  fontFamily: '',
192  theme: 'system',
193  contrast: 'standard',
194  rail: false,
195  focus: false,
196  contentFontSize: DEFAULT_CONTENT_FS,
197  density: 'comfortable',
198  motion: 'system',
199  transparency: 'translucent',
200  uiScale: DEFAULT_UI_SCALE,
201  electricityPrice: 0,
202  electricityCurrency: '',
203  doneSound: false,
204  approvalNotify: false,
205  whileBusy: 'wait',
206  shareTelemetry: false,
207};
208
209function uid(prefix = 'id'): string {
210  return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`;
211}
212
213/** localStorage, looked up at each call (it may not exist when this file is loaded outside a browser). */
214const browserStorage: StorageLike = {
215  getItem: key => localStorage.getItem(key),
216  setItem: (key, value) => localStorage.setItem(key, value),
217  removeItem: key => localStorage.removeItem(key),
218  key: index => localStorage.key(index),
219  get length() { return localStorage.length; },
220};
221/** A chat as the page works with it: a reply that was streaming when the page went away is marked interrupted, not left running. */
222function fixSession(session: Session): Session {
223  return {
224    ...session,
225    ...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}),
226    ...(!session.showcase && session.agents ? { agents: settleAgents(session.agents) } : {}),
227    messages: (session.messages ?? []).map(message => message.streaming ? {
228      ...message,
229      streaming: false,
230      error: message.error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.',
231    } : message),
232  };
233}
234
235/**
236 * The chats shown before the host has answered. Once the browser's chats were handed to the host (the flag) the host's files are the only
237 * truth and the page starts empty until it has read them (the boot screen is up until then); before that, and when the host cannot be
238 * asked, the browser's old copy is shown. It is only ever read.
239 */
240function loadSessions(): Session[] {
241  try {
242    if (browserStorage.getItem(HOST_FLAG_KEY) === '1') return [];
243    return readBrowserSessions(browserStorage).sessions.map(fixSession);
244  } catch {
245    return [];
246  }
247}
248
249/**
250 * v2 adds focus, reading size, density and the motion override. A v1 blob (only
251 * theme and rail) is read as-is and upgraded on the next write, so the first run
252 * after this change keeps the user's theme instead of resetting it.
253 */
254function loadPrefs(): Prefs {
255  for (const key of [PREFS_KEY, PREFS_KEY_V1]) {
256    try {
257      const raw = localStorage.getItem(key);
258      if (!raw) continue;
259      const parsed = JSON.parse(raw) as Partial<Prefs>;
260      return {
261        ...PREFS_DEFAULTS,
262        ...parsed,
263        language: validLanguage(parsed.language) ? parsed.language : 'en',
264        fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '',
265        ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX),
266        sizeDefaults: SIZE_DEFAULTS_VERSION,
267        electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0,
268        electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '',
269        doneSound: parsed.doneSound === true,
270        approvalNotify: parsed.approvalNotify === true,
271        whileBusy: validWhileBusy(parsed.whileBusy) ? parsed.whileBusy : 'wait',
272      };
273    } catch {
274      /* fall through to the next key */
275    }
276  }
277  // Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other.
278  const tags = typeof navigator === 'undefined' ? [] : navigator.languages?.length ? navigator.languages : [navigator.language];
279  return { ...PREFS_DEFAULTS, language: detectLanguage(tags) ?? 'en' };
280}
281
282const prefs = loadPrefs();
283// Use the saved language for the very first render, before host bootstrap (main.tsx waits for its strings before it draws).
284void setTranslationLanguage(prefs.language);
285
286/** The last approval question a notification was shown for, so one question is announced once. */
287let lastApprovalNotice = '';
288
289let state: AppState = {
290  language: prefs.language,
291  fontFamily: prefs.fontFamily,
292  configDraft: (() => { try { return sessionStorage.getItem('strata.config-draft.v1'); } catch { return null; } })(),
293  navOpen: false,
294  ready: false,
295  connection: 'connecting',
296  shareTelemetry: prefs.shareTelemetry,
297  theme: prefs.theme,
298  contrast: prefs.contrast,
299  rail: prefs.rail,
300  focus: prefs.focus,
301  contentFontSize: prefs.contentFontSize,
302  density: prefs.density,
303  motion: prefs.motion,
304  transparency: prefs.transparency,
305  uiScale: prefs.uiScale,
306  electricityPrice: prefs.electricityPrice,
307  electricityCurrency: prefs.electricityCurrency,
308  doneSound: prefs.doneSound,
309  approvalNotify: prefs.approvalNotify,
310  whileBusy: prefs.whileBusy,
311  parked: {},
312  quotes: {},
313  agentAsks: {},
314  paletteOpen: false,
315  shortcutsOpen: false,
316  settingsSection: 'Appearance',
317  hardware: null,
318  library: null,
319  imageModels: null,
320  runtime: null,
321  providers: null,
322  /** The open chat's API model, or null for the local model (the default for every chat). */
323  remoteModel: null,
324  engine: null,
325  serving: null,
326  monitor: null,
327  setup: null,
328  skills: [],
329  files: [],
330  workspacePath: '',
331  workspaces: [],
332  activeWorkspace: null,
333  setupOpen: false,
334  sessions: loadSessions(),
335  sessionSave: null,
336  activeSession: null,
337  streaming: false,
338  liveChats: 0,
339  toasts: [],
340  touchedPaths: (() => {
341    try {
342      return JSON.parse(localStorage.getItem(TOUCHED_KEY) ?? '{}') as Record<string, string>;
343    } catch {
344      return {};
345    }
346  })(),
347  actionError: null,
348  busy: {},
349};
350
351const listeners = new Set<() => void>();
352
353/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */
354const liveTurns = new Map<string, { abort: AbortController; agent: boolean }>();
355
356function set(patch: Partial<AppState> | ((s: AppState) => Partial<AppState>)) {
357  const before = state.activeSession;
358  const next = typeof patch === 'function' ? patch(state) : patch;
359  state = { ...state, ...next };
360  // Opening another chat shows that chat's model choice and whether that chat is mid-turn.
361  if (state.activeSession !== before) {
362    const chosen = state.sessions.find(s => s.id === state.activeSession)?.preferences?.remoteModel ?? null;
363    state = { ...state, remoteModel: 'remoteModel' in next ? state.remoteModel : chosen, streaming: !!state.activeSession && liveTurns.has(state.activeSession) };
364  }
365  for (const l of listeners) l();
366}
367
368function subscribe(l: () => void) {
369  listeners.add(l);
370  return () => listeners.delete(l);
371}
372
373export function getState(): AppState {
374  return state;
375}
376
377export function setConfigDraft(configDraft: string | null) {
378  set({ configDraft });
379  try {
380    if (configDraft === null) sessionStorage.removeItem('strata.config-draft.v1');
381    else sessionStorage.setItem('strata.config-draft.v1', configDraft);
382  } catch { /* Keep the session draft even when browser storage is unavailable. */ }
383}
384
385export function setNavOpen(navOpen: boolean) { set({ navOpen }); }
386export function setSettingsSection(settingsSection: AppState['settingsSection']) { set({ settingsSection }); }
387
388/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */
389export function selectRemoteModel(remoteModel: RemoteModelSelection | null) {
390  if (state.streaming) return;
391  if (remoteModel && !state.providers?.connections.some(c => c.id === remoteModel.connectionId && c.models.some(m => m.id === remoteModel.modelId))) return;
392  set({ remoteModel });
393  const id = state.activeSession;
394  if (id) patchSession(id, s => ({ ...s, preferences: { ...s.preferences, remoteModel } }));
395  try { localStorage.removeItem('strata.remote-model.v1'); } catch { /* The old global choice is retired. */ }
396}
397function applyProviders(providers: ModelProviders) {
398  // A chat whose API model was removed keeps its choice: the next send says the model is gone, rather
399  // than quietly answering from the local model.
400  set({ providers });
401}
402export async function saveModelConnection(draft: ModelConnectionDraft) {
403  applyProviders(await api.post<ModelProviders>('/api/model-providers', draft));
404}
405export async function removeModelConnection(id: string) {
406  applyProviders(await api.del<ModelProviders>(`/api/model-providers/${encodeURIComponent(id)}`));
407}
408
409function libraryResponse(data: ModelLibrary): ModelLibrary {
410  if (!data || !Array.isArray(data.variants)) throw new Error('The engine returned an incomplete model list. Retry the operation.');
411  return data;
412}
413
414export function lifecycleStatus(s = state) {
415  return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy });
416}
417/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */
418export function useLifecycle() {
419  const connected = useStore(s => s.connection === 'live');
420  const streaming = useStore(s => !!s.streaming || s.liveChats > 0);
421  const stats = useStore(s => s.serving?.stats);
422  const busy = useStore(s => s.busy);
423  return lifecyclePolicy({ connected, streaming, stats, busy });
424}
425export function lifecycleAvailable(): boolean {
426  const result = lifecycleStatus();
427  if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason);
428  return result.allowed;
429}
430
431export function useStore<T>(selector: (s: AppState) => T): T {
432  return useSyncExternalStore(
433    subscribe,
434    () => selector(state),
435    () => selector(state),
436  );
437}
438
439/* ------------------------------------------------------------------ toasts */
440
441/** Dismissal timers, held so a hovered toast can be paused rather than lost. */
442const toastTimers = new Map<string, ReturnType<typeof setTimeout>>();
443const TOAST_MS = 5200;
444
445export function pushToast(tone: Toast['tone'], title: string, body?: string, action?: Toast['action']): string {
446  const id = uid('toast');
447  // Cap the stack: past three, the oldest collapses rather than pushing the
448  // rest off-screen. A toast nobody can read is not a notification.
449  const next = [...state.toasts, { id, tone, title, body, ...(action ? { action } : {}) }];
450  const overflow = next.length > 3 ? next.slice(0, next.length - 3) : [];
451  for (const gone of overflow) {
452    const t = toastTimers.get(gone.id);
453    if (t) clearTimeout(t);
454    toastTimers.delete(gone.id);
455  }
456  const kept = overflow.length ? next.slice(-3) : next;
457  set({ toasts: kept });
458  if (!action) toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS));
459  return id;
460}
461
462/**
463 * Stops a toast's clock while the pointer is over it, so reading one does not
464 * race its own dismissal. Restarting gives a full window rather than the
465 * remainder — the intent is "I am reading this", and a resumed half-second is
466 * not enough to act on.
467 */
468export function holdToast(id: string) {
469  const t = toastTimers.get(id);
470  if (t) clearTimeout(t);
471  toastTimers.delete(id);
472}
473
474export function releaseToast(id: string) {
475  if (toastTimers.has(id)) return;
476  if (!state.toasts.some((t) => t.id === id && !t.leaving)) return;
477  toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS));
478}
479
480export function dismissToast(id: string) {
481  const t = toastTimers.get(id);
482  if (t) clearTimeout(t);
483  toastTimers.delete(id);
484  set((s) => ({ toasts: s.toasts.map((x) => (x.id === id ? { ...x, leaving: true } : x)) }));
485  setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), 340);
486}
487
488/* ------------------------------------------------------------------- prefs */
489
490/**
491 * Preferences live on <html> as data attributes plus one custom property, so CSS
492 * owns presentation and React owns state — the same split the theme already
493 * used. Nothing here re-renders a screen: the attributes do the work.
494 */
495function applyPrefs() {
496  const root = document.documentElement;
497  void setTranslationLanguage(state.language);
498  root.lang = state.language === 'zh' ? 'zh-CN' : state.language;
499  if(state.fontFamily)root.style.setProperty('--st-font',`${JSON.stringify(state.fontFamily)},system-ui,-apple-system,"Segoe UI",sans-serif`);
500  else root.style.removeProperty('--st-font');
501  root.dataset.theme = state.theme === 'system' ? matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : state.theme;
502  document.querySelector<HTMLMetaElement>('meta[name="theme-color"]')?.setAttribute('content', root.dataset.theme === 'dark' ? '#0e1113' : '#f9fafb');
503  root.dataset.contrast = state.contrast;
504  root.dataset.density = state.density;
505  root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`);
506  // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were
507  // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs
508  // larger prose does not necessarily want larger buttons.
509  root.style.setProperty('--st-ui-scale', '1');
510  root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale));
511
512  // "system" means the OS decides, so the attribute is absent rather than set
513  // to a third value the stylesheet would have to special-case.
514  if (state.motion === 'system') delete root.dataset.motion;
515  else root.dataset.motion = state.motion;
516
517  if (state.focus) root.dataset.focus = 'true';
518  else delete root.dataset.focus;
519
520  // "translucent" is the default, so the attribute only appears when it is off.
521  if (state.transparency === 'opaque') root.dataset.transparency = 'opaque';
522  else delete root.dataset.transparency;
523}
524
525function savePrefs() {
526  const snapshot: Prefs = {
527    sizeDefaults: SIZE_DEFAULTS_VERSION,
528    language: state.language,
529    fontFamily: state.fontFamily,
530    theme: state.theme,
531    contrast: state.contrast,
532    rail: state.rail,
533    focus: state.focus,
534    contentFontSize: state.contentFontSize,
535    density: state.density,
536    motion: state.motion,
537    transparency: state.transparency,
538    uiScale: state.uiScale,
539    electricityPrice: state.electricityPrice,
540    electricityCurrency: state.electricityCurrency,
541    doneSound: state.doneSound,
542    approvalNotify: state.approvalNotify,
543    whileBusy: state.whileBusy,
544    shareTelemetry: state.shareTelemetry,
545  };
546  try {
547    localStorage.setItem(PREFS_KEY, JSON.stringify(snapshot));
548  } catch {
549    /* a full quota must not break the UI */
550  }
551  applyPrefs();
552}
553
554export function setTheme(theme: 'dark' | 'light' | 'system') {
555  set({ theme });
556  savePrefs();
557}
558
559export function toggleRail() {
560  set({ rail: !state.rail });
561  savePrefs();
562}
563/** A language whose strings are already here switches at once; the first use of another one waits for its file (a moment), then switches everything together. The last pick wins. */
564let languageRequest=0;
565export function setLanguage(language:Language){
566  if(!validLanguage(language))return;
567  const request=++languageRequest;
568  const apply=()=>{if(request!==languageRequest)return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);};
569  if(catalogLoaded(language))apply();else void loadCatalog(language).then(apply);
570}
571let shellAnnounced = false;
572/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */
573function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);}
574/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */
575async function announcePortNotice(){
576  try{
577    const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell');
578    if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used]));
579  }catch{/* a browser or an older host has no shell */}
580}
581export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();}
582
583export function setFocus(focus: boolean) {
584  set({ focus });
585  savePrefs();
586}
587
588export function toggleFocus() {
589  setFocus(!state.focus);
590}
591
592/**
593 * Puts every appearance and reading preference back to its shipped value.
594 *
595 * Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance
596 * setting, and re-enabling reporting as a side effect of resetting one's font
597 * size would be exactly the kind of thing this control exists to prevent.
598 *
599 * Deliberately does **not** touch `rail` or `focus`: those are where you happen
600 * to be working, not settings you chose, and collapsing the sidebar on someone
601 * who asked to reset their font size would be a surprise. The engine has its own
602 * reset, since an expert override and a font size have nothing to do with each
603 * other.
604 */
605export function resetAppearance() {
606  set({
607    fontFamily: PREFS_DEFAULTS.fontFamily,
608    theme: PREFS_DEFAULTS.theme,
609    contrast: PREFS_DEFAULTS.contrast,
610    contentFontSize: PREFS_DEFAULTS.contentFontSize,
611    density: PREFS_DEFAULTS.density,
612    motion: PREFS_DEFAULTS.motion,
613    transparency: PREFS_DEFAULTS.transparency,
614    uiScale: PREFS_DEFAULTS.uiScale,
615  });
616  savePrefs();
617}
618
619/**
620 * Records the standing privacy choice.
621 *
622 * The control was local component state that nothing persisted and nothing
623 * read — it snapped back on every reload, so a reader who turned reporting off
624 * had no way to know their choice had not been recorded. A privacy control that
625 * silently forgets is worse than no control at all.
626 */
627export function setShareTelemetry(on: boolean) {
628  set({ shareTelemetry: on });
629  savePrefs();
630}
631
632export function setContentFontSize(px: number) {
633  const clamped = Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Math.round(px)));
634  set({ contentFontSize: clamped });
635  savePrefs();
636}
637
638export function setDensity(density: 'comfortable' | 'compact') {
639  set({ density });
640  savePrefs();
641}
642
643export function setMotion(motion: 'system' | 'full' | 'reduced') {
644  set({ motion });
645  savePrefs();
646}
647
648export function setTransparency(transparency: 'translucent' | 'opaque') {
649  set({ transparency });
650  savePrefs();
651}
652
653/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */
654export function setElectricity(price: number, currency: string) {
655  const ok = Number.isFinite(price) && price > 0 && price < 1000;
656  set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' });
657  savePrefs();
658}
659
660export function setWhileBusy(whileBusy: WhileBusy) {
661  if (!validWhileBusy(whileBusy)) return;
662  set({ whileBusy });
663  savePrefs();
664}
665
666/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */
667export function parkMessage(sessionId: string, text: string) {
668  const clean = text.trim();
669  if (!clean) return;
670  set({ parked: { ...state.parked, [sessionId]: [...(state.parked[sessionId] ?? []), clean] } });
671}
672function setAsks(sessionId: string, list: AgentAsk[]) {
673  const next = { ...state.agentAsks };
674  if (list.length) next[sessionId] = list; else delete next[sessionId];
675  set({ agentAsks: next });
676}
677/** The agent asked the person something (a frame of the host), or the question ended without an answer. */
678export function addAgentAsk(sessionId: string, frame: { callId?: unknown; questions?: unknown }) {
679  const ask = readAsk(frame);
680  // A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer.
681  if (ask && loopScheduler.isRunning(sessionId)) { void answerAgentAsk(sessionId, ask.callId, null).catch(() => {}); return; }
682  if (!ask) return;
683  const known = (state.agentAsks[sessionId] ?? []).some(a => a.callId === ask.callId);
684  setAsks(sessionId, [...(state.agentAsks[sessionId] ?? []).filter(a => a.callId !== ask.callId), ask]);
685  // #5617: a question waits for the person like an approval does: the same opt-in notification, once per question
686  if (!known) void questionAsked(state.approvalNotify);
687}
688export function removeAgentAsk(sessionId: string, callId?: string) {
689  const rest = callId === undefined ? [] : (state.agentAsks[sessionId] ?? []).filter(a => a.callId !== callId);
690  if ((state.agentAsks[sessionId]?.length ?? 0) !== rest.length) setAsks(sessionId, rest);
691}
692/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */
693export async function answerAgentAsk(sessionId: string, callId: string, answers: AgentAnswer[] | null) {
694  await api.post('/api/chat/answer', { sessionId, callId, ...(answers ? { answers } : { skip: true }) });
695  removeAgentAsk(sessionId, callId);
696}
697
698/** Puts a turn or a selected passage above the message box. */
699export function addQuote(sessionId: string, text: string, messageId: string, role: 'user' | 'assistant') {
700  const list = state.quotes[sessionId] ?? [];
701  const next = addToQuotes(list, { text, messageId, role });
702  if (next.length !== list.length) set({ quotes: { ...state.quotes, [sessionId]: next } });
703}
704export function removeQuote(sessionId: string, id: string) {
705  const rest = (state.quotes[sessionId] ?? []).filter(q => q.id !== id);
706  const next = { ...state.quotes };
707  if (rest.length) next[sessionId] = rest; else delete next[sessionId];
708  set({ quotes: next });
709}
710export function clearQuotes(sessionId: string) {
711  if (!state.quotes[sessionId]) return;
712  const next = { ...state.quotes };
713  delete next[sessionId];
714  set({ quotes: next });
715}
716
717/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */
718export function takeParked(sessionId: string, index = 0): string | undefined {
719  const list = state.parked[sessionId] ?? [];
720  if (index < 0 || index >= list.length) return undefined;
721  const rest = list.filter((_, i) => i !== index);
722  const next = { ...state.parked };
723  if (rest.length) next[sessionId] = rest; else delete next[sessionId];
724  set({ parked: next });
725  return list[index];
726}
727
728export function setDoneSound(doneSound: boolean) {
729  set({ doneSound });
730  savePrefs();
731}
732
733export function setApprovalNotify(approvalNotify: boolean) {
734  set({ approvalNotify });
735  savePrefs();
736}
737
738export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const;
739
740export function setUiScale(uiScale: number) {
741  set({ uiScale });
742  savePrefs();
743}
744
745export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX };
746
747/* -------------------------------------------------------------- workspaces */
748
749/** Opens the system folder chooser. Returns null when it is dismissed. */
750export async function pickWorkspace(): Promise<string | null> {
751  const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string };
752  return res.path ?? null;
753}
754
755export async function addWorkspace(path: string) {
756  try {
757    const ws = await api.post<Workspace>('/api/workspaces', { path });
758    set({ workspaces: [...state.workspaces, ws] });
759    pushToast('success', 'Workspace added', `Strata can now read files in ${ws.name}.`);
760  } catch (err) {
761    pushToast('error', "Couldn't add that folder", err instanceof Error ? err.message : String(err));
762  }
763}
764
765/** The name the sidebar shows for a workspace; its folder is unchanged. */
766export async function renameWorkspace(id: string, name: string) {
767  try {
768    const ws = await api.patch<Workspace>(`/api/workspaces/${id}`, { name });
769    set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) });
770  } catch (err) {
771    pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err));
772  }
773}
774
775export async function removeWorkspace(id: string) {
776  const ws = state.workspaces.find((w) => w.id === id);
777  try {
778    await api.del(`/api/workspaces/${id}`);
779    set({ workspaces: state.workspaces.filter((w) => w.id !== id) });
780    if (state.activeWorkspace === id) set({ activeWorkspace: state.workspaces[0]?.id ?? null });
781  } catch (err) {
782    pushToast('error', "Couldn't remove that workspace", err instanceof Error ? err.message : String(err));
783  }
784  void ws;
785}
786
787/**
788 * Pins a conversation to the top of its workspace.
789 *
790 * Sessions are currently ordered by recency, which is right until you have
791 * thirty of them and two matter. `Session.pinned` has existed in the type since
792 * the beginning and was never written to.
793 */
794export function toggleArchive(id: string) {
795  const sessions = state.sessions.map((s) => (s.id === id ? { ...s, archived: !s.archived } : s));
796  persistSessions(sessions);
797  set({ sessions });
798}
799
800export function togglePin(id: string) {
801  const sessions = state.sessions.map((s) => (s.id === id ? { ...s, pinned: !s.pinned } : s));
802  persistSessions(sessions);
803  set({ sessions });
804}
805
806export function setActiveWorkspace(id: string) {
807  set({ activeWorkspace: id });
808  void loadWorkspaceFiles();
809}
810
811export function openSetup(open: boolean) {
812  set({ setupOpen: open });
813}
814
815export function setPalette(open: boolean) {
816  set({ paletteOpen: open });
817}
818
819export function setShortcuts(open: boolean) {
820  set({ shortcutsOpen: open });
821}
822
823/* --------------------------------------------------------------- transport */
824
825function applyEvent(e: StreamEvent) {
826  const data = e.data as Record<string, unknown>;
827  switch (e.event) {
828    case 'monitor':
829      set({ monitor: data as unknown as MonitorState });
830      break;
831    case 'skills':
832      set({ skills: data as unknown as Skill[] });
833      break;
834    case 'models':
835      if (Array.isArray(data.variants)) set({ library: data as unknown as ModelLibrary });
836      break;
837    case 'runtime':
838      set({runtime:data as unknown as RuntimeModels});
839      break;
840    case 'native':
841      applyNativeEvent(data);
842      break;
843    case 'image-models':
844      if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary });
845      break;
846    case 'providers':
847      applyProviders(data as unknown as ModelProviders);
848      break;
849    case 'goal':
850      if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal);
851      break;
852    case 'plan':
853      if (typeof data.chatId === 'string') applyPlanFrame(data.chatId, data.plan);
854      break;
855    case 'queue':
856      if (typeof data.chatId === 'string') applyQueueFrame(data.chatId, data.queue);
857      break;
858    case 'timeskip':
859      applyTimeSkipEvent(data);
860      break;
861    case 'engine':
862      set({ engine: data as unknown as EngineConfig });
863      break;
864    case 'serving':
865      set({ serving: newestServingState(state.serving, data as unknown as ServingState) });
866      break;
867    case 'setup':
868      set({ setup: data as unknown as SetupState });
869      break;
870    case 'task': {
871      // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed.
872      const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null };
873      if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? ''));
874      else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); }
875      else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); }
876      break;
877    }
878    case 'chats':
879      // Another window saved or removed a chat (this window's own saves carry its name and are ignored).
880      if (typeof data.id === 'string' && data.from !== WINDOW_ID) void applyChatChange(data.id, typeof data.rev === 'number' ? data.rev : null, data.deleted === true);
881      break;
882    case 'agent':
883      if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) }));
884      break;
885    default:
886      break;
887  }
888}
889
890/** QAGUI 0213: how long one start-up GET may take, how often it is tried, and the pause between tries (a test may shorten them). */
891export const bootstrapTiming = { timeoutMs: 8000, tries: 3, backoffMs: 400 };
892
893/** One GET with a time limit, tried again after a timeout, a lost connection or a host error. A refusal (4xx) is final. */
894export async function getWithRetry<T>(path: string): Promise<T> {
895  const { timeoutMs, tries, backoffMs } = bootstrapTiming;
896  let last: unknown;
897  for (let attempt = 0; attempt < tries; attempt++) {
898    if (attempt) await new Promise(r => setTimeout(r, backoffMs * 2 ** (attempt - 1)));
899    const abort = new AbortController();
900    let timer: ReturnType<typeof setTimeout> | undefined;
901    try {
902      return await Promise.race([
903        api.get<T>(path, abort.signal),
904        new Promise<never>((_, reject) => { timer = setTimeout(() => { abort.abort(); reject(new Error(`No answer from ${path}`)); }, timeoutMs); }),
905      ]);
906    } catch (err) {
907      last = err;
908      if (err instanceof ApiError && err.status >= 400 && err.status < 500) throw err;
909    } finally { clearTimeout(timer); }
910  }
911  throw last;
912}
913
914let closeEvents: (() => void) | null = null;
915export async function bootstrap() {
916  applyPrefs();
917  try {
918    let chatsTimer: ReturnType<typeof setTimeout> | undefined;
919    await Promise.race([
920      loadChatsFromHost(),
921      new Promise<never>((_, reject) => { chatsTimer = setTimeout(() => reject(new Error('The chats did not load in time')), bootstrapTiming.timeoutMs); }),
922    ]).catch(() => { sessionWriter.enable(); }).finally(() => clearTimeout(chatsTimer));
923    // Only what the first screen cannot do without holds up 'live'; the rest is read at the same time and fills in when it arrives.
924    const soft = <T,>(path: string) => getWithRetry<T>(path).catch(() => null);
925    const late = {
926      hardware: soft<Hardware>('/api/hardware'),
927      monitor: soft<MonitorState>('/api/monitor'),
928      skills: soft<Skill[]>('/api/skills'),
929      providers: soft<ModelProviders>('/api/model-providers'),
930      imageModels: soft<ImageModelLibrary>('/api/image-models'),
931      runtime: soft<RuntimeModels>('/api/runtime'),
932    };
933    const [setup, library, engine, serving, workspaceState] = await Promise.all([
934      getWithRetry<SetupState>('/api/setup'),
935      getWithRetry<ModelLibrary>('/api/models'),
936      getWithRetry<EngineConfig>('/api/engine'),
937      getWithRetry<ServingState>('/api/serving'),
938      getWithRetry<{ workspaces: Workspace[] }>('/api/workspaces'),
939    ]);
940    set({
941      ready: true,
942      setup,
943      library: libraryResponse(library),
944      engine,
945      serving: newestServingState(state.serving, serving),
946      workspacePath: workspaceState.workspaces[0]?.path ?? '',
947      workspaces: workspaceState.workspaces,
948      activeWorkspace: workspaceState.workspaces.some(w => w.id === state.activeWorkspace) ? state.activeWorkspace : workspaceIdForSession(workspaceState.workspaces, state.sessions.find(s => s.id === state.activeSession)) ?? workspaceState.workspaces[0]?.id ?? null,
949      connection: 'live',
950    });
951    void late.hardware.then(hardware => { if (hardware) set({ hardware }); });
952    void late.monitor.then(monitor => { if (monitor) set({ monitor }); });
953    void late.skills.then(skills => { if (skills) set({ skills }); });
954    void late.providers.then(providers => { if (providers) applyProviders(providers); });
955    void late.imageModels.then(imageModels => { if (imageModels) set({ imageModels }); });
956    void late.runtime.then(runtime => { if (runtime) set({ runtime }); });
957    if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); }
958    closeEvents?.();
959    let reconnect = false;
960    closeEvents = onEvent(applyEvent, (status) => {
961      if (status === 'offline') reconnect = true;
962      if (status === 'live' && reconnect) {
963        reconnect = false;
964        // The restarted host may have new logs, config or readiness. Refresh
965        // those facts in place while retaining conversations and unsent drafts.
966        void bootstrap();
967        return;
968      }
969      set({ connection: status });
970    });
971    if (!setup.complete && !setup.dismissed && !window.location.hash.includes('setup')) navigate('setup');
972  } catch (err) {
973    set({ ready: true, connection: 'offline' });
974    pushToast(
975      'error',
976      'Engine host unreachable',
977      err instanceof Error ? err.message : 'Start it with `npm run host` and reload.',
978    );
979  }
980}
981
982/* ------------------------------------------------------------- reads/writes */
983
984export async function refreshHardware() {
985  set((s) => ({ busy: { ...s.busy, hardware: true } }));
986  try {
987    set({ hardware: await api.get<Hardware>('/api/hardware?reprobe=1') });
988  } finally {
989    set((s) => ({ busy: { ...s.busy, hardware: false } }));
990  }
991}
992
993function modelFits(id: string) {
994  const model = state.library?.variants.find(v => v.id === id);
995  if (state.library?.mode === 'real' && model && state.hardware && state.engine && ['too-large', 'unsupported'].includes(estimate(model, state.hardware, execution(Object.fromEntries(state.engine.expert.map(p => [p.id, p.value])), contextTokens(state.engine.beginner.contextLength))).fit)) {
996    pushToast('warn', 'Choose a smaller model', 'The estimated memory requirement exceeds this computer.');
997    return false;
998  }
999  return true;
1000}
1001
1002export async function selectImageModel(selected: ImageModelChoice) {
1003  set(s => ({ busy: { ...s.busy, 'image:select': true } }));
1004  try { set({ imageModels: await api.patch<ImageModelLibrary>('/api/image-models', { selected }) }); }
1005  finally { set(s => ({ busy: { ...s.busy, 'image:select': false } })); }
1006}
1007export async function installImageModel(id: Exclude<ImageModelChoice, 'off'>) {
1008  set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/install`) });
1009}
1010export async function cancelImageModel(id: Exclude<ImageModelChoice, 'off'>) {
1011  set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/cancel`) });
1012}
1013export async function applyImageModel() {
1014  set({ imageModels: await api.post<ImageModelLibrary>('/api/image-models/apply') });
1015}
1016
1017export async function installVariant(id: string) {
1018  // Download eligibility is checked against disk space by the host. Runtime fit
1019  // is reviewed separately when the model is loaded.
1020  if (state.busy[`install:${id}`]) return false;
1021  set((s) => ({ busy: { ...s.busy, [`install:${id}`]: true } }));
1022  try {
1023    const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/install`));
1024    set({ library });
1025    const complete = library.variants.find(v => v.id === id)?.state === 'installed';
1026    pushToast(complete ? 'success' : 'info', complete ? 'Files installed' : library.mode === 'simulated' ? 'Example installation started' : 'Download started', complete ? 'Load the model to start a request.' : 'Progress is shown in Models.');
1027    return true;
1028  } catch (err) {
1029    pushToast('error', 'Download failed', err instanceof Error ? err.message : undefined);
1030    return false;
1031  } finally {
1032    set((s) => ({ busy: { ...s.busy, [`install:${id}`]: false } }));
1033  }
1034}
1035
1036export async function cancelInstall(id: string) {
1037  try { set({ library: libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/cancel`)) }); } catch (e) { pushToast('error', 'Cancel failed', e instanceof Error ? e.message : String(e)); }
1038}
1039
1040export async function loadVariant(id: string) {
1041  if (!modelFits(id)) return false;
1042  if (!lifecycleAvailable()) return false;
1043  set((s) => ({ busy: { ...s.busy, [`load:${id}`]: true }, actionError: null }));
1044  try {
1045    const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/load`));
1046    set({ library });
1047    const model = library.variants.find(v => v.id === id);
1048    if (library.loaded !== id || model?.state !== 'loaded') throw new Error(model?.error ?? 'The model did not finish loading.');
1049    pushToast('success', library.mode === 'simulated' ? 'Example model ready' : 'Model loaded', library.mode === 'simulated' ? 'Answers are simulated samples, not from a real model.' : 'Ready for a request.');
1050    return true;
1051  } catch (err) {
1052    const message = err instanceof Error ? err.message : 'The model did not load.';
1053    set({
1054      actionError: {
1055        label: 'Could not load model',
1056        message,
1057        retry: () => void loadVariant(id),
1058      },
1059    });
1060    pushToast('error', 'Could not load model', message);
1061    return false;
1062  } finally {
1063    set((s) => ({ busy: { ...s.busy, [`load:${id}`]: false } }));
1064  }
1065}
1066
1067export async function unloadModel() {
1068  if (!lifecycleAvailable()) return false;
1069  set(s => ({ busy: { ...s.busy, unload: true } }));
1070  try {
1071    const previousInstance=state.runtime?.defaultId;
1072    const library = libraryResponse(await api.post<ModelLibrary>('/api/models/unload'));
1073    const runtime=await api.get<RuntimeModels>('/api/runtime');
1074    set({runtime});
1075    set({ library });
1076    if (previousInstance?runtime.instances.some(i=>i.id===previousInstance):library.loaded!==null) throw new Error('The engine still reports this model instance as loaded.');
1077    pushToast('info', 'Model unloaded', library.mode === 'simulated' ? 'Example load state cleared.' : 'Model memory released.');
1078    return true;
1079  } catch (err) { pushToast('error', 'Unload failed', err instanceof Error ? err.message : String(err)); return false; }
1080  finally { set(s => ({ busy: { ...s.busy, unload: false } })); }
1081}
1082
1083export async function removeVariant(id: string) {
1084  if (state.library?.loaded === id && !lifecycleAvailable()) return false;
1085  const local = !!state.library?.variants.find(v => v.id === id)?.local;
1086  try { const library = libraryResponse(await api.del<ModelLibrary>(`/api/models/${id}`)); set({ library });
1087    const remaining = library.variants.find(v => v.id === id);
1088    if (remaining && remaining.state !== 'available') throw new Error('The model files were not removed.');
1089    pushToast('success', local ? 'Local model removed' : 'Files removed', local ? 'The original GGUF files are kept.' : library.mode === 'simulated' ? 'Example install state cleared.' : 'Model files removed from disk.'); return true;
1090  } catch (e) { pushToast('error', 'Remove failed', e instanceof Error ? e.message : String(e)); return false; }
1091}
1092
1093export async function waitForInstalled(id: string) {
1094  const deadline = Date.now() + 60 * 60 * 1000;
1095  while (Date.now() < deadline) {
1096    const v = state.library?.variants.find(v => v.id === id);
1097    if (v && ['installed', 'loaded'].includes(v.state)) return;
1098    if (!v || ['available', 'error'].includes(v.state)) throw new Error(v?.error ?? 'Download cancelled.');
1099    await new Promise(resolve => setTimeout(resolve, 500));
1100  }
1101  throw new Error('Download timed out. Try again from Models.');
1102}
1103
1104export async function saveEngine(patch: Partial<EngineConfig> | Record<string, unknown>, silent = false, requireIdle = false) {
1105  if (requireIdle) {
1106    const status = lifecycleStatus();
1107    if (!status.allowed) throw new Error(status.reason);
1108  }
1109  const engine = await api.patch<EngineConfig>('/api/engine', patch);
1110  set({ engine, actionError: null });
1111  if (!silent) pushToast('success', 'Settings saved', 'Load settings take effect on the next load. Sampling defaults affect the next request.');
1112  return engine;
1113}
1114
1115export async function restartEngine() {
1116  if (state.library?.mode === 'simulated') { pushToast('info', 'Restart unavailable with the example engine', 'Save settings for the next load.'); return false; }
1117  if (!lifecycleAvailable()) return false;
1118  set((s) => ({ busy: { ...s.busy, restart: true }, actionError: null }));
1119  try {
1120    const engine = await api.post<EngineConfig>('/api/engine/restart');
1121    set({ engine });
1122    if (!engine.engine.running) throw new Error(engine.engine.error ?? 'The engine is not running. Load a model before applying settings.');
1123    pushToast('success', 'Engine restarted', 'Warm-up takes a few seconds.');
1124    return true;
1125  } catch (err) {
1126    // Reported in place as well as in a toast: the toast is a summary, the
1127    // surface that failed is where the retry belongs.
1128    set({
1129      actionError: {
1130        label: 'Restart failed',
1131        message: err instanceof Error ? err.message : 'The engine did not come back up.',
1132        retry: () => void restartEngine(),
1133      },
1134    });
1135    pushToast('error', 'Restart failed', err instanceof Error ? err.message : undefined);
1136    return false;
1137  } finally {
1138    set((s) => ({ busy: { ...s.busy, restart: false } }));
1139  }
1140}
1141
1142export function dismissActionError() {
1143  set({ actionError: null });
1144}
1145
1146export async function resetEngine() {
1147  set({ engine: await api.post<EngineConfig>('/api/engine/reset') });
1148  pushToast('info', 'Back to recommended', 'Every value returned to the safe default.');
1149}
1150
1151/**
1152 * Checks an engine config — the saved one by default, or a draft to preview what
1153 * a change would do before committing to it.
1154 */
1155export async function validateEngine(draft?: unknown) {
1156  return api.post<{
1157    ok: boolean;
1158    issues: { level: 'warn' | 'error'; message: string }[];
1159    predicted?: EngineConfig['predicted'];
1160  }>('/api/engine/validate', draft ?? {});
1161}
1162
1163export async function exportEngine() {
1164  return api.get<Record<string, unknown>>('/api/engine/export');
1165}
1166
1167export async function setCloudflare(body: {action: 'start' | 'stop' | 'prepare'; mode?: 'quick' | 'domain'; hostname?: string; token?: string}) {
1168  const result = await api.post<ServingState>('/api/serving/tunnel', body);
1169  set({ serving: newestServingState(state.serving, result) });
1170}
1171
1172export async function setLocalSharing(enabled: boolean) {
1173  const result = await api.post<ServingState>('/api/serving/share', { enabled });
1174  set({ serving: newestServingState(state.serving, result) });
1175}
1176
1177export async function setServingAccess(patch: { otherDevices?: boolean; apiKey?: string | null }) {
1178  const result = await api.patch<ServingState>('/api/serving', patch);
1179  set({ serving: newestServingState(state.serving, result) });
1180}
1181
1182export async function pauseServing(paused: boolean) {
1183  const result = await api.patch<ServingState>('/api/serving', { pauseServing: paused });
1184  set({ serving: newestServingState(state.serving, result) });
1185}
1186
1187export async function cancelRequest(id: string) {
1188  const result = await api.post<ServingState>(`/api/serving/requests/${id}/cancel`);
1189  set({ serving: newestServingState(state.serving, result) });
1190}
1191
1192export async function completeSetupStep(step: number, choices?: SetupState['choices'], dismissed = false) {
1193  set({ setup: await api.post<SetupState>('/api/setup/step', { step, choices, dismissed, flowVersion: 2 }) });
1194}
1195
1196export async function completeSetup() {
1197  const setup = await api.post<SetupState>('/api/setup/complete');
1198  set({ setup });
1199}
1200
1201export async function setSkills(skills: Skill[]) {
1202  set({ skills });
1203}
1204
1205/**
1206 * Re-reads the skill list from the host.
1207 *
1208 * For the case where a skill was added to the workspace folder while the app was
1209 * open — otherwise the only way to see it is to restart.
1210 */
1211export async function loadSkills() {
1212  set({ skills: await api.get<Skill[]>('/api/skills') });
1213}
1214
1215/** Re-reads the workspace tree from disk, for the same reason. */
1216export async function loadWorkspaceFiles() {
1217  const data = await api.get<{ path: string; entries: WorkspaceFile[] }>(`/api/workspace${state.activeWorkspace ? '?root=' + encodeURIComponent(state.activeWorkspace) : ''}`);
1218  set({ files: data.entries, workspacePath: data.path });
1219}
1220
1221export async function toggleSkill(id: string, enabled: boolean) {
1222  set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { enabled }) });
1223}
1224
1225export async function editSkill(id: string, patch: Pick<Skill, 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn'>) {
1226  set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, patch) });
1227}
1228
1229/**
1230 * Narrows a skill to the workspace you are in, or widens it again.
1231 *
1232 * Passing null clears the narrowing. The host resolves `onlyIn` against the
1233 * workspace the request came from, so the answer depends on where the reader
1234 * is rather than on a single global switch.
1235 */
1236export async function scopeSkill(id: string, workspaceId: string | null) {
1237  set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { onlyIn: workspaceId }) });
1238}
1239
1240/* ---------------------------------------------------------------- sessions */
1241
1242const chatTransport = createHttpTransport();
1243let saveToast: string | null = null;
1244
1245const sessionWriter = createSessionWriter({
1246  transport: chatTransport,
1247  enabled: false,   // on once the host's chats have been read (loadChatsFromHost), so an older copy here never replaces a newer file
1248  // Nothing is trimmed to fit (#5192). A chat the host cannot write keeps its last file and stays whole here; it is reported and
1249  // tried again. A host that does not answer is retried quietly: that is the app being down, not a full disk.
1250  onResult: (result: SaveResult) => {
1251    if (result.ok) {
1252      try { browserStorage.removeItem(PENDING_KEY); } catch { /* removed at the next start */ }
1253      if (state.sessionSave) set({ sessionSave: null });
1254      if (saveToast) { dismissToast(saveToast); saveToast = null; }
1255      return;
1256    }
1257    const real = result.failed.filter(f => f.reason !== 'offline');
1258    if (!real.length) return;
1259    const failedIds = sessionWriter.unsaved().map(s => s.id);
1260    const reason = real[0].reason === 'offline' ? 'other' : real[0].reason;
1261    const was = state.sessionSave;
1262    if (!was || was.reason !== reason || was.failedIds.join() !== failedIds.join()) set({ sessionSave: { failedIds, reason } });
1263    if (!was && !saveToast) {
1264      saveToast = pushToast('error', 'Some chats could not be saved', tr("Strata's chat storage is full, so the newest changes to {0} chat(s) are only in this window. Delete old chats to make room; they then save by themselves.", [failedIds.length]), {
1265        label: 'Copy unsaved chats',
1266        run: () => { const text = unsavedSessionsJson(); if (text) void copyText(text, '', { toast: (tone, title, body) => { pushToast(tone, title, body || undefined); } }); },
1267      });
1268    }
1269  },
1270});
1271
1272/** The chats the host could not write, as one JSON text (to keep a copy by hand), or null when all are saved. */
1273export function unsavedSessionsJson(): string | null {
1274  const unsaved = sessionWriter.unsaved();
1275  return unsaved.length ? exportSessions(unsaved) : null;
1276}
1277
1278/**
1279 * Save the chat list. A one-off change (new, rename, delete, pin) is sent now; `soon` is for the streaming
1280 * path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second.
1281 */
1282function persistSessions(sessions: Session[], soon = false) {
1283  sessionWriter.schedule(sessions);
1284  if (!soon) void sessionWriter.flush();
1285}
1286
1287/** Send the newest chat list now: a turn ended, or the page is going away. */
1288export function flushSessions(): Promise<SaveResult> {
1289  return sessionWriter.flush();
1290}
1291
1292/** The page is going away: send what can still be sent, and keep a last-moment copy of what the host has not confirmed (taken back at the next start). */
1293function leavingPage() {
1294  void sessionWriter.flush();
1295  const unconfirmed = sessionWriter.notOnHost();
1296  if (unconfirmed.length) keepLastMomentCopy(browserStorage, unconfirmed);
1297}
1298
1299if (typeof window !== 'undefined' && typeof document !== 'undefined' && window.addEventListener) {
1300  window.addEventListener('pagehide', leavingPage);
1301  document.addEventListener?.('visibilitychange', () => { if (document.visibilityState === 'hidden') leavingPage(); });
1302}
1303
1304let chatsRead = false;
1305/**
1306 * The first read of the chats at start, and again after the host came back: the host's files become the chats shown (the browser's
1307 * old chats are handed over first, once), then saving starts. A host that does not answer leaves the page as it is.
1308 */
1309export async function loadChatsFromHost() {
1310  if (chatsRead) { await syncChatsFromHost(); return; }
1311  const result = await hydrateChats({
1312    transport: chatTransport, browser: browserStorage, current: state.sessions,
1313    isLive: id => liveTurns.has(id),
1314  });
1315  if (result.offline) {
1316    // Show the browser's old copy so the person can still read; saves are retried until the host answers.
1317    if (!state.sessions.length) { try { set({ sessions: readBrowserSessions(browserStorage).sessions.map(fixSession) }); } catch { /* none */ } }
1318    for (const s of state.sessions) sessionWriter.adopt(s, null);
1319    sessionWriter.enable();
1320    return;
1321  }
1322  chatsRead = true;
1323  const sessions = result.sessions.map(fixSession);
1324  for (const s of sessions) { const rev = result.revs.get(s.id); if (rev !== undefined && !result.recovered.includes(s.id)) sessionWriter.adopt(s, rev); }
1325  set({ sessions });
1326  // Whatever the host does not have yet (a chat it refused during the move, a last-moment copy) is sent now; a refusal raises the notice.
1327  sessionWriter.schedule(sessions);
1328  sessionWriter.enable();
1329  void resumeSessions();
1330}
1331
1332/** One chat that another window saved or removed: taken over unless this window is working in it. */
1333export async function applyChatChange(id: string, rev: number | null, deleted: boolean) {
1334  const here = state.sessions.find(s => s.id === id);
1335  if (deleted) {
1336    if (here && !liveTurns.has(id) && !sessionWriter.dirty(here)) {
1337      sessionWriter.forget(id);
1338      set({ sessions: state.sessions.filter(s => s.id !== id), ...(state.activeSession === id ? { activeSession: null } : {}) });
1339    }
1340    return;
1341  }
1342  if (rev !== null && sessionWriter.rev(id) >= rev) return;
1343  if (here && (liveTurns.has(id) || sessionWriter.dirty(here))) return;   // this window's own work wins; its next save keeps the displaced version on the host
1344  const got = await chatTransport.get(id).catch(() => null);
1345  if (!got) return;
1346  const fresh = state.sessions.find(s => s.id === id);
1347  if (fresh && (liveTurns.has(id) || sessionWriter.dirty(fresh))) return;
1348  sessionWriter.adopt(got.session, got.rev);
1349  const next = fresh ? state.sessions.map(s => (s.id === id ? got.session : s)) : [...state.sessions, got.session].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
1350  set({ sessions: next });
1351}
1352
1353/** After the host was away: take over what other windows saved or removed meanwhile. */
1354async function syncChatsFromHost() {
1355  const list = await chatTransport.list().catch(() => null);
1356  if (!list) return;
1357  const onHost = new Set(list.chats.map(c => c.id));
1358  for (const entry of list.chats) await applyChatChange(entry.id, entry.rev, false);
1359  for (const s of state.sessions) if (!onHost.has(s.id) && sessionWriter.rev(s.id) > 0) await applyChatChange(s.id, null, true);
1360  sessionWriter.enable();
1361}
1362
1363export function newSession(): Session {
1364  const session: Session = {
1365    id: uid('s'),
1366    title: 'New conversation',
1367    defaultTitle: true,
1368    createdAt: new Date().toISOString(),
1369    updatedAt: new Date().toISOString(),
1370    messages: [],
1371    workspace: state.workspaces.find(w => w.id === state.activeWorkspace)?.path ?? state.workspacePath,
1372    tokensIn: 0,
1373    tokensOut: 0,
1374    ...(state.activeSession === null && state.remoteModel ? { preferences: { remoteModel: state.remoteModel } } : {}),
1375  };
1376  const sessions = [session, ...state.sessions];
1377  persistSessions(sessions);
1378  set({ sessions, activeSession: session.id });
1379  return session;
1380}
1381
1382export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) {
1383  const sessionId = id ?? newSession().id;
1384  patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } }));
1385  // A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included).
1386  if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined);
1387}
1388export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) {
1389  if(!sessionId)return;
1390  patchSession(sessionId,s=>({...s,closedPreviews:closed?[...new Set([...(s.closedPreviews??[]),artifactId])]:(s.closedPreviews??[]).filter(id=>id!==artifactId),previewOpen:selected??undefined}));
1391}
1392export function createChatShowcase() {
1393  const session=newSession();const at=new Date().toISOString();
1394  patchSession(session.id,s=>({...s,title:'Chat showcase · code, tools & media',showcase:true,statsAvailable:true,tokensIn:28000000,tokensOut:4000000,messages:showcaseMessages(at),agents:SHOWCASE_AGENTS,showcaseAgentStates:true}));
1395  go('chat',session.id);
1396}
1397
1398/** A visible example for checking the subagent interface in the design build. */
1399export function createSubagentExample() {
1400  const session = newSession(); const now = Date.now();
1401  patchSession(session.id, s => ({ ...s, title: 'Subagent preview', showcase: true, showcaseAgentStates: true,
1402    agents: [
1403      {id:'example-layout',name:'Layout review',description:'Checking spacing and component alignment.',status:'working',durationMs:39000,tokens:12600,updatedAt:now},
1404      {id:'example-interactions',name:'Interaction review',description:'Checking menus, controls and keyboard navigation.',status:'working',durationMs:21000,tokens:8400,updatedAt:now},
1405      {id:'example-copy',name:'Copy review',description:'Labels and descriptions reviewed.',status:'completed',durationMs:18000,tokens:4200,updatedAt:now},
1406    ], messages: [{id:uid('m'),role:'assistant',at:new Date(now).toISOString(),example:true,content:'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.'}]
1407  }));
1408  go('chat', session.id);
1409}
1410
1411export function createPreviewExamples() {
1412  const session = newSession();
1413  const at = new Date().toISOString();
1414  patchSession(session.id, s => ({ ...s, title: 'Design review · six previews', previewOpen:'sample-website', messages: [
1415    { id:uid('m'), role:'user', at, content:'Open six different output types so I can iterate on the preview design.' },
1416    { id:uid('m'), role:'assistant', at, demo:true, content:'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.', artifacts:PREVIEW_EXAMPLES },
1417  ] }));
1418  go('chat', session.id);
1419}
1420
1421/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */
1422export function continueTaskInNewChat(task: Task) {
1423  const session = newSession();
1424  go('chat', session.id);
1425  void sendMessage(taskHandoverMessage(task), { title: taskHandoverTitle(task), markdown: true });
1426}
1427
1428export function selectSession(id: string) {
1429  // A chat comes back in the workspace it was made in, so its next turn runs in the same folder (#3754).
1430  const workspace = workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === id));
1431  const change = workspace && workspace !== state.activeWorkspace;
1432  set(change ? { activeSession: id, activeWorkspace: workspace } : { activeSession: id });
1433  if (change) void loadWorkspaceFiles();
1434  markRead(id);
1435}
1436
1437/** Records that a conversation has been looked at. */
1438export function markRead(id: string) {
1439  const at = new Date().toISOString();
1440  const sessions = state.sessions.map((s) => (s.id === id ? { ...s, lastReadAt: at } : s));
1441  persistSessions(sessions);
1442  set({ sessions });
1443}
1444
1445/**
1446 * Whether a conversation has moved on since it was last looked at.
1447 *
1448 * The active conversation is never unread: you are looking at it, or its reply
1449 * is arriving in front of you.
1450 */
1451export function isUnread(s: Session, activeSession: string | null): boolean {
1452  if (s.id === activeSession) return false;
1453  if (!s.lastReadAt) return s.messages.length > 0;
1454  return s.updatedAt > s.lastReadAt;
1455}
1456
1457export function deleteSession(id: string) {
1458  const sessions = state.sessions.filter((s) => s.id !== id);
1459  persistSessions(sessions);
1460  set({ sessions, activeSession: state.activeSession === id ? (sessions[0]?.id ?? null) : state.activeSession });
1461}
1462
1463export function renameSession(id: string, title: string) {
1464  const sessions = state.sessions.map((s) => (s.id === id ? { ...s, title, defaultTitle: false } : s));
1465  persistSessions(sessions);
1466  set({ sessions });
1467}
1468
1469function patchSession(id: string, fn: (s: Session) => Session) {
1470  const sessions = state.sessions.map((s) => (s.id === id ? fn(s) : s));
1471  persistSessions(sessions, true);
1472  set({ sessions });
1473}
1474
1475// The demo clock belongs to the session, so hiding the sidebar or navigating
1476// away never pauses it. Only start and completion are written to storage.
1477const timeSkipTimers = new Map<string, ReturnType<typeof setTimeout>>();
1478function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) {
1479  const timerId = `${sessionId}:${run.id}`;
1480  clearTimeout(timeSkipTimers.get(timerId));
1481  if (run.completedAt || run.job) return;
1482  timeSkipTimers.set(timerId, setTimeout(() => {
1483    timeSkipTimers.delete(timerId);
1484    const session = state.sessions.find(s => s.id === sessionId);
1485    const current = session?.timeSkips?.find(r => r.id === run.id);
1486    if (!current || current.startedAt !== run.startedAt || !session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant')) return;
1487    patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(),
1488      timeSkips: s.timeSkips?.map(r => r.id === run.id ? { ...r, completedAt: run.startedAt + TIME_SKIP_DURATION } : r),
1489      messages: s.messages.map(m => m.timeSkipId === run.id && m.role === 'assistant' ? { ...m, content: 'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } : m),
1490    }));
1491  }, Math.max(0, run.startedAt + TIME_SKIP_DURATION - Date.now())));
1492}
1493
1494export function replayTimeSkip(sessionId: string, runId: string) {
1495  const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId);
1496  if (!run) return;
1497  const next = { ...run, startedAt: Date.now(), completedAt: undefined, retainedVersion: undefined };
1498  patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r),
1499    messages: s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } : m),
1500  }));
1501  scheduleTimeSkip(sessionId, next);
1502}
1503
1504export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) {
1505  const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId);
1506  if (!run) return;
1507  if (run.job) { void keepTimeSkip(sessionId, runId, version); return; }
1508  const next = withTimeSkipResult(run, version, Date.now());
1509  if (next === run) return;
1510  patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) }));
1511}
1512
1513/* ------------------------------------------------------- Time-skip, for real
1514   The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the
1515   person chooses. The sidebar follows the job's own record; nothing here invents progress. */
1516const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted'];
1517const TS_WORKING = () => tr('Working on a copy of your files. Follow the progress in the sidebar.');
1518const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side.');
1519
1520function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) {
1521  patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(),
1522    timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r),
1523    messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m),
1524  }));
1525}
1526
1527/** The job's error in a sentence a person can use. */
1528export function plainTimeSkipError(raw: string | null | undefined): string {
1529  const text = String(raw ?? '').trim();
1530  if (!text) return tr('Something went wrong.');
1531  const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text);
1532  const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim();
1533  if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.');
1534  if (/too big/i.test(body)) return tr('This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.');
1535  if (/folder of your own/i.test(body)) return tr('Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.');
1536  if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.');
1537  if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.');
1538  return body.length > 300 ? body.slice(0, 299) + '…' : body;
1539}
1540
1541/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */
1542function applyTimeSkipEvent(data: Record<string, unknown>) {
1543  const id = typeof data.id === 'string' ? data.id : '';
1544  if (!id) return;
1545  for (const session of state.sessions) {
1546    const run = session.timeSkips?.find(r => r.job?.id === id);
1547    if (!run || run.completedAt) continue;
1548    patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } }));
1549  }
1550}
1551
1552function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string {
1553  if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]);
1554  if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.');
1555  if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.');
1556  return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY();
1557}
1558
1559async function startTimeSkipReal(prompt: string) {
1560  const sessionId = state.activeSession ?? newSession().id;
1561  const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(),
1562    job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } };
1563  const at = new Date().toISOString();
1564  patchSession(sessionId, s => ({ ...s,
1565    defaultTitle: false,
1566    title: s.messages.length ? s.title : shortTitle(prompt), updatedAt: at,
1567    // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works.
1568    timeSkips: [...(s.timeSkips ?? []), run],
1569    messages: [...s.messages,
1570      { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id },
1571      { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() },
1572    ],
1573  }));
1574  go('chat', sessionId);
1575  markTurn(sessionId, { abort: new AbortController(), agent: false });
1576  try {
1577    const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) });
1578    patchRun(sessionId, run.id, r => ({ ...r, job: started.run }));
1579    void followTimeSkip(sessionId, run.id);
1580  } catch (e) {
1581    const message = plainTimeSkipError(e instanceof Error ? e.message : String(e));
1582    patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message]));
1583    markTurn(sessionId, null);
1584  }
1585}
1586
1587const followingTimeSkips = new Set<string>();
1588/** Read the job's record until it ends. Safe to call again for a run already being followed. */
1589export async function followTimeSkip(sessionId: string, runId: string) {
1590  const key = sessionId + ':' + runId;
1591  if (followingTimeSkips.has(key)) return;
1592  followingTimeSkips.add(key);
1593  let misses = 0;
1594  try {
1595    for (;;) {
1596      const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId);
1597      if (!run?.job?.id || run.completedAt) return;
1598      let job: TimeSkipJob | null = null;
1599      try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; }
1600      catch { misses += 1; }
1601      if (job && TS_TERMINAL.includes(job.phase)) {
1602        let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {};
1603        // The changed files are what the person came for: ask again a few times before settling for "nothing to compare".
1604        for (let tryNo = 0; tryNo < 4; tryNo++) {
1605          try {
1606            const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id));
1607            files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more };
1608            break;
1609          } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); }
1610        }
1611        const finished = { ...job, ...forkFields(job as unknown as Record<string, unknown>) };
1612        patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files));
1613        // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab.
1614        if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) }));
1615        markTurn(sessionId, null);
1616        return;
1617      }
1618      if (job) { const live = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); }
1619      if (misses >= 6) {
1620        patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.'));
1621        markTurn(sessionId, null);
1622        return;
1623      }
1624      await new Promise(r => setTimeout(r, 2000));
1625    }
1626  } finally { followingTimeSkips.delete(key); }
1627}
1628
1629/** Ask the host to stop a running trial. The saved version stays. */
1630export async function stopTimeSkip(sessionId: string, runId: string) {
1631  const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id;
1632  if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined);
1633}
1634
1635/** Put the update into the person's files, or put the original back. Both are checked and undoable. */
1636export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) {
1637  const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId);
1638  const job = run?.job;
1639  if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return;
1640  if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; }
1641  try {
1642    if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' });
1643    else if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null });
1644    else await api.post('/api/timeskip/apply', { id: job.id, restore: true });
1645    patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version }));
1646    pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back'));
1647  } catch (e) {
1648    pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e)));
1649  }
1650}
1651
1652function startTimeSkipDemo(prompt: string) {
1653  if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; }
1654  const sessionId = state.activeSession ?? newSession().id;
1655  const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now() };
1656  const at = new Date().toISOString();
1657  patchSession(sessionId, s => ({ ...s,
1658    defaultTitle: false,
1659    title: s.messages.length ? s.title : shortTitle(prompt), updatedAt: at,
1660    timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id),
1661    messages: [...s.messages,
1662      { id: uid('m'), role: 'user', at, content: `/time-skip ${prompt}`, timeSkipId: run.id },
1663      { id: uid('m'), role: 'assistant', at, example: true, timeSkipId: run.id, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' },
1664    ],
1665  }));
1666  scheduleTimeSkip(sessionId, run);
1667  go('chat', sessionId);
1668}
1669
1670function markTurn(sessionId: string, turn: { abort: AbortController; agent: boolean } | null) {
1671  if (turn) liveTurns.set(sessionId, turn); else liveTurns.delete(sessionId);
1672  set({ streaming: !!state.activeSession && liveTurns.has(state.activeSession), liveChats: liveTurns.size });
1673  document.documentElement.dataset.streaming = liveTurns.size ? 'true' : 'false';
1674}
1675
1676/**
1677 * Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's
1678 * Harness session and answers only once the turn has ended, and the stream then closes by itself with
1679 * what was produced. For any other turn the host reports nothing to stop and the request is aborted.
1680 */
1681export function stopStreaming() {
1682  const id = state.activeSession;
1683  const turn = id ? liveTurns.get(id) : undefined;
1684  if (!id || !turn) return;
1685  const abort = () => { turn.abort.abort(); };
1686  void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then(
1687    result => {
1688      if (!result.stopped) abort();
1689      // An agent turn that was told to stop but is slow to end must not leave the chat stuck.
1690      else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000);
1691    },
1692    abort,
1693  );
1694}
1695
1696/**
1697 * Re-runs the last exchange: drops the assistant reply and asks again.
1698 *
1699 * Kept in the store rather than the screen because it has to touch the message
1700 * list, and every attempt to do this from a component ends up duplicating the
1701 * stream handling that already lives here.
1702 */
1703export async function retryLast(messageId?: string) {
1704  const source = state.sessions.find(s => s.id === state.activeSession);
1705  if (!source || state.streaming) return;
1706  const end = messageId ? source.messages.findIndex(m => m.id === messageId) : source.messages.length - 1;
1707  const user = source.messages.slice(0, end + 1).reverse().find(m => m.role === 'user');
1708  if (!user) return;
1709  const prompt = rewindTo(user.id);
1710  if (prompt !== null) {
1711    // Retry sends immediately; only Edit should leave the prompt in the composer.
1712    sessionStorage.setItem(`strata.chat-draft.${state.activeSession}`, '');
1713    await sendMessage(prompt);
1714  }
1715}
1716
1717/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */
1718function failedExchange(): { prompt: string; sessionId: string } | null {
1719  const sessionId = state.activeSession;
1720  const chat = state.sessions.find(s => s.id === sessionId);
1721  if (!sessionId || !chat || state.streaming) return null;
1722  const reply = chat.messages[chat.messages.length - 1], ask = chat.messages[chat.messages.length - 2];
1723  return reply?.role === 'assistant' && reply.error && ask?.role === 'user' ? { prompt: ask.content, sessionId } : null;
1724}
1725/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */
1726function dropFailedExchange(sessionId: string) {
1727  patchSession(sessionId, s => ({ ...s, messages: s.messages.slice(0, -2) }));
1728}
1729
1730/**
1731 * The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then
1732 * ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps
1733 * the newest message as it is), so it is not sent a second time: a large one twice would not fit either.
1734 */
1735export async function summarizeAndContinue() {
1736  if (!failedExchange()) return;
1737  await sendMessage('/compact');
1738  await sendMessage('Please answer my last message now.');
1739}
1740
1741/**
1742 * The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the
1743 * assistant reads in parts, or a shortened preview), and that is sent in its place.
1744 */
1745export async function sendOversized(mode: 'file' | 'preview') {
1746  const failed = failedExchange();
1747  if (!failed) return;
1748  let reply: { message?: string };
1749  try {
1750    reply = await api.post<{ message?: string }>('/api/chat/oversize', { sessionId: failed.sessionId, mode, text: failed.prompt, nativeModelId: nativeState()?.instances.length ? nativeState()?.defaultId : undefined });
1751  } catch {
1752    pushToast('error', 'The message could not be prepared. Try a shorter message.');
1753    return;
1754  }
1755  if (!reply.message) return;
1756  dropFailedExchange(failed.sessionId);
1757  await sendMessage(reply.message);
1758}
1759
1760/** A new, empty chat, opened. */
1761export function startNewChat() {
1762  const session = newSession();
1763  go('chat', session.id);
1764}
1765
1766/**
1767 * Forks a conversation at a message, leaving the original untouched.
1768 *
1769 * The alternative people reach for is duplicating the whole session and
1770 * deleting messages by hand, which loses the original. Branching keeps both:
1771 * the new session carries the history up to the chosen turn and diverges there.
1772 */
1773export function branchFrom(messageId: string): string | null {
1774  const sessionId = state.activeSession;
1775  if (!sessionId) return null;
1776  const source = state.sessions.find((s) => s.id === sessionId);
1777  if (!source) return null;
1778  const at = source.messages.findIndex((m) => m.id === messageId);
1779  if (at < 0) return null;
1780
1781  const now = new Date().toISOString();
1782  const branch: Session = {
1783    ...source,
1784    id: uid('s'),
1785    title: `${source.title} (branch)`,
1786    defaultTitle: false,
1787    createdAt: now,
1788    updatedAt: now,
1789    messages: source.messages.slice(0, at + 1).map((m) => ({ ...m, id: uid('m') })),
1790    tokensIn: 0,
1791    tokensOut: source.messages.slice(0, at + 1).reduce((n, m) => n + (m.tokens ?? 0), 0),
1792    statsAvailable: false,
1793  };
1794  const sessions = [branch, ...state.sessions];
1795  persistSessions(sessions);
1796  set({ sessions, activeSession: branch.id });
1797  for (const run of branch.timeSkips ?? []) scheduleTimeSkip(branch.id, run);
1798  // The URL wins over `activeSession` when it names a session, so a programmatic
1799  // switch has to move the route too — otherwise the sidebar shows the branch
1800  // while the transcript still shows the original, which reads as a broken
1801  // button rather than a created branch.
1802  navigate('chat', branch.id);
1803  return branch.id;
1804}
1805
1806/**
1807 * Asks the model to keep going from where it stopped.
1808 *
1809 * Sent as an ordinary user turn rather than a special mode, because that is
1810 * what it is: a continuation is a request, and the transcript should show it.
1811 */
1812export async function continueLast() {
1813  const sessionId = state.activeSession;
1814  if (!sessionId || state.streaming) return;
1815  const session = state.sessions.find((s) => s.id === sessionId);
1816  const last = session?.messages[session.messages.length - 1];
1817  if (!last || last.role !== 'assistant' || !last.content.trim()) return;
1818  await sendMessage('Continue from where you left off. Do not repeat what you have already written.');
1819}
1820
1821/**
1822 * Rewinds the transcript to just before a turn so it can be re-asked with a
1823 * different prompt. Returns the text so the composer can be filled with it.
1824 */
1825export function rewindTo(messageId: string): string | null {
1826  if (state.streaming) return null;
1827  const source = state.sessions.find(s => s.id === state.activeSession);
1828  const at = source?.messages.findIndex(m => m.id === messageId) ?? -1;
1829  if (!source || at < 0) return null;
1830  const prompt = source.messages[at].content;
1831  const branchId = branchFrom(messageId);
1832  if (!branchId) return null;
1833  patchSession(branchId, s => ({ ...s, messages: s.messages.slice(0, -1), tokensIn: 0, tokensOut: s.messages.slice(0, -1).reduce((n, m) => n + (m.tokens ?? 0), 0) }));
1834  sessionStorage.setItem(`strata.chat-draft.${branchId}`, prompt);
1835  return prompt;
1836}
1837
1838export function exportConversation() {
1839  const session = state.sessions.find(s => s.id === state.activeSession);
1840  if (!session) return;
1841  const text = '# ' + session.title + '\n\n' + session.messages.map(m => '## ' + m.role + '\n\n' + (m.role === 'assistant' ? tidyAnswer(m.content) : m.content)).join('\n\n');
1842  const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' }));
1843  const a = document.createElement('a'); a.href = url; a.download = session.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) + '.md';
1844  document.body.append(a); a.click(); a.remove();
1845  // Keep the Blob alive until browsers have started consuming the download.
1846  setTimeout(() => URL.revokeObjectURL(url), 1000);
1847}
1848
1849/* ---------------------------------------------------------------- /loop
1850   The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is
1851   lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */
1852
1853/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */
1854function addNote(sessionId: string, content: string) {
1855  const at = new Date().toISOString();
1856  patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] }));
1857}
1858
1859const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local);
1860
1861const loopScheduler = new LoopScheduler({
1862  async send(sessionId, { text, shown }) {
1863    const before = lastAnswer(sessionId)?.id;
1864    await sendMessage(text, { fromLoop: true, shown, title: shortTitle(shown) });
1865    const answer = lastAnswer(sessionId);
1866    if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false };
1867    return { answered: true, text: answer.content ?? '', failed: !!answer.error };
1868  },
1869  note: addNote,
1870  exists: sessionId => state.sessions.some(s => s.id === sessionId),
1871  ready: sessionId => state.activeSession === sessionId && !state.streaming,
1872  now: () => Date.now(),
1873  setTimer: (fn, ms) => setTimeout(fn, ms),
1874  clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
1875  track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })),
1876});
1877
1878export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); }
1879
1880/* ------------------------------------------------------------- task board */
1881
1882/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */
1883export function liveChatIds(): string[] { return [...liveTurns.keys()]; }
1884export function loopChatIds(): string[] { return loopScheduler.ids(); }
1885
1886/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */
1887export function stopChat(id: string) {
1888  const turn = liveTurns.get(id);
1889  if (!turn) return;
1890  const abort = () => { turn.abort.abort(); };
1891  void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then(
1892    result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); },
1893    abort,
1894  );
1895}
1896
1897/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */
1898export function stopLoop(id: string) {
1899  if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.'));
1900}
1901
1902/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */
1903export function dismissChat(id: string) {
1904  const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s));
1905  persistSessions(sessions);
1906  set({ sessions });
1907}
1908
1909/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */
1910export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) {
1911  const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId);
1912  if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved);
1913}
1914
1915/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */
1916export function continueChatInNewChat(sessionId: string) {
1917  const old = state.sessions.find(s => s.id === sessionId);
1918  if (!old) return;
1919  const session = newSession();
1920  go('chat', session.id);
1921  void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true });
1922}
1923
1924async function runLoopCommand(command: LoopCommand) {
1925  const sessionId = state.activeSession ?? newSession().id;
1926  const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); };
1927  if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; }
1928  if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; }
1929  if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }
1930  go('chat', sessionId);
1931  await loopScheduler.start(sessionId, command);
1932}
1933
1934/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */
1935export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); }
1936
1937/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */
1938export async function approvePlan(sessionId: string, planId: string) {
1939  const { prompt } = await planApprove(sessionId, planId);
1940  // A chat in Plan mode only reads; carrying the plan out needs a mode that may act.
1941  if (state.sessions.find(s => s.id === sessionId)?.preferences?.mode === 'plan') setChatPreferences(sessionId, { mode: 'manual' });
1942  if (prompt) await sendMessage(prompt, { shown: tr('Approved the plan.') });
1943}
1944
1945/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */
1946export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); }
1947
1948export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean; reattach?: string; requestId?: string } = {}) {
1949  // `reattach`: a turn the host is still running for this chat (or finished while the page was away) is taken over again after a reload, not started.
1950  const reattach = options.reattach;
1951  if (state.streaming && !reattach) {
1952    // Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait.
1953    const waiting = state.activeSession, line = text.trim();
1954    if (waiting && line && !options.planId && !options.goalAction) {
1955      try { if (!(await queueMessage(waiting, line))) pushToast('info', 'The assistant is still answering', 'Send your message when it has finished.'); }
1956      catch (e) { pushToast('error', 'The message was not queued', plainFailureText(e instanceof Error ? e.message : String(e)).message); }
1957    }
1958    return;
1959  }
1960  const resume = options.goalAction === 'resume';
1961  const planStart = options.planId;
1962  const loopCommand = options.fromLoop || resume || planStart || reattach ? null : parseLoop(text.trim());
1963  if (loopCommand) { await runLoopCommand(loopCommand); return; }
1964  const demoPrompt = resume || planStart || reattach ? null : timeSkipPrompt(text.trim());
1965  if (demoPrompt !== null) {
1966    if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.');
1967    else if (state.connection === 'connecting' && demoPrompt) pushToast('info', 'Still starting up', 'Time-skip needs the app to finish starting. Try again in a moment.');
1968    else startTimeSkipDemo(demoPrompt);
1969    return;
1970  }
1971  // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing.
1972  if (state.connection === 'live' && !reattach) {
1973    // The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send.
1974    if (!nativeState() && !state.remoteModel && !state.library?.loaded) { pushToast('info', 'Still starting up', 'Strata is still checking your models. Try again in a moment.'); return; }
1975    const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded });
1976    if (why) { pushToast('info', why.title, why.message); return; }
1977  }
1978  const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers);
1979  if(!reattach&&pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;}
1980  const pictures=reattach?[]:takeChatPhotos(state.activeSession);
1981  const body=text.trim()||(pictures.length?'Describe this picture.':'');
1982  if(!body&&!resume&&!planStart&&!reattach)return;
1983
1984  let sessionId = reattach ?? state.activeSession;
1985  if (!sessionId) sessionId = newSession().id;
1986
1987  const userMsg: ChatMessage = { id: uid('m'), role: 'user', content: options.shown ?? body, at: new Date().toISOString(),...(pictures.length?{photos:pictures}:{}),...(options.markdown?{markdown:true}:{}) };
1988  // A taken-over turn goes on in the reply the page already has (the last one, if it is the assistant's).
1989  const lastReply = reattach ? [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse()[0] : undefined;
1990  const resumedReply = lastReply?.role === 'assistant' ? lastReply : undefined;
1991  let assistantId = resumedReply?.id ?? uid('m');
1992  const assistantMsg: ChatMessage = {
1993    id: assistantId,
1994    role: 'assistant',
1995    content: '',
1996    at: new Date().toISOString(),
1997    streaming: true,
1998  };
1999
2000  /* Everything said before this turn, which the model needs in order to have a
2001     conversation at all.
2002
2003     It was never sent. The real-engine path builds its prompt as
2004     `[...history, message]`, and `history` was always empty, so each message
2005     arrived as the first thing the model had ever heard — no memory of the
2006     turns above it in the transcript. The demo path hides this, because its
2007     replies are canned.
2008
2009     The context meter was reading the same empty array, which is why it sat at
2010     ~350 tokens however long the conversation grew. */
2011  const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? [])
2012    .filter(m => !m.timeSkipId && !m.local)
2013    .filter((m) => m.role === 'user' || m.role === 'assistant')
2014    .filter((m) => m.content.trim())
2015    .map((m) => ({ role: m.role, content: m.content,photos:m.photos }))
2016    // Bounded so a long conversation cannot send an unbounded body.
2017    .slice(-40);
2018
2019  patchSession(sessionId, (s) => reattach ? ({
2020    ...s,
2021    messages: resumedReply
2022      ? s.messages.map(m => m.id === resumedReply.id ? { ...m, streaming: true } : m)
2023      : [...s.messages, assistantMsg],
2024  }) : ({
2025    ...s,
2026    defaultTitle: false,
2027    title: s.messages.length === 0 && !resume && !planStart ? (options.title ?? (shortTitle(body))) : s.title,
2028    updatedAt: new Date().toISOString(),
2029    messages: [...s.messages, ...(resume || planStart ? [] : [userMsg]), assistantMsg],
2030  }));
2031
2032  const turnAbort = new AbortController();
2033  markTurn(sessionId, { abort: turnAbort, agent: false });
2034  // Read by the router to skip view transitions mid-stream, and by CSS to keep
2035  // the transcript still while tokens arrive.
2036
2037  const patchAssistant = (fn: (m: ChatMessage) => ChatMessage) =>
2038    patchSession(sessionId, (s) => ({
2039      ...s,
2040      updatedAt: new Date().toISOString(),
2041      messages: s.messages.map((m) => (m.id === assistantId ? fn(m) : m)),
2042    }));
2043
2044  const started = performance.now();
2045
2046  const imageSlots=photoHistorySlots(prior,pictures.length);
2047  /* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every
2048     word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering
2049     and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure
2050     apply what is waiting first, so the order the person sees is the order it was written. */
2051  const waiting: ['reasoning' | 'delta', string][] = [];
2052  let waitingTimer: ReturnType<typeof setTimeout> | null = null;
2053  const applyReasoning = (text: string) => patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + text, reasoningStartedAt: m.reasoningStartedAt ?? Date.now() }));
2054  const applyDelta = (text: string) => patchAssistant((m) => { const content=tidyAnswer(m.content+text); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,text)}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });
2055  const flushWaiting = () => {
2056    if (waitingTimer !== null) { clearTimeout(waitingTimer); waitingTimer = null; }
2057    for (const [kind, text] of waiting.splice(0)) if (kind === 'delta') applyDelta(text); else applyReasoning(text);
2058  };
2059  const queueText = (kind: 'reasoning' | 'delta', text: string) => {
2060    const last = waiting[waiting.length - 1];
2061    if (last && last[0] === kind) last[1] += text; else waiting.push([kind, text]);
2062    waitingTimer ??= setTimeout(flushWaiting, 90);
2063  };
2064  try {
2065    await streamPost(
2066      reattach ? '/api/chat/attach' : planStart ? '/api/plan/start-goal' : '/api/chat/stream',
2067      reattach ? { sessionId, ...(options.requestId ? { requestId: options.requestId } : {}) } : {
2068        sessionId,
2069        ...(planStart ? { planId: planStart } : {}),
2070        ...(resume ? { goalAction: 'resume' } : planStart ? {} : { message: options.shown ? body : body }),
2071        history:await Promise.all(prior.map(async(m,index)=>{const included=pictureCheck.ok?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})),
2072        model: state.library?.loaded ?? state.library?.current ?? null,
2073        remoteModel: state.remoteModel,
2074        nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined,
2075        ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}),
2076        useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true,
2077        // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly.
2078        ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}),
2079        thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'Medium',
2080        thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0,
2081        // The Mode menu's choice for this chat, read when the turn starts; the host applies it to the agent.
2082        mode:state.sessions.find(s=>s.id===sessionId)?.preferences?.mode??'manual',
2083        // So a skill narrowed to another workspace does not fire here.
2084        workspaceId: workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === sessionId)) ?? state.activeWorkspace,
2085      },
2086      (frame) => {
2087        // A line from the app itself carries `key` (the English sentence): shown in the person's language.
2088        if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) };
2089        const type = frame.type as string;
2090        if (type === 'delta' || type === 'reasoning') { queueText(type, String(frame.text ?? '')); return; }
2091        flushWaiting();
2092        if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; }
2093        // The host has a turn to take over: the failure the page wrote when it lost the stream no longer applies.
2094        if (type === 'start' && frame.resumed === true) patchAssistant(m => ({ ...m, error: undefined, errorCode: undefined }));
2095        if (type === 'queued') {
2096          patchAssistant(m => ({ ...m, requestId: String(frame.requestId) }));
2097        } else if (type === 'start') {
2098          patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] }));
2099        } else if (type === 'resync') {
2100          // A taken-over turn: what was said while no page was here. The reply continues from what the page had; where the two disagree the host's text stands.
2101          const said = String(frame.content ?? ''), thought = String(frame.reasoning ?? '');
2102          patchAssistant(m => {
2103            let next = m;
2104            if (said) next = said.startsWith(next.content) ? { ...next, content: tidyAnswer(said), ...(next.blocks && said.length > next.content.length ? { blocks: appendText(next.blocks, said.slice(next.content.length)) } : {}) } : { ...next, content: tidyAnswer(said), blocks: undefined };
2105            if (thought && thought.length >= (next.reasoning ?? '').length) next = { ...next, reasoning: thought, reasoningStartedAt: next.reasoningStartedAt ?? Date.now() };
2106            return next;
2107          });
2108        } else if (type === 'status') {
2109          applyStatusFrame(sessionId, frame as Record<string, unknown>);
2110          // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question.
2111          if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) {
2112            lastApprovalNotice = `${sessionId}:${String(frame.seq)}`;
2113            const tool = (frame.args as { tool?: unknown } | undefined)?.tool;
2114            void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : '');
2115          }
2116        } else if (type === 'goal') {
2117          applyGoalFrame(sessionId, frame.goal);
2118        } else if (type === 'plan') {
2119          applyPlanFrame(sessionId, frame.plan);
2120          // A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose).
2121          const planned = frame.plan as { id?: unknown } | null;
2122          if (frame.event === 'proposed' && planned && typeof planned.id === 'string') { const pid = planned.id; patchAssistant(m => ({ ...m, planId: pid })); }
2123        } else if (type === 'queued-message') {
2124          applyQueueFrame(sessionId, frame.queue);
2125          const sent = frame.message as { text?: unknown } | undefined;
2126          if (frame.state === 'delivered' && sent && typeof sent.text === 'string') {
2127            // The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply.
2128            const before = assistantId; assistantId = uid('m');
2129            const next: ChatMessage = { id: assistantId, role: 'assistant', content: '', at: new Date().toISOString(), streaming: true };
2130            patchSession(sessionId, sess => ({ ...sess, messages: [...sess.messages.map(m => m.id === before ? { ...m, streaming: false } : m), { id: uid('m'), role: 'user', content: sent.text as string, at: new Date().toISOString() }, next] }));
2131          }
2132        } else if (type === 'queued-release') {
2133          // The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished.
2134          const left = Array.isArray(frame.messages) ? frame.messages.flatMap(q => (q && typeof (q as { text?: unknown }).text === 'string' ? [String((q as { text: string }).text)] : [])) : [];
2135          if (left.length) releasedMessages.set(sessionId, [...(releasedMessages.get(sessionId) ?? []), ...left]);
2136        } else if (type === 'plan-step') {
2137          /* the whole plan follows in a plan frame; the live status already says which step is running */
2138        } else if (type === 'reasoning') {
2139          /* applied through queueText above */
2140        } else if (type === 'notice') {
2141          // The host says why this chat is not using the agent. One toast per reason per page load.
2142          const code = String(frame.code ?? 'notice');
2143          if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); }
2144        } else if (type === 'agent-question') {
2145          addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown });
2146        } else if (type === 'agent-question-end') {
2147          removeAgentAsk(sessionId, String(frame.callId ?? ''));
2148        } else if (type === 'agent-tool-draft') {
2149          // A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost.
2150          const d = frame.draft as (ToolDraft & { done?: boolean }) | undefined;
2151          if (d && typeof d.id === 'string') {
2152            const { done, ...view } = d;
2153            patchAssistant(m => {
2154              const rest = (m.drafts ?? []).filter(x => x.id !== d.id);
2155              return { ...m, drafts: done ? (rest.length ? rest : undefined) : [...rest, view] };
2156            });
2157          }
2158        } else if (type === 'agent-tool') {
2159          const tool = frame.tool as ToolCall;
2160          patchAssistant(m => {
2161            const existing = m.tools?.find(t => t.id === tool.id);
2162            const next: ToolCall = { ...existing, ...tool, live: true };
2163            return { ...m, tools: existing ? m.tools!.map(t => t.id === tool.id ? next : t) : [...(m.tools ?? []), next] };
2164          });
2165        } else if (type === 'agent') {
2166          patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) }));
2167        } else if (type === 'delta') {
2168          /* applied through queueText above */
2169        } else if (type === 'deliverable') {
2170          const file = readDeliverable(frame);
2171          if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) }));
2172        } else if (type === 'skills-used') {
2173          const skills = readSkills(frame);
2174          if (skills.length) patchAssistant(m => ({ ...m, skills }));
2175        } else if (type === 'activity-group') {
2176          const group = readGroup(frame);
2177          if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) }));
2178        } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) {
2179          patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] }));
2180        } else if(type==='native-tool'){
2181          const event=frame.event as {event:string;id:string;name?:string;arguments?:Record<string,unknown>;text?:string;ok?:boolean;ms?:number};
2182          if(event.id)patchAssistant(m=>{const existing=m.tools?.find(t=>t.id===event.id);const tool={id:event.id,name:event.name??existing?.name??'Connected tool',args:event.arguments??existing?.args??{},preview:'Authorized connected tool',effect:'Access configured in the MCP server',scope:'connected' as const,state:event.event==='result'?event.ok?'done' as const:'error' as const:'running' as const,result:event.text,durationMs:event.ms};return {...m,tools:[...(m.tools??[]).filter(t=>t.id!==tool.id),{...existing,...tool}]};});
2183        } else if (type === 'tool') {
2184          const tool = frame.tool as ChatMessage['tools'] extends (infer T)[] | undefined ? T : never;
2185          patchAssistant((m) => ({ ...m, tools: [...(m.tools ?? []), { ...tool, state: 'proposed' }] }));
2186        } else if (type === 'stats') {
2187          patchAssistant((m) => ({
2188            ...m,
2189            tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : m.tokens,
2190            tps: typeof frame.tps === 'number' ? frame.tps : m.tps,
2191            promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps,
2192          }));
2193        } else if (type === 'context') {
2194          // What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end.
2195          const used = Number(frame.contextTokens), max = Number(frame.contextMax);
2196          if (Number.isFinite(used) && used > 0) patchAssistant((m) => ({ ...m, contextUsed: used, ...(Number.isFinite(max) && max > 0 ? { contextMax: max } : {}) }));
2197        } else if (type === 'error') {
2198          clearStatus(sessionId);
2199          // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here.
2200          const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message;
2201          patchAssistant((m) => ({ ...m, drafts: undefined, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) }));
2202        } else if (type === 'done') {
2203          clearStatus(sessionId);
2204          workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started));
2205          patchSession(sessionId, (sess) => ({
2206            ...sess,
2207            tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0),
2208            tokensOut: sess.tokensOut + Number(frame.tokensOut ?? 0),
2209            statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'),
2210          }));
2211          patchAssistant((m) => ({
2212            ...m,
2213            streaming: false,
2214            drafts: undefined,
2215            durationMs: Number(frame.durationMs ?? performance.now() - started),
2216            tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined,
2217            ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined,
2218            inputTokens: typeof frame.tokensIn === 'number' ? frame.tokensIn : undefined,
2219            contextUsed: typeof frame.contextTokens === 'number' ? frame.contextTokens : undefined,
2220            usageSource: frame.usageSource === 'reported' || frame.usageSource === 'demo' ? frame.usageSource : 'unavailable',
2221            tps: typeof frame.tps === 'number' ? frame.tps : m.tps,
2222            promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps,
2223          }));
2224          // The final text is in `state`: write it once now instead of waiting for the coalescing timer.
2225          flushSessions();
2226        }
2227      },
2228      turnAbort.signal,
2229    );
2230  } catch (err) {
2231    flushWaiting();
2232    if (reattach && (err as { status?: number } | null)?.status === 404) {
2233      // Nothing to take over (the turn ended and the host no longer holds it): the reply stays as the page had it.
2234      patchAssistant((m) => ({ ...m, streaming: false }));
2235    } else if ((err as Error).name !== 'AbortError') {
2236      patchAssistant((m) => ({
2237        ...m,
2238        streaming: false,
2239        error: err instanceof Error ? err.message : 'Engine error',
2240      }));
2241      pushToast('error', 'Generation failed', err instanceof Error ? err.message : undefined);
2242    } else {
2243      patchAssistant((m) => ({ ...m, streaming: false }));
2244    }
2245  } finally {
2246    flushWaiting();
2247    // A cancelled or failed turn is still worth keeping.
2248    flushSessions();
2249    clearStatus(sessionId);
2250    markTurn(sessionId, null);
2251    removeAgentAsk(sessionId);
2252    const next = releasedMessages.get(sessionId)?.shift();
2253    if (next !== undefined) { if (!releasedMessages.get(sessionId)?.length) releasedMessages.delete(sessionId); setTimeout(() => void sendMessage(next), 0); }
2254  }
2255}
2256
2257/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */
2258const releasedMessages = new Map<string, string[]>();
2259
2260/* -------------------------------------------------------------- tool grants */
2261
2262const noticed = new Set<string>();
2263
2264/**
2265 * Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the
2266 * Harness approval for exactly this chat and call; the card then follows what the Harness reports
2267 * (running, done, denied). The card shows the choice straight away and goes back if the host refuses.
2268 */
2269function answerAgentTool(sessionId: string, messageId: string, tool: ToolCall, approved: boolean) {
2270  const setState = (state_: ToolCall['state'], result?: string) => patchSession(sessionId, s => ({
2271    ...s, messages: s.messages.map(m => m.id === messageId ? { ...m, tools: (m.tools ?? []).map(t => t.id === tool.id ? { ...t, state: state_, ...(result !== undefined ? { result } : {}) } : t) } : m),
2272  }));
2273  setState(approved ? 'running' : 'denied');
2274  api.post('/api/chat/approval', { sessionId, toolId: tool.id, decision: approved ? 'approve' : 'deny' }).catch(error => {
2275    setState('proposed');
2276    pushToast('error', 'That answer was not delivered', error instanceof Error ? error.message : undefined);
2277  });
2278}
2279
2280/**
2281 * Approving a tool in the design build resolves locally: there is no tool
2282 * runtime behind it yet, so the result is a labelled stand-in. The interaction —
2283 * what is asked, what is shown, what needs a grant — is the real deliverable.
2284 */
2285export function resolveTool(messageId: string, toolId: string, approved: boolean) {
2286  const sessionId = state.activeSession;
2287  if (!sessionId) return;
2288  const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId);
2289  if (tool?.live) { answerAgentTool(sessionId, messageId, tool, approved); return; }
2290
2291  patchSession(sessionId, (s) => ({
2292    ...s,
2293    messages: s.messages.map((m) =>
2294      m.id === messageId
2295        ? {
2296            ...m,
2297            tools: (m.tools ?? []).map((t) =>
2298              t.id === toolId
2299                ? {
2300                    ...t,
2301                    state: approved ? 'done' : 'denied',
2302                    durationMs: undefined,
2303                    result: approved ? 'Approval recorded. Nothing was executed.' : 'Denied. Nothing ran.',
2304                  }
2305                : t,
2306            ),
2307          }
2308        : m,
2309    ),
2310  }));
2311
2312}
2313
2314/* ------------------------------------------------------------------- routes */
2315
2316export function go(route: Route, param?: string) {
2317  navigate(route, param);
2318  // Focus mode is a reading mode for the conversation. Leaving it to work on
2319  // something else leaves the mode, rather than stranding a bare shell.
2320  if (state.focus && route !== 'chat' && route !== 'settings') setFocus(false);
2321  set({ paletteOpen: false, navOpen: false });
2322}
2323
2324/* ---------------------------------------------------------------- bootstrap */
2325
2326export function bootOnce() {
2327  if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return;
2328  (globalThis as { __strataBooted?: boolean }).__strataBooted = true;
2329  void bootstrap();
2330}
2331
2332let sessionsResumed = false;
2333/**
2334 * Once, after the chats were first read from the host: what a chat can still have going on. Time-skip runs are followed again, a loop the last
2335 * window left "running" has ended, a turn the host is still running is taken over (or one that ended while the page was away is shown whole),
2336 * and tool cards the browser remembers as waiting for a turn that no longer exists are marked interrupted.
2337 */
2338async function resumeSessions() {
2339  if (sessionsResumed) return;
2340  sessionsResumed = true;
2341  for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } }
2342  // A loop lives in the window: one the last window left "running" has ended, and the board says so.
2343  if (state.sessions.some(s => s.loop?.state === 'running')) {
2344    const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s);
2345    persistSessions(sessions);
2346    set({ sessions });
2347  }
2348  await takeOverTurns();
2349  void reconcileAgentTools();
2350}
2351
2352/**
2353 * A reload does not stop an agent turn: the host keeps it going. The page asks which chats have a turn running and takes each one over again
2354 * (the catch-up, then the rest as it is written, the Stop button and the approvals waiting). A chat whose last reply was cut off by the page
2355 * going away is asked about too: if its turn ended meanwhile, the host still holds the end of it and shows it whole; if not, nothing changes.
2356 */
2357async function takeOverTurns() {
2358  let running: { chatId: string }[] = [];
2359  try { running = (await api.get<{ turns: { chatId: string }[] }>('/api/chat/active')).turns; } catch { /* an older host, or none reachable: nothing to take over */ }
2360  const live = new Set(running.map(t => t.chatId));
2361  for (const id of live) if (state.sessions.some(s => s.id === id) && !liveTurns.has(id)) void sendMessage('', { reattach: id });
2362  // Cut-off replies of chats with no turn running: the most recent few, asked once each.
2363  const cut = state.sessions.filter(s => !live.has(s.id) && !liveTurns.has(s.id)).slice().sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)).slice(0, 12).flatMap(s => {
2364    const last = s.messages[s.messages.length - 1];
2365    return last?.role === 'assistant' && last.requestId && last.usageSource === undefined && !last.local ? [{ id: s.id, requestId: last.requestId }] : [];
2366  });
2367  await Promise.allSettled(cut.map(c => sendMessage('', { reattach: c.id, requestId: c.requestId })));
2368}
2369
2370/**
2371 * After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no
2372 * longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as
2373 * interrupted so nothing looks like it is still working.
2374 */
2375async function reconcileAgentTools() {
2376  const open = (t: ToolCall) => t.live && (t.state === 'proposed' || t.state === 'running');
2377  for (const session of state.sessions) {
2378    if (liveTurns.has(session.id)) continue;   // a turn taken over again reports its own cards
2379    if (!session.messages.some(m => m.tools?.some(open))) continue;
2380    let waiting = new Set<string>();
2381    try {
2382      const r = await api.get<{ pending: { callId: string }[] }>(`/api/agent/pending?chatId=${encodeURIComponent(session.id)}`);
2383      waiting = new Set(r.pending.map(p => p.callId));
2384    } catch { /* The host is unreachable; leave the cards for the next load. */ continue; }
2385    patchSession(session.id, sess => ({ ...sess, messages: sess.messages.map(m => m.tools?.some(open) ? { ...m, tools: m.tools.map(t => open(t) && !waiting.has(t.id) ? { ...t, state: 'error' as const, result: 'The page closed before this finished. Check the workspace to see what it did.' } : t) } : m) }));
2386  }
2387}
2388
2389
2390export function setContrast(contrast: 'standard' | 'increased') { set({ contrast }); savePrefs(); }
2391matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') applyPrefs(); });
2392
2393export async function loadRuntimeModel(body:unknown){
2394  const result=await api.post<{state:RuntimeModels;instance:{id:string}}>('/api/runtime/load',body);
2395  set({runtime:result.state});return result.instance.id;
2396}
2397export async function runtimeModelAction(id:string,action:'unload'|'default'){
2398  set({runtime:await api.post<RuntimeModels>(`/api/runtime/${id}/${action}`)});
2399}
2400
2401export async function changeModelDirectory(directory: string, unload: boolean) {
2402  set(s => ({ busy: { ...s.busy, modelDirectory: true } }));
2403  try {
2404    const result = await api.post<{ library: ModelLibrary; imageModels: ImageModelLibrary; runtime: RuntimeModels; hardware: Hardware; setup: SetupState }>('/api/storage/models-directory', { directory, unload });
2405    set(result);
2406    return result;
2407  } finally {
2408    set(s => ({ busy: { ...s.busy, modelDirectory: false } }));
2409  }
2410}
2411
2412export async function addLocalModel(path: string, name?: string) {
2413  const result = await api.post<{ library: ModelLibrary; variantId: string }>('/api/local-models', { path, name });
2414  set({ library: result.library });
2415  return result.variantId;
2416}