okami.mom/strata

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

Niko1221Reuse a retained legacy model library through a guarded native data root, without moving weights (#3362)3f8124586

main
8.0 KiB176 linesraw
1import { migrateSetup } from './setup.mjs';
2/** Tiny persisted state for the host: one JSON file under STRATA_HOME. */
3import { accessSync, constants, mkdirSync, readFileSync, writeFileSync, existsSync, realpathSync, readdirSync, statSync, statfsSync, symlinkSync } from 'node:fs';
4import { alignModels, isDriveRoot, libraryFolderFromPick, makeFolder } from './model-folder.mjs';
5import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
6import { homedir } from 'node:os';
7import { defaultModelDirectory } from './model-directory-default.mjs';
8
9/**
10 * Prefer ~/.strata, the way the packaged app stores its data. Sandboxes and
11 * locked-down accounts cannot write to the home directory, so fall back to a
12 * folder next to the checkout rather than failing to boot.
13 */
14function resolveHome() {
15  const candidates = [process.env.STRATA_HOME, join(homedir(), '.strata'), join(process.cwd(), '.strata')].filter(
16    Boolean,
17  );
18  for (const dir of candidates) {
19    try {
20      mkdirSync(join(dir, 'models'), { recursive: true });
21      mkdirSync(join(dir, 'data'), { recursive: true });
22      return dir;
23    } catch {
24      /* try the next candidate */
25    }
26  }
27  throw new Error('No writable data directory found — set STRATA_HOME to a writable path');
28}
29
30export const HOME = resolveHome();
31export const DATA_DIR = join(HOME, 'data');
32const STATE_FILE = join(DATA_DIR, 'state.json');
33
34const DEFAULTS = {
35  version: 1,
36  setup: { complete: false, flowVersion: 2, step: 1, history: [] },
37  installed: {}, // id -> { installedAt, bytes }
38  current: null,
39  loaded: null,
40  beginner: {
41    priority: 'balanced',
42    contextLength: 'recommended',
43    readImages: false,
44    gpuIdle: 'never',
45  },
46  expert: {}, // id -> value
47  serving: { otherDevices: false, apiKey: null, pauseServing: false },
48};
49
50function read() {
51  try {
52    if (!existsSync(STATE_FILE)) return structuredClone(DEFAULTS);
53    const parsed = JSON.parse(readFileSync(STATE_FILE, 'utf8'));
54    return { ...structuredClone(DEFAULTS), ...parsed, setup: migrateSetup(parsed.setup) };
55  } catch {
56    return structuredClone(DEFAULTS);
57  }
58}
59
60let state = read();
61const DEFAULT_MODELS_DIRECTORY=defaultModelDirectory();
62/**
63 * The model folder for a new install: the saved one, an existing library inside STRATA_HOME, else Documents/Strata/Models. A Documents folder
64 * that cannot be made (Controlled folder access, a disconnected share, an offline OneDrive known folder) must not stop the host from starting:
65 * the models go to STRATA_HOME/models instead, and `notice` says so in plain words.
66 */
67export function pickModelsDirectory({ saved, home, preferred, fixedByEnv = false }) {
68 if (saved) return { directory: saved, notice: '' };
69 const fallback = join(home, 'models');
70 let legacy = fallback;
71 try { legacy = realpathSync(fallback); } catch { /* the folder is made at start; keep the plain path */ }
72 function hasWeights(folder,depth=0){try{return readdirSync(folder,{withFileTypes:true}).some(entry=>entry.isFile()&&/\.gguf(?:\.part|\.partial)?$/i.test(entry.name)||entry.isDirectory()&&depth<4&&hasWeights(join(folder,entry.name),depth+1));}catch{return false;}}
73 // Keep an existing library in place. A new install uses Documents/Strata/Models.
74 if (!fixedByEnv && hasWeights(legacy)) return { directory: legacy, notice: '' };
75 try {
76  mkdirSync(preferred, { recursive: true });
77  accessSync(preferred, constants.R_OK | constants.W_OK | constants.X_OK);
78  return { directory: realpathSync(preferred), notice: '' };
79 } catch (error) {
80  return { directory: legacy, notice: `Strata could not use ${preferred} for models (${error.code ?? error.message}), so models go to ${legacy}. You can pick another folder in Settings.` };
81 }
82}
83const MODELS_PICK = pickModelsDirectory({ saved: state.modelsDir, home: HOME, preferred: DEFAULT_MODELS_DIRECTORY, fixedByEnv: !!process.env.STRATA_MODELS_DIR });
84/** Plain words for the person when the usual model folder could not be used (empty otherwise). */
85export const MODELS_DIR_NOTICE = MODELS_PICK.notice;
86if (MODELS_DIR_NOTICE) console.warn(`[strata] ${MODELS_DIR_NOTICE}`);
87export let MODELS_DIR = MODELS_PICK.directory;
88
89/** Native setup writes weights to data_dir/models. Keep its data root one level up. */
90export function nativeDataDirectory(input) {
91 if(!input||!existsSync(input))return input;
92 if(MODELS_DIR_NOTICE)return input;
93 const root=realpathSync(input),legacy=realpathSync(join(HOME,'models'));
94 // Retained legacy libraries are model folders too, not native data roots.
95 // A named data root satisfies the installer's guard; its alias leaves weights in place.
96 if(root===legacy){
97  const data=join(HOME,'Strata-data'),nativeModels=join(data,'models');
98  mkdirSync(data,{recursive:true});
99  // Unlike a fresh default, a retained library must not fall back to an empty folder if linking fails.
100  if(!existsSync(nativeModels))symlinkSync(process.platform==='win32'?root:relative(data,root),nativeModels,process.platform==='win32'?'junction':'dir');
101  const a=statSync(nativeModels),b=statSync(root);
102  if(realpathSync(nativeModels)!==root&&!(a.ino&&a.ino===b.ino&&a.dev===b.dev))throw new Error('The model folder conflicts with another library. Choose a different folder.');
103  return data;
104 }
105 if(process.env.STRATA_MODELS_DIR||!existsSync(DEFAULT_MODELS_DIRECTORY)||root!==realpathSync(DEFAULT_MODELS_DIRECTORY))return input;
106 const data=dirname(root);
107 // `models` and `Models` are one folder on Windows and macOS; where they are not (Linux) a link makes them one, and where no link can be made (exFAT, a share) models go in `models`.
108 alignModels(data,root);
109 return data;
110}
111
112/** Existing folders only: a mistyped or disconnected drive must never become a new empty library. */
113export function validateModelsDirectory(input) {
114  if (typeof input !== 'string' || !input.trim() || input.includes('\0')) throw new Error('Enter a model directory.');
115  const path = input.trim().replace(/^~(?=$|[\\/])/, homedir());
116  if (!isAbsolute(path)) throw new Error('Enter the full path to an existing folder.');
117  let directory;
118  try {
119    directory = realpathSync(path);
120    if (!statSync(directory).isDirectory()) throw new Error();
121    accessSync(directory, constants.R_OK | constants.W_OK | constants.X_OK);
122  } catch { throw new Error('This folder is unavailable or not writable. Check the path and folder permissions.'); }
123  // A whole drive (D:\) is not filled with models: D:\Strata\Models is made and used.
124  if (isDriveRoot(directory)) directory = realpathSync(makeFolder(libraryFolderFromPick(directory).path));
125  const data = realpathSync(DATA_DIR);
126  const contains = (parent, child) => { const r = relative(parent, child); return !r || !r.startsWith('..') && !isAbsolute(r); };
127  if (directory === parse(directory).root || contains(directory, data) || contains(data, directory)) throw new Error('Choose a separate folder for models, outside Strata’s app data.');
128  return resolve(directory);
129}
130
131export function changeModelsDirectory(directory) {
132  const next = validateModelsDirectory(directory);
133  if (next === MODELS_DIR) return false;
134  const installedByDirectory = { ...state.installedByDirectory, [MODELS_DIR]: state.installed ?? {} };
135  const updated = { ...state, modelsDir: next, installedByDirectory, installed: installedByDirectory[next] ?? {}, current: null, loaded: null };
136  // Commit the preference before exposing it; a persistence error leaves the old library active.
137  writeFileSync(STATE_FILE, JSON.stringify(updated, null, 2));
138  state = updated; MODELS_DIR = next;
139  return true;
140}
141
142export function get() {
143  return state;
144}
145
146export function save() {
147  try {
148    writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
149  } catch (err) {
150    console.error('[strata] could not persist state:', err.message);
151  }
152}
153
154export function update(patch) {
155  state = { ...state, ...patch };
156  save();
157  return state;
158}
159
160export function diskFreeGb(path = HOME) {
161  try {
162    const s = statfsSync(path);
163    return (s.bavail * s.bsize) / 1024 ** 3;
164  } catch {
165    return 0;
166  }
167}
168
169export function diskTotalGb(path = HOME) {
170  try {
171    const s = statfsSync(path);
172    return (s.blocks * s.bsize) / 1024 ** 3;
173  } catch {
174    return 0;
175  }
176}